Exemplo n.º 1
0
 // ----------
 private RefactoringStatus checkAccessor(
     IProgressMonitor pm, IMethod existingAccessor, String newAccessorName) throws CoreException {
   RefactoringStatus result = new RefactoringStatus();
   result.merge(checkAccessorDeclarations(pm, existingAccessor));
   result.merge(checkNewAccessor(existingAccessor, newAccessorName));
   return result;
 }
  private RefactoringStatus checkExpression() throws JavaModelException {
    RefactoringStatus result = new RefactoringStatus();
    result.merge(checkExpressionBinding());
    if (result.hasFatalError()) return result;
    checkAllStaticFinal();

    IExpressionFragment selectedExpression = getSelectedExpression();
    Expression associatedExpression = selectedExpression.getAssociatedExpression();
    if (associatedExpression instanceof NullLiteral)
      result.merge(
          RefactoringStatus.createFatalErrorStatus(
              RefactoringCoreMessages.ExtractConstantRefactoring_null_literals));
    else if (!ConstantChecks.isLoadTimeConstant(selectedExpression))
      result.merge(
          RefactoringStatus.createFatalErrorStatus(
              RefactoringCoreMessages.ExtractConstantRefactoring_not_load_time_constant));
    else if (associatedExpression instanceof SimpleName) {
      if (associatedExpression.getParent() instanceof QualifiedName
              && associatedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY
          || associatedExpression.getParent() instanceof FieldAccess
              && associatedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY)
        return RefactoringStatus.createFatalErrorStatus(
            RefactoringCoreMessages.ExtractConstantRefactoring_select_expression);
    }

    return result;
  }
Exemplo n.º 3
0
  /**
   * Final check before the actual refactoring
   *
   * @return status
   * @throws OperationCanceledException
   */
  public RefactoringStatus checkFinalConditions() throws OperationCanceledException {
    RefactoringStatus status = new RefactoringStatus();
    IContainer destination = fProcessor.getDestination();
    IProject sourceProject = fProcessor.getSourceSelection()[0].getProject();
    IProject destinationProject = destination.getProject();
    if (sourceProject != destinationProject)
      status.merge(MoveUtils.checkMove(phpFiles, sourceProject, destination));

    // Checks if one of the resources already exists with the same name in
    // the destination
    IPath dest = fProcessor.getDestination().getFullPath();
    IResource[] sourceResources = fProcessor.getSourceSelection();

    for (IResource element : sourceResources) {
      String newFilePath = dest.toOSString() + File.separatorChar + element.getName();
      IResource resource =
          ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(newFilePath));
      if (resource != null && resource.exists()) {
        status.merge(
            RefactoringStatus.createFatalErrorStatus(
                NLS.bind(
                    PhpRefactoringCoreMessages.getString("MoveDelegate.6"),
                    element.getName(),
                    dest.toOSString()))); // $NON-NLS-1$
      }
    }
    return status;
  }
 private RefactoringStatus validatePage(boolean text) {
   RefactoringStatus result = new RefactoringStatus();
   if (text) {
     result.merge(validateMethodName());
     result.merge(validateParameters());
   } else {
     result.merge(validateParameters());
     result.merge(validateMethodName());
   }
   return result;
 }
Exemplo n.º 5
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));
   }
 }
  public RefactoringStatus checkActivationBasics(CompilationUnit rootNode) throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    fRootNode = rootNode;

    fAnalyzer = new SurroundWithTryCatchAnalyzer(fCUnit, fSelection);
    fRootNode.accept(fAnalyzer);
    result.merge(fAnalyzer.getStatus());
    ITypeBinding[] exceptions = fAnalyzer.getExceptions();
    if (fIsMultiCatch && (exceptions == null || exceptions.length <= 1)) {
      result.merge(
          RefactoringStatus.createWarningStatus(
              RefactoringCoreMessages.SurroundWithTryCatchRefactoring_notMultipleexceptions));
    }
    return result;
  }
Exemplo n.º 8
0
  @Override
  public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
    pm.beginTask(RefactoringCoreMessages.ExtractMethodRefactoring_checking_new_name, 3);
    pm.subTask(EMPTY);

    RefactoringStatus result = checkMethodName();
    pm.worked(1);

    result.merge(checkParameterNames());
    pm.worked(1);

    result.merge(checkPossibleConflicts(new SubProgressMonitor(pm, 1)));

    pm.done();
    return result;
  }
  private void failHelper1(
      int startLine,
      int startColumn,
      int endLine,
      int endColumn,
      boolean makeFinal,
      String className,
      int visibility,
      int expectedSeverity)
      throws Exception {
    ICompilationUnit cu = createCUfromTestFile(getPackageP(), false, true);
    ISourceRange selection =
        TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn);
    ConvertAnonymousToNestedRefactoring ref =
        new ConvertAnonymousToNestedRefactoring(cu, selection.getOffset(), selection.getLength());

    RefactoringStatus preconditionResult = ref.checkInitialConditions(new NullProgressMonitor());
    if (preconditionResult.isOK()) preconditionResult = null;
    assertEquals("activation was supposed to be successful", null, preconditionResult);

    ref.setClassName(className);
    ref.setDeclareFinal(makeFinal);
    ref.setVisibility(visibility);

    if (preconditionResult == null)
      preconditionResult = ref.checkFinalConditions(new NullProgressMonitor());
    else preconditionResult.merge(ref.checkFinalConditions(new NullProgressMonitor()));
    if (preconditionResult.isOK()) preconditionResult = null;
    assertNotNull("precondition was supposed to fail", preconditionResult);

    assertEquals("incorrect severity:", expectedSeverity, preconditionResult.getSeverity());
  }
  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) {
        JavaScriptUnit 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;

      return result;
    } finally {
      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;
  }
Exemplo n.º 12
0
 @Override
 public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
   pm.beginTask("", 2); // $NON-NLS-1$
   RefactoringStatus result;
   try {
     result = new RefactoringStatus();
     IJavaElement element = (IJavaElement) getModifiedElement();
     // don't check for read-only since we don't go through
     // validate edit.
     result.merge(super.isValid(new SubProgressMonitor(pm, 1)));
     if (result.hasFatalError()) return result;
     if (element != null && element.exists() && element instanceof IPackageFragment) {
       IPackageFragment pack = (IPackageFragment) element;
       if (fRenameSubpackages) {
         IPackageFragment[] allPackages = JavaElementUtil.getPackageAndSubpackages(pack);
         SubProgressMonitor subPm = new SubProgressMonitor(pm, 1);
         subPm.beginTask("", allPackages.length); // $NON-NLS-1$
         for (int i = 0; i < allPackages.length; i++) {
           // don't check for read-only since we don't go through
           // validate edit.
           checkIfModifiable(result, allPackages[i].getResource(), VALIDATE_NOT_DIRTY);
           if (result.hasFatalError()) return result;
           isValid(result, allPackages[i], new SubProgressMonitor(subPm, 1));
         }
       } else {
         isValid(result, pack, new SubProgressMonitor(pm, 1));
       }
     }
   } finally {
     pm.done();
   }
   return result;
 }
Exemplo n.º 13
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;
  }
 public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
   RefactoringStatus result = new RefactoringStatus();
   if (fSourceProvider == null && Invocations.isInvocation(fInitialNode)) {
     fSourceProvider = resolveSourceProvider(result, fInitialTypeRoot, fInitialNode);
     if (result.hasFatalError()) return result;
   }
   result.merge(fSourceProvider.checkActivation());
   result.merge(fTargetProvider.checkActivation());
   return result;
 }
  private void checkFunction(final RefactoringStatus result) {
    if ((fFunction.getElementType() & IRElement.MASK_C2) != IRElement.R_COMMON_FUNCTION
        && (fFunction.getElementType() & IRElement.MASK_C2) != IRElement.R_COMMON_FUNCTION) {
      result.merge(
          RefactoringStatus.createFatalErrorStatus(
              Messages.FunctionToS4Method_error_SelectionAlreadyS4_message));
      return;
    }
    final RAstNode node = (RAstNode) fFunction.getAdapter(IAstNode.class);
    if (RAst.hasErrors(node)) {
      result.merge(
          RefactoringStatus.createWarningStatus(
              Messages.FunctionToS4Method_warning_SelectionSyntaxError_message));
    }
    //		if (fSelectionRegion != null
    //				&& (fSelectionRegion.getOffset() != fOperationRegion.getOffset() ||
    // fSelectionRegion.getLength() != fOperationRegion.getLength())) {
    //			result.merge(RefactoringStatus.createWarningStatus("The selected code does not equal
    // exactly the found expression(s)."));
    //		}

    RElementName elementName = fFunction.getElementName();
    while (elementName.getNextSegment() != null) {
      elementName = elementName.getNamespace();
    }
    fFunctionName = elementName.getDisplayName();

    final ArgsDefinition argsDef = fFunction.getArgsDefinition();
    final int count = (argsDef != null) ? argsDef.size() : 0;
    fVariablesList = new ArrayList(count);
    boolean dots = false;
    for (int i = 0; i < count; i++) {
      final Arg arg = argsDef.get(i);
      final Variable variable = new Variable(arg);
      if (variable.getName().equals(RTerminal.S_ELLIPSIS)) {
        dots = true;
        variable.init(true);
      } else {
        variable.init(!dots);
      }
      fVariablesList.add(variable);
    }
  }
 private RefactoringStatus validateMethodName() {
   RefactoringStatus result = new RefactoringStatus();
   String text = getText();
   if ("".equals(text)) { // $NON-NLS-1$
     result.addFatalError(RefactoringMessages.ExtractMethodInputPage_validation_emptyMethodName);
     return result;
   }
   result.merge(fRefactoring.checkMethodName());
   return result;
 }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {

    RefactoringStatus status = new RefactoringStatus();

    if ((!(getTargetFragment() instanceof TestMethod)) || (getTargetFragment() == null)) {
      status.merge(
          RefactoringStatus.createFatalErrorStatus("Selection is not valid. Select a method."));
    } else {
      targetMethod = (TestMethod) getTargetFragment();
    }

    if (status.hasEntries()) {
      status.merge(
          RefactoringStatus.createFatalErrorStatus(
              "Note: Select the bigger method wich groups smaller ones, press group incremental tests, all asserts will be brought to the selected method, the smaller methods will be removed."));
    }
    return status;
  }
  private RefactoringStatus analyzeRenameChanges(IProgressMonitor pm) throws CoreException {
    ICompilationUnit[] newDeclarationWCs = null;
    try {
      pm.beginTask("", 4); // $NON-NLS-1$
      RefactoringStatus result = new RefactoringStatus();
      ICompilationUnit[] declarationCUs = getDeclarationCUs();
      newDeclarationWCs =
          RenameAnalyzeUtil.createNewWorkingCopies(
              declarationCUs, fChangeManager, fWorkingCopyOwner, new SubProgressMonitor(pm, 1));

      IMethod[] wcOldMethods = new IMethod[fMethodsToRename.size()];
      IMethod[] wcNewMethods = new IMethod[fMethodsToRename.size()];
      int i = 0;
      for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); i++) {
        IMethod method = iter.next();
        ICompilationUnit newCu =
            RenameAnalyzeUtil.findWorkingCopyForCu(newDeclarationWCs, method.getCompilationUnit());
        IType typeWc =
            (IType) JavaModelUtil.findInCompilationUnit(newCu, method.getDeclaringType());
        if (typeWc == null) {
          // should not happen
          i--;
          wcOldMethods =
              CollectionsUtil.toArray(
                  Arrays.asList(wcOldMethods).subList(0, wcOldMethods.length - 1), IMethod.class);
          wcNewMethods =
              CollectionsUtil.toArray(
                  Arrays.asList(wcNewMethods).subList(0, wcNewMethods.length - 1), IMethod.class);
          continue;
        }
        wcOldMethods[i] = getMethodInWorkingCopy(method, getCurrentElementName(), typeWc);
        wcNewMethods[i] = getMethodInWorkingCopy(method, getNewElementName(), typeWc);
      }

      //			SearchResultGroup[] newOccurrences= findNewOccurrences(newMethods, newDeclarationWCs, new
      // SubProgressMonitor(pm, 3));
      SearchResultGroup[] newOccurrences =
          batchFindNewOccurrences(
              wcNewMethods, wcOldMethods, newDeclarationWCs, new SubProgressMonitor(pm, 3), result);

      result.merge(
          RenameAnalyzeUtil.analyzeRenameChanges2(
              fChangeManager, fOccurrences, newOccurrences, getNewElementName()));
      return result;
    } finally {
      pm.done();
      if (newDeclarationWCs != null) {
        for (int i = 0; i < newDeclarationWCs.length; i++) {
          newDeclarationWCs[i].discardWorkingCopy();
        }
      }
    }
  }
 private RefactoringStatus validateParameters() {
   RefactoringStatus result = new RefactoringStatus();
   for (ParameterInfo parameter : fRefactoring.getParameters()) {
     if ("".equals(parameter.getNewName())) {
       result.addFatalError(
           RefactoringMessages.ExtractMethodInputPage_validation_emptyParameterName);
       return result;
     }
   }
   result.merge(fRefactoring.checkParameterNames());
   return result;
 }
Exemplo n.º 20
0
  /**
   * This method analyzes a set of local variable renames inside one cu. It checks whether any new
   * compile errors have been introduced by the rename(s) and whether the correct node(s) has/have
   * been renamed.
   *
   * @param analyzePackages the LocalAnalyzePackages containing the information about the local
   *     renames
   * @param cuChange the TextChange containing all local variable changes to be applied.
   * @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit
   * @param recovery whether statements and bindings recovery should be performed when parsing the
   *     changed CU
   * @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are
   *     found
   * @throws CoreException thrown if there was an error greating the preview content of the change
   */
  public static RefactoringStatus analyzeLocalRenames(
      LocalAnalyzePackage[] analyzePackages,
      TextChange cuChange,
      CompilationUnit oldCUNode,
      boolean recovery)
      throws CoreException {

    RefactoringStatus result = new RefactoringStatus();
    ICompilationUnit compilationUnit = (ICompilationUnit) oldCUNode.getJavaElement();

    String newCuSource = cuChange.getPreviewContent(new NullProgressMonitor());
    CompilationUnit newCUNode =
        new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL)
            .parse(newCuSource, compilationUnit, true, recovery, null);

    result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode));
    if (result.hasError()) return result;

    for (int i = 0; i < analyzePackages.length; i++) {
      ASTNode enclosing =
          getEnclosingBlockOrMethodOrLambda(
              analyzePackages[i].fDeclarationEdit, cuChange, newCUNode);

      // get new declaration
      IRegion newRegion =
          RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange);
      ASTNode newDeclaration =
          NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength());
      Assert.isTrue(newDeclaration instanceof Name);

      VariableDeclaration declaration = getVariableDeclaration((Name) newDeclaration);
      Assert.isNotNull(declaration);

      SimpleName[] problemNodes =
          ProblemNodeFinder.getProblemNodes(
              enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange);
      result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes));
    }
    return result;
  }
Exemplo n.º 21
0
  private RefactoringStatus createChanges(IProgressMonitor pm) throws CoreException {
    pm.beginTask(RefactoringCoreMessages.RenameFieldRefactoring_checking, 10);
    RefactoringStatus result = new RefactoringStatus();
    if (!fIsComposite) fChangeManager.clear();

    // Delegate creation requires ASTRewrite which
    // creates a new change -> do this first.
    if (fDelegateUpdating) result.merge(addDelegates());

    addDeclarationUpdate();

    if (fUpdateReferences) {
      addReferenceUpdates(new SubProgressMonitor(pm, 1));
      result.merge(analyzeRenameChanges(new SubProgressMonitor(pm, 2)));
      if (result.hasFatalError()) return result;
    } else {
      pm.worked(3);
    }

    if (getGetter() != null && fRenameGetter) {
      addGetterOccurrences(new SubProgressMonitor(pm, 1), result);
    } else {
      pm.worked(1);
    }

    if (getSetter() != null && fRenameSetter) {
      addSetterOccurrences(new SubProgressMonitor(pm, 1), result);
    } else {
      pm.worked(1);
    }

    if (fUpdateTextualMatches) {
      addTextMatches(new SubProgressMonitor(pm, 5));
    } else {
      pm.worked(5);
    }
    pm.done();
    return result;
  }
Exemplo n.º 22
0
 @Override
 public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
   try {
     pm.beginTask("", 4); // $NON-NLS-1$
     RefactoringStatus result = new RefactoringStatus();
     // prepare AST
     utils = new ExtractUtils(unit);
     unitNode = utils.getUnitNode();
     pm.worked(1);
     // check selection
     result.merge(checkSelection(new SubProgressMonitor(pm, 3)));
     if (result.hasFatalError()) {
       return result;
     }
     // prepare parts
     result.merge(initializeParameters());
     initializeOccurrences();
     // done
     return result;
   } finally {
     pm.done();
   }
 }
 /*
  * Used from www.eclipse.org/articles/article.php?file=Article-Unleashing-the-Power-of-Refactoring/index.html
  */
 @Override
 public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
     throws CoreException, OperationCanceledException {
   RefactoringStatus status = new RefactoringStatus();
   try {
     pm.beginTask("Checking preconditions...", 1);
     if (method == null) {
       status.merge(RefactoringStatus.createFatalErrorStatus("Method has not been specified."));
     } else if (varName == null) {
       status.merge(RefactoringStatus.createFatalErrorStatus("Variable has not been specified."));
     } else if (!method.exists()) {
       status.merge(RefactoringStatus.createFatalErrorStatus("Method does not exist."));
     } else {
       if (!method.isBinary() && !method.getCompilationUnit().isStructureKnown()) {
         status.merge(
             RefactoringStatus.createFatalErrorStatus(
                 "Compilation unit contains compile errors."));
       }
     }
   } finally {
     pm.done();
   }
   return status;
 }
  @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;
  }
Exemplo n.º 25
0
  // ----------------
  private RefactoringStatus analyzeRenameChanges(IProgressMonitor pm) throws CoreException {
    ICompilationUnit[] newWorkingCopies = null;
    WorkingCopyOwner newWCOwner = new WorkingCopyOwner() {
          /* must subclass */
        };
    try {
      pm.beginTask("", 2); // $NON-NLS-1$
      RefactoringStatus result = new RefactoringStatus();
      SearchResultGroup[] oldReferences = fReferences;

      List compilationUnitsToModify = new ArrayList();
      if (fIsComposite) {
        // limited change set, no accessors.
        for (int i = 0; i < oldReferences.length; i++)
          compilationUnitsToModify.add(oldReferences[i].getCompilationUnit());
        compilationUnitsToModify.add(fField.getCompilationUnit());
      } else {
        // include all cus, including accessors
        compilationUnitsToModify.addAll(Arrays.asList(fChangeManager.getAllCompilationUnits()));
      }

      newWorkingCopies =
          RenameAnalyzeUtil.createNewWorkingCopies(
              (ICompilationUnit[])
                  compilationUnitsToModify.toArray(
                      new ICompilationUnit[compilationUnitsToModify.size()]),
              fChangeManager,
              newWCOwner,
              new SubProgressMonitor(pm, 1));

      SearchResultGroup[] newReferences =
          getNewReferences(new SubProgressMonitor(pm, 1), result, newWCOwner, newWorkingCopies);
      result.merge(
          RenameAnalyzeUtil.analyzeRenameChanges2(
              fChangeManager, oldReferences, newReferences, getNewElementName()));
      return result;
    } finally {
      pm.done();
      if (newWorkingCopies != null) {
        for (int i = 0; i < newWorkingCopies.length; i++) {
          newWorkingCopies[i].discardWorkingCopy();
        }
      }
    }
  }
  @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;
  }
Exemplo n.º 27
0
 private RefactoringStatus checkNestedHierarchy(IType type) throws CoreException {
   IType[] nestedTypes = type.getTypes();
   if (nestedTypes == null) return null;
   RefactoringStatus result = new RefactoringStatus();
   for (int i = 0; i < nestedTypes.length; i++) {
     IField otherField = nestedTypes[i].getField(getNewElementName());
     if (otherField.exists()) {
       String msg =
           Messages.format(
               RefactoringCoreMessages.RenameFieldRefactoring_hiding,
               new String[] {
                 BasicElementLabels.getJavaElementName(fField.getElementName()),
                 BasicElementLabels.getJavaElementName(getNewElementName()),
                 BasicElementLabels.getJavaElementName(nestedTypes[i].getFullyQualifiedName('.'))
               });
       result.addWarning(msg, JavaStatusContext.create(otherField));
     }
     result.merge(checkNestedHierarchy(nestedTypes[i]));
   }
   return result;
 }
  private void helper1(
      int startLine,
      int startColumn,
      int endLine,
      int endColumn,
      boolean makeFinal,
      boolean makeStatic,
      String className,
      int visibility)
      throws Exception {
    ICompilationUnit cu = createCUfromTestFile(getPackageP(), true, true);
    ISourceRange selection =
        TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn);
    ConvertAnonymousToNestedRefactoring ref =
        new ConvertAnonymousToNestedRefactoring(cu, selection.getOffset(), selection.getLength());

    RefactoringStatus preconditionResult = ref.checkInitialConditions(new NullProgressMonitor());
    if (preconditionResult.isOK()) preconditionResult = null;
    assertEquals("activation was supposed to be successful", null, preconditionResult);

    ref.setClassName(className);
    ref.setDeclareFinal(makeFinal);
    ref.setDeclareStatic(makeStatic);
    ref.setVisibility(visibility);

    if (preconditionResult == null)
      preconditionResult = ref.checkFinalConditions(new NullProgressMonitor());
    else preconditionResult.merge(ref.checkFinalConditions(new NullProgressMonitor()));
    if (preconditionResult.isOK()) preconditionResult = null;
    assertEquals("precondition was supposed to pass", null, preconditionResult);

    performChange(ref, false);

    IPackageFragment pack = (IPackageFragment) cu.getParent();
    String newCuName = getSimpleTestFileName(true, true);
    ICompilationUnit newcu = pack.getCompilationUnit(newCuName);
    assertTrue(newCuName + " does not exist", newcu.exists());
    assertEqualLines(getFileContents(getTestFileName(true, false)), newcu.getSource());
  }
  private RefactoringStatus checkSelection(IProgressMonitor pm) throws JavaModelException {
    try {
      pm.beginTask("", 2); // $NON-NLS-1$

      IExpressionFragment selectedExpression = getSelectedExpression();

      if (selectedExpression == null) {
        String message = RefactoringCoreMessages.ExtractConstantRefactoring_select_expression;
        return CodeRefactoringUtil.checkMethodSyntaxErrors(
            fSelectionStart, fSelectionLength, fCuRewrite.getRoot(), message);
      }
      pm.worked(1);

      RefactoringStatus result = new RefactoringStatus();
      result.merge(checkExpression());
      if (result.hasFatalError()) return result;
      pm.worked(1);

      return result;
    } finally {
      pm.done();
    }
  }
Exemplo n.º 30
0
 /** Checks if the parameter names are valid. */
 public RefactoringStatus checkParameterNames() {
   RefactoringStatus result = new RefactoringStatus();
   for (ParameterInfo parameter : parameters) {
     result.merge(Checks.checkParameter(parameter.getNewName()));
     for (ParameterInfo other : parameters) {
       if (parameter != other && StringUtils.equals(other.getNewName(), parameter.getNewName())) {
         result.addError(
             Messages.format(
                 RefactoringCoreMessages.ExtractMethodRefactoring_error_sameParameter,
                 other.getNewName()));
         return result;
       }
     }
     if (parameter.isRenamed() && usedNames.contains(parameter.getNewName())) {
       result.addError(
           Messages.format(
               RefactoringCoreMessages.ExtractMethodRefactoring_error_nameInUse,
               parameter.getNewName()));
       return result;
     }
   }
   return result;
 }