@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; }
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"); }
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); }
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"); }
private InMemoryClassJavaFileObject makeInMemoryClassJavaFileObject( SimpleJavaFileObject f ) { String fqn = f.toUri().getPath().substring( 1 ).replace( '/', '.' ); int iDot = fqn.lastIndexOf( '.' ); fqn = fqn.substring( 0, iDot ); InMemoryClassJavaFileObject memF = new InMemoryClassJavaFileObject( fqn, f.getKind() ); try( OutputStream os = memF.openOutputStream(); InputStream in = f.openInputStream() ) { os.write( StreamUtil.getContent( in ) ); } catch( IOException e ) { throw new RuntimeException( e ); } return memF; }
@BeforeClass public static void compileDependencyClass() throws IOException, ClassNotFoundException { JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); Assume.assumeNotNull(javaCompiler); classes = temporaryFolder.newFolder("classes");; StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ROOT, UTF_8); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, ImmutableList.of(classes)); SimpleJavaFileObject compilationUnit = new SimpleJavaFileObject(URI.create("FooTest.java"), Kind.SOURCE) { String fooTestSource = Resources.toString(Resources.getResource("com/dremio/exec/compile/FooTest.java"), UTF_8); @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return fooTestSource; } }; CompilationTask task = javaCompiler.getTask(null, fileManager, null, Collections.<String>emptyList(), null, ImmutableList.of(compilationUnit)); assertTrue(task.call()); }
@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); } }
public JavaFileObject toJavaFileObject() { URI uri = URI.create((packageName.isEmpty() ? typeSpec.name : packageName.replace('.', '/') + '/' + typeSpec.name) + Kind.SOURCE.extension); return new SimpleJavaFileObject(uri, Kind.SOURCE) { private final long lastModified = System.currentTimeMillis(); @Override public String getCharContent(boolean ignoreEncodingErrors) { return JavaFile.this.toString(); } @Override public InputStream openInputStream() throws IOException { return new ByteArrayInputStream(getCharContent(true).getBytes()); } @Override public long getLastModified() { return lastModified; } }; }
public JavaFileObject toJavaFileObject() { URI uri = URI.create((packageName.isEmpty() ? typeSpec.name : packageName.replace('.', '/') + '/' + typeSpec.name) + Kind.SOURCE.extension); return new SimpleJavaFileObject(uri, Kind.SOURCE) { private final long lastModified = System.currentTimeMillis(); @Override public String getCharContent(boolean ignoreEncodingErrors) { return JavaFile.this.toString(); } @Override public InputStream openInputStream() throws IOException { return new ByteArrayInputStream(getCharContent(true).getBytes(UTF_8)); } @Override public long getLastModified() { return lastModified; } }; }
@Override public JavaFileObject getJavaFileForOutput( Location location, final String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException { return new SimpleJavaFileObject(EMPTY_URI, kind) { @Override public OutputStream openOutputStream() throws IOException { ByteArrayOutputStream outputStream = byteCodeForClasses.get(className); if (outputStream != null) { throw new IllegalStateException("Cannot write more than once"); } // Reasonable size for a simple .class. outputStream = new ByteArrayOutputStream(256); byteCodeForClasses.put(className, outputStream); return outputStream; } }; }
private void assertCompileSucceeds(final String uri, final String content) throws Exception { JavaCompiler javac = BazelJavaCompiler.newInstance(); JavaFileObject source = new SimpleJavaFileObject(URI.create(uri), JavaFileObject.Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return content; } }; StandardJavaFileManager fileManager = javac.getStandardFileManager(null, null, null); // setting the output path by passing a flag to getTask is not reliable fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(getTmpDir())); DiagnosticCollector<JavaFileObject> messages = new DiagnosticCollector<>(); JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, messages, null, null, Collections.singletonList(source)); assertThat(task.call()).isTrue(); assertThat(messages.getDiagnostics()).isEmpty(); }
public void test1() { Context context = new Context(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); Options.instance(context).put("allowStringFolding", "false"); JCTree.JCCompilationUnit unit; JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); try { fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of()); } catch (IOException e) { // impossible throw new IOError(e); } 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); ParserFactory parserFactory = ParserFactory.instance(context); Parser parser = parserFactory.newParser( src, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true); unit = parser.parseCompilationUnit(); unit.sourcefile = source; }
public void test4() { Context context = new Context(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); Options.instance(context).put("allowStringFolding", "false"); JCTree.JCCompilationUnit unit; JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); try { fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of()); } catch (IOException e) { // impossible throw new IOError(e); } 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); ParserFactory parserFactory = ParserFactory.instance(context); Parser parser = parserFactory.newParser( src, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true); unit = parser.parseCompilationUnit(); unit.sourcefile = source; }
public void test3() { Context context = new Context(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); Options.instance(context).put("allowStringFolding", "false"); JCTree.JCCompilationUnit unit; JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); try { fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of()); } catch (IOException e) { // impossible throw new IOError(e); } 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); ParserFactory parserFactory = ParserFactory.instance(context); Parser parser = parserFactory.newParser( src, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true); unit = parser.parseCompilationUnit(); unit.sourcefile = source; }