コード例 #1
0
  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);
    }
  }
コード例 #2
0
  @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;
  }
コード例 #3
0
  @Override
  public void run(IProgressMonitor monitor) throws CoreException {
    if (monitor == null) monitor = new NullProgressMonitor();
    try {
      monitor.beginTask("", 1); // $NON-NLS-1$
      monitor.setTaskName(CodeGenerationMessages.GenerateToStringOperation_description);

      AbstractTypeDeclaration declaration =
          (AbstractTypeDeclaration)
              ASTNodes.findDeclaration(fContext.getTypeBinding(), fRewrite.getRoot());
      ListRewrite rewriter =
          fRewrite
              .getASTRewrite()
              .getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
      if (fContext.getTypeBinding() != null && rewriter != null) {

        MethodDeclaration toStringMethod = fGenerator.generateToStringMethod();

        List<BodyDeclaration> list = declaration.bodyDeclarations();
        BodyDeclaration replace = findMethodToReplace(list, toStringMethod);
        if (replace == null
            || ((Boolean)
                    toStringMethod.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY))
                .booleanValue()) insertMethod(toStringMethod, rewriter, replace);

        List<MethodDeclaration> helperMethods = fGenerator.generateHelperMethods();
        for (Iterator<MethodDeclaration> iterator = helperMethods.iterator();
            iterator.hasNext(); ) {
          MethodDeclaration method = iterator.next();
          replace = findMethodToReplace(list, method);
          if (replace == null
              || ((Boolean) method.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY))
                  .booleanValue()) {
            insertMethod(method, rewriter, replace);
          }
        }

        JavaModelUtil.applyEdit(
            (ICompilationUnit) fUnit.getJavaElement(),
            fRewrite.createChange(true).getEdit(),
            false,
            monitor);
      }

    } finally {
      monitor.done();
    }
  }
コード例 #4
0
    /** {@inheritDoc} */
    public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model)
        throws CoreException {
      ASTRewrite rewrite = cuRewrite.getASTRewrite();

      TextEditGroup group =
          createTextEditGroup(
              FixMessages.VariableDeclarationFix_changeModifierOfUnknownToFinal_description,
              cuRewrite);

      if (fDeclaration instanceof VariableDeclarationStatement) {
        VariableDeclarationFragment[] toChange =
            (VariableDeclarationFragment[])
                fToChange.toArray(new VariableDeclarationFragment[fToChange.size()]);
        VariableDeclarationRewrite.rewriteModifiers(
            (VariableDeclarationStatement) fDeclaration,
            toChange,
            fIncludedModifiers,
            fExcludedModifiers,
            rewrite,
            group);
      } else if (fDeclaration instanceof FieldDeclaration) {
        VariableDeclarationFragment[] toChange =
            (VariableDeclarationFragment[])
                fToChange.toArray(new VariableDeclarationFragment[fToChange.size()]);
        VariableDeclarationRewrite.rewriteModifiers(
            (FieldDeclaration) fDeclaration,
            toChange,
            fIncludedModifiers,
            fExcludedModifiers,
            rewrite,
            group);
      } else if (fDeclaration instanceof SingleVariableDeclaration) {
        VariableDeclarationRewrite.rewriteModifiers(
            (SingleVariableDeclaration) fDeclaration,
            fIncludedModifiers,
            fExcludedModifiers,
            rewrite,
            group);
      } else if (fDeclaration instanceof VariableDeclarationExpression) {
        VariableDeclarationRewrite.rewriteModifiers(
            (VariableDeclarationExpression) fDeclaration,
            fIncludedModifiers,
            fExcludedModifiers,
            rewrite,
            group);
      }
    }
コード例 #5
0
 /** {@inheritDoc} */
 public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model)
     throws CoreException {
   AST ast = cuRewrite.getRoot().getAST();
   ListRewrite listRewrite =
       cuRewrite
           .getASTRewrite()
           .getListRewrite(fBodyDeclaration, fBodyDeclaration.getModifiersProperty());
   Annotation newAnnotation = ast.newMarkerAnnotation();
   newAnnotation.setTypeName(ast.newSimpleName(fAnnotation));
   TextEditGroup group =
       createTextEditGroup(
           Messages.format(
               FixMessages.Java50Fix_AddMissingAnnotation_description,
               BasicElementLabels.getJavaElementName(fAnnotation)),
           cuRewrite);
   listRewrite.insertFirst(newAnnotation, group);
 }
コード例 #6
0
  /** {@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);
  }
コード例 #7
0
    /** {@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]));
    }
コード例 #8
0
  private void createConstantDeclaration() throws CoreException {
    Type type = getConstantType();

    IExpressionFragment fragment = getSelectedExpression();
    Expression initializer =
        getSelectedExpression().createCopyTarget(fCuRewrite.getASTRewrite(), true);

    AST ast = fCuRewrite.getAST();
    VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment();
    variableDeclarationFragment.setName(ast.newSimpleName(fConstantName));
    variableDeclarationFragment.setInitializer(initializer);

    FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(variableDeclarationFragment);
    fieldDeclaration.setType(type);
    Modifier.ModifierKeyword accessModifier = Modifier.ModifierKeyword.toKeyword(fVisibility);
    if (accessModifier != null) fieldDeclaration.modifiers().add(ast.newModifier(accessModifier));
    fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
    fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));

    boolean createComments =
        JavaPreferencesSettings.getCodeGenerationSettings(fCu.getJavaProject()).createComments;
    if (createComments) {
      String comment =
          CodeGeneration.getFieldComment(
              fCu, getConstantTypeName(), fConstantName, StubUtility.getLineDelimiterUsed(fCu));
      if (comment != null && comment.length() > 0) {
        Javadoc doc =
            (Javadoc) fCuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
        fieldDeclaration.setJavadoc(doc);
      }
    }

    AbstractTypeDeclaration parent = getContainingTypeDeclarationNode();
    ListRewrite listRewrite =
        fCuRewrite.getASTRewrite().getListRewrite(parent, parent.getBodyDeclarationsProperty());
    TextEditGroup msg =
        fCuRewrite.createGroupDescription(
            RefactoringCoreMessages.ExtractConstantRefactoring_declare_constant);
    if (insertFirst()) {
      listRewrite.insertFirst(fieldDeclaration, msg);
    } else {
      listRewrite.insertAfter(fieldDeclaration, getNodeToInsertConstantDeclarationAfter(), msg);
    }

    if (fLinkedProposalModel != null) {
      ASTRewrite rewrite = fCuRewrite.getASTRewrite();
      LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
      nameGroup.addPosition(rewrite.track(variableDeclarationFragment.getName()), true);

      String[] nameSuggestions = guessConstantNames();
      if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fConstantName)) {
        nameGroup.addProposal(fConstantName, null, nameSuggestions.length + 1);
      }
      for (int i = 0; i < nameSuggestions.length; i++) {
        nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i);
      }

      LinkedProposalPositionGroup typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
      typeGroup.addPosition(rewrite.track(type), true);

      ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression());
      if (typeBinding != null) {
        ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(ast, typeBinding);
        for (int i = 0; i < relaxingTypes.length; i++) {
          typeGroup.addProposal(relaxingTypes[i], fCuRewrite.getCu(), relaxingTypes.length - i);
        }
      }
      boolean isInterface =
          parent.resolveBinding() != null && parent.resolveBinding().isInterface();
      ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(
          fLinkedProposalModel, rewrite, fieldDeclaration.modifiers(), isInterface);
    }
  }