Java Code Examples for javax.tools.Diagnostic#getStartPosition()

The following examples show how to use javax.tools.Diagnostic#getStartPosition() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DiagnosticPresenter.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void click(Diagnostic diagnostic) {
    Log.d(TAG, "click() called with: diagnostic = [" + diagnostic + "]");
    mMainActivity.closeDrawer(GravityCompat.START);

    Object source = diagnostic.getSource();
    if (source instanceof JavaFileObject && diagnostic.getKind() == Diagnostic.Kind.ERROR) {
        String path = ((JavaFileObject) source).getName();
        int i = mPagePresenter.gotoPage(path);
        if (i == -1) {
            mPagePresenter.addPage(path, true);
        }
        EditPageContract.SourceView editor = mPagePresenter.getCurrentPage();
        if (editor == null) {
            Log.d(TAG, "click: editor null");
            return;
        }
        int startPosition = (int) diagnostic.getStartPosition();
        int endPosition = (int) diagnostic.getEndPosition();
        editor.highlightError(startPosition, endPosition);
        editor.setCursorPosition(endPosition);
    } else {
        // TODO: 19/07/2017 implement other
    }
}
 
Example 2
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Check the tree has compile error in given errors.
 *
 * @param tree compilation tree
 * @param errors Array of error code
 * @return true if tree has compile error present in list of errors.
 * @since 2.37
 */
public boolean hasError(@NonNull Tree tree, String... errors) {
    long startPos = info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), tree);
    long endPos = info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), tree);

    List<Diagnostic> diagnosticsList = info.getDiagnostics();
    for (Diagnostic d : diagnosticsList) {
        if ((d.getKind() == Diagnostic.Kind.ERROR) && ((d.getStartPosition() >= startPos) && (d.getEndPosition() <= endPos))) {
            if (errors == null || errors.length == 0) {
                return true;
            } else {
                for (String error : errors) {
                    if (error.equals(d.getCode())) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
 
Example 3
Source File: EndPositions.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example 4
Source File: EndPositions.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example 5
Source File: TaskFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Diag diag(final Diagnostic<? extends JavaFileObject> d) {
    return new Diag() {

        @Override
        public boolean isError() {
            return d.getKind() == Diagnostic.Kind.ERROR;
        }

        @Override
        public long getPosition() {
            return d.getPosition();
        }

        @Override
        public long getStartPosition() {
            return d.getStartPosition();
        }

        @Override
        public long getEndPosition() {
            return d.getEndPosition();
        }

        @Override
        public String getCode() {
            return d.getCode();
        }

        @Override
        public String getMessage(Locale locale) {
            return expunge(d.getMessage(locale));
        }
    };
}
 
Example 6
Source File: TreeEndPosTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static void compile(JavaSource src) throws IOException {
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(ba);
    File tempDir = new File(".");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector dc = new DiagnosticCollector();
    JavaFileManager javaFileManager = getJavaFileManager(compiler, dc);
    List<String> options = new ArrayList<>();
    options.add("-cp");
    options.add(tempDir.getPath());
    options.add("-d");
    options.add(tempDir.getPath());
    options.add("-XDshouldStopPolicy=GENERATE");

    List<JavaFileObject> sources = new ArrayList<>();
    sources.add(src);
    JavaCompiler.CompilationTask task =
            compiler.getTask(writer, javaFileManager,
            dc, options, null,
            sources);
    task.call();
    for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) {
        long actualStart = diagnostic.getStartPosition();
        long actualEnd = diagnostic.getEndPosition();
        System.out.println("Source: " + src.source);
        System.out.println("Diagnostic: " + diagnostic);
        System.out.print("Start position: Expected: " + src.startPos);
        System.out.println(", Actual: " + actualStart);
        System.out.print("End position: Expected: " + src.endPos);
        System.out.println(", Actual: " + actualEnd);
        if (src.startPos != actualStart || src.endPos != actualEnd) {
            throw new RuntimeException("error: trees don't match");
        }
    }
}
 
Example 7
Source File: EndPositions.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example 8
Source File: RemoveInvalidModifier.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the diagnostics entry
 * @param compilationInfo
 * @param start
 * @param codes
 * @return 
 */
private Diagnostic getDiagnostic(CompilationInfo compilationInfo, long start, Set<String> errorCodes) {
    Diagnostic result = null;
    for (Diagnostic d : compilationInfo.getDiagnostics()) {
        if (start != d.getStartPosition()) {
            continue;
        }
        if (!errorCodes.contains(d.getCode())) {
            continue;
        }
        result=d;
    }
    return result;
}
 
Example 9
Source File: ErrorHintsProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static long getPrefferedPosition(CompilationInfo info, Diagnostic d) throws IOException {
    if ("compiler.err.doesnt.exist".equals(d.getCode()) || "compiler.err.try.with.resources.expr.needs.var".equals(d.getCode())) {
        return d.getStartPosition();
    }
    if ("compiler.err.cant.resolve.location".equals(d.getCode()) || "compiler.err.cant.resolve.location.args".equals(d.getCode())) {
        int[] span = findUnresolvedElementSpan(info, (int) d.getPosition());
        
        if (span != null) {
            return span[0];
        } else {
            return d.getPosition();
        }
    }
    if ("compiler.err.not.stmt".equals(d.getCode())) {
        //check for "Collections.":
        TreePath path = findUnresolvedElement(info, (int) d.getStartPosition() - 1);
        Element el = path != null ? info.getTrees().getElement(path) : null;
        
        if (el == null || el.asType().getKind() == TypeKind.ERROR) {
            return d.getStartPosition() - 1;
        }
        /*
        if (el.asType().getKind() == TypeKind.PACKAGE) {
            //check if the package does actually exist:
            String s = ((PackageElement) el).getQualifiedName().toString();
            if (info.getElements().getPackageElement(s) == null) {
                //it does not:
                return d.getStartPosition() - 1;
            }
        }
                */
        
        return d.getStartPosition();
    }
    
    return d.getPosition();
}
 
Example 10
Source File: TreeEndPosTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void compile(JavaSource src) throws IOException {
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(ba);
    File tempDir = new File(".");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector dc = new DiagnosticCollector();
    try (JavaFileManager javaFileManager = getJavaFileManager(compiler, dc)) {
        List<String> options = new ArrayList<>();
        options.add("-cp");
        options.add(tempDir.getPath());
        options.add("-d");
        options.add(tempDir.getPath());
        options.add("--should-stop:at=GENERATE");

        List<JavaFileObject> sources = new ArrayList<>();
        sources.add(src);
        JavaCompiler.CompilationTask task =
                compiler.getTask(writer, javaFileManager,
                dc, options, null,
                sources);
        task.call();
        for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) {
            long actualStart = diagnostic.getStartPosition();
            long actualEnd = diagnostic.getEndPosition();
            System.out.println("Source: " + src.source);
            System.out.println("Diagnostic: " + diagnostic);
            System.out.print("Start position: Expected: " + src.startPos);
            System.out.println(", Actual: " + actualStart);
            System.out.print("End position: Expected: " + src.endPos);
            System.out.println(", Actual: " + actualEnd);
            if (src.startPos != actualStart || src.endPos != actualEnd) {
                throw new RuntimeException("error: trees don't match");
            }
        }
    }
}
 
Example 11
Source File: JavacParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String diagnosticToString(Diagnostic<JavaFileObject> d) {
    return d.getSource().toUri().toString() + ":" +
           d.getKind() + ":" +
           d.getStartPosition() + ":" +
           d.getPosition() + ":" +
           d.getEndPosition() + ":" +
           d.getLineNumber() + ":" +
           d.getColumnNumber() + ":" +
           d.getCode() + ":" +
           d.getMessage(null);
}
 
Example 12
Source File: TreeEndPosTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static void compile(JavaSource src) throws IOException {
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(ba);
    File tempDir = new File(".");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector dc = new DiagnosticCollector();
    JavaFileManager javaFileManager = getJavaFileManager(compiler, dc);
    List<String> options = new ArrayList<>();
    options.add("-cp");
    options.add(tempDir.getPath());
    options.add("-d");
    options.add(tempDir.getPath());
    options.add("-XDshouldStopPolicy=GENERATE");

    List<JavaFileObject> sources = new ArrayList<>();
    sources.add(src);
    JavaCompiler.CompilationTask task =
            compiler.getTask(writer, javaFileManager,
            dc, options, null,
            sources);
    task.call();
    for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) {
        long actualStart = diagnostic.getStartPosition();
        long actualEnd = diagnostic.getEndPosition();
        System.out.println("Source: " + src.source);
        System.out.println("Diagnostic: " + diagnostic);
        System.out.print("Start position: Expected: " + src.startPos);
        System.out.println(", Actual: " + actualStart);
        System.out.print("End position: Expected: " + src.endPos);
        System.out.println(", Actual: " + actualEnd);
        if (src.startPos != actualStart || src.endPos != actualEnd) {
            throw new RuntimeException("error: trees don't match");
        }
    }
}
 
Example 13
Source File: TreeEndPosTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static void compile(JavaSource src) throws IOException {
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(ba);
    File tempDir = new File(".");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector dc = new DiagnosticCollector();
    JavaFileManager javaFileManager = getJavaFileManager(compiler, dc);
    List<String> options = new ArrayList<>();
    options.add("-cp");
    options.add(tempDir.getPath());
    options.add("-d");
    options.add(tempDir.getPath());
    options.add("-XDshouldStopPolicy=GENERATE");

    List<JavaFileObject> sources = new ArrayList<>();
    sources.add(src);
    JavaCompiler.CompilationTask task =
            compiler.getTask(writer, javaFileManager,
            dc, options, null,
            sources);
    task.call();
    for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) {
        long actualStart = diagnostic.getStartPosition();
        long actualEnd = diagnostic.getEndPosition();
        System.out.println("Source: " + src.source);
        System.out.println("Diagnostic: " + diagnostic);
        System.out.print("Start position: Expected: " + src.startPos);
        System.out.println(", Actual: " + actualStart);
        System.out.print("End position: Expected: " + src.endPos);
        System.out.println(", Actual: " + actualEnd);
        if (src.startPos != actualStart || src.endPos != actualEnd) {
            throw new RuntimeException("error: trees don't match");
        }
    }
}
 
Example 14
Source File: EndPositions.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example 15
Source File: TreeEndPosTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
static void compile(JavaSource src) throws IOException {
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(ba);
    File tempDir = new File(".");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector dc = new DiagnosticCollector();
    JavaFileManager javaFileManager = getJavaFileManager(compiler, dc);
    List<String> options = new ArrayList<>();
    options.add("-cp");
    options.add(tempDir.getPath());
    options.add("-d");
    options.add(tempDir.getPath());
    options.add("-XDshouldStopPolicy=GENERATE");

    List<JavaFileObject> sources = new ArrayList<>();
    sources.add(src);
    JavaCompiler.CompilationTask task =
            compiler.getTask(writer, javaFileManager,
            dc, options, null,
            sources);
    task.call();
    for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) {
        long actualStart = diagnostic.getStartPosition();
        long actualEnd = diagnostic.getEndPosition();
        System.out.println("Source: " + src.source);
        System.out.println("Diagnostic: " + diagnostic);
        System.out.print("Start position: Expected: " + src.startPos);
        System.out.println(", Actual: " + actualStart);
        System.out.print("End position: Expected: " + src.endPos);
        System.out.println(", Actual: " + actualEnd);
        if (src.startPos != actualStart || src.endPos != actualEnd) {
            throw new RuntimeException("error: trees don't match");
        }
    }
}
 
Example 16
Source File: TreeEndPosTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static void compile(JavaSource src) throws IOException {
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(ba);
    File tempDir = new File(".");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector dc = new DiagnosticCollector();
    JavaFileManager javaFileManager = getJavaFileManager(compiler, dc);
    List<String> options = new ArrayList<>();
    options.add("-cp");
    options.add(tempDir.getPath());
    options.add("-d");
    options.add(tempDir.getPath());
    options.add("-XDshouldStopPolicy=GENERATE");

    List<JavaFileObject> sources = new ArrayList<>();
    sources.add(src);
    JavaCompiler.CompilationTask task =
            compiler.getTask(writer, javaFileManager,
            dc, options, null,
            sources);
    task.call();
    for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) {
        long actualStart = diagnostic.getStartPosition();
        long actualEnd = diagnostic.getEndPosition();
        System.out.println("Source: " + src.source);
        System.out.println("Diagnostic: " + diagnostic);
        System.out.print("Start position: Expected: " + src.startPos);
        System.out.println(", Actual: " + actualStart);
        System.out.print("End position: Expected: " + src.endPos);
        System.out.println(", Actual: " + actualEnd);
        if (src.startPos != actualStart || src.endPos != actualEnd) {
            throw new RuntimeException("error: trees don't match");
        }
    }
}
 
Example 17
Source File: EndPositions.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example 18
Source File: TreeEndPosTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static void compile(JavaSource src) throws IOException {
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(ba);
    File tempDir = new File(".");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector dc = new DiagnosticCollector();
    JavaFileManager javaFileManager = getJavaFileManager(compiler, dc);
    List<String> options = new ArrayList<>();
    options.add("-cp");
    options.add(tempDir.getPath());
    options.add("-d");
    options.add(tempDir.getPath());
    options.add("-XDshouldStopPolicy=GENERATE");

    List<JavaFileObject> sources = new ArrayList<>();
    sources.add(src);
    JavaCompiler.CompilationTask task =
            compiler.getTask(writer, javaFileManager,
            dc, options, null,
            sources);
    task.call();
    for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) {
        long actualStart = diagnostic.getStartPosition();
        long actualEnd = diagnostic.getEndPosition();
        System.out.println("Source: " + src.source);
        System.out.println("Diagnostic: " + diagnostic);
        System.out.print("Start position: Expected: " + src.startPos);
        System.out.println(", Actual: " + actualStart);
        System.out.print("End position: Expected: " + src.endPos);
        System.out.println(", Actual: " + actualEnd);
        if (src.startPos != actualStart || src.endPos != actualEnd) {
            throw new RuntimeException("error: trees don't match");
        }
    }
}
 
Example 19
Source File: ConvertToDiamondBulkHint.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern("new $clazz<$tparams$>($params$)")
})
public static ErrorDescription compute(HintContext ctx) {
    // hint disabled for var type variable initialization.
    TreePath parentPath = ctx.getPath().getParentPath();
    boolean isVarInit = MatcherUtilities.matches(ctx, parentPath, "$mods$ $type $name = $init;");   //NOI18N
    if (isVarInit) {
        if (ctx.getInfo().getTreeUtilities().isVarType(parentPath)) {
            return null;
        }
    }

    if (ctx.getMultiVariables().get("$tparams$").isEmpty()) return null;
    
    TreePath clazz = ctx.getVariables().get("$clazz");
    long start = ctx.getInfo().getTrees().getSourcePositions().getStartPosition(clazz.getCompilationUnit(), clazz.getLeaf());

    ctx.getVariables().put("$init", ctx.getPath());
    
    OUTER: for (Diagnostic<?> d : ctx.getInfo().getDiagnostics()) {
        if (start != d.getStartPosition()) continue;
        if (!CODES.contains(d.getCode())) continue;

        FOUND: for (Entry<String, Collection<String>> e : key2Pattern.entrySet()) {
            for (String p : e.getValue()) {
                if (p == null || MatcherUtilities.matches(ctx, ctx.getPath().getParentPath(), p)) {
                    boolean enabled = isEnabled(ctx, e.getKey());

                    if (!enabled) {
                        continue OUTER;
                    } else {
                        break FOUND;
                    } 
                }
            }
        }
        
        // check that the resolved symbol has no overloads, which would
        // take parametrized supertypes of the arguments
        if (checkAmbiguousOverload(ctx.getInfo(), ctx.getPath())) {
            return null;
        }

        return ErrorDescriptionFactory.forTree(ctx, clazz.getParentPath(), d.getMessage(null), new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix());
    }

    return null;
}
 
Example 20
Source File: CreateSubclass.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind({Tree.Kind.CLASS, Tree.Kind.INTERFACE})
public static ErrorDescription check(HintContext context) {
    TreePath tp = context.getPath();
    ClassTree cls = (ClassTree) tp.getLeaf();
    CompilationInfo info = context.getInfo();
    SourcePositions sourcePositions = info.getTrees().getSourcePositions();
    long startPos = sourcePositions.getStartPosition(tp.getCompilationUnit(), cls);
    if (startPos > Integer.MAX_VALUE) {
        return null;
    }
    int[] bodySpan = info.getTreeUtilities().findBodySpan(cls);
    if (bodySpan == null || bodySpan[0] <= startPos) {
        return null;
    }
    int caret = context.getCaretLocation();
    if (startPos < 0 || caret < 0 || caret < startPos || caret >= bodySpan[0]) {
        return null;
    }

    // #222487
    // If there is a compile-time error on the class, then don't offer to
    // create a subclass.
    List<Diagnostic> errors = info.getDiagnostics();
    if (!errors.isEmpty()) {
        for (Diagnostic d : errors) {
            if (d.getKind() != Diagnostic.Kind.ERROR) {
                continue;
            }
            // Check that the error's start position is within the class header
            // Note: d.getEndPosition() is not used because, for example,
            // a "compiler.err.does.not.override.abstract" error ends at
            // the end of the class tree.
            if (startPos <= d.getStartPosition() && d.getStartPosition() <= bodySpan[0]) {
                return null;
            }
        }
    }

    TypeElement typeElement = (TypeElement) info.getTrees().getElement(tp);
    
    if (typeElement == null || typeElement.getModifiers().contains(Modifier.FINAL)) return null;

    Element outer = typeElement.getEnclosingElement();
    // do not offer the hint for non-static inner classes. Permit for classes nested into itnerface - no enclosing instance
    if (outer != null && outer.getKind() != ElementKind.PACKAGE && outer.getKind() != ElementKind.INTERFACE) {
        if (outer.getKind() != ElementKind.CLASS && outer.getKind() != ElementKind.ENUM) {
            return null;
        }
        if (!typeElement.getModifiers().contains(Modifier.STATIC)) {
            return null;
        }
    }

    
    ClassPath cp = info.getClasspathInfo().getClassPath(PathKind.SOURCE);
    FileObject root = cp.findOwnerRoot(info.getFileObject());
    if (root == null) { //File not part of any project
        return null;
    }

    PackageElement packageElement = (PackageElement) info.getElementUtilities().outermostTypeElement(typeElement).getEnclosingElement();
    CreateSubclassFix fix = new CreateSubclassFix(info, root, packageElement.getQualifiedName().toString(), typeElement.getSimpleName().toString() + "Impl", typeElement); //NOI18N
    return ErrorDescriptionFactory.forTree(context, context.getPath(), NbBundle.getMessage(CreateSubclass.class, typeElement.getKind() == ElementKind.CLASS
            ? typeElement.getModifiers().contains(Modifier.ABSTRACT) ? "ERR_ImplementAbstractClass" : "ERR_CreateSubclass" : "ERR_ImplementInterface"), fix); //NOI18N
}