test/tools/javac/failover/CheckAttributedTree.java

Wed, 23 Jan 2013 20:57:40 +0000

author
vromero
date
Wed, 23 Jan 2013 20:57:40 +0000
changeset 1520
5c956be64b9e
parent 1482
954541f13717
child 1521
71f35e4b93a5
permissions
-rw-r--r--

8006694: temporarily workaround combo tests are causing time out in several platforms
Reviewed-by: jjg
Contributed-by: maurizio.cimadamore@oracle.com

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

mercurial