Java Code Examples for org.eclipse.jdt.core.dom.rewrite.ASTRewrite#set()
The following examples show how to use
org.eclipse.jdt.core.dom.rewrite.ASTRewrite#set() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExtractMethodFragmentRefactoring.java From JDeodorant with MIT License | 6 votes |
protected TryStatement copyTryStatement(ASTRewrite sourceRewriter, AST ast, TryStatement tryStatementParent) { TryStatement newTryStatement = ast.newTryStatement(); ListRewrite resourceRewrite = sourceRewriter.getListRewrite(newTryStatement, TryStatement.RESOURCES_PROPERTY); List<VariableDeclarationExpression> resources = tryStatementParent.resources(); for(VariableDeclarationExpression expression : resources) { resourceRewrite.insertLast(expression, null); } ListRewrite catchClauseRewrite = sourceRewriter.getListRewrite(newTryStatement, TryStatement.CATCH_CLAUSES_PROPERTY); List<CatchClause> catchClauses = tryStatementParent.catchClauses(); for(CatchClause catchClause : catchClauses) { catchClauseRewrite.insertLast(catchClause, null); } if(tryStatementParent.getFinally() != null) { sourceRewriter.set(newTryStatement, TryStatement.FINALLY_PROPERTY, tryStatementParent.getFinally(), null); } return newTryStatement; }
Example 2
Source File: QuickAssistProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private static boolean getAddElseProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) { if (!(node instanceof IfStatement)) { return false; } IfStatement ifStatement= (IfStatement) node; if (ifStatement.getElseStatement() != null) { return false; } if (resultingCollections == null) { return true; } AST ast= node.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); Block body= ast.newBlock(); rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, body, null); String label= CorrectionMessages.QuickAssistProcessor_addelseblock_description; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_ELSE_BLOCK, image); resultingCollections.add(proposal); return true; }
Example 3
Source File: MoveMethodRefactoring.java From JDeodorant with MIT License | 6 votes |
private SimpleName addSourceClassParameterToMovedMethod(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) { AST ast = newMethodDeclaration.getAST(); SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration(); SimpleName typeName = ast.newSimpleName(sourceTypeDeclaration.getName().getIdentifier()); Type parameterType = ast.newSimpleType(typeName); targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, parameterType, null); String sourceTypeName = sourceTypeDeclaration.getName().getIdentifier(); SimpleName parameterName = ast.newSimpleName(sourceTypeName.replaceFirst(Character.toString(sourceTypeName.charAt(0)), Character.toString(Character.toLowerCase(sourceTypeName.charAt(0))))); targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, parameterName, null); ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY); parametersRewrite.insertLast(parameter, null); this.additionalArgumentsAddedToMovedMethod.add("this"); this.additionalTypeBindingsToBeImportedInTargetClass.add(sourceTypeDeclaration.resolveBinding()); addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, parameterName.getIdentifier()); setPublicModifierToSourceTypeDeclaration(); return parameterName; }
Example 4
Source File: ReturnTypeSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
public static void addMethodWithConstrNameProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode instanceof MethodDeclaration) { MethodDeclaration declaration= (MethodDeclaration) selectedNode; ASTRewrite rewrite= ASTRewrite.create(declaration.getAST()); rewrite.set(declaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.TRUE, null); String label= CorrectionMessages.ReturnTypeSubProcessor_constrnamemethod_description; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_CONSTRUCTOR, image); proposals.add(proposal); } }
Example 5
Source File: MoveMethodRefactoring.java From JDeodorant with MIT License | 6 votes |
private void addParameterToMovedMethod(MethodDeclaration newMethodDeclaration, SimpleName fieldName, ASTRewrite targetRewriter) { AST ast = newMethodDeclaration.getAST(); SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration(); Type fieldType = null; FieldDeclaration[] fields = sourceTypeDeclaration.getFields(); for(FieldDeclaration field : fields) { List<VariableDeclarationFragment> fragments = field.fragments(); for(VariableDeclarationFragment fragment : fragments) { if(fragment.getName().getIdentifier().equals(fieldName.getIdentifier())) { fieldType = field.getType(); break; } } } targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldType, null); targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, ast.newSimpleName(fieldName.getIdentifier()), null); ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY); parametersRewrite.insertLast(parameter, null); this.additionalArgumentsAddedToMovedMethod.add(fieldName.getIdentifier()); this.additionalTypeBindingsToBeImportedInTargetClass.add(fieldType.resolveBinding()); addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, fieldName.getIdentifier()); }
Example 6
Source File: MoveMethodRefactoring.java From JDeodorant with MIT License | 6 votes |
private void addParamTagElementToJavadoc(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter, String parameterToBeAdded) { if(newMethodDeclaration.getJavadoc() != null) { AST ast = newMethodDeclaration.getAST(); Javadoc javadoc = newMethodDeclaration.getJavadoc(); List<TagElement> tags = javadoc.tags(); TagElement returnTagElement = null; for(TagElement tag : tags) { if(tag.getTagName() != null && tag.getTagName().equals(TagElement.TAG_RETURN)) { returnTagElement = tag; break; } } TagElement tagElement = ast.newTagElement(); targetRewriter.set(tagElement, TagElement.TAG_NAME_PROPERTY, TagElement.TAG_PARAM, null); ListRewrite fragmentsRewrite = targetRewriter.getListRewrite(tagElement, TagElement.FRAGMENTS_PROPERTY); SimpleName paramName = ast.newSimpleName(parameterToBeAdded); fragmentsRewrite.insertLast(paramName, null); ListRewrite tagsRewrite = targetRewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY); if(returnTagElement != null) tagsRewrite.insertBefore(tagElement, returnTagElement, null); else tagsRewrite.insertLast(tagElement, null); } }
Example 7
Source File: MoveMethodRefactoring.java From JDeodorant with MIT License | 6 votes |
private void modifySourceStaticMethodInvocationsInTargetClass(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) { ExpressionExtractor extractor = new ExpressionExtractor(); List<Expression> sourceMethodInvocations = extractor.getMethodInvocations(sourceMethod.getBody()); List<Expression> newMethodInvocations = extractor.getMethodInvocations(newMethodDeclaration.getBody()); int i = 0; for(Expression expression : sourceMethodInvocations) { if(expression instanceof MethodInvocation) { MethodInvocation methodInvocation = (MethodInvocation)expression; IMethodBinding methodBinding = methodInvocation.resolveMethodBinding(); if((methodBinding.getModifiers() & Modifier.STATIC) != 0 && methodBinding.getDeclaringClass().isEqualTo(sourceTypeDeclaration.resolveBinding()) && !additionalMethodsToBeMoved.containsKey(methodInvocation)) { AST ast = newMethodDeclaration.getAST(); SimpleName qualifier = ast.newSimpleName(sourceTypeDeclaration.getName().getIdentifier()); targetRewriter.set(newMethodInvocations.get(i), MethodInvocation.EXPRESSION_PROPERTY, qualifier, null); this.additionalTypeBindingsToBeImportedInTargetClass.add(sourceTypeDeclaration.resolveBinding()); } } i++; } }
Example 8
Source File: PolymorphismRefactoring.java From JDeodorant with MIT License | 5 votes |
protected Expression generateDefaultValue(ASTRewrite sourceRewriter, AST ast, ITypeBinding returnTypeBinding) { Expression returnedExpression = null; if(returnTypeBinding.isPrimitive()) { if(returnTypeBinding.getQualifiedName().equals("boolean")) { returnedExpression = ast.newBooleanLiteral(false); } else if(returnTypeBinding.getQualifiedName().equals("char")) { CharacterLiteral characterLiteral = ast.newCharacterLiteral(); sourceRewriter.set(characterLiteral, CharacterLiteral.ESCAPED_VALUE_PROPERTY, "\u0000", null); returnedExpression = characterLiteral; } else if(returnTypeBinding.getQualifiedName().equals("int") || returnTypeBinding.getQualifiedName().equals("short") || returnTypeBinding.getQualifiedName().equals("byte")) { returnedExpression = ast.newNumberLiteral("0"); } else if(returnTypeBinding.getQualifiedName().equals("long")) { returnedExpression = ast.newNumberLiteral("0L"); } else if(returnTypeBinding.getQualifiedName().equals("float")) { returnedExpression = ast.newNumberLiteral("0.0f"); } else if(returnTypeBinding.getQualifiedName().equals("double")) { returnedExpression = ast.newNumberLiteral("0.0d"); } else if(returnTypeBinding.getQualifiedName().equals("void")) { returnedExpression = null; } } else { returnedExpression = ast.newNullLiteral(); } return returnedExpression; }
Example 9
Source File: AdvancedQuickAssistProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private static void addExplicitTypeArgumentsIfNecessary(ASTRewrite rewrite, ASTRewriteCorrectionProposal proposal, Expression invocation) { if (Invocations.isResolvedTypeInferredFromExpectedType(invocation)) { ITypeBinding[] typeArguments= Invocations.getInferredTypeArguments(invocation); if (typeArguments == null) return; ImportRewrite importRewrite= proposal.getImportRewrite(); if (importRewrite == null) { importRewrite= proposal.createImportRewrite((CompilationUnit) invocation.getRoot()); } ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(invocation, importRewrite); AST ast= invocation.getAST(); ListRewrite typeArgsRewrite= Invocations.getInferredTypeArgumentsRewrite(rewrite, invocation); for (int i= 0; i < typeArguments.length; i++) { Type typeArgumentNode= importRewrite.addImport(typeArguments[i], ast, importRewriteContext); typeArgsRewrite.insertLast(typeArgumentNode, null); } if (invocation instanceof MethodInvocation) { MethodInvocation methodInvocation= (MethodInvocation) invocation; Expression expression= methodInvocation.getExpression(); if (expression == null) { IMethodBinding methodBinding= methodInvocation.resolveMethodBinding(); if (methodBinding != null && Modifier.isStatic(methodBinding.getModifiers())) { expression= ast.newName(importRewrite.addImport(methodBinding.getDeclaringClass().getTypeDeclaration(), importRewriteContext)); } else { expression= ast.newThisExpression(); } rewrite.set(invocation, MethodInvocation.EXPRESSION_PROPERTY, expression, null); } } } }
Example 10
Source File: LocalCorrectionsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (!(selectedNode instanceof Name)) { return; } Name name= (Name) selectedNode; IBinding binding= name.resolveBinding(); if (!(binding instanceof IVariableBinding)) { return; } IVariableBinding varBinding= (IVariableBinding) binding; CompilationUnit astRoot= context.getASTRoot(); ASTNode node= astRoot.findDeclaringNode(binding); if (node instanceof VariableDeclarationFragment) { ASTRewrite rewrite= ASTRewrite.create(node.getAST()); VariableDeclarationFragment fragment= (VariableDeclarationFragment) node; if (fragment.getInitializer() != null) { return; } Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType()); if (expression == null) { return; } rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, expression, null); String label= CorrectionMessages.LocalCorrectionsSubProcessor_uninitializedvariable_description; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.INITIALIZE_VARIABLE, image); proposal.addLinkedPosition(rewrite.track(expression), false, "initializer"); //$NON-NLS-1$ proposals.add(proposal); } }
Example 11
Source File: ControlStatementsFix.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { ASTRewrite rewrite= cuRewrite.getASTRewrite(); Block block= (Block)fStatement.getStructuralProperty(fChild); Statement statement= (Statement)block.statements().get(0); Statement moveTarget= (Statement)rewrite.createMoveTarget(statement); TextEditGroup group= createTextEditGroup(FixMessages.ControlStatementsFix_removeBrackets_proposalDescription, cuRewrite); rewrite.set(fStatement, fChild, moveTarget, group); }
Example 12
Source File: CreateElementInCUOperation.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Inserts the given child into the given AST, * based on the position settings of this operation. * * @see #createAfter(IJavaElement) * @see #createBefore(IJavaElement) */ protected void insertASTNode(ASTRewrite rewriter, ASTNode parent, ASTNode child) throws JavaModelException { StructuralPropertyDescriptor propertyDescriptor = getChildPropertyDescriptor(parent); if (propertyDescriptor instanceof ChildListPropertyDescriptor) { ChildListPropertyDescriptor childListPropertyDescriptor = (ChildListPropertyDescriptor) propertyDescriptor; ListRewrite rewrite = rewriter.getListRewrite(parent, childListPropertyDescriptor); switch (this.insertionPolicy) { case INSERT_BEFORE: ASTNode element = ((JavaElement) this.anchorElement).findNode(this.cuAST); if (childListPropertyDescriptor.getElementType().isAssignableFrom(element.getClass())) rewrite.insertBefore(child, element, null); else // case of an empty import list: the anchor element is the top level type and cannot be used in insertBefore as it is not the same type rewrite.insertLast(child, null); break; case INSERT_AFTER: element = ((JavaElement) this.anchorElement).findNode(this.cuAST); if (childListPropertyDescriptor.getElementType().isAssignableFrom(element.getClass())) rewrite.insertAfter(child, element, null); else // case of an empty import list: the anchor element is the top level type and cannot be used in insertAfter as it is not the same type rewrite.insertLast(child, null); break; case INSERT_LAST: rewrite.insertLast(child, null); break; } } else { rewriter.set(parent, propertyDescriptor, child, null); } }
Example 13
Source File: AdvancedQuickAssistProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private static boolean getInverseIfProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) { if (!(covering instanceof IfStatement)) { return false; } IfStatement ifStatement= (IfStatement) covering; if (ifStatement.getElseStatement() == null) { return false; } // we could produce quick assist if (resultingCollections == null) { return true; } // AST ast= covering.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); Statement thenStatement= ifStatement.getThenStatement(); Statement elseStatement= ifStatement.getElseStatement(); // prepare original nodes Expression inversedExpression= getInversedExpression(rewrite, ifStatement.getExpression()); Statement newElseStatement= (Statement) rewrite.createMoveTarget(thenStatement); Statement newThenStatement= (Statement) rewrite.createMoveTarget(elseStatement); // set new nodes rewrite.set(ifStatement, IfStatement.EXPRESSION_PROPERTY, inversedExpression, null); if (elseStatement instanceof IfStatement) {// bug 79507 && bug 74580 Block elseBlock= ast.newBlock(); elseBlock.statements().add(newThenStatement); newThenStatement= elseBlock; } rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, newThenStatement, null); rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, newElseStatement, null); // add correction proposal String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseIf_description; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_IF_STATEMENT, image); resultingCollections.add(proposal); return true; }
Example 14
Source File: MoveMethodRefactoring.java From JDeodorant with MIT License | 5 votes |
private void addParameterToMovedMethod(MethodDeclaration newMethodDeclaration, IVariableBinding variableBinding, ASTRewrite targetRewriter) { AST ast = newMethodDeclaration.getAST(); SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration(); ITypeBinding typeBinding = variableBinding.getType(); Type fieldType = RefactoringUtility.generateTypeFromTypeBinding(typeBinding, ast, targetRewriter); targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldType, null); targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, ast.newSimpleName(variableBinding.getName()), null); ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY); parametersRewrite.insertLast(parameter, null); this.additionalArgumentsAddedToMovedMethod.add(variableBinding.getName()); this.additionalTypeBindingsToBeImportedInTargetClass.add(variableBinding.getType()); addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, variableBinding.getName()); }
Example 15
Source File: ExtractSupertypeProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Creates a new type signature of a subtype. * * @param subRewrite * the compilation unit rewrite of a subtype * @param declaration * the type declaration of a subtype * @param extractedType * the extracted super type * @param extractedBinding * the binding of the extracted super type * @param monitor * the progress monitor to use * @throws JavaModelException * if the type parameters cannot be retrieved */ protected final void createTypeSignature(final CompilationUnitRewrite subRewrite, final AbstractTypeDeclaration declaration, final IType extractedType, final ITypeBinding extractedBinding, final IProgressMonitor monitor) throws JavaModelException { Assert.isNotNull(subRewrite); Assert.isNotNull(declaration); Assert.isNotNull(extractedType); Assert.isNotNull(monitor); try { monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing, 10); final AST ast= subRewrite.getAST(); Type type= null; if (extractedBinding != null) { type= subRewrite.getImportRewrite().addImport(extractedBinding, ast); } else { subRewrite.getImportRewrite().addImport(extractedType.getFullyQualifiedName('.')); type= ast.newSimpleType(ast.newSimpleName(extractedType.getElementName())); } subRewrite.getImportRemover().registerAddedImport(extractedType.getFullyQualifiedName('.')); if (type != null) { final ITypeParameter[] parameters= extractedType.getTypeParameters(); if (parameters.length > 0) { final ParameterizedType parameterized= ast.newParameterizedType(type); for (int index= 0; index < parameters.length; index++) parameterized.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getElementName()))); type= parameterized; } } final ASTRewrite rewriter= subRewrite.getASTRewrite(); if (type != null && declaration instanceof TypeDeclaration) { final TypeDeclaration extended= (TypeDeclaration) declaration; final Type superClass= extended.getSuperclassType(); if (superClass != null) { rewriter.replace(superClass, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE)); subRewrite.getImportRemover().registerRemovedNode(superClass); } else rewriter.set(extended, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE)); } } finally { monitor.done(); } }
Example 16
Source File: ExtractMethodFragmentRefactoring.java From JDeodorant with MIT License | 5 votes |
protected Expression generateDefaultValue(ASTRewrite sourceRewriter, AST ast, ITypeBinding returnTypeBinding) { Expression returnedExpression = null; if(returnTypeBinding.isPrimitive()) { if(returnTypeBinding.getQualifiedName().equals("boolean")) { returnedExpression = ast.newBooleanLiteral(false); } else if(returnTypeBinding.getQualifiedName().equals("char")) { CharacterLiteral characterLiteral = ast.newCharacterLiteral(); sourceRewriter.set(characterLiteral, CharacterLiteral.ESCAPED_VALUE_PROPERTY, "\u0000", null); returnedExpression = characterLiteral; } else if(returnTypeBinding.getQualifiedName().equals("int") || returnTypeBinding.getQualifiedName().equals("short") || returnTypeBinding.getQualifiedName().equals("byte")) { returnedExpression = ast.newNumberLiteral("0"); } else if(returnTypeBinding.getQualifiedName().equals("long")) { returnedExpression = ast.newNumberLiteral("0L"); } else if(returnTypeBinding.getQualifiedName().equals("float")) { returnedExpression = ast.newNumberLiteral("0.0f"); } else if(returnTypeBinding.getQualifiedName().equals("double")) { returnedExpression = ast.newNumberLiteral("0.0d"); } else if(returnTypeBinding.getQualifiedName().equals("void")) { returnedExpression = null; } } else { returnedExpression = ast.newNullLiteral(); } return returnedExpression; }
Example 17
Source File: MoveInstanceMethodProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
@Override public final boolean visit(final MethodInvocation node) { Assert.isNotNull(node); final Expression expression= node.getExpression(); final IMethodBinding method= node.resolveMethodBinding(); if (method != null) { final ASTRewrite rewrite= fRewrite; if (expression == null) { final AST ast= node.getAST(); if (!JdtFlags.isStatic(method)) rewrite.set(node, MethodInvocation.EXPRESSION_PROPERTY, ast.newSimpleName(fTargetName), null); else if (!fStaticImports.contains(method)) { ITypeBinding declaring= method.getDeclaringClass(); if (declaring != null) { IType type= (IType) declaring.getJavaElement(); if (type != null) { rewrite.set(node, MethodInvocation.EXPRESSION_PROPERTY, ast.newName(type.getTypeQualifiedName('.')), null); } } } return true; } else { if (expression instanceof FieldAccess) { final FieldAccess access= (FieldAccess) expression; if (Bindings.equals(fTarget, access.resolveFieldBinding())) { rewrite.remove(expression, null); visit(node.arguments()); return false; } } else if (expression instanceof Name) { final Name name= (Name) expression; if (Bindings.equals(fTarget, name.resolveBinding())) { rewrite.remove(expression, null); visit(node.arguments()); return false; } } } } return true; }
Example 18
Source File: ModifierChangeCorrectionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
@Override protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot = ASTResolving.findParentCompilationUnit(fNode); ASTNode boundNode = astRoot.findDeclaringNode(fBinding); ASTNode declNode = null; if (boundNode != null) { declNode = boundNode; // is same CU } else { //setSelectionDescription(selectionDescription); CompilationUnit newRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null); declNode = newRoot.findDeclaringNode(fBinding.getKey()); } if (declNode != null) { AST ast = declNode.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); if (declNode.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { VariableDeclarationFragment fragment = (VariableDeclarationFragment) declNode; ASTNode parent = declNode.getParent(); if (parent instanceof FieldDeclaration) { FieldDeclaration fieldDecl = (FieldDeclaration) parent; if (fieldDecl.fragments().size() > 1 && (fieldDecl.getParent() instanceof AbstractTypeDeclaration)) { // split VariableDeclarationRewrite.rewriteModifiers(fieldDecl, new VariableDeclarationFragment[] { fragment }, fIncludedModifiers, fExcludedModifiers, rewrite, null); return rewrite; } } else if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement varDecl = (VariableDeclarationStatement) parent; if (varDecl.fragments().size() > 1 && (varDecl.getParent() instanceof Block)) { // split VariableDeclarationRewrite.rewriteModifiers(varDecl, new VariableDeclarationFragment[] { fragment }, fIncludedModifiers, fExcludedModifiers, rewrite, null); return rewrite; } } else if (parent instanceof VariableDeclarationExpression) { // can't separate } declNode = parent; } else if (declNode.getNodeType() == ASTNode.METHOD_DECLARATION) { MethodDeclaration methodDecl = (MethodDeclaration) declNode; if (!methodDecl.isConstructor()) { IMethodBinding methodBinding = methodDecl.resolveBinding(); if (methodDecl.getBody() == null && methodBinding != null && Modifier.isAbstract(methodBinding.getModifiers()) && Modifier.isStatic(fIncludedModifiers)) { // add body ICompilationUnit unit = getCompilationUnit(); String delimiter = unit.findRecommendedLineSeparator(); String bodyStatement = ""; //$NON-NLS-1$ Block body = ast.newBlock(); rewrite.set(methodDecl, MethodDeclaration.BODY_PROPERTY, body, null); Type returnType = methodDecl.getReturnType2(); if (returnType != null) { Expression expression = ASTNodeFactory.newDefaultExpression(ast, returnType, methodDecl.getExtraDimensions()); if (expression != null) { ReturnStatement returnStatement = ast.newReturnStatement(); returnStatement.setExpression(expression); bodyStatement = ASTNodes.asFormattedString(returnStatement, 0, delimiter, unit.getJavaProject().getOptions(true)); } } String placeHolder = CodeGeneration.getMethodBodyContent(unit, methodBinding.getDeclaringClass().getName(), methodBinding.getName(), false, bodyStatement, delimiter); if (placeHolder != null) { ReturnStatement todoNode = (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT); body.statements().add(todoNode); } } } } ModifierRewrite listRewrite = ModifierRewrite.create(rewrite, declNode); PositionInformation trackedDeclNode = listRewrite.setModifiers(fIncludedModifiers, fExcludedModifiers, null); LinkedProposalPositionGroupCore positionGroup = new LinkedProposalPositionGroupCore("group"); //$NON-NLS-1$ positionGroup.addPosition(trackedDeclNode); getLinkedProposalModel().addPositionGroup(positionGroup); if (boundNode != null) { // only set end position if in same CU setEndPosition(rewrite.track(fNode)); } return rewrite; } return null; }
Example 19
Source File: UnresolvedElementsSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection<ChangeCorrectionProposal> proposals) { ITypeBinding declaringType= binding.getDeclaringClass(); ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode); ITypeBinding currType= parentType; boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers()); while (currType != null && !Bindings.isSuperType(declaringType, currType)) { if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) { return; } currType= currType.getDeclaringClass(); } if (currType == null || currType == parentType) { return; } ASTRewrite rewrite= ASTRewrite.create(invocationNode.getAST()); String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetoouter_description, org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(currType)); ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_WITH_ENCLOSING_TYPE); ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot()); ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(invocationNode, imports); AST ast= invocationNode.getAST(); String qualifier= imports.addImport(currType, importRewriteContext); Name name= ASTNodeFactory.newName(ast, qualifier); Expression newExpression; if (isInstanceMethod) { ThisExpression expr= ast.newThisExpression(); expr.setQualifier(name); newExpression= expr; } else { newExpression= name; } rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null); proposals.add(proposal); }
Example 20
Source File: ReturnTypeSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
public static void addMissingReturnTypeProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (selectedNode == null) { return; } BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl instanceof MethodDeclaration) { MethodDeclaration methodDeclaration= (MethodDeclaration) decl; ReturnStatementCollector eval= new ReturnStatementCollector(); decl.accept(eval); AST ast= astRoot.getAST(); ITypeBinding typeBinding= eval.getTypeBinding(decl.getAST()); typeBinding= Bindings.normalizeTypeBinding(typeBinding); if (typeBinding == null) { typeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$ } if (typeBinding.isWildcardType()) { typeBinding= ASTResolving.normalizeWildcardType(typeBinding, true, ast); } ASTRewrite rewrite= ASTRewrite.create(ast); String label= Messages.format(CorrectionMessages.ReturnTypeSubProcessor_missingreturntype_description, BindingLabelProviderCore.getBindingLabel(typeBinding, BindingLabelProviderCore.DEFAULT_TEXTFLAGS)); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, CodeActionKind.QuickFix, cu, rewrite, IProposalRelevance.MISSING_RETURN_TYPE); ImportRewrite imports= proposal.createImportRewrite(astRoot); ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports); Type type= imports.addImport(typeBinding, ast, importRewriteContext, TypeLocation.RETURN_TYPE); rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, type, null); rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null); Javadoc javadoc= methodDeclaration.getJavadoc(); if (javadoc != null && typeBinding != null) { TagElement newTag= ast.newTagElement(); newTag.setTagName(TagElement.TAG_RETURN); TextElement commentStart= ast.newTextElement(); newTag.fragments().add(commentStart); JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null); proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start"); //$NON-NLS-1$ } String key= "return_type"; //$NON-NLS-1$ proposal.addLinkedPosition(rewrite.track(type), true, key); if (typeBinding != null) { ITypeBinding[] bindings= ASTResolving.getRelaxingTypes(ast, typeBinding); for (int i= 0; i < bindings.length; i++) { proposal.addLinkedPositionProposal(key, bindings[i]); } } proposals.add(proposal); // change to constructor ASTNode parentType= ASTResolving.findParentType(decl); if (parentType instanceof AbstractTypeDeclaration) { boolean isInterface= parentType instanceof TypeDeclaration && ((TypeDeclaration) parentType).isInterface(); if (!isInterface) { String constructorName= ((AbstractTypeDeclaration) parentType).getName().getIdentifier(); ASTNode nameNode= methodDeclaration.getName(); label= Messages.format(CorrectionMessages.ReturnTypeSubProcessor_wrongconstructorname_description, BasicElementLabels.getJavaElementName(constructorName)); proposals.add(new ReplaceCorrectionProposal(label, cu, nameNode.getStartPosition(), nameNode.getLength(), constructorName, IProposalRelevance.CHANGE_TO_CONSTRUCTOR)); } } } }