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