use of com.sun.source.tree.CompilationUnitTree in project j2objc by google.
the class JavacParser method parse.
@Override
public CompilationUnit parse(String mainType, String path, String source) {
try {
JavacEnvironment parserEnv = createEnvironment(path, source);
JavacTask task = parserEnv.task();
CompilationUnitTree unit = task.parse().iterator().next();
task.analyze();
processDiagnostics(parserEnv.diagnostics());
return TreeConverter.convertCompilationUnit(options, parserEnv, unit);
} catch (IOException e) {
ErrorUtil.fatalError(e, path);
}
return null;
}
use of com.sun.source.tree.CompilationUnitTree in project j2objc by google.
the class JavacParser method parseFiles.
@Override
public void parseFiles(Collection<String> paths, Handler handler, SourceVersion sourceVersion) {
List<File> files = new ArrayList<>();
for (String path : paths) {
files.add(new File(path));
}
try {
JavacEnvironment env = createEnvironment(files, null, false);
List<CompilationUnitTree> units = new ArrayList<>();
for (CompilationUnitTree unit : env.task().parse()) {
units.add(unit);
}
env.task().analyze();
processDiagnostics(env.diagnostics());
if (ErrorUtil.errorCount() == 0) {
for (CompilationUnitTree ast : units) {
com.google.devtools.j2objc.ast.CompilationUnit unit = TreeConverter.convertCompilationUnit(options, env, ast);
processDiagnostics(env.diagnostics());
handler.handleParsedUnit(unit.getSourceFilePath(), unit);
}
}
} catch (IOException e) {
ErrorUtil.fatalError(e, "javac file manager error");
}
}
use of com.sun.source.tree.CompilationUnitTree in project vertx-docgen by vert-x3.
the class JavaDocGenerator method renderSource.
public String renderSource(TreePath path, List<? extends Tree> trees, String source) {
CompilationUnitTree unit = path.getCompilationUnit();
int from = (int) docTrees.getSourcePositions().getStartPosition(unit, trees.get(0));
int to = (int) docTrees.getSourcePositions().getEndPosition(unit, trees.get(trees.size() - 1));
// Correct boundaries
while (from > 1 && source.charAt(from - 1) != '\n') {
from--;
}
while (to < source.length() && source.charAt(to) != '\n') {
to++;
}
String block = source.substring(from, to);
// Determine margin
int blockMargin = Integer.MAX_VALUE;
LineMap lineMap = unit.getLineMap();
for (Tree statement : trees) {
int statementStart = (int) docTrees.getSourcePositions().getStartPosition(unit, statement);
int lineStart = statementStart;
while (lineMap.getLineNumber(statementStart) == lineMap.getLineNumber(lineStart - 1)) {
lineStart--;
}
blockMargin = Math.min(blockMargin, statementStart - lineStart);
}
// Crop the fragment
StringBuilder fragment = new StringBuilder();
for (Iterator<String> sc = new Scanner(block).useDelimiter("\n"); sc.hasNext(); ) {
String line = sc.next();
int margin = Math.min(blockMargin, line.length());
line = line.substring(margin);
fragment.append(line);
if (sc.hasNext()) {
fragment.append('\n');
}
}
return fragment.toString();
}
use of com.sun.source.tree.CompilationUnitTree in project error-prone by google.
the class FindIdentifiers method findAllIdents.
/**
* Finds the set of all bare variable identifiers in scope at the current location. Identifiers
* are ordered by ascending distance/scope count from the current location to match shadowing
* rules. That is, if two variables with the same simple names appear in the set, the one that
* appears first in iteration order is the one you get if you use the bare name in the source
* code.
*
* <p>We do not report variables that would require a qualfied access. We also do not handle
* wildcard imports.
*/
public static LinkedHashSet<VarSymbol> findAllIdents(VisitorState state) {
ImmutableSet.Builder<VarSymbol> result = new ImmutableSet.Builder<>();
Tree prev = state.getPath().getLeaf();
for (Tree curr : state.getPath().getParentPath()) {
switch(curr.getKind()) {
case BLOCK:
for (StatementTree stmt : ((BlockTree) curr).getStatements()) {
if (stmt.equals(prev)) {
break;
}
addIfVariable(stmt, result);
}
break;
case METHOD:
for (VariableTree param : ((MethodTree) curr).getParameters()) {
result.add(ASTHelpers.getSymbol(param));
}
break;
case CATCH:
result.add(ASTHelpers.getSymbol(((CatchTree) curr).getParameter()));
break;
case CLASS:
case INTERFACE:
case ENUM:
case ANNOTATION_TYPE:
// field is referred to by qualified name, but we don't support that.
for (Tree member : ((ClassTree) curr).getMembers()) {
if (member.equals(prev)) {
break;
}
addIfVariable(member, result);
}
// Collect inherited fields.
Type classType = ASTHelpers.getType(curr);
List<Type> classTypeClosure = state.getTypes().closure(classType);
List<Type> superTypes = classTypeClosure.size() <= 1 ? Collections.emptyList() : classTypeClosure.subList(1, classTypeClosure.size());
for (Type type : superTypes) {
Scope scope = type.tsym.members();
ImmutableList.Builder<VarSymbol> varsList = ImmutableList.builder();
for (Symbol var : scope.getSymbols(VarSymbol.class::isInstance)) {
varsList.add((VarSymbol) var);
}
result.addAll(varsList.build().reverse());
}
break;
case FOR_LOOP:
addAllIfVariable(((ForLoopTree) curr).getInitializer(), result);
break;
case ENHANCED_FOR_LOOP:
result.add(ASTHelpers.getSymbol(((EnhancedForLoopTree) curr).getVariable()));
break;
case TRY:
TryTree tryTree = (TryTree) curr;
boolean inResources = false;
for (Tree resource : tryTree.getResources()) {
if (resource.equals(prev)) {
inResources = true;
break;
}
}
if (inResources) {
// Case 1: we're in one of the resource declarations
for (Tree resource : tryTree.getResources()) {
if (resource.equals(prev)) {
break;
}
addIfVariable(resource, result);
}
} else if (tryTree.getBlock().equals(prev)) {
// Case 2: We're in the block (not a catch or finally)
addAllIfVariable(tryTree.getResources(), result);
}
break;
case COMPILATION_UNIT:
for (ImportTree importTree : ((CompilationUnitTree) curr).getImports()) {
if (importTree.isStatic() && importTree.getQualifiedIdentifier().getKind() == Kind.MEMBER_SELECT) {
MemberSelectTree memberSelectTree = (MemberSelectTree) importTree.getQualifiedIdentifier();
Scope scope = state.getTypes().membersClosure(ASTHelpers.getType(memberSelectTree.getExpression()), /* skipInterface= */
false);
for (Symbol var : scope.getSymbols(sym -> sym instanceof VarSymbol && sym.getSimpleName().equals(memberSelectTree.getIdentifier()))) {
result.add((VarSymbol) var);
}
}
}
break;
default:
// other node types don't introduce variables
break;
}
prev = curr;
}
// TODO(eaftan): switch out collector for ImmutableSet.toImmutableSet()
return result.build().stream().filter(var -> isVisible(var, state.getPath())).collect(Collectors.toCollection(LinkedHashSet::new));
}
use of com.sun.source.tree.CompilationUnitTree in project error-prone by google.
the class BugCheckerRefactoringTestHelper method doCompile.
private JCCompilationUnit doCompile(final JavaFileObject input, Iterable<JavaFileObject> files, Context context) throws IOException {
JavacTool tool = JavacTool.create();
DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>();
context.put(ErrorProneOptions.class, ErrorProneOptions.empty());
JavacTaskImpl task = (JavacTaskImpl) tool.getTask(CharStreams.nullWriter(), fileManager, diagnosticsCollector, options, /*classes=*/
null, files, context);
Iterable<? extends CompilationUnitTree> trees = task.parse();
task.analyze();
JCCompilationUnit tree = Iterables.getOnlyElement(Iterables.filter(Iterables.filter(trees, JCCompilationUnit.class), compilationUnit -> compilationUnit.getSourceFile() == input));
Iterable<Diagnostic<? extends JavaFileObject>> errorDiagnostics = Iterables.filter(diagnosticsCollector.getDiagnostics(), d -> d.getKind() == Diagnostic.Kind.ERROR);
if (!Iterables.isEmpty(errorDiagnostics)) {
fail("compilation failed unexpectedly: " + errorDiagnostics);
}
return tree;
}
Aggregations