Example usage for org.eclipse.jdt.internal.compiler.parser SourceTypeConverter FIELD_AND_METHOD

List of usage examples for org.eclipse.jdt.internal.compiler.parser SourceTypeConverter FIELD_AND_METHOD

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.parser SourceTypeConverter FIELD_AND_METHOD.

Prototype

int FIELD_AND_METHOD

To view the source code for org.eclipse.jdt.internal.compiler.parser SourceTypeConverter FIELD_AND_METHOD.

Click Source Link

Usage

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

License:Open Source License

/**
 * Add additional source types (the first one is the requested type, the rest is formed by the
 * secondary types defined in the same compilation unit).
 *///from www  .j a v a 2  s. c o  m
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding,
        AccessRestriction accessRestriction) {
    CompilationResult result = new CompilationResult(sourceTypes[0].getFileName(), 1, 1,
            this.compilerOptions.maxProblemsPerUnit);
    CompilationUnitDeclaration unit = SourceTypeConverter.buildCompilationUnit(sourceTypes, //sourceTypes[0] is always toplevel here
            SourceTypeConverter.FIELD_AND_METHOD // need field and methods
                    | SourceTypeConverter.MEMBER_TYPE, // need member types
            // no need for field initialization
            this.lookupEnvironment.problemReporter, result);

    if (unit != null) {
        this.lookupEnvironment.buildTypeBindings(unit, accessRestriction);
        this.lookupEnvironment.completeTypeBindings(unit, true);
    }
}

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

License:Open Source License

/**
 * Add additional source types/*from  w  ww .j av  a  2  s  . c o m*/
 */
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding,
        AccessRestriction accessRestriction) {
    // case of SearchableEnvironment of an IJavaProject is used
    ISourceType sourceType = sourceTypes[0];
    while (sourceType.getEnclosingType() != null)
        sourceType = sourceType.getEnclosingType();
    if (sourceType instanceof SourceTypeElementInfo) {
        // get source
        SourceTypeElementInfo elementInfo = (SourceTypeElementInfo) sourceType;
        IType type = elementInfo.getHandle();
        ICompilationUnit sourceUnit = (ICompilationUnit) type.getCompilationUnit();
        accept(sourceUnit, accessRestriction);
    } else {
        CompilationResult result = new CompilationResult(sourceType.getFileName(), 1, 1, 0);
        CompilationUnitDeclaration unit = SourceTypeConverter.buildCompilationUnit(sourceTypes,
                SourceTypeConverter.FIELD_AND_METHOD // need field and methods
                        | SourceTypeConverter.MEMBER_TYPE, // need member types
                // no need for field initialization
                this.lookupEnvironment.problemReporter, result);
        this.lookupEnvironment.buildTypeBindings(unit, accessRestriction);
        this.lookupEnvironment.completeTypeBindings(unit, true);
    }
}

From source file:com.redhat.ceylon.eclipse.core.model.loader.JDTModelLoader.java

License:Open Source License

public void createLookupEnvironment() {
    try {//  w  w w  . java 2 s  .co  m
        lookupEnvironment = new LookupEnvironment(new ITypeRequestor() {

            private Parser basicParser;

            @Override
            public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding,
                    AccessRestriction accessRestriction) {
                // case of SearchableEnvironment of an IJavaProject is used
                ISourceType sourceType = sourceTypes[0];
                while (sourceType.getEnclosingType() != null)
                    sourceType = sourceType.getEnclosingType();
                if (sourceType instanceof SourceTypeElementInfo) {
                    // get source
                    SourceTypeElementInfo elementInfo = (SourceTypeElementInfo) sourceType;
                    IType type = elementInfo.getHandle();
                    ICompilationUnit sourceUnit = (ICompilationUnit) type.getCompilationUnit();
                    accept(sourceUnit, accessRestriction);
                } else {
                    CompilationResult result = new CompilationResult(sourceType.getFileName(), 1, 1, 0);
                    CompilationUnitDeclaration unit = SourceTypeConverter.buildCompilationUnit(sourceTypes,
                            SourceTypeConverter.FIELD_AND_METHOD // need field and methods
                                    | SourceTypeConverter.MEMBER_TYPE, // need member types
                            // no need for field initialization
                            lookupEnvironment.problemReporter, result);
                    lookupEnvironment.buildTypeBindings(unit, accessRestriction);
                    lookupEnvironment.completeTypeBindings(unit, true);
                }
            }

            @Override
            public void accept(IBinaryType binaryType, PackageBinding packageBinding,
                    AccessRestriction accessRestriction) {
                lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);
            }

            @Override
            public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {
                // Switch the current policy and compilation result for this unit to the requested one.
                CompilationResult unitResult = new CompilationResult(sourceUnit, 1, 1,
                        compilerOptions.maxProblemsPerUnit);
                try {
                    CompilationUnitDeclaration parsedUnit = basicParser().dietParse(sourceUnit, unitResult);
                    lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);
                    lookupEnvironment.completeTypeBindings(parsedUnit, true);
                } catch (AbortCompilationUnit e) {
                    // at this point, currentCompilationUnitResult may not be sourceUnit, but some other
                    // one requested further along to resolve sourceUnit.
                    if (unitResult.compilationUnit == sourceUnit) { // only report once
                        //requestor.acceptResult(unitResult.tagAsAccepted());
                    } else {
                        throw e; // want to abort enclosing request to compile
                    }
                }
                // Display unit error in debug mode
                if (BasicSearchEngine.VERBOSE) {
                    if (unitResult.problemCount > 0) {
                        System.out.println(unitResult);
                    }
                }
            }

            private Parser basicParser() {
                if (this.basicParser == null) {
                    ProblemReporter problemReporter = new ProblemReporter(
                            DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions,
                            new DefaultProblemFactory());
                    this.basicParser = new Parser(problemReporter, false);
                    this.basicParser.reportOnlyOneSyntaxError = true;
                }
                return this.basicParser;
            }
        }, compilerOptions, problemReporter,
                ((JavaProject) javaProject).newSearchableNameEnvironment((WorkingCopyOwner) null));
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

License:Open Source License

/**
 * Add additional source types// w  w w . j ava  2  s.c  o  m
 */
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding,
        AccessRestriction accessRestriction) {
    // ensure to jump back to toplevel type for first one (could be a member)
    while (sourceTypes[0].getEnclosingType() != null) {
        sourceTypes[0] = sourceTypes[0].getEnclosingType();
    }

    CompilationResult result = new CompilationResult(sourceTypes[0].getFileName(), 1, 1,
            this.options.maxProblemsPerUnit);

    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=305259, build the compilation unit in its own sand box.
    final long savedComplianceLevel = this.options.complianceLevel;
    final long savedSourceLevel = this.options.sourceLevel;

    try {
        IJavaProject project = ((SourceTypeElementInfo) sourceTypes[0]).getHandle().getJavaProject();
        this.options.complianceLevel = CompilerOptions
                .versionToJdkLevel(project.getOption(JavaCore.COMPILER_COMPLIANCE, true));
        this.options.sourceLevel = CompilerOptions
                .versionToJdkLevel(project.getOption(JavaCore.COMPILER_SOURCE, true));

        // need to hold onto this
        CompilationUnitDeclaration unit = SourceTypeConverter.buildCompilationUnit(sourceTypes, //sourceTypes[0] is always toplevel here
                SourceTypeConverter.FIELD_AND_METHOD // need field and methods
                        | SourceTypeConverter.MEMBER_TYPE // need member types
                        | SourceTypeConverter.FIELD_INITIALIZATION, // need field initialization
                this.lookupEnvironment.problemReporter, result);

        if (unit != null) {
            this.lookupEnvironment.buildTypeBindings(unit, accessRestriction);
            this.lookupEnvironment.completeTypeBindings(unit);
        }
    } finally {
        this.options.complianceLevel = savedComplianceLevel;
        this.options.sourceLevel = savedSourceLevel;
    }
}

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:/*from   w w w.ja va 2 s.com*/
 *    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.objectteams.otdt.tests.otmodel.OTReconcilerTests.java

License:Open Source License

public void testAnchoredType01() throws CoreException, InterruptedException {
    try {//from   w  w  w . j  a  va2  s  . c o  m
        // Resources creation
        IJavaProject p = createOTJavaProject("P", new String[] { "" }, new String[] { "JCL15_LIB" }, "bin");
        IProject project = p.getProject();
        IProjectDescription prjDesc = project.getDescription();
        //prjDesc.setNatureIds(OTDTPlugin.createProjectNatures(prjDesc));
        prjDesc.setBuildSpec(OTDTPlugin.createProjectBuildCommands(prjDesc));
        project.setDescription(prjDesc, null);

        OTREContainer.initializeOTJProject(project);

        this.createFile("/P/BaseTeam.java",
                "public team class BaseTeam {\n" + "   public class Role {}\n" + "}\n");

        String sourceFoo = "public team class Foo {\n" + "   protected team class Mid playedBy BaseTeam {\n"
                + "      public class Inner1 playedBy Role<@Mid.base> {}\n"
                + "      protected class Inner2 playedBy Role<@base> {}\n"
                + "      @SuppressWarnings(\"roletypesyntax\")\n"
                + "      protected class Inner3 playedBy base.Role {}\n" + "   }\n" + "}\n";
        this.createFile("/P/Foo.java", sourceFoo);

        char[] sourceChars = sourceFoo.toCharArray();
        this.problemRequestor.initialize(sourceChars);

        ICompilationUnit fooWC = getCompilationUnit("/P/Foo.java").getWorkingCopy(this.wcOwner, null);
        IType foo = fooWC.getType("Foo");

        CompilerOptions compilerOptions = new CompilerOptions(p.getOptions(true));
        ProblemReporter problemReporter = new ProblemReporter(
                DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions,
                new DefaultProblemFactory());

        // force usage of type converter:
        CompilationUnitDeclaration parsedUnit = SourceTypeConverter.buildCompilationUnit(
                new ISourceType[] { (ISourceType) ((SourceType) foo).getElementInfo() },
                SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE, problemReporter,
                new CompilationResult("Foo.java".toCharArray(), 1, 1, 90));

        // force resolving:
        process(parsedUnit, p, compilerOptions, problemReporter, ITranslationStates.STATE_RESOLVED);

        // evaluate result:
        String result = "";
        CategorizedProblem[] problems = parsedUnit.compilationResult().problems;
        assertNotNull(problems);
        for (IProblem problem : problems)
            if (problem != null && problem.isError())
                result += problem;
        assertEquals("", result);
    } finally {
        deleteProject("P");
    }
}

From source file:org.eclipse.objectteams.otdt.tests.otmodel.OTReconcilerTests.java

License:Open Source License

public void testAnchoredType02() throws CoreException, InterruptedException {
    try {/*  ww  w.j a  v  a 2 s  . com*/
        // Resources creation
        IJavaProject p = createOTJavaProject("P", new String[] { "" }, new String[] { "JCL15_LIB" }, "bin");
        IProject project = p.getProject();
        IProjectDescription prjDesc = project.getDescription();
        //prjDesc.setNatureIds(OTDTPlugin.createProjectNatures(prjDesc));
        prjDesc.setBuildSpec(OTDTPlugin.createProjectBuildCommands(prjDesc));
        project.setDescription(prjDesc, null);

        OTREContainer.initializeOTJProject(project);

        this.createFile("/P/BaseTeam.java",
                "public team class BaseTeam {\n" + "   public class Role {}\n" + "   Role baseField;" + "}\n");

        String sourceFoo = "public team class Foo {\n" + "   protected team class Mid playedBy BaseTeam {\n"
                + "      public class Inner playedBy Role<@Mid.base> {}\n"
                + "       Inner get1() -> get Role<@Mid.base> baseField;\n"
                + "       Inner get2() -> get Role<@base> baseField;\n"
                + "      @SuppressWarnings(\"roletypesyntax\")\n"
                + "       Inner get3() -> get base.Role baseField;\n" + "   }\n" + "}\n";
        this.createFile("/P/Foo.java", sourceFoo);

        char[] sourceChars = sourceFoo.toCharArray();
        this.problemRequestor.initialize(sourceChars);

        ICompilationUnit fooWC = getCompilationUnit("/P/Foo.java").getWorkingCopy(this.wcOwner, null);
        IType foo = fooWC.getType("Foo");

        CompilerOptions compilerOptions = new CompilerOptions(p.getOptions(true));
        ProblemReporter problemReporter = new ProblemReporter(
                DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions,
                new DefaultProblemFactory());

        // force usage of type converter:
        CompilationUnitDeclaration parsedUnit = SourceTypeConverter.buildCompilationUnit(
                new ISourceType[] { (ISourceType) ((SourceType) foo).getElementInfo() },
                SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE, problemReporter,
                new CompilationResult("Foo.java".toCharArray(), 1, 1, 90));

        // force resolving:
        process(parsedUnit, p, compilerOptions, problemReporter, ITranslationStates.STATE_RESOLVED);

        // evaluate result:
        String result = "";
        CategorizedProblem[] problems = parsedUnit.compilationResult().problems;
        assertNotNull(problems);
        for (IProblem problem : problems)
            if (problem != null && problem.isError())
                result += problem;
        assertEquals("", result);
    } finally {
        deleteProject("P");
    }
}