boot/src/main/java/org/apidesign/html/boot/impl/FnUtils.java
changeset 323 86aabecda7a3
parent 309 7025177bd67e
child 331 72dda6af599b
child 349 53634fd10e30
     1.1 --- a/boot/src/main/java/org/apidesign/html/boot/impl/FnUtils.java	Thu Oct 10 14:02:18 2013 +0200
     1.2 +++ b/boot/src/main/java/org/apidesign/html/boot/impl/FnUtils.java	Wed Nov 06 15:15:54 2013 +0100
     1.3 @@ -20,6 +20,7 @@
     1.4   */
     1.5  package org.apidesign.html.boot.impl;
     1.6  
     1.7 +import java.io.Closeable;
     1.8  import java.io.InputStream;
     1.9  import java.io.InputStreamReader;
    1.10  import java.io.Reader;
    1.11 @@ -28,23 +29,41 @@
    1.12  import java.util.Collections;
    1.13  import java.util.Enumeration;
    1.14  import java.util.List;
    1.15 +import java.util.concurrent.Callable;
    1.16  import org.apidesign.html.boot.spi.Fn;
    1.17 +import org.objectweb.asm.AnnotationVisitor;
    1.18 +import org.objectweb.asm.ClassReader;
    1.19 +import org.objectweb.asm.ClassVisitor;
    1.20 +import org.objectweb.asm.ClassWriter;
    1.21 +import org.objectweb.asm.Label;
    1.22 +import org.objectweb.asm.MethodVisitor;
    1.23 +import org.objectweb.asm.Opcodes;
    1.24 +import org.objectweb.asm.Type;
    1.25 +import org.objectweb.asm.signature.SignatureReader;
    1.26 +import org.objectweb.asm.signature.SignatureVisitor;
    1.27 +import org.objectweb.asm.signature.SignatureWriter;
    1.28  
    1.29  /**
    1.30   *
    1.31   * @author Jaroslav Tulach <jtulach@netbeans.org>
    1.32   */
    1.33 -public final class FnUtils {
    1.34 +public final class FnUtils implements Fn.Presenter {
    1.35      
    1.36      private FnUtils() {
    1.37      }
    1.38      
    1.39 -    public static Fn define(Class<?> caller, String code, String... names) {
    1.40 -        return FnContext.currentPresenter().defineFn(code, names);
    1.41 -    }
    1.42 -    
    1.43      public static boolean isJavaScriptCapable(ClassLoader l) {
    1.44 -        return l instanceof JsClassLoader;
    1.45 +        if (l instanceof JsClassLoader) {
    1.46 +            return true;
    1.47 +        }
    1.48 +        Class<?> clazz;
    1.49 +        try (Closeable c = Fn.activate(new FnUtils())) {
    1.50 +            clazz = Class.forName(Test.class.getName(), true, l);
    1.51 +            final Object is = ((Callable<?>)clazz.newInstance()).call();
    1.52 +            return Boolean.TRUE.equals(is);
    1.53 +        } catch (Exception ex) {
    1.54 +            return false;
    1.55 +        }
    1.56      }
    1.57      
    1.58      public static boolean isValid(Fn fn) {
    1.59 @@ -100,7 +119,7 @@
    1.60          }.parse(body);
    1.61      }
    1.62  
    1.63 -    static void loadScript(JsClassLoader jcl, String resource) {
    1.64 +    static void loadScript(ClassLoader jcl, String resource) {
    1.65          final InputStream script = jcl.getResourceAsStream(resource);
    1.66          if (script == null) {
    1.67              throw new NullPointerException("Can't find " + resource);
    1.68 @@ -109,7 +128,7 @@
    1.69              Reader isr = null;
    1.70              try {
    1.71                  isr = new InputStreamReader(script, "UTF-8");
    1.72 -                jcl.loadScript(isr);
    1.73 +                FnContext.currentPresenter().loadScript(isr);
    1.74              } finally {
    1.75                  if (isr != null) {
    1.76                      isr.close();
    1.77 @@ -119,4 +138,429 @@
    1.78              throw new IllegalStateException("Can't execute " + resource, ex);
    1.79          } 
    1.80      }
    1.81 +
    1.82 +    @Override
    1.83 +    public Fn defineFn(String code, String... names) {
    1.84 +        return new TrueFn();
    1.85 +    }
    1.86 +
    1.87 +    @Override
    1.88 +    public void displayPage(URL page, Runnable onPageLoad) {
    1.89 +    }
    1.90 +
    1.91 +    @Override
    1.92 +    public void loadScript(Reader code) throws Exception {
    1.93 +    }
    1.94 +    
    1.95 +    private static final class FindInClass extends ClassVisitor {
    1.96 +        private String name;
    1.97 +        private int found;
    1.98 +        private ClassLoader loader;
    1.99 +
   1.100 +        public FindInClass(ClassLoader l, ClassVisitor cv) {
   1.101 +            super(Opcodes.ASM4, cv);
   1.102 +            this.loader = l;
   1.103 +        }
   1.104 +
   1.105 +        @Override
   1.106 +        public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
   1.107 +            this.name = name;
   1.108 +            super.visit(version, access, name, signature, superName, interfaces);
   1.109 +        }
   1.110 +
   1.111 +        @Override
   1.112 +        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
   1.113 +            if ("Lnet/java/html/js/JavaScriptResource;".equals(desc)) {
   1.114 +                return new LoadResource();
   1.115 +            }
   1.116 +            return super.visitAnnotation(desc, visible);
   1.117 +        }
   1.118 +
   1.119 +        @Override
   1.120 +        public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
   1.121 +            return new FindInMethod(access, name, desc,
   1.122 +                    super.visitMethod(access & (~Opcodes.ACC_NATIVE), name, desc, signature, exceptions)
   1.123 +            );
   1.124 +        }
   1.125 +
   1.126 +        private final class FindInMethod extends MethodVisitor {
   1.127 +
   1.128 +            private final String name;
   1.129 +            private final String desc;
   1.130 +            private final int access;
   1.131 +            private List<String> args;
   1.132 +            private String body;
   1.133 +            private boolean bodyGenerated;
   1.134 +
   1.135 +            public FindInMethod(int access, String name, String desc, MethodVisitor mv) {
   1.136 +                super(Opcodes.ASM4, mv);
   1.137 +                this.access = access;
   1.138 +                this.name = name;
   1.139 +                this.desc = desc;
   1.140 +            }
   1.141 +
   1.142 +            @Override
   1.143 +            public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
   1.144 +                if ("Lnet/java/html/js/JavaScriptBody;".equals(desc) // NOI18N
   1.145 +                        || "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;".equals(desc) // NOI18N
   1.146 +                        ) {
   1.147 +                    found++;
   1.148 +                    return new FindInAnno();
   1.149 +                }
   1.150 +                return super.visitAnnotation(desc, visible);
   1.151 +            }
   1.152 +
   1.153 +            private void generateJSBody(List<String> args, String body) {
   1.154 +                this.args = args;
   1.155 +                this.body = body;
   1.156 +            }
   1.157 +
   1.158 +            @Override
   1.159 +            public void visitCode() {
   1.160 +                if (body == null) {
   1.161 +                    return;
   1.162 +                }
   1.163 +                generateBody();
   1.164 +            }
   1.165 +
   1.166 +            private boolean generateBody() {
   1.167 +                if (bodyGenerated) {
   1.168 +                    return false;
   1.169 +                }
   1.170 +                bodyGenerated = true;
   1.171 +
   1.172 +                super.visitFieldInsn(
   1.173 +                        Opcodes.GETSTATIC, FindInClass.this.name,
   1.174 +                        "$$fn$$" + name + "_" + found,
   1.175 +                        "Lorg/apidesign/html/boot/spi/Fn;"
   1.176 +                );
   1.177 +                super.visitInsn(Opcodes.DUP);
   1.178 +                super.visitMethodInsn(
   1.179 +                        Opcodes.INVOKESTATIC,
   1.180 +                        "org/apidesign/html/boot/spi/Fn", "isValid",
   1.181 +                        "(Lorg/apidesign/html/boot/spi/Fn;)Z"
   1.182 +                );
   1.183 +                Label ifNotNull = new Label();
   1.184 +                super.visitJumpInsn(Opcodes.IFNE, ifNotNull);
   1.185 +
   1.186 +                // init Fn
   1.187 +                super.visitInsn(Opcodes.POP);
   1.188 +                super.visitLdcInsn(Type.getObjectType(FindInClass.this.name));
   1.189 +                super.visitLdcInsn(body);
   1.190 +                super.visitIntInsn(Opcodes.SIPUSH, args.size());
   1.191 +                super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
   1.192 +                boolean needsVM = false;
   1.193 +                for (int i = 0; i < args.size(); i++) {
   1.194 +                    assert !needsVM;
   1.195 +                    String argName = args.get(i);
   1.196 +                    needsVM = "vm".equals(argName);
   1.197 +                    super.visitInsn(Opcodes.DUP);
   1.198 +                    super.visitIntInsn(Opcodes.BIPUSH, i);
   1.199 +                    super.visitLdcInsn(argName);
   1.200 +                    super.visitInsn(Opcodes.AASTORE);
   1.201 +                }
   1.202 +                super.visitMethodInsn(Opcodes.INVOKESTATIC,
   1.203 +                        "org/apidesign/html/boot/spi/Fn", "define",
   1.204 +                        "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/String;)Lorg/apidesign/html/boot/spi/Fn;"
   1.205 +                );
   1.206 +                super.visitInsn(Opcodes.DUP);
   1.207 +                super.visitFieldInsn(
   1.208 +                        Opcodes.PUTSTATIC, FindInClass.this.name,
   1.209 +                        "$$fn$$" + name + "_" + found,
   1.210 +                        "Lorg/apidesign/html/boot/spi/Fn;"
   1.211 +                );
   1.212 +                // end of Fn init
   1.213 +
   1.214 +                super.visitLabel(ifNotNull);
   1.215 +
   1.216 +                final int offset;
   1.217 +                if ((access & Opcodes.ACC_STATIC) == 0) {
   1.218 +                    offset = 1;
   1.219 +                    super.visitIntInsn(Opcodes.ALOAD, 0);
   1.220 +                } else {
   1.221 +                    offset = 0;
   1.222 +                    super.visitInsn(Opcodes.ACONST_NULL);
   1.223 +                }
   1.224 +
   1.225 +                super.visitIntInsn(Opcodes.SIPUSH, args.size());
   1.226 +                super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
   1.227 +
   1.228 +                class SV extends SignatureVisitor {
   1.229 +
   1.230 +                    private boolean nowReturn;
   1.231 +                    private Type returnType;
   1.232 +                    private int index;
   1.233 +                    private int loadIndex = offset;
   1.234 +
   1.235 +                    public SV() {
   1.236 +                        super(Opcodes.ASM4);
   1.237 +                    }
   1.238 +
   1.239 +                    @Override
   1.240 +                    public void visitBaseType(char descriptor) {
   1.241 +                        final Type t = Type.getType("" + descriptor);
   1.242 +                        if (nowReturn) {
   1.243 +                            returnType = t;
   1.244 +                            return;
   1.245 +                        }
   1.246 +                        FindInMethod.super.visitInsn(Opcodes.DUP);
   1.247 +                        FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index++);
   1.248 +                        FindInMethod.super.visitVarInsn(t.getOpcode(Opcodes.ILOAD), loadIndex++);
   1.249 +                        String factory;
   1.250 +                        switch (descriptor) {
   1.251 +                            case 'I':
   1.252 +                                factory = "java/lang/Integer";
   1.253 +                                break;
   1.254 +                            case 'J':
   1.255 +                                factory = "java/lang/Long";
   1.256 +                                loadIndex++;
   1.257 +                                break;
   1.258 +                            case 'S':
   1.259 +                                factory = "java/lang/Short";
   1.260 +                                break;
   1.261 +                            case 'F':
   1.262 +                                factory = "java/lang/Float";
   1.263 +                                break;
   1.264 +                            case 'D':
   1.265 +                                factory = "java/lang/Double";
   1.266 +                                loadIndex++;
   1.267 +                                break;
   1.268 +                            case 'Z':
   1.269 +                                factory = "java/lang/Boolean";
   1.270 +                                break;
   1.271 +                            case 'C':
   1.272 +                                factory = "java/lang/Character";
   1.273 +                                break;
   1.274 +                            case 'B':
   1.275 +                                factory = "java/lang/Byte";
   1.276 +                                break;
   1.277 +                            default:
   1.278 +                                throw new IllegalStateException(t.toString());
   1.279 +                        }
   1.280 +                        FindInMethod.super.visitMethodInsn(Opcodes.INVOKESTATIC,
   1.281 +                                factory, "valueOf", "(" + descriptor + ")L" + factory + ";"
   1.282 +                        );
   1.283 +                        FindInMethod.super.visitInsn(Opcodes.AASTORE);
   1.284 +                    }
   1.285 +
   1.286 +                    @Override
   1.287 +                    public SignatureVisitor visitArrayType() {
   1.288 +                        if (nowReturn) {
   1.289 +                            throw new IllegalStateException("Not supported yet");
   1.290 +                        }
   1.291 +                        loadObject();
   1.292 +                        return new SignatureWriter();
   1.293 +                    }
   1.294 +
   1.295 +                    @Override
   1.296 +                    public void visitClassType(String name) {
   1.297 +                        if (nowReturn) {
   1.298 +                            returnType = Type.getObjectType(name);
   1.299 +                            return;
   1.300 +                        }
   1.301 +                        loadObject();
   1.302 +                    }
   1.303 +
   1.304 +                    @Override
   1.305 +                    public SignatureVisitor visitReturnType() {
   1.306 +                        nowReturn = true;
   1.307 +                        return this;
   1.308 +                    }
   1.309 +
   1.310 +                    private void loadObject() {
   1.311 +                        FindInMethod.super.visitInsn(Opcodes.DUP);
   1.312 +                        FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index++);
   1.313 +                        FindInMethod.super.visitVarInsn(Opcodes.ALOAD, loadIndex++);
   1.314 +                        FindInMethod.super.visitInsn(Opcodes.AASTORE);
   1.315 +                    }
   1.316 +
   1.317 +                }
   1.318 +                SV sv = new SV();
   1.319 +                SignatureReader sr = new SignatureReader(desc);
   1.320 +                sr.accept(sv);
   1.321 +
   1.322 +                if (needsVM) {
   1.323 +                    FindInMethod.super.visitInsn(Opcodes.DUP);
   1.324 +                    FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, sv.index);
   1.325 +                    int lastSlash = FindInClass.this.name.lastIndexOf('/');
   1.326 +                    String jsCallbacks = FindInClass.this.name.substring(0, lastSlash + 1) + "$JsCallbacks$";
   1.327 +                    FindInMethod.super.visitFieldInsn(Opcodes.GETSTATIC, jsCallbacks, "VM", "L" + jsCallbacks + ";");
   1.328 +                    FindInMethod.super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, jsCallbacks, "current", "()L" + jsCallbacks + ";");
   1.329 +                    FindInMethod.super.visitInsn(Opcodes.AASTORE);
   1.330 +                }
   1.331 +
   1.332 +                super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
   1.333 +                        "org/apidesign/html/boot/spi/Fn", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"
   1.334 +                );
   1.335 +                switch (sv.returnType.getSort()) {
   1.336 +                    case Type.VOID:
   1.337 +                        super.visitInsn(Opcodes.RETURN);
   1.338 +                        break;
   1.339 +                    case Type.ARRAY:
   1.340 +                    case Type.OBJECT:
   1.341 +                        super.visitTypeInsn(Opcodes.CHECKCAST, sv.returnType.getInternalName());
   1.342 +                        super.visitInsn(Opcodes.ARETURN);
   1.343 +                        break;
   1.344 +                    case Type.BOOLEAN:
   1.345 +                        super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Boolean");
   1.346 +                        super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
   1.347 +                                "java/lang/Boolean", "booleanValue", "()Z"
   1.348 +                        );
   1.349 +                        super.visitInsn(Opcodes.IRETURN);
   1.350 +                        break;
   1.351 +                    default:
   1.352 +                        super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Number");
   1.353 +                        super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
   1.354 +                                "java/lang/Number", sv.returnType.getClassName() + "Value", "()" + sv.returnType.getDescriptor()
   1.355 +                        );
   1.356 +                        super.visitInsn(sv.returnType.getOpcode(Opcodes.IRETURN));
   1.357 +                }
   1.358 +                return true;
   1.359 +            }
   1.360 +
   1.361 +            @Override
   1.362 +            public void visitEnd() {
   1.363 +                super.visitEnd();
   1.364 +                if (body != null) {
   1.365 +                    if (generateBody()) {
   1.366 +                        // native method
   1.367 +                        super.visitMaxs(1, 0);
   1.368 +                    }
   1.369 +                    FindInClass.this.visitField(
   1.370 +                            Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC,
   1.371 +                            "$$fn$$" + name + "_" + found,
   1.372 +                            "Lorg/apidesign/html/boot/spi/Fn;",
   1.373 +                            null, null
   1.374 +                    );
   1.375 +                }
   1.376 +            }
   1.377 +
   1.378 +            private final class FindInAnno extends AnnotationVisitor {
   1.379 +
   1.380 +                private List<String> args = new ArrayList<String>();
   1.381 +                private String body;
   1.382 +                private boolean javacall = false;
   1.383 +
   1.384 +                public FindInAnno() {
   1.385 +                    super(Opcodes.ASM4);
   1.386 +                }
   1.387 +
   1.388 +                @Override
   1.389 +                public void visit(String name, Object value) {
   1.390 +                    if (name == null) {
   1.391 +                        args.add((String) value);
   1.392 +                        return;
   1.393 +                    }
   1.394 +                    if (name.equals("javacall")) { // NOI18N
   1.395 +                        javacall = (Boolean) value;
   1.396 +                        return;
   1.397 +                    }
   1.398 +                    assert name.equals("body");
   1.399 +                    body = (String) value;
   1.400 +                }
   1.401 +
   1.402 +                @Override
   1.403 +                public AnnotationVisitor visitArray(String name) {
   1.404 +                    return this;
   1.405 +                }
   1.406 +
   1.407 +                @Override
   1.408 +                public void visitEnd() {
   1.409 +                    if (body != null) {
   1.410 +                        if (javacall) {
   1.411 +                            body = callback(body);
   1.412 +                            args.add("vm");
   1.413 +                        }
   1.414 +                        generateJSBody(args, body);
   1.415 +                    }
   1.416 +                }
   1.417 +            }
   1.418 +        }
   1.419 +
   1.420 +        private final class LoadResource extends AnnotationVisitor {
   1.421 +
   1.422 +            public LoadResource() {
   1.423 +                super(Opcodes.ASM4);
   1.424 +            }
   1.425 +
   1.426 +            @Override
   1.427 +            public void visit(String attrName, Object value) {
   1.428 +                String relPath = (String) value;
   1.429 +                if (relPath.startsWith("/")) {
   1.430 +                    loadScript(loader, relPath);
   1.431 +                } else {
   1.432 +                    int last = name.lastIndexOf('/');
   1.433 +                    String fullPath = name.substring(0, last + 1) + relPath;
   1.434 +                    loadScript(loader, fullPath);
   1.435 +                }
   1.436 +            }
   1.437 +        }
   1.438 +    }
   1.439 +
   1.440 +    private static class ClassWriterEx extends ClassWriter {
   1.441 +
   1.442 +        private ClassLoader loader;
   1.443 +
   1.444 +        public ClassWriterEx(ClassLoader l, ClassReader classReader, int flags) {
   1.445 +            super(classReader, flags);
   1.446 +            this.loader = l;
   1.447 +        }
   1.448 +
   1.449 +        @Override
   1.450 +        protected String getCommonSuperClass(final String type1, final String type2) {
   1.451 +            Class<?> c, d;
   1.452 +            try {
   1.453 +                c = Class.forName(type1.replace('/', '.'), false, loader);
   1.454 +                d = Class.forName(type2.replace('/', '.'), false, loader);
   1.455 +            } catch (Exception e) {
   1.456 +                throw new RuntimeException(e.toString());
   1.457 +            }
   1.458 +            if (c.isAssignableFrom(d)) {
   1.459 +                return type1;
   1.460 +            }
   1.461 +            if (d.isAssignableFrom(c)) {
   1.462 +                return type2;
   1.463 +            }
   1.464 +            if (c.isInterface() || d.isInterface()) {
   1.465 +                return "java/lang/Object";
   1.466 +            } else {
   1.467 +                do {
   1.468 +                    c = c.getSuperclass();
   1.469 +                } while (!c.isAssignableFrom(d));
   1.470 +                return c.getName().replace('.', '/');
   1.471 +            }
   1.472 +        }
   1.473 +    }
   1.474 +
   1.475 +    static byte[] transform(ClassLoader loader, byte[] arr) {
   1.476 +        ClassReader cr = new ClassReader(arr) {
   1.477 +            // to allow us to compile with -profile compact1 on 
   1.478 +            // JDK8 while processing the class as JDK7, the highest
   1.479 +            // class format asm 4.1 understands to
   1.480 +            @Override
   1.481 +            public short readShort(int index) {
   1.482 +                short s = super.readShort(index);
   1.483 +                if (index == 6 && s > Opcodes.V1_7) {
   1.484 +                    return Opcodes.V1_7;
   1.485 +                }
   1.486 +                return s;
   1.487 +            }
   1.488 +        };
   1.489 +        FindInClass tst = new FindInClass(loader, null);
   1.490 +        cr.accept(tst, 0);
   1.491 +        if (tst.found > 0) {
   1.492 +            ClassWriter w = new ClassWriterEx(loader, cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
   1.493 +            FindInClass fic = new FindInClass(loader, w);
   1.494 +            cr.accept(fic, 0);
   1.495 +            arr = w.toByteArray();
   1.496 +        }
   1.497 +        return arr;
   1.498 +    }
   1.499 +
   1.500 +    private static final class TrueFn extends Fn {
   1.501 +        @Override
   1.502 +        public Object invoke(Object thiz, Object... args) throws Exception {
   1.503 +            return Boolean.TRUE;
   1.504 +        }
   1.505 +    } // end of TrueFn
   1.506  }