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