Example usage for org.eclipse.jdt.core.dom ASTParser setIgnoreMethodBodies

List of usage examples for org.eclipse.jdt.core.dom ASTParser setIgnoreMethodBodies

Introduction

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

Prototype

public void setIgnoreMethodBodies(boolean enabled) 

Source Link

Document

Requests an abstract syntax tree without method bodies.

Usage

From source file:ca.ecliptical.pde.internal.ds.DSAnnotationCompilationParticipant.java

License:Open Source License

private void processAnnotations(IJavaProject javaProject, Map<ICompilationUnit, BuildContext> fileMap) {
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setResolveBindings(true);//from w  w w  .  j a  va 2 s .c  o  m
    parser.setBindingsRecovery(true);
    parser.setProject(javaProject);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    ProjectContext projectContext = processingContext.get(javaProject);
    ProjectState state = projectContext.getState();

    parser.setIgnoreMethodBodies(state.getErrorLevel() == ValidationErrorLevel.none);

    ICompilationUnit[] cuArr = fileMap.keySet().toArray(new ICompilationUnit[fileMap.size()]);
    Map<ICompilationUnit, Collection<IDSModel>> models = new HashMap<ICompilationUnit, Collection<IDSModel>>();
    parser.createASTs(cuArr, new String[0], new AnnotationProcessor(models, fileMap, state.getErrorLevel()),
            null);

    Map<String, Collection<String>> cuMap = state.getMappings();
    Collection<String> unprocessed = projectContext.getUnprocessed();
    Collection<String> abandoned = projectContext.getAbandoned();

    IPath outputPath = new Path(state.getPath()).addTrailingSeparator();

    // save each model to a file; track changes to mappings
    for (Map.Entry<ICompilationUnit, Collection<IDSModel>> entry : models.entrySet()) {
        ICompilationUnit cu = entry.getKey();
        IType cuType = cu.findPrimaryType();
        if (cuType == null) {
            if (debug.isDebugging())
                debug.trace(String.format("CU %s has no primary type!", cu.getElementName())); //$NON-NLS-1$

            continue; // should never happen
        }

        String cuKey = cuType.getFullyQualifiedName();

        unprocessed.remove(cuKey);
        Collection<String> oldDSKeys = cuMap.remove(cuKey);
        Collection<String> dsKeys = new HashSet<String>();
        cuMap.put(cuKey, dsKeys);

        for (IDSModel model : entry.getValue()) {
            String compName = model.getDSComponent().getAttributeName();
            IPath filePath = outputPath.append(compName).addFileExtension("xml"); //$NON-NLS-1$
            String dsKey = filePath.toPortableString();

            // exclude file from garbage collection
            if (oldDSKeys != null)
                oldDSKeys.remove(dsKey);

            // add file to CU mapping
            dsKeys.add(dsKey);

            // actually save the file
            IFile compFile = PDEProject.getBundleRelativeFile(javaProject.getProject(), filePath);
            model.setUnderlyingResource(compFile);

            try {
                ensureDSProject(compFile.getProject());
            } catch (CoreException e) {
                Activator.getDefault().getLog().log(e.getStatus());
            }

            IPath parentPath = compFile.getParent().getProjectRelativePath();
            if (!parentPath.isEmpty()) {
                IFolder folder = javaProject.getProject().getFolder(parentPath);
                try {
                    ensureExists(folder);
                } catch (CoreException e) {
                    Activator.getDefault().getLog().log(e.getStatus());
                    model.dispose();
                    continue;
                }
            }

            if (debug.isDebugging())
                debug.trace(String.format("Saving model: %s", compFile.getFullPath())); //$NON-NLS-1$

            model.save();
            model.dispose();
        }

        // track abandoned files (may be garbage)
        if (oldDSKeys != null)
            abandoned.addAll(oldDSKeys);
    }
}

From source file:cideplus.ui.astview.ASTView.java

License:Open Source License

private CompilationUnit createAST(ITypeRoot input, int astLevel, int offset)
        throws JavaModelException, CoreException {
    long startTime;
    long endTime;
    CompilationUnit root;/* w  w  w.  jav a2  s  .  c o m*/

    if ((getCurrentInputKind() == ASTInputKindAction.USE_RECONCILE)) {
        final IProblemRequestor problemRequestor = new IProblemRequestor() { //strange: don't get bindings when supplying null as problemRequestor
            public void acceptProblem(IProblem problem) {
                /*not interested*/}

            public void beginReporting() {
                /*not interested*/}

            public void endReporting() {
                /*not interested*/}

            public boolean isActive() {
                return true;
            }
        };
        WorkingCopyOwner workingCopyOwner = new WorkingCopyOwner() {
            @Override
            public IProblemRequestor getProblemRequestor(ICompilationUnit workingCopy) {
                return problemRequestor;
            }
        };
        ICompilationUnit wc = input.getWorkingCopy(workingCopyOwner, null);
        try {
            int reconcileFlags = ICompilationUnit.FORCE_PROBLEM_DETECTION;
            if (fStatementsRecovery)
                reconcileFlags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY;
            if (fBindingsRecovery)
                reconcileFlags |= ICompilationUnit.ENABLE_BINDINGS_RECOVERY;
            if (fIgnoreMethodBodies)
                reconcileFlags |= ICompilationUnit.IGNORE_METHOD_BODIES;
            startTime = System.currentTimeMillis();
            root = wc.reconcile(getCurrentASTLevel(), reconcileFlags, null, null);
            endTime = System.currentTimeMillis();
        } finally {
            wc.discardWorkingCopy();
        }

    } else if (input instanceof ICompilationUnit && (getCurrentInputKind() == ASTInputKindAction.USE_CACHE)) {
        ICompilationUnit cu = (ICompilationUnit) input;
        startTime = System.currentTimeMillis();
        root = SharedASTProvider.getAST(cu, SharedASTProvider.WAIT_NO, null);
        endTime = System.currentTimeMillis();

    } else {
        ASTParser parser = ASTParser.newParser(astLevel);
        parser.setResolveBindings(fCreateBindings);
        if (input instanceof ICompilationUnit) {
            parser.setSource((ICompilationUnit) input);
        } else {
            parser.setSource((IClassFile) input);
        }
        parser.setStatementsRecovery(fStatementsRecovery);
        parser.setBindingsRecovery(fBindingsRecovery);
        parser.setIgnoreMethodBodies(fIgnoreMethodBodies);
        if (getCurrentInputKind() == ASTInputKindAction.USE_FOCAL) {
            parser.setFocalPosition(offset);
        }
        startTime = System.currentTimeMillis();
        root = (CompilationUnit) parser.createAST(null);
        endTime = System.currentTimeMillis();
    }
    if (root != null) {
        updateContentDescription(input, root, endTime - startTime);
    }
    return root;
}

From source file:com.liferay.blade.eclipse.provider.CUCache.java

License:Open Source License

@SuppressWarnings("unchecked")
private static CompilationUnit createCompilationUnit(String unitName, char[] javaSource) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);

    Map<String, String> options = JavaCore.getOptions();

    JavaCore.setComplianceOptions(JavaCore.VERSION_1_6, options);

    parser.setCompilerOptions(options);/* w  w  w.ja v  a  2s  .  co  m*/

    //setUnitName for resolve bindings
    parser.setUnitName(unitName);

    String[] sources = { "" };
    String[] classpath = { "" };
    //setEnvironment for resolve bindings even if the args is empty
    parser.setEnvironment(classpath, sources, new String[] { "UTF-8" }, true);

    parser.setResolveBindings(true);
    parser.setStatementsRecovery(true);
    parser.setBindingsRecovery(true);
    parser.setSource(javaSource);
    parser.setIgnoreMethodBodies(false);

    return (CompilationUnit) parser.createAST(null);
}

From source file:com.liferay.blade.eclipse.provider.CUCacheJDT.java

License:Open Source License

@SuppressWarnings("unchecked")
private CompilationUnit createCompilationUnit(String unitName, char[] javaSource) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);

    Map<String, String> options = JavaCore.getOptions();

    JavaCore.setComplianceOptions(JavaCore.VERSION_1_6, options);

    parser.setCompilerOptions(options);/*from www . j  a v a 2  s.co m*/

    //setUnitName for resolve bindings
    parser.setUnitName(unitName);

    String[] sources = { "" };
    String[] classpath = { "" };
    //setEnvironment for resolve bindings even if the args is empty
    parser.setEnvironment(classpath, sources, new String[] { "UTF-8" }, true);

    parser.setResolveBindings(true);
    parser.setStatementsRecovery(true);
    parser.setBindingsRecovery(true);
    parser.setSource(javaSource);
    parser.setIgnoreMethodBodies(false);

    return (CompilationUnit) parser.createAST(null);
}

From source file:com.liferay.ide.project.ui.migration.CUCache.java

License:Open Source License

@SuppressWarnings("unchecked")
private static CompilationUnit createCompilationUnit(String unitName, char[] javaSource) {
    ASTParser parser = ASTParser.newParser(AST.JLS2);

    Map<String, String> options = JavaCore.getOptions();

    JavaCore.setComplianceOptions(JavaCore.VERSION_1_6, options);

    parser.setCompilerOptions(options);//from  w w w .  j  av  a  2 s  .c  om

    // setUnitName for resolve bindings
    parser.setUnitName(unitName);

    String[] sources = { "" };
    String[] classpath = { "" };
    // setEnvironment for resolve bindings even if the args is empty
    parser.setEnvironment(classpath, sources, new String[] { "UTF-8" }, true);

    parser.setResolveBindings(true);
    parser.setStatementsRecovery(true);
    parser.setBindingsRecovery(true);
    parser.setSource(javaSource);
    parser.setIgnoreMethodBodies(false);

    return (CompilationUnit) parser.createAST(null);
}

From source file:com.worldline.awltech.i18ntools.editor.data.model.I18NEnumVisitor.java

License:Open Source License

public static I18NEnumVisitor create(ICompilationUnit compilationUnit) {
    I18NEnumVisitor visitor = new I18NEnumVisitor();

    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setIgnoreMethodBodies(true);
    parser.setResolveBindings(true);/*  w ww  .j a va2 s.co  m*/
    parser.setSource(compilationUnit);
    ASTNode createdAST = parser.createAST(new NullProgressMonitor());

    createdAST.accept(visitor);

    return visitor;
}

From source file:de.gebit.integrity.ui.utils.JavadocUtil.java

License:Open Source License

/**
 * Returns the {@link AbstractTypeDeclaration} for the given {@link ICompilationUnit}. This basically parses the
 * given compilation unit into an Abstract Syntax Tree, using the parser provided by the JDT for the job.
 * /*  ww w.  j  av  a  2s  .c  o  m*/
 * @param aCompilationUnit
 *            the compilation unit to parse
 * @return the AST
 */
protected static AbstractTypeDeclaration parseCompilationUnit(ICompilationUnit aCompilationUnit) {
    ASTParser tempParser = ASTParser.newParser(AST.JLS4);
    tempParser.setSource(aCompilationUnit);
    tempParser.setIgnoreMethodBodies(true);
    tempParser.setKind(ASTParser.K_COMPILATION_UNIT);
    tempParser.setCompilerOptions(ASTPARSER_OPTIONS);
    CompilationUnit tempNode = (CompilationUnit) tempParser.createAST(null);

    return (AbstractTypeDeclaration) tempNode.types().get(0);
}

From source file:fr.labri.harmony.rta.junit.jdt.JDTGeneratorRTA.java

License:Open Source License

private boolean generate(String file) {

    if (!this.modifiedUrls.contains(file) && !this.modifiedUrls.isEmpty())
        return false;

    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setEnvironment(classPath, sourcePath, null, true);
    parser.setResolveBindings(true);/*from www.jav  a  2 s.c om*/
    parser.setBindingsRecovery(true);
    parser.setStatementsRecovery(true);
    parser.setIgnoreMethodBodies(false);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    Map<String, String> pOptions = JavaCore.getOptions();
    pOptions.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7);
    pOptions.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7);
    pOptions.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);
    parser.setCompilerOptions(pOptions);

    JDTRequestorRTA req = null;
    String shortPath = file.substring(localPath.length());
    if (!shortPath.startsWith("/"))
        shortPath = "/" + shortPath;

    JavaFile jf = new JavaFile(file, shortPath, null);
    JDTVisitorRTA.currentFile = jf;

    if (file.contains("/test/") || file.contains("/tests/") || file.contains("/test-sources/")
            || file.contains("/testsrc/"))
        req = new JDTRequestorRTA(file, hashes, true);
    else
        req = new JDTRequestorRTA(file, hashes, false);
    parser.createASTs(new String[] { file }, null, new String[] {}, req, null);

    JavaFile j = new JavaFile(JDTVisitorRTA.currentFile.getFullPath(), JDTVisitorRTA.currentFile.getShortPath(),
            JDTVisitorRTA.currentFile.getEnclosedClass());
    JDTVisitorRTA.files.add(j);

    return true;
}

From source file:javadoctest.internal.DocTestExtractor.java

License:Open Source License

public List<ExtractedDocTest> extractExamples(String source) {
    // Fast exit for classes without <pre in their docs. A small contribution to cutting down read time
    if (!source.contains("<pre")) {
        return Collections.EMPTY_LIST;
    }//ww  w .  j  ava2s .  co m

    ASTParser parser = ASTParser.newParser(AST.JLS2);

    parser.setResolveBindings(false);
    parser.setStatementsRecovery(false);
    parser.setBindingsRecovery(false);
    parser.setSource(source.toCharArray());
    parser.setIgnoreMethodBodies(false);

    ASTNode ast = parser.createAST(null);

    final AtomicReference<String> className = new AtomicReference<>();
    final AtomicReference<String> classPkg = new AtomicReference<>();

    final List<String> imports = new LinkedList<>();
    final List<ExtractedDocTest> examples = new ArrayList<>();
    ASTVisitor visitor = new ASTVisitor() {
        @Override
        public boolean visit(ImportDeclaration node) {
            // We collect imports as well,
            imports.add(node.getName().toString());
            return true;
        }

        @Override
        public boolean visit(PackageDeclaration node) {
            classPkg.set(node.getName().toString());
            return true;
        }

        @Override
        public boolean visit(FieldDeclaration node) {
            examples.addAll(extractExamples(imports, classPkg.get(), className.get(),
                    node.fragments().get(0).toString(), node));
            return true;
        }

        @Override
        public boolean visit(MethodDeclaration node) {
            examples.addAll(
                    extractExamples(imports, classPkg.get(), className.get(), node.getName().toString(), node));
            return true;
        }

        @Override
        public boolean visit(TypeDeclaration node) {
            if (className.get() == null) {
                className.set(node.getName().getIdentifier().toString());
            }
            examples.addAll(extractExamples(imports, classPkg.get(), className.get(),
                    node.getName().toString() + " classdoc", node));
            return true;
        }
    };
    ast.accept(visitor);
    return examples;
}

From source file:net.atos.optimus.common.tools.ltk.AbstractImportsManager.java

License:Open Source License

/**
 * Executes the imports process on the file located at the given path, with
 * given contents//from   w ww.ja v  a  2  s  .c  o m
 * 
 * @param filePath
 *            : Destination File Path (used to retrieve project, in order to
 *            get CU's context only)
 * @param initialContents
 *            : Initial Contents
 * @return Updated Contents.
 */
public CharSequence execute(String filePath, CharSequence initialContents) {
    ASTParser parser = ASTParserFactory.INSTANCE.newParser();

    try {

        ICompilationUnit compilationUnit = getCUFromFullPath(filePath);
        if (compilationUnit == null) {
            return initialContents;
        }

        parser.setUnitName(compilationUnit.getResource().getFullPath().removeFileExtension().lastSegment());
        parser.setBindingsRecovery(true);
        parser.setResolveBindings(true);
        parser.setIgnoreMethodBodies(false);
        parser.setStatementsRecovery(true);
        parser.setProject(compilationUnit.getJavaProject());
        parser.setSource(initialContents.toString().toCharArray());

        ASTNode astNode = parser.createAST(new NullProgressMonitor());
        IDocument document = new Document(initialContents.toString().toString());
        if (astNode instanceof CompilationUnit) {
            CompilationUnit domCompilationUnit = (CompilationUnit) astNode;
            domCompilationUnit.recordModifications();
            if (apply(domCompilationUnit)) {
                TextEdit rewrite = domCompilationUnit.rewrite(document, null);
                try {
                    rewrite.apply(document);
                    return document.get();
                } catch (MalformedTreeException e) {
                    Activator.getDefault().logError("Import Creation encountered Exception", e);
                } catch (BadLocationException e) {
                    Activator.getDefault().logError("Import Creation encountered Exception", e);
                }
            }
        }

    } catch (IllegalStateException e) {
        // Workspace is closed
        // Binding resolution will probably not work
    }

    return initialContents;
}