Java Code Examples for org.eclipse.jdt.core.dom.rewrite.ListRewrite#insertFirst()
The following examples show how to use
org.eclipse.jdt.core.dom.rewrite.ListRewrite#insertFirst() .
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: ReorgPolicyFactory.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.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 2
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 3
Source File: CreateSuperCallResolution.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
@Override protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException { Assert.isNotNull(rewrite); Assert.isNotNull(workingUnit); Assert.isNotNull(bug); TypeDeclaration type = getTypeDeclaration(workingUnit, bug.getPrimaryClass()); MethodDeclaration method = getMethodDeclaration(type, bug.getPrimaryMethod()); AST ast = rewrite.getAST(); SuperMethodInvocation superCall = createSuperMethodInvocation(rewrite, method); ExpressionStatement statement = ast.newExpressionStatement(superCall); Block methodBody = method.getBody(); ListRewrite listRewrite = rewrite.getListRewrite(methodBody, Block.STATEMENTS_PROPERTY); if (isInsertFirst()) { listRewrite.insertFirst(statement, null); } else { listRewrite.insertLast(statement, null); } }
Example 4
Source File: ExtractClassRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private List<ResourceChange> createParameterObject(ParameterObjectFactory pof, IPackageFragmentRoot packageRoot) throws CoreException { FieldUpdate fieldUpdate= new FieldUpdate(); if (fDescriptor.isCreateTopLevel()) return pof.createTopLevelParameterObject(packageRoot, fieldUpdate); else { CompilationUnit root= fBaseCURewrite.getRoot(); TypeDeclaration typeDecl= ASTNodeSearchUtil.getTypeDeclarationNode(fDescriptor.getType(), root); ASTRewrite rewrite= fBaseCURewrite.getASTRewrite(); ListRewrite listRewrite= rewrite.getListRewrite(typeDecl, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); TypeDeclaration paramClass= pof.createClassDeclaration(typeDecl.getName().getFullyQualifiedName(), fBaseCURewrite, fieldUpdate); paramClass.modifiers().add(rewrite.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD)); if (shouldParamClassBeStatic(typeDecl)) { paramClass.modifiers().add(rewrite.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD)); } listRewrite.insertFirst(paramClass, fBaseCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_insert_parameter)); return new ArrayList<ResourceChange>(); //Change will be generated later for fBaseCURewrite } }
Example 5
Source File: JavadocTagsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
public static void insertTag(ListRewrite rewriter, TagElement newElement, Set<String> sameKindLeadingNames, TextEditGroup groupDescription) { List<? extends ASTNode> tags= rewriter.getRewrittenList(); String insertedTagName= newElement.getTagName(); ASTNode after= null; int tagRanking= getTagRanking(insertedTagName); for (int i= tags.size() - 1; i >= 0; i--) { TagElement curr= (TagElement) tags.get(i); String tagName= curr.getTagName(); if (tagName == null || tagRanking > getTagRanking(tagName)) { after= curr; break; } if (sameKindLeadingNames != null && isSameTag(insertedTagName, tagName)) { String arg= getArgument(curr); if (arg != null && sameKindLeadingNames.contains(arg)) { after= curr; break; } } } if (after != null) { rewriter.insertAfter(newElement, after, groupDescription); } else { rewriter.insertFirst(newElement, groupDescription); } }
Example 6
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 7
Source File: Java50Fix.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 { 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); }
Example 8
Source File: ExtractTempRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void insertAt(ASTNode target, Statement declaration) { ASTRewrite rewrite= fCURewrite.getASTRewrite(); TextEditGroup groupDescription= fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable); ASTNode parent= target.getParent(); StructuralPropertyDescriptor locationInParent= target.getLocationInParent(); while (locationInParent != Block.STATEMENTS_PROPERTY && locationInParent != SwitchStatement.STATEMENTS_PROPERTY) { if (locationInParent == IfStatement.THEN_STATEMENT_PROPERTY || locationInParent == IfStatement.ELSE_STATEMENT_PROPERTY || locationInParent == ForStatement.BODY_PROPERTY || locationInParent == EnhancedForStatement.BODY_PROPERTY || locationInParent == DoStatement.BODY_PROPERTY || locationInParent == WhileStatement.BODY_PROPERTY) { // create intermediate block if target was the body property of a control statement: Block replacement= rewrite.getAST().newBlock(); ListRewrite replacementRewrite= rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY); replacementRewrite.insertFirst(declaration, null); replacementRewrite.insertLast(rewrite.createMoveTarget(target), null); rewrite.replace(target, replacement, groupDescription); return; } target= parent; parent= parent.getParent(); locationInParent= target.getLocationInParent(); } ListRewrite listRewrite= rewrite.getListRewrite(parent, (ChildListPropertyDescriptor)locationInParent); listRewrite.insertBefore(declaration, target, groupDescription); }
Example 9
Source File: IntroduceParameterObjectProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
@Override public void updateBody(MethodDeclaration methodDeclaration, final CompilationUnitRewrite cuRewrite, RefactoringStatus result) throws CoreException { // ensure that the parameterObject is imported fParameterObjectFactory.createType(fCreateAsTopLevel, cuRewrite, methodDeclaration.getStartPosition()); if (cuRewrite.getCu().equals(getCompilationUnit()) && !fParameterClassCreated) { createParameterClass(methodDeclaration, cuRewrite); fParameterClassCreated= true; } Block body= methodDeclaration.getBody(); final List<SingleVariableDeclaration> parameters= methodDeclaration.parameters(); if (body != null) { // abstract methods don't have bodies final ASTRewrite rewriter= cuRewrite.getASTRewrite(); ListRewrite bodyStatements= rewriter.getListRewrite(body, Block.STATEMENTS_PROPERTY); List<ParameterInfo> managedParams= getParameterInfos(); for (Iterator<ParameterInfo> iter= managedParams.iterator(); iter.hasNext();) { final ParameterInfo pi= iter.next(); if (isValidField(pi)) { if (isReadOnly(pi, body, parameters, null)) { body.accept(new ASTVisitor(false) { @Override public boolean visit(SimpleName node) { updateSimpleName(rewriter, pi, node, parameters, cuRewrite.getCu().getJavaProject()); return false; } }); pi.setInlined(true); } else { ExpressionStatement initializer= fParameterObjectFactory.createInitializer(pi, getParameterName(), cuRewrite); bodyStatements.insertFirst(initializer, null); } } } } }
Example 10
Source File: MoveMethodRefactoring.java From JDeodorant with MIT License | 5 votes |
private void setPublicModifierToSourceMethod(IMethodBinding methodBinding, TypeDeclaration sourceTypeDeclaration) { MethodDeclaration[] methodDeclarations = sourceTypeDeclaration.getMethods(); for(MethodDeclaration methodDeclaration : methodDeclarations) { if(methodDeclaration.resolveBinding().isEqualTo(methodBinding)) { CompilationUnit sourceCompilationUnit = RefactoringUtility.findCompilationUnit(methodDeclaration); ASTRewrite sourceRewriter = ASTRewrite.create(sourceCompilationUnit.getAST()); ListRewrite modifierRewrite = sourceRewriter.getListRewrite(methodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY); Modifier publicModifier = methodDeclaration.getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD); boolean modifierFound = false; List<IExtendedModifier> modifiers = methodDeclaration.modifiers(); for(IExtendedModifier extendedModifier : modifiers) { if(extendedModifier.isModifier()) { Modifier modifier = (Modifier)extendedModifier; if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PUBLIC_KEYWORD)) { modifierFound = true; } else if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PRIVATE_KEYWORD)) { modifierFound = true; modifierRewrite.replace(modifier, publicModifier, null); updateAccessModifier(sourceRewriter, sourceCompilationUnit); } else if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PROTECTED_KEYWORD)) { modifierFound = true; IPackageBinding targetTypeDeclarationPackageBinding = this.targetTypeDeclaration.resolveBinding().getPackage(); IPackageBinding typeDeclarationPackageBinding = sourceTypeDeclaration.resolveBinding().getPackage(); if(targetTypeDeclarationPackageBinding != null && typeDeclarationPackageBinding != null && !targetTypeDeclarationPackageBinding.isEqualTo(typeDeclarationPackageBinding)) { modifierRewrite.replace(modifier, publicModifier, null); updateAccessModifier(sourceRewriter, sourceCompilationUnit); } } } } if(!modifierFound) { modifierRewrite.insertFirst(publicModifier, null); updateAccessModifier(sourceRewriter, sourceCompilationUnit); } } } }
Example 11
Source File: ExtractClassRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
@Override public void fieldCreated(CompilationUnitRewrite cuRewrite, FieldDeclaration field, ParameterInfo pi) { FieldInfo fieldInfo= getFieldInfo(pi.getOldName()); FieldDeclaration parent= (FieldDeclaration) fieldInfo.declaration.getParent(); List<IExtendedModifier> modifiers= parent.modifiers(); ListRewrite listRewrite= cuRewrite.getASTRewrite().getListRewrite(field, FieldDeclaration.MODIFIERS2_PROPERTY); for (Iterator<IExtendedModifier> iterator= modifiers.iterator(); iterator.hasNext();) { IExtendedModifier mod= iterator.next(); //Temporarily disabled until initialization of final fields is handled correctly // if (mod.isModifier()) { // Modifier modifier= (Modifier) mod; // if (modifier.isFinal()) // listRewrite.insertLast(moveNode(cuRewrite, modifier), null); // } if (mod.isAnnotation()) { listRewrite.insertFirst(moveNode(cuRewrite, (ASTNode) mod), null); } } if (fieldInfo.initializer != null && fieldInfo.hasFieldReference()) { List<VariableDeclarationFragment> fragments= field.fragments(); for (Iterator<VariableDeclarationFragment> iterator= fragments.iterator(); iterator.hasNext();) { VariableDeclarationFragment vdf= iterator.next(); vdf.setInitializer((Expression) moveNode(cuRewrite, fieldInfo.initializer)); } } if (parent.getJavadoc() != null) { field.setJavadoc((Javadoc) moveNode(cuRewrite, parent.getJavadoc())); } }
Example 12
Source File: ClientBundleResource.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
public MethodDeclaration createMethodDeclaration(IType clientBundle, ASTRewrite astRewrite, ImportRewrite importRewrite, boolean addComments) throws CoreException { AST ast = astRewrite.getAST(); MethodDeclaration methodDecl = ast.newMethodDeclaration(); // Method is named after the resource it accesses methodDecl.setName(ast.newSimpleName(getMethodName())); // Method return type is a ResourcePrototype subtype ITypeBinding resourceTypeBinding = JavaASTUtils.resolveType(clientBundle.getJavaProject(), getReturnTypeName()); Type resourceType = importRewrite.addImport(resourceTypeBinding, ast); methodDecl.setReturnType2(resourceType); // Add @Source annotation if necessary String sourceAnnotationValue = getSourceAnnotationValue(clientBundle); if (sourceAnnotationValue != null) { // Build the annotation SingleMemberAnnotation sourceAnnotation = ast.newSingleMemberAnnotation(); sourceAnnotation.setTypeName(ast.newName("Source")); StringLiteral annotationValue = ast.newStringLiteral(); annotationValue.setLiteralValue(sourceAnnotationValue); sourceAnnotation.setValue(annotationValue); // Add the annotation to the method ChildListPropertyDescriptor modifiers = methodDecl.getModifiersProperty(); ListRewrite modifiersRewriter = astRewrite.getListRewrite(methodDecl, modifiers); modifiersRewriter.insertFirst(sourceAnnotation, null); } return methodDecl; }
Example 13
Source File: JavadocTagsSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public static void insertTag(ListRewrite rewriter, TagElement newElement, Set<String> sameKindLeadingNames, TextEditGroup groupDescription) { List<? extends ASTNode> tags= rewriter.getRewrittenList(); String insertedTagName= newElement.getTagName(); ASTNode after= null; int tagRanking= getTagRanking(insertedTagName); for (int i= tags.size() - 1; i >= 0; i--) { TagElement curr= (TagElement) tags.get(i); String tagName= curr.getTagName(); if (tagName == null || tagRanking > getTagRanking(tagName)) { after= curr; break; } if (sameKindLeadingNames != null && isSameTag(insertedTagName, tagName)) { String arg= getArgument(curr); if (arg != null && sameKindLeadingNames.contains(arg)) { after= curr; break; } } } if (after != null) { rewriter.insertAfter(newElement, after, groupDescription); } else { rewriter.insertFirst(newElement, groupDescription); } }
Example 14
Source File: CopyrightManager.java From hybris-commerce-eclipse-plugin with Apache License 2.0 | 5 votes |
/** * Adds copyright header to the compilation unit * * @param compilationUnit * compilation unit affected * @return compilation unit change */ public CompilationUnitChange addCopyrightsHeader(final CompilationUnit compilationUnit) { final ICompilationUnit unit = (ICompilationUnit) compilationUnit.getJavaElement(); change = new CompilationUnitChange(ADD_COPYRIGHT, unit); rewriter = ASTRewrite.create(compilationUnit.getAST()); final ListRewrite listRewrite = rewriter.getListRewrite(compilationUnit.getPackage(), PackageDeclaration.ANNOTATIONS_PROPERTY); final Comment placeHolder = (Comment) rewriter.createStringPlaceholder(getCopyrightText() + NEW_LINE_SEPARATOR, ASTNode.BLOCK_COMMENT); listRewrite.insertFirst(placeHolder, null); rewriteCompilationUnit(unit, getNewUnitSource(unit, null)); return change; }
Example 15
Source File: ConstructorInsertionFragment.java From SparkBuilderGenerator with MIT License | 5 votes |
public void insertMethodToFirstPlace(TypeDeclaration originalType, ListRewrite listRewrite, MethodDeclaration constructor) { FieldDeclaration[] fields = originalType.getFields(); if (fields == null || fields.length == 0) { listRewrite.insertFirst(constructor, null); } else { listRewrite.insertAfter(constructor, fields[fields.length - 1], null); } }
Example 16
Source File: ChangeSignatureProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private void insertTag(TagElement tag, TagElement previousTag, ListRewrite tagsRewrite) { if (previousTag == null) tagsRewrite.insertFirst(tag, fDescription); else tagsRewrite.insertAfter(tag, previousTag, fDescription); }
Example 17
Source File: ExtractConstantRefactoring.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
private void createConstantDeclaration() throws CoreException { Type type = getConstantType(); IExpressionFragment fragment = getSelectedExpression(); Expression initializer = getSelectedExpression().createCopyTarget(fCuRewrite.getASTRewrite(), true); AST ast = fCuRewrite.getAST(); VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment(); variableDeclarationFragment.setName(ast.newSimpleName(fConstantName)); variableDeclarationFragment.setInitializer(initializer); FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(variableDeclarationFragment); fieldDeclaration.setType(type); Modifier.ModifierKeyword accessModifier = Modifier.ModifierKeyword.toKeyword(fVisibility); if (accessModifier != null) { fieldDeclaration.modifiers().add(ast.newModifier(accessModifier)); } fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD)); // boolean createComments = JavaPreferencesSettings.getCodeGenerationSettings(fCu.getJavaProject()).createComments; // if (createComments) { String comment = CodeGeneration.getFieldComment(fCu, getConstantTypeName(), fConstantName, StubUtility.getLineDelimiterUsed(fCu)); if (comment != null && comment.length() > 0 && !"/**\n *\n */".equals(comment)) { Javadoc doc = (Javadoc) fCuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC); fieldDeclaration.setJavadoc(doc); } // } AbstractTypeDeclaration parent = getContainingTypeDeclarationNode(); ListRewrite listRewrite = fCuRewrite.getASTRewrite().getListRewrite(parent, parent.getBodyDeclarationsProperty()); TextEditGroup msg = fCuRewrite.createGroupDescription(RefactoringCoreMessages.ExtractConstantRefactoring_declare_constant); if (insertFirst()) { listRewrite.insertFirst(fieldDeclaration, msg); } else { listRewrite.insertAfter(fieldDeclaration, getNodeToInsertConstantDeclarationAfter(), msg); } if (fLinkedProposalModel != null) { ASTRewrite rewrite = fCuRewrite.getASTRewrite(); LinkedProposalPositionGroupCore nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true); nameGroup.addPosition(rewrite.track(variableDeclarationFragment.getName()), true); String[] nameSuggestions = guessConstantNames(); if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fConstantName)) { nameGroup.addProposal(fConstantName, nameSuggestions.length + 1); } for (int i = 0; i < nameSuggestions.length; i++) { nameGroup.addProposal(nameSuggestions[i], nameSuggestions.length - i); } LinkedProposalPositionGroupCore typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true); typeGroup.addPosition(rewrite.track(type), true); ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression()); if (typeBinding != null) { ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(ast, typeBinding); for (int i = 0; i < relaxingTypes.length; i++) { typeGroup.addProposal(relaxingTypes[i], fCuRewrite.getCu(), relaxingTypes.length - i); } } boolean isInterface = parent.resolveBinding() != null && parent.resolveBinding().isInterface(); ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, rewrite, fieldDeclaration.modifiers(), isInterface); } }
Example 18
Source File: ExtractConstantRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private void createConstantDeclaration() throws CoreException { Type type= getConstantType(); IExpressionFragment fragment= getSelectedExpression(); Expression initializer= getSelectedExpression().createCopyTarget(fCuRewrite.getASTRewrite(), true); AST ast= fCuRewrite.getAST(); VariableDeclarationFragment variableDeclarationFragment= ast.newVariableDeclarationFragment(); variableDeclarationFragment.setName(ast.newSimpleName(fConstantName)); variableDeclarationFragment.setInitializer(initializer); FieldDeclaration fieldDeclaration= ast.newFieldDeclaration(variableDeclarationFragment); fieldDeclaration.setType(type); Modifier.ModifierKeyword accessModifier= Modifier.ModifierKeyword.toKeyword(fVisibility); if (accessModifier != null) fieldDeclaration.modifiers().add(ast.newModifier(accessModifier)); fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD)); boolean createComments= JavaPreferencesSettings.getCodeGenerationSettings(fCu.getJavaProject()).createComments; if (createComments) { String comment= CodeGeneration.getFieldComment(fCu, getConstantTypeName(), fConstantName, StubUtility.getLineDelimiterUsed(fCu)); if (comment != null && comment.length() > 0) { Javadoc doc= (Javadoc) fCuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC); fieldDeclaration.setJavadoc(doc); } } AbstractTypeDeclaration parent= getContainingTypeDeclarationNode(); ListRewrite listRewrite= fCuRewrite.getASTRewrite().getListRewrite(parent, parent.getBodyDeclarationsProperty()); TextEditGroup msg= fCuRewrite.createGroupDescription(RefactoringCoreMessages.ExtractConstantRefactoring_declare_constant); if (insertFirst()) { listRewrite.insertFirst(fieldDeclaration, msg); } else { listRewrite.insertAfter(fieldDeclaration, getNodeToInsertConstantDeclarationAfter(), msg); } if (fLinkedProposalModel != null) { ASTRewrite rewrite= fCuRewrite.getASTRewrite(); LinkedProposalPositionGroup nameGroup= fLinkedProposalModel.getPositionGroup(KEY_NAME, true); nameGroup.addPosition(rewrite.track(variableDeclarationFragment.getName()), true); String[] nameSuggestions= guessConstantNames(); if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fConstantName)) { nameGroup.addProposal(fConstantName, null, nameSuggestions.length + 1); } for (int i= 0; i < nameSuggestions.length; i++) { nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i); } LinkedProposalPositionGroup typeGroup= fLinkedProposalModel.getPositionGroup(KEY_TYPE, true); typeGroup.addPosition(rewrite.track(type), true); ITypeBinding typeBinding= guessBindingForReference(fragment.getAssociatedExpression()); if (typeBinding != null) { ITypeBinding[] relaxingTypes= ASTResolving.getNarrowingTypes(ast, typeBinding); for (int i= 0; i < relaxingTypes.length; i++) { typeGroup.addProposal(relaxingTypes[i], fCuRewrite.getCu(), relaxingTypes.length - i); } } boolean isInterface= parent.resolveBinding() != null && parent.resolveBinding().isInterface(); ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, rewrite, fieldDeclaration.modifiers(), isInterface); } }
Example 19
Source File: OverrideCompletionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite, boolean snippetStringSupport) throws CoreException, BadLocationException { Document recoveredDocument= new Document(); CompilationUnit unit= getRecoveredAST(document, offset, recoveredDocument); ImportRewriteContext context = new ContextSensitiveImportRewriteContext(unit, offset, importRewrite); ITypeBinding declaringType= null; ChildListPropertyDescriptor descriptor= null; ASTNode node= NodeFinder.perform(unit, offset, 1); node= ASTResolving.findParentType(node); String result = null; if (node instanceof AnonymousClassDeclaration) { declaringType= ((AnonymousClassDeclaration) node).resolveBinding(); descriptor= AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY; } else if (node instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) node; descriptor= declaration.getBodyDeclarationsProperty(); declaringType= declaration.resolveBinding(); } if (declaringType != null) { ASTRewrite rewrite= ASTRewrite.create(unit.getAST()); IMethodBinding methodToOverride= Bindings.findMethodInHierarchy(declaringType, fMethodName, fParamTypes); if (methodToOverride == null && declaringType.isInterface()) { methodToOverride= Bindings.findMethodInType(node.getAST().resolveWellKnownType("java.lang.Object"), fMethodName, fParamTypes); //$NON-NLS-1$ } if (methodToOverride != null) { CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(fJavaProject.getProject()); MethodDeclaration stub = StubUtility2Core.createImplementationStubCore(fCompilationUnit, rewrite, importRewrite, context, methodToOverride, declaringType, settings, declaringType.isInterface(), node, snippetStringSupport); ListRewrite rewriter= rewrite.getListRewrite(node, descriptor); rewriter.insertFirst(stub, null); ITrackedNodePosition position= rewrite.track(stub); try { Map<String, String> options = fJavaProject.getOptions(true); rewrite.rewriteAST(recoveredDocument, options).apply(recoveredDocument); String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength()); String indentAt = getIndentAt(recoveredDocument, position.getStartPosition(), settings); int generatedIndent = IndentManipulation.measureIndentUnits(indentAt, settings.tabWidth, settings.indentWidth); // Kinda fishy but empirical data shows Override needs to change indent by at // least 1 generatedIndent = Math.max(1, generatedIndent); // Cancel generated code indent String delimiter = TextUtilities.getDefaultLineDelimiter(document); result = IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth, settings.indentWidth, "", delimiter); } catch (MalformedTreeException | BadLocationException exception) { JavaLanguageServerPlugin.logException("Unable to compute override proposal", exception); } } } return result; }
Example 20
Source File: GenerateHashCodeEqualsOperation.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private void addHelper(ListRewrite rewriter, ASTNode insertion, MethodDeclaration stub) { if (insertion != null) rewriter.insertBefore(stub, insertion, null); else rewriter.insertFirst(stub, null); }