test/tools/javac/failover/CheckAttributedTree.java

Thu, 31 Aug 2017 15:17:03 +0800

author
aoqi
date
Thu, 31 Aug 2017 15:17:03 +0800
changeset 2525
2eb010b6cb22
parent 1521
71f35e4b93a5
parent 0
959103a6100f
permissions
-rw-r--r--

merge

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

mercurial