test/tools/javac/failover/CheckAttributedTree.java

Tue, 08 Jan 2013 13:47:57 +0000

author
vromero
date
Tue, 08 Jan 2013 13:47:57 +0000
changeset 1482
954541f13717
parent 1348
573ceb23beeb
child 1520
5c956be64b9e
permissions
-rw-r--r--

8005167: execution time of combo tests in javac should be improved
Reviewed-by: jjg, jjh

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

mercurial