Example usage for org.eclipse.jdt.internal.compiler.ast CompilationUnitDeclaration cleanUp

List of usage examples for org.eclipse.jdt.internal.compiler.ast CompilationUnitDeclaration cleanUp

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.ast CompilationUnitDeclaration cleanUp.

Prototype

public void cleanUp() 

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
    }//w w w.  j a v a2  s  .c o 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:edu.tum.cs.conqat.inspection.sampling.RandomCodeSampleStrategy.java

License:Apache License

/**
 * Finds all identifiers by visiting the compiled javaClassElements by an
 * {@link IdentifierVisitor}./*from  ww w  .  j  a  va  2s. c  o  m*/
 */
private List<Sample> getIdentifierSamples(List<IJavaElement> javaClassElements) throws ConQATException {
    List<Sample> samples = new ArrayList<Sample>();
    for (IJavaElement element : javaClassElements) {
        CompilationUnitDeclaration unitDeclaration = JavaLibrary.getEcjAST(element)
                .getCompilationUnitDeclaration();
        ASTVisitor visitor = new IdentifierVisitor();
        unitDeclaration.traverse(visitor, unitDeclaration.scope);
        unitDeclaration.cleanUp();
        String sourcePath = element.getLocation();
        for (ASTNode node : foundASTNodes) {
            StringBuffer buffer = new StringBuffer();
            node.print(0, buffer);
            String name = buffer.toString();
            Sample sample = CmFactory.eINSTANCE.createSample();
            sample.setName(name);
            sample.setSourcePath(sourcePath);
            sample.setSourceStart(node.sourceStart);
            sample.setSourceEnd(node.sourceEnd + 1);
            sample.setPackagePath(element.getId());
            samples.add(sample);
        }
        foundASTNodes.clear();
    }
    return samples;
}

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

License:Open Source License

public org.eclipse.jdt.core.dom.CompilationUnit makeConsistent(CompilationUnit workingCopy)
        throws JavaModelException {
    if (!workingCopy.isConsistent()) {
        // make working copy consistent
        if (this.problems == null)
            this.problems = new HashMap();
        this.resolveBindings = this.requestorIsActive;
        this.ast = workingCopy.makeConsistent(this.astLevel, this.resolveBindings, this.reconcileFlags,
                this.problems, this.progressMonitor);
        this.deltaBuilder.buildDeltas();
        if (this.ast != null && this.deltaBuilder.delta != null)
            this.deltaBuilder.delta.changedAST(this.ast);
        return this.ast;
    }/* w w w.j a  v  a  2  s . c  o  m*/
    if (this.ast != null)
        return this.ast; // no need to recompute AST if known already

    CompilationUnitDeclaration unit = null;
    try {
        JavaModelManager.getJavaModelManager().abortOnMissingSource.set(Boolean.TRUE);
        CompilationUnit source = workingCopy.cloneCachingContents();
        // find problems if needed
        if (JavaProject.hasJavaNature(workingCopy.getJavaProject().getProject())
                && (this.reconcileFlags & ICompilationUnit.FORCE_PROBLEM_DETECTION) != 0) {
            this.resolveBindings = this.requestorIsActive;
            if (this.problems == null)
                this.problems = new HashMap();
            unit = CompilationUnitProblemFinder.process(source, this.workingCopyOwner, this.problems,
                    this.astLevel != ICompilationUnit.NO_AST/* creating AST if level is not NO_AST */,
                    this.reconcileFlags, this.progressMonitor);
            // GROOVY cache the ModuleNode in the ModuleNodeMapper
            if (unit instanceof GroovyCompilationUnitDeclaration) {
                // should always be true
                ModuleNodeMapper.getInstance().maybeCacheModuleNode(workingCopy.getPerWorkingCopyInfo(),
                        (GroovyCompilationUnitDeclaration) unit);
            }
            // GROOVY end

            if (this.progressMonitor != null)
                this.progressMonitor.worked(1);
        }

        // create AST if needed
        if (this.astLevel != ICompilationUnit.NO_AST && unit != null/*
                                                                    * unit is null if working copy is consistent && (problem
                                                                    * detection not forced || non-Java project) -> don't create
                                                                    * AST as per API
                                                                    */) {
            Map options = workingCopy.getJavaProject().getOptions(true);
            // convert AST
            this.ast = AST.convertCompilationUnit(this.astLevel, unit, options, this.resolveBindings, source,
                    this.reconcileFlags, this.progressMonitor);
            if (this.ast != null) {
                if (this.deltaBuilder.delta == null) {
                    this.deltaBuilder.delta = new JavaElementDelta(workingCopy);
                }
                this.deltaBuilder.delta.changedAST(this.ast);
            }
            if (this.progressMonitor != null)
                this.progressMonitor.worked(1);
        }
    } catch (JavaModelException e) {
        if (JavaProject.hasJavaNature(workingCopy.getJavaProject().getProject()))
            throw e;
        // else JavaProject has lost its nature (or most likely was closed/deleted) while reconciling -> ignore
        // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=100919)
    } finally {
        JavaModelManager.getJavaModelManager().abortOnMissingSource.set(null);
        if (unit != null) {
            unit.cleanUp();
        }
    }
    return this.ast;
}

From source file:org.eclipse.ajdt.core.javaelements.AJCompilationUnit.java

License:Open Source License

/**
 * builds the structure of this Compilation unit.  We need to use an aspect-aware parser for this (in the org.aspectj.org.eclipse... world, which
 * makes things a little messy/*www . java 2s . c om*/
 */
protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements,
        IResource underlyingResource) throws JavaModelException {
    AJCompilationUnitInfo unitInfo = (AJCompilationUnitInfo) info;

    if (ajFile == null) {
        return false;
    }

    // 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
    AJCompilationUnitStructureRequestor requestor = new AJCompilationUnitStructureRequestor(this, unitInfo,
            newElements);
    JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
    IJavaProject project = getJavaProject();

    boolean createAST;
    boolean resolveBindings;
    int reconcileFlags;
    //        HashMap problems;
    AJCompilationUnitInfo astHolder = (AJCompilationUnitInfo) info;
    createAST = astHolder.getASTLevel() != NO_AST;
    resolveBindings = astHolder.doResolveBindings();
    reconcileFlags = astHolder.getReconcileFlags();
    //        problems = astHolder.getProblems();

    boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null
            && AspectJPlugin.isAJProject(project.getProject());
    org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory problemFactory = new org.aspectj.org.eclipse.jdt.internal.compiler.problem.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$
    }

    // ensure parser sees the real contents (not the fake java buffer)
    this.requestOriginalContentMode();

    // use an aspectj aware source parser
    AJSourceElementParser ajdtParser = new AJSourceElementParser(requestor, problemFactory,
            new org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions(options),
            true/*report local declarations*/,
            !createAST /*optimize string literals only if not creating a DOM AST*/);

    ajdtParser.reportOnlyOneSyntaxError = !computeProblems;
    ajdtParser.setMethodsFullRecovery(true);
    ajdtParser.setStatementsRecovery((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);

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

    // 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.setTimestamp(((IFile) underlyingResource).getModificationStamp());

    // compute other problems if needed
    CompilationUnitDeclaration compilationUnitDeclaration = null;
    final AJCompilationUnit source = ajCloneCachingContents();
    requestor.setSource(source.getContents());
    try {
        if (false) {
            // for now, don't go here
            // the problem is that we can't find problems and build structure at the same time
            // they require difference kinds of parsers.
            //            if (computeProblems) {
            //                if (problems == null) {
            //                    // report problems to the problem requestor
            //                    problems = new HashMap();
            //                    compilationUnitDeclaration = AJCompilationUnitProblemFinder.processAJ(
            //                            source, ajdtParser, 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 = AJCompilationUnitProblemFinder.processAJ(source, ajdtParser, this.owner, problems, createAST, reconcileFlags, pm);
            //                }
        } else {
            // since we are doing n aspectj aware parse with the AJ parser
            // need to wrap the results in a JDT CompilationUnitDeclaration
            org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration ajDeclaration = ajdtParser
                    .parseCompilationUnit(
                            new org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit() {
                                public char[] getContents() {
                                    return source.getContents();
                                }

                                public char[] getMainTypeName() {
                                    return source.getMainTypeName();
                                }

                                public char[][] getPackageName() {
                                    return source.getPackageName();
                                }

                                public char[] getFileName() {
                                    return source.getFileName();
                                }

                                public boolean ignoreOptionalProblems() {
                                    return false;
                                }
                            }, true /*full parse to find local elements*/);
            compilationUnitDeclaration = new AJCompilationUnitDeclarationWrapper(ajDeclaration, source);
        }

        if (createAST) {
            // XXX hmmmm...may not work
            int astLevel = unitInfo.getASTLevel();
            org.eclipse.jdt.core.dom.CompilationUnit cu = AST.convertCompilationUnit(astLevel,
                    compilationUnitDeclaration, options, computeProblems, source, reconcileFlags, pm);
            unitInfo.setAST(cu);
        }
    } finally {
        discardOriginalContentMode();
        if (compilationUnitDeclaration != null) {
            compilationUnitDeclaration.cleanUp();
        }
    }

    return unitInfo.isStructureKnown();
}

From source file:org.eclipse.ajdt.core.reconcile.AJReconcileWorkingCopyOperation.java

License:Open Source License

public org.eclipse.jdt.core.dom.CompilationUnit makeConsistent(CompilationUnit workingCopy)
        throws JavaModelException {
    if (!workingCopy.isConsistent()) {
        // make working copy consistent
        if (this.problems == null)
            this.problems = new HashMap();
        this.resolveBindings = this.requestorIsActive;
        this.ast = workingCopy.makeConsistent(this.astLevel, this.resolveBindings, reconcileFlags,
                this.problems, this.progressMonitor);
        this.deltaBuilder.buildDeltas();
        if (this.ast != null && this.deltaBuilder.delta != null)
            this.deltaBuilder.delta.changedAST(this.ast);
        return this.ast;
    }/*from  w w w.  j  a v a 2  s.  c om*/
    if (this.ast != null)
        return this.ast; // no need to recompute AST if known already

    CompilationUnitDeclaration unit = null;
    try {
        JavaModelManager.getJavaModelManager().abortOnMissingSource.set(Boolean.TRUE);
        CompilationUnit source;
        if (workingCopy instanceof AJCompilationUnit) {
            source = ((AJCompilationUnit) workingCopy).ajCloneCachingContents();
        } else {
            source = workingCopy.cloneCachingContents();
        }
        // find problems if needed
        if (JavaProject.hasJavaNature(workingCopy.getJavaProject().getProject())
                && (this.reconcileFlags & ICompilationUnit.FORCE_PROBLEM_DETECTION) != 0) {
            this.resolveBindings = this.requestorIsActive;
            if (this.problems == null)
                this.problems = new HashMap();
            unit = AJCompilationUnitProblemFinder.processAJ(source, this.workingCopyOwner, this.problems,
                    this.astLevel != ICompilationUnit.NO_AST/*creating AST if level is not NO_AST */,
                    reconcileFlags, this.progressMonitor);
            if (this.progressMonitor != null)
                this.progressMonitor.worked(1);
        }

        // create AST if needed
        if (this.astLevel != ICompilationUnit.NO_AST
                && unit != null/*unit is null if working copy is consistent && (problem detection not forced || non-Java project) -> don't create AST as per API*/) {
            Map options = workingCopy.getJavaProject().getOptions(true);
            // convert AST
            this.ast = AST.convertCompilationUnit(this.astLevel, unit, options, this.resolveBindings, source,
                    reconcileFlags, this.progressMonitor);
            if (this.ast != null) {
                if (this.deltaBuilder.delta == null) {
                    this.deltaBuilder.delta = new JavaElementDelta(workingCopy);
                }
                this.deltaBuilder.delta.changedAST(this.ast);
            }
            if (this.progressMonitor != null)
                this.progressMonitor.worked(1);
        }
    } catch (JavaModelException e) {
        if (JavaProject.hasJavaNature(workingCopy.getJavaProject().getProject()))
            throw e;
        // else JavaProject has lost its nature (or most likely was closed/deleted) while reconciling -> ignore
        // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=100919)
    } finally {
        JavaModelManager.getJavaModelManager().abortOnMissingSource.set(null);
        if (unit != null) {
            unit.cleanUp();
        }
    }
    return this.ast;
}

From source file:org.eclipse.jdt.core.dom.CompilationUnitResolver.java

License:Open Source License

private void resolve(ICompilationUnit[] compilationUnits, String[] bindingKeys, ASTRequestor astRequestor,
        int apiLevel, Map compilerOptions, WorkingCopyOwner owner, int flags) {

    // temporarily connect ourselves to the ASTResolver - must disconnect when done
    astRequestor.compilationUnitResolver = this;
    this.bindingTables = new DefaultBindingResolver.BindingTables();
    CompilationUnitDeclaration unit = null;
    try {//from w w  w .  j  a  va 2 s.  c  om
        int length = compilationUnits.length;
        org.eclipse.jdt.internal.compiler.env.ICompilationUnit[] sourceUnits = new org.eclipse.jdt.internal.compiler.env.ICompilationUnit[length];
        System.arraycopy(compilationUnits, 0, sourceUnits, 0, length);
        beginToCompile(sourceUnits, bindingKeys);
        // process all units (some more could be injected in the loop by the lookup environment)
        for (int i = 0; i < this.totalUnits; i++) {
            if (resolvedRequestedSourcesAndKeys(i)) {
                // no need to keep resolving if no more ASTs and no more binding keys are needed
                // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=114935
                // cleanup remaining units
                for (; i < this.totalUnits; i++) {
                    this.unitsToProcess[i].cleanUp();
                    this.unitsToProcess[i] = null;
                }
                break;
            }
            unit = this.unitsToProcess[i];
            try {
                super.process(unit, i); // this.process(...) is optimized to not process already known units

                // requested AST
                char[] fileName = unit.compilationResult.getFileName();
                ICompilationUnit source = (ICompilationUnit) this.requestedSources.get(fileName);
                if (source != null) {
                    // convert AST
                    CompilationResult compilationResult = unit.compilationResult;
                    org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = compilationResult.compilationUnit;
                    char[] contents = sourceUnit.getContents();
                    AST ast = AST.newAST(apiLevel);
                    ast.setFlag(flags | AST.RESOLVED_BINDINGS);
                    ast.setDefaultNodeFlag(ASTNode.ORIGINAL);
                    ASTConverter converter = new ASTConverter(compilerOptions, true/*need to resolve bindings*/,
                            this.monitor);
                    BindingResolver resolver = new DefaultBindingResolver(unit.scope, owner, this.bindingTables,
                            (flags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0, this.fromJavaProject);
                    ast.setBindingResolver(resolver);
                    converter.setAST(ast);
                    CompilationUnit compilationUnit = converter.convert(unit, contents);
                    compilationUnit.setTypeRoot(source);
                    compilationUnit.setLineEndTable(compilationResult.getLineSeparatorPositions());
                    ast.setDefaultNodeFlag(0);
                    ast.setOriginalModificationCount(ast.modificationCount());

                    // pass it to requestor
                    astRequestor.acceptAST(source, compilationUnit);

                    worked(1);

                    // remove at the end so that we don't resolve twice if a source and a key for the same file name have been requested
                    this.requestedSources.put(fileName, null); // mark it as removed
                }

                // requested binding
                Object key = this.requestedKeys.get(fileName);
                if (key != null) {
                    if (key instanceof BindingKeyResolver) {
                        reportBinding(key, astRequestor, owner, unit);
                        worked(1);
                    } else if (key instanceof ArrayList) {
                        Iterator iterator = ((ArrayList) key).iterator();
                        while (iterator.hasNext()) {
                            reportBinding(iterator.next(), astRequestor, owner, unit);
                            worked(1);
                        }
                    }

                    // remove at the end so that we don't resolve twice if a source and a key for the same file name have been requested
                    this.requestedKeys.put(fileName, null); // mark it as removed
                }
            } finally {
                // cleanup compilation unit result
                unit.cleanUp();
            }
            this.unitsToProcess[i] = null; // release reference to processed unit declaration
            this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
        }

        // remaining binding keys
        DefaultBindingResolver resolver = new DefaultBindingResolver(this.lookupEnvironment, owner,
                this.bindingTables, (flags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0, true);
        Object[] keys = this.requestedKeys.valueTable;
        for (int j = 0, keysLength = keys.length; j < keysLength; j++) {
            BindingKeyResolver keyResolver = (BindingKeyResolver) keys[j];
            if (keyResolver == null)
                continue;
            Binding compilerBinding = keyResolver.getCompilerBinding();
            IBinding binding = compilerBinding == null ? null : resolver.getBinding(compilerBinding);
            // pass it to requestor
            astRequestor.acceptBinding(((BindingKeyResolver) this.requestedKeys.valueTable[j]).getKey(),
                    binding);
            worked(1);
        }
    } catch (OperationCanceledException e) {
        throw e;
    } catch (AbortCompilation e) {
        this.handleInternalException(e, unit);
    } catch (Error e) {
        this.handleInternalException(e, unit, null);
        throw e; // rethrow
    } catch (RuntimeException e) {
        this.handleInternalException(e, unit, null);
        throw e; // rethrow
    } finally {
        // disconnect ourselves from ast requestor
        astRequestor.compilationUnitResolver = null;
    }
}

From source file:org.eclipse.jdt.core.dom.CompilationUnitResolver.java

License:Open Source License

private void resolve(String[] sourceCompilationUnits, String[] encodings, String[] bindingKeys,
        FileASTRequestor astRequestor, int apiLevel, Map compilerOptions, int flags) {

    // temporarily connect ourselves to the ASTResolver - must disconnect when done
    astRequestor.compilationUnitResolver = this;
    this.bindingTables = new DefaultBindingResolver.BindingTables();
    CompilationUnitDeclaration unit = null;
    try {// w  w  w  . jav  a2s.  co m
        int length = sourceCompilationUnits.length;
        org.eclipse.jdt.internal.compiler.env.ICompilationUnit[] sourceUnits = new org.eclipse.jdt.internal.compiler.env.ICompilationUnit[length];
        int count = 0;
        for (int i = 0; i < length; i++) {
            char[] contents = null;
            String encoding = encodings != null ? encodings[i] : null;
            String sourceUnitPath = sourceCompilationUnits[i];
            try {
                contents = Util.getFileCharContent(new File(sourceUnitPath), encoding);
            } catch (IOException e) {
                // go to the next unit
                continue;
            }
            if (contents == null) {
                // go to the next unit
                continue;
            }
            sourceUnits[count++] = new org.eclipse.jdt.internal.compiler.batch.CompilationUnit(contents,
                    sourceUnitPath, encoding);
        }
        beginToCompile(sourceUnits, bindingKeys);
        // process all units (some more could be injected in the loop by the lookup environment)
        for (int i = 0; i < this.totalUnits; i++) {
            if (resolvedRequestedSourcesAndKeys(i)) {
                // no need to keep resolving if no more ASTs and no more binding keys are needed
                // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=114935
                // cleanup remaining units
                for (; i < this.totalUnits; i++) {
                    this.unitsToProcess[i].cleanUp();
                    this.unitsToProcess[i] = null;
                }
                break;
            }
            unit = this.unitsToProcess[i];
            try {
                super.process(unit, i); // this.process(...) is optimized to not process already known units

                // requested AST
                char[] fileName = unit.compilationResult.getFileName();
                org.eclipse.jdt.internal.compiler.env.ICompilationUnit source = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) this.requestedSources
                        .get(fileName);
                if (source != null) {
                    // convert AST
                    CompilationResult compilationResult = unit.compilationResult;
                    org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = compilationResult.compilationUnit;
                    char[] contents = sourceUnit.getContents();
                    AST ast = AST.newAST(apiLevel);
                    ast.setFlag(flags | AST.RESOLVED_BINDINGS);
                    ast.setDefaultNodeFlag(ASTNode.ORIGINAL);
                    ASTConverter converter = new ASTConverter(compilerOptions, true/*need to resolve bindings*/,
                            this.monitor);
                    BindingResolver resolver = new DefaultBindingResolver(unit.scope, null, this.bindingTables,
                            (flags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0, this.fromJavaProject);
                    ast.setBindingResolver(resolver);
                    converter.setAST(ast);
                    CompilationUnit compilationUnit = converter.convert(unit, contents);
                    compilationUnit.setTypeRoot(null);
                    compilationUnit.setLineEndTable(compilationResult.getLineSeparatorPositions());
                    ast.setDefaultNodeFlag(0);
                    ast.setOriginalModificationCount(ast.modificationCount());

                    // pass it to requestor
                    astRequestor.acceptAST(new String(source.getFileName()), compilationUnit);

                    worked(1);

                    // remove at the end so that we don't resolve twice if a source and a key for the same file name have been requested
                    this.requestedSources.put(fileName, null); // mark it as removed
                }

                // requested binding
                Object key = this.requestedKeys.get(fileName);
                if (key != null) {
                    if (key instanceof BindingKeyResolver) {
                        reportBinding(key, astRequestor, unit);
                        worked(1);
                    } else if (key instanceof ArrayList) {
                        Iterator iterator = ((ArrayList) key).iterator();
                        while (iterator.hasNext()) {
                            reportBinding(iterator.next(), astRequestor, unit);
                            worked(1);
                        }
                    }

                    // remove at the end so that we don't resolve twice if a source and a key for the same file name have been requested
                    this.requestedKeys.put(fileName, null); // mark it as removed
                }
            } finally {
                // cleanup compilation unit result
                unit.cleanUp();
            }
            this.unitsToProcess[i] = null; // release reference to processed unit declaration
            this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
        }

        // remaining binding keys
        DefaultBindingResolver resolver = new DefaultBindingResolver(this.lookupEnvironment, null,
                this.bindingTables, (flags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0, true);
        Object[] keys = this.requestedKeys.valueTable;
        for (int j = 0, keysLength = keys.length; j < keysLength; j++) {
            BindingKeyResolver keyResolver = (BindingKeyResolver) keys[j];
            if (keyResolver == null)
                continue;
            Binding compilerBinding = keyResolver.getCompilerBinding();
            IBinding binding = compilerBinding == null ? null : resolver.getBinding(compilerBinding);
            // pass it to requestor
            astRequestor.acceptBinding(((BindingKeyResolver) this.requestedKeys.valueTable[j]).getKey(),
                    binding);
            worked(1);
        }
    } catch (OperationCanceledException e) {
        throw e;
    } catch (AbortCompilation e) {
        this.handleInternalException(e, unit);
    } catch (Error e) {
        this.handleInternalException(e, unit, null);
        throw e; // rethrow
    } catch (RuntimeException e) {
        this.handleInternalException(e, unit, null);
        throw e; // rethrow
    } finally {
        // disconnect ourselves from ast requestor
        astRequestor.compilationUnitResolver = null;
    }
}

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
    }//  ww w  .j a v  a 2 s  .c  o m

    // 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.nabucco.framework.mda.model.java.JavaModelLoader.java

License:Open Source License

/**
 * Process a compilation unit already parsed and build.
 * //from www. j a  v a  2  s . co m
 * @param environment
 *            the lookup environment
 * @param parser
 *            the parser
 * @param unit
 *            the compilation unit
 */
private void process(LookupEnvironment environment, Parser parser, CompilationUnitDeclaration unit) {

    environment.unitBeingCompleted = unit;

    parser.getMethodBodies(unit);

    // fault in fields & methods
    if (unit.scope != null) {
        unit.scope.faultInTypes();
    }

    // verify inherited methods
    if (unit.scope != null) {
        unit.scope.verifyMethods(environment.methodVerifier());
    }

    // type checking
    unit.resolve();

    // flow analysis
    unit.analyseCode();

    // code generation
    unit.generateCode();

    if (JavaModelSupport.createCompilerOptions().produceReferenceInfo && unit.scope != null) {
        unit.scope.storeDependencyInfo();
    }

    unit.finalizeProblems();

    environment.unitBeingCompleted = null;

    unit.ignoreFurtherInvestigation = false;
    unit.cleanUp();
}