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

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

Introduction

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

Prototype

public void resolve() 

Source Link

Usage

From source file:com.codenvy.ide.ext.java.server.internal.codeassist.SelectionEngine.java

License:Open Source License

/**
 * Ask the engine to compute the selection at the specified position
 * of the given compilation unit./*w  w w. j  ava2  s.c o  m*/
        
 *  @param sourceUnit org.eclipse.jdt.internal.compiler.env.ICompilationUnit
 *      the source of the current compilation unit.
 *
 *  @param selectionSourceStart int
 *  @param selectionSourceEnd int
 *      a range in the source where the selection is.
 */
public void select(ICompilationUnit sourceUnit, int selectionSourceStart, int selectionSourceEnd) {

    char[] source = sourceUnit.getContents();

    if (DEBUG) {
        System.out.print("SELECTION IN "); //$NON-NLS-1$
        System.out.print(sourceUnit.getFileName());
        System.out.print(" FROM "); //$NON-NLS-1$
        System.out.print(selectionSourceStart);
        System.out.print(" TO "); //$NON-NLS-1$
        System.out.println(selectionSourceEnd);
        System.out.println("SELECTION - Source :"); //$NON-NLS-1$
        System.out.println(source);
    }
    if (!checkSelection(source, selectionSourceStart, selectionSourceEnd)) {
        return;
    }
    if (DEBUG) {
        System.out.print("SELECTION - Checked : \""); //$NON-NLS-1$
        System.out.print(new String(source, this.actualSelectionStart,
                this.actualSelectionEnd - this.actualSelectionStart + 1));
        System.out.println('"');
    }
    try {
        this.acceptedAnswer = false;
        CompilationResult result = new CompilationResult(sourceUnit, 1, 1,
                this.compilerOptions.maxProblemsPerUnit);
        CompilationUnitDeclaration parsedUnit = this.parser.dietParse(sourceUnit, result,
                this.actualSelectionStart, this.actualSelectionEnd);

        if (parsedUnit != null) {
            if (DEBUG) {
                System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$
                System.out.println(parsedUnit.toString());
            }

            // scan the package & import statements first
            if (parsedUnit.currentPackage instanceof SelectionOnPackageReference) {
                char[][] tokens = ((SelectionOnPackageReference) parsedUnit.currentPackage).tokens;
                this.noProposal = false;
                this.requestor.acceptPackage(CharOperation.concatWith(tokens, '.'));
                return;
            }
            ImportReference[] imports = parsedUnit.imports;
            if (imports != null) {
                for (int i = 0, length = imports.length; i < length; i++) {
                    ImportReference importReference = imports[i];
                    if (importReference instanceof SelectionOnImportReference) {
                        char[][] tokens = ((SelectionOnImportReference) importReference).tokens;
                        this.noProposal = false;
                        this.requestor.acceptPackage(CharOperation.concatWith(tokens, '.'));
                        this.nameEnvironment.findTypes(CharOperation.concatWith(tokens, '.'), false, false,
                                IJavaSearchConstants.TYPE, this);

                        this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
                        if ((this.unitScope = parsedUnit.scope) != null) {
                            int tokenCount = tokens.length;
                            char[] lastToken = tokens[tokenCount - 1];
                            char[][] qualifierTokens = CharOperation.subarray(tokens, 0, tokenCount - 1);

                            if (qualifierTokens != null && qualifierTokens.length > 0) {
                                Binding binding = this.unitScope.getTypeOrPackage(qualifierTokens);
                                if (binding != null && binding instanceof ReferenceBinding) {
                                    ReferenceBinding ref = (ReferenceBinding) binding;
                                    selectMemberTypeFromImport(parsedUnit, lastToken, ref,
                                            importReference.isStatic());
                                    if (importReference.isStatic()) {
                                        selectStaticFieldFromStaticImport(parsedUnit, lastToken, ref);
                                        selectStaticMethodFromStaticImport(parsedUnit, lastToken, ref);
                                    }
                                }
                            }
                        }

                        // accept qualified types only if no unqualified type was accepted
                        if (!this.acceptedAnswer) {
                            acceptQualifiedTypes();
                            if (!this.acceptedAnswer) {
                                this.nameEnvironment.findTypes(this.selectedIdentifier, false, false,
                                        IJavaSearchConstants.TYPE, this);
                                // try with simple type name
                                if (!this.acceptedAnswer) {
                                    acceptQualifiedTypes();
                                }
                            }
                        }
                        if (this.noProposal && this.problem != null) {
                            this.requestor.acceptError(this.problem);
                        }
                        return;
                    }
                }
            }
            if (parsedUnit.types != null || parsedUnit.isPackageInfo()) {
                if (selectDeclaration(parsedUnit))
                    return;
                this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
                if ((this.unitScope = parsedUnit.scope) != null) {
                    try {
                        this.lookupEnvironment.completeTypeBindings(parsedUnit, true);

                        CompilationUnitDeclaration previousUnitBeingCompleted = this.lookupEnvironment.unitBeingCompleted;
                        this.lookupEnvironment.unitBeingCompleted = parsedUnit;
                        parsedUnit.scope.faultInTypes();
                        this.lookupEnvironment.unitBeingCompleted = previousUnitBeingCompleted;
                        ASTNode node = null;
                        if (parsedUnit.types != null)
                            node = parseBlockStatements(parsedUnit, selectionSourceStart);
                        if (DEBUG) {
                            System.out.println("SELECTION - AST :"); //$NON-NLS-1$
                            System.out.println(parsedUnit.toString());
                        }
                        parsedUnit.resolve();
                        if (node != null) {
                            selectLocalDeclaration(node);
                        }
                    } catch (SelectionNodeFound e) {
                        if (e.binding != null) {
                            if (DEBUG) {
                                System.out.println("SELECTION - Selection binding:"); //$NON-NLS-1$
                                System.out.println(e.binding.toString());
                            }
                            // if null then we found a problem in the selection node
                            selectFrom(e.binding, parsedUnit, sourceUnit, e.isDeclaration);
                        }
                    }
                }
            }
        }
        // only reaches here if no selection could be derived from the parsed tree
        // thus use the selected source and perform a textual type search
        if (!this.acceptedAnswer) {
            this.nameEnvironment.findTypes(this.selectedIdentifier, false, false, IJavaSearchConstants.TYPE,
                    this);

            // accept qualified types only if no unqualified type was accepted
            if (!this.acceptedAnswer) {
                acceptQualifiedTypes();

                // accept types from all the workspace only if no type was found in the project scope
                if (this.noProposal) {
                    findAllTypes(this.selectedIdentifier);
                }
            }
        }
        if (this.noProposal && this.problem != null) {
            this.requestor.acceptError(this.problem);
        }
    } catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D
        if (DEBUG) {
            System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$
            e.printStackTrace(System.out);
        }
    } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
        if (DEBUG) {
            System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$
            e.printStackTrace(System.out);
        }
    } finally {
        reset(true);
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.codeassist.SelectionEngine.java

License:Open Source License

/**
 * Asks the engine to compute the selection of the given type
 * from the given context//from w ww  .j  av  a 2s .  c o m
 *
 *  @param typeName char[]
 *      a type name which is to be resolved in the context of a compilation unit.
 *      NOTE: the type name is supposed to be correctly reduced (no whitespaces, no unicodes left)
 *
 *  @param context org.eclipse.jdt.core.IType
 *      the context in which code assist is invoked.
 */
public void selectType(char[] typeName, IType context) throws JavaModelException {
    try {
        this.acceptedAnswer = false;

        // only the type erasure are returned by IType.resolvedType(...)
        if (CharOperation.indexOf('<', typeName) != -1) {
            char[] typeSig = Signature.createCharArrayTypeSignature(typeName, false/*not resolved*/);
            typeSig = Signature.getTypeErasure(typeSig);
            typeName = Signature.toCharArray(typeSig);
        }

        CompilationUnitDeclaration parsedUnit = null;
        TypeDeclaration typeDeclaration = null;
        org.eclipse.jdt.core.ICompilationUnit cu = context.getCompilationUnit();
        if (cu != null) {
            IType[] topLevelTypes = cu.getTypes();
            int length = topLevelTypes.length;
            SourceTypeElementInfo[] topLevelInfos = new SourceTypeElementInfo[length];
            for (int i = 0; i < length; i++) {
                topLevelInfos[i] = (SourceTypeElementInfo) ((SourceType) topLevelTypes[i]).getElementInfo();
            }
            CompilationResult result = new CompilationResult(
                    (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) cu, 1, 1,
                    this.compilerOptions.maxProblemsPerUnit);
            int flags = SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE;
            if (context.isAnonymous() || context.isLocal())
                flags |= SourceTypeConverter.LOCAL_TYPE;
            parsedUnit = SourceTypeConverter.buildCompilationUnit(topLevelInfos, flags,
                    this.parser.problemReporter(), result);
            if (parsedUnit != null && parsedUnit.types != null) {
                if (DEBUG) {
                    System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$
                    System.out.println(parsedUnit.toString());
                }
                // find the type declaration that corresponds to the original source type
                typeDeclaration = new ASTNodeFinder(parsedUnit).findType(context);
            }
        } else { // binary type
            ClassFile classFile = (ClassFile) context.getClassFile();
            ClassFileReader reader = (ClassFileReader) classFile.getBinaryTypeInfo(
                    (IFile) null/*classFile.resource()*/,
                    false/*don't fully initialize so as to keep constant pool (used below)*/);
            CompilationResult result = new CompilationResult(reader.getFileName(), 1, 1,
                    this.compilerOptions.maxProblemsPerUnit);
            parsedUnit = new CompilationUnitDeclaration(this.parser.problemReporter(), result, 0);
            HashSetOfCharArrayArray typeNames = new HashSetOfCharArrayArray();

            BinaryTypeConverter converter = new BinaryTypeConverter(this.parser.problemReporter(), result,
                    typeNames);
            typeDeclaration = converter.buildTypeDeclaration(context, parsedUnit);
            parsedUnit.imports = converter.buildImports(reader);
        }

        if (typeDeclaration != null) {

            // add fake field with the type we're looking for
            // note: since we didn't ask for fields above, there is no field defined yet
            FieldDeclaration field = new FieldDeclaration();
            int dot;
            if ((dot = CharOperation.lastIndexOf('.', typeName)) == -1) {
                this.selectedIdentifier = typeName;
                field.type = new SelectionOnSingleTypeReference(typeName, -1);
                // position not used
            } else {
                char[][] previousIdentifiers = CharOperation.splitOn('.', typeName, 0, dot);
                char[] selectionIdentifier = CharOperation.subarray(typeName, dot + 1, typeName.length);
                this.selectedIdentifier = selectionIdentifier;
                field.type = new SelectionOnQualifiedTypeReference(previousIdentifiers, selectionIdentifier,
                        new long[previousIdentifiers.length + 1]);
            }
            field.name = "<fakeField>".toCharArray(); //$NON-NLS-1$
            typeDeclaration.fields = new FieldDeclaration[] { field };

            // build bindings
            this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
            if ((this.unitScope = parsedUnit.scope) != null) {
                try {
                    // build fields
                    // note: this builds fields only in the parsed unit (the buildFieldsAndMethods flag is not passed along)
                    this.lookupEnvironment.completeTypeBindings(parsedUnit, true);

                    // resolve
                    parsedUnit.scope.faultInTypes();
                    parsedUnit.resolve();
                } catch (SelectionNodeFound e) {
                    if (e.binding != null) {
                        if (DEBUG) {
                            System.out.println("SELECTION - Selection binding :"); //$NON-NLS-1$
                            System.out.println(e.binding.toString());
                        }
                        // if null then we found a problem in the selection node
                        selectFrom(e.binding, parsedUnit, e.isDeclaration);
                    }
                }
            }
        }
        if (this.noProposal && this.problem != null) {
            this.requestor.acceptError(this.problem);
        }
    } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
    } finally {
        reset(true);
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

protected void process(PossibleMatch possibleMatch, boolean bindingsWereCreated) throws CoreException {
    this.currentPossibleMatch = possibleMatch;
    CompilationUnitDeclaration unit = possibleMatch.parsedUnit;
    try {// w  ww.  j a va 2s  .  c  o m
        if (unit.isEmpty()) {
            if (this.currentPossibleMatch.openable instanceof ClassFile) {
                ClassFile classFile = (ClassFile) this.currentPossibleMatch.openable;
                IBinaryType info = null;
                try {
                    info = getBinaryInfo(classFile, classFile.resource());
                } catch (CoreException ce) {
                    // Do nothing
                }
                if (info != null) {
                    boolean mayBeGeneric = this.patternLocator.mayBeGeneric;
                    this.patternLocator.mayBeGeneric = false; // there's no longer generic in class files
                    try {
                        new ClassFileMatchLocator().locateMatches(this, classFile, info);
                    } finally {
                        this.patternLocator.mayBeGeneric = mayBeGeneric;
                    }
                }
            }
            return;
        }
        if (hasAlreadyDefinedType(unit))
            return; // skip type has it is hidden so not visible

        // Move getMethodBodies to #parseAndBuildings(...) method to allow possible match resolution management
        //getMethodBodies(unit);

        boolean mustResolve = (this.pattern.mustResolve || possibleMatch.nodeSet.mustResolve);
        if (bindingsWereCreated && mustResolve) {
            if (unit.types != null) {
                if (BasicSearchEngine.VERBOSE)
                    System.out
                            .println("Resolving " + this.currentPossibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$

                this.lookupEnvironment.unitBeingCompleted = unit;
                reduceParseTree(unit);

                if (unit.scope != null) {
                    // fault in fields & methods
                    unit.scope.faultInTypes();
                }
                unit.resolve();
            } else if (unit.isPackageInfo()) {
                if (BasicSearchEngine.VERBOSE)
                    System.out
                            .println("Resolving " + this.currentPossibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$
                unit.resolve();
            }
        }
        reportMatching(unit, mustResolve);
    } catch (AbortCompilation e) {
        if (BasicSearchEngine.VERBOSE) {
            System.out.println("AbortCompilation while resolving unit " + String.valueOf(unit.getFileName())); //$NON-NLS-1$
            e.printStackTrace();
        }
        // could not resolve: report inaccurate matches
        reportMatching(unit, false); // do not resolve when cu has errors
        if (!(e instanceof AbortCompilationUnit)) {
            // problem with class path
            throw e;
        }
    } finally {
        this.lookupEnvironment.unitBeingCompleted = null;
        this.currentPossibleMatch = null;
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.SuperTypeNamesCollector.java

License:Open Source License

protected CompilationUnitDeclaration buildBindings(ICompilationUnit compilationUnit, boolean isTopLevelOrMember)
        throws JavaModelException {
    // source unit
    org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) compilationUnit;

    CompilationResult compilationResult = new CompilationResult(sourceUnit, 1, 1, 0);
    CompilationUnitDeclaration unit = isTopLevelOrMember
            ? this.locator.basicParser().dietParse(sourceUnit, compilationResult)
            : this.locator.basicParser().parse(sourceUnit, compilationResult);
    if (unit != null) {
        this.locator.lookupEnvironment.buildTypeBindings(unit, null /*no access restriction*/);
        this.locator.lookupEnvironment.completeTypeBindings(unit, !isTopLevelOrMember);
        if (!isTopLevelOrMember) {
            if (unit.scope != null)
                unit.scope.faultInTypes(); // fault in fields & methods
            unit.resolve();
        }/*from   w  w  w  .  j a  v a2  s  . c  om*/
    }
    return unit;
}

From source file:net.sf.j2s.core.compiler.Java2ScriptImageCompiler.java

License:Open Source License

/**
 * Process a compilation unit already parsed and build.
 *//*from  w ww . jav a 2s. com*/
public void process(CompilationUnitDeclaration unit, int i) {
    if (binaryFolder != null) {
        ICompilationUnit sourceUnit = (ICompilationUnit) sourceUnits.get(i);
        ExtendedCompilers.process(sourceUnit, binaryFolder);
        sourceUnits.set(i, new String()); // set to null!
    }

    this.lookupEnvironment.unitBeingCompleted = unit;
    long parseStart = System.currentTimeMillis();

    this.parser.getMethodBodies(unit);

    long resolveStart = System.currentTimeMillis();
    this.stats.parseTime += resolveStart - parseStart;

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

    // verify inherited methods
    if (unit.scope != null)
        unit.scope.verifyMethods(this.lookupEnvironment.methodVerifier());

    // type checking
    unit.resolve();

    long analyzeStart = System.currentTimeMillis();
    this.stats.resolveTime += analyzeStart - resolveStart;

    //No need of analysis or generation of code if statements are not required      
    if (!this.options.ignoreMethodBodies)
        unit.analyseCode(); // flow analysis

    long generateStart = System.currentTimeMillis();
    this.stats.analyzeTime += generateStart - analyzeStart;

    if (!this.options.ignoreMethodBodies)
        unit.generateCode(); // code generation

    // reference info
    if (this.options.produceReferenceInfo && unit.scope != null)
        unit.scope.storeDependencyInfo();

    // finalize problems (suppressWarnings)
    unit.finalizeProblems();

    this.stats.generateTime += System.currentTimeMillis() - generateStart;

    // refresh the total number of units known at this stage
    unit.compilationResult.totalUnitsKnown = this.totalUnits;

    this.lookupEnvironment.unitBeingCompleted = null;
}

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

License:Open Source License

private CompilationUnitDeclaration resolve(CompilationUnitDeclaration unit,
        org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit, NodeSearcher nodeSearcher,
        boolean verifyMethods, boolean analyzeCode, boolean generateCode) {

    try {//from  ww  w .  j a v  a  2 s.c  om

        if (unit == null) {
            // build and record parsed units
            this.parseThreshold = 0; // will request a full parse
            beginToCompile(new org.eclipse.jdt.internal.compiler.env.ICompilationUnit[] { sourceUnit });
            // find the right unit from what was injected via accept(ICompilationUnit,..):
            for (int i = 0, max = this.totalUnits; i < max; i++) {
                CompilationUnitDeclaration currentCompilationUnitDeclaration = this.unitsToProcess[i];
                if (currentCompilationUnitDeclaration != null
                        && currentCompilationUnitDeclaration.compilationResult.compilationUnit == sourceUnit) {
                    unit = currentCompilationUnitDeclaration;
                    break;
                }
            }
            if (unit == null) {
                unit = this.unitsToProcess[0]; // fall back to old behavior
            }
        } else {
            // initial type binding creation
            this.lookupEnvironment.buildTypeBindings(unit, null /*no access restriction*/);

            // binding resolution
            this.lookupEnvironment.completeTypeBindings();
        }

        if (nodeSearcher == null) {
            this.parser.getMethodBodies(unit); // no-op if method bodies have already been parsed
        } else {
            int searchPosition = nodeSearcher.position;
            char[] source = sourceUnit.getContents();
            int length = source.length;
            if (searchPosition >= 0 && searchPosition <= length) {
                unit.traverse(nodeSearcher, unit.scope);

                org.eclipse.jdt.internal.compiler.ast.ASTNode node = nodeSearcher.found;

                if (node != null) {
                    // save existing values to restore them at the end of the parsing process
                    // see bug 47079 for more details
                    int[] oldLineEnds = this.parser.scanner.lineEnds;
                    int oldLinePtr = this.parser.scanner.linePtr;

                    this.parser.scanner.setSource(source, unit.compilationResult);

                    org.eclipse.jdt.internal.compiler.ast.TypeDeclaration enclosingTypeDeclaration = nodeSearcher.enclosingType;
                    if (node instanceof AbstractMethodDeclaration) {
                        ((AbstractMethodDeclaration) node).parseStatements(this.parser, unit);
                    } else if (enclosingTypeDeclaration != null) {
                        if (node instanceof org.eclipse.jdt.internal.compiler.ast.Initializer) {
                            ((org.eclipse.jdt.internal.compiler.ast.Initializer) node)
                                    .parseStatements(this.parser, enclosingTypeDeclaration, unit);
                        } else if (node instanceof org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) {
                            ((org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) node)
                                    .parseMethods(this.parser, unit);
                        }
                    }
                    // this is done to prevent any side effects on the compilation unit result
                    // line separator positions array.
                    this.parser.scanner.lineEnds = oldLineEnds;
                    this.parser.scanner.linePtr = oldLinePtr;
                }
            }
        }

        if (unit.scope != null) {
            // fault in fields & methods
            unit.scope.faultInTypes();
            if (unit.scope != null && verifyMethods) {
                // http://dev.eclipse.org/bugs/show_bug.cgi?id=23117
                // verify inherited methods
                unit.scope.verifyMethods(this.lookupEnvironment.methodVerifier());
            }
            // type checking
            unit.resolve();

            // flow analysis
            if (analyzeCode)
                unit.analyseCode();

            // code generation
            if (generateCode)
                unit.generateCode();

            // finalize problems (suppressWarnings)
            unit.finalizeProblems();
        }
        if (this.unitsToProcess != null)
            this.unitsToProcess[0] = null; // release reference to processed unit declaration
        this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
        return unit;
    } catch (AbortCompilation e) {
        this.handleInternalException(e, unit);
        return unit == null ? this.unitsToProcess[0] : unit;
    } catch (Error e) {
        this.handleInternalException(e, unit, null);
        throw e; // rethrow
    } catch (RuntimeException e) {
        this.handleInternalException(e, unit, null);
        throw e; // rethrow
    } finally {
        // No reset is performed there anymore since,
        // within the CodeAssist (or related tools),
        // the compiler may be called *after* a call
        // to this resolve(...) method. And such a call
        // needs to have a compiler with a non-empty
        // environment.
        // this.reset();
    }
}

From source file:org.eclipse.jdt.internal.core.hierarchy.HierarchyResolver.java

License:Open Source License

/**
 * Resolve the supertypes for the types contained in the given openables (ICompilationUnits and/or IClassFiles).
 * Inform the requestor of the resolved supertypes for each
 * supplied source type using:// w  w w .  ja  v a2  s.co  m
 *    connect(ISourceType suppliedType, IGenericType superclass, IGenericType[] superinterfaces)
 *
 * Also inform the requestor of the supertypes of each
 * additional requested super type which is also a source type
 * instead of a binary type.
 * @param openables
 * @param localTypes
 * @param monitor
 */
public void resolve(Openable[] openables, HashSet localTypes, IProgressMonitor monitor) {
    try {
        int openablesLength = openables.length;
        CompilationUnitDeclaration[] parsedUnits = new CompilationUnitDeclaration[openablesLength];
        boolean[] hasLocalType = new boolean[openablesLength];
        org.eclipse.jdt.core.ICompilationUnit[] cus = new org.eclipse.jdt.core.ICompilationUnit[openablesLength];
        int unitsIndex = 0;

        CompilationUnitDeclaration focusUnit = null;
        ReferenceBinding focusBinaryBinding = null;
        IType focus = this.builder.getType();
        Openable focusOpenable = null;
        if (focus != null) {
            if (focus.isBinary()) {
                focusOpenable = (Openable) focus.getClassFile();
            } else {
                focusOpenable = (Openable) focus.getCompilationUnit();
            }
        }

        // build type bindings

        // GROOVY start: ensure downstream groovy parses share the same compilationunit
        /* old {
        Parser parser = new Parser(this.lookupEnvironment.problemReporter, true);
        } new */
        Parser parser = LanguageSupportFactory.getParser(this, this.lookupEnvironment.globalOptions,
                this.lookupEnvironment.problemReporter, true, 1);
        // GROOVY end
        for (int i = 0; i < openablesLength; i++) {
            Openable openable = openables[i];
            if (openable instanceof org.eclipse.jdt.core.ICompilationUnit) {
                org.eclipse.jdt.core.ICompilationUnit cu = (org.eclipse.jdt.core.ICompilationUnit) openable;

                // contains a potential subtype as a local or anonymous type?
                boolean containsLocalType = false;
                if (localTypes == null) { // case of hierarchy on region
                    containsLocalType = true;
                } else {
                    IPath path = cu.getPath();
                    containsLocalType = localTypes.contains(path.toString());
                }

                // build parsed unit
                CompilationUnitDeclaration parsedUnit = null;
                if (cu.isOpen()) {
                    // create parsed unit from source element infos
                    CompilationResult result = new CompilationResult((ICompilationUnit) cu, i, openablesLength,
                            this.options.maxProblemsPerUnit);
                    SourceTypeElementInfo[] typeInfos = null;
                    try {
                        IType[] topLevelTypes = cu.getTypes();
                        int topLevelLength = topLevelTypes.length;
                        if (topLevelLength == 0)
                            continue; // empty cu: no need to parse (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=65677)
                        typeInfos = new SourceTypeElementInfo[topLevelLength];
                        for (int j = 0; j < topLevelLength; j++) {
                            IType topLevelType = topLevelTypes[j];
                            typeInfos[j] = (SourceTypeElementInfo) ((JavaElement) topLevelType)
                                    .getElementInfo();
                        }
                    } catch (JavaModelException e) {
                        // types/cu exist since cu is opened
                    }
                    int flags = !containsLocalType ? SourceTypeConverter.MEMBER_TYPE
                            : SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE
                                    | SourceTypeConverter.LOCAL_TYPE;
                    parsedUnit = SourceTypeConverter.buildCompilationUnit(typeInfos, flags,
                            this.lookupEnvironment.problemReporter, result);

                    // We would have got all the necessary local types by now and hence there is no further need 
                    // to parse the method bodies. Parser.getMethodBodies, which is called latter in this function, 
                    // will not parse the method statements if ASTNode.HasAllMethodBodies is set. 
                    if (containsLocalType)
                        parsedUnit.bits |= ASTNode.HasAllMethodBodies;
                } else {
                    // create parsed unit from file
                    IFile file = (IFile) cu.getResource();
                    ICompilationUnit sourceUnit = this.builder.createCompilationUnitFromPath(openable, file);

                    CompilationResult unitResult = new CompilationResult(sourceUnit, i, openablesLength,
                            this.options.maxProblemsPerUnit);
                    parsedUnit = parser.dietParse(sourceUnit, unitResult);
                }

                if (parsedUnit != null) {
                    hasLocalType[unitsIndex] = containsLocalType;
                    cus[unitsIndex] = cu;
                    parsedUnits[unitsIndex++] = parsedUnit;
                    try {
                        this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
                        if (openable.equals(focusOpenable)) {
                            focusUnit = parsedUnit;
                        }
                    } catch (AbortCompilation e) {
                        // classpath problem for this type: ignore
                    }
                }
            } else {
                // cache binary type binding
                ClassFile classFile = (ClassFile) openable;
                IBinaryType binaryType = (IBinaryType) JavaModelManager.getJavaModelManager()
                        .getInfo(classFile.getType());
                if (binaryType == null) {
                    // create binary type from file
                    if (classFile.getPackageFragmentRoot().isArchive()) {
                        binaryType = this.builder.createInfoFromClassFileInJar(classFile);
                    } else {
                        IResource file = classFile.resource();
                        binaryType = this.builder.createInfoFromClassFile(classFile, file);
                    }
                }
                if (binaryType != null) {
                    try {
                        BinaryTypeBinding binaryTypeBinding = this.lookupEnvironment.cacheBinaryType(binaryType,
                                false/*don't need field and method (bug 125067)*/,
                                null /*no access restriction*/);
                        remember(binaryType, binaryTypeBinding);
                        if (openable.equals(focusOpenable)) {
                            focusBinaryBinding = binaryTypeBinding;
                        }
                    } catch (AbortCompilation e) {
                        // classpath problem for this type: ignore
                    }
                }
            }
        }

        // remember type declaration of focus if local/anonymous early (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=210498)
        TypeDeclaration focusLocalType = null;
        if (focus != null && focusBinaryBinding == null && focusUnit != null
                && ((Member) focus).getOuterMostLocalContext() != null) {
            focusLocalType = new ASTNodeFinder(focusUnit).findType(focus);
        }

        for (int i = 0; i <= this.typeIndex; i++) {
            IGenericType suppliedType = this.typeModels[i];
            if (suppliedType != null && suppliedType.isBinaryType()) {
                CompilationUnitDeclaration previousUnitBeingCompleted = this.lookupEnvironment.unitBeingCompleted;
                // fault in its hierarchy...
                try {
                    // ensure that unitBeingCompleted is set so that we don't get an AbortCompilation for a missing type
                    // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=213249 )
                    if (previousUnitBeingCompleted == null) {
                        this.lookupEnvironment.unitBeingCompleted = FakeUnit;
                    }
                    ReferenceBinding typeBinding = this.typeBindings[i];
                    typeBinding.superclass();
                    typeBinding.superInterfaces();
                } catch (AbortCompilation e) {
                    // classpath problem for this type: ignore
                } finally {
                    this.lookupEnvironment.unitBeingCompleted = previousUnitBeingCompleted;
                }
            }
        }

        // complete type bindings (i.e. connect super types)
        for (int i = 0; i < unitsIndex; i++) {
            CompilationUnitDeclaration parsedUnit = parsedUnits[i];
            if (parsedUnit != null) {
                try {
                    if (hasLocalType[i]) { // NB: no-op if method bodies have been already parsed
                        if (monitor != null && monitor.isCanceled())
                            throw new OperationCanceledException();
                        parser.getMethodBodies(parsedUnit);
                    }
                } catch (AbortCompilation e) {
                    // classpath problem for this type: don't try to resolve (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=49809)
                    hasLocalType[i] = false;
                }
            }
        }
        // complete type bindings and build fields and methods only for local types
        // (in this case the constructor is needed when resolving local types)
        // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=145333)
        try {
            this.lookupEnvironment.completeTypeBindings(parsedUnits, hasLocalType, unitsIndex);
            // remember type bindings
            for (int i = 0; i < unitsIndex; i++) {
                CompilationUnitDeclaration parsedUnit = parsedUnits[i];
                if (parsedUnit != null && !parsedUnit.hasErrors()) {
                    boolean containsLocalType = hasLocalType[i];
                    if (containsLocalType) {
                        if (monitor != null && monitor.isCanceled())
                            throw new OperationCanceledException();
                        parsedUnit.scope.faultInTypes();
                        parsedUnit.resolve();
                    }

                    rememberAllTypes(parsedUnit, cus[i], containsLocalType);
                }
            }
        } catch (AbortCompilation e) {
            // skip it silently
        }
        worked(monitor, 1);

        // if no potential subtype was a real subtype of the binary focus type, no need to go further
        // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=54043)
        if (focusBinaryBinding == null && focus != null && focus.isBinary()) {
            char[] fullyQualifiedName = focus.getFullyQualifiedName().toCharArray();
            focusBinaryBinding = this.lookupEnvironment
                    .getCachedType(CharOperation.splitOn('.', fullyQualifiedName));
            if (focusBinaryBinding == null)
                return;
        }

        reportHierarchy(focus, focusLocalType, focusBinaryBinding);

    } catch (ClassCastException e) { // work-around for 1GF5W1S - can happen in case duplicates are fed to the hierarchy with binaries hiding sources
    } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
        if (TypeHierarchy.DEBUG)
            e.printStackTrace();
    } finally {
        reset();
    }
}

From source file:org.eclipse.jdt.internal.core.search.matching.MatchLocator.java

License:Open Source License

protected void process(PossibleMatch possibleMatch, boolean bindingsWereCreated) throws CoreException {
    // GROOVY Start
    // Do not process non-Java files.  They use a separate delegated search
    if (LanguageSupportFactory.isInterestingSourceFile(new String(possibleMatch.getFileName()))) {
        try {/*from   w w  w  .  ja v a 2  s.  c  o m*/
            this.lookupEnvironment.buildTypeBindings(possibleMatch.parsedUnit, null /*no access restriction*/);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        possibleMatch.parsedUnit.resolve();
        return;
    }
    // GROOVY End

    this.currentPossibleMatch = possibleMatch;
    CompilationUnitDeclaration unit = possibleMatch.parsedUnit;
    try {
        if (unit.isEmpty()) {
            if (this.currentPossibleMatch.openable instanceof ClassFile) {
                ClassFile classFile = (ClassFile) this.currentPossibleMatch.openable;
                IBinaryType info = null;
                try {
                    info = getBinaryInfo(classFile, classFile.resource());
                } catch (CoreException ce) {
                    // Do nothing
                }
                if (info != null) {
                    boolean mayBeGeneric = this.patternLocator.mayBeGeneric;
                    this.patternLocator.mayBeGeneric = false; // there's no longer generic in class files
                    try {
                        new ClassFileMatchLocator().locateMatches(this, classFile, info);
                    } finally {
                        this.patternLocator.mayBeGeneric = mayBeGeneric;
                    }
                }
            }
            return;
        }
        if (hasAlreadyDefinedType(unit))
            return; // skip type has it is hidden so not visible

        // Move getMethodBodies to #parseAndBuildings(...) method to allow possible match resolution management
        //getMethodBodies(unit);

        boolean mustResolve = (this.pattern.mustResolve || possibleMatch.nodeSet.mustResolve);
        if (bindingsWereCreated && mustResolve) {
            if (unit.types != null) {
                if (BasicSearchEngine.VERBOSE)
                    System.out
                            .println("Resolving " + this.currentPossibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$

                this.lookupEnvironment.unitBeingCompleted = unit;
                reduceParseTree(unit);

                if (unit.scope != null) {
                    // fault in fields & methods
                    unit.scope.faultInTypes();
                }
                unit.resolve();
            } else if (unit.isPackageInfo()) {
                if (BasicSearchEngine.VERBOSE)
                    System.out
                            .println("Resolving " + this.currentPossibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$
                unit.resolve();
            }
        }
        reportMatching(unit, mustResolve);
    } catch (AbortCompilation e) {
        // could not resolve: report inaccurate matches
        reportMatching(unit, false); // do not resolve when cu has errors
        if (!(e instanceof AbortCompilationUnit)) {
            // problem with class path
            throw e;
        }
    } finally {
        this.lookupEnvironment.unitBeingCompleted = null;
        this.currentPossibleMatch = null;
    }
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.control.Dependencies.java

License:Open Source License

private static Pair<Boolean, Success> establishUnitState(CompilationUnitDeclaration unit, int state,
        Success success, AccessRestriction accessRestriction) {
    boolean done = true;
    if (StateHelper.unitHasState(unit, state))
        return new Pair<Boolean, Success>(done, Success.OK);

    // original calls stolen from Compiler.process are handled here:
    try {//from  w  w  w . java  2  s .  c om
        switch (state) {
        case STATE_ROLE_FILES_LINKED:
            establishRoleFilesLinked(unit, Config.getLookupEnvironment());
            break;
        case STATE_BINDINGS_BUILT:
            Config.getLookupEnvironment().internalBuildTypeBindings(unit, accessRestriction);
            break;
        case STATE_LENV_BUILD_TYPE_HIERARCHY:
        case STATE_LENV_CHECK_AND_SET_IMPORTS:
        case STATE_LENV_CONNECT_TYPE_HIERARCHY:
        case STATE_LENV_DONE_FIELDS_AND_METHODS:
        case STATE_ROLES_LINKED:
            checkReadKnownRoles(unit);
            LookupEnvironment lookupEnvironment = Config.getLookupEnvironment();
            if (Config.getBundledCompleteTypeBindingsMode()) {
                int stateReached = Config.getLookupEnvironment().internalCompleteTypeBindings(unit);
                StateHelper.setStateRecursive(unit, stateReached, true);
                if (stateReached >= state)
                    return new Pair<Boolean, Success>(done,
                            (stateReached >= state) ? Success.OK : Success.NotReady);
                // if not successful try directly:
            }
            // completely under our control:
            switch (state) {
            case STATE_LENV_BUILD_TYPE_HIERARCHY:
                break; // no-op
            case STATE_LENV_CHECK_AND_SET_IMPORTS:
                unit.scope.checkAndSetImports();
                break;
            case STATE_LENV_CONNECT_TYPE_HIERARCHY:
                CompilationUnitDeclaration previousUnit = lookupEnvironment.unitBeingCompleted;
                lookupEnvironment.unitBeingCompleted = unit;
                try {
                    unit.scope.connectTypeHierarchy();
                } finally {
                    lookupEnvironment.unitBeingCompleted = previousUnit;
                }
                break;
            case STATE_LENV_DONE_FIELDS_AND_METHODS:
                unit.scope.checkParameterizedTypes();
                if (Config.getBuildFieldsAndMethods())
                    unit.scope.buildFieldsAndMethods();
                break;
            case STATE_ROLES_LINKED:
                RoleSplitter.linkRoles(unit);
            }
            break;
        case STATE_METHODS_PARSED:
            if (success == Success.OK && unit.parseMethodBodies)
                Config.delegateGetMethodBodies(unit);
            // special case: mark the unit but also descend into types (for role units)
            unit.state.setState(STATE_METHODS_PARSED);
            done = false;
            break;
        case STATE_METHODS_VERIFIED:
            if (Config.getVerifyMethods())
                unit.scope.verifyMethods(Config.getLookupEnvironment().methodVerifier());
            break;
        case STATE_RESOLVED:
            unit.resolve();
            break;
        case STATE_CODE_ANALYZED:
            if (Config.getAnalyzeCode())
                unit.analyseCode();
            break;
        case STATE_BYTE_CODE_GENERATED:
            if (Config.getGenerateCode())
                unit.generateCode();
            // descending into already generated types is
            // prevented by TypeDeclaration.hasBeenGenerated
            break;
        default:
            done = false;
        }
    } catch (Config.NotConfiguredException e) {
        e.logWarning("Processing CU " + String.valueOf(unit.getFileName()) + " failed"); //$NON-NLS-1$ //$NON-NLS-2$
        success = Success.Fail;
    }

    return new Pair<Boolean, Success>(done, success);
}

From source file:org.nabucco.framework.mda.model.java.JavaModelLoader.java

License:Open Source License

/**
 * Process a compilation unit already parsed and build.
 * //from   ww w . ja va  2s . c  o  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();
}