boot/src/main/java/org/apidesign/html/boot/impl/JsClassLoader.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 19 Jun 2013 12:55:41 +0200
branchclassloader
changeset 124 94dfab239310
parent 123 8e54b83ea65c
child 132 0712b460733d
permissions -rw-r--r--
No need to have static define method in the Fn interface
     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 ("Lnet/java/html/js/JavaScriptBody;".equals(desc)) { // NOI18N
   168                     found++;
   169                     return new FindInAnno();
   170                 }
   171                 return super.visitAnnotation(desc, visible);
   172             }
   173 
   174             private void generateJSBody(List<String> args, String body) {
   175                 this.args = args;
   176                 this.body = body;
   177             }
   178             
   179             @Override
   180             public void visitCode() {
   181                 if (body == null) {
   182                     return;
   183                 } 
   184                 generateBody();
   185             }
   186             
   187             private boolean generateBody() {
   188                 if (bodyGenerated) {
   189                     return false;
   190                 }
   191                 bodyGenerated = true;
   192                 
   193                 super.visitFieldInsn(
   194                     Opcodes.GETSTATIC, FindInClass.this.name, 
   195                     "$$fn$$" + name + "_" + found, 
   196                     "Lorg/apidesign/html/boot/spi/Fn;"
   197                 );
   198                 super.visitInsn(Opcodes.DUP);
   199                 Label ifNotNull = new Label();
   200                 super.visitJumpInsn(Opcodes.IFNONNULL, ifNotNull);
   201                 
   202                 // init Fn
   203                 super.visitInsn(Opcodes.POP);
   204                 super.visitLdcInsn(Type.getObjectType(FindInClass.this.name));
   205                 super.visitLdcInsn(body);
   206                 super.visitIntInsn(Opcodes.SIPUSH, args.size());
   207                 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
   208                 for (int i = 0; i < args.size(); i++) {
   209                     String name = args.get(i);
   210                     super.visitInsn(Opcodes.DUP);
   211                     super.visitIntInsn(Opcodes.BIPUSH, i);
   212                     super.visitLdcInsn(name);
   213                     super.visitInsn(Opcodes.AASTORE);
   214                 }
   215                 super.visitMethodInsn(Opcodes.INVOKESTATIC, 
   216                     "org/apidesign/html/boot/impl/FnUtils", "define", 
   217                     "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/String;)Lorg/apidesign/html/boot/spi/Fn;"
   218                 );
   219                 // end of Fn init
   220                 
   221                 super.visitLabel(ifNotNull);
   222                 
   223                 final int offset;
   224                 if ((access & Opcodes.ACC_STATIC) == 0) {
   225                     offset = 1;
   226                     super.visitIntInsn(Opcodes.ALOAD, 0);
   227                 } else {
   228                     offset = 0;
   229                     super.visitInsn(Opcodes.ACONST_NULL);
   230                 }
   231                 
   232                 super.visitIntInsn(Opcodes.SIPUSH, args.size());
   233                 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
   234                 
   235                 class SV extends SignatureVisitor {
   236                     private boolean nowReturn;
   237                     private Type returnType;
   238                     private int index;
   239                     
   240                     public SV() {
   241                         super(Opcodes.ASM4);
   242                     }
   243                     
   244                     @Override
   245                     public void visitBaseType(char descriptor) {
   246                         final Type t = Type.getType("" + descriptor);
   247                         if (nowReturn) {
   248                             returnType = t;
   249                             return;
   250                         }
   251                         FindInMethod.super.visitInsn(Opcodes.DUP);
   252                         FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index);
   253                         FindInMethod.super.visitVarInsn(t.getOpcode(Opcodes.ILOAD), index + offset);
   254                         String factory;
   255                         switch (descriptor) {
   256                         case 'I': factory = "java/lang/Integer"; break;
   257                         case 'J': factory = "java/lang/Long"; break;
   258                         case 'S': factory = "java/lang/Short"; break;
   259                         case 'F': factory = "java/lang/Float"; break;
   260                         case 'D': factory = "java/lang/Double"; break;
   261                         case 'Z': factory = "java/lang/Boolean"; break;
   262                         case 'C': factory = "java/lang/Character"; break;
   263                         case 'B': factory = "java/lang/Byte"; break;
   264                         default: throw new IllegalStateException(t.toString());
   265                         }
   266                         FindInMethod.super.visitMethodInsn(Opcodes.INVOKESTATIC,
   267                             factory, "valueOf", "(" + descriptor + ")L" + factory + ";"
   268                         );
   269                         FindInMethod.super.visitInsn(Opcodes.AASTORE);
   270                         index++;
   271                     }
   272 
   273                     @Override
   274                     public void visitClassType(String name) {
   275                         if (nowReturn) {
   276                             returnType = Type.getObjectType(name);
   277                             return;
   278                         }
   279                         FindInMethod.super.visitInsn(Opcodes.DUP);
   280                         FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index);
   281                         FindInMethod.super.visitVarInsn(Opcodes.ALOAD, index + offset);
   282                         FindInMethod.super.visitInsn(Opcodes.AASTORE);
   283                         index++;
   284                     }
   285 
   286                     @Override
   287                     public SignatureVisitor visitReturnType() {
   288                         nowReturn = true;
   289                         return this;
   290                     }
   291                     
   292                     
   293                 }
   294                 SV sv = new SV();
   295                 SignatureReader sr = new SignatureReader(desc);
   296                 sr.accept(sv);
   297                 
   298                 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, 
   299                     "org/apidesign/html/boot/spi/Fn", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"
   300                 );
   301                 switch (sv.returnType.getSort()) {
   302                 case Type.VOID: 
   303                     super.visitInsn(Opcodes.RETURN);
   304                     break;
   305                 case Type.ARRAY:
   306                 case Type.OBJECT:
   307                     super.visitTypeInsn(Opcodes.CHECKCAST, sv.returnType.getInternalName());
   308                     super.visitInsn(Opcodes.ARETURN);
   309                     break;
   310                 default:
   311                     super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Number");
   312                     super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, 
   313                         "java/lang/Number", sv.returnType.getClassName() + "Value", "()" + sv.returnType.getDescriptor()
   314                     );
   315                     super.visitInsn(sv.returnType.getOpcode(Opcodes.IRETURN));
   316                 }
   317                 return true;
   318             }
   319 
   320             @Override
   321             public void visitEnd() {
   322                 super.visitEnd();
   323                 if (body != null) {
   324                     if (generateBody()) {
   325                         // native method
   326                         super.visitMaxs(1, 0);
   327                     }
   328                     FindInClass.this.visitField(
   329                         Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC, 
   330                         "$$fn$$" + name + "_" + found, 
   331                         "Lorg/apidesign/html/boot/spi/Fn;", 
   332                         null, null
   333                     );
   334                 }
   335             }
   336             
   337             
   338             
   339             
   340         
   341             private final class FindInAnno extends AnnotationVisitor {
   342                 private List<String> args = new ArrayList<String>();
   343                 private String body;
   344 
   345                 public FindInAnno() {
   346                     super(Opcodes.ASM4);
   347                 }
   348 
   349                 @Override
   350                 public void visit(String name, Object value) {
   351                     if (name == null) {
   352                         args.add((String) value);
   353                         return;
   354                     }
   355                     assert name.equals("body");
   356                     body = (String) value;
   357                 }
   358 
   359                 @Override
   360                 public AnnotationVisitor visitArray(String name) {
   361                     return this;
   362                 }
   363 
   364                 @Override
   365                 public void visitEnd() {
   366                     if (body != null) {
   367                         generateJSBody(args, body);
   368                     }
   369                 }
   370             }
   371         }
   372     }
   373     
   374     private class ClassWriterEx extends ClassWriter {
   375 
   376         public ClassWriterEx(ClassReader classReader, int flags) {
   377             super(classReader, flags);
   378         }
   379         
   380         @Override
   381         protected String getCommonSuperClass(final String type1, final String type2) {
   382             Class<?> c, d;
   383             ClassLoader classLoader = JsClassLoader.this;
   384             try {
   385                 c = Class.forName(type1.replace('/', '.'), false, classLoader);
   386                 d = Class.forName(type2.replace('/', '.'), false, classLoader);
   387             } catch (Exception e) {
   388                 throw new RuntimeException(e.toString());
   389             }
   390             if (c.isAssignableFrom(d)) {
   391                 return type1;
   392             }
   393             if (d.isAssignableFrom(c)) {
   394                 return type2;
   395             }
   396             if (c.isInterface() || d.isInterface()) {
   397                 return "java/lang/Object";
   398             } else {
   399                 do {
   400                     c = c.getSuperclass();
   401                 } while (!c.isAssignableFrom(d));
   402                 return c.getName().replace('.', '/');
   403             }
   404         }        
   405     }
   406 }