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

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

Introduction

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

Prototype

public char[] getFileName() 

Source Link

Usage

From source file:com.android.tools.lint.EcjParser.java

License:Apache License

/** Parse the given source units and class path and store it into the given output map */
public static INameEnvironment parse(CompilerOptions options, @NonNull List<ICompilationUnit> sourceUnits,
        @NonNull List<String> classPath, @NonNull Map<ICompilationUnit, CompilationUnitDeclaration> outputMap,
        @Nullable LintClient client) {//  w  w w  .ja  va  2  s. c o m
    INameEnvironment environment = new FileSystem(classPath.toArray(new String[classPath.size()]),
            new String[0], options.defaultEncoding);
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    ICompilerRequestor requestor = new ICompilerRequestor() {
        @Override
        public void acceptResult(CompilationResult result) {
            // Not used; we need the corresponding CompilationUnitDeclaration for the source
            // units (the AST parsed from source) which we don't get access to here, so we
            // instead subclass AST to get our hands on them.
        }
    };

    NonGeneratingCompiler compiler = new NonGeneratingCompiler(environment, policy, options, requestor,
            problemFactory, outputMap);
    try {
        compiler.compile(sourceUnits.toArray(new ICompilationUnit[sourceUnits.size()]));
    } catch (OutOfMemoryError e) {
        environment.cleanup();

        // Since we're running out of memory, if it's all still held we could potentially
        // fail attempting to log the failure. Actively get rid of the large ECJ data
        // structure references first so minimize the chance of that
        //noinspection UnusedAssignment
        compiler = null;
        //noinspection UnusedAssignment
        environment = null;
        //noinspection UnusedAssignment
        requestor = null;
        //noinspection UnusedAssignment
        problemFactory = null;
        //noinspection UnusedAssignment
        policy = null;

        String msg = "Ran out of memory analyzing .java sources with ECJ: Some lint checks "
                + "may not be accurate (missing type information from the compiler)";
        if (client != null) {
            // Don't log exception too; this isn't a compiler error per se where we
            // need to pin point the exact unlucky code that asked for memory when it
            // had already run out
            client.log(null, msg);
        } else {
            System.out.println(msg);
        }
    } catch (Throwable t) {
        if (client != null) {
            CompilationUnitDeclaration currentUnit = compiler.getCurrentUnit();
            if (currentUnit == null || currentUnit.getFileName() == null) {
                client.log(t, "ECJ compiler crashed");
            } else {
                client.log(t, "ECJ compiler crashed processing %1$s", new String(currentUnit.getFileName()));
            }
        } else {
            t.printStackTrace();
        }

        environment.cleanup();
        environment = null;
    }

    return environment;
}

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 {//from w w  w  .  j a va 2 s. c  om
        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.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 .j  av  a  2s .  c om*/
    }
}

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()));
    }/* ww w. j av  a  2  s . com*/
}

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

License:Open Source License

/**
 * Collect data about interesting methods on a particular type in a
 * compilation unit.//  w  ww .  j  ava  2  s  .c  o m
 *  
 * @param cud
 * @param typeDecl
 */
private void collectMethods(CompilationUnitDeclaration cud, TypeDeclaration typeDecl) {
    AbstractMethodDeclaration[] methods = typeDecl.methods;
    if (methods == null) {
        return;
    }

    // Lazy initialize these when an interesting method is actually hit.
    String enclosingType = null;
    String loc = null;
    boolean lazyInitialized = false;

    for (AbstractMethodDeclaration method : methods) {
        if (!interestingMethod(method)) {
            continue;
        }

        if (!lazyInitialized) {
            char[] constantPoolName = typeDecl.binding.constantPoolName();
            if (constantPoolName == null) {
                // Unreachable local type
                return;
            }
            enclosingType = InternalName.toBinaryName(String.valueOf(constantPoolName));
            loc = String.valueOf(cud.getFileName());
            lazyInitialized = true;
        }
        processMethod(typeDecl, method, enclosingType, loc);
    }
}

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   ww  w .  ja  va 2  s . co  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:lombok.core.debug.DebugSnapshot.java

License:Open Source License

private String ownerName() {
    CompilationUnitDeclaration node = owner.get();
    if (node == null)
        return "--GCed--";
    char[] tn = node.getMainTypeName();
    char[] fs = node.getFileName();
    if (tn == null || tn.length == 0) {
        return (fs == null || fs.length == 0) ? "--UNKNOWN--" : new String(fs);
    }/*from   w  ww  .  j a  va 2s  .  c  om*/

    return new String(tn);
}

From source file:lombok.eclipse.handlers.EclipseHandlerUtil.java

License:Open Source License

/**
 * Generates an error in the Eclipse error log. Note that most people never look at it!
 * //w w w  .j  a  va  2  s .  co  m
 * @param cud The {@code CompilationUnitDeclaration} where the error occurred.
 *     An error will be generated on line 0 linking to the error log entry. Can be {@code null}.
 * @param message Human readable description of the problem.
 * @param ex The associated exception. Can be {@code null}.
 */
public static void error(CompilationUnitDeclaration cud, String message, Throwable ex) {
    ProblemReporter.error(message, ex);
    if (cud != null)
        EclipseAST.addProblemToCompilationResult(cud.getFileName(), cud.compilationResult, false,
                message + " - See error log.", 0, 0);
}

From source file:lombok.eclipse.TransformEclipseAST.java

License:Open Source License

/**
 * This method is called immediately after Eclipse finishes building a CompilationUnitDeclaration, which is
 * the top-level AST node when Eclipse parses a source file. The signature is 'magic' - you should not
 * change it!/*from   w  w  w  . j  a  v a2  s  .c  o  m*/
 * 
 * Eclipse's parsers often operate in diet mode, which means many parts of the AST have been left blank.
 * Be ready to deal with just about anything being null, such as the Statement[] arrays of the Method AST nodes.
 * 
 * @param parser The Eclipse parser object that generated the AST. Not actually used; mostly there to satisfy parameter rules for lombok.patcher scripts.
 * @param ast The AST node belonging to the compilation unit (java speak for a single source file).
 */
public static void transform(Parser parser, CompilationUnitDeclaration ast) {
    if (disableLombok)
        return;

    if (Symbols.hasSymbol("lombok.disable"))
        return;

    // Do NOT abort if (ast.bits & ASTNode.HasAllMethodBodies) != 0 - that doesn't work.

    try {
        DebugSnapshotStore.INSTANCE.snapshot(ast, "transform entry");
        long histoToken = lombokTracker == null ? 0L : lombokTracker.start();
        EclipseAST existing = getAST(ast, false);
        new TransformEclipseAST(existing).go();
        if (lombokTracker != null)
            lombokTracker.end(histoToken);
        DebugSnapshotStore.INSTANCE.snapshot(ast, "transform exit");
    } catch (Throwable t) {
        DebugSnapshotStore.INSTANCE.snapshot(ast, "transform error: %s", t.getClass().getSimpleName());
        try {
            String message = "Lombok can't parse this source: " + t.toString();

            EclipseAST.addProblemToCompilationResult(ast.getFileName(), ast.compilationResult, false, message,
                    0, 0);
            t.printStackTrace();
        } catch (Throwable t2) {
            try {
                error(ast, "Can't create an error in the problems dialog while adding: " + t.toString(), t2);
            } catch (Throwable t3) {
                //This seems risky to just silently turn off lombok, but if we get this far, something pretty
                //drastic went wrong. For example, the eclipse help system's JSP compiler will trigger a lombok call,
                //but due to class loader shenanigans we'll actually get here due to a cascade of
                //ClassNotFoundErrors. This is the right action for the help system (no lombok needed for that JSP compiler,
                //of course). 'disableLombok' is static, but each context classloader (e.g. each eclipse OSGi plugin) has
                //it's own edition of this class, so this won't turn off lombok everywhere.
                disableLombok = true;
            }
        }
    }
}

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

License:Open Source License

/**
 * Add the possibleMatch to the loop//www.  ja  v a2 s  .com
 *  ->  build compilation unit declarations, their bindings and record their results.
 */
protected boolean parseAndBuildBindings(PossibleMatch possibleMatch, boolean mustResolve) throws CoreException {
    if (this.progressMonitor != null && this.progressMonitor.isCanceled())
        throw new OperationCanceledException();

    try {
        if (BasicSearchEngine.VERBOSE)
            System.out.println("Parsing " + possibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$

        this.parser.nodeSet = possibleMatch.nodeSet;
        CompilationResult unitResult = new CompilationResult(possibleMatch, 1, 1,
                this.options.maxProblemsPerUnit);
        CompilationUnitDeclaration parsedUnit = this.parser.dietParse(possibleMatch, unitResult);
        if (parsedUnit != null) {
            if (!parsedUnit.isEmpty()) {
                if (mustResolve) {
                    this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
                }
                if (hasAlreadyDefinedType(parsedUnit))
                    return false; // skip type has it is hidden so not visible

                // GROOVY Start
                // old
                // getMethodBodies(parsedUnit, possibleMatch.nodeSet);
                // new
                // Only getMethodBodies for Java files
                if (!LanguageSupportFactory.isInterestingSourceFile(new String(parsedUnit.getFileName()))) {
                    getMethodBodies(parsedUnit, possibleMatch.nodeSet);
                }
                // GROOVY End
                if (this.patternLocator.mayBeGeneric && !mustResolve && possibleMatch.nodeSet.mustResolve) {
                    // special case: possible match node set force resolution although pattern does not
                    // => we need to build types for this compilation unit
                    this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
                }
            }

            // add the possibleMatch with its parsedUnit to matchesToProcess
            possibleMatch.parsedUnit = parsedUnit;
            int size = this.matchesToProcess.length;
            if (this.numberOfMatches == size)
                System.arraycopy(this.matchesToProcess, 0,
                        this.matchesToProcess = new PossibleMatch[size == 0 ? 1 : size * 2], 0,
                        this.numberOfMatches);
            this.matchesToProcess[this.numberOfMatches++] = possibleMatch;
        }
    } finally {
        this.parser.nodeSet = null;
    }
    return true;
}