org.eclipse.jdt.core.dom.rewrite.ASTRewrite Java Examples
The following examples show how to use
org.eclipse.jdt.core.dom.rewrite.ASTRewrite.
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: CreateDoPrivilegedBlockResolution.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
private ParameterizedType createPrivilegedActionType(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) { AST ast = rewrite.getAST(); Name privilegedActionName; if (isUpdateImports()) { privilegedActionName = ast.newSimpleName(PrivilegedAction.class.getSimpleName()); } else { privilegedActionName = ast.newName(PrivilegedAction.class.getName()); } SimpleType rawPrivilegedActionType = ast.newSimpleType(privilegedActionName); ParameterizedType privilegedActionType = ast.newParameterizedType(rawPrivilegedActionType); Type typeArgument = (Type) rewrite.createCopyTarget(classLoaderCreation.getType()); List<Type> typeArguments = checkedList(privilegedActionType.typeArguments()); typeArguments.add(typeArgument); return privilegedActionType; }
Example #2
Source File: MoveInstanceMethodProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Creates the method content of the moved method. * * @param document * the document representing the source compilation unit * @param declaration * the source method declaration * @param rewrite * the ast rewrite to use * @return the string representing the moved method body * @throws BadLocationException * if an offset into the document is invalid */ protected String createMethodContent(final IDocument document, final MethodDeclaration declaration, final ASTRewrite rewrite) throws BadLocationException { Assert.isNotNull(document); Assert.isNotNull(declaration); Assert.isNotNull(rewrite); final IRegion range= new Region(declaration.getStartPosition(), declaration.getLength()); final RangeMarker marker= new RangeMarker(range.getOffset(), range.getLength()); final IJavaProject project= fMethod.getJavaProject(); final TextEdit[] edits= rewrite.rewriteAST(document, project.getOptions(true)).removeChildren(); for (int index= 0; index < edits.length; index++) marker.addChild(edits[index]); final MultiTextEdit result= new MultiTextEdit(); result.addChild(marker); final TextEditProcessor processor= new TextEditProcessor(document, new MultiTextEdit(0, document.getLength()), TextEdit.UPDATE_REGIONS); processor.getRoot().addChild(result); processor.performEdits(); final IRegion region= document.getLineInformation(document.getLineOfOffset(marker.getOffset())); return Strings.changeIndent(document.get(marker.getOffset(), marker.getLength()), Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project), project, "", TextUtilities.getDefaultLineDelimiter(document)); //$NON-NLS-1$ }
Example #3
Source File: NewAnnotationMemberProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private Type getNewType(ASTRewrite rewrite) { AST ast= rewrite.getAST(); Type newTypeNode= null; ITypeBinding binding= null; if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) { Expression value= ((MemberValuePair) fInvocationNode.getParent()).getValue(); binding= value.resolveTypeBinding(); } else if (fInvocationNode instanceof Expression) { binding= ((Expression) fInvocationNode).resolveTypeBinding(); } if (binding != null) { ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fInvocationNode, getImportRewrite()); newTypeNode= getImportRewrite().addImport(binding, ast, importRewriteContext); } if (newTypeNode == null) { newTypeNode= ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$ } return newTypeNode; }
Example #4
Source File: ConvertForLoopOperation.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * {@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); }
Example #5
Source File: AbstractUpdateSignatureProposal.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 6 votes |
@Override protected ASTRewrite getRewrite() { MethodDeclaration dstMethod = findBestUpdateMatch(rpcPair); CompilationUnit astRoot = ASTResolving.createQuickFixAST( getCompilationUnit(), null); createImportRewrite(astRoot); ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); MethodDeclaration rewriterDstMethod = JavaASTUtils.findMethodDeclaration( astRoot, dstMethod.resolveBinding().getKey()); if (rewriterDstMethod == null) { return null; } MethodDeclaration newSignature = computeMethodSignature(rewrite.getAST(), rpcPair, rewriterDstMethod); rewrite.replace(rewriterDstMethod, newSignature, null); return rewrite; }
Example #6
Source File: LocalCorrectionsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) { AST ast= selectedNode.getAST(); SwitchStatement parent= (SwitchStatement) selectedNode.getParent(); for (Statement statement : (List<Statement>) parent.statements()) { if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) { // insert //$CASES-OMITTED$: ASTRewrite rewrite= ASTRewrite.create(ast); rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer()); ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); ASTNode casesOmittedComment= rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$ listRewrite.insertBefore(casesOmittedComment, statement, null); String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED, image); proposals.add(proposal); break; } } } }
Example #7
Source File: NewVariableCorrectionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
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); return rewrite; } return null; }
Example #8
Source File: NewMethodCorrectionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Override protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException { AST ast= rewrite.getAST(); List<Expression> arguments= fArguments; for (int i= 0; i < arguments.size(); i++) { Expression elem= arguments.get(i); SingleVariableDeclaration param= ast.newSingleVariableDeclaration(); // argument type String argTypeKey= "arg_type_" + i; //$NON-NLS-1$ Type type= evaluateParameterType(ast, elem, argTypeKey, context); param.setType(type); // argument name String argNameKey= "arg_name_" + i; //$NON-NLS-1$ String name= evaluateParameterName(takenNames, elem, type, argNameKey); param.setName(ast.newSimpleName(name)); params.add(param); } }
Example #9
Source File: JavadocTagsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void insertAllMissingTypeTags(ASTRewrite rewriter, TypeDeclaration typeDecl) { AST ast= typeDecl.getAST(); Javadoc javadoc= typeDecl.getJavadoc(); ListRewrite tagsRewriter= rewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY); List<TypeParameter> typeParams= typeDecl.typeParameters(); for (int i= typeParams.size() - 1; i >= 0; i--) { TypeParameter decl= typeParams.get(i); String name= '<' + decl.getName().getIdentifier() + '>'; if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) { TagElement newTag= ast.newTagElement(); newTag.setTagName(TagElement.TAG_PARAM); TextElement text= ast.newTextElement(); text.setText(name); newTag.fragments().add(text); insertTabStop(rewriter, newTag.fragments(), "typeParam" + i); //$NON-NLS-1$ insertTag(tagsRewriter, newTag, getPreviousTypeParamNames(typeParams, decl)); } } }
Example #10
Source File: MoveInnerToTopRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void addEnclosingInstanceTypeParameters(final ITypeBinding[] parameters, final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) { Assert.isNotNull(parameters); Assert.isNotNull(declaration); Assert.isNotNull(rewrite); if (declaration instanceof TypeDeclaration) { final TypeDeclaration type= (TypeDeclaration) declaration; final List<TypeParameter> existing= type.typeParameters(); final Set<String> names= new HashSet<String>(); TypeParameter parameter= null; for (final Iterator<TypeParameter> iterator= existing.iterator(); iterator.hasNext();) { parameter= iterator.next(); names.add(parameter.getName().getIdentifier()); } final ListRewrite rewriter= rewrite.getListRewrite(type, TypeDeclaration.TYPE_PARAMETERS_PROPERTY); String name= null; for (int index= 0; index < parameters.length; index++) { name= parameters[index].getName(); if (!names.contains(name)) { parameter= type.getAST().newTypeParameter(); parameter.setName(type.getAST().newSimpleName(name)); rewriter.insertLast(parameter, null); } } } }
Example #11
Source File: JavaStatementPostfixContext.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Adds a new field to the {@link AST} using the given type and variable name. The method * returns a {@link TextEdit} which can then be applied using the {@link #applyTextEdit(TextEdit)} method. * * @param type * @param varName * @return a {@link TextEdit} which represents the changes which would be made, or <code>null</code> if the field * can not be created. */ public TextEdit addField(String type, String varName, boolean publicField, boolean staticField, boolean finalField, String value) { if (isReadOnly()) return null; if (!domInitialized) initDomAST(); boolean isStatic = isBodyStatic(); int modifiers = (!publicField) ? Modifier.PRIVATE : Modifier.PUBLIC; if (isStatic || staticField) { modifiers |= Modifier.STATIC; } if (finalField) { modifiers |= Modifier.FINAL; } ASTRewrite rewrite= ASTRewrite.create(parentDeclaration.getAST()); VariableDeclarationFragment newDeclFrag = addFieldDeclaration(rewrite, parentDeclaration, modifiers, varName, type, value); TextEdit te = rewrite.rewriteAST(getDocument(), null); return te; }
Example #12
Source File: ConstructorFromSuperclassProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Override protected ASTRewrite getRewrite() throws CoreException { AST ast= fTypeNode.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); createImportRewrite((CompilationUnit) fTypeNode.getRoot()); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit().getJavaProject()); if (!settings.createComments) { settings= null; } ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fTypeNode, getImportRewrite()); MethodDeclaration newMethodDecl= createNewMethodDeclaration(ast, fSuperConstructor, rewrite, importRewriteContext, settings); rewrite.getListRewrite(fTypeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY).insertFirst(newMethodDecl, null); addLinkedRanges(rewrite, newMethodDecl); return rewrite; }
Example #13
Source File: UseEqualsResolution.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
protected Expression createEqualsExpression(ASTRewrite rewrite, InfixExpression stringEqualityCheck) { Assert.isNotNull(rewrite); Assert.isNotNull(stringEqualityCheck); final AST ast = rewrite.getAST(); MethodInvocation equalsInvocation = ast.newMethodInvocation(); Expression leftOperand = createLeftOperand(rewrite, stringEqualityCheck.getLeftOperand()); Expression rightOperand = createRightOperand(rewrite, stringEqualityCheck.getRightOperand()); equalsInvocation.setName(ast.newSimpleName(EQUALS_METHOD_NAME)); equalsInvocation.setExpression(leftOperand); ListRewrite argumentsRewrite = rewrite.getListRewrite(equalsInvocation, MethodInvocation.ARGUMENTS_PROPERTY); argumentsRewrite.insertLast(rightOperand, null); return equalsInvocation; }
Example #14
Source File: UnusedCodeFix.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedModel) throws CoreException { ASTRewrite rewrite= cuRewrite.getASTRewrite(); IBinding binding= fUnusedName.resolveBinding(); CompilationUnit root= (CompilationUnit) fUnusedName.getRoot(); String displayString= FixMessages.UnusedCodeFix_RemoveUnusedTypeParameter_description; TextEditGroup group= createTextEditGroup(displayString, cuRewrite); 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); } }
Example #15
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 #16
Source File: ReorgPolicyFactory.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private void copyImportsToDestination(IImportContainer container, ASTRewrite rewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException { ListRewrite listRewrite= rewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY); IJavaElement[] importDeclarations= container.getChildren(); for (int i= 0; i < importDeclarations.length; i++) { IImportDeclaration declaration= (IImportDeclaration) importDeclarations[i]; ImportDeclaration sourceNode= ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode); ImportDeclaration copiedNode= (ImportDeclaration) ASTNode.copySubtree(rewrite.getAST(), sourceNode); if (getLocation() == IReorgDestination.LOCATION_BEFORE) { listRewrite.insertFirst(copiedNode, null); } else { listRewrite.insertLast(copiedNode, null); } } }
Example #17
Source File: JavadocTagsSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private void insertAllMissingTypeTags(ASTRewrite rewriter, TypeDeclaration typeDecl) { AST ast= typeDecl.getAST(); Javadoc javadoc= typeDecl.getJavadoc(); ListRewrite tagsRewriter= rewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY); List<TypeParameter> typeParams= typeDecl.typeParameters(); for (int i= typeParams.size() - 1; i >= 0; i--) { TypeParameter decl= typeParams.get(i); String name= '<' + decl.getName().getIdentifier() + '>'; if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) { TagElement newTag= ast.newTagElement(); newTag.setTagName(TagElement.TAG_PARAM); TextElement text= ast.newTextElement(); text.setText(name); newTag.fragments().add(text); insertTabStop(rewriter, newTag.fragments(), "typeParam" + i); //$NON-NLS-1$ insertTag(tagsRewriter, newTag, getPreviousTypeParamNames(typeParams, decl)); } } }
Example #18
Source File: PullUpRefactoringProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private Javadoc createJavadocForStub(final String enclosingTypeName, final MethodDeclaration oldMethod, final MethodDeclaration newMethodNode, final ICompilationUnit cu, final ASTRewrite rewrite) throws CoreException { if (fSettings.createComments) { final IMethodBinding binding= oldMethod.resolveBinding(); if (binding != null) { final ITypeBinding[] params= binding.getParameterTypes(); final String fullTypeName= getDestinationType().getFullyQualifiedName('.'); final String[] fullParamNames= new String[params.length]; for (int i= 0; i < fullParamNames.length; i++) { fullParamNames[i]= Bindings.getFullyQualifiedName(params[i]); } final String comment= CodeGeneration.getMethodComment(cu, enclosingTypeName, newMethodNode, false, binding.getName(), fullTypeName, fullParamNames, StubUtility.getLineDelimiterUsed(cu)); if (comment != null) return (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); } } return null; }
Example #19
Source File: ConstructorFromSuperclassProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
@Override protected ASTRewrite getRewrite() throws CoreException { AST ast= fTypeNode.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); createImportRewrite((CompilationUnit) fTypeNode.getRoot()); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit().getJavaProject()); if (!settings.createComments) { settings= null; } ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fTypeNode, getImportRewrite()); MethodDeclaration newMethodDecl= createNewMethodDeclaration(ast, fSuperConstructor, rewrite, importRewriteContext, settings); rewrite.getListRewrite(fTypeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY).insertFirst(newMethodDecl, null); addLinkedRanges(rewrite, newMethodDecl); return rewrite; }
Example #20
Source File: QuickAssistProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private static boolean getAddFinallyProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) { TryStatement tryStatement= ASTResolving.findParentTryStatement(node); if (tryStatement == null || tryStatement.getFinally() != null) { return false; } Statement statement= ASTResolving.findParentStatement(node); if (tryStatement != statement && tryStatement.getBody() != statement) { return false; // an node inside a catch or finally block } if (resultingCollections == null) { return true; } AST ast= tryStatement.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); Block finallyBody= ast.newBlock(); rewrite.set(tryStatement, TryStatement.FINALLY_PROPERTY, finallyBody, null); String label= CorrectionMessages.QuickAssistProcessor_addfinallyblock_description; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_FINALLY_BLOCK, image); resultingCollections.add(proposal); return true; }
Example #21
Source File: LocalCorrectionsSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) { ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot()); if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) { AST ast = selectedNode.getAST(); SwitchStatement parent = (SwitchStatement) selectedNode.getParent(); for (Statement statement : (List<Statement>) parent.statements()) { if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) { // insert //$CASES-OMITTED$: ASTRewrite rewrite = ASTRewrite.create(ast); rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer()); ListRewrite listRewrite = rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); ASTNode casesOmittedComment = rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$ listRewrite.insertBefore(casesOmittedComment, statement, null); String label = CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted; ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED); proposals.add(proposal); break; } } } }
Example #22
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 #23
Source File: ImplementInterfaceProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@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, TypeLocation.OTHER); ListRewrite listRewrite= rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY); listRewrite.insertLast(newInterface, null); return rewrite; } return null; }
Example #24
Source File: MoveInstanceMethodProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private ASTNode getFieldReference(SimpleName oldNameNode, ASTRewrite rewrite) { String name= oldNameNode.getIdentifier(); AST ast= rewrite.getAST(); if (isParameterName(name) || StubUtility.useThisForFieldAccess(fTargetRewrite.getCu().getJavaProject())) { FieldAccess fieldAccess= ast.newFieldAccess(); fieldAccess.setExpression(ast.newThisExpression()); fieldAccess.setName((SimpleName) rewrite.createMoveTarget(oldNameNode)); return fieldAccess; } return rewrite.createMoveTarget(oldNameNode); }
Example #25
Source File: JsonDeserializeAdder.java From SparkBuilderGenerator with MIT License | 5 votes |
public void addJsonDeserializeAnnotation(CompilationUnitModificationDomain compilationUnitModificationDomain, TypeDeclaration builderType) { AST ast = compilationUnitModificationDomain.getAst(); ASTRewrite rewriter = compilationUnitModificationDomain.getAstRewriter(); ListRewrite modifierRewrite = rewriter.getListRewrite(compilationUnitModificationDomain.getOriginalType(), TypeDeclaration.MODIFIERS2_PROPERTY); NormalAnnotation annotation = createAnnotation(ast, compilationUnitModificationDomain, builderType); modifierRewrite.insertFirst(annotation, null); importRepository.addImport(StaticPreferences.JSON_DESERIALIZE_FULLY_QUALIFIED_NAME); }
Example #26
Source File: CastCorrectionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) { AST ast= rewrite.getAST(); ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite); if (fCastType != null) { return importRewrite.addImport(fCastType, ast,context, TypeLocation.CAST); } ASTNode node= fNodeToCast; ASTNode parent= node.getParent(); if (parent instanceof CastExpression) { node= parent; parent= parent.getParent(); } while (parent instanceof ParenthesizedExpression) { node= parent; parent= parent.getParent(); } if (parent instanceof MethodInvocation) { MethodInvocation invocation= (MethodInvocation) node.getParent(); if (invocation.getExpression() == node) { IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node); ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext); if (bindings.length > 0) { ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding()); Type newTypeNode= importRewrite.addImport(first, ast, context, TypeLocation.CAST); return newTypeNode; } } } Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ return newCastType; }
Example #27
Source File: GenerateForLoopAssistProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Creates an {@link Assignment} as first expression appearing in an index based * <code>for</code> loop's body. This Assignment declares a local variable and initializes it * using the {@link List}'s current element identified by the loop index. * * @param rewrite the current {@link ASTRewrite} instance * @param loopVariableName the name of the index variable in String representation * @return a completed {@link Assignment} containing the mentioned declaration and * initialization */ private Expression getIndexBasedForBodyAssignment(ASTRewrite rewrite, SimpleName loopVariableName) { AST ast= rewrite.getAST(); ITypeBinding loopOverType= extractElementType(ast); Assignment assignResolvedVariable= ast.newAssignment(); // left hand side SimpleName resolvedVariableName= resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false); VariableDeclarationFragment resolvedVariableDeclarationFragment= ast.newVariableDeclarationFragment(); resolvedVariableDeclarationFragment.setName(resolvedVariableName); VariableDeclarationExpression resolvedVariableDeclaration= ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment); resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite()))); assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration); // right hand side MethodInvocation invokeGetExpression= ast.newMethodInvocation(); invokeGetExpression.setName(ast.newSimpleName("get")); //$NON-NLS-1$ SimpleName indexVariableName= ast.newSimpleName(loopVariableName.getIdentifier()); addLinkedPosition(rewrite.track(indexVariableName), LinkedPositionGroup.NO_STOP, indexVariableName.getIdentifier()); invokeGetExpression.arguments().add(indexVariableName); invokeGetExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression)); assignResolvedVariable.setRightHandSide(invokeGetExpression); assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN); return assignResolvedVariable; }
Example #28
Source File: GetterSetterCorrectionSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public ProposalParameter(boolean useSuper, ICompilationUnit compilationUnit, ASTRewrite rewrite, Expression accessNode, Expression qualifier, IVariableBinding variableBinding) { this.useSuper = useSuper; this.compilationUnit = compilationUnit; this.astRewrite = rewrite; this.accessNode = accessNode; this.qualifier = qualifier; this.variableBinding = variableBinding; }
Example #29
Source File: AdvancedQuickAssistProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private static boolean getInverseConditionalExpressionProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) { // try to find conditional expression as parent while (covering instanceof Expression) { if (covering instanceof ConditionalExpression) break; covering= covering.getParent(); } if (!(covering instanceof ConditionalExpression)) { return false; } ConditionalExpression expression= (ConditionalExpression) covering; // we could produce quick assist if (resultingCollections == null) { return true; } // AST ast= covering.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); // prepare new conditional expression ConditionalExpression newExpression= ast.newConditionalExpression(); newExpression.setExpression(getInversedExpression(rewrite, expression.getExpression())); newExpression.setThenExpression((Expression) rewrite.createCopyTarget(expression.getElseExpression())); newExpression.setElseExpression((Expression) rewrite.createCopyTarget(expression.getThenExpression())); // replace old expression with new rewrite.replace(expression, newExpression, null); // add correction proposal String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseConditionalExpression_description; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_CONDITIONAL_EXPRESSION, image); resultingCollections.add(proposal); return true; }
Example #30
Source File: ModifierCorrectionSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private static Modifier removeModifier(final MethodDeclaration decl, final ASTRewrite rewrite, final int modifier) { Modifier modifierNode= ASTNodes.findModifierNode(modifier, decl.modifiers()); if (modifierNode != null) { rewrite.remove(modifierNode, null); } return modifierNode; }