Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Add/Modify CoffeeScript AST and write the result to a CoffeeScript file #494

Open
minostro opened this issue May 27, 2017 · 4 comments

Comments

@minostro
Copy link

Hey folks,

I would like to perform some changes in all the CoffeeScript files that are defined in a couple of repos that I have. I saw that by using coffeescript I can get a hold of the AST by doing the following

coffeescript = require 'coffee-script'
ast = coffee.nodes("my-file.coffee")

The problem with this approach is that there is no way to write the modified AST back to a coffee file. I got a suggestion of compiling the AST(coffeescript) to javascript, and then use js2coffee to write the result back to a coffeescript file. Is there a way to pass the modified AST(coffeescript) to js2coffee to generate a coffeescript file?

@GeoffreyBooth
Copy link

GeoffreyBooth commented Sep 4, 2017

You basically want to fork the compile function from coffeescript.coffee. In particular, this line:

fragments = parser.parse(tokens).compileToFragments options

can be rewritten as:

nodes = parser.parse tokens
fragments = nodes.compileToFragments options

In between these two lines, you can manipulate the nodes however you want.

EDIT: Just noticed you’re trying to get to CoffeeScript in the end. Sorry, not sure how to get there. The above will at least let you make your own version of the CoffeeScript compiler that includes your AST manipulations, then as you said you could pass that generated JS through js2coffee.

@minostro
Copy link
Author

minostro commented Sep 4, 2017

@GeoffreyBooth thanks for the insight!

@GeoffreyBooth
Copy link

@minostro Did you ever figure this out?

@minostro
Copy link
Author

minostro commented Dec 3, 2017

@GeoffreyBooth nope...unfortunately, got pull into something else :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants