org.eclipse.jdt.core.dom.AST Java Examples
The following examples show how to use
org.eclipse.jdt.core.dom.AST.
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: ReturnTypeSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
public ITypeBinding getTypeBinding(AST ast) { boolean couldBeObject= false; for (int i= 0; i < fResult.size(); i++) { ReturnStatement node= fResult.get(i); Expression expr= node.getExpression(); if (expr != null) { ITypeBinding binding= Bindings.normalizeTypeBinding(expr.resolveTypeBinding()); if (binding != null) { return binding; } else { couldBeObject= true; } } else { return ast.resolveWellKnownType("void"); //$NON-NLS-1$ } } if (couldBeObject) { return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } return ast.resolveWellKnownType("void"); //$NON-NLS-1$ }
Example #2
Source File: RegularBuilderCompilationUnitGenerator.java From SparkBuilderGenerator with MIT License | 6 votes |
public void generateBuilder(CompilationUnitModificationDomain compilationUnitModificationDomain, RegularBuilderUserPreference preference) { // TODO: replace parameters, where these go separately with compilation modification domain AST ast = compilationUnitModificationDomain.getAst(); ListRewrite listRewrite = compilationUnitModificationDomain.getListRewrite(); TypeDeclaration originalType = compilationUnitModificationDomain.getOriginalType(); builderRemover.removeExistingBuilderWhenNeeded(compilationUnitModificationDomain); TypeDeclaration builderType = regularBuilderClassCreator.createBuilderClass(ast, originalType, preference); defaultConstructorAppender.addDefaultConstructorIfNeeded(compilationUnitModificationDomain, preference.getBuilderFields()); privateConstructorPopulator.addPrivateConstructorToCompilationUnit(ast, originalType, builderType, listRewrite, preference.getBuilderFields()); builderMethodPopulator.addBuilderMethodToCompilationUnit(ast, listRewrite, originalType, builderType, preference); instanceCopyBuilderMethodPopulator.addInstanceCopyBuilderMethodToCompilationUnitIfNeeded(compilationUnitModificationDomain, builderType, preference); listRewrite.insertLast(builderType, null); globalBuilderPostProcessor.postProcessBuilder(compilationUnitModificationDomain, builderType); importPopulator.populateImports(compilationUnitModificationDomain); }
Example #3
Source File: ReplaceTypeCodeWithStateStrategy.java From JDeodorant with MIT License | 6 votes |
private void createStateField() { ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST()); AST contextAST = sourceTypeDeclaration.getAST(); ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST); FieldDeclaration typeFieldDeclaration = contextAST.newFieldDeclaration(typeFragment); sourceRewriter.set(typeFieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null); ListRewrite typeFieldDeclarationModifiersRewrite = sourceRewriter.getListRewrite(typeFieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY); typeFieldDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD), null); contextBodyRewrite.insertBefore(typeFieldDeclaration, typeCheckElimination.getTypeField().getParent(), null); try { TextEdit sourceEdit = sourceRewriter.rewriteAST(); ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceEdit); change.addTextEditGroup(new TextEditGroup("Create field holding the current state", new TextEdit[] {sourceEdit})); } catch (JavaModelException e) { e.printStackTrace(); } }
Example #4
Source File: DimensionRewrite.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
/** * Creates a {@link ASTRewrite#createCopyTarget(ASTNode) copy} of <code>type</code> * and adds <code>extraDimensions</code> to it. * * @param type the type to copy * @param extraDimensions the dimensions to add * @param rewrite the ASTRewrite with which to create new nodes * @return the copy target with added dimensions */ public static Type copyTypeAndAddDimensions(Type type, List<Dimension> extraDimensions, ASTRewrite rewrite) { AST ast= rewrite.getAST(); if (extraDimensions.isEmpty()) { return (Type) rewrite.createCopyTarget(type); } ArrayType result; if (type instanceof ArrayType) { ArrayType arrayType= (ArrayType) type; Type varElementType= (Type) rewrite.createCopyTarget(arrayType.getElementType()); result= ast.newArrayType(varElementType, 0); result.dimensions().addAll(copyDimensions(extraDimensions, rewrite)); result.dimensions().addAll(copyDimensions(arrayType.dimensions(), rewrite)); } else { Type elementType= (Type) rewrite.createCopyTarget(type); result= ast.newArrayType(elementType, 0); result.dimensions().addAll(copyDimensions(extraDimensions, rewrite)); } return result; }
Example #5
Source File: NewAnnotationMemberProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private SimpleName getNewName(ASTRewrite rewrite) { AST ast= rewrite.getAST(); String name; if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) { name= ((SimpleName) fInvocationNode).getIdentifier(); if (ast == fInvocationNode.getAST()) { addLinkedPosition(rewrite.track(fInvocationNode), true, KEY_NAME); } } else { name= "value"; //$NON-NLS-1$ } SimpleName newNameNode= ast.newSimpleName(name); addLinkedPosition(rewrite.track(newNameNode), false, KEY_NAME); return newNameNode; }
Example #6
Source File: CreateDoPrivilegedBlockResolution.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
protected void updateImportDeclarations(ASTRewrite rewrite, CompilationUnit compilationUnit) { Assert.isNotNull(rewrite); Assert.isNotNull(compilationUnit); if (isUpdateImports()) { final AST ast = rewrite.getAST(); SortedSet<ImportDeclaration> imports = new TreeSet<>(importComparator); imports.add(createImportDeclaration(ast, PrivilegedAction.class)); if (!isStaticImport()) { imports.add(createImportDeclaration(ast, AccessController.class)); } else { imports.add(createImportDeclaration(ast, AccessController.class, DO_PRIVILEGED_METHOD_NAME)); } addImports(rewrite, compilationUnit, imports); } }
Example #7
Source File: PromoteTempToFieldRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void addInitializersToConstructors(ASTRewrite rewrite) throws CoreException { Assert.isTrue(! isDeclaredInAnonymousClass()); final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration)getMethodDeclaration().getParent(); final MethodDeclaration[] constructors= getAllConstructors(declaration); if (constructors.length == 0) { AST ast= rewrite.getAST(); MethodDeclaration newConstructor= ast.newMethodDeclaration(); newConstructor.setConstructor(true); newConstructor.modifiers().addAll(ast.newModifiers(declaration.getModifiers() & ModifierRewrite.VISIBILITY_MODIFIERS)); newConstructor.setName(ast.newSimpleName(declaration.getName().getIdentifier())); newConstructor.setJavadoc(getNewConstructorComment(rewrite)); newConstructor.setBody(ast.newBlock()); addFieldInitializationToConstructor(rewrite, newConstructor); int insertionIndex= computeInsertIndexForNewConstructor(declaration); rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newConstructor, insertionIndex, null); } else { for (int index= 0; index < constructors.length; index++) { if (shouldInsertTempInitialization(constructors[index])) addFieldInitializationToConstructor(rewrite, constructors[index]); } } }
Example #8
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 #9
Source File: TypeParametersFix.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { TextEditGroup group= createTextEditGroup(FixMessages.TypeParametersFix_insert_inferred_type_arguments_description, cuRewrite); ASTRewrite rewrite= cuRewrite.getASTRewrite(); ImportRewrite importRewrite= cuRewrite.getImportRewrite(); AST ast= cuRewrite.getRoot().getAST(); for (int i= 0; i < fCreatedTypes.length; i++) { ParameterizedType createdType= fCreatedTypes[i]; ITypeBinding[] typeArguments= createdType.resolveBinding().getTypeArguments(); ContextSensitiveImportRewriteContext importContext= new ContextSensitiveImportRewriteContext(cuRewrite.getRoot(), createdType.getStartPosition(), importRewrite); ListRewrite argumentsRewrite= rewrite.getListRewrite(createdType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY); for (int j= 0; j < typeArguments.length; j++) { ITypeBinding typeArgument= typeArguments[j]; Type argumentNode= importRewrite.addImport(typeArgument, ast, importContext); argumentsRewrite.insertLast(argumentNode, group); } } }
Example #10
Source File: CreateAndOddnessCheckResolution.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
/** * Creates the new <CODE>InfixExpression</CODE> <CODE>(x & 1) == 1</CODE>. */ @Override protected InfixExpression createCorrectOddnessCheck(ASTRewrite rewrite, Expression numberExpression) { Assert.isNotNull(rewrite); Assert.isNotNull(numberExpression); final AST ast = rewrite.getAST(); InfixExpression andOddnessCheck = ast.newInfixExpression(); ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression(); InfixExpression andExpression = ast.newInfixExpression(); andExpression.setLeftOperand((Expression) rewrite.createMoveTarget(numberExpression)); andExpression.setOperator(AND); andExpression.setRightOperand(ast.newNumberLiteral("1")); parenthesizedExpression.setExpression(andExpression); andOddnessCheck.setLeftOperand(parenthesizedExpression); andOddnessCheck.setOperator(EQUALS); andOddnessCheck.setRightOperand(ast.newNumberLiteral("1")); return andOddnessCheck; }
Example #11
Source File: AbstractUpdateSignatureProposal.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 6 votes |
/** * Generates a sync/async method declaration based on the associated * async/sync method signature. */ private MethodDeclaration computeMethodSignature(AST ast, RpcPair rpcPair, MethodDeclaration dstMethod) { MethodDeclaration method = ast.newMethodDeclaration(); // New method has same name as original String methodName = rpcPair.srcMethod.getName().getIdentifier(); method.setName(ast.newSimpleName(methodName)); // Update the parameters @SuppressWarnings("unchecked") List<SingleVariableDeclaration> params = method.parameters(); params.addAll(computeParams(ast, rpcPair.srcMethod, dstMethod, getImportRewrite())); // Update the return type method.setReturnType2(computeReturnType(ast, rpcPair.srcMethod, dstMethod, getImportRewrite())); return method; }
Example #12
Source File: MissingReturnTypeInLambdaCorrectionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
@Override protected Expression computeProposals(AST ast, ITypeBinding returnBinding, int returnOffset, CompilationUnit root, Expression result) { ScopeAnalyzer analyzer= new ScopeAnalyzer(root); IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY); org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(root, returnOffset, 0); ASTNode varDeclFrag= ASTResolving.findAncestor(finder.getCoveringNode(), ASTNode.VARIABLE_DECLARATION_FRAGMENT); IVariableBinding varDeclFragBinding= null; if (varDeclFrag != null) varDeclFragBinding= ((VariableDeclarationFragment) varDeclFrag).resolveBinding(); for (int i= 0; i < bindings.length; i++) { IVariableBinding curr= (IVariableBinding) bindings[i]; ITypeBinding type= curr.getType(); // Bindings are compared to make sure that a lambda does not return a variable which is yet to be initialised. if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr) && !Bindings.equals(curr, varDeclFragBinding)) { if (result == null) { result= ast.newSimpleName(curr.getName()); } addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName(), null); } } return result; }
Example #13
Source File: AddArgumentCorrectionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
@Override protected ASTRewrite getRewrite() { AST ast= fCallerNode.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); ChildListPropertyDescriptor property= getProperty(); for (int i= 0; i < fInsertIndexes.length; i++) { int idx= fInsertIndexes[i]; String key= "newarg_" + i; //$NON-NLS-1$ Expression newArg= evaluateArgumentExpressions(ast, fParamTypes[idx], key); ListRewrite listRewriter= rewrite.getListRewrite(fCallerNode, property); listRewriter.insertAt(newArg, idx, null); addLinkedPosition(rewrite.track(newArg), i == 0, key); } return rewrite; }
Example #14
Source File: SrcTreeGenerator.java From sahagin-java with Apache License 2.0 | 6 votes |
private static void parseAST(String[] srcFiles, Charset srcCharset, String[] classPathEntries, FileASTRequestor requestor) { ASTParser parser = ASTParser.newParser(AST.JLS8); Map<String, String> options = JavaCore.getOptions(); JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options); parser.setCompilerOptions(options); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setResolveBindings(true); parser.setBindingsRecovery(true); parser.setEnvironment(classPathEntries, null, null, true); String[] srcEncodings = new String[srcFiles.length]; for (int i = 0; i < srcEncodings.length; i++) { srcEncodings[i] = srcCharset.name(); } parser.createASTs( srcFiles, srcEncodings, new String[]{}, requestor, null); }
Example #15
Source File: JavadocTagsSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
public static void getInvalidQualificationProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) { ASTNode node= problem.getCoveringNode(context.getASTRoot()); if (!(node instanceof Name)) { return; } Name name= (Name) node; IBinding binding= name.resolveBinding(); if (!(binding instanceof ITypeBinding)) { return; } ITypeBinding typeBinding= (ITypeBinding)binding; AST ast= node.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null); String label= CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description; ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME); proposals.add(proposal); }
Example #16
Source File: TypeURIHelper.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
public URI getFullURI(IJavaElement javaElement) { @SuppressWarnings("all") ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setProject(javaElement.getJavaProject()); IBinding[] bindings = parser.createBindings(new IJavaElement[] { javaElement }, null); if (bindings[0] != null) { return getFullURI(bindings[0]); } return null; }
Example #17
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 #18
Source File: JsonDeserializeAdder.java From SparkBuilderGenerator with MIT License | 5 votes |
private NormalAnnotation createAnnotation(AST ast, CompilationUnitModificationDomain compilationUnitModificationDomain, TypeDeclaration builderType) { TypeLiteral typeLiteral = createBuilderClassReferenceLiteral(ast, compilationUnitModificationDomain, builderType); NormalAnnotation jsonDeserializeAnnotation = ast.newNormalAnnotation(); jsonDeserializeAnnotation.setTypeName(ast.newSimpleName(JSON_DESERIALIZE_CLASS_NAME)); MemberValuePair builderAttribute = ast.newMemberValuePair(); builderAttribute.setName(ast.newSimpleName("builder")); builderAttribute.setValue(typeLiteral); jsonDeserializeAnnotation.values().add(builderAttribute); return jsonDeserializeAnnotation; }
Example #19
Source File: ExtractConstantRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void replaceExpressionsWithConstant() throws JavaModelException { ASTRewrite astRewrite= fCuRewrite.getASTRewrite(); AST ast= astRewrite.getAST(); IASTFragment[] fragmentsToReplace= getFragmentsToReplace(); for (int i= 0; i < fragmentsToReplace.length; i++) { IASTFragment fragment= fragmentsToReplace[i]; ASTNode node= fragment.getAssociatedNode(); boolean inTypeDeclarationAnnotation= isInTypeDeclarationAnnotation(node); if (inTypeDeclarationAnnotation && JdtFlags.VISIBILITY_STRING_PRIVATE == getVisibility()) continue; SimpleName ref= ast.newSimpleName(fConstantName); Name replacement= ref; boolean qualifyReference= qualifyReferencesWithDeclaringClassName(); if (!qualifyReference) { qualifyReference= inTypeDeclarationAnnotation; } if (qualifyReference) { replacement= ast.newQualifiedName(ast.newSimpleName(getContainingTypeBinding().getName()), ref); } TextEditGroup description= fCuRewrite.createGroupDescription(RefactoringCoreMessages.ExtractConstantRefactoring_replace); fragment.replace(astRewrite, replacement, description); if (fLinkedProposalModel != null) fLinkedProposalModel.getPositionGroup(KEY_NAME, true).addPosition(astRewrite.track(ref), false); } }
Example #20
Source File: NullAnnotationsRewriteOperations.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
@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 }
Example #21
Source File: QuickAssistProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private static void addExceptionToThrows(AST ast, MethodDeclaration methodDeclaration, ASTRewrite rewrite, Type type2) { ITypeBinding binding= type2.resolveBinding(); if (binding == null || isNotYetThrown(binding, methodDeclaration.thrownExceptionTypes())) { Type newType= (Type) ASTNode.copySubtree(ast, type2); ListRewrite listRewriter= rewrite.getListRewrite(methodDeclaration, MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY); listRewriter.insertLast(newType, null); } }
Example #22
Source File: JavaASTUtilsTest.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
@Override protected void setUp() throws Exception { super.setUp(); // Have JDT parse the compilation unit ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setProject(getTestProject()); parser.setSource(testClass.getCompilationUnit()); ast = parser.createAST(null); }
Example #23
Source File: JavadocAdder.java From SparkBuilderGenerator with MIT License | 5 votes |
public void addJavadocForWithBuilderMethod(AST ast, String typeName, String parameterName, MethodDeclaration builderMethod) { if (preferencesManager.getPreferenceValue(PluginPreferenceList.GENERATE_JAVADOC_ON_BUILDER_METHOD)) { Javadoc javadoc = javadocGenerator.generateJavadoc(ast, String.format(Locale.ENGLISH, "Creates builder to build {@link %s} and setting %s parameter.", typeName, parameterName), Collections.singletonMap(RETURN_JAVADOC_TAG_NAME, "created builder")); builderMethod.setJavadoc(javadoc); } }
Example #24
Source File: FieldDeclarationPostProcessor.java From SparkBuilderGenerator with MIT License | 5 votes |
public VariableDeclarationFragment postProcessFragment(AST ast, BuilderField builderField, VariableDeclarationFragment variableDeclarationFragment) { if (isPostProcessingRequired()) { Optional<String> result = fullyQualifiedNameExtractor.getFullyQualifiedBaseTypeName(builderField); if (result.isPresent()) { postProcessDeclaration(ast, variableDeclarationFragment, result.get()); } } return variableDeclarationFragment; }
Example #25
Source File: NewCUProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private TextEdit constructEnclosingTypeEdit(ICompilationUnit icu) throws CoreException { ASTParser astParser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); astParser.setSource(icu); CompilationUnit cu = (CompilationUnit) astParser.createAST(null); TypeDeclaration enclosingDecl = findEnclosingTypeDeclaration(cu, fTypeContainer.getElementName()); AST ast = cu.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); final AbstractTypeDeclaration newDeclaration; switch (fTypeKind) { case K_CLASS: newDeclaration = ast.newTypeDeclaration(); ((TypeDeclaration) newDeclaration).setInterface(false); break; case K_INTERFACE: newDeclaration = ast.newTypeDeclaration(); ((TypeDeclaration) newDeclaration).setInterface(true); break; case K_ENUM: newDeclaration = ast.newEnumDeclaration(); break; case K_ANNOTATION: newDeclaration = ast.newAnnotationTypeDeclaration(); break; default: return null; } newDeclaration.setJavadoc(null); newDeclaration.setName(ast.newSimpleName(ASTNodes.getSimpleNameIdentifier(fNode))); newDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); if (isParameterizedType(fTypeKind, fNode)) { addTypeParameters((TypeDeclaration) newDeclaration); } ListRewrite lrw = rewrite.getListRewrite(enclosingDecl, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); lrw.insertLast(newDeclaration, null); return rewrite.rewriteAST(); }
Example #26
Source File: CopyResourceElementsOperation.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Renames the main type in <code>cu</code>. */ private void updateTypeName(ICompilationUnit cu, CompilationUnit astCU, String oldName, String newName, ASTRewrite rewriter) throws JavaModelException { if (newName != null) { String oldTypeName= Util.getNameWithoutJavaLikeExtension(oldName); String newTypeName= Util.getNameWithoutJavaLikeExtension(newName); AST ast = astCU.getAST(); // update main type name IType[] types = cu.getTypes(); for (int i = 0, max = types.length; i < max; i++) { IType currentType = types[i]; if (currentType.getElementName().equals(oldTypeName)) { AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) ((JavaElement) currentType).findNode(astCU); if (typeNode != null) { // rename type rewriter.replace(typeNode.getName(), ast.newSimpleName(newTypeName), null); // rename constructors Iterator bodyDeclarations = typeNode.bodyDeclarations().iterator(); while (bodyDeclarations.hasNext()) { Object bodyDeclaration = bodyDeclarations.next(); if (bodyDeclaration instanceof MethodDeclaration) { MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration; if (methodDeclaration.isConstructor()) { SimpleName methodName = methodDeclaration.getName(); if (methodName.getIdentifier().equals(oldTypeName)) { rewriter.replace(methodName, ast.newSimpleName(newTypeName), null); } } } } } } } } }
Example #27
Source File: MoveStaticMemberAnalyzer.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void rewriteName(Name name, ITypeBinding type) { AST creator= name.getAST(); boolean fullyQualified= false; if (name instanceof QualifiedName) { SimpleName left= ASTNodes.getLeftMostSimpleName(name); if (left.resolveBinding() instanceof IPackageBinding) fullyQualified= true; } if (fullyQualified) { fCuRewrite.getASTRewrite().replace( name, ASTNodeFactory.newName(creator, type.getQualifiedName()), fCuRewrite.createGroupDescription(REFERENCE_UPDATE)); fCuRewrite.getImportRemover().registerRemovedNode(name); } else { ImportRewriteContext context= new ContextSensitiveImportRewriteContext(name, fCuRewrite.getImportRewrite()); Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST(), context); fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName()); Name n= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result)); fCuRewrite.getASTRewrite().replace( name, n, fCuRewrite.createGroupDescription(REFERENCE_UPDATE)); fCuRewrite.getImportRemover().registerRemovedNode(name); fNeedsImport= true; } }
Example #28
Source File: ConvertForLoopOperation.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private SingleVariableDeclaration createParameterDeclaration(String parameterName, VariableDeclarationFragment fragement, Expression arrayAccess, ForStatement statement, ImportRewrite importRewrite, ASTRewrite rewrite, TextEditGroup group, LinkedProposalPositionGroup pg, boolean makeFinal) { CompilationUnit compilationUnit= (CompilationUnit)arrayAccess.getRoot(); AST ast= compilationUnit.getAST(); SingleVariableDeclaration result= ast.newSingleVariableDeclaration(); SimpleName name= ast.newSimpleName(parameterName); pg.addPosition(rewrite.track(name), true); result.setName(name); ITypeBinding arrayTypeBinding= arrayAccess.resolveTypeBinding(); Type type= importType(arrayTypeBinding.getElementType(), statement, importRewrite, compilationUnit); if (arrayTypeBinding.getDimensions() != 1) { type= ast.newArrayType(type, arrayTypeBinding.getDimensions() - 1); } result.setType(type); if (fragement != null) { VariableDeclarationStatement declaration= (VariableDeclarationStatement)fragement.getParent(); ModifierRewrite.create(rewrite, result).copyAllModifiers(declaration, group); } if (makeFinal && (fragement == null || ASTNodes.findModifierNode(Modifier.FINAL, ASTNodes.getModifiers(fragement)) == null)) { ModifierRewrite.create(rewrite, result).setModifiers(Modifier.FINAL, 0, group); } return result; }
Example #29
Source File: JsniFormattingUtil.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
private static int getMethodDeclarationOffset(IDocument document, int offset) { // Have JDT parse the compilation unit // AST.JLS4 is a superset of earlier version including AST.JLS3 ASTParser parser = ASTParser.newParser(AST.JLS4); parser.setResolveBindings(false); parser.setSource(document.get().toCharArray()); ASTNode ast = parser.createAST(null); // Figure out the offset of the containing method declaration JsniMethodFinder finder = new JsniMethodFinder(offset); ast.accept(finder); return finder.getJsniMethodDeclarationOffset(); }
Example #30
Source File: ParameterObjectFactory.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private MethodDeclaration createSetter(ParameterInfo pi, String declaringType, CompilationUnitRewrite cuRewrite) throws CoreException { AST ast= cuRewrite.getAST(); ICompilationUnit cu= cuRewrite.getCu(); IJavaProject project= cu.getJavaProject(); MethodDeclaration methodDeclaration= ast.newMethodDeclaration(); String fieldName= pi.getNewName(); String setterName= getSetterName(pi, ast, project); String lineDelim= StubUtility.getLineDelimiterUsed(cu); String bareFieldname= NamingConventions.getBaseName(NamingConventions.VK_INSTANCE_FIELD, fieldName, project); String paramName= StubUtility.suggestArgumentName(project, bareFieldname, null); if (createComments(project)) { String comment= CodeGeneration.getSetterComment(cu, declaringType, setterName, fieldName, pi.getNewTypeName(), paramName, bareFieldname, lineDelim); if (comment != null) methodDeclaration.setJavadoc((Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC)); } methodDeclaration.setName(ast.newSimpleName(setterName)); methodDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); SingleVariableDeclaration variable= ast.newSingleVariableDeclaration(); variable.setType(importBinding(pi.getNewTypeBinding(), cuRewrite)); variable.setName(ast.newSimpleName(paramName)); methodDeclaration.parameters().add(variable); Block block= ast.newBlock(); methodDeclaration.setBody(block); boolean useThis= StubUtility.useThisForFieldAccess(project); if (useThis || fieldName.equals(paramName)) { fieldName= "this." + fieldName; //$NON-NLS-1$ } String bodyContent= CodeGeneration.getSetterMethodBodyContent(cu, declaringType, setterName, fieldName, paramName, lineDelim); ASTNode setterBody= cuRewrite.getASTRewrite().createStringPlaceholder(bodyContent, ASTNode.EXPRESSION_STATEMENT); block.statements().add(setterBody); return methodDeclaration; }