List of usage examples for org.eclipse.jdt.core.dom BodyDeclaration getNodeType
public final int getNodeType()
From source file:at.bestsolution.fxide.jdt.corext.util.JdtFlags.java
License:Open Source License
public static boolean isStatic(BodyDeclaration bodyDeclaration) { if (isNestedInterfaceOrAnnotation(bodyDeclaration)) return true; int nodeType = bodyDeclaration.getNodeType(); if (!(nodeType == ASTNode.METHOD_DECLARATION || nodeType == ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION) && isInterfaceOrAnnotationMember(bodyDeclaration)) return true; if (bodyDeclaration instanceof EnumConstantDeclaration) return true; if (bodyDeclaration instanceof EnumDeclaration && bodyDeclaration.getParent() instanceof AbstractTypeDeclaration) return true; return Modifier.isStatic(bodyDeclaration.getModifiers()); }
From source file:com.github.parzonka.ccms.engine.SortElementsOperation.java
License:Open Source License
private ASTRewrite sortCompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit ast, final TextEditGroup group) { ast.accept(new ASTVisitor() { @Override//from w w w . j ava 2 s . c om public boolean visit(org.eclipse.jdt.core.dom.CompilationUnit compilationUnit) { final List<AbstractTypeDeclaration> types = compilationUnit.types(); for (final Iterator<AbstractTypeDeclaration> iter = types.iterator(); iter.hasNext();) { final AbstractTypeDeclaration typeDeclaration = iter.next(); typeDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(typeDeclaration.getStartPosition())); compilationUnit.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(typeDeclaration))); } return true; } @Override public boolean visit(AnnotationTypeDeclaration annotationTypeDeclaration) { final List bodyDeclarations = annotationTypeDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); annotationTypeDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } return true; } @Override public boolean visit(AnonymousClassDeclaration anonymousClassDeclaration) { final List bodyDeclarations = anonymousClassDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); anonymousClassDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } return true; } @Override public boolean visit(TypeDeclaration typeDeclaration) { final List bodyDeclarations = typeDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); typeDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } return true; } @Override public boolean visit(EnumDeclaration enumDeclaration) { final List bodyDeclarations = enumDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); enumDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } final List enumConstants = enumDeclaration.enumConstants(); for (final Iterator iter = enumConstants.iterator(); iter.hasNext();) { final EnumConstantDeclaration enumConstantDeclaration = (EnumConstantDeclaration) iter.next(); enumConstantDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(enumConstantDeclaration.getStartPosition())); enumDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(enumConstantDeclaration))); } return true; } }); final ASTRewrite rewriter = ASTRewrite.create(ast.getAST()); final boolean[] hasChanges = new boolean[] { false }; ast.accept(new ASTVisitor() { /** * This * * @param elements * @param listRewrite */ private void sortElements(List<BodyDeclaration> elements, ListRewrite listRewrite) { if (elements.size() == 0) return; final List<BodyDeclaration> myCopy = new ArrayList<BodyDeclaration>(); myCopy.addAll(elements); // orderexperiment final List<Signature> methods = new ArrayList<Signature>(); for (final BodyDeclaration bd : myCopy) { if (bd.getNodeType() == ASTNode.METHOD_DECLARATION) { methods.add(new Signature((MethodDeclaration) bd)); } } Collections.sort(methods, ((BodyDeclarationComparator) SortElementsOperation.this.comparator) .getMethodDeclarationComparator()); logger.info("Sorting of methods based on appearance:"); int j = 0; for (final Signature sig : methods) { logger.info("Method [{}] : {}", ++j, sig); } Collections.sort(myCopy, SortElementsOperation.this.comparator); logger.info("Final sorting order just before the AST-Rewrite:"); for (final BodyDeclaration bd : myCopy) { if (bd.getNodeType() == ASTNode.METHOD_DECLARATION) { logger.info("{}", new Signature((MethodDeclaration) bd)); } else { logger.info("{}", bd.toString()); } } for (int i = 0; i < elements.size(); i++) { final BodyDeclaration oldNode = elements.get(i); final BodyDeclaration newNode = myCopy.get(i); if (oldNode != newNode) { if (oldNode.getNodeType() == ASTNode.METHOD_DECLARATION && newNode.getNodeType() == ASTNode.METHOD_DECLARATION) { final Signature oldMethodSignature = new Signature((MethodDeclaration) oldNode); final Signature newMethodSignature = new Signature((MethodDeclaration) newNode); logger.trace("Swapping [{}]for [{}]", oldMethodSignature, newMethodSignature); } else { logger.trace("Swapping [{}]for [{}]", oldNode.getNodeType(), newNode.getNodeType()); } listRewrite.replace(oldNode, rewriter.createMoveTarget(newNode), group); hasChanges[0] = true; } } } @Override public boolean visit(org.eclipse.jdt.core.dom.CompilationUnit compilationUnit) { if (checkMalformedNodes(compilationUnit)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(compilationUnit.types(), rewriter.getListRewrite(compilationUnit, org.eclipse.jdt.core.dom.CompilationUnit.TYPES_PROPERTY)); return true; } @Override public boolean visit(AnnotationTypeDeclaration annotationTypeDeclaration) { if (checkMalformedNodes(annotationTypeDeclaration)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(annotationTypeDeclaration.bodyDeclarations(), rewriter.getListRewrite( annotationTypeDeclaration, AnnotationTypeDeclaration.BODY_DECLARATIONS_PROPERTY)); return true; } @Override public boolean visit(AnonymousClassDeclaration anonymousClassDeclaration) { if (checkMalformedNodes(anonymousClassDeclaration)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(anonymousClassDeclaration.bodyDeclarations(), rewriter.getListRewrite( anonymousClassDeclaration, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY)); return true; } @Override public boolean visit(TypeDeclaration typeDeclaration) { if (checkMalformedNodes(typeDeclaration)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(typeDeclaration.bodyDeclarations(), rewriter.getListRewrite(typeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY)); return true; } @Override public boolean visit(EnumDeclaration enumDeclaration) { if (checkMalformedNodes(enumDeclaration)) { return true; // abort sorting of current element } sortElements(enumDeclaration.bodyDeclarations(), rewriter.getListRewrite(enumDeclaration, EnumDeclaration.BODY_DECLARATIONS_PROPERTY)); sortElements(enumDeclaration.enumConstants(), rewriter.getListRewrite(enumDeclaration, EnumDeclaration.ENUM_CONSTANTS_PROPERTY)); return true; } }); if (!hasChanges[0]) return null; return rewriter; }
From source file:com.github.parzonka.ccms.sorter.comparator.BodyDeclarationComparator.java
License:Open Source License
/** * This comparator follows the contract defined in * CompilationUnitSorter.sort./*www . j ava 2 s .com*/ * * @see Comparator#compare(java.lang.Object, java.lang.Object) * @see CompilationUnitSorter#sort(int, * org.eclipse.jdt.core.ICompilationUnit, int[], java.util.Comparator, * int, org.eclipse.core.runtime.IProgressMonitor) */ @Override public int compare(BodyDeclaration bodyDeclaration1, BodyDeclaration bodyDeclaration2) { if (isSortPreserved(bodyDeclaration1) && isSortPreserved(bodyDeclaration2)) { final int preservedOrder = preserveRelativeOrder(bodyDeclaration1, bodyDeclaration2); logger.trace("Keeping preserved order: [{}] : [{}] = " + preservedOrder, bodyDeclaration1.toString(), bodyDeclaration2.toString()); return preservedOrder; } final int cat1 = category(bodyDeclaration1); final int cat2 = category(bodyDeclaration2); if (cat1 != cat2) { final int categoryOrder = cat1 - cat2; logger.trace("Keeping category order: [{}] : [{}] = " + categoryOrder, bodyDeclaration1.toString(), bodyDeclaration2.toString()); return categoryOrder; } if (bodyDeclaration1.getNodeType() == ASTNode.METHOD_DECLARATION) { final MethodDeclaration method1 = (MethodDeclaration) bodyDeclaration1; final MethodDeclaration method2 = (MethodDeclaration) bodyDeclaration2; final Signature signature1 = new Signature(method1); final Signature signature2 = new Signature(method2); if (this.knownMethodSignatures.contains(signature1) && this.knownMethodSignatures.contains(signature2)) { final int compare = this.methodDeclarationComparator.compare(signature1, signature2); logger.trace("Comparing methods [{}] : [{}] = " + compare, signature1, signature2); if (compare == 0) logger.warn("No absolute compare value between [{}] and [{}]", signature1, signature2); return compare; } logger.warn("A method signature was not known!"); logger.warn("{} known={}", signature1, this.knownMethodSignatures.contains(signature1)); logger.warn("{} known={}", signature2, this.knownMethodSignatures.contains(signature2)); } final int relativeOrder = preserveRelativeOrder(bodyDeclaration1, bodyDeclaration2); logger.trace("Keeping relative order: [{}] : [{}]= " + relativeOrder, bodyDeclaration1.toString(), bodyDeclaration2.toString()); return relativeOrder; }
From source file:com.github.parzonka.ccms.sorter.comparator.BodyDeclarationComparator.java
License:Open Source License
private boolean isSortPreserved(BodyDeclaration bodyDeclaration) { switch (bodyDeclaration.getNodeType()) { case ASTNode.FIELD_DECLARATION: case ASTNode.ENUM_CONSTANT_DECLARATION: case ASTNode.INITIALIZER: case ASTNode.TYPE_DECLARATION: return true; default://from www .j ava2 s. c om return false; } }
From source file:com.github.parzonka.ccms.sorter.comparator.BodyDeclarationComparator.java
License:Open Source License
private int category(BodyDeclaration bodyDeclaration) { switch (bodyDeclaration.getNodeType()) { case ASTNode.METHOD_DECLARATION: { final MethodDeclaration method = (MethodDeclaration) bodyDeclaration; if (method.isConstructor()) { return getMemberCategory(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX); } else//from ww w. ja va 2 s .c o m return getMemberCategory(MembersOrderPreferenceCache.METHOD_INDEX); } case ASTNode.FIELD_DECLARATION: { return getMemberCategory(MembersOrderPreferenceCache.FIELDS_INDEX); } case ASTNode.INITIALIZER: { final int flags = ((Initializer) bodyDeclaration).getModifiers(); if (Modifier.isStatic(flags)) return getMemberCategory(MembersOrderPreferenceCache.STATIC_INIT_INDEX); else return getMemberCategory(MembersOrderPreferenceCache.INIT_INDEX); } case ASTNode.TYPE_DECLARATION: case ASTNode.ENUM_DECLARATION: case ASTNode.ANNOTATION_TYPE_DECLARATION: return getMemberCategory(MembersOrderPreferenceCache.TYPE_INDEX); case ASTNode.ENUM_CONSTANT_DECLARATION: return getMemberCategory(MembersOrderPreferenceCache.ENUM_CONSTANTS_INDEX); case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: return getMemberCategory(MembersOrderPreferenceCache.METHOD_INDEX); } throw new IllegalStateException(); }
From source file:com.google.currysrc.api.process.ast.BodyDeclarationLocators.java
License:Apache License
/** * Creates {@link BodyDeclarationLocator} objects that can find the supplied * {@link BodyDeclaration}. Usually returns a single element, except for fields declarations. *//*from w w w. j ava 2 s . c o m*/ public static List<BodyDeclarationLocator> createLocators(BodyDeclaration bodyDeclaration) { AbstractTypeDeclaration typeDeclaration = TypeLocator.findTypeDeclarationNode(bodyDeclaration); if (typeDeclaration == null) { throw new AssertionError("Unable to find type declaration for " + typeDeclaration); } TypeLocator typeLocator = new TypeLocator(typeDeclaration); int nodeType = bodyDeclaration.getNodeType(); switch (nodeType) { case ASTNode.FIELD_DECLARATION: List<String> fieldNames = FieldLocator.getFieldNames((FieldDeclaration) bodyDeclaration); List<BodyDeclarationLocator> fieldLocators = new ArrayList<>(fieldNames.size()); for (String fieldName : fieldNames) { fieldLocators.add(new FieldLocator(typeLocator, fieldName)); } return fieldLocators; case ASTNode.METHOD_DECLARATION: MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration; List<String> parameterTypeNames = ParameterMatcher.getParameterTypeNames(methodDeclaration); return ImmutableList.<BodyDeclarationLocator>of(new MethodLocator(typeLocator, methodDeclaration.getName().getIdentifier(), parameterTypeNames)); case ASTNode.TYPE_DECLARATION: case ASTNode.ENUM_DECLARATION: return ImmutableList.<BodyDeclarationLocator>of(typeLocator); case ASTNode.ENUM_CONSTANT_DECLARATION: EnumConstantDeclaration enumConstantDeclaration = (EnumConstantDeclaration) bodyDeclaration; String constantName = enumConstantDeclaration.getName().getIdentifier(); return ImmutableList.<BodyDeclarationLocator>of(new EnumConstantLocator(typeLocator, constantName)); default: throw new IllegalArgumentException("Unsupported node type: " + nodeType); } }
From source file:com.google.currysrc.api.process.JavadocUtils.java
License:Apache License
/** * Returns {@code true} if the BodyDeclaration is one that is normally documented. e.g. returns * false for initializers./*w w w . java 2 s. com*/ */ public static boolean isNormallyDocumented(BodyDeclaration node) { int nodeType = node.getNodeType(); return nodeType != ASTNode.INITIALIZER; }
From source file:com.google.devtools.j2cpp.translate.InitializationNormalizer.java
License:Open Source License
void normalizeMembers(AbstractTypeDeclaration node) { List<Statement> initStatements = Lists.newArrayList(); List<Statement> classInitStatements = Lists.newArrayList(); List<MethodDeclaration> methods = Lists.newArrayList(); ITypeBinding binding = Types.getTypeBinding(node); // Scan class, gathering initialization statements in declaration order. @SuppressWarnings("unchecked") List<BodyDeclaration> members = node.bodyDeclarations(); // safe by specification Iterator<BodyDeclaration> iterator = members.iterator(); while (iterator.hasNext()) { BodyDeclaration member = iterator.next(); switch (member.getNodeType()) { case ASTNode.ENUM_DECLARATION: case ASTNode.TYPE_DECLARATION: normalizeMembers((AbstractTypeDeclaration) member); break; case ASTNode.METHOD_DECLARATION: methods.add((MethodDeclaration) member); break; case ASTNode.INITIALIZER: addInitializer(member, initStatements, classInitStatements); iterator.remove();//from www . jav a 2 s. c om break; case ASTNode.FIELD_DECLARATION: if (!binding.isInterface()) { // All interface fields are constants. addFieldInitializer(member, initStatements, classInitStatements); } break; } } // Update any primary constructors with init statements. if (!initStatements.isEmpty() || binding.isEnum()) { boolean needsConstructor = true; for (MethodDeclaration md : methods) { if (md.isConstructor()) { needsConstructor = false; } normalizeMethod(md, initStatements); } if (needsConstructor) { addDefaultConstructor(binding, members, initStatements, node.getAST()); } } // Create an initialize method, if necessary. if (!classInitStatements.isEmpty()) { addClassInitializer(binding, members, classInitStatements, node.getAST()); } }
From source file:com.google.googlejavaformat.java.JavaInputAstVisitor.java
License:Apache License
/** * Add a list of {@link BodyDeclaration}s * @param bodyDeclarations the {@link BodyDeclaration}s * @param braces whether to include braces in the output * @param first0 is the first {@link BodyDeclaration} the first to be output? *///from w w w .ja v a 2s . c o m void addBodyDeclarations(List<BodyDeclaration> bodyDeclarations, BracesOrNot braces, FirstDeclarationsOrNot first0) { if (bodyDeclarations.isEmpty()) { if (braces.isYes()) { builder.space(); tokenBreakTrailingComment("{", plusTwo); builder.blankLineWanted(BlankLineWanted.NO); builder.open(ZERO); token("}", plusTwo); builder.close(); } } else { if (braces.isYes()) { builder.space(); tokenBreakTrailingComment("{", plusTwo); builder.open(ZERO); } builder.open(plusTwo); boolean first = first0.isYes(); boolean lastOneGotBlankLineBefore = false; for (BodyDeclaration bodyDeclaration : bodyDeclarations) { dropEmptyDeclarations(); builder.forcedBreak(); boolean thisOneGetsBlankLineBefore = bodyDeclaration.getNodeType() != ASTNode.FIELD_DECLARATION || hasJavaDoc(bodyDeclaration); if (first) { builder.blankLineWanted(BlankLineWanted.PRESERVE); } else if (!first && (thisOneGetsBlankLineBefore || lastOneGotBlankLineBefore)) { builder.blankLineWanted(BlankLineWanted.YES); } markForPartialFormat(); bodyDeclaration.accept(this); first = false; lastOneGotBlankLineBefore = thisOneGetsBlankLineBefore; } builder.close(); builder.forcedBreak(); markForPartialFormat(); if (braces.isYes()) { dropEmptyDeclarations(); builder.blankLineWanted(BlankLineWanted.NO); token("}", plusTwo); builder.close(); } } }
From source file:de.akra.idocit.java.services.JavaInterfaceParser.java
License:Apache License
/** * Convert an {@link AbstractTypeDeclaration} to a {@link JavaInterface}. * /*from ww w . jav a 2s. c o m*/ * @param parent * The parent {@link SignatureElement}. * @param absTypeDeclaration * The {@link AbstractTypeDeclaration} to process. * @param category * The category for the {@link JavaInterface}. * @return a new {@link JavaInterface}. * @throws ParserConfigurationException * @throws IOException * @throws SAXException * @see AbstractTypeDeclaration */ private JavaInterface processAbstractTypeDeclaration(final SignatureElement parent, final AbstractTypeDeclaration absTypeDeclaration, final String category, final AbsJavadocParser parser) throws SAXException, IOException, ParserConfigurationException, ParsingException { final JavaInterface jInterface = new JavaInterface(parent, category, Numerus.SINGULAR); jInterface.setIdentifier(absTypeDeclaration.getName().getIdentifier()); jInterface.setQualifiedIdentifier(absTypeDeclaration.getName().getFullyQualifiedName()); jInterface.setRefToASTNode(absTypeDeclaration); final Javadoc javadoc = absTypeDeclaration.getJavadoc(); final List<Addressee> addressees = ServiceManager.getInstance().getPersistenceService() .loadConfiguredAddressees(); final List<ThematicRole> roles = ServiceManager.getInstance().getPersistenceService().loadThematicRoles(); List<Documentation> docs = parser.parseIDocItJavadoc(javadoc, addressees, roles, null); if (docs.isEmpty()) { docs = parser.convertExistingJavadoc(javadoc); } jInterface.setDocumentations(docs); final List<ThematicRole> knownRoles = ServiceManager.getInstance().getPersistenceService() .loadThematicRoles(); final List<TagElement> additionalTags = parser.findAdditionalTags(javadoc, knownRoles); jInterface.setAdditionalTags(additionalTags); @SuppressWarnings("unchecked") final List<BodyDeclaration> bodyDeclarations = (List<BodyDeclaration>) absTypeDeclaration .bodyDeclarations(); List<Interface> innerInterface = Collections.emptyList(); List<Operation> operations = Collections.emptyList(); for (final BodyDeclaration bodyDec : bodyDeclarations) { // only public elements are processed. In Java interfaces everything is // public. if (ReflectionHelper.isPublic(bodyDec.getModifiers()) || Constants.CATEGORY_INTERFACE.equals(category)) { switch (bodyDec.getNodeType()) { case ASTNode.TYPE_DECLARATION: { if (innerInterface == Collections.EMPTY_LIST) { innerInterface = new ArrayList<Interface>(SignatureElement.DEFAULT_ARRAY_SIZE); } final TypeDeclaration typeDec = (TypeDeclaration) bodyDec; innerInterface.add(processTypeDeclaration(jInterface, typeDec, parser)); break; } case ASTNode.ENUM_DECLARATION: { if (innerInterface == Collections.EMPTY_LIST) { innerInterface = new ArrayList<Interface>(SignatureElement.DEFAULT_ARRAY_SIZE); } final EnumDeclaration enumDec = (EnumDeclaration) bodyDec; innerInterface.add(processEnumDeclaration(jInterface, enumDec, parser)); break; } case ASTNode.METHOD_DECLARATION: { if (operations == Collections.EMPTY_LIST) { // init with number of all declarations for fields, methods, // enumerations, classes etc. to avoid resizing of the array operations = new ArrayList<Operation>(bodyDeclarations.size()); } final MethodDeclaration methodDec = (MethodDeclaration) bodyDec; operations.add(processMethodDeclaration(jInterface, methodDec, parser, knownRoles)); break; } default: { // Do nothing! logger.info("Nodetype of ASTNode is " + bodyDec.getNodeType()); } } } } jInterface.setInnerInterfaces(innerInterface); jInterface.setOperations(operations); return jInterface; }