Yaakov Belch
Yaakov Belch

Reputation: 4863

CoffeeScript: calculate parse tree (like coffee -n) in a program

Is there a way to compute the CoffeeScript parse tree of a program (provided as a string) inside CoffeeScript without calling an external program?

For example, let's say I have a string 'square=(n)->n*n' inside a CoffeeScript program. I want to get the same output as storing this string in a file square.coffee and calling on the command line coffee -n square.coffee --- but without creating another process:

Block
  Assign
    Value "square"
    Code
      Param "n"
      Block
        Op *
          Value "n"
          Value "n"

Please, provide with your solution a link to documentation how to interpret the resulting data structure.

Upvotes: 0

Views: 74

Answers (1)

Patrick J. S.
Patrick J. S.

Reputation: 2935

Just look in 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.

So this:

(require 'coffee-script').nodes 'square = (n)->n*n'

Will give you a syntax tree. Before you print it, you could use its toString method to get the same output as the coffee CLI.

For the filesystem operations, just use node's readFile or readFileSync from the fs library:

{readFileSync} = require 'fs'
{nodes}        = require 'coffee-script'

nodes readFileSync('squares.coffee').toString()

Upvotes: 1

Related Questions