/* (non-Javadoc)
   * @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#createTextChange()
   */
  protected TextChange createTextChange() throws CoreException {
    CompilationUnitChange createChange = fFix.createChange(null);
    createChange.setSaveMode(TextFileChange.LEAVE_DIRTY);

    if (fFix instanceof ILinkedFix) {
      setLinkedProposalModel(((ILinkedFix) fFix).getLinkedPositions());
    }

    return createChange;
  }
Ejemplo n.º 2
0
  private RefactoringStatus addDelegates() throws JavaModelException, CoreException {

    RefactoringStatus status = new RefactoringStatus();
    CompilationUnitRewrite rewrite = new CompilationUnitRewrite(fField.getCompilationUnit());
    rewrite.setResolveBindings(true);

    // add delegate for the field
    if (RefactoringAvailabilityTester.isDelegateCreationAvailable(fField)) {
      FieldDeclaration fieldDeclaration =
          ASTNodeSearchUtil.getFieldDeclarationNode(fField, rewrite.getRoot());
      if (fieldDeclaration.fragments().size() > 1) {
        status.addWarning(
            Messages.format(
                RefactoringCoreMessages
                    .DelegateCreator_cannot_create_field_delegate_more_than_one_fragment,
                BasicElementLabels.getJavaElementName(fField.getElementName())),
            JavaStatusContext.create(fField));
      } else if (((VariableDeclarationFragment) fieldDeclaration.fragments().get(0))
              .getInitializer()
          == null) {
        status.addWarning(
            Messages.format(
                RefactoringCoreMessages.DelegateCreator_cannot_create_field_delegate_no_initializer,
                BasicElementLabels.getJavaElementName(fField.getElementName())),
            JavaStatusContext.create(fField));
      } else {
        DelegateFieldCreator creator = new DelegateFieldCreator();
        creator.setDeclareDeprecated(fDelegateDeprecation);
        creator.setDeclaration(fieldDeclaration);
        creator.setNewElementName(getNewElementName());
        creator.setSourceRewrite(rewrite);
        creator.prepareDelegate();
        creator.createEdit();
      }
    }

    // add delegates for getter and setter methods
    // there may be getters even if the field is static final
    if (getGetter() != null && fRenameGetter)
      addMethodDelegate(getGetter(), getNewGetterName(), rewrite);
    if (getSetter() != null && fRenameSetter)
      addMethodDelegate(getSetter(), getNewSetterName(), rewrite);

    final CompilationUnitChange change = rewrite.createChange(true);
    if (change != null) {
      change.setKeepPreviewEdits(true);
      fChangeManager.manage(fField.getCompilationUnit(), change);
    }

    return status;
  }
  /**
   * Removes the current variable declaration from the AST and inserts it into the lowest possible
   * scope where the variable is first used. Returns the modification to the AST within a Change
   * object.
   */
  private Change recordASTModifications() {
    AST ast = compilationUnit.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);

    // duplicate the original variable declaration in lower scope before getting rid of it
    VariableDeclarationStatement oldDeclaration =
        (VariableDeclarationStatement) variableVisitor.getDeclaration();

    assert variableVisitor.getFirstAssignment() instanceof Assignment;
    Assignment variableAssignment = (Assignment) variableVisitor.getFirstAssignment();
    ASTNode newScopeParent = variableAssignment.getParent().getParent();

    String codeString = oldDeclaration.toString();
    ASTNode newDeclaration =
        rewriter.createStringPlaceholder(
            codeString.substring(0, codeString.length() - 1),
            ASTNode.VARIABLE_DECLARATION_STATEMENT);

    ListRewrite listRewrite = rewriter.getListRewrite(newScopeParent, Block.STATEMENTS_PROPERTY);
    listRewrite.insertAt(newDeclaration, 0, null);

    // get rid of the higher scope declaration
    rewriter.remove(oldDeclaration, null);

    ICompilationUnit iCompUnit = method.getCompilationUnit();

    final String description = "ReduceScopeOfVariable";
    final String comment = "ReduceScopeOfVariable does blah...";

    // record the change
    CompilationUnitChange change =
        new CompilationUnitChange("Reduce scope of variable", iCompUnit) {
          public ChangeDescriptor getDescriptor() {
            Map<Object, Object> arguments = new HashMap<Object, Object>();
            arguments.put("method", method);
            arguments.put("var", varName);
            return new RefactoringChangeDescriptor(
                new ReduceScopeOfVariableDescriptor(
                    method.getJavaProject().getElementName(), description, comment, arguments));
          }
        };
    try {
      change.setEdit(rewriter.rewriteAST());
    } catch (Exception e) {
    }

    return change;
  }
 @Override
 protected CompilationUnitChange getChange(ICompilationUnit compilationUnit) {
   CompilationUnitChange change = new CompilationUnitChange("", compilationUnit);
   MultiTextEdit edit = new MultiTextEdit();
   change.setEdit(edit);
   try {
     MarkerResolutionUtils.updateAnnotation(
         EnumJaxrsClassname.RETENTION.simpleName,
         compilationUnit,
         type,
         "(ElementType.METHOD)",
         edit);
   } catch (JavaModelException e) {
     Logger.error(
         "Failed to add @Retention annotation on type " + type.getFullyQualifiedName(), e);
   }
   return change;
 }
  /* non Java-doc
   * @see IRefactoring#createChange(IProgressMonitor)
   */
  @Override
  public Change createChange(IProgressMonitor pm) throws CoreException {
    final String NN = ""; // $NON-NLS-1$
    if (pm == null) pm = new NullProgressMonitor();
    pm.beginTask(NN, 2);
    try {
      final CompilationUnitChange result = new CompilationUnitChange(getName(), fCUnit);
      if (fLeaveDirty) result.setSaveMode(TextFileChange.LEAVE_DIRTY);
      MultiTextEdit root = new MultiTextEdit();
      result.setEdit(root);
      fRewriter = ASTRewrite.create(fAnalyzer.getEnclosingBodyDeclaration().getAST());
      fRewriter.setTargetSourceRangeComputer(
          new SelectionAwareSourceRangeComputer(
              fAnalyzer.getSelectedNodes(),
              fCUnit.getBuffer(),
              fSelection.getOffset(),
              fSelection.getLength()));
      fImportRewrite = StubUtility.createImportRewrite(fRootNode, true);

      fLinkedProposalModel = new LinkedProposalModel();

      fScope =
          CodeScopeBuilder.perform(fAnalyzer.getEnclosingBodyDeclaration(), fSelection)
              .findScope(fSelection.getOffset(), fSelection.getLength());
      fScope.setCursor(fSelection.getOffset());

      fSelectedNodes = fAnalyzer.getSelectedNodes();

      createTryCatchStatement(fCUnit.getBuffer(), fCUnit.findRecommendedLineSeparator());

      if (fImportRewrite.hasRecordedChanges()) {
        TextEdit edit = fImportRewrite.rewriteImports(null);
        root.addChild(edit);
        result.addTextEditGroup(new TextEditGroup(NN, new TextEdit[] {edit}));
      }
      TextEdit change = fRewriter.rewriteAST();
      root.addChild(change);
      result.addTextEditGroup(new TextEditGroup(NN, new TextEdit[] {change}));
      return result;
    } finally {
      pm.done();
    }
  }
  private void checkSource(SubProgressMonitor monitor, RefactoringStatus result)
      throws CoreException {
    String newCuSource = fChange.getPreviewContent(new NullProgressMonitor());
    CompilationUnit newCUNode =
        new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL)
            .parse(newCuSource, fCu, true, true, monitor);

    IProblem[] newProblems =
        RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCuRewrite.getRoot());
    for (int i = 0; i < newProblems.length; i++) {
      IProblem problem = newProblems[i];
      if (problem.isError())
        result.addEntry(
            new RefactoringStatusEntry(
                (problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING),
                problem.getMessage(),
                new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
    }
  }
 @Override
 public Change createChange(IProgressMonitor monitor) throws CoreException {
   ExtractConstantDescriptor descriptor = createRefactoringDescriptor();
   fChange.setDescriptor(new RefactoringChangeDescriptor(descriptor));
   return fChange;
 }
  public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
    pm.beginTask("", 20); // $NON-NLS-1$
    fChangeManager = new TextChangeManager();
    RefactoringStatus result = new RefactoringStatus();
    fSourceProvider.initialize();
    fTargetProvider.initialize();

    pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
    RefactoringStatus searchStatus = new RefactoringStatus();
    String binaryRefsDescription =
        Messages.format(
            RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description,
            BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName()));
    ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
    ICompilationUnit[] units =
        fTargetProvider.getAffectedCompilationUnits(
            searchStatus, binaryRefs, new SubProgressMonitor(pm, 1));
    binaryRefs.addErrorIfNecessary(searchStatus);
    if (searchStatus.hasFatalError()) {
      result.merge(searchStatus);
      return result;
    }

    IFile[] filesToBeModified = getFilesToBeModified(units);
    result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
    if (result.hasFatalError()) return result;
    result.merge(
        ResourceChangeChecker.checkFilesToBeChanged(
            filesToBeModified, new SubProgressMonitor(pm, 1)));
    checkOverridden(result, new SubProgressMonitor(pm, 4));
    IProgressMonitor sub = new SubProgressMonitor(pm, 15);
    sub.beginTask("", units.length * 3); // $NON-NLS-1$
    for (int c = 0; c < units.length; c++) {
      ICompilationUnit unit = units[c];
      sub.subTask(
          Messages.format(
              RefactoringCoreMessages.InlineMethodRefactoring_processing,
              BasicElementLabels.getFileName(unit)));
      CallInliner inliner = null;
      try {
        boolean added = false;
        MultiTextEdit root = new MultiTextEdit();
        CompilationUnitChange change = (CompilationUnitChange) fChangeManager.get(unit);
        change.setEdit(root);
        BodyDeclaration[] bodies =
            fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
        if (bodies.length == 0) continue;
        inliner = new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider);
        for (int b = 0; b < bodies.length; b++) {
          BodyDeclaration body = bodies[b];
          inliner.initialize(body);
          RefactoringStatus nestedInvocations = new RefactoringStatus();
          ASTNode[] invocations =
              removeNestedCalls(
                  nestedInvocations,
                  unit,
                  fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
          for (int i = 0; i < invocations.length; i++) {
            ASTNode invocation = invocations[i];
            result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
            if (result.hasFatalError()) break;
            if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
              added = true;
              TextEditGroup group =
                  new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
              change.addTextEditGroup(group);
              result.merge(inliner.perform(group));
            } else {
              fDeleteSource = false;
            }
          }
          // do this after we have inlined the method calls. We still want
          // to generate the modifications.
          if (!nestedInvocations.isOK()) {
            result.merge(nestedInvocations);
            fDeleteSource = false;
          }
        }
        if (!added) {
          fChangeManager.remove(unit);
        } else {
          root.addChild(inliner.getModifications());
          ImportRewrite rewrite = inliner.getImportEdit();
          if (rewrite.hasRecordedChanges()) {
            TextEdit edit = rewrite.rewriteImports(null);
            if (edit instanceof MultiTextEdit
                ? ((MultiTextEdit) edit).getChildrenSize() > 0
                : true) {
              root.addChild(edit);
              change.addTextEditGroup(
                  new TextEditGroup(
                      RefactoringCoreMessages.InlineMethodRefactoring_edit_import,
                      new TextEdit[] {edit}));
            }
          }
        }
      } finally {
        if (inliner != null) inliner.dispose();
      }
      sub.worked(1);
      if (sub.isCanceled()) throw new OperationCanceledException();
    }
    result.merge(searchStatus);
    sub.done();
    pm.done();
    return result;
  }