Example usage for org.eclipse.jdt.internal.compiler.problem DefaultProblemFactory DefaultProblemFactory

List of usage examples for org.eclipse.jdt.internal.compiler.problem DefaultProblemFactory DefaultProblemFactory

Introduction

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

Prototype

public DefaultProblemFactory(Locale loc) 

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) {//  ww w .j  a  v a  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.codeassist.SelectionEngine.java

License:Open Source License

/**
 * The SelectionEngine is responsible for computing the selected object.
 *
 * It requires a searchable name environment, which supports some
 * specific search APIs, and a requestor to feed back the results to a UI.
 *
 *  @param nameEnvironment org.eclipse.jdt.internal.core.SearchableEnvironment
 *      used to resolve type/package references and search for types/packages
 *      based on partial names.// w  w w .  j a  v a  2 s.  co  m
 *
 *  @param requestor org.eclipse.jdt.internal.codeassist.ISelectionRequestor
 *      since the engine might produce answers of various forms, the engine
 *      is associated with a requestor able to accept all possible completions.
 *
 *  @param settings java.util.Map
 *      set of options used to configure the code assist engine.
 */
public SelectionEngine(SearchableEnvironment nameEnvironment, ISelectionRequestor requestor, Map settings,
        WorkingCopyOwner owner, IndexManager indexManager, JavaProject javaProject) {

    super(settings);

    this.requestor = requestor;
    this.indexManager = indexManager;
    this.javaProject = javaProject;
    this.nameEnvironment = nameEnvironment;

    ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
            this.compilerOptions, new DefaultProblemFactory(Locale.getDefault())) {

        public CategorizedProblem createProblem(char[] fileName, int problemId, String[] problemArguments,
                String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition,
                int lineNumber, int columnNumber) {
            CategorizedProblem pb = super.createProblem(fileName, problemId, problemArguments, messageArguments,
                    severity, problemStartPosition, problemEndPosition, lineNumber, columnNumber);
            if (SelectionEngine.this.problem == null && pb.isError() && (pb.getID() & IProblem.Syntax) == 0) {
                SelectionEngine.this.problem = pb;
            }

            return pb;
        }
    };
    this.lookupEnvironment = new LookupEnvironment(this, this.compilerOptions, problemReporter,
            nameEnvironment);
    this.parser = new SelectionParser(problemReporter);
    this.owner = owner;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.indexing.IndexManager.java

License:Open Source License

public SourceElementParser getSourceElementParser(JavaProject project, ISourceElementRequestor requestor) {
    // disable task tags to speed up parsing
    Map options = project.getOptions(true);
    options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
    try {/*from w  ww  .  j  a v a 2 s . c  o  m*/
        SourceElementParser parser = new IndexingParser(requestor,
                new DefaultProblemFactory(Locale.getDefault()), new CompilerOptions(options), true, // index local declarations
                true, // optimize string literals
                false); // do not use source javadoc parser to speed up parsing
        parser.reportOnlyOneSyntaxError = true;

        // Always check javadoc while indexing
        parser.javadocParser.checkDocComment = true;
        parser.javadocParser.reportProblems = false;

        return parser;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.mysema.codegen.ECJEvaluatorFactory.java

License:Apache License

protected void compile(String source, ClassType projectionType, String[] names, Type[] types, String id,
        Map<String, Object> constants) throws IOException {
    // create source
    source = createSource(source, projectionType, names, types, id, constants);

    // compile/*from   ww  w  . j av  a 2  s  .  co  m*/
    final char[] targetContents = source.toCharArray();
    final String targetName = id;
    final ICompilationUnit[] targetCompilationUnits = new ICompilationUnit[] { new ICompilationUnit() {
        @Override
        public char[] getContents() {
            return targetContents;
        }

        @Override
        public char[] getMainTypeName() {
            int dot = targetName.lastIndexOf('.');
            if (dot > 0)
                return targetName.substring(dot + 1).toCharArray();
            else
                return targetName.toCharArray();
        }

        @Override
        public char[][] getPackageName() {
            StringTokenizer tok = new StringTokenizer(targetName, ".");
            char[][] result = new char[tok.countTokens() - 1][];
            for (int j = 0; j < result.length; j++) {
                result[j] = tok.nextToken().toCharArray();
            }
            return result;
        }

        @Override
        public char[] getFileName() {
            return CharOperation.concat(targetName.toCharArray(), ".java".toCharArray());
        }

        @Override
        public boolean ignoreOptionalProblems() {
            return true;
        }
    } };

    INameEnvironment env = new INameEnvironment() {

        private String join(char[][] compoundName, char separator) {
            if (compoundName == null) {
                return "";
            } else {
                List<String> parts = Lists.newArrayListWithCapacity(compoundName.length);
                for (char[] part : compoundName) {
                    parts.add(new String(part));
                }
                return Joiner.on(separator).join(parts);
            }
        }

        @Override
        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            return findType(join(compoundTypeName, '.'));
        }

        @Override
        public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
            return findType(CharOperation.arrayConcat(packageName, typeName));
        }

        private boolean isClass(String result) {
            if (Strings.isNullOrEmpty(result)) {
                return false;
            }

            // if it's the class we're compiling, then of course it's a class
            if (result.equals(targetName)) {
                return true;
            }
            InputStream is = null;
            try {
                // if this is a class we've already compiled, it's a class
                is = loader.getResourceAsStream(result);
                if (is == null) {
                    // use our normal class loader now...
                    String resourceName = result.replace('.', '/') + ".class";
                    is = parentClassLoader.getResourceAsStream(resourceName);
                    if (is == null && !result.contains(".")) {
                        // we couldn't find the class, and it has no package; is it a core class?
                        is = parentClassLoader.getResourceAsStream("java/lang/" + resourceName);
                    }
                }
                return is != null;
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException ex) {
                    }
                }
            }
        }

        @Override
        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            // if the parent is a class, the child can't be a package
            String parent = join(parentPackageName, '.');
            if (isClass(parent))
                return false;

            // if the child is a class, it's not a package
            String qualifiedName = (parent.isEmpty() ? "" : parent + ".") + new String(packageName);
            return !isClass(qualifiedName);
        }

        @Override
        public void cleanup() {
        }

        private NameEnvironmentAnswer findType(String className) {
            String resourceName = className.replace('.', '/') + ".class";
            InputStream is = null;
            try {
                // we're only asking ECJ to compile a single class; we shouldn't need this
                if (className.equals(targetName)) {
                    return new NameEnvironmentAnswer(targetCompilationUnits[0], null);
                }

                is = loader.getResourceAsStream(resourceName);
                if (is == null) {
                    is = parentClassLoader.getResourceAsStream(resourceName);
                }

                if (is != null) {
                    ClassFileReader cfr = new ClassFileReader(ByteStreams.toByteArray(is),
                            className.toCharArray(), true);
                    return new NameEnvironmentAnswer(cfr, null);
                } else {
                    return null;
                }
            } catch (ClassFormatException ex) {
                throw new RuntimeException(ex);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }

        }
    };

    ICompilerRequestor requestor = new ICompilerRequestor() {

        @Override
        public void acceptResult(CompilationResult result) {
            if (result.hasErrors()) {
                for (CategorizedProblem problem : result.getProblems()) {
                    if (problem.isError()) {
                        problemList.add(problem.getMessage());
                    }
                }
            } else {
                for (ClassFile clazz : result.getClassFiles()) {
                    try {
                        MemJavaFileObject jfo = (MemJavaFileObject) fileManager.getJavaFileForOutput(
                                StandardLocation.CLASS_OUTPUT, new String(clazz.fileName()),
                                JavaFileObject.Kind.CLASS, null);
                        OutputStream os = jfo.openOutputStream();
                        os.write(clazz.getBytes());
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    };

    problemList.clear();

    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitAfterAllProblems();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    try {
        //Compiler compiler = new Compiler(env, policy, getCompilerOptions(), requestor, problemFactory, true);
        Compiler compiler = new Compiler(env, policy, compilerOptions, requestor, problemFactory);
        compiler.compile(targetCompilationUnits);
        if (!problemList.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String problem : problemList) {
                sb.append("\t").append(problem).append("\n");
            }
            throw new CodegenException("Compilation of " + id + " failed:\n" + source + "\n" + sb.toString());
        }
    } catch (RuntimeException ex) {
        // if we encountered an IOException, unbox and throw it;
        // if we encountered a ClassFormatException, box it as an IOException and throw it
        // otherwise, it's a legit RuntimeException, 
        //    not one of our checked exceptions boxed as unchecked; just rethrow
        Throwable cause = ex.getCause();
        if (cause != null) {
            if (cause instanceof IOException) {
                throw (IOException) cause;
            } else if (cause instanceof ClassFormatException) {
                throw new IOException(cause);
            }
        }
        throw ex;
    }
}

From source file:com.opensymphony.webwork.util.classloader.compilers.eclipse.EclipseJavaCompiler.java

License:Apache License

public void compile(final String[] pClazzNames, final ResourceReader pReader, final ResourceStore pStore,
        final CompilationProblemHandler pProblemHandler) {

    final Map settingsMap = settings.getMap();
    final Set clazzIndex = new HashSet();
    ICompilationUnit[] compilationUnits = new ICompilationUnit[pClazzNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        final String clazzName = pClazzNames[i];
        compilationUnits[i] = new CompilationUnit(pReader, clazzName);
        clazzIndex.add(clazzName);/* w ww .  jav a2 s.co  m*/
        log.debug("compiling " + clazzName);
    }

    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final INameEnvironment nameEnvironment = new INameEnvironment() {

        public NameEnvironmentAnswer findType(final char[][] compoundTypeName) {
            final StringBuffer result = new StringBuffer();
            for (int i = 0; i < compoundTypeName.length; i++) {
                if (i != 0) {
                    result.append('.');
                }
                result.append(compoundTypeName[i]);
            }
            return findType(result.toString());
        }

        public NameEnvironmentAnswer findType(final char[] typeName, final char[][] packageName) {
            final StringBuffer result = new StringBuffer();
            for (int i = 0; i < packageName.length; i++) {
                result.append(packageName[i]);
                result.append('.');
            }
            result.append(typeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(final String clazzName) {
            byte[] clazzBytes = pStore.read(clazzName);
            if (clazzBytes != null) {
                // log.debug("loading from store " + clazzName);
                final char[] fileName = clazzName.toCharArray();
                try {
                    final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
                    return new NameEnvironmentAnswer(classFileReader, null);
                } catch (final ClassFormatException e) {
                    log.error("wrong class format", e);
                }
            } else {
                if (pReader.isAvailable(clazzName.replace('.', '/') + ".java")) {
                    log.debug("compile " + clazzName);
                    ICompilationUnit compilationUnit = new CompilationUnit(pReader, clazzName);
                    return new NameEnvironmentAnswer(compilationUnit, null);
                }

                final String resourceName = clazzName.replace('.', '/') + ".class";
                final InputStream is = this.getClass().getClassLoader().getResourceAsStream(resourceName);
                if (is != null) {
                    final byte[] buffer = new byte[8192];
                    final ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.length);
                    int count;
                    try {
                        while ((count = is.read(buffer, 0, buffer.length)) > 0) {
                            baos.write(buffer, 0, count);
                        }
                        baos.flush();
                        clazzBytes = baos.toByteArray();
                        final char[] fileName = clazzName.toCharArray();
                        ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
                        return new NameEnvironmentAnswer(classFileReader, null);
                    } catch (final IOException e) {
                        log.error("could not read class", e);
                    } catch (final ClassFormatException e) {
                        log.error("wrong class format", e);
                    } finally {
                        try {
                            baos.close();
                        } catch (final IOException oe) {
                            log.error("could not close output stream", oe);
                        }
                        try {
                            is.close();
                        } catch (final IOException ie) {
                            log.error("could not close input stream", ie);
                        }
                    }
                }
            }
            return null;
        }

        private boolean isPackage(final String clazzName) {
            final String resourceName = clazzName.replace('.', '/') + ".class";
            final URL resource = this.getClass().getClassLoader().getResource(resourceName);
            return resource == null;
        }

        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            final StringBuffer result = new StringBuffer();
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    if (i != 0) {
                        result.append('.');
                    }
                    result.append(parentPackageName[i]);
                }
            }
            if (Character.isUpperCase(packageName[0])) {
                return false;
            }
            if (parentPackageName != null && parentPackageName.length > 0) {
                result.append('.');
            }
            result.append(packageName);
            return isPackage(result.toString());
        }

        public void cleanup() {
        }
    };

    final ICompilerRequestor compilerRequestor = new ICompilerRequestor() {
        public void acceptResult(CompilationResult result) {
            if (result.hasProblems()) {
                if (pProblemHandler != null) {
                    final IProblem[] problems = result.getProblems();
                    for (int i = 0; i < problems.length; i++) {
                        final IProblem problem = problems[i];
                        pProblemHandler.handle(new EclipseCompilationProblem(problem));
                    }
                }
            }
            if (!result.hasErrors()) {
                final ClassFile[] clazzFiles = result.getClassFiles();
                for (int i = 0; i < clazzFiles.length; i++) {
                    final ClassFile clazzFile = clazzFiles[i];
                    final char[][] compoundName = clazzFile.getCompoundName();
                    final StringBuffer clazzName = new StringBuffer();
                    for (int j = 0; j < compoundName.length; j++) {
                        if (j != 0) {
                            clazzName.append('.');
                        }
                        clazzName.append(compoundName[j]);
                    }
                    pStore.write(clazzName.toString(), clazzFile.getBytes());
                }
            }
        }
    };

    pProblemHandler.onStart();

    try {

        final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor,
                problemFactory);

        compiler.compile(compilationUnits);

    } finally {
        pProblemHandler.onStop();
    }
}

From source file:com.xqbase.compiler.eclipse.EclipseJavaCompiler.java

License:Open Source License

public CompilerResult performCompile(CompilerConfiguration config) throws CompilerException {

    // added by xqbase-compiler-eclipse
    if (config.getGeneratedSourcesDirectory() != null) {
        config.getGeneratedSourcesDirectory().mkdirs();
    }//from   w  ww.  j av a  2 s  .  c  o m

    List<CompilerMessage> errors = new LinkedList<CompilerMessage>();

    List<String> classpathEntries = config.getClasspathEntries();

    URL[] urls = new URL[1 + classpathEntries.size()];

    int i = 0;

    try {
        urls[i++] = new File(config.getOutputLocation()).toURL();

        for (String entry : classpathEntries) {
            urls[i++] = new File(entry).toURL();
        }
    } catch (MalformedURLException e) {
        throw new CompilerException("Error while converting the classpath entries to URLs.", e);
    }

    ClassLoader classLoader = new URLClassLoader(urls);

    SourceCodeLocator sourceCodeLocator = new SourceCodeLocator(config.getSourceLocations());

    INameEnvironment env = new EclipseCompilerINameEnvironment(sourceCodeLocator, classLoader, errors);

    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();

    // ----------------------------------------------------------------------
    // Build settings from configuration
    // ----------------------------------------------------------------------

    Map<String, String> settings = new HashMap<String, String>();

    if (config.isDebug()) {
        settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
        settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
        settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
    }

    if (!config.isShowWarnings()) {
        Map opts = new CompilerOptions().getMap();
        for (Object optKey : opts.keySet()) {
            if (opts.get(optKey).equals(CompilerOptions.WARNING)) {
                settings.put((String) optKey, CompilerOptions.IGNORE);
            }
        }
    }

    String sourceVersion = decodeVersion(config.getSourceVersion());

    if (sourceVersion != null) {
        settings.put(CompilerOptions.OPTION_Source, sourceVersion);
    }

    String targetVersion = decodeVersion(config.getTargetVersion());

    if (targetVersion != null) {
        settings.put(CompilerOptions.OPTION_TargetPlatform, targetVersion);

        if (config.isOptimize()) {
            settings.put(CompilerOptions.OPTION_Compliance, targetVersion);
        }
    }

    if (StringUtils.isNotEmpty(config.getSourceEncoding())) {
        settings.put(CompilerOptions.OPTION_Encoding, config.getSourceEncoding());
    }

    if (config.isShowDeprecation()) {
        settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING);
    } else {
        settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
    }

    // ----------------------------------------------------------------------
    // Set Eclipse-specific options
    // ----------------------------------------------------------------------

    settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);

    // compiler-specific extra options override anything else in the config object...
    Map<String, String> extras = config.getCustomCompilerArguments();
    if (extras != null && !extras.isEmpty()) {
        settings.putAll(extras);
    }

    if (settings.containsKey("-properties")) {
        initializeWarnings(settings.get("-properties"), settings);
        settings.remove("-properties");
    }

    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    ICompilerRequestor requestor = new EclipseCompilerICompilerRequestor(config.getOutputLocation(), errors);

    List<CompilationUnit> compilationUnits = new ArrayList<CompilationUnit>();

    for (String sourceRoot : config.getSourceLocations()) {
        Set<String> sources = getSourceFilesForSourceRoot(config, sourceRoot);

        for (String source : sources) {
            CompilationUnit unit = new CompilationUnit(source, makeClassName(source, sourceRoot), errors,
                    config.getSourceEncoding());

            compilationUnits.add(unit);
        }
    }

    // ----------------------------------------------------------------------
    // Compile!
    // ----------------------------------------------------------------------

    CompilerOptions options = new CompilerOptions(settings);
    Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);

    ICompilationUnit[] units = compilationUnits.toArray(new ICompilationUnit[compilationUnits.size()]);

    compiler.compile(units);

    CompilerResult compilerResult = new CompilerResult().compilerMessages(errors);

    for (CompilerMessage compilerMessage : errors) {
        if (compilerMessage.isError()) {
            compilerResult.setSuccess(false);
            continue;
        }
    }

    return compilerResult;
}

From source file:jetbrick.template.compiler.JdtCompiler.java

License:Open Source License

@Override
protected void generateJavaClass(JavaSource source) throws IOException {
    INameEnvironment env = new NameEnvironment(source);
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    CompilerOptions options = getCompilerOptions();
    CompilerRequestor requestor = new CompilerRequestor();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);
    compiler.compile(new ICompilationUnit[] { new CompilationUnit(source) });

    if (requestor.hasErrors()) {
        String sourceCode = source.getSourceCode();
        String[] sourceCodeLines = sourceCode.split("(\r\n|\r|\n)", -1);
        StringBuilder sb = new StringBuilder();
        sb.append("Compilation failed.");
        sb.append('\n');
        for (IProblem p : requestor.getErrors()) {
            sb.append(p.getMessage()).append('\n');
            int start = p.getSourceStart();
            int column = start; // default
            for (int i = start; i >= 0; i--) {
                char c = sourceCode.charAt(i);
                if (c == '\n' || c == '\r') {
                    column = start - i;/*from w  w w.  j  a  v  a2  s . co m*/
                    break;
                }
            }
            sb.append(StringUtils.getPrettyError(sourceCodeLines, p.getSourceLineNumber(), column,
                    p.getSourceStart(), p.getSourceEnd(), 3));
        }
        sb.append(requestor.getErrors().length);
        sb.append(" error(s)\n");
        throw new CompileErrorException(sb.toString());
    }

    requestor.save(source.getOutputdir());
}

From source file:lombok.ast.ecj.EcjTreeBuilder.java

License:Open Source License

private static ProblemReporter createDefaultProblemReporter(CompilerOptions options) {
    return new ProblemReporter(new IErrorHandlingPolicy() {
        public boolean proceedOnErrors() {
            return true;
        }//from w  w  w.  jav  a2s.c  o  m

        public boolean stopOnFirstError() {
            return false;
        }

        @Override
        public boolean ignoreAllErrors() {
            return false;
        }
    }, options, new DefaultProblemFactory(Locale.ENGLISH));
}

From source file:lombok.RunTestsViaEcj.java

License:Open Source License

@Override
public void transformCode(Collection<CompilerMessage> messages, StringWriter result, File file, String encoding,
        Map<String, String> formatPreferences) throws Throwable {
    final AtomicReference<CompilationResult> compilationResult_ = new AtomicReference<CompilationResult>();
    final AtomicReference<CompilationUnitDeclaration> compilationUnit_ = new AtomicReference<CompilationUnitDeclaration>();
    ICompilerRequestor bitbucketRequestor = new ICompilerRequestor() {
        @Override/*w  w w. j  a  v  a2  s. c om*/
        public void acceptResult(CompilationResult result) {
            compilationResult_.set(result);
        }
    };

    String source = readFile(file);
    final CompilationUnit sourceUnit = new CompilationUnit(source.toCharArray(), file.getName(),
            encoding == null ? "UTF-8" : encoding);

    Compiler ecjCompiler = new Compiler(createFileSystem(file), ecjErrorHandlingPolicy(), ecjCompilerOptions(),
            bitbucketRequestor, new DefaultProblemFactory(Locale.ENGLISH)) {
        @Override
        protected synchronized void addCompilationUnit(ICompilationUnit inUnit,
                CompilationUnitDeclaration parsedUnit) {
            if (inUnit == sourceUnit)
                compilationUnit_.set(parsedUnit);
            super.addCompilationUnit(inUnit, parsedUnit);
        }
    };

    ecjCompiler.compile(new ICompilationUnit[] { sourceUnit });

    CompilationResult compilationResult = compilationResult_.get();
    CategorizedProblem[] problems = compilationResult.getAllProblems();

    if (problems != null)
        for (CategorizedProblem p : problems) {
            messages.add(new CompilerMessage(p.getSourceLineNumber(), p.getSourceStart(), p.isError(),
                    p.getMessage()));
        }

    CompilationUnitDeclaration cud = compilationUnit_.get();

    if (cud == null)
        result.append("---- NO CompilationUnit provided by ecj ----");
    else
        result.append(cud.toString());
}

From source file:lombok.RunTestsViaEclipse.java

License:Open Source License

@Override
public void transformCode(final StringBuilder messages, StringWriter result, File file) throws Throwable {
    // setup parser and compiler
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH);
    final INameEnvironment nameEnvironment = new LombokTestNameEnvironment();
    final ICompilerRequestor compilerRequestor = new LombokTestCompilerRequestor();
    final ISourceElementRequestor sourceElementRequestor = new LombokTestSourceElementRequestor();
    final CompilerOptions options = ecjCompilerOptions();
    final LombokTestCompiler jdtCompiler = new LombokTestCompiler(nameEnvironment, policy, options,
            compilerRequestor, problemFactory);
    final SourceElementParser parser = new SourceElementParser(sourceElementRequestor, problemFactory, options,
            true, true);/*from ww  w  .j  a va 2s.c  o  m*/

    // read the file
    final String source = readFile(file);
    final CompilationUnit sourceUnit = new CompilationUnit(source.toCharArray(), file.getName(), "UTF-8");

    // parse
    final CompilationUnitDeclaration cud = parser.parseCompilationUnit(sourceUnit, true, null);
    // build
    jdtCompiler.lookupEnvironment.buildTypeBindings(cud, null);
    jdtCompiler.lookupEnvironment.completeTypeBindings(cud, true);
    // process
    if (cud.scope != null)
        cud.scope.verifyMethods(jdtCompiler.lookupEnvironment.methodVerifier());

    // handle problems
    final CategorizedProblem[] problems = cud.compilationResult.getAllProblems();

    if (problems != null)
        for (CategorizedProblem p : problems) {
            messages.append(String.format("%d %s %s\n", p.getSourceLineNumber(),
                    p.isError() ? "error" : p.isWarning() ? "warning" : "unknown", p.getMessage()));
        }

    // set transformed code
    result.append(cud.toString());
}