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