【问题标题】:How to use the CoffeeScript API in order to manipulate the AST and write .coffee output如何使用 CoffeeScript API 来操作 AST 并编写 .coffee 输出
【发布时间】:2014-01-27 17:08:52
【问题描述】:

我想创建一些函数来读取源 .coffee 文件,使用 CoffeeScript 解析器检查 AST(可能使用 traverseChildren 函数),更改一些节点,然后将更改后的 AST 写回目标 .coffee文件。

这种操作的一个简单(但无用)示例是,我想查找树中的所有字符串并连接“Luis was here”。所以如果我有

console.log 'Hello, world!'

然后在我的函数遍历文件后,它会生成:

console.log 'Hello, world!Luis was here'

它仍然是 CoffeeScript,而不是“编译”的 JavaScript。阅读 .coffee 并生成 .js 非常容易,但这不是我想要的。我找不到将 CoffeeScript API 用于此类任务的方法。

提前感谢您的帮助...

【问题讨论】:

    标签: javascript compiler-construction coffeescript


    【解决方案1】:

    由于 CoffeeScript 编译器是用 CoffeeScript 编写的,因此您可以在 CoffeeScript 中使用它。编写另一个 CoffeeScript 程序,读取您的源代码,操作 AST,然后编写 JavaScript:

    一个简短的例子,比如在 mycustom.coffee 文件中:

    fs = require 'fs'
    coffee = require 'coffee-script'
    
    generateCustom = (source, destination, callback) ->
      nodes = coffee.nodes source
      # You now have access to the AST through nodes
      # Walk the AST, modify it...
      # and then write the JavaScript via compile()
      js = nodes.compile()
      fs.writeFile destination, js, (err) ->
        if err then throw err
        callback 'Done'
    
    destination = process.argv[3]
    source = process.argv[2]
    generateCustom source, destination, (report) -> console.log report
    

    像这样调用这个程序:

    > coffee mycustom.coffee source.coffee destination.js

    也就是说,如果您的转换非常简单,那么您可能更容易通过操作令牌流来创建自定义重写器。

    【讨论】:

    • 非常感谢,我试试看。
    猜你喜欢
    • 2013-09-28
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 2013-02-11
    • 1970-01-01
    相关资源
    最近更新 更多