CoffeeScript:在程序中计算解析树(如 coffee -n)
CoffeeScript: calculate parse tree (like coffee -n) in a program
有没有办法在不调用外部程序的情况下在 CoffeeScript 中计算程序(以字符串形式提供)的 CoffeeScript 解析树?
例如,假设我在 CoffeeScript 程序中有一个字符串 'square=(n)->n*n'。我想获得与将此字符串存储在文件 square.coffee
中并在命令行上调用 coffee -n square.coffee
相同的输出 --- 但不创建另一个进程:
Block
Assign
Value "square"
Code
Param "n"
Block
Op *
Value "n"
Value "n"
请提供您的解决方案 link 以记录如何解释生成的数据结构。
看看 the source: the -n
flag invokes (require 'coffee-script).nodes
. The result is a syntax tree which corresponds to grammar.coffee and would be interpreted with nodes.coffee.
所以这个:
(require 'coffee-script').nodes 'square = (n)->n*n'
会给你一个语法树。在打印之前,您可以使用其 toString
方法获得与 coffee
CLI 相同的输出。
对于文件系统操作,只需使用 fs
库中节点的 readFile
或 readFileSync
:
{readFileSync} = require 'fs'
{nodes} = require 'coffee-script'
nodes readFileSync('squares.coffee').toString()
有没有办法在不调用外部程序的情况下在 CoffeeScript 中计算程序(以字符串形式提供)的 CoffeeScript 解析树?
例如,假设我在 CoffeeScript 程序中有一个字符串 'square=(n)->n*n'。我想获得与将此字符串存储在文件 square.coffee
中并在命令行上调用 coffee -n square.coffee
相同的输出 --- 但不创建另一个进程:
Block
Assign
Value "square"
Code
Param "n"
Block
Op *
Value "n"
Value "n"
请提供您的解决方案 link 以记录如何解释生成的数据结构。
看看 the source: the -n
flag invokes (require 'coffee-script).nodes
. The result is a syntax tree which corresponds to grammar.coffee and would be interpreted with nodes.coffee.
所以这个:
(require 'coffee-script').nodes 'square = (n)->n*n'
会给你一个语法树。在打印之前,您可以使用其 toString
方法获得与 coffee
CLI 相同的输出。
对于文件系统操作,只需使用 fs
库中节点的 readFile
或 readFileSync
:
{readFileSync} = require 'fs'
{nodes} = require 'coffee-script'
nodes readFileSync('squares.coffee').toString()