Как выглядит выход Дарт? - PullRequest
32 голосов
/ 10 октября 2011

Dart, новый веб-язык Google, говорит, что поддерживает вывод в JavaScript.

Как выглядит простое преобразование?

Ответы [ 2 ]

46 голосов
/ 10 октября 2011
main() {
      print('Hello, Dart!');
}

При компиляции с помощью dart2js (по состоянию на 2013-04-26) (см. Примечание внизу) оно преобразуется в:

// Generated by dart2js, the Dart to JavaScript compiler.
// The code supports the following hooks:
// dartPrint(message)   - if this function is defined it is called
//                        instead of the Dart [print] method.
// dartMainRunner(main) - if this function is defined, the Dart [main]
//                        method will not be invoked directly.
//                        Instead, a closure that will invoke [main] is
//                        passed to [dartMainRunner].
function Isolate() {}
init();

var $ = Isolate.$isolateProperties;
// Bound closures
$.Primitives_printString = function(string) {
  if (typeof dartPrint == "function") {
    dartPrint(string);
    return;
  }
  if (typeof window == "object") {
    if (typeof console == "object")
      console.log(string);
    return;
  }
  if (typeof print == "function") {
    print(string);
    return;
  }
  throw "Unable to print message: " + String(string);
};

$.main = function() {
  $.Primitives_printString("Hello, Dart!");
};

$.String = {builtin$cls: "String"};

var $ = null;
Isolate = Isolate.$finishIsolateConstructor(Isolate);
var $ = new Isolate();
// BEGIN invoke [main].
if (typeof document !== "undefined" && document.readyState !== "complete") {
  document.addEventListener("readystatechange", function () {
    if (document.readyState == "complete") {
      if (typeof dartMainRunner === "function") {
        dartMainRunner(function() { $.main(); });
      } else {
        $.main();
      }
    }
  }, false);
} else {
  if (typeof dartMainRunner === "function") {
    dartMainRunner(function() { $.main(); });
  } else {
    $.main();
  }
}
// END invoke [main].
function init() {
  Isolate.$isolateProperties = {};
  Isolate.$finishIsolateConstructor = function(oldIsolate) {
    var isolateProperties = oldIsolate.$isolateProperties;
    isolateProperties.$currentScript = typeof document == "object" ? document.currentScript || document.scripts[document.scripts.length - 1] : null;
    var isolatePrototype = oldIsolate.prototype;
    var str = "{\n";
    str += "var properties = Isolate.$isolateProperties;\n";
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    for (var staticName in isolateProperties) {
      if (hasOwnProperty.call(isolateProperties, staticName)) {
        str += "this." + staticName + "= properties." + staticName + ";\n";
      }
    }
    str += "}\n";
    var newIsolate = new Function(str);
    newIsolate.prototype = isolatePrototype;
    isolatePrototype.constructor = newIsolate;
    newIsolate.$isolateProperties = isolateProperties;
    return newIsolate;
  };
}
//@ sourceMappingURL=out.js.map

Примечание для потомков: Первоначальный ответ на этот вопрос был изменен, чтобы отразить текущее состояние дел.

В 2012-05-12 вылет дротика для Hello World составлял 18 718 символов.

2012-08-29 было выведено 1531 символов.

В 2013-04-26 было выведено 2642 символа.

dart2js может минимизировать код. Вот пример (по состоянию на 2013-04-26)

// Generated by dart2js, the Dart to JavaScript compiler.
function I(){}
init()
var $=I.p
$.ib=function(a){if(typeof dartPrint=="function"){dartPrint(a)
return}if(typeof window=="object"){if(typeof console=="object")console.log(a)
return}if(typeof print=="function"){print(a)
return}throw "Unable to print message: " + String(a)}
$.E2=function(){$.ib("Hello, Dart!")}
$.qU={builtin$cls:"qU"}

var $=null
I = I.$finishIsolateConstructor(I)
var $=new I()
if (typeof document !== "undefined" && document.readyState !== "complete") {
  document.addEventListener("readystatechange", function () {
    if (document.readyState == "complete") {
      if (typeof dartMainRunner === "function") {
        dartMainRunner(function() { $.E2(); });
      } else {
        $.E2();
      }
    }
  }, false);
} else {
  if (typeof dartMainRunner === "function") {
    dartMainRunner(function() { $.E2(); });
  } else {
    $.E2();
  }
}
function init(){I.p={}
I.$finishIsolateConstructor=function(a){var z=a.p
z.$currentScript=typeof document=="object"?document.currentScript||document.scripts[document.scripts.length-1]:null
var y=a.prototype
var x="{\n"
x+="var properties = I.p;\n"
var w=Object.prototype.hasOwnProperty
for(var v in z){if(w.call(z,v)){x+="this."+v+"= properties."+v+";\n"}}x+="}\n"
var u=new Function(x)
u.prototype=y
y.constructor=u
u.p=z
return u}}//@ sourceMappingURL=out.js.map

2013-04-26, минимальный код был 1386 символов.

10 голосов
/ 05 ноября 2011

Выход компилятора Dart-> JavaScript является движущейся целью. Первый выпуск (технический предварительный просмотр) не сильно тряхнул дерево и поэтому был довольно большим. Новый (экспериментальный) компилятор лягушки намного лучше в этом отношении ( блог Дэвида Чендлера ), но я ожидаю, что DartC тоже значительно улучшится.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...