test/tools/javac/tree/TreePosTest.java

Tue, 08 Nov 2011 17:06:58 -0800

author
jjg
date
Tue, 08 Nov 2011 17:06:58 -0800
changeset 1136
ae361e7f435a
parent 1127
ca49d50318dc
child 1138
7375d4979bd3
permissions
-rw-r--r--

7108669: cleanup Log methods for direct printing to streams
Reviewed-by: mcimadamore

     1 /*
     2  * Copyright (c) 2010, 2011, 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 java.awt.BorderLayout;
    25 import java.awt.Color;
    26 import java.awt.Dimension;
    27 import java.awt.EventQueue;
    28 import java.awt.Font;
    29 import java.awt.GridBagConstraints;
    30 import java.awt.GridBagLayout;
    31 import java.awt.Rectangle;
    32 import java.awt.event.ActionEvent;
    33 import java.awt.event.ActionListener;
    34 import java.awt.event.MouseAdapter;
    35 import java.awt.event.MouseEvent;
    36 import java.io.File;
    37 import java.io.IOException;
    38 import java.io.PrintStream;
    39 import java.io.PrintWriter;
    40 import java.io.StringWriter;
    41 import java.lang.reflect.Field;
    42 import java.lang.reflect.Modifier;
    43 import java.nio.charset.Charset;
    44 import java.util.ArrayList;
    45 import java.util.Collections;
    46 import java.util.HashMap;
    47 import java.util.HashSet;
    48 import java.util.Iterator;
    49 import java.util.List;
    50 import java.util.Map;
    51 import java.util.Set;
    52 import javax.swing.DefaultComboBoxModel;
    53 import javax.swing.JComboBox;
    54 import javax.swing.JComponent;
    55 import javax.swing.JFrame;
    56 import javax.swing.JLabel;
    57 import javax.swing.JPanel;
    58 import javax.swing.JScrollPane;
    59 import javax.swing.JTextArea;
    60 import javax.swing.JTextField;
    61 import javax.swing.SwingUtilities;
    62 import javax.swing.event.CaretEvent;
    63 import javax.swing.event.CaretListener;
    64 import javax.swing.text.BadLocationException;
    65 import javax.swing.text.DefaultHighlighter;
    66 import javax.swing.text.Highlighter;
    67 import javax.tools.Diagnostic;
    68 import javax.tools.DiagnosticListener;
    69 import javax.tools.JavaFileObject;
    70 import javax.tools.StandardJavaFileManager;
    72 import com.sun.source.tree.CompilationUnitTree;
    73 import com.sun.source.util.JavacTask;
    74 import com.sun.tools.javac.api.JavacTool;
    75 import com.sun.tools.javac.code.Flags;
    76 import com.sun.tools.javac.tree.JCTree;
    77 import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
    78 import com.sun.tools.javac.tree.JCTree.JCNewClass;
    79 import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
    80 import com.sun.tools.javac.tree.TreeInfo;
    81 import com.sun.tools.javac.tree.TreeScanner;
    83 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    84 import static com.sun.tools.javac.util.Position.NOPOS;
    86 /**
    87  * Utility and test program to check validity of tree positions for tree nodes.
    88  * The program can be run standalone, or as a jtreg test.  In standalone mode,
    89  * errors can be displayed in a gui viewer. For info on command line args,
    90  * run program with no args.
    91  *
    92  * <p>
    93  * jtreg: Note that by using the -r switch in the test description below, this test
    94  * will process all java files in the langtools/test directory, thus implicitly
    95  * covering any new language features that may be tested in this test suite.
    96  */
    98 /*
    99  * @test
   100  * @bug 6919889
   101  * @summary assorted position errors in compiler syntax trees
   102  * @run main TreePosTest -q -r -ef ./tools/javac/typeAnnotations -ef ./tools/javap/typeAnnotations -et ANNOTATED_TYPE .
   103  */
   104 public class TreePosTest {
   105     /**
   106      * Main entry point.
   107      * If test.src is set, program runs in jtreg mode, and will throw an Error
   108      * if any errors arise, otherwise System.exit will be used, unless the gui
   109      * viewer is being used. In jtreg mode, the default base directory for file
   110      * args is the value of ${test.src}. In jtreg mode, the -r option can be
   111      * given to change the default base directory to the root test directory.
   112      */
   113     public static void main(String... args) {
   114         String testSrc = System.getProperty("test.src");
   115         File baseDir = (testSrc == null) ? null : new File(testSrc);
   116         boolean ok = new TreePosTest().run(baseDir, args);
   117         if (!ok) {
   118             if (testSrc != null)  // jtreg mode
   119                 throw new Error("failed");
   120             else
   121                 System.exit(1);
   122         }
   123     }
   125     /**
   126      * Run the program. A base directory can be provided for file arguments.
   127      * In jtreg mode, the -r option can be given to change the default base
   128      * directory to the test root directory. For other options, see usage().
   129      * @param baseDir base directory for any file arguments.
   130      * @param args command line args
   131      * @return true if successful or in gui mode
   132      */
   133     boolean run(File baseDir, String... args) {
   134         if (args.length == 0) {
   135             usage(System.out);
   136             return true;
   137         }
   139         List<File> files = new ArrayList<File>();
   140         for (int i = 0; i < args.length; i++) {
   141             String arg = args[i];
   142             if (arg.equals("-encoding") && i + 1 < args.length)
   143                 encoding = args[++i];
   144             else if (arg.equals("-gui"))
   145                 gui = true;
   146             else if (arg.equals("-q"))
   147                 quiet = true;
   148             else if (arg.equals("-v"))
   149                 verbose = true;
   150             else if (arg.equals("-t") && i + 1 < args.length)
   151                 tags.add(args[++i]);
   152             else if (arg.equals("-ef") && i + 1 < args.length)
   153                 excludeFiles.add(new File(baseDir, args[++i]));
   154             else if (arg.equals("-et") && i + 1 < args.length)
   155                 excludeTags.add(args[++i]);
   156             else if (arg.equals("-r")) {
   157                 if (excludeFiles.size() > 0)
   158                     throw new Error("-r must be used before -ef");
   159                 File d = baseDir;
   160                 while (!new File(d, "TEST.ROOT").exists()) {
   161                     d = d.getParentFile();
   162                     if (d == null)
   163                         throw new Error("cannot find TEST.ROOT");
   164                 }
   165                 baseDir = d;
   166             }
   167             else if (arg.startsWith("-"))
   168                 throw new Error("unknown option: " + arg);
   169             else {
   170                 while (i < args.length)
   171                     files.add(new File(baseDir, args[i++]));
   172             }
   173         }
   175         for (File file: files) {
   176             if (file.exists())
   177                 test(file);
   178             else
   179                 error("File not found: " + file);
   180         }
   182         if (fileCount != 1)
   183             System.err.println(fileCount + " files read");
   184         if (errors > 0)
   185             System.err.println(errors + " errors");
   187         return (gui || errors == 0);
   188     }
   190     /**
   191      * Print command line help.
   192      * @param out output stream
   193      */
   194     void usage(PrintStream out) {
   195         out.println("Usage:");
   196         out.println("  java TreePosTest options... files...");
   197         out.println("");
   198         out.println("where options include:");
   199         out.println("-gui      Display returns in a GUI viewer");
   200         out.println("-q        Quiet: don't report on inapplicable files");
   201         out.println("-v        Verbose: report on files as they are being read");
   202         out.println("-t tag    Limit checks to tree nodes with this tag");
   203         out.println("          Can be repeated if desired");
   204         out.println("-ef file  Exclude file or directory");
   205         out.println("-et tag   Exclude tree nodes with given tag name");
   206         out.println("");
   207         out.println("files may be directories or files");
   208         out.println("directories will be scanned recursively");
   209         out.println("non java files, or java files which cannot be parsed, will be ignored");
   210         out.println("");
   211     }
   213     /**
   214      * Test a file. If the file is a directory, it will be recursively scanned
   215      * for java files.
   216      * @param file the file or directory to test
   217      */
   218     void test(File file) {
   219         if (excludeFiles.contains(file)) {
   220             if (!quiet)
   221                 error("File " + file + " excluded");
   222             return;
   223         }
   225         if (file.isDirectory()) {
   226             for (File f: file.listFiles()) {
   227                 test(f);
   228             }
   229             return;
   230         }
   232         if (file.isFile() && file.getName().endsWith(".java")) {
   233             try {
   234                 if (verbose)
   235                     System.err.println(file);
   236                 fileCount++;
   237                 PosTester p = new PosTester();
   238                 p.test(read(file));
   239             } catch (ParseException e) {
   240                 if (!quiet) {
   241                     error("Error parsing " + file + "\n" + e.getMessage());
   242                 }
   243             } catch (IOException e) {
   244                 error("Error reading " + file + ": " + e);
   245             }
   246             return;
   247         }
   249         if (!quiet)
   250             error("File " + file + " ignored");
   251     }
   253     // See CR:  6982992 Tests CheckAttributedTree.java, JavacTreeScannerTest.java, and SourceTreeeScannerTest.java timeout
   254     StringWriter sw = new StringWriter();
   255     PrintWriter pw = new PrintWriter(sw);
   256     Reporter r = new Reporter(pw);
   257     JavacTool tool = JavacTool.create();
   258     StandardJavaFileManager fm = tool.getStandardFileManager(r, null, null);
   260     /**
   261      * Read a file.
   262      * @param file the file to be read
   263      * @return the tree for the content of the file
   264      * @throws IOException if any IO errors occur
   265      * @throws TreePosTest.ParseException if any errors occur while parsing the file
   266      */
   267     JCCompilationUnit read(File file) throws IOException, ParseException {
   268         JavacTool tool = JavacTool.create();
   269         r.errors = 0;
   270         Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file);
   271         JavacTask task = tool.getTask(pw, fm, r, Collections.<String>emptyList(), null, files);
   272         Iterable<? extends CompilationUnitTree> trees = task.parse();
   273         pw.flush();
   274         if (r.errors > 0)
   275             throw new ParseException(sw.toString());
   276         Iterator<? extends CompilationUnitTree> iter = trees.iterator();
   277         if (!iter.hasNext())
   278             throw new Error("no trees found");
   279         JCCompilationUnit t = (JCCompilationUnit) iter.next();
   280         if (iter.hasNext())
   281             throw new Error("too many trees found");
   282         return t;
   283     }
   285     /**
   286      * Report an error. When the program is complete, the program will either
   287      * exit or throw an Error if any errors have been reported.
   288      * @param msg the error message
   289      */
   290     void error(String msg) {
   291         System.err.println(msg);
   292         errors++;
   293     }
   295     /**
   296      * Names for tree tags.
   297      */
   298     private static String getTagName(JCTree.Tag tag) {
   299         String name = tag.name();
   300         return (name == null) ? "??" : name;
   301     }
   303     /** Number of files that have been analyzed. */
   304     int fileCount;
   305     /** Number of errors reported. */
   306     int errors;
   307     /** Flag: don't report irrelevant files. */
   308     boolean quiet;
   309     /** Flag: report files as they are processed. */
   310     boolean verbose;
   311     /** Flag: show errors in GUI viewer. */
   312     boolean gui;
   313     /** Option: encoding for test files. */
   314     String encoding;
   315     /** The GUI viewer for errors. */
   316     Viewer viewer;
   317     /** The set of tags for tree nodes to be analyzed; if empty, all tree nodes
   318      * are analyzed. */
   319     Set<String> tags = new HashSet<String>();
   320     /** Set of files and directories to be excluded from analysis. */
   321     Set<File> excludeFiles = new HashSet<File>();
   322     /** Set of tag names to be excluded from analysis. */
   323     Set<String> excludeTags = new HashSet<String>();
   325     /**
   326      * Main class for testing assertions concerning tree positions for tree nodes.
   327      */
   328     private class PosTester extends TreeScanner {
   329         void test(JCCompilationUnit tree) {
   330             sourcefile = tree.sourcefile;
   331             endPosTable = tree.endPositions;
   332             encl = new Info();
   333             tree.accept(this);
   334         }
   336         @Override
   337         public void scan(JCTree tree) {
   338             if (tree == null)
   339                 return;
   341             Info self = new Info(tree, endPosTable);
   342             if (check(encl, self)) {
   343                 // Modifiers nodes are present throughout the tree even where
   344                 // there is no corresponding source text.
   345                 // Redundant semicolons in a class definition can cause empty
   346                 // initializer blocks with no positions.
   347                 if ((self.tag == MODIFIERS || self.tag == BLOCK)
   348                         && self.pos == NOPOS) {
   349                     // If pos is NOPOS, so should be the start and end positions
   350                     check("start == NOPOS", encl, self, self.start == NOPOS);
   351                     check("end == NOPOS", encl, self, self.end == NOPOS);
   352                 } else {
   353                     // For this node, start , pos, and endpos should be all defined
   354                     check("start != NOPOS", encl, self, self.start != NOPOS);
   355                     check("pos != NOPOS", encl, self, self.pos != NOPOS);
   356                     check("end != NOPOS", encl, self, self.end != NOPOS);
   357                     // The following should normally be ordered
   358                     // encl.start <= start <= pos <= end <= encl.end
   359                     // In addition, the position of the enclosing node should be
   360                     // within this node.
   361                     // The primary exceptions are for array type nodes, because of the
   362                     // need to support legacy syntax:
   363                     //    e.g.    int a[];    int[] b[];    int f()[] { return null; }
   364                     // and because of inconsistent nesting of left and right of
   365                     // array declarations:
   366                     //    e.g.    int[][] a = new int[2][];
   367                     check("encl.start <= start", encl, self, encl.start <= self.start);
   368                     check("start <= pos", encl, self, self.start <= self.pos);
   369                     if (!(self.tag == TYPEARRAY
   370                             && (encl.tag == VARDEF ||
   371                                 encl.tag == METHODDEF ||
   372                                 encl.tag == TYPEARRAY))) {
   373                         check("encl.pos <= start || end <= encl.pos",
   374                                 encl, self, encl.pos <= self.start || self.end <= encl.pos);
   375                     }
   376                     check("pos <= end", encl, self, self.pos <= self.end);
   377                     if (!(self.tag == TYPEARRAY && encl.tag == TYPEARRAY)) {
   378                         check("end <= encl.end", encl, self, self.end <= encl.end);
   379                     }
   380                 }
   381             }
   383             Info prevEncl = encl;
   384             encl = self;
   385             tree.accept(this);
   386             encl = prevEncl;
   387         }
   389         @Override
   390         public void visitVarDef(JCVariableDecl tree) {
   391             // enum member declarations are desugared in the parser and have
   392             // ill-defined semantics for tree positions, so for now, we
   393             // skip the synthesized bits and just check parts which came from
   394             // the original source text
   395             if ((tree.mods.flags & Flags.ENUM) != 0) {
   396                 scan(tree.mods);
   397                 if (tree.init != null) {
   398                     if (tree.init.hasTag(NEWCLASS)) {
   399                         JCNewClass init = (JCNewClass) tree.init;
   400                         if (init.args != null && init.args.nonEmpty()) {
   401                             scan(init.args);
   402                         }
   403                         if (init.def != null && init.def.defs != null) {
   404                             scan(init.def.defs);
   405                         }
   406                     }
   407                 }
   408             } else
   409                 super.visitVarDef(tree);
   410         }
   412         boolean check(Info encl, Info self) {
   413             if (excludeTags.size() > 0) {
   414                 if (encl != null && excludeTags.contains(getTagName(encl.tag))
   415                         || excludeTags.contains(getTagName(self.tag)))
   416                     return false;
   417             }
   418             return tags.size() == 0 || tags.contains(getTagName(self.tag));
   419         }
   421         void check(String label, Info encl, Info self, boolean ok) {
   422             if (!ok) {
   423                 if (gui) {
   424                     if (viewer == null)
   425                         viewer = new Viewer();
   426                     viewer.addEntry(sourcefile, label, encl, self);
   427                 }
   429                 String s = self.tree.toString();
   430                 String msg = sourcefile.getName() + ": " + label + ": " +
   431                         "encl:" + encl + " this:" + self + "\n" +
   432                         s.substring(0, Math.min(80, s.length())).replaceAll("[\r\n]+", " ");
   433                 error(msg);
   434             }
   435         }
   437         JavaFileObject sourcefile;
   438         Map<JCTree, Integer> endPosTable;
   439         Info encl;
   441     }
   443     /**
   444      * Utility class providing easy access to position and other info for a tree node.
   445      */
   446     private class Info {
   447         Info() {
   448             tree = null;
   449             tag = ERRONEOUS;
   450             start = 0;
   451             pos = 0;
   452             end = Integer.MAX_VALUE;
   453         }
   455         Info(JCTree tree, Map<JCTree, Integer> endPosTable) {
   456             this.tree = tree;
   457             tag = tree.getTag();
   458             start = TreeInfo.getStartPos(tree);
   459             pos = tree.pos;
   460             end = TreeInfo.getEndPos(tree, endPosTable);
   461         }
   463         @Override
   464         public String toString() {
   465             return getTagName(tree.getTag()) + "[start:" + start + ",pos:" + pos + ",end:" + end + "]";
   466         }
   468         final JCTree tree;
   469         final JCTree.Tag tag;
   470         final int start;
   471         final int pos;
   472         final int end;
   473     }
   475     /**
   476      * Thrown when errors are found parsing a java file.
   477      */
   478     private static class ParseException extends Exception {
   479         ParseException(String msg) {
   480             super(msg);
   481         }
   482     }
   484     /**
   485      * DiagnosticListener to report diagnostics and count any errors that occur.
   486      */
   487     private static class Reporter implements DiagnosticListener<JavaFileObject> {
   488         Reporter(PrintWriter out) {
   489             this.out = out;
   490         }
   492         public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
   493             out.println(diagnostic);
   494             switch (diagnostic.getKind()) {
   495                 case ERROR:
   496                     errors++;
   497             }
   498         }
   499         int errors;
   500         PrintWriter out;
   501     }
   503     /**
   504      * GUI viewer for issues found by TreePosTester. The viewer provides a drop
   505      * down list for selecting error conditions, a header area providing details
   506      * about an error, and a text area with the ranges of text highlighted as
   507      * appropriate.
   508      */
   509     private class Viewer extends JFrame {
   510         /**
   511          * Create a viewer.
   512          */
   513         Viewer() {
   514             initGUI();
   515         }
   517         /**
   518          * Add another entry to the list of errors.
   519          * @param file The file containing the error
   520          * @param check The condition that was being tested, and which failed
   521          * @param encl the enclosing tree node
   522          * @param self the tree node containing the error
   523          */
   524         void addEntry(JavaFileObject file, String check, Info encl, Info self) {
   525             Entry e = new Entry(file, check, encl, self);
   526             DefaultComboBoxModel m = (DefaultComboBoxModel) entries.getModel();
   527             m.addElement(e);
   528             if (m.getSize() == 1)
   529                 entries.setSelectedItem(e);
   530         }
   532         /**
   533          * Initialize the GUI window.
   534          */
   535         private void initGUI() {
   536             JPanel head = new JPanel(new GridBagLayout());
   537             GridBagConstraints lc = new GridBagConstraints();
   538             GridBagConstraints fc = new GridBagConstraints();
   539             fc.anchor = GridBagConstraints.WEST;
   540             fc.fill = GridBagConstraints.HORIZONTAL;
   541             fc.gridwidth = GridBagConstraints.REMAINDER;
   543             entries = new JComboBox();
   544             entries.addActionListener(new ActionListener() {
   545                 public void actionPerformed(ActionEvent e) {
   546                     showEntry((Entry) entries.getSelectedItem());
   547                 }
   548             });
   549             fc.insets.bottom = 10;
   550             head.add(entries, fc);
   551             fc.insets.bottom = 0;
   552             head.add(new JLabel("check:"), lc);
   553             head.add(checkField = createTextField(80), fc);
   554             fc.fill = GridBagConstraints.NONE;
   555             head.add(setBackground(new JLabel("encl:"), enclColor), lc);
   556             head.add(enclPanel = new InfoPanel(), fc);
   557             head.add(setBackground(new JLabel("self:"), selfColor), lc);
   558             head.add(selfPanel = new InfoPanel(), fc);
   559             add(head, BorderLayout.NORTH);
   561             body = new JTextArea();
   562             body.setFont(Font.decode(Font.MONOSPACED));
   563             body.addCaretListener(new CaretListener() {
   564                 public void caretUpdate(CaretEvent e) {
   565                     int dot = e.getDot();
   566                     int mark = e.getMark();
   567                     if (dot == mark)
   568                         statusText.setText("dot: " + dot);
   569                     else
   570                         statusText.setText("dot: " + dot + ", mark:" + mark);
   571                 }
   572             });
   573             JScrollPane p = new JScrollPane(body,
   574                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
   575                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
   576             p.setPreferredSize(new Dimension(640, 480));
   577             add(p, BorderLayout.CENTER);
   579             statusText = createTextField(80);
   580             add(statusText, BorderLayout.SOUTH);
   582             pack();
   583             setLocationRelativeTo(null); // centered on screen
   584             setVisible(true);
   585             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   586         }
   588         /** Show an entry that has been selected. */
   589         private void showEntry(Entry e) {
   590             try {
   591                 // update simple fields
   592                 setTitle(e.file.getName());
   593                 checkField.setText(e.check);
   594                 enclPanel.setInfo(e.encl);
   595                 selfPanel.setInfo(e.self);
   596                 // show file text with highlights
   597                 body.setText(e.file.getCharContent(true).toString());
   598                 Highlighter highlighter = body.getHighlighter();
   599                 highlighter.removeAllHighlights();
   600                 addHighlight(highlighter, e.encl, enclColor);
   601                 addHighlight(highlighter, e.self, selfColor);
   602                 scroll(body, getMinPos(enclPanel.info, selfPanel.info));
   603             } catch (IOException ex) {
   604                 body.setText("Cannot read " + e.file.getName() + ": " + e);
   605             }
   606         }
   608         /** Create a test field. */
   609         private JTextField createTextField(int width) {
   610             JTextField f = new JTextField(width);
   611             f.setEditable(false);
   612             f.setBorder(null);
   613             return f;
   614         }
   616         /** Add a highlighted region based on the positions in an Info object. */
   617         private void addHighlight(Highlighter h, Info info, Color c) {
   618             int start = info.start;
   619             int end = info.end;
   620             if (start == -1 && end == -1)
   621                 return;
   622             if (start == -1)
   623                 start = end;
   624             if (end == -1)
   625                 end = start;
   626             try {
   627                 h.addHighlight(info.start, info.end,
   628                         new DefaultHighlighter.DefaultHighlightPainter(c));
   629                 if (info.pos != -1) {
   630                     Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
   631                     h.addHighlight(info.pos, info.pos + 1,
   632                         new DefaultHighlighter.DefaultHighlightPainter(c2));
   633                 }
   634             } catch (BadLocationException e) {
   635                 e.printStackTrace();
   636             }
   637         }
   639         /** Get the minimum valid position in a set of info objects. */
   640         private int getMinPos(Info... values) {
   641             int i = Integer.MAX_VALUE;
   642             for (Info info: values) {
   643                 if (info.start >= 0) i = Math.min(i, info.start);
   644                 if (info.pos   >= 0) i = Math.min(i, info.pos);
   645                 if (info.end   >= 0) i = Math.min(i, info.end);
   646             }
   647             return (i == Integer.MAX_VALUE) ? 0 : i;
   648         }
   650         /** Set the background on a component. */
   651         private JComponent setBackground(JComponent comp, Color c) {
   652             comp.setOpaque(true);
   653             comp.setBackground(c);
   654             return comp;
   655         }
   657         /** Scroll a text area to display a given position near the middle of the visible area. */
   658         private void scroll(final JTextArea t, final int pos) {
   659             // Using invokeLater appears to give text a chance to sort itself out
   660             // before the scroll happens; otherwise scrollRectToVisible doesn't work.
   661             // Maybe there's a better way to sync with the text...
   662             EventQueue.invokeLater(new Runnable() {
   663                 public void run() {
   664                     try {
   665                         Rectangle r = t.modelToView(pos);
   666                         JScrollPane p = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, t);
   667                         r.y = Math.max(0, r.y - p.getHeight() * 2 / 5);
   668                         r.height += p.getHeight() * 4 / 5;
   669                         t.scrollRectToVisible(r);
   670                     } catch (BadLocationException ignore) {
   671                     }
   672                 }
   673             });
   674         }
   676         private JComboBox entries;
   677         private JTextField checkField;
   678         private InfoPanel enclPanel;
   679         private InfoPanel selfPanel;
   680         private JTextArea body;
   681         private JTextField statusText;
   683         private Color selfColor = new Color(0.f, 1.f, 0.f, 0.2f); // 20% green
   684         private Color enclColor = new Color(1.f, 0.f, 0.f, 0.2f); // 20% red
   686         /** Panel to display an Info object. */
   687         private class InfoPanel extends JPanel {
   688             InfoPanel() {
   689                 add(tagName = createTextField(20));
   690                 add(new JLabel("start:"));
   691                 add(addListener(start = createTextField(6)));
   692                 add(new JLabel("pos:"));
   693                 add(addListener(pos = createTextField(6)));
   694                 add(new JLabel("end:"));
   695                 add(addListener(end = createTextField(6)));
   696             }
   698             void setInfo(Info info) {
   699                 this.info = info;
   700                 tagName.setText(getTagName(info.tag));
   701                 start.setText(String.valueOf(info.start));
   702                 pos.setText(String.valueOf(info.pos));
   703                 end.setText(String.valueOf(info.end));
   704             }
   706             JTextField addListener(final JTextField f) {
   707                 f.addMouseListener(new MouseAdapter() {
   708                     @Override
   709                     public void mouseClicked(MouseEvent e) {
   710                         body.setCaretPosition(Integer.valueOf(f.getText()));
   711                         body.getCaret().setVisible(true);
   712                     }
   713                 });
   714                 return f;
   715             }
   717             Info info;
   718             JTextField tagName;
   719             JTextField start;
   720             JTextField pos;
   721             JTextField end;
   722         }
   724         /** Object to record information about an error to be displayed. */
   725         private class Entry {
   726             Entry(JavaFileObject file, String check, Info encl, Info self) {
   727                 this.file = file;
   728                 this.check = check;
   729                 this.encl = encl;
   730                 this.self= self;
   731             }
   733             @Override
   734             public String toString() {
   735                 return file.getName() + " " + check + " " + getMinPos(encl, self);
   736             }
   738             final JavaFileObject file;
   739             final String check;
   740             final Info encl;
   741             final Info self;
   742         }
   743     }
   744 }

mercurial