Example usage for org.eclipse.jdt.core.dom CompilationUnit getCommentList

List of usage examples for org.eclipse.jdt.core.dom CompilationUnit getCommentList

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom CompilationUnit getCommentList.

Prototype

public List getCommentList() 

Source Link

Document

Returns a list of the comments encountered while parsing this compilation unit.

Usage

From source file:ASTParser.ParseJavaFile.java

private void parse(final String str, File outputFile) {
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(str.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    StringBuffer allComments = new StringBuffer();

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    for (Comment comment : (List<Comment>) cu.getCommentList()) {
        CommentVisitor commentVisitor = new CommentVisitor(cu, str);
        comment.accept(commentVisitor);/*from  w w w  .j av a  2  s  .c  o m*/
        //            System.out.println(commentVisitor.getAllComments().toString());
        allComments.append(commentVisitor.getAllComments().toString());
    }

    allComments = ParseWords.parseAllWords(allComments);
    writeToFile(allComments.toString(), outputFile);
}

From source file:boa.datagen.util.Java7Visitor.java

License:Apache License

@Override
public boolean visit(CompilationUnit node) {
    //      b.setPosition(pos.build());
    PackageDeclaration pkg = node.getPackage();
    if (pkg == null) {
        b.setName("");
    } else {//  w w w .jav  a  2 s  .com
        b.setName(pkg.getName().getFullyQualifiedName());
        for (Object a : pkg.annotations()) {
            ((Annotation) a).accept(this);
            b.addModifiers(modifiers.pop());
        }
    }
    for (Object i : node.imports()) {
        ImportDeclaration id = (ImportDeclaration) i;
        String imp = "";
        if (id.isStatic())
            imp += "static ";
        imp += id.getName().getFullyQualifiedName();
        if (id.isOnDemand())
            imp += ".*";
        imports.add(imp);
    }
    for (Object t : node.types()) {
        declarations.push(new ArrayList<boa.types.Ast.Declaration>());
        ((AbstractTypeDeclaration) t).accept(this);
        for (boa.types.Ast.Declaration d : declarations.pop())
            b.addDeclarations(d);
    }
    for (Object c : node.getCommentList())
        ((org.eclipse.jdt.core.dom.Comment) c).accept(this);
    return false;
}

From source file:br.uff.ic.gems.resources.ast.ASTExtractor.java

public void parser() throws IOException {
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    File file = new File(filePath);

    String stringFile = FileUtils.readFileToString(file);
    parser.setSource(stringFile.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    //Setting options
    Map options;/*from  w w  w.  j  a va 2s . c om*/
    options = JavaCore.getOptions();
    options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);
    parser.setCompilerOptions(options);

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    Visitor visitor = new Visitor(cu);
    cu.accept(visitor);

    List<Comment> commentList = cu.getCommentList();

    for (Comment comment : commentList) {
        comment.accept(visitor);
    }

    languageConstructs = visitor.getLanguageConstructs();

}

From source file:com.alex.example.fixlicense.actions.SampleAction.java

License:Open Source License

private void processHeadLicense(IDocument doc) throws Exception {
    CompilationUnit cu = getAST(doc);
    Comment comment = null;//from   w w  w . j av  a 2s . c  om
    if (cu.getCommentList().size() == 0) {
        doc.replace(0, 0, license);
    } else {
        comment = (Comment) cu.getCommentList().get(0);
        String firstComment = doc.get().substring(comment.getStartPosition(),
                comment.getStartPosition() + comment.getLength());
        if (validateHeadLicense(firstComment)) {
            doc.replace(comment.getStartPosition(), comment.getLength(), license);
        } else {
            doc.replace(0, 0, license);
        }
    }
}

From source file:com.bsiag.eclipse.jdt.java.formatter.DefaultCodeFormatter.java

License:Open Source License

private TextEdit formatComments(String source, int kind, IRegion[] regions) {
    MultiTextEdit result = new MultiTextEdit();
    if (!init(source))
        return result;

    CommentsPreparator commentsPreparator = new CommentsPreparator(this.tokenManager, this.workingOptions,
            this.sourceLevel);
    CommentWrapExecutor commentWrapper = new CommentWrapExecutor(this.tokenManager, this.workingOptions);
    switch (kind) {
    case K_JAVA_DOC:
        ASTParser parser = ASTParser.newParser(AST.JLS8);
        for (Token token : this.tokens) {
            if (token.tokenType == TokenNameCOMMENT_JAVADOC) {
                parser.setSourceRange(token.originalStart, token.countChars());
                CompilationUnit cu = (CompilationUnit) parseSourceCode(parser, ASTParser.K_COMPILATION_UNIT,
                        true);//from www.  j a v  a 2 s.  c om
                Javadoc javadoc = (Javadoc) cu.getCommentList().get(0);
                javadoc.accept(commentsPreparator);
                int startPosition = this.tokenManager.findSourcePositionInLine(token.originalStart);
                commentWrapper.wrapMultiLineComment(token, startPosition, false, false);
            }
        }
        break;
    case K_MULTI_LINE_COMMENT:
        for (int i = 0; i < this.tokens.size(); i++) {
            Token token = this.tokens.get(i);
            if (token.tokenType == TokenNameCOMMENT_BLOCK) {
                commentsPreparator.handleBlockComment(i);
                int startPosition = this.tokenManager.findSourcePositionInLine(token.originalStart);
                commentWrapper.wrapMultiLineComment(token, startPosition, false, false);
            }
        }
        break;
    case K_SINGLE_LINE_COMMENT:
        for (int i = 0; i < this.tokens.size(); i++) {
            Token token = this.tokens.get(i);
            if (token.tokenType == TokenNameCOMMENT_LINE) {
                commentsPreparator.handleLineComment(i);
                if (i >= this.tokens.size() || this.tokens.get(i) != token) {
                    // current token has been removed and merged with previous one
                    i--;
                    token = this.tokens.get(i);
                }
                int startPosition = this.tokenManager.findSourcePositionInLine(token.originalStart);
                commentWrapper.wrapLineComment(token, startPosition);
            }
        }
        break;
    default:
        throw new AssertionError(String.valueOf(kind));
    }

    this.tokenManager.applyFormatOff();

    TextEditsBuilder resultBuilder = new TextEditsBuilder(source, regions, this.tokenManager,
            this.workingOptions);
    resultBuilder.setAlignChar(DefaultCodeFormatterOptions.SPACE);
    for (Token token : this.tokens) {
        List<Token> structure = token.getInternalStructure();
        if (structure != null && !structure.isEmpty())
            resultBuilder.processComment(token);
    }

    for (TextEdit edit : resultBuilder.getEdits()) {
        result.addChild(edit);
    }
    return result;
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.JavaSyncUtils.java

License:Open Source License

/**
 * Loads the java file and sets the retrieved comments for every method/attribute found inside it
 * @throws JavaModelException /*from   w  w  w  .j  a  va  2s.  c om*/
 * @flowerModelElementId _zVs8LZiOEd6aNMdNFvR5WQ
 */
@SuppressWarnings("unchecked")
public static CompilationUnit loadJavaFile(IFile file, ASTParser parser) throws Exception {
    CompilationUnit result = null;
    char[] fileContent;
    try {
        fileContent = getFileContent(file).toCharArray();
    } catch (ResourceException e) {
        file.refreshLocal(IResource.DEPTH_INFINITE, null);
        fileContent = getFileContent(file).toCharArray();
    }

    HashMap defaultOptions = new HashMap(JavaCore.getOptions());
    String compilerSourceLevel = (String) defaultOptions.get(JavaCore.COMPILER_SOURCE);

    // Source level 1.5 is necessary to enable annotations
    if (Double.valueOf(compilerSourceLevel) < 1.5) {
        defaultOptions.put(JavaCore.COMPILER_SOURCE, "1.5");
        parser.setCompilerOptions(defaultOptions);
    }

    parser.setSource(fileContent);
    result = (CompilationUnit) parser.createAST(null);

    for (Object o : result.getCommentList()) {
        if (o instanceof Javadoc) {
            Javadoc doc = (Javadoc) o;
            String docComment = new String(fileContent, doc.getStartPosition(), doc.getLength());

            //use Pattern and Matcher instead of string.replaceAll(...) to compile the pattern only once
            Matcher matcher = COMMENT_LINE_PATTERN.matcher(docComment);
            docComment = matcher.replaceAll("\r\n");
            matcher = COMMENT_MARKERS_PATTERN.matcher(docComment);
            docComment = matcher.replaceAll("");

            doc.setProperty("comment", docComment);
        }
    }
    return result;
}

From source file:com.google.currysrc.processors.BaseJavadocNodeScanner.java

License:Apache License

@Override
public final void process(Context context, CompilationUnit cu) {
    // This could just call cu.visit() but iterating over the comments should be more efficient.
    List<Comment> comments = cu.getCommentList();
    ASTRewrite rewrite = context.rewrite();
    Reporter reporter = context.reporter();
    for (Comment comment : Lists.reverse(comments)) {
        if (comment instanceof Javadoc) {
            Javadoc javadoc = (Javadoc) comment;
            visit(reporter, javadoc, rewrite);
        }/*  w w  w  . j ava  2s . c  o m*/
    }
}

From source file:com.google.currysrc.processors.BaseModifyCommentScanner.java

License:Apache License

@Override
public final void process(Context context, CompilationUnit cu) {
    Document document = context.document();
    Reporter reporter = context.reporter();
    List<Comment> comments = cu.getCommentList();
    try {//from w w w .  j  a v a 2s. c om
        for (Comment comment : Lists.reverse(comments)) {
            String commentText = document.get(comment.getStartPosition(), comment.getLength());
            String newCommentText = processComment(reporter, comment, commentText);
            if (newCommentText != null) {
                document.replace(comment.getStartPosition(), comment.getLength(), newCommentText);
            }
        }
    } catch (BadLocationException e) {
        throw new AssertionError(e);
    }
}

From source file:com.google.devtools.j2objc.util.ASTUtil.java

License:Apache License

@SuppressWarnings("unchecked")
public static List<Comment> getCommentList(CompilationUnit unit) {
    return unit.getCommentList();
}

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);/*  w w  w  .ja  v a 2 s .c o  m*/
        }
    }

    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();
}