public DiffContext(CompilationInfo copy, Set<Tree> syntheticTrees) { this.tokenSequence = copy.getTokenHierarchy().tokenSequence(JavaTokenId.language()); this.mainCode = this.origText = copy.getText(); this.style = getCodeStyle(copy); this.context = JavaSourceAccessor.getINSTANCE().getJavacTask(copy).getContext(); this.mainUnit = this.origUnit = (JCCompilationUnit) copy.getCompilationUnit(); this.trees = copy.getTrees(); this.doc = copy.getSnapshot().getSource().getDocument(false); //TODO: true or false? this.positionConverter = copy.getPositionConverter(); this.file = copy.getFileObject(); this.syntheticTrees = syntheticTrees; this.textLength = copy.getSnapshot() == null ? Integer.MAX_VALUE : copy.getSnapshot().getOriginalOffset(copy.getSnapshot().getText().length()); this.blockSequences = new BlockSequences(this.tokenSequence, doc, textLength); this.forceInitialComment = false; }
/** * Note: the constructor is only used when creating new compilation units; a special flag will be set up, so an initial comment is not skipped. */ public DiffContext(CompilationInfo copy, CompilationUnitTree cut, String code, PositionConverter positionConverter, FileObject file, Set<Tree> syntheticTrees, CompilationUnitTree mainUnit, String mainCode) { this.tokenSequence = TokenHierarchy.create(code, JavaTokenId.language()).tokenSequence(JavaTokenId.language()); this.origText = code; this.style = getCodeStyle(copy); this.context = JavaSourceAccessor.getINSTANCE().getJavacTask(copy).getContext(); this.origUnit = (JCCompilationUnit) cut; this.trees = copy.getTrees(); this.doc = null; this.positionConverter = positionConverter; this.file = file; this.syntheticTrees = syntheticTrees; this.mainUnit = (JCCompilationUnit) mainUnit; this.mainCode = mainCode; this.textLength = copy.getSnapshot() == null ? Integer.MAX_VALUE : copy.getSnapshot().getOriginalOffset(copy.getSnapshot().getText().length()); this.blockSequences = new BlockSequences(this.tokenSequence, doc, textLength); this.forceInitialComment = true; }
public static CompilationUnitTree parseArbitrarySource(JavacTask task, JavaFileObject file) throws IOException { JavacTaskImpl taskImpl = (JavacTaskImpl) task; com.sun.tools.javac.util.Context context = taskImpl.getContext(); Log log = Log.instance(context); JavaFileObject prevSource = log.useSource(file); try { ParserFactory fac = ParserFactory.instance(context); JCCompilationUnit cut = fac.newParser(file.getCharContent(true), true, true, true).parseCompilationUnit(); cut.sourcefile = file; return cut; } finally { log.useSource(prevSource); } }
/** * Resolve an identifier. * * @param name The identifier to resolve */ public Symbol resolveIdent(String name) { if (name.equals("")) return syms.errSymbol; JavaFileObject prev = log.useSource(null); try { JCExpression tree = null; for (String s : name.split("\\.", -1)) { if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords return syms.errSymbol; tree = (tree == null) ? make.Ident(names.fromString(s)) : make.Select(tree, names.fromString(s)); } JCCompilationUnit toplevel = make.TopLevel(List.<JCAnnotation>nil(), null, List.<JCTree>nil()); toplevel.packge = syms.unnamedPackage; return attr.attribIdent(tree, toplevel); } finally { log.useSource(prev); } }
/** * Parses a list of files. */ public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) { if (shouldStop(CompileState.PARSE)) return List.nil(); //parse all files ListBuffer<JCCompilationUnit> trees = lb(); Set<JavaFileObject> filesSoFar = new HashSet<JavaFileObject>(); for (JavaFileObject fileObject : fileObjects) { if (!filesSoFar.contains(fileObject)) { filesSoFar.add(fileObject); trees.append(parse(fileObject)); } } return trees.toList(); }
/** Resolve an identifier. * @param msym The module in which the search should be performed * @param name The identifier to resolve */ public Symbol resolveIdent(ModuleSymbol msym, String name) { if (name.equals("")) return syms.errSymbol; JavaFileObject prev = log.useSource(null); try { JCExpression tree = null; for (String s : name.split("\\.", -1)) { if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords return syms.errSymbol; tree = (tree == null) ? make.Ident(names.fromString(s)) : make.Select(tree, names.fromString(s)); } JCCompilationUnit toplevel = make.TopLevel(List.nil()); toplevel.modle = msym; toplevel.packge = msym.unnamedPackage; return attr.attribIdent(tree, toplevel); } finally { log.useSource(prev); } }
/** * Parses a list of files. */ public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) { if (shouldStop(CompileState.PARSE)) return List.nil(); //parse all files ListBuffer<JCCompilationUnit> trees = new ListBuffer<>(); Set<JavaFileObject> filesSoFar = new HashSet<>(); for (JavaFileObject fileObject : fileObjects) { if (!filesSoFar.contains(fileObject)) { filesSoFar.add(fileObject); trees.append(parse(fileObject)); } } return trees.toList(); }
private Iterable<? extends CompilationUnitTree> parseInternal() { try { prepareCompiler(true); List<JCCompilationUnit> units = compiler.parseFiles(args.getFileObjects()); for (JCCompilationUnit unit: units) { JavaFileObject file = unit.getSourceFile(); if (notYetEntered.containsKey(file)) notYetEntered.put(file, unit); } return units; } finally { parsed = true; if (compiler != null && compiler.log != null) compiler.log.flush(); } }
private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) { for (Env<AttrContext> env: queue) { switch (env.tree.getTag()) { case CLASSDEF: JCClassDecl cdef = (JCClassDecl) env.tree; if (cdef.sym != null) elems.append(cdef.sym); break; case MODULEDEF: JCModuleDecl mod = (JCModuleDecl) env.tree; if (mod.sym != null) elems.append(mod.sym); break; case PACKAGEDEF: JCCompilationUnit unit = env.toplevel; if (unit.packge != null) elems.append(unit.packge); break; } } genList.addAll(queue); }
public void initModules(List<JCCompilationUnit> trees) { Assert.check(!inInitModules); try { inInitModules = true; Assert.checkNull(rootModules); enter(trees, modules -> { Assert.checkNull(rootModules); Assert.checkNull(allModules); this.rootModules = modules; setupAllModules(); //initialize the module graph Assert.checkNonNull(allModules); inInitModules = false; }, null); } finally { inInitModules = false; } }
@Override @DefinedBy(Api.COMPILER_TREE) public void finished(TaskEvent e) { switch (e.getKind()) { case ANALYZE: collectClassSymbols((JCCompilationUnit) e.getCompilationUnit()); break; case COMPILATION: Log.debug("Compilation finished"); Log.debug("Extracting pub APIs for the following symbols:"); for (ClassSymbol cs : classSymbols) Log.debug(" " + cs.fullname); extractPubApis(); // Save result for later retrieval. (Important that we do this // before we return from this method, because we may not access // symbols after compilation is finished.) PubAPIs pa = PubAPIs.instance(context); explicitPubApis = pa.getPubapis(explicitJFOs, true); nonExplicitPubApis = pa.getPubapis(explicitJFOs, false); Log.debug("done"); break; } }
private String getModuleName(Location location) throws ToolException { try { JavaFileObject jfo = fm.getJavaFileForInput(location, "module-info", JavaFileObject.Kind.SOURCE); if (jfo != null) { JCCompilationUnit jcu = compiler.parse(jfo); JCModuleDecl module = TreeInfo.getModule(jcu); if (module != null) { return module.getName().toString(); } } } catch (IOException ioe) { String text = messager.getText("main.file.manager.list", location); throw new ToolException(SYSERR, text, ioe); } return null; }
public List<int[]> gatherTreeSpans(File file, String content) throws IOException { JCCompilationUnit unit = read(file.toURI(), content); List<int[]> spans = new ArrayList<>(); new TreePathScanner<Void, Void>() { @Override public Void scan(Tree tree, Void p) { if (tree != null) { int start = ((JCTree) tree).getStartPosition(); int end = ((JCTree) tree).getEndPosition(unit.endPositions); spans.add(new int[] {start, end}); } return super.scan(tree, p); } }.scan(unit, null); return spans; }
/** * 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, Collections.<String>emptyList(), 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; }
/** * 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; }
/** Resolve an identifier. * @param msym The module in which the search should be performed * @param name The identifier to resolve */ public Symbol resolveIdent(ModuleSymbol msym, String name) { if (name.equals("")) return syms.errSymbol; JavaFileObject prev = log.useSource(null); try { JCExpression tree = null; for (String s : name.split("\\.", -1)) { if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords return syms.errSymbol; tree = (tree == null) ? make.Ident(names.fromString(s)) : make.Select(tree, names.fromString(s)); } JCCompilationUnit toplevel = make.TopLevel(List.<JCTree>nil()); toplevel.modle = msym; toplevel.packge = msym.unnamedPackage; return attr.attribIdent(tree, toplevel); } finally { log.useSource(prev); } }
private Completer getSourceCompleter(JCCompilationUnit tree) { return new Completer() { @Override public void complete(Symbol sym) throws CompletionFailure { ModuleSymbol msym = (ModuleSymbol) sym; msym.flags_field |= UNATTRIBUTED; ModuleVisitor v = new ModuleVisitor(); JavaFileObject prev = log.useSource(tree.sourcefile); try { tree.defs.head.accept(v); completeModule(msym); checkCyclicDependencies((JCModuleDecl) tree.defs.head); } finally { log.useSource(prev); msym.flags_field &= ~UNATTRIBUTED; } } @Override public String toString() { return "SourceCompleter: " + tree.sourcefile.getName(); } }; }
@SuppressWarnings("unchecked") private boolean attach(JCCompilationUnit top, final JCTree node, CommentInfo cmt) { String docCommentContent = cmt.content; if (docCommentContent.startsWith("/**")) docCommentContent = docCommentContent.substring(3); if (docCommentContent.endsWith("*/")) docCommentContent = docCommentContent.substring(0, docCommentContent.length() -2); docCommentContent = CONTENT_STRIPPER.matcher(docCommentContent).replaceAll("$1"); docCommentContent = docCommentContent.trim(); if (Javac.getDocComments(top) == null) Javac.initDocComments(top); Object map_ = Javac.getDocComments(top); if (map_ instanceof Map) { ((Map<JCTree, String>) map_).put(node, docCommentContent); return true; } else if (Javac.instanceOfDocCommentTable(map_)) { CommentAttacher_8.attach(node, docCommentContent, map_); return true; } return false; }
@SuppressWarnings({"unchecked", "rawtypes"}) public PrettyPrinter(Writer out, JCCompilationUnit cu, List<CommentInfo> comments, FormatPreferences preferences) { this.out = out; this.comments = comments; this.compilationUnit = cu; this.formatPreferences = preferences; /* load doc comments */ { Object dc = getDocComments(compilationUnit); if (dc instanceof Map<?, ?>) { this.docComments = (Map) dc; this.docTable = null; } else if (dc instanceof DocCommentTable) { this.docComments = null; this.docTable = (DocCommentTable) dc; } else { this.docComments = null; this.docTable = null; } } }
/** * Handles the provided annotation node by first finding a qualifying instance of * {@link JavacAnnotationHandler} and if one exists, calling it with a freshly cooked up * instance of {@link lombok.core.AnnotationValues}. * * Note that depending on the printASTOnly flag, the {@link lombok.core.PrintAST} annotation * will either be silently skipped, or everything that isn't {@code PrintAST} will be skipped. * * The HandlerLibrary will attempt to guess if the given annotation node represents a lombok annotation. * For example, if {@code lombok.*} is in the import list, then this method will guess that * {@code Getter} refers to {@code lombok.Getter}, presuming that {@link lombok.javac.handlers.HandleGetter} * has been loaded. * * @param unit The Compilation Unit that contains the Annotation AST Node. * @param node The Lombok AST Node representing the Annotation AST Node. * @param annotation 'node.get()' - convenience parameter. */ public void handleAnnotation(JCCompilationUnit unit, JavacNode node, JCAnnotation annotation, long priority) { TypeResolver resolver = new TypeResolver(node.getImportList()); String rawType = annotation.annotationType.toString(); String fqn = resolver.typeRefToFullyQualifiedName(node, typeLibrary, rawType); if (fqn == null) return; AnnotationHandlerContainer<?> container = annotationHandlers.get(fqn); if (container == null) return; try { if (container.getPriority() == priority) { if (checkAndSetHandled(annotation)) container.handle(node); } } catch (AnnotationValueDecodeFail fail) { fail.owner.setError(fail.getMessage(), fail.idx); } catch (Throwable t) { String sourceName = "(unknown).java"; if (unit != null && unit.sourcefile != null) sourceName = unit.sourcefile.getName(); javacError(String.format("Lombok annotation handler %s failed on " + sourceName, container.handler.getClass()), t); } }
/** {@inheritDoc} */ @Override protected JavacNode buildTree(JCTree node, Kind kind) { switch (kind) { case COMPILATION_UNIT: return buildCompilationUnit((JCCompilationUnit) node); case TYPE: return buildType((JCClassDecl) node); case FIELD: return buildField((JCVariableDecl) node); case INITIALIZER: return buildInitializer((JCBlock) node); case METHOD: return buildMethod((JCMethodDecl) node); case ARGUMENT: return buildLocalVar((JCVariableDecl) node, kind); case LOCAL: return buildLocalVar((JCVariableDecl) node, kind); case STATEMENT: return buildStatementOrExpression(node); case ANNOTATION: return buildAnnotation((JCAnnotation) node, false); default: throw new AssertionError("Did not expect: " + kind); } }
protected void diffTopLevel(JCCompilationUnit oldT, JCCompilationUnit newT, int[] elementBounds) { oldTopLevel = oldT; int localPointer = diffPackage(oldT.getPackage(), newT.getPackage(), elementBounds[0]); PositionEstimator est = EstimatorFactory.imports(oldT.getImports(), newT.getImports(), diffContext); localPointer = diffList(oldT.getImports(), newT.getImports(), localPointer, est, Measure.DEFAULT, printer); est = EstimatorFactory.toplevel(oldT.getTypeDecls(), newT.getTypeDecls(), diffContext); localPointer = diffList(oldT.getTypeDecls(), newT.getTypeDecls(), localPointer, est, Measure.REAL_MEMBER, printer); checkLocalPointer(oldT, newT, localPointer); printer.print(origText.substring(localPointer)); }
@Override public void finished(TaskEvent e) { if (e.getKind() == Kind.ANALYZE) { JCCompilationUnit toplevel = (JCCompilationUnit) e.getCompilationUnit(); if (toplevel != null && toplevel.sourcefile != null) { flowCompleted.add(toplevel.sourcefile.toUri()); } } }
private static boolean isSynthetic(CompilationUnitTree cut, Tree leaf) throws NullPointerException { JCTree tree = (JCTree) leaf; if (tree.pos == (-1)) return true; if (leaf.getKind() == Kind.METHOD) { //check for synthetic constructor: return (((JCMethodDecl)leaf).mods.flags & Flags.GENERATEDCONSTR) != 0L; } //check for synthetic superconstructor call: if (cut != null && leaf.getKind() == Kind.EXPRESSION_STATEMENT) { ExpressionStatementTree est = (ExpressionStatementTree) leaf; if (est.getExpression().getKind() == Kind.METHOD_INVOCATION) { MethodInvocationTree mit = (MethodInvocationTree) est.getExpression(); if (mit.getMethodSelect().getKind() == Kind.IDENTIFIER) { IdentifierTree it = (IdentifierTree) mit.getMethodSelect(); if ("super".equals(it.getName().toString())) { return ((JCCompilationUnit) cut).endPositions.getEndPos(tree) == (-1); } } } } return false; }
public JCBlock reparseMethodBody(CompilationUnitTree topLevel, MethodTree methodToReparse, String newBodyText, int annonIndex, final Map<? super JCTree,? super LazyDocCommentTable.Entry> docComments) { CharBuffer buf = CharBuffer.wrap((newBodyText+"\u0000").toCharArray(), 0, newBodyText.length()); JavacParser parser = newParser(context, buf, ((JCBlock)methodToReparse.getBody()).pos, ((JCCompilationUnit)topLevel).endPositions); final JCStatement statement = parser.parseStatement(); NBParserFactory.assignAnonymousClassIndices(Names.instance(context), statement, Names.instance(context).empty, annonIndex); if (statement.getKind() == Tree.Kind.BLOCK) { if (docComments != null) { docComments.putAll(((LazyDocCommentTable) parser.getDocComments()).table); } return (JCBlock) statement; } return null; }
public BlockTree reflowMethodBody(CompilationUnitTree topLevel, ClassTree ownerClass, MethodTree methodToReparse) { Flow flow = Flow.instance(context); TreeMaker make = TreeMaker.instance(context); flow.reanalyzeMethod(make.forToplevel((JCCompilationUnit)topLevel), (JCClassDecl)ownerClass); return methodToReparse.getBody(); }
@Override public void visitTopLevel(JCTree.JCCompilationUnit tree) { if (TreeInfo.isModuleInfo(tree) && tree.modle == syms.noModule) { //workaround: when source level is == 8, then visitTopLevel crashes for module-info.java return ; } super.visitTopLevel(tree); }
/** * Parse contents of file. * * @param filename The name of the file to be parsed. */ public JCCompilationUnit parse(JavaFileObject filename) { JavaFileObject prev = log.useSource(filename); try { JCCompilationUnit t = parse(filename, readSource(filename)); if (t.endPositions != null) log.setEndPosTable(filename, t.endPositions); return t; } finally { log.useSource(prev); } }
Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) { // use a LinkedHashMap to preserve the order of the original list as much as possible Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>(); for (Env<AttrContext> env : envs) { Queue<Env<AttrContext>> sublist = map.get(env.toplevel); if (sublist == null) { sublist = new ListBuffer<Env<AttrContext>>(); map.put(env.toplevel, sublist); } sublist.add(env); } return map; }
/** Create a fresh environment for toplevels. * @param tree The toplevel tree. */ Env<AttrContext> topLevelEnv(JCCompilationUnit tree) { Env<AttrContext> localEnv = new Env<AttrContext>(tree, new AttrContext()); localEnv.toplevel = tree; localEnv.enclClass = predefClassDef; tree.namedImportScope = new ImportScope(tree.packge); tree.starImportScope = new StarImportScope(tree.packge); localEnv.info.scope = tree.namedImportScope; localEnv.info.lint = lint; return localEnv; }
public Env<AttrContext> getTopLevelEnv(JCCompilationUnit tree) { Env<AttrContext> localEnv = new Env<AttrContext>(tree, new AttrContext()); localEnv.toplevel = tree; localEnv.enclClass = predefClassDef; localEnv.info.scope = tree.namedImportScope; localEnv.info.lint = lint; return localEnv; }
/** Main method: enter one class from a list of toplevel trees and * place the rest on uncompleted for later processing. * @param trees The list of trees to be processed. * @param c The class symbol to be processed. */ public void complete(List<JCCompilationUnit> trees, ClassSymbol c) { annotate.enterStart(); ListBuffer<ClassSymbol> prevUncompleted = uncompleted; if (memberEnter.completionEnabled) uncompleted = new ListBuffer<ClassSymbol>(); try { // enter all classes, and construct uncompleted list classEnter(trees, null); // complete all uncompleted classes in memberEnter if (memberEnter.completionEnabled) { while (uncompleted.nonEmpty()) { ClassSymbol clazz = uncompleted.next(); if (c == null || c == clazz || prevUncompleted == null) clazz.complete(); else // defer prevUncompleted.append(clazz); } // if there remain any unimported toplevels (these must have // no classes at all), process their import statements as well. for (JCCompilationUnit tree : trees) { if (tree.starImportScope.elems == null) { JavaFileObject prev = log.useSource(tree.sourcefile); Env<AttrContext> topEnv = topLevelEnv(tree); memberEnter.memberEnter(tree, topEnv); log.useSource(prev); } } } } finally { uncompleted = prevUncompleted; annotate.enterDone(); } }
/** * Constructor */ public PackageDocImpl(DocEnv env, PackageSymbol sym, TreePath treePath) { super(env, treePath); this.sym = sym; this.tree = (treePath == null) ? null : (JCCompilationUnit) treePath.getCompilationUnit(); foundDoc = (documentation != null); }
private void parse(JavaFileObject fo, ListBuffer<JCCompilationUnit> trees, boolean trace) { if (uniquefiles.add(fo)) { // ignore duplicates if (trace) docenv.notice("main.Loading_source_file", fo.getName()); trees.append(parse(fo)); } }
/** * From a list of top level trees, return the list of contained class definitions */ List<JCClassDecl> listClasses(List<JCCompilationUnit> trees) { ListBuffer<JCClassDecl> result = new ListBuffer<JCClassDecl>(); for (JCCompilationUnit t : trees) { for (JCTree def : t.defs) { if (def.hasTag(JCTree.Tag.CLASSDEF)) result.append((JCClassDecl)def); } } return result.toList(); }