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

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

Introduction

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

Prototype

public char[] getFileName() 

Source Link

Document

Answer the initial file name

Usage

From source file:ch.uzh.ifi.seal.changedistiller.ast.java.JavaCompilationUtils.java

License:Apache License

/**
 * Returns the compiled source as a {@link JavaCompilation}.
 * /*from  w ww .j  a  v a2 s . com*/
 * @param Java source
 *            to compile
 * @return the compilation of the Java source
 * @throws InvalidSyntaxException if the file has syntax errors.
 */
public static JavaCompilation compile(String source, String fileName) {
    CompilerOptions options = getDefaultCompilerOptions();
    Parser parser = createCommentRecorderParser(options);
    ICompilationUnit cu = createCompilationUnit(source, fileName);
    CompilationResult compilationResult = createDefaultCompilationResult(cu, options);
    JavaCompilation javaCompilation = new JavaCompilation(parser.parse(cu, compilationResult), parser.scanner);

    if (compilationResult.hasSyntaxError) {
        throw new InvalidSyntaxException(new String(compilationResult.getFileName()),
                compilationResult.toString());
    }

    return javaCompilation;
}

From source file:fr.inria.astor.core.manipulation.compiler.bytecode.JDTByteCodeCompiler.java

License:Open Source License

/**
 * //w ww .  j  ava2  s  . c o m
 */
@Override
public void acceptResult(CompilationResult result) {
    if (result.hasErrors()) {
        String problems = "";
        for (CategorizedProblem cp : result.getAllProblems()) {
            problems += new String(result.getFileName()) + "-l:(" + cp.getSourceLineNumber() + "):"
                    + cp.toString() + ", ";
        }
        classErrors.add(problems);
    }

    for (ClassFile f : result.getClassFiles()) {
        classFiles.add(f);
    }
}

From source file:io.takari.maven.plugins.compile.jdt.CompilerJdt.java

License:Open Source License

@Override
public void acceptResult(CompilationResult result) {
    if (result == null) {
        return; // ah?
    }/* w w w .  ja va  2 s  .  c o  m*/
    final String sourceName = new String(result.getFileName());
    final File sourceFile = new File(sourceName);

    Resource<File> input = context.getProcessedSource(sourceFile);

    // track type references
    if (result.rootReferences != null && result.qualifiedReferences != null
            && result.simpleNameReferences != null) {
        context.setAttribute(input.getResource(), ATTR_REFERENCES, new ReferenceCollection(
                result.rootReferences, result.qualifiedReferences, result.simpleNameReferences));
    }

    if (result.hasProblems() && (!isLenientProcOnly() || isShowWarnings())) {
        for (CategorizedProblem problem : result.getProblems()) {
            MessageSeverity severity = isLenientProcOnly() ? MessageSeverity.WARNING
                    : problem.isError() ? MessageSeverity.ERROR : MessageSeverity.WARNING;
            input.addMessage(problem.getSourceLineNumber(), ((DefaultProblem) problem).column,
                    problem.getMessage(), severity, null /* cause */);
        }
    }

    try {
        if (!result.hasErrors() && !isProcOnly()) {
            for (ClassFile classFile : result.getClassFiles()) {
                char[] filename = classFile.fileName();
                int length = filename.length;
                char[] relativeName = new char[length + 6];
                System.arraycopy(filename, 0, relativeName, 0, length);
                System.arraycopy(SuffixConstants.SUFFIX_class, 0, relativeName, length, 6);
                CharOperation.replace(relativeName, '/', File.separatorChar);
                String relativeStringName = new String(relativeName);
                writeClassFile(input, relativeStringName, classFile);
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // XXX double check affected sources are recompiled when this source has errors
}

From source file:org.codehaus.jdt.groovy.integration.internal.GroovyLanguageSupport.java

License:Open Source License

public CompilationUnitDeclaration newCompilationUnitDeclaration(ICompilationUnit unit,
        ProblemReporter problemReporter, CompilationResult compilationResult, int sourceLength) {
    if (ContentTypeUtils.isGroovyLikeFileName(compilationResult.getFileName())) {
        CompilerConfiguration groovyCompilerConfig = new CompilerConfiguration();
        // groovyCompilerConfig.setPluginFactory(new ErrorRecoveredCSTParserPluginFactory(null));
        ErrorCollector errorCollector = new GroovyErrorCollectorForJDT(groovyCompilerConfig);
        SourceUnit groovySourceUnit = new SourceUnit(new String(compilationResult.getFileName()),
                new String(unit.getContents()), groovyCompilerConfig, null, errorCollector);

        // FIXASC missing the classloader configuration (eg. to include transformers)
        org.codehaus.groovy.control.CompilationUnit groovyCU = new org.codehaus.groovy.control.CompilationUnit(
                groovyCompilerConfig);/*from w ww  .  j a v a2 s. c o m*/
        // groovyCU.removeOutputPhaseOperation();
        JDTResolver resolver = new JDTResolver(groovyCU);
        groovyCU.setResolveVisitor(resolver);

        // TODO groovy get this from the Antlr parser
        compilationResult.lineSeparatorPositions = GroovyUtils.getSourceLineSeparatorsIn(unit.getContents());

        groovyCU.addSource(groovySourceUnit);
        GroovyCompilationUnitDeclaration gcuDeclaration = new GroovyCompilationUnitDeclaration(problemReporter,
                compilationResult, sourceLength, groovyCU, groovySourceUnit, null);

        // boolean success =
        gcuDeclaration.processToPhase(Phases.CONVERSION);

        // Regardless of a successful outcome, build what is possible in the face of any errors
        gcuDeclaration.populateCompilationUnitDeclaration();
        for (TypeDeclaration decl : gcuDeclaration.types) {
            GroovyTypeDeclaration gtDeclaration = (GroovyTypeDeclaration) decl;
            resolver.record(gtDeclaration);
        }

        return gcuDeclaration;
    } else {
        return new CompilationUnitDeclaration(problemReporter, compilationResult, sourceLength);
    }
}

From source file:org.conqat.engine.java.ecj.ErrorAwareCompilerRequestor.java

License:Apache License

/** {@inheritDoc} */
@Override/*from w w w  .j  a  v a 2  s . com*/
public void acceptResult(CompilationResult result) {
    if (String.valueOf(result.getFileName()).equals(path)) {
        EcjUtils.addAllProblems(result.getErrors(), errors);
    }
}

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

License:Open Source License

/**
 * Add the initial set of compilation units into the loop
 *  ->  build compilation unit declarations, their bindings and record their results.
 *//*from www  . ja v a  2  s  .  co  m*/
protected void beginToCompile(org.eclipse.jdt.internal.compiler.env.ICompilationUnit[] sourceUnits,
        String[] bindingKeys) {
    int sourceLength = sourceUnits.length;
    int keyLength = bindingKeys.length;
    int maxUnits = sourceLength + keyLength;
    this.totalUnits = 0;
    this.unitsToProcess = new CompilationUnitDeclaration[maxUnits];
    int index = 0;

    // walks the source units
    this.requestedSources = new HashtableOfObject();
    for (int i = 0; i < sourceLength; i++) {
        org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = sourceUnits[i];
        CompilationUnitDeclaration parsedUnit;
        CompilationResult unitResult = new CompilationResult(sourceUnit, index++, maxUnits,
                this.options.maxProblemsPerUnit);
        try {
            if (this.options.verbose) {
                this.out.println(
                        Messages.bind(Messages.compilation_request, new String[] { String.valueOf(index++ + 1),
                                String.valueOf(maxUnits), new String(sourceUnit.getFileName()) }));
            }
            // diet parsing for large collection of units
            if (this.totalUnits < this.parseThreshold) {
                parsedUnit = this.parser.parse(sourceUnit, unitResult);
            } else {
                parsedUnit = this.parser.dietParse(sourceUnit, unitResult);
            }
            // initial type binding creation
            this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
            addCompilationUnit(sourceUnit, parsedUnit);
            this.requestedSources.put(unitResult.getFileName(), sourceUnit);
            worked(1);
        } finally {
            sourceUnits[i] = null; // no longer hold onto the unit
        }
    }

    // walk the binding keys
    this.requestedKeys = new HashtableOfObject();
    for (int i = 0; i < keyLength; i++) {
        BindingKeyResolver resolver = new BindingKeyResolver(bindingKeys[i], this, this.lookupEnvironment);
        resolver.parse(true/*pause after fully qualified name*/);
        // If it doesn't have a type name, then it is either an array type, package or base type, which will definitely not have a compilation unit.
        // Skipping it will speed up performance because the call will open jars. (theodora)
        CompilationUnitDeclaration parsedUnit = resolver.hasTypeName()
                ? resolver.getCompilationUnitDeclaration()
                : null;
        if (parsedUnit != null) {
            char[] fileName = parsedUnit.compilationResult.getFileName();
            Object existing = this.requestedKeys.get(fileName);
            if (existing == null)
                this.requestedKeys.put(fileName, resolver);
            else if (existing instanceof ArrayList)
                ((ArrayList) existing).add(resolver);
            else {
                ArrayList list = new ArrayList();
                list.add(existing);
                list.add(resolver);
                this.requestedKeys.put(fileName, list);
            }

        } else {
            char[] key = resolver.hasTypeName() ? resolver.getKey().toCharArray() // binary binding
                    : CharOperation.concatWith(resolver.compoundName(), '.'); // package binding or base type binding
            this.requestedKeys.put(key, resolver);
        }
        worked(1);
    }

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

From source file:org.eclipse.jdt.internal.compiler.parser.SourceTypeConverter.java

License:Open Source License

private CompilationUnitDeclaration convert(ISourceType[] sourceTypes, CompilationResult compilationResult)
        throws JavaModelException {
    // GROOVY start
    /* old {// w w  w  . ja  v  a 2  s  .  c o m
    this.unit = new CompilationUnitDeclaration(this.problemReporter, compilationResult, 0);
    } new */
    this.unit = LanguageSupportFactory.newCompilationUnitDeclaration(
            (ICompilationUnit) ((SourceTypeElementInfo) sourceTypes[0]).getHandle().getCompilationUnit(),
            this.problemReporter, compilationResult, 0);
    // GROOVY end

    // not filled at this point

    if (sourceTypes.length == 0)
        return this.unit;
    SourceTypeElementInfo topLevelTypeInfo = (SourceTypeElementInfo) sourceTypes[0];
    org.eclipse.jdt.core.ICompilationUnit cuHandle = topLevelTypeInfo.getHandle().getCompilationUnit();
    this.cu = (ICompilationUnit) cuHandle;

    // GROOVY start
    // trying to avoid building an incorrect TypeDeclaration below (when it should be a GroovyTypeDeclaration).
    // similar to code below that creates the Parser and calls dietParse
    // FIXASC think about doing the necessary rewrite below rather than this - does it make things too slow?

    //      final boolean isInterestingProject = LanguageSupportFactory.isInterestingProject(compilationResult.getCompilationUnit().getjavaBuilder.getProject());
    // GROOVY should be 'true' here?
    if (LanguageSupportFactory.isInterestingSourceFile(new String(compilationResult.getFileName()))) {
        try {
            return LanguageSupportFactory
                    .getParser(this, this.problemReporter.options, this.problemReporter, true, 3)
                    .dietParse(this.cu, compilationResult);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    // GROOVY end

    if (this.has1_5Compliance
            && ((CompilationUnitElementInfo) ((JavaElement) this.cu).getElementInfo()).annotationNumber > 10) { // experimental value
        // If more than 10 annotations, diet parse as this is faster, but not if
        // the client wants local and anonymous types to be converted (https://bugs.eclipse.org/bugs/show_bug.cgi?id=254738) 
        if ((this.flags & LOCAL_TYPE) == 0) {
            return new Parser(this.problemReporter, true).dietParse(this.cu, compilationResult);
        }
    }

    /* only positions available */
    int start = topLevelTypeInfo.getNameSourceStart();
    int end = topLevelTypeInfo.getNameSourceEnd();

    /* convert package and imports */
    String[] packageName = ((PackageFragment) cuHandle.getParent()).names;
    if (packageName.length > 0)
        // if its null then it is defined in the default package
        this.unit.currentPackage = createImportReference(packageName, start, end, false,
                ClassFileConstants.AccDefault);
    IImportDeclaration[] importDeclarations = topLevelTypeInfo.getHandle().getCompilationUnit().getImports();
    int importCount = importDeclarations.length;
    this.unit.imports = new ImportReference[importCount];
    for (int i = 0; i < importCount; i++) {
        ImportDeclaration importDeclaration = (ImportDeclaration) importDeclarations[i];
        ISourceImport sourceImport = (ISourceImport) importDeclaration.getElementInfo();
        String nameWithoutStar = importDeclaration.getNameWithoutStar();
        this.unit.imports[i] = createImportReference(
                Util.splitOn('.', nameWithoutStar, 0, nameWithoutStar.length()),
                sourceImport.getDeclarationSourceStart(), sourceImport.getDeclarationSourceEnd(),
                importDeclaration.isOnDemand(), sourceImport.getModifiers());
    }
    /* convert type(s) */
    try {
        int typeCount = sourceTypes.length;
        final TypeDeclaration[] types = new TypeDeclaration[typeCount];
        /*
         * We used a temporary types collection to prevent this.unit.types from being null during a call to
         * convert(...) when the source is syntactically incorrect and the parser is flushing the unit's types.
         * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=97466
         */
        for (int i = 0; i < typeCount; i++) {
            SourceTypeElementInfo typeInfo = (SourceTypeElementInfo) sourceTypes[i];
            types[i] = convert((SourceType) typeInfo.getHandle(), compilationResult);
        }
        this.unit.types = types;
        return this.unit;
    } catch (AnonymousMemberFound e) {
        return new Parser(this.problemReporter, true).parse(this.cu, compilationResult);
    }
}

From source file:org.eclipse.jdt.internal.compiler.problem.ProblemHandler.java

License:Open Source License

public void handle(int problemId, String[] problemArguments, int elaborationId, String[] messageArguments,
        int severity, int problemStartPosition, int problemEndPosition, ReferenceContext referenceContext,
        CompilationResult unitResult) {

    if (severity == ProblemSeverities.Ignore)
        return;// w  w  w . ja  v a 2 s. c  o  m

    // if no reference context, we need to abort from the current compilation process
    if (referenceContext == null) {
        if ((severity & ProblemSeverities.Error) != 0) { // non reportable error is fatal
            CategorizedProblem problem = this.createProblem(null, problemId, problemArguments, elaborationId,
                    messageArguments, severity, 0, 0, 0, 0);
            throw new AbortCompilation(null, problem);
        } else {
            return; // ignore non reportable warning
        }
    }

    int[] lineEnds;
    int lineNumber = problemStartPosition >= 0 ? Util.getLineNumber(problemStartPosition,
            lineEnds = unitResult.getLineSeparatorPositions(), 0, lineEnds.length - 1) : 0;
    int columnNumber = problemStartPosition >= 0
            ? Util.searchColumnNumber(unitResult.getLineSeparatorPositions(), lineNumber, problemStartPosition)
            : 0;
    CategorizedProblem problem = this.createProblem(unitResult.getFileName(), problemId, problemArguments,
            elaborationId, messageArguments, severity, problemStartPosition, problemEndPosition, lineNumber,
            columnNumber);

    if (problem == null)
        return; // problem couldn't be created, ignore

    switch (severity & ProblemSeverities.Error) {
    case ProblemSeverities.Error:
        record(problem, unitResult, referenceContext);
        if ((severity & ProblemSeverities.Fatal) != 0) {
            referenceContext.tagAsHavingErrors();
            // should abort ?
            int abortLevel;
            if ((abortLevel = this.policy.stopOnFirstError() ? ProblemSeverities.AbortCompilation
                    : severity & ProblemSeverities.Abort) != 0) {
                referenceContext.abort(abortLevel, problem);
            }
        }
        break;
    case ProblemSeverities.Warning:
        // GROOVY start - still required?
        if ((this.options.groovyFlags & 0x01) != 0) {
            if ((unitResult.compilationUnit instanceof SourceFile)
                    && ((SourceFile) unitResult.compilationUnit).isInLinkedSourceFolder()) {
                return;
            }
        }
        // GROOVY end
        record(problem, unitResult, referenceContext);
        break;
    }
}

From source file:org.eclipse.xtext.xbase.compiler.InMemoryJavaCompiler.java

License:Open Source License

public InMemoryJavaCompiler.Result compile(final JavaSource... sources) {
    final InMemoryJavaCompiler.Result result = new InMemoryJavaCompiler.Result(this.parentClassLoader);
    IErrorHandlingPolicy _proceedWithAllProblems = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final ICompilerRequestor _function = (CompilationResult it) -> {
        ClassFile[] _classFiles = it.getClassFiles();
        for (final ClassFile cf : _classFiles) {
            final Function1<char[], String> _function_1 = (char[] it_1) -> {
                return String.valueOf(it_1);
            };//from w w  w . jav a  2s  .co m
            result.classMap.put(
                    IterableExtensions.join(ListExtensions.<char[], String>map(
                            ((List<char[]>) Conversions.doWrapArray(cf.getCompoundName())), _function_1), "."),
                    cf.getBytes());
        }
    };
    org.eclipse.jdt.internal.compiler.Compiler compiler = new org.eclipse.jdt.internal.compiler.Compiler(
            this.nameEnv, _proceedWithAllProblems, this.compilerOptions, _function,
            new DefaultProblemFactory() {
                @Override
                public CategorizedProblem createProblem(final char[] originatingFileName, final int problemId,
                        final String[] problemArguments, final int elaborationId,
                        final String[] messageArguments, final int severity, final int startPosition,
                        final int endPosition, final int lineNumber, final int columnNumber) {
                    final CategorizedProblem problem = super.createProblem(originatingFileName, problemId,
                            problemArguments, elaborationId, messageArguments, severity, startPosition,
                            endPosition, lineNumber, columnNumber);
                    result.compilationProblems.add(problem);
                    return problem;
                }

                @Override
                public CategorizedProblem createProblem(final char[] originatingFileName, final int problemId,
                        final String[] problemArguments, final String[] messageArguments, final int severity,
                        final int startPosition, final int endPosition, final int lineNumber,
                        final int columnNumber) {
                    final CategorizedProblem problem = super.createProblem(originatingFileName, problemId,
                            problemArguments, messageArguments, severity, startPosition, endPosition,
                            lineNumber, columnNumber);
                    result.compilationProblems.add(problem);
                    return problem;
                }
            });
    final Function1<JavaSource, CompilationUnit> _function_1 = (JavaSource it) -> {
        char[] _charArray = it.getCode().toCharArray();
        String _fileName = it.getFileName();
        return new CompilationUnit(_charArray, _fileName, null);
    };
    ICompilationUnit[] units = ((ICompilationUnit[]) Conversions.unwrapArray(
            ListExtensions.<JavaSource, CompilationUnit>map(
                    ((List<JavaSource>) Conversions.doWrapArray(sources)), _function_1),
            ICompilationUnit.class));
    compiler.compile(units);
    return result;
}

From source file:org.eclipse.xtext.xbase.testing.InMemoryJavaCompiler.java

License:Open Source License

public InMemoryJavaCompiler.Result compile(final JavaSource... sources) {
    final InMemoryJavaCompiler.Result result = new InMemoryJavaCompiler.Result(this.parentClassLoader);
    IErrorHandlingPolicy _proceedWithAllProblems = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final ICompilerRequestor _function = (CompilationResult it) -> {
        ClassFile[] _classFiles = it.getClassFiles();
        for (final ClassFile cf : _classFiles) {
            char[][] _compoundName = cf.getCompoundName();
            final Function1<char[], String> _function_1 = (char[] it_1) -> {
                return String.valueOf(it_1);
            };// www  . j av a 2 s  .c o m
            List<String> _map = ListExtensions
                    .<char[], String>map(((List<char[]>) Conversions.doWrapArray(_compoundName)), _function_1);
            String _join = IterableExtensions.join(_map, ".");
            byte[] _bytes = cf.getBytes();
            result.classMap.put(_join, _bytes);
        }
    };
    org.eclipse.jdt.internal.compiler.Compiler compiler = new org.eclipse.jdt.internal.compiler.Compiler(
            this.nameEnv, _proceedWithAllProblems, this.compilerOptions, _function,
            new DefaultProblemFactory() {
                @Override
                public CategorizedProblem createProblem(final char[] originatingFileName, final int problemId,
                        final String[] problemArguments, final int elaborationId,
                        final String[] messageArguments, final int severity, final int startPosition,
                        final int endPosition, final int lineNumber, final int columnNumber) {
                    final CategorizedProblem problem = super.createProblem(originatingFileName, problemId,
                            problemArguments, elaborationId, messageArguments, severity, startPosition,
                            endPosition, lineNumber, columnNumber);
                    result.compilationProblems.add(problem);
                    return problem;
                }

                @Override
                public CategorizedProblem createProblem(final char[] originatingFileName, final int problemId,
                        final String[] problemArguments, final String[] messageArguments, final int severity,
                        final int startPosition, final int endPosition, final int lineNumber,
                        final int columnNumber) {
                    final CategorizedProblem problem = super.createProblem(originatingFileName, problemId,
                            problemArguments, messageArguments, severity, startPosition, endPosition,
                            lineNumber, columnNumber);
                    result.compilationProblems.add(problem);
                    return problem;
                }
            });
    final Function1<JavaSource, CompilationUnit> _function_1 = (JavaSource it) -> {
        String _code = it.getCode();
        char[] _charArray = _code.toCharArray();
        String _fileName = it.getFileName();
        return new CompilationUnit(_charArray, _fileName, null);
    };
    ICompilationUnit[] units = ((ICompilationUnit[]) Conversions.unwrapArray(
            ListExtensions.<JavaSource, CompilationUnit>map(
                    ((List<JavaSource>) Conversions.doWrapArray(sources)), _function_1),
            ICompilationUnit.class));
    compiler.compile(units);
    return result;
}