2 个版本
0.0.2 | 2021 年 5 月 18 日 |
---|---|
0.0.1 | 2021 年 5 月 17 日 |
#37 in #eval
每月 22 次下载
用于 ctjs
19KB
414 行
ctjs
在编译时执行 JavaScript 以生成 Rust 代码。支持评估表达式和自定义 derive。
eval
use ctjs::eval;
const X: f64 = eval! {
// This is JavaScript
const x = 5;
String(x * Math.PI)
};
assert!(X > 15.0);
assert!(X < 16.0);
自定义 derive
use ctjs::JsMacro;
#[derive(Debug, JsMacro)]
#[js_macro = "fruit_derive"]
enum Fruit {
#[js(name = "granny smith")]
Apple,
Orange,
Pear,
}
fruit_derive! {
js!(
let output = "const _: () = {\n";
output += "use std::fmt::{self, Write};\n";
// name is "Fruit"
output += "impl fmt::Display for " + name + "{\n";
output += "fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n";
output += "write!(f, \"{}\", match self {\n";
// ident is "Apple" or "Orange" or "Pear"
for (const { ident, attrs } of item.variants) {
let string = '"' + ident.toLowerCase() + '"';
const kv = ctjs.parse_attrs(attrs);
if (kv.name) {
string = kv.name;
}
output += "Self::" + ident + " => " + string + ",\n";
}
output += "})\n";
output += "}\n}\n};\n";
output
)
}
let fruits = vec![Fruit::Apple, Fruit::Orange, Fruit::Pear];
for fruit in &fruits {
println!("Debug: {:?}, Display: {}", fruit, fruit);
}
assert_eq!(&fruits[0].to_string(), "granny smith");
assert_eq!(&fruits[1].to_string(), "orange");
assert_eq!(&fruits[2].to_string(), "pear");
当前版本:0.0.2
前期工作
所有代码均以 MIT 许可证授权
依赖项
~5.5MB
~138K SLoC