invoke_witc/
lib.rs

1use proc_macro::TokenStream;
2use std::process::{Command, Output};
3use syn::{parse_macro_input, Lit, Meta, MetaList, NestedMeta};
4
5fn lit_as_str(lit: &Lit) -> String {
6    match lit {
7        Lit::Str(s) => s.value(),
8        _ => unreachable!(),
9    }
10}
11fn name_value_meta(meta: &Meta) -> (String, String) {
12    match meta {
13        Meta::NameValue(nv) => (
14            nv.path.get_ident().unwrap().to_string(),
15            lit_as_str(&nv.lit),
16        ),
17        _ => unreachable!(),
18    }
19}
20
21fn check_version() {
22    let ver_output = Command::new("witc-exe")
23        .args(["--version"])
24        .output()
25        .unwrap();
26    let ver = String::from_utf8(ver_output.stdout).unwrap();
27    if ver != "0.3.1\n" {
28        panic!("witc-exe version mismatch: expected 0.3.1, got {}", ver);
29    }
30}
31
32#[proc_macro]
33pub fn wit_instance(input: TokenStream) -> TokenStream {
34    check_version();
35    let MetaList { path, nested, .. } = parse_macro_input!(input);
36    let mode = path.get_ident().unwrap().to_string();
37    let r: Output = match &nested[0] {
38        NestedMeta::Lit(lit) => {
39            let wit_file = lit_as_str(lit);
40            Command::new("witc-exe")
41                .args(["instance", &mode, &wit_file])
42                .output()
43                .unwrap()
44        }
45        NestedMeta::Meta(meta) => {
46            let (in_out_name, wit_file) = name_value_meta(meta);
47            Command::new("witc-exe")
48                .args(["instance", &mode, &wit_file, &in_out_name])
49                .output()
50                .unwrap()
51        }
52    };
53    String::from_utf8_lossy(&r.stdout).parse().unwrap()
54}
55
56#[proc_macro]
57pub fn wit_runtime(input: TokenStream) -> TokenStream {
58    check_version();
59    let MetaList { path, nested, .. } = parse_macro_input!(input);
60    let mode = path.get_ident().unwrap().to_string();
61    let r: Output = match &nested[0] {
62        NestedMeta::Lit(lit) => {
63            let wit_file = lit_as_str(lit);
64            Command::new("witc-exe")
65                .args(["runtime", &mode, &wit_file])
66                .output()
67                .unwrap()
68        }
69        NestedMeta::Meta(meta) => {
70            let (in_out_name, wit_file) = name_value_meta(meta);
71            Command::new("witc-exe")
72                .args(["runtime", &mode, &wit_file, &in_out_name])
73                .output()
74                .unwrap()
75        }
76    };
77    String::from_utf8_lossy(&r.stdout).parse().unwrap()
78}