test/tools/javac/tree/TreePosTest.java

Thu, 21 Feb 2013 15:26:46 +0000

author
mcimadamore
date
Thu, 21 Feb 2013 15:26:46 +0000
changeset 1599
9f0ec00514b6
parent 1521
71f35e4b93a5
child 2525
2eb010b6cb22
permissions
-rw-r--r--

8007461: Regression: bad overload resolution when inner class and outer class have method with same name
Summary: Fix regression in varargs method resolution introduced by bad refactoring
Reviewed-by: jjg

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

mercurial