For the web-based everything notebook that I’m working on, I’ve been writing backend hookups to various programming REPLs, including IPython and Gorilla. I wanted to be able to evaluate rust code as well in this notebook environment, and so I set about writing a simple server that would compile up a string in rust when asked. This proved do have a couple of gotchas, so I thought I’d air my thoughts here.
For the impatient, here’s the code. Just beware of the caveat at the bottom of this post.
librustc API doesn’t have a nice, simple “here’s the string, compile it please” method, so that’s what I wrote. Here’s the basic signature:
sysroot from the above definition has to do with the location of the compiled rust libraries (given that there’s not a fool-proof way of automatically knowing where these would be). If the libraries are located in
/usr/local/lib/rustlib, then sysroot is
/usr/local/. Here are the headers we’ll need:
There are several crates involved here;
librustc is currently in the process of being refactored, so the locations of some of these items might change.
The function that is exposed by
This requires the creation of a basic session and accompanying config, in addition to the input and the output that we provide.
And now the final pieces; a few helper functions to expose a simple interface:
Now you’re all set to be compiling rust from rust!
For bonus points, let’s make this a little more rusty be taking advantage of
Traits. This will allow us to do away with the type-specialized functions
This way we can call
compile(mystring, ...) or
compile(mypath, ...), and the compiler will translate the calls to
compile::<String>(mystring, ...) and
compile::<Path>(mypath, ...). Awesome!
As it happens, there’s a bug in
librustc that prevents your from compiling multiple files in a row – there’s some global state being stored somewhere, and I don’t as yet know how to reset it (github issue). So, for the moment, I’ve resorted to just creating a subprocess calling the binary
rustc, which is far from ideal, but works.
Here’s the code from this post all together in a single file: compile_inline.rs.