Example usage for org.eclipse.jdt.internal.compiler SourceElementParser parseCompilationUnit

List of usage examples for org.eclipse.jdt.internal.compiler SourceElementParser parseCompilationUnit

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler SourceElementParser parseCompilationUnit.

Prototype

public CompilationUnitDeclaration parseCompilationUnit(ICompilationUnit unit, boolean fullParse,
            IProgressMonitor pm) 

Source Link

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.CompilationUnit.java

License:Open Source License

protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements,
        File underlyingResource) throws JavaModelException {
    CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;

    // ensure buffer is opened
    IBuffer buffer = getBufferManager().getBuffer(CompilationUnit.this);
    if (buffer == null) {
        openBuffer(pm, unitInfo); // open buffer independently from the info, since we are building the info
    }//from   w  ww.  ja v  a  2 s  .co  m

    // generate structure and compute syntax problems if needed
    CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo,
            newElements, manager);
    JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
    IJavaProject project = getJavaProject();

    boolean createAST;
    boolean resolveBindings;
    int reconcileFlags;
    HashMap problems;
    if (info instanceof ASTHolderCUInfo) {
        ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info;
        createAST = astHolder.astLevel != NO_AST;
        resolveBindings = astHolder.resolveBindings;
        reconcileFlags = astHolder.reconcileFlags;
        problems = astHolder.problems;
    } else {
        createAST = false;
        resolveBindings = true;
        reconcileFlags = 0;
        problems = null;
    }
    boolean computeProblems = false;
    //   boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null && JavaProject
    //         .hasJavaNature(project.getProject());
    IProblemFactory problemFactory = new DefaultProblemFactory();
    Map options = project == null ? JavaCore.getOptions() : project.getOptions(true);
    if (!computeProblems) {
        // disable task tags checking to speed up parsing
        options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
    }
    CompilerOptions compilerOptions = new CompilerOptions(options);
    compilerOptions.ignoreMethodBodies = (reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
    SourceElementParser parser = new SourceElementParser(requestor, problemFactory, compilerOptions,
            true/*report local declarations*/,
            !createAST /*optimize string literals only if not creating a DOM AST*/);
    parser.reportOnlyOneSyntaxError = !computeProblems;
    parser.setMethodsFullRecovery(true);
    parser.setStatementsRecovery((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);

    if (!computeProblems && !resolveBindings && !createAST) // disable javadoc parsing if not computing problems, not resolving and not creating ast
        parser.javadocParser.checkDocComment = false;
    requestor.parser = parser;

    // update timestamp (might be IResource.NULL_STAMP if original does not exist)
    if (underlyingResource == null) {
        underlyingResource = resource();
    }
    // underlying resource is null in the case of a working copy on a class file in a jar
    if (underlyingResource != null)
        unitInfo.timestamp = (underlyingResource).lastModified();

    // compute other problems if needed
    CompilationUnitDeclaration compilationUnitDeclaration = null;
    CompilationUnit source = cloneCachingContents();
    try {
        if (computeProblems) {
            //         if (problems == null) {
            //            // report problems to the problem requestor
            //            problems = new HashMap();
            //            compilationUnitDeclaration = CompilationUnitProblemFinder
            //                  .process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
            //            try {
            //               perWorkingCopyInfo.beginReporting();
            //               for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) {
            //                  CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror.next();
            //                  if (categorizedProblems == null) continue;
            //                  for (int i = 0, length = categorizedProblems.length; i < length; i++) {
            //                     perWorkingCopyInfo.acceptProblem(categorizedProblems[i]);
            //                  }
            //               }
            //            } finally {
            //               perWorkingCopyInfo.endReporting();
            //            }
            //         } else {
            //            // collect problems
            //            compilationUnitDeclaration = CompilationUnitProblemFinder
            //                  .process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
            //         }
        } else {
            compilationUnitDeclaration = parser.parseCompilationUnit(source,
                    true /*full parse to find local elements*/, pm);
        }

        if (createAST) {
            //         int astLevel = ((ASTHolderCUInfo) info).astLevel;
            //         org.eclipse.jdt.core.dom.CompilationUnit cu = AST
            //               .convertCompilationUnit(astLevel, compilationUnitDeclaration, options, computeProblems, source, reconcileFlags, pm);
            //         ((ASTHolderCUInfo) info).ast = cu;
        }
    } finally {
        if (compilationUnitDeclaration != null) {
            unitInfo.hasFunctionalTypes = compilationUnitDeclaration.hasFunctionalTypes();
            compilationUnitDeclaration.cleanUp();
        }
    }

    return unitInfo.isStructureKnown();
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.indexing.SourceIndexer.java

License:Open Source License

public void indexDocument() {
    // Create a new Parser
    SourceIndexerRequestor requestor = new SourceIndexerRequestor(this);
    String documentPath = this.document.getPath();
    SourceElementParser parser = this.document.getParser();
    if (parser == null) {
        //todo change this code
        IPath path = new Path(documentPath);
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0));
        parser = JavaModelManager.getJavaModelManager().indexManager
                .getSourceElementParser(JavaCore.create(project), requestor);
    } else {//from   w  w w.j a v  a  2 s. co m
        parser.setRequestor(requestor);
    }

    // Launch the parser
    char[] source = null;
    char[] name = null;
    try {
        source = this.document.getCharContents();
        name = documentPath.toCharArray();
    } catch (Exception e) {
        // ignore
    }
    if (source == null || name == null)
        return; // could not retrieve document info (e.g. resource was discarded)
    CompilationUnit compilationUnit = new CompilationUnit(source, name);
    try {
        parser.parseCompilationUnit(compilationUnit, true/*full parse*/, null/*no progress*/);
    } catch (Exception e) {
        if (JobManager.VERBOSE) {
            e.printStackTrace();
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.SourceMapper.java

License:Open Source License

/**
 * Maps the given source code to the given binary type and its children.
 * If a non-null java element is passed, finds the name range for the
 * given java element without storing it.
 *///  w w w  . j a v a 2s  . com
public synchronized ISourceRange mapSource(IType type, char[] contents, IBinaryType info,
        IJavaElement elementToFind) {

    this.binaryType = (BinaryType) type;

    // check whether it is already mapped
    if (this.sourceRanges.get(type) != null)
        return (elementToFind != null) ? getNameRange(elementToFind) : null;

    this.importsTable.remove(this.binaryType);
    this.importsCounterTable.remove(this.binaryType);
    this.searchedElement = elementToFind;
    this.types = new IType[1];
    this.typeDeclarationStarts = new int[1];
    this.typeNameRanges = new SourceRange[1];
    this.typeModifiers = new int[1];
    this.typeDepth = -1;
    this.memberDeclarationStart = new int[1];
    this.memberName = new String[1];
    this.memberNameRange = new SourceRange[1];
    this.methodParameterTypes = new char[1][][];
    this.methodParameterNames = new char[1][][];
    this.anonymousCounter = 0;

    HashMap oldSourceRanges = null;
    if (elementToFind != null) {
        oldSourceRanges = (HashMap) this.sourceRanges.clone();
    }
    try {
        IProblemFactory factory = new DefaultProblemFactory();
        SourceElementParser parser = null;
        this.anonymousClassName = 0;
        if (info == null) {
            try {
                info = (IBinaryType) this.binaryType.getElementInfo();
            } catch (JavaModelException e) {
                return null;
            }
        }
        boolean isAnonymousClass = info.isAnonymous();
        char[] fullName = info.getName();
        if (isAnonymousClass) {
            String eltName = this.binaryType.getParent().getElementName();
            eltName = eltName.substring(eltName.lastIndexOf('$') + 1, eltName.length());
            try {
                this.anonymousClassName = Integer.parseInt(eltName);
            } catch (NumberFormatException e) {
                // ignore
            }
        }
        boolean doFullParse = hasToRetrieveSourceRangesForLocalClass(fullName);
        parser = new SourceElementParser(this, factory, new CompilerOptions(this.options), doFullParse,
                true/*optimize string literals*/);
        parser.javadocParser.checkDocComment = false; // disable javadoc parsing
        IJavaElement javaElement = this.binaryType.getCompilationUnit();
        if (javaElement == null)
            javaElement = this.binaryType.getParent();
        parser.parseCompilationUnit(
                new BasicCompilationUnit(contents, null, this.binaryType.sourceFileName(info), javaElement),
                doFullParse, null/*no progress*/);
        if (elementToFind != null) {
            ISourceRange range = getNameRange(elementToFind);
            return range;
        } else {
            return null;
        }
    } finally {
        if (elementToFind != null) {
            this.sourceRanges = oldSourceRanges;
        }
        this.binaryType = null;
        this.searchedElement = null;
        this.types = null;
        this.typeDeclarationStarts = null;
        this.typeNameRanges = null;
        this.typeDepth = -1;
    }
}

From source file:lombok.RunTestsViaEclipse.java

License:Open Source License

@Override
public void transformCode(final StringBuilder messages, StringWriter result, File file) throws Throwable {
    // setup parser and compiler
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH);
    final INameEnvironment nameEnvironment = new LombokTestNameEnvironment();
    final ICompilerRequestor compilerRequestor = new LombokTestCompilerRequestor();
    final ISourceElementRequestor sourceElementRequestor = new LombokTestSourceElementRequestor();
    final CompilerOptions options = ecjCompilerOptions();
    final LombokTestCompiler jdtCompiler = new LombokTestCompiler(nameEnvironment, policy, options,
            compilerRequestor, problemFactory);
    final SourceElementParser parser = new SourceElementParser(sourceElementRequestor, problemFactory, options,
            true, true);/*w  w  w . ja  va2s  .c o m*/

    // read the file
    final String source = readFile(file);
    final CompilationUnit sourceUnit = new CompilationUnit(source.toCharArray(), file.getName(), "UTF-8");

    // parse
    final CompilationUnitDeclaration cud = parser.parseCompilationUnit(sourceUnit, true, null);
    // build
    jdtCompiler.lookupEnvironment.buildTypeBindings(cud, null);
    jdtCompiler.lookupEnvironment.completeTypeBindings(cud, true);
    // process
    if (cud.scope != null)
        cud.scope.verifyMethods(jdtCompiler.lookupEnvironment.methodVerifier());

    // handle problems
    final CategorizedProblem[] problems = cud.compilationResult.getAllProblems();

    if (problems != null)
        for (CategorizedProblem p : problems) {
            messages.append(String.format("%d %s %s\n", p.getSourceLineNumber(),
                    p.isError() ? "error" : p.isWarning() ? "warning" : "unknown", p.getMessage()));
        }

    // set transformed code
    result.append(cud.toString());
}

From source file:org.codehaus.jdt.groovy.model.GroovyCompilationUnit.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes", "nls", "restriction" })
@Override//from   w ww.  j a v  a2s .c o  m
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements,
        IResource underlyingResource) throws JavaModelException {
    try {
        depth.set(depth.get() + 1);

        // if (!isOnBuildPath()) {
        // return false;
        // }

        if (GroovyLogManager.manager.hasLoggers()) {
            GroovyLogManager.manager.log(TraceCategory.COMPILER, "Build Structure starting for " + this.name);
            GroovyLogManager.manager
                    .logStart("Build structure: " + name + " : " + Thread.currentThread().getName());
        }

        CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;

        // ensure buffer is opened
        IBuffer buffer = getBufferManager().getBuffer(this);
        if (buffer == null) {
            openBuffer(pm, unitInfo); // open buffer independently from the
            // info, since we are building the info
        }

        // generate structure and compute syntax problems if needed
        GroovyCompilationUnitStructureRequestor requestor = new GroovyCompilationUnitStructureRequestor(this,
                unitInfo, newElements);
        JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
        JavaProject project = (JavaProject) getJavaProject();

        // determine what kind of buildStructure we are doing
        boolean createAST;
        int reconcileFlags;
        boolean resolveBindings;
        HashMap problems;
        if (info instanceof ASTHolderCUInfo) {
            ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info;
            createAST = ((Integer) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "astLevel", //$NON-NLS-1$
                    astHolder)).intValue() != NO_AST;
            resolveBindings = ((Boolean) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class,
                    "resolveBindings", astHolder)).booleanValue();
            reconcileFlags = ((Integer) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "reconcileFlags", //$NON-NLS-1$
                    astHolder)).intValue();
            problems = (HashMap) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "problems", astHolder);
        } else {
            createAST = false;
            resolveBindings = false;
            reconcileFlags = 0;
            problems = null;
        }

        boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null
                && JavaProject.hasJavaNature(project.getProject());
        IProblemFactory problemFactory = new DefaultProblemFactory();

        // compiler options
        Map<String, String> options = (project == null ? JavaCore.getOptions() : project.getOptions(true));
        if (!computeProblems) {
            // disable task tags checking to speed up parsing
            options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
        }

        // FIXASC deal with the case of project==null to reduce duplication in this next line and call to setGroovyClasspath
        // Required for Groovy, but not for Java
        options.put(CompilerOptions.OPTIONG_BuildGroovyFiles, CompilerOptions.ENABLED);

        CompilerOptions compilerOptions = new CompilerOptions(options);

        if (project != null) {
            CompilerUtils.setGroovyClasspath(compilerOptions, project);
        }

        // Required for Groovy, but not for Java
        ProblemReporter reporter = new ProblemReporter(new GroovyErrorHandlingPolicy(!computeProblems),
                compilerOptions, new DefaultProblemFactory());

        SourceElementParser parser = new MultiplexingSourceElementRequestorParser(reporter, requestor, /*
                                                                                                       * not needed if
                                                                                                       * computing groovy only
                                                                                                       */
                problemFactory, compilerOptions, true/* report local declarations */, !createAST /*
                                                                                                 * optimize string literals only if not
                                                                                                 * creating a DOM AST
                                                                                                 */);
        parser.reportOnlyOneSyntaxError = !computeProblems;
        // maybe not needed for groovy, but I don't want to find out.
        parser.setMethodsFullRecovery(true);
        parser.setStatementsRecovery((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);

        if (!computeProblems && !resolveBindings && !createAST) // disable javadoc parsing if not computing problems, not
            // resolving
            // and not creating ast
            parser.javadocParser.checkDocComment = false;
        requestor.setParser(parser);

        // update timestamp (might be IResource.NULL_STAMP if original does not
        // exist)
        if (underlyingResource == null) {
            underlyingResource = getResource();
        }
        // underlying resource is null in the case of a working copy on a class
        // file in a jar
        if (underlyingResource != null) {
            ReflectionUtils.setPrivateField(CompilationUnitElementInfo.class, "timestamp", unitInfo, //$NON-NLS-1$
                    underlyingResource.getModificationStamp());
        }

        GroovyCompilationUnitDeclaration compilationUnitDeclaration = null;
        CompilationUnit source = cloneCachingContents();
        try {
            // GROOVY
            // note that this is a slightly different approach than taken by super.buildStructure
            // in super.buildStructure, there is a test here to see if computeProblems is true.
            // if false, then parser.parserCompilationUnit is called.
            // this will not work for Groovy because we need to ensure bindings are resolved
            // for many operations (content assist and code select) to work.
            // So, for groovy, always use CompilationUnitProblemFinder.process and then process problems
            // separately only if necessary
            // addendum (GRECLIPSE-942). The testcase for that bug includes a package with 200
            // types in that refer to each other in a chain, through field references. If a reconcile
            // references the top of the chain we can go through a massive number of recursive calls into
            // this buildStructure for each one. The 'full' parse (with bindings) is only required for
            // the top most (regardless of the computeProblems setting) and so we track how many recursive
            // calls we have made - if we are at depth 2 we do what JDT was going to do (the quick thing).
            if (computeProblems || depth.get() < 2) {
                if (problems == null) {
                    // report problems to the problem requestor
                    problems = new HashMap();
                    compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) CompilationUnitProblemFinder
                            .process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
                    if (computeProblems) {
                        try {
                            perWorkingCopyInfo.beginReporting();
                            for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) {
                                CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror
                                        .next();
                                if (categorizedProblems == null)
                                    continue;
                                for (int i = 0, length = categorizedProblems.length; i < length; i++) {
                                    perWorkingCopyInfo.acceptProblem(categorizedProblems[i]);
                                }
                            }
                        } finally {
                            perWorkingCopyInfo.endReporting();
                        }
                    }
                } else {
                    // collect problems
                    compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) CompilationUnitProblemFinder
                            .process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
                }
            } else {
                compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) parser
                        .parseCompilationUnit(source, true /* full parse to find local elements */, pm);
            }

            // GROOVY
            // if this is a working copy, then we have more work to do
            maybeCacheModuleNode(perWorkingCopyInfo, compilationUnitDeclaration);

            // create the DOM AST from the compiler AST
            if (createAST) {
                org.eclipse.jdt.core.dom.CompilationUnit ast;
                try {
                    ast = AST.convertCompilationUnit(AST.JLS3, compilationUnitDeclaration, options,
                            computeProblems, source, reconcileFlags, pm);
                    ReflectionUtils.setPrivateField(ASTHolderCUInfo.class, "ast", info, ast); //$NON-NLS-1$
                } catch (OperationCanceledException e) {
                    // catch this exception so as to not enter the catch(RuntimeException e) below
                    // might need to do the same for AbortCompilation
                    throw e;
                } catch (IllegalArgumentException e) {
                    // if necessary, we can do some better reporting here.
                    Util.log(e, "Problem with build structure: Offset for AST node is incorrect in " //$NON-NLS-1$
                            + this.getParent().getElementName() + "." + getElementName()); //$NON-NLS-1$
                } catch (Exception e) {
                    Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
                }
            }
        } catch (OperationCanceledException e) {
            // catch this exception so as to not enter the catch(RuntimeException e) below
            // might need to do the same for AbortCompilation
            throw e;
        } catch (JavaModelException e) {
            // GRECLIPSE-1480 don't log element does not exist exceptions. since this could occur when element is in a non-java
            // project
            if (e.getStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST
                    || this.getJavaProject().exists()) {
                Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
            }
        } catch (Exception e) {
            // GROOVY: The groovy compiler does not handle broken code well in many situations
            // use this general catch clause so that exceptions thrown by broken code
            // do not bubble up the stack.
            Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
        } finally {
            if (compilationUnitDeclaration != null) {
                compilationUnitDeclaration.cleanUp();
            }
        }
        return unitInfo.isStructureKnown();
    } finally {
        depth.set(depth.get() - 1);
        if (GroovyLogManager.manager.hasLoggers()) {
            GroovyLogManager.manager.logEnd(
                    "Build structure: " + name + " : " + Thread.currentThread().getName(),
                    TraceCategory.COMPILER);
        }
    }
}

From source file:org.eclipse.che.jdt.internal.core.search.indexing.SourceIndexer.java

License:Open Source License

public void indexDocument() {
    // Create a new Parser
    String documentPath = this.document.getPath();
    SourceElementParser parser = this.document.getParser();
    if (parser == null) {
        //         IPath path = new Path(documentPath);
        //         IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0));
        //         parser = JavaModelManager.getJavaModelManager().indexManager.getSourceElementParser(JavaCore.create(project), requestor);
        parser = indexManager.getSourceElementParser(javaProject, requestor);
    } else {/*w w w . ja  v  a  2s  . c o  m*/
        parser.setRequestor(requestor);
    }

    // Launch the parser
    char[] source = null;
    char[] name = null;
    try {
        source = this.document.getCharContents();
        name = documentPath.toCharArray();
    } catch (Exception e) {
        // ignore
    }
    if (source == null || name == null)
        return; // could not retrieve document info (e.g. resource was discarded)
    this.compilationUnit = new CompilationUnit(source, name);
    try {
        if (parser.parseCompilationUnit(this.compilationUnit, true, null).hasFunctionalTypes())
            this.document.requireIndexingResolvedDocument();
    } catch (Exception e) {
        if (JobManager.VERBOSE) {
            e.printStackTrace();
        }
    }
}

From source file:org.eclipse.jdt.internal.core.CompilationUnit.java

License:Open Source License

protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements,
        IResource underlyingResource) throws JavaModelException {
    CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;

    // ensure buffer is opened
    IBuffer buffer = getBufferManager().getBuffer(CompilationUnit.this);
    if (buffer == null) {
        openBuffer(pm, unitInfo); // open buffer independently from the info, since we are building the info
    }//from w  w  w  .  jav  a2s. c om

    // generate structure and compute syntax problems if needed
    CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo,
            newElements);
    JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
    IJavaProject project = getJavaProject();

    boolean createAST;
    boolean resolveBindings;
    int reconcileFlags;
    HashMap problems;
    if (info instanceof ASTHolderCUInfo) {
        ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info;
        createAST = astHolder.astLevel != NO_AST;
        resolveBindings = astHolder.resolveBindings;
        reconcileFlags = astHolder.reconcileFlags;
        problems = astHolder.problems;
    } else {
        createAST = false;
        resolveBindings = false;
        reconcileFlags = 0;
        problems = null;
    }

    boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null
            && JavaProject.hasJavaNature(project.getProject());
    IProblemFactory problemFactory = new DefaultProblemFactory();
    Map options = project == null ? JavaCore.getOptions() : project.getOptions(true);
    if (!computeProblems) {
        // disable task tags checking to speed up parsing
        options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
    }
    CompilerOptions compilerOptions = new CompilerOptions(options);
    compilerOptions.ignoreMethodBodies = (reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
    SourceElementParser parser = new SourceElementParser(requestor, problemFactory, compilerOptions,
            true/*report local declarations*/,
            !createAST /*optimize string literals only if not creating a DOM AST*/);
    parser.reportOnlyOneSyntaxError = !computeProblems;
    parser.setMethodsFullRecovery(true);
    parser.setStatementsRecovery((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);

    if (!computeProblems && !resolveBindings && !createAST) // disable javadoc parsing if not computing problems, not resolving and not creating ast
        parser.javadocParser.checkDocComment = false;
    requestor.parser = parser;

    // update timestamp (might be IResource.NULL_STAMP if original does not exist)
    if (underlyingResource == null) {
        underlyingResource = getResource();
    }
    // underlying resource is null in the case of a working copy on a class file in a jar
    if (underlyingResource != null)
        unitInfo.timestamp = ((IFile) underlyingResource).getModificationStamp();

    // compute other problems if needed
    CompilationUnitDeclaration compilationUnitDeclaration = null;
    CompilationUnit source = cloneCachingContents();
    try {
        if (computeProblems) {
            if (problems == null) {
                // report problems to the problem requestor
                problems = new HashMap();
                compilationUnitDeclaration = CompilationUnitProblemFinder.process(source, parser, this.owner,
                        problems, createAST, reconcileFlags, pm);
                try {
                    perWorkingCopyInfo.beginReporting();
                    for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) {
                        CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror.next();
                        if (categorizedProblems == null)
                            continue;
                        for (int i = 0, length = categorizedProblems.length; i < length; i++) {
                            perWorkingCopyInfo.acceptProblem(categorizedProblems[i]);
                        }
                    }
                } finally {
                    perWorkingCopyInfo.endReporting();
                }
            } else {
                // collect problems
                compilationUnitDeclaration = CompilationUnitProblemFinder.process(source, parser, this.owner,
                        problems, createAST, reconcileFlags, pm);
            }
        } else {
            compilationUnitDeclaration = parser.parseCompilationUnit(source,
                    true /*full parse to find local elements*/, pm);
        }

        if (createAST) {
            int astLevel = ((ASTHolderCUInfo) info).astLevel;
            org.eclipse.jdt.core.dom.CompilationUnit cu = AST.convertCompilationUnit(astLevel,
                    compilationUnitDeclaration, options, computeProblems, source, reconcileFlags, pm);
            ((ASTHolderCUInfo) info).ast = cu;
        }
    } finally {
        if (compilationUnitDeclaration != null) {
            compilationUnitDeclaration.cleanUp();
        }
    }

    return unitInfo.isStructureKnown();
}

From source file:org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.java

License:Open Source License

public static CompilationUnitDeclaration process(CompilationUnit unitElement, SourceElementParser parser,
        WorkingCopyOwner workingCopyOwner, HashMap problems, boolean creatingAST, int reconcileFlags,
        IProgressMonitor monitor) throws JavaModelException {

    JavaProject project = (JavaProject) unitElement.getJavaProject();
    CancelableNameEnvironment environment = null;
    CancelableProblemFactory problemFactory = null;
    CompilationUnitProblemFinder problemFinder = null;
    CompilationUnitDeclaration unit = null;
    try {//from   www  . ja  v a 2  s . c  o m
        environment = new CancelableNameEnvironment(project, workingCopyOwner, monitor);
        problemFactory = new CancelableProblemFactory(monitor);
        CompilerOptions compilerOptions = getCompilerOptions(project.getOptions(true), creatingAST,
                ((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0));
        boolean ignoreMethodBodies = (reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
        compilerOptions.ignoreMethodBodies = ignoreMethodBodies;
        // GROOVY start
        // options fetched prior to building problem finder then configured based on project
        CompilerUtils.configureOptionsBasedOnNature(compilerOptions, project);
        // GROOVY end
        problemFinder = new CompilationUnitProblemFinder(environment, getHandlingPolicy(), compilerOptions,
                getRequestor(), problemFactory);
        boolean analyzeAndGenerateCode = true;
        if (ignoreMethodBodies) {
            analyzeAndGenerateCode = false;
        }
        try {
            if (parser != null) {
                problemFinder.parser = parser;
                unit = parser.parseCompilationUnit(unitElement, true/*full parse*/, monitor);
                problemFinder.resolve(unit, unitElement, true, // verify methods
                        analyzeAndGenerateCode, // analyze code
                        analyzeAndGenerateCode); // generate code
            } else {
                unit = problemFinder.resolve(unitElement, true, // verify methods
                        analyzeAndGenerateCode, // analyze code
                        analyzeAndGenerateCode); // generate code
            }
        } catch (AbortCompilation e) {
            problemFinder.handleInternalException(e, unit);
        }
        if (unit != null) {
            CompilationResult unitResult = unit.compilationResult;
            CategorizedProblem[] unitProblems = unitResult.getProblems();
            int length = unitProblems == null ? 0 : unitProblems.length;
            if (length > 0) {
                CategorizedProblem[] categorizedProblems = new CategorizedProblem[length];
                System.arraycopy(unitProblems, 0, categorizedProblems, 0, length);
                problems.put(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, categorizedProblems);
            }
            unitProblems = unitResult.getTasks();
            length = unitProblems == null ? 0 : unitProblems.length;
            if (length > 0) {
                CategorizedProblem[] categorizedProblems = new CategorizedProblem[length];
                System.arraycopy(unitProblems, 0, categorizedProblems, 0, length);
                problems.put(IJavaModelMarker.TASK_MARKER, categorizedProblems);
            }
            if (NameLookup.VERBOSE) {
                System.out.println(
                        Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " //$NON-NLS-1$
                                + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$
                System.out.println(
                        Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " //$NON-NLS-1$
                                + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$
            }
        }
    } catch (OperationCanceledException e) {
        // catch this exception so as to not enter the catch(RuntimeException e) below
        throw e;
    } catch (RuntimeException e) {
        // avoid breaking other tools due to internal compiler failure (40334)
        String lineDelimiter = unitElement.findRecommendedLineSeparator();
        StringBuffer message = new StringBuffer("Exception occurred during problem detection:"); //$NON-NLS-1$
        message.append(lineDelimiter);
        message.append(
                "----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$
        message.append(lineDelimiter);
        message.append(unitElement.getSource());
        message.append(lineDelimiter);
        message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$
        Util.log(e, message.toString());
        throw new JavaModelException(e, IJavaModelStatusConstants.COMPILER_FAILURE);
    } finally {
        if (environment != null)
            environment.setMonitor(null); // don't hold a reference to this external object
        if (problemFactory != null)
            problemFactory.monitor = null; // don't hold a reference to this external object
        // NB: unit.cleanUp() is done by caller
        if (problemFinder != null && !creatingAST)
            problemFinder.lookupEnvironment.reset();
    }
    return unit;
}

From source file:org.eclipse.jdt.internal.core.SourceMapper.java

License:Open Source License

/**
 * Maps the given source code to the given binary type and its children.
 * If a non-null java element is passed, finds the name range for the
 * given java element without storing it.
 *///from  ww  w.j  av  a 2  s .  c o  m
public synchronized ISourceRange mapSource(IType type, char[] contents, IBinaryType info,
        IJavaElement elementToFind) {

    this.binaryType = (BinaryType) type;

    // check whether it is already mapped
    if (this.sourceRanges.get(type) != null)
        return (elementToFind != null) ? getNameRange(elementToFind) : null;

    this.importsTable.remove(this.binaryType);
    this.importsCounterTable.remove(this.binaryType);
    this.searchedElement = elementToFind;
    this.types = new IType[1];
    this.typeDeclarationStarts = new int[1];
    this.typeNameRanges = new SourceRange[1];
    this.typeModifiers = new int[1];
    this.typeDepth = -1;
    this.memberDeclarationStart = new int[1];
    this.memberName = new String[1];
    this.memberNameRange = new SourceRange[1];
    this.methodParameterTypes = new char[1][][];
    this.methodParameterNames = new char[1][][];
    this.anonymousCounter = 0;

    HashMap oldSourceRanges = null;
    if (elementToFind != null) {
        oldSourceRanges = (HashMap) this.sourceRanges.clone();
    }
    try {
        IProblemFactory factory = new DefaultProblemFactory();
        SourceElementParser parser = null;
        this.anonymousClassName = 0;
        if (info == null) {
            try {
                info = (IBinaryType) this.binaryType.getElementInfo();
            } catch (JavaModelException e) {
                return null;
            }
        }
        boolean isAnonymousClass = info.isAnonymous();
        char[] fullName = info.getName();
        if (isAnonymousClass) {
            String eltName = this.binaryType.getParent().getElementName();
            eltName = eltName.substring(eltName.lastIndexOf('$') + 1, eltName.length());
            try {
                this.anonymousClassName = Integer.parseInt(eltName);
            } catch (NumberFormatException e) {
                // ignore
            }
        }
        boolean doFullParse = hasToRetrieveSourceRangesForLocalClass(fullName);
        // GROOVY start
        /* old {
        parser = new SourceElementParser(this, factory, new CompilerOptions(this.options), doFullParse, true/*optimize string literals..);
        } new */
        parser = LanguageSupportFactory.getSourceElementParser(this, factory, new CompilerOptions(this.options),
                doFullParse, true/*optimize string literals*/, true);
        // GROOVY end
        parser.javadocParser.checkDocComment = false; // disable javadoc parsing
        IJavaElement javaElement = this.binaryType.getCompilationUnit();
        if (javaElement == null)
            javaElement = this.binaryType.getParent();
        parser.parseCompilationUnit(
                new BasicCompilationUnit(contents, null, this.binaryType.sourceFileName(info), javaElement),
                doFullParse, null/*no progress*/);
        // GROOVY start
        // if this is an interesting file in an interesting project,
        // then filter out all binary members that do not have a direct
        // mapping to the source
        IProject project = javaElement.getJavaProject().getProject();
        if (LanguageSupportFactory.isInterestingProject(project)
                && LanguageSupportFactory.isInterestingSourceFile(this.binaryType.getSourceFileName(info))) {
            LanguageSupportFactory.filterNonSourceMembers(this.binaryType);
        }

        // GROOVY end
        if (elementToFind != null) {
            ISourceRange range = getNameRange(elementToFind);
            return range;
        } else {
            return null;
        }
    } finally {
        if (elementToFind != null) {
            this.sourceRanges = oldSourceRanges;
        }
        this.binaryType = null;
        this.searchedElement = null;
        this.types = null;
        this.typeDeclarationStarts = null;
        this.typeNameRanges = null;
        this.typeDepth = -1;
    }
}

From source file:org.eclipse.objectteams.otdt.tests.compiler.smap.AbstractSourceMapGeneratorTest.java

License:Open Source License

public boolean parseAndCompile(org.eclipse.jdt.core.ICompilationUnit[] units,
        HashMap<String, int[]> methodLineNumbers, String[] classPaths, String outputPath)
        throws JavaModelException {
    CompilerOptions options = getCompilerOptions();
    SourceElementParser parser = new SourceElementParser(this, new DefaultProblemFactory(Locale.getDefault()),
            options, false, false);// w w  w.  j a  va  2  s .c om
    ICompilationUnit[] cUnits = new ICompilationUnit[units.length];

    for (int idx = 0; idx < units.length; idx++) {
        org.eclipse.jdt.core.ICompilationUnit unit = units[idx];

        String unit_src = unit.getSource();
        IResource unit_res = unit.getCorrespondingResource();
        String unit_fileName = unit_res.toString();
        char[] unit_source = unit_src.toCharArray();
        ICompilationUnit unit_sourceUnit = new CompilationUnit(unit_source, unit_fileName, null);

        CompilationUnitDeclaration cuDecl = parser.parseCompilationUnit(unit_sourceUnit, true, null);

        if (cuDecl.hasErrors()) {
            // approximated error reporting:
            String expectedErrorlog = "Filename : L/JSR-045/src/" + unit_fileName + "\n" + "COMPILED type(s) "
                    + "to be filled in\n" + "No REUSED BINARY type\n" + "No PROBLEM";
            String actualErrorlog = cuDecl.compilationResult().toString();
            assertEquals("COMPILATION FAILED. Errorlog should be empty.", expectedErrorlog, actualErrorlog);
            return false;
        }

        cUnits[idx] = unit_sourceUnit;
    }

    Requestor requestor = new Requestor(false, null, /*no custom requestor */
            false, /* show category */
            false /* show warning token*/, methodLineNumbers);
    if (outputPath != null) {
        requestor.outputPath = outputPath;
        File outDir = new File(outputPath);
        if (!outDir.exists())
            outDir.mkdir();
    }

    CustomizedCompiler batchCompiler;
    try {
        batchCompiler = new CustomizedCompiler(getNameEnvironment(new String[] {}, classPaths),
                getErrorHandlingPolicy(), options, requestor, getProblemFactory());
    } catch (IOException ioex) {
        throw new JavaModelException(ioex, IJavaModelStatusConstants.INVALID_CLASSPATH);
    }

    batchCompiler.addCallBack(this);

    batchCompiler.compile(cUnits); // compile all files together

    boolean hasErrors = requestor.hasErrors;

    //errorlog contains errore and warnings, skip warnings
    if (hasErrors) {
        String expectedErrorlog = "";
        String actualErrorlog = requestor.problemLog;
        assertEquals("COMPILATION FAILED. Errorlog should be empty.", expectedErrorlog, actualErrorlog);
    }

    if (methodLineNumbers != null)
        requestor.checkAllLineNumbersSeen();

    return !hasErrors;
}