boot/src/main/java/org/apidesign/html/boot/impl/JsClassLoader.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 20 Jun 2013 10:26:05 +0200
branchclassloader
changeset 132 0712b460733d
parent 124 94dfab239310
child 143 b3b56bed079e
permissions -rw-r--r--
Making sure ko-fx existing tests pass
     1 /**
     2  * HTML via Java(tm) Language Bindings
     3  * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     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.
     8  *
     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.
    16  *
    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
    20  */
    21 package org.apidesign.html.boot.impl;
    22 
    23 import org.apidesign.html.boot.spi.Fn;
    24 import java.io.IOException;
    25 import java.io.InputStream;
    26 import java.net.URL;
    27 import java.util.ArrayList;
    28 import java.util.Enumeration;
    29 import java.util.List;
    30 import org.objectweb.asm.AnnotationVisitor;
    31 import org.objectweb.asm.ClassReader;
    32 import org.objectweb.asm.ClassVisitor;
    33 import org.objectweb.asm.ClassWriter;
    34 import org.objectweb.asm.Label;
    35 import org.objectweb.asm.MethodVisitor;
    36 import org.objectweb.asm.Opcodes;
    37 import org.objectweb.asm.Type;
    38 import org.objectweb.asm.signature.SignatureReader;
    39 import org.objectweb.asm.signature.SignatureVisitor;
    40 
    41 /** 
    42  *
    43  * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
    44  */
    45 abstract class JsClassLoader extends ClassLoader {
    46     JsClassLoader(ClassLoader parent) {
    47         super(parent);
    48     }
    49     
    50     @Override
    51     protected abstract URL findResource(String name);
    52     
    53     @Override
    54     protected abstract Enumeration<URL> findResources(String name);
    55 
    56     @Override
    57     protected Class<?> findClass(String name) throws ClassNotFoundException {
    58         if (name.startsWith("javafx")) {
    59             return Class.forName(name);
    60         }
    61         if (name.startsWith("netscape")) {
    62             return Class.forName(name);
    63         }
    64         if (name.startsWith("com.sun")) {
    65             return Class.forName(name);
    66         }
    67         if (name.equals(JsClassLoader.class.getName())) {
    68             return JsClassLoader.class;
    69         }
    70         if (name.equals(Fn.class.getName())) {
    71             return Fn.class;
    72         }
    73         if (name.equals(FnUtils.class.getName())) {
    74             return FnUtils.class;
    75         }
    76         URL u = findResource(name.replace('.', '/') + ".class");
    77         if (u != null) {
    78             InputStream is = null;
    79             try {
    80                 is = u.openStream();
    81                 byte[] arr = new byte[is.available()];
    82                 int len = 0;
    83                 while (len < arr.length) {
    84                     int read = is.read(arr, len, arr.length - len);
    85                     if (read == -1) {
    86                         throw new IOException("Can't read " + u);
    87                     }
    88                     len += read;
    89                 }
    90                 is.close();
    91                 is = null;
    92                 ClassReader cr = new ClassReader(arr);
    93                 FindInClass tst = new FindInClass(null);
    94                 cr.accept(tst, 0);
    95                 if (tst.found > 0) {
    96                     ClassWriter w = new ClassWriterEx(cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    97                     FindInClass fic = new FindInClass(w);
    98                     cr.accept(fic, 0);
    99                     arr = w.toByteArray();
   100                 }
   101                 if (arr != null) {
   102                     return defineClass(name, arr, 0, arr.length);
   103                 }
   104             } catch (IOException ex) {
   105                 throw new ClassNotFoundException("Can't load " + name, ex);
   106             } finally {
   107                 try {
   108                     if (is != null) is.close();
   109                 } catch (IOException ex) {
   110                     throw new ClassNotFoundException(null, ex);
   111                 }
   112             }
   113         }
   114         if (
   115             name.equals("org.apidesign.html.boot.spi.Fn") ||
   116             name.equals("org.apidesign.html.boot.impl.FnUtils")
   117         ) {
   118             return Class.forName(name);
   119         }
   120         
   121         return super.findClass(name);
   122     }
   123     
   124     protected abstract Fn defineFn(String code, String... names);
   125     
   126     
   127     private static final class FindInClass extends ClassVisitor {
   128         private String name;
   129         private int found;
   130         
   131         public FindInClass(ClassVisitor cv) {
   132             super(Opcodes.ASM4, cv);
   133         }
   134 
   135         @Override
   136         public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
   137             this.name = name;
   138             super.visit(version, access, name, signature, superName, interfaces);
   139         }
   140         
   141         
   142 
   143         @Override
   144         public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
   145             return new FindInMethod(access, name, desc,
   146                 super.visitMethod(access & (~Opcodes.ACC_NATIVE), name, desc, signature, exceptions)
   147             );
   148         }
   149         
   150         private final class FindInMethod extends MethodVisitor {
   151             private final String name;
   152             private final String desc;
   153             private final int access;
   154             private List<String> args;
   155             private String body;
   156             private boolean bodyGenerated;
   157             
   158             public FindInMethod(int access, String name, String desc, MethodVisitor mv) {
   159                 super(Opcodes.ASM4, mv);
   160                 this.access = access;
   161                 this.name = name;
   162                 this.desc = desc;
   163             }
   164 
   165             @Override
   166             public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
   167                 if (
   168                     "Lnet/java/html/js/JavaScriptBody;".equals(desc) // NOI18N
   169                     || "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;".equals(desc) // NOI18N
   170                 ) {
   171                     found++;
   172                     return new FindInAnno();
   173                 }
   174                 return super.visitAnnotation(desc, visible);
   175             }
   176 
   177             private void generateJSBody(List<String> args, String body) {
   178                 this.args = args;
   179                 this.body = body;
   180             }
   181             
   182             @Override
   183             public void visitCode() {
   184                 if (body == null) {
   185                     return;
   186                 } 
   187                 generateBody();
   188             }
   189             
   190             private boolean generateBody() {
   191                 if (bodyGenerated) {
   192                     return false;
   193                 }
   194                 bodyGenerated = true;
   195                 
   196                 super.visitFieldInsn(
   197                     Opcodes.GETSTATIC, FindInClass.this.name, 
   198                     "$$fn$$" + name + "_" + found, 
   199                     "Lorg/apidesign/html/boot/spi/Fn;"
   200                 );
   201                 super.visitInsn(Opcodes.DUP);
   202                 Label ifNotNull = new Label();
   203                 super.visitJumpInsn(Opcodes.IFNONNULL, ifNotNull);
   204                 
   205                 // init Fn
   206                 super.visitInsn(Opcodes.POP);
   207                 super.visitLdcInsn(Type.getObjectType(FindInClass.this.name));
   208                 super.visitLdcInsn(body);
   209                 super.visitIntInsn(Opcodes.SIPUSH, args.size());
   210                 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
   211                 for (int i = 0; i < args.size(); i++) {
   212                     String name = args.get(i);
   213                     super.visitInsn(Opcodes.DUP);
   214                     super.visitIntInsn(Opcodes.BIPUSH, i);
   215                     super.visitLdcInsn(name);
   216                     super.visitInsn(Opcodes.AASTORE);
   217                 }
   218                 super.visitMethodInsn(Opcodes.INVOKESTATIC, 
   219                     "org/apidesign/html/boot/impl/FnUtils", "define", 
   220                     "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/String;)Lorg/apidesign/html/boot/spi/Fn;"
   221                 );
   222                 // end of Fn init
   223                 
   224                 super.visitLabel(ifNotNull);
   225                 
   226                 final int offset;
   227                 if ((access & Opcodes.ACC_STATIC) == 0) {
   228                     offset = 1;
   229                     super.visitIntInsn(Opcodes.ALOAD, 0);
   230                 } else {
   231                     offset = 0;
   232                     super.visitInsn(Opcodes.ACONST_NULL);
   233                 }
   234                 
   235                 super.visitIntInsn(Opcodes.SIPUSH, args.size());
   236                 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
   237                 
   238                 class SV extends SignatureVisitor {
   239                     private boolean nowReturn;
   240                     private Type returnType;
   241                     private int index;
   242                     
   243                     public SV() {
   244                         super(Opcodes.ASM4);
   245                     }
   246                     
   247                     @Override
   248                     public void visitBaseType(char descriptor) {
   249                         final Type t = Type.getType("" + descriptor);
   250                         if (nowReturn) {
   251                             returnType = t;
   252                             return;
   253                         }
   254                         FindInMethod.super.visitInsn(Opcodes.DUP);
   255                         FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index);
   256                         FindInMethod.super.visitVarInsn(t.getOpcode(Opcodes.ILOAD), index + offset);
   257                         String factory;
   258                         switch (descriptor) {
   259                         case 'I': factory = "java/lang/Integer"; break;
   260                         case 'J': factory = "java/lang/Long"; break;
   261                         case 'S': factory = "java/lang/Short"; break;
   262                         case 'F': factory = "java/lang/Float"; break;
   263                         case 'D': factory = "java/lang/Double"; break;
   264                         case 'Z': factory = "java/lang/Boolean"; break;
   265                         case 'C': factory = "java/lang/Character"; break;
   266                         case 'B': factory = "java/lang/Byte"; break;
   267                         default: throw new IllegalStateException(t.toString());
   268                         }
   269                         FindInMethod.super.visitMethodInsn(Opcodes.INVOKESTATIC,
   270                             factory, "valueOf", "(" + descriptor + ")L" + factory + ";"
   271                         );
   272                         FindInMethod.super.visitInsn(Opcodes.AASTORE);
   273                         index++;
   274                     }
   275 
   276                     @Override
   277                     public void visitClassType(String name) {
   278                         if (nowReturn) {
   279                             returnType = Type.getObjectType(name);
   280                             return;
   281                         }
   282                         FindInMethod.super.visitInsn(Opcodes.DUP);
   283                         FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index);
   284                         FindInMethod.super.visitVarInsn(Opcodes.ALOAD, index + offset);
   285                         FindInMethod.super.visitInsn(Opcodes.AASTORE);
   286                         index++;
   287                     }
   288 
   289                     @Override
   290                     public SignatureVisitor visitReturnType() {
   291                         nowReturn = true;
   292                         return this;
   293                     }
   294                     
   295                     
   296                 }
   297                 SV sv = new SV();
   298                 SignatureReader sr = new SignatureReader(desc);
   299                 sr.accept(sv);
   300                 
   301                 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, 
   302                     "org/apidesign/html/boot/spi/Fn", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"
   303                 );
   304                 switch (sv.returnType.getSort()) {
   305                 case Type.VOID: 
   306                     super.visitInsn(Opcodes.RETURN);
   307                     break;
   308                 case Type.ARRAY:
   309                 case Type.OBJECT:
   310                     super.visitTypeInsn(Opcodes.CHECKCAST, sv.returnType.getInternalName());
   311                     super.visitInsn(Opcodes.ARETURN);
   312                     break;
   313                 default:
   314                     super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Number");
   315                     super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, 
   316                         "java/lang/Number", sv.returnType.getClassName() + "Value", "()" + sv.returnType.getDescriptor()
   317                     );
   318                     super.visitInsn(sv.returnType.getOpcode(Opcodes.IRETURN));
   319                 }
   320                 return true;
   321             }
   322 
   323             @Override
   324             public void visitEnd() {
   325                 super.visitEnd();
   326                 if (body != null) {
   327                     if (generateBody()) {
   328                         // native method
   329                         super.visitMaxs(1, 0);
   330                     }
   331                     FindInClass.this.visitField(
   332                         Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC, 
   333                         "$$fn$$" + name + "_" + found, 
   334                         "Lorg/apidesign/html/boot/spi/Fn;", 
   335                         null, null
   336                     );
   337                 }
   338             }
   339             
   340             
   341             
   342             
   343         
   344             private final class FindInAnno extends AnnotationVisitor {
   345                 private List<String> args = new ArrayList<String>();
   346                 private String body;
   347 
   348                 public FindInAnno() {
   349                     super(Opcodes.ASM4);
   350                 }
   351 
   352                 @Override
   353                 public void visit(String name, Object value) {
   354                     if (name == null) {
   355                         args.add((String) value);
   356                         return;
   357                     }
   358                     assert name.equals("body");
   359                     body = (String) value;
   360                 }
   361 
   362                 @Override
   363                 public AnnotationVisitor visitArray(String name) {
   364                     return this;
   365                 }
   366 
   367                 @Override
   368                 public void visitEnd() {
   369                     if (body != null) {
   370                         generateJSBody(args, body);
   371                     }
   372                 }
   373             }
   374         }
   375     }
   376     
   377     private class ClassWriterEx extends ClassWriter {
   378 
   379         public ClassWriterEx(ClassReader classReader, int flags) {
   380             super(classReader, flags);
   381         }
   382         
   383         @Override
   384         protected String getCommonSuperClass(final String type1, final String type2) {
   385             Class<?> c, d;
   386             ClassLoader classLoader = JsClassLoader.this;
   387             try {
   388                 c = Class.forName(type1.replace('/', '.'), false, classLoader);
   389                 d = Class.forName(type2.replace('/', '.'), false, classLoader);
   390             } catch (Exception e) {
   391                 throw new RuntimeException(e.toString());
   392             }
   393             if (c.isAssignableFrom(d)) {
   394                 return type1;
   395             }
   396             if (d.isAssignableFrom(c)) {
   397                 return type2;
   398             }
   399             if (c.isInterface() || d.isInterface()) {
   400                 return "java/lang/Object";
   401             } else {
   402                 do {
   403                     c = c.getSuperclass();
   404                 } while (!c.isAssignableFrom(d));
   405                 return c.getName().replace('.', '/');
   406             }
   407         }        
   408     }
   409 }