2 * HTML via Java(tm) Language Bindings
3 * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. apidesign.org
13 * designates this particular file as subject to the
14 * "Classpath" exception as provided by apidesign.org
15 * in the License file that accompanied this code.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. Look for COPYING file in the top folder.
19 * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
21 package org.apidesign.html.boot.impl;
23 import java.io.Closeable;
24 import java.io.InputStream;
25 import java.io.InputStreamReader;
26 import java.io.Reader;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.Enumeration;
31 import java.util.List;
33 import java.util.concurrent.Callable;
34 import org.apidesign.html.boot.spi.Fn;
35 import org.objectweb.asm.AnnotationVisitor;
36 import org.objectweb.asm.ClassReader;
37 import org.objectweb.asm.ClassVisitor;
38 import org.objectweb.asm.ClassWriter;
39 import org.objectweb.asm.Label;
40 import org.objectweb.asm.MethodVisitor;
41 import org.objectweb.asm.Opcodes;
42 import org.objectweb.asm.Type;
43 import org.objectweb.asm.signature.SignatureReader;
44 import org.objectweb.asm.signature.SignatureVisitor;
45 import org.objectweb.asm.signature.SignatureWriter;
49 * @author Jaroslav Tulach <jtulach@netbeans.org>
51 public final class FnUtils implements Fn.Presenter {
56 /** Seeks for {@link JavaScriptBody} and {@link JavaScriptResource} annotations
57 * in the bytecode and converts them into real code. Used by Maven plugin
58 * postprocessing classes.
60 * @param bytecode the original bytecode with javascript specific annotations
61 * @param resources the resources to load
62 * @return the transformed bytecode
65 public static byte[] transform(byte[] bytecode, Map<String,InputStream> resources) {
66 return transform(null, bytecode);
69 public static boolean isJavaScriptCapable(ClassLoader l) {
70 if (l instanceof JsClassLoader) {
74 try (Closeable c = Fn.activate(new FnUtils())) {
75 clazz = Class.forName(Test.class.getName(), true, l);
76 final Object is = ((Callable<?>)clazz.newInstance()).call();
77 return Boolean.TRUE.equals(is);
78 } catch (Exception ex) {
83 public static boolean isValid(Fn fn) {
84 return fn != null && fn.isValid();
87 public static ClassLoader newLoader(final FindResources f, final Fn.Presenter d, ClassLoader parent) {
88 return new JsClassLoader(parent) {
90 protected URL findResource(String name) {
91 List<URL> l = res(name, true);
92 return l.isEmpty() ? null : l.get(0);
96 protected Enumeration<URL> findResources(String name) {
97 return Collections.enumeration(res(name, false));
100 private List<URL> res(String name, boolean oneIsEnough) {
101 List<URL> l = new ArrayList<URL>();
102 f.findResources(name, l, oneIsEnough);
107 protected Fn defineFn(String code, String... names) {
108 return d.defineFn(code, names);
112 protected void loadScript(Reader code) throws Exception {
118 static String callback(final String body) {
119 return new JsCallback() {
121 protected CharSequence callMethod(
122 String ident, String fqn, String method, String params
124 StringBuilder sb = new StringBuilder();
125 sb.append("vm.").append(mangle(fqn, method, params));
136 static void loadScript(ClassLoader jcl, String resource) {
137 final InputStream script = jcl.getResourceAsStream(resource);
138 if (script == null) {
139 throw new NullPointerException("Can't find " + resource);
144 isr = new InputStreamReader(script, "UTF-8");
145 FnContext.currentPresenter().loadScript(isr);
151 } catch (Exception ex) {
152 throw new IllegalStateException("Can't execute " + resource, ex);
157 public Fn defineFn(String code, String... names) {
162 public void displayPage(URL page, Runnable onPageLoad) {
166 public void loadScript(Reader code) throws Exception {
169 private static final class FindInClass extends ClassVisitor {
172 private ClassLoader loader;
174 public FindInClass(ClassLoader l, ClassVisitor cv) {
175 super(Opcodes.ASM4, cv);
180 public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
182 super.visit(version, access, name, signature, superName, interfaces);
186 public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
187 if ("Lnet/java/html/js/JavaScriptResource;".equals(desc)) {
188 return new LoadResource();
190 return super.visitAnnotation(desc, visible);
194 public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
195 return new FindInMethod(access, name, desc,
196 super.visitMethod(access & (~Opcodes.ACC_NATIVE), name, desc, signature, exceptions)
200 private final class FindInMethod extends MethodVisitor {
202 private final String name;
203 private final String desc;
204 private final int access;
205 private List<String> args;
207 private boolean bodyGenerated;
209 public FindInMethod(int access, String name, String desc, MethodVisitor mv) {
210 super(Opcodes.ASM4, mv);
211 this.access = access;
217 public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
218 if ("Lnet/java/html/js/JavaScriptBody;".equals(desc) // NOI18N
219 || "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;".equals(desc) // NOI18N
222 return new FindInAnno();
224 return super.visitAnnotation(desc, visible);
227 private void generateJSBody(List<String> args, String body) {
233 public void visitCode() {
240 private boolean generateBody() {
244 bodyGenerated = true;
246 super.visitFieldInsn(
247 Opcodes.GETSTATIC, FindInClass.this.name,
248 "$$fn$$" + name + "_" + found,
249 "Lorg/apidesign/html/boot/spi/Fn;"
251 super.visitInsn(Opcodes.DUP);
252 super.visitMethodInsn(
253 Opcodes.INVOKESTATIC,
254 "org/apidesign/html/boot/spi/Fn", "isValid",
255 "(Lorg/apidesign/html/boot/spi/Fn;)Z"
257 Label ifNotNull = new Label();
258 super.visitJumpInsn(Opcodes.IFNE, ifNotNull);
261 super.visitInsn(Opcodes.POP);
262 super.visitLdcInsn(Type.getObjectType(FindInClass.this.name));
263 super.visitLdcInsn(body);
264 super.visitIntInsn(Opcodes.SIPUSH, args.size());
265 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
266 boolean needsVM = false;
267 for (int i = 0; i < args.size(); i++) {
269 String argName = args.get(i);
270 needsVM = "vm".equals(argName);
271 super.visitInsn(Opcodes.DUP);
272 super.visitIntInsn(Opcodes.BIPUSH, i);
273 super.visitLdcInsn(argName);
274 super.visitInsn(Opcodes.AASTORE);
276 super.visitMethodInsn(Opcodes.INVOKESTATIC,
277 "org/apidesign/html/boot/spi/Fn", "define",
278 "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/String;)Lorg/apidesign/html/boot/spi/Fn;"
280 super.visitInsn(Opcodes.DUP);
281 super.visitFieldInsn(
282 Opcodes.PUTSTATIC, FindInClass.this.name,
283 "$$fn$$" + name + "_" + found,
284 "Lorg/apidesign/html/boot/spi/Fn;"
288 super.visitLabel(ifNotNull);
291 if ((access & Opcodes.ACC_STATIC) == 0) {
293 super.visitIntInsn(Opcodes.ALOAD, 0);
296 super.visitInsn(Opcodes.ACONST_NULL);
299 super.visitIntInsn(Opcodes.SIPUSH, args.size());
300 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
302 class SV extends SignatureVisitor {
304 private boolean nowReturn;
305 private Type returnType;
307 private int loadIndex = offset;
314 public void visitBaseType(char descriptor) {
315 final Type t = Type.getType("" + descriptor);
320 FindInMethod.super.visitInsn(Opcodes.DUP);
321 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index++);
322 FindInMethod.super.visitVarInsn(t.getOpcode(Opcodes.ILOAD), loadIndex++);
324 switch (descriptor) {
326 factory = "java/lang/Integer";
329 factory = "java/lang/Long";
333 factory = "java/lang/Short";
336 factory = "java/lang/Float";
339 factory = "java/lang/Double";
343 factory = "java/lang/Boolean";
346 factory = "java/lang/Character";
349 factory = "java/lang/Byte";
352 throw new IllegalStateException(t.toString());
354 FindInMethod.super.visitMethodInsn(Opcodes.INVOKESTATIC,
355 factory, "valueOf", "(" + descriptor + ")L" + factory + ";"
357 FindInMethod.super.visitInsn(Opcodes.AASTORE);
361 public SignatureVisitor visitArrayType() {
363 throw new IllegalStateException("Not supported yet");
366 return new SignatureWriter();
370 public void visitClassType(String name) {
372 returnType = Type.getObjectType(name);
379 public SignatureVisitor visitReturnType() {
384 private void loadObject() {
385 FindInMethod.super.visitInsn(Opcodes.DUP);
386 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index++);
387 FindInMethod.super.visitVarInsn(Opcodes.ALOAD, loadIndex++);
388 FindInMethod.super.visitInsn(Opcodes.AASTORE);
393 SignatureReader sr = new SignatureReader(desc);
397 FindInMethod.super.visitInsn(Opcodes.DUP);
398 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, sv.index);
399 int lastSlash = FindInClass.this.name.lastIndexOf('/');
400 String jsCallbacks = FindInClass.this.name.substring(0, lastSlash + 1) + "$JsCallbacks$";
401 FindInMethod.super.visitFieldInsn(Opcodes.GETSTATIC, jsCallbacks, "VM", "L" + jsCallbacks + ";");
402 FindInMethod.super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, jsCallbacks, "current", "()L" + jsCallbacks + ";");
403 FindInMethod.super.visitInsn(Opcodes.AASTORE);
406 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
407 "org/apidesign/html/boot/spi/Fn", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"
409 switch (sv.returnType.getSort()) {
411 super.visitInsn(Opcodes.RETURN);
415 super.visitTypeInsn(Opcodes.CHECKCAST, sv.returnType.getInternalName());
416 super.visitInsn(Opcodes.ARETURN);
419 super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Boolean");
420 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
421 "java/lang/Boolean", "booleanValue", "()Z"
423 super.visitInsn(Opcodes.IRETURN);
426 super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Number");
427 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
428 "java/lang/Number", sv.returnType.getClassName() + "Value", "()" + sv.returnType.getDescriptor()
430 super.visitInsn(sv.returnType.getOpcode(Opcodes.IRETURN));
436 public void visitEnd() {
439 if (generateBody()) {
441 super.visitMaxs(1, 0);
443 FindInClass.this.visitField(
444 Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC,
445 "$$fn$$" + name + "_" + found,
446 "Lorg/apidesign/html/boot/spi/Fn;",
452 private final class FindInAnno extends AnnotationVisitor {
454 private List<String> args = new ArrayList<String>();
456 private boolean javacall = false;
458 public FindInAnno() {
463 public void visit(String name, Object value) {
465 args.add((String) value);
468 if (name.equals("javacall")) { // NOI18N
469 javacall = (Boolean) value;
472 assert name.equals("body");
473 body = (String) value;
477 public AnnotationVisitor visitArray(String name) {
482 public void visitEnd() {
485 body = callback(body);
488 generateJSBody(args, body);
494 private final class LoadResource extends AnnotationVisitor {
496 public LoadResource() {
501 public void visit(String attrName, Object value) {
502 String relPath = (String) value;
503 if (relPath.startsWith("/")) {
504 loadScript(loader, relPath);
506 int last = name.lastIndexOf('/');
507 String fullPath = name.substring(0, last + 1) + relPath;
508 loadScript(loader, fullPath);
514 private static class ClassWriterEx extends ClassWriter {
516 private ClassLoader loader;
518 public ClassWriterEx(ClassLoader l, ClassReader classReader, int flags) {
519 super(classReader, flags);
524 protected String getCommonSuperClass(final String type1, final String type2) {
527 c = Class.forName(type1.replace('/', '.'), false, loader);
528 d = Class.forName(type2.replace('/', '.'), false, loader);
529 } catch (Exception e) {
530 throw new RuntimeException(e.toString());
532 if (c.isAssignableFrom(d)) {
535 if (d.isAssignableFrom(c)) {
538 if (c.isInterface() || d.isInterface()) {
539 return "java/lang/Object";
542 c = c.getSuperclass();
543 } while (!c.isAssignableFrom(d));
544 return c.getName().replace('.', '/');
549 static byte[] transform(ClassLoader loader, byte[] arr) {
550 ClassReader cr = new ClassReader(arr) {
551 // to allow us to compile with -profile compact1 on
552 // JDK8 while processing the class as JDK7, the highest
553 // class format asm 4.1 understands to
555 public short readShort(int index) {
556 short s = super.readShort(index);
557 if (index == 6 && s > Opcodes.V1_7) {
563 FindInClass tst = new FindInClass(loader, null);
566 ClassWriter w = new ClassWriterEx(loader, cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
567 FindInClass fic = new FindInClass(loader, w);
569 arr = w.toByteArray();
574 private static final class TrueFn extends Fn {
576 public Object invoke(Object thiz, Object... args) throws Exception {