675N/A/*
675N/A * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
675N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
675N/A *
675N/A * This code is free software; you can redistribute it and/or modify it
675N/A * under the terms of the GNU General Public License version 2 only, as
675N/A * published by the Free Software Foundation.
675N/A *
675N/A * This code is distributed in the hope that it will be useful, but WITHOUT
675N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
675N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
675N/A * version 2 for more details (a copy is included in the LICENSE file that
675N/A * accompanied this code).
675N/A *
675N/A * You should have received a copy of the GNU General Public License version
675N/A * 2 along with this work; if not, write to the Free Software Foundation,
675N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
675N/A *
675N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
675N/A * or visit www.oracle.com if you need additional information or have any
675N/A * questions.
675N/A */
675N/A
675N/Aimport com.sun.source.util.TaskEvent;
675N/Aimport java.awt.BorderLayout;
675N/Aimport java.awt.Color;
675N/Aimport java.awt.Dimension;
675N/Aimport java.awt.EventQueue;
675N/Aimport java.awt.Font;
675N/Aimport java.awt.GridBagConstraints;
675N/Aimport java.awt.GridBagLayout;
675N/Aimport java.awt.Rectangle;
675N/Aimport java.awt.event.ActionEvent;
675N/Aimport java.awt.event.ActionListener;
675N/Aimport java.awt.event.MouseAdapter;
675N/Aimport java.awt.event.MouseEvent;
675N/Aimport javax.swing.DefaultComboBoxModel;
675N/Aimport javax.swing.JComboBox;
675N/Aimport javax.swing.JComponent;
675N/Aimport javax.swing.JFrame;
675N/Aimport javax.swing.JLabel;
675N/Aimport javax.swing.JPanel;
675N/Aimport javax.swing.JScrollPane;
675N/Aimport javax.swing.JTextArea;
675N/Aimport javax.swing.JTextField;
675N/Aimport javax.swing.SwingUtilities;
675N/Aimport javax.swing.event.CaretEvent;
675N/Aimport javax.swing.event.CaretListener;
675N/Aimport javax.swing.text.BadLocationException;
675N/Aimport javax.swing.text.DefaultHighlighter;
675N/Aimport javax.swing.text.Highlighter;
675N/Aimport java.io.File;
675N/Aimport java.io.IOException;
675N/Aimport java.io.PrintStream;
675N/Aimport java.io.PrintWriter;
675N/Aimport java.io.StringWriter;
675N/Aimport java.lang.reflect.Field;
675N/Aimport java.lang.reflect.Modifier;
675N/Aimport java.nio.charset.Charset;
675N/Aimport java.util.ArrayList;
675N/Aimport java.util.HashMap;
675N/Aimport java.util.List;
675N/Aimport java.util.Map;
675N/Aimport javax.tools.Diagnostic;
675N/Aimport javax.tools.DiagnosticListener;
675N/Aimport javax.tools.JavaFileObject;
675N/Aimport javax.tools.StandardJavaFileManager;
675N/A
675N/Aimport com.sun.source.tree.CompilationUnitTree;
675N/Aimport com.sun.source.util.JavacTask;
675N/Aimport com.sun.source.util.TaskListener;
675N/Aimport com.sun.tools.javac.api.JavacTool;
675N/Aimport com.sun.tools.javac.code.Symbol;
675N/Aimport com.sun.tools.javac.code.Type;
675N/Aimport com.sun.tools.javac.tree.JCTree;
675N/Aimport com.sun.tools.javac.tree.JCTree.JCClassDecl;
675N/Aimport com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
675N/Aimport com.sun.tools.javac.tree.JCTree.JCImport;
675N/Aimport com.sun.tools.javac.tree.TreeInfo;
675N/Aimport com.sun.tools.javac.tree.TreeScanner;
675N/Aimport com.sun.tools.javac.util.Pair;
675N/A
675N/Aimport java.util.Arrays;
675N/Aimport java.util.HashSet;
675N/Aimport java.util.Set;
675N/Aimport javax.lang.model.element.Element;
675N/A
675N/A/**
675N/A * Utility and test program to check validity of tree positions for tree nodes.
675N/A * The program can be run standalone, or as a jtreg test. In standalone mode,
675N/A * errors can be displayed in a gui viewer. For info on command line args,
675N/A * run program with no args.
675N/A *
675N/A * <p>
675N/A * jtreg: Note that by using the -r switch in the test description below, this test
675N/A * will process all java files in the langtools/test directory, thus implicitly
675N/A * covering any new language features that may be tested in this test suite.
675N/A */
675N/A
675N/A/*
675N/A * @test
675N/A * @bug 6970584
675N/A * @summary assorted position errors in compiler syntax trees
675N/A * @run main CheckAttributedTree -q -r -et ERRONEOUS .
675N/A */
675N/Apublic class CheckAttributedTree {
675N/A /**
675N/A * Main entry point.
675N/A * If test.src is set, program runs in jtreg mode, and will throw an Error
675N/A * if any errors arise, otherwise System.exit will be used, unless the gui
675N/A * viewer is being used. In jtreg mode, the default base directory for file
675N/A * args is the value of ${test.src}. In jtreg mode, the -r option can be
675N/A * given to change the default base directory to the root test directory.
675N/A */
675N/A public static void main(String... args) {
675N/A String testSrc = System.getProperty("test.src");
675N/A File baseDir = (testSrc == null) ? null : new File(testSrc);
675N/A boolean ok = new CheckAttributedTree().run(baseDir, args);
675N/A if (!ok) {
675N/A if (testSrc != null) // jtreg mode
675N/A throw new Error("failed");
675N/A else
675N/A System.exit(1);
675N/A }
675N/A }
675N/A
675N/A /**
675N/A * Run the program. A base directory can be provided for file arguments.
675N/A * In jtreg mode, the -r option can be given to change the default base
675N/A * directory to the test root directory. For other options, see usage().
675N/A * @param baseDir base directory for any file arguments.
675N/A * @param args command line args
675N/A * @return true if successful or in gui mode
675N/A */
675N/A boolean run(File baseDir, String... args) {
675N/A if (args.length == 0) {
675N/A usage(System.out);
675N/A return true;
675N/A }
675N/A
675N/A List<File> files = new ArrayList<File>();
675N/A for (int i = 0; i < args.length; i++) {
675N/A String arg = args[i];
675N/A if (arg.equals("-encoding") && i + 1 < args.length)
675N/A encoding = args[++i];
675N/A else if (arg.equals("-gui"))
675N/A gui = true;
675N/A else if (arg.equals("-q"))
675N/A quiet = true;
675N/A else if (arg.equals("-v"))
675N/A verbose = true;
675N/A else if (arg.equals("-t") && i + 1 < args.length)
675N/A tags.add(args[++i]);
675N/A else if (arg.equals("-ef") && i + 1 < args.length)
675N/A excludeFiles.add(new File(baseDir, args[++i]));
675N/A else if (arg.equals("-et") && i + 1 < args.length)
675N/A excludeTags.add(args[++i]);
675N/A else if (arg.equals("-r")) {
675N/A if (excludeFiles.size() > 0)
675N/A throw new Error("-r must be used before -ef");
675N/A File d = baseDir;
675N/A while (!new File(d, "TEST.ROOT").exists()) {
675N/A if (d == null)
675N/A throw new Error("cannot find TEST.ROOT");
675N/A d = d.getParentFile();
675N/A }
675N/A baseDir = d;
675N/A }
675N/A else if (arg.startsWith("-"))
675N/A throw new Error("unknown option: " + arg);
675N/A else {
675N/A while (i < args.length)
675N/A files.add(new File(baseDir, args[i++]));
675N/A }
675N/A }
675N/A
675N/A for (File file: files) {
675N/A if (file.exists())
675N/A test(file);
675N/A else
675N/A error("File not found: " + file);
675N/A }
675N/A
675N/A if (fileCount != 1)
675N/A System.err.println(fileCount + " files read");
675N/A if (errors > 0)
675N/A System.err.println(errors + " errors");
675N/A
675N/A return (gui || errors == 0);
675N/A }
675N/A
675N/A /**
675N/A * Print command line help.
675N/A * @param out output stream
675N/A */
675N/A void usage(PrintStream out) {
675N/A out.println("Usage:");
675N/A out.println(" java CheckAttributedTree options... files...");
675N/A out.println("");
675N/A out.println("where options include:");
675N/A out.println("-q Quiet: don't report on inapplicable files");
675N/A out.println("-gui Display returns in a GUI viewer");
675N/A out.println("-v Verbose: report on files as they are being read");
675N/A out.println("-t tag Limit checks to tree nodes with this tag");
675N/A out.println(" Can be repeated if desired");
675N/A out.println("-ef file Exclude file or directory");
675N/A out.println("-et tag Exclude tree nodes with given tag name");
675N/A out.println("");
675N/A out.println("files may be directories or files");
675N/A out.println("directories will be scanned recursively");
675N/A out.println("non java files, or java files which cannot be parsed, will be ignored");
675N/A out.println("");
675N/A }
675N/A
675N/A /**
675N/A * Test a file. If the file is a directory, it will be recursively scanned
675N/A * for java files.
675N/A * @param file the file or directory to test
675N/A */
675N/A void test(File file) {
675N/A if (excludeFiles.contains(file)) {
675N/A if (!quiet)
675N/A error("File " + file + " excluded");
675N/A return;
675N/A }
675N/A
675N/A if (file.isDirectory()) {
675N/A for (File f: file.listFiles()) {
675N/A test(f);
675N/A }
675N/A return;
675N/A }
675N/A
675N/A if (file.isFile() && file.getName().endsWith(".java")) {
675N/A try {
675N/A if (verbose)
675N/A System.err.println(file);
675N/A fileCount++;
675N/A NPETester p = new NPETester();
675N/A p.test(read(file));
675N/A } catch (AttributionException e) {
675N/A if (!quiet) {
675N/A error("Error attributing " + file + "\n" + e.getMessage());
675N/A }
675N/A } catch (IOException e) {
675N/A error("Error reading " + file + ": " + e);
675N/A }
675N/A return;
675N/A }
675N/A
675N/A if (!quiet)
675N/A error("File " + file + " ignored");
675N/A }
675N/A
807N/A // See CR: 6982992 Tests CheckAttributedTree.java, JavacTreeScannerTest.java, and SourceTreeeScannerTest.java timeout
807N/A StringWriter sw = new StringWriter();
807N/A PrintWriter pw = new PrintWriter(sw);
807N/A Reporter r = new Reporter(pw);
807N/A JavacTool tool = JavacTool.create();
807N/A StandardJavaFileManager fm = tool.getStandardFileManager(r, null, null);
807N/A
675N/A /**
675N/A * Read a file.
675N/A * @param file the file to be read
675N/A * @return the tree for the content of the file
675N/A * @throws IOException if any IO errors occur
675N/A * @throws TreePosTest.ParseException if any errors occur while parsing the file
675N/A */
675N/A List<Pair<JCCompilationUnit, JCTree>> read(File file) throws IOException, AttributionException {
675N/A JavacTool tool = JavacTool.create();
807N/A r.errors = 0;
675N/A Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file);
675N/A String[] opts = { "-XDshouldStopPolicy=ATTR", "-XDverboseCompilePolicy" };
675N/A JavacTask task = tool.getTask(pw, fm, r, Arrays.asList(opts), null, files);
675N/A final List<Element> analyzedElems = new ArrayList<>();
675N/A task.setTaskListener(new TaskListener() {
675N/A public void started(TaskEvent e) {
675N/A if (e.getKind() == TaskEvent.Kind.ANALYZE)
675N/A analyzedElems.add(e.getTypeElement());
675N/A }
675N/A public void finished(TaskEvent e) { }
675N/A });
675N/A
675N/A try {
675N/A Iterable<? extends CompilationUnitTree> trees = task.parse();
675N/A task.analyze();
675N/A List<Pair<JCCompilationUnit, JCTree>> res = new ArrayList<>();
682N/A //System.out.println("Try to add pairs. Elems are " + analyzedElems);
675N/A for (CompilationUnitTree t : trees) {
675N/A JCCompilationUnit cu = (JCCompilationUnit)t;
675N/A for (JCTree def : cu.defs) {
675N/A if (def.getTag() == JCTree.CLASSDEF &&
675N/A analyzedElems.contains(((JCTree.JCClassDecl)def).sym)) {
682N/A //System.out.println("Adding pair...");
675N/A res.add(new Pair<>(cu, def));
675N/A }
675N/A }
675N/A }
675N/A return res;
675N/A }
675N/A catch (Throwable t) {
675N/A throw new AttributionException("Exception while attributing file: " + file);
675N/A }
675N/A }
675N/A
675N/A /**
675N/A * Report an error. When the program is complete, the program will either
675N/A * exit or throw an Error if any errors have been reported.
675N/A * @param msg the error message
675N/A */
675N/A void error(String msg) {
675N/A System.err.println(msg);
675N/A errors++;
675N/A }
675N/A
675N/A /** Number of files that have been analyzed. */
675N/A int fileCount;
675N/A /** Number of errors reported. */
675N/A int errors;
675N/A /** Flag: don't report irrelevant files. */
675N/A boolean quiet;
675N/A /** Flag: show errors in GUI viewer. */
675N/A boolean gui;
675N/A /** The GUI viewer for errors. */
675N/A Viewer viewer;
675N/A /** Flag: report files as they are processed. */
675N/A boolean verbose;
675N/A /** Option: encoding for test files. */
675N/A String encoding;
675N/A /** The set of tags for tree nodes to be analyzed; if empty, all tree nodes
675N/A * are analyzed. */
675N/A Set<String> tags = new HashSet<String>();
675N/A /** Set of files and directories to be excluded from analysis. */
675N/A Set<File> excludeFiles = new HashSet<File>();
675N/A /** Set of tag names to be excluded from analysis. */
675N/A Set<String> excludeTags = new HashSet<String>();
675N/A /** Utility class for trees */
675N/A TreeUtil treeUtil = new TreeUtil();
675N/A
675N/A /**
675N/A * Main class for testing assertions concerning types/symbol
675N/A * left uninitialized after attribution
675N/A */
675N/A private class NPETester extends TreeScanner {
675N/A void test(List<Pair<JCCompilationUnit, JCTree>> trees) {
675N/A for (Pair<JCCompilationUnit, JCTree> p : trees) {
675N/A sourcefile = p.fst.sourcefile;
675N/A endPosTable = p.fst.endPositions;
675N/A encl = new Info(p.snd, endPosTable);
675N/A p.snd.accept(this);
675N/A }
675N/A }
675N/A
675N/A @Override
675N/A public void scan(JCTree tree) {
675N/A if (tree == null ||
675N/A excludeTags.contains(treeUtil.nameFromTag(tree.getTag()))) {
675N/A return;
675N/A }
675N/A
675N/A Info self = new Info(tree, endPosTable);
675N/A check(!mandatoryType(tree) ||
675N/A (tree.type != null &&
675N/A checkFields(tree)),
675N/A "'null' found in tree ",
675N/A self);
675N/A
675N/A Info prevEncl = encl;
675N/A encl = self;
675N/A tree.accept(this);
675N/A encl = prevEncl;
675N/A }
675N/A
675N/A private boolean mandatoryType(JCTree that) {
675N/A return that instanceof JCTree.JCExpression ||
675N/A that.getTag() == JCTree.VARDEF ||
675N/A that.getTag() == JCTree.METHODDEF ||
675N/A that.getTag() == JCTree.CLASSDEF;
675N/A }
675N/A
675N/A private final List<String> excludedFields = Arrays.asList("varargsElement");
675N/A
675N/A void check(boolean ok, String label, Info self) {
675N/A if (!ok) {
675N/A if (gui) {
675N/A if (viewer == null)
675N/A viewer = new Viewer();
675N/A viewer.addEntry(sourcefile, label, encl, self);
675N/A }
675N/A error(label + self.toString() + " encl: " + encl.toString() + " in file: " + sourcefile + " " + self.tree);
675N/A }
675N/A }
675N/A
675N/A boolean checkFields(JCTree t) {
675N/A List<Field> fieldsToCheck = treeUtil.getFieldsOfType(t,
675N/A excludedFields,
675N/A Symbol.class,
675N/A Type.class);
675N/A for (Field f : fieldsToCheck) {
675N/A try {
675N/A if (f.get(t) == null) {
675N/A return false;
675N/A }
675N/A }
675N/A catch (IllegalAccessException e) {
675N/A System.err.println("Cannot read field: " + f);
675N/A //swallow it
675N/A }
675N/A }
675N/A return true;
675N/A }
675N/A
675N/A @Override
675N/A public void visitImport(JCImport tree) { }
675N/A
675N/A @Override
675N/A public void visitTopLevel(JCCompilationUnit tree) {
675N/A scan(tree.defs);
675N/A }
675N/A
675N/A JavaFileObject sourcefile;
675N/A Map<JCTree, Integer> endPosTable;
675N/A Info encl;
675N/A }
675N/A
675N/A /**
675N/A * Utility class providing easy access to position and other info for a tree node.
675N/A */
675N/A private class Info {
675N/A Info() {
675N/A tree = null;
675N/A tag = JCTree.ERRONEOUS;
675N/A start = 0;
675N/A pos = 0;
675N/A end = Integer.MAX_VALUE;
675N/A }
675N/A
675N/A Info(JCTree tree, Map<JCTree, Integer> endPosTable) {
675N/A this.tree = tree;
675N/A tag = tree.getTag();
675N/A start = TreeInfo.getStartPos(tree);
675N/A pos = tree.pos;
675N/A end = TreeInfo.getEndPos(tree, endPosTable);
675N/A }
675N/A
675N/A @Override
675N/A public String toString() {
675N/A return treeUtil.nameFromTag(tree.getTag()) + "[start:" + start + ",pos:" + pos + ",end:" + end + "]";
675N/A }
675N/A
675N/A final JCTree tree;
675N/A final int tag;
675N/A final int start;
675N/A final int pos;
675N/A final int end;
675N/A }
675N/A
675N/A /**
675N/A * Names for tree tags.
675N/A * javac does not provide an API to convert tag values to strings, so this class uses
675N/A * reflection to determine names of public static final int values in JCTree.
675N/A */
675N/A private static class TreeUtil {
675N/A String nameFromTag(int tag) {
675N/A if (names == null) {
675N/A names = new HashMap<Integer, String>();
675N/A Class c = JCTree.class;
675N/A for (Field f : c.getDeclaredFields()) {
675N/A if (f.getType().equals(int.class)) {
675N/A int mods = f.getModifiers();
675N/A if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
675N/A try {
675N/A names.put(f.getInt(null), f.getName());
675N/A } catch (IllegalAccessException e) {
675N/A }
675N/A }
675N/A }
675N/A }
675N/A }
675N/A String name = names.get(tag);
675N/A return (name == null) ? "??" : name;
675N/A }
675N/A
675N/A List<Field> getFieldsOfType(JCTree t, List<String> excludeNames, Class<?>... types) {
675N/A List<Field> buf = new ArrayList<Field>();
675N/A for (Field f : t.getClass().getDeclaredFields()) {
675N/A if (!excludeNames.contains(f.getName())) {
675N/A for (Class<?> type : types) {
675N/A if (type.isAssignableFrom(f.getType())) {
675N/A f.setAccessible(true);
675N/A buf.add(f);
675N/A break;
675N/A }
675N/A }
675N/A }
675N/A }
675N/A return buf;
675N/A }
675N/A
675N/A private Map<Integer, String> names;
675N/A }
675N/A
675N/A /**
675N/A * Thrown when errors are found parsing a java file.
675N/A */
675N/A private static class ParseException extends Exception {
675N/A ParseException(String msg) {
675N/A super(msg);
675N/A }
675N/A }
675N/A
675N/A private static class AttributionException extends Exception {
675N/A AttributionException(String msg) {
675N/A super(msg);
675N/A }
675N/A }
675N/A
675N/A /**
675N/A * DiagnosticListener to report diagnostics and count any errors that occur.
675N/A */
675N/A private static class Reporter implements DiagnosticListener<JavaFileObject> {
675N/A Reporter(PrintWriter out) {
675N/A this.out = out;
675N/A }
675N/A
675N/A public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
675N/A out.println(diagnostic);
675N/A switch (diagnostic.getKind()) {
675N/A case ERROR:
675N/A errors++;
675N/A }
675N/A }
675N/A int errors;
675N/A PrintWriter out;
675N/A }
675N/A
675N/A /**
675N/A * GUI viewer for issues found by TreePosTester. The viewer provides a drop
675N/A * down list for selecting error conditions, a header area providing details
675N/A * about an error, and a text area with the ranges of text highlighted as
675N/A * appropriate.
675N/A */
675N/A private class Viewer extends JFrame {
675N/A /**
675N/A * Create a viewer.
675N/A */
675N/A Viewer() {
675N/A initGUI();
675N/A }
675N/A
675N/A /**
675N/A * Add another entry to the list of errors.
675N/A * @param file The file containing the error
675N/A * @param check The condition that was being tested, and which failed
675N/A * @param encl the enclosing tree node
675N/A * @param self the tree node containing the error
675N/A */
675N/A void addEntry(JavaFileObject file, String check, Info encl, Info self) {
675N/A Entry e = new Entry(file, check, encl, self);
675N/A DefaultComboBoxModel m = (DefaultComboBoxModel) entries.getModel();
675N/A m.addElement(e);
675N/A if (m.getSize() == 1)
675N/A entries.setSelectedItem(e);
675N/A }
675N/A
675N/A /**
675N/A * Initialize the GUI window.
675N/A */
675N/A private void initGUI() {
675N/A JPanel head = new JPanel(new GridBagLayout());
675N/A GridBagConstraints lc = new GridBagConstraints();
675N/A GridBagConstraints fc = new GridBagConstraints();
675N/A fc.anchor = GridBagConstraints.WEST;
675N/A fc.fill = GridBagConstraints.HORIZONTAL;
675N/A fc.gridwidth = GridBagConstraints.REMAINDER;
675N/A
675N/A entries = new JComboBox();
675N/A entries.addActionListener(new ActionListener() {
675N/A public void actionPerformed(ActionEvent e) {
675N/A showEntry((Entry) entries.getSelectedItem());
675N/A }
675N/A });
675N/A fc.insets.bottom = 10;
675N/A head.add(entries, fc);
675N/A fc.insets.bottom = 0;
675N/A head.add(new JLabel("check:"), lc);
675N/A head.add(checkField = createTextField(80), fc);
675N/A fc.fill = GridBagConstraints.NONE;
675N/A head.add(setBackground(new JLabel("encl:"), enclColor), lc);
675N/A head.add(enclPanel = new InfoPanel(), fc);
675N/A head.add(setBackground(new JLabel("self:"), selfColor), lc);
675N/A head.add(selfPanel = new InfoPanel(), fc);
675N/A add(head, BorderLayout.NORTH);
675N/A
675N/A body = new JTextArea();
675N/A body.setFont(Font.decode(Font.MONOSPACED));
675N/A body.addCaretListener(new CaretListener() {
675N/A public void caretUpdate(CaretEvent e) {
675N/A int dot = e.getDot();
675N/A int mark = e.getMark();
675N/A if (dot == mark)
675N/A statusText.setText("dot: " + dot);
675N/A else
675N/A statusText.setText("dot: " + dot + ", mark:" + mark);
675N/A }
675N/A });
675N/A JScrollPane p = new JScrollPane(body,
675N/A JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
675N/A JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
675N/A p.setPreferredSize(new Dimension(640, 480));
675N/A add(p, BorderLayout.CENTER);
675N/A
675N/A statusText = createTextField(80);
675N/A add(statusText, BorderLayout.SOUTH);
675N/A
675N/A pack();
675N/A setLocationRelativeTo(null); // centered on screen
675N/A setVisible(true);
675N/A setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
675N/A }
675N/A
675N/A /** Show an entry that has been selected. */
675N/A private void showEntry(Entry e) {
675N/A try {
675N/A // update simple fields
675N/A setTitle(e.file.getName());
675N/A checkField.setText(e.check);
675N/A enclPanel.setInfo(e.encl);
675N/A selfPanel.setInfo(e.self);
675N/A // show file text with highlights
675N/A body.setText(e.file.getCharContent(true).toString());
675N/A Highlighter highlighter = body.getHighlighter();
675N/A highlighter.removeAllHighlights();
675N/A addHighlight(highlighter, e.encl, enclColor);
675N/A addHighlight(highlighter, e.self, selfColor);
675N/A scroll(body, getMinPos(enclPanel.info, selfPanel.info));
675N/A } catch (IOException ex) {
675N/A body.setText("Cannot read " + e.file.getName() + ": " + e);
675N/A }
675N/A }
675N/A
675N/A /** Create a test field. */
675N/A private JTextField createTextField(int width) {
675N/A JTextField f = new JTextField(width);
675N/A f.setEditable(false);
675N/A f.setBorder(null);
675N/A return f;
675N/A }
675N/A
675N/A /** Add a highlighted region based on the positions in an Info object. */
675N/A private void addHighlight(Highlighter h, Info info, Color c) {
675N/A int start = info.start;
675N/A int end = info.end;
675N/A if (start == -1 && end == -1)
675N/A return;
675N/A if (start == -1)
675N/A start = end;
675N/A if (end == -1)
675N/A end = start;
675N/A try {
675N/A h.addHighlight(info.start, info.end,
675N/A new DefaultHighlighter.DefaultHighlightPainter(c));
675N/A if (info.pos != -1) {
675N/A Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
675N/A h.addHighlight(info.pos, info.pos + 1,
675N/A new DefaultHighlighter.DefaultHighlightPainter(c2));
675N/A }
675N/A } catch (BadLocationException e) {
675N/A e.printStackTrace();
675N/A }
675N/A }
675N/A
675N/A /** Get the minimum valid position in a set of info objects. */
675N/A private int getMinPos(Info... values) {
675N/A int i = Integer.MAX_VALUE;
675N/A for (Info info: values) {
675N/A if (info.start >= 0) i = Math.min(i, info.start);
675N/A if (info.pos >= 0) i = Math.min(i, info.pos);
675N/A if (info.end >= 0) i = Math.min(i, info.end);
675N/A }
675N/A return (i == Integer.MAX_VALUE) ? 0 : i;
675N/A }
675N/A
675N/A /** Set the background on a component. */
675N/A private JComponent setBackground(JComponent comp, Color c) {
675N/A comp.setOpaque(true);
675N/A comp.setBackground(c);
675N/A return comp;
675N/A }
675N/A
675N/A /** Scroll a text area to display a given position near the middle of the visible area. */
675N/A private void scroll(final JTextArea t, final int pos) {
675N/A // Using invokeLater appears to give text a chance to sort itself out
675N/A // before the scroll happens; otherwise scrollRectToVisible doesn't work.
675N/A // Maybe there's a better way to sync with the text...
675N/A EventQueue.invokeLater(new Runnable() {
675N/A public void run() {
675N/A try {
675N/A Rectangle r = t.modelToView(pos);
675N/A JScrollPane p = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, t);
675N/A r.y = Math.max(0, r.y - p.getHeight() * 2 / 5);
675N/A r.height += p.getHeight() * 4 / 5;
675N/A t.scrollRectToVisible(r);
675N/A } catch (BadLocationException ignore) {
675N/A }
675N/A }
675N/A });
675N/A }
675N/A
675N/A private JComboBox entries;
675N/A private JTextField checkField;
675N/A private InfoPanel enclPanel;
675N/A private InfoPanel selfPanel;
675N/A private JTextArea body;
675N/A private JTextField statusText;
675N/A
675N/A private Color selfColor = new Color(0.f, 1.f, 0.f, 0.2f); // 20% green
675N/A private Color enclColor = new Color(1.f, 0.f, 0.f, 0.2f); // 20% red
675N/A
675N/A /** Panel to display an Info object. */
675N/A private class InfoPanel extends JPanel {
675N/A InfoPanel() {
675N/A add(tagName = createTextField(20));
675N/A add(new JLabel("start:"));
675N/A add(addListener(start = createTextField(6)));
675N/A add(new JLabel("pos:"));
675N/A add(addListener(pos = createTextField(6)));
675N/A add(new JLabel("end:"));
675N/A add(addListener(end = createTextField(6)));
675N/A }
675N/A
675N/A void setInfo(Info info) {
675N/A this.info = info;
675N/A tagName.setText(treeUtil.nameFromTag(info.tag));
675N/A start.setText(String.valueOf(info.start));
675N/A pos.setText(String.valueOf(info.pos));
675N/A end.setText(String.valueOf(info.end));
675N/A }
675N/A
675N/A JTextField addListener(final JTextField f) {
675N/A f.addMouseListener(new MouseAdapter() {
675N/A @Override
675N/A public void mouseClicked(MouseEvent e) {
675N/A body.setCaretPosition(Integer.valueOf(f.getText()));
675N/A body.getCaret().setVisible(true);
675N/A }
675N/A });
675N/A return f;
675N/A }
675N/A
675N/A Info info;
675N/A JTextField tagName;
675N/A JTextField start;
675N/A JTextField pos;
675N/A JTextField end;
675N/A }
675N/A
675N/A /** Object to record information about an error to be displayed. */
675N/A private class Entry {
675N/A Entry(JavaFileObject file, String check, Info encl, Info self) {
675N/A this.file = file;
675N/A this.check = check;
675N/A this.encl = encl;
675N/A this.self= self;
675N/A }
675N/A
675N/A @Override
675N/A public String toString() {
675N/A return file.getName() + " " + check + " " + getMinPos(encl, self);
675N/A }
675N/A
675N/A final JavaFileObject file;
675N/A final String check;
675N/A final Info encl;
675N/A final Info self;
675N/A }
675N/A }
675N/A}