Esempio n. 1
0
    /** {@inheritDoc} */
    @Override
    public void rewriteAST(CompilationUnitRewrite cuRewrite) throws CoreException {
      ASTRewrite rewrite = cuRewrite.getASTRewrite();

      TextEditGroup group =
          createTextEditGroup(
              FixMessages.INSTANCE.UnusedCodeFix_RemoveCast_description(), cuRewrite);

      while (fUnnecessaryCasts.size() > 0) {
        CastExpression castExpression = fUnnecessaryCasts.iterator().next();
        fUnnecessaryCasts.remove(castExpression);
        CastExpression down = castExpression;
        while (fUnnecessaryCasts.contains(down.getExpression())) {
          down = (CastExpression) down.getExpression();
          fUnnecessaryCasts.remove(down);
        }

        Expression expression = down.getExpression();
        ASTNode move = rewrite.createMoveTarget(expression);

        CastExpression top = castExpression;
        while (fUnnecessaryCasts.contains(top.getParent())) {
          top = (CastExpression) top.getParent();
          fUnnecessaryCasts.remove(top);
        }

        ASTNode toReplace = top;
        if (top.getParent() instanceof ParenthesizedExpression
            && !NecessaryParenthesesChecker.needsParentheses(
                expression, top.getParent(), top.getLocationInParent())) {
          toReplace = top.getParent();
        }
        rewrite.replace(toReplace, move, group);
      }
    }
Esempio n. 2
0
 private void removeStatement(ASTRewrite rewrite, ASTNode statementNode, TextEditGroup group) {
   if (ASTNodes.isControlStatementBody(statementNode.getLocationInParent())) {
     rewrite.replace(statementNode, rewrite.getAST().newBlock(), group);
   } else {
     rewrite.remove(statementNode, group);
   }
 }
Esempio n. 3
0
    /** {@inheritDoc} */
    @Override
    public void rewriteAST(CompilationUnitRewrite cuRewrite) throws CoreException {

      TextEditGroup group =
          createTextEditGroup(
              FixMessages.INSTANCE.UnusedCodeFix_RemoveCast_description(), cuRewrite);

      ASTRewrite rewrite = cuRewrite.getASTRewrite();

      CastExpression cast = fCast;
      Expression expression = cast.getExpression();
      ASTNode placeholder = rewrite.createCopyTarget(expression);

      if (NecessaryParenthesesChecker.needsParentheses(
          expression, cast.getParent(), cast.getLocationInParent())) {
        rewrite.replace(fCast, placeholder, group);
      } else {
        rewrite.replace(
            fCast.getParent() instanceof ParenthesizedExpression
                ? fCast.getParent()
                : fSelectedNode,
            placeholder,
            group);
      }
    }
  /**
   * Attaches the changes of this compilation unit rewrite to the given CU Change. The given change
   * <b>must</b> either have no root edit, or a MultiTextEdit as a root edit. The edits in the given
   * change <b>must not</b> overlap with the changes of this compilation unit.
   *
   * @param cuChange existing CompilationUnitChange with a MultiTextEdit root or no root at all.
   * @param generateGroups <code>true</code> to generate text edit groups, <code>false</code>
   *     otherwise
   * @param monitor the progress monitor or <code>null</code>
   * @return a change combining the changes of this rewrite and the given rewrite, or <code>null
   *     </code> for an empty change
   * @throws CoreException when text buffer acquisition or import rewrite text edit creation fails
   */
  public CompilationUnitChange attachChange(CompilationUnitChange cuChange, boolean generateGroups)
      throws CoreException {
    boolean needsAstRewrite =
        fRewrite != null; // TODO: do we need something like ASTRewrite#hasChanges() here?
    boolean needsImportRemoval = fImportRemover != null && fImportRemover.hasRemovedNodes();
    boolean needsImportRewrite =
        fImportRewrite != null && fImportRewrite.hasRecordedChanges() || needsImportRemoval;
    if (!needsAstRewrite && !needsImportRemoval && !needsImportRewrite) return null;

    MultiTextEdit multiEdit = (MultiTextEdit) cuChange.getEdit();
    if (multiEdit == null) {
      multiEdit = new MultiTextEdit();
      cuChange.setEdit(multiEdit);
    }

    if (needsAstRewrite) {
      TextEdit rewriteEdit;
      if (fRememberContent != null) {
        rewriteEdit =
            fRewrite.rewriteAST(fRememberContent, WorkerMessageHandler.get().getOptions());
      } else {
        rewriteEdit = fRewrite.rewriteAST(document, WorkerMessageHandler.get().getOptions());
      }
      if (!isEmptyEdit(rewriteEdit)) {
        multiEdit.addChild(rewriteEdit);
        if (generateGroups) {
          for (Iterator<TextEditGroup> iter = fTextEditGroups.iterator(); iter.hasNext(); ) {
            TextEditGroup group = iter.next();
            cuChange.addTextEditGroup(group);
          }
        }
      }
    }
    if (needsImportRemoval) {
      fImportRemover.applyRemoves(getImportRewrite());
    }
    if (needsImportRewrite) {
      TextEdit importsEdit = fImportRewrite.rewriteImports();
      if (!isEmptyEdit(importsEdit)) {
        multiEdit.addChild(importsEdit);
        String importUpdateName = RefactoringCoreMessages.INSTANCE.ASTData_update_imports();
        cuChange.addTextEditGroup(new TextEditGroup(importUpdateName, importsEdit));
      }
    } else {

    }
    if (isEmptyEdit(multiEdit)) return null;
    return cuChange;
  }
Esempio n. 5
0
 private void removeVariableWithInitializer(
     ASTRewrite rewrite, ASTNode initializerNode, ASTNode statementNode, TextEditGroup group) {
   boolean performRemove = fForceRemove;
   if (!performRemove) {
     ArrayList<Expression> sideEffectNodes = new ArrayList<Expression>();
     initializerNode.accept(new SideEffectFinder(sideEffectNodes));
     performRemove = sideEffectNodes.isEmpty();
   }
   if (performRemove) {
     removeStatement(rewrite, statementNode, group);
     fRemovedAssignmentsCount++;
   } else {
     ASTNode initNode = rewrite.createMoveTarget(initializerNode);
     ExpressionStatement statement =
         rewrite.getAST().newExpressionStatement((Expression) initNode);
     rewrite.replace(statementNode, statement, null);
     fAlteredAssignmentsCount++;
   }
 }
Esempio n. 6
0
    private void removeUnusedName(CompilationUnitRewrite cuRewrite, SimpleName simpleName) {
      ASTRewrite rewrite = cuRewrite.getASTRewrite();
      CompilationUnit completeRoot = cuRewrite.getRoot();

      IBinding binding = simpleName.resolveBinding();
      CompilationUnit root = (CompilationUnit) simpleName.getRoot();
      String displayString = getDisplayString(binding);
      TextEditGroup group = createTextEditGroup(displayString, cuRewrite);
      if (binding.getKind() == IBinding.METHOD) {
        IMethodBinding decl = ((IMethodBinding) binding).getMethodDeclaration();
        ASTNode declaration = root.findDeclaringNode(decl);
        rewrite.remove(declaration, group);
      } else if (binding.getKind() == IBinding.TYPE) {
        ITypeBinding decl = ((ITypeBinding) binding).getTypeDeclaration();
        ASTNode declaration = root.findDeclaringNode(decl);
        if (declaration.getParent() instanceof TypeDeclarationStatement) {
          declaration = declaration.getParent();
        }
        rewrite.remove(declaration, group);
      } else if (binding.getKind() == IBinding.VARIABLE) {
        SimpleName nameNode =
            (SimpleName)
                NodeFinder.perform(
                    completeRoot, simpleName.getStartPosition(), simpleName.getLength());
        SimpleName[] references =
            LinkedNodeFinder.findByBinding(completeRoot, nameNode.resolveBinding());
        for (int i = 0; i < references.length; i++) {
          removeVariableReferences(rewrite, references[i], group);
        }

        IVariableBinding bindingDecl =
            ((IVariableBinding) nameNode.resolveBinding()).getVariableDeclaration();
        ASTNode declaringNode = completeRoot.findDeclaringNode(bindingDecl);
        if (declaringNode instanceof SingleVariableDeclaration) {
          removeParamTag(rewrite, (SingleVariableDeclaration) declaringNode, group);
        }
      } else {
        // unexpected
      }
    }
Esempio n. 7
0
 private void removeParamTag(
     ASTRewrite rewrite, SingleVariableDeclaration varDecl, TextEditGroup group) {
   if (varDecl.getParent() instanceof MethodDeclaration) {
     Javadoc javadoc = ((MethodDeclaration) varDecl.getParent()).getJavadoc();
     if (javadoc != null) {
       TagElement tagElement =
           JavadocTagsSubProcessor.findParamTag(javadoc, varDecl.getName().getIdentifier());
       if (tagElement != null) {
         rewrite.remove(tagElement, group);
       }
     }
   }
 }
 public ASTRewrite getASTRewrite() {
   if (fRewrite == null) {
     fRewrite = ASTRewrite.create(getRoot().getAST());
     if (fRememberContent != null) { // wain until ast rewrite is accessed first
       //            try
       //            {
       fRememberContent = document;
       //            }
       //            catch (JavaModelException e)
       //            {
       //               fRememberContent = null;
       //            }
     }
   }
   return fRewrite;
 }
Esempio n. 9
0
    private void splitUpDeclarations(
        ASTRewrite rewrite,
        TextEditGroup group,
        VariableDeclarationFragment frag,
        ListRewrite statementRewrite,
        VariableDeclarationStatement originalStatement) {
      Expression initializer = frag.getInitializer();
      // keep constructors and method invocations
      if (initializer instanceof MethodInvocation || initializer instanceof ClassInstanceCreation) {
        Expression movedInitializer = (Expression) rewrite.createMoveTarget(initializer);

        ExpressionStatement newInitializer =
            rewrite.getAST().newExpressionStatement(movedInitializer);
        statementRewrite.insertAfter(newInitializer, originalStatement, group);

        VariableDeclarationStatement newDeclaration = null;
        List<VariableDeclarationFragment> fragments = originalStatement.fragments();
        int fragIndex = fragments.indexOf(frag);
        ListIterator<VariableDeclarationFragment> fragmentIterator =
            fragments.listIterator(fragIndex + 1);
        while (fragmentIterator.hasNext()) {
          VariableDeclarationFragment currentFragment = fragmentIterator.next();
          VariableDeclarationFragment movedFragment =
              (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment);
          if (newDeclaration == null) {
            newDeclaration = rewrite.getAST().newVariableDeclarationStatement(movedFragment);
            Type copiedType = (Type) rewrite.createCopyTarget(originalStatement.getType());
            newDeclaration.setType(copiedType);
          } else newDeclaration.fragments().add(movedFragment);
        }
        if (newDeclaration != null) {
          statementRewrite.insertAfter(newDeclaration, newInitializer, group);
        }
        if (originalStatement.fragments().size() == newDeclaration.fragments().size() + 1) {
          rewrite.remove(originalStatement, group);
        }
      }
    }
  public static void rewriteModifiers(
      final FieldDeclaration declarationNode,
      final VariableDeclarationFragment[] toChange,
      final int includedModifiers,
      final int excludedModifiers,
      final ASTRewrite rewrite,
      final TextEditGroup group) {
    final List<VariableDeclarationFragment> fragmentsToChange = Arrays.asList(toChange);
    AST ast = declarationNode.getAST();
    /*
     * Problem: Same declarationNode can be the subject of multiple calls to this method.
     * For the 2nd++ calls, the original declarationNode has already been rewritten, and this has to be taken into account.
     *
     * Assumption:
     * - Modifiers for each VariableDeclarationFragment are modified at most once.
     *
     * Solution:
     * - Maintain a map from original VariableDeclarationFragments to their new FieldDeclaration.
     * - Original modifiers in declarationNode belong to the first fragment.
     * - When a later fragment needs different modifiers, we create a new FieldDeclaration and move all successive fragments into that
     * declaration
     * - When a fragment has been moved to a new declaration, make sure we don't create a new move target again,
     * but instead use the already created one
     */
    List<VariableDeclarationFragment> fragments = declarationNode.fragments();
    Iterator<VariableDeclarationFragment> iter = fragments.iterator();

    ListRewrite blockRewrite;
    if (declarationNode.getParent() instanceof AbstractTypeDeclaration) {
      blockRewrite =
          rewrite.getListRewrite(
              declarationNode.getParent(),
              ((AbstractTypeDeclaration) declarationNode.getParent())
                  .getBodyDeclarationsProperty());
    } else {
      blockRewrite =
          rewrite.getListRewrite(
              declarationNode.getParent(), AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
    }

    VariableDeclarationFragment lastFragment = iter.next();
    ASTNode lastStatement = declarationNode;

    if (fragmentsToChange.contains(lastFragment)) {
      ModifierRewrite modifierRewrite = ModifierRewrite.create(rewrite, declarationNode);
      modifierRewrite.setModifiers(includedModifiers, excludedModifiers, group);
    }

    ListRewrite fragmentsRewrite = null;
    while (iter.hasNext()) {
      VariableDeclarationFragment currentFragment = iter.next();

      Map<VariableDeclarationFragment, MovedFragment> lookup =
          (Map<VariableDeclarationFragment, MovedFragment>)
              rewrite.getProperty(MovedFragment.class.getName());
      if (lookup == null) {
        lookup = new HashMap<VariableDeclarationFragment, MovedFragment>();
        rewrite.setProperty(MovedFragment.class.getName(), lookup);
      }
      MovedFragment currentMovedFragment = lookup.get(currentFragment);

      boolean changeLast = fragmentsToChange.contains(lastFragment);
      boolean changeCurrent = fragmentsToChange.contains(currentFragment);
      if (changeLast != changeCurrent || lookup.containsKey(lastFragment)) {
        ModifierRewrite modifierRewrite = null;
        if (currentMovedFragment != null) {
          // Current fragment has already been moved.

          if (currentMovedFragment.fUsesOriginalModifiers) {
            // Need to put in the right modifiers (removing any existing ones).
            modifierRewrite = ModifierRewrite.create(rewrite, currentMovedFragment.fDeclaration);
            ListRewrite listRewrite =
                rewrite.getListRewrite(
                    currentMovedFragment.fDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY);
            List<ASTNode> extendedList = listRewrite.getRewrittenList();
            for (int i = 0; i < extendedList.size(); i++) {
              ASTNode curr = extendedList.get(i);
              if (curr instanceof Modifier) rewrite.remove(curr, group);
            }
          }
          // otherwise, don't need to touch the modifiers, so leave modifierRewrite null

        } else { // need to split an existing field declaration
          VariableDeclarationFragment moveTarget;
          moveTarget = (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment);

          FieldDeclaration newStatement =
              (FieldDeclaration) ast.createInstance(FieldDeclaration.FIELD_DECLARATION);
          rewrite
              .getListRewrite(newStatement, FieldDeclaration.FRAGMENTS_PROPERTY)
              .insertLast(moveTarget, group);
          lookup.put(currentFragment, new MovedFragment(moveTarget, newStatement, !changeCurrent));
          rewrite.set(
              newStatement,
              FieldDeclaration.TYPE_PROPERTY,
              rewrite.createCopyTarget(declarationNode.getType()),
              group);

          modifierRewrite = ModifierRewrite.create(rewrite, newStatement);
          modifierRewrite.copyAllAnnotations(declarationNode, group);
          blockRewrite.insertAfter(newStatement, lastStatement, group);

          fragmentsRewrite =
              rewrite.getListRewrite(newStatement, FieldDeclaration.FRAGMENTS_PROPERTY);
          lastStatement = newStatement;
        }

        if (modifierRewrite != null) {
          if (changeCurrent) {
            int newModifiers =
                (declarationNode.getModifiers() & ~excludedModifiers) | includedModifiers;
            modifierRewrite.setModifiers(newModifiers, excludedModifiers, group);
          } else {
            int newModifiers = declarationNode.getModifiers();
            modifierRewrite.setModifiers(newModifiers, Modifier.NONE, group);
          }
        }

      } else if (fragmentsRewrite != null) {
        VariableDeclarationFragment fragment0;
        boolean usesOriginalModifiers = true;
        if (currentMovedFragment != null) {
          fragment0 = currentMovedFragment.fMoveTarget;
          usesOriginalModifiers = currentMovedFragment.fUsesOriginalModifiers;
          rewrite
              .getListRewrite(
                  currentMovedFragment.fDeclaration, FieldDeclaration.FRAGMENTS_PROPERTY)
              .remove(fragment0, group);
        } else {
          fragment0 = (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment);
        }
        lookup.put(
            currentFragment, new MovedFragment(fragment0, lastStatement, usesOriginalModifiers));
        fragmentsRewrite.insertLast(fragment0, group);
      }
      lastFragment = currentFragment;
    }
  }
  public static void rewriteModifiers(
      final VariableDeclarationStatement declarationNode,
      final VariableDeclarationFragment[] toChange,
      final int includedModifiers,
      final int excludedModifiers,
      ASTRewrite rewrite,
      final TextEditGroup group) {
    final List<VariableDeclarationFragment> fragmentsToChange = Arrays.asList(toChange);
    AST ast = declarationNode.getAST();

    List<VariableDeclarationFragment> fragments = declarationNode.fragments();
    Iterator<VariableDeclarationFragment> iter = fragments.iterator();

    ListRewrite blockRewrite = null;
    ASTNode parentStatement = declarationNode.getParent();
    if (parentStatement instanceof SwitchStatement) {
      blockRewrite = rewrite.getListRewrite(parentStatement, SwitchStatement.STATEMENTS_PROPERTY);
    } else if (parentStatement instanceof Block) {
      blockRewrite = rewrite.getListRewrite(parentStatement, Block.STATEMENTS_PROPERTY);
    } else {
      // should not happen. VariableDeclaration's can not be in a control statement body
      Assert.isTrue(false);
    }

    VariableDeclarationFragment lastFragment = iter.next();
    ASTNode lastStatement = declarationNode;

    boolean modifiersModified = false;
    if (fragmentsToChange.contains(lastFragment)) {
      ModifierRewrite modifierRewrite = ModifierRewrite.create(rewrite, declarationNode);
      modifierRewrite.setModifiers(includedModifiers, excludedModifiers, group);
      modifiersModified = true;
    }

    ListRewrite fragmentsRewrite = null;
    while (iter.hasNext()) {
      VariableDeclarationFragment currentFragment = iter.next();

      if (fragmentsToChange.contains(lastFragment) != fragmentsToChange.contains(currentFragment)) {

        VariableDeclarationStatement newStatement =
            ast.newVariableDeclarationStatement(
                (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment));
        newStatement.setType((Type) rewrite.createCopyTarget(declarationNode.getType()));

        ModifierRewrite modifierRewrite = ModifierRewrite.create(rewrite, newStatement);
        if (fragmentsToChange.contains(currentFragment)) {
          modifierRewrite.copyAllAnnotations(declarationNode, group);
          int newModifiers =
              (declarationNode.getModifiers() & ~excludedModifiers) | includedModifiers;
          modifierRewrite.setModifiers(newModifiers, excludedModifiers, group);
        } else {
          modifierRewrite.copyAllModifiers(declarationNode, group, modifiersModified);
        }
        blockRewrite.insertAfter(newStatement, lastStatement, group);

        fragmentsRewrite =
            rewrite.getListRewrite(newStatement, VariableDeclarationStatement.FRAGMENTS_PROPERTY);
        lastStatement = newStatement;
      } else if (fragmentsRewrite != null) {
        ASTNode fragment0 = rewrite.createMoveTarget(currentFragment);
        fragmentsRewrite.insertLast(fragment0, group);
      }
      lastFragment = currentFragment;
    }
  }
Esempio n. 12
0
    /**
     * Remove the field or variable declaration including the initializer.
     *
     * @param rewrite the AST rewriter to use
     * @param reference a reference to the variable to remove
     * @param group the text edit group to use
     */
    private void removeVariableReferences(
        ASTRewrite rewrite, SimpleName reference, TextEditGroup group) {
      ASTNode parent = reference.getParent();
      while (parent instanceof QualifiedName) {
        parent = parent.getParent();
      }
      if (parent instanceof FieldAccess) {
        parent = parent.getParent();
      }

      int nameParentType = parent.getNodeType();
      if (nameParentType == ASTNode.ASSIGNMENT) {
        Assignment assignment = (Assignment) parent;
        Expression rightHand = assignment.getRightHandSide();

        ASTNode assignParent = assignment.getParent();
        if (assignParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT
            && rightHand.getNodeType() != ASTNode.ASSIGNMENT) {
          removeVariableWithInitializer(rewrite, rightHand, assignParent, group);
        } else {
          rewrite.replace(assignment, rewrite.createCopyTarget(rightHand), group);
        }
      } else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
        rewrite.remove(parent, group);
      } else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
        VariableDeclarationFragment frag = (VariableDeclarationFragment) parent;
        ASTNode varDecl = frag.getParent();
        List<VariableDeclarationFragment> fragments;
        if (varDecl instanceof VariableDeclarationExpression) {
          fragments = ((VariableDeclarationExpression) varDecl).fragments();
        } else if (varDecl instanceof FieldDeclaration) {
          fragments = ((FieldDeclaration) varDecl).fragments();
        } else {
          fragments = ((VariableDeclarationStatement) varDecl).fragments();
        }
        Expression initializer = frag.getInitializer();
        if (initializer instanceof CastExpression) {
          initializer = ((CastExpression) initializer).getExpression();
        }
        boolean sideEffectInitializer =
            initializer instanceof MethodInvocation || initializer instanceof ClassInstanceCreation;
        if (fragments.size() == fUnusedNames.length) {
          if (fForceRemove) {
            rewrite.remove(varDecl, group);
            return;
          }
          if (parent.getParent() instanceof FieldDeclaration) {
            rewrite.remove(varDecl, group);
            return;
          }
          if (sideEffectInitializer) {
            Expression movedInit = (Expression) rewrite.createMoveTarget(initializer);
            ExpressionStatement wrapped = rewrite.getAST().newExpressionStatement(movedInit);
            rewrite.replace(varDecl, wrapped, group);
          } else {
            rewrite.remove(varDecl, group);
          }
        } else {
          if (fForceRemove) {
            rewrite.remove(frag, group);
            return;
          }
          // multiple declarations in one line
          ASTNode declaration = parent.getParent();
          if (declaration instanceof FieldDeclaration) {
            rewrite.remove(frag, group);
            return;
          }
          if (declaration instanceof VariableDeclarationStatement) {
            ASTNode lst = declaration.getParent();
            ListRewrite listRewrite = null;
            if (lst instanceof Block) {
              listRewrite = rewrite.getListRewrite(lst, Block.STATEMENTS_PROPERTY);
            } else if (lst instanceof SwitchStatement) {
              listRewrite = rewrite.getListRewrite(lst, SwitchStatement.STATEMENTS_PROPERTY);
            } else {
              Assert.isTrue(false);
            }
            splitUpDeclarations(
                rewrite, group, frag, listRewrite, (VariableDeclarationStatement) declaration);
            rewrite.remove(frag, group);
            return;
          }
          if (declaration instanceof VariableDeclarationExpression) {
            // keep constructors and method invocations
            if (!sideEffectInitializer) {
              rewrite.remove(frag, group);
            }
          }
        }
      } else if (nameParentType == ASTNode.POSTFIX_EXPRESSION
          || nameParentType == ASTNode.PREFIX_EXPRESSION) {
        Expression expression = (Expression) parent;
        ASTNode expressionParent = expression.getParent();
        if (expressionParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
          removeStatement(rewrite, expressionParent, group);
        } else {
          rewrite.remove(expression, group);
        }
      }
    }