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