/** * * @return list of top classes, or an empty list of none were found */ static List<ClassTree> findTopClasses( CompilationUnitTree compilationUnit, TreeUtilities treeUtils) { List<? extends Tree> typeDecls = compilationUnit.getTypeDecls(); if ((typeDecls == null) || typeDecls.isEmpty()) { return Collections.<ClassTree>emptyList(); } List<ClassTree> result = new ArrayList<ClassTree>(typeDecls.size()); for (Tree typeDecl : typeDecls) { if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) { ClassTree clsTree = (ClassTree) typeDecl; if (isTestable(clsTree, treeUtils)) { result.add(clsTree); } } } return result; }
public void run(WorkingCopy workingCopy) throws Exception { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); for (Tree typeDeclaration : cut.getTypeDecls()){ if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDeclaration.getKind())){ ClassTree clazz = (ClassTree) typeDeclaration; EntityManagerGenerationStrategySupport strategy = (EntityManagerGenerationStrategySupport) getStrategy(workingCopy, make, clazz, new GenerationOptions()); doAsserts(strategy); } else { fail("No class found"); // should not happen } } }
@Override public void run(WorkingCopy compiler) throws IOException { compiler.toPhase(JavaSource.Phase.RESOLVED); CompilationUnitTree cu = compiler.getCompilationUnit(); if (cu == null) { ErrorManager.getDefault().log(ErrorManager.ERROR, "compiler.getCompilationUnit() is null " + compiler); // NOI18N return; } FileObject file = compiler.getFileObject(); FileObject folder = file.getParent(); final String newName; if(folder.getFileObject(oldName, file.getExt()) != null) { newName = file.getName(); } else { newName = oldName; } CopyTransformer findVisitor = new CopyTransformer(compiler, oldName, newName, insertImport, oldPackage); findVisitor.scan(compiler.getCompilationUnit(), null); }
/** * * @return list of {@code Element}s representing top classes, * or an empty list of none were found */ private static List<TypeElement> findTopClassElems( CompilationInfo compInfo, CompilationUnitTree compilationUnit, Filter filter) { List<? extends Tree> typeDecls = compilationUnit.getTypeDecls(); if ((typeDecls == null) || typeDecls.isEmpty()) { return Collections.<TypeElement>emptyList(); } List<TypeElement> result = new ArrayList<TypeElement>(typeDecls.size()); Trees trees = compInfo.getTrees(); for (Tree typeDecl : typeDecls) { if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) { Element element = trees.getElement( new TreePath(new TreePath(compilationUnit), typeDecl)); TypeElement typeElement = (TypeElement) element; if (filter.passes(typeElement, compInfo)) { result.add(typeElement); } } } return result; }
public void testMoveFirst() throws IOException, FileStateInvalidException { JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); List<ImportTree> imports = new ArrayList<ImportTree>(cut.getImports()); ImportTree oneImport = imports.remove(0); imports.add(3, oneImport); CompilationUnitTree unit = make.CompilationUnit( cut.getPackageName(), imports, cut.getTypeDecls(), cut.getSourceFile() ); workingCopy.rewrite(cut, unit); } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertFiles("testMoveFirst_ImportFormatTest.pass"); }
@Override protected void performRewrite(TransformationContext ctx) { WorkingCopy copy = ctx.getWorkingCopy(); TreePath tp = ctx.getPath(); CompilationUnitTree cut = copy.getCompilationUnit(); TreeMaker make = copy.getTreeMaker(); CompilationUnitTree newCut = cut; for (TreePathHandle tph : tphList) { TreePath path = tph.resolve(copy); if ( path != null && path.getLeaf() instanceof ImportTree) { newCut = make.removeCompUnitImport(newCut, (ImportTree)path.getLeaf()); } } copy.rewrite(cut, newCut); }
/** * Read a file. * @param file the file to be read * @return the tree for the content of the file * @throws IOException if any IO errors occur * @throws TreePosTest.ParseException if any errors occur while parsing the file */ JCCompilationUnit read(File file) throws IOException, ParseException { JavacTool tool = JavacTool.create(); r.errors = 0; Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file); JavacTask task = tool.getTask(pw, fm, r, List.of("-proc:none"), null, files); Iterable<? extends CompilationUnitTree> trees = task.parse(); pw.flush(); if (r.errors > 0) throw new ParseException(sw.toString()); Iterator<? extends CompilationUnitTree> iter = trees.iterator(); if (!iter.hasNext()) throw new Error("no trees found"); JCCompilationUnit t = (JCCompilationUnit) iter.next(); if (iter.hasNext()) throw new Error("too many trees found"); return t; }
public void testRemoveInnerImport() throws IOException, FileStateInvalidException { JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); List<ImportTree> imports = new ArrayList<ImportTree>(cut.getImports()); imports.remove(1); CompilationUnitTree unit = make.CompilationUnit( cut.getPackageName(), imports, cut.getTypeDecls(), cut.getSourceFile() ); workingCopy.rewrite(cut, unit); } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertFiles("testRemoveInnerImport_ImportFormatTest.pass"); }
/** * Returns tree which was reparsed by an incremental reparse. * When the source file wasn't parsed yet or the parse was a full parse * this method returns null. * <p class="nonnormative"> * Currently the leaf tree is a MethodTree but this may change in the future. * Client of this method is responsible to check the corresponding TreeKind * to find out if it may perform on the changed subtree or it needs to * reprocess the whole tree. * </p> * @return {@link TreePath} or null * @since 0.31 */ public @CheckForNull @CheckReturnValue TreePath getChangedTree () { checkConfinement(); if (JavaSource.Phase.PARSED.compareTo (impl.getPhase())>0) { return null; } final Pair<DocPositionRegion,MethodTree> changedTree = impl.getChangedTree(); if (changedTree == null) { return null; } final CompilationUnitTree cu = impl.getCompilationUnit(); if (cu == null) { return null; } return TreePath.getPath(cu, changedTree.second()); }
/** Creates new Class from package * @param packageName destination * @param className name * @throws Exception * @return */ public static void addImport(JavaSource js,final String importText,final boolean isStatic) throws IOException { CancellableTask task = new CancellableTask<WorkingCopy>() { public void cancel() { throw new UnsupportedOperationException("Not supported yet."); } public void run(WorkingCopy workingCopy) throws Exception { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); CompilationUnitTree copy = make.addCompUnitImport(cut,make.Import(make.Identifier(importText), isStatic)); workingCopy.rewrite(cut, copy); } }; js.runModificationTask(task).commit(); }
public void testWrapAssignment() throws Exception { String code = "package hierbas.del.litoral;\n\n" + "import java.util.concurrent.atomic.AtomicBoolean;\n\n" + "public class Test {\n" + " public void t(AtomicBoolean ab) {\n" + " new AtomicBoolean();\n" + " }\n" + "}\n"; runWrappingTest(code, new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); MethodTree method = (MethodTree) clazz.getMembers().get(1); ExpressionStatementTree init = (ExpressionStatementTree) method.getBody().getStatements().get(0); AssignmentTree bt = make.Assignment(make.Identifier("ab"), init.getExpression()); workingCopy.rewrite(init, make.ExpressionStatement(bt)); } }, FmtOptions.wrapAssignOps, WrapStyle.WRAP_IF_LONG.name()); }
public boolean run(DocletEnvironment root) { DocTrees trees = root.getDocTrees(); SourcePositions sourcePositions = trees.getSourcePositions(); for (TypeElement klass : ElementFilter.typesIn(root.getIncludedElements())) { for (ExecutableElement method : getMethods(klass)) { if (method.getSimpleName().toString().equals("tabbedMethod")) { TreePath path = trees.getPath(method); CompilationUnitTree cu = path.getCompilationUnit(); long pos = sourcePositions.getStartPosition(cu, path.getLeaf()); LineMap lineMap = cu.getLineMap(); long columnNumber = lineMap.getColumnNumber(pos); if (columnNumber == 9) { System.out.println(columnNumber + ": OK!"); return true; } else { System.err.println(columnNumber + ": wrong tab expansion"); return false; } } } } return false; }
private Pair<JavacTask, CompilationUnitTree> findSource(String moduleName, String binaryName) throws IOException { JavaFileObject jfo = fm.getJavaFileForInput(StandardLocation.SOURCE_PATH, binaryName, JavaFileObject.Kind.SOURCE); if (jfo == null) return null; List<JavaFileObject> jfos = Arrays.asList(jfo); JavaFileManager patchFM = moduleName != null ? new PatchModuleFileManager(baseFileManager, jfo, moduleName) : baseFileManager; JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, patchFM, d -> {}, null, null, jfos); Iterable<? extends CompilationUnitTree> cuts = task.parse(); task.enter(); return Pair.of(task, cuts.iterator().next()); }
public static List<? extends Tree> getAllTree(JavaSource source) { final List<? extends Tree>[] allTree = new List[1]; try { source.runUserActionTask(new AbstractTask<CompilationController>() { public void run(CompilationController controller) throws IOException { String className = controller.getFileObject().getName(); CompilationUnitTree cu = controller.getCompilationUnit(); if (cu != null) { allTree[0] = cu.getTypeDecls(); } } }, true); } catch (IOException ex) { ex.printStackTrace(); } return allTree[0]; }
@Test void testOperatorMissingError() throws IOException { String code = "package test; public class ErrorTest { " + "void method() { int x = y z } }"; CompilationUnitTree cut = getCompilationUnitTree(code); final List<String> values = new ArrayList<>(); final List<String> expectedValues = new ArrayList<>(Arrays.asList("[z]")); new TreeScanner<Void, Void>() { @Override public Void visitErroneous(ErroneousTree node, Void p) { values.add(getErroneousTreeValues(node).toString()); return null; } }.scan(cut, null); assertEquals("testOperatorMissingError: The Erroneous tree " + "error values: " + values + " do not match expected error values: " + expectedValues, values, expectedValues); }
@Test void testStartPositionForMethodWithoutModifiers() throws IOException { String code = "package t; class Test { <T> void t() {} }"; 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 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)); }
public void testSynteticDefaultConstructor() throws Exception { performTest("SynteticDefaultConstructor"); source.runModificationTask(new Task<WorkingCopy>() { public void run(WorkingCopy copy) throws IOException { copy.toPhase(Phase.RESOLVED); ClassTree topLevel = findTopLevelClass(copy); SourceUtilsTestUtil2.run(copy, new AddSimpleField(), topLevel); } }).commit(); JavaSourceAccessor.getINSTANCE().revalidate(source); CompilationInfo check = SourceUtilsTestUtil.getCompilationInfo(source, Phase.RESOLVED); CompilationUnitTree cu = check.getCompilationUnit(); assertEquals(check.getDiagnostics().toString(), 0, check.getDiagnostics().size()); ClassTree newTopLevel = findTopLevelClass(check); Element clazz = check.getTrees().getElement(TreePath.getPath(cu, newTopLevel)); Element pack = clazz.getEnclosingElement(); assertEquals(ElementKind.PACKAGE, pack.getKind()); assertEquals("test", ((PackageElement) pack).getQualifiedName().toString()); assertEquals(clazz.getEnclosedElements().toString(), 2 + 1/*syntetic default constructor*/, clazz.getEnclosedElements().size()); }
static List<? extends Tree> parse(String srcfile) throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(srcfile); String classPath = System.getProperty("java.class.path"); List<String> options = Arrays.asList("-classpath", classPath); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); Context context = new Context(); JavacTaskImpl task = (JavacTaskImpl) ((JavacTool) compiler).getTask(null, null, diagnostics, options, null, fileObjects, context); TrialParserFactory.instance(context); Iterable<? extends CompilationUnitTree> asts = task.parse(); Iterator<? extends CompilationUnitTree> it = asts.iterator(); if (it.hasNext()) { CompilationUnitTree cut = it.next(); return cut.getTypeDecls(); } else { throw new AssertionError("Expected compilation unit"); } }
public static Collection<String> getImports(CompilationController controller) { Set<String> imports = new HashSet<String>(); CompilationUnitTree cu = controller.getCompilationUnit(); if (cu != null) { List<? extends ImportTree> importTrees = cu.getImports(); for (ImportTree importTree : importTrees) { imports.add(importTree.getQualifiedIdentifier().toString()); } } return imports; }
public boolean run(String sourcepath, File outdir, List<String> classes) { //System.err.println("run: sourcepath:" + sourcepath + " outdir:" + outdir + " classes:" + classes); if (sourcepath == null) throw new IllegalArgumentException("sourcepath not set"); if (outdir == null) throw new IllegalArgumentException("source output dir not set"); JavacTool tool = JavacTool.create(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); try { fm.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(outdir)); fm.setLocation(StandardLocation.SOURCE_PATH, splitPath(sourcepath)); List<JavaFileObject> files = new ArrayList<JavaFileObject>(); for (String c: classes) { JavaFileObject fo = fm.getJavaFileForInput( StandardLocation.SOURCE_PATH, c, JavaFileObject.Kind.SOURCE); if (fo == null) error("class not found: " + c); else files.add(fo); } JavacTask t = tool.getTask(null, fm, null, null, null, files); Iterable<? extends CompilationUnitTree> trees = t.parse(); for (CompilationUnitTree tree: trees) { makeStub(fm, tree); } } catch (IOException e) { error("IO error " + e, e); } return (errors == 0); }
public void testRemoveFirstTwo() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n\n" + "import java.util.*;\n\n" + "public class Test implements List, Collection, Serializable {\n" + " public void taragui() {\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "import java.util.*;\n\n" + "public class Test implements Serializable {\n" + " public void taragui() {\n" + " }\n" + "}\n"; JavaSource src = getJavaSource(testFile); Task task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); for (Tree typeDecl : cut.getTypeDecls()) { // should check kind, here we can be sure! ClassTree clazz = (ClassTree) typeDecl; ClassTree copy = make.removeClassImplementsClause(clazz, 0); copy = make.removeClassImplementsClause(copy, 0); workingCopy.rewrite(clazz, copy); } } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertEquals(golden, res); }
private void performInnerToOuterTest(String generateOuter, Problem... expectedProblems) throws Exception { final InnerToOuterRefactoring[] r = new InnerToOuterRefactoring[1]; JavaSource.forFileObject(src.getFileObject("t/A.java")).runUserActionTask(new Task<CompilationController>() { @Override public void run(CompilationController parameter) throws Exception { parameter.toPhase(JavaSource.Phase.RESOLVED); CompilationUnitTree cut = parameter.getCompilationUnit(); ClassTree outter = (ClassTree) cut.getTypeDecls().get(0); ClassTree inner = (ClassTree) outter.getMembers().get(outter.getMembers().size() - 1); TreePath tp = TreePath.getPath(cut, inner); r[0] = new InnerToOuterRefactoring(TreePathHandle.create(tp, parameter)); } }, true); r[0].setClassName("F"); r[0].setReferenceName(generateOuter); RefactoringSession rs = RefactoringSession.create("Session"); List<Problem> problems = new LinkedList<Problem>(); addAllProblems(problems, r[0].preCheck()); addAllProblems(problems, r[0].prepare(rs)); addAllProblems(problems, rs.doRefactoring(true)); assertProblems(Arrays.asList(expectedProblems), problems); }
private static TypeElement findClass(CompilationController ctrl, String className) { CompilationUnitTree cunit = ctrl.getCompilationUnit(); for (Tree declTree : cunit.getTypeDecls()) { ClassTree classTree = (ClassTree) declTree; if (className.equals(classTree.getSimpleName().toString())) { Trees trees = ctrl.getTrees(); TypeElement classElm = (TypeElement) trees.getElement(trees.getPath(cunit, classTree)); return classElm; } } return null; }
private static int findBodyStartImpl(Tree cltree, CompilationUnitTree cu, SourcePositions positions, Document doc) { int start = (int)positions.getStartPosition(cu, cltree); int end = (int)positions.getEndPosition(cu, cltree); if (start == (-1) || end == (-1)) { return -1; } if (start > doc.getLength() || end > doc.getLength()) { return (-1); } try { String text = doc.getText(start, end - start); int index = text.indexOf('{'); if (index == (-1)) { return -1; // throw new IllegalStateException("Should NEVER happen."); } return start + index; } catch (BadLocationException e) { LOG.log(Level.INFO, null, e); } return (-1); }
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(); } }
@Override public void run(CompilationController info) throws Exception { info.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); CompilationUnitTree unit = info.getCompilationUnit(); if (unit.getTypeDecls().isEmpty()) { ui = createRefactoringUI(null, info); } else { TreePathHandle representedObject = TreePathHandle.create(TreePath.getPath(unit, unit.getTypeDecls().get(0)),info); ui = createRefactoringUI(representedObject, info); } }
public JavaElementFoldVisitor(CompilationInfo info, CompilationUnitTree cu, SourcePositions sp, Document doc, FoldCreator<T> creator) { this.info = info; this.cu = cu; this.sp = sp; this.doc = doc; this.creator = creator; }
/** */ public void run(CompilationController controller) throws IOException { try { controller.toPhase(Phase.RESOLVED); //cursor position needed } catch (IOException ex) { Logger.getLogger("global").log(Level.SEVERE, null, ex); //NOI18N } if (cancelled) { return; } Element element = elemHandle.resolve(controller); if (cancelled || (element == null)) { return; } Trees trees = controller.getTrees(); CompilationUnitTree compUnit = controller.getCompilationUnit(); DeclarationTreeFinder treeFinder = new DeclarationTreeFinder( element, trees); treeFinder.scan(compUnit, null); Tree tree = treeFinder.getDeclarationTree(); if (tree != null) { SourcePositions srcPositions = trees.getSourcePositions(); long startPos = srcPositions.getStartPosition(compUnit, tree); long endPos = srcPositions.getEndPosition(compUnit, tree); if ((startPos >= 0) && (startPos <= (long) Integer.MAX_VALUE) && (endPos >= 0) && (endPos <= (long) Integer.MAX_VALUE)) { positionRange = new int[2]; positionRange[0] = (int) startPos; positionRange[1] = (int) endPos; } } }
@Override public void run(WorkingCopy compiler) throws IOException { try { try { visitor.setWorkingCopy(compiler); } catch (ToPhaseException e) { return; } CompilationUnitTree cu = compiler.getCompilationUnit(); if (cu == null) { ErrorManager.getDefault().log(ErrorManager.ERROR, "compiler.getCompilationUnit() is null " + compiler); // NOI18N return; } Element el = null; if (treePathHandle != null) { el = treePathHandle.resolveElement(compiler); if (el == null) { ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot resolve " + treePathHandle + "in " + compiler.getFileObject().getPath()); return; } } visitor.scan(compiler.getCompilationUnit(), el); } finally { fireProgressListenerStep(); } }
private void performFieldTest(final String newName) throws Exception { final InvertBooleanRefactoring[] r = new InvertBooleanRefactoring[1]; FileObject testFile = src.getFileObject("test/Test.java"); JavaSource.forFileObject(testFile).runUserActionTask(new Task<CompilationController>() { public void run(CompilationController parameter) throws Exception { parameter.toPhase(JavaSource.Phase.RESOLVED); CompilationUnitTree cut = parameter.getCompilationUnit(); VariableTree var = (VariableTree) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(1); TreePath tp = TreePath.getPath(cut, var); r[0] = new InvertBooleanRefactoring(TreePathHandle.create(tp, parameter)); r[0].setNewName(newName); } }, true); RefactoringSession rs = RefactoringSession.create("Session"); Thread.sleep(1000); r[0].prepare(rs); rs.doRefactoring(true); IndexingManager.getDefault().refreshIndex(src.getURL(), null); SourceUtils.waitScanFinished(); assertEquals(false, TaskCache.getDefault().isInError(src, true)); }
protected void computeFQNs(final Map<JavaFileObject, List<String>> file2FQNs, CompilationUnitTree cut, CompileTuple tuple) { String pack; if (cut.getPackageName() != null) { pack = cut.getPackageName().toString() + "."; //XXX } else { pack = ""; } String path = tuple.indexable.getRelativePath(); int i = path.lastIndexOf('.'); if (i >= 0) path = path.substring(0, i); path = FileObjects.convertFolder2Package(path); List<String> fqns = new LinkedList<String>(); boolean hasClassesLivingElsewhere = false; for (Tree t : cut.getTypeDecls()) { if (TreeUtilities.CLASS_TREE_KINDS.contains(t.getKind())) { String fqn = pack + ((ClassTree) t).getSimpleName().toString(); fqns.add(fqn); if (!path.equals(fqn)) { hasClassesLivingElsewhere = true; } } } if (hasClassesLivingElsewhere) { file2FQNs.put(tuple.jfo, fqns); } }
private void hijackJavacCompilerForJava9( TaskEvent te ) { if( IS_JAVA_8 ) { return; } CompilationUnitTree compilationUnit = te.getCompilationUnit(); if( !(compilationUnit instanceof JCTree.JCCompilationUnit) ) { return; } Symbol module = (Symbol)ReflectUtil.field( compilationUnit, "modle" ).get(); if( module == null || _seenModules.contains( module ) ) { return; } _seenModules.add( module ); BootstrapPlugin.openModule( _ctx, "jdk.compiler" ); // Override javac's Resolve (lol) ReflectUtil.method( ReflectUtil.type( "manifold.internal.javac.ManResolve" ), "instance", Context.class ).invokeStatic( _ctx ); // Override javac's ClassFinder ReflectUtil.method( ReflectUtil.type( "manifold.internal.javac.ManClassFinder" ), "instance", Context.class ).invokeStatic( _ctx ); }
@Override public Void visitCompilationUnit(CompilationUnitTree node, Void p) { for (Tree t : node.getTypeDecls()) { visit (t,p); } return null; }
public DocCommentTree getDocCommentTree(TreePath path) { CompilationUnitTree t = path.getCompilationUnit(); Tree leaf = path.getLeaf(); if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) { JCCompilationUnit cu = (JCCompilationUnit) t; if (cu.docComments != null) { return cu.docComments.getCommentTree((JCTree) leaf); } } return null; }
private void performTest(final String builderName, final Setter setter, Problem... expectedProblems) throws Exception { final ReplaceConstructorWithBuilderRefactoring[] r = new ReplaceConstructorWithBuilderRefactoring[1]; FileObject testFile = src.getFileObject("test/Test.java"); JavaSource.forFileObject(testFile).runUserActionTask(new Task<CompilationController>() { public void run(CompilationController parameter) throws Exception { parameter.toPhase(JavaSource.Phase.RESOLVED); CompilationUnitTree cut = parameter.getCompilationUnit(); MethodTree var = (MethodTree) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0); TreePath tp = TreePath.getPath(cut, var); r[0] = new ReplaceConstructorWithBuilderRefactoring(TreePathHandle.create(tp, parameter)); r[0].setBuilderName(builderName); r[0].setBuildMethodName("createTest"); r[0].setSetters(Collections.singletonList(setter)); } }, true); RefactoringSession rs = RefactoringSession.create("Session"); Thread.sleep(1000); List<Problem> problems = new LinkedList<Problem>(); addAllProblems(problems, r[0].preCheck()); if (!problemIsFatal(problems)) { addAllProblems(problems, r[0].prepare(rs)); } if (!problemIsFatal(problems)) { addAllProblems(problems, rs.doRefactoring(true)); } assertProblems(Arrays.asList(expectedProblems), problems); IndexingManager.getDefault().refreshIndex(src.toURL(), null); SourceUtils.waitScanFinished(); //assertEquals(false, TaskCache.getDefault().isInError(src, true)); }
private String getDiagSource(Element e) { if (e == null) { return programName; } JavacTrees trees = JavacTrees.instance(context); TreePath path = trees.getPath(e); DocSourcePositions sourcePositions = trees.getSourcePositions(); JCTree tree = trees.getTree(e); CompilationUnitTree cu = path.getCompilationUnit(); long spos = sourcePositions.getStartPosition(cu, tree); long lineNumber = cu.getLineMap().getLineNumber(spos); String fname = cu.getSourceFile().getName(); String posString = fname + ":" + lineNumber; return posString; }
/** * Create a new CompilationUnitTree from a template. * * @param sourceRoot a source root under which the new file is created * @param path a relative path to file separated by '/' * @param kind the kind of Element to use for the template, can be null or * CLASS, INTERFACE, ANNOTATION_TYPE, ENUM, PACKAGE * @return new CompilationUnitTree created from a template * @throws IOException when an exception occurs while creating the template * @since 0.101 */ public CompilationUnitTree createFromTemplate(FileObject sourceRoot, String path, ElementKind kind) throws IOException { String[] nameComponent = FileObjects.getFolderAndBaseName(path, '/'); JavaFileObject sourceFile = FileObjects.templateFileObject(sourceRoot, nameComponent[0], nameComponent[1]); FileObject template = FileUtil.getConfigFile(copy.template(kind)); FileObject targetFile = copy.doCreateFromTemplate(template, sourceFile); CompilationUnitTree templateCUT = ParsingUtils.parseArbitrarySource(copy.impl.getJavacTask(), FileObjects.sourceFileObject(targetFile, targetFile.getParent())); CompilationUnitTree importComments = GeneratorUtilities.get(copy).importComments(templateCUT, templateCUT); CompilationUnitTree result = copy.getTreeMaker().CompilationUnit(importComments.getPackageAnnotations(), sourceRoot, path, importComments.getImports(), importComments.getTypeDecls()); return result; }
private boolean isEvil(Tree tree) { Tree.Kind kind = tree.getKind(); switch (kind) { case COMPILATION_UNIT: CompilationUnitTree cut = (CompilationUnitTree) tree; return cut.getPackageName() == null; // case MODIFIERS: case PRIMITIVE_TYPE: return true; default: return false; } }
private static boolean isInHeader(CompilationInfo info, MethodTree tree, int offset) { CompilationUnitTree cut = info.getCompilationUnit(); SourcePositions sp = info.getTrees().getSourcePositions(); long lastKnownOffsetInHeader = sp.getStartPosition(cut, tree); List<? extends ExpressionTree> throwz; List<? extends VariableTree> params; List<? extends TypeParameterTree> typeparams; if ((throwz = tree.getThrows()) != null && !throwz.isEmpty()) { lastKnownOffsetInHeader = sp.getEndPosition(cut, throwz.get(throwz.size() - 1)); } else if ((params = tree.getParameters()) != null && !params.isEmpty()) { lastKnownOffsetInHeader = sp.getEndPosition(cut, params.get(params.size() - 1)); } else if ((typeparams = tree.getTypeParameters()) != null && !typeparams.isEmpty()) { lastKnownOffsetInHeader = sp.getEndPosition(cut, typeparams.get(typeparams.size() - 1)); } else if (tree.getReturnType() != null) { lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getReturnType()); } else if (tree.getModifiers() != null) { lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getModifiers()); } TokenSequence<JavaTokenId> ts = info.getTreeUtilities().tokensFor(tree); ts.move((int) lastKnownOffsetInHeader); while (ts.moveNext()) { if (ts.token().id() == JavaTokenId.LBRACE || ts.token().id() == JavaTokenId.SEMICOLON) { return offset < ts.offset(); } } return false; }
private ExpressionToTypeInfo(AnalyzeTask at, CompilationUnitTree cu, JShell state) { this.at = at; this.cu = cu; this.state = state; this.syms = Symtab.instance(at.context); this.types = Types.instance(at.context); }