Luis Crespo
Luis Crespo

Reputation: 788

How to use the CoffeeScript API in order to manipulate the AST and write .coffee output

I want to make some function that reads a source .coffee file, uses the CoffeeScript parser to inspect the AST (probably using the traverseChildren function), change some of the nodes, then write the changed AST back to a destination .coffee file.

A simple (but useless) example of such manipulation is, I want to find all strings in the tree and concatenate "Luis was here". So if I have

console.log 'Hello, world!'

Then after my function has gone through the file, it would generate:

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

Which is still CoffeeScript, not "compiled" JavaScript. It is very easy to read .coffee and generate .js, but that is not what I want. I can't find a way to use the CoffeeScript API for such kind of task.

Thanks in advance for your help...

Upvotes: 0

Views: 430

Answers (1)

boundvariable
boundvariable

Reputation: 71

As the CoffeeScript compiler is written in CoffeeScript you use it in CoffeeScript. Write another CoffeeScript program that reads your source, manipulates the AST and then write the JavaScript:

A brief example, say in a mycustom.coffee file:

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

Invoke this program like:

> coffee mycustom.coffee source.coffee destination.js

That said, if your transformation is very simple then it might be easier for you to create a custom rewriter by manipulating the token stream.

Upvotes: 2

Related Questions