TreePosTest.java revision 2453:3dfd962149b2
1/*
2 * Copyright (c) 2010, 2013, 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
24import java.awt.BorderLayout;
25import java.awt.Color;
26import java.awt.Dimension;
27import java.awt.EventQueue;
28import java.awt.Font;
29import java.awt.GridBagConstraints;
30import java.awt.GridBagLayout;
31import java.awt.Rectangle;
32import java.awt.event.ActionEvent;
33import java.awt.event.ActionListener;
34import java.awt.event.MouseAdapter;
35import java.awt.event.MouseEvent;
36import java.io.File;
37import java.io.IOException;
38import java.io.PrintStream;
39import java.io.PrintWriter;
40import java.io.StringWriter;
41import java.lang.reflect.Field;
42import java.lang.reflect.Modifier;
43import java.nio.charset.Charset;
44import java.util.ArrayList;
45import java.util.Collections;
46import java.util.HashMap;
47import java.util.HashSet;
48import java.util.Iterator;
49import java.util.List;
50import java.util.Map;
51import java.util.Set;
52import javax.swing.DefaultComboBoxModel;
53import javax.swing.JComboBox;
54import javax.swing.JComponent;
55import javax.swing.JFrame;
56import javax.swing.JLabel;
57import javax.swing.JPanel;
58import javax.swing.JScrollPane;
59import javax.swing.JTextArea;
60import javax.swing.JTextField;
61import javax.swing.SwingUtilities;
62import javax.swing.event.CaretEvent;
63import javax.swing.event.CaretListener;
64import javax.swing.text.BadLocationException;
65import javax.swing.text.DefaultHighlighter;
66import javax.swing.text.Highlighter;
67import javax.tools.Diagnostic;
68import javax.tools.DiagnosticListener;
69import javax.tools.JavaFileObject;
70import javax.tools.StandardJavaFileManager;
71
72import com.sun.source.tree.CompilationUnitTree;
73import com.sun.source.util.JavacTask;
74import com.sun.tools.javac.api.JavacTool;
75import com.sun.tools.javac.code.Flags;
76import com.sun.tools.javac.tree.EndPosTable;
77import com.sun.tools.javac.tree.JCTree;
78import com.sun.tools.javac.tree.JCTree.JCAnnotatedType;
79import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
80import com.sun.tools.javac.tree.JCTree.JCNewClass;
81import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
82import com.sun.tools.javac.tree.TreeInfo;
83import com.sun.tools.javac.tree.TreeScanner;
84
85import static com.sun.tools.javac.tree.JCTree.Tag.*;
86import static com.sun.tools.javac.util.Position.NOPOS;
87
88/**
89 * Utility and test program to check validity of tree positions for tree nodes.
90 * The program can be run standalone, or as a jtreg test.  In standalone mode,
91 * errors can be displayed in a gui viewer. For info on command line args,
92 * run program with no args.
93 *
94 * <p>
95 * jtreg: Note that by using the -r switch in the test description below, this test
96 * will process all java files in the langtools/test directory, thus implicitly
97 * covering any new language features that may be tested in this test suite.
98 */
99
100/*
101 * @test
102 * @bug 6919889
103 * @summary assorted position errors in compiler syntax trees
104 * OLD: -q -r -ef ./tools/javac/typeAnnotations -ef ./tools/javap/typeAnnotations -et ANNOTATED_TYPE .
105 * @run main TreePosTest -q -r .
106 */
107public class TreePosTest {
108    /**
109     * Main entry point.
110     * If test.src is set, program runs in jtreg mode, and will throw an Error
111     * if any errors arise, otherwise System.exit will be used, unless the gui
112     * viewer is being used. In jtreg mode, the default base directory for file
113     * args is the value of ${test.src}. In jtreg mode, the -r option can be
114     * given to change the default base directory to the root test directory.
115     */
116    public static void main(String... args) {
117        String testSrc = System.getProperty("test.src");
118        File baseDir = (testSrc == null) ? null : new File(testSrc);
119        boolean ok = new TreePosTest().run(baseDir, args);
120        if (!ok) {
121            if (testSrc != null)  // jtreg mode
122                throw new Error("failed");
123            else
124                System.exit(1);
125        }
126    }
127
128    /**
129     * Run the program. A base directory can be provided for file arguments.
130     * In jtreg mode, the -r option can be given to change the default base
131     * directory to the test root directory. For other options, see usage().
132     * @param baseDir base directory for any file arguments.
133     * @param args command line args
134     * @return true if successful or in gui mode
135     */
136    boolean run(File baseDir, String... args) {
137        if (args.length == 0) {
138            usage(System.out);
139            return true;
140        }
141
142        List<File> files = new ArrayList<File>();
143        for (int i = 0; i < args.length; i++) {
144            String arg = args[i];
145            if (arg.equals("-encoding") && i + 1 < args.length)
146                encoding = args[++i];
147            else if (arg.equals("-gui"))
148                gui = true;
149            else if (arg.equals("-q"))
150                quiet = true;
151            else if (arg.equals("-v"))
152                verbose = true;
153            else if (arg.equals("-t") && i + 1 < args.length)
154                tags.add(args[++i]);
155            else if (arg.equals("-ef") && i + 1 < args.length)
156                excludeFiles.add(new File(baseDir, args[++i]));
157            else if (arg.equals("-et") && i + 1 < args.length)
158                excludeTags.add(args[++i]);
159            else if (arg.equals("-r")) {
160                if (excludeFiles.size() > 0)
161                    throw new Error("-r must be used before -ef");
162                File d = baseDir;
163                while (!new File(d, "TEST.ROOT").exists()) {
164                    d = d.getParentFile();
165                    if (d == null)
166                        throw new Error("cannot find TEST.ROOT");
167                }
168                baseDir = d;
169            }
170            else if (arg.startsWith("-"))
171                throw new Error("unknown option: " + arg);
172            else {
173                while (i < args.length)
174                    files.add(new File(baseDir, args[i++]));
175            }
176        }
177
178        for (File file: files) {
179            if (file.exists())
180                test(file);
181            else
182                error("File not found: " + file);
183        }
184
185        if (fileCount != 1)
186            System.err.println(fileCount + " files read");
187        if (errors > 0)
188            System.err.println(errors + " errors");
189
190        return (gui || errors == 0);
191    }
192
193    /**
194     * Print command line help.
195     * @param out output stream
196     */
197    void usage(PrintStream out) {
198        out.println("Usage:");
199        out.println("  java TreePosTest options... files...");
200        out.println("");
201        out.println("where options include:");
202        out.println("-gui      Display returns in a GUI viewer");
203        out.println("-q        Quiet: don't report on inapplicable files");
204        out.println("-v        Verbose: report on files as they are being read");
205        out.println("-t tag    Limit checks to tree nodes with this tag");
206        out.println("          Can be repeated if desired");
207        out.println("-ef file  Exclude file or directory");
208        out.println("-et tag   Exclude tree nodes with given tag name");
209        out.println("");
210        out.println("files may be directories or files");
211        out.println("directories will be scanned recursively");
212        out.println("non java files, or java files which cannot be parsed, will be ignored");
213        out.println("");
214    }
215
216    /**
217     * Test a file. If the file is a directory, it will be recursively scanned
218     * for java files.
219     * @param file the file or directory to test
220     */
221    void test(File file) {
222        if (excludeFiles.contains(file)) {
223            if (!quiet)
224                error("File " + file + " excluded");
225            return;
226        }
227
228        if (file.isDirectory()) {
229            for (File f: file.listFiles()) {
230                test(f);
231            }
232            return;
233        }
234
235        if (file.isFile() && file.getName().endsWith(".java")) {
236            try {
237                if (verbose)
238                    System.err.println(file);
239                fileCount++;
240                PosTester p = new PosTester();
241                p.test(read(file));
242            } catch (ParseException e) {
243                if (!quiet) {
244                    error("Error parsing " + file + "\n" + e.getMessage());
245                }
246            } catch (IOException e) {
247                error("Error reading " + file + ": " + e);
248            }
249            return;
250        }
251
252        if (!quiet)
253            error("File " + file + " ignored");
254    }
255
256    // See CR:  6982992 Tests CheckAttributedTree.java, JavacTreeScannerTest.java, and SourceTreeeScannerTest.java timeout
257    StringWriter sw = new StringWriter();
258    PrintWriter pw = new PrintWriter(sw);
259    Reporter r = new Reporter(pw);
260    JavacTool tool = JavacTool.create();
261    StandardJavaFileManager fm = tool.getStandardFileManager(r, null, null);
262
263    /**
264     * Read a file.
265     * @param file the file to be read
266     * @return the tree for the content of the file
267     * @throws IOException if any IO errors occur
268     * @throws TreePosTest.ParseException if any errors occur while parsing the file
269     */
270    JCCompilationUnit read(File file) throws IOException, ParseException {
271        JavacTool tool = JavacTool.create();
272        r.errors = 0;
273        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file);
274        JavacTask task = tool.getTask(pw, fm, r, Collections.<String>emptyList(), null, files);
275        Iterable<? extends CompilationUnitTree> trees = task.parse();
276        pw.flush();
277        if (r.errors > 0)
278            throw new ParseException(sw.toString());
279        Iterator<? extends CompilationUnitTree> iter = trees.iterator();
280        if (!iter.hasNext())
281            throw new Error("no trees found");
282        JCCompilationUnit t = (JCCompilationUnit) iter.next();
283        if (iter.hasNext())
284            throw new Error("too many trees found");
285        return t;
286    }
287
288    /**
289     * Report an error. When the program is complete, the program will either
290     * exit or throw an Error if any errors have been reported.
291     * @param msg the error message
292     */
293    void error(String msg) {
294        System.err.println(msg);
295        errors++;
296    }
297
298    /**
299     * Names for tree tags.
300     */
301    private static String getTagName(JCTree.Tag tag) {
302        String name = tag.name();
303        return (name == null) ? "??" : name;
304    }
305
306    /** Number of files that have been analyzed. */
307    int fileCount;
308    /** Number of errors reported. */
309    int errors;
310    /** Flag: don't report irrelevant files. */
311    boolean quiet;
312    /** Flag: report files as they are processed. */
313    boolean verbose;
314    /** Flag: show errors in GUI viewer. */
315    boolean gui;
316    /** Option: encoding for test files. */
317    String encoding;
318    /** The GUI viewer for errors. */
319    Viewer viewer;
320    /** The set of tags for tree nodes to be analyzed; if empty, all tree nodes
321     * are analyzed. */
322    Set<String> tags = new HashSet<String>();
323    /** Set of files and directories to be excluded from analysis. */
324    Set<File> excludeFiles = new HashSet<File>();
325    /** Set of tag names to be excluded from analysis. */
326    Set<String> excludeTags = new HashSet<String>();
327
328    /**
329     * Main class for testing assertions concerning tree positions for tree nodes.
330     */
331    private class PosTester extends TreeScanner {
332        void test(JCCompilationUnit tree) {
333            sourcefile = tree.sourcefile;
334            endPosTable = tree.endPositions;
335            encl = new Info();
336            tree.accept(this);
337        }
338
339        @Override
340        public void scan(JCTree tree) {
341            if (tree == null)
342                return;
343
344            Info self = new Info(tree, endPosTable);
345            if (check(encl, self)) {
346                // Modifiers nodes are present throughout the tree even where
347                // there is no corresponding source text.
348                // Redundant semicolons in a class definition can cause empty
349                // initializer blocks with no positions.
350                if ((self.tag == MODIFIERS || self.tag == BLOCK)
351                        && self.pos == NOPOS) {
352                    // If pos is NOPOS, so should be the start and end positions
353                    check("start == NOPOS", encl, self, self.start == NOPOS);
354                    check("end == NOPOS", encl, self, self.end == NOPOS);
355                } else {
356                    // For this node, start , pos, and endpos should be all defined
357                    check("start != NOPOS", encl, self, self.start != NOPOS);
358                    check("pos != NOPOS", encl, self, self.pos != NOPOS);
359                    check("end != NOPOS", encl, self, self.end != NOPOS);
360                    // The following should normally be ordered
361                    // encl.start <= start <= pos <= end <= encl.end
362                    // In addition, the position of the enclosing node should be
363                    // within this node.
364                    // The primary exceptions are for array type nodes, because of the
365                    // need to support legacy syntax:
366                    //    e.g.    int a[];    int[] b[];    int f()[] { return null; }
367                    // and because of inconsistent nesting of left and right of
368                    // array declarations:
369                    //    e.g.    int[][] a = new int[2][];
370                    if (!(encl.tag == REFERENCE && self.tag == ANNOTATED_TYPE)) {
371                    check("encl.start <= start", encl, self, encl.start <= self.start);
372                    }
373                    check("start <= pos", encl, self, self.start <= self.pos);
374                    if (!( (self.tag == TYPEARRAY ||
375                            isAnnotatedArray(self.tree))
376                            && (encl.tag == VARDEF ||
377                                encl.tag == METHODDEF ||
378                                encl.tag == TYPEARRAY ||
379                                isAnnotatedArray(encl.tree))
380                           ||
381                            encl.tag == ANNOTATED_TYPE && self.tag == SELECT
382                           ||
383                            encl.tag == REFERENCE && self.tag == ANNOTATED_TYPE
384                         )) {
385                        check("encl.pos <= start || end <= encl.pos",
386                                encl, self, encl.pos <= self.start || self.end <= encl.pos);
387                    }
388                    check("pos <= end", encl, self, self.pos <= self.end);
389                    if (!( (self.tag == TYPEARRAY || isAnnotatedArray(self.tree)) &&
390                            (encl.tag == TYPEARRAY || isAnnotatedArray(encl.tree))
391                           ||
392                            encl.tag == MODIFIERS && self.tag == ANNOTATION
393                         ) ) {
394                        check("end <= encl.end", encl, self, self.end <= encl.end);
395                    }
396                }
397            }
398
399            Info prevEncl = encl;
400            encl = self;
401            tree.accept(this);
402            encl = prevEncl;
403        }
404
405        private boolean isAnnotatedArray(JCTree tree) {
406            return tree.hasTag(ANNOTATED_TYPE) &&
407                            ((JCAnnotatedType)tree).underlyingType.hasTag(TYPEARRAY);
408        }
409
410        @Override
411        public void visitVarDef(JCVariableDecl tree) {
412            // enum member declarations are desugared in the parser and have
413            // ill-defined semantics for tree positions, so for now, we
414            // skip the synthesized bits and just check parts which came from
415            // the original source text
416            if ((tree.mods.flags & Flags.ENUM) != 0) {
417                scan(tree.mods);
418                if (tree.init != null) {
419                    if (tree.init.hasTag(NEWCLASS)) {
420                        JCNewClass init = (JCNewClass) tree.init;
421                        if (init.args != null && init.args.nonEmpty()) {
422                            scan(init.args);
423                        }
424                        if (init.def != null && init.def.defs != null) {
425                            scan(init.def.defs);
426                        }
427                    }
428                }
429            } else
430                super.visitVarDef(tree);
431        }
432
433        boolean check(Info encl, Info self) {
434            if (excludeTags.size() > 0) {
435                if (encl != null && excludeTags.contains(getTagName(encl.tag))
436                        || excludeTags.contains(getTagName(self.tag)))
437                    return false;
438            }
439            return tags.size() == 0 || tags.contains(getTagName(self.tag));
440        }
441
442        void check(String label, Info encl, Info self, boolean ok) {
443            if (!ok) {
444                if (gui) {
445                    if (viewer == null)
446                        viewer = new Viewer();
447                    viewer.addEntry(sourcefile, label, encl, self);
448                }
449
450                String s = "encl: " + encl.tree.toString() +
451                        "  this: " + self.tree.toString();
452                String msg = sourcefile.getName() + ": " + label + ": " +
453                        "encl:" + encl + " this:" + self + "\n" +
454                        s.substring(0, Math.min(80, s.length())).replaceAll("[\r\n]+", " ");
455                error(msg);
456            }
457        }
458
459        JavaFileObject sourcefile;
460        EndPosTable endPosTable;
461        Info encl;
462
463    }
464
465    /**
466     * Utility class providing easy access to position and other info for a tree node.
467     */
468    private class Info {
469        Info() {
470            tree = null;
471            tag = ERRONEOUS;
472            start = 0;
473            pos = 0;
474            end = Integer.MAX_VALUE;
475        }
476
477        Info(JCTree tree, EndPosTable endPosTable) {
478            this.tree = tree;
479            tag = tree.getTag();
480            start = TreeInfo.getStartPos(tree);
481            pos = tree.pos;
482            end = TreeInfo.getEndPos(tree, endPosTable);
483        }
484
485        @Override
486        public String toString() {
487            return getTagName(tree.getTag()) + "[start:" + start + ",pos:" + pos + ",end:" + end + "]";
488        }
489
490        final JCTree tree;
491        final JCTree.Tag tag;
492        final int start;
493        final int pos;
494        final int end;
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(getTagName(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
768