gdp-wired 0.31.1 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +95 -6
- package/dist/core/c/reader.d.ts +86 -0
- package/dist/core/c/reader.js +860 -0
- package/dist/core/check.js +20 -6
- package/dist/core/cli.d.ts +76 -0
- package/dist/core/cli.js +636 -0
- package/dist/core/dsl.d.ts +6 -4
- package/dist/core/dsl.js +30 -16
- package/dist/core/effect.d.ts +6 -4
- package/dist/core/effect.js +48 -10
- package/dist/core/ex/harness.exs +177 -0
- package/dist/core/ex/json.exs +46 -0
- package/dist/core/ex/reader.exs +462 -0
- package/dist/core/exists.d.ts +3 -0
- package/dist/core/exists.js +19 -5
- package/dist/core/extract-c.d.ts +35 -0
- package/dist/core/extract-c.js +424 -0
- package/dist/core/extract-check.js +27 -6
- package/dist/core/extract-ex.d.ts +16 -0
- package/dist/core/extract-ex.js +33 -0
- package/dist/core/extract-go-check.d.ts +28 -0
- package/dist/core/extract-go-check.js +639 -0
- package/dist/core/extract-go.d.ts +231 -0
- package/dist/core/extract-go.js +1166 -0
- package/dist/core/extract-jvm.d.ts +23 -0
- package/dist/core/extract-jvm.js +220 -0
- package/dist/core/extract-print.js +17 -7
- package/dist/core/extract-py.d.ts +15 -0
- package/dist/core/extract-py.js +31 -0
- package/dist/core/extract-rb.d.ts +17 -0
- package/dist/core/extract-rb.js +31 -0
- package/dist/core/extract-read.d.ts +20 -0
- package/dist/core/extract-read.js +46 -6
- package/dist/core/extract-rs.d.ts +12 -0
- package/dist/core/extract-rs.js +306 -0
- package/dist/core/extract-shapes.d.ts +2 -0
- package/dist/core/extract-shapes.js +6 -5
- package/dist/core/extract-step.d.ts +806 -0
- package/dist/core/extract-step.js +4141 -0
- package/dist/core/extract-swift.d.ts +27 -0
- package/dist/core/extract-swift.js +484 -0
- package/dist/core/extract-xstate.d.ts +10 -3
- package/dist/core/extract-xstate.js +50 -4
- package/dist/core/extract.d.ts +22 -3
- package/dist/core/extract.js +107 -18
- package/dist/core/go/go.mod +3 -0
- package/dist/core/go/reader.go +901 -0
- package/dist/core/infer.d.ts +4 -0
- package/dist/core/infer.js +1838 -69
- package/dist/core/jvm/Harness.java +361 -0
- package/dist/core/jvm/JavaReader.java +825 -0
- package/dist/core/jvm/Jvm.java +332 -0
- package/dist/core/jvm/KtReader.java +960 -0
- package/dist/core/jvm/Rt.java +10 -0
- package/dist/core/laws.d.ts +83 -0
- package/dist/core/laws.js +623 -0
- package/dist/core/machine.d.ts +2 -0
- package/dist/core/machine.js +87 -0
- package/dist/core/py/harness.py +328 -0
- package/dist/core/py/reader.py +447 -0
- package/dist/core/rb/harness.rb +233 -0
- package/dist/core/rb/reader.rb +375 -0
- package/dist/core/relational.d.ts +49 -0
- package/dist/core/relational.js +345 -0
- package/dist/core/rs/Cargo.lock +108 -0
- package/dist/core/rs/Cargo.toml +14 -0
- package/dist/core/rs/src/main.rs +681 -0
- package/dist/core/swift/Harness.swift +124 -0
- package/dist/core/swift/Main.swift +34 -0
- package/dist/core/swift/Package.swift +13 -0
- package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
- package/dist/interchange/check.d.ts +16 -0
- package/dist/interchange/check.js +111 -0
- package/dist/interchange/format.d.ts +150 -0
- package/dist/interchange/format.js +678 -0
- package/dist/kernel/epr.d.ts +40 -0
- package/dist/kernel/epr.js +1882 -0
- package/dist/kernel/kernel.d.ts +45 -1
- package/dist/kernel/kernel.js +138 -13
- package/dist/kernel/prove.d.ts +45 -0
- package/dist/kernel/prove.js +658 -51
- package/dist/lean-kernel/emit.d.ts +17 -2
- package/dist/lean-kernel/emit.js +87 -7
- package/package.json +57 -2
|
@@ -0,0 +1,681 @@
|
|
|
1
|
+
// The extractor's Rust reader (core/extract-rs.ts): a crate read through syn and lowered into the shared step IR
|
|
2
|
+
// (core/extract-step.ts's SModule, as JSON on stdout), which the shared executor runs into the rule. Rust is
|
|
3
|
+
// expression-oriented, so the lowering is to A-normal form: an `if` or `match` used as a value, a `?`, a `return`
|
|
4
|
+
// inside an expression become statements over temporaries. Nothing here decides the subset beyond the syntax: a
|
|
5
|
+
// construct the IR has no node for becomes {"e": "no"} / {"s": "no"} with the reason, refused only where a step reaches
|
|
6
|
+
// it. Integer semantics are the IR's own operations: `+ - *` trap on overflow (a debug build's panic), the
|
|
7
|
+
// `wrapping_`, `saturating_` and `checked_` forms wrap, saturate or give an Option, `/` and `%` truncate.
|
|
8
|
+
//
|
|
9
|
+
// gdp-rsreader '{"root": <crate>, "names": [<struct or functions>]}'
|
|
10
|
+
use proc_macro2::Span;
|
|
11
|
+
use quote::ToTokens;
|
|
12
|
+
use serde_json::{json, Map, Value};
|
|
13
|
+
use std::collections::{BTreeMap, BTreeSet};
|
|
14
|
+
use std::path::{Path, PathBuf};
|
|
15
|
+
use syn::spanned::Spanned;
|
|
16
|
+
use syn::{BinOp, Expr, Fields, ImplItem, Item, Lit, Pat, ReturnType, Stmt, Type, UnOp};
|
|
17
|
+
|
|
18
|
+
struct File { rel: String, items: Vec<Item>, module: String }
|
|
19
|
+
#[derive(Clone, Default)]
|
|
20
|
+
struct Enum { values: Vec<String>, discs: Vec<i64>, data: bool }
|
|
21
|
+
|
|
22
|
+
struct Reader {
|
|
23
|
+
files: Vec<File>,
|
|
24
|
+
structs: BTreeMap<String, (String, syn::ItemStruct)>, // name -> (file, item)
|
|
25
|
+
smod: BTreeMap<String, String>, // name -> its module path
|
|
26
|
+
enums: BTreeMap<String, Enum>,
|
|
27
|
+
consts: BTreeMap<String, Value>,
|
|
28
|
+
recs: Map<String, Value>,
|
|
29
|
+
funcs: Map<String, Value>,
|
|
30
|
+
methods: BTreeMap<String, Vec<(String, String, syn::ImplItemFn)>>, // type -> (file, module, fn)
|
|
31
|
+
free: BTreeMap<String, (String, syn::ItemFn)>,
|
|
32
|
+
fmod: BTreeMap<String, String>,
|
|
33
|
+
// per function
|
|
34
|
+
file: String,
|
|
35
|
+
tmp: usize,
|
|
36
|
+
locals: Vec<BTreeSet<String>>,
|
|
37
|
+
self_ty: Option<String>,
|
|
38
|
+
lifted: Vec<(String, Value)>,
|
|
39
|
+
fid: String,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
fn text(t: &impl ToTokens) -> String {
|
|
43
|
+
let s = t.to_token_stream().to_string().split_whitespace().collect::<Vec<_>>().join(" ");
|
|
44
|
+
if s.len() <= 60 { s } else { format!("{}...", &s[..s.char_indices().nth(57).map(|x| x.0).unwrap_or(s.len())]) }
|
|
45
|
+
}
|
|
46
|
+
fn no(p: &str, why: String) -> Value { json!({"e": "no", "p": p, "why": why}) }
|
|
47
|
+
fn sno(p: &str, why: String) -> Value { json!({"s": "no", "p": p, "why": why}) }
|
|
48
|
+
fn last_ident(p: &syn::Path) -> String { p.segments.last().map(|s| s.ident.to_string()).unwrap_or_default() }
|
|
49
|
+
fn path_str(p: &syn::Path) -> String { p.segments.iter().map(|s| s.ident.to_string()).collect::<Vec<_>>().join("::") }
|
|
50
|
+
fn is_place(v: &Value) -> bool { matches!(v["e"].as_str(), Some("var") | Some("get") | Some("idx")) }
|
|
51
|
+
|
|
52
|
+
impl Reader {
|
|
53
|
+
fn at(&self, s: Span) -> String { let l = s.start(); format!("{}:{}:{}", self.file, l.line, l.column + 1) }
|
|
54
|
+
|
|
55
|
+
// --- the crate: its files by `mod` declarations from src/lib.rs (or src/main.rs) ---------------------------------
|
|
56
|
+
fn load(root: &Path) -> Result<Vec<File>, String> {
|
|
57
|
+
let mut out = vec![];
|
|
58
|
+
let lib = if root.join("src/lib.rs").exists() { "src/lib.rs" } else { "src/main.rs" };
|
|
59
|
+
Self::load_file(root, Path::new(lib), "crate", &mut out)?;
|
|
60
|
+
Ok(out)
|
|
61
|
+
}
|
|
62
|
+
fn load_file(root: &Path, rel: &Path, module: &str, out: &mut Vec<File>) -> Result<(), String> {
|
|
63
|
+
let src = std::fs::read_to_string(root.join(rel)).map_err(|e| format!("{}: {e}", rel.display()))?;
|
|
64
|
+
let f = syn::parse_file(&src).map_err(|e| format!("{}: {e}", rel.display()))?;
|
|
65
|
+
let dir: PathBuf = if rel.file_name().map(|n| n == "lib.rs" || n == "main.rs" || n == "mod.rs").unwrap_or(false) { rel.parent().unwrap().to_path_buf() } else { rel.with_extension("") };
|
|
66
|
+
let mut items = vec![];
|
|
67
|
+
for it in f.items {
|
|
68
|
+
if let Item::Mod(m) = &it {
|
|
69
|
+
if m.attrs.iter().any(|a| a.path().is_ident("cfg") && text(&a.meta).contains("test")) { continue }
|
|
70
|
+
let name = m.ident.to_string();
|
|
71
|
+
let sub = format!("{module}::{name}");
|
|
72
|
+
match &m.content {
|
|
73
|
+
Some((_, inner)) => { out.push(File { rel: rel.display().to_string(), items: inner.clone(), module: sub }); }
|
|
74
|
+
None => {
|
|
75
|
+
let a = dir.join(format!("{name}.rs"));
|
|
76
|
+
let b = dir.join(&name).join("mod.rs");
|
|
77
|
+
let r = if root.join(&a).exists() { a } else if root.join(&b).exists() { b } else { continue };
|
|
78
|
+
Self::load_file(root, &r, &sub, out)?;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
continue
|
|
82
|
+
}
|
|
83
|
+
items.push(it);
|
|
84
|
+
}
|
|
85
|
+
out.push(File { rel: rel.display().to_string(), items, module: module.to_string() });
|
|
86
|
+
Ok(())
|
|
87
|
+
}
|
|
88
|
+
fn index(&mut self) {
|
|
89
|
+
for f in &self.files {
|
|
90
|
+
for it in &f.items {
|
|
91
|
+
match it {
|
|
92
|
+
Item::Struct(s) => { self.structs.insert(s.ident.to_string(), (f.rel.clone(), s.clone())); self.smod.insert(s.ident.to_string(), f.module.clone()); }
|
|
93
|
+
Item::Enum(e) => {
|
|
94
|
+
let mut en = Enum::default();
|
|
95
|
+
let mut next = 0i64;
|
|
96
|
+
for v in &e.variants {
|
|
97
|
+
if !matches!(v.fields, Fields::Unit) { en.data = true }
|
|
98
|
+
if let Some((_, Expr::Lit(l))) = &v.discriminant { if let Lit::Int(i) = &l.lit { next = i.base10_parse().unwrap_or(next) } }
|
|
99
|
+
en.values.push(v.ident.to_string()); en.discs.push(next); next += 1;
|
|
100
|
+
}
|
|
101
|
+
self.enums.insert(e.ident.to_string(), en);
|
|
102
|
+
}
|
|
103
|
+
Item::Impl(im) => {
|
|
104
|
+
if let Type::Path(tp) = &*im.self_ty {
|
|
105
|
+
let ty = last_ident(&tp.path);
|
|
106
|
+
for ii in &im.items { if let ImplItem::Fn(m) = ii { self.methods.entry(ty.clone()).or_default().push((f.rel.clone(), f.module.clone(), m.clone())); } }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
Item::Fn(fun) => { self.free.insert(fun.sig.ident.to_string(), (f.rel.clone(), fun.clone())); self.fmod.insert(fun.sig.ident.to_string(), f.module.clone()); }
|
|
110
|
+
Item::Const(c) => { if let Expr::Lit(l) = &*c.expr { if let Some(v) = self.lit(&l.lit, "") { self.consts.insert(c.ident.to_string(), v); } } }
|
|
111
|
+
_ => {}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// --- types -------------------------------------------------------------------------------------------------------
|
|
118
|
+
fn ty(&self, t: &Type) -> Value {
|
|
119
|
+
match t {
|
|
120
|
+
Type::Reference(r) => {
|
|
121
|
+
if let Type::Path(p) = &*r.elem { if p.path.is_ident("str") { return json!({"k": "str"}) } }
|
|
122
|
+
self.ty(&r.elem)
|
|
123
|
+
}
|
|
124
|
+
Type::Paren(p) => self.ty(&p.elem),
|
|
125
|
+
Type::Tuple(t) if t.elems.is_empty() => json!({"k": "none"}),
|
|
126
|
+
Type::Path(p) => {
|
|
127
|
+
let seg = match p.path.segments.last() { Some(s) => s, None => return json!({"k": "opaque", "why": text(t)}) };
|
|
128
|
+
let name = seg.ident.to_string();
|
|
129
|
+
let args: Vec<Type> = match &seg.arguments { syn::PathArguments::AngleBracketed(a) => a.args.iter().filter_map(|x| if let syn::GenericArgument::Type(t) = x { Some(t.clone()) } else { None }).collect(), _ => vec![] };
|
|
130
|
+
let int = |bits: u32, signed: bool| json!({"k": "int", "bits": bits, "signed": signed, "rs": name});
|
|
131
|
+
match name.as_str() {
|
|
132
|
+
"u8" => int(8, false), "u16" => int(16, false), "u32" => int(32, false), "u64" | "usize" => int(64, false), "u128" => int(128, false),
|
|
133
|
+
"i8" => int(8, true), "i16" => int(16, true), "i32" => int(32, true), "i64" | "isize" => int(64, true), "i128" => int(128, true),
|
|
134
|
+
"bool" => json!({"k": "bool"}), "String" | "str" => json!({"k": "str"}),
|
|
135
|
+
"f32" | "f64" => json!({"k": "opaque", "why": format!("{name}, a float (a binary fraction that rounds; the subset reads integers)")}),
|
|
136
|
+
"Instant" => json!({"k": "int", "bits": 0, "signed": true, "unit": "instant"}),
|
|
137
|
+
"Duration" => json!({"k": "int", "bits": 0, "signed": false, "unit": "duration"}),
|
|
138
|
+
"AtomicU8" => json!({"k": "int", "bits": 8, "signed": false, "atomic": name, "rs": "u8"}), "AtomicU16" => json!({"k": "int", "bits": 16, "signed": false, "atomic": name, "rs": "u16"}),
|
|
139
|
+
"AtomicU32" => json!({"k": "int", "bits": 32, "signed": false, "atomic": name, "rs": "u32"}), "AtomicU64" => json!({"k": "int", "bits": 64, "signed": false, "atomic": name, "rs": "u64"}), "AtomicUsize" => json!({"k": "int", "bits": 64, "signed": false, "atomic": name, "rs": "usize"}),
|
|
140
|
+
"AtomicI32" => json!({"k": "int", "bits": 32, "signed": true, "atomic": name, "rs": "i32"}), "AtomicI64" => json!({"k": "int", "bits": 64, "signed": true, "atomic": name, "rs": "i64"}), "AtomicIsize" => json!({"k": "int", "bits": 64, "signed": true, "atomic": name, "rs": "isize"}),
|
|
141
|
+
"AtomicBool" => json!({"k": "bool", "atomic": name}),
|
|
142
|
+
"Option" if args.len() == 1 => json!({"k": "opt", "of": self.ty(&args[0])}),
|
|
143
|
+
"Result" if !args.is_empty() => json!({"k": "res", "of": self.ty(&args[0])}),
|
|
144
|
+
"HashMap" | "BTreeMap" if args.len() == 2 => json!({"k": "map", "key": self.ty(&args[0]), "val": self.ty(&args[1]), "rs": name}),
|
|
145
|
+
"Vec" if args.len() == 1 => json!({"k": "list", "of": self.ty(&args[0])}),
|
|
146
|
+
"Mutex" | "RwLock" if args.len() == 1 => { let mut v = self.ty(&args[0]); let std = p.path.segments.iter().any(|s| s.ident == "std") || self.std_lock(); v["lock"] = json!(if std { "std" } else { "parking_lot" }); v["lockty"] = json!(name); v }
|
|
147
|
+
"Self" => match &self.self_ty { Some(s) => self.named(s, t), None => json!({"k": "opaque", "why": "Self outside an impl"}) },
|
|
148
|
+
_ => self.named(&name, t),
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
_ => json!({"k": "opaque", "why": text(t)}),
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// Whether the crate's Mutex is std's (its lock() a Result) rather than parking_lot's.
|
|
155
|
+
fn std_lock(&self) -> bool { !self.files.iter().any(|f| f.items.iter().any(|i| matches!(i, Item::Use(u) if text(u).contains("parking_lot")))) }
|
|
156
|
+
fn named(&self, name: &str, t: &Type) -> Value {
|
|
157
|
+
if let Some(e) = self.enums.get(name) {
|
|
158
|
+
if e.data { return json!({"k": "opaque", "why": format!("{name}, an enum with data (a variant record)")}) }
|
|
159
|
+
return json!({"k": "choice", "values": e.values, "discs": e.discs, "enum": name})
|
|
160
|
+
}
|
|
161
|
+
if self.structs.contains_key(name) { return json!({"k": "rec", "name": name}) }
|
|
162
|
+
json!({"k": "opaque", "why": format!("{}, a type outside the crate's own", text(t))})
|
|
163
|
+
}
|
|
164
|
+
fn rec(&mut self, name: &str) {
|
|
165
|
+
if self.recs.contains_key(name) { return }
|
|
166
|
+
let (file, s) = match self.structs.get(name) { Some(x) => x.clone(), None => return };
|
|
167
|
+
self.recs.insert(name.to_string(), Value::Null);
|
|
168
|
+
let saved = self.self_ty.replace(name.to_string());
|
|
169
|
+
let mut fields = vec![];
|
|
170
|
+
if let Fields::Named(f) = &s.fields { for fd in &f.named { fields.push(json!({"name": fd.ident.as_ref().unwrap().to_string(), "t": self.ty(&fd.ty), "rs": text(&fd.ty)})) } }
|
|
171
|
+
let derives: Vec<String> = s.attrs.iter().filter(|a| a.path().is_ident("derive")).flat_map(|a| text(&a.meta).replace("derive (", "").replace(')', "").split(',').map(|x| x.trim().to_string()).collect::<Vec<_>>()).collect();
|
|
172
|
+
let generic = !s.generics.params.is_empty();
|
|
173
|
+
let mut kinds = vec![json!("value")];
|
|
174
|
+
if derives.iter().any(|d| d == "Default") { kinds.push(json!("default")) }
|
|
175
|
+
if generic { kinds.push(json!(format!("generic:{}", text(&s.generics)))) }
|
|
176
|
+
// Its methods (each lowered once, inherent and trait impls alike).
|
|
177
|
+
let mut methods = Map::new();
|
|
178
|
+
for (mfile, _module, m) in self.methods.get(name).cloned().unwrap_or_default() {
|
|
179
|
+
let fid = format!("{name}::{}", m.sig.ident);
|
|
180
|
+
methods.insert(m.sig.ident.to_string(), json!(fid.clone()));
|
|
181
|
+
let f = self.func(&mfile, &m.sig, &m.block, &m.attrs, Some(name), &fid);
|
|
182
|
+
self.funcs.insert(fid, f);
|
|
183
|
+
}
|
|
184
|
+
self.self_ty = saved;
|
|
185
|
+
self.recs.insert(name.to_string(), json!({"name": name, "short": name, "fields": fields, "methods": methods, "kinds": kinds, "own": true, "module": self.smod.get(name).cloned().unwrap_or_default(), "file": file, "p": format!("{}:{}:1", file, s.ident.span().start().line), "derives": derives}));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// --- functions ---------------------------------------------------------------------------------------------------
|
|
189
|
+
fn func(&mut self, file: &str, sig: &syn::Signature, block: &syn::Block, attrs: &[syn::Attribute], cls: Option<&str>, fid: &str) -> Value {
|
|
190
|
+
let saved = (std::mem::replace(&mut self.file, file.to_string()), self.tmp, std::mem::take(&mut self.locals), std::mem::replace(&mut self.fid, fid.to_string()));
|
|
191
|
+
self.tmp = 0;
|
|
192
|
+
let mut params = vec![];
|
|
193
|
+
let mut names = BTreeSet::new();
|
|
194
|
+
let mut is_static = true;
|
|
195
|
+
let mut recv = Value::Null;
|
|
196
|
+
for a in &sig.inputs {
|
|
197
|
+
match a {
|
|
198
|
+
syn::FnArg::Receiver(r) => { is_static = false; names.insert("self".to_string()); recv = json!(if r.reference.is_none() { "value" } else if r.mutability.is_some() { "mut" } else { "ref" }); params.push(json!({"name": "self", "t": {"k": "any"}, "self": true})) }
|
|
199
|
+
syn::FnArg::Typed(pt) => {
|
|
200
|
+
let n = match &*pt.pat { Pat::Ident(i) => i.ident.to_string(), _ => format!("_arg{}", params.len()) };
|
|
201
|
+
names.insert(n.clone());
|
|
202
|
+
params.push(json!({"name": n, "t": self.ty(&pt.ty), "rs": text(&pt.ty)}));
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
self.locals.push(names);
|
|
207
|
+
for s in &block.stmts { if let Stmt::Local(l) = s { self.bind_pat(&l.pat) } }
|
|
208
|
+
let (mut body, tail) = self.block(block);
|
|
209
|
+
if !tail.is_null() && tail["e"] != "none" { body.push(json!({"s": "ret", "p": self.at(block.span()), "x": tail})) }
|
|
210
|
+
let ret = match &sig.output { ReturnType::Default => json!({"k": "none"}), ReturnType::Type(_, t) => self.ty(t) };
|
|
211
|
+
let generic = !sig.generics.params.is_empty();
|
|
212
|
+
let decs: Vec<Value> = attrs.iter().filter(|a| !a.path().is_ident("doc") && !a.path().is_ident("inline") && !a.path().is_ident("must_use") && !a.path().is_ident("allow")).map(|a| json!({"name": format!("attr:{}", text(a.path())), "text": text(&a.meta), "p": self.at(a.span())})).collect();
|
|
213
|
+
let out = json!({"id": fid, "name": sig.ident.to_string(), "cls": cls, "p": self.at(sig.ident.span()), "span": [file, sig.span().start().line, block.span().end().line],
|
|
214
|
+
"params": params, "ret": ret, "body": body, "async": sig.asyncness.is_some(), "static": is_static, "recv": recv, "decorators": decs, "generic": generic});
|
|
215
|
+
self.file = saved.0; self.tmp = saved.1; self.locals = saved.2; self.fid = saved.3;
|
|
216
|
+
out
|
|
217
|
+
}
|
|
218
|
+
fn bind_pat(&mut self, p: &Pat) {
|
|
219
|
+
match p {
|
|
220
|
+
Pat::Ident(i) => { if let Some(l) = self.locals.last_mut() { l.insert(i.ident.to_string()); } }
|
|
221
|
+
Pat::Type(t) => self.bind_pat(&t.pat),
|
|
222
|
+
Pat::Tuple(t) => for x in &t.elems { self.bind_pat(x) },
|
|
223
|
+
_ => {}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
fn is_local(&self, n: &str) -> bool { self.locals.iter().any(|l| l.contains(n)) }
|
|
227
|
+
fn temp(&mut self) -> String { self.tmp += 1; let n = format!("$t{}", self.tmp); if let Some(l) = self.locals.last_mut() { l.insert(n.clone()); } n }
|
|
228
|
+
|
|
229
|
+
// --- statements: each lowered with what its expressions need before them ----------------------------------------
|
|
230
|
+
fn block(&mut self, b: &syn::Block) -> (Vec<Value>, Value) {
|
|
231
|
+
let mut out = vec![];
|
|
232
|
+
let n = b.stmts.len();
|
|
233
|
+
for (i, s) in b.stmts.iter().enumerate() {
|
|
234
|
+
let last = i + 1 == n;
|
|
235
|
+
match s {
|
|
236
|
+
Stmt::Local(l) => {
|
|
237
|
+
self.bind_pat(&l.pat);
|
|
238
|
+
let p = self.at(l.span());
|
|
239
|
+
let init = match &l.init { Some(i) => i, None => continue };
|
|
240
|
+
if init.diverge.is_some() { out.push(sno(&p, "let ... else".into())); continue }
|
|
241
|
+
let (mut pre, v) = self.expr(&init.expr);
|
|
242
|
+
out.append(&mut pre);
|
|
243
|
+
let v = if is_place(&v) { json!({"e": "copy", "x": v, "p": p}) } else { v };
|
|
244
|
+
let to = self.target_pat(&l.pat, &p);
|
|
245
|
+
out.push(json!({"s": "set", "p": p, "to": to, "x": v}));
|
|
246
|
+
}
|
|
247
|
+
Stmt::Expr(e, semi) => {
|
|
248
|
+
let (mut pre, v) = self.expr(e);
|
|
249
|
+
out.append(&mut pre);
|
|
250
|
+
if last && semi.is_none() { return (out, v) }
|
|
251
|
+
if v["e"] != "none" && v["e"] != "unit" { out.push(json!({"s": "expr", "p": self.at(e.span()), "x": v})) }
|
|
252
|
+
}
|
|
253
|
+
Stmt::Macro(m) => { let (mut pre, v) = self.mac(&m.mac, m.span()); out.append(&mut pre); if !v.is_null() && v["e"] != "unit" { out.push(json!({"s": "expr", "p": self.at(m.span()), "x": v})) } }
|
|
254
|
+
Stmt::Item(it) => out.push(sno(&self.at(it.span()), "an item declared in a function".into())),
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
(out, json!({"e": "unit", "p": self.at(b.span())}))
|
|
258
|
+
}
|
|
259
|
+
fn target_pat(&self, p: &Pat, at: &str) -> Value {
|
|
260
|
+
match p {
|
|
261
|
+
Pat::Ident(i) => json!({"e": "var", "n": i.ident.to_string(), "p": at}),
|
|
262
|
+
Pat::Type(t) => self.target_pat(&t.pat, at),
|
|
263
|
+
Pat::Tuple(t) => json!({"e": "tuple", "xs": t.elems.iter().map(|x| self.target_pat(x, at)).collect::<Vec<_>>(), "p": at}),
|
|
264
|
+
Pat::Wild(_) => json!({"e": "var", "n": "_", "p": at}),
|
|
265
|
+
_ => no(at, format!("{}: a pattern outside the subset", text(p))),
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// --- expressions: (statements before, the value) ----------------------------------------------------------------
|
|
270
|
+
fn expr(&mut self, e: &Expr) -> (Vec<Value>, Value) {
|
|
271
|
+
let p = self.at(e.span());
|
|
272
|
+
let t = text(e);
|
|
273
|
+
match e {
|
|
274
|
+
Expr::Paren(x) => self.expr(&x.expr),
|
|
275
|
+
Expr::Group(x) => self.expr(&x.expr),
|
|
276
|
+
Expr::Lit(l) => (vec![], self.lit(&l.lit, &p).unwrap_or_else(|| no(&p, format!("{t}: a literal outside the subset")))),
|
|
277
|
+
Expr::Path(x) => (vec![], self.path_expr(&x.path, &p, &t)),
|
|
278
|
+
Expr::Reference(r) => { let (pre, v) = self.expr(&r.expr); (pre, json!({"e": "ref", "x": v, "p": p})) }
|
|
279
|
+
Expr::Unary(u) => {
|
|
280
|
+
let (pre, v) = self.expr(&u.expr);
|
|
281
|
+
(pre, match u.op { UnOp::Neg(_) => json!({"e": "neg", "x": v, "p": p}), UnOp::Not(_) => json!({"e": "not", "x": v, "p": p, "strict": true}), UnOp::Deref(_) => v, _ => no(&p, format!("{t}: an operator outside the subset")) })
|
|
282
|
+
}
|
|
283
|
+
Expr::Binary(b) => self.binary(b, &p, &t),
|
|
284
|
+
Expr::Assign(a) => {
|
|
285
|
+
let (mut pre, v) = self.expr(&a.right);
|
|
286
|
+
let (mut tp, to) = self.expr(&a.left);
|
|
287
|
+
pre.append(&mut tp);
|
|
288
|
+
let v = if is_place(&v) { json!({"e": "copy", "x": v, "p": p}) } else { v };
|
|
289
|
+
pre.push(json!({"s": "set", "p": p, "to": to, "x": v}));
|
|
290
|
+
(pre, json!({"e": "unit", "p": p}))
|
|
291
|
+
}
|
|
292
|
+
Expr::Field(f) => {
|
|
293
|
+
let (pre, v) = self.expr(&f.base);
|
|
294
|
+
match &f.member { syn::Member::Named(n) => (pre, json!({"e": "get", "x": v, "f": n.to_string(), "p": p, "text": t})), _ => (pre, no(&p, format!("{t}: a tuple's field"))) }
|
|
295
|
+
}
|
|
296
|
+
Expr::Index(i) => { let (mut pre, v) = self.expr(&i.expr); let (mut ip, k) = self.expr(&i.index); pre.append(&mut ip); (pre, json!({"e": "idx", "x": v, "i": k, "p": p, "text": t})) }
|
|
297
|
+
Expr::Cast(c) => { let (pre, v) = self.expr(&c.expr); (pre, json!({"e": "cast", "x": v, "ty": self.ty(&c.ty), "p": p, "text": t})) }
|
|
298
|
+
Expr::Tuple(tu) => {
|
|
299
|
+
if tu.elems.is_empty() { return (vec![], json!({"e": "unit", "p": p})) }
|
|
300
|
+
let mut pre = vec![]; let mut xs = vec![];
|
|
301
|
+
for x in &tu.elems { let (mut a, v) = self.expr(x); pre.append(&mut a); xs.push(v) }
|
|
302
|
+
(pre, json!({"e": "tuple", "xs": xs, "p": p}))
|
|
303
|
+
}
|
|
304
|
+
Expr::Block(b) => self.block(&b.block),
|
|
305
|
+
Expr::Unsafe(b) => self.block(&b.block),
|
|
306
|
+
Expr::Return(r) => {
|
|
307
|
+
let (mut pre, v) = match &r.expr { Some(x) => self.expr(x), None => (vec![], json!({"e": "unit", "p": p})) };
|
|
308
|
+
let v = if is_place(&v) { json!({"e": "copy", "x": v, "p": p}) } else { v };
|
|
309
|
+
pre.push(json!({"s": "ret", "p": p, "x": v}));
|
|
310
|
+
(pre, json!({"e": "unit", "p": p}))
|
|
311
|
+
}
|
|
312
|
+
Expr::Try(x) => {
|
|
313
|
+
// `e?`: where e is an Err (or None), the function returns it; else its value.
|
|
314
|
+
let (mut pre, v) = self.expr(&x.expr);
|
|
315
|
+
let q = self.temp();
|
|
316
|
+
pre.push(json!({"s": "set", "p": p, "to": {"e": "var", "n": q, "p": p}, "x": v}));
|
|
317
|
+
pre.push(json!({"s": "if", "p": p, "c": {"e": "is", "x": {"e": "var", "n": q, "p": p}, "k": "bad", "p": p}, "then": [{"s": "ret", "p": p, "x": {"e": "bad", "x": {"e": "var", "n": q, "p": p}, "p": p}}], "else": []}));
|
|
318
|
+
(pre, json!({"e": "unwrap", "x": {"e": "var", "n": q, "p": p}, "k": "good", "p": p}))
|
|
319
|
+
}
|
|
320
|
+
Expr::If(i) => self.if_expr(i, &p),
|
|
321
|
+
Expr::Match(m) => self.match_expr(m, &p),
|
|
322
|
+
// (a call's end too: a check stubs an answered one by rewriting it from its position to its end)
|
|
323
|
+
Expr::Call(c) => { let (s, mut v) = self.call(c, &p, &t); if v["e"] == "call" { let l = c.span().end(); v["end"] = json!(format!("{}:{}", l.line, l.column + 1)); } (s, v) }
|
|
324
|
+
Expr::MethodCall(m) => { let (s, mut v) = self.method(m, &p, &t); if v["e"] == "call" { let l = m.span().end(); v["end"] = json!(format!("{}:{}", l.line, l.column + 1)); } (s, v) }
|
|
325
|
+
Expr::Struct(s) => {
|
|
326
|
+
// An enum's variant with fields (an error's payload, say): a value the subset keeps only where nothing reads it.
|
|
327
|
+
if s.path.segments.len() >= 2 && self.enums.contains_key(&s.path.segments[s.path.segments.len() - 2].ident.to_string()) {
|
|
328
|
+
let mut pre = vec![];
|
|
329
|
+
for f in &s.fields { let (mut a, _) = self.expr(&f.expr); pre.append(&mut a); }
|
|
330
|
+
return (pre, json!({"e": "opaque", "why": format!("{t}: an enum variant with data"), "p": p}))
|
|
331
|
+
}
|
|
332
|
+
let name = last_ident(&s.path);
|
|
333
|
+
let name = if name == "Self" { self.self_ty.clone().unwrap_or(name) } else { name };
|
|
334
|
+
if s.rest.is_some() { return (vec![], no(&p, format!("{t}: a struct update (..rest)"))) }
|
|
335
|
+
let mut pre = vec![]; let mut fields = vec![];
|
|
336
|
+
for f in &s.fields {
|
|
337
|
+
let n = match &f.member { syn::Member::Named(n) => n.to_string(), _ => return (vec![], no(&p, format!("{t}: a tuple struct"))) };
|
|
338
|
+
let (mut a, v) = self.expr(&f.expr); pre.append(&mut a);
|
|
339
|
+
let v = if is_place(&v) { json!({"e": "copy", "x": v, "p": p}) } else { v };
|
|
340
|
+
fields.push(json!([n, v]));
|
|
341
|
+
}
|
|
342
|
+
self.rec(&name);
|
|
343
|
+
(pre, json!({"e": "new", "rec": name, "fields": fields, "p": p, "text": t}))
|
|
344
|
+
}
|
|
345
|
+
Expr::Closure(c) => self.closure(c, &p),
|
|
346
|
+
Expr::Macro(m) => { let (pre, v) = self.mac(&m.mac, m.span()); (pre, if v.is_null() { json!({"e": "unit", "p": p}) } else { v }) }
|
|
347
|
+
Expr::Let(_) => (vec![], no(&p, format!("{t}: a let outside an if"))),
|
|
348
|
+
Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => (vec![sno(&p, "a loop".into())], json!({"e": "unit", "p": p})),
|
|
349
|
+
Expr::Await(_) | Expr::Async(_) => (vec![], no(&p, format!("{t}: async"))),
|
|
350
|
+
_ => (vec![], no(&p, format!("{t}: an expression outside the subset"))),
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
fn lit(&self, l: &Lit, p: &str) -> Option<Value> {
|
|
354
|
+
match l {
|
|
355
|
+
Lit::Int(i) => {
|
|
356
|
+
let v: i128 = i.base10_parse().ok()?;
|
|
357
|
+
let suffix = i.suffix();
|
|
358
|
+
let mut o = json!({"e": "int", "v": v.to_string(), "p": p});
|
|
359
|
+
if !suffix.is_empty() { o["ty"] = self.ty(&syn::parse_str::<Type>(suffix).ok()?); }
|
|
360
|
+
Some(o)
|
|
361
|
+
}
|
|
362
|
+
Lit::Bool(b) => Some(json!({"e": "bool", "v": b.value, "p": p})),
|
|
363
|
+
Lit::Str(s) => Some(json!({"e": "str", "v": s.value(), "p": p})),
|
|
364
|
+
_ => None,
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
fn path_expr(&mut self, path: &syn::Path, p: &str, t: &str) -> Value {
|
|
368
|
+
let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
|
|
369
|
+
if segs.len() == 1 {
|
|
370
|
+
let n = &segs[0];
|
|
371
|
+
if self.is_local(n) { return json!({"e": "var", "n": n, "p": p}) }
|
|
372
|
+
if n == "None" { return json!({"e": "none", "p": p}) }
|
|
373
|
+
if let Some(c) = self.consts.get(n) { let mut c = c.clone(); c["p"] = json!(p); return c }
|
|
374
|
+
if self.free.contains_key(n) { return json!({"e": "fn", "id": n, "p": p}) }
|
|
375
|
+
return json!({"e": "ext", "q": n, "text": t, "p": p})
|
|
376
|
+
}
|
|
377
|
+
let ty = if segs[0] == "Self" { self.self_ty.clone().unwrap_or_default() } else { segs[segs.len() - 2].clone() };
|
|
378
|
+
let last = segs.last().unwrap();
|
|
379
|
+
if let Some(e) = self.enums.get(&ty) {
|
|
380
|
+
if e.values.contains(last) { return json!({"e": "variant", "enum": ty, "v": last, "values": e.values, "discs": e.discs, "p": p}) }
|
|
381
|
+
}
|
|
382
|
+
if let Some(c) = self.consts.get(last) { if segs.len() == 2 && (segs[0] == "Self" || self.structs.contains_key(&segs[0])) { let mut c = c.clone(); c["p"] = json!(p); return c } }
|
|
383
|
+
if (ty == "Duration" && last == "ZERO") || (segs.len() >= 2 && segs[segs.len() - 2] == "Ordering") { return json!({"e": "int", "v": "0", "p": p, "ord": last}) }
|
|
384
|
+
if self.structs.contains_key(&ty) { self.rec(&ty); return json!({"e": "fn", "id": format!("{ty}::{last}"), "p": p}) }
|
|
385
|
+
// A method of an enum (an `impl From<u8> for State`, say): lowered as a function of its type.
|
|
386
|
+
if self.enums.contains_key(&ty) && self.methods.get(&ty).map(|ms| ms.iter().any(|m| m.2.sig.ident == last)).unwrap_or(false) {
|
|
387
|
+
let fid = format!("{ty}::{last}");
|
|
388
|
+
if !self.funcs.contains_key(&fid) {
|
|
389
|
+
self.funcs.insert(fid.clone(), Value::Null);
|
|
390
|
+
let (mfile, _, m) = self.methods[&ty].iter().find(|m| m.2.sig.ident == last).cloned().unwrap();
|
|
391
|
+
let saved = self.self_ty.replace(ty.clone());
|
|
392
|
+
let f = self.func(&mfile, &m.sig, &m.block, &m.attrs, None, &fid);
|
|
393
|
+
self.self_ty = saved;
|
|
394
|
+
self.funcs.insert(fid.clone(), f);
|
|
395
|
+
}
|
|
396
|
+
return json!({"e": "fn", "id": fid, "p": p})
|
|
397
|
+
}
|
|
398
|
+
json!({"e": "ext", "q": segs.join("::"), "text": t, "p": p})
|
|
399
|
+
}
|
|
400
|
+
fn binary(&mut self, b: &syn::ExprBinary, p: &str, t: &str) -> (Vec<Value>, Value) {
|
|
401
|
+
let compound = |op: &BinOp| -> Option<&'static str> { Some(match op { BinOp::AddAssign(_) => "+", BinOp::SubAssign(_) => "-", BinOp::MulAssign(_) => "*", BinOp::DivAssign(_) => "/", BinOp::RemAssign(_) => "%", _ => return None }) };
|
|
402
|
+
if let Some(op) = compound(&b.op) {
|
|
403
|
+
let (mut pre, v) = self.expr(&b.right);
|
|
404
|
+
let (mut tp, to) = self.expr(&b.left);
|
|
405
|
+
pre.append(&mut tp);
|
|
406
|
+
let x = json!({"e": "bin", "op": op, "x": to.clone(), "y": v, "p": p, "text": t, "ovf": "trap", "div": "trunc"});
|
|
407
|
+
pre.push(json!({"s": "set", "p": p, "to": to, "x": x}));
|
|
408
|
+
return (pre, json!({"e": "unit", "p": p}))
|
|
409
|
+
}
|
|
410
|
+
let (mut pre, l) = self.expr(&b.left);
|
|
411
|
+
let (rpre, r) = self.expr(&b.right);
|
|
412
|
+
let logical = match b.op { BinOp::And(_) => Some("and"), BinOp::Or(_) => Some("or"), _ => None };
|
|
413
|
+
if let Some(lg) = logical {
|
|
414
|
+
if rpre.is_empty() { return (pre, json!({"e": lg, "xs": [l, r], "p": p, "strict": true})) }
|
|
415
|
+
// The right side has statements: an if over a temporary, as the short circuit runs it.
|
|
416
|
+
let tmp = self.temp();
|
|
417
|
+
let var = json!({"e": "var", "n": tmp, "p": p});
|
|
418
|
+
let mut then = rpre; then.push(json!({"s": "set", "p": p, "to": var, "x": r}));
|
|
419
|
+
let short = json!({"s": "set", "p": p, "to": var, "x": {"e": "bool", "v": lg == "or", "p": p}});
|
|
420
|
+
let (a, bb) = if lg == "and" { (then, vec![short]) } else { (vec![short], then) };
|
|
421
|
+
pre.push(json!({"s": "if", "p": p, "c": l, "then": a, "else": bb}));
|
|
422
|
+
return (pre, var)
|
|
423
|
+
}
|
|
424
|
+
let mut rpre = rpre; pre.append(&mut rpre);
|
|
425
|
+
let arith = match b.op { BinOp::Add(_) => Some("+"), BinOp::Sub(_) => Some("-"), BinOp::Mul(_) => Some("*"), BinOp::Div(_) => Some("/"), BinOp::Rem(_) => Some("%"), _ => None };
|
|
426
|
+
if let Some(op) = arith { return (pre, json!({"e": "bin", "op": op, "x": l, "y": r, "p": p, "text": t, "ovf": "trap", "div": "trunc"})) }
|
|
427
|
+
let cmp = match b.op { BinOp::Lt(_) => "<", BinOp::Le(_) => "<=", BinOp::Gt(_) => ">", BinOp::Ge(_) => ">=", BinOp::Eq(_) => "==", BinOp::Ne(_) => "!=", _ => return (pre, no(p, format!("{t}: a bit operation"))) };
|
|
428
|
+
(pre, json!({"e": "cmp", "op": cmp, "x": l, "y": r, "p": p, "text": t}))
|
|
429
|
+
}
|
|
430
|
+
// An if used as a statement or a value: its branches' statements, each ending by setting a temporary.
|
|
431
|
+
fn if_expr(&mut self, i: &syn::ExprIf, p: &str) -> (Vec<Value>, Value) {
|
|
432
|
+
let tmp = self.temp();
|
|
433
|
+
let var = json!({"e": "var", "n": tmp, "p": p});
|
|
434
|
+
let (mut pre, cond, binds) = self.cond(&i.cond, p);
|
|
435
|
+
let (mut then, tv) = { self.locals.push(BTreeSet::new()); let r = self.block(&i.then_branch); self.locals.pop(); r };
|
|
436
|
+
let mut tb = binds; tb.append(&mut then);
|
|
437
|
+
tb.push(json!({"s": "set", "p": p, "to": var, "x": tv}));
|
|
438
|
+
let mut eb = vec![];
|
|
439
|
+
if let Some((_, e)) = &i.else_branch { let (mut s, v) = self.expr(e); eb.append(&mut s); eb.push(json!({"s": "set", "p": p, "to": var, "x": v})) }
|
|
440
|
+
else { eb.push(json!({"s": "set", "p": p, "to": var, "x": {"e": "unit", "p": p}})) }
|
|
441
|
+
pre.push(json!({"s": "if", "p": p, "c": cond, "then": tb, "else": eb}));
|
|
442
|
+
(pre, var)
|
|
443
|
+
}
|
|
444
|
+
// A condition: a boolean, or `let PAT = e` (its test, and the bindings it makes where it holds).
|
|
445
|
+
fn cond(&mut self, c: &Expr, p: &str) -> (Vec<Value>, Value, Vec<Value>) {
|
|
446
|
+
if let Expr::Let(l) = c {
|
|
447
|
+
let (mut pre, v) = self.expr(&l.expr);
|
|
448
|
+
let tmp = self.temp();
|
|
449
|
+
pre.push(json!({"s": "set", "p": p, "to": {"e": "var", "n": tmp, "p": p}, "x": v}));
|
|
450
|
+
let (test, binds) = self.pattern(&l.pat, &json!({"e": "var", "n": tmp, "p": p}), p);
|
|
451
|
+
return (pre, test, binds)
|
|
452
|
+
}
|
|
453
|
+
let (pre, v) = self.expr(c);
|
|
454
|
+
(pre, v, vec![])
|
|
455
|
+
}
|
|
456
|
+
// A pattern against a value: the test, and the bindings (set where it holds).
|
|
457
|
+
fn pattern(&mut self, pat: &Pat, v: &Value, p: &str) -> (Value, Vec<Value>) {
|
|
458
|
+
let t = json!({"e": "bool", "v": true, "p": p});
|
|
459
|
+
match pat {
|
|
460
|
+
Pat::Wild(_) => (t, vec![]),
|
|
461
|
+
Pat::Ident(i) if i.subpat.is_none() => {
|
|
462
|
+
let n = i.ident.to_string();
|
|
463
|
+
if n == "None" { return (json!({"e": "is", "x": v, "k": "none", "p": p}), vec![]) }
|
|
464
|
+
self.bind_pat(pat);
|
|
465
|
+
(t, vec![json!({"s": "set", "p": p, "to": {"e": "var", "n": n, "p": p}, "x": v})])
|
|
466
|
+
}
|
|
467
|
+
Pat::Ident(i) => { let (tt, mut b) = self.pattern(&i.subpat.as_ref().unwrap().1, v, p); self.bind_pat(pat); b.insert(0, json!({"s": "set", "p": p, "to": {"e": "var", "n": i.ident.to_string(), "p": p}, "x": v})); (tt, b) }
|
|
468
|
+
Pat::Lit(l) => (json!({"e": "cmp", "op": "==", "x": v, "y": self.lit(&l.lit, p).unwrap_or_else(|| no(p, "a literal pattern".into())), "p": p}), vec![]),
|
|
469
|
+
Pat::Or(o) => {
|
|
470
|
+
let mut tests = vec![];
|
|
471
|
+
for c in &o.cases { let (tt, b) = self.pattern(c, v, p); if !b.is_empty() { return (no(p, format!("{}: an or-pattern that binds", text(pat))), vec![]) } tests.push(tt) }
|
|
472
|
+
(json!({"e": "or", "xs": tests, "p": p, "strict": true}), vec![])
|
|
473
|
+
}
|
|
474
|
+
Pat::Path(pp) => {
|
|
475
|
+
let segs: Vec<String> = pp.path.segments.iter().map(|s| s.ident.to_string()).collect();
|
|
476
|
+
if segs.len() == 1 && segs[0] == "None" { return (json!({"e": "is", "x": v, "k": "none", "p": p}), vec![]) }
|
|
477
|
+
(json!({"e": "cmp", "op": "==", "x": v, "y": self.path_expr(&pp.path, p, &text(pat)), "p": p}), vec![])
|
|
478
|
+
}
|
|
479
|
+
Pat::TupleStruct(ts) => {
|
|
480
|
+
let name = last_ident(&ts.path);
|
|
481
|
+
let k = match name.as_str() { "Some" => "some", "Ok" => "ok", "Err" => "err", _ => return (no(p, format!("{}: a variant with data", text(pat))), vec![]) };
|
|
482
|
+
if ts.elems.len() != 1 { return (no(p, format!("{}: a pattern of {} values", text(pat), ts.elems.len())), vec![]) }
|
|
483
|
+
let inner = json!({"e": "unwrap", "x": v, "k": k, "p": p});
|
|
484
|
+
let (tt, b) = self.pattern(&ts.elems[0], &inner, p);
|
|
485
|
+
(json!({"e": "and", "xs": [{"e": "is", "x": v, "k": k, "p": p}, tt], "p": p, "strict": true}), b)
|
|
486
|
+
}
|
|
487
|
+
Pat::Reference(r) => self.pattern(&r.pat, v, p),
|
|
488
|
+
Pat::Range(_) | Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_) | _ => (no(p, format!("{}: a pattern outside the subset", text(pat))), vec![]),
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
fn match_expr(&mut self, m: &syn::ExprMatch, p: &str) -> (Vec<Value>, Value) {
|
|
492
|
+
let (mut pre, v) = self.expr(&m.expr);
|
|
493
|
+
let scrut = self.temp();
|
|
494
|
+
pre.push(json!({"s": "set", "p": p, "to": {"e": "var", "n": scrut, "p": p}, "x": v}));
|
|
495
|
+
let sv = json!({"e": "var", "n": scrut, "p": p});
|
|
496
|
+
let res = self.temp();
|
|
497
|
+
let rv = json!({"e": "var", "n": res, "p": p});
|
|
498
|
+
// Arms in order: each an if over the ones before it not matching (the last falling to a failure: Rust's match
|
|
499
|
+
// is exhaustive, so that branch is unreachable where the types are the code's).
|
|
500
|
+
let mut chain: Vec<Value> = vec![json!({"s": "fail", "p": p, "why": "a match no arm takes (unreachable for the code's own values)"})];
|
|
501
|
+
for arm in m.arms.iter().rev() {
|
|
502
|
+
let ap = self.at(arm.span());
|
|
503
|
+
self.locals.push(BTreeSet::new());
|
|
504
|
+
let (mut test, mut binds) = self.pattern(&arm.pat, &sv, &ap);
|
|
505
|
+
let guard = arm.guard.as_ref().map(|(_, g)| self.expr(g));
|
|
506
|
+
let (mut body, bv) = self.expr(&arm.body);
|
|
507
|
+
self.locals.pop();
|
|
508
|
+
let mut then = vec![];
|
|
509
|
+
if let Some((gpre, gv)) = guard {
|
|
510
|
+
// A guard reads the bindings: tested inside them, falling to the next arms where it fails.
|
|
511
|
+
let mut inner = gpre; inner.append(&mut body); inner.push(json!({"s": "set", "p": ap, "to": rv, "x": bv}));
|
|
512
|
+
then.append(&mut binds);
|
|
513
|
+
then.push(json!({"s": "if", "p": ap, "c": gv, "then": inner, "else": chain.clone()}));
|
|
514
|
+
} else { then.append(&mut binds); then.append(&mut body); then.push(json!({"s": "set", "p": ap, "to": rv, "x": bv})); }
|
|
515
|
+
if test["e"] == "bool" && test["v"] == true { chain = then; continue }
|
|
516
|
+
chain = vec![json!({"s": "if", "p": ap, "c": test, "then": then, "else": chain})];
|
|
517
|
+
}
|
|
518
|
+
pre.append(&mut chain);
|
|
519
|
+
(pre, rv)
|
|
520
|
+
}
|
|
521
|
+
fn closure(&mut self, c: &syn::ExprClosure, p: &str) -> (Vec<Value>, Value) {
|
|
522
|
+
// A closure: lifted to a function of its parameters and the locals it reads (by value at its making; one that
|
|
523
|
+
// assigns to them is refused).
|
|
524
|
+
let id = format!("{}#closure{}", self.fid, self.lifted.len() + 1);
|
|
525
|
+
let mut params = vec![];
|
|
526
|
+
let mut names = BTreeSet::new();
|
|
527
|
+
for a in &c.inputs {
|
|
528
|
+
match a {
|
|
529
|
+
Pat::Ident(i) => { names.insert(i.ident.to_string()); params.push(json!({"name": i.ident.to_string(), "t": {"k": "any"}})) }
|
|
530
|
+
Pat::Type(t) => { if let Pat::Ident(i) = &*t.pat { names.insert(i.ident.to_string()); params.push(json!({"name": i.ident.to_string(), "t": self.ty(&t.ty)})) } }
|
|
531
|
+
_ => return (vec![], no(p, "a closure's pattern parameter".into())),
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
let caps: Vec<String> = self.locals.iter().flatten().filter(|n| !n.starts_with('$') && !names.contains(*n) && mentions(&c.body, n)).cloned().collect::<BTreeSet<_>>().into_iter().collect();
|
|
535
|
+
if caps.iter().any(|n| assigns(&c.body, n)) { return (vec![], no(p, "a closure that assigns to what it captures".into())) }
|
|
536
|
+
for n in &caps { params.push(json!({"name": n, "t": {"k": "any"}, "cap": true})) }
|
|
537
|
+
let mut scope: BTreeSet<String> = names; scope.extend(caps.iter().cloned());
|
|
538
|
+
let saved_locals = std::mem::replace(&mut self.locals, vec![scope]);
|
|
539
|
+
let saved_tmp = self.tmp;
|
|
540
|
+
let saved_fid = std::mem::replace(&mut self.fid, id.clone());
|
|
541
|
+
let (mut body, v) = match &*c.body { Expr::Block(b) => self.block(&b.block), e => self.expr(e) };
|
|
542
|
+
body.push(json!({"s": "ret", "p": p, "x": v}));
|
|
543
|
+
self.locals = saved_locals; self.tmp = saved_tmp; self.fid = saved_fid;
|
|
544
|
+
let f = json!({"id": id, "name": id, "p": p, "span": [self.file, c.span().start().line, c.span().end().line], "params": params, "ret": {"k": "any"}, "body": body, "async": false, "static": true, "decorators": []});
|
|
545
|
+
self.lifted.push((id.clone(), f));
|
|
546
|
+
(vec![], json!({"e": "closure", "id": id, "caps": caps, "p": p}))
|
|
547
|
+
}
|
|
548
|
+
fn args(&mut self, xs: &syn::punctuated::Punctuated<Expr, syn::token::Comma>) -> (Vec<Value>, Vec<Value>) {
|
|
549
|
+
let mut pre = vec![]; let mut out = vec![];
|
|
550
|
+
for a in xs { let (mut s, v) = self.expr(a); pre.append(&mut s); out.push(if is_place(&v) { json!({"e": "copy", "x": v, "p": v["p"]}) } else { v }) }
|
|
551
|
+
(pre, out)
|
|
552
|
+
}
|
|
553
|
+
fn call(&mut self, c: &syn::ExprCall, p: &str, t: &str) -> (Vec<Value>, Value) {
|
|
554
|
+
let (mut pre, args) = self.args(&c.args);
|
|
555
|
+
let f = match &*c.func { Expr::Path(x) => x.path.clone(), _ => { let (mut fp, fv) = self.expr(&c.func); pre.append(&mut fp); return (pre, json!({"e": "call", "f": fv, "args": args, "kw": [], "p": p, "text": t})) } };
|
|
556
|
+
let segs: Vec<String> = f.segments.iter().map(|s| s.ident.to_string()).collect();
|
|
557
|
+
let name = segs.last().unwrap().as_str();
|
|
558
|
+
let a0 = args.first().cloned().unwrap_or(Value::Null);
|
|
559
|
+
let k = |kind: &str| json!({"e": kind, "x": a0, "p": p});
|
|
560
|
+
let v = match (segs.len(), name) {
|
|
561
|
+
(1, "Some") => k("some"), (1, "Ok") => k("ok"), (1, "Err") => k("err"),
|
|
562
|
+
(_, "max") | (_, "min") if segs.iter().any(|s| s == "cmp") || (segs.len() == 1 && !self.free.contains_key(name)) => json!({"e": "call", "f": {"e": "builtin", "n": name, "p": p}, "args": args, "kw": [], "p": p, "text": t}),
|
|
563
|
+
(2, _) if segs[0] == "Instant" && name == "now" => json!({"e": "clock", "p": p}),
|
|
564
|
+
// An atomic's or a lock's constructor: the value it holds (read and written as the field it is).
|
|
565
|
+
(_, "new") if segs.len() >= 2 && (segs[segs.len() - 2].starts_with("Atomic") || ["Mutex", "RwLock", "Cell", "RefCell"].contains(&segs[segs.len() - 2].as_str())) => a0.clone(),
|
|
566
|
+
(2, _) if segs[0] == "Duration" => {
|
|
567
|
+
let unit = match name { "from_secs" => 1_000_000_000i64, "from_millis" => 1_000_000, "from_micros" => 1_000, "from_nanos" => 1, _ => 0 };
|
|
568
|
+
if unit == 0 { no(p, format!("{t}: Duration::{name}")) } else { json!({"e": "bin", "op": "*", "x": a0, "y": {"e": "int", "v": unit.to_string(), "p": p}, "p": p, "text": t, "ovf": "trap", "dur": true}) }
|
|
569
|
+
}
|
|
570
|
+
(2, "from") if ["u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"].contains(&segs[0].as_str()) => json!({"e": "cast", "x": a0, "ty": self.ty(&syn::parse_str::<Type>(&segs[0]).unwrap()), "p": p, "text": t}),
|
|
571
|
+
_ => {
|
|
572
|
+
let fv = self.path_expr(&f, p, t);
|
|
573
|
+
if fv["e"] == "var" { json!({"e": "call", "f": fv, "args": args, "kw": [], "p": p, "text": t}) }
|
|
574
|
+
else { json!({"e": "call", "f": fv, "args": args, "kw": [], "p": p, "text": t}) }
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
(pre, v)
|
|
578
|
+
}
|
|
579
|
+
fn method(&mut self, m: &syn::ExprMethodCall, p: &str, t: &str) -> (Vec<Value>, Value) {
|
|
580
|
+
let (mut pre, r) = self.expr(&m.receiver);
|
|
581
|
+
let (mut ap, args) = self.args(&m.args);
|
|
582
|
+
pre.append(&mut ap);
|
|
583
|
+
let name = m.method.to_string();
|
|
584
|
+
let a = |i: usize| args.get(i).cloned().unwrap_or(Value::Null);
|
|
585
|
+
let bin = |op: &str, ovf: &str| json!({"e": "bin", "op": op, "x": r, "y": a(0), "p": p, "text": t, "ovf": ovf, "div": "trunc"});
|
|
586
|
+
let v = match name.as_str() {
|
|
587
|
+
// Options and Results.
|
|
588
|
+
"is_some" => json!({"e": "is", "x": r, "k": "some", "p": p}), "is_none" => json!({"e": "is", "x": r, "k": "none", "p": p}),
|
|
589
|
+
"is_ok" => json!({"e": "is", "x": r, "k": "ok", "p": p}), "is_err" => json!({"e": "is", "x": r, "k": "err", "p": p}),
|
|
590
|
+
"unwrap" | "expect" if m.receiver.to_token_stream().to_string().ends_with("lock ()") => r,
|
|
591
|
+
"unwrap" | "expect" => json!({"e": "expect", "x": r, "p": p, "text": t}),
|
|
592
|
+
"unwrap_or" => json!({"e": "opt_or", "x": r, "d": a(0), "p": p}),
|
|
593
|
+
"unwrap_or_default" => json!({"e": "opt_or", "x": r, "d": {"e": "zero", "p": p}, "p": p}),
|
|
594
|
+
"ok" => json!({"e": "res_ok", "x": r, "p": p}),
|
|
595
|
+
// Integers (and Durations and Instants, which are integers here).
|
|
596
|
+
"min" | "max" => json!({"e": "call", "f": {"e": "builtin", "n": name, "p": p}, "args": [r, a(0)], "kw": [], "p": p, "text": t}),
|
|
597
|
+
"abs" => json!({"e": "call", "f": {"e": "builtin", "n": "abs", "p": p}, "args": [r], "kw": [], "p": p, "text": t}),
|
|
598
|
+
"saturating_add" => bin("+", "sat"), "saturating_sub" => bin("-", "sat"), "saturating_mul" => bin("*", "sat"),
|
|
599
|
+
"wrapping_add" => bin("+", "wrap"), "wrapping_sub" => bin("-", "wrap"), "wrapping_mul" => bin("*", "wrap"),
|
|
600
|
+
"checked_add" => bin("+", "checked"), "checked_sub" => bin("-", "checked"), "checked_mul" => bin("*", "checked"), "checked_div" => bin("/", "checked"),
|
|
601
|
+
"duration_since" | "saturating_duration_since" => bin("-", "sat0"),
|
|
602
|
+
"checked_duration_since" => bin("-", "checked0"),
|
|
603
|
+
"elapsed" => json!({"e": "bin", "op": "-", "x": {"e": "clock", "p": p}, "y": r, "p": p, "text": t, "ovf": "sat0"}),
|
|
604
|
+
"as_nanos" => r, "as_micros" => json!({"e": "bin", "op": "/", "x": r, "y": {"e": "int", "v": "1000", "p": p}, "p": p, "ovf": "trap", "div": "trunc"}),
|
|
605
|
+
"as_millis" => json!({"e": "bin", "op": "/", "x": r, "y": {"e": "int", "v": "1000000", "p": p}, "p": p, "ovf": "trap", "div": "trunc"}),
|
|
606
|
+
"as_secs" => json!({"e": "bin", "op": "/", "x": r, "y": {"e": "int", "v": "1000000000", "p": p}, "p": p, "ovf": "trap", "div": "trunc"}),
|
|
607
|
+
"is_zero" => json!({"e": "cmp", "op": "==", "x": r, "y": {"e": "int", "v": "0", "p": p}, "p": p}),
|
|
608
|
+
// Atomics: a read-modify-write of the field they are (one step is one call: the claim is for calls that don't
|
|
609
|
+
// interleave).
|
|
610
|
+
"load" | "store" | "fetch_add" | "fetch_sub" | "swap" | "compare_exchange" | "compare_exchange_weak" | "fetch_max" | "fetch_min" if args.iter().any(|x| x.get("ord").is_some()) =>
|
|
611
|
+
json!({"e": "rmw", "op": name, "place": r, "args": args.iter().filter(|x| x.get("ord").is_none()).cloned().collect::<Vec<_>>(), "p": p, "text": t}),
|
|
612
|
+
// A Mutex's lock is its value (a step holds it to its end).
|
|
613
|
+
"lock" | "read" | "write" if args.is_empty() => json!({"e": "lock", "x": r, "p": p}),
|
|
614
|
+
"clone" | "to_owned" | "into" | "to_string" | "as_str" if args.is_empty() => json!({"e": "copy", "x": r, "p": p}),
|
|
615
|
+
_ => json!({"e": "call", "f": {"e": "get", "x": r, "f": name, "p": p, "text": format!("{}.{name}", text(&m.receiver))}, "args": args, "kw": [], "p": p, "text": t}),
|
|
616
|
+
};
|
|
617
|
+
(pre, v)
|
|
618
|
+
}
|
|
619
|
+
fn mac(&mut self, m: &syn::Macro, s: Span) -> (Vec<Value>, Value) {
|
|
620
|
+
let p = self.at(s);
|
|
621
|
+
let name = last_ident(&m.path);
|
|
622
|
+
let args: Vec<Expr> = m.parse_body_with(syn::punctuated::Punctuated::<Expr, syn::token::Comma>::parse_terminated).map(|x| x.into_iter().collect()).unwrap_or_default();
|
|
623
|
+
let fail = |why: String| json!({"s": "fail", "p": p, "why": why});
|
|
624
|
+
match name.as_str() {
|
|
625
|
+
"panic" | "unreachable" | "todo" | "unimplemented" => (vec![fail(format!("{name}!"))], Value::Null),
|
|
626
|
+
"assert" | "debug_assert" if !args.is_empty() => {
|
|
627
|
+
let (mut pre, c) = self.expr(&args[0]);
|
|
628
|
+
pre.push(json!({"s": "if", "p": p, "c": c, "then": [], "else": [fail(format!("{name}!({})", text(&args[0])))]}));
|
|
629
|
+
(pre, Value::Null)
|
|
630
|
+
}
|
|
631
|
+
"assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne" if args.len() >= 2 => {
|
|
632
|
+
let (mut pre, a) = self.expr(&args[0]); let (mut bp, b) = self.expr(&args[1]); pre.append(&mut bp);
|
|
633
|
+
let op = if name.ends_with("_eq") { "==" } else { "!=" };
|
|
634
|
+
pre.push(json!({"s": "if", "p": p, "c": {"e": "cmp", "op": op, "x": a, "y": b, "p": p}, "then": [], "else": [fail(format!("{name}!"))]}));
|
|
635
|
+
(pre, Value::Null)
|
|
636
|
+
}
|
|
637
|
+
"format" | "println" | "eprintln" | "print" | "eprint" | "write" | "writeln" | "trace" | "debug" | "info" | "warn" | "error" => (vec![], json!({"e": "opaque", "why": format!("{name}!(...): a formatted string or a log line"), "p": p})),
|
|
638
|
+
"matches" if args.len() >= 1 => (vec![], no(&p, "matches!".into())),
|
|
639
|
+
_ => (vec![], no(&p, format!("{name}!: a macro the subset doesn't read"))),
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
fn mentions(e: &Expr, n: &str) -> bool { e.to_token_stream().into_iter().any(|t| tok_has(&t, n)) }
|
|
644
|
+
fn tok_has(t: &proc_macro2::TokenTree, n: &str) -> bool { match t { proc_macro2::TokenTree::Ident(i) => i == n, proc_macro2::TokenTree::Group(g) => g.stream().into_iter().any(|x| tok_has(&x, n)), _ => false } }
|
|
645
|
+
fn assigns(e: &Expr, n: &str) -> bool {
|
|
646
|
+
let s = e.to_token_stream().to_string();
|
|
647
|
+
let mut i = 0;
|
|
648
|
+
while let Some(k) = s[i..].find(n) {
|
|
649
|
+
let at = i + k; let rest = &s[at + n.len()..];
|
|
650
|
+
let before_ok = at == 0 || !s[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_' || c == '.');
|
|
651
|
+
if before_ok && (rest.starts_with(" = ") || rest.starts_with(" += ") || rest.starts_with(" -= ") || rest.starts_with(" *= ")) { return true }
|
|
652
|
+
i = at + n.len();
|
|
653
|
+
}
|
|
654
|
+
false
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
fn main() {
|
|
658
|
+
let req: Value = serde_json::from_str(&std::env::args().nth(1).expect("a request")).expect("JSON");
|
|
659
|
+
let root = PathBuf::from(req["root"].as_str().unwrap());
|
|
660
|
+
let files = match Reader::load(&root) { Ok(f) => f, Err(e) => { println!("{}", json!({"error": e})); return } };
|
|
661
|
+
let mut r = Reader { files, smod: BTreeMap::new(), structs: BTreeMap::new(), enums: BTreeMap::new(), consts: BTreeMap::new(), recs: Map::new(), funcs: Map::new(), methods: BTreeMap::new(), free: BTreeMap::new(), fmod: BTreeMap::new(), file: String::new(), tmp: 0, locals: vec![], self_ty: None, lifted: vec![], fid: String::new() };
|
|
662
|
+
r.index();
|
|
663
|
+
for n in r.structs.keys().cloned().collect::<Vec<_>>() { r.rec(&n); }
|
|
664
|
+
let mut entries = vec![];
|
|
665
|
+
let mut entry_file = String::new();
|
|
666
|
+
// (no names: every struct of the crate, for the entry inferred)
|
|
667
|
+
let all: Vec<Value> = r.structs.keys().map(|k| json!(k)).collect();
|
|
668
|
+
let names = req["names"].as_array().unwrap();
|
|
669
|
+
for n in if names.is_empty() { &all } else { names } {
|
|
670
|
+
let n = n.as_str().unwrap();
|
|
671
|
+
if r.structs.contains_key(n) { entry_file = r.structs[n].0.clone(); r.rec(n); entries.push(json!({"k": "class", "rec": n})); }
|
|
672
|
+
else if let Some((file, f)) = r.free.get(n).cloned() { entry_file = file.clone(); let fv = r.func(&file, &f.sig, &f.block, &f.attrs, None, n); r.funcs.insert(n.to_string(), fv); entries.push(json!({"k": "func", "id": n})); }
|
|
673
|
+
else { entries.push(json!({"k": "missing", "name": n})); }
|
|
674
|
+
}
|
|
675
|
+
// The crate's free functions, for the calls the entries make.
|
|
676
|
+
for (n, (file, f)) in r.free.clone() { if !r.funcs.contains_key(&n) { let fv = r.func(&file, &f.sig, &f.block, &f.attrs, None, &n); r.funcs.insert(n, fv); } }
|
|
677
|
+
for (id, f) in std::mem::take(&mut r.lifted) { r.funcs.insert(id, f); }
|
|
678
|
+
let recs: Map<String, Value> = r.recs.into_iter().filter(|(_, v)| !v.is_null()).collect();
|
|
679
|
+
let enums: Map<String, Value> = r.enums.iter().map(|(k, e)| (k.clone(), json!({"values": e.values, "discs": e.discs, "data": e.data}))).collect();
|
|
680
|
+
println!("{}", json!({"lang": "rust", "file": Path::new(&entry_file).file_name().map(|x| x.to_string_lossy().to_string()).unwrap_or_default(), "path": root.join(&entry_file).display().to_string(), "module": "crate", "root": root.display().to_string(), "entries": entries, "fmods": r.fmod, "recs": recs, "funcs": r.funcs, "enums": enums}));
|
|
681
|
+
}
|