Example usage for org.eclipse.jdt.internal.compiler DefaultErrorHandlingPolicies exitOnFirstError

List of usage examples for org.eclipse.jdt.internal.compiler DefaultErrorHandlingPolicies exitOnFirstError

Introduction

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

Prototype

public static IErrorHandlingPolicy exitOnFirstError() 

Source Link

Usage

From source file:com.android.tools.idea.lint.LombokPsiConverterTest.java

License:Apache License

@Nullable
private static Node parse(String code) {
    CompilerOptions options = new CompilerOptions();
    options.complianceLevel = options.sourceLevel = options.targetJDK = ClassFileConstants.JDK1_7;
    options.parseLiteralExpressionsAsConstants = true;
    ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitOnFirstError(),
            options, new DefaultProblemFactory());
    Parser parser = new Parser(problemReporter, options.parseLiteralExpressionsAsConstants);
    parser.javadocParser.checkDocComment = false;
    EcjTreeConverter converter = new EcjTreeConverter();
    org.eclipse.jdt.internal.compiler.batch.CompilationUnit sourceUnit = new org.eclipse.jdt.internal.compiler.batch.CompilationUnit(
            code.toCharArray(), "unitTest", "UTF-8");
    CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0);
    CompilationUnitDeclaration unit = parser.parse(sourceUnit, compilationResult);
    if (unit == null) {
        return null;
    }// w  ww  . ja v  a 2 s . c  o  m
    converter.visit(code, unit);
    List<? extends Node> nodes = converter.getAll();
    for (lombok.ast.Node node : nodes) {
        if (node instanceof lombok.ast.CompilationUnit) {
            return node;
        }
    }
    return null;
}

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

License:Apache License

private Parser getParser() {
    if (mParser == null) {
        CompilerOptions options = createCompilerOptions();
        ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitOnFirstError(),
                options, new DefaultProblemFactory());
        mParser = new Parser(problemReporter, options.parseLiteralExpressionsAsConstants);
        mParser.javadocParser.checkDocComment = false;
    }/*from   w  w  w.j  a  va2  s  .  c om*/
    return mParser;
}

From source file:org.rythmengine.internal.compiler.TemplateCompiler.java

License:Apache License

/**
 * Please compile this className//from   ww  w  . ja v  a2  s .  co  m
 */
@SuppressWarnings("deprecation")
public void compile(String[] classNames) {

    ICompilationUnit[] compilationUnits = new CompilationUnit[classNames.length];
    for (int i = 0; i < classNames.length; i++) {
        compilationUnits[i] = new CompilationUnit(classNames[i]);
    }
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH);

    /**
     * To find types ...
     */
    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 findStandType(final String name) throws ClassFormatException {
            if (notFoundTypes.contains(name)) {
                return null;
            }
            RythmEngine engine = engine();
            byte[] bytes = engine.classLoader().getClassDefinition(name);
            if (bytes != null) {
                ClassFileReader classFileReader = new ClassFileReader(bytes, name.toCharArray(), true);
                return new NameEnvironmentAnswer(classFileReader, null);
            }
            if (engine.isProdMode()) {
                notFoundTypes.add(name);
            } else if (name.matches("^(java\\.|play\\.|com\\.greenlaw110\\.).*")) {
                notFoundTypes.add(name);
            }
            return null;
        }

        private NameEnvironmentAnswer findType(final String name) {
            try {
                if (!name.contains(TemplateClass.CN_SUFFIX)) {
                    return findStandType(name);
                }

                char[] fileName = name.toCharArray();
                TemplateClass templateClass = classCache.getByClassName(name);

                // TemplateClass exists
                if (templateClass != null) {
                    if (templateClass.javaByteCode != null) {
                        ClassFileReader classFileReader = new ClassFileReader(templateClass.javaByteCode,
                                fileName, true);
                        return new NameEnvironmentAnswer(classFileReader, null);
                    }
                    // Cascade compilation
                    ICompilationUnit compilationUnit = new CompilationUnit(name);
                    return new NameEnvironmentAnswer(compilationUnit, null);
                }

                // So it's a standard class
                return findStandType(name);
            } catch (ClassFormatException e) {
                // Something very very bad
                throw new RuntimeException(e);
            }
        }

        @Override
        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            // Rebuild something usable
            StringBuilder sb = new StringBuilder();
            if (parentPackageName != null) {
                for (char[] p : parentPackageName) {
                    sb.append(new String(p));
                    sb.append(".");
                }
            }
            sb.append(new String(packageName));
            String name = sb.toString();
            if (packagesCache.containsKey(name)) {
                return packagesCache.get(name).booleanValue();
            }
            // Check if thera a .java or .class for this resource
            if (engine().classLoader().getClassDefinition(name) != null) {
                packagesCache.put(name, false);
                return false;
            }
            if (engine().classes().getByClassName(name) != null) {
                packagesCache.put(name, false);
                return false;
            }
            packagesCache.put(name, true);
            return true;
        }

        public void cleanup() {
        }
    };

    final RythmEngine engine = engine();

    /**
     * Compilation result
     */
    ICompilerRequestor compilerRequestor = new ICompilerRequestor() {

        public void acceptResult(CompilationResult result) {
            // If error
            if (result.hasErrors()) {
                for (IProblem problem : result.getErrors()) {
                    int line = problem.getSourceLineNumber();
                    int column = problem.getSourceStart();
                    String message = problem.getMessage();
                    throw CompileException.compilerException(
                            String.valueOf(result.compilationUnit.getMainTypeName()), line, message);
                }
            }
            // Something has been compiled
            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]);
                }

                if (logger.isTraceEnabled()) {
                    logger.trace("Compiled %s", getTemplateByClassName(clazzName.toString()));
                }

                String cn = clazzName.toString();
                TemplateClass tc = classCache.getByClassName(cn);
                if (null == tc) {
                    int pos = cn.indexOf("$");
                    if (-1 != pos) {
                        // inner class
                        TemplateClass root = classCache.getByClassName(cn.substring(0, pos));
                        tc = TemplateClass.createInnerClass(cn, clazzFile.getBytes(), root);
                        tc.delayedEnhance(root);
                        classCache.add(tc);
                    } else {
                        throw new RuntimeException("Cannot find class by name: " + cn);
                    }
                } else {
                    tc.compiled(clazzFile.getBytes());
                }
            }
        }
    };

    /**
     * The JDT compiler
     */
    Compiler jdtCompiler = new Compiler(nameEnvironment, policy, settings, compilerRequestor, problemFactory) {

        @Override
        protected void handleInternalException(Throwable e, CompilationUnitDeclaration ud,
                CompilationResult result) {
        }
    };

    // Go !
    jdtCompiler.compile(compilationUnits);

}

From source file:org.suren.autotest.web.framework.jdt.JDTUtils.java

License:Apache License

public void compileFile(File srcFile) {
    INameEnvironment env = new SuRenNameEnvironment(workDir);
    ICompilerRequestor compilerRequestor = new SuRenCompilerRequestor(workDir);

    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH);
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError();

    CompilerOptions compilerOptions = getCompilerOptions();

    org.eclipse.jdt.internal.compiler.Compiler jdtCompiler = new org.eclipse.jdt.internal.compiler.Compiler(env,
            policy, compilerOptions, compilerRequestor, problemFactory);

    ICompilationUnit[] unit = new ICompilationUnit[] { new SuRenCompiler(srcFile, workDir) };
    ;//from  w ww. j  a v  a  2  s. c o m
    jdtCompiler.compile(unit);
}

From source file:org.tinygroup.template.compiler.MemorySourceCompiler.java

License:GNU General Public License

public void compile(String engineId, final MemorySource[] sources) {
    for (MemorySource source : sources) {
        String javaFileName = source.getQualifiedClassName().replaceAll("[.]", "/") + ".java";
        try {//w w  w . j  a va2 s.  co  m
            File file = new File(outputDir + engineId + File.separator, javaFileName);
            File path = file.getParentFile();
            if (!path.exists()) {
                path.mkdirs();
            }
            IOUtils.writeToOutputStream(new FileOutputStream(file), source.getContent(), "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * To find types ...
     */
    INameEnvironment nameEnvironment = new NameEnvironment(engineId, sources);
    /**
     * Compilation result
     */
    ICompilerRequestor compilerRequestor = new CompilerRequestor(sources[0], engineId);

    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.CHINA);
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError();

    /**
     * The JDT compiler
     */
    Compiler jdtCompiler = new Compiler(nameEnvironment, policy, getCompilerOptions(), compilerRequestor,
            problemFactory);

    // Go !

    ICompilationUnit[] units = new ICompilationUnit[sources.length];
    for (int i = 0; i < sources.length; i++) {
        units[i] = new CompilationUnit(sources[i]);
    }
    jdtCompiler.compile(units);
}

From source file:org.z2env.impl.components.java.jdt.SimpleJDTCompiler.java

License:Apache License

public boolean compile() {
    long start = System.currentTimeMillis();
    _delete(this.outRoot);
    this.outRoot.mkdirs();
    Map<String, String> settings = new HashMap<String, String>();

    LangLevel ll = JavaComponentUtil.determineLanguageLevel();

    switch (ll) {
    case JAVA6://w  w w  .  j  a va2  s  . c  o m
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
        break;
    case JAVA7:
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
        break;
    case JAVA8:
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
        break;
    default:
        throw new IllegalStateException("Unsupported language level: " + ll);
    }

    // general compiler options - derived from the VM
    settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_Encoding, UTF8);

    CompilerOptions options = new CompilerOptions(settings);

    INameEnvironment ne = new NameEnvironmentImpl(this.classPath, UTF8, this.srcs);
    CompilerRequestorImpl cr = new CompilerRequestorImpl(this.outRoot);
    ICompilationUnit[] sources = _findSource();
    if (logger.isLoggable(Level.FINE)) {
        logger.fine("Compiling " + sources.length + " source files from " + Arrays.asList(this.srcs) + " to "
                + this.outRoot + " using lang level " + ll);
    }
    org.eclipse.jdt.internal.compiler.Compiler c = new Compiler(ne,
            DefaultErrorHandlingPolicies.exitOnFirstError(), options, cr,
            new DefaultProblemFactory(Locale.getDefault()));
    c.compile(sources);
    long duration = System.currentTimeMillis() - start;
    if (logger.isLoggable(Level.FINE)) {
        logger.fine("Compilation of " + Arrays.asList(this.srcs) + " completed after " + duration + "ms");
    }
    this.successful = !cr.hasError();
    return this.successful;
}