aoqi@0: /*
aoqi@0: * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
aoqi@0: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
aoqi@0: *
aoqi@0: * This code is free software; you can redistribute it and/or modify it
aoqi@0: * under the terms of the GNU General Public License version 2 only, as
aoqi@0: * published by the Free Software Foundation.
aoqi@0: *
aoqi@0: * This code is distributed in the hope that it will be useful, but WITHOUT
aoqi@0: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
aoqi@0: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
aoqi@0: * version 2 for more details (a copy is included in the LICENSE file that
aoqi@0: * accompanied this code).
aoqi@0: *
aoqi@0: * You should have received a copy of the GNU General Public License version
aoqi@0: * 2 along with this work; if not, write to the Free Software Foundation,
aoqi@0: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
aoqi@0: *
aoqi@0: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
aoqi@0: * or visit www.oracle.com if you need additional information or have any
aoqi@0: * questions.
aoqi@0: */
aoqi@0:
aoqi@0: /*
aoqi@0: * @test
aoqi@0: * @bug 6970584 8006694
aoqi@0: * @summary assorted position errors in compiler syntax trees
aoqi@0: * temporarily workaround combo tests are causing time out in several platforms
aoqi@0: * @library ../lib
aoqi@0: * @build JavacTestingAbstractThreadedTest
aoqi@0: * @run main/othervm CheckAttributedTree -q -r -et ERRONEOUS .
aoqi@0: */
aoqi@0:
aoqi@0: // use /othervm to avoid jtreg timeout issues (CODETOOLS-7900047)
aoqi@0: // see JDK-8006746
aoqi@0:
aoqi@0: import java.awt.BorderLayout;
aoqi@0: import java.awt.Color;
aoqi@0: import java.awt.Dimension;
aoqi@0: import java.awt.EventQueue;
aoqi@0: import java.awt.Font;
aoqi@0: import java.awt.GridBagConstraints;
aoqi@0: import java.awt.GridBagLayout;
aoqi@0: import java.awt.Rectangle;
aoqi@0: import java.awt.event.ActionEvent;
aoqi@0: import java.awt.event.ActionListener;
aoqi@0: import java.awt.event.MouseAdapter;
aoqi@0: import java.awt.event.MouseEvent;
aoqi@0: import java.io.File;
aoqi@0: import java.io.IOException;
aoqi@0: import java.io.PrintStream;
aoqi@0: import java.io.PrintWriter;
aoqi@0: import java.io.StringWriter;
aoqi@0: import java.lang.reflect.Field;
aoqi@0: import java.util.ArrayList;
aoqi@0: import java.util.Arrays;
aoqi@0: import java.util.concurrent.atomic.AtomicInteger;
aoqi@0: import java.util.HashSet;
aoqi@0: import java.util.List;
aoqi@0: import java.util.Set;
aoqi@0:
aoqi@0: import javax.lang.model.element.Element;
aoqi@0: import javax.swing.DefaultComboBoxModel;
aoqi@0: import javax.swing.JComboBox;
aoqi@0: import javax.swing.JComponent;
aoqi@0: import javax.swing.JFrame;
aoqi@0: import javax.swing.JLabel;
aoqi@0: import javax.swing.JPanel;
aoqi@0: import javax.swing.JScrollPane;
aoqi@0: import javax.swing.JTextArea;
aoqi@0: import javax.swing.JTextField;
aoqi@0: import javax.swing.SwingUtilities;
aoqi@0: import javax.swing.event.CaretEvent;
aoqi@0: import javax.swing.event.CaretListener;
aoqi@0: import javax.swing.text.BadLocationException;
aoqi@0: import javax.swing.text.DefaultHighlighter;
aoqi@0: import javax.swing.text.Highlighter;
aoqi@0: import javax.tools.Diagnostic;
aoqi@0: import javax.tools.DiagnosticListener;
aoqi@0: import javax.tools.JavaFileObject;
aoqi@0:
aoqi@0: import com.sun.source.tree.CompilationUnitTree;
aoqi@0: import com.sun.source.util.TaskEvent;
aoqi@0: import com.sun.source.util.JavacTask;
aoqi@0: import com.sun.source.util.TaskListener;
aoqi@0: import com.sun.tools.javac.code.Symbol;
aoqi@0: import com.sun.tools.javac.code.Type;
aoqi@0: import com.sun.tools.javac.tree.EndPosTable;
aoqi@0: import com.sun.tools.javac.tree.JCTree;
aoqi@0: import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
aoqi@0: import com.sun.tools.javac.tree.JCTree.JCImport;
aoqi@0: import com.sun.tools.javac.tree.TreeInfo;
aoqi@0: import com.sun.tools.javac.tree.TreeScanner;
aoqi@0: import com.sun.tools.javac.util.Pair;
aoqi@0:
aoqi@0: import static com.sun.tools.javac.tree.JCTree.Tag.*;
aoqi@0:
aoqi@0: /**
aoqi@0: * Utility and test program to check validity of tree positions for tree nodes.
aoqi@0: * The program can be run standalone, or as a jtreg test. In standalone mode,
aoqi@0: * errors can be displayed in a gui viewer. For info on command line args,
aoqi@0: * run program with no args.
aoqi@0: *
aoqi@0: *
aoqi@0: * jtreg: Note that by using the -r switch in the test description below, this test
aoqi@0: * will process all java files in the langtools/test directory, thus implicitly
aoqi@0: * covering any new language features that may be tested in this test suite.
aoqi@0: */
aoqi@0:
aoqi@0: public class CheckAttributedTree extends JavacTestingAbstractThreadedTest {
aoqi@0: /**
aoqi@0: * Main entry point.
aoqi@0: * If test.src is set, program runs in jtreg mode, and will throw an Error
aoqi@0: * if any errors arise, otherwise System.exit will be used, unless the gui
aoqi@0: * viewer is being used. In jtreg mode, the default base directory for file
aoqi@0: * args is the value of ${test.src}. In jtreg mode, the -r option can be
aoqi@0: * given to change the default base directory to the root test directory.
aoqi@0: */
aoqi@0: public static void main(String... args) throws Exception {
aoqi@0: String testSrc = System.getProperty("test.src");
aoqi@0: File baseDir = (testSrc == null) ? null : new File(testSrc);
aoqi@0: throwAssertionOnError = false;
aoqi@0: boolean ok = new CheckAttributedTree().run(baseDir, args);
aoqi@0: if (!ok) {
aoqi@0: if (testSrc != null) // jtreg mode
aoqi@0: throw new Error("failed");
aoqi@0: else
aoqi@0: System.exit(1);
aoqi@0: }
aoqi@0: }
aoqi@0:
aoqi@0: /**
aoqi@0: * Run the program. A base directory can be provided for file arguments.
aoqi@0: * In jtreg mode, the -r option can be given to change the default base
aoqi@0: * directory to the test root directory. For other options, see usage().
aoqi@0: * @param baseDir base directory for any file arguments.
aoqi@0: * @param args command line args
aoqi@0: * @return true if successful or in gui mode
aoqi@0: */
aoqi@0: boolean run(File baseDir, String... args) throws Exception {
aoqi@0: if (args.length == 0) {
aoqi@0: usage(System.out);
aoqi@0: return true;
aoqi@0: }
aoqi@0:
aoqi@0: List files = new ArrayList();
aoqi@0: for (int i = 0; i < args.length; i++) {
aoqi@0: String arg = args[i];
aoqi@0: if (arg.equals("-encoding") && i + 1 < args.length)
aoqi@0: encoding = args[++i];
aoqi@0: else if (arg.equals("-gui"))
aoqi@0: gui = true;
aoqi@0: else if (arg.equals("-q"))
aoqi@0: quiet = true;
aoqi@0: else if (arg.equals("-v")) {
aoqi@0: verbose = true;
aoqi@0: printAll = true;
aoqi@0: }
aoqi@0: else if (arg.equals("-t") && i + 1 < args.length)
aoqi@0: tags.add(args[++i]);
aoqi@0: else if (arg.equals("-ef") && i + 1 < args.length)
aoqi@0: excludeFiles.add(new File(baseDir, args[++i]));
aoqi@0: else if (arg.equals("-et") && i + 1 < args.length)
aoqi@0: excludeTags.add(args[++i]);
aoqi@0: else if (arg.equals("-r")) {
aoqi@0: if (excludeFiles.size() > 0)
aoqi@0: throw new Error("-r must be used before -ef");
aoqi@0: File d = baseDir;
aoqi@0: while (!new File(d, "TEST.ROOT").exists()) {
aoqi@0: if (d == null)
aoqi@0: throw new Error("cannot find TEST.ROOT");
aoqi@0: d = d.getParentFile();
aoqi@0: }
aoqi@0: baseDir = d;
aoqi@0: }
aoqi@0: else if (arg.startsWith("-"))
aoqi@0: throw new Error("unknown option: " + arg);
aoqi@0: else {
aoqi@0: while (i < args.length)
aoqi@0: files.add(new File(baseDir, args[i++]));
aoqi@0: }
aoqi@0: }
aoqi@0:
aoqi@0: for (File file: files) {
aoqi@0: if (file.exists())
aoqi@0: test(file);
aoqi@0: else
aoqi@0: error("File not found: " + file);
aoqi@0: }
aoqi@0:
aoqi@0: if (fileCount.get() != 1)
aoqi@0: errWriter.println(fileCount + " files read");
aoqi@0: checkAfterExec(false);
aoqi@0:
aoqi@0: return (gui || errCount.get() == 0);
aoqi@0: }
aoqi@0:
aoqi@0: /**
aoqi@0: * Print command line help.
aoqi@0: * @param out output stream
aoqi@0: */
aoqi@0: void usage(PrintStream out) {
aoqi@0: out.println("Usage:");
aoqi@0: out.println(" java CheckAttributedTree options... files...");
aoqi@0: out.println("");
aoqi@0: out.println("where options include:");
aoqi@0: out.println("-q Quiet: don't report on inapplicable files");
aoqi@0: out.println("-gui Display returns in a GUI viewer");
aoqi@0: out.println("-v Verbose: report on files as they are being read");
aoqi@0: out.println("-t tag Limit checks to tree nodes with this tag");
aoqi@0: out.println(" Can be repeated if desired");
aoqi@0: out.println("-ef file Exclude file or directory");
aoqi@0: out.println("-et tag Exclude tree nodes with given tag name");
aoqi@0: out.println("");
aoqi@0: out.println("files may be directories or files");
aoqi@0: out.println("directories will be scanned recursively");
aoqi@0: out.println("non java files, or java files which cannot be parsed, will be ignored");
aoqi@0: out.println("");
aoqi@0: }
aoqi@0:
aoqi@0: /**
aoqi@0: * Test a file. If the file is a directory, it will be recursively scanned
aoqi@0: * for java files.
aoqi@0: * @param file the file or directory to test
aoqi@0: */
aoqi@0: void test(final File file) {
aoqi@0: if (excludeFiles.contains(file)) {
aoqi@0: if (!quiet)
aoqi@0: error("File " + file + " excluded");
aoqi@0: return;
aoqi@0: }
aoqi@0:
aoqi@0: if (file.isDirectory()) {
aoqi@0: for (File f: file.listFiles()) {
aoqi@0: test(f);
aoqi@0: }
aoqi@0: return;
aoqi@0: }
aoqi@0:
aoqi@0: if (file.isFile() && file.getName().endsWith(".java")) {
aoqi@0: pool.execute(new Runnable() {
aoqi@0: @Override
aoqi@0: public void run() {
aoqi@0: try {
aoqi@0: if (verbose)
aoqi@0: errWriter.println(file);
aoqi@0: fileCount.incrementAndGet();
aoqi@0: NPETester p = new NPETester();
aoqi@0: p.test(read(file));
aoqi@0: } catch (AttributionException e) {
aoqi@0: if (!quiet) {
aoqi@0: error("Error attributing " + file + "\n" + e.getMessage());
aoqi@0: }
aoqi@0: } catch (IOException e) {
aoqi@0: error("Error reading " + file + ": " + e);
aoqi@0: }
aoqi@0: }
aoqi@0: });
aoqi@0: }
aoqi@0:
aoqi@0: if (!quiet)
aoqi@0: error("File " + file + " ignored");
aoqi@0: }
aoqi@0:
aoqi@0: // See CR: 6982992 Tests CheckAttributedTree.java, JavacTreeScannerTest.java, and SourceTreeeScannerTest.java timeout
aoqi@0: StringWriter sw = new StringWriter();
aoqi@0: PrintWriter pw = new PrintWriter(sw);
aoqi@0: Reporter r = new Reporter(pw);
aoqi@0:
aoqi@0: /**
aoqi@0: * Read a file.
aoqi@0: * @param file the file to be read
aoqi@0: * @return the tree for the content of the file
aoqi@0: * @throws IOException if any IO errors occur
aoqi@0: * @throws TreePosTest.ParseException if any errors occur while parsing the file
aoqi@0: */
aoqi@0: List> read(File file) throws IOException, AttributionException {
aoqi@0: r.errors = 0;
aoqi@0: Iterable extends JavaFileObject> files = fm.get().getJavaFileObjects(file);
aoqi@0: String[] opts = { "-XDshouldStopPolicy=ATTR", "-XDverboseCompilePolicy" };
aoqi@0: JavacTask task = (JavacTask)comp.getTask(pw, fm.get(), r, Arrays.asList(opts), null, files);
aoqi@0: final List analyzedElems = new ArrayList<>();
aoqi@0: task.setTaskListener(new TaskListener() {
aoqi@0: public void started(TaskEvent e) {
aoqi@0: if (e.getKind() == TaskEvent.Kind.ANALYZE)
aoqi@0: analyzedElems.add(e.getTypeElement());
aoqi@0: }
aoqi@0: public void finished(TaskEvent e) { }
aoqi@0: });
aoqi@0:
aoqi@0: try {
aoqi@0: Iterable extends CompilationUnitTree> trees = task.parse();
aoqi@0: task.analyze();
aoqi@0: List> res = new ArrayList<>();
aoqi@0: //System.out.println("Try to add pairs. Elems are " + analyzedElems);
aoqi@0: for (CompilationUnitTree t : trees) {
aoqi@0: JCCompilationUnit cu = (JCCompilationUnit)t;
aoqi@0: for (JCTree def : cu.defs) {
aoqi@0: if (def.hasTag(CLASSDEF) &&
aoqi@0: analyzedElems.contains(((JCTree.JCClassDecl)def).sym)) {
aoqi@0: //System.out.println("Adding pair...");
aoqi@0: res.add(new Pair<>(cu, def));
aoqi@0: }
aoqi@0: }
aoqi@0: }
aoqi@0: return res;
aoqi@0: }
aoqi@0: catch (Throwable t) {
aoqi@0: throw new AttributionException("Exception while attributing file: " + file);
aoqi@0: }
aoqi@0: }
aoqi@0:
aoqi@0: /**
aoqi@0: * Report an error. When the program is complete, the program will either
aoqi@0: * exit or throw an Error if any errors have been reported.
aoqi@0: * @param msg the error message
aoqi@0: */
aoqi@0: void error(String msg) {
aoqi@0: System.err.println(msg);
aoqi@0: errCount.incrementAndGet();
aoqi@0: }
aoqi@0:
aoqi@0: /** Flag: don't report irrelevant files. */
aoqi@0: boolean quiet;
aoqi@0: /** Flag: show errors in GUI viewer. */
aoqi@0: boolean gui;
aoqi@0: /** The GUI viewer for errors. */
aoqi@0: Viewer viewer;
aoqi@0: /** Flag: report files as they are processed. */
aoqi@0: boolean verbose;
aoqi@0: /** Option: encoding for test files. */
aoqi@0: String encoding;
aoqi@0: /** The set of tags for tree nodes to be analyzed; if empty, all tree nodes
aoqi@0: * are analyzed. */
aoqi@0: Set tags = new HashSet();
aoqi@0: /** Set of files and directories to be excluded from analysis. */
aoqi@0: Set excludeFiles = new HashSet();
aoqi@0: /** Set of tag names to be excluded from analysis. */
aoqi@0: Set excludeTags = new HashSet();
aoqi@0: /** Utility class for trees */
aoqi@0: TreeUtil treeUtil = new TreeUtil();
aoqi@0:
aoqi@0: /**
aoqi@0: * Main class for testing assertions concerning types/symbol
aoqi@0: * left uninitialized after attribution
aoqi@0: */
aoqi@0: private class NPETester extends TreeScanner {
aoqi@0: void test(List> trees) {
aoqi@0: for (Pair p : trees) {
aoqi@0: sourcefile = p.fst.sourcefile;
aoqi@0: endPosTable = p.fst.endPositions;
aoqi@0: encl = new Info(p.snd, endPosTable);
aoqi@0: p.snd.accept(this);
aoqi@0: }
aoqi@0: }
aoqi@0:
aoqi@0: @Override
aoqi@0: public void scan(JCTree tree) {
aoqi@0: if (tree == null ||
aoqi@0: excludeTags.contains(treeUtil.nameFromTag(tree.getTag()))) {
aoqi@0: return;
aoqi@0: }
aoqi@0:
aoqi@0: Info self = new Info(tree, endPosTable);
aoqi@0: if (mandatoryType(tree)) {
aoqi@0: check(tree.type != null,
aoqi@0: "'null' field 'type' found in tree ", self);
aoqi@0: if (tree.type==null)
aoqi@0: new Throwable().printStackTrace();
aoqi@0: }
aoqi@0:
aoqi@0: Field errField = checkFields(tree);
aoqi@0: if (errField!=null) {
aoqi@0: check(false,
aoqi@0: "'null' field '" + errField.getName() + "' found in tree ", self);
aoqi@0: }
aoqi@0:
aoqi@0: Info prevEncl = encl;
aoqi@0: encl = self;
aoqi@0: tree.accept(this);
aoqi@0: encl = prevEncl;
aoqi@0: }
aoqi@0:
aoqi@0: private boolean mandatoryType(JCTree that) {
aoqi@0: return that instanceof JCTree.JCExpression ||
aoqi@0: that.hasTag(VARDEF) ||
aoqi@0: that.hasTag(METHODDEF) ||
aoqi@0: that.hasTag(CLASSDEF);
aoqi@0: }
aoqi@0:
aoqi@0: private final List excludedFields = Arrays.asList("varargsElement", "targetType");
aoqi@0:
aoqi@0: void check(boolean ok, String label, Info self) {
aoqi@0: if (!ok) {
aoqi@0: if (gui) {
aoqi@0: if (viewer == null)
aoqi@0: viewer = new Viewer();
aoqi@0: viewer.addEntry(sourcefile, label, encl, self);
aoqi@0: }
aoqi@0: error(label + self.toString() + " encl: " + encl.toString() +
aoqi@0: " in file: " + sourcefile + " " + self.tree);
aoqi@0: }
aoqi@0: }
aoqi@0:
aoqi@0: Field checkFields(JCTree t) {
aoqi@0: List fieldsToCheck = treeUtil.getFieldsOfType(t,
aoqi@0: excludedFields,
aoqi@0: Symbol.class,
aoqi@0: Type.class);
aoqi@0: for (Field f : fieldsToCheck) {
aoqi@0: try {
aoqi@0: if (f.get(t) == null) {
aoqi@0: return f;
aoqi@0: }
aoqi@0: }
aoqi@0: catch (IllegalAccessException e) {
aoqi@0: System.err.println("Cannot read field: " + f);
aoqi@0: //swallow it
aoqi@0: }
aoqi@0: }
aoqi@0: return null;
aoqi@0: }
aoqi@0:
aoqi@0: @Override
aoqi@0: public void visitImport(JCImport tree) { }
aoqi@0:
aoqi@0: @Override
aoqi@0: public void visitTopLevel(JCCompilationUnit tree) {
aoqi@0: scan(tree.defs);
aoqi@0: }
aoqi@0:
aoqi@0: JavaFileObject sourcefile;
aoqi@0: EndPosTable endPosTable;
aoqi@0: Info encl;
aoqi@0: }
aoqi@0:
aoqi@0: /**
aoqi@0: * Utility class providing easy access to position and other info for a tree node.
aoqi@0: */
aoqi@0: private class Info {
aoqi@0: Info() {
aoqi@0: tree = null;
aoqi@0: tag = ERRONEOUS;
aoqi@0: start = 0;
aoqi@0: pos = 0;
aoqi@0: end = Integer.MAX_VALUE;
aoqi@0: }
aoqi@0:
aoqi@0: Info(JCTree tree, EndPosTable endPosTable) {
aoqi@0: this.tree = tree;
aoqi@0: tag = tree.getTag();
aoqi@0: start = TreeInfo.getStartPos(tree);
aoqi@0: pos = tree.pos;
aoqi@0: end = TreeInfo.getEndPos(tree, endPosTable);
aoqi@0: }
aoqi@0:
aoqi@0: @Override
aoqi@0: public String toString() {
aoqi@0: return treeUtil.nameFromTag(tree.getTag()) + "[start:" + start + ",pos:" + pos + ",end:" + end + "]";
aoqi@0: }
aoqi@0:
aoqi@0: final JCTree tree;
aoqi@0: final JCTree.Tag tag;
aoqi@0: final int start;
aoqi@0: final int pos;
aoqi@0: final int end;
aoqi@0: }
aoqi@0:
aoqi@0: /**
aoqi@0: * Names for tree tags.
aoqi@0: */
aoqi@0: private static class TreeUtil {
aoqi@0: String nameFromTag(JCTree.Tag tag) {
aoqi@0: String name = tag.name();
aoqi@0: return (name == null) ? "??" : name;
aoqi@0: }
aoqi@0:
aoqi@0: List getFieldsOfType(JCTree t, List excludeNames, Class>... types) {
aoqi@0: List buf = new ArrayList();
aoqi@0: for (Field f : t.getClass().getDeclaredFields()) {
aoqi@0: if (!excludeNames.contains(f.getName())) {
aoqi@0: for (Class> type : types) {
aoqi@0: if (type.isAssignableFrom(f.getType())) {
aoqi@0: f.setAccessible(true);
aoqi@0: buf.add(f);
aoqi@0: break;
aoqi@0: }
aoqi@0: }
aoqi@0: }
aoqi@0: }
aoqi@0: return buf;
aoqi@0: }
aoqi@0: }
aoqi@0:
aoqi@0: /**
aoqi@0: * Thrown when errors are found parsing a java file.
aoqi@0: */
aoqi@0: private static class ParseException extends Exception {
aoqi@0: ParseException(String msg) {
aoqi@0: super(msg);
aoqi@0: }
aoqi@0: }
aoqi@0:
aoqi@0: private static class AttributionException extends Exception {
aoqi@0: AttributionException(String msg) {
aoqi@0: super(msg);
aoqi@0: }
aoqi@0: }
aoqi@0:
aoqi@0: /**
aoqi@0: * DiagnosticListener to report diagnostics and count any errors that occur.
aoqi@0: */
aoqi@0: private static class Reporter implements DiagnosticListener {
aoqi@0: Reporter(PrintWriter out) {
aoqi@0: this.out = out;
aoqi@0: }
aoqi@0:
aoqi@0: public void report(Diagnostic extends JavaFileObject> diagnostic) {
aoqi@0: //out.println(diagnostic);
aoqi@0: switch (diagnostic.getKind()) {
aoqi@0: case ERROR:
aoqi@0: errors++;
aoqi@0: }
aoqi@0: }
aoqi@0: int errors;
aoqi@0: PrintWriter out;
aoqi@0: }
aoqi@0:
aoqi@0: /**
aoqi@0: * GUI viewer for issues found by TreePosTester. The viewer provides a drop
aoqi@0: * down list for selecting error conditions, a header area providing details
aoqi@0: * about an error, and a text area with the ranges of text highlighted as
aoqi@0: * appropriate.
aoqi@0: */
aoqi@0: private class Viewer extends JFrame {
aoqi@0: /**
aoqi@0: * Create a viewer.
aoqi@0: */
aoqi@0: Viewer() {
aoqi@0: initGUI();
aoqi@0: }
aoqi@0:
aoqi@0: /**
aoqi@0: * Add another entry to the list of errors.
aoqi@0: * @param file The file containing the error
aoqi@0: * @param check The condition that was being tested, and which failed
aoqi@0: * @param encl the enclosing tree node
aoqi@0: * @param self the tree node containing the error
aoqi@0: */
aoqi@0: void addEntry(JavaFileObject file, String check, Info encl, Info self) {
aoqi@0: Entry e = new Entry(file, check, encl, self);
aoqi@0: DefaultComboBoxModel m = (DefaultComboBoxModel) entries.getModel();
aoqi@0: m.addElement(e);
aoqi@0: if (m.getSize() == 1)
aoqi@0: entries.setSelectedItem(e);
aoqi@0: }
aoqi@0:
aoqi@0: /**
aoqi@0: * Initialize the GUI window.
aoqi@0: */
aoqi@0: private void initGUI() {
aoqi@0: JPanel head = new JPanel(new GridBagLayout());
aoqi@0: GridBagConstraints lc = new GridBagConstraints();
aoqi@0: GridBagConstraints fc = new GridBagConstraints();
aoqi@0: fc.anchor = GridBagConstraints.WEST;
aoqi@0: fc.fill = GridBagConstraints.HORIZONTAL;
aoqi@0: fc.gridwidth = GridBagConstraints.REMAINDER;
aoqi@0:
aoqi@0: entries = new JComboBox();
aoqi@0: entries.addActionListener(new ActionListener() {
aoqi@0: public void actionPerformed(ActionEvent e) {
aoqi@0: showEntry((Entry) entries.getSelectedItem());
aoqi@0: }
aoqi@0: });
aoqi@0: fc.insets.bottom = 10;
aoqi@0: head.add(entries, fc);
aoqi@0: fc.insets.bottom = 0;
aoqi@0: head.add(new JLabel("check:"), lc);
aoqi@0: head.add(checkField = createTextField(80), fc);
aoqi@0: fc.fill = GridBagConstraints.NONE;
aoqi@0: head.add(setBackground(new JLabel("encl:"), enclColor), lc);
aoqi@0: head.add(enclPanel = new InfoPanel(), fc);
aoqi@0: head.add(setBackground(new JLabel("self:"), selfColor), lc);
aoqi@0: head.add(selfPanel = new InfoPanel(), fc);
aoqi@0: add(head, BorderLayout.NORTH);
aoqi@0:
aoqi@0: body = new JTextArea();
aoqi@0: body.setFont(Font.decode(Font.MONOSPACED));
aoqi@0: body.addCaretListener(new CaretListener() {
aoqi@0: public void caretUpdate(CaretEvent e) {
aoqi@0: int dot = e.getDot();
aoqi@0: int mark = e.getMark();
aoqi@0: if (dot == mark)
aoqi@0: statusText.setText("dot: " + dot);
aoqi@0: else
aoqi@0: statusText.setText("dot: " + dot + ", mark:" + mark);
aoqi@0: }
aoqi@0: });
aoqi@0: JScrollPane p = new JScrollPane(body,
aoqi@0: JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
aoqi@0: JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
aoqi@0: p.setPreferredSize(new Dimension(640, 480));
aoqi@0: add(p, BorderLayout.CENTER);
aoqi@0:
aoqi@0: statusText = createTextField(80);
aoqi@0: add(statusText, BorderLayout.SOUTH);
aoqi@0:
aoqi@0: pack();
aoqi@0: setLocationRelativeTo(null); // centered on screen
aoqi@0: setVisible(true);
aoqi@0: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aoqi@0: }
aoqi@0:
aoqi@0: /** Show an entry that has been selected. */
aoqi@0: private void showEntry(Entry e) {
aoqi@0: try {
aoqi@0: // update simple fields
aoqi@0: setTitle(e.file.getName());
aoqi@0: checkField.setText(e.check);
aoqi@0: enclPanel.setInfo(e.encl);
aoqi@0: selfPanel.setInfo(e.self);
aoqi@0: // show file text with highlights
aoqi@0: body.setText(e.file.getCharContent(true).toString());
aoqi@0: Highlighter highlighter = body.getHighlighter();
aoqi@0: highlighter.removeAllHighlights();
aoqi@0: addHighlight(highlighter, e.encl, enclColor);
aoqi@0: addHighlight(highlighter, e.self, selfColor);
aoqi@0: scroll(body, getMinPos(enclPanel.info, selfPanel.info));
aoqi@0: } catch (IOException ex) {
aoqi@0: body.setText("Cannot read " + e.file.getName() + ": " + e);
aoqi@0: }
aoqi@0: }
aoqi@0:
aoqi@0: /** Create a test field. */
aoqi@0: private JTextField createTextField(int width) {
aoqi@0: JTextField f = new JTextField(width);
aoqi@0: f.setEditable(false);
aoqi@0: f.setBorder(null);
aoqi@0: return f;
aoqi@0: }
aoqi@0:
aoqi@0: /** Add a highlighted region based on the positions in an Info object. */
aoqi@0: private void addHighlight(Highlighter h, Info info, Color c) {
aoqi@0: int start = info.start;
aoqi@0: int end = info.end;
aoqi@0: if (start == -1 && end == -1)
aoqi@0: return;
aoqi@0: if (start == -1)
aoqi@0: start = end;
aoqi@0: if (end == -1)
aoqi@0: end = start;
aoqi@0: try {
aoqi@0: h.addHighlight(info.start, info.end,
aoqi@0: new DefaultHighlighter.DefaultHighlightPainter(c));
aoqi@0: if (info.pos != -1) {
aoqi@0: Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
aoqi@0: h.addHighlight(info.pos, info.pos + 1,
aoqi@0: new DefaultHighlighter.DefaultHighlightPainter(c2));
aoqi@0: }
aoqi@0: } catch (BadLocationException e) {
aoqi@0: e.printStackTrace();
aoqi@0: }
aoqi@0: }
aoqi@0:
aoqi@0: /** Get the minimum valid position in a set of info objects. */
aoqi@0: private int getMinPos(Info... values) {
aoqi@0: int i = Integer.MAX_VALUE;
aoqi@0: for (Info info: values) {
aoqi@0: if (info.start >= 0) i = Math.min(i, info.start);
aoqi@0: if (info.pos >= 0) i = Math.min(i, info.pos);
aoqi@0: if (info.end >= 0) i = Math.min(i, info.end);
aoqi@0: }
aoqi@0: return (i == Integer.MAX_VALUE) ? 0 : i;
aoqi@0: }
aoqi@0:
aoqi@0: /** Set the background on a component. */
aoqi@0: private JComponent setBackground(JComponent comp, Color c) {
aoqi@0: comp.setOpaque(true);
aoqi@0: comp.setBackground(c);
aoqi@0: return comp;
aoqi@0: }
aoqi@0:
aoqi@0: /** Scroll a text area to display a given position near the middle of the visible area. */
aoqi@0: private void scroll(final JTextArea t, final int pos) {
aoqi@0: // Using invokeLater appears to give text a chance to sort itself out
aoqi@0: // before the scroll happens; otherwise scrollRectToVisible doesn't work.
aoqi@0: // Maybe there's a better way to sync with the text...
aoqi@0: EventQueue.invokeLater(new Runnable() {
aoqi@0: public void run() {
aoqi@0: try {
aoqi@0: Rectangle r = t.modelToView(pos);
aoqi@0: JScrollPane p = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, t);
aoqi@0: r.y = Math.max(0, r.y - p.getHeight() * 2 / 5);
aoqi@0: r.height += p.getHeight() * 4 / 5;
aoqi@0: t.scrollRectToVisible(r);
aoqi@0: } catch (BadLocationException ignore) {
aoqi@0: }
aoqi@0: }
aoqi@0: });
aoqi@0: }
aoqi@0:
aoqi@0: private JComboBox entries;
aoqi@0: private JTextField checkField;
aoqi@0: private InfoPanel enclPanel;
aoqi@0: private InfoPanel selfPanel;
aoqi@0: private JTextArea body;
aoqi@0: private JTextField statusText;
aoqi@0:
aoqi@0: private Color selfColor = new Color(0.f, 1.f, 0.f, 0.2f); // 20% green
aoqi@0: private Color enclColor = new Color(1.f, 0.f, 0.f, 0.2f); // 20% red
aoqi@0:
aoqi@0: /** Panel to display an Info object. */
aoqi@0: private class InfoPanel extends JPanel {
aoqi@0: InfoPanel() {
aoqi@0: add(tagName = createTextField(20));
aoqi@0: add(new JLabel("start:"));
aoqi@0: add(addListener(start = createTextField(6)));
aoqi@0: add(new JLabel("pos:"));
aoqi@0: add(addListener(pos = createTextField(6)));
aoqi@0: add(new JLabel("end:"));
aoqi@0: add(addListener(end = createTextField(6)));
aoqi@0: }
aoqi@0:
aoqi@0: void setInfo(Info info) {
aoqi@0: this.info = info;
aoqi@0: tagName.setText(treeUtil.nameFromTag(info.tag));
aoqi@0: start.setText(String.valueOf(info.start));
aoqi@0: pos.setText(String.valueOf(info.pos));
aoqi@0: end.setText(String.valueOf(info.end));
aoqi@0: }
aoqi@0:
aoqi@0: JTextField addListener(final JTextField f) {
aoqi@0: f.addMouseListener(new MouseAdapter() {
aoqi@0: @Override
aoqi@0: public void mouseClicked(MouseEvent e) {
aoqi@0: body.setCaretPosition(Integer.valueOf(f.getText()));
aoqi@0: body.getCaret().setVisible(true);
aoqi@0: }
aoqi@0: });
aoqi@0: return f;
aoqi@0: }
aoqi@0:
aoqi@0: Info info;
aoqi@0: JTextField tagName;
aoqi@0: JTextField start;
aoqi@0: JTextField pos;
aoqi@0: JTextField end;
aoqi@0: }
aoqi@0:
aoqi@0: /** Object to record information about an error to be displayed. */
aoqi@0: private class Entry {
aoqi@0: Entry(JavaFileObject file, String check, Info encl, Info self) {
aoqi@0: this.file = file;
aoqi@0: this.check = check;
aoqi@0: this.encl = encl;
aoqi@0: this.self= self;
aoqi@0: }
aoqi@0:
aoqi@0: @Override
aoqi@0: public String toString() {
aoqi@0: return file.getName() + " " + check + " " + getMinPos(encl, self);
aoqi@0: }
aoqi@0:
aoqi@0: final JavaFileObject file;
aoqi@0: final String check;
aoqi@0: final Info encl;
aoqi@0: final Info self;
aoqi@0: }
aoqi@0: }
aoqi@0:
aoqi@0: /** Number of files that have been analyzed. */
aoqi@0: static AtomicInteger fileCount = new AtomicInteger();
aoqi@0:
aoqi@0: }