test/tools/javac/failover/CheckAttributedTree.java

Wed, 23 Jan 2013 13:27:24 -0800

author
jjg
date
Wed, 23 Jan 2013 13:27:24 -0800
changeset 1521
71f35e4b93a5
parent 1520
5c956be64b9e
child 2525
2eb010b6cb22
permissions
-rw-r--r--

8006775: JSR 308: Compiler changes in JDK8
Reviewed-by: jjg
Contributed-by: mernst@cs.washington.edu, wmdietl@cs.washington.edu, mpapi@csail.mit.edu, mahmood@notnoop.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             if (mandatoryType(tree)) {
   366                 check(tree.type != null,
   367                         "'null' field 'type' found in tree ", self);
   368                 if (tree.type==null)
   369                     new Throwable().printStackTrace();
   370             }
   372             Field errField = checkFields(tree);
   373             if (errField!=null) {
   374                 check(false,
   375                         "'null' field '" + errField.getName() + "' found in tree ", self);
   376             }
   378             Info prevEncl = encl;
   379             encl = self;
   380             tree.accept(this);
   381             encl = prevEncl;
   382         }
   384         private boolean mandatoryType(JCTree that) {
   385             return that instanceof JCTree.JCExpression ||
   386                     that.hasTag(VARDEF) ||
   387                     that.hasTag(METHODDEF) ||
   388                     that.hasTag(CLASSDEF);
   389         }
   391         private final List<String> excludedFields = Arrays.asList("varargsElement", "targetType");
   393         void check(boolean ok, String label, Info self) {
   394             if (!ok) {
   395                 if (gui) {
   396                     if (viewer == null)
   397                         viewer = new Viewer();
   398                     viewer.addEntry(sourcefile, label, encl, self);
   399                 }
   400                 error(label + self.toString() + " encl: " + encl.toString() +
   401                         " in file: " + sourcefile + "  " + self.tree);
   402             }
   403         }
   405         Field checkFields(JCTree t) {
   406             List<Field> fieldsToCheck = treeUtil.getFieldsOfType(t,
   407                     excludedFields,
   408                     Symbol.class,
   409                     Type.class);
   410             for (Field f : fieldsToCheck) {
   411                 try {
   412                     if (f.get(t) == null) {
   413                         return f;
   414                     }
   415                 }
   416                 catch (IllegalAccessException e) {
   417                     System.err.println("Cannot read field: " + f);
   418                     //swallow it
   419                 }
   420             }
   421             return null;
   422         }
   424         @Override
   425         public void visitImport(JCImport tree) { }
   427         @Override
   428         public void visitTopLevel(JCCompilationUnit tree) {
   429             scan(tree.defs);
   430         }
   432         JavaFileObject sourcefile;
   433         EndPosTable endPosTable;
   434         Info encl;
   435     }
   437     /**
   438      * Utility class providing easy access to position and other info for a tree node.
   439      */
   440     private class Info {
   441         Info() {
   442             tree = null;
   443             tag = ERRONEOUS;
   444             start = 0;
   445             pos = 0;
   446             end = Integer.MAX_VALUE;
   447         }
   449         Info(JCTree tree, EndPosTable endPosTable) {
   450             this.tree = tree;
   451             tag = tree.getTag();
   452             start = TreeInfo.getStartPos(tree);
   453             pos = tree.pos;
   454             end = TreeInfo.getEndPos(tree, endPosTable);
   455         }
   457         @Override
   458         public String toString() {
   459             return treeUtil.nameFromTag(tree.getTag()) + "[start:" + start + ",pos:" + pos + ",end:" + end + "]";
   460         }
   462         final JCTree tree;
   463         final JCTree.Tag tag;
   464         final int start;
   465         final int pos;
   466         final int end;
   467     }
   469     /**
   470      * Names for tree tags.
   471      */
   472     private static class TreeUtil {
   473         String nameFromTag(JCTree.Tag tag) {
   474             String name = tag.name();
   475             return (name == null) ? "??" : name;
   476         }
   478         List<Field> getFieldsOfType(JCTree t, List<String> excludeNames, Class<?>... types) {
   479             List<Field> buf = new ArrayList<Field>();
   480             for (Field f : t.getClass().getDeclaredFields()) {
   481                 if (!excludeNames.contains(f.getName())) {
   482                     for (Class<?> type : types) {
   483                         if (type.isAssignableFrom(f.getType())) {
   484                             f.setAccessible(true);
   485                             buf.add(f);
   486                             break;
   487                         }
   488                     }
   489                 }
   490             }
   491             return buf;
   492         }
   493     }
   495     /**
   496      * Thrown when errors are found parsing a java file.
   497      */
   498     private static class ParseException extends Exception {
   499         ParseException(String msg) {
   500             super(msg);
   501         }
   502     }
   504     private static class AttributionException extends Exception {
   505         AttributionException(String msg) {
   506             super(msg);
   507         }
   508     }
   510     /**
   511      * DiagnosticListener to report diagnostics and count any errors that occur.
   512      */
   513     private static class Reporter implements DiagnosticListener<JavaFileObject> {
   514         Reporter(PrintWriter out) {
   515             this.out = out;
   516         }
   518         public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
   519             //out.println(diagnostic);
   520             switch (diagnostic.getKind()) {
   521                 case ERROR:
   522                     errors++;
   523             }
   524         }
   525         int errors;
   526         PrintWriter out;
   527     }
   529     /**
   530      * GUI viewer for issues found by TreePosTester. The viewer provides a drop
   531      * down list for selecting error conditions, a header area providing details
   532      * about an error, and a text area with the ranges of text highlighted as
   533      * appropriate.
   534      */
   535     private class Viewer extends JFrame {
   536         /**
   537          * Create a viewer.
   538          */
   539         Viewer() {
   540             initGUI();
   541         }
   543         /**
   544          * Add another entry to the list of errors.
   545          * @param file The file containing the error
   546          * @param check The condition that was being tested, and which failed
   547          * @param encl the enclosing tree node
   548          * @param self the tree node containing the error
   549          */
   550         void addEntry(JavaFileObject file, String check, Info encl, Info self) {
   551             Entry e = new Entry(file, check, encl, self);
   552             DefaultComboBoxModel m = (DefaultComboBoxModel) entries.getModel();
   553             m.addElement(e);
   554             if (m.getSize() == 1)
   555                 entries.setSelectedItem(e);
   556         }
   558         /**
   559          * Initialize the GUI window.
   560          */
   561         private void initGUI() {
   562             JPanel head = new JPanel(new GridBagLayout());
   563             GridBagConstraints lc = new GridBagConstraints();
   564             GridBagConstraints fc = new GridBagConstraints();
   565             fc.anchor = GridBagConstraints.WEST;
   566             fc.fill = GridBagConstraints.HORIZONTAL;
   567             fc.gridwidth = GridBagConstraints.REMAINDER;
   569             entries = new JComboBox();
   570             entries.addActionListener(new ActionListener() {
   571                 public void actionPerformed(ActionEvent e) {
   572                     showEntry((Entry) entries.getSelectedItem());
   573                 }
   574             });
   575             fc.insets.bottom = 10;
   576             head.add(entries, fc);
   577             fc.insets.bottom = 0;
   578             head.add(new JLabel("check:"), lc);
   579             head.add(checkField = createTextField(80), fc);
   580             fc.fill = GridBagConstraints.NONE;
   581             head.add(setBackground(new JLabel("encl:"), enclColor), lc);
   582             head.add(enclPanel = new InfoPanel(), fc);
   583             head.add(setBackground(new JLabel("self:"), selfColor), lc);
   584             head.add(selfPanel = new InfoPanel(), fc);
   585             add(head, BorderLayout.NORTH);
   587             body = new JTextArea();
   588             body.setFont(Font.decode(Font.MONOSPACED));
   589             body.addCaretListener(new CaretListener() {
   590                 public void caretUpdate(CaretEvent e) {
   591                     int dot = e.getDot();
   592                     int mark = e.getMark();
   593                     if (dot == mark)
   594                         statusText.setText("dot: " + dot);
   595                     else
   596                         statusText.setText("dot: " + dot + ", mark:" + mark);
   597                 }
   598             });
   599             JScrollPane p = new JScrollPane(body,
   600                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
   601                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
   602             p.setPreferredSize(new Dimension(640, 480));
   603             add(p, BorderLayout.CENTER);
   605             statusText = createTextField(80);
   606             add(statusText, BorderLayout.SOUTH);
   608             pack();
   609             setLocationRelativeTo(null); // centered on screen
   610             setVisible(true);
   611             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   612         }
   614         /** Show an entry that has been selected. */
   615         private void showEntry(Entry e) {
   616             try {
   617                 // update simple fields
   618                 setTitle(e.file.getName());
   619                 checkField.setText(e.check);
   620                 enclPanel.setInfo(e.encl);
   621                 selfPanel.setInfo(e.self);
   622                 // show file text with highlights
   623                 body.setText(e.file.getCharContent(true).toString());
   624                 Highlighter highlighter = body.getHighlighter();
   625                 highlighter.removeAllHighlights();
   626                 addHighlight(highlighter, e.encl, enclColor);
   627                 addHighlight(highlighter, e.self, selfColor);
   628                 scroll(body, getMinPos(enclPanel.info, selfPanel.info));
   629             } catch (IOException ex) {
   630                 body.setText("Cannot read " + e.file.getName() + ": " + e);
   631             }
   632         }
   634         /** Create a test field. */
   635         private JTextField createTextField(int width) {
   636             JTextField f = new JTextField(width);
   637             f.setEditable(false);
   638             f.setBorder(null);
   639             return f;
   640         }
   642         /** Add a highlighted region based on the positions in an Info object. */
   643         private void addHighlight(Highlighter h, Info info, Color c) {
   644             int start = info.start;
   645             int end = info.end;
   646             if (start == -1 && end == -1)
   647                 return;
   648             if (start == -1)
   649                 start = end;
   650             if (end == -1)
   651                 end = start;
   652             try {
   653                 h.addHighlight(info.start, info.end,
   654                         new DefaultHighlighter.DefaultHighlightPainter(c));
   655                 if (info.pos != -1) {
   656                     Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
   657                     h.addHighlight(info.pos, info.pos + 1,
   658                         new DefaultHighlighter.DefaultHighlightPainter(c2));
   659                 }
   660             } catch (BadLocationException e) {
   661                 e.printStackTrace();
   662             }
   663         }
   665         /** Get the minimum valid position in a set of info objects. */
   666         private int getMinPos(Info... values) {
   667             int i = Integer.MAX_VALUE;
   668             for (Info info: values) {
   669                 if (info.start >= 0) i = Math.min(i, info.start);
   670                 if (info.pos   >= 0) i = Math.min(i, info.pos);
   671                 if (info.end   >= 0) i = Math.min(i, info.end);
   672             }
   673             return (i == Integer.MAX_VALUE) ? 0 : i;
   674         }
   676         /** Set the background on a component. */
   677         private JComponent setBackground(JComponent comp, Color c) {
   678             comp.setOpaque(true);
   679             comp.setBackground(c);
   680             return comp;
   681         }
   683         /** Scroll a text area to display a given position near the middle of the visible area. */
   684         private void scroll(final JTextArea t, final int pos) {
   685             // Using invokeLater appears to give text a chance to sort itself out
   686             // before the scroll happens; otherwise scrollRectToVisible doesn't work.
   687             // Maybe there's a better way to sync with the text...
   688             EventQueue.invokeLater(new Runnable() {
   689                 public void run() {
   690                     try {
   691                         Rectangle r = t.modelToView(pos);
   692                         JScrollPane p = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, t);
   693                         r.y = Math.max(0, r.y - p.getHeight() * 2 / 5);
   694                         r.height += p.getHeight() * 4 / 5;
   695                         t.scrollRectToVisible(r);
   696                     } catch (BadLocationException ignore) {
   697                     }
   698                 }
   699             });
   700         }
   702         private JComboBox entries;
   703         private JTextField checkField;
   704         private InfoPanel enclPanel;
   705         private InfoPanel selfPanel;
   706         private JTextArea body;
   707         private JTextField statusText;
   709         private Color selfColor = new Color(0.f, 1.f, 0.f, 0.2f); // 20% green
   710         private Color enclColor = new Color(1.f, 0.f, 0.f, 0.2f); // 20% red
   712         /** Panel to display an Info object. */
   713         private class InfoPanel extends JPanel {
   714             InfoPanel() {
   715                 add(tagName = createTextField(20));
   716                 add(new JLabel("start:"));
   717                 add(addListener(start = createTextField(6)));
   718                 add(new JLabel("pos:"));
   719                 add(addListener(pos = createTextField(6)));
   720                 add(new JLabel("end:"));
   721                 add(addListener(end = createTextField(6)));
   722             }
   724             void setInfo(Info info) {
   725                 this.info = info;
   726                 tagName.setText(treeUtil.nameFromTag(info.tag));
   727                 start.setText(String.valueOf(info.start));
   728                 pos.setText(String.valueOf(info.pos));
   729                 end.setText(String.valueOf(info.end));
   730             }
   732             JTextField addListener(final JTextField f) {
   733                 f.addMouseListener(new MouseAdapter() {
   734                     @Override
   735                     public void mouseClicked(MouseEvent e) {
   736                         body.setCaretPosition(Integer.valueOf(f.getText()));
   737                         body.getCaret().setVisible(true);
   738                     }
   739                 });
   740                 return f;
   741             }
   743             Info info;
   744             JTextField tagName;
   745             JTextField start;
   746             JTextField pos;
   747             JTextField end;
   748         }
   750         /** Object to record information about an error to be displayed. */
   751         private class Entry {
   752             Entry(JavaFileObject file, String check, Info encl, Info self) {
   753                 this.file = file;
   754                 this.check = check;
   755                 this.encl = encl;
   756                 this.self= self;
   757             }
   759             @Override
   760             public String toString() {
   761                 return file.getName() + " " + check + " " + getMinPos(encl, self);
   762             }
   764             final JavaFileObject file;
   765             final String check;
   766             final Info encl;
   767             final Info self;
   768         }
   769     }
   771     /** Number of files that have been analyzed. */
   772     static AtomicInteger fileCount = new AtomicInteger();
   774 }

mercurial