TreePosRoundsTest.java revision 694:3c9b64e55c5d
1/* 2 * Copyright (c) 2010, 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 6985205 27 * @summary access to tree positions and doc comments may be lost across annotation processing rounds 28 * @build TreePosRoundsTest 29 * @compile -proc:only -processor TreePosRoundsTest TreePosRoundsTest.java 30 * @run main TreePosRoundsTest 31 */ 32 33import java.io.*; 34import java.util.*; 35import javax.annotation.processing.*; 36import javax.lang.model.*; 37import javax.lang.model.element.*; 38import javax.tools.*; 39 40import com.sun.source.tree.*; 41import com.sun.source.util.*; 42import javax.tools.JavaCompiler.CompilationTask; 43 44// This test is an annotation processor that performs multiple rounds of 45// processing, and on each round, it checks that source positions are 46// available and correct. 47// 48// The test can be run directly as a processor from the javac command line 49// or via JSR 199 by invoking the main program. 50 51@SupportedAnnotationTypes("*") 52public class TreePosRoundsTest extends AbstractProcessor { 53 public static void main(String... args) throws Exception { 54 String testSrc = System.getProperty("test.src"); 55 String testClasses = System.getProperty("test.classes"); 56 JavaCompiler c = ToolProvider.getSystemJavaCompiler(); 57 StandardJavaFileManager fm = c.getStandardFileManager(null, null, null); 58 String thisName = TreePosRoundsTest.class.getName(); 59 File thisFile = new File(testSrc, thisName + ".java"); 60 Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile); 61 List<String> options = Arrays.asList( 62 "-proc:only", 63 "-processor", thisName, 64 "-processorpath", testClasses); 65 CompilationTask t = c.getTask(null, fm, null, options, null, files); 66 boolean ok = t.call(); 67 if (!ok) 68 throw new Exception("processing failed"); 69 } 70 71 Filer filer; 72 Messager messager; 73 74 @Override 75 public SourceVersion getSupportedSourceVersion() { 76 return SourceVersion.latest(); 77 } 78 79 @Override 80 public void init(ProcessingEnvironment pEnv) { 81 super.init(pEnv); 82 filer = pEnv.getFiler(); 83 messager = pEnv.getMessager(); 84 } 85 86 int round = 0; 87 88 @Override 89 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { 90 round++; 91 92 // Scan trees for elements, verifying source tree positions 93 for (Element e: roundEnv.getRootElements()) { 94 try { 95 Trees trees = Trees.instance(processingEnv); // cannot cache this across rounds 96 TreePath p = trees.getPath(e); 97 new TestTreeScanner(p.getCompilationUnit(), trees).scan(trees.getPath(e), null); 98 } catch (IOException ex) { 99 messager.printMessage(Diagnostic.Kind.ERROR, 100 "Cannot get source: " + ex, e); 101 } 102 } 103 104 final int MAXROUNDS = 3; 105 if (round < MAXROUNDS) 106 generateSource("Gen" + round); 107 108 return true; 109 } 110 111 void generateSource(String name) { 112 StringBuilder text = new StringBuilder(); 113 text.append("class ").append(name).append("{\n"); 114 text.append(" int one = 1;\n"); 115 text.append(" int two = 2;\n"); 116 text.append(" int three = one + two;\n"); 117 text.append("}\n"); 118 119 try { 120 JavaFileObject fo = filer.createSourceFile(name); 121 Writer out = fo.openWriter(); 122 try { 123 out.write(text.toString()); 124 } finally { 125 out.close(); 126 } 127 } catch (IOException e) { 128 throw new Error(e); 129 } 130 } 131 132 class TestTreeScanner extends TreePathScanner<Void,Void> { 133 TestTreeScanner(CompilationUnitTree unit, Trees trees) throws IOException { 134 this.unit = unit; 135 JavaFileObject sf = unit.getSourceFile(); 136 source = sf.getCharContent(true).toString(); 137 sourcePositions = trees.getSourcePositions(); 138 } 139 140 @Override 141 public Void visitVariable(VariableTree tree, Void _) { 142 check(getCurrentPath()); 143 return super.visitVariable(tree, _); 144 } 145 146 void check(TreePath tp) { 147 Tree tree = tp.getLeaf(); 148 149 String expect = tree.toString(); 150 if (tree.getKind() == Tree.Kind.VARIABLE) { 151 // tree.toString() does not know enough context to add ";", 152 // so deal with that manually... 153 Tree.Kind enclKind = tp.getParentPath().getLeaf().getKind(); 154 //System.err.println(" encl: " +enclKind); 155 if (enclKind == Tree.Kind.CLASS || enclKind == Tree.Kind.BLOCK) 156 expect += ";"; 157 } 158 //System.err.println("expect: " + expect); 159 160 int start = (int)sourcePositions.getStartPosition(unit, tree); 161 if (start == Diagnostic.NOPOS) { 162 messager.printMessage(Diagnostic.Kind.ERROR, "start pos not set for " + trim(tree)); 163 return; 164 } 165 166 int end = (int)sourcePositions.getEndPosition(unit, tree); 167 if (end == Diagnostic.NOPOS) { 168 messager.printMessage(Diagnostic.Kind.ERROR, "end pos not set for " + trim(tree)); 169 return; 170 } 171 172 String found = source.substring(start, end); 173 //System.err.println(" found: " + found); 174 175 // allow for long lines, in which case just compare beginning and 176 // end of the strings 177 boolean equal; 178 if (found.contains("\n")) { 179 String head = found.substring(0, found.indexOf("\n")); 180 String tail = found.substring(found.lastIndexOf("\n")).trim(); 181 equal = expect.startsWith(head) && expect.endsWith(tail); 182 } else { 183 equal = expect.equals(found); 184 } 185 186 if (!equal) { 187 messager.printMessage(Diagnostic.Kind.ERROR, 188 "unexpected value found: '" + found + "'; expected: '" + expect + "'"); 189 } 190 } 191 192 String trim(Tree tree) { 193 final int MAXLEN = 32; 194 String s = tree.toString().replaceAll("\\s+", " ").trim(); 195 return (s.length() < MAXLEN) ? s : s.substring(0, MAXLEN); 196 197 } 198 199 CompilationUnitTree unit; 200 SourcePositions sourcePositions; 201 String source; 202 } 203 204} 205