private void replaceExpressionsWithConstant() throws JavaModelException {
    ASTRewrite astRewrite = fCuRewrite.getASTRewrite();
    AST ast = astRewrite.getAST();

    IASTFragment[] fragmentsToReplace = getFragmentsToReplace();
    for (int i = 0; i < fragmentsToReplace.length; i++) {
      IASTFragment fragment = fragmentsToReplace[i];
      ASTNode node = fragment.getAssociatedNode();
      boolean inTypeDeclarationAnnotation = isInTypeDeclarationAnnotation(node);
      if (inTypeDeclarationAnnotation && JdtFlags.VISIBILITY_STRING_PRIVATE == getVisibility())
        continue;

      SimpleName ref = ast.newSimpleName(fConstantName);
      Name replacement = ref;
      boolean qualifyReference = qualifyReferencesWithDeclaringClassName();
      if (!qualifyReference) {
        qualifyReference = inTypeDeclarationAnnotation;
      }
      if (qualifyReference) {
        replacement =
            ast.newQualifiedName(ast.newSimpleName(getContainingTypeBinding().getName()), ref);
      }
      TextEditGroup description =
          fCuRewrite.createGroupDescription(
              RefactoringCoreMessages.ExtractConstantRefactoring_replace);

      fragment.replace(astRewrite, replacement, description);
      if (fLinkedProposalModel != null)
        fLinkedProposalModel
            .getPositionGroup(KEY_NAME, true)
            .addPosition(astRewrite.track(ref), false);
    }
  }
  private ASTRewrite doAddEnumConst(CompilationUnit astRoot) {
    SimpleName node = fOriginalNode;

    ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding);
    if (newTypeDecl == null) {
      astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
      newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
    }

    if (newTypeDecl != null) {
      AST ast = newTypeDecl.getAST();

      ASTRewrite rewrite = ASTRewrite.create(ast);

      EnumConstantDeclaration constDecl = ast.newEnumConstantDeclaration();
      constDecl.setName(ast.newSimpleName(node.getIdentifier()));

      ListRewrite listRewriter =
          rewrite.getListRewrite(newTypeDecl, EnumDeclaration.ENUM_CONSTANTS_PROPERTY);
      listRewriter.insertLast(constDecl, null);

      addLinkedPosition(rewrite.track(constDecl.getName()), false, KEY_NAME);

      return rewrite;
    }
    return null;
  }
  @Override
  protected ASTRewrite getRewrite() throws CoreException {
    ASTNode boundNode = fAstRoot.findDeclaringNode(fBinding);
    ASTNode declNode = null;
    CompilationUnit newRoot = fAstRoot;
    if (boundNode != null) {
      declNode = boundNode; // is same CU
    } else {
      newRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
      declNode = newRoot.findDeclaringNode(fBinding.getKey());
    }
    ImportRewrite imports = createImportRewrite(newRoot);

    if (declNode instanceof TypeDeclaration) {
      AST ast = declNode.getAST();
      ASTRewrite rewrite = ASTRewrite.create(ast);

      ImportRewriteContext importRewriteContext =
          new ContextSensitiveImportRewriteContext(declNode, imports);
      Type newInterface = imports.addImport(fNewInterface, ast, importRewriteContext);
      ListRewrite listRewrite =
          rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY);
      listRewrite.insertLast(newInterface, null);

      // set up linked mode
      final String KEY_TYPE = "type"; // $NON-NLS-1$
      addLinkedPosition(rewrite.track(newInterface), true, KEY_TYPE);
      return rewrite;
    }
    return null;
  }
  /**
   * Updates the content of <code>cu</code>, modifying the type name and/or package declaration as
   * necessary.
   *
   * @return an AST rewrite or null if no rewrite needed
   */
  private TextEdit updateContent(ICompilationUnit cu, PackageFragment dest, String newName)
      throws JavaModelException {
    String[] currPackageName = ((PackageFragment) cu.getParent()).names;
    String[] destPackageName = dest.names;
    if (Util.equalArraysOrNull(currPackageName, destPackageName) && newName == null) {
      return null; // nothing to change
    } else {
      // ensure cu is consistent (noop if already consistent)
      cu.makeConsistent(this.progressMonitor);

      // GROOVY start
      // don't use the ASTParser if not a Java compilation unit
      if (LanguageSupportFactory.isInterestingSourceFile(cu.getElementName())) {
        // ZALUUM
        // old return updateNonJavaContent(cu, destPackageName, currPackageName, newName);
        return LanguageSupportFactory.updateContent(cu, destPackageName, currPackageName, newName);
        // END ZALUUM
      }
      // GROOVY end

      this.parser.setSource(cu);
      CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
      AST ast = astCU.getAST();
      ASTRewrite rewrite = ASTRewrite.create(ast);
      updateTypeName(cu, astCU, cu.getElementName(), newName, rewrite);
      updatePackageStatement(astCU, destPackageName, rewrite, cu);
      return rewrite.rewriteAST();
    }
  }
  public static void getInvalidQualificationProposals(
      IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ASTNode node = problem.getCoveringNode(context.getASTRoot());
    if (!(node instanceof Name)) {
      return;
    }
    Name name = (Name) node;
    IBinding binding = name.resolveBinding();
    if (!(binding instanceof ITypeBinding)) {
      return;
    }
    ITypeBinding typeBinding = (ITypeBinding) binding;

    AST ast = node.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null);

    String label = CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description;
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    ASTRewriteCorrectionProposal proposal =
        new ASTRewriteCorrectionProposal(
            label,
            context.getCompilationUnit(),
            rewrite,
            IProposalRelevance.QUALIFY_INNER_TYPE_NAME,
            image);

    proposals.add(proposal);
  }
 /**
  * Updates a javadoc tag, by either adding a new one or removing an existing one
  *
  * @param body
  */
 private void updateTag(BodyDeclaration body) {
   Javadoc docnode = body.getJavadoc();
   AST ast = body.getAST();
   if (docnode == null) {
     docnode = ast.newJavadoc();
     rewrite.set(body, body.getJavadocProperty(), docnode, null);
   }
   ListRewrite lrewrite = rewrite.getListRewrite(docnode, Javadoc.TAGS_PROPERTY);
   if (remove) {
     List<TagElement> tags =
         (List<TagElement>) docnode.getStructuralProperty(Javadoc.TAGS_PROPERTY);
     if (tags != null) {
       TagElement tag = null;
       for (int i = 0; i < tags.size(); i++) {
         tag = tags.get(i);
         if (tagname.equals(tag.getTagName())) {
           lrewrite.remove(tag, null);
         }
       }
     }
   } else {
     TagElement newtag = ast.newTagElement();
     newtag.setTagName(tagname);
     lrewrite.insertLast(newtag, null);
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.andmore.android.model.java.JavaClass#addComments()
   */
  @Override
  protected void addComments() throws AndroidException {
    ASTNode todoComment;

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(document.get().toCharArray());

    compUnit = (CompilationUnit) parser.createAST(null);
    ast = compUnit.getAST();
    rewrite = ASTRewrite.create(ast);

    todoComment =
        rewrite.createStringPlaceholder(
            CodeUtilsNLS.MODEL_Common_ToDoPutYourCodeHere, ASTNode.EMPTY_STATEMENT);

    TypeDeclaration receiverClass = (TypeDeclaration) compUnit.types().get(0);
    MethodDeclaration method;
    Block block;

    // Adds the Override annotation and ToDo comment to all overridden
    // methods
    for (int i = 0; i < receiverClass.bodyDeclarations().size(); i++) {
      method = (MethodDeclaration) receiverClass.bodyDeclarations().get(i);

      // Adds the Override annotation
      rewrite
          .getListRewrite(method, method.getModifiersProperty())
          .insertFirst(OVERRIDE_ANNOTATION, null);

      // Adds the ToDo comment
      block = method.getBody();
      rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertFirst(todoComment, null);
    }

    try {
      // Writes the modifications
      TextEdit modifications = rewrite.rewriteAST(document, null);
      modifications.apply(document);
    } catch (IllegalArgumentException e) {
      String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className);

      AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e);
      throw new AndroidException(errMsg);
    } catch (MalformedTreeException e) {
      String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className);

      AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e);
      throw new AndroidException(errMsg);
    } catch (BadLocationException e) {
      String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className);

      AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e);
      throw new AndroidException(errMsg);
    }
  }
  @Override
  protected Statement convert(
      CompilationUnitRewrite cuRewrite, TextEditGroup group, LinkedProposalModel positionGroups)
      throws CoreException {
    ASTRewrite rewrite = cuRewrite.getASTRewrite();
    ImportRewrite importRewrite = cuRewrite.getImportRewrite();

    ForStatement forStatement = getForStatement();

    IJavaProject javaProject =
        ((CompilationUnit) forStatement.getRoot()).getJavaElement().getJavaProject();
    String[] proposals = getVariableNameProposals(fArrayAccess.resolveTypeBinding(), javaProject);

    String parameterName;
    if (fElementDeclaration != null) {
      parameterName = fElementDeclaration.getName().getIdentifier();
    } else {
      parameterName = proposals[0];
    }

    LinkedProposalPositionGroup pg = positionGroups.getPositionGroup(parameterName, true);
    if (fElementDeclaration != null) pg.addProposal(parameterName, null, 10);
    for (int i = 0; i < proposals.length; i++) {
      pg.addProposal(proposals[i], null, 10);
    }

    AST ast = forStatement.getAST();
    EnhancedForStatement result = ast.newEnhancedForStatement();

    SingleVariableDeclaration parameterDeclaration =
        createParameterDeclaration(
            parameterName,
            fElementDeclaration,
            fArrayAccess,
            forStatement,
            importRewrite,
            rewrite,
            group,
            pg,
            fMakeFinal);
    result.setParameter(parameterDeclaration);

    result.setExpression((Expression) rewrite.createCopyTarget(fArrayAccess));

    convertBody(
        forStatement.getBody(), fIndexBinding, fArrayBinding, parameterName, rewrite, group, pg);
    result.setBody(getBody(cuRewrite, group, positionGroups));

    positionGroups.setEndPosition(rewrite.track(result));

    return result;
  }
Esempio n. 9
0
  private Delta deduplicate(CompilationUnit root, ASTRewrite rewrite, Cause cause) {

    final List<ASTNode> nodes = cause.getAffectedNodes();
    final int size = nodes.size();
    final int cloneNumber = size == 0 ? size : size - 1; // minus the original declaration

    if (cloneNumber == 0) {
      throw new RuntimeException("calling deduplicate() when there are no detected clones");
    } else if (cloneNumber >= 1) {
      // NOTE: THIS WORKS ONLY AT METHOD LEVEL, other forms of duplication will
      // will be ignored.

      // The strategy this code follows to perform deduplication is the following:
      // per duplicated method declaration, find all of its invocations. Then
      // rename each found invocation using the name of the original method declaration.
      // After that, remove the duplicated method declaration.
      if (AstUtil.isOfType(MethodDeclaration.class, nodes.get(0))) {
        final MethodDeclaration original = AstUtil.exactCast(MethodDeclaration.class, nodes.get(0));
        final Iterable<ASTNode> rest = Iterables.skip(nodes, 1);
        for (ASTNode eachClone : rest) {
          final MethodDeclaration duplicate = AstUtil.exactCast(MethodDeclaration.class, eachClone);
          final MethodDeclaration copied =
              AstUtil.copySubtree(MethodDeclaration.class, root.getAST(), duplicate);
          final boolean sameReturn = sameReturnType(original, copied);

          if (!sameReturn) { // all or none. We don't do partial deduplication
            throw new RuntimeException(
                "automatic deduplication cannot be done on methods "
                    + "with different return types; please consider "
                    + "manual deduplication.");
          }

          final MethodInvocationVisitor invokesOfDuplication =
              new MethodInvocationVisitor(copied.getName());
          root.accept(invokesOfDuplication);
          final Set<MethodInvocation> invokes = invokesOfDuplication.getMethodInvocations();

          for (MethodInvocation each : invokes) {
            final MethodInvocation copiedInvoke =
                AstUtil.copySubtree(MethodInvocation.class, root.getAST(), each);
            copiedInvoke.setName(root.getAST().newSimpleName(original.getName().getIdentifier()));
            rewrite.replace(each, copiedInvoke, null);
          }

          rewrite.remove(duplicate, null);
        }
      }
    }

    return createDelta(root, rewrite);
  }
  // similar to
  // org.eclipse.jdt.internal.ui.text.correction.ModifierCorrectionSubProcessor.removeOverrideAnnotationProposal(..)
  public void removeDeprecatedAnnotation(
      IDocument document, ICompilationUnit cu, BodyDeclaration decl) {
    Annotation annot = findAnnotation(decl.modifiers());
    if (annot != null) {
      ASTRewrite rewrite = ASTRewrite.create(annot.getAST());
      rewrite.remove(annot, null);

      callASTRewriteCorrectionProposal(getDisplayString(), cu, rewrite, 6, getImage(), document);

      ITextViewer viewer = getViewer(JavaPlugin.getActivePage().getActiveEditor());
      ITrackedNodePosition trackPos = rewrite.track(decl);
      if (trackPos != null && viewer != null) {
        viewer.setSelectedRange(trackPos.getStartPosition(), 0);
      }
    }
  }
 @Override
 protected ASTRewrite getRewrite() throws CoreException {
   AST ast = fBodyDecl.getAST();
   ASTRewrite rewrite = ASTRewrite.create(ast);
   insertMissingJavadocTag(rewrite, fMissingNode, fBodyDecl);
   return rewrite;
 }
  private ASTRewrite doAddParam(CompilationUnit cu) {
    AST ast = cu.getAST();
    SimpleName node = fOriginalNode;

    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(node);
    if (decl instanceof MethodDeclaration) {
      MethodDeclaration methodDeclaration = (MethodDeclaration) decl;

      ASTRewrite rewrite = ASTRewrite.create(ast);

      ImportRewrite imports = createImportRewrite((CompilationUnit) decl.getRoot());
      ImportRewriteContext importRewriteContext =
          new ContextSensitiveImportRewriteContext(decl, imports);

      SingleVariableDeclaration newDecl = ast.newSingleVariableDeclaration();
      newDecl.setType(
          evaluateVariableType(
              ast, imports, importRewriteContext, methodDeclaration.resolveBinding()));
      newDecl.setName(ast.newSimpleName(node.getIdentifier()));

      ListRewrite listRewriter =
          rewrite.getListRewrite(decl, MethodDeclaration.PARAMETERS_PROPERTY);
      listRewriter.insertLast(newDecl, null);

      addLinkedPosition(rewrite.track(node), true, KEY_NAME);

      // add javadoc tag
      Javadoc javadoc = methodDeclaration.getJavadoc();
      if (javadoc != null) {
        HashSet<String> leadingNames = new HashSet<String>();
        for (Iterator<SingleVariableDeclaration> iter = methodDeclaration.parameters().iterator();
            iter.hasNext(); ) {
          SingleVariableDeclaration curr = iter.next();
          leadingNames.add(curr.getName().getIdentifier());
        }
        SimpleName newTagRef = ast.newSimpleName(node.getIdentifier());

        TagElement newTagElement = ast.newTagElement();
        newTagElement.setTagName(TagElement.TAG_PARAM);
        newTagElement.fragments().add(newTagRef);
        TextElement commentStart = ast.newTextElement();
        newTagElement.fragments().add(commentStart);

        addLinkedPosition(rewrite.track(newTagRef), false, KEY_NAME);
        addLinkedPosition(rewrite.track(commentStart), false, "comment_start"); // $NON-NLS-1$

        ListRewrite tagsRewriter = rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
        JavadocTagsSubProcessor.insertTag(tagsRewriter, newTagElement, leadingNames);
      }

      addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
      addLinkedPosition(rewrite.track(newDecl.getName()), false, KEY_NAME);

      return rewrite;
    }
    return null;
  }
 /**
  * Converts an assignment, postfix expression or prefix expression into an assignable equivalent
  * expression using the getter.
  *
  * @param node the assignment/prefix/postfix node
  * @param astRewrite the astRewrite to use
  * @param getterExpression the expression to insert for read accesses or <code>null</code> if such
  *     an expression does not exist
  * @param variableType the type of the variable that the result will be assigned to
  * @param is50OrHigher <code>true</code> if a 5.0 or higher environment can be used
  * @return an expression that can be assigned to the type variableType with node being replaced by
  *     a equivalent expression using the getter
  */
 public static Expression getAssignedValue(
     ASTNode node,
     ASTRewrite astRewrite,
     Expression getterExpression,
     ITypeBinding variableType,
     boolean is50OrHigher) {
   InfixExpression.Operator op = null;
   AST ast = astRewrite.getAST();
   if (isNotInBlock(node)) return null;
   if (node.getNodeType() == ASTNode.ASSIGNMENT) {
     Assignment assignment = ((Assignment) node);
     Expression rightHandSide = assignment.getRightHandSide();
     Expression copiedRightOp = (Expression) astRewrite.createCopyTarget(rightHandSide);
     if (assignment.getOperator() == Operator.ASSIGN) {
       ITypeBinding rightHandSideType = rightHandSide.resolveTypeBinding();
       copiedRightOp =
           createNarrowCastIfNessecary(
               copiedRightOp, rightHandSideType, ast, variableType, is50OrHigher);
       return copiedRightOp;
     }
     if (getterExpression != null) {
       InfixExpression infix = ast.newInfixExpression();
       infix.setLeftOperand(getterExpression);
       infix.setOperator(ASTNodes.convertToInfixOperator(assignment.getOperator()));
       infix.setRightOperand(copiedRightOp);
       ITypeBinding infixType = infix.resolveTypeBinding();
       return createNarrowCastIfNessecary(infix, infixType, ast, variableType, is50OrHigher);
     }
   } else if (node.getNodeType() == ASTNode.POSTFIX_EXPRESSION) {
     PostfixExpression po = (PostfixExpression) node;
     if (po.getOperator() == PostfixExpression.Operator.INCREMENT)
       op = InfixExpression.Operator.PLUS;
     if (po.getOperator() == PostfixExpression.Operator.DECREMENT)
       op = InfixExpression.Operator.MINUS;
   } else if (node.getNodeType() == ASTNode.PREFIX_EXPRESSION) {
     PrefixExpression pe = (PrefixExpression) node;
     if (pe.getOperator() == PrefixExpression.Operator.INCREMENT)
       op = InfixExpression.Operator.PLUS;
     if (pe.getOperator() == PrefixExpression.Operator.DECREMENT)
       op = InfixExpression.Operator.MINUS;
   }
   if (op != null && getterExpression != null) {
     return createInfixInvocationFromPostPrefixExpression(
         op, getterExpression, ast, variableType, is50OrHigher);
   }
   return null;
 }
 /**
  * Updates the content of <code>cu</code>, modifying the type name and/or package declaration as
  * necessary.
  *
  * @return an AST rewrite or null if no rewrite needed
  */
 private TextEdit updateContent(ICompilationUnit cu, PackageFragment dest, String newName)
     throws JavaModelException {
   String[] currPackageName = ((PackageFragment) cu.getParent()).names;
   String[] destPackageName = dest.names;
   if (Util.equalArraysOrNull(currPackageName, destPackageName) && newName == null) {
     return null; // nothing to change
   } else {
     // ensure cu is consistent (noop if already consistent)
     cu.makeConsistent(this.progressMonitor);
     this.parser.setSource(cu);
     CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
     AST ast = astCU.getAST();
     ASTRewrite rewrite = ASTRewrite.create(ast);
     updateTypeName(cu, astCU, cu.getElementName(), newName, rewrite);
     updatePackageStatement(astCU, destPackageName, rewrite, cu);
     return rewrite.rewriteAST();
   }
 }
  /* 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();
    }
  }
 @Override
 protected ASTRewrite getRewrite() throws CoreException {
   ASTRewrite rewrite = ASTRewrite.create(fBodyDecl.getAST());
   if (fBodyDecl instanceof MethodDeclaration) {
     insertAllMissingMethodTags(rewrite, (MethodDeclaration) fBodyDecl);
   } else {
     insertAllMissingTypeTags(rewrite, (TypeDeclaration) fBodyDecl);
   }
   return rewrite;
 }
 private Statement getCatchBody(String type, String name, String lineSeparator)
     throws CoreException {
   String s =
       StubUtility.getCatchBodyContent(fCUnit, type, name, fSelectedNodes[0], lineSeparator);
   if (s == null) {
     return null;
   } else {
     return (Statement) fRewriter.createStringPlaceholder(s, ASTNode.RETURN_STATEMENT);
   }
 }
  /** {@inheritDoc} */
  @Override
  public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups)
      throws CoreException {
    TextEditGroup group =
        createTextEditGroup(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description, cuRewrite);
    ASTRewrite rewrite = cuRewrite.getASTRewrite();

    TightSourceRangeComputer rangeComputer;
    if (rewrite.getExtendedSourceRangeComputer() instanceof TightSourceRangeComputer) {
      rangeComputer = (TightSourceRangeComputer) rewrite.getExtendedSourceRangeComputer();
    } else {
      rangeComputer = new TightSourceRangeComputer();
    }
    rangeComputer.addTightSourceNode(getForStatement());
    rewrite.setTargetSourceRangeComputer(rangeComputer);

    Statement statement = convert(cuRewrite, group, positionGroups);
    rewrite.replace(getForStatement(), statement, group);
  }
 private void updatePackageStatement(
     CompilationUnit astCU, String[] pkgName, ASTRewrite rewriter, ICompilationUnit cu)
     throws JavaModelException {
   boolean defaultPackage = pkgName.length == 0;
   AST ast = astCU.getAST();
   if (defaultPackage) {
     // remove existing package statement
     PackageDeclaration pkg = astCU.getPackage();
     if (pkg != null) {
       int pkgStart;
       Javadoc javadoc = pkg.getJavadoc();
       if (javadoc != null) {
         pkgStart = javadoc.getStartPosition() + javadoc.getLength() + 1;
       } else {
         pkgStart = pkg.getStartPosition();
       }
       int extendedStart = astCU.getExtendedStartPosition(pkg);
       if (pkgStart != extendedStart) {
         // keep the comments associated with package declaration
         // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=247757
         String commentSource = cu.getSource().substring(extendedStart, pkgStart);
         ASTNode comment =
             rewriter.createStringPlaceholder(commentSource, ASTNode.PACKAGE_DECLARATION);
         rewriter.set(astCU, CompilationUnit.PACKAGE_PROPERTY, comment, null);
       } else {
         rewriter.set(astCU, CompilationUnit.PACKAGE_PROPERTY, null, null);
       }
     }
   } else {
     org.eclipse.jdt.core.dom.PackageDeclaration pkg = astCU.getPackage();
     if (pkg != null) {
       // rename package statement
       Name name = ast.newName(pkgName);
       rewriter.set(pkg, PackageDeclaration.NAME_PROPERTY, name, null);
     } else {
       // create new package statement
       pkg = ast.newPackageDeclaration();
       pkg.setName(ast.newName(pkgName));
       rewriter.set(astCU, CompilationUnit.PACKAGE_PROPERTY, pkg, null);
     }
   }
 }
  @Override
  protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit targetAstRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
    createImportRewrite(targetAstRoot);

    ASTRewrite rewrite = ASTRewrite.create(targetAstRoot.getAST());

    // Find the method declaration in the AST we just generated (the one that
    // the AST rewriter is hooked up to).
    MethodDeclaration rewriterAstMethodDecl =
        JavaASTUtils.findMethodDeclaration(targetAstRoot, methodDecl.resolveBinding().getKey());
    if (rewriterAstMethodDecl == null) {
      return null;
    }

    // Remove the extra method declaration
    rewrite.remove(rewriterAstMethodDecl, null);

    return rewrite;
  }
  private void createEdits(
      ICompilationUnit unit, ASTRewrite rewriter, List<TextEditGroup> descriptions)
      throws CoreException {
    TextChange change = fChangeManager.get(unit);
    MultiTextEdit root = new MultiTextEdit();
    change.setEdit(root);

    for (TextEditGroup group : descriptions) change.addTextEditGroup(group);

    root.addChild(rewriter.rewriteAST());
  }
 /** Renames the main type in <code>cu</code>. */
 private void updateTypeName(
     ICompilationUnit cu,
     CompilationUnit astCU,
     String oldName,
     String newName,
     ASTRewrite rewriter)
     throws JavaModelException {
   if (newName != null) {
     String oldTypeName = Util.getNameWithoutJavaLikeExtension(oldName);
     String newTypeName = Util.getNameWithoutJavaLikeExtension(newName);
     AST ast = astCU.getAST();
     // update main type name
     IType[] types = cu.getTypes();
     for (int i = 0, max = types.length; i < max; i++) {
       IType currentType = types[i];
       if (currentType.getElementName().equals(oldTypeName)) {
         AbstractTypeDeclaration typeNode =
             (AbstractTypeDeclaration) ((JavaElement) currentType).findNode(astCU);
         if (typeNode != null) {
           // rename type
           rewriter.replace(typeNode.getName(), ast.newSimpleName(newTypeName), null);
           // rename constructors
           Iterator bodyDeclarations = typeNode.bodyDeclarations().iterator();
           while (bodyDeclarations.hasNext()) {
             Object bodyDeclaration = bodyDeclarations.next();
             if (bodyDeclaration instanceof MethodDeclaration) {
               MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
               if (methodDeclaration.isConstructor()) {
                 SimpleName methodName = methodDeclaration.getName();
                 if (methodName.getIdentifier().equals(oldTypeName)) {
                   rewriter.replace(methodName, ast.newSimpleName(newTypeName), null);
                 }
               }
             }
           }
         }
       }
     }
   }
 }
    /** {@inheritDoc} */
    public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups)
        throws CoreException {
      InferTypeArgumentsTCModel model = new InferTypeArgumentsTCModel();
      InferTypeArgumentsConstraintCreator creator =
          new InferTypeArgumentsConstraintCreator(model, true);

      CompilationUnit root = cuRewrite.getRoot();
      root.accept(creator);

      InferTypeArgumentsConstraintsSolver solver = new InferTypeArgumentsConstraintsSolver(model);
      InferTypeArgumentsUpdate update = solver.solveConstraints(new NullProgressMonitor());
      solver = null; // free caches

      ASTNode[] nodes =
          InferTypeArgumentsRefactoring.inferArguments(fTypes, update, model, cuRewrite);
      if (nodes.length == 0) return;

      ASTRewrite astRewrite = cuRewrite.getASTRewrite();
      for (int i = 0; i < nodes.length; i++) {
        if (nodes[i] instanceof ParameterizedType) {
          ParameterizedType type = (ParameterizedType) nodes[0];
          List args = (List) type.getStructuralProperty(ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
          int j = 0;
          for (Iterator iter = args.iterator(); iter.hasNext(); ) {
            LinkedProposalPositionGroup group =
                new LinkedProposalPositionGroup("G" + i + "_" + j); // $NON-NLS-1$ //$NON-NLS-2$
            Type argType = (Type) iter.next();
            if (!positionGroups.hasLinkedPositions()) {
              group.addPosition(astRewrite.track(argType), true);
            } else {
              group.addPosition(astRewrite.track(argType), false);
            }
            positionGroups.addPositionGroup(group);
            j++;
          }
        }
      }
      positionGroups.setEndPosition(astRewrite.track(nodes[0]));
    }
  public static void getRemoveJavadocTagProposals(
      IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ASTNode node = problem.getCoveringNode(context.getASTRoot());
    while (node != null && !(node instanceof TagElement)) {
      node = node.getParent();
    }
    if (node == null) {
      return;
    }
    ASTRewrite rewrite = ASTRewrite.create(node.getAST());
    rewrite.remove(node, null);

    String label = CorrectionMessages.JavadocTagsSubProcessor_removetag_description;
    Image image =
        JavaPlugin.getDefault()
            .getWorkbench()
            .getSharedImages()
            .getImage(ISharedImages.IMG_TOOL_DELETE);
    proposals.add(
        new ASTRewriteCorrectionProposal(
            label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_TAG, image));
  }
 /**
  * Adds the specified tag to the source member defined by the member name and signature
  *
  * @param unit
  * @param membername
  * @param signature
  * @param tagname
  * @param remove
  * @throws CoreException
  * @throws MalformedTreeException
  * @throws BadLocationException
  */
 private void updateTagInSource(
     ICompilationUnit unit, String membername, String signature, String tagname, boolean remove)
     throws CoreException, MalformedTreeException, BadLocationException {
   ASTParser parser = ASTParser.newParser(AST.JLS4);
   parser.setSource(unit);
   CompilationUnit cunit = (CompilationUnit) parser.createAST(new NullProgressMonitor());
   assertNotNull("the ast compilation unit cannot be null", cunit);
   cunit.recordModifications();
   ASTRewrite rewrite = ASTRewrite.create(cunit.getAST());
   cunit.accept(new SourceChangeVisitor(membername, signature, tagname, remove, rewrite));
   ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
   IPath path = cunit.getJavaElement().getPath();
   try {
     bm.connect(path, LocationKind.IFILE, null);
     ITextFileBuffer tfb = bm.getTextFileBuffer(path, LocationKind.IFILE);
     IDocument document = tfb.getDocument();
     TextEdit edits = rewrite.rewriteAST(document, null);
     edits.apply(document);
     tfb.commit(new NullProgressMonitor(), true);
   } finally {
     bm.disconnect(path, LocationKind.IFILE, null);
   }
 }
 /**
  * Creates a place holder ASTNode for the given element.
  *
  * @param rewriter
  * @param element
  * @param delimiter the line delimiter
  * @param project
  * @return a ASTNode or null
  * @throws CoreException
  */
 private ASTNode createASTNode(
     ASTRewrite rewriter, ITypedElement element, String delimiter, IJavaProject project)
     throws CoreException {
   if (element instanceof IStreamContentAccessor) {
     String content = JavaCompareUtilities.readString((IStreamContentAccessor) element);
     if (content != null) {
       content = trimTextBlock(content, delimiter, project);
       if (content != null) {
         int type = getPlaceHolderType(element);
         if (type != -1) return rewriter.createStringPlaceholder(content, type);
       }
     }
   }
   return null;
 }
  @Override
  protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug)
      throws BugResolutionException {
    assert rewrite != null;
    assert workingUnit != null;
    assert bug != null;

    TypeDeclaration type = getTypeDeclaration(workingUnit, bug.getPrimaryClass());
    MethodDeclaration method = getMethodDeclaration(type, bug.getPrimaryMethod());
    Modifier originalModifier = getPublicModifier(method);

    ListRewrite listRewrite = rewrite.getListRewrite(method, MethodDeclaration.MODIFIERS2_PROPERTY);
    Modifier protectedModifier = workingUnit.getAST().newModifier(PROTECTED_KEYWORD);
    listRewrite.replace(originalModifier, protectedModifier, null);
  }
Esempio n. 28
0
  @Override
  protected Change initChanger(Cause cause, Map<String, Parameter> parameters) {
    final SourceChange change = new SourceChange(cause, this, parameters);
    try {

      final CompilationUnit root = getCompilationUnit(cause);
      final ASTRewrite rewrite = ASTRewrite.create(root.getAST());

      change.getDeltas().add(deduplicate(root, rewrite, cause));

    } catch (Throwable ex) {
      change.getErrors().add(ex.getMessage());
    }

    return change;
  }
 private static TextChange addTextEditFromRewrite(
     TextChangeManager manager, ICompilationUnit cu, ASTRewrite rewrite) throws CoreException {
   try {
     ITextFileBuffer buffer = RefactoringFileBuffers.acquire(cu);
     TextEdit resultingEdits =
         rewrite.rewriteAST(buffer.getDocument(), cu.getJavaProject().getOptions(true));
     TextChange textChange = manager.get(cu);
     if (textChange instanceof TextFileChange) {
       TextFileChange tfc = (TextFileChange) textChange;
       tfc.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
     }
     String message = RefactoringCoreMessages.DeleteChangeCreator_1;
     TextChangeCompatibility.addTextEdit(textChange, message, resultingEdits);
     return textChange;
   } finally {
     RefactoringFileBuffers.release(cu);
   }
 }
Esempio n. 30
0
  /** 取得Quick Fix後改變的程式碼 */
  private Change getChange(CompilationUnit actRoot, ASTRewrite rewrite) {
    try {
      ICompilationUnit cu = (ICompilationUnit) actOpenable;
      Document document = new Document(cu.getBuffer().getContents());

      TextEdit edits = null;
      if (rewrite != null) edits = rewrite.rewriteAST(document, null);
      else edits = actRoot.rewrite(document, cu.getJavaProject().getOptions(true));

      TextFileChange textFileChange =
          new TextFileChange(cu.getElementName(), (IFile) cu.getResource());
      textFileChange.setEdit(edits);

      return textFileChange;
    } catch (JavaModelException e) {
      logger.error("[Apply Change Rethrow Unchecked Exception] EXCEPTION ", e);
    }
    return null;
  }