@Override public boolean visit(VariableDeclarationFragment param) { ASTNode parent = param.getParent(); if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement statement = (VariableDeclarationStatement) parent; ASTNode annotation = getAnnotation(statement.modifiers(), "Domain"); if (annotation != null) { ListRewrite paramRewrite = rewrite.getListRewrite(statement, VariableDeclarationStatement.MODIFIERS2_PROPERTY); paramRewrite.remove(annotation, null); } } return super.visit(param); }
/** * Performs global post-processing of synthesized code: * - Adds import declarations * * @param ast the owner of the document * @param env environment that was used for synthesis * @param document draft program document * @throws BadLocationException if an error occurred when rewriting document */ private void postprocessGlobal(AST ast, Environment env, Document document) throws BadLocationException { /* add imports */ ASTRewrite rewriter = ASTRewrite.create(ast); ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY); Set<Class> toImport = new HashSet<>(env.imports); toImport.addAll(sketch.exceptionsThrown()); // add all catch(...) types to imports for (Class cls : toImport) { while (cls.isArray()) cls = cls.getComponentType(); if (cls.isPrimitive() || cls.getPackage().getName().equals("java.lang")) continue; ImportDeclaration impDecl = cu.getAST().newImportDeclaration(); String className = cls.getName().replaceAll("\\$", "\\."); impDecl.setName(cu.getAST().newName(className.split("\\."))); lrw.insertLast(impDecl, null); } rewriter.rewriteAST(document, null).apply(document); }
public void generateBuilder(CompilationUnitModificationDomain modificationDomain, List<StagedBuilderProperties> stagedBuilderStages) { AST ast = modificationDomain.getAst(); TypeDeclaration originalType = modificationDomain.getOriginalType(); ListRewrite listRewrite = modificationDomain.getListRewrite(); builderRemover.removeExistingBuilderWhenNeeded(modificationDomain); // TODO: eventually have a better design to avoid nulls here List<TypeDeclaration> stageInterfaces = createStageInterfaces(modificationDomain, stagedBuilderStages); TypeDeclaration builderType = stagedBuilderClassCreator.createBuilderClass(modificationDomain, stagedBuilderStages, stageInterfaces); privateConstructorPopulator.addPrivateConstructorToCompilationUnit(ast, originalType, builderType, listRewrite, collectAllFieldsFromAllStages(stagedBuilderStages)); stagedBuilderStaticBuilderCreatorMethodCreator.addBuilderMethodToCompilationUnit(modificationDomain, builderType, stagedBuilderStages); stageInterfaces.stream().forEach(stageInterface -> listRewrite.insertLast(stageInterface, null)); listRewrite.insertLast(builderType, null); importPopulator.populateImports(modificationDomain); }
public void addBuilderMethodToCompilationUnit(CompilationUnitModificationDomain modificationDomain, TypeDeclaration builderType, StagedBuilderProperties currentStage) { AST ast = modificationDomain.getAst(); ListRewrite listRewrite = modificationDomain.getListRewrite(); BuilderField firstField = currentStage.getNamedVariableDeclarationField().get(0); StagedBuilderProperties nextStage = currentStage.getNextStage().orElse(currentStage); MethodDeclaration staticWithMethod = stagedBuilderWithMethodDefiniationCreatorFragment.createNewWithMethod(ast, firstField, nextStage); staticWithMethod.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD)); String parameterName = firstField.getBuilderFieldName(); String withMethodName = staticWithMethod.getName().toString(); Block block = newBuilderAndWithMethodCallCreationFragment.createReturnBlock(ast, builderType, withMethodName, parameterName); javadocAdder.addJavadocForWithBuilderMethod(ast, builderType.getName().toString(), parameterName, staticWithMethod); staticWithMethod.setBody(block); listRewrite.insertLast(staticWithMethod, null); }
protected void handleManyMany(ASTNode[] replacements, TextEditGroup description) { ListRewrite container= fRewrite.getListRewrite(fToReplace[0].getParent(), (ChildListPropertyDescriptor)fDescriptor); if (fToReplace.length == replacements.length) { for (int i= 0; i < fToReplace.length; i++) { container.replace(fToReplace[i], replacements[i], description); } } else if (fToReplace.length < replacements.length) { for (int i= 0; i < fToReplace.length; i++) { container.replace(fToReplace[i], replacements[i], description); } for (int i= fToReplace.length; i < replacements.length; i++) { container.insertAfter(replacements[i], replacements[i - 1], description); } } else if (fToReplace.length > replacements.length) { int delta= fToReplace.length - replacements.length; for(int i= 0; i < delta; i++) { container.remove(fToReplace[i], description); } for (int i= delta, r= 0; i < fToReplace.length; i++, r++) { container.replace(fToReplace[i], replacements[r], description); } } }
@Override protected void handleOneMany(ASTNode[] replacements, TextEditGroup description) { AST ast= fToReplace[0].getAST(); // to replace == 1, but more than one replacement. Have to check if we // need to insert a block to not change structure if (ASTNodes.isControlStatementBody(fDescriptor)) { Block block= ast.newBlock(); ListRewrite statements= fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); for (int i= 0; i < replacements.length; i++) { statements.insertLast(replacements[i], description); } fRewrite.replace(fToReplace[0], block, description); } else { ListRewrite container= fRewrite.getListRewrite(fToReplace[0].getParent(), (ChildListPropertyDescriptor)fDescriptor); container.replace(fToReplace[0], replacements[0], description); for (int i= 1; i < replacements.length; i++) { container.insertAfter(replacements[i], replacements[i - 1], description); } } }
/** * Removes all {@link Annotation} whose only {@link Target} is {@link ElementType#TYPE_USE} from * <code>node</code>'s <code>childListProperty</code>. * <p> * In a combination of {@link ElementType#TYPE_USE} and {@link ElementType#TYPE_PARAMETER} * the latter is ignored, because this is implied by the former and creates no ambiguity.</p> * * @param node ASTNode * @param childListProperty child list property * @param rewrite rewrite that removes the nodes * @param editGroup the edit group in which to collect the corresponding text edits, or null if * ungrouped */ public static void removePureTypeAnnotations(ASTNode node, ChildListPropertyDescriptor childListProperty, ASTRewrite rewrite, TextEditGroup editGroup) { CompilationUnit root= (CompilationUnit) node.getRoot(); if (!JavaModelUtil.is18OrHigher(root.getJavaElement().getJavaProject())) { return; } ListRewrite listRewrite= rewrite.getListRewrite(node, childListProperty); @SuppressWarnings("unchecked") List<? extends ASTNode> children= (List<? extends ASTNode>) node.getStructuralProperty(childListProperty); for (ASTNode child : children) { if (child instanceof Annotation) { Annotation annotation= (Annotation) child; if (isPureTypeAnnotation(annotation)) { listRewrite.remove(child, editGroup); } } } }
/** * Evaluates the insertion position of a new node. * * @param listRewrite The list rewriter to which the new node will be added * @param sibling The Java element before which the new element should be added. * @return the AST node of the list to insert before or null to insert as last. * @throws JavaModelException thrown if accessing the Java element failed */ public static ASTNode getNodeToInsertBefore(ListRewrite listRewrite, IJavaElement sibling) throws JavaModelException { if (sibling instanceof IMember) { ISourceRange sourceRange= ((IMember) sibling).getSourceRange(); if (sourceRange == null) { return null; } int insertPos= sourceRange.getOffset(); List<? extends ASTNode> members= listRewrite.getOriginalList(); for (int i= 0; i < members.size(); i++) { ASTNode curr= members.get(i); if (curr.getStartPosition() >= insertPos) { return curr; } } } return null; }
private void splitUpDeclarations(ASTRewrite rewrite, TextEditGroup group, VariableDeclarationFragment frag, VariableDeclarationStatement originalStatement, List<Expression> sideEffects) { if (sideEffects.size() > 0) { ListRewrite statementRewrite= rewrite.getListRewrite(originalStatement.getParent(), (ChildListPropertyDescriptor) originalStatement.getLocationInParent()); Statement previousStatement= originalStatement; for (int i= 0; i < sideEffects.size(); i++) { Expression sideEffect= sideEffects.get(i); Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect); ExpressionStatement wrapped= rewrite.getAST().newExpressionStatement(movedInit); statementRewrite.insertAfter(wrapped, previousStatement, group); previousStatement= wrapped; } 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, previousStatement, group); if (originalStatement.fragments().size() == newDeclaration.fragments().size() + 1){ rewrite.remove(originalStatement, group); } } } }
@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; }
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; }
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)); } } }
private void setFieldAnnotation(ASTRewrite rewrite, FieldDeclaration fieldDeclaration, String annotation) { SingleMemberAnnotation newFieldAnnotation = fieldDeclaration.getAST().newSingleMemberAnnotation(); newFieldAnnotation.setTypeName(rewrite.getAST().newSimpleName("Domain")); StringLiteral newStringLiteral = rewrite.getAST().newStringLiteral(); newStringLiteral.setLiteralValue(annotation); newFieldAnnotation.setValue(newStringLiteral); ASTNode modifier = getModifier(fieldDeclaration.modifiers()); if (modifier != null) { ListRewrite paramRewrite = rewrite.getListRewrite(fieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY); paramRewrite.insertAfter(newFieldAnnotation, modifier, null); } else { ListRewrite fieldRewrite = rewrite.getListRewrite(fieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY); fieldRewrite.insertFirst(newFieldAnnotation, null); } }
private void setTypeAnnotationDomains(ASTRewrite rewrite, TypeDeclaration typeDeclaration, String annotation, String domainName, ASTNode after) { SingleMemberAnnotation newParamAnnotation = getTypeAnnotationDomain(rewrite, typeDeclaration, annotation, domainName); ListRewrite paramRewrite = rewrite.getListRewrite(typeDeclaration, TypeDeclaration.MODIFIERS2_PROPERTY); if (after == null) { paramRewrite.insertFirst(newParamAnnotation, null); } else { paramRewrite.insertAfter(newParamAnnotation, after, null); } }
private void declareOtherDomains(ASTRewrite rewrite, ListRewrite listRewrite, TypeDeclaration typeDeclaration) { String qualifiedName = typeDeclaration.resolveBinding().getQualifiedName(); OGraphFacade facade = RefinementAnalysis.getFacade(); RefinementModel refinementModel = facade.getRefinementModel(); List<IOtherRefinement> otherRefinements = refinementModel.getOtherRefinements(); for(IOtherRefinement otherRefinement : otherRefinements ) { if (otherRefinement instanceof CreateDomain ) { CreateDomain createDomain = (CreateDomain)otherRefinement; String fullyQualifiedName = createDomain.getSrcIObject().getC().getFullyQualifiedName(); if (fullyQualifiedName.equals(qualifiedName)) { StringLiteral newStringLiteralPARAM = rewrite.getAST().newStringLiteral(); newStringLiteralPARAM.setLiteralValue(createDomain.getDstDomain()); listRewrite.insertLast(newStringLiteralPARAM, null); } } } }
private SingleMemberAnnotation getTypeAnnotationDomainAssumes(ASTRewrite rewrite, TypeDeclaration typeDeclaration, String annotation, String domainName) { ArrayInitializer initializer = rewrite.getAST().newArrayInitializer(); if (domainName != null) { ListRewrite listRewrite = rewrite.getListRewrite(initializer, ArrayInitializer.EXPRESSIONS_PROPERTY); StringLiteral newStringLiteral = rewrite.getAST().newStringLiteral(); newStringLiteral.setLiteralValue(domainName); listRewrite.insertFirst(newStringLiteral, null); declareOtherDomains(rewrite, listRewrite, typeDeclaration); } SingleMemberAnnotation newParamAnnotation = typeDeclaration.getAST().newSingleMemberAnnotation(); newParamAnnotation.setTypeName(rewrite.getAST().newSimpleName(annotation)); newParamAnnotation.setValue(initializer); return newParamAnnotation; }
private SingleMemberAnnotation getTypeAnnotationParams(ASTRewrite rewrite, TypeDeclaration typeDeclaration, String annotation) { ArrayInitializer initializer = rewrite.getAST().newArrayInitializer(); if (!typeDeclaration.resolveBinding().getQualifiedName().equals(Config.MAINCLASS)) { StringLiteral newStringLiteral = rewrite.getAST().newStringLiteral(); newStringLiteral.setLiteralValue("p"); ListRewrite listRewrite = rewrite.getListRewrite(initializer, ArrayInitializer.EXPRESSIONS_PROPERTY); listRewrite.insertFirst(newStringLiteral, null); } SingleMemberAnnotation newParamAnnotation = typeDeclaration.getAST().newSingleMemberAnnotation(); newParamAnnotation.setTypeName(rewrite.getAST().newSimpleName(annotation)); newParamAnnotation.setValue(initializer); return newParamAnnotation; }
protected void handleManyMany(ASTNode[] replacements, TextEditGroup description) { ListRewrite container = fRewrite.getListRewrite( fToReplace[0].getParent(), (ChildListPropertyDescriptor) fDescriptor); if (fToReplace.length == replacements.length) { for (int i = 0; i < fToReplace.length; i++) { container.replace(fToReplace[i], replacements[i], description); } } else if (fToReplace.length < replacements.length) { for (int i = 0; i < fToReplace.length; i++) { container.replace(fToReplace[i], replacements[i], description); } for (int i = fToReplace.length; i < replacements.length; i++) { container.insertAfter(replacements[i], replacements[i - 1], description); } } else if (fToReplace.length > replacements.length) { int delta = fToReplace.length - replacements.length; for (int i = 0; i < delta; i++) { container.remove(fToReplace[i], description); } for (int i = delta, r = 0; i < fToReplace.length; i++, r++) { container.replace(fToReplace[i], replacements[r], description); } } }
@Override protected void handleOneMany(ASTNode[] replacements, TextEditGroup description) { AST ast = fToReplace[0].getAST(); // to replace == 1, but more than one replacement. Have to check if we // need to insert a block to not change structure if (ASTNodes.isControlStatementBody(fDescriptor)) { Block block = ast.newBlock(); ListRewrite statements = fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); for (int i = 0; i < replacements.length; i++) { statements.insertLast(replacements[i], description); } fRewrite.replace(fToReplace[0], block, description); } else { ListRewrite container = fRewrite.getListRewrite( fToReplace[0].getParent(), (ChildListPropertyDescriptor) fDescriptor); container.replace(fToReplace[0], replacements[0], description); for (int i = 1; i < replacements.length; i++) { container.insertAfter(replacements[i], replacements[i - 1], description); } } }
/** * Evaluates the insertion position of a new node. * * @param listRewrite The list rewriter to which the new node will be added * @param sibling The Java element before which the new element should be added. * @return the AST node of the list to insert before or null to insert as last. * @throws JavaModelException thrown if accessing the Java element failed */ public static ASTNode getNodeToInsertBefore(ListRewrite listRewrite, IJavaElement sibling) throws JavaModelException { if (sibling instanceof IMember) { ISourceRange sourceRange = ((IMember) sibling).getSourceRange(); if (sourceRange == null) { return null; } int insertPos = sourceRange.getOffset(); List<? extends ASTNode> members = listRewrite.getOriginalList(); for (int i = 0; i < members.size(); i++) { ASTNode curr = members.get(i); if (curr.getStartPosition() >= insertPos) { return curr; } } } return null; }
/** {@inheritDoc} */ @Override 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); }
boolean checkExisting( List<IExtendedModifier> existingModifiers, ListRewrite listRewrite, TextEditGroup editGroup) { for (Object mod : existingModifiers) { if (mod instanceof MarkerAnnotation) { MarkerAnnotation annotation = (MarkerAnnotation) mod; String existingName = annotation.getTypeName().getFullyQualifiedName(); int lastDot = fAnnotationToRemove.lastIndexOf('.'); if (existingName.equals(fAnnotationToRemove) || (lastDot != -1 && fAnnotationToRemove.substring(lastDot + 1).equals(existingName))) { if (!fAllowRemove) return false; // veto this change listRewrite.remove(annotation, editGroup); return true; } // paranoia: check if by accident the annotation is already present (shouldn't happen): lastDot = fAnnotationToAdd.lastIndexOf('.'); if (existingName.equals(fAnnotationToAdd) || (lastDot != -1 && fAnnotationToAdd.substring(lastDot + 1).equals(existingName))) { return false; // already present } } } return true; }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { AST ast = cuRewrite.getRoot().getAST(); ListRewrite listRewrite = cuRewrite .getASTRewrite() .getListRewrite(fBodyDeclaration, fBodyDeclaration.getModifiersProperty()); TextEditGroup group = createTextEditGroup(fMessage, cuRewrite); if (!checkExisting(fBodyDeclaration.modifiers(), listRewrite, group)) return; if (hasNonNullDefault(fBodyDeclaration.resolveBinding())) return; // should be safe, as in this case checkExisting() should've already produced a // change (remove existing // annotation). Annotation newAnnotation = ast.newMarkerAnnotation(); ImportRewrite importRewrite = cuRewrite.getImportRewrite(); String resolvableName = importRewrite.addImport(fAnnotationToAdd); newAnnotation.setTypeName(ast.newName(resolvableName)); listRewrite.insertLast( newAnnotation, group); // null annotation is last modifier, directly preceding the return type }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedModel) throws CoreException { AST ast = cuRewrite.getRoot().getAST(); ListRewrite listRewrite = cuRewrite .getASTRewrite() .getListRewrite(fArgument, SingleVariableDeclaration.MODIFIERS2_PROPERTY); TextEditGroup group = createTextEditGroup(fMessage, cuRewrite); if (!checkExisting(fArgument.modifiers(), listRewrite, group)) return; Annotation newAnnotation = ast.newMarkerAnnotation(); ImportRewrite importRewrite = cuRewrite.getImportRewrite(); String resolvableName = importRewrite.addImport(fAnnotationToAdd); newAnnotation.setTypeName(ast.newName(resolvableName)); listRewrite.insertLast( newAnnotation, group); // null annotation is last modifier, directly preceding the type }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { TextEditGroup group = createTextEditGroup( FixMessages.TypeParametersFix_remove_redundant_type_arguments_description, cuRewrite); ASTRewrite rewrite = cuRewrite.getASTRewrite(); rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer()); ListRewrite listRewrite = rewrite.getListRewrite(fParameterizedType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY); List<Type> typeArguments = fParameterizedType.typeArguments(); for (Iterator<Type> iterator = typeArguments.iterator(); iterator.hasNext(); ) { listRewrite.remove(iterator.next(), group); } }
private void addExceptionToNodeList( ExceptionInfo exceptionInfo, ListRewrite exceptionListRewrite) { String fullyQualified = exceptionInfo.getFullyQualifiedName(); for (Iterator<? extends ASTNode> iter = exceptionListRewrite.getOriginalList().iterator(); iter.hasNext(); ) { Type exType = (Type) iter.next(); // XXX: existing superclasses of the added exception are redundant and could be removed ITypeBinding typeBinding = exType.resolveBinding(); if (typeBinding == null) continue; // newly added or unresolvable type if (typeBinding.getQualifiedName().equals(fullyQualified)) return; // don't add it again } String importedType = getImportRewrite().addImport(exceptionInfo.getFullyQualifiedName()); getImportRemover().registerAddedImport(importedType); ASTNode exNode = getASTRewrite().createStringPlaceholder(importedType, ASTNode.SIMPLE_TYPE); exceptionListRewrite.insertLast(exNode, fDescription); }
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); } } }
private void copyImportToDestination( IImportDeclaration declaration, ASTRewrite targetRewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException { ImportDeclaration sourceNode = ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode); ImportDeclaration copiedNode = (ImportDeclaration) ASTNode.copySubtree(targetRewrite.getAST(), sourceNode); ListRewrite listRewrite = targetRewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY); if (getJavaElementDestination() instanceof IImportDeclaration) { ImportDeclaration destinationNode = ASTNodeSearchUtil.getImportDeclarationNode( (IImportDeclaration) getJavaElementDestination(), destinationCuNode); insertRelative(copiedNode, destinationNode, listRewrite); } else { // dropped on container, we could be better here listRewrite.insertLast(copiedNode, null); } }
/** * Adds a "param" javadoc tag for a new last parameter if necessary. * * @param parameterName * @param methodDeclaration * @param astRewrite * @param javaProject * @param groupDescription */ public static void addParamJavadoc( String parameterName, MethodDeclaration methodDeclaration, ASTRewrite astRewrite, IJavaProject javaProject, TextEditGroup groupDescription) { if (!shouldAddParamJavadoc(methodDeclaration)) return; ListRewrite tagsRewrite = astRewrite.getListRewrite(methodDeclaration.getJavadoc(), Javadoc.TAGS_PROPERTY); HashSet<String> leadingNames = new HashSet<String>(); for (Iterator<SingleVariableDeclaration> iter = methodDeclaration.parameters().iterator(); iter.hasNext(); ) { SingleVariableDeclaration curr = iter.next(); leadingNames.add(curr.getName().getIdentifier()); } TagElement parameterTag = createParamTag(parameterName, astRewrite.getAST(), javaProject); JavadocTagsSubProcessor.insertTag(tagsRewrite, parameterTag, leadingNames, groupDescription); }
private static void createMissingDefaultProposal( IInvocationContext context, SwitchStatement switchStatement, Image image, Collection<ICommandAccess> proposals) { AST ast = switchStatement.getAST(); ASTRewrite astRewrite = ASTRewrite.create(ast); ListRewrite listRewrite = astRewrite.getListRewrite(switchStatement, SwitchStatement.STATEMENTS_PROPERTY); SwitchCase newSwitchCase = ast.newSwitchCase(); newSwitchCase.setExpression(null); listRewrite.insertLast(newSwitchCase, null); listRewrite.insertLast(ast.newBreakStatement(), null); String label = CorrectionMessages.LocalCorrectionsSubProcessor_add_default_case_description; proposals.add( new ASTRewriteCorrectionProposal( label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_MISSING_DEFAULT_CASE, image)); }
private static boolean addSuppressArgument( ASTRewrite rewrite, Expression value, StringLiteral newStringLiteral) { if (value instanceof ArrayInitializer) { ListRewrite listRewrite = rewrite.getListRewrite(value, ArrayInitializer.EXPRESSIONS_PROPERTY); listRewrite.insertLast(newStringLiteral, null); } else if (value instanceof StringLiteral) { ArrayInitializer newArr = rewrite.getAST().newArrayInitializer(); newArr.expressions().add(rewrite.createMoveTarget(value)); newArr.expressions().add(newStringLiteral); rewrite.replace(value, newArr, null); } else { return false; } return true; }
@Override protected ASTRewrite getRewrite() throws CoreException { if (fMethodDeclaration == null) { CompilationUnit astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null); fMethodDeclaration = (MethodDeclaration) astRoot.findDeclaringNode(fMethodBinding.getKey()); } AST ast = fMethodDeclaration.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); ListRewrite listRewrite = rewrite.getListRewrite(fMethodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY); MarkerAnnotation annotation = ast.newMarkerAnnotation(); String importString = createImportRewrite((CompilationUnit) fMethodDeclaration.getRoot()) .addImport("java.lang.SafeVarargs"); // $NON-NLS-1$ annotation.setTypeName(ast.newName(importString)); listRewrite.insertFirst(annotation, null); // set up linked mode addLinkedPosition(rewrite.track(annotation), true, "annotation"); // $NON-NLS-1$ return rewrite; }
public static ASTNode getCopyOfInner( ASTRewrite rewrite, ASTNode statement, boolean toControlStatementBody) { if (statement.getNodeType() == ASTNode.BLOCK) { Block block = (Block) statement; List<Statement> innerStatements = block.statements(); int nStatements = innerStatements.size(); if (nStatements == 1) { return rewrite.createCopyTarget(innerStatements.get(0)); } else if (nStatements > 1) { if (toControlStatementBody) { return rewrite.createCopyTarget(block); } ListRewrite listRewrite = rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); ASTNode first = innerStatements.get(0); ASTNode last = innerStatements.get(nStatements - 1); return listRewrite.createCopyTarget(first, last); } return null; } else { return rewrite.createCopyTarget(statement); } }
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)); } } }