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