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