@Override
  public final RefactoringStatus checkNewElementName(String newName) {
    Assert.isNotNull(newName, "new name"); // $NON-NLS-1$

    RefactoringStatus status =
        Checks.checkName(newName, JavaConventionsUtil.validateMethodName(newName, fMethod));
    if (status.isOK() && !Checks.startsWithLowerCase(newName))
      status =
          RefactoringStatus.createWarningStatus(
              fIsComposite
                  ? Messages.format(
                      RefactoringCoreMessages.Checks_method_names_lowercase2,
                      new String[] {
                        BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel()
                      })
                  : RefactoringCoreMessages.Checks_method_names_lowercase);

    if (Checks.isAlreadyNamed(fMethod, newName))
      status.addFatalError(
          fIsComposite
              ? Messages.format(
                  RefactoringCoreMessages.RenameMethodRefactoring_same_name2,
                  new String[] {
                    BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel()
                  })
              : RefactoringCoreMessages.RenameMethodRefactoring_same_name,
          JavaStatusContext.create(fMethod));
    return status;
  }
Ejemplo n.º 2
0
  /*
   * (non java-doc)
   * Analyzes all compilation units in which type is referenced
   */
  private RefactoringStatus analyzeAffectedCompilationUnits() throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    fReferences = Checks.excludeCompilationUnits(fReferences, result);
    if (result.hasFatalError()) return result;

    result.merge(Checks.checkCompileErrorsInAffectedFiles(fReferences));
    return result;
  }
Ejemplo n.º 3
0
  protected RefactoringStatus doCheckFinalConditions(
      IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
    try {
      pm.beginTask("", 18); // $NON-NLS-1$
      pm.setTaskName(RefactoringCoreMessages.RenameFieldRefactoring_checking);
      RefactoringStatus result = new RefactoringStatus();
      result.merge(Checks.checkIfCuBroken(fField));
      if (result.hasFatalError()) return result;
      result.merge(checkNewElementName(getNewElementName()));
      pm.worked(1);
      result.merge(checkEnclosingHierarchy());
      pm.worked(1);
      result.merge(checkNestedHierarchy(fField.getDeclaringType()));
      pm.worked(1);

      if (fUpdateReferences) {
        pm.setTaskName(RefactoringCoreMessages.RenameFieldRefactoring_searching);
        fReferences = getReferences(new SubProgressMonitor(pm, 3), result);
        pm.setTaskName(RefactoringCoreMessages.RenameFieldRefactoring_checking);
      } else {
        fReferences = new SearchResultGroup[0];
        pm.worked(3);
      }

      if (fUpdateReferences) result.merge(analyzeAffectedCompilationUnits());
      else Checks.checkCompileErrorsInAffectedFile(result, fField.getResource());

      if (getGetter() != null && fRenameGetter) {
        result.merge(checkAccessor(new SubProgressMonitor(pm, 1), getGetter(), getNewGetterName()));
        result.merge(
            Checks.checkIfConstructorName(
                getGetter(), getNewGetterName(), fField.getDeclaringType().getElementName()));
      } else {
        pm.worked(1);
      }

      if (getSetter() != null && fRenameSetter) {
        result.merge(checkAccessor(new SubProgressMonitor(pm, 1), getSetter(), getNewSetterName()));
        result.merge(
            Checks.checkIfConstructorName(
                getSetter(), getNewSetterName(), fField.getDeclaringType().getElementName()));
      } else {
        pm.worked(1);
      }

      result.merge(createChanges(new SubProgressMonitor(pm, 10)));
      if (result.hasFatalError()) return result;

      return result;
    } finally {
      pm.done();
    }
  }
 public void checkInput(RefactoringStatus status, String methodName, ASTNode destination) {
   ITypeBinding[] arguments = getArgumentTypes();
   ITypeBinding type = ASTNodes.getEnclosingType(destination);
   status.merge(Checks.checkMethodInType(type, methodName, arguments));
   ITypeBinding superClass = type.getSuperclass();
   if (superClass != null) {
     status.merge(Checks.checkMethodInHierarchy(superClass, methodName, null, arguments));
   }
   for (ITypeBinding superInterface : type.getInterfaces()) {
     status.merge(Checks.checkMethodInHierarchy(superInterface, methodName, null, arguments));
   }
 }
 private RefactoringStatus checkExpressionFragmentIsRValue() throws JavaModelException {
   /* Moved this functionality to Checks, to allow sharing with
   ExtractTempRefactoring, others */
   switch (Checks.checkExpressionIsRValue(getSelectedExpression().getAssociatedExpression())) {
     case Checks.NOT_RVALUE_MISC:
       return RefactoringStatus.createStatus(
           RefactoringStatus.FATAL,
           RefactoringCoreMessages.ExtractConstantRefactoring_select_expression,
           null,
           Corext.getPluginId(),
           RefactoringStatusCodes.EXPRESSION_NOT_RVALUE,
           null);
     case Checks.NOT_RVALUE_VOID:
       return RefactoringStatus.createStatus(
           RefactoringStatus.FATAL,
           RefactoringCoreMessages.ExtractConstantRefactoring_no_void,
           null,
           Corext.getPluginId(),
           RefactoringStatusCodes.EXPRESSION_NOT_RVALUE_VOID,
           null);
     case Checks.IS_RVALUE_GUESSED:
     case Checks.IS_RVALUE:
       return new RefactoringStatus();
     default:
       Assert.isTrue(false);
       return null;
   }
 }
 static final IMethod[] hierarchyDeclaresMethodName(
     IProgressMonitor pm, ITypeHierarchy hierarchy, IMethod method, String newName)
     throws CoreException {
   try {
     Set<IMethod> result = new HashSet<>();
     IType type = method.getDeclaringType();
     IMethod foundMethod =
         Checks.findMethod(newName, method.getParameterTypes().length, false, type);
     if (foundMethod != null) result.add(foundMethod);
     IMethod[] foundInHierarchyClasses =
         classesDeclareMethodName(
             hierarchy, Arrays.asList(hierarchy.getAllClasses()), method, newName);
     if (foundInHierarchyClasses != null) result.addAll(Arrays.asList(foundInHierarchyClasses));
     IType[] implementingClasses = hierarchy.getImplementingClasses(type);
     IMethod[] foundInImplementingClasses =
         classesDeclareMethodName(hierarchy, Arrays.asList(implementingClasses), method, newName);
     if (foundInImplementingClasses != null)
       result.addAll(Arrays.asList(foundInImplementingClasses));
     return result.toArray(new IMethod[result.size()]);
   } finally {
     if (pm != null) {
       pm.done();
     }
   }
 }
  private RefactoringStatus checkRelatedMethods() throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); ) {
      IMethod method = iter.next();

      result.merge(
          Checks.checkIfConstructorName(
              method, getNewElementName(), method.getDeclaringType().getElementName()));

      String[] msgData =
          new String[] {
            BasicElementLabels.getJavaElementName(method.getElementName()),
            BasicElementLabels.getJavaElementName(
                method.getDeclaringType().getFullyQualifiedName('.'))
          };
      if (!method.exists()) {
        result.addFatalError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_not_in_model, msgData));
        continue;
      }
      if (method.isBinary())
        result.addFatalError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_binary, msgData));
      if (method.isReadOnly())
        result.addFatalError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_read_only, msgData));
      if (JdtFlags.isNative(method))
        result.addError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_native_1, msgData));
    }
    return result;
  }
 /**
  * This method performs checks on the constant name which are quick enough to be performed every
  * time the ui input component contents are changed.
  *
  * @return return the resulting status
  * @throws JavaModelException thrown when the operation could not be executed
  */
 public RefactoringStatus checkConstantNameOnChange() throws JavaModelException {
   if (Arrays.asList(getExcludedVariableNames()).contains(fConstantName))
     return RefactoringStatus.createErrorStatus(
         Messages.format(
             RefactoringCoreMessages.ExtractConstantRefactoring_another_variable,
             BasicElementLabels.getJavaElementName(getConstantName())));
   return Checks.checkConstantName(fConstantName, fCu);
 }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    if (!fMethod.exists()) {
      String message =
          Messages.format(
              RefactoringCoreMessages.RenameMethodRefactoring_deleted,
              BasicElementLabels.getFileName(fMethod.getCompilationUnit()));
      return RefactoringStatus.createFatalErrorStatus(message);
    }

    RefactoringStatus result = Checks.checkAvailability(fMethod);
    if (result.hasFatalError()) return result;
    result.merge(Checks.checkIfCuBroken(fMethod));
    if (JdtFlags.isNative(fMethod))
      result.addError(RefactoringCoreMessages.RenameMethodRefactoring_no_native);
    return result;
  }
  private IExpressionFragment getSelectedExpression() throws JavaModelException {
    if (fSelectedExpression != null) return fSelectedExpression;

    IASTFragment selectedFragment =
        ASTFragmentFactory.createFragmentForSourceRange(
            new SourceRange(fSelectionStart, fSelectionLength), fCuRewrite.getRoot(), fCu);

    if (selectedFragment instanceof IExpressionFragment
        && !Checks.isInsideJavadoc(selectedFragment.getAssociatedNode())) {
      fSelectedExpression = (IExpressionFragment) selectedFragment;
    }

    if (fSelectedExpression != null
        && Checks.isEnumCase(fSelectedExpression.getAssociatedExpression().getParent())) {
      fSelectedExpression = null;
    }

    return fSelectedExpression;
  }
Ejemplo n.º 11
0
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    IField primary = (IField) fField.getPrimaryElement();
    if (primary == null || !primary.exists()) {
      String message =
          Messages.format(
              RefactoringCoreMessages.RenameFieldRefactoring_deleted,
              BasicElementLabels.getFileName(fField.getCompilationUnit()));
      return RefactoringStatus.createFatalErrorStatus(message);
    }
    fField = primary;

    return Checks.checkIfCuBroken(fField);
  }
Ejemplo n.º 12
0
  public RefactoringStatus checkNewElementName(String newName) throws CoreException {
    Assert.isNotNull(newName, "new name"); // $NON-NLS-1$
    RefactoringStatus result = Checks.checkFieldName(newName, fField);

    if (isInstanceField(fField) && (!Checks.startsWithLowerCase(newName)))
      result.addWarning(
          fIsComposite
              ? Messages.format(
                  RefactoringCoreMessages.RenameFieldRefactoring_should_start_lowercase2,
                  new String[] {
                    BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel()
                  })
              : RefactoringCoreMessages.RenameFieldRefactoring_should_start_lowercase);

    if (Checks.isAlreadyNamed(fField, newName))
      result.addError(
          fIsComposite
              ? Messages.format(
                  RefactoringCoreMessages.RenameFieldRefactoring_another_name2,
                  new String[] {
                    BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel()
                  })
              : RefactoringCoreMessages.RenameFieldRefactoring_another_name,
          JavaStatusContext.create(fField));

    if (fField.getDeclaringType().getField(newName).exists())
      result.addError(
          fIsComposite
              ? Messages.format(
                  RefactoringCoreMessages.RenameFieldRefactoring_field_already_defined2,
                  new String[] {
                    BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel()
                  })
              : RefactoringCoreMessages.RenameFieldRefactoring_field_already_defined,
          JavaStatusContext.create(fField.getDeclaringType().getField(newName)));
    return result;
  }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {

    RefactoringStatus result = new RefactoringStatus();
    result.merge(Checks.checkAvailability(targetClass));

    if (result.hasFatalError()) return result;

    fRoot = new RefactoringASTParser(AST.JLS3).parse(targetClass.getCompilationUnit(), true, pm);
    ISourceRange sourceRange = targetClass.getNameRange();

    ASTNode node = NodeFinder.perform(fRoot, sourceRange.getOffset(), sourceRange.getLength());
    if (node == null) {
      return mappingErrorFound(result, node);
    } else {
      targetClassDeclaration = ASTNodeSearchUtil.getTypeDeclarationNode(targetClass, fRoot);
    }
    fRewriter = ASTRewrite.create(fRoot.getAST());
    return result;
  }
Ejemplo n.º 14
0
 private RefactoringStatus checkEnclosingHierarchy() {
   IType current = fField.getDeclaringType();
   if (Checks.isTopLevel(current)) return null;
   RefactoringStatus result = new RefactoringStatus();
   while (current != null) {
     IField otherField = current.getField(getNewElementName());
     if (otherField.exists()) {
       String msg =
           Messages.format(
               RefactoringCoreMessages.RenameFieldRefactoring_hiding2,
               new String[] {
                 BasicElementLabels.getJavaElementName(getNewElementName()),
                 BasicElementLabels.getJavaElementName(current.getFullyQualifiedName('.')),
                 BasicElementLabels.getJavaElementName(otherField.getElementName())
               });
       result.addWarning(msg, JavaStatusContext.create(otherField));
     }
     current = current.getDeclaringType();
   }
   return result;
 }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    try {
      pm.beginTask("", 7); // $NON-NLS-1$

      RefactoringStatus result = Checks.validateEdit(fCu, getValidationContext());
      if (result.hasFatalError()) return result;
      pm.worked(1);

      if (fCuRewrite == null) {
        CompilationUnit cuNode =
            RefactoringASTParser.parseWithASTProvider(fCu, true, new SubProgressMonitor(pm, 3));
        fCuRewrite = new CompilationUnitRewrite(fCu, cuNode);
      } else {
        pm.worked(3);
      }
      result.merge(checkSelection(new SubProgressMonitor(pm, 3)));

      if (result.hasFatalError()) return result;

      if (isLiteralNodeSelected()) fReplaceAllOccurrences = false;

      if (isInTypeDeclarationAnnotation(getSelectedExpression().getAssociatedNode())) {
        fVisibility = JdtFlags.VISIBILITY_STRING_PACKAGE;
      }

      ITypeBinding targetType = getContainingTypeBinding();
      if (targetType.isInterface()) {
        fTargetIsInterface = true;
        fVisibility = JdtFlags.VISIBILITY_STRING_PUBLIC;
      }

      return result;
    } finally {
      pm.done();
    }
  }
  // -------
  private static IMethod[] classesDeclareMethodName(
      ITypeHierarchy hier, List<IType> classes, IMethod method, String newName)
      throws CoreException {
    Set<IMethod> result = new HashSet<>();
    IType type = method.getDeclaringType();
    List<IType> subtypes = Arrays.asList(hier.getAllSubtypes(type));

    int parameterCount = method.getParameterTypes().length;
    boolean isMethodPrivate = JdtFlags.isPrivate(method);

    for (Iterator<IType> iter = classes.iterator(); iter.hasNext(); ) {
      IType clazz = iter.next();
      IMethod[] methods = clazz.getMethods();
      boolean isSubclass = subtypes.contains(clazz);
      for (int j = 0; j < methods.length; j++) {
        IMethod foundMethod =
            Checks.findMethod(newName, parameterCount, false, new IMethod[] {methods[j]});
        if (foundMethod == null) continue;
        if (isSubclass || type.equals(clazz)) result.add(foundMethod);
        else if ((!isMethodPrivate) && (!JdtFlags.isPrivate(methods[j]))) result.add(foundMethod);
      }
    }
    return result.toArray(new IMethod[result.size()]);
  }
 /*
  * @see Refactoring#checkInput(IProgressMonitor)
  */
 @Override
 public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
   return Checks.validateModifiesFiles(
       ResourceUtil.getFiles(new ICompilationUnit[] {fCUnit}), getValidationContext());
 }
  @SuppressWarnings({"unchecked"})
  @Override
  public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {
    RefactoringStatus result = new RefactoringStatus();
    fChangeManager.clear();
    pm.beginTask("", 12);
    pm.setTaskName("Convert to AtomicInteger checking preconditions");
    pm.worked(1);
    if (result.hasFatalError()) return result;
    pm.setTaskName("ConvertToAtomicInteger searching for cunits");
    final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5);
    ICompilationUnit[] affectedCUs =
        RefactoringSearchEngine.findAffectedCompilationUnits(
            SearchPattern.createPattern(targetClass, IJavaSearchConstants.ALL_OCCURRENCES),
            RefactoringScopeFactory.create(targetClass, true),
            subPm,
            result,
            true);

    if (result.hasFatalError()) return result;

    pm.setTaskName("Analyzing the field");
    IProgressMonitor sub = new SubProgressMonitor(pm, 5);
    sub.beginTask("", affectedCUs.length);

    List ownerDescriptions = new ArrayList();
    ICompilationUnit owner = targetClass.getCompilationUnit();

    for (int i = 0; i < affectedCUs.length; i++) {
      ICompilationUnit unit = affectedCUs[i];
      sub.subTask(unit.getElementName());
      CompilationUnit root = null;
      ASTRewrite rewriter = null;
      List descriptions;
      if (owner.equals(unit)) {
        root = fRoot;
        rewriter = fRewriter;
        descriptions = ownerDescriptions;
      } else {
        root = new RefactoringASTParser(AST.JLS3).parse(unit, true);
        rewriter = ASTRewrite.create(root.getAST());
        descriptions = new ArrayList();
      }
      checkCompileErrors(result, root, unit);

      // We will perform a different set of analysis and rewrites for the compilation unit
      // containing the
      // target class and other compilation units
      if (owner.equals(unit)) {

        // Analysis passes
        ClassMutatorAnalysis mutatorAnalysis = new ClassMutatorAnalysis(targetClass, pm);
        mutatorAnalysis.findMutators();

        ClassConstructorAnalysis constructorAnalysis =
            new ClassConstructorAnalysis(targetClassDeclaration);
        targetClassDeclaration.accept(constructorAnalysis);

        // Rewrite pass
        MakeClassImmutableRewriter immutableRewriter =
            new MakeClassImmutableRewriter(this, unit, rewriter);
        immutableRewriter.rewrite(targetClassDeclaration, mutatorAnalysis, constructorAnalysis);

        result.merge(immutableRewriter.getStatus());
        if (result.hasFatalError()) {
          fChangeManager.clear();
          return result;
        }
      } else {

        // descriptions.addAll(immutableRewriter.getGroupDescriptions());
        createEdits(unit, rewriter, descriptions);
      }

      sub.worked(1);
      if (pm.isCanceled()) throw new OperationCanceledException();
    }

    createEdits(owner, fRewriter, ownerDescriptions);

    sub.done();
    IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
    result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
    if (result.hasFatalError()) return result;
    ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1));
    return result;
  }
  @Override
  protected RefactoringStatus doCheckFinalConditions(
      IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
    try {
      RefactoringStatus result = new RefactoringStatus();
      pm.beginTask("", 9); // $NON-NLS-1$
      // TODO workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=40367
      if (!Checks.isAvailable(fMethod)) {
        result.addFatalError(
            RefactoringCoreMessages.RenameMethodProcessor_is_binary,
            JavaStatusContext.create(fMethod));
        return result;
      }
      result.merge(Checks.checkIfCuBroken(fMethod));
      if (result.hasFatalError()) return result;
      pm.setTaskName(
          RefactoringCoreMessages.RenameMethodRefactoring_taskName_checkingPreconditions);
      result.merge(checkNewElementName(getNewElementName()));
      if (result.hasFatalError()) return result;

      boolean mustAnalyzeShadowing;
      IMethod[] newNameMethods =
          searchForDeclarationsOfClashingMethods(new SubProgressMonitor(pm, 1));
      if (newNameMethods.length == 0) {
        mustAnalyzeShadowing = false;
        pm.worked(1);
      } else {
        IType[] outerTypes =
            searchForOuterTypesOfReferences(newNameMethods, new SubProgressMonitor(pm, 1));
        if (outerTypes.length > 0) {
          // There exists a reference to a clashing method, where the reference is in a nested type.
          // That nested type could be a type in a ripple method's hierarchy, which could
          // cause the reference to bind to the new ripple method instead of to
          // its old binding (a method of an enclosing scope).
          // -> Getting *more* references than before -> Semantics not preserved.
          // Examples: RenameVirtualMethodInClassTests#testFail39() and #testFail41()
          // TODO: could pass declaringTypes to the RippleMethodFinder and check whether
          // a hierarchy contains one of outerTypes (or an outer type of an outerType, recursively).
          mustAnalyzeShadowing = true;

        } else {
          boolean hasOldRefsInInnerTypes = true;
          // TODO: to implement this optimization:
          // - move search for references to before this check.
          // - collect references in inner types.
          // - for each reference, check for all supertypes and their enclosing types
          // (recursively), whether they declare a rippleMethod
          if (hasOldRefsInInnerTypes) {
            // There exists a reference to a ripple method in a nested type
            // of a type in the hierarchy of any ripple method.
            // When that reference is renamed, and one of the supertypes of the
            // nested type declared a method matching the new name, then
            // the renamed reference will bind to the method in its supertype,
            // since inherited methods bind stronger than methods from enclosing scopes.
            // Getting *less* references than before -> Semantics not preserved.
            // Examples: RenamePrivateMethodTests#testFail2(), RenamePrivateMethodTests#testFail5()
            mustAnalyzeShadowing = true;
          } else {
            mustAnalyzeShadowing = false;
          }
        }
      }

      String binaryRefsDescription =
          Messages.format(
              RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description,
              BasicElementLabels.getJavaElementName(getCurrentElementName()));
      ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);

      initializeMethodsToRename(new SubProgressMonitor(pm, 1), binaryRefs);
      pm.setTaskName(
          RefactoringCoreMessages.RenameMethodRefactoring_taskName_searchingForReferences);
      fOccurrences = getOccurrences(new SubProgressMonitor(pm, 3), result, binaryRefs);
      binaryRefs.addErrorIfNecessary(result);

      pm.setTaskName(
          RefactoringCoreMessages.RenameMethodRefactoring_taskName_checkingPreconditions);

      if (fUpdateReferences) result.merge(checkRelatedMethods());

      result.merge(analyzeCompilationUnits()); // removes CUs with syntax errors
      pm.worked(1);

      if (result.hasFatalError()) return result;

      createChanges(new SubProgressMonitor(pm, 1), result);
      if (fUpdateReferences & mustAnalyzeShadowing)
        result.merge(analyzeRenameChanges(new SubProgressMonitor(pm, 1)));
      else pm.worked(1);

      return result;
    } finally {
      pm.done();
    }
  }