List of usage examples for org.eclipse.jdt.core.dom BodyDeclaration getStartPosition
public final int getStartPosition()
From source file:br.uff.ic.gems.resources.ast.Visitor.java
public int beginLine(BodyDeclaration node) { int beginLine = INVALID_LINE; List modifiers = node.modifiers(); for (Object modifier : modifiers) { if (modifier instanceof Modifier) { Modifier m = (Modifier) modifier; beginLine = cu.getLineNumber(m.getStartPosition()); }// w w w .j a v a2 s . com } if (beginLine == INVALID_LINE) { beginLine = cu.getLineNumber(node.getStartPosition()); Javadoc javadoc = node.getJavadoc(); int javadocBegin = INVALID_JAVADOC; if (javadoc != null) { javadocBegin = cu.getLineNumber(javadoc.getStartPosition()); } if (beginLine == javadocBegin) { beginLine = cu.getLineNumber(javadoc.getStartPosition() + javadoc.getLength() + 1); } } return beginLine; }
From source file:br.uff.ic.gems.resources.ast.Visitor.java
public int beginColunm(BodyDeclaration node) { int begincolumn = INVALID_COLUMN; List modifiers = node.modifiers(); for (Object modifier : modifiers) { if (modifier instanceof Modifier) { Modifier m = (Modifier) modifier; begincolumn = cu.getColumnNumber(m.getStartPosition()); }/*from w w w . ja v a 2 s . c o m*/ } if (begincolumn == INVALID_COLUMN) { begincolumn = cu.getColumnNumber(node.getStartPosition()); Javadoc javadoc = node.getJavadoc(); int javadocBegin = INVALID_JAVADOC; if (javadoc != null) { javadocBegin = cu.getColumnNumber(javadoc.getStartPosition()); } if (begincolumn == javadocBegin) { begincolumn = cu.getColumnNumber(javadoc.getStartPosition() + javadoc.getLength() + 1); } } return begincolumn; }
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// w w w . j av a 2s . co m 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.google.googlejavaformat.java.JavaInputAstVisitor.java
License:Apache License
/** Does this {@link BodyDeclaration} have JavaDoc preceding it? */ private boolean hasJavaDoc(BodyDeclaration bodyDeclaration) { int position = bodyDeclaration.getStartPosition(); Map.Entry<Integer, ? extends Input.Token> entry = builder.getInput().getPositionTokenMap() .ceilingEntry(position);// w w w . j a v a2s . c o m if (entry != null) { for (Input.Tok tok : entry.getValue().getToksBefore()) { if (tok.getText().startsWith("/**")) { return true; } } } return false; }
From source file:com.halware.nakedide.eclipse.ext.annot.utils.AstUtils.java
License:Open Source License
/** * Returns the offset and length for the {@link MethodDeclaration}, optionally * including any modifiers (including annotations and visibility). * /* www .j a v a 2 s . c o m*/ * @param declaration * @param includingModifiers - whether to include modifiers in the offset and length. */ public final static OffsetAndLength calculateOffset(BodyDeclaration declaration, boolean includingModifiers) { if (!(declaration instanceof MethodDeclaration) && !(declaration instanceof TypeDeclaration)) { throw new IllegalArgumentException("declaration must be TypeDeclaration or MethodDeclaration"); } SimpleName methodName = nameFor(declaration); if (!includingModifiers) { return new OffsetAndLength(methodName.getStartPosition(), methodName.getLength()); } else { // including modifiers int endOfMethodName = methodName.getStartPosition() + methodName.getLength(); ChildListPropertyDescriptor modifiersProperty = declaration.getModifiersProperty(); List<ASTNode> methodModifiers = Generics.asT(declaration.getStructuralProperty(modifiersProperty)); if (methodModifiers.size() > 0) { int startOfModifiers = methodModifiers.get(0).getStartPosition(); return new OffsetAndLength(startOfModifiers, endOfMethodName - startOfModifiers); } if (declaration instanceof MethodDeclaration) { Type returnType2 = ((MethodDeclaration) declaration).getReturnType2(); if (returnType2 != null) { int startOfReturnType = returnType2.getStartPosition(); return new OffsetAndLength(startOfReturnType, endOfMethodName - startOfReturnType); } } int startOfMethodName = declaration.getStartPosition(); return new OffsetAndLength(startOfMethodName, endOfMethodName - startOfMethodName); } }
From source file:de.ovgu.featureide.munge.signatures.MungeSignatureBuilder.java
License:Open Source License
private static Collection<AbstractSignature> parse(ProjectSignatures projectSignatures, ASTNode root) { final HashMap<AbstractSignature, AbstractSignature> map = new HashMap<>(); final CompilationUnit cu = (CompilationUnit) root; final PackageDeclaration pckgDecl = cu.getPackage(); final String packageName = (pckgDecl == null) ? null : pckgDecl.getName().getFullyQualifiedName(); List<?> l = cu.getCommentList(); List<Javadoc> cl = new LinkedList<>(); for (Object object : l) { if (object instanceof Javadoc) { Javadoc comment = (Javadoc) object; cl.add(comment);/*from w w w . java2s. com*/ } } final ListIterator<Javadoc> it = cl.listIterator(); final FeatureDataConstructor featureDataConstructor = new FeatureDataConstructor(projectSignatures, FeatureDataConstructor.TYPE_PP); root.accept(new ASTVisitor() { private BodyDeclaration curDeclaration = null; private PreprocessorFeatureData curfeatureData = null; private String lastComment = null; private MethodDeclaration lastCommentedMethod = null; @Override public boolean visit(Javadoc node) { if (curDeclaration != null) { final StringBuilder sb = new StringBuilder(); while (it.hasNext()) { final Javadoc comment = it.next(); if (comment.getStartPosition() <= curDeclaration.getStartPosition()) { sb.append(comment); sb.append("\n"); } else { it.previous(); break; } } lastComment = sb.toString(); curfeatureData.setComment(lastComment); lastCommentedMethod = (curDeclaration instanceof MethodDeclaration) ? (MethodDeclaration) curDeclaration : null; } return false; } private void attachFeatureData(AbstractSignature curSignature, BodyDeclaration curDeclaration) { this.curDeclaration = curDeclaration; final Javadoc javadoc = curDeclaration.getJavadoc(); final int startPosition = (javadoc == null) ? curDeclaration.getStartPosition() : curDeclaration.getStartPosition() + javadoc.getLength(); curfeatureData = (PreprocessorFeatureData) featureDataConstructor.create(null, unit.getLineNumber(startPosition), unit.getLineNumber(curDeclaration.getStartPosition() + curDeclaration.getLength())); curSignature.setFeatureData(curfeatureData); map.put(curSignature, curSignature); } @Override public boolean visit(CompilationUnit unit) { this.unit = unit; return true; } CompilationUnit unit = null; @Override public boolean visit(MethodDeclaration node) { int pos = unit.getLineNumber(node.getBody().getStartPosition()); int end = unit.getLineNumber(node.getBody().getStartPosition() + node.getBody().getLength()); final MungeMethodSignature methodSignature = new MungeMethodSignature(getParent(node.getParent()), node.getName().getIdentifier(), node.getModifiers(), node.getReturnType2(), node.parameters(), node.isConstructor(), pos, end); attachFeatureData(methodSignature, node); if (node.getJavadoc() == null && lastCommentedMethod != null && lastCommentedMethod.getName().equals(node.getName())) { curfeatureData.setComment(lastComment); } else { lastCommentedMethod = null; } return true; } private AbstractClassSignature getParent(ASTNode astnode) { final AbstractClassSignature sig; if (astnode instanceof TypeDeclaration) { final TypeDeclaration node = (TypeDeclaration) astnode; sig = new MungeClassSignature(null, node.getName().getIdentifier(), node.getModifiers(), node.isInterface() ? "interface" : "class", packageName); } else { return null; } AbstractClassSignature uniqueSig = (AbstractClassSignature) map.get(sig); if (uniqueSig == null) { visit((TypeDeclaration) astnode); } return uniqueSig; } @Override public boolean visit(FieldDeclaration node) { for (Iterator<?> it = node.fragments().iterator(); it.hasNext();) { VariableDeclarationFragment fragment = (VariableDeclarationFragment) it.next(); final MungeFieldSignature fieldSignature = new MungeFieldSignature(getParent(node.getParent()), fragment.getName().getIdentifier(), node.getModifiers(), node.getType()); attachFeatureData(fieldSignature, node); } return true; } @Override public boolean visit(TypeDeclaration node) { final MungeClassSignature classSignature = new MungeClassSignature(getParent(node.getParent()), node.getName().getIdentifier(), node.getModifiers(), node.isInterface() ? "interface" : "class", packageName); attachFeatureData(classSignature, node); return super.visit(node); } }); return map.keySet(); }
From source file:org.autorefactor.refactoring.rules.RemoveSemiColonRefactoring.java
License:Open Source License
private boolean visit(BodyDeclaration node) { final BodyDeclaration nextSibling = getNextSibling(node); final ASTNode parent = node.getParent(); if (nextSibling != null) { return removeSuperfluousSemiColons(node, getEndPosition(node), nextSibling.getStartPosition()); } else if (parent instanceof AbstractTypeDeclaration) { final AbstractTypeDeclaration typeDecl = (AbstractTypeDeclaration) parent; return removeSuperfluousSemiColons(node, getEndPosition(node), getEndPosition(typeDecl) - 1); } else if (parent instanceof AnonymousClassDeclaration) { final AnonymousClassDeclaration classDecl = (AnonymousClassDeclaration) parent; return removeSuperfluousSemiColons(node, getEndPosition(node), getEndPosition(classDecl) - 1); } else if (parent instanceof CompilationUnit) { final CompilationUnit cu = (CompilationUnit) parent; return removeSuperfluousSemiColons(node, getEndPosition(node), getEndPosition(cu) - 1); } else if (parent instanceof TypeDeclarationStatement) { return VISIT_SUBTREE; }/*from w w w .j a v a2 s. c o m*/ throw new NotImplementedException(node, "for a parent of type " + (parent != null ? parent.getClass().getSimpleName() : null)); }
From source file:org.eclipse.pde.api.tools.ui.internal.markers.NodeFinder.java
License:Open Source License
/** * Visit the {@link BodyDeclaration} node to see if it is at the specified * position/*from w ww. j av a2 s. co m*/ * * @param bodyDeclaration * @return */ private boolean visitNode(BodyDeclaration bodyDeclaration) { int start = bodyDeclaration.getStartPosition(); int end = bodyDeclaration.getLength() - 1 + start; switch (bodyDeclaration.getNodeType()) { case ASTNode.TYPE_DECLARATION: case ASTNode.ENUM_DECLARATION: case ASTNode.ANNOTATION_TYPE_DECLARATION: if (start <= this.position && this.position <= end) { this.declaration = bodyDeclaration; return true; } return false; case ASTNode.ENUM_CONSTANT_DECLARATION: case ASTNode.FIELD_DECLARATION: case ASTNode.METHOD_DECLARATION: case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: if (start <= this.position && this.position <= end) { this.declaration = bodyDeclaration; } return false; default: return false; } }
From source file:org.eclipse.wb.internal.core.utils.ast.AstEditor.java
License:Open Source License
/** * Adds new {@link BodyDeclaration} with given source in location of given {@link StatementTarget} * ./*from w w w . jav a2 s .c o m*/ * * @param lines * the lines of source for new {@link BodyDeclaration}. * @param target * describes location for new {@link BodyDeclaration}. */ private BodyDeclaration addBodyDeclaration(List<String> lines, BodyDeclarationTarget target) throws Exception { Assert.isNotNull(lines); Assert.isNotNull(target); // type or body declaration required TypeDeclaration targetType = target.getType(); BodyDeclaration targetDecl = target.getDeclaration(); Assert.isTrue(targetType != null || targetDecl != null); // prepare code generation constants AstCodeGeneration generation = getGeneration(); String singleIndent = generation.getIndentation(1); String eol = generation.getEndOfLine(); // relative to BodyDeclaration if (targetDecl != null) { // prepare information about target body declaration targetType = (TypeDeclaration) targetDecl.getParent(); String indent = getWhitespaceToLeft(targetDecl.getStartPosition(), false); int index = targetType.bodyDeclarations().indexOf(targetDecl); // add new declaration BodyDeclaration newDeclaration; String source = getIndentedSource(lines, indent, singleIndent, eol); if (target.isBefore()) { // add before any empty lines and EOLC lines int position = skipWhitespaceAndPureEOLCToLeft(targetDecl.getStartPosition()); source = source + eol; // parse declaration newDeclaration = getParser().parseBodyDeclaration(position, source); // add source replaceSubstring(position, 0, source); // add declaration DomGenerics.bodyDeclarations(targetType).add(index, newDeclaration); } else { // move at the end of target int position = AstNodeUtils.getSourceEnd(targetDecl); position = skipWhitespaceEOLCToRight(position); source = eol + source; // parse declaration newDeclaration = getParser().parseBodyDeclaration(position, source); // add source replaceSubstring(position, 0, source); // add declaration DomGenerics.bodyDeclarations(targetType).add(index + 1, newDeclaration); } // resolveImports(newDeclaration); return newDeclaration; } // relative to TypeDeclaration { removeDanglingJavadoc(); // prepare indent String indent; { ASTNode indentNode; if (AnonymousTypeDeclaration.is(targetType)) { indentNode = AstNodeUtils.getEnclosingStatement(targetType); } else { indentNode = targetType; } indent = getWhitespaceToLeft(indentNode.getStartPosition(), false) + singleIndent; } String source = getIndentedSource(lines, indent, singleIndent, eol); // add new body declaration BodyDeclaration newDeclaration; if (target.isBefore()) { // prepare position as position after '{' of type declaration int position = indexOfAny("{", targetType.getName().getStartPosition()) + 1; source = eol + source; // parse declaration newDeclaration = getParser().parseBodyDeclaration(position, source); // add source replaceSubstring(position, 0, source); // add declaration DomGenerics.bodyDeclarations(targetType).add(0, newDeclaration); } else { // prepare position as position of '}' of type declaration int position = AstNodeUtils.getSourceEnd(targetType) - 1; position -= getWhitespaceToLeft(position, false).length(); source = source + eol; // parse declaration newDeclaration = getParser().parseBodyDeclaration(position, source); // add source replaceSubstring(position, 0, source); // add declaration DomGenerics.bodyDeclarations(targetType).add(newDeclaration); } // resolveImports(newDeclaration); return newDeclaration; } }
From source file:org.eclipse.wb.internal.core.utils.ast.AstEditor.java
License:Open Source License
/** * Removes given {@link BodyDeclaration}. */// w ww. ja v a 2 s . co m public void removeBodyDeclaration(BodyDeclaration declaration) throws Exception { List<BodyDeclaration> declarations; if (declaration.getParent() instanceof TypeDeclaration) { TypeDeclaration typeDeclaration = (TypeDeclaration) declaration.getParent(); declarations = DomGenerics.bodyDeclarations(typeDeclaration); } else { declarations = DomGenerics.bodyDeclarations((AnonymousClassDeclaration) declaration.getParent()); } // prepare start of source to remove int startIndex; { int index = declarations.indexOf(declaration); if (index != 0) { BodyDeclaration prevDeclaration = declarations.get(index - 1); startIndex = prevDeclaration.getStartPosition() + prevDeclaration.getLength(); startIndex = skipWhitespaceEOLCToRight(startIndex); } else { if (declaration.getParent() instanceof TypeDeclaration) { TypeDeclaration typeDeclaration = (TypeDeclaration) declaration.getParent(); startIndex = indexOfAny("{", typeDeclaration.getName().getStartPosition()) + 1; } else { startIndex = indexOfAny("{", declaration.getParent().getStartPosition()) + 1; } } } // prepare end of source to remove int endIndex; { endIndex = declaration.getStartPosition() + declaration.getLength(); endIndex = skipWhitespaceEOLCToRight(endIndex); } // remove declaration and corresponding source declarations.remove(declaration); replaceSubstring(startIndex, endIndex - startIndex, ""); }