Recently, I started playing around with the TypeScript library. In case you’re not familiar: the TypeScript language is a superset of JavaScript that adds optional typing. It’s very similar to Flow. But that’s not important here.
What’s interesting is that the TypeScript library is a JavaScript library that includes a parser (text → AST) and printer (AST → text). It’s able to parse not only TypeScript, but also plain JavaScript as well as JSX and even Flow. What’s an AST?
Let me show you a simple example:
<a href="https://medium.com/media/cfec2fceee90a134012ec5ea19d295a5/href">https://medium.com/media/cfec2fceee90a134012ec5ea19d295a5/href</a>
Now, the interesting part is that you can change the Abstract Syntax Tree and reprint the code. For example:
<a href="https://medium.com/media/948b5fa76ca557fdce80e259ac517b4d/href">https://medium.com/media/948b5fa76ca557fdce80e259ac517b4d/href</a>
Or you can have fun and push it a level further, by parsing the script’s own code and asking it to rewrite itself. I’m not sure why you’d do that, but hey, why not?
<a href="https://medium.com/media/093b4502a225024bd41ea225a9024c9d/href">https://medium.com/media/093b4502a225024bd41ea225a9024c9d/href</a>
Clone this GitHub repo if you’d like to try it.
That’s it for today. If you liked this post, you may also like my previous post about parsing your own language with ANTLR4.
Thanks for reading, have a nice day!