test/tools/javac/failover/CheckAttributedTree.java

Tue, 28 Dec 2010 15:54:52 -0800

author
ohair
date
Tue, 28 Dec 2010 15:54:52 -0800
changeset 798
4868a36f6fd8
parent 683
bbc9765d9ec6
child 808
e8719f95f2d0
permissions
-rw-r--r--

6962318: Update copyright year
Reviewed-by: xdono

     1 /*
     2  * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  */
    24 import com.sun.source.util.TaskEvent;
    25 import java.awt.BorderLayout;
    26 import java.awt.Color;
    27 import java.awt.Dimension;
    28 import java.awt.EventQueue;
    29 import java.awt.Font;
    30 import java.awt.GridBagConstraints;
    31 import java.awt.GridBagLayout;
    32 import java.awt.Rectangle;
    33 import java.awt.event.ActionEvent;
    34 import java.awt.event.ActionListener;
    35 import java.awt.event.MouseAdapter;
    36 import java.awt.event.MouseEvent;
    37 import javax.swing.DefaultComboBoxModel;
    38 import javax.swing.JComboBox;
    39 import javax.swing.JComponent;
    40 import javax.swing.JFrame;
    41 import javax.swing.JLabel;
    42 import javax.swing.JPanel;
    43 import javax.swing.JScrollPane;
    44 import javax.swing.JTextArea;
    45 import javax.swing.JTextField;
    46 import javax.swing.SwingUtilities;
    47 import javax.swing.event.CaretEvent;
    48 import javax.swing.event.CaretListener;
    49 import javax.swing.text.BadLocationException;
    50 import javax.swing.text.DefaultHighlighter;
    51 import javax.swing.text.Highlighter;
    52 import java.io.File;
    53 import java.io.IOException;
    54 import java.io.PrintStream;
    55 import java.io.PrintWriter;
    56 import java.io.StringWriter;
    57 import java.lang.reflect.Field;
    58 import java.lang.reflect.Modifier;
    59 import java.nio.charset.Charset;
    60 import java.util.ArrayList;
    61 import java.util.HashMap;
    62 import java.util.List;
    63 import java.util.Map;
    64 import javax.tools.Diagnostic;
    65 import javax.tools.DiagnosticListener;
    66 import javax.tools.JavaFileObject;
    67 import javax.tools.StandardJavaFileManager;
    69 import com.sun.source.tree.CompilationUnitTree;
    70 import com.sun.source.util.JavacTask;
    71 import com.sun.source.util.TaskListener;
    72 import com.sun.tools.javac.api.JavacTool;
    73 import com.sun.tools.javac.code.Symbol;
    74 import com.sun.tools.javac.code.Type;
    75 import com.sun.tools.javac.tree.JCTree;
    76 import com.sun.tools.javac.tree.JCTree.JCClassDecl;
    77 import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
    78 import com.sun.tools.javac.tree.JCTree.JCImport;
    79 import com.sun.tools.javac.tree.TreeInfo;
    80 import com.sun.tools.javac.tree.TreeScanner;
    81 import com.sun.tools.javac.util.Pair;
    83 import java.util.Arrays;
    84 import java.util.HashSet;
    85 import java.util.Set;
    86 import javax.lang.model.element.Element;
    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  */
   100 /*
   101  * @test
   102  * @bug 6970584
   103  * @summary assorted position errors in compiler syntax trees
   104  * @run main CheckAttributedTree -q -r -et ERRONEOUS .
   105  */
   106 public class CheckAttributedTree {
   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) {
   116         String testSrc = System.getProperty("test.src");
   117         File baseDir = (testSrc == null) ? null : new File(testSrc);
   118         boolean ok = new CheckAttributedTree().run(baseDir, args);
   119         if (!ok) {
   120             if (testSrc != null)  // jtreg mode
   121                 throw new Error("failed");
   122             else
   123                 System.exit(1);
   124         }
   125     }
   127     /**
   128      * Run the program. A base directory can be provided for file arguments.
   129      * In jtreg mode, the -r option can be given to change the default base
   130      * directory to the test root directory. For other options, see usage().
   131      * @param baseDir base directory for any file arguments.
   132      * @param args command line args
   133      * @return true if successful or in gui mode
   134      */
   135     boolean run(File baseDir, String... args) {
   136         if (args.length == 0) {
   137             usage(System.out);
   138             return true;
   139         }
   141         List<File> files = new ArrayList<File>();
   142         for (int i = 0; i < args.length; i++) {
   143             String arg = args[i];
   144             if (arg.equals("-encoding") && i + 1 < args.length)
   145                 encoding = args[++i];
   146             else if (arg.equals("-gui"))
   147                 gui = true;
   148             else if (arg.equals("-q"))
   149                 quiet = true;
   150             else if (arg.equals("-v"))
   151                 verbose = true;
   152             else if (arg.equals("-t") && i + 1 < args.length)
   153                 tags.add(args[++i]);
   154             else if (arg.equals("-ef") && i + 1 < args.length)
   155                 excludeFiles.add(new File(baseDir, args[++i]));
   156             else if (arg.equals("-et") && i + 1 < args.length)
   157                 excludeTags.add(args[++i]);
   158             else if (arg.equals("-r")) {
   159                 if (excludeFiles.size() > 0)
   160                     throw new Error("-r must be used before -ef");
   161                 File d = baseDir;
   162                 while (!new File(d, "TEST.ROOT").exists()) {
   163                     if (d == null)
   164                         throw new Error("cannot find TEST.ROOT");
   165                     d = d.getParentFile();
   166                 }
   167                 baseDir = d;
   168             }
   169             else if (arg.startsWith("-"))
   170                 throw new Error("unknown option: " + arg);
   171             else {
   172                 while (i < args.length)
   173                     files.add(new File(baseDir, args[i++]));
   174             }
   175         }
   177         for (File file: files) {
   178             if (file.exists())
   179                 test(file);
   180             else
   181                 error("File not found: " + file);
   182         }
   184         if (fileCount != 1)
   185             System.err.println(fileCount + " files read");
   186         if (errors > 0)
   187             System.err.println(errors + " errors");
   189         return (gui || errors == 0);
   190     }
   192     /**
   193      * Print command line help.
   194      * @param out output stream
   195      */
   196     void usage(PrintStream out) {
   197         out.println("Usage:");
   198         out.println("  java CheckAttributedTree options... files...");
   199         out.println("");
   200         out.println("where options include:");
   201         out.println("-q        Quiet: don't report on inapplicable files");
   202         out.println("-gui      Display returns in a GUI viewer");
   203         out.println("-v        Verbose: report on files as they are being read");
   204         out.println("-t tag    Limit checks to tree nodes with this tag");
   205         out.println("          Can be repeated if desired");
   206         out.println("-ef file  Exclude file or directory");
   207         out.println("-et tag   Exclude tree nodes with given tag name");
   208         out.println("");
   209         out.println("files may be directories or files");
   210         out.println("directories will be scanned recursively");
   211         out.println("non java files, or java files which cannot be parsed, will be ignored");
   212         out.println("");
   213     }
   215     /**
   216      * Test a file. If the file is a directory, it will be recursively scanned
   217      * for java files.
   218      * @param file the file or directory to test
   219      */
   220     void test(File file) {
   221         if (excludeFiles.contains(file)) {
   222             if (!quiet)
   223                 error("File " + file + " excluded");
   224             return;
   225         }
   227         if (file.isDirectory()) {
   228             for (File f: file.listFiles()) {
   229                 test(f);
   230             }
   231             return;
   232         }
   234         if (file.isFile() && file.getName().endsWith(".java")) {
   235             try {
   236                 if (verbose)
   237                     System.err.println(file);
   238                 fileCount++;
   239                 NPETester p = new NPETester();
   240                 p.test(read(file));
   241             } catch (AttributionException e) {
   242                 if (!quiet) {
   243                     error("Error attributing " + file + "\n" + e.getMessage());
   244                 }
   245             } catch (IOException e) {
   246                 error("Error reading " + file + ": " + e);
   247             }
   248             return;
   249         }
   251         if (!quiet)
   252             error("File " + file + " ignored");
   253     }
   255     /**
   256      * Read a file.
   257      * @param file the file to be read
   258      * @return the tree for the content of the file
   259      * @throws IOException if any IO errors occur
   260      * @throws TreePosTest.ParseException if any errors occur while parsing the file
   261      */
   262     List<Pair<JCCompilationUnit, JCTree>> read(File file) throws IOException, AttributionException {
   263         StringWriter sw = new StringWriter();
   264         PrintWriter pw = new PrintWriter(sw);
   265         Reporter r = new Reporter(pw);
   266         JavacTool tool = JavacTool.create();
   267         Charset cs = (encoding == null ? null : Charset.forName(encoding));
   268         StandardJavaFileManager fm = tool.getStandardFileManager(r, null, null);
   269         Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file);
   270         String[] opts = { "-XDshouldStopPolicy=ATTR", "-XDverboseCompilePolicy" };
   271         JavacTask task = tool.getTask(pw, fm, r, Arrays.asList(opts), null, files);
   272         final List<Element> analyzedElems = new ArrayList<>();
   273         task.setTaskListener(new TaskListener() {
   274             public void started(TaskEvent e) {
   275                 if (e.getKind() == TaskEvent.Kind.ANALYZE)
   276                         analyzedElems.add(e.getTypeElement());
   277             }
   278             public void finished(TaskEvent e) { }
   279         });
   281         try {
   282             Iterable<? extends CompilationUnitTree> trees = task.parse();
   283             task.analyze();
   284             List<Pair<JCCompilationUnit, JCTree>> res = new ArrayList<>();
   285             //System.out.println("Try to add pairs. Elems are " + analyzedElems);
   286             for (CompilationUnitTree t : trees) {
   287                JCCompilationUnit cu = (JCCompilationUnit)t;
   288                for (JCTree def : cu.defs) {
   289                    if (def.getTag() == JCTree.CLASSDEF &&
   290                            analyzedElems.contains(((JCTree.JCClassDecl)def).sym)) {
   291                        //System.out.println("Adding pair...");
   292                        res.add(new Pair<>(cu, def));
   293                    }
   294                }
   295             }
   296             return res;
   297         }
   298         catch (Throwable t) {
   299             throw new AttributionException("Exception while attributing file: " + file);
   300         }
   301     }
   303     /**
   304      * Report an error. When the program is complete, the program will either
   305      * exit or throw an Error if any errors have been reported.
   306      * @param msg the error message
   307      */
   308     void error(String msg) {
   309         System.err.println(msg);
   310         errors++;
   311     }
   313     /** Number of files that have been analyzed. */
   314     int fileCount;
   315     /** Number of errors reported. */
   316     int errors;
   317     /** Flag: don't report irrelevant files. */
   318     boolean quiet;
   319     /** Flag: show errors in GUI viewer. */
   320     boolean gui;
   321     /** The GUI viewer for errors. */
   322     Viewer viewer;
   323     /** Flag: report files as they are processed. */
   324     boolean verbose;
   325     /** Option: encoding for test files. */
   326     String encoding;
   327     /** The set of tags for tree nodes to be analyzed; if empty, all tree nodes
   328      * are analyzed. */
   329     Set<String> tags = new HashSet<String>();
   330     /** Set of files and directories to be excluded from analysis. */
   331     Set<File> excludeFiles = new HashSet<File>();
   332     /** Set of tag names to be excluded from analysis. */
   333     Set<String> excludeTags = new HashSet<String>();
   334     /** Utility class for trees */
   335     TreeUtil treeUtil = new TreeUtil();
   337     /**
   338      * Main class for testing assertions concerning types/symbol
   339      * left uninitialized after attribution
   340      */
   341     private class NPETester extends TreeScanner {
   342         void test(List<Pair<JCCompilationUnit, JCTree>> trees) {
   343             for (Pair<JCCompilationUnit, JCTree> p : trees) {
   344                 sourcefile = p.fst.sourcefile;
   345                 endPosTable = p.fst.endPositions;
   346                 encl = new Info(p.snd, endPosTable);
   347                 p.snd.accept(this);
   348             }
   349         }
   351         @Override
   352         public void scan(JCTree tree) {
   353             if (tree == null ||
   354                     excludeTags.contains(treeUtil.nameFromTag(tree.getTag()))) {
   355                 return;
   356             }
   358             Info self = new Info(tree, endPosTable);
   359             check(!mandatoryType(tree) ||
   360                     (tree.type != null &&
   361                     checkFields(tree)),
   362                     "'null' found in tree ",
   363                     self);
   365             Info prevEncl = encl;
   366             encl = self;
   367             tree.accept(this);
   368             encl = prevEncl;
   369         }
   371         private boolean mandatoryType(JCTree that) {
   372             return that instanceof JCTree.JCExpression ||
   373                     that.getTag() == JCTree.VARDEF ||
   374                     that.getTag() == JCTree.METHODDEF ||
   375                     that.getTag() == JCTree.CLASSDEF;
   376         }
   378         private final List<String> excludedFields = Arrays.asList("varargsElement");
   380         void check(boolean ok, String label, Info self) {
   381             if (!ok) {
   382                 if (gui) {
   383                     if (viewer == null)
   384                         viewer = new Viewer();
   385                     viewer.addEntry(sourcefile, label, encl, self);
   386                 }
   387                 error(label + self.toString() + " encl: " + encl.toString() + " in file: " + sourcefile + "  " + self.tree);
   388             }
   389         }
   391         boolean checkFields(JCTree t) {
   392             List<Field> fieldsToCheck = treeUtil.getFieldsOfType(t,
   393                     excludedFields,
   394                     Symbol.class,
   395                     Type.class);
   396             for (Field f : fieldsToCheck) {
   397                 try {
   398                     if (f.get(t) == null) {
   399                         return false;
   400                     }
   401                 }
   402                 catch (IllegalAccessException e) {
   403                     System.err.println("Cannot read field: " + f);
   404                     //swallow it
   405                 }
   406             }
   407             return true;
   408         }
   410         @Override
   411         public void visitImport(JCImport tree) { }
   413         @Override
   414         public void visitTopLevel(JCCompilationUnit tree) {
   415             scan(tree.defs);
   416         }
   418         JavaFileObject sourcefile;
   419         Map<JCTree, Integer> endPosTable;
   420         Info encl;
   421     }
   423     /**
   424      * Utility class providing easy access to position and other info for a tree node.
   425      */
   426     private class Info {
   427         Info() {
   428             tree = null;
   429             tag = JCTree.ERRONEOUS;
   430             start = 0;
   431             pos = 0;
   432             end = Integer.MAX_VALUE;
   433         }
   435         Info(JCTree tree, Map<JCTree, Integer> endPosTable) {
   436             this.tree = tree;
   437             tag = tree.getTag();
   438             start = TreeInfo.getStartPos(tree);
   439             pos = tree.pos;
   440             end = TreeInfo.getEndPos(tree, endPosTable);
   441         }
   443         @Override
   444         public String toString() {
   445             return treeUtil.nameFromTag(tree.getTag()) + "[start:" + start + ",pos:" + pos + ",end:" + end + "]";
   446         }
   448         final JCTree tree;
   449         final int tag;
   450         final int start;
   451         final int pos;
   452         final int end;
   453     }
   455     /**
   456      * Names for tree tags.
   457      * javac does not provide an API to convert tag values to strings, so this class uses
   458      * reflection to determine names of public static final int values in JCTree.
   459      */
   460     private static class TreeUtil {
   461         String nameFromTag(int tag) {
   462             if (names == null) {
   463                 names = new HashMap<Integer, String>();
   464                 Class c = JCTree.class;
   465                 for (Field f : c.getDeclaredFields()) {
   466                     if (f.getType().equals(int.class)) {
   467                         int mods = f.getModifiers();
   468                         if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
   469                             try {
   470                                 names.put(f.getInt(null), f.getName());
   471                             } catch (IllegalAccessException e) {
   472                             }
   473                         }
   474                     }
   475                 }
   476             }
   477             String name = names.get(tag);
   478             return (name == null) ? "??" : name;
   479         }
   481         List<Field> getFieldsOfType(JCTree t, List<String> excludeNames, Class<?>... types) {
   482             List<Field> buf = new ArrayList<Field>();
   483             for (Field f : t.getClass().getDeclaredFields()) {
   484                 if (!excludeNames.contains(f.getName())) {
   485                     for (Class<?> type : types) {
   486                         if (type.isAssignableFrom(f.getType())) {
   487                             f.setAccessible(true);
   488                             buf.add(f);
   489                             break;
   490                         }
   491                     }
   492                 }
   493             }
   494             return buf;
   495         }
   497         private Map<Integer, String> names;
   498     }
   500     /**
   501      * Thrown when errors are found parsing a java file.
   502      */
   503     private static class ParseException extends Exception {
   504         ParseException(String msg) {
   505             super(msg);
   506         }
   507     }
   509     private static class AttributionException extends Exception {
   510         AttributionException(String msg) {
   511             super(msg);
   512         }
   513     }
   515     /**
   516      * DiagnosticListener to report diagnostics and count any errors that occur.
   517      */
   518     private static class Reporter implements DiagnosticListener<JavaFileObject> {
   519         Reporter(PrintWriter out) {
   520             this.out = out;
   521         }
   523         public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
   524             out.println(diagnostic);
   525             switch (diagnostic.getKind()) {
   526                 case ERROR:
   527                     errors++;
   528             }
   529         }
   530         int errors;
   531         PrintWriter out;
   532     }
   534     /**
   535      * GUI viewer for issues found by TreePosTester. The viewer provides a drop
   536      * down list for selecting error conditions, a header area providing details
   537      * about an error, and a text area with the ranges of text highlighted as
   538      * appropriate.
   539      */
   540     private class Viewer extends JFrame {
   541         /**
   542          * Create a viewer.
   543          */
   544         Viewer() {
   545             initGUI();
   546         }
   548         /**
   549          * Add another entry to the list of errors.
   550          * @param file The file containing the error
   551          * @param check The condition that was being tested, and which failed
   552          * @param encl the enclosing tree node
   553          * @param self the tree node containing the error
   554          */
   555         void addEntry(JavaFileObject file, String check, Info encl, Info self) {
   556             Entry e = new Entry(file, check, encl, self);
   557             DefaultComboBoxModel m = (DefaultComboBoxModel) entries.getModel();
   558             m.addElement(e);
   559             if (m.getSize() == 1)
   560                 entries.setSelectedItem(e);
   561         }
   563         /**
   564          * Initialize the GUI window.
   565          */
   566         private void initGUI() {
   567             JPanel head = new JPanel(new GridBagLayout());
   568             GridBagConstraints lc = new GridBagConstraints();
   569             GridBagConstraints fc = new GridBagConstraints();
   570             fc.anchor = GridBagConstraints.WEST;
   571             fc.fill = GridBagConstraints.HORIZONTAL;
   572             fc.gridwidth = GridBagConstraints.REMAINDER;
   574             entries = new JComboBox();
   575             entries.addActionListener(new ActionListener() {
   576                 public void actionPerformed(ActionEvent e) {
   577                     showEntry((Entry) entries.getSelectedItem());
   578                 }
   579             });
   580             fc.insets.bottom = 10;
   581             head.add(entries, fc);
   582             fc.insets.bottom = 0;
   583             head.add(new JLabel("check:"), lc);
   584             head.add(checkField = createTextField(80), fc);
   585             fc.fill = GridBagConstraints.NONE;
   586             head.add(setBackground(new JLabel("encl:"), enclColor), lc);
   587             head.add(enclPanel = new InfoPanel(), fc);
   588             head.add(setBackground(new JLabel("self:"), selfColor), lc);
   589             head.add(selfPanel = new InfoPanel(), fc);
   590             add(head, BorderLayout.NORTH);
   592             body = new JTextArea();
   593             body.setFont(Font.decode(Font.MONOSPACED));
   594             body.addCaretListener(new CaretListener() {
   595                 public void caretUpdate(CaretEvent e) {
   596                     int dot = e.getDot();
   597                     int mark = e.getMark();
   598                     if (dot == mark)
   599                         statusText.setText("dot: " + dot);
   600                     else
   601                         statusText.setText("dot: " + dot + ", mark:" + mark);
   602                 }
   603             });
   604             JScrollPane p = new JScrollPane(body,
   605                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
   606                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
   607             p.setPreferredSize(new Dimension(640, 480));
   608             add(p, BorderLayout.CENTER);
   610             statusText = createTextField(80);
   611             add(statusText, BorderLayout.SOUTH);
   613             pack();
   614             setLocationRelativeTo(null); // centered on screen
   615             setVisible(true);
   616             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   617         }
   619         /** Show an entry that has been selected. */
   620         private void showEntry(Entry e) {
   621             try {
   622                 // update simple fields
   623                 setTitle(e.file.getName());
   624                 checkField.setText(e.check);
   625                 enclPanel.setInfo(e.encl);
   626                 selfPanel.setInfo(e.self);
   627                 // show file text with highlights
   628                 body.setText(e.file.getCharContent(true).toString());
   629                 Highlighter highlighter = body.getHighlighter();
   630                 highlighter.removeAllHighlights();
   631                 addHighlight(highlighter, e.encl, enclColor);
   632                 addHighlight(highlighter, e.self, selfColor);
   633                 scroll(body, getMinPos(enclPanel.info, selfPanel.info));
   634             } catch (IOException ex) {
   635                 body.setText("Cannot read " + e.file.getName() + ": " + e);
   636             }
   637         }
   639         /** Create a test field. */
   640         private JTextField createTextField(int width) {
   641             JTextField f = new JTextField(width);
   642             f.setEditable(false);
   643             f.setBorder(null);
   644             return f;
   645         }
   647         /** Add a highlighted region based on the positions in an Info object. */
   648         private void addHighlight(Highlighter h, Info info, Color c) {
   649             int start = info.start;
   650             int end = info.end;
   651             if (start == -1 && end == -1)
   652                 return;
   653             if (start == -1)
   654                 start = end;
   655             if (end == -1)
   656                 end = start;
   657             try {
   658                 h.addHighlight(info.start, info.end,
   659                         new DefaultHighlighter.DefaultHighlightPainter(c));
   660                 if (info.pos != -1) {
   661                     Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
   662                     h.addHighlight(info.pos, info.pos + 1,
   663                         new DefaultHighlighter.DefaultHighlightPainter(c2));
   664                 }
   665             } catch (BadLocationException e) {
   666                 e.printStackTrace();
   667             }
   668         }
   670         /** Get the minimum valid position in a set of info objects. */
   671         private int getMinPos(Info... values) {
   672             int i = Integer.MAX_VALUE;
   673             for (Info info: values) {
   674                 if (info.start >= 0) i = Math.min(i, info.start);
   675                 if (info.pos   >= 0) i = Math.min(i, info.pos);
   676                 if (info.end   >= 0) i = Math.min(i, info.end);
   677             }
   678             return (i == Integer.MAX_VALUE) ? 0 : i;
   679         }
   681         /** Set the background on a component. */
   682         private JComponent setBackground(JComponent comp, Color c) {
   683             comp.setOpaque(true);
   684             comp.setBackground(c);
   685             return comp;
   686         }
   688         /** Scroll a text area to display a given position near the middle of the visible area. */
   689         private void scroll(final JTextArea t, final int pos) {
   690             // Using invokeLater appears to give text a chance to sort itself out
   691             // before the scroll happens; otherwise scrollRectToVisible doesn't work.
   692             // Maybe there's a better way to sync with the text...
   693             EventQueue.invokeLater(new Runnable() {
   694                 public void run() {
   695                     try {
   696                         Rectangle r = t.modelToView(pos);
   697                         JScrollPane p = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, t);
   698                         r.y = Math.max(0, r.y - p.getHeight() * 2 / 5);
   699                         r.height += p.getHeight() * 4 / 5;
   700                         t.scrollRectToVisible(r);
   701                     } catch (BadLocationException ignore) {
   702                     }
   703                 }
   704             });
   705         }
   707         private JComboBox entries;
   708         private JTextField checkField;
   709         private InfoPanel enclPanel;
   710         private InfoPanel selfPanel;
   711         private JTextArea body;
   712         private JTextField statusText;
   714         private Color selfColor = new Color(0.f, 1.f, 0.f, 0.2f); // 20% green
   715         private Color enclColor = new Color(1.f, 0.f, 0.f, 0.2f); // 20% red
   717         /** Panel to display an Info object. */
   718         private class InfoPanel extends JPanel {
   719             InfoPanel() {
   720                 add(tagName = createTextField(20));
   721                 add(new JLabel("start:"));
   722                 add(addListener(start = createTextField(6)));
   723                 add(new JLabel("pos:"));
   724                 add(addListener(pos = createTextField(6)));
   725                 add(new JLabel("end:"));
   726                 add(addListener(end = createTextField(6)));
   727             }
   729             void setInfo(Info info) {
   730                 this.info = info;
   731                 tagName.setText(treeUtil.nameFromTag(info.tag));
   732                 start.setText(String.valueOf(info.start));
   733                 pos.setText(String.valueOf(info.pos));
   734                 end.setText(String.valueOf(info.end));
   735             }
   737             JTextField addListener(final JTextField f) {
   738                 f.addMouseListener(new MouseAdapter() {
   739                     @Override
   740                     public void mouseClicked(MouseEvent e) {
   741                         body.setCaretPosition(Integer.valueOf(f.getText()));
   742                         body.getCaret().setVisible(true);
   743                     }
   744                 });
   745                 return f;
   746             }
   748             Info info;
   749             JTextField tagName;
   750             JTextField start;
   751             JTextField pos;
   752             JTextField end;
   753         }
   755         /** Object to record information about an error to be displayed. */
   756         private class Entry {
   757             Entry(JavaFileObject file, String check, Info encl, Info self) {
   758                 this.file = file;
   759                 this.check = check;
   760                 this.encl = encl;
   761                 this.self= self;
   762             }
   764             @Override
   765             public String toString() {
   766                 return file.getName() + " " + check + " " + getMinPos(encl, self);
   767             }
   769             final JavaFileObject file;
   770             final String check;
   771             final Info encl;
   772             final Info self;
   773         }
   774     }
   775 }

mercurial