test/tools/javac/tree/TreePosTest.java

Tue, 19 Oct 2010 15:02:48 -0700

author
jjg
date
Tue, 19 Oct 2010 15:02:48 -0700
changeset 722
4851ff2ffc10
parent 554
9d9f26857129
child 808
e8719f95f2d0
permissions
-rw-r--r--

6987760: remove 308 support from JDK7
Reviewed-by: darcy, mcimadamore

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

mercurial