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