rt/vm/src/main/java/org/apidesign/vm4brwsr/VM.java
author Lubomir Nerad <lubomir.nerad@oracle.com>
Tue, 07 May 2013 19:01:14 +0200
branchclosure
changeset 1085 6a4ef883e233
parent 1084 f5c9934a252c
child 1086 2ac4283ee209
permissions -rw-r--r--
Access non-final exported methods through "invoker"
     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 VM(Appendable out, Bck2Brwsr.Resources resources) {
    38         super(out);
    39         this.resources = resources;
    40         this.classDataCache = new ClassDataCache(resources);
    41         this.exportedSymbols = new ExportedSymbols(resources);
    42         this.invokerMethods = new StringArray();
    43     }
    44 
    45     static {
    46         // uses VMLazy to load dynamic classes
    47         boolean assertsOn = false;
    48         assert assertsOn = true;
    49         if (assertsOn) {
    50             VMLazy.init();
    51             Zips.init();
    52         }
    53     }
    54 
    55     @Override
    56     boolean debug(String msg) throws IOException {
    57         return false;
    58     }
    59     
    60     static void compileStandalone(Bck2Brwsr.Resources l, Appendable out, StringArray names) throws IOException {
    61         VM vm = new Standalone(out, l);
    62         vm.doCompile(names);
    63     }
    64 
    65     static void compileExtension(Bck2Brwsr.Resources l, Appendable out, StringArray names) throws IOException {
    66         VM vm = new Extension(out, l);
    67         vm.doCompile(names);
    68     }
    69 
    70     private void doCompile(StringArray names) throws IOException {
    71         generatePrologue();
    72         out.append(
    73                 "\n  var invoker = function Invoker() {"
    74                     + "\n    return Invoker.target[Invoker.method]"
    75                                       + ".apply(Invoker.target, arguments);"
    76                     + "\n  };");
    77         generateBody(names);
    78         for (String invokerMethod: invokerMethods.toArray()) {
    79             out.append("\n  invoker." + invokerMethod + " = function(target) {"
    80                            + "\n    invoker.target = target;"
    81                            + "\n    invoker.method = '" + invokerMethod + "';"
    82                            + "\n    return invoker;"
    83                            + "\n  };");
    84         }
    85         out.append("\n");
    86         generateEpilogue();
    87     }
    88 
    89     protected abstract void generatePrologue() throws IOException;
    90 
    91     protected abstract void generateEpilogue() throws IOException;
    92 
    93     protected abstract String generateClass(String className)
    94             throws IOException;
    95 
    96     protected abstract String getExportsObject();
    97 
    98     @Override
    99     protected final void declaredClass(ClassData classData, String mangledName)
   100             throws IOException {
   101         if (exportedSymbols.isExported(classData)) {
   102             out.append("\n").append(getExportsObject()).append("['")
   103                                                .append(mangledName)
   104                                                .append("'] = ")
   105                             .append(accessClass(mangledName))
   106                .append(";\n");
   107         }
   108     }
   109 
   110     @Override
   111     protected void declaredField(FieldData fieldData,
   112                                  String destObject,
   113                                  String mangledName) throws IOException {
   114         if (exportedSymbols.isExported(fieldData)) {
   115             exportMember(destObject, mangledName);
   116         }
   117     }
   118 
   119     @Override
   120     protected void declaredMethod(MethodData methodData,
   121                                   String destObject,
   122                                   String mangledName) throws IOException {
   123         if (exportedSymbols.isExported(methodData)) {
   124             exportMember(destObject, mangledName);
   125         }
   126     }
   127 
   128     private void exportMember(String destObject, String memberName)
   129             throws IOException {
   130         out.append("\n").append(destObject).append("['")
   131                                            .append(memberName)
   132                                            .append("'] = ")
   133                         .append(destObject).append(".").append(memberName)
   134            .append(";\n");
   135     }
   136 
   137     private void generateBody(StringArray names) throws IOException {
   138         StringArray processed = new StringArray();
   139         StringArray initCode = new StringArray();
   140         for (String baseClass : names.toArray()) {
   141             references.add(baseClass);
   142             for (;;) {
   143                 String name = null;
   144                 for (String n : references.toArray()) {
   145                     if (processed.contains(n)) {
   146                         continue;
   147                     }
   148                     name = n;
   149                 }
   150                 if (name == null) {
   151                     break;
   152                 }
   153 
   154                 try {
   155                     String ic = generateClass(name);
   156                     processed.add(name);
   157                     initCode.add(ic == null ? "" : ic);
   158                 } catch (RuntimeException ex) {
   159                     if (out instanceof CharSequence) {
   160                         CharSequence seq = (CharSequence)out;
   161                         int lastBlock = seq.length();
   162                         while (lastBlock-- > 0) {
   163                             if (seq.charAt(lastBlock) == '{') {
   164                                 break;
   165                             }
   166                         }
   167                         throw new IOException("Error while compiling " + name + "\n"
   168                             + seq.subSequence(lastBlock + 1, seq.length()), ex
   169                         );
   170                     } else {
   171                         throw new IOException("Error while compiling " + name + "\n"
   172                             + out, ex
   173                         );
   174                     }
   175                 }
   176             }
   177 
   178             for (String resource : scripts.toArray()) {
   179                 while (resource.startsWith("/")) {
   180                     resource = resource.substring(1);
   181                 }
   182                 InputStream emul = resources.get(resource);
   183                 if (emul == null) {
   184                     throw new IOException("Can't find " + resource);
   185                 }
   186                 readResource(emul, out);
   187             }
   188             scripts = new StringArray();
   189 
   190             StringArray toInit = StringArray.asList(references.toArray());
   191             toInit.reverse();
   192 
   193             for (String ic : toInit.toArray()) {
   194                 int indx = processed.indexOf(ic);
   195                 if (indx >= 0) {
   196                     final String theCode = initCode.toArray()[indx];
   197                     if (!theCode.isEmpty()) {
   198                         out.append(theCode).append("\n");
   199                     }
   200                     initCode.toArray()[indx] = "";
   201                 }
   202             }
   203         }
   204     }
   205 
   206     private static void readResource(InputStream emul, Appendable out) throws IOException {
   207         try {
   208             int state = 0;
   209             for (;;) {
   210                 int ch = emul.read();
   211                 if (ch == -1) {
   212                     break;
   213                 }
   214                 if (ch < 0 || ch > 255) {
   215                     throw new IOException("Invalid char in emulation " + ch);
   216                 }
   217                 switch (state) {
   218                     case 0: 
   219                         if (ch == '/') {
   220                             state = 1;
   221                         } else {
   222                             out.append((char)ch);
   223                         }
   224                         break;
   225                     case 1:
   226                         if (ch == '*') {
   227                             state = 2;
   228                         } else {
   229                             out.append('/').append((char)ch);
   230                             state = 0;
   231                         }
   232                         break;
   233                     case 2:
   234                         if (ch == '*') {
   235                             state = 3;
   236                         }
   237                         break;
   238                     case 3:
   239                         if (ch == '/') {
   240                             state = 0;
   241                         } else {
   242                             state = 2;
   243                         }
   244                         break;
   245                 }
   246             }
   247         } finally {
   248             emul.close();
   249         }
   250     }
   251 
   252     static String toString(String name) throws IOException {
   253         StringBuilder sb = new StringBuilder();
   254 //        compile(sb, name);
   255         return sb.toString().toString();
   256     }
   257 
   258     private StringArray scripts = new StringArray();
   259     private StringArray references = new StringArray();
   260     
   261     @Override
   262     protected boolean requireReference(String cn) {
   263         if (references.contains(cn)) {
   264             return false;
   265         }
   266         references.add(cn);
   267         return true;
   268     }
   269 
   270     @Override
   271     protected void requireScript(String resourcePath) {
   272         scripts.add(resourcePath);
   273     }
   274 
   275     @Override
   276     String assignClass(String className) {
   277         return "vm." + className + " = ";
   278     }
   279     
   280     @Override
   281     String accessClass(String className) {
   282         return "vm." + className;
   283     }
   284 
   285     @Override
   286     protected String accessField(String object, String mangledName,
   287                                  String[] fieldInfoName) throws IOException {
   288         final FieldData field =
   289                 classDataCache.findField(fieldInfoName[0],
   290                                          fieldInfoName[1],
   291                                          fieldInfoName[2]);
   292         return accessNonVirtualMember(object, mangledName,
   293                                       (field != null) ? field.cls : null);
   294     }
   295 
   296     @Override
   297     protected String accessStaticMethod(
   298                              String object,
   299                              String mangledName,
   300                              String[] fieldInfoName) throws IOException {
   301         final MethodData method =
   302                 classDataCache.findMethod(fieldInfoName[0],
   303                                           fieldInfoName[1],
   304                                           fieldInfoName[2]);
   305         return accessNonVirtualMember(object, mangledName,
   306                                       (method != null) ? method.cls : null);
   307     }
   308 
   309     @Override
   310     protected String accessVirtualMethod(
   311                              String object,
   312                              String mangledName,
   313                              String[] fieldInfoName) throws IOException {
   314         final ClassData referencedClass =
   315                 classDataCache.getClassData(fieldInfoName[0]);
   316         final MethodData method =
   317                 classDataCache.findMethod(referencedClass,
   318                                           fieldInfoName[1],
   319                                           fieldInfoName[2]);
   320 
   321         if ((method != null)
   322                 && (((method.access & ByteCodeParser.ACC_FINAL) != 0)
   323                         || ((referencedClass.getAccessFlags()
   324                                  & ByteCodeParser.ACC_FINAL) != 0)
   325                         || !exportedSymbols.isExported(method))) {
   326             return object + "." + mangledName;
   327         }
   328 
   329         return accessThroughInvoker(object, mangledName);
   330     }
   331 
   332     private String accessThroughInvoker(String object, String mangledName) {
   333         if (!invokerMethods.contains(mangledName)) {
   334             invokerMethods.add(mangledName);
   335         }
   336         return "invoker." + mangledName + '(' + object + ')';
   337     }
   338 
   339     private static String accessNonVirtualMember(String object,
   340                                                  String mangledName,
   341                                                  ClassData declaringClass) {
   342         return (declaringClass != null) ? object + "." + mangledName
   343                                         : object + "['" + mangledName + "']";
   344     }
   345 
   346     private static final class Standalone extends VM {
   347         private Standalone(Appendable out, Bck2Brwsr.Resources resources) {
   348             super(out, resources);
   349         }
   350 
   351         @Override
   352         protected void generatePrologue() throws IOException {
   353             out.append("(function VM(global) {var fillInVMSkeleton = function(vm) {");
   354         }
   355 
   356         @Override
   357         protected void generateEpilogue() throws IOException {
   358             out.append(
   359                   "  return vm;\n"
   360                 + "  };\n"
   361                 + "  var extensions = [];\n"
   362                 + "  global.bck2brwsr = function() {\n"
   363                 + "    var args = Array.prototype.slice.apply(arguments);\n"
   364                 + "    var vm = fillInVMSkeleton({});\n"
   365                 + "    for (var i = 0; i < extensions.length; ++i) {\n"
   366                 + "      extensions[i](vm);\n"
   367                 + "    }\n"
   368                 + "    var loader = {};\n"
   369                 + "    loader.vm = vm;\n"
   370                 + "    loader.loadClass = function(name) {\n"
   371                 + "      var attr = name.replace__Ljava_lang_String_2CC('.','_');\n"
   372                 + "      var fn = vm[attr];\n"
   373                 + "      if (fn) return fn(false);\n"
   374                 + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   375                 + "        load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   376                 + "    }\n"
   377                 + "    if (vm.loadClass) {\n"
   378                 + "      throw 'Cannot initialize the bck2brwsr VM twice!';\n"
   379                 + "    }\n"
   380                 + "    vm.loadClass = loader.loadClass;\n"
   381                 + "    vm.loadBytes = function(name) {\n"
   382                 + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   383                 + "        loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   384                 + "    }\n"
   385                 + "    vm.java_lang_reflect_Array(false);\n"
   386                 + "    vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   387                 + "      loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, null, args);\n"
   388                 + "    return loader;\n"
   389                 + "  };\n");
   390             out.append(
   391                   "  global.bck2brwsr.registerExtension"
   392                              + " = function(extension) {\n"
   393                 + "    extensions.push(extension);\n"
   394                 + "  };\n");
   395             out.append("}(this));");
   396         }
   397 
   398         @Override
   399         protected String generateClass(String className) throws IOException {
   400             ClassData classData = classDataCache.getClassData(className);
   401             if (classData == null) {
   402                 throw new IOException("Can't find class " + className);
   403             }
   404             return compile(classData);
   405         }
   406 
   407         @Override
   408         protected String getExportsObject() {
   409             return "vm";
   410         }
   411     }
   412 
   413     private static final class Extension extends VM {
   414         private Extension(Appendable out, Bck2Brwsr.Resources resources) {
   415             super(out, resources);
   416         }
   417 
   418         @Override
   419         protected void generatePrologue() throws IOException {
   420             out.append("bck2brwsr.registerExtension(function(exports) {\n"
   421                            + "  var vm = {};\n");
   422             out.append("  function link(n, inst) {\n"
   423                            + "    var cls = n.replace__Ljava_lang_String_2CC("
   424                                                   + "'/', '_').toString();\n"
   425                            + "    var dot = n.replace__Ljava_lang_String_2CC("
   426                                                   + "'/', '.').toString();\n"
   427                            + "    exports.loadClass(dot);\n"
   428                            + "    vm[cls] = exports[cls];\n"
   429                            + "    return vm[cls](inst);\n"
   430                            + "  };\n");
   431         }
   432 
   433         @Override
   434         protected void generateEpilogue() throws IOException {
   435             out.append("});");
   436         }
   437 
   438         @Override
   439         protected String generateClass(String className) throws IOException {
   440             ClassData classData = classDataCache.getClassData(className);
   441             if (classData == null) {
   442                 out.append("\n").append(assignClass(
   443                                             className.replace('/', '_')))
   444                    .append("function() {\n  return link('")
   445                    .append(className)
   446                    .append("', arguments.length == 0 || arguments[0] === true);"
   447                                + "\n};");
   448 
   449                 return null;
   450             }
   451 
   452             return compile(classData);
   453         }
   454 
   455         @Override
   456         protected String getExportsObject() {
   457             return "exports";
   458         }
   459     }
   460 }