test/tools/javac/tree/TreePosTest.java

Wed, 27 Apr 2016 01:34:52 +0800

author
aoqi
date
Wed, 27 Apr 2016 01:34:52 +0800
changeset 0
959103a6100f
child 2525
2eb010b6cb22
permissions
-rw-r--r--

Initial load
http://hg.openjdk.java.net/jdk8u/jdk8u/langtools/
changeset: 2573:53ca196be1ae
tag: jdk8u25-b17

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

mercurial