3

Given metadata about the library I am trying to create in the form of an expression tree, I would like to be able to convert this into some sort of Rust-specific syntax tree that can be given to the Rust compiler.

I found a related question but it is outdated.

Community
  • 1
  • 1
Sam
  • 2,407
  • 2
  • 14
  • 37

1 Answers1

4

Yes there is. The Rust compiler itself. The entire compiler is a library and rustc is just a small crate that calls into the compiler. As an example there's the stupid-stats crate. It runs the rust compiler to generate some statistics about the code.

All you need is to import the rustc and rustc_driver crates (with extern crate) and implement the rustc_driver::CompilerCalls trait for a type (lets call it MyDriver). Then you can run rustc like this:

let args: Vec<_> = std::env::args().collect();
let mut my_driver = MyDriver::new();
rustc_driver::run_compiler(&args, &mut my_driver);

You need to make sure that the path to the standard library and core library is passed. In my case I added

"-L $HOME/.multirust/toolchains/nightly/lib/rustlib/x86_64-unknown-linux-gnu/lib"

to the command line. You cannot simply add this to the args vector, because $HOME isn't parsed here. So you need some more code that extracts the $HOME env var and builds your command.

oli_obk
  • 22,881
  • 2
  • 66
  • 85
  • Thanks. How does one map the expression tree into a syntax tree that the rust compiler understands OR can the compiler only handle rust source code in some text representation? – Sam Nov 18 '15 at 10:02
  • phew, that requires a lower level interface than the one I showed. It's certainly possible, but you need to create the AST (the HIR) yourself. I suggest you look at the `librustc*` and see how the rustc binary is created. – oli_obk Nov 18 '15 at 11:54