Search in sources :

Example 26 with IProblem

use of org.eclipse.jdt.core.compiler.IProblem in project Japid by branaway.

the class CompilerRequestor method acceptResult.

@Override
public void acceptResult(CompilationResult result) {
    // If error
    if (result.hasErrors()) {
        // bran: sort the problems and report the first one
        CategorizedProblem[] errors = result.getErrors();
        Arrays.sort(errors, new Comparator<CategorizedProblem>() {

            @Override
            public int compare(CategorizedProblem o1, CategorizedProblem o2) {
                return o1.getSourceLineNumber() - o2.getSourceLineNumber();
            }
        });
        for (IProblem problem : errors) {
            String className = new String(problem.getOriginatingFileName()).replace("/", ".");
            className = className.substring(0, className.length() - 5);
            String message = problem.getMessage();
            if (problem.getID() == IProblem.CannotImportPackage) {
                // Non sense !
                message = problem.getArguments()[0] + " cannot be resolved";
            }
            RendererClass rc = this.rendererCompiler.japidClasses.get(className);
            if (rc.getSrcFile() == null)
                throw new RuntimeException("no source file for compiling " + className);
            if (rc.getOriSourceCode() == null)
                throw new RuntimeException("no original source code for compiling " + className);
            JapidTemplate tmpl = new JapidTemplate(rc.getSrcFile().getPath(), rc.getOriSourceCode());
            throw new JapidCompilationException(tmpl, DirUtil.mapJavaLineToSrcLine(rc.getSourceCode(), problem.getSourceLineNumber()), message + " while compiling " + className);
        }
    }
    // 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]);
        }
        byte[] bytes = clazzFile.getBytes();
        JapidFlags.debug("Bytecode generated for " + clazzName);
        // XXX address anonymous inner class issue!! ....$1...
        String cname = clazzName.toString();
        RendererClass rc = this.rendererCompiler.japidClasses.get(cname);
        if (rc == null) {
            if (cname.contains("$")) {
                // inner class
                rc = new RendererClass();
                rc.setClassName(cname);
                this.rendererCompiler.japidClasses.put(cname, rc);
            } else {
                throw new RuntimeException("name not in the classes container: " + cname);
            }
        }
        rc.setBytecode(bytes);
    }
}
Also used : JapidTemplate(cn.bran.japid.template.JapidTemplate) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) JapidCompilationException(cn.bran.japid.compiler.JapidCompilationException) IProblem(org.eclipse.jdt.core.compiler.IProblem) CategorizedProblem(org.eclipse.jdt.core.compiler.CategorizedProblem)

Example 27 with IProblem

use of org.eclipse.jdt.core.compiler.IProblem in project tomcat by apache.

the class JDTCompiler method generateClass.

/**
 * Compile the servlet from .java file to .class file
 */
@Override
protected void generateClass(Map<String, SmapStratum> smaps) throws FileNotFoundException, JasperException, Exception {
    long t1 = 0;
    if (log.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }
    final String sourceFile = ctxt.getServletJavaFileName();
    final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
    String packageName = ctxt.getServletPackageName();
    final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName();
    final ClassLoader classLoader = ctxt.getJspLoader();
    String[] fileNames = new String[] { sourceFile };
    String[] classNames = new String[] { targetClassName };
    final List<JavacErrorDetail> problemList = new ArrayList<>();
    class CompilationUnit implements ICompilationUnit {

        private final String className;

        private final String sourceFile;

        CompilationUnit(String sourceFile, String className) {
            this.className = className;
            this.sourceFile = sourceFile;
        }

        @Override
        public char[] getFileName() {
            return sourceFile.toCharArray();
        }

        @Override
        public char[] getContents() {
            char[] result = null;
            try (FileInputStream is = new FileInputStream(sourceFile);
                InputStreamReader isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding());
                Reader reader = new BufferedReader(isr)) {
                char[] chars = new char[8192];
                StringBuilder buf = new StringBuilder();
                int count;
                while ((count = reader.read(chars, 0, chars.length)) > 0) {
                    buf.append(chars, 0, count);
                }
                result = new char[buf.length()];
                buf.getChars(0, result.length, result, 0);
            } catch (IOException e) {
                log.error(Localizer.getMessage("jsp.error.compilation.source", sourceFile), e);
            }
            return result;
        }

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

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

        @Override
        public boolean ignoreOptionalProblems() {
            return false;
        }
    }
    final INameEnvironment env = new INameEnvironment() {

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

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

        private NameEnvironmentAnswer findType(String className) {
            if (className.equals(targetClassName)) {
                ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
                return new NameEnvironmentAnswer(compilationUnit, null);
            }
            String resourceName = className.replace('.', '/') + ".class";
            try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
                if (is != null) {
                    byte[] classBytes;
                    byte[] buf = new byte[8192];
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
                    int count;
                    while ((count = is.read(buf, 0, buf.length)) > 0) {
                        baos.write(buf, 0, count);
                    }
                    baos.flush();
                    classBytes = baos.toByteArray();
                    char[] fileName = className.toCharArray();
                    ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
                    return new NameEnvironmentAnswer(classFileReader, null);
                }
            } catch (IOException | ClassFormatException exc) {
                log.error(Localizer.getMessage("jsp.error.compilation.dependent", className), exc);
            }
            return null;
        }

        private boolean isPackage(String result) {
            if (result.equals(targetClassName) || result.startsWith(targetClassName + '$')) {
                return false;
            }
            String resourceName = result.replace('.', '/') + ".class";
            try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
                return is == null;
            } catch (IOException e) {
                // we are here, since close on is failed. That means it was not null
                return false;
            }
        }

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

        @Override
        public void cleanup() {
        }
    };
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final Map<String, String> settings = new HashMap<>();
    settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
    if (ctxt.getOptions().getJavaEncoding() != null) {
        settings.put(CompilerOptions.OPTION_Encoding, ctxt.getOptions().getJavaEncoding());
    }
    if (ctxt.getOptions().getClassDebugInfo()) {
        settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
    }
    // Source JVM
    if (ctxt.getOptions().getCompilerSourceVM() != null) {
        String opt = ctxt.getOptions().getCompilerSourceVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        } else if (opt.equals("1.6")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
        } else if (opt.equals("1.7")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
        } else if (opt.equals("1.8")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
        // Version format changed from Java 9 onwards.
        // Support old format that was used in EA implementation as well
        } else if (opt.equals("9") || opt.equals("1.9")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_9);
        } else if (opt.equals("10")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_10);
        } else if (opt.equals("11")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_11);
        } else if (opt.equals("12")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_12);
        } else if (opt.equals("13")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_13);
        } else if (opt.equals("14")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_14);
        } else if (opt.equals("15")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_15);
        } else if (opt.equals("16")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_16);
        } else if (opt.equals("17")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_17);
        } else if (opt.equals("18")) {
            // Constant not available in latest ECJ version shipped with
            // Tomcat. May be supported in a snapshot build.
            // This is checked against the actual version below.
            settings.put(CompilerOptions.OPTION_Source, "18");
        } else {
            log.warn(Localizer.getMessage("jsp.warning.unknown.sourceVM", opt));
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_11);
        }
    } else {
        // Default to 11
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_11);
    }
    // Target JVM
    if (ctxt.getOptions().getCompilerTargetVM() != null) {
        String opt = ctxt.getOptions().getCompilerTargetVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
        } else if (opt.equals("1.6")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
        } else if (opt.equals("1.7")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
        } else if (opt.equals("1.8")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
        // Version format changed from Java 9 onwards.
        // Support old format that was used in EA implementation as well
        } else if (opt.equals("9") || opt.equals("1.9")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_9);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_9);
        } else if (opt.equals("10")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_10);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_10);
        } else if (opt.equals("11")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_11);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_11);
        } else if (opt.equals("12")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_12);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_12);
        } else if (opt.equals("13")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_13);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_13);
        } else if (opt.equals("14")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_14);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_14);
        } else if (opt.equals("15")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_15);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_15);
        } else if (opt.equals("16")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_16);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_16);
        } else if (opt.equals("17")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_17);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_17);
        } else if (opt.equals("18")) {
            // Constant not available in latest ECJ version shipped with
            // Tomcat. May be supported in a snapshot build.
            // This is checked against the actual version below.
            settings.put(CompilerOptions.OPTION_TargetPlatform, "18");
            settings.put(CompilerOptions.OPTION_Compliance, "18");
        } else {
            log.warn(Localizer.getMessage("jsp.warning.unknown.targetVM", opt));
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_11);
        }
    } else {
        // Default to 11
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_11);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_11);
    }
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final ICompilerRequestor requestor = new ICompilerRequestor() {

        @Override
        public void acceptResult(CompilationResult result) {
            try {
                if (result.hasProblems()) {
                    IProblem[] problems = result.getProblems();
                    for (IProblem problem : problems) {
                        if (problem.isError()) {
                            String name = new String(problem.getOriginatingFileName());
                            try {
                                problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuilder(problem.getMessage()), problem.getSourceLineNumber(), ctxt));
                            } catch (JasperException e) {
                                log.error(Localizer.getMessage("jsp.error.compilation.jdtProblemError"), e);
                            }
                        }
                    }
                }
                if (problemList.isEmpty()) {
                    ClassFile[] classFiles = result.getClassFiles();
                    for (ClassFile classFile : classFiles) {
                        char[][] compoundName = classFile.getCompoundName();
                        StringBuilder classFileName = new StringBuilder(outputDir).append('/');
                        for (int j = 0; j < compoundName.length; j++) {
                            if (j > 0) {
                                classFileName.append('/');
                            }
                            classFileName.append(compoundName[j]);
                        }
                        byte[] bytes = classFile.getBytes();
                        classFileName.append(".class");
                        try (FileOutputStream fout = new FileOutputStream(classFileName.toString());
                            BufferedOutputStream bos = new BufferedOutputStream(fout)) {
                            bos.write(bytes);
                        }
                    }
                }
            } catch (IOException exc) {
                log.error(Localizer.getMessage("jsp.error.compilation.jdt"), exc);
            }
        }
    };
    ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        String className = classNames[i];
        compilationUnits[i] = new CompilationUnit(fileNames[i], className);
    }
    CompilerOptions cOptions = new CompilerOptions(settings);
    // Check source/target JDK versions as the newest versions are allowed
    // in Tomcat configuration but may not be supported by the ECJ version
    // being used.
    String requestedSource = ctxt.getOptions().getCompilerSourceVM();
    if (requestedSource != null) {
        String actualSource = CompilerOptions.versionFromJdkLevel(cOptions.sourceLevel);
        if (!requestedSource.equals(actualSource)) {
            log.warn(Localizer.getMessage("jsp.warning.unsupported.sourceVM", requestedSource, actualSource));
        }
    }
    String requestedTarget = ctxt.getOptions().getCompilerTargetVM();
    if (requestedTarget != null) {
        String actualTarget = CompilerOptions.versionFromJdkLevel(cOptions.targetJDK);
        if (!requestedTarget.equals(actualTarget)) {
            log.warn(Localizer.getMessage("jsp.warning.unsupported.targetVM", requestedTarget, actualTarget));
        }
    }
    cOptions.parseLiteralExpressionsAsConstants = true;
    Compiler compiler = new Compiler(env, policy, cOptions, requestor, problemFactory);
    compiler.compile(compilationUnits);
    if (!ctxt.keepGenerated()) {
        File javaFile = new File(ctxt.getServletJavaFileName());
        if (!javaFile.delete()) {
            throw new JasperException(Localizer.getMessage("jsp.warning.compiler.javafile.delete.fail", javaFile));
        }
    }
    if (!problemList.isEmpty()) {
        JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
        errDispatcher.javacError(jeds);
    }
    if (log.isDebugEnabled()) {
        long t2 = System.currentTimeMillis();
        log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
    }
    if (ctxt.isPrototypeMode()) {
        return;
    }
    // JSR45 Support
    if (!options.isSmapSuppressed()) {
        SmapUtil.installSmap(smaps);
    }
}
Also used : IErrorHandlingPolicy(org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy) NameEnvironmentAnswer(org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer) HashMap(java.util.HashMap) ClassFileReader(org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader) ArrayList(java.util.ArrayList) ClassFileReader(org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) ClassFormatException(org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException) JasperException(org.apache.jasper.JasperException) INameEnvironment(org.eclipse.jdt.internal.compiler.env.INameEnvironment) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory) BufferedOutputStream(java.io.BufferedOutputStream) IProblemFactory(org.eclipse.jdt.internal.compiler.IProblemFactory) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) Compiler(org.eclipse.jdt.internal.compiler.Compiler) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) InputStreamReader(java.io.InputStreamReader) ICompilerRequestor(org.eclipse.jdt.internal.compiler.ICompilerRequestor) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IProblem(org.eclipse.jdt.core.compiler.IProblem) FileInputStream(java.io.FileInputStream) StringTokenizer(java.util.StringTokenizer) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) CompilationResult(org.eclipse.jdt.internal.compiler.CompilationResult) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) File(java.io.File)

Example 28 with IProblem

use of org.eclipse.jdt.core.compiler.IProblem in project japid42 by branaway.

the class CompilerRequestor method acceptResult.

@Override
public void acceptResult(CompilationResult result) {
    // If error
    if (result.hasErrors()) {
        // bran: sort the problems and report the first one
        CategorizedProblem[] errors = result.getErrors();
        Arrays.sort(errors, new Comparator<CategorizedProblem>() {

            @Override
            public int compare(CategorizedProblem o1, CategorizedProblem o2) {
                return o1.getSourceLineNumber() - o2.getSourceLineNumber();
            }
        });
        for (IProblem problem : errors) {
            String className = new String(problem.getOriginatingFileName()).replace("/", ".");
            className = className.substring(0, className.length() - 5);
            String message = problem.getMessage();
            int line = problem.getSourceLineNumber();
            String srcFile = new String(problem.getOriginatingFileName());
            if (problem.getID() == IProblem.CannotImportPackage) {
                // Non sense !
                message = problem.getArguments()[0] + " cannot be resolved";
            }
            RendererClass rc = JapidRenderer.japidClasses.get(className);
            if (rc.getJapidSourceCode() == null)
                throw new RuntimeException("no original source code for compiling " + className);
            String descr = srcFile + "(" + line + "): " + message;
            String javaSourceCode = rc.getJavaSourceCode();
            int oriSrcLineNum = DirUtil.mapJavaLineToSrcLine(javaSourceCode, problem.getSourceLineNumber());
            String scriptPath = rc.getScriptPath();
            if (oriSrcLineNum > 0) {
                // has a original script marker
                descr = scriptPath + "(line " + oriSrcLineNum + "): " + message;
                JapidTemplateException te = new JapidTemplateException("Japid Compilation Error", descr, oriSrcLineNum, scriptPath, rc.getJapidSourceCode());
                throw te;
            } else {
                JapidTemplateException te = new JapidTemplateException("Japid Compilation Error", descr, line, srcFile, javaSourceCode);
                throw te;
            }
        }
    }
    // 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]);
        }
        byte[] bytes = clazzFile.getBytes();
        JapidFlags.debug("compiled: " + clazzName);
        // XXX address anonymous inner class issue!! ....$1...
        String cname = clazzName.toString();
        RendererClass rc = JapidRenderer.japidClasses.get(cname);
        if (rc == null) {
            if (cname.contains("$")) {
                // inner class
                rc = new RendererClass();
                rc.className = cname;
                JapidRenderer.japidClasses.put(cname, rc);
            } else {
                throw new RuntimeException("name not in the classes container: " + cname);
            }
        }
        rc.setBytecode(bytes);
        rc.setClz(null);
        rc.setLastCompiled(System.currentTimeMillis());
    }
}
Also used : ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) IProblem(org.eclipse.jdt.core.compiler.IProblem) CategorizedProblem(org.eclipse.jdt.core.compiler.CategorizedProblem) JapidTemplateException(cn.bran.japid.exceptions.JapidTemplateException)

Example 29 with IProblem

use of org.eclipse.jdt.core.compiler.IProblem in project bayou by capergroup.

the class Parser method parse.

public void parse() throws ParseException {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source.toCharArray());
    Map<String, String> options = JavaCore.getOptions();
    options.put("org.eclipse.jdt.core.compiler.source", "1.8");
    parser.setCompilerOptions(options);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setUnitName("Program.java");
    parser.setEnvironment(new String[] { classpath != null ? classpath : "" }, new String[] { "" }, new String[] { "UTF-8" }, true);
    parser.setResolveBindings(true);
    cu = (CompilationUnit) parser.createAST(null);
    List<IProblem> problems = Arrays.stream(cu.getProblems()).filter(p -> (p.isError() && // we use "Program.java"
    p.getID() != IProblem.PublicClassMustMatchFileName && // Evidence varargs
    p.getID() != IProblem.ParameterMismatch) || (p.getID() == IProblem.RawTypeReference)).collect(Collectors.toList());
    if (problems.size() > 0)
        throw new ParseException(problems);
}
Also used : Arrays(java.util.Arrays) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) MalformedURLException(java.net.MalformedURLException) JavaCore(org.eclipse.jdt.core.JavaCore) URL(java.net.URL) Collectors(java.util.stream.Collectors) File(java.io.File) ArrayList(java.util.ArrayList) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ASTParser(org.eclipse.jdt.core.dom.ASTParser) Map(java.util.Map) AST(org.eclipse.jdt.core.dom.AST) IProblem(org.eclipse.jdt.core.compiler.IProblem) LogManager(org.apache.logging.log4j.LogManager) ASTParser(org.eclipse.jdt.core.dom.ASTParser) IProblem(org.eclipse.jdt.core.compiler.IProblem)

Example 30 with IProblem

use of org.eclipse.jdt.core.compiler.IProblem in project j2objc by google.

the class JdtParser method checkCompilationErrors.

private boolean checkCompilationErrors(String filename, CompilationUnit unit) {
    boolean hasErrors = false;
    for (IProblem problem : unit.getProblems()) {
        if (problem.isError()) {
            ErrorUtil.error(String.format("%s:%s: %s", filename, problem.getSourceLineNumber(), problem.getMessage()));
            hasErrors = true;
        }
        if (problem.isWarning()) {
            ErrorUtil.warning(String.format("%s:%s: warning: %s", filename, problem.getSourceLineNumber(), problem.getMessage()));
        }
    }
    return !hasErrors;
}
Also used : IProblem(org.eclipse.jdt.core.compiler.IProblem)

Aggregations

IProblem (org.eclipse.jdt.core.compiler.IProblem)62 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)28 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)25 ArrayList (java.util.ArrayList)21 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)10 File (java.io.File)9 ASTParser (org.eclipse.jdt.core.dom.ASTParser)9 ClassFile (org.eclipse.jdt.internal.compiler.ClassFile)7 IProblemLocation (org.eclipse.jdt.ui.text.java.IProblemLocation)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 IOException (java.io.IOException)5 InputStream (java.io.InputStream)5 HashMap (java.util.HashMap)5 ASTNode (org.eclipse.jdt.core.dom.ASTNode)5 RefactoringStatusEntry (org.eclipse.ltk.core.refactoring.RefactoringStatusEntry)5 URI (java.net.URI)4 HashSet (java.util.HashSet)4 StringTokenizer (java.util.StringTokenizer)4 IJavaProject (org.eclipse.jdt.core.IJavaProject)4 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)4