com.sun.tools.javac.api.JavacTaskImpl Java Examples

The following examples show how to use com.sun.tools.javac.api.JavacTaskImpl. 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: BadClassfile.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private static void test(String classname, String expected) throws Exception {
    File classfile = new File(System.getProperty("test.classes", "."), classname + ".class");
    ClassFile cf = ClassFile.read(classfile);

    cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion,
             Target.JDK1_7.majorVersion, cf.constant_pool, cf.access_flags,
            cf.this_class, cf.super_class, cf.interfaces, cf.fields,
            cf.methods, cf.attributes);

    new ClassWriter().write(cf, classfile);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null, Arrays.asList("-classpath", System.getProperty("test.classes", ".")), null, null);

    try {
        Symbol clazz = com.sun.tools.javac.main.JavaCompiler.instance(task.getContext()).resolveIdent(classname);

        clazz.complete();
    } catch (BadClassFile f) {
        JCDiagnostic embeddedDiag = (JCDiagnostic) f.diag.getArgs()[1];
        assertEquals(expected, embeddedDiag.getCode());
        assertEquals(Integer.toString(Target.JDK1_7.majorVersion), embeddedDiag.getArgs()[0]);
        assertEquals(Integer.toString(Target.JDK1_7.minorVersion), embeddedDiag.getArgs()[1]);
    }
}
 
Example #2
Source File: JavacParserTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPositionForEnumModifiers() throws IOException {
    final String theString = "public";
    String code = "package test; " + theString + " enum Test {A;}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ModifiersTree mt = clazz.getModifiers();
    int spos = code.indexOf(theString);
    int epos = spos + theString.length();
    assertEquals("testPositionForEnumModifiers",
            spos, pos.getStartPosition(cut, mt));
    assertEquals("testPositionForEnumModifiers",
            epos, pos.getEndPosition(cut, mt));
}
 
Example #3
Source File: JavacParserTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen2() throws IOException {

     String code = "package t; class Test { " +
             "private static void t(String name) { " +
             "if (name != null) class X {} } }";
     DiagnosticCollector<JavaFileObject> coll =
             new DiagnosticCollector<JavaFileObject>();
     JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
             null, Arrays.asList(new MyFileObject(code)));

     ct.parse();

     List<String> codes = new LinkedList<String>();

     for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
         codes.add(d.getCode());
     }

     assertEquals("testVariableInIfThen2",
             Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
 }
 
Example #4
Source File: JavacParserTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testNewClassWithEnclosing() throws IOException {

    final String theString = "Test.this.new d()";
    String code = "package test; class Test { " +
            "class d {} private void method() { " +
            "Object o = " + theString + "; } }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ExpressionTree est =
            ((VariableTree) ((MethodTree) clazz.getMembers().get(1)).getBody().getStatements().get(0)).getInitializer();

    final int spos = code.indexOf(theString);
    final int epos = spos + theString.length();
    assertEquals("testNewClassWithEnclosing",
            spos, pos.getStartPosition(cut, est));
    assertEquals("testNewClassWithEnclosing",
            epos, pos.getEndPosition(cut, est));
}
 
Example #5
Source File: SourceAnalyzerFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected UsagesVisitor (
        JavacTaskImpl jt,
        CompilationUnitTree cu,
        JavaFileManager manager,
        javax.tools.JavaFileObject sibling,
        Set<? super Pair<String,String>> topLevels) throws MalformedURLException, IllegalArgumentException {
    this(
            jt,
            cu,
            inferBinaryName(manager, sibling),
            sibling.toUri().toURL(),
            false,
            false,
            null,
            null,
            topLevels);
}
 
Example #6
Source File: JavacParser.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static JavacTaskImpl createJavacTask (
        @NonNull final ClasspathInfo cpInfo,
        @NullAllowed final DiagnosticListener<? super JavaFileObject> diagnosticListener,
        @NullAllowed final String sourceLevel,
        @NullAllowed final SourceLevelQuery.Profile sourceProfile,
        @NullAllowed FQN2Files fqn2Files,
        @NullAllowed final CancelService cancelService,
        @NullAllowed final APTUtils aptUtils,
        @NullAllowed final CompilerOptionsQuery.Result compilerOptions,
        @NonNull Iterable<? extends JavaFileObject> files) {
    return createJavacTask(
            cpInfo,
            diagnosticListener,
            sourceLevel,
            sourceProfile,
            EnumSet.of(ConfigFlags.BACKGROUND_COMPILATION, ConfigFlags.MULTI_SOURCE),
            fqn2Files,
            cancelService,
            aptUtils,
            compilerOptions,
            Collections.emptySet(),
            files);
}
 
Example #7
Source File: JavacParserTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen2() throws IOException {

     String code = "package t; class Test { " +
             "private static void t(String name) { " +
             "if (name != null) class X {} } }";
     DiagnosticCollector<JavaFileObject> coll =
             new DiagnosticCollector<JavaFileObject>();
     JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
             null, Arrays.asList(new MyFileObject(code)));

     ct.parse();

     List<String> codes = new LinkedList<String>();

     for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
         codes.add(d.getCode());
     }

     assertEquals("testVariableInIfThen2",
             Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
 }
 
Example #8
Source File: JavacParserTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testStartPositionForMethodWithoutModifiers() throws IOException {

    String code = "package t; class Test { <T> void t() {} }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    MethodTree mt = (MethodTree) clazz.getMembers().get(0);
    Trees t = Trees.instance(ct);
    int start = (int) t.getSourcePositions().getStartPosition(cut, mt);
    int end = (int) t.getSourcePositions().getEndPosition(cut, mt);

    assertEquals("testStartPositionForMethodWithoutModifiers",
            "<T> void t() {}", code.substring(start, end));
}
 
Example #9
Source File: TestLambdaBytecode.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    int id = checkCount.incrementAndGet();
    JavaSource source = new JavaSource(id);
    JavacTaskImpl ct = (JavacTaskImpl)comp.getTask(null, fm.get(), dc,
            null, null, Arrays.asList(source));
    try {
        ct.generate();
    } catch (Throwable t) {
        t.printStackTrace();
        throw new AssertionError(
                String.format("Error thrown when compiling following code\n%s",
                source.source));
    }
    if (dc.diagFound) {
        boolean errorExpected = !mk1.isOK() || !mk2.isOK();
        errorExpected |= mk1.isStatic() && !mk2.isStatic();

        if (!errorExpected) {
            throw new AssertionError(
                    String.format("Diags found when compiling following code\n%s\n\n%s",
                    source.source, dc.printDiags()));
        }
        return;
    }
    verifyBytecode(id, source);
}
 
Example #10
Source File: JavacParserTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPositionForEnumModifiers() throws IOException {
    final String theString = "public";
    String code = "package test; " + theString + " enum Test {A;}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ModifiersTree mt = clazz.getModifiers();
    int spos = code.indexOf(theString);
    int epos = spos + theString.length();
    assertEquals("testPositionForEnumModifiers",
            spos, pos.getStartPosition(cut, mt));
    assertEquals("testPositionForEnumModifiers",
            epos, pos.getEndPosition(cut, mt));
}
 
Example #11
Source File: BadClassfile.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void test(String classname, String expected) throws Exception {
    File classfile = new File(System.getProperty("test.classes", "."), classname + ".class");
    ClassFile cf = ClassFile.read(classfile);

    cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion,
             Target.JDK1_7.majorVersion, cf.constant_pool, cf.access_flags,
            cf.this_class, cf.super_class, cf.interfaces, cf.fields,
            cf.methods, cf.attributes);

    new ClassWriter().write(cf, classfile);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null, Arrays.asList("-classpath", System.getProperty("test.classes", ".")), null, null);

    try {
        Symbol clazz = com.sun.tools.javac.main.JavaCompiler.instance(task.getContext()).resolveIdent(classname);

        clazz.complete();
    } catch (BadClassFile f) {
        JCDiagnostic embeddedDiag = (JCDiagnostic) f.diag.getArgs()[1];
        assertEquals(expected, embeddedDiag.getCode());
        assertEquals(Integer.toString(Target.JDK1_7.majorVersion), embeddedDiag.getArgs()[0]);
        assertEquals(Integer.toString(Target.JDK1_7.minorVersion), embeddedDiag.getArgs()[1]);
    }
}
 
Example #12
Source File: JavaSourceTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testMultipleFilesSameJavac() throws Exception {
    final FileObject testFile1 = createTestFile("Test1");
    final FileObject testFile2 = createTestFile("Test2");
    final ClassPath bootPath = createBootPath();
    final ClassPath compilePath = createCompilePath();
    final ClassPath srcPath = createSourcePath();
    final JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, srcPath), testFile1, testFile2);
    js.runUserActionTask(new Task<CompilationController>() {
        private JavacTaskImpl seenTask;

        @Override
        public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(Phase.RESOLVED);
            
            JavacTaskImpl currentTask = parameter.impl.getJavacTask();
            
            if (seenTask == null) {
                seenTask= currentTask;
            } else if (seenTask != currentTask) {
               fail();
            }
        }
    }, true);
}
 
Example #13
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen1() throws IOException {

    String code = "package t; class Test { " +
            "private static void t(String name) { " +
            "if (name != null) String nn = name.trim(); } }";

    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen1",
            Arrays.<String>asList("compiler.err.variable.not.allowed"),
            codes);
}
 
Example #14
Source File: JavacParserTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen2() throws IOException {

     String code = "package t; class Test { " +
             "private static void t(String name) { " +
             "if (name != null) class X {} } }";
     DiagnosticCollector<JavaFileObject> coll =
             new DiagnosticCollector<JavaFileObject>();
     JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
             null, Arrays.asList(new MyFileObject(code)));

     ct.parse();

     List<String> codes = new LinkedList<String>();

     for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
         codes.add(d.getCode());
     }

     assertEquals("testVariableInIfThen2",
             Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
 }
 
Example #15
Source File: JavacParserTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen3() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) abstract class F {} }}";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen3",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
 
Example #16
Source File: BadConstantValue.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static BadClassFile loadBadClass(String className) {
    // load the class, and save the thrown BadClassFile exception
    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null,
            Arrays.asList("-classpath", classesdir.getPath()), null, null);
    Symtab syms = Symtab.instance(task.getContext());
    task.ensureEntered();
    BadClassFile badClassFile;
    try {
        com.sun.tools.javac.main.JavaCompiler.instance(task.getContext())
                .resolveIdent(syms.unnamedModule, className).complete();
    } catch (BadClassFile e) {
        return e;
    }
    return null;
}
 
Example #17
Source File: BadClassfile.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static void test(String classname, String expected) throws Exception {
    File classfile = new File(System.getProperty("test.classes", "."), classname + ".class");
    ClassFile cf = ClassFile.read(classfile);

    cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion,
             Target.JDK1_7.majorVersion, cf.constant_pool, cf.access_flags,
            cf.this_class, cf.super_class, cf.interfaces, cf.fields,
            cf.methods, cf.attributes);

    new ClassWriter().write(cf, classfile);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null, Arrays.asList("-classpath", System.getProperty("test.classes", ".")), null, null);

    try {
        Symbol clazz = com.sun.tools.javac.main.JavaCompiler.instance(task.getContext()).resolveIdent(classname);

        clazz.complete();
    } catch (BadClassFile f) {
        JCDiagnostic embeddedDiag = (JCDiagnostic) f.diag.getArgs()[1];
        assertEquals(expected, embeddedDiag.getCode());
        assertEquals(Integer.toString(Target.JDK1_7.majorVersion), embeddedDiag.getArgs()[0]);
        assertEquals(Integer.toString(Target.JDK1_7.minorVersion), embeddedDiag.getArgs()[1]);
    }
}
 
Example #18
Source File: TestInvokeDynamic.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    int id = checkCount.incrementAndGet();
    JavaSource source = new JavaSource(id);
    JavacTaskImpl ct = (JavacTaskImpl)comp.getTask(null, fm.get(), dc,
            Arrays.asList("-g"), null, Arrays.asList(source));
    Context context = ct.getContext();
    Symtab syms = Symtab.instance(context);
    Names names = Names.instance(context);
    Types types = Types.instance(context);
    ct.addTaskListener(new Indifier(syms, names, types));
    try {
        ct.generate();
    } catch (Throwable t) {
        t.printStackTrace();
        throw new AssertionError(
                String.format("Error thrown when compiling following code\n%s",
                source.source));
    }
    if (dc.diagFound) {
        throw new AssertionError(
                String.format("Diags found when compiling following code\n%s\n\n%s",
                source.source, dc.printDiags()));
    }
    verifyBytecode(id);
}
 
Example #19
Source File: JavacParserTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testNewClassWithEnclosing() throws IOException {

    final String theString = "Test.this.new d()";
    String code = "package test; class Test { " +
            "class d {} private void method() { " +
            "Object o = " + theString + "; } }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ExpressionTree est =
            ((VariableTree) ((MethodTree) clazz.getMembers().get(1)).getBody().getStatements().get(0)).getInitializer();

    final int spos = code.indexOf(theString);
    final int epos = spos + theString.length();
    assertEquals("testNewClassWithEnclosing",
            spos, pos.getStartPosition(cut, est));
    assertEquals("testNewClassWithEnclosing",
            epos, pos.getEndPosition(cut, est));
}
 
Example #20
Source File: ElementUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static TypeElement getTypeElementByBinaryName(JavacTask task, ModuleElement mod, String name) {
    Context ctx = ((JavacTaskImpl) task).getContext();
    Names names = Names.instance(ctx);
    Symtab syms = Symtab.instance(ctx);
    Check chk = Check.instance(ctx);
    final Name wrappedName = names.fromString(name);
    ClassSymbol clazz = chk.getCompiled((ModuleSymbol) mod, wrappedName);
    if (clazz != null) {
        return clazz;
    }
    clazz = syms.enterClass((ModuleSymbol) mod, wrappedName);
    
    try {
        clazz.complete();
        
        if (clazz.kind == Kind.TYP &&
            clazz.flatName() == wrappedName) {
            return clazz;
        }
    } catch (CompletionFailure cf) {
    }

    return null;
}
 
Example #21
Source File: JavacParserTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testNewClassWithEnclosing() throws IOException {

    final String theString = "Test.this.new d()";
    String code = "package test; class Test { " +
            "class d {} private void method() { " +
            "Object o = " + theString + "; } }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ExpressionTree est =
            ((VariableTree) ((MethodTree) clazz.getMembers().get(1)).getBody().getStatements().get(0)).getInitializer();

    final int spos = code.indexOf(theString);
    final int epos = spos + theString.length();
    assertEquals("testNewClassWithEnclosing",
            spos, pos.getStartPosition(cut, est));
    assertEquals("testNewClassWithEnclosing",
            epos, pos.getEndPosition(cut, est));
}
 
Example #22
Source File: JavacParserTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen2() throws IOException {

     String code = "package t; class Test { " +
             "private static void t(String name) { " +
             "if (name != null) class X {} } }";
     DiagnosticCollector<JavaFileObject> coll =
             new DiagnosticCollector<JavaFileObject>();
     JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
             null, Arrays.asList(new MyFileObject(code)));

     ct.parse();

     List<String> codes = new LinkedList<String>();

     for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
         codes.add(d.getCode());
     }

     assertEquals("testVariableInIfThen2",
             Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
 }
 
Example #23
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen2() throws IOException {

     String code = "package t; class Test { " +
             "private static void t(String name) { " +
             "if (name != null) class X {} } }";
     DiagnosticCollector<JavaFileObject> coll =
             new DiagnosticCollector<JavaFileObject>();
     JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
             null, Arrays.asList(new MyFileObject(code)));

     ct.parse();

     List<String> codes = new LinkedList<String>();

     for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
         codes.add(d.getCode());
     }

     assertEquals("testVariableInIfThen2",
             Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
 }
 
Example #24
Source File: JavacParserTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testStartPositionForMethodWithoutModifiers() throws IOException {

    String code = "package t; class Test { <T> void t() {} }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    MethodTree mt = (MethodTree) clazz.getMembers().get(0);
    Trees t = Trees.instance(ct);
    int start = (int) t.getSourcePositions().getStartPosition(cut, mt);
    int end = (int) t.getSourcePositions().getEndPosition(cut, mt);

    assertEquals("testStartPositionForMethodWithoutModifiers",
            "<T> void t() {}", code.substring(start, end));
}
 
Example #25
Source File: TestJavacTask.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static void basicTest(String... args) throws IOException {
    String srcdir = System.getProperty("test.src");
    File file = new File(srcdir, args[0]);
    JavacTaskImpl task = getTask(file);
    for (TypeElement clazz : task.enter(task.parse()))
        System.out.println(clazz.getSimpleName());
}
 
Example #26
Source File: JavacParserTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
void testStartPositionEnumConstantInit() throws IOException {

        String code = "package t; enum Test { AAA; }";

        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
                null, Arrays.asList(new MyFileObject(code)));
        CompilationUnitTree cut = ct.parse().iterator().next();
        ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
        VariableTree enumAAA = (VariableTree) clazz.getMembers().get(0);
        Trees t = Trees.instance(ct);
        int start = (int) t.getSourcePositions().getStartPosition(cut,
                enumAAA.getInitializer());

        assertEquals("testStartPositionEnumConstantInit", -1, start);
    }
 
Example #27
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 #28
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void testPositionBrokenSource126732b() throws IOException {
    String[] commands = new String[]{
        "break",
        "break A",
        "continue ",
        "continue A",};

    for (String command : commands) {

        String code = "package test;\n"
                + "public class Test {\n"
                + "    public static void test() {\n"
                + "        while (true) {\n"
                + "            " + command + " {\n"
                + "                new Runnable() {\n"
                + "        };\n"
                + "        }\n"
                + "    }\n"
                + "}";

        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null,
                null, null, Arrays.asList(new MyFileObject(code)));
        CompilationUnitTree cut = ct.parse().iterator().next();

        ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
        MethodTree method = (MethodTree) clazz.getMembers().get(0);
        List<? extends StatementTree> statements =
                ((BlockTree) ((WhileLoopTree) method.getBody().getStatements().get(0)).getStatement()).getStatements();

        StatementTree ret = statements.get(0);
        StatementTree block = statements.get(1);

        Trees t = Trees.instance(ct);
        int len = code.indexOf(command + " {") + (command + " ").length();
        assertEquals(command, len,
                t.getSourcePositions().getEndPosition(cut, ret));
        assertEquals(command, len,
                t.getSourcePositions().getStartPosition(cut, block));
    }
}
 
Example #29
Source File: ModuleOraculumTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void assertPatchModules(JavacTaskImpl impl, String... expectedPatches) throws IOException {
    JavaFileManager fm = impl.getContext().get(JavaFileManager.class);
    for (String expected : expectedPatches) {
        assertNotNull(fm.getLocationForModule(StandardLocation.PATCH_MODULE_PATH, expected));
    }
    Set<String> actualNames = new HashSet<>();
    for (Set<Location> locations : fm.listLocationsForModules(StandardLocation.PATCH_MODULE_PATH)) {
        actualNames.add(fm.inferModuleName(locations.iterator().next()));
    }
    assertEquals(new HashSet<>(Arrays.asList(expectedPatches)), actualNames);
}
 
Example #30
Source File: MakeQualIdent.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {
    JavacTool tool = JavacTool.create();
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, null);
    Context ctx = ((JavacTaskImpl)task).getContext();
    TreeMaker treeMaker = TreeMaker.instance(ctx);
    Symtab syms = Symtab.instance(ctx);

    String stringTree = printTree(treeMaker.QualIdent(syms.stringType.tsym));

    if (!"java.lang.String".equals(stringTree)) {
        throw new IllegalStateException(stringTree);
    }
}