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 result to coffescript file #4556

Closed
minostro opened this issue May 27, 2017 · 6 comments
Closed
Labels

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 I can get a hold of the AST by doing the following

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

Is there a way to write the AST back to a coffescript file?

@GeoffreyBooth
Copy link
Collaborator

As in, generate CoffeeScript code from a set of AST nodes? Not using just the CoffeeScript module itself. The coffeescript module just takes Coffee input and generates JS output.

The https://github.com/js2coffee/js2coffee module takes JavaScript and converts it into CoffeeScript, so I guess you could use coffeescript to generate JavaScript which you then pass through js2coffee to get CoffeeScript back. This wouldn’t be as pointless as it sounds, as such a roundabout would at least clean up style (standardizing whitespace and so on). If you fork js2coffee you might find a way to give it an input of AST nodes rather than a JavaScript string.

@minostro
Copy link
Author

@GeoffreyBooth Thanks! I'll give it a try

@lydell
Copy link
Collaborator

lydell commented May 27, 2017

Somewhat related is that CoffeeScriptRedux was very ambitious and included a CoffeeScript code generator; see https://github.com/michaelficarra/cscodegen

@minostro
Copy link
Author

@lydell I'll ask them, thanks!

@jashkenas
Copy link
Owner

jashkenas commented May 30, 2017

Is there a way to write the AST back to a coffescript file?

You sure can! To quote the comment on that method:

# Parse a string of CoffeeScript code or an array of lexed tokens, and
# return the AST. You can then compile it by calling `.compile()` on the root,
# or traverse it by using `.traverseChildren()` with a callback.

So, you can then use traverseChildren, passing in a function, to walk the whole AST, modifying if you like as you go ... and then call .compile on the root node to get the resulting JavaScript back as a string.

Edit: Whoops -- read too fast.

Is there a way to write the AST back to a coffescript file?

Nope, my bad.

@minostro
Copy link
Author

@jashkenas np 👍

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

No branches or pull requests

4 participants