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