Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Rust macros parse JSON?

Tags:

json

rust

I'd like to define constant values by using a JSON configuration file, something like this:

enum E {
    ONE = get!(include_json!("a.json"), 0),
    TWO = get!(include_json!("a.json"), 1),
}

Is there any way to parse JSON at compile-time?

like image 224
kriw Avatar asked Feb 11 '17 16:02

kriw


People also ask

How do you make JSON in Rust?

An easy way create Value s is with the serde_json::json macro. This essentially allows you to write JSON directly in Rust source code. If you have a Value representing an object or array, you can access the fields using Value::get , similar to Vec::get and HashMap::get .

Are rust macros compile time?

In Rust Macros are executed at compile time. They generally expand into new pieces of code that the compiler will then need to further process.

Why does rust use macros?

Rust has excellent support for macros. Macros enable you to write code that writes other code, which is known as metaprogramming. Macros provide functionality similar to functions but without the runtime cost. There is some compile-time cost, however, since macros are expanded during compile time.


1 Answers

There are multiple ways to parse json at compile-time. In order of "involvement":

  • using the build.rs script to generate your source code during build; it's technically cheating, of course, but it's easy,
  • using a const function in combination with the include_str!, it would require nightly and I am not sure whether the compile-time engine is powerful enough at the time being,
  • writing a compiler plugin, which is what include_str! is, it also requires nightly and the interface may change with each release of the compiler.

Thus I would advise you to use the build.rs script approach for now since it's both simple and stable.

like image 64
Matthieu M. Avatar answered Sep 21 '22 05:09

Matthieu M.