Search in sources :

Example 6 with CategorizedProblem

use of org.eclipse.jdt.core.compiler.CategorizedProblem in project lombok by rzwitserloot.

the class EclipseAstProblemView method addProblemToCompilationResult.

/**
	 * Adds a problem to the provided CompilationResult object so that it will show up
	 * in the Problems/Warnings view.
	 */
public static void addProblemToCompilationResult(char[] fileNameArray, CompilationResult result, boolean isWarning, String message, int sourceStart, int sourceEnd) {
    if (result == null)
        return;
    if (fileNameArray == null)
        fileNameArray = "(unknown).java".toCharArray();
    int lineNumber = 0;
    int columnNumber = 1;
    int[] lineEnds = null;
    lineNumber = sourceStart >= 0 ? Util.getLineNumber(sourceStart, lineEnds = result.getLineSeparatorPositions(), 0, lineEnds.length - 1) : 0;
    columnNumber = sourceStart >= 0 ? Util.searchColumnNumber(result.getLineSeparatorPositions(), lineNumber, sourceStart) : 0;
    CategorizedProblem ecProblem = new LombokProblem(fileNameArray, message, 0, new String[0], isWarning ? ProblemSeverities.Warning : ProblemSeverities.Error, sourceStart, sourceEnd, lineNumber, columnNumber);
    result.record(ecProblem, null);
}
Also used : CategorizedProblem(org.eclipse.jdt.core.compiler.CategorizedProblem)

Example 7 with CategorizedProblem

use of org.eclipse.jdt.core.compiler.CategorizedProblem 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 8 with CategorizedProblem

use of org.eclipse.jdt.core.compiler.CategorizedProblem 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 9 with CategorizedProblem

use of org.eclipse.jdt.core.compiler.CategorizedProblem in project che by eclipse.

the class CheASTParser method internalCreateASTForKind.

/**
	 * Parses the given source between the bounds specified by the given offset (inclusive)
	 * and the given length and creates and returns a corresponding abstract syntax tree.
	 * <p>
	 * When the parse is successful the result returned includes the ASTs for the
	 * requested source:
	 * <ul>
	 * <li>{@link #K_CLASS_BODY_DECLARATIONS K_CLASS_BODY_DECLARATIONS}: The result node
	 * is a {@link TypeDeclaration TypeDeclaration} whose
	 * {@link TypeDeclaration#bodyDeclarations() bodyDeclarations}
	 * are the new trees. Other aspects of the type declaration are unspecified.</li>
	 * <li>{@link #K_STATEMENTS K_STATEMENTS}: The result node is a
	 * {@link Block Block} whose {@link Block#statements() statements}
	 * are the new trees. Other aspects of the block are unspecified.</li>
	 * <li>{@link #K_EXPRESSION K_EXPRESSION}: The result node is a subclass of
	 * {@link Expression Expression}. Other aspects of the expression are unspecified.</li>
	 * </ul>
	 * The resulting AST node is rooted under an contrived
	 * {@link CompilationUnit CompilationUnit} node, to allow the
	 * client to retrieve the following pieces of information
	 * available there:
	 * <ul>
	 * <li>{@linkplain CompilationUnit#getLineNumber(int) Line number map}. Line
	 * numbers start at 1 and only cover the subrange scanned
	 * (<code>source[offset]</code> through <code>source[offset+length-1]</code>).</li>
	 * <li>{@linkplain CompilationUnit#getMessages() Compiler messages}
	 * and {@linkplain CompilationUnit#getProblems() detailed problem reports}.
	 * Character positions are relative to the start of
	 * <code>source</code>; line positions are for the subrange scanned.</li>
	 * <li>{@linkplain CompilationUnit#getCommentList() Comment list}
	 * for the subrange scanned.</li>
	 * </ul>
	 * The contrived nodes do not have source positions. Other aspects of the
	 * {@link CompilationUnit CompilationUnit} node are unspecified, including
	 * the exact arrangment of intervening nodes.
	 * </p>
	 * <p>
	 * Lexical or syntax errors detected while parsing can result in
	 * a result node being marked as {@link ASTNode#MALFORMED MALFORMED}.
	 * In more severe failure cases where the parser is unable to
	 * recognize the input, this method returns
	 * a {@link CompilationUnit CompilationUnit} node with at least the
	 * compiler messages.
	 * </p>
	 * <p>Each node in the subtree (other than the contrived nodes)
	 * carries source range(s) information relating back
	 * to positions in the given source (the given source itself
	 * is not remembered with the AST).
	 * The source range usually begins at the first character of the first token
	 * corresponding to the node; leading whitespace and comments are <b>not</b>
	 * included. The source range usually extends through the last character of
	 * the last token corresponding to the node; trailing whitespace and
	 * comments are <b>not</b> included. There are a handful of exceptions
	 * (including the various body declarations); the
	 * specification for these node type spells out the details.
	 * Source ranges nest properly: the source range for a child is always
	 * within the source range of its parent, and the source ranges of sibling
	 * nodes never overlap.
	 * </p>
	 * <p>
	 * This method does not compute binding information; all <code>resolveBinding</code>
	 * methods applied to nodes of the resulting AST return <code>null</code>.
	 * </p>
	 *
	 * @return an AST node whose type depends on the kind of parse
	 *  requested, with a fallback to a <code>CompilationUnit</code>
	 *  in the case of severe parsing errors
	 * @see ASTNode#getStartPosition()
	 * @see ASTNode#getLength()
	 */
private ASTNode internalCreateASTForKind() {
    final ASTConverter converter = new ASTConverter(this.compilerOptions, false, null);
    converter.compilationUnitSource = this.rawSource;
    converter.compilationUnitSourceLength = this.rawSource.length;
    converter.scanner.setSource(this.rawSource);
    AST ast = AST.newAST(this.apiLevel);
    ast.setDefaultNodeFlag(ASTNode.ORIGINAL);
    ast.setBindingResolver(new BindingResolver());
    if ((this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0) {
        ast.setFlag(ICompilationUnit.ENABLE_STATEMENTS_RECOVERY);
    }
    converter.setAST(ast);
    CodeSnippetParsingUtil codeSnippetParsingUtil = new CodeSnippetParsingUtil((this.bits & CompilationUnitResolver.IGNORE_METHOD_BODIES) != 0);
    CompilationUnit compilationUnit = ast.newCompilationUnit();
    if (this.sourceLength == -1) {
        this.sourceLength = this.rawSource.length;
    }
    switch(this.astKind) {
        case K_STATEMENTS:
            ConstructorDeclaration constructorDeclaration = codeSnippetParsingUtil.parseStatements(this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true, (this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0);
            RecoveryScannerData data = constructorDeclaration.compilationResult.recoveryScannerData;
            if (data != null) {
                Scanner scanner = converter.scanner;
                converter.scanner = new RecoveryScanner(scanner, data.removeUnused());
                converter.docParser.scanner = converter.scanner;
                converter.scanner.setSource(scanner.source);
                compilationUnit.setStatementsRecoveryData(data);
            }
            RecordedParsingInformation recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation;
            int[][] comments = recordedParsingInformation.commentPositions;
            if (comments != null) {
                converter.buildCommentsTable(compilationUnit, comments);
            }
            compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds);
            Block block = ast.newBlock();
            block.setSourceRange(this.sourceOffset, this.sourceOffset + this.sourceLength);
            org.eclipse.jdt.internal.compiler.ast.Statement[] statements = constructorDeclaration.statements;
            if (statements != null) {
                int statementsLength = statements.length;
                for (int i = 0; i < statementsLength; i++) {
                    if (statements[i] instanceof org.eclipse.jdt.internal.compiler.ast.LocalDeclaration) {
                        converter.checkAndAddMultipleLocalDeclaration(statements, i, block.statements());
                    } else {
                        Statement statement = converter.convert(statements[i]);
                        if (statement != null) {
                            block.statements().add(statement);
                        }
                    }
                }
            }
            rootNodeToCompilationUnit(ast, compilationUnit, block, recordedParsingInformation, data);
            ast.setDefaultNodeFlag(0);
            ast.setOriginalModificationCount(ast.modificationCount());
            return block;
        case K_EXPRESSION:
            org.eclipse.jdt.internal.compiler.ast.Expression expression = codeSnippetParsingUtil.parseExpression(this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true);
            recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation;
            comments = recordedParsingInformation.commentPositions;
            if (comments != null) {
                converter.buildCommentsTable(compilationUnit, comments);
            }
            compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds);
            if (expression != null) {
                Expression expression2 = converter.convert(expression);
                rootNodeToCompilationUnit(expression2.getAST(), compilationUnit, expression2, codeSnippetParsingUtil.recordedParsingInformation, null);
                ast.setDefaultNodeFlag(0);
                ast.setOriginalModificationCount(ast.modificationCount());
                return expression2;
            } else {
                CategorizedProblem[] problems = recordedParsingInformation.problems;
                if (problems != null) {
                    compilationUnit.setProblems(problems);
                }
                ast.setDefaultNodeFlag(0);
                ast.setOriginalModificationCount(ast.modificationCount());
                return compilationUnit;
            }
        case K_CLASS_BODY_DECLARATIONS:
            final org.eclipse.jdt.internal.compiler.ast.ASTNode[] nodes = codeSnippetParsingUtil.parseClassBodyDeclarations(this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true, (this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0);
            recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation;
            comments = recordedParsingInformation.commentPositions;
            if (comments != null) {
                converter.buildCommentsTable(compilationUnit, comments);
            }
            compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds);
            if (nodes != null) {
                // source has no syntax error or the statement recovery is enabled
                TypeDeclaration typeDeclaration = converter.convert(nodes);
                typeDeclaration.setSourceRange(this.sourceOffset, this.sourceOffset + this.sourceLength);
                rootNodeToCompilationUnit(typeDeclaration.getAST(), compilationUnit, typeDeclaration, codeSnippetParsingUtil.recordedParsingInformation, null);
                ast.setDefaultNodeFlag(0);
                ast.setOriginalModificationCount(ast.modificationCount());
                return typeDeclaration;
            } else {
                // source has syntax error and the statement recovery is disabled
                CategorizedProblem[] problems = recordedParsingInformation.problems;
                if (problems != null) {
                    compilationUnit.setProblems(problems);
                }
                ast.setDefaultNodeFlag(0);
                ast.setOriginalModificationCount(ast.modificationCount());
                return compilationUnit;
            }
    }
    throw new IllegalStateException();
}
Also used : Scanner(org.eclipse.jdt.internal.compiler.parser.Scanner) RecoveryScanner(org.eclipse.jdt.internal.compiler.parser.RecoveryScanner) ConstructorDeclaration(org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration) CodeSnippetParsingUtil(org.eclipse.jdt.internal.core.util.CodeSnippetParsingUtil) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) BasicCompilationUnit(org.eclipse.jdt.internal.core.BasicCompilationUnit) RecoveryScanner(org.eclipse.jdt.internal.compiler.parser.RecoveryScanner) CategorizedProblem(org.eclipse.jdt.core.compiler.CategorizedProblem) RecoveryScannerData(org.eclipse.jdt.internal.compiler.parser.RecoveryScannerData) RecordedParsingInformation(org.eclipse.jdt.internal.core.util.RecordedParsingInformation)

Aggregations

CategorizedProblem (org.eclipse.jdt.core.compiler.CategorizedProblem)9 IProblem (org.eclipse.jdt.core.compiler.IProblem)3 CompilationUnitDeclaration (org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration)3 ClassFile (org.eclipse.jdt.internal.compiler.ClassFile)2 CompilerOptions (org.eclipse.jdt.internal.compiler.impl.CompilerOptions)2 CancelableNameEnvironment (org.eclipse.jdt.internal.core.CancelableNameEnvironment)2 CancelableProblemFactory (org.eclipse.jdt.internal.core.CancelableProblemFactory)2 JapidCompilationException (cn.bran.japid.compiler.JapidCompilationException)1 JapidTemplateException (cn.bran.japid.exceptions.JapidTemplateException)1 JapidTemplate (cn.bran.japid.template.JapidTemplate)1 Iterator (java.util.Iterator)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 CompilerMessage (lombok.javac.CapturingDiagnosticListener.CompilerMessage)1 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)1 IJavaProject (org.eclipse.jdt.core.IJavaProject)1 JavaModelException (org.eclipse.jdt.core.JavaModelException)1 CompilationResult (org.eclipse.jdt.internal.compiler.CompilationResult)1 Compiler (org.eclipse.jdt.internal.compiler.Compiler)1 ICompilerRequestor (org.eclipse.jdt.internal.compiler.ICompilerRequestor)1 ConstructorDeclaration (org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration)1