Example usage for org.eclipse.jdt.internal.compiler CompilationResult getCompilationUnit

List of usage examples for org.eclipse.jdt.internal.compiler CompilationResult getCompilationUnit

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler CompilationResult getCompilationUnit.

Prototype

public ICompilationUnit getCompilationUnit() 

Source Link

Document

Answer the initial compilation unit corresponding to the present compilation result

Usage

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.  j av  a2s . c om
 * 
 * @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:net.sf.j2s.core.builder.AbstractImageBuilder.java

License:Open Source License

public void acceptResult(CompilationResult result) {
    // In Batch mode, we write out the class files, hold onto the dependency info
    // & additional types and report problems.

    // In Incremental mode, when writing out a class file we need to compare it
    // against the previous file, remembering if structural changes occured.
    // Before reporting the new problems, we need to update the problem count &
    // remove the old problems. Plus delete additional class files that no longer exist.

    SourceFile compilationUnit = (SourceFile) result.getCompilationUnit(); // go directly back to the sourceFile
    if (!this.workQueue.isCompiled(compilationUnit)) {
        this.workQueue.finished(compilationUnit);

        try {/*from ww  w.  ja v a  2 s  . c  o  m*/
            updateProblemsFor(compilationUnit, result); // record compilation problems before potentially adding duplicate errors
            updateTasksFor(compilationUnit, result); // record tasks
        } catch (CoreException e) {
            throw internalException(e);
        }

        if (result.hasInconsistentToplevelHierarchies)
            // ensure that this file is always retrieved from source for the rest of the build
            if (!this.problemSourceFiles.contains(compilationUnit))
                this.problemSourceFiles.add(compilationUnit);

        IType mainType = null;
        String mainTypeName = null;
        String typeLocator = compilationUnit.typeLocator();
        ClassFile[] classFiles = result.getClassFiles();
        int length = classFiles.length;
        ArrayList duplicateTypeNames = null;
        ArrayList definedTypeNames = new ArrayList(length);
        for (int i = 0; i < length; i++) {
            ClassFile classFile = classFiles[i];

            char[][] compoundName = classFile.getCompoundName();
            char[] typeName = compoundName[compoundName.length - 1];
            boolean isNestedType = classFile.isNestedType;

            // Look for a possible collision, if one exists, report an error but do not write the class file
            if (isNestedType) {
                String qualifiedTypeName = new String(classFile.outerMostEnclosingClassFile().fileName());
                if (this.newState.isDuplicateLocator(qualifiedTypeName, typeLocator))
                    continue;
            } else {
                String qualifiedTypeName = new String(classFile.fileName()); // the qualified type name "p1/p2/A"
                if (this.newState.isDuplicateLocator(qualifiedTypeName, typeLocator)) {
                    if (duplicateTypeNames == null)
                        duplicateTypeNames = new ArrayList();
                    duplicateTypeNames.add(compoundName);
                    if (mainType == null) {
                        try {
                            mainTypeName = compilationUnit.initialTypeName; // slash separated qualified name "p1/p1/A"
                            mainType = this.javaBuilder.javaProject.findType(mainTypeName.replace('/', '.'));
                        } catch (JavaModelException e) {
                            // ignore
                        }
                    }
                    IType type;
                    if (qualifiedTypeName.equals(mainTypeName)) {
                        type = mainType;
                    } else {
                        String simpleName = qualifiedTypeName.substring(qualifiedTypeName.lastIndexOf('/') + 1);
                        type = mainType == null ? null : mainType.getCompilationUnit().getType(simpleName);
                    }
                    createProblemFor(compilationUnit.resource, type,
                            Messages.bind(Messages.build_duplicateClassFile, new String(typeName)),
                            JavaCore.ERROR);
                    continue;
                }
                this.newState.recordLocatorForType(qualifiedTypeName, typeLocator);
                if (result.checkSecondaryTypes && !qualifiedTypeName.equals(compilationUnit.initialTypeName))
                    acceptSecondaryType(classFile);
            }
            try {
                definedTypeNames.add(writeClassFile(classFile, compilationUnit, !isNestedType));
            } catch (CoreException e) {
                Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$
                if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS)
                    createProblemFor(compilationUnit.resource, null,
                            Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR);
                else
                    createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile,
                            JavaCore.ERROR);
            }
        }
        if (result.hasAnnotations && this.filesWithAnnotations != null) // only initialized if an annotation processor is attached
            this.filesWithAnnotations.add(compilationUnit);

        this.compiler.lookupEnvironment.releaseClassFiles(classFiles);
        finishedWith(typeLocator, result, compilationUnit.getMainTypeName(), definedTypeNames,
                duplicateTypeNames);
        this.notifier.compiled(compilationUnit);
    }
}

From source file:net.sf.j2s.core.builder.IncrementalImageBuilder.java

License:Open Source License

protected void finishedWith(String sourceLocator, CompilationResult result, char[] mainTypeName,
        ArrayList definedTypeNames, ArrayList duplicateTypeNames) {
    char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(sourceLocator);
    if (previousTypeNames == null)
        previousTypeNames = new char[][] { mainTypeName };
    IPath packagePath = null;/*  w w  w .  j  av  a2  s  . co m*/
    next: for (int i = 0, l = previousTypeNames.length; i < l; i++) {
        char[] previous = previousTypeNames[i];
        for (int j = 0, m = definedTypeNames.size(); j < m; j++)
            if (CharOperation.equals(previous, (char[]) definedTypeNames.get(j)))
                continue next;

        SourceFile sourceFile = (SourceFile) result.getCompilationUnit();
        if (packagePath == null) {
            int count = sourceFile.sourceLocation.sourceFolder.getFullPath().segmentCount();
            packagePath = sourceFile.resource.getFullPath().removeFirstSegments(count).removeLastSegments(1);
        }
        if (this.secondaryTypesToRemove == null)
            this.secondaryTypesToRemove = new SimpleLookupTable();
        ArrayList types = (ArrayList) this.secondaryTypesToRemove.get(sourceFile.sourceLocation.binaryFolder);
        if (types == null)
            types = new ArrayList(definedTypeNames.size());
        types.add(packagePath.append(new String(previous)));
        this.secondaryTypesToRemove.put(sourceFile.sourceLocation.binaryFolder, types);
    }
    super.finishedWith(sourceLocator, result, mainTypeName, definedTypeNames, duplicateTypeNames);
}

From source file:net.sf.jasperreports.engine.design.JRJdtCompiler.java

License:LGPL

protected ICompilerRequestor getCompilerRequestor(final JRCompilationUnit[] units,
        final StringBuffer problemBuffer) {
    final ICompilerRequestor requestor = new ICompilerRequestor() {
        public void acceptResult(CompilationResult result) {
            String className = ((CompilationUnit) result.getCompilationUnit()).className;

            int classIdx;
            for (classIdx = 0; classIdx < units.length; ++classIdx) {
                if (className.equals(units[classIdx].getName())) {
                    break;
                }//from  ww w  .j  a  va  2  s .c o m
            }

            if (result.hasErrors()) {
                String sourceCode = units[classIdx].getSourceCode();

                IProblem[] problems = getJavaCompilationErrors(result);
                for (int i = 0; i < problems.length; i++) {
                    IProblem problem = problems[i];
                    //if (problem.isError()) 
                    {
                        problemBuffer.append(i + 1);
                        problemBuffer.append(". ");
                        problemBuffer.append(problem.getMessage());

                        if (problem.getSourceStart() >= 0 && problem.getSourceEnd() >= 0) {
                            int problemStartIndex = sourceCode.lastIndexOf("\n", problem.getSourceStart()) + 1;
                            int problemEndIndex = sourceCode.indexOf("\n", problem.getSourceEnd());
                            if (problemEndIndex < 0) {
                                problemEndIndex = sourceCode.length();
                            }

                            problemBuffer.append("\n");
                            problemBuffer.append(sourceCode.substring(problemStartIndex, problemEndIndex));
                            problemBuffer.append("\n");
                            for (int j = problemStartIndex; j < problem.getSourceStart(); j++) {
                                problemBuffer.append(" ");
                            }
                            if (problem.getSourceStart() == problem.getSourceEnd()) {
                                problemBuffer.append("^");
                            } else {
                                problemBuffer.append("<");
                                for (int j = problem.getSourceStart() + 1; j < problem.getSourceEnd(); j++) {
                                    problemBuffer.append("-");
                                }
                                problemBuffer.append(">");
                            }
                        }

                        problemBuffer.append("\n");
                    }
                }
                problemBuffer.append(problems.length);
                problemBuffer.append(" errors\n");
            }
            if (problemBuffer.length() == 0) {
                ClassFile[] resultClassFiles = result.getClassFiles();
                for (int i = 0; i < resultClassFiles.length; i++) {
                    units[classIdx].setCompileData(resultClassFiles[i].getBytes());
                }
            }
        }
    };

    return requestor;
}

From source file:org.ant4eclipse.lib.jdt.ecj.internal.tools.CompilerRequestorImpl.java

License:Open Source License

/**
 * {@inheritDoc}/*ww  w .  ja v  a2s. c o  m*/
 */
public void acceptResult(CompilationResult result) {

    // get the compilation unit...
    CompilationUnitImpl compilationUnitImpl = (CompilationUnitImpl) result.getCompilationUnit();

    // ...and the source file
    SourceFile sourceFile = compilationUnitImpl.getSourceFile();

    // return immediately if the source file is a ReferableSourceFile
    if (sourceFile instanceof ReferableSourceFile) {

        // add the problems...
        if (result.getAllProblems() != null) {
            if (A4ELogging.isTraceingEnabled()) {
                A4ELogging.trace("Could not compile referenced class '%s'. Reason: %s",
                        sourceFile.getSourceFileName(), Arrays.asList(result.getAllProblems()));
            }
        }

        return;
    }

    // get the destination directory
    File destinationDirectory = sourceFile.getDestinationFolder();

    if (!result.hasErrors()) {
        ClassFile[] classFiles = result.getClassFiles();
        for (ClassFile classFile2 : classFiles) {
            char[][] compoundName = classFile2.getCompoundName();
            StringBuffer classFileName = new StringBuffer();
            for (int j = 0; j < compoundName.length; j++) {
                classFileName.append(compoundName[j]);
                if (j < compoundName.length - 1) {
                    classFileName.append('/');
                }
            }
            classFileName.append(".class");
            File classFile = new File(destinationDirectory, classFileName.toString());
            File classDir = classFile.getParentFile();
            if (!classDir.exists()) {
                classDir.mkdirs();
            }
            try {
                A4ELogging.debug("writing class file: '%s'", classFile);
                Utilities.writeFile(classFile, classFile2.getBytes());
                this._compiledClassFiles.put(classFileName.toString(), classFile);
            } catch (Ant4EclipseException ioe) {
                A4ELogging.error("Could not write classfile '%s': %s", classFileName.toString(),
                        ioe.toString());
                ioe.printStackTrace();
                this._compilationSuccessful = false;
            }
        }
    } else {
        this._compilationSuccessful = false;
    }

    // add the problems...
    if (result.getAllProblems() != null) {
        this._categorizedProblems.addAll(Arrays.asList(result.getAllProblems()));
    }
}