javax.tools.SimpleJavaFileObject Java Examples

The following examples show how to use javax.tools.SimpleJavaFileObject. 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: TestNonSerializableLambdaNameStability.java    From TencentKona-8 with GNU General Public License v2.0 7 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
    try {
        return new SimpleJavaFileObject(new URI("mem://" + className.replace('.', '/') + kind.extension), kind) {
            @Override public OutputStream openOutputStream() throws IOException {
                return new ByteArrayOutputStream() {
                    @Override public void close() throws IOException {
                        super.close();
                        name2Content.put(className, toByteArray());
                    }
                };
            }
        };
    } catch (URISyntaxException ex) {
        throw new AssertionError(ex);
    }
}
 
Example #2
Source File: T6733837.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example #3
Source File: JavaParser.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@Nullable
public JCTree.JCCompilationUnit parse(final String src) {
    if (!canParse) return null;
    long time = System.currentTimeMillis();

    SimpleJavaFileObject source = new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return src;
        }
    };
    Log.instance(context).useSource(source);
    Parser parser = parserFactory.newParser(src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    JCTree.JCCompilationUnit unit;
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
    android.util.Log.d(TAG, "parse: time " + (System.currentTimeMillis() - time) + " ms");
    return unit;
}
 
Example #4
Source File: JavaLexerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void run() throws Exception {
    Context ctx = new Context();
    Log log = Log.instance(ctx);
    String input = "0bL 0b20L 0xL ";
    log.useSource(new SimpleJavaFileObject(new URI("mem://Test.java"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return input;
        }
    });
    char[] inputArr = input.toCharArray();
    JavaTokenizer tokenizer = new JavaTokenizer(ScannerFactory.instance(ctx), inputArr, inputArr.length) {
    };

    assertKind(input, tokenizer, TokenKind.LONGLITERAL, "0bL");
    assertKind(input, tokenizer, TokenKind.LONGLITERAL, "0b20L");
    assertKind(input, tokenizer, TokenKind.LONGLITERAL, "0xL");
}
 
Example #5
Source File: T6852595.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #6
Source File: TestNonSerializableLambdaNameStability.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
    try {
        return new SimpleJavaFileObject(new URI("mem://" + className.replace('.', '/') + kind.extension), kind) {
            @Override public OutputStream openOutputStream() throws IOException {
                return new ByteArrayOutputStream() {
                    @Override public void close() throws IOException {
                        super.close();
                        name2Content.put(className, toByteArray());
                    }
                };
            }
        };
    } catch (URISyntaxException ex) {
        throw new AssertionError(ex);
    }
}
 
Example #7
Source File: BootClassPathUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, javax.tools.FileObject sibling) throws IOException {
    if (location == StandardLocation.CLASS_OUTPUT) {
        String relPath = className.replace('.', '/') + ".class";
        try {
            return new SimpleJavaFileObject(new URI("mem://" + relPath), kind) {
                @Override
                public OutputStream openOutputStream() throws IOException {
                    return new ByteArrayOutputStream() {
                        @Override
                        public void close() throws IOException {
                            super.close();
                            FileObject target = FileUtil.createData(sink, relPath);
                            try (OutputStream out = target.getOutputStream()) {
                                out.write(toByteArray());
                            }
                        }
                    };
                }
            };
        } catch (URISyntaxException ex) {
            throw new IOException(ex);
        }
    }
    return super.getJavaFileForOutput(location, className, kind, sibling);
}
 
Example #8
Source File: T6733837.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example #9
Source File: T6852595.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #10
Source File: T6733837.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example #11
Source File: T6852595.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #12
Source File: T6852595.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #13
Source File: T6733837.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example #14
Source File: T6852595.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #15
Source File: T6733837.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void exec() {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "\tclass ErroneousWithTab";
        }
    };
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    task = tool.getTask(sw, fm, null, null, null, files);
    try {
        ((JavacTask)task).analyze();
    }
    catch (Throwable t) {
        throw new Error("Compiler threw an exception");
    }
    System.err.println(sw.toString());
    if (!sw.toString().contains("/Test.java"))
        throw new Error("Bad source name in diagnostic");
}
 
Example #16
Source File: BootClassPathUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, javax.tools.FileObject sibling) throws IOException {
    if (location == StandardLocation.CLASS_OUTPUT) {
        String relPath = className.replace('.', '/') + ".class";
        try {
            return new SimpleJavaFileObject(new URI("mem://" + relPath), kind) {
                @Override
                public OutputStream openOutputStream() throws IOException {
                    return new ByteArrayOutputStream() {
                        @Override
                        public void close() throws IOException {
                            super.close();
                            FileObject target = FileUtil.createData(sink, relPath);
                            try (OutputStream out = target.getOutputStream()) {
                                out.write(toByteArray());
                            }
                        }
                    };
                }
            };
        } catch (URISyntaxException ex) {
            throw new IOException(ex);
        }
    }
    return super.getJavaFileForOutput(location, className, kind, sibling);
}
 
Example #17
Source File: TestNonSerializableLambdaNameStability.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
    try {
        return new SimpleJavaFileObject(new URI("mem://" + className.replace('.', '/') + kind.extension), kind) {
            @Override public OutputStream openOutputStream() throws IOException {
                return new ByteArrayOutputStream() {
                    @Override public void close() throws IOException {
                        super.close();
                        name2Content.put(className, toByteArray());
                    }
                };
            }
        };
    } catch (URISyntaxException ex) {
        throw new AssertionError(ex);
    }
}
 
Example #18
Source File: APITest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected JavaFileObject createSimpleJavaFileObject(final String binaryName, final String content) {
    return new SimpleJavaFileObject(
            URI.create("myfo:///" + binaryName + ".java"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncoding) {
            return content;
        }
    };
}
 
Example #19
Source File: TestCircularClassfile.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
SimpleJavaFileObject getSource() {
    return new SimpleJavaFileObject(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return sourceStr;
        }
    };
}
 
Example #20
Source File: T6402077.java    From openjdk-jdk8u-backup 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
            //      0123456789012345678901234
            return "class Test { Test() { } }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    JavacTask task = (JavacTask)javac.getTask(null, null, null, null, null,
                                              compilationUnits);
    Trees trees = Trees.instance(task);
    CompilationUnitTree toplevel = task.parse().iterator().next();
    Tree tree = ((ClassTree)toplevel.getTypeDecls().get(0)).getMembers().get(0);
    long pos = trees.getSourcePositions().getStartPosition(toplevel, tree);
    if (pos != 13)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree);
    if (pos != 23)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree, pos));
}
 
Example #21
Source File: TestSearchPaths.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
JavaFileObject getSource(final String source) {
    return new SimpleJavaFileObject(getURIFromSource(source), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return source;
        }
    };
}
 
Example #22
Source File: JavacParserTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testMissingSupertype() throws Exception {
    FileObject file = createFile("test/Test.java", "package test; class Test extends Super {}");

    createFile("test/Super.java", "package test; class Super extends Missing {}");

    List<String> missingCompileOptions = Arrays.asList("-source", "8", "-d", FileUtil.toFile(cp).getAbsolutePath());
    SimpleJavaFileObject missingFO = new SimpleJavaFileObject(URI.create("mem://Missing.java"), Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return "package test; public class Missing {}";
        }
        @Override
        public boolean isNameCompatible(String simpleName, Kind kind) {
            return "Missing".equals(simpleName);
        }
    };

    assertTrue(ToolProvider.getSystemJavaCompiler().getTask(null, null, null, missingCompileOptions, null, Arrays.asList(missingFO)).call());

    FileObject testClass = cp.getFileObject("test/Missing.class");

    assertNotNull(testClass);

    JavaSource js = JavaSource.forFileObject(file);

    SourceUtilsTestUtil.compileRecursively(sourceRoot);

    testClass.delete();

    js.runUserActionTask(new Task<CompilationController>() {
        public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(Phase.RESOLVED);
        }
    }, true);
}
 
Example #23
Source File: T6404194.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
            //      01234567890123456 7890 123456789012345
            return "@SuppressWarning(\"foo\") @Deprecated class Test { Test() { } }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    JavacTask task = (JavacTask)javac.getTask(null, null, null, null, null, compilationUnits);
    Trees trees = Trees.instance(task);
    CompilationUnitTree toplevel = task.parse().iterator().next();
    ClassTree classTree = (ClassTree)toplevel.getTypeDecls().get(0);
    List<? extends Tree> annotations = classTree.getModifiers().getAnnotations();
    Tree tree1 = annotations.get(0);
    Tree tree2 = annotations.get(1);
    long pos = trees.getSourcePositions().getStartPosition(toplevel, tree1);
    if (pos != 0)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree1, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree1);
    if (pos != 23)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree1, pos));
    pos = trees.getSourcePositions().getStartPosition(toplevel, tree2);
    if (pos != 24)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree2, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree2);
    if (pos != 35)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree2, pos));
}
 
Example #24
Source File: RunTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
JavaFileObject createFile(String name, final String body) {
    return new SimpleJavaFileObject(URI.create(name), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return body;
        }
    };
}
 
Example #25
Source File: CompletionFailure.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
SimpleJavaFileObject asJFO(java.io.File dir) {
    return new SimpleJavaFileObject(new File(dir, filename).toURI(), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return contents;
        }
    };
}
 
Example #26
Source File: T6608214.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 {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create(""),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class Test<S> { <T extends S & Runnable> void test(){}}";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    String bootPath = System.getProperty("sun.boot.class.path");
    List<String> opts = Arrays.asList("-bootclasspath",  bootPath, "-Xjcov");
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null,opts,null,files);
    ct.analyze();
}
 
Example #27
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 #28
Source File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #29
Source File: TestCircularClassfile.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
SimpleJavaFileObject getSource() {
    return new SimpleJavaFileObject(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return "class Test { public static void main(String[] args) { #M } }"
                    .replace("#M", mainMethod);
        }
    };
}
 
Example #30
Source File: TestCircularClassfile.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
SimpleJavaFileObject getSource() {
    return new SimpleJavaFileObject(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return sourceStr;
        }
    };
}