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

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

Introduction

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

Prototype

CompilationResult compilationResult

To view the source code for org.eclipse.jdt.internal.compiler.ast CompilationUnitDeclaration compilationResult.

Click Source Link

Usage

From source file:com.android.build.gradle.tasks.annotations.ExtractAnnotationsDriver.java

License:Apache License

@SuppressWarnings("MethodMayBeStatic")
public void run(@NonNull String[] args) {
    List<String> classpath = Lists.newArrayList();
    List<File> sources = Lists.newArrayList();
    List<File> mergePaths = Lists.newArrayList();
    List<File> apiFilters = null;
    File rmTypeDefs = null;/*from  w w w. j  ava2s .  c  o m*/
    boolean verbose = true;
    boolean allowMissingTypes = false;
    boolean allowErrors = false;
    boolean listFiltered = true;
    boolean skipClassRetention = false;

    String encoding = Charsets.UTF_8.name();
    File output = null;
    File proguard = null;
    long languageLevel = EcjParser.getLanguageLevel(1, 7);
    if (args.length == 1 && "--help".equals(args[0])) {
        usage(System.out);
    }
    if (args.length < 2) {
        usage(System.err);
    }
    for (int i = 0, n = args.length; i < n; i++) {
        String flag = args[i];

        if (flag.equals("--quiet")) {
            verbose = false;
            continue;
        } else if (flag.equals("--allow-missing-types")) {
            allowMissingTypes = true;
            continue;
        } else if (flag.equals("--allow-errors")) {
            allowErrors = true;
            continue;
        } else if (flag.equals("--hide-filtered")) {
            listFiltered = false;
            continue;
        } else if (flag.equals("--skip-class-retention")) {
            skipClassRetention = true;
            continue;
        }
        if (i == n - 1) {
            usage(System.err);
        }
        String value = args[i + 1];
        i++;

        if (flag.equals("--sources")) {
            sources = getFiles(value);
        } else if (flag.equals("--classpath")) {
            classpath = getPaths(value);
        } else if (flag.equals("--merge-zips")) {
            mergePaths = getFiles(value);
        } else if (flag.equals("--output")) {
            output = new File(value);
            if (output.exists()) {
                if (output.isDirectory()) {
                    abort(output + " is a directory");
                }
                boolean deleted = output.delete();
                if (!deleted) {
                    abort("Could not delete previous version of " + output);
                }
            } else if (output.getParentFile() != null && !output.getParentFile().exists()) {
                abort(output.getParentFile() + " does not exist");
            }
        } else if (flag.equals("--proguard")) {
            proguard = new File(value);
            if (proguard.exists()) {
                if (proguard.isDirectory()) {
                    abort(proguard + " is a directory");
                }
                boolean deleted = proguard.delete();
                if (!deleted) {
                    abort("Could not delete previous version of " + proguard);
                }
            } else if (proguard.getParentFile() != null && !proguard.getParentFile().exists()) {
                abort(proguard.getParentFile() + " does not exist");
            }
        } else if (flag.equals("--encoding")) {
            encoding = value;
        } else if (flag.equals("--api-filter")) {
            if (apiFilters == null) {
                apiFilters = Lists.newArrayList();
            }
            for (String path : Splitter.on(",").omitEmptyStrings().split(value)) {
                File apiFilter = new File(path);
                if (!apiFilter.isFile()) {
                    String message = apiFilter + " does not exist or is not a file";
                    abort(message);
                }
                apiFilters.add(apiFilter);
            }
        } else if (flag.equals("--language-level")) {
            if ("1.6".equals(value)) {
                languageLevel = EcjParser.getLanguageLevel(1, 6);
            } else if ("1.7".equals(value)) {
                languageLevel = EcjParser.getLanguageLevel(1, 7);
            } else {
                abort("Unsupported language level " + value);
            }
        } else if (flag.equals("--rmtypedefs")) {
            rmTypeDefs = new File(value);
            if (!rmTypeDefs.isDirectory()) {
                abort(rmTypeDefs + " is not a directory");
            }
        } else {
            System.err.println("Unknown flag " + flag + ": Use --help for usage information");
        }
    }

    if (sources.isEmpty()) {
        abort("Must specify at least one source path");
    }
    if (classpath.isEmpty()) {
        abort("Must specify classpath pointing to at least android.jar or the framework");
    }
    if (output == null && proguard == null) {
        abort("Must specify output path with --output or a proguard path with --proguard");
    }

    // API definition files
    ApiDatabase database = null;
    if (apiFilters != null && !apiFilters.isEmpty()) {
        try {
            List<String> lines = Lists.newArrayList();
            for (File file : apiFilters) {
                lines.addAll(Files.readLines(file, Charsets.UTF_8));
            }
            database = new ApiDatabase(lines);
        } catch (IOException e) {
            abort("Could not open API database " + apiFilters + ": " + e.getLocalizedMessage());
        }
    }

    Extractor extractor = new Extractor(database, rmTypeDefs, verbose, !skipClassRetention, true);
    extractor.setListIgnored(listFiltered);

    try {
        Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> pair = parseSources(sources, classpath,
                encoding, languageLevel);
        Collection<CompilationUnitDeclaration> units = pair.getFirst();

        boolean abort = false;
        int errorCount = 0;
        for (CompilationUnitDeclaration unit : units) {
            // so maybe I don't need my map!!
            IProblem[] problems = unit.compilationResult().getAllProblems();
            if (problems != null) {
                for (IProblem problem : problems) {
                    if (problem.isError()) {
                        errorCount++;
                        String message = problem.getMessage();
                        if (allowMissingTypes) {
                            if (message.contains("cannot be resolved")) {
                                continue;
                            }
                        }

                        System.out.println("Error: " + new String(problem.getOriginatingFileName()) + ":"
                                + problem.getSourceLineNumber() + ": " + message);
                        abort = !allowErrors;
                    }
                }
            }
        }
        if (errorCount > 0) {
            System.err.println("Found " + errorCount + " errors");
        }
        if (abort) {
            abort("Not extracting annotations (compilation problems encountered)");
        }

        INameEnvironment environment = pair.getSecond();
        extractor.extractFromProjectSource(units);

        if (mergePaths != null) {
            for (File jar : mergePaths) {
                extractor.mergeExisting(jar);
            }
        }

        extractor.export(output, proguard);

        // Remove typedefs?
        //noinspection VariableNotUsedInsideIf
        if (rmTypeDefs != null) {
            extractor.removeTypedefClasses();
        }

        environment.cleanup();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.android.build.gradle.tasks.ExtractAnnotations.java

License:Apache License

@Override
@TaskAction//from  w ww.  j a  va  2s.  c  o  m
protected void compile() {
    if (!hasAndroidAnnotations()) {
        return;
    }

    if (encoding == null) {
        encoding = UTF_8;
    }

    EcjParser.EcjResult result = parseSources();
    Collection<CompilationUnitDeclaration> parsedUnits = result.getCompilationUnits();

    try {
        if (!allowErrors) {
            for (CompilationUnitDeclaration unit : parsedUnits) {
                // so maybe I don't need my map!!
                CategorizedProblem[] problems = unit.compilationResult().getAllProblems();
                for (IProblem problem : problems) {
                    if (problem.isError()) {
                        getLogger().warn("Not extracting annotations (compilation problems " + "encountered)\n"
                                + "Error: " + new String(problem.getOriginatingFileName()) + ":"
                                + problem.getSourceLineNumber() + ": " + problem.getMessage());
                        // TODO: Consider whether we abort the build at this point!
                        return;
                    }
                }
            }
        }

        // API definition file
        ApiDatabase database = null;
        if (apiFilter != null && apiFilter.exists()) {
            try {
                database = new ApiDatabase(apiFilter);
            } catch (IOException e) {
                throw new BuildException("Could not open API database " + apiFilter, e);
            }
        }

        boolean displayInfo = getProject().getLogger().isEnabled(LogLevel.INFO);

        Extractor extractor = new Extractor(database, classDir, displayInfo,
                false /*includeClassRetentionAnnotations*/, false /*sortAnnotations*/);
        extractor.extractFromProjectSource(parsedUnits);
        if (mergeJars != null) {
            for (File jar : mergeJars) {
                extractor.mergeExisting(jar);
            }
        }
        extractor.export(output, proguard);
        if (typedefFile != null) {
            extractor.writeTypedefFile(typedefFile);
        } else {
            extractor.removeTypedefClasses();
        }
    } finally {
        result.dispose();
    }
}

From source file:com.google.gwt.dev.CompileModule.java

License:Apache License

private static void checkForErrors(TreeLogger logger, CompilationUnitDeclaration[] goldenCuds)
        throws UnableToCompleteException {
    for (CompilationUnitDeclaration cud : goldenCuds) {
        CompilationResult result = cud.compilationResult();
        if (result.hasErrors()) {
            logger.log(TreeLogger.ERROR, "Aborting on '" + String.valueOf(cud.getFileName()) + "'");
            throw new UnableToCompleteException();
        }//from   w  ww.ja  v a2  s. c o m
    }
}

From source file:com.google.gwt.dev.javac.CompilationUnitInvalidator.java

License:Open Source License

public static void reportErrors(TreeLogger logger, CompilationUnitDeclaration cud, String sourceForDump) {
    CategorizedProblem[] problems = cud.compilationResult().getProblems();
    String fileName = String.valueOf(cud.getFileName());
    boolean isError = cud.compilationResult().hasErrors();
    TreeLogger branch = reportErrors(logger, problems, fileName, isError);
    if (branch != null) {
        Util.maybeDumpSource(branch, fileName, sourceForDump, String.valueOf(cud.getMainTypeName()));
    }/*  w  w w  . jav a  2 s  . c o  m*/
}

From source file:com.google.gwt.dev.javac.GWTProblem.java

License:Open Source License

public static void recordError(ASTNode node, CompilationUnitDeclaration cud, String message,
        HelpInfo helpInfo) {//from w  w  w. j  a  v a2s  . c  o  m
    recordProblem(node, cud.compilationResult(), message, helpInfo, ProblemSeverities.Error);
}

From source file:com.google.gwt.dev.javac.JavaSourceParser.java

License:Open Source License

/**
 * Parse Java source./*from www  .j  a v  a2s.c om*/
 * 
 * @param javaSource String containing Java source to parse
 * @return a CompilationUnitDeclaration or null if parsing failed
 */
private static CompilationUnitDeclaration parseJava(String javaSource) {
    CodeSnippetParsingUtil parsingUtil = new CodeSnippetParsingUtil();
    CompilerOptions options = new CompilerOptions();
    options.complianceLevel = ClassFileConstants.JDK1_5;
    options.sourceLevel = ClassFileConstants.JDK1_5;
    CompilationUnitDeclaration unit = parsingUtil.parseCompilationUnit(javaSource.toString().toCharArray(),
            options.getMap(), true);
    if (unit.compilationResult().hasProblems()) {
        return null;
    }
    return unit;
}

From source file:com.google.gwt.dev.jjs.JavaToJavaScriptCompiler.java

License:Apache License

/**
 * Look through the list of compiled units for errors and log them to the
 * console.//from   w ww  .  j  a  v a  2s.  c  o  m
 * 
 * @param logger logger to use for compilation errors
 * @param cuds compiled units to analyze for errors.
 * @param itemizeErrors log each error or simply log one message if the build
 *          failed.
 * @throws UnableToCompleteException if a compilation error is found in the
 *           cuds argument.
 */
static void checkForErrors(TreeLogger logger, CompilationUnitDeclaration[] cuds, boolean itemizeErrors)
        throws UnableToCompleteException {
    Event checkForErrorsEvent = SpeedTracerLogger.start(CompilerEventType.CHECK_FOR_ERRORS);
    boolean compilationFailed = false;
    if (cuds.length == 0) {
        compilationFailed = true;
    }
    for (CompilationUnitDeclaration cud : cuds) {
        final CompilationResult result = cud.compilationResult();
        if (result.hasErrors()) {
            compilationFailed = true;
            // Early out if we don't need to itemize.
            if (!itemizeErrors) {
                break;
            }
            String typeName = new String(cud.getMainTypeName());
            CompilationProblemReporter.reportErrors(logger, result.getErrors(), new String(cud.getFileName()),
                    true, new SourceFetcher() {
                        public String getSource() {
                            return new String(result.getCompilationUnit().getContents());
                        }
                    }, typeName, false);
        }
    }
    checkForErrorsEvent.end();
    if (compilationFailed) {
        logger.log(TreeLogger.ERROR, "Cannot proceed due to previous errors", null);
        throw new UnableToCompleteException();
    }
}

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

License:Open Source License

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

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

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

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

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

        cUnits[idx] = unit_sourceUnit;
    }

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

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

    batchCompiler.addCallBack(this);

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

    boolean hasErrors = requestor.hasErrors;

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

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

    return !hasErrors;
}

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 .ja  v  a  2  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 {/*from   ww  w.  ja v a  2 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" + "   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");
    }
}