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