Example usage for org.eclipse.jdt.core.compiler IProblem getSourceLineNumber

List of usage examples for org.eclipse.jdt.core.compiler IProblem getSourceLineNumber

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.compiler IProblem getSourceLineNumber.

Prototype

int getSourceLineNumber();

Source Link

Document

Answer the line number in source where the problem begins.

Usage

From source file:at.bestsolution.javafx.ide.jdt.internal.JavaEditor.java

License:Open Source License

@Inject
public JavaEditor(BorderPane pane, IEditorInput input) {
    editor = new SourceEditor();
    pane.setCenter(editor);//  ww w . jav a 2 s  . c o m

    IResourceFileInput fsInput = (IResourceFileInput) input;
    try {
        unit = ((ICompilationUnit) JavaCore.create(fsInput.getFile()))
                .getWorkingCopy(new FXWorkingCopyOwner(new IProblemRequestor() {
                    private List<ProblemMarker> l = new ArrayList<>();

                    @Override
                    public boolean isActive() {
                        // TODO Auto-generated method stub
                        return true;
                    }

                    @Override
                    public void endReporting() {
                        setMarkers(l);
                    }

                    @Override
                    public void beginReporting() {
                        l.clear();
                    }

                    @Override
                    public void acceptProblem(IProblem problem) {
                        int linenumber = problem.getSourceLineNumber();
                        int startCol = problem.getSourceStart();
                        int endCol = problem.getSourceEnd();

                        if (endCol == startCol) {
                            endCol++;
                        }

                        String description = problem.getMessage();
                        ProblemMarker marker = new ProblemMarker(
                                problem.isError() ? at.bestsolution.javafx.ide.editor.ProblemMarker.Type.ERROR
                                        : at.bestsolution.javafx.ide.editor.ProblemMarker.Type.WARNING,
                                linenumber, startCol, endCol, description);
                        l.add(marker);
                    }
                }), new NullProgressMonitor());
    } catch (JavaModelException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    final Document doc = createDocument(unit);
    editor.setDocument(doc);
    editor.setContentProposalComputer(new ContentProposalComputer() {

        @Override
        public List<Proposal> computeProposals(String line, String prefix, int offset) {
            final List<Proposal> l = new ArrayList<ContentProposalComputer.Proposal>();

            try {
                unit.codeComplete(offset, new CompletionRequestor() {

                    @Override
                    public void accept(CompletionProposal proposal) {
                        String completion = new String(proposal.getCompletion());

                        if (!Flags.isPublic(proposal.getFlags())) {
                            return;
                        }

                        if (proposal.getKind() == CompletionProposal.METHOD_REF) {
                            String sig = Signature.toString(new String(proposal.getSignature()),
                                    new String(proposal.getName()), null, false, false);
                            StyledString s = new StyledString(sig + " : " + Signature.getSimpleName(Signature
                                    .toString(Signature.getReturnType(new String(proposal.getSignature())))));
                            s.appendString(
                                    " - " + Signature.getSignatureSimpleName(
                                            new String(proposal.getDeclarationSignature())),
                                    Style.colored("#AAAAAA"));

                            l.add(new Proposal(Type.METHOD, completion, s));
                        } else if (proposal.getKind() == CompletionProposal.FIELD_REF) {
                            StyledString s = new StyledString(
                                    completion + " : "
                                            + (proposal.getSignature() != null
                                                    ? Signature.getSignatureSimpleName(
                                                            new String(proposal.getSignature()))
                                                    : "<unknown>"));
                            s.appendString(
                                    " - " + (proposal.getDeclarationSignature() != null
                                            ? Signature.getSignatureSimpleName(
                                                    new String(proposal.getDeclarationSignature()))
                                            : "<unknown>"),
                                    Style.colored("#AAAAAA"));
                            l.add(new Proposal(Type.FIELD, completion, s));
                        } else if (proposal.getKind() == CompletionProposal.TYPE_REF) {
                            if (proposal.getAccessibility() == IAccessRule.K_NON_ACCESSIBLE) {
                                return;
                            }

                            StyledString s = new StyledString(
                                    Signature.getSignatureSimpleName(new String(proposal.getSignature())));
                            s.appendString(" - " + new String(proposal.getDeclarationSignature()),
                                    Style.colored("#AAAAAA"));
                            l.add(new Proposal(Type.TYPE, new String(proposal.getCompletion()), s));
                        } else {
                            System.err.println(proposal);
                        }
                    }
                });
            } catch (JavaModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return l;
        }

    });
    editor.setSaveCallback(new Runnable() {

        @Override
        public void run() {
            try {
                unit.commitWorkingCopy(true, null);
            } catch (JavaModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    try {
        unit.reconcile(ICompilationUnit.NO_AST, true, null, null);
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.android.build.gradle.tasks.annotations.ExtractAnnotationsDriver.java

License:Apache License

@SuppressWarnings("MethodMayBeStatic")
public void run(@NonNull String[] args) {
    List<String> classpath = Lists.newArrayList();
    List<File> sources = Lists.newArrayList();
    List<File> mergePaths = Lists.newArrayList();
    List<File> apiFilters = null;
    File rmTypeDefs = null;//from  w  ww  . j av a2  s .  c  o  m
    boolean verbose = true;
    boolean allowMissingTypes = false;
    boolean allowErrors = false;
    boolean listFiltered = true;
    boolean skipClassRetention = false;

    String encoding = Charsets.UTF_8.name();
    File output = null;
    File proguard = null;
    long languageLevel = EcjParser.getLanguageLevel(1, 7);
    if (args.length == 1 && "--help".equals(args[0])) {
        usage(System.out);
    }
    if (args.length < 2) {
        usage(System.err);
    }
    for (int i = 0, n = args.length; i < n; i++) {
        String flag = args[i];

        if (flag.equals("--quiet")) {
            verbose = false;
            continue;
        } else if (flag.equals("--allow-missing-types")) {
            allowMissingTypes = true;
            continue;
        } else if (flag.equals("--allow-errors")) {
            allowErrors = true;
            continue;
        } else if (flag.equals("--hide-filtered")) {
            listFiltered = false;
            continue;
        } else if (flag.equals("--skip-class-retention")) {
            skipClassRetention = true;
            continue;
        }
        if (i == n - 1) {
            usage(System.err);
        }
        String value = args[i + 1];
        i++;

        if (flag.equals("--sources")) {
            sources = getFiles(value);
        } else if (flag.equals("--classpath")) {
            classpath = getPaths(value);
        } else if (flag.equals("--merge-zips")) {
            mergePaths = getFiles(value);
        } else if (flag.equals("--output")) {
            output = new File(value);
            if (output.exists()) {
                if (output.isDirectory()) {
                    abort(output + " is a directory");
                }
                boolean deleted = output.delete();
                if (!deleted) {
                    abort("Could not delete previous version of " + output);
                }
            } else if (output.getParentFile() != null && !output.getParentFile().exists()) {
                abort(output.getParentFile() + " does not exist");
            }
        } else if (flag.equals("--proguard")) {
            proguard = new File(value);
            if (proguard.exists()) {
                if (proguard.isDirectory()) {
                    abort(proguard + " is a directory");
                }
                boolean deleted = proguard.delete();
                if (!deleted) {
                    abort("Could not delete previous version of " + proguard);
                }
            } else if (proguard.getParentFile() != null && !proguard.getParentFile().exists()) {
                abort(proguard.getParentFile() + " does not exist");
            }
        } else if (flag.equals("--encoding")) {
            encoding = value;
        } else if (flag.equals("--api-filter")) {
            if (apiFilters == null) {
                apiFilters = Lists.newArrayList();
            }
            for (String path : Splitter.on(",").omitEmptyStrings().split(value)) {
                File apiFilter = new File(path);
                if (!apiFilter.isFile()) {
                    String message = apiFilter + " does not exist or is not a file";
                    abort(message);
                }
                apiFilters.add(apiFilter);
            }
        } else if (flag.equals("--language-level")) {
            if ("1.6".equals(value)) {
                languageLevel = EcjParser.getLanguageLevel(1, 6);
            } else if ("1.7".equals(value)) {
                languageLevel = EcjParser.getLanguageLevel(1, 7);
            } else {
                abort("Unsupported language level " + value);
            }
        } else if (flag.equals("--rmtypedefs")) {
            rmTypeDefs = new File(value);
            if (!rmTypeDefs.isDirectory()) {
                abort(rmTypeDefs + " is not a directory");
            }
        } else {
            System.err.println("Unknown flag " + flag + ": Use --help for usage information");
        }
    }

    if (sources.isEmpty()) {
        abort("Must specify at least one source path");
    }
    if (classpath.isEmpty()) {
        abort("Must specify classpath pointing to at least android.jar or the framework");
    }
    if (output == null && proguard == null) {
        abort("Must specify output path with --output or a proguard path with --proguard");
    }

    // API definition files
    ApiDatabase database = null;
    if (apiFilters != null && !apiFilters.isEmpty()) {
        try {
            List<String> lines = Lists.newArrayList();
            for (File file : apiFilters) {
                lines.addAll(Files.readLines(file, Charsets.UTF_8));
            }
            database = new ApiDatabase(lines);
        } catch (IOException e) {
            abort("Could not open API database " + apiFilters + ": " + e.getLocalizedMessage());
        }
    }

    Extractor extractor = new Extractor(database, rmTypeDefs, verbose, !skipClassRetention, true);
    extractor.setListIgnored(listFiltered);

    try {
        Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> pair = parseSources(sources, classpath,
                encoding, languageLevel);
        Collection<CompilationUnitDeclaration> units = pair.getFirst();

        boolean abort = false;
        int errorCount = 0;
        for (CompilationUnitDeclaration unit : units) {
            // so maybe I don't need my map!!
            IProblem[] problems = unit.compilationResult().getAllProblems();
            if (problems != null) {
                for (IProblem problem : problems) {
                    if (problem.isError()) {
                        errorCount++;
                        String message = problem.getMessage();
                        if (allowMissingTypes) {
                            if (message.contains("cannot be resolved")) {
                                continue;
                            }
                        }

                        System.out.println("Error: " + new String(problem.getOriginatingFileName()) + ":"
                                + problem.getSourceLineNumber() + ": " + message);
                        abort = !allowErrors;
                    }
                }
            }
        }
        if (errorCount > 0) {
            System.err.println("Found " + errorCount + " errors");
        }
        if (abort) {
            abort("Not extracting annotations (compilation problems encountered)");
        }

        INameEnvironment environment = pair.getSecond();
        extractor.extractFromProjectSource(units);

        if (mergePaths != null) {
            for (File jar : mergePaths) {
                extractor.mergeExisting(jar);
            }
        }

        extractor.export(output, proguard);

        // Remove typedefs?
        //noinspection VariableNotUsedInsideIf
        if (rmTypeDefs != null) {
            extractor.removeTypedefClasses();
        }

        environment.cleanup();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.android.build.gradle.tasks.ExtractAnnotations.java

License:Apache License

@Override
@TaskAction/*  www .ja v a 2  s .  c  om*/
protected void compile() {
    if (!hasAndroidAnnotations()) {
        return;
    }

    if (encoding == null) {
        encoding = UTF_8;
    }

    EcjParser.EcjResult result = parseSources();
    Collection<CompilationUnitDeclaration> parsedUnits = result.getCompilationUnits();

    try {
        if (!allowErrors) {
            for (CompilationUnitDeclaration unit : parsedUnits) {
                // so maybe I don't need my map!!
                CategorizedProblem[] problems = unit.compilationResult().getAllProblems();
                for (IProblem problem : problems) {
                    if (problem.isError()) {
                        getLogger().warn("Not extracting annotations (compilation problems " + "encountered)\n"
                                + "Error: " + new String(problem.getOriginatingFileName()) + ":"
                                + problem.getSourceLineNumber() + ": " + problem.getMessage());
                        // TODO: Consider whether we abort the build at this point!
                        return;
                    }
                }
            }
        }

        // API definition file
        ApiDatabase database = null;
        if (apiFilter != null && apiFilter.exists()) {
            try {
                database = new ApiDatabase(apiFilter);
            } catch (IOException e) {
                throw new BuildException("Could not open API database " + apiFilter, e);
            }
        }

        boolean displayInfo = getProject().getLogger().isEnabled(LogLevel.INFO);

        Extractor extractor = new Extractor(database, classDir, displayInfo,
                false /*includeClassRetentionAnnotations*/, false /*sortAnnotations*/);
        extractor.extractFromProjectSource(parsedUnits);
        if (mergeJars != null) {
            for (File jar : mergeJars) {
                extractor.mergeExisting(jar);
            }
        }
        extractor.export(output, proguard);
        if (typedefFile != null) {
            extractor.writeTypedefFile(typedefFile);
        } else {
            extractor.removeTypedefClasses();
        }
    } finally {
        result.dispose();
    }
}

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

License:Apache License

@Override
public void prepareJavaParse(@NonNull final List<JavaContext> contexts) {
    if (mProject == null || contexts.isEmpty()) {
        return;/*from ww  w  . j a v  a2s  . c om*/
    }

    List<ICompilationUnit> sources = Lists.newArrayListWithExpectedSize(contexts.size());
    mSourceUnits = Maps.newHashMapWithExpectedSize(sources.size());
    for (JavaContext context : contexts) {
        String contents = context.getContents();
        if (contents == null) {
            continue;
        }
        File file = context.file;
        CompilationUnit unit = new CompilationUnit(contents.toCharArray(), file.getPath(), UTF_8);
        sources.add(unit);
        mSourceUnits.put(file, unit);
    }
    List<String> classPath = computeClassPath(contexts);
    mCompiled = Maps.newHashMapWithExpectedSize(mSourceUnits.size());
    try {
        mEnvironment = parse(createCompilerOptions(), sources, classPath, mCompiled, mClient);
    } catch (Throwable t) {
        mClient.log(t, "ECJ compiler crashed");
    }

    if (DEBUG_DUMP_PARSE_ERRORS) {
        for (CompilationUnitDeclaration unit : mCompiled.values()) {
            // so maybe I don't need my map!!
            CategorizedProblem[] problems = unit.compilationResult().getAllProblems();
            if (problems != null) {
                for (IProblem problem : problems) {
                    if (problem == null || !problem.isError()) {
                        continue;
                    }
                    System.out.println(new String(problem.getOriginatingFileName()) + ":"
                            + (problem.isError() ? "Error" : "Warning") + ": " + problem.getSourceLineNumber()
                            + ": " + problem.getMessage());
                }
            }
        }
    }
}

From source file:com.google.devtools.j2cpp.J2ObjC.java

License:Open Source License

private static CompilationUnit parse(String filename, String source) {
    logger.finest("parsing " + filename);
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    Map<String, String> compilerOptions = Options.getCompilerOptions();
    parser.setCompilerOptions(compilerOptions);
    parser.setSource(source.toCharArray());
    parser.setResolveBindings(true);/*from   w ww .j  a  v a2s.  c  o  m*/
    setPaths(parser);
    parser.setUnitName(filename);
    CompilationUnit unit = (CompilationUnit) parser.createAST(null);

    for (IProblem problem : getCompilationErrors(unit)) {
        if (problem.isError()) {
            error(String.format("%s:%s: %s", filename, problem.getSourceLineNumber(), problem.getMessage()));
        }
    }
    return unit;
}

From source file:com.google.devtools.j2objc.J2ObjC.java

License:Open Source License

private static CompilationUnit parse(String filename, String source) {
    logger.finest("parsing " + filename);
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    Map<String, String> compilerOptions = Options.getCompilerOptions();
    parser.setCompilerOptions(compilerOptions);
    parser.setSource(source.toCharArray());
    parser.setResolveBindings(true);//from  www .  j  a  v a  2s. c o m
    setPaths(parser);
    parser.setUnitName(filename);
    CompilationUnit unit = (CompilationUnit) parser.createAST(null);

    for (IProblem problem : getCompilationErrors(unit)) {
        if (problem.isError()) {
            error(String.format("%s:%s: %s", filename, problem.getSourceLineNumber(), problem.getMessage()));
        }
    }
    return unit;
}

From source file:com.google.devtools.j2objc.jdt.JdtParser.java

License:Apache License

private boolean checkCompilationErrors(String filename, CompilationUnit unit) {
    boolean hasErrors = false;
    for (IProblem problem : unit.getProblems()) {
        if (problem.isError()) {
            ErrorUtil.error(//from   ww w.  j ava  2s  .  c  o m
                    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;
}

From source file:com.google.devtools.j2objc.util.JdtParser.java

License:Apache License

private boolean checkCompilationErrors(String filename, CompilationUnit unit) {
    boolean hasErrors = false;
    for (IProblem problem : unit.getProblems()) {
        if (problem.isError()) {
            ErrorUtil.error(//from ww  w.  j a va  2s  .c o m
                    String.format("%s:%s: %s", filename, problem.getSourceLineNumber(), problem.getMessage()));
            hasErrors = true;
        }
    }
    return !hasErrors;
}

From source file:com.j2swift.util.JdtParser.java

License:Apache License

protected boolean checkCompilationErrors(String filename, CompilationUnit unit) {
    boolean hasErrors = false;
    for (IProblem problem : unit.getProblems()) {
        if (problem.isError()) {
            ErrorUtil.error(/*from  ww w.j  av a  2  s  .c om*/
                    String.format("%s:%s: %s", filename, problem.getSourceLineNumber(), problem.getMessage()));
            hasErrors = true;
        }
    }
    return !hasErrors;
}

From source file:com.microsoft.javapkgsrv.JavaParser.java

License:MIT License

public List<Problem> ProcessFileParseMessagesRequest(Integer fileId) {
    List<FileParseMessagesResponse.Problem> ret = new ArrayList<FileParseMessagesResponse.Problem>();
    if (ActiveUnits.containsKey(fileId)) {
        CompilationUnit cu = ActiveUnits.get(fileId);
        IProblem[] problems = cu.getProblems();

        for (IProblem problem : problems) {
            System.out.println(problem.toString());
            FileParseMessagesResponse.Problem.Builder retProblem = FileParseMessagesResponse.Problem
                    .newBuilder().setId(problem.getID()).setMessage(problem.getMessage())
                    .setFileName(new String(problem.getOriginatingFileName()))
                    .setScopeStart(problem.getSourceStart()).setScopeEnd(problem.getSourceEnd() + 1)
                    .setLineNumber(problem.getSourceLineNumber()).setProblemType(GetProblemType(problem));
            for (String arg : problem.getArguments())
                retProblem.addArguments(arg);
            ret.add(retProblem.build());
        }/*  w w w  .  j  av  a  2s  .com*/
    }
    return ret;
}