rt/vm/src/main/java/org/apidesign/vm4brwsr/VM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 26 Apr 2014 19:13:56 +0200
branchclosure
changeset 1489 8d0fc428ff72
parent 1143 22beb858e00a
child 1491 4a1398eff4fb
permissions -rw-r--r--
Can execute VMTest in browser, if it is annotated with @Exported annotation like the BooleanTest
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 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.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.vm4brwsr;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import org.apidesign.vm4brwsr.ByteCodeParser.ClassData;
    23 import org.apidesign.vm4brwsr.ByteCodeParser.FieldData;
    24 import org.apidesign.vm4brwsr.ByteCodeParser.MethodData;
    25 
    26 /** Generator of JavaScript from bytecode of classes on classpath of the VM.
    27  *
    28  * @author Jaroslav Tulach <jtulach@netbeans.org>
    29  */
    30 abstract class VM extends ByteCodeToJavaScript {
    31     protected final ClassDataCache classDataCache;
    32 
    33     private final Bck2Brwsr.Resources resources;
    34     private final ExportedSymbols exportedSymbols;
    35     private final StringArray invokerMethods;
    36 
    37     private static final Class<?> FIXED_DEPENDENCIES[] = {
    38             Class.class,
    39             ArithmeticException.class,
    40             VM.class
    41         };
    42 
    43     private VM(Appendable out, Bck2Brwsr.Resources resources) {
    44         super(out);
    45         this.resources = resources;
    46         this.classDataCache = new ClassDataCache(resources);
    47         this.exportedSymbols = new ExportedSymbols(resources);
    48         this.invokerMethods = new StringArray();
    49     }
    50 
    51     static {
    52         // uses VMLazy to load dynamic classes
    53         boolean assertsOn = false;
    54         assert assertsOn = true;
    55         if (assertsOn) {
    56             VMLazy.init();
    57             Zips.init();
    58         }
    59     }
    60 
    61     @Override
    62     boolean debug(String msg) throws IOException {
    63         return false;
    64     }
    65     
    66     static void compile(Appendable out, Bck2Brwsr.Resources l, StringArray names, boolean extension) throws IOException {
    67         VM vm = extension ? new Extension(out, l, names.toArray())
    68                           : new Standalone(out, l);
    69 
    70         final StringArray fixedNames = new StringArray();
    71 
    72         for (final Class<?> fixedClass: FIXED_DEPENDENCIES) {
    73             fixedNames.add(fixedClass.getName().replace('.', '/'));
    74         }
    75 
    76         vm.doCompile(fixedNames.addAndNew(names.toArray()));
    77     }
    78 
    79     private void doCompile(StringArray names) throws IOException {
    80         generatePrologue();
    81         out.append(
    82                 "\n  var invoker = function Invoker() {"
    83                     + "\n    return Invoker.target[Invoker.method]"
    84                                       + ".apply(Invoker.target, arguments);"
    85                     + "\n  };");
    86         generateBody(names);
    87         for (String invokerMethod: invokerMethods.toArray()) {
    88             out.append("\n  invoker." + invokerMethod + " = function(target) {"
    89                            + "\n    invoker.target = target;"
    90                            + "\n    invoker.method = '" + invokerMethod + "';"
    91                            + "\n    return invoker;"
    92                            + "\n  };");
    93         }
    94         out.append("\n");
    95         generateEpilogue();
    96     }
    97 
    98     protected abstract void generatePrologue() throws IOException;
    99 
   100     protected abstract void generateEpilogue() throws IOException;
   101 
   102     protected abstract String getExportsObject();
   103 
   104     protected abstract boolean isExternalClass(String className);
   105 
   106     @Override
   107     protected final void declaredClass(ClassData classData, String mangledName)
   108             throws IOException {
   109         if (exportedSymbols.isExported(classData)) {
   110             out.append("\n").append(getExportsObject()).append("['")
   111                                                .append(mangledName)
   112                                                .append("'] = ")
   113                             .append(accessClass(mangledName))
   114                .append(";\n");
   115         }
   116     }
   117 
   118     protected String generateClass(String className) throws IOException {
   119         ClassData classData = classDataCache.getClassData(className);
   120         if (classData == null) {
   121             throw new IOException("Can't find class " + className);
   122         }
   123         return compile(classData);
   124     }
   125 
   126     @Override
   127     protected void declaredField(FieldData fieldData,
   128                                  String destObject,
   129                                  String mangledName) throws IOException {
   130         if (exportedSymbols.isExported(fieldData)) {
   131             exportMember(destObject, mangledName);
   132         }
   133     }
   134 
   135     @Override
   136     protected void declaredMethod(MethodData methodData,
   137                                   String destObject,
   138                                   String mangledName) throws IOException {
   139         if (isHierarchyExported(methodData)) {
   140             exportMember(destObject, mangledName);
   141         }
   142     }
   143 
   144     private void exportMember(String destObject, String memberName)
   145             throws IOException {
   146         out.append("\n").append(destObject).append("['")
   147                                            .append(memberName)
   148                                            .append("'] = ")
   149                         .append(destObject).append(".").append(memberName)
   150            .append(";\n");
   151     }
   152 
   153     private void generateBody(StringArray names) throws IOException {
   154         StringArray processed = new StringArray();
   155         StringArray initCode = new StringArray();
   156         for (String baseClass : names.toArray()) {
   157             references.add(baseClass);
   158             for (;;) {
   159                 String name = null;
   160                 for (String n : references.toArray()) {
   161                     if (processed.contains(n)) {
   162                         continue;
   163                     }
   164                     name = n;
   165                 }
   166                 if (name == null) {
   167                     break;
   168                 }
   169 
   170                 try {
   171                     String ic = generateClass(name);
   172                     processed.add(name);
   173                     initCode.add(ic == null ? "" : ic);
   174                 } catch (RuntimeException ex) {
   175                     if (out instanceof CharSequence) {
   176                         CharSequence seq = (CharSequence)out;
   177                         int lastBlock = seq.length();
   178                         while (lastBlock-- > 0) {
   179                             if (seq.charAt(lastBlock) == '{') {
   180                                 break;
   181                             }
   182                         }
   183                         throw new IOException("Error while compiling " + name + "\n"
   184                             + seq.subSequence(lastBlock + 1, seq.length()), ex
   185                         );
   186                     } else {
   187                         throw new IOException("Error while compiling " + name + "\n"
   188                             + out, ex
   189                         );
   190                     }
   191                 }
   192             }
   193 
   194             for (String resource : scripts.toArray()) {
   195                 while (resource.startsWith("/")) {
   196                     resource = resource.substring(1);
   197                 }
   198                 InputStream emul = resources.get(resource);
   199                 if (emul == null) {
   200                     throw new IOException("Can't find " + resource);
   201                 }
   202                 readResource(emul, out);
   203             }
   204             scripts = new StringArray();
   205 
   206             StringArray toInit = StringArray.asList(references.toArray());
   207             toInit.reverse();
   208 
   209             for (String ic : toInit.toArray()) {
   210                 int indx = processed.indexOf(ic);
   211                 if (indx >= 0) {
   212                     final String theCode = initCode.toArray()[indx];
   213                     if (!theCode.isEmpty()) {
   214                         out.append(theCode).append("\n");
   215                     }
   216                     initCode.toArray()[indx] = "";
   217                 }
   218             }
   219         }
   220     }
   221 
   222     private static void readResource(InputStream emul, Appendable out) throws IOException {
   223         try {
   224             int state = 0;
   225             for (;;) {
   226                 int ch = emul.read();
   227                 if (ch == -1) {
   228                     break;
   229                 }
   230                 if (ch < 0 || ch > 255) {
   231                     throw new IOException("Invalid char in emulation " + ch);
   232                 }
   233                 switch (state) {
   234                     case 0: 
   235                         if (ch == '/') {
   236                             state = 1;
   237                         } else {
   238                             out.append((char)ch);
   239                         }
   240                         break;
   241                     case 1:
   242                         if (ch == '*') {
   243                             state = 2;
   244                         } else {
   245                             out.append('/').append((char)ch);
   246                             state = 0;
   247                         }
   248                         break;
   249                     case 2:
   250                         if (ch == '*') {
   251                             state = 3;
   252                         }
   253                         break;
   254                     case 3:
   255                         if (ch == '/') {
   256                             state = 0;
   257                         } else {
   258                             state = 2;
   259                         }
   260                         break;
   261                 }
   262             }
   263         } finally {
   264             emul.close();
   265         }
   266     }
   267 
   268     static String toString(String name) throws IOException {
   269         StringBuilder sb = new StringBuilder();
   270 //        compile(sb, name);
   271         return sb.toString().toString();
   272     }
   273 
   274     private StringArray scripts = new StringArray();
   275     private StringArray references = new StringArray();
   276     
   277     @Override
   278     protected boolean requireReference(String cn) {
   279         if (references.contains(cn)) {
   280             return false;
   281         }
   282         references.add(cn);
   283         return true;
   284     }
   285 
   286     @Override
   287     protected void requireScript(String resourcePath) {
   288         scripts.add(resourcePath);
   289     }
   290 
   291     @Override
   292     String assignClass(String className) {
   293         return "vm." + className + " = ";
   294     }
   295     
   296     @Override
   297     String accessClass(String className) {
   298         return "vm." + className;
   299     }
   300 
   301     @Override
   302     protected String accessField(String object, String mangledName,
   303                                  String[] fieldInfoName) throws IOException {
   304         final FieldData field =
   305                 classDataCache.findField(fieldInfoName[0],
   306                                          fieldInfoName[1],
   307                                          fieldInfoName[2]);
   308         return accessNonVirtualMember(object, mangledName,
   309                                       (field != null) ? field.cls : null);
   310     }
   311 
   312     @Override
   313     protected String accessStaticMethod(
   314                              String object,
   315                              String mangledName,
   316                              String[] fieldInfoName) throws IOException {
   317         final MethodData method =
   318                 classDataCache.findMethod(fieldInfoName[0],
   319                                           fieldInfoName[1],
   320                                           fieldInfoName[2]);
   321         return accessNonVirtualMember(object, mangledName,
   322                                       (method != null) ? method.cls : null);
   323     }
   324 
   325     @Override
   326     protected String accessVirtualMethod(
   327                              String object,
   328                              String mangledName,
   329                              String[] fieldInfoName) throws IOException {
   330         final ClassData referencedClass =
   331                 classDataCache.getClassData(fieldInfoName[0]);
   332         final MethodData method =
   333                 classDataCache.findMethod(referencedClass,
   334                                           fieldInfoName[1],
   335                                           fieldInfoName[2]);
   336 
   337         if ((method != null)
   338                 && !isExternalClass(method.cls.getClassName())
   339                 && (((method.access & ByteCodeParser.ACC_FINAL) != 0)
   340                         || ((referencedClass.getAccessFlags()
   341                                  & ByteCodeParser.ACC_FINAL) != 0)
   342                         || !isHierarchyExported(method))) {
   343             return object + "." + mangledName;
   344         }
   345 
   346         return accessThroughInvoker(object, mangledName);
   347     }
   348 
   349     private String accessThroughInvoker(String object, String mangledName) {
   350         if (!invokerMethods.contains(mangledName)) {
   351             invokerMethods.add(mangledName);
   352         }
   353         return "invoker." + mangledName + '(' + object + ')';
   354     }
   355 
   356     private boolean isHierarchyExported(final MethodData methodData)
   357             throws IOException {
   358         if (exportedSymbols.isExported(methodData)) {
   359             return true;
   360         }
   361         if ((methodData.access & (ByteCodeParser.ACC_PRIVATE
   362                                       | ByteCodeParser.ACC_STATIC)) != 0) {
   363             return false;
   364         }
   365 
   366         final ExportedMethodFinder exportedMethodFinder =
   367                 new ExportedMethodFinder(exportedSymbols);
   368 
   369         classDataCache.findMethods(
   370                 methodData.cls,
   371                 methodData.getName(),
   372                 methodData.getInternalSig(),
   373                 exportedMethodFinder);
   374 
   375         return (exportedMethodFinder.getFound() != null);
   376     }
   377 
   378     private String accessNonVirtualMember(String object,
   379                                           String mangledName,
   380                                           ClassData declaringClass) {
   381         return ((declaringClass != null)
   382                     && !isExternalClass(declaringClass.getClassName()))
   383                             ? object + "." + mangledName
   384                             : object + "['" + mangledName + "']";
   385     }
   386 
   387     private static final class ExportedMethodFinder
   388             implements ClassDataCache.TraversalCallback<MethodData> {
   389         private final ExportedSymbols exportedSymbols;
   390         private MethodData found;
   391 
   392         public ExportedMethodFinder(final ExportedSymbols exportedSymbols) {
   393             this.exportedSymbols = exportedSymbols;
   394         }
   395 
   396         @Override
   397         public boolean traverse(final MethodData methodData) {
   398             try {
   399                 if (exportedSymbols.isExported(methodData)) {
   400                     found = methodData;
   401                     return false;
   402                 }
   403             } catch (final IOException e) {
   404             }
   405 
   406             return true;
   407         }
   408 
   409         public MethodData getFound() {
   410             return found;
   411         }
   412     }
   413 
   414     private static final class Standalone extends VM {
   415         private Standalone(Appendable out, Bck2Brwsr.Resources resources) {
   416             super(out, resources);
   417         }
   418 
   419         @Override
   420         protected void generatePrologue() throws IOException {
   421             out.append("(function VM(global) {var fillInVMSkeleton = function(vm) {");
   422         }
   423 
   424         @Override
   425         protected void generateEpilogue() throws IOException {
   426             out.append(
   427                   "  return vm;\n"
   428                 + "  };\n"
   429                 + "  var extensions = [];\n"
   430                 + "  global.bck2brwsr = function() {\n"
   431                 + "    var args = Array.prototype.slice.apply(arguments);\n"
   432                 + "    var vm = fillInVMSkeleton({});\n"
   433                 + "    for (var i = 0; i < extensions.length; ++i) {\n"
   434                 + "      extensions[i](vm);\n"
   435                 + "    }\n"
   436                 + "    var knownExtensions = extensions.length;\n"
   437                 + "    var loader = {};\n"
   438                 + "    loader.vm = vm;\n"
   439                 + "    loader.loadClass = function(name) {\n"
   440                 + "      var attr = name.replace__Ljava_lang_String_2CC('.','_');\n"
   441                 + "      var fn = vm[attr];\n"
   442                 + "      if (fn) return fn(false);\n"
   443                 + "      try {\n"
   444                 + "        return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   445                 + "          load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   446                 + "      } catch (err) {\n"
   447                 + "        while (knownExtensions < extensions.length) {\n"
   448                 + "          extensions[knownExtensions++](vm);\n"
   449                 + "        }\n"
   450                 + "        fn = vm[attr];\n"
   451                 + "        if (fn) return fn(false);\n"
   452                 + "        throw err;\n"
   453                 + "      }\n"
   454                 + "    }\n"
   455                 + "    if (vm.loadClass) {\n"
   456                 + "      throw 'Cannot initialize the bck2brwsr VM twice!';\n"
   457                 + "    }\n"
   458                 + "    vm.loadClass = loader.loadClass;\n"
   459                 + "    vm.loadBytes = function(name) {\n"
   460                 + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   461                 + "        loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   462                 + "    }\n"
   463                 + "    vm.java_lang_reflect_Array(false);\n"
   464                 + "    vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   465                 + "      loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, null, args);\n"
   466                 + "    return loader;\n"
   467                 + "  };\n");
   468             out.append(
   469                   "  global.bck2brwsr.registerExtension = function(extension) {\n"
   470                 + "    extensions.push(extension);\n"
   471                 + "    return null;\n"
   472                 + "  };\n");
   473             out.append("}(this));");
   474         }
   475 
   476         @Override
   477         protected String getExportsObject() {
   478             return "vm";
   479         }
   480 
   481         @Override
   482         protected boolean isExternalClass(String className) {
   483             return false;
   484         }
   485     }
   486 
   487     private static final class Extension extends VM {
   488         private final StringArray extensionClasses;
   489 
   490         private Extension(Appendable out, Bck2Brwsr.Resources resources,
   491                           String[] extClassesArray) {
   492             super(out, resources);
   493             this.extensionClasses = StringArray.asList(extClassesArray);
   494         }
   495 
   496         @Override
   497         protected void generatePrologue() throws IOException {
   498             out.append("bck2brwsr.registerExtension(function(exports) {\n"
   499                            + "  var vm = {};\n");
   500             out.append("  function link(n, inst) {\n"
   501                            + "    var cls = n['replace__Ljava_lang_String_2CC']"
   502                                                   + "('/', '_').toString();\n"
   503                            + "    var dot = n['replace__Ljava_lang_String_2CC']"
   504                                                   + "('/', '.').toString();\n"
   505                            + "    exports.loadClass(dot);\n"
   506                            + "    vm[cls] = exports[cls];\n"
   507                            + "    return vm[cls](inst);\n"
   508                            + "  };\n");
   509         }
   510 
   511         @Override
   512         protected void generateEpilogue() throws IOException {
   513             out.append("});");
   514         }
   515 
   516         @Override
   517         protected String generateClass(String className) throws IOException {
   518             if (isExternalClass(className)) {
   519                 out.append("\n").append(assignClass(
   520                                             className.replace('/', '_')))
   521                    .append("function() {\n  return link('")
   522                    .append(className)
   523                    .append("', arguments.length == 0 || arguments[0] === true);"
   524                                + "\n};");
   525 
   526                 return null;
   527             }
   528 
   529             return super.generateClass(className);
   530         }
   531 
   532         @Override
   533         protected String getExportsObject() {
   534             return "exports";
   535         }
   536 
   537         @Override
   538         protected boolean isExternalClass(String className) {
   539             return !extensionClasses.contains(className);
   540         }
   541     }
   542 }