paint-brush
Parsing JavaScript in JavaScriptby@fwouts
1,459 reads
1,459 reads

Parsing JavaScript in JavaScript

by François WoutsAugust 26th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Recently, I started playing around with the TypeScript library. In case you’re not familiar: the <a href="https://www.typescriptlang.org/">TypeScript</a> language is a superset of JavaScript that adds optional typing. It’s very similar to <a href="https://flow.org/">Flow</a>. But that’s not important here.

Coin Mentioned

Mention Thumbnail
featured image - Parsing JavaScript in JavaScript
François Wouts HackerNoon profile picture

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!