最小自托管js编译器

网友投稿 606 2022-11-03

最小自托管js编译器

最小自托管js编译器

This is an experimental source-to-source compiler that understands basic JavaScript and offers two extra language features on top. The compiler is bootstrapped (able to compile itself) and written in only 1k lines of code.

I created this project to give a basic, not too much time-consuming overview, how compilers like Babel work behind the scenes.

Overview:

bin/stub contains the latest generated version (the "compiler.exe") src/index contains the compiler source code we can edit (gets compiled by our stub)

Usage:

node build

Features:

Pass by reference:

// variables with native types get passed by value in js -// with 'inout' we tell the compiler to transform passed in variables into referenceable objectsfunction swap(inout a, inout b) { let tmp = a; a = b; b = tmp;};let test1 = 5;let test2 = 10;console.log(test1, test2); // 5, 10swap(test1, test2); // swap both variablesconsole.log(test1, test2); // 10, 5

Compiles into:

function swap(a, b) { let tmp = a.$iov; a.$iov = b.$iov; b.$iov = tmp;};let test1 = { $iov: 5 };let test2 = { $iov: 10 };console.log(test1.$iov, test2.$iov); // here we point to the variable's valueswap(test1, test2); // here we pass the variable's referenceconsole.log(test1.$iov, test2.$iov); // much hax

Enums:

enum Direction { Up = 0, Down, Left, Right}let dir = .Up || Direction.Right;

Compiles into:

var Direction;(function(Direction) { Direction[Direction['Up'] = 0] = 'Up'; Direction[Direction['Down'] = 1] = 'Down'; Direction[Direction['Left'] = 2] = 'Left'; Direction[Direction['Right'] = 3] = 'Right';})(Direction || (Direction = {}));let dir = 0 || 3;

How it works:

The first version of the compiler was written in very simple javascript, using only explicitly necessary language features. The compiler got extended more and more until it was able to parse the required subset of javascript language features, which are needed to parse and transform strings. In the next step the code generator got added which spits out plain javascript without any formatting. This code then turned into the stub file as well as remains our source file.

Stub usage:

let compiler = require("./bin/stub");compiler.compile("const a = 10;", { console: console, // uses log and error method error: function(msg) { console.error("Error: " + msg); // wat happens on a error }});

See toy-compiler for a more extended version offering classes and a simple preprocessor.

Another compile-to-js project is this one, which offers a Swift-like language with type inference, custom operators, pass-by-reference etc.

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springmvc中下载中文文件名称为下划线的解决方案
下一篇:Tinyreset 现代Web的微小CSS reset
相关文章

 发表评论

暂时没有评论,来抢沙发吧~