1 /*
   2  * Copyright (c) 2005, 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     4813736
  27  * @summary Additional functionality test of task and JSR 269
  28  * @author  Peter von der Ah\u00e9
  29  * @library ./lib
  30  * @run main TestJavacTaskScanner TestJavacTaskScanner.java
  31  */
  32 
  33 import com.sun.tools.javac.api.JavacTaskImpl;
  34 import com.sun.tools.javac.parser.*;
  35 import com.sun.tools.javac.parser.Tokens.Token;
  36 import com.sun.tools.javac.util.*;
  37 import java.io.*;
  38 import java.net.*;
  39 import java.nio.*;
  40 import java.nio.charset.Charset;
  41 import java.util.Arrays;
  42 import javax.lang.model.element.Element;
  43 import javax.lang.model.element.TypeElement;
  44 import javax.lang.model.type.DeclaredType;
  45 import javax.lang.model.type.TypeMirror;
  46 import javax.lang.model.util.Elements;
  47 import javax.lang.model.util.Types;
  48 import javax.tools.*;
  49 
  50 import static javax.tools.StandardLocation.CLASS_PATH;
  51 import static javax.tools.StandardLocation.SOURCE_PATH;
  52 import static javax.tools.StandardLocation.CLASS_OUTPUT;
  53 
  54 public class TestJavacTaskScanner extends ToolTester {
  55 
  56     final JavacTaskImpl task;
  57     final Elements elements;
  58     final Types types;
  59 
  60     int numTokens;
  61     int numParseTypeElements;
  62     int numAllMembers;
  63 
  64     TestJavacTaskScanner(File file) {
  65         final Iterable<? extends JavaFileObject> compilationUnits =
  66             fm.getJavaFileObjects(new File[] {file});
  67         StandardJavaFileManager fm = getLocalFileManager(tool, null, null);
  68         task = (JavacTaskImpl)tool.getTask(null, fm, null, null, null, compilationUnits);
  69         task.getContext().put(ScannerFactory.scannerFactoryKey,
  70                 new MyScanner.Factory(task.getContext(), this));
  71         elements = task.getElements();
  72         types = task.getTypes();
  73     }
  74 
  75     public void run() {
  76         Iterable<? extends TypeElement> toplevels;
  77         try {
  78             toplevels = task.enter(task.parse());
  79         } catch (IOException ex) {
  80             throw new AssertionError(ex);
  81         }
  82         for (TypeElement clazz : toplevels) {
  83             System.out.format("Testing %s:%n%n", clazz.getSimpleName());
  84             testParseType(clazz);
  85             testGetAllMembers(clazz);
  86             System.out.println();
  87             System.out.println();
  88             System.out.println();
  89         }
  90 
  91         System.out.println("#tokens: " + numTokens);
  92         System.out.println("#parseTypeElements: " + numParseTypeElements);
  93         System.out.println("#allMembers: " + numAllMembers);
  94 
  95         check(numTokens, "#Tokens", 1222);
  96         check(numParseTypeElements, "#parseTypeElements", 136);
  97         check(numAllMembers, "#allMembers", 52);
  98     }
  99 
 100     void check(int value, String name, int expected) {
 101         // allow some slop in the comparison to allow for minor edits in the
 102         // test and in the platform
 103         if (value < expected * 9 / 10)
 104             throw new Error(name + " lower than expected; expected " + expected + "; found: " + value);
 105         if (value > expected * 11 / 10)
 106             throw new Error(name + " higher than expected; expected " + expected + "; found: " + value);
 107     }
 108 
 109     void testParseType(TypeElement clazz) {
 110         DeclaredType type = (DeclaredType)task.parseType("List<String>", clazz);
 111         for (Element member : elements.getAllMembers((TypeElement)type.asElement())) {
 112             TypeMirror mt = types.asMemberOf(type, member);
 113             System.out.format("%s : %s -> %s%n", member.getSimpleName(), member.asType(), mt);
 114             numParseTypeElements++;
 115         }
 116     }
 117 
 118     public static void main(String... args) throws IOException {
 119         String srcdir = System.getProperty("test.src");
 120         new TestJavacTaskScanner(new File(srcdir, args[0])).run();
 121     }
 122 
 123     private void testGetAllMembers(TypeElement clazz) {
 124         for (Element member : elements.getAllMembers(clazz)) {
 125             System.out.format("%s : %s%n", member.getSimpleName(), member.asType());
 126             numAllMembers++;
 127         }
 128     }
 129 
 130     /* Similar to ToolTester.getFileManager, except that this version also ensures
 131      * javac classes will be available on the classpath.  The javac classes are assumed
 132      * to be on the classpath used to run this test (this is true when using jtreg).
 133      * The classes are found by obtaining the URL for a sample javac class, using
 134      * getClassLoader().getResource(), and then deconstructing the URL to find the
 135      * underlying directory or jar file to place on the classpath.
 136      */
 137     public StandardJavaFileManager getLocalFileManager(JavaCompiler tool,
 138                                                         DiagnosticListener<JavaFileObject> dl,
 139                                                         Charset encoding) {
 140         File javac_classes;
 141         try {
 142             final String javacMainClass = "com/sun/tools/javac/Main.class";
 143             URL url = getClass().getClassLoader().getResource(javacMainClass);
 144             if (url == null)
 145                 throw new Error("can't locate javac classes");
 146             URI uri = url.toURI();
 147             String scheme = uri.getScheme();
 148             String ssp = uri.getSchemeSpecificPart();
 149             if (scheme.equals("jar")) {
 150                 javac_classes = new File(new URI(ssp.substring(0, ssp.indexOf("!/"))));
 151             } else if (scheme.equals("file")) {
 152                 javac_classes = new File(ssp.substring(0, ssp.indexOf(javacMainClass)));
 153             } else
 154                 throw new Error("unknown URL: " + url);
 155         } catch (URISyntaxException e) {
 156             throw new Error(e);
 157         }
 158         System.err.println("javac_classes: " + javac_classes);
 159 
 160         StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, encoding);
 161         try {
 162             fm.setLocation(SOURCE_PATH,  Arrays.asList(test_src));
 163             fm.setLocation(CLASS_PATH,   Arrays.asList(test_classes, javac_classes));
 164             fm.setLocation(CLASS_OUTPUT, Arrays.asList(test_classes));
 165         } catch (IOException e) {
 166             throw new AssertionError(e);
 167         }
 168         return fm;
 169     }
 170 }
 171 
 172 class MyScanner extends Scanner {
 173 
 174     public static class Factory extends ScannerFactory {
 175         public Factory(Context context, TestJavacTaskScanner test) {
 176             super(context);
 177             this.test = test;
 178         }
 179 
 180         @Override
 181         public Scanner newScanner(CharSequence input, boolean keepDocComments) {
 182             assert !keepDocComments;
 183             if (input instanceof CharBuffer) {
 184                 return new MyScanner(this, (CharBuffer)input, test);
 185             } else {
 186                 char[] array = input.toString().toCharArray();
 187                 return newScanner(array, array.length, keepDocComments);
 188             }
 189         }
 190 
 191         @Override
 192         public Scanner newScanner(char[] input, int inputLength, boolean keepDocComments) {
 193             assert !keepDocComments;
 194             return new MyScanner(this, input, inputLength, test);
 195         }
 196 
 197         private TestJavacTaskScanner test;
 198     }
 199     protected MyScanner(ScannerFactory fac, CharBuffer buffer, TestJavacTaskScanner test) {
 200         super(fac, buffer);
 201         this.test = test;
 202     }
 203     protected MyScanner(ScannerFactory fac, char[] input, int inputLength, TestJavacTaskScanner test) {
 204         super(fac, input, inputLength);
 205         this.test = test;
 206     }
 207 
 208     public void nextToken() {
 209         super.nextToken();
 210         Token tk = token();
 211         System.err.format("Saw token %s %n", tk.kind);
 212         test.numTokens++;
 213     }
 214 
 215     private TestJavacTaskScanner test;
 216 
 217 }