transpiler

2019-08-14 admin

transpiler是什么

什么是transpiler,AST-based transpiler wrapper

transpiler使用教程帮助文档

Transpiler

Build Status

AST-based transpiler wrapper.

Usage

var myTranspiler = require('transpiler').create(<spec>);

var myResult = myTranspiler.transpile(<AST>, <DATA|null>, [<OPTIONS>]);

Here’s a transpiler for a very simple AST spec that represents expressions:

var transpilerSpec = {
    nodes: {
        'EXPR': function (node, transpile) {
            return transpile(node.left) + ' ' + node.operator + ' ' + transpile(node.right);
        },
        'OPERAND': function (node) {
            return node.value;
        }
    }
};

We can create a transpiler that uses this spec like so:

var expressionTranspiler = require('transpiler').create(transpilerSpec);

Now we’re ready to perform a transpile. Let’s start with a simple example, here’s my AST:

var myAST = {
    name: 'EXPR',
    left: {
        name: 'OPERAND',
        value: 21
    },
    operator: '+',
    right: {
        name: 'OPERAND',
        value: 27
    }
};

And let’s transpile:

console.log(expressionTranspiler.transpile(myAST)); // Logs '21 + 27'

Overrides

It’s possible to override or customise the way certain nodes are transpiled. As an example, let’s change it so that operands with the value 27 are wrapped in yes(...). Here’s my AST again:

var myAST = {
    name: 'EXPR',
    left: {
        name: 'OPERAND',
        value: 21
    },
    operator: '+',
    right: {
        name: 'OPERAND',
        value: 27
    }
};

Now let’s transpile, but this time we’ll specify a custom way to transpile OPERAND nodes:

console.log(expressionTranspiler.transpile(myAST, null, {
    nodes: {
        'OPERAND': function (node, transpile, context, original) {
            if (node.value === 27) {
                return 'yes(' + original(node) + ')';
            }

            return original(node);
        }
    }
})); // Logs '21 + yes(27)'

Keeping up to date

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-72476.html

文章标题:transpiler

回到顶部