2017-10-09

Creating and Printing a TypeScript AST from Rust

Rust and TypeScript are two of the most loved languages. One of the Rust goals is integration with other languages. In this post I explore how to generate TypeScript code from Rust using TypeScript's own API by porting one of their examples. I've wrapped a minimal amount of the TypeScript API needed for this example. I learned quite a bit about Rust while making this and would appreciate a review and feedback of the design and code. When you try running it, it should produce this:



Microsoft has heavily invested in both the Chakra JavaScript engine and TypeScript. The core part of the engine is open source and cross platform. ChakraCore exposes a C API for embedding and using the engine from your own apps. Elliot Linder has started wrapping that low level API into something easier to consume in Rust.

TypeScript exposes a compiler API. I first tried it out three years ago, but I was only only able to read the TypeScript, not generate TypeScript. I've been a squeaky wheel since then, asking politely and persistently for the ability to generate TypeScript. As of TypeScript 2.3.0 release in April it is possible. Their example titled Creating and Printing a TypeScript AST shows how to do it from TypeScript itself:

Loading gist ...
Here is how I've ported it to Rust:

Loading gist ...
The two main things that could make this port much better would be if:

Proof of Concept

Where do we go from here? This was simply a proof of concept to show that it could work, gauge interest, and see if I could get help resolving some of the harder problems with the design. It should be possible to read the TypeScript definition files and generate these bindings. It should be a much simpler app than bindgen which does that for C/C++, but it would still be a decent amount of work.