Java Code Examples for com.sun.source.util.JavacTask#getElements()

The following examples show how to use com.sun.source.util.JavacTask#getElements() . 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: CompromiseSATest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testMethodSignatureFromElement () throws Exception {
InputStream in = this.prepareData(TEST_CLASS);
try {
    JavacTask jt = prepareJavac ();
    Elements elements = jt.getElements();
    TypeElement be = elements.getTypeElement(TEST_CLASS);
    ClassFile cf = new ClassFile (in, true);
    String className = cf.getName().getInternalName().replace('/','.');	 //NOI18N
    List<? extends Element> members = be.getEnclosedElements();
    for (Element e : members) {
	if (e.getKind() == ElementKind.METHOD) {
	    String[] msig = ClassFileUtil.createExecutableDescriptor((ExecutableElement) e);
	    assertEquals (className,msig[0]);
	    assertEquals (e.getSimpleName().toString(),msig[1]);
	    Method m = cf.getMethod(e.getSimpleName().toString(),msig[2]);
	    assertNotNull (m);
	}
    }
} finally {
    in.close ();
}
   }
 
Example 2
Source File: CompromiseSATest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testConstructorSignatureFromElement () throws Exception {	
InputStream in = this.prepareData(TEST_CLASS);
try {
    JavacTask jt = prepareJavac ();
    Elements elements = jt.getElements();
    TypeElement be = elements.getTypeElement(TEST_CLASS);
    ClassFile cf = new ClassFile (in, true);
    String className = cf.getName().getInternalName().replace('/','.'); //NOI18N
    List<? extends Element> members = be.getEnclosedElements();
    for (Element e : members) {
	if (e.getKind() == ElementKind.CONSTRUCTOR) {
	    String[] msig = ClassFileUtil.createExecutableDescriptor((ExecutableElement) e);
	    assertEquals (className,msig[0]);
	    assertEquals (e.getSimpleName().toString(),msig[1]);
	    Method m = cf.getMethod (e.getSimpleName().toString(),msig[2]);
	    assertNotNull (m);
	}
    }
} finally {
    in.close ();
}
   }
 
Example 3
Source File: CompromiseSATest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testFieldSignatureFromElement () throws Exception {
InputStream in = this.prepareData(TEST_CLASS);
try {
    JavacTask jt = prepareJavac ();
    Elements elements = jt.getElements();
    TypeElement be = elements.getTypeElement(TEST_CLASS);
    ClassFile cf = new ClassFile (in, true);
    String className = cf.getName().getInternalName().replace('/','.');	    //NOI18N
    List<? extends Element> members = be.getEnclosedElements();
    for (Element e : members) {
	if (e.getKind() == ElementKind.FIELD) {
	    String[] msig = ClassFileUtil.createFieldDescriptor((VariableElement) e);
	    assertEquals (className,msig[0]);
	    assertEquals (e.getSimpleName().toString(),msig[1]);
	    Variable v = cf.getVariable (e.getSimpleName().toString());		    
	    assertNotNull (v);		    
	    assertEquals (v.getDescriptor(), msig[2]);
	}
    }
} finally {
    in.close ();
}
   }
 
Example 4
Source File: TurbineElementsTest.java    From turbine with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  JavacTask task =
      IntegrationTestSupport.runJavacAnalysis(
          SOURCES.sources, ImmutableList.of(), ImmutableList.of());
  task.analyze();
  javacElements = task.getElements();

  BindingResult bound =
      IntegrationTestSupport.turbineAnalysis(
          SOURCES.sources,
          ImmutableList.of(),
          TestClassPaths.TURBINE_BOOTCLASSPATH,
          Optional.empty());
  Env<ClassSymbol, TypeBoundClass> env =
      CompoundEnv.<ClassSymbol, TypeBoundClass>of(bound.classPathEnv())
          .append(new SimpleEnv<>(bound.units()));
  factory = new ModelFactory(env, TurbineElementsTest.class.getClassLoader(), bound.tli());
  TurbineTypes turbineTypes = new TurbineTypes(factory);
  turbineElements = new TurbineElements(factory, turbineTypes);
}
 
Example 5
Source File: DeptectiveTreeVisitor.java    From deptective with Apache License 2.0 5 votes vote down vote up
public DeptectiveTreeVisitor(JavacTask task, Log log, PackageReferenceHandler packageReferenceHandler) {
    elements = task.getElements();
    types = task.getTypes();
    trees = Trees.instance(task);
    this.log = log;
    this.packageReferenceHandler = packageReferenceHandler;
}
 
Example 6
Source File: DeptectiveTreeVisitor.java    From deptective with Apache License 2.0 5 votes vote down vote up
public DeptectiveTreeVisitor(JavacTask task, Log log, PackageReferenceHandler packageReferenceHandler) {
    elements = task.getElements();
    types = task.getTypes();
    trees = Trees.instance(task);
    this.log = log;
    this.packageReferenceHandler = packageReferenceHandler;
}
 
Example 7
Source File: JavadocHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private Pair<JavacTask, TreePath> getSourceElement(JavacTask origin, Element el) throws IOException {
    String handle = elementSignature(el);
    Pair<JavacTask, TreePath> cached = signature2Source.get(handle);

    if (cached != null) {
        return cached.fst != null ? cached : null;
    }

    TypeElement type = topLevelType(el);

    if (type == null)
        return null;

    Elements elements = origin.getElements();
    String binaryName = elements.getBinaryName(type).toString();
    ModuleElement module = elements.getModuleOf(type);
    String moduleName = module == null || module.isUnnamed()
            ? null
            : module.getQualifiedName().toString();
    Pair<JavacTask, CompilationUnitTree> source = findSource(moduleName, binaryName);

    if (source == null)
        return null;

    fillElementCache(source.fst, source.snd);

    cached = signature2Source.get(handle);

    if (cached != null) {
        return cached;
    } else {
        signature2Source.put(handle, Pair.of(null, null));
        return null;
    }
}
 
Example 8
Source File: DependenciesTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void runTest(Stream<Path> inputs) {
    JavacTool tool = JavacTool.create();
    try (JavacFileManager fm = tool.getStandardFileManager(null, null, null)) {
        Path classes = Paths.get(System.getProperty("test.classes"));
        Iterable<? extends JavaFileObject> reconFiles =
                fm.getJavaFileObjectsFromFiles(inputs.sorted().map(p -> p.toFile()) :: iterator);
        List<String> options = Arrays.asList("-classpath", classes.toAbsolutePath().toString());
        JavacTask reconTask = tool.getTask(null, fm, null, options, null, reconFiles);
        Iterable<? extends CompilationUnitTree> reconUnits = reconTask.parse();
        JavacTrees reconTrees = JavacTrees.instance(reconTask);
        SearchAnnotations scanner = new SearchAnnotations(reconTrees,
                                                          reconTask.getElements());
        List<JavaFileObject> validateFiles = new ArrayList<>();

        reconTask.analyze();
        scanner.scan(reconUnits, null);

        for (CompilationUnitTree cut : reconUnits) {
            validateFiles.add(ClearAnnotations.clearAnnotations(reconTrees, cut));
        }

        Context validateContext = new Context();
        TestDependencies.preRegister(validateContext);
        JavacTask validateTask =
                tool.getTask(null, fm, null, options, null, validateFiles, validateContext);

        validateTask.analyze();

        TestDependencies deps = (TestDependencies) Dependencies.instance(validateContext);

        if (!scanner.topLevel2Expected.equals(deps.topLevel2Completing)) {
            throw new IllegalStateException(  "expected=" + scanner.topLevel2Expected +
                                            "; actual=" + deps.topLevel2Completing);
        }
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    } finally {
        inputs.close();
    }
}
 
Example 9
Source File: DocCommentTreeApiTester.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests DocTrees.getDocTreePath(PackageElement p, FileObject fo).
 *
 * @param javaFileName the java anchor file
 * @param pkgFileName the package file name
 * @throws Exception e if something goes awry
 */
public void runDocTreePath(String javaFileName, String pkgFileName) throws Exception  {
    List<File> javaFiles = new ArrayList<>();
    javaFiles.add(new File(testSrc, javaFileName));

    List<File> dirs = new ArrayList<>();
    dirs.add(new File(testSrc));

    try (StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null)) {
        fm.setLocation(javax.tools.StandardLocation.SOURCE_PATH, dirs);
        Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(javaFiles);

        final JavacTask t = javac.getTask(null, fm, null, null, null, fos);
        final DocTrees trees = DocTrees.instance(t);
        final Elements elementUtils = t.getElements();

        Iterable<? extends Element> elements = t.analyze();

        Element klass = elements.iterator().next();
        PackageElement pkg = elementUtils.getPackageOf(klass);

        FileObject htmlFo = fm.getFileForInput(javax.tools.StandardLocation.SOURCE_PATH,
                t.getElements().getPackageOf(klass).getQualifiedName().toString(),
                "package.html");
        System.out.println();
        DocTreePath treePath = trees.getDocTreePath(htmlFo, pkg);
        DocCommentTree dcTree = treePath.getDocComment();

        StringWriter sw = new StringWriter();
        printer.print(dcTree, sw);
        String found = sw.toString();

        String expected = getExpected(htmlFo.openReader(true));
        astcheck(pkgFileName, expected, found);
    }
}
 
Example 10
Source File: TurbineElementsGetAllMembersTest.java    From turbine with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
  JavacTask javacTask =
      IntegrationTestSupport.runJavacAnalysis(
          input.sources, ImmutableList.of(), ImmutableList.of());
  Elements javacElements = javacTask.getElements();
  List<? extends Element> javacMembers =
      javacElements.getAllMembers(requireNonNull(javacElements.getTypeElement("Test")));

  ImmutableList<CompUnit> units =
      input.sources.entrySet().stream()
          .map(e -> new SourceFile(e.getKey(), e.getValue()))
          .map(Parser::parse)
          .collect(toImmutableList());

  Binder.BindingResult bound =
      Binder.bind(
          units,
          ClassPathBinder.bindClasspath(ImmutableList.of()),
          TestClassPaths.TURBINE_BOOTCLASSPATH,
          Optional.empty());

  Env<ClassSymbol, TypeBoundClass> env =
      CompoundEnv.<ClassSymbol, TypeBoundClass>of(bound.classPathEnv())
          .append(new SimpleEnv<>(bound.units()));
  ModelFactory factory = new ModelFactory(env, ClassLoader.getSystemClassLoader(), bound.tli());
  TurbineTypes turbineTypes = new TurbineTypes(factory);
  TurbineElements turbineElements = new TurbineElements(factory, turbineTypes);
  List<? extends Element> turbineMembers =
      turbineElements.getAllMembers(factory.typeElement(new ClassSymbol("Test")));

  assertThat(formatElements(turbineMembers))
      .containsExactlyElementsIn(formatElements(javacMembers));
}
 
Example 11
Source File: JavacEnvironment.java    From j2objc with Apache License 2.0 5 votes vote down vote up
JavacEnvironment(JavacTask task, StandardJavaFileManager fileManager,
    DiagnosticCollector<JavaFileObject> diagnostics) {
  this.task = task;
  this.fileManager = fileManager;
  this.diagnostics = diagnostics;
  elements = task.getElements();
  types = task.getTypes();
  trees = Trees.instance(task);
}