Sat, 17 Nov 2012 19:01:03 +0000
8003280: Add lambda tests
Summary: Turn on lambda expression, method reference and default method support
Reviewed-by: jjg
1 /*
2 * Copyright (c) 2012, 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 */
24 /*
25 * @test
26 * @bug 7194586
27 *
28 * @bug 8003280
29 * @summary Add lambda tests
30 * Add back-end support for invokedynamic
31 *
32 */
34 import com.sun.source.tree.MethodInvocationTree;
35 import com.sun.source.tree.MethodTree;
36 import com.sun.source.util.TaskEvent;
37 import com.sun.source.util.TaskListener;
38 import com.sun.source.util.TreeScanner;
40 import com.sun.tools.classfile.Attribute;
41 import com.sun.tools.classfile.BootstrapMethods_attribute;
42 import com.sun.tools.classfile.ClassFile;
43 import com.sun.tools.classfile.Code_attribute;
44 import com.sun.tools.classfile.ConstantPool.*;
45 import com.sun.tools.classfile.Instruction;
46 import com.sun.tools.classfile.Method;
48 import com.sun.tools.javac.api.JavacTaskImpl;
49 import com.sun.tools.javac.api.JavacTool;
50 import com.sun.tools.javac.code.Symbol;
51 import com.sun.tools.javac.code.Symbol.MethodSymbol;
52 import com.sun.tools.javac.code.Symtab;
53 import com.sun.tools.javac.jvm.Pool;
54 import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
55 import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
56 import com.sun.tools.javac.tree.JCTree.JCIdent;
57 import com.sun.tools.javac.util.Context;
58 import com.sun.tools.javac.util.Names;
60 import java.io.File;
61 import java.net.URI;
62 import java.util.ArrayList;
63 import java.util.Arrays;
64 import java.util.Locale;
66 import javax.tools.Diagnostic;
67 import javax.tools.JavaCompiler;
68 import javax.tools.JavaFileManager;
69 import javax.tools.JavaFileObject;
70 import javax.tools.SimpleJavaFileObject;
71 import javax.tools.StandardJavaFileManager;
72 import javax.tools.ToolProvider;
74 import static com.sun.tools.javac.jvm.ClassFile.*;
76 public class TestInvokeDynamic {
78 static int checkCount = 0;
80 enum StaticArgumentKind {
81 STRING("Hello!", "String", "Ljava/lang/String;") {
82 @Override
83 boolean check(CPInfo cpInfo) throws Exception {
84 return (cpInfo instanceof CONSTANT_String_info) &&
85 ((CONSTANT_String_info)cpInfo).getString().equals(value);
86 }
87 },
88 CLASS(null, "Class<?>", "Ljava/lang/Class;") {
89 @Override
90 boolean check(CPInfo cpInfo) throws Exception {
91 return (cpInfo instanceof CONSTANT_Class_info) &&
92 ((CONSTANT_Class_info)cpInfo).getName().equals("java/lang/String");
93 }
94 },
95 INTEGER(1, "int", "I") {
96 @Override
97 boolean check(CPInfo cpInfo) throws Exception {
98 return (cpInfo instanceof CONSTANT_Integer_info) &&
99 ((CONSTANT_Integer_info)cpInfo).value == ((Integer)value).intValue();
100 }
101 },
102 LONG(1L, "long", "J") {
103 @Override
104 boolean check(CPInfo cpInfo) throws Exception {
105 return (cpInfo instanceof CONSTANT_Long_info) &&
106 ((CONSTANT_Long_info)cpInfo).value == ((Long)value).longValue();
107 }
108 },
109 FLOAT(1.0f, "float", "F") {
110 @Override
111 boolean check(CPInfo cpInfo) throws Exception {
112 return (cpInfo instanceof CONSTANT_Float_info) &&
113 ((CONSTANT_Float_info)cpInfo).value == ((Float)value).floatValue();
114 }
115 },
116 DOUBLE(1.0, "double","D") {
117 @Override
118 boolean check(CPInfo cpInfo) throws Exception {
119 return (cpInfo instanceof CONSTANT_Double_info) &&
120 ((CONSTANT_Double_info)cpInfo).value == ((Double)value).doubleValue();
121 }
122 },
123 METHOD_HANDLE(null, "MethodHandle", "Ljava/lang/invoke/MethodHandle;") {
124 @Override
125 boolean check(CPInfo cpInfo) throws Exception {
126 if (!(cpInfo instanceof CONSTANT_MethodHandle_info)) return false;
127 CONSTANT_MethodHandle_info handleInfo = (CONSTANT_MethodHandle_info)cpInfo;
128 return handleInfo.getCPRefInfo().getClassName().equals("Array") &&
129 handleInfo.reference_kind == RefKind.REF_invokeVirtual &&
130 handleInfo.getCPRefInfo().getNameAndTypeInfo().getName().equals("clone") &&
131 handleInfo.getCPRefInfo().getNameAndTypeInfo().getType().equals("()Ljava/lang/Object;");
132 }
133 },
134 METHOD_TYPE(null, "MethodType", "Ljava/lang/invoke/MethodType;") {
135 @Override
136 boolean check(CPInfo cpInfo) throws Exception {
137 return (cpInfo instanceof CONSTANT_MethodType_info) &&
138 ((CONSTANT_MethodType_info)cpInfo).getType().equals("()Ljava/lang/Object;");
139 }
140 };
142 Object value;
143 String sourceTypeStr;
144 String bytecodeTypeStr;
146 StaticArgumentKind(Object value, String sourceTypeStr, String bytecodeTypeStr) {
147 this.value = value;
148 this.sourceTypeStr = sourceTypeStr;
149 this.bytecodeTypeStr = bytecodeTypeStr;
150 }
152 abstract boolean check(CPInfo cpInfo) throws Exception;
154 Object getValue(Symtab syms, Names names) {
155 switch (this) {
156 case STRING:
157 case INTEGER:
158 case LONG:
159 case FLOAT:
160 case DOUBLE:
161 return value;
162 case CLASS:
163 return syms.stringType.tsym;
164 case METHOD_HANDLE:
165 return new Pool.MethodHandle(REF_invokeVirtual, syms.arrayCloneMethod);
166 case METHOD_TYPE:
167 return syms.arrayCloneMethod.type;
168 default:
169 throw new AssertionError();
170 }
171 }
172 }
174 enum StaticArgumentsArity {
175 ZERO(0),
176 ONE(1),
177 TWO(2),
178 THREE(3);
180 int arity;
182 StaticArgumentsArity(int arity) {
183 this.arity = arity;
184 }
185 }
187 public static void main(String... args) throws Exception {
188 // Create a single file manager and compiler and reuse it for each compile to save time.
189 StandardJavaFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
190 final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
191 for (StaticArgumentsArity arity : StaticArgumentsArity.values()) {
192 if (arity.arity == 0) {
193 new TestInvokeDynamic(arity).compileAndCheck(fm, tool);
194 } else {
195 for (StaticArgumentKind sak1 : StaticArgumentKind.values()) {
196 if (arity.arity == 1) {
197 new TestInvokeDynamic(arity, sak1).compileAndCheck(fm, tool);
198 } else {
199 for (StaticArgumentKind sak2 : StaticArgumentKind.values()) {
200 if (arity.arity == 2) {
201 new TestInvokeDynamic(arity, sak1, sak2).compileAndCheck(fm, tool);
202 } else {
203 for (StaticArgumentKind sak3 : StaticArgumentKind.values()) {
204 new TestInvokeDynamic(arity, sak1, sak2, sak3).compileAndCheck(fm, tool);
205 }
206 }
207 }
208 }
209 }
210 }
211 }
213 System.out.println("Total checks made: " + checkCount);
214 }
216 StaticArgumentsArity arity;
217 StaticArgumentKind[] saks;
218 JavaSource source;
219 DiagChecker dc;
221 TestInvokeDynamic(StaticArgumentsArity arity, StaticArgumentKind... saks) {
222 this.arity = arity;
223 this.saks = saks;
224 source = new JavaSource();
225 dc = new DiagChecker();
226 }
228 void compileAndCheck(JavaFileManager fm, JavaCompiler tool) throws Exception {
229 JavacTaskImpl ct = (JavacTaskImpl)tool.getTask(null, fm, dc,
230 null, null, Arrays.asList(source));
231 Context context = ct.getContext();
232 Symtab syms = Symtab.instance(context);
233 Names names = Names.instance(context);
234 ct.addTaskListener(new Indifier(syms, names));
235 try {
236 ct.generate();
237 } catch (Throwable t) {
238 t.printStackTrace();
239 throw new AssertionError(String.format("Error thrown when compiling following code\n%s", source.source));
240 }
241 if (dc.diagFound) {
242 throw new AssertionError(String.format("Diags found when compiling following code\n%s\n\n%s", source.source, dc.printDiags()));
243 }
244 verifyBytecode();
245 }
247 void verifyBytecode() {
248 File compiledTest = new File("Test.class");
249 try {
250 ClassFile cf = ClassFile.read(compiledTest);
251 Method testMethod = null;
252 for (Method m : cf.methods) {
253 if (m.getName(cf.constant_pool).equals("test")) {
254 testMethod = m;
255 break;
256 }
257 }
258 if (testMethod == null) {
259 throw new Error("Test method not found");
260 }
261 Code_attribute ea = (Code_attribute)testMethod.attributes.get(Attribute.Code);
262 if (testMethod == null) {
263 throw new Error("Code attribute for test() method not found");
264 }
266 int bsmIdx = -1;
268 for (Instruction i : ea.getInstructions()) {
269 if (i.getMnemonic().equals("invokedynamic")) {
270 CONSTANT_InvokeDynamic_info indyInfo =
271 (CONSTANT_InvokeDynamic_info)cf.constant_pool.get(i.getShort(1));
272 bsmIdx = indyInfo.bootstrap_method_attr_index;
273 if (!indyInfo.getNameAndTypeInfo().getType().equals("()V")) {
274 throw new AssertionError("type mismatch for CONSTANT_InvokeDynamic_info");
275 }
276 }
277 }
278 if (bsmIdx == -1) {
279 throw new Error("Missing invokedynamic in generated code");
280 }
282 BootstrapMethods_attribute bsm_attr = (BootstrapMethods_attribute)cf.getAttribute(Attribute.BootstrapMethods);
283 if (bsm_attr.bootstrap_method_specifiers.length != 1) {
284 throw new Error("Bad number of method specifiers in BootstrapMethods attribute");
285 }
286 BootstrapMethods_attribute.BootstrapMethodSpecifier bsm_spec =
287 bsm_attr.bootstrap_method_specifiers[0];
289 if (bsm_spec.bootstrap_arguments.length != arity.arity) {
290 throw new Error("Bad number of static invokedynamic args in BootstrapMethod attribute");
291 }
293 int count = 0;
294 for (StaticArgumentKind sak : saks) {
295 if (!sak.check(cf.constant_pool.get(bsm_spec.bootstrap_arguments[count]))) {
296 throw new Error("Bad static argument value " + sak);
297 }
298 count++;
299 }
301 CONSTANT_MethodHandle_info bsm_handle =
302 (CONSTANT_MethodHandle_info)cf.constant_pool.get(bsm_spec.bootstrap_method_ref);
304 if (bsm_handle.reference_kind != RefKind.REF_invokeStatic) {
305 throw new Error("Bad kind on boostrap method handle");
306 }
308 CONSTANT_Methodref_info bsm_ref =
309 (CONSTANT_Methodref_info)cf.constant_pool.get(bsm_handle.reference_index);
311 if (!bsm_ref.getClassInfo().getName().equals("Bootstrap")) {
312 throw new Error("Bad owner of boostrap method");
313 }
315 if (!bsm_ref.getNameAndTypeInfo().getName().equals("bsm")) {
316 throw new Error("Bad boostrap method name");
317 }
319 if (!bsm_ref.getNameAndTypeInfo().getType().equals(asBSMSignatureString())) {
320 throw new Error("Bad boostrap method type" + bsm_ref.getNameAndTypeInfo().getType() + " " + asBSMSignatureString());
321 }
322 } catch (Exception e) {
323 e.printStackTrace();
324 throw new Error("error reading " + compiledTest +": " + e);
325 }
326 }
328 String asBSMSignatureString() {
329 StringBuilder buf = new StringBuilder();
330 buf.append("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;");
331 for (StaticArgumentKind sak : saks) {
332 buf.append(sak.bytecodeTypeStr);
333 }
334 buf.append(")Ljava/lang/invoke/CallSite;");
335 return buf.toString();
336 }
338 class JavaSource extends SimpleJavaFileObject {
340 static final String source_template = "import java.lang.invoke.*;\n" +
341 "class Bootstrap {\n" +
342 " public static CallSite bsm(MethodHandles.Lookup lookup, String name, MethodType methodType #SARGS) {\n" +
343 " return null;\n" +
344 " }\n" +
345 "}\n" +
346 "class Test {\n" +
347 " void m() { }\n" +
348 " void test() { m(); }\n" +
349 "}";
351 String source;
353 JavaSource() {
354 super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
355 source = source_template.replace("#SARGS", asSignatureString());
356 }
358 @Override
359 public CharSequence getCharContent(boolean ignoreEncodingErrors) {
360 return source;
361 }
363 String asSignatureString() {
364 int count = 0;
365 StringBuilder buf = new StringBuilder();
366 for (StaticArgumentKind sak : saks) {
367 buf.append(",");
368 buf.append(sak.sourceTypeStr);
369 buf.append(' ');
370 buf.append(String.format("x%d", count++));
371 }
372 return buf.toString();
373 }
374 }
376 class Indifier extends TreeScanner<Void, Void> implements TaskListener {
378 MethodSymbol bsm;
379 Symtab syms;
380 Names names;
382 Indifier(Symtab syms, Names names) {
383 this.syms = syms;
384 this.names = names;
385 }
387 @Override
388 public void started(TaskEvent e) {
389 //do nothing
390 }
392 @Override
393 public void finished(TaskEvent e) {
394 if (e.getKind() == TaskEvent.Kind.ANALYZE) {
395 scan(e.getCompilationUnit(), null);
396 }
397 }
399 @Override
400 public Void visitMethodInvocation(MethodInvocationTree node, Void p) {
401 super.visitMethodInvocation(node, p);
402 JCMethodInvocation apply = (JCMethodInvocation)node;
403 JCIdent ident = (JCIdent)apply.meth;
404 Symbol oldSym = ident.sym;
405 if (!oldSym.isConstructor()) {
406 Object[] staticArgs = new Object[arity.arity];
407 for (int i = 0; i < arity.arity ; i++) {
408 staticArgs[i] = saks[i].getValue(syms, names);
409 }
410 ident.sym = new Symbol.DynamicMethodSymbol(oldSym.name, oldSym.owner, REF_invokeStatic, bsm, oldSym.type, staticArgs);
411 }
412 return null;
413 }
415 @Override
416 public Void visitMethod(MethodTree node, Void p) {
417 super.visitMethod(node, p);
418 if (node.getName().toString().equals("bsm")) {
419 bsm = ((JCMethodDecl)node).sym;
420 }
421 return null;
422 }
423 }
425 static class DiagChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
427 boolean diagFound;
428 ArrayList<String> diags = new ArrayList<>();
430 public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
431 diags.add(diagnostic.getMessage(Locale.getDefault()));
432 diagFound = true;
433 }
435 String printDiags() {
436 StringBuilder buf = new StringBuilder();
437 for (String s : diags) {
438 buf.append(s);
439 buf.append("\n");
440 }
441 return buf.toString();
442 }
443 }
444 }