/** *Printcommandlinehelp. *@paramoutoutputstream
*/ void usage(PrintStream out) {
out.println("Usage:");
out.println(" java TreePosTest options... files...");
out.println("");
out.println("where options include:");
out.println("-gui Display returns in a GUI viewer");
out.println("-q Quiet: don't report on inapplicable files");
out.println("-v Verbose: report on files as they are being read");
out.println("-t tag Limit checks to tree nodes with this tag");
out.println(" Can be repeated if desired");
out.println("-ef file Exclude file or directory");
out.println("-et tag Exclude tree nodes with given tag name");
out.println("");
out.println("files may be directories or files");
out.println("directories will be scanned recursively");
out.println("non java files, or java files which cannot be parsed, will be ignored");
out.println("");
}
// See CR: 6982992 Tests CheckAttributedTree.java, JavacTreeScannerTest.java, and SourceTreeeScannerTest.java timeout
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Reporter r = new Reporter(pw);
JavacTool tool = JavacTool.create();
StandardJavaFileManager fm = tool.getStandardFileManager(r, null, null);
/** *Readafile. *@paramfilethefiletoberead *@returnthetreeforthecontentofthefile *@throwsIOExceptionifanyIOerrorsoccur *@throwsTreePosTest.ParseExceptionifanyerrorsoccurwhileparsingthefile
*/
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) thrownew ParseException(sw.toString());
Iterator<? extends CompilationUnitTree> iter = trees.iterator(); if (!iter.hasNext()) thrownew Error("no trees found");
JCCompilationUnit t = (JCCompilationUnit) iter.next(); if (iter.hasNext()) thrownew Error("too many trees found"); return t;
}
/** Number of files that have been analyzed. */ int fileCount; /** Number of errors reported. */ int errors; /** Flag: don't report irrelevant files. */ boolean quiet; /** Flag: report files as they are processed. */ boolean verbose; /** Flag: show errors in GUI viewer. */ boolean gui; /** Option: encoding for test files. */
String encoding; /** The GUI viewer for errors. */
Viewer viewer; /** The set of tags for tree nodes to be analyzed; if empty, all tree nodes
* are analyzed. */
Set<String> tags = new HashSet<String>(); /** Set of files and directories to be excluded from analysis. */
Set<File> excludeFiles = new HashSet<File>(); /** Set of tag names to be excluded from analysis. */
Set<String> excludeTags = new HashSet<String>();
@Override publicvoid scan(JCTree tree) { if (tree == null) return;
Info self = new Info(tree, endPosTable); if (check(encl, self)) { // Modifiers nodes are present throughout the tree even where // there is no corresponding source text. // Redundant semicolons in a class definition can cause empty // initializer blocks with no positions. if ((self.tag == MODIFIERS || self.tag == BLOCK)
&& self.pos == NOPOS) { // If pos is NOPOS, so should be the start and end positions
check("start == NOPOS", encl, self, self.start == NOPOS);
check("end == NOPOS", encl, self, self.end == NOPOS);
} else { // For this node, start , pos, and endpos should be all defined
check("start != NOPOS", encl, self, self.start != NOPOS);
check("pos != NOPOS", encl, self, self.pos != NOPOS);
check("end != NOPOS", encl, self, self.end != NOPOS); // The following should normally be ordered // encl.start <= start <= pos <= end <= encl.end // In addition, the position of the enclosing node should be // within this node. // The primary exceptions are for array type nodes, because of the // need to support legacy syntax: // e.g. int a[]; int[] b[]; int f()[] { return null; } // and because of inconsistent nesting of left and right of // array declarations: // e.g. int[][] a = new int[2][]; if (!(encl.tag == REFERENCE && self.tag == ANNOTATED_TYPE)) {
check("encl.start <= start", encl, self, encl.start <= self.start);
}
check("start <= pos", encl, self, self.start <= self.pos); if (!( (self.tag == TYPEARRAY ||
isAnnotatedArray(self.tree))
&& (encl.tag == VARDEF ||
encl.tag == METHODDEF ||
encl.tag == TYPEARRAY ||
isAnnotatedArray(encl.tree))
||
encl.tag == ANNOTATED_TYPE && self.tag == SELECT
||
encl.tag == REFERENCE && self.tag == ANNOTATED_TYPE
)) {
check("encl.pos <= start || end <= encl.pos",
encl, self, encl.pos <= self.start || self.end <= encl.pos);
}
check("pos <= end", encl, self, self.pos <= self.end); if (!( (self.tag == TYPEARRAY || isAnnotatedArray(self.tree)) &&
(encl.tag == TYPEARRAY || isAnnotatedArray(encl.tree))
||
encl.tag == MODIFIERS && self.tag == ANNOTATION
) ) {
check("end <= encl.end", encl, self, self.end <= encl.end);
}
}
}
@Override publicvoid visitMethodDef(JCMethodDecl tree) { // ignore compact record constructors if ((tree.mods.flags & Flags.COMPACT_RECORD_CONSTRUCTOR) == 0) { super.visitMethodDef(tree);
}
}
@Override publicvoid visitVarDef(JCVariableDecl tree) { // enum member declarations are desugared in the parser and have // ill-defined semantics for tree positions, so for now, we // skip the synthesized bits and just check parts which came from // the original source text if ((tree.mods.flags & Flags.ENUM) != 0) {
scan(tree.mods); if (tree.init != null) { if (tree.init.hasTag(NEWCLASS)) {
JCNewClass init = (JCNewClass) tree.init; if (init.args != null && init.args.nonEmpty()) {
scan(init.args);
} if (init.def != null && init.def.defs != null) {
scan(init.def.defs);
}
}
}
} else super.visitVarDef(tree);
}
boolean check(Info encl, Info self) { if (excludeTags.size() > 0) { if (encl != null && excludeTags.contains(getTagName(encl.tag))
|| excludeTags.contains(getTagName(self.tag))) returnfalse;
} return tags.size() == 0 || tags.contains(getTagName(self.tag));
}
void check(String label, Info encl, Info self, boolean ok) { if (!ok) { if (gui) { if (viewer == null)
viewer = new Viewer();
viewer.addEntry(sourcefile, label, encl, self);
}
pack();
setLocationRelativeTo(null); // centered on screen
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/** Show an entry that has been selected. */ privatevoid showEntry(Entry e) { try { // update simple fields
setTitle(e.file.getName());
checkField.setText(e.check);
enclPanel.setInfo(e.encl);
selfPanel.setInfo(e.self); // show file text with highlights
body.setText(e.file.getCharContent(true).toString());
Highlighter highlighter = body.getHighlighter();
highlighter.removeAllHighlights();
addHighlight(highlighter, e.encl, enclColor);
addHighlight(highlighter, e.self, selfColor);
scroll(body, getMinPos(enclPanel.info, selfPanel.info));
} catch (IOException ex) {
body.setText("Cannot read " + e.file.getName() + ": " + e);
}
}
/** Create a test field. */ private JTextField createTextField(int width) {
JTextField f = new JTextField(width);
f.setEditable(false);
f.setBorder(null); return f;
}
/** Add a highlighted region based on the positions in an Info object. */ privatevoid addHighlight(Highlighter h, Info info, Color c) { int start = info.start; int end = info.end; if (start == -1 && end == -1) return; if (start == -1)
start = end; if (end == -1)
end = start; try {
h.addHighlight(info.start, info.end, new DefaultHighlighter.DefaultHighlightPainter(c)); if (info.pos != -1) {
Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
h.addHighlight(info.pos, info.pos + 1, new DefaultHighlighter.DefaultHighlightPainter(c2));
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
/** Get the minimum valid position in a set of info objects. */ privateint getMinPos(Info... values) { int i = Integer.MAX_VALUE; for (Info info: values) { if (info.start >= 0) i = Math.min(i, info.start); if (info.pos >= 0) i = Math.min(i, info.pos); if (info.end >= 0) i = Math.min(i, info.end);
} return (i == Integer.MAX_VALUE) ? 0 : i;
}
/** Set the background on a component. */ private JComponent setBackground(JComponent comp, Color c) {
comp.setOpaque(true);
comp.setBackground(c); return comp;
}
/** Scroll a text area to display a given position near the middle of the visible area. */ privatevoid scroll(final JTextArea t, finalint pos) { // Using invokeLater appears to give text a chance to sort itself out // before the scroll happens; otherwise scrollRectToVisible doesn't work. // Maybe there's a better way to sync with the text...
EventQueue.invokeLater(new Runnable() { publicvoid run() { try {
Rectangle r = t.modelToView(pos);
JScrollPane p = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, t);
r.y = Math.max(0, r.y - p.getHeight() * 2 / 5);
r.height += p.getHeight() * 4 / 5;
t.scrollRectToVisible(r);
} catch (BadLocationException ignore) {
}
}
});
}
/** Object to record information about an error to be displayed. */ privateclass Entry {
Entry(JavaFileObject file, String check, Info encl, Info self) { this.file = file; this.check = check; this.encl = encl; this.self= self;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.