use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project error-prone by google.
the class ExpressionTemplate method getPrecedence.
/**
* Returns the precedence level appropriate for unambiguously printing
* leaf as a subexpression of its parent.
*/
private static int getPrecedence(JCTree leaf, Context context) {
JCCompilationUnit comp = context.get(JCCompilationUnit.class);
JCTree parent = TreeInfo.pathFor(leaf, comp).get(1);
if (parent instanceof JCConditional) {
// This intentionally differs from Pretty, because Pretty appears buggy:
// http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html
JCConditional conditional = (JCConditional) parent;
return TreeInfo.condPrec + ((conditional.cond == leaf) ? 1 : 0);
} else if (parent instanceof JCAssign) {
JCAssign assign = (JCAssign) parent;
return TreeInfo.assignPrec + ((assign.lhs == leaf) ? 1 : 0);
} else if (parent instanceof JCAssignOp) {
JCAssignOp assignOp = (JCAssignOp) parent;
return TreeInfo.assignopPrec + ((assignOp.lhs == leaf) ? 1 : 0);
} else if (parent instanceof JCUnary) {
return TreeInfo.opPrec(parent.getTag());
} else if (parent instanceof JCBinary) {
JCBinary binary = (JCBinary) parent;
return TreeInfo.opPrec(parent.getTag()) + ((binary.rhs == leaf) ? 1 : 0);
} else if (parent instanceof JCTypeCast) {
JCTypeCast typeCast = (JCTypeCast) parent;
return (typeCast.expr == leaf) ? TreeInfo.prefixPrec : TreeInfo.noPrec;
} else if (parent instanceof JCInstanceOf) {
JCInstanceOf instanceOf = (JCInstanceOf) parent;
return TreeInfo.ordPrec + ((instanceOf.clazz == leaf) ? 1 : 0);
} else if (parent instanceof JCArrayAccess) {
JCArrayAccess arrayAccess = (JCArrayAccess) parent;
return (arrayAccess.indexed == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
} else if (parent instanceof JCFieldAccess) {
JCFieldAccess fieldAccess = (JCFieldAccess) parent;
return (fieldAccess.selected == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
} else {
return TreeInfo.noPrec;
}
}
use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit 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;
}
use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project lombok by rzwitserloot.
the class Delombok method delombok.
public boolean delombok() throws IOException {
LombokOptions options = LombokOptionsFactory.getDelombokOptions(context);
options.deleteLombokAnnotations();
options.putJavacOption("ENCODING", charset.name());
if (classpath != null)
options.putJavacOption("CLASSPATH", classpath);
if (sourcepath != null)
options.putJavacOption("SOURCEPATH", sourcepath);
if (bootclasspath != null)
options.putJavacOption("BOOTCLASSPATH", bootclasspath);
options.setFormatPreferences(new FormatPreferences(formatPrefs));
options.put("compilePolicy", "check");
CommentCatcher catcher = CommentCatcher.create(context);
JavaCompiler compiler = catcher.getCompiler();
List<JCCompilationUnit> roots = new ArrayList<JCCompilationUnit>();
Map<JCCompilationUnit, File> baseMap = new IdentityHashMap<JCCompilationUnit, File>();
compiler.initProcessAnnotations(Collections.singleton(new lombok.javac.apt.LombokProcessor()));
for (File fileToParse : filesToParse) {
@SuppressWarnings("deprecation") JCCompilationUnit unit = compiler.parse(fileToParse.getAbsolutePath());
baseMap.put(unit, fileToBase.get(fileToParse));
roots.add(unit);
}
if (compiler.errorCount() > 0) {
// At least one parse error. No point continuing (a real javac run doesn't either).
return false;
}
for (JCCompilationUnit unit : roots) {
catcher.setComments(unit, new DocCommentIntegrator().integrate(catcher.getComments(unit), unit));
}
com.sun.tools.javac.util.List<JCCompilationUnit> trees = compiler.enterTrees(toJavacList(roots));
JavaCompiler delegate = compiler.processAnnotations(trees);
Object care = callAttributeMethodOnJavaCompiler(delegate, delegate.todo);
callFlowMethodOnJavaCompiler(delegate, care);
FormatPreferences fps = new FormatPreferences(formatPrefs);
for (JCCompilationUnit unit : roots) {
DelombokResult result = new DelombokResult(catcher.getComments(unit), unit, force || options.isChanged(unit), fps);
if (verbose)
feedback.printf("File: %s [%s%s]\n", unit.sourcefile.getName(), result.isChanged() ? "delomboked" : "unchanged", force && !options.isChanged(unit) ? " (forced)" : "");
Writer rawWriter;
if (presetWriter != null)
rawWriter = createUnicodeEscapeWriter(presetWriter);
else if (output == null)
rawWriter = createStandardOutWriter();
else
rawWriter = createFileWriter(output, baseMap.get(unit), unit.sourcefile.toUri());
BufferedWriter writer = new BufferedWriter(rawWriter);
try {
result.print(writer);
} finally {
if (output != null) {
writer.close();
} else {
writer.flush();
}
}
}
delegate.close();
return true;
}
use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project lombok by rzwitserloot.
the class JavacHandlerUtil method copyJavadoc.
/**
* Copies javadoc on one node to the other.
*
* in 'GETTER' copyMode, first a 'GETTER' segment is searched for. If it exists, that will become the javadoc for the 'to' node, and this section is
* stripped out of the 'from' node. If no 'GETTER' segment is found, then the entire javadoc is taken minus any {@code @param} lines and other sections.
* any {@code @return} lines are stripped from 'from'.
*
* in 'SETTER' mode, stripping works similarly to 'GETTER' mode, except {@code param} are copied and stripped from the original and {@code @return} are skipped.
*/
public static void copyJavadoc(JavacNode from, JCTree to, CopyJavadoc copyMode) {
if (copyMode == null)
copyMode = CopyJavadoc.VERBATIM;
try {
JCCompilationUnit cu = ((JCCompilationUnit) from.top().get());
Object dc = Javac.getDocComments(cu);
if (dc instanceof Map) {
copyJavadoc_jdk6_7(from, to, copyMode, dc);
} else if (Javac.instanceOfDocCommentTable(dc)) {
CopyJavadoc_8.copyJavadoc(from, to, copyMode, dc);
}
} catch (Exception ignore) {
}
}
use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project lombok by rzwitserloot.
the class JavacHandlerUtil method unboxAndRemoveAnnotationParameter.
static List<JCAnnotation> unboxAndRemoveAnnotationParameter(JCAnnotation ast, String parameterName, String errorName, JavacNode annotationNode) {
ListBuffer<JCExpression> params = new ListBuffer<JCExpression>();
ListBuffer<JCAnnotation> result = new ListBuffer<JCAnnotation>();
outer: for (JCExpression param : ast.args) {
boolean allowRaw;
String nameOfParam = "value";
JCExpression valueOfParam = null;
if (param instanceof JCAssign) {
JCAssign assign = (JCAssign) param;
if (assign.lhs instanceof JCIdent) {
JCIdent ident = (JCIdent) assign.lhs;
nameOfParam = ident.name.toString();
}
valueOfParam = assign.rhs;
}
/* strip trailing underscores */
{
int lastIdx;
for (lastIdx = nameOfParam.length(); lastIdx > 0; lastIdx--) {
if (nameOfParam.charAt(lastIdx - 1) != '_')
break;
}
allowRaw = lastIdx < nameOfParam.length();
nameOfParam = nameOfParam.substring(0, lastIdx);
}
if (!parameterName.equals(nameOfParam)) {
params.append(param);
continue outer;
}
int endPos = Javac.getEndPosition(param.pos(), (JCCompilationUnit) annotationNode.top().get());
annotationNode.getAst().removeFromDeferredDiagnostics(param.pos, endPos);
if (valueOfParam instanceof JCAnnotation) {
String dummyAnnotationName = ((JCAnnotation) valueOfParam).annotationType.toString();
dummyAnnotationName = dummyAnnotationName.replace("_", "").replace("$", "").replace("x", "").replace("X", "");
if (dummyAnnotationName.length() > 0) {
if (allowRaw) {
result.append((JCAnnotation) valueOfParam);
} else {
addError(errorName, annotationNode);
continue outer;
}
} else {
for (JCExpression expr : ((JCAnnotation) valueOfParam).args) {
if (expr instanceof JCAssign && ((JCAssign) expr).lhs instanceof JCIdent) {
JCIdent id = (JCIdent) ((JCAssign) expr).lhs;
if ("value".equals(id.name.toString())) {
expr = ((JCAssign) expr).rhs;
} else {
addError(errorName, annotationNode);
}
}
if (expr instanceof JCAnnotation) {
result.append((JCAnnotation) expr);
} else if (expr instanceof JCNewArray) {
for (JCExpression expr2 : ((JCNewArray) expr).elems) {
if (expr2 instanceof JCAnnotation) {
result.append((JCAnnotation) expr2);
} else {
addError(errorName, annotationNode);
continue outer;
}
}
} else {
addError(errorName, annotationNode);
continue outer;
}
}
}
} else if (valueOfParam instanceof JCNewArray) {
JCNewArray arr = (JCNewArray) valueOfParam;
if (arr.elems.isEmpty()) {
// Just remove it, this is always fine.
} else if (allowRaw) {
for (JCExpression jce : arr.elems) {
if (jce instanceof JCAnnotation)
result.append((JCAnnotation) jce);
else
addError(errorName, annotationNode);
}
} else {
addError(errorName, annotationNode);
}
} else {
addError(errorName, annotationNode);
}
}
ast.args = params.toList();
return result.toList();
}
Aggregations