1 /*
  2  * Copyright (c) 2010, 2021, 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 /*
 25  * @test
 26  * @bug 6970584 8006694 8062373 8129962
 27  * @summary assorted position errors in compiler syntax trees
 28  *  temporarily workaround combo tests are causing time out in several platforms
 29  * @enablePreview
 30  * @library ../lib
 31  * @modules java.desktop
 32  *          jdk.compiler/com.sun.tools.javac.api
 33  *          jdk.compiler/com.sun.tools.javac.code
 34  *          jdk.compiler/com.sun.tools.javac.file
 35  *          jdk.compiler/com.sun.tools.javac.tree
 36  *          jdk.compiler/com.sun.tools.javac.util
 37  * @build combo.ComboTestHelper
 38  * @run main CheckAttributedTree -q -r -et ERRONEOUS .
 39  */
 40 
 41 import java.awt.BorderLayout;
 42 import java.awt.Color;
 43 import java.awt.Dimension;
 44 import java.awt.EventQueue;
 45 import java.awt.Font;
 46 import java.awt.GridBagConstraints;
 47 import java.awt.GridBagLayout;
 48 import java.awt.Rectangle;
 49 import java.awt.event.ActionEvent;
 50 import java.awt.event.ActionListener;
 51 import java.awt.event.MouseAdapter;
 52 import java.awt.event.MouseEvent;
 53 import java.io.File;
 54 import java.io.IOException;
 55 import java.io.PrintStream;
 56 import java.io.PrintWriter;
 57 import java.io.StringWriter;
 58 import java.lang.reflect.Field;
 59 import java.nio.file.FileVisitResult;
 60 import java.nio.file.Files;
 61 import java.nio.file.Path;
 62 import java.nio.file.SimpleFileVisitor;
 63 import java.nio.file.attribute.BasicFileAttributes;
 64 import java.util.ArrayList;
 65 import java.util.Arrays;
 66 import java.util.HashSet;
 67 import java.util.List;
 68 import java.util.Set;
 69 import java.util.concurrent.atomic.AtomicInteger;
 70 import java.util.function.BiConsumer;
 71 
 72 import javax.lang.model.element.Element;
 73 import javax.swing.DefaultComboBoxModel;
 74 import javax.swing.JComboBox;
 75 import javax.swing.JComponent;
 76 import javax.swing.JFrame;
 77 import javax.swing.JLabel;
 78 import javax.swing.JPanel;
 79 import javax.swing.JScrollPane;
 80 import javax.swing.JTextArea;
 81 import javax.swing.JTextField;
 82 import javax.swing.SwingUtilities;
 83 import javax.swing.event.CaretEvent;
 84 import javax.swing.event.CaretListener;
 85 import javax.swing.text.BadLocationException;
 86 import javax.swing.text.DefaultHighlighter;
 87 import javax.swing.text.Highlighter;
 88 import javax.tools.JavaFileObject;
 89 
 90 import com.sun.source.tree.CompilationUnitTree;
 91 import com.sun.source.util.TaskEvent;
 92 import com.sun.source.util.TaskEvent.Kind;
 93 import com.sun.source.util.TaskListener;
 94 import com.sun.tools.javac.code.Symbol;
 95 import com.sun.tools.javac.code.Type;
 96 import com.sun.tools.javac.tree.EndPosTable;
 97 import com.sun.tools.javac.tree.JCTree;
 98 import com.sun.tools.javac.tree.JCTree.JCBreak;
 99 import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
100 import com.sun.tools.javac.tree.JCTree.JCImport;
101 import com.sun.tools.javac.tree.TreeInfo;
102 import com.sun.tools.javac.tree.TreeScanner;
103 import com.sun.tools.javac.util.Pair;
104 
105 import static com.sun.tools.javac.tree.JCTree.Tag.*;
106 
107 import combo.ComboTestHelper;
108 import combo.ComboInstance;
109 import combo.ComboTestHelper.IgnoreMode;
110 
111 /**
112  * Utility and test program to check validity of tree positions for tree nodes.
113  * The program can be run standalone, or as a jtreg test.  In standalone mode,
114  * errors can be displayed in a gui viewer. For info on command line args,
115  * run program with no args.
116  *
117  * <p>
118  * jtreg: Note that by using the -r switch in the test description below, this test
119  * will process all java files in the langtools/test directory, thus implicitly
120  * covering any new language features that may be tested in this test suite.
121  */
122 
123 public class CheckAttributedTree {
124     /**
125      * Main entry point.
126      * If test.src is set, program runs in jtreg mode, and will throw an Error
127      * if any errors arise, otherwise System.exit will be used, unless the gui
128      * viewer is being used. In jtreg mode, the default base directory for file
129      * args is the value of ${test.src}. In jtreg mode, the -r option can be
130      * given to change the default base directory to the root test directory.
131      */
132     public static void main(String... args) throws Exception {
133         String testSrc = System.getProperty("test.src");
134         File baseDir = (testSrc == null) ? null : new File(testSrc);
135         boolean ok = new CheckAttributedTree().run(baseDir, args);
136         if (!ok) {
137             if (testSrc != null)  // jtreg mode
138                 throw new Error("failed");
139             else
140                 System.exit(1);
141         }
142         System.err.println("total number of compilations " + totalNumberOfCompilations);
143         System.err.println("number of failed compilations " + numberOfFailedCompilations);
144     }
145 
146     static private int totalNumberOfCompilations = 0;
147     static private int numberOfFailedCompilations = 0;
148 
149     /**
150      * Run the program. A base directory can be provided for file arguments.
151      * In jtreg mode, the -r option can be given to change the default base
152      * directory to the test root directory. For other options, see usage().
153      * @param baseDir base directory for any file arguments.
154      * @param args command line args
155      * @return true if successful or in gui mode
156      */
157     boolean run(File baseDir, String... args) throws Exception {
158         if (args.length == 0) {
159             usage(System.out);
160             return true;
161         }
162 
163         List<File> files = new ArrayList<File>();
164         for (int i = 0; i < args.length; i++) {
165             String arg = args[i];
166             if (arg.equals("-encoding") && i + 1 < args.length)
167                 encoding = args[++i];
168             else if (arg.equals("-gui"))
169                 gui = true;
170             else if (arg.equals("-q"))
171                 quiet = true;
172             else if (arg.equals("-v")) {
173                 verbose = true;
174             }
175             else if (arg.equals("-t") && i + 1 < args.length)
176                 tags.add(args[++i]);
177             else if (arg.equals("-ef") && i + 1 < args.length)
178                 excludeFiles.add(new File(baseDir, args[++i]));
179             else if (arg.equals("-et") && i + 1 < args.length)
180                 excludeTags.add(args[++i]);
181             else if (arg.equals("-r")) {
182                 if (excludeFiles.size() > 0)
183                     throw new Error("-r must be used before -ef");
184                 File d = baseDir;
185                 while (!new File(d, "TEST.ROOT").exists()) {
186                     if (d == null)
187                         throw new Error("cannot find TEST.ROOT");
188                     d = d.getParentFile();
189                 }
190                 baseDir = d;
191             }
192             else if (arg.startsWith("-"))
193                 throw new Error("unknown option: " + arg);
194             else {
195                 while (i < args.length)
196                     files.add(new File(baseDir, args[i++]));
197             }
198         }
199 
200         ComboTestHelper<FileChecker> cth = new ComboTestHelper<>();
201         cth.withIgnoreMode(IgnoreMode.IGNORE_ALL)
202                 .withFilter(FileChecker::checkFile)
203                 .withDimension("FILE", (x, file) -> x.file = file, getAllFiles(files))
204                 .run(FileChecker::new);
205 
206         if (fileCount.get() != 1)
207             errWriter.println(fileCount + " files read");
208 
209         if (verbose) {
210             System.out.println(errSWriter.toString());
211         }
212 
213         return (gui || !cth.info().hasFailures());
214     }
215 
216     File[] getAllFiles(List<File> roots) throws IOException {
217         long now = System.currentTimeMillis();
218         ArrayList<File> buf = new ArrayList<>();
219         for (File file : roots) {
220             Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
221                 @Override
222                 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
223                     buf.add(file.toFile());
224                     return FileVisitResult.CONTINUE;
225                 }
226             });
227         }
228         long delta = System.currentTimeMillis() - now;
229         System.err.println("All files = " + buf.size() + " " + delta);
230         return buf.toArray(new File[buf.size()]);
231     }
232 
233     /**
234      * Print command line help.
235      * @param out output stream
236      */
237     void usage(PrintStream out) {
238         out.println("Usage:");
239         out.println("  java CheckAttributedTree options... files...");
240         out.println("");
241         out.println("where options include:");
242         out.println("-q        Quiet: don't report on inapplicable files");
243         out.println("-gui      Display returns in a GUI viewer");
244         out.println("-v        Verbose: report on files as they are being read");
245         out.println("-t tag    Limit checks to tree nodes with this tag");
246         out.println("          Can be repeated if desired");
247         out.println("-ef file  Exclude file or directory");
248         out.println("-et tag   Exclude tree nodes with given tag name");
249         out.println("");
250         out.println("files may be directories or files");
251         out.println("directories will be scanned recursively");
252         out.println("non java files, or java files which cannot be parsed, will be ignored");
253         out.println("");
254     }
255 
256     class FileChecker extends ComboInstance<FileChecker> {
257 
258         File file;
259 
260         boolean checkFile() {
261             if (!file.exists()) {
262                 error("File not found: " + file);
263                 return false;
264             }
265             if (excludeFiles.contains(file)) {
266                 if (!quiet)
267                     error("File " + file + " excluded");
268                 return false;
269             }
270             if (!file.getName().endsWith(".java")) {
271                 if (!quiet)
272                     error("File " + file + " ignored");
273                 return false;
274             }
275 
276             return true;
277         }
278 
279         public void doWork() {
280             if (!file.exists()) {
281                 error("File not found: " + file);
282             }
283             if (excludeFiles.contains(file)) {
284                 if (!quiet)
285                     error("File " + file + " excluded");
286                 return;
287             }
288             if (!file.getName().endsWith(".java")) {
289                 if (!quiet)
290                     error("File " + file + " ignored");
291             }
292             try {
293                 if (verbose)
294                     errWriter.println(file);
295                 fileCount.incrementAndGet();
296                 NPETester p = new NPETester();
297                 readAndCheck(file, p::test);
298             } catch (Throwable t) {
299                 if (!quiet) {
300                     error("Error checking " + file + "\n" + t.getMessage());
301                 }
302             }
303         }
304 
305         /**
306          * Read and check a file.
307          * @param file the file to be read
308          * @return the tree for the content of the file
309          * @throws IOException if any IO errors occur
310          * @throws AttributionException if any errors occur while analyzing the file
311          */
312         void readAndCheck(File file, BiConsumer<JCCompilationUnit, JCTree> c) throws IOException {
313             Iterable<? extends JavaFileObject> files = fileManager().getJavaFileObjects(file);
314             final List<Element> analyzedElems = new ArrayList<>();
315             final List<CompilationUnitTree> trees = new ArrayList<>();
316             totalNumberOfCompilations++;
317             newCompilationTask()
318                 .withWriter(pw)
319                     .withOption("--should-stop=ifError=ATTR")
320                     .withOption("--should-stop=ifNoError=ATTR")
321                     .withOption("-XDverboseCompilePolicy")
322                     .withOption("-Xdoclint:none")
323                     .withSource(files.iterator().next())
324                     .withListener(new TaskListener() {
325                         public void started(TaskEvent e) {
326                             if (e.getKind() == TaskEvent.Kind.ANALYZE)
327                             analyzedElems.add(e.getTypeElement());
328                     }
329 
330                     public void finished(TaskEvent e) {
331                         if (e.getKind() == Kind.PARSE)
332                             trees.add(e.getCompilationUnit());
333                     }
334                 }).analyze(res -> {
335                 Iterable<? extends Element> elems = res.get();
336                 if (elems.iterator().hasNext()) {
337                     for (CompilationUnitTree t : trees) {
338                        JCCompilationUnit cu = (JCCompilationUnit)t;
339                        for (JCTree def : cu.defs) {
340                            if (def.hasTag(CLASSDEF) &&
341                                    analyzedElems.contains(((JCTree.JCClassDecl)def).sym)) {
342                                c.accept(cu, def);
343                            }
344                        }
345                     }
346                 } else {
347                     numberOfFailedCompilations++;
348                 }
349             });
350         }
351 
352         /**
353          * Report an error. When the program is complete, the program will either
354          * exit or throw an Error if any errors have been reported.
355          * @param msg the error message
356          */
357         void error(String msg) {
358             System.err.println();
359             System.err.println(msg);
360             System.err.println();
361             fail(msg);
362         }
363 
364         /**
365          * Main class for testing assertions concerning types/symbol
366          * left uninitialized after attribution
367          */
368         private class NPETester extends TreeScanner {
369             void test(JCCompilationUnit cut, JCTree tree) {
370                 sourcefile = cut.sourcefile;
371                 endPosTable = cut.endPositions;
372                 encl = new Info(tree, endPosTable);
373                 tree.accept(this);
374             }
375 
376             @Override
377             public void scan(JCTree tree) {
378                 if (tree == null ||
379                         excludeTags.contains(treeUtil.nameFromTag(tree.getTag()))) {
380                     return;
381                 }
382 
383                 Info self = new Info(tree, endPosTable);
384                 if (mandatoryType(tree)) {
385                     check(tree.type != null,
386                             "'null' field 'type' found in tree ", self);
387                     if (tree.type==null)
388                         Thread.dumpStack();
389                 }
390 
391                 Field errField = checkFields(tree);
392                 if (errField!=null) {
393                     check(false,
394                             "'null' field '" + errField.getName() + "' found in tree ", self);
395                 }
396 
397                 Info prevEncl = encl;
398                 encl = self;
399                 tree.accept(this);
400                 encl = prevEncl;
401             }
402 
403             private boolean mandatoryType(JCTree that) {
404                 return that instanceof JCTree.JCExpression ||
405                         that.hasTag(VARDEF) ||
406                         that.hasTag(METHODDEF) ||
407                         that.hasTag(CLASSDEF);
408             }
409 
410             private final List<String> excludedFields = Arrays.asList("varargsElement", "targetType", "factoryProduct");
411 
412             void check(boolean ok, String label, Info self) {
413                 if (!ok) {
414                     if (gui) {
415                         if (viewer == null)
416                             viewer = new Viewer();
417                         viewer.addEntry(sourcefile, label, encl, self);
418                     }
419                     error(label + self.toString() + " encl: " + encl.toString() +
420                             " in file: " + sourcefile + "  " + self.tree);
421                 }
422             }
423 
424             Field checkFields(JCTree t) {
425                 List<Field> fieldsToCheck = treeUtil.getFieldsOfType(t,
426                         excludedFields,
427                         Symbol.class,
428                         Type.class);
429                 for (Field f : fieldsToCheck) {
430                     try {
431                         if (f.get(t) == null) {
432                             return f;
433                         }
434                     }
435                     catch (IllegalAccessException e) {
436                         System.err.println("Cannot read field: " + f);
437                         //swallow it
438                     }
439                 }
440                 return null;
441             }
442 
443             @Override
444             public void visitImport(JCImport tree) { }
445 
446             @Override
447             public void visitTopLevel(JCCompilationUnit tree) {
448                 scan(tree.defs);
449             }
450 
451             @Override
452             public void visitBreak(JCBreak tree) {
453                 if (tree.isValueBreak())
454                     super.visitBreak(tree);
455             }
456 
457             JavaFileObject sourcefile;
458             EndPosTable endPosTable;
459             Info encl;
460         }
461     }
462 
463     // See CR:  6982992 Tests CheckAttributedTree.java, JavacTreeScannerTest.java, and SourceTreeeScannerTest.java timeout
464     StringWriter sw = new StringWriter();
465     PrintWriter pw = new PrintWriter(sw);
466 
467     StringWriter errSWriter = new StringWriter();
468     PrintWriter errWriter = new PrintWriter(errSWriter);
469 
470     /** Flag: don't report irrelevant files. */
471     boolean quiet;
472     /** Flag: show errors in GUI viewer. */
473     boolean gui;
474     /** The GUI viewer for errors. */
475     Viewer viewer;
476     /** Flag: report files as they are processed. */
477     boolean verbose;
478     /** Option: encoding for test files. */
479     String encoding;
480     /** The set of tags for tree nodes to be analyzed; if empty, all tree nodes
481      * are analyzed. */
482     Set<String> tags = new HashSet<String>();
483     /** Set of files and directories to be excluded from analysis. */
484     Set<File> excludeFiles = new HashSet<File>();
485     /** Set of tag names to be excluded from analysis. */
486     Set<String> excludeTags = new HashSet<String>();
487     /** Utility class for trees */
488     TreeUtil treeUtil = new TreeUtil();
489 
490     /**
491      * Utility class providing easy access to position and other info for a tree node.
492      */
493     private class Info {
494         Info() {
495             tree = null;
496             tag = ERRONEOUS;
497             start = 0;
498             pos = 0;
499             end = Integer.MAX_VALUE;
500         }
501 
502         Info(JCTree tree, EndPosTable endPosTable) {
503             this.tree = tree;
504             tag = tree.getTag();
505             start = TreeInfo.getStartPos(tree);
506             pos = tree.pos;
507             end = TreeInfo.getEndPos(tree, endPosTable);
508         }
509 
510         @Override
511         public String toString() {
512             return treeUtil.nameFromTag(tree.getTag()) + "[start:" + start + ",pos:" + pos + ",end:" + end + "]";
513         }
514 
515         final JCTree tree;
516         final JCTree.Tag tag;
517         final int start;
518         final int pos;
519         final int end;
520     }
521 
522     /**
523      * Names for tree tags.
524      */
525     private static class TreeUtil {
526         String nameFromTag(JCTree.Tag tag) {
527             String name = tag.name();
528             return (name == null) ? "??" : name;
529         }
530 
531         List<Field> getFieldsOfType(JCTree t, List<String> excludeNames, Class<?>... types) {
532             List<Field> buf = new ArrayList<Field>();
533             for (Field f : t.getClass().getDeclaredFields()) {
534                 if (!excludeNames.contains(f.getName())) {
535                     for (Class<?> type : types) {
536                         if (type.isAssignableFrom(f.getType())) {
537                             f.setAccessible(true);
538                             buf.add(f);
539                             break;
540                         }
541                     }
542                 }
543             }
544             return buf;
545         }
546     }
547 
548     /**
549      * GUI viewer for issues found by TreePosTester. The viewer provides a drop
550      * down list for selecting error conditions, a header area providing details
551      * about an error, and a text area with the ranges of text highlighted as
552      * appropriate.
553      */
554     private class Viewer extends JFrame {
555         /**
556          * Create a viewer.
557          */
558         Viewer() {
559             initGUI();
560         }
561 
562         /**
563          * Add another entry to the list of errors.
564          * @param file The file containing the error
565          * @param check The condition that was being tested, and which failed
566          * @param encl the enclosing tree node
567          * @param self the tree node containing the error
568          */
569         void addEntry(JavaFileObject file, String check, Info encl, Info self) {
570             Entry e = new Entry(file, check, encl, self);
571             DefaultComboBoxModel m = (DefaultComboBoxModel) entries.getModel();
572             m.addElement(e);
573             if (m.getSize() == 1)
574                 entries.setSelectedItem(e);
575         }
576 
577         /**
578          * Initialize the GUI window.
579          */
580         private void initGUI() {
581             JPanel head = new JPanel(new GridBagLayout());
582             GridBagConstraints lc = new GridBagConstraints();
583             GridBagConstraints fc = new GridBagConstraints();
584             fc.anchor = GridBagConstraints.WEST;
585             fc.fill = GridBagConstraints.HORIZONTAL;
586             fc.gridwidth = GridBagConstraints.REMAINDER;
587 
588             entries = new JComboBox();
589             entries.addActionListener(new ActionListener() {
590                 public void actionPerformed(ActionEvent e) {
591                     showEntry((Entry) entries.getSelectedItem());
592                 }
593             });
594             fc.insets.bottom = 10;
595             head.add(entries, fc);
596             fc.insets.bottom = 0;
597             head.add(new JLabel("check:"), lc);
598             head.add(checkField = createTextField(80), fc);
599             fc.fill = GridBagConstraints.NONE;
600             head.add(setBackground(new JLabel("encl:"), enclColor), lc);
601             head.add(enclPanel = new InfoPanel(), fc);
602             head.add(setBackground(new JLabel("self:"), selfColor), lc);
603             head.add(selfPanel = new InfoPanel(), fc);
604             add(head, BorderLayout.NORTH);
605 
606             body = new JTextArea();
607             body.setFont(Font.decode(Font.MONOSPACED));
608             body.addCaretListener(new CaretListener() {
609                 public void caretUpdate(CaretEvent e) {
610                     int dot = e.getDot();
611                     int mark = e.getMark();
612                     if (dot == mark)
613                         statusText.setText("dot: " + dot);
614                     else
615                         statusText.setText("dot: " + dot + ", mark:" + mark);
616                 }
617             });
618             JScrollPane p = new JScrollPane(body,
619                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
620                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
621             p.setPreferredSize(new Dimension(640, 480));
622             add(p, BorderLayout.CENTER);
623 
624             statusText = createTextField(80);
625             add(statusText, BorderLayout.SOUTH);
626 
627             pack();
628             setLocationRelativeTo(null); // centered on screen
629             setVisible(true);
630             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
631         }
632 
633         /** Show an entry that has been selected. */
634         private void showEntry(Entry e) {
635             try {
636                 // update simple fields
637                 setTitle(e.file.getName());
638                 checkField.setText(e.check);
639                 enclPanel.setInfo(e.encl);
640                 selfPanel.setInfo(e.self);
641                 // show file text with highlights
642                 body.setText(e.file.getCharContent(true).toString());
643                 Highlighter highlighter = body.getHighlighter();
644                 highlighter.removeAllHighlights();
645                 addHighlight(highlighter, e.encl, enclColor);
646                 addHighlight(highlighter, e.self, selfColor);
647                 scroll(body, getMinPos(enclPanel.info, selfPanel.info));
648             } catch (IOException ex) {
649                 body.setText("Cannot read " + e.file.getName() + ": " + e);
650             }
651         }
652 
653         /** Create a test field. */
654         private JTextField createTextField(int width) {
655             JTextField f = new JTextField(width);
656             f.setEditable(false);
657             f.setBorder(null);
658             return f;
659         }
660 
661         /** Add a highlighted region based on the positions in an Info object. */
662         private void addHighlight(Highlighter h, Info info, Color c) {
663             int start = info.start;
664             int end = info.end;
665             if (start == -1 && end == -1)
666                 return;
667             if (start == -1)
668                 start = end;
669             if (end == -1)
670                 end = start;
671             try {
672                 h.addHighlight(info.start, info.end,
673                         new DefaultHighlighter.DefaultHighlightPainter(c));
674                 if (info.pos != -1) {
675                     Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
676                     h.addHighlight(info.pos, info.pos + 1,
677                         new DefaultHighlighter.DefaultHighlightPainter(c2));
678                 }
679             } catch (BadLocationException e) {
680                 e.printStackTrace();
681             }
682         }
683 
684         /** Get the minimum valid position in a set of info objects. */
685         private int getMinPos(Info... values) {
686             int i = Integer.MAX_VALUE;
687             for (Info info: values) {
688                 if (info.start >= 0) i = Math.min(i, info.start);
689                 if (info.pos   >= 0) i = Math.min(i, info.pos);
690                 if (info.end   >= 0) i = Math.min(i, info.end);
691             }
692             return (i == Integer.MAX_VALUE) ? 0 : i;
693         }
694 
695         /** Set the background on a component. */
696         private JComponent setBackground(JComponent comp, Color c) {
697             comp.setOpaque(true);
698             comp.setBackground(c);
699             return comp;
700         }
701 
702         /** Scroll a text area to display a given position near the middle of the visible area. */
703         private void scroll(final JTextArea t, final int pos) {
704             // Using invokeLater appears to give text a chance to sort itself out
705             // before the scroll happens; otherwise scrollRectToVisible doesn't work.
706             // Maybe there's a better way to sync with the text...
707             EventQueue.invokeLater(new Runnable() {
708                 public void run() {
709                     try {
710                         Rectangle r = t.modelToView(pos);
711                         JScrollPane p = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, t);
712                         r.y = Math.max(0, r.y - p.getHeight() * 2 / 5);
713                         r.height += p.getHeight() * 4 / 5;
714                         t.scrollRectToVisible(r);
715                     } catch (BadLocationException ignore) {
716                     }
717                 }
718             });
719         }
720 
721         private JComboBox entries;
722         private JTextField checkField;
723         private InfoPanel enclPanel;
724         private InfoPanel selfPanel;
725         private JTextArea body;
726         private JTextField statusText;
727 
728         private Color selfColor = new Color(0.f, 1.f, 0.f, 0.2f); // 20% green
729         private Color enclColor = new Color(1.f, 0.f, 0.f, 0.2f); // 20% red
730 
731         /** Panel to display an Info object. */
732         private class InfoPanel extends JPanel {
733             InfoPanel() {
734                 add(tagName = createTextField(20));
735                 add(new JLabel("start:"));
736                 add(addListener(start = createTextField(6)));
737                 add(new JLabel("pos:"));
738                 add(addListener(pos = createTextField(6)));
739                 add(new JLabel("end:"));
740                 add(addListener(end = createTextField(6)));
741             }
742 
743             void setInfo(Info info) {
744                 this.info = info;
745                 tagName.setText(treeUtil.nameFromTag(info.tag));
746                 start.setText(String.valueOf(info.start));
747                 pos.setText(String.valueOf(info.pos));
748                 end.setText(String.valueOf(info.end));
749             }
750 
751             JTextField addListener(final JTextField f) {
752                 f.addMouseListener(new MouseAdapter() {
753                     @Override
754                     public void mouseClicked(MouseEvent e) {
755                         body.setCaretPosition(Integer.valueOf(f.getText()));
756                         body.getCaret().setVisible(true);
757                     }
758                 });
759                 return f;
760             }
761 
762             Info info;
763             JTextField tagName;
764             JTextField start;
765             JTextField pos;
766             JTextField end;
767         }
768 
769         /** Object to record information about an error to be displayed. */
770         private class Entry {
771             Entry(JavaFileObject file, String check, Info encl, Info self) {
772                 this.file = file;
773                 this.check = check;
774                 this.encl = encl;
775                 this.self= self;
776             }
777 
778             @Override
779             public String toString() {
780                 return file.getName() + " " + check + " " + getMinPos(encl, self);
781             }
782 
783             final JavaFileObject file;
784             final String check;
785             final Info encl;
786             final Info self;
787         }
788     }
789 
790     /** Number of files that have been analyzed. */
791     static AtomicInteger fileCount = new AtomicInteger();
792 
793 }