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