langtools/test/tools/javac/treepostests/TreePosTest.java
changeset 4870 a132763160d7
child 4874 67e82eb7b395
equal deleted inserted replaced
4869:0dc780b4fcf3 4870:a132763160d7
       
     1 /*
       
     2  * Copyright 2010 Sun Microsystems, Inc.  All Rights Reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.
       
     8  *
       
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    12  * version 2 for more details (a copy is included in the LICENSE file that
       
    13  * accompanied this code).
       
    14  *
       
    15  * You should have received a copy of the GNU General Public License version
       
    16  * 2 along with this work; if not, write to the Free Software Foundation,
       
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    18  *
       
    19  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
       
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
       
    21  * have any questions.
       
    22  */
       
    23 
       
    24 import java.awt.BorderLayout;
       
    25 import java.awt.Color;
       
    26 import java.awt.Dimension;
       
    27 import java.awt.EventQueue;
       
    28 import java.awt.Font;
       
    29 import java.awt.GridBagConstraints;
       
    30 import java.awt.GridBagLayout;
       
    31 import java.awt.Rectangle;
       
    32 import java.awt.event.ActionEvent;
       
    33 import java.awt.event.ActionListener;
       
    34 import java.awt.event.MouseAdapter;
       
    35 import java.awt.event.MouseEvent;
       
    36 import java.io.File;
       
    37 import java.io.IOException;
       
    38 import java.io.PrintStream;
       
    39 import java.io.PrintWriter;
       
    40 import java.io.StringWriter;
       
    41 import java.lang.reflect.Field;
       
    42 import java.lang.reflect.Modifier;
       
    43 import java.nio.charset.Charset;
       
    44 import java.util.ArrayList;
       
    45 import java.util.Collections;
       
    46 import java.util.HashMap;
       
    47 import java.util.HashSet;
       
    48 import java.util.Iterator;
       
    49 import java.util.List;
       
    50 import java.util.Map;
       
    51 import java.util.Set;
       
    52 import javax.swing.DefaultComboBoxModel;
       
    53 import javax.swing.JComboBox;
       
    54 import javax.swing.JComponent;
       
    55 import javax.swing.JFrame;
       
    56 import javax.swing.JLabel;
       
    57 import javax.swing.JPanel;
       
    58 import javax.swing.JScrollPane;
       
    59 import javax.swing.JTextArea;
       
    60 import javax.swing.JTextField;
       
    61 import javax.swing.SwingUtilities;
       
    62 import javax.swing.event.CaretEvent;
       
    63 import javax.swing.event.CaretListener;
       
    64 import javax.swing.text.BadLocationException;
       
    65 import javax.swing.text.DefaultHighlighter;
       
    66 import javax.swing.text.Highlighter;
       
    67 import javax.tools.Diagnostic;
       
    68 import javax.tools.DiagnosticListener;
       
    69 import javax.tools.JavaFileObject;
       
    70 import javax.tools.StandardJavaFileManager;
       
    71 
       
    72 import com.sun.source.tree.CompilationUnitTree;
       
    73 import com.sun.source.util.JavacTask;
       
    74 import com.sun.tools.javac.api.JavacTool;
       
    75 import com.sun.tools.javac.code.Flags;
       
    76 import com.sun.tools.javac.tree.JCTree;
       
    77 import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
       
    78 import com.sun.tools.javac.tree.JCTree.JCNewClass;
       
    79 import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
       
    80 import com.sun.tools.javac.tree.TreeInfo;
       
    81 import com.sun.tools.javac.tree.TreeScanner;
       
    82 
       
    83 import static com.sun.tools.javac.util.Position.NOPOS;
       
    84 
       
    85 /**
       
    86  * Utility and test program to check validity of tree positions for tree nodes.
       
    87  * The program can be run standalone, or as a jtreg test.  In standalone mode,
       
    88  * errors can be displayed in a gui viewer. For info on command line args,
       
    89  * run program with no args.
       
    90  *
       
    91  * <p>
       
    92  * jtreg: Note that by using the -r switch in the test description below, this test
       
    93  * will process all java files in the langtools/test directory, thus implicitly
       
    94  * covering any new language features that may be tested in this test suite.
       
    95  */
       
    96 
       
    97 /*
       
    98  * @test
       
    99  * @bug 6919889
       
   100  * @summary assorted position errors in compiler syntax trees
       
   101  * @run main TreePosTest -q -r -ef ./tools/javac/typeAnnotations .
       
   102  */
       
   103 public class TreePosTest {
       
   104     /**
       
   105      * Main entry point.
       
   106      * If test.src is set, program runs in jtreg mode, and will throw an Error
       
   107      * if any errors arise, otherwise System.exit will be used, unless the gui
       
   108      * viewer is being used. In jtreg mode, the default base directory for file
       
   109      * args is the value of ${test.src}. In jtreg mode, the -r option can be
       
   110      * given to change the default base directory to the root test directory.
       
   111      */
       
   112     public static void main(String... args) {
       
   113         String testSrc = System.getProperty("test.src");
       
   114         File baseDir = (testSrc == null) ? null : new File(testSrc);
       
   115         boolean ok = new TreePosTest().run(baseDir, args);
       
   116         if (!ok) {
       
   117             if (testSrc != null)  // jtreg mode
       
   118                 throw new Error("failed");
       
   119             else
       
   120                 System.exit(1);
       
   121         }
       
   122     }
       
   123 
       
   124     /**
       
   125      * Run the program. A base directory can be provided for file arguments.
       
   126      * In jtreg mode, the -r option can be given to change the default base
       
   127      * directory to the test root directory. For other options, see usage().
       
   128      * @param baseDir base directory for any file arguments.
       
   129      * @param args command line args
       
   130      * @return true if successful or in gui mode
       
   131      */
       
   132     boolean run(File baseDir, String... args) {
       
   133         if (args.length == 0) {
       
   134             usage(System.out);
       
   135             return true;
       
   136         }
       
   137 
       
   138         List<File> files = new ArrayList<File>();
       
   139         for (int i = 0; i < args.length; i++) {
       
   140             String arg = args[i];
       
   141             if (arg.equals("-encoding") && i + 1 < args.length)
       
   142                 encoding = args[++i];
       
   143             else if (arg.equals("-gui"))
       
   144                 gui = true;
       
   145             else if (arg.equals("-q"))
       
   146                 quiet = true;
       
   147             else if (arg.equals("-v"))
       
   148                 verbose = true;
       
   149             else if (arg.equals("-t") && i + 1 < args.length)
       
   150                 tags.add(args[++i]);
       
   151             else if (arg.equals("-ef") && i + 1 < args.length)
       
   152                 excludeFiles.add(new File(baseDir, args[++i]));
       
   153             else if (arg.equals("-r")) {
       
   154                 if (excludeFiles.size() > 0)
       
   155                     throw new Error("-r must be used before -ef");
       
   156                 File d = baseDir;
       
   157                 while (!new File(d, "TEST.ROOT").exists()) {
       
   158                     d = d.getParentFile();
       
   159                     if (d == null)
       
   160                         throw new Error("cannot find TEST.ROOT");
       
   161                 }
       
   162                 baseDir = d;
       
   163             }
       
   164             else if (arg.startsWith("-"))
       
   165                 throw new Error("unknown option: " + arg);
       
   166             else {
       
   167                 while (i < args.length)
       
   168                     files.add(new File(baseDir, args[i++]));
       
   169             }
       
   170         }
       
   171 
       
   172         for (File file: files) {
       
   173             if (file.exists())
       
   174                 test(file);
       
   175             else
       
   176                 error("File not found: " + file);
       
   177         }
       
   178 
       
   179         if (fileCount != 1)
       
   180             System.err.println(fileCount + " files read");
       
   181         if (errors > 0)
       
   182             System.err.println(errors + " errors");
       
   183 
       
   184         return (gui || errors == 0);
       
   185     }
       
   186 
       
   187     /**
       
   188      * Print command line help.
       
   189      * @param out output stream
       
   190      */
       
   191     void usage(PrintStream out) {
       
   192         out.println("Usage:");
       
   193         out.println("  java TreePosTest options... files...");
       
   194         out.println("");
       
   195         out.println("where options include:");
       
   196         out.println("-gui      Display returns in a GUI viewer");
       
   197         out.println("-q        Quiet: don't report on inapplicable files");
       
   198         out.println("-v        Verbose: report on files as they are being read");
       
   199         out.println("-t tag    Limit checks to tree nodes with this tag");
       
   200         out.println("          Can be repeated if desired");
       
   201         out.println("-ef file  Exclude file or directory");
       
   202         out.println("");
       
   203         out.println("files may be directories or files");
       
   204         out.println("directories will be scanned recursively");
       
   205         out.println("non java files, or java files which cannot be parsed, will be ignored");
       
   206         out.println("");
       
   207     }
       
   208 
       
   209     /**
       
   210      * Test a file. If the file is a directory, it will be recursively scanned
       
   211      * for java files.
       
   212      * @param file the file or directory to test
       
   213      */
       
   214     void test(File file) {
       
   215         if (excludeFiles.contains(file)) {
       
   216             if (!quiet)
       
   217                 error("File " + file + " excluded");
       
   218             return;
       
   219         }
       
   220 
       
   221         if (file.isDirectory()) {
       
   222             for (File f: file.listFiles()) {
       
   223                 test(f);
       
   224             }
       
   225             return;
       
   226         }
       
   227 
       
   228         if (file.isFile() && file.getName().endsWith(".java")) {
       
   229             try {
       
   230                 if (verbose)
       
   231                     System.err.println(file);
       
   232                 fileCount++;
       
   233                 PosTester p = new PosTester();
       
   234                 p.test(read(file));
       
   235             } catch (ParseException e) {
       
   236                 if (!quiet) {
       
   237                     error("Error parsing " + file + "\n" + e.getMessage());
       
   238                 }
       
   239             } catch (IOException e) {
       
   240                 error("Error reading " + file + ": " + e);
       
   241             }
       
   242             return;
       
   243         }
       
   244 
       
   245         if (!quiet)
       
   246             error("File " + file + " ignored");
       
   247     }
       
   248 
       
   249     /**
       
   250      * Read a file.
       
   251      * @param file the file to be read
       
   252      * @return the tree for the content of the file
       
   253      * @throws IOException if any IO errors occur
       
   254      * @throws TreePosTest.ParseException if any errors occur while parsing the file
       
   255      */
       
   256     JCCompilationUnit read(File file) throws IOException, ParseException {
       
   257         StringWriter sw = new StringWriter();
       
   258         PrintWriter pw = new PrintWriter(sw);
       
   259         Reporter r = new Reporter(pw);
       
   260         JavacTool tool = JavacTool.create();
       
   261         Charset cs = (encoding == null ? null : Charset.forName(encoding));
       
   262         StandardJavaFileManager fm = tool.getStandardFileManager(r, null, null);
       
   263         Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file);
       
   264         JavacTask task = tool.getTask(pw, fm, r, Collections.<String>emptyList(), null, files);
       
   265         Iterable<? extends CompilationUnitTree> trees = task.parse();
       
   266         pw.flush();
       
   267         if (r.errors > 0)
       
   268             throw new ParseException(sw.toString());
       
   269         Iterator<? extends CompilationUnitTree> iter = trees.iterator();
       
   270         if (!iter.hasNext())
       
   271             throw new Error("no trees found");
       
   272         JCCompilationUnit t = (JCCompilationUnit) iter.next();
       
   273         if (iter.hasNext())
       
   274             throw new Error("too many trees found");
       
   275         return t;
       
   276     }
       
   277 
       
   278     /**
       
   279      * Report an error. When the program is complete, the program will either
       
   280      * exit or throw an Error if any errors have been reported.
       
   281      * @param msg the error message
       
   282      */
       
   283     void error(String msg) {
       
   284         System.err.println(msg);
       
   285         errors++;
       
   286     }
       
   287 
       
   288     /** Number of files that have been analyzed. */
       
   289     int fileCount;
       
   290     /** Number of errors reported. */
       
   291     int errors;
       
   292     /** Flag: don't report irrelevant files. */
       
   293     boolean quiet;
       
   294     /** Flag: report files as they are processed. */
       
   295     boolean verbose;
       
   296     /** Flag: show errors in GUI viewer. */
       
   297     boolean gui;
       
   298     /** Option: encoding for test files. */
       
   299     String encoding;
       
   300     /** The GUI viewer for errors. */
       
   301     Viewer viewer;
       
   302     /** The set of tags for tree nodes to be analyzed; if empty, all tree nodes
       
   303      * are analyzed. */
       
   304     Set<String> tags = new HashSet<String>();
       
   305     /** Set of files and directories to be excluded from analysis. */
       
   306     Set<File> excludeFiles = new HashSet<File>();
       
   307     /** Table of printable names for tree tag values. */
       
   308     TagNames tagNames = new TagNames();
       
   309 
       
   310     /**
       
   311      * Main class for testing assertions concerning tree positions for tree nodes.
       
   312      */
       
   313     private class PosTester extends TreeScanner {
       
   314         void test(JCCompilationUnit tree) {
       
   315             sourcefile = tree.sourcefile;
       
   316             endPosTable = tree.endPositions;
       
   317             encl = new Info();
       
   318             tree.accept(this);
       
   319         }
       
   320 
       
   321         @Override
       
   322         public void scan(JCTree tree) {
       
   323             if (tree == null)
       
   324                 return;
       
   325 
       
   326             Info self = new Info(tree, endPosTable);
       
   327             if (check(self)) {
       
   328                 // Modifiers nodes are present throughout the tree even where
       
   329                 // there is no corresponding source text.
       
   330                 // Redundant semicolons in a class definition can cause empty
       
   331                 // initializer blocks with no positions.
       
   332                 if ((self.tag == JCTree.MODIFIERS || self.tag == JCTree.BLOCK)
       
   333                         && self.pos == NOPOS) {
       
   334                     // If pos is NOPOS, so should be the start and end positions
       
   335                     check("start == NOPOS", encl, self, self.start == NOPOS);
       
   336                     check("end == NOPOS", encl, self, self.end == NOPOS);
       
   337                 } else {
       
   338                     // For this node, start , pos, and endpos should be all defined
       
   339                     check("start != NOPOS", encl, self, self.start != NOPOS);
       
   340                     check("pos != NOPOS", encl, self, self.pos != NOPOS);
       
   341                     check("end != NOPOS", encl, self, self.end != NOPOS);
       
   342                     // The following should normally be ordered
       
   343                     // encl.start <= start <= pos <= end <= encl.end
       
   344                     // In addition, the position of the enclosing node should be
       
   345                     // within this node.
       
   346                     // The primary exceptions are for array type nodes, because of the
       
   347                     // need to support legacy syntax:
       
   348                     //    e.g.    int a[];    int[] b[];    int f()[] { return null; }
       
   349                     // and because of inconsistent nesting of left and right of
       
   350                     // array declarations:
       
   351                     //    e.g.    int[][] a = new int[2][];
       
   352                     check("encl.start <= start", encl, self, encl.start <= self.start);
       
   353                     check("start <= pos", encl, self, self.start <= self.pos);
       
   354                     if (!(self.tag == JCTree.TYPEARRAY
       
   355                             && (encl.tag == JCTree.VARDEF || encl.tag == JCTree.TYPEARRAY))) {
       
   356                         check("encl.pos <= start || end <= encl.pos",
       
   357                                 encl, self, encl.pos <= self.start || self.end <= encl.pos);
       
   358                     }
       
   359                     check("pos <= end", encl, self, self.pos <= self.end);
       
   360                     if (!(self.tag == JCTree.TYPEARRAY && encl.tag == JCTree.TYPEARRAY)) {
       
   361                         check("end <= encl.end", encl, self, self.end <= encl.end);
       
   362                     }
       
   363                 }
       
   364             }
       
   365 
       
   366             Info prevEncl = encl;
       
   367             encl = self;
       
   368             tree.accept(this);
       
   369             encl = prevEncl;
       
   370         }
       
   371 
       
   372         @Override
       
   373         public void visitVarDef(JCVariableDecl tree) {
       
   374             // enum member declarations are desugared in the parser and have
       
   375             // ill-defined semantics for tree positions, so for now, we
       
   376             // skip the synthesized bits and just check parts which came from
       
   377             // the original source text
       
   378             if ((tree.mods.flags & Flags.ENUM) != 0) {
       
   379                 scan(tree.mods);
       
   380                 if (tree.init != null) {
       
   381                     if (tree.init.getTag() == JCTree.NEWCLASS) {
       
   382                         JCNewClass init = (JCNewClass) tree.init;
       
   383                         if (init.args != null && init.args.nonEmpty()) {
       
   384                             scan(init.args);
       
   385                         }
       
   386                         if (init.def != null && init.def.defs != null) {
       
   387                             scan(init.def.defs);
       
   388                         }
       
   389                     }
       
   390                 }
       
   391             } else
       
   392                 super.visitVarDef(tree);
       
   393         }
       
   394 
       
   395         boolean check(Info x) {
       
   396             return tags.size() == 0 || tags.contains(tagNames.get(x.tag));
       
   397         }
       
   398 
       
   399         void check(String label, Info encl, Info self, boolean ok) {
       
   400             if (!ok) {
       
   401                 if (gui) {
       
   402                     if (viewer == null)
       
   403                         viewer = new Viewer();
       
   404                     viewer.addEntry(sourcefile, label, encl, self);
       
   405                 }
       
   406 
       
   407                 String s = self.tree.toString();
       
   408                 String msg = sourcefile.getName() + ": " + label + ": " +
       
   409                         "encl:" + encl + " this:" + self + "\n" +
       
   410                         s.substring(0, Math.min(80, s.length())).replaceAll("[\r\n]+", " ");
       
   411                 error(msg);
       
   412             }
       
   413         }
       
   414 
       
   415         JavaFileObject sourcefile;
       
   416         Map<JCTree, Integer> endPosTable;
       
   417         Info encl;
       
   418 
       
   419     }
       
   420 
       
   421     /**
       
   422      * Utility class providing easy access to position and other info for a tree node.
       
   423      */
       
   424     private class Info {
       
   425         Info() {
       
   426             tree = null;
       
   427             tag = JCTree.ERRONEOUS;
       
   428             start = 0;
       
   429             pos = 0;
       
   430             end = Integer.MAX_VALUE;
       
   431         }
       
   432 
       
   433         Info(JCTree tree, Map<JCTree, Integer> endPosTable) {
       
   434             this.tree = tree;
       
   435             tag = tree.getTag();
       
   436             start = TreeInfo.getStartPos(tree);
       
   437             pos = tree.pos;
       
   438             end = TreeInfo.getEndPos(tree, endPosTable);
       
   439         }
       
   440 
       
   441         @Override
       
   442         public String toString() {
       
   443             return tagNames.get(tree.getTag()) + "[start:" + start + ",pos:" + pos + ",end:" + end + "]";
       
   444         }
       
   445 
       
   446         final JCTree tree;
       
   447         final int tag;
       
   448         final int start;
       
   449         final int pos;
       
   450         final int end;
       
   451     }
       
   452 
       
   453     /**
       
   454      * Names for tree tags.
       
   455      * javac does not provide an API to convert tag values to strings, so this class uses
       
   456      * reflection to determine names of public static final int values in JCTree.
       
   457      */
       
   458     private static class TagNames {
       
   459         String get(int tag) {
       
   460             if (map == null) {
       
   461                 map = new HashMap<Integer, String>();
       
   462                 Class c = JCTree.class;
       
   463                 for (Field f : c.getDeclaredFields()) {
       
   464                     if (f.getType().equals(int.class)) {
       
   465                         int mods = f.getModifiers();
       
   466                         if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
       
   467                             try {
       
   468                                 map.put(f.getInt(null), f.getName());
       
   469                             } catch (IllegalAccessException e) {
       
   470                             }
       
   471                         }
       
   472                     }
       
   473                 }
       
   474             }
       
   475             String name = map.get(tag);
       
   476             return (name == null) ? "??" : name;
       
   477         }
       
   478 
       
   479         private Map<Integer, String> map;
       
   480     }
       
   481 
       
   482     /**
       
   483      * Thrown when errors are found parsing a java file.
       
   484      */
       
   485     private static class ParseException extends Exception {
       
   486         ParseException(String msg) {
       
   487             super(msg);
       
   488         }
       
   489     }
       
   490 
       
   491     /**
       
   492      * DiagnosticListener to report diagnostics and count any errors that occur.
       
   493      */
       
   494     private static class Reporter implements DiagnosticListener<JavaFileObject> {
       
   495         Reporter(PrintWriter out) {
       
   496             this.out = out;
       
   497         }
       
   498 
       
   499         public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
       
   500             out.println(diagnostic);
       
   501             switch (diagnostic.getKind()) {
       
   502                 case ERROR:
       
   503                     errors++;
       
   504             }
       
   505         }
       
   506         int errors;
       
   507         PrintWriter out;
       
   508     }
       
   509 
       
   510     /**
       
   511      * GUI viewer for issues found by TreePosTester. The viewer provides a drop
       
   512      * down list for selecting error conditions, a header area providing details
       
   513      * about an error, and a text area with the ranges of text highlighted as
       
   514      * appropriate.
       
   515      */
       
   516     private class Viewer extends JFrame {
       
   517         /**
       
   518          * Create a viewer.
       
   519          */
       
   520         Viewer() {
       
   521             initGUI();
       
   522         }
       
   523 
       
   524         /**
       
   525          * Add another entry to the list of errors.
       
   526          * @param file The file containing the error
       
   527          * @param check The condition that was being tested, and which failed
       
   528          * @param encl the enclosing tree node
       
   529          * @param self the tree node containing the error
       
   530          */
       
   531         void addEntry(JavaFileObject file, String check, Info encl, Info self) {
       
   532             Entry e = new Entry(file, check, encl, self);
       
   533             DefaultComboBoxModel m = (DefaultComboBoxModel) entries.getModel();
       
   534             m.addElement(e);
       
   535             if (m.getSize() == 1)
       
   536                 entries.setSelectedItem(e);
       
   537         }
       
   538 
       
   539         /**
       
   540          * Initialize the GUI window.
       
   541          */
       
   542         private void initGUI() {
       
   543             JPanel head = new JPanel(new GridBagLayout());
       
   544             GridBagConstraints lc = new GridBagConstraints();
       
   545             GridBagConstraints fc = new GridBagConstraints();
       
   546             fc.anchor = GridBagConstraints.WEST;
       
   547             fc.fill = GridBagConstraints.HORIZONTAL;
       
   548             fc.gridwidth = GridBagConstraints.REMAINDER;
       
   549 
       
   550             entries = new JComboBox();
       
   551             entries.addActionListener(new ActionListener() {
       
   552                 public void actionPerformed(ActionEvent e) {
       
   553                     showEntry((Entry) entries.getSelectedItem());
       
   554                 }
       
   555             });
       
   556             fc.insets.bottom = 10;
       
   557             head.add(entries, fc);
       
   558             fc.insets.bottom = 0;
       
   559             head.add(new JLabel("check:"), lc);
       
   560             head.add(checkField = createTextField(80), fc);
       
   561             fc.fill = GridBagConstraints.NONE;
       
   562             head.add(setBackground(new JLabel("encl:"), enclColor), lc);
       
   563             head.add(enclPanel = new InfoPanel(), fc);
       
   564             head.add(setBackground(new JLabel("self:"), selfColor), lc);
       
   565             head.add(selfPanel = new InfoPanel(), fc);
       
   566             add(head, BorderLayout.NORTH);
       
   567 
       
   568             body = new JTextArea();
       
   569             body.setFont(Font.decode(Font.MONOSPACED));
       
   570             body.addCaretListener(new CaretListener() {
       
   571                 public void caretUpdate(CaretEvent e) {
       
   572                     int dot = e.getDot();
       
   573                     int mark = e.getMark();
       
   574                     if (dot == mark)
       
   575                         statusText.setText("dot: " + dot);
       
   576                     else
       
   577                         statusText.setText("dot: " + dot + ", mark:" + mark);
       
   578                 }
       
   579             });
       
   580             JScrollPane p = new JScrollPane(body,
       
   581                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
       
   582                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
       
   583             p.setPreferredSize(new Dimension(640, 480));
       
   584             add(p, BorderLayout.CENTER);
       
   585 
       
   586             statusText = createTextField(80);
       
   587             add(statusText, BorderLayout.SOUTH);
       
   588 
       
   589             pack();
       
   590             setLocationRelativeTo(null); // centered on screen
       
   591             setVisible(true);
       
   592             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
   593         }
       
   594 
       
   595         /** Show an entry that has been selected. */
       
   596         private void showEntry(Entry e) {
       
   597             try {
       
   598                 // update simple fields
       
   599                 setTitle(e.file.getName());
       
   600                 checkField.setText(e.check);
       
   601                 enclPanel.setInfo(e.encl);
       
   602                 selfPanel.setInfo(e.self);
       
   603                 // show file text with highlights
       
   604                 body.setText(e.file.getCharContent(true).toString());
       
   605                 Highlighter highlighter = body.getHighlighter();
       
   606                 highlighter.removeAllHighlights();
       
   607                 addHighlight(highlighter, e.encl, enclColor);
       
   608                 addHighlight(highlighter, e.self, selfColor);
       
   609                 scroll(body, getMinPos(enclPanel.info, selfPanel.info));
       
   610             } catch (IOException ex) {
       
   611                 body.setText("Cannot read " + e.file.getName() + ": " + e);
       
   612             }
       
   613         }
       
   614 
       
   615         /** Create a test field. */
       
   616         private JTextField createTextField(int width) {
       
   617             JTextField f = new JTextField(width);
       
   618             f.setEditable(false);
       
   619             f.setBorder(null);
       
   620             return f;
       
   621         }
       
   622 
       
   623         /** Add a highlighted region based on the positions in an Info object. */
       
   624         private void addHighlight(Highlighter h, Info info, Color c) {
       
   625             int start = info.start;
       
   626             int end = info.end;
       
   627             if (start == -1 && end == -1)
       
   628                 return;
       
   629             if (start == -1)
       
   630                 start = end;
       
   631             if (end == -1)
       
   632                 end = start;
       
   633             try {
       
   634                 h.addHighlight(info.start, info.end,
       
   635                         new DefaultHighlighter.DefaultHighlightPainter(c));
       
   636                 if (info.pos != -1) {
       
   637                     Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
       
   638                     h.addHighlight(info.pos, info.pos + 1,
       
   639                         new DefaultHighlighter.DefaultHighlightPainter(c2));
       
   640                 }
       
   641             } catch (BadLocationException e) {
       
   642                 e.printStackTrace();
       
   643             }
       
   644         }
       
   645 
       
   646         /** Get the minimum valid position in a set of info objects. */
       
   647         private int getMinPos(Info... values) {
       
   648             int i = Integer.MAX_VALUE;
       
   649             for (Info info: values) {
       
   650                 if (info.start >= 0) i = Math.min(i, info.start);
       
   651                 if (info.pos   >= 0) i = Math.min(i, info.pos);
       
   652                 if (info.end   >= 0) i = Math.min(i, info.end);
       
   653             }
       
   654             return (i == Integer.MAX_VALUE) ? 0 : i;
       
   655         }
       
   656 
       
   657         /** Set the background on a component. */
       
   658         private JComponent setBackground(JComponent comp, Color c) {
       
   659             comp.setOpaque(true);
       
   660             comp.setBackground(c);
       
   661             return comp;
       
   662         }
       
   663 
       
   664         /** Scroll a text area to display a given position near the middle of the visible area. */
       
   665         private void scroll(final JTextArea t, final int pos) {
       
   666             // Using invokeLater appears to give text a chance to sort itself out
       
   667             // before the scroll happens; otherwise scrollRectToVisible doesn't work.
       
   668             // Maybe there's a better way to sync with the text...
       
   669             EventQueue.invokeLater(new Runnable() {
       
   670                 public void run() {
       
   671                     try {
       
   672                         Rectangle r = t.modelToView(pos);
       
   673                         JScrollPane p = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, t);
       
   674                         r.y = Math.max(0, r.y - p.getHeight() * 2 / 5);
       
   675                         r.height += p.getHeight() * 4 / 5;
       
   676                         t.scrollRectToVisible(r);
       
   677                     } catch (BadLocationException ignore) {
       
   678                     }
       
   679                 }
       
   680             });
       
   681         }
       
   682 
       
   683         private JComboBox entries;
       
   684         private JTextField checkField;
       
   685         private InfoPanel enclPanel;
       
   686         private InfoPanel selfPanel;
       
   687         private JTextArea body;
       
   688         private JTextField statusText;
       
   689 
       
   690         private Color selfColor = new Color(0.f, 1.f, 0.f, 0.2f); // 20% green
       
   691         private Color enclColor = new Color(1.f, 0.f, 0.f, 0.2f); // 20% red
       
   692 
       
   693         /** Panel to display an Info object. */
       
   694         private class InfoPanel extends JPanel {
       
   695             InfoPanel() {
       
   696                 add(tagName = createTextField(20));
       
   697                 add(new JLabel("start:"));
       
   698                 add(addListener(start = createTextField(6)));
       
   699                 add(new JLabel("pos:"));
       
   700                 add(addListener(pos = createTextField(6)));
       
   701                 add(new JLabel("end:"));
       
   702                 add(addListener(end = createTextField(6)));
       
   703             }
       
   704 
       
   705             void setInfo(Info info) {
       
   706                 this.info = info;
       
   707                 tagName.setText(tagNames.get(info.tag));
       
   708                 start.setText(String.valueOf(info.start));
       
   709                 pos.setText(String.valueOf(info.pos));
       
   710                 end.setText(String.valueOf(info.end));
       
   711             }
       
   712 
       
   713             JTextField addListener(final JTextField f) {
       
   714                 f.addMouseListener(new MouseAdapter() {
       
   715                     @Override
       
   716                     public void mouseClicked(MouseEvent e) {
       
   717                         body.setCaretPosition(Integer.valueOf(f.getText()));
       
   718                         body.getCaret().setVisible(true);
       
   719                     }
       
   720                 });
       
   721                 return f;
       
   722             }
       
   723 
       
   724             Info info;
       
   725             JTextField tagName;
       
   726             JTextField start;
       
   727             JTextField pos;
       
   728             JTextField end;
       
   729         }
       
   730 
       
   731         /** Object to record information about an error to be displayed. */
       
   732         private class Entry {
       
   733             Entry(JavaFileObject file, String check, Info encl, Info self) {
       
   734                 this.file = file;
       
   735                 this.check = check;
       
   736                 this.encl = encl;
       
   737                 this.self= self;
       
   738             }
       
   739 
       
   740             @Override
       
   741             public String toString() {
       
   742                 return file.getName() + " " + check + " " + getMinPos(encl, self);
       
   743             }
       
   744 
       
   745             final JavaFileObject file;
       
   746             final String check;
       
   747             final Info encl;
       
   748             final Info self;
       
   749         }
       
   750     }
       
   751 }
       
   752