nandi/rustnimpublic Fork 0
af6e50f646055dc5b291c9e602bc9ee01874f9d6
Commits
Clone
git clone https://git.rickub.com/nandi/rustnim.git
git clone ssh://git@rickub.com/nandi/rustnim.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

lower.rs · 5264 lines · 222.7 KBRust Blame HistoryRaw
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1//! Rust AST -> Nim source.
2//!
3//! The governing rule is in DESIGN.md and it shapes every function here:
4//! anything whose Rust semantics cannot be reproduced exactly in Nim returns
5//! `Err` with a reason. Nothing is emitted on a guess. Where a construct maps
6//! one-to-one (signed `shr`, unsigned wrapping, truncating `div`/`mod`) the
7//! mapping is direct and there is a comment saying why that is safe.
8
9use crate::fmt;
10use crate::ty::{self, Nim};
11use std::collections::HashMap;
12use syn::{
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago13 BinOp, Expr, FnArg, GenericArgument, Item, Lit, Local, Pat, ReturnType, Stmt, UnOp,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago14};
15
16// --------------------------------------------------------------- vocabulary
17
18/// Nim keywords. Rust code may legally use any of these as an identifier.
19const NIM_KEYWORDS: &[&str] = &[
20 "addr", "and", "as", "asm", "bind", "block", "break", "case", "cast",
21 "concept", "const", "continue", "converter", "defer", "discard", "distinct",
22 "div", "do", "elif", "else", "end", "enum", "except", "export", "finally",
23 "for", "from", "func", "if", "import", "in", "include", "interface", "is",
24 "isnot", "iterator", "let", "macro", "method", "mixin", "mod", "nil", "not",
25 "notin", "object", "of", "or", "out", "proc", "ptr", "raise", "ref",
26 "return", "shl", "shr", "static", "template", "try", "tuple", "type",
27 "using", "var", "when", "while", "xor", "result", "echo",
28];
29
30fn ident(name: &str) -> String {
31 if NIM_KEYWORDS.contains(&name) {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago32 return format!("{name}_r");
33 }
34 // Nim identifiers may not begin with an underscore, and may not contain
35 // two in a row. Rust uses both freely (`_unused`, `__private`).
36 let mut out = String::new();
37 let mut last_us = false;
38 for (i, c) in name.chars().enumerate() {
39 if c == '_' {
40 if i == 0 {
41 out.push('u');
42 out.push('_');
43 last_us = true;
44 continue;
45 }
46 if last_us {
47 continue;
48 }
49 last_us = true;
50 out.push('_');
51 } else {
52 last_us = false;
53 out.push(c);
54 }
55 }
56 if out.ends_with('_') {
57 out.push('x');
58 }
59 out
60}
61
62/// A `for`-loop source, resolved from a chain of iterator adaptors.
63///
64/// Rust's slice iterators are lazy and compose; Nim's `for` is over one
65/// sequence. So a chain is resolved into this shape and then emitted as a
66/// single index loop, with each binding becoming an *lvalue* into the original
67/// container. That is what makes `*dst = v` through `iter_mut()` write back to
68/// the caller's slice rather than to a copy.
69#[derive(Clone, Debug)]
70enum Iter {
71 /// `a..b` / `a..=b`.
72 Range { lo: String, hi: String, closed: bool, ty: Option<Nim> },
73 /// `for x in a`, `a.iter()`, `a.iter_mut()`. `off`/`len` let the same
74 /// shape cover a subslice view. `mutable` only affects whether the binding
75 /// may be assigned through.
76 Elems { code: String, off: String, len: String, elem: Option<Nim>, mutable: bool },
77 /// `a.chunks_exact(k)` / `chunks_exact_mut(k)`: the binding is a window of
78 /// `k` elements starting at `k * i`.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago79 Chunks { code: String, base: String, len: String, k: String, elem: Option<Nim>, mutable: bool },
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago80 /// `a.windows(k)`: like `Chunks` but advancing one element at a time.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago81 Windows { code: String, base: String, len: String, k: String, elem: Option<Nim> },
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago82 /// `.enumerate()` — the index is the first half of the pair.
83 Enumerate(Box<Iter>),
84 /// `.zip(other)` — stops at the shorter, as Rust's does.
85 Zip(Box<Iter>, Box<Iter>),
86}
87
88impl Iter {
89 /// The number of iterations, as a Nim expression in terms of the loop's
90 /// own containers.
91 fn len(&self) -> String {
92 match self {
93 Iter::Range { lo, hi, closed, .. } => {
94 let n = format!("(int({hi}) - int({lo}))");
95 if *closed { format!("({n} + 1)") } else { n }
96 }
97 Iter::Elems { len, .. } => len.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago98 Iter::Chunks { k, len, .. } => format!("({} div int({}))", len, k),
99 Iter::Windows { len, k, .. } => format!("(max(0, {} - int({}) + 1))", len, k),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago100 Iter::Enumerate(i) => i.len(),
101 Iter::Zip(a, b) => format!("min({}, {})", a.len(), b.len()),
102 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago103 }
104}
105
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago106/// How a `for`-loop pattern name refers back into the container it came from.
107#[derive(Clone, Debug)]
108enum Alias {
109 /// The name stands for this Nim lvalue expression.
110 Value { code: String, ty: Option<Nim> },
111 /// The name stands for a window: `code[off .. off + len - 1]`.
112 Window { code: String, off: String, len: String, elem: Option<Nim> },
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago113 /// The name stands for an iterator that has not been consumed yet, as in
114 /// `let it = xs.chunks_exact(k);`. Rust's iterators are values; ours are
115 /// resolved chains, so the chain is carried until a `for` consumes it.
116 Iterator(Box<Iter>),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago117}
118
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago119/// A lowered expression: its Nim text, and its type where we know it.
120///
121/// The type is not decoration. Nim needs it to pick `div` over `/`, to size a
122/// `cast`, and to annotate every binding so that Nim's own type checker
123/// catches a mistake in this file rather than letting it through as output
124/// that runs and is wrong.
125#[derive(Clone, Debug)]
126struct Val {
127 code: String,
128 ty: Option<Nim>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago129 /// Set when the value *is* a slice view rather than a Nim value: binding
130 /// it introduces an alias, not a copy.
131 window: Option<Alias>,
132 /// For `get`/`get_mut`: the condition under which the `Option` is `Some`,
133 /// carried until an `ok_or`/`?` or an `unwrap` consumes it. Nim's view
134 /// types cannot live inside an object, so an `Option` of a view has no
135 /// runtime representation -- it is tracked here instead.
136 guard: Option<String>,
137 /// The error an `ok_or` attached to that guard.
138 guard_err: Option<String>,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago139}
140
141impl Val {
142 fn new(code: impl Into<String>, ty: Option<Nim>) -> Self {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago143 Val { code: code.into(), ty, window: None, guard: None, guard_err: None }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago144 }
145 fn untyped(code: impl Into<String>) -> Self {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago146 Val::new(code, None)
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago147 }
148}
149
150struct Sig {
151 params: Vec<Nim>,
152 ret: Nim,
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago153 /// Type parameters this signature is generic in, so a call site can bind
154 /// them from its argument types.
155 generics: Vec<String>,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago156}
157
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago158/// One variant of a Rust enum.
159#[derive(Clone)]
160struct Variant {
161 name: String,
162 /// `(nim field name, type)`. Empty for a unit variant. Tuple variants get
163 /// `f0`, `f1`, ...; every field is prefixed with the variant name because
164 /// Nim requires the branches of a variant object to have distinct fields.
165 fields: Vec<(String, Nim)>,
166}
167
168#[derive(Clone)]
169struct EnumDef {
170 name: String,
171 /// True when every variant is a unit variant, which Nim represents as a
172 /// plain `enum` rather than an object variant.
173 simple: bool,
174 variants: Vec<Variant>,
175}
176
177impl EnumDef {
178 fn kind_ident(&self, v: &str) -> String {
179 format!("k{}{}", self.name, v)
180 }
181 fn ctor_ident(&self, v: &str) -> String {
182 format!("{}{}", self.name, v)
183 }
184 fn get(&self, v: &str) -> Option<&Variant> {
185 self.variants.iter().find(|x| x.name == v)
186 }
187}
188
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago189pub struct Lowerer {
190 out: String,
191 indent: usize,
192 scopes: Vec<HashMap<String, Nim>>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago193 /// Names introduced by a `for` pattern that stand for an lvalue or a
194 /// window into a container, rather than for a variable of their own.
195 alias_scopes: Vec<HashMap<String, Alias>>,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago196 /// `(module, name) -> signature`. Rust keeps `lower::decode` and
197 /// `mixed::decode` apart by module; flattening into one Nim module would
198 /// merge them, so the module is part of the key and of the emitted name.
199 fns: HashMap<(String, String), Sig>,
200 /// Module being lowered: the file stem, or empty for the crate root.
201 cur_mod: String,
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago202 /// The type of the `impl` block being lowered, which `Self` names.
203 self_ty: Option<Nim>,
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago204 /// Type parameters of the enclosing `impl`, which its methods share.
205 impl_generics: Vec<String>,
206 /// Type parameters of the proc being lowered, impl's included.
207 fn_generics: Vec<String>,
208 /// Type parameters declared by each generic struct or enum.
209 type_generics: HashMap<String, Vec<String>>,
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago210 /// `(type, name) -> type` for `type Item = ..;` inside an `impl`. Rust
211 /// writes those as `Self::Item`, which has to resolve before any
212 /// signature mentioning it is mapped.
213 assoc: HashMap<(String, String), Nim>,
214 /// `(type, name) -> (nim name, type)` for `const` items inside an `impl`.
215 assoc_consts: HashMap<(String, String), (String, Nim)>,
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 15h ago216 /// Types declared by a `bitflags!` invocation.
217 bitflags: std::collections::HashSet<String>,
218 /// `(type, flag) -> nim const name`.
219 flag_consts: HashMap<(String, String), String>,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago220 /// `use` brings a name into scope from another module. Flattening loses
221 /// the module structure, so the mapping is recorded and consulted when a
222 /// bare call is resolved.
223 use_map: HashMap<String, String>,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago224 /// struct name -> (field, type)
225 structs: HashMap<String, Vec<(String, Nim)>>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago226 enums: HashMap<String, EnumDef>,
227 /// variant name -> enums declaring it. A variant named by more than one
228 /// enum must be written qualified, or it is rejected as ambiguous.
229 variant_owner: HashMap<String, Vec<String>>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago230 /// `(receiver type, method) -> signature`. Keyed by type because two
231 /// types may define the same method name, and Nim tells them apart by
232 /// overload resolution on the first parameter.
233 methods: HashMap<(String, String), Sig>,
234 /// The formatting traits implemented for each type, so `{}`/`{:?}`/`{:x}`
235 /// on a user type can be checked rather than assumed.
236 fmt_impls: HashMap<(String, String), ()>,
237 /// `(from, to)` conversions declared by `impl From<A> for B`.
238 from_impls: HashMap<(String, String), String>,
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago239 /// Operator traits implemented for a type, so `a += b` on a user type can
240 /// be dispatched to the impl rather than to Nim's built-in operator.
241 op_impls: HashMap<(String, String), ()>,
242 /// `(type, method) -> nim name`, for calls written as `Type::method(..)`.
243 statics: HashMap<(String, String), String>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago244 /// Forward declarations, emitted between the type definitions and the
245 /// bodies. Rust has no declaration-before-use rule and Nim does, so every
246 /// proc is declared up front rather than the input being reordered --
247 /// which would not work for mutual recursion anyway.
248 forwards: Vec<String>,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago249 /// Element type a `vec![..]` should build, from the binding's annotation.
250 vec_expect: Option<Nim>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago251 /// While lowering a formatting impl: the `Formatter` parameter's name.
252 /// Writes through it produce the proc's string result.
253 fmt_param: Option<String>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago254 /// `type X<T> = ...`, expanded before any type is mapped.
255 aliases: HashMap<String, (Vec<String>, syn::Type)>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago256 /// Module names supplied as separate input files. A `mod x;` naming one
257 /// of these is satisfied by that file having been passed in.
258 pub modules: Vec<String>,
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 16h ago259 /// How many items were actually translated. If this is zero the input
260 /// produced nothing but the prelude, and reporting success for that is
261 /// the precise failure this project exists to avoid -- see `findings/`.
262 emitted: usize,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago263 /// Cargo features that are on, as `--cfg feature=<name>`. `#[cfg]` is
264 /// evaluated against these exactly as rustc would, so an item that is
265 /// dropped here is genuinely not part of the program being compiled.
266 pub features: Vec<String>,
267 dropped_by_cfg: usize,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago268 /// Return type of the proc being lowered, so `return e` and a trailing
269 /// expression can type their literals the way Rust's inference would.
270 ret: Option<Nim>,
271 /// `(name, type)` that the arms of the `if`/`match` being lowered as a
272 /// statement must assign their value to.
273 target: Option<(String, Option<Nim>)>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago274 /// Set while lowering a `while` condition, which Nim re-evaluates each
275 /// iteration and so cannot have statements hoisted out of it.
276 in_loop_cond: bool,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago277 tmp: usize,
278}
279
280impl Lowerer {
281 pub fn new() -> Self {
282 Lowerer {
283 out: String::new(),
284 indent: 0,
285 scopes: vec![HashMap::new()],
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago286 alias_scopes: vec![HashMap::new()],
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago287 fns: HashMap::new(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago288 cur_mod: String::new(),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago289 self_ty: None,
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago290 impl_generics: Vec::new(),
291 fn_generics: Vec::new(),
292 type_generics: HashMap::new(),
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago293 assoc: HashMap::new(),
294 assoc_consts: HashMap::new(),
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 15h ago295 bitflags: std::collections::HashSet::new(),
296 flag_consts: HashMap::new(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago297 use_map: HashMap::new(),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago298 structs: HashMap::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago299 enums: HashMap::new(),
300 variant_owner: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago301 methods: HashMap::new(),
302 fmt_impls: HashMap::new(),
303 from_impls: HashMap::new(),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago304 op_impls: HashMap::new(),
305 statics: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago306 fmt_param: None,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago307 vec_expect: None,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago308 forwards: Vec::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago309 aliases: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago310 modules: Vec::new(),
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 16h ago311 emitted: 0,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago312 features: Vec::new(),
313 dropped_by_cfg: 0,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago314 ret: None,
315 target: None,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago316 in_loop_cond: false,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago317 tmp: 0,
318 }
319 }
320
321 // ------------------------------------------------------------ emission
322
323 fn line(&mut self, s: &str) {
324 for _ in 0..self.indent {
325 self.out.push_str(" ");
326 }
327 self.out.push_str(s);
328 self.out.push('\n');
329 }
330
331 fn blank(&mut self) {
332 self.out.push('\n');
333 }
334
335 fn fresh(&mut self, hint: &str) -> String {
336 self.tmp += 1;
337 format!("rsTmp{}{}", hint, self.tmp)
338 }
339
340 // --------------------------------------------------------------- scope
341
342 fn push_scope(&mut self) {
343 self.scopes.push(HashMap::new());
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago344 self.alias_scopes.push(HashMap::new());
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago345 }
346 fn pop_scope(&mut self) {
347 self.scopes.pop();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago348 self.alias_scopes.pop();
349 }
350 fn bind_alias(&mut self, name: &str, a: Alias) {
351 self.alias_scopes
352 .last_mut()
353 .unwrap()
354 .insert(name.to_string(), a);
355 }
356 fn lookup_alias(&self, name: &str) -> Option<Alias> {
357 self.alias_scopes
358 .iter()
359 .rev()
360 .find_map(|s| s.get(name).cloned())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago361 }
362 fn bind(&mut self, name: &str, t: Nim) {
363 self.scopes.last_mut().unwrap().insert(name.to_string(), t);
364 }
365 fn lookup(&self, name: &str) -> Option<Nim> {
366 self.scopes.iter().rev().find_map(|s| s.get(name).cloned())
367 }
368
369 // ---------------------------------------------------------------- file
370
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago371 pub fn lower_file(&mut self, files: &[(String, syn::File)]) -> Result<String, String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago372 self.out.push_str(include_str!("prelude.nim"));
373 self.blank();
374
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago375 // Pass 0: type aliases. A signature in one file may use an alias
376 // declared in another, and inputs are given in whatever order suits
377 // the caller, so aliases are registered before anything is mapped.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago378 for (m, f) in files {
379 self.cur_mod = m.clone();
380 for item in &f.items {
381 self.collect_aliases(item)?;
382 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago383 }
384
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago385 // Pass 1: signatures and struct shapes, so that a call can be typed
386 // regardless of declaration order (Rust has no forward declarations).
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago387 for (m, f) in files {
388 self.cur_mod = m.clone();
389 for item in &f.items {
390 self.collect(item)?;
391 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago392 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago393 // Pass 2: type definitions, which every signature may mention.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago394 for (m, f) in files {
395 self.cur_mod = m.clone();
396 for item in &f.items {
397 self.item_types(item)?;
398 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago399 }
400
401 // Pass 3: forward declarations. Rust imposes no declaration order and
402 // Nim does, so everything is declared before any body is emitted;
403 // reordering the input would not handle mutual recursion anyway.
404 if !self.forwards.is_empty() {
405 for f in self.forwards.clone() {
406 self.line(&f);
407 }
408 self.blank();
409 }
410
411 // Pass 4: bodies.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago412 for (m, f) in files {
413 self.cur_mod = m.clone();
414 for item in &f.items {
415 self.item(item)?;
416 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago417 }
418
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 16h ago419 // An input that translates to nothing is a failure, however plausible
420 // the output file looks. The prelude alone is not a translation.
421 if self.emitted == 0 {
422 return Err(format!(
423 "nothing was translated: the input has no items this lowering \
424 emits{}. Writing a file containing only the prelude would \
425 report success for work that was not done",
426 if self.dropped_by_cfg > 0 {
427 format!(
428 " ({} item(s) were dropped by `#[cfg]`; enable them with \
429 `--cfg feature=<name>`)",
430 self.dropped_by_cfg
431 )
432 } else {
433 String::new()
434 }
435 ));
436 }
437
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago438 if self.fns.contains_key(&(String::new(), "main".to_string())) {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago439 self.blank();
440 self.line("when isMainModule:");
441 self.indent += 1;
442 self.line("try:");
443 self.line(" main()");
444 // Rust's panic exits 101 with a message on stderr. Nim's Defects
445 // exit 1. Mapping them here is what keeps the differential runner's
446 // exit-status comparison meaningful for panicking programs.
447 self.line("except RustPanic as e:");
448 self.line(" stderr.writeLine(\"thread 'main' panicked: \" & e.msg)");
449 self.line(" quit(101)");
450 self.line("except Defect as e:");
451 self.line(" stderr.writeLine(\"thread 'main' panicked: \" & e.msg)");
452 self.line(" quit(101)");
453 self.indent -= 1;
454 }
455 Ok(std::mem::take(&mut self.out))
456 }
457
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago458 fn collect_aliases(&mut self, item: &Item) -> Result<(), String> {
459 if !self.cfg_keeps(item_attrs(item))? {
460 return Ok(());
461 }
462 match item {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago463 Item::Use(u) => self.collect_use(&u.tree, &[]),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago464 Item::Type(t) => {
465 let params: Vec<String> = t
466 .generics
467 .params
468 .iter()
469 .filter_map(|g| match g {
470 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
471 _ => None,
472 })
473 .collect();
474 self.aliases
475 .insert(t.ident.to_string(), (params, (*t.ty).clone()));
476 }
477 Item::Mod(m) if m.content.is_some() => {
478 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
479 for i in &items {
480 self.collect_aliases(i)?;
481 }
482 }
483 _ => {}
484 }
485 Ok(())
486 }
487
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago488 /// Record what a `use` brings into scope, as `name -> module`.
489 fn collect_use(&mut self, t: &syn::UseTree, prefix: &[String]) {
490 use syn::UseTree;
491 match t {
492 UseTree::Path(p) => {
493 let mut pre = prefix.to_vec();
494 pre.push(p.ident.to_string());
495 self.collect_use(&p.tree, &pre);
496 }
497 UseTree::Group(g) => {
498 for t in &g.items {
499 self.collect_use(t, prefix);
500 }
501 }
502 UseTree::Name(n) => {
503 let m = module_of(prefix);
504 self.use_map.insert(n.ident.to_string(), m);
505 }
506 UseTree::Rename(r) => {
507 let m = module_of(prefix);
508 self.use_map.insert(r.rename.to_string(), m);
509 }
510 // A glob brings in an unknown set of names; resolution falls back
511 // to the current module and the root, as it would without it.
512 UseTree::Glob(_) => {}
513 }
514 }
515
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago516 fn collect(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago517 // A `#[cfg(..)]` item exists only under some feature set. Dropping it
518 // silently would change what the program does; picking a feature set
519 // on the user's behalf would be a guess. So it is reported, except on
520 // items that carry no runtime meaning here anyway.
521 if !self.cfg_keeps(item_attrs(item))? {
522 self.dropped_by_cfg += 1;
523 return Ok(());
524 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago525 match item {
526 Item::Fn(f) => {
527 let (params, ret) = self.signature(&f.sig)?;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago528 let gen_names = Self::generics_of(&f.sig.generics);
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago529 let name = f.sig.ident.to_string();
530 let nim = self.fn_name(&self.cur_mod, &name);
531 self.forwards.push(self.head_of(&nim, &f.sig, None)?);
532 self.fns
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago533 .insert((self.cur_mod.clone(), name), Sig { params, ret, generics: gen_names.clone() });
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago534 }
535 Item::Struct(s) => {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago536 if s.generics.params.iter().any(|p| matches!(p, syn::GenericParam::Const(_))) {
537 return Err(format!(
538 "`struct {}` has a const generic parameter, which Nim has \
539 no equivalent for",
540 s.ident
541 ));
542 }
543 let g = Self::generics_of(&s.generics);
544 // The parameters must be in scope while the field types are
545 // mapped, so that `T` resolves to itself rather than to an
546 // unknown named type.
547 self.type_generics.insert(s.ident.to_string(), g);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago548 let mut fields = Vec::new();
549 for (i, f) in s.fields.iter().enumerate() {
550 let name = match &f.ident {
551 Some(id) => id.to_string(),
552 None => format!("f{i}"), // tuple struct
553 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago554 // A field of `&[T]` / `&str` type is a borrow, and Nim's
555 // view types allow it as an object field, so it stays a
556 // view rather than being copied into a `seq`.
557 let t = self.map_ty(&f.ty)?;
558 let t = if returns_borrow(&f.ty) { t.unvar() } else { t.owned() };
559 fields.push((name, t));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago560 }
561 self.structs.insert(s.ident.to_string(), fields);
562 }
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 15h ago563 Item::Macro(m) if path_name(&m.mac.path) == "bitflags" => {
564 self.collect_bitflags(&m.mac)?;
565 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago566 Item::Mod(m) if m.content.is_some() => {
567 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
568 for i in &items {
569 self.collect(i)?;
570 }
571 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago572 Item::Type(t) => {
573 let params: Vec<String> = t
574 .generics
575 .params
576 .iter()
577 .filter_map(|g| match g {
578 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
579 _ => None,
580 })
581 .collect();
582 self.aliases
583 .insert(t.ident.to_string(), (params, (*t.ty).clone()));
584 }
585 Item::Enum(e) => {
586 let name = e.ident.to_string();
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago587 if e.generics.params.iter().any(|p| matches!(p, syn::GenericParam::Const(_))) {
588 return Err(format!(
589 "`enum {name}` has a const generic parameter, which Nim \
590 has no equivalent for"
591 ));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago592 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago593 self.type_generics
594 .insert(name.clone(), Self::generics_of(&e.generics));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago595 let mut variants = Vec::new();
596 for v in &e.variants {
597 let vname = v.ident.to_string();
598 if v.discriminant.is_some() {
599 return Err(format!(
600 "`{name}::{vname}` has an explicit discriminant; Rust's \
601 `as` on such an enum has a value this lowering does not \
602 yet preserve"
603 ));
604 }
605 let mut fields = Vec::new();
606 for (i, f) in v.fields.iter().enumerate() {
607 // Nim requires the branches of a variant object to have
608 // distinct field names, so each is prefixed.
609 let fname = match &f.ident {
610 Some(id) => format!("{vname}_{id}"),
611 None => format!("{vname}_f{i}"),
612 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago613 let t = self.map_ty(&f.ty)?;
614 let t = if returns_borrow(&f.ty) { t.unvar() } else { t.owned() };
615 fields.push((fname, t));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago616 }
617 variants.push(Variant { name: vname, fields });
618 }
619 let simple = variants.iter().all(|v| v.fields.is_empty());
620 for v in &variants {
621 self.variant_owner
622 .entry(v.name.clone())
623 .or_default()
624 .push(name.clone());
625 }
626 self.enums.insert(
627 name.clone(),
628 EnumDef { name, simple, variants },
629 );
630 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago631 Item::Impl(im) => {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago632 let outer_g =
633 std::mem::replace(&mut self.impl_generics, Self::generics_of(&im.generics));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago634 let self_ty = self.map_ty(&im.self_ty)?;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago635 let outer_self = self.self_ty.replace(self_ty.clone());
636 let r = self.collect_impl(im, &self_ty);
637 self.self_ty = outer_self;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago638 self.impl_generics = outer_g;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago639 return r;
640 }
641 _ => {}
642 }
643 Ok(())
644 }
645
646 fn collect_impl(&mut self, im: &syn::ItemImpl, self_ty: &Nim) -> Result<(), String> {
647 {
648 let self_ty = self_ty.clone();
649 let tyname = type_name(&self_ty);
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago650 // Associated types first: a signature in the same block may name
651 // one, and it has to resolve by the time that signature is mapped.
652 for it in &im.items {
653 if let syn::ImplItem::Type(t) = it {
654 let v = self.map_ty(&t.ty)?;
655 self.assoc.insert((tyname.clone(), t.ident.to_string()), v);
656 }
657 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago658 if let Some((path, _)) = &im.trait_ {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago659 let tr = path_name(path);
660 if im.items.is_empty() {
661 // A marker trait with no items. We do not model trait
662 // resolution at all, so it generates nothing; any use
663 // that actually needed the trait (a `dyn`, a bound) is
664 // rejected where it appears.
665 return Ok(());
666 }
667 if is_fmt_trait(&tr) {
668 self.forwards.push(format!(
669 "proc {}*(self: {}): string",
670 fmt_proc(&tr),
671 self_ty.render()
672 ));
673 self.fmt_impls.insert((tyname, tr), ());
674 return Ok(());
675 }
676 if tr == "From" {
677 let syn::ImplItem::Fn(m) = &im.items[0] else {
678 return Err("`impl From` must contain `fn from`".into());
679 };
680 let (params, _) = self.signature(&m.sig)?;
681 let src = params
682 .first()
683 .ok_or("`fn from` takes one argument")?
684 .clone();
685 let name = format!("rsFrom{}{}", tyname, type_name(&src));
686 self.forwards.push(self.head_of(&name, &m.sig, None)?);
687 self.from_impls
688 .insert((type_name(&src), tyname), name);
689 return Ok(());
690 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago691 // Any other trait: its methods are emitted as procs on
692 // the type, named after the trait so two traits declaring
693 // the same method name do not collide. The *trait* is not
694 // modelled -- no dynamic dispatch, no bounds -- and a use
695 // that needs it is rejected where it appears.
696 if let Some(op) = operator_trait(&tr) {
697 self.op_impls.insert((tyname.clone(), op.to_string()), ());
698 }
699 for it in &im.items {
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago700 // Already recorded above; a const is emitted with the
701 // bodies.
702 if matches!(it, syn::ImplItem::Type(_) | syn::ImplItem::Const(_)) {
703 continue;
704 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago705 let syn::ImplItem::Fn(m) = it else {
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago706 return Err(format!(
707 "unsupported item in `impl {tr}`: only `fn`, \
708 `type` and `const` are implemented"
709 ));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago710 };
711 let mname = m.sig.ident.to_string();
712 let (mut params, ret) = self.signature(&m.sig)?;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago713 let mut gen_names = self.impl_generics.clone();
714 gen_names.extend(Self::generics_of(&m.sig.generics));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago715 let recv = if takes_self(&m.sig) {
716 params.insert(0, self_ty.clone());
717 Some(self_ty.clone())
718 } else {
719 None
720 };
721 let nim = trait_method_name(&tyname, &tr, &mname);
722 self.forwards.push(self.head_of(&nim, &m.sig, recv.as_ref())?);
723 self.methods
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago724 .insert((tyname.clone(), mname.clone()), Sig { params, ret, generics: gen_names.clone() });
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago725 self.statics.insert((tyname.clone(), mname), nim);
726 }
727 return Ok(());
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago728 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago729 for it in &im.items {
730 if let syn::ImplItem::Fn(m) = it {
731 let (mut params, ret) = self.signature(&m.sig)?;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago732 let mut gen_names = self.impl_generics.clone();
733 gen_names.extend(Self::generics_of(&m.sig.generics));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago734 if takes_self(&m.sig) {
735 params.insert(0, self_ty.clone());
736 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago737 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago738 let nim = self.fn_name(&self.cur_mod, &m.sig.ident.to_string());
739 let head = self.head_of(&nim, &m.sig, recv.as_ref())?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago740 self.forwards.push(head);
741 self.methods
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago742 .insert((tyname.clone(), m.sig.ident.to_string()), Sig { params, ret, generics: gen_names.clone() });
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago743 self.statics
744 .insert((tyname.clone(), m.sig.ident.to_string()), nim);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago745 }
746 }
747 }
748 Ok(())
749 }
750
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago751 /// Whether `#[cfg(..)]` keeps this item, given the enabled features.
752 ///
753 /// This is evaluation, not approximation: rustc does the same thing, and
754 /// an item whose predicate is false is not part of the compiled program.
755 /// A predicate that cannot be evaluated is reported rather than assumed.
756 fn cfg_keeps(&self, attrs: &[syn::Attribute]) -> Result<bool, String> {
757 for a in attrs {
758 if a.path().is_ident("cfg") {
759 let pred: syn::Meta = a
760 .parse_args()
761 .map_err(|e| format!("cannot parse `#[cfg(..)]`: {e}"))?;
762 if !self.cfg_eval(&pred)? {
763 return Ok(false);
764 }
765 }
766 }
767 Ok(true)
768 }
769
770 fn cfg_eval(&self, m: &syn::Meta) -> Result<bool, String> {
771 match m {
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago772 // Bare flags whose value is determined by the profile this project
773 // models: a normal (non-`--test`) debug build, not a docs build.
774 // Anything platform-specific stays rejected, since we would be
775 // picking a target on the user's behalf.
776 syn::Meta::Path(p) if p.is_ident("test") => Ok(false),
777 syn::Meta::Path(p) if p.is_ident("debug_assertions") => Ok(true),
778 syn::Meta::Path(p) if p.is_ident("docsrs") || p.is_ident("doc") => Ok(false),
Evaluate host cfg predicates, and measure what that actually buys 0e6c394 nandithebull 16h ago779 syn::Meta::Path(p) if p.is_ident("doctest") || p.is_ident("miri") => Ok(false),
780 // Host facts. The generated Nim is compiled for this machine, so
781 // these are known rather than chosen. See DESIGN.md item 10: it
782 // does make the output host-shaped.
783 syn::Meta::Path(p) if p.is_ident("unix") => Ok(cfg!(unix)),
784 syn::Meta::Path(p) if p.is_ident("windows") => Ok(cfg!(windows)),
785 syn::Meta::NameValue(nv)
786 if nv.path.is_ident("target_os")
787 || nv.path.is_ident("target_arch")
788 || nv.path.is_ident("target_family")
789 || nv.path.is_ident("target_vendor") =>
790 {
791 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
792 return Err("this `cfg` key expects a string".into());
793 };
794 let key = nv.path.get_ident().map(|i| i.to_string()).unwrap_or_default();
795 Ok(s.value()
796 == match key.as_str() {
797 "target_os" => std::env::consts::OS,
798 "target_arch" => std::env::consts::ARCH,
799 "target_family" => std::env::consts::FAMILY,
800 _ => "unknown",
801 })
802 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago803 // The generated Nim is compiled for the same machine, so the
804 // target's word size and endianness are known rather than
805 // guessed. This does mean the output is host-shaped: a crate that
806 // branches on pointer width has had that branch decided here.
807 syn::Meta::NameValue(nv) if nv.path.is_ident("target_pointer_width") => {
808 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
809 return Err("`target_pointer_width = ..` expects a string".into());
810 };
811 Ok(s.value() == (usize::BITS).to_string())
812 }
813 syn::Meta::NameValue(nv) if nv.path.is_ident("target_endian") => {
814 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
815 return Err("`target_endian = ..` expects a string".into());
816 };
817 Ok(s.value() == if cfg!(target_endian = "big") { "big" } else { "little" })
818 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago819 syn::Meta::NameValue(nv) if nv.path.is_ident("feature") => {
820 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
821 return Err("`feature = ..` expects a string".into());
822 };
823 Ok(self.features.iter().any(|f| *f == s.value()))
824 }
825 syn::Meta::List(l) if l.path.is_ident("not") => {
826 let inner: syn::Meta = l.parse_args().map_err(|e| e.to_string())?;
827 Ok(!self.cfg_eval(&inner)?)
828 }
829 syn::Meta::List(l) if l.path.is_ident("all") || l.path.is_ident("any") => {
830 let items: syn::punctuated::Punctuated<syn::Meta, syn::Token![,]> = l
831 .parse_args_with(syn::punctuated::Punctuated::parse_terminated)
832 .map_err(|e| e.to_string())?;
833 let all = l.path.is_ident("all");
834 let mut acc = all;
835 for i in &items {
836 let v = self.cfg_eval(i)?;
837 acc = if all { acc && v } else { acc || v };
838 }
839 Ok(acc)
840 }
841 other => Err(format!(
Evaluate host cfg predicates, and measure what that actually buys 0e6c394 nandithebull 16h ago842 "`#[cfg({})]` is not a predicate rustnim can evaluate. \
843 Features (`--cfg feature=..`), host facts (`unix`, `windows`, \
844 `target_os`, `target_arch`, `target_family`, \
845 `target_pointer_width`, `target_endian`), `doc`/`doctest`/\
846 `miri`, and `not`/`all`/`any` over those are. A custom or \
847 build-script `cfg` has no value we could know",
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago848 quote_meta(other)
849 )),
850 }
851 }
852
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago853 /// Map a Rust type, resolving `Self` and expanding any `type` alias. Every type in the
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago854 /// lowering goes through here rather than calling `ty::map` directly, so
855 /// an alias cannot be missed in one position and honoured in another.
856 fn map_ty(&self, t: &syn::Type) -> Result<Nim, String> {
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago857 // `Self::Item` names an associated type of the enclosing `impl`.
858 if let syn::Type::Path(p) = t {
859 let segs: Vec<String> =
860 p.path.segments.iter().map(|s| s.ident.to_string()).collect();
861 if segs.len() == 2 {
862 let owner = if segs[0] == "Self" {
863 self.self_ty.as_ref().map(type_name)
864 } else {
865 Some(segs[0].clone())
866 };
867 if let Some(o) = owner {
868 if let Some(a) = self.assoc.get(&(o, segs[1].clone())) {
869 return Ok(a.clone());
870 }
871 }
872 }
873 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago874 let n = ty::map(&self.expand(t, 0)?)?;
875 Ok(self.subst_self(n))
876 }
877
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago878 /// Substitute a generic type's parameters with the arguments the use site
879 /// supplies: a field of `Holder<T>` read through a `Holder<i32>` is `i32`.
880 fn subst_type_args(&self, name: &str, used_as: &Nim, field: Nim) -> Nim {
881 let Some(params) = self.type_generics.get(name) else { return field };
882 if params.is_empty() {
883 return field;
884 }
885 let Nim::Named(n, args) = used_as else { return field };
886 if n != name || args.len() != params.len() {
887 return field;
888 }
889 let map: HashMap<String, Nim> =
890 params.iter().cloned().zip(args.iter().cloned()).collect();
891 Self::subst(&field, &map)
892 }
893
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago894 /// `Self` inside an `impl` block names the type being implemented.
895 fn subst_self(&self, t: Nim) -> Nim {
896 let Some(me) = &self.self_ty else { return t };
897 match t {
898 Nim::Named(n, _) if n == "Self" => me.clone(),
899 Nim::Seq(e) => Nim::Seq(Box::new(self.subst_self(*e))),
900 Nim::OpenArray(e) => Nim::OpenArray(Box::new(self.subst_self(*e))),
901 Nim::Array(n, e) => Nim::Array(n, Box::new(self.subst_self(*e))),
902 Nim::Var(e) => Nim::Var(Box::new(self.subst_self(*e))),
903 Nim::Named(n, a) => {
904 Nim::Named(n, a.into_iter().map(|x| self.subst_self(x)).collect())
905 }
906 other => other,
907 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago908 }
909
910 fn expand(&self, t: &syn::Type, depth: usize) -> Result<syn::Type, String> {
911 if depth > 16 {
912 return Err("type alias expansion did not terminate; is it cyclic?".into());
913 }
914 let syn::Type::Path(p) = t else { return Ok(t.clone()) };
915 // Only an unqualified name can be one of this file's aliases.
916 // `fmt::Result` and `core::result::Result` are different types that
917 // merely end in the same segment.
918 if p.path.segments.len() != 1 {
919 return Ok(t.clone());
920 }
921 let Some(seg) = p.path.segments.last() else { return Ok(t.clone()) };
922 let Some((params, target)) = self.aliases.get(&seg.ident.to_string()) else {
923 return Ok(t.clone());
924 };
925 let args: Vec<syn::Type> = match &seg.arguments {
926 syn::PathArguments::AngleBracketed(a) => a
927 .args
928 .iter()
929 .filter_map(|g| match g {
930 GenericArgument::Type(t) => Some(t.clone()),
931 _ => None,
932 })
933 .collect(),
934 _ => vec![],
935 };
936 if args.len() != params.len() {
937 // Flattening several files into one module can bring a crate's own
938 // alias (`type Result<T> = Result<T, Error>`) into scope at a site
939 // that meant the builtin (`Result<T, E>`). Rust kept them apart by
940 // module; here they are told apart by arity, and a use that fits
941 // neither is left for `ty::map` to report.
942 return Ok(t.clone());
943 }
944 self.expand(&substitute(target, params, &args), depth + 1)
945 }
946
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago947 /// The type parameters a generic item declares.
948 ///
949 /// Trait bounds and `where` clauses are dropped. Nim instantiates a
950 /// generic structurally: an operation the bound would have permitted
951 /// either exists for the instantiated type or is a compile error at the
952 /// instantiation site. So dropping a bound cannot make an accepted
953 /// program mean something different — it only makes rustnim accept some
954 /// programs rustc would have rejected, which does not matter when the
955 /// input is known-good Rust.
956 fn generics_of(g: &syn::Generics) -> Vec<String> {
957 g.params
958 .iter()
959 .filter_map(|p| match p {
960 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
961 _ => None,
962 })
963 .collect()
964 }
965
966 /// Bind a signature's type parameters by matching its declared parameter
967 /// types against the actual argument types, then substitute into `ret`.
968 ///
969 /// This is the small amount of inference a call site needs: Nim will
970 /// resolve the instantiation itself, but the *binding* still has to be
971 /// annotated with a concrete type, and `T` is not one.
972 fn instantiate(sig: &Sig, args: &[Option<Nim>]) -> Nim {
973 if sig.generics.is_empty() {
974 return sig.ret.clone();
975 }
976 let mut bound: HashMap<String, Nim> = HashMap::new();
977 for (decl, actual) in sig.params.iter().zip(args) {
978 if let Some(a) = actual {
979 Self::unify(decl, a, &sig.generics, &mut bound);
980 }
981 }
982 Self::subst(&sig.ret, &bound)
983 }
984
985 fn unify(decl: &Nim, actual: &Nim, params: &[String], out: &mut HashMap<String, Nim>) {
986 match (decl, actual) {
987 (Nim::Named(n, da), _) if params.iter().any(|p| p == n) && da.is_empty() => {
988 out.entry(n.clone()).or_insert_with(|| actual.clone());
989 }
990 (Nim::Named(_, da), Nim::Named(_, aa)) if da.len() == aa.len() => {
991 for (d, a) in da.iter().zip(aa) {
992 Self::unify(d, a, params, out);
993 }
994 }
995 (Nim::Seq(d), Nim::Seq(a))
996 | (Nim::OpenArray(d), Nim::OpenArray(a))
997 | (Nim::Seq(d), Nim::OpenArray(a))
998 | (Nim::OpenArray(d), Nim::Seq(a))
999 | (Nim::Var(d), Nim::Var(a))
1000 | (Nim::Array(_, d), Nim::Array(_, a)) => Self::unify(d, a, params, out),
1001 (Nim::Var(d), a) => Self::unify(d, a, params, out),
1002 (d, Nim::Var(a)) => Self::unify(d, a, params, out),
1003 (Nim::Tuple(d), Nim::Tuple(a)) if d.len() == a.len() => {
1004 for (d, a) in d.iter().zip(a) {
1005 Self::unify(d, a, params, out);
1006 }
1007 }
1008 _ => {}
1009 }
1010 }
1011
1012 fn subst(t: &Nim, m: &HashMap<String, Nim>) -> Nim {
1013 match t {
1014 Nim::Named(n, a) if a.is_empty() => m.get(n).cloned().unwrap_or_else(|| t.clone()),
1015 Nim::Named(n, a) => {
1016 Nim::Named(n.clone(), a.iter().map(|x| Self::subst(x, m)).collect())
1017 }
1018 Nim::Seq(e) => Nim::Seq(Box::new(Self::subst(e, m))),
1019 Nim::OpenArray(e) => Nim::OpenArray(Box::new(Self::subst(e, m))),
1020 Nim::Array(n, e) => Nim::Array(*n, Box::new(Self::subst(e, m))),
1021 Nim::Var(e) => Nim::Var(Box::new(Self::subst(e, m))),
1022 Nim::Tuple(ts) => Nim::Tuple(ts.iter().map(|x| Self::subst(x, m)).collect()),
1023 other => other.clone(),
1024 }
1025 }
1026
1027 /// Whether a type mentions a type parameter that is in scope here. Such a
1028 /// type cannot be used as a Nim annotation at an instantiation site: Nim
1029 /// infers it, and writing `T` would name something that is not bound.
1030 fn mentions_type_param(&self, t: &Nim) -> bool {
1031 match t {
1032 Nim::Named(n, a) => {
1033 self.fn_generics.iter().any(|g| g == n)
1034 || a.iter().any(|x| self.mentions_type_param(x))
1035 }
1036 Nim::Seq(e) | Nim::OpenArray(e) | Nim::Var(e) | Nim::Array(_, e) => {
1037 self.mentions_type_param(e)
1038 }
1039 Nim::Tuple(ts) => ts.iter().any(|x| self.mentions_type_param(x)),
1040 Nim::Proc(a, r) => {
1041 a.iter().any(|x| self.mentions_type_param(x)) || self.mentions_type_param(r)
1042 }
1043 _ => false,
1044 }
1045 }
1046
1047 /// `[T, U]`, or empty.
1048 fn gen_list(params: &[String]) -> String {
1049 if params.is_empty() {
1050 String::new()
1051 } else {
1052 format!("[{}]", params.join(", "))
1053 }
1054 }
1055
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago1056 /// The Nim name for a function, qualified by its module.
1057 fn fn_name(&self, module: &str, name: &str) -> String {
1058 if module.is_empty() {
1059 ident(name)
1060 } else {
1061 format!("{}_{}", module, ident(name))
1062 }
1063 }
1064
1065 /// Resolve a call path to the module and name it refers to: an explicit
1066 /// `mixed::decode`, then the current module, then the crate root.
1067 fn resolve_fn(&self, path: &syn::Path) -> Option<(String, String)> {
1068 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
1069 let last = segs.last()?.clone();
1070 if segs.len() >= 2 {
1071 let q = &segs[segs.len() - 2];
1072 if self.fns.contains_key(&(q.clone(), last.clone())) {
1073 return Some((q.clone(), last));
1074 }
1075 }
1076 let imported = self.use_map.get(&last).cloned();
1077 for m in [Some(self.cur_mod.clone()), imported, Some(String::new())]
1078 .into_iter()
1079 .flatten()
1080 {
1081 if self.fns.contains_key(&(m.clone(), last.clone())) {
1082 return Some((m, last));
1083 }
1084 }
1085 None
1086 }
1087
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1088 /// The Nim `proc` head for a Rust signature, used both for the forward
1089 /// declaration and for the definition, so the two cannot drift apart.
1090 fn head_of(
1091 &self,
1092 name: &str,
1093 sig: &syn::Signature,
1094 recv: Option<&Nim>,
1095 ) -> Result<String, String> {
1096 let (ptys, ret) = self.signature(sig)?;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1097 // A method inside `impl<T> Foo<T>` is generic in the impl's
1098 // parameters as well as its own.
1099 let mut params = self.impl_generics.clone();
1100 for g in Self::generics_of(&sig.generics) {
1101 if !params.contains(&g) {
1102 params.push(g);
1103 }
1104 }
1105 let gens = Self::gen_list(&params);
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1106 let mut parts = Vec::new();
1107 if let Some(self_ty) = recv {
1108 let mutable = matches!(
1109 sig.inputs.first(),
1110 Some(FnArg::Receiver(r))
1111 if matches!(&r.kind, syn::ReceiverKind::Reference(_, _, m) if m.is_some())
1112 );
1113 let t = if mutable { Nim::Var(Box::new(self_ty.clone())) } else { self_ty.clone() };
1114 parts.push(format!("self: {}", t.render()));
1115 }
1116 let typed: Vec<&syn::PatType> = sig
1117 .inputs
1118 .iter()
1119 .filter_map(|a| match a {
1120 FnArg::Typed(t) => Some(t),
1121 _ => None,
1122 })
1123 .collect();
1124 for (i, (p, t)) in typed.iter().zip(ptys.iter()).enumerate() {
1125 let pname = match &*p.pat {
1126 Pat::Ident(id) => id.ident.to_string(),
1127 Pat::Wild(_) => format!("unused{}", parts.len()),
1128 _ => return Err("only plain identifier parameters are supported".into()),
1129 };
1130 let _ = i;
1131 parts.push(format!("{}: {}", ident(&pname), t.render()));
1132 }
1133 Ok(if ret == Nim::Unit {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1134 format!("proc {}*{}({})", ident(name), gens, parts.join(", "))
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1135 } else {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1136 format!(
1137 "proc {}*{}({}): {}",
1138 ident(name),
1139 gens,
1140 parts.join(", "),
1141 ret.render()
1142 )
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1143 })
1144 }
1145
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1146 fn signature(&self, sig: &syn::Signature) -> Result<(Vec<Nim>, Nim), String> {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago1147 // `unsafe fn` marks a contract for callers; it does not change what
1148 // the body means, so it lowers like any other proc.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1149 if sig.asyncness.is_some() {
1150 return Err(format!("`async fn {}`: Nim has no equivalent", sig.ident));
1151 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1152 // Lifetime parameters carry no runtime meaning and Nim is GC'd, so
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1153 // they disappear. Type parameters become Nim generic parameters.
1154 // Const parameters have no Nim equivalent and are still rejected.
1155 if sig.generics.params.iter().any(|p| matches!(p, syn::GenericParam::Const(_))) {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1156 return Err(format!(
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1157 "`fn {}` has a const generic parameter, which Nim has no \
1158 equivalent for",
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1159 sig.ident
1160 ));
1161 }
1162 let mut params = Vec::new();
1163 for a in &sig.inputs {
1164 if let FnArg::Typed(t) = a {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1165 params.push(self.map_ty(&t.ty)?);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1166 }
1167 }
1168 let ret = match &sig.output {
1169 ReturnType::Default => Nim::Unit,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1170 // A returned `&[T]` is a borrow of the caller's buffer, so it
1171 // stays an `openArray` view. Only an owned type (`Vec<T>`) becomes
1172 // a `seq`, which `owned()` would do to both.
1173 ReturnType::Type(_, t) => {
1174 let n = self.map_ty(t)?;
1175 if returns_borrow(t) { n } else { n.owned() }
1176 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1177 };
1178 Ok((params, ret))
1179 }
1180
1181 // --------------------------------------------------------------- items
1182
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1183 /// Emit the type definitions only: they must precede every signature.
1184 fn item_types(&mut self, item: &Item) -> Result<(), String> {
1185 if !self.cfg_keeps(item_attrs(item))? {
1186 return Ok(());
1187 }
1188 match item {
1189 Item::Struct(_) | Item::Enum(_) | Item::Const(_) => self.item_inner(item),
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 15h ago1190 Item::Macro(m) if path_name(&m.mac.path) == "bitflags" => self.item_inner(item),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1191 Item::Mod(m) if m.content.is_some() => {
1192 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
1193 for i in &items {
1194 self.item_types(i)?;
1195 }
1196 Ok(())
1197 }
1198 _ => Ok(()),
1199 }
1200 }
1201
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1202 fn item(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1203 if !self.cfg_keeps(item_attrs(item))? {
1204 return Ok(());
1205 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1206 // Types were emitted in their own pass.
1207 if matches!(item, Item::Struct(_) | Item::Enum(_) | Item::Const(_)) {
1208 return Ok(());
1209 }
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 15h ago1210 if matches!(item, Item::Macro(m) if path_name(&m.mac.path) == "bitflags") {
1211 return Ok(()); // emitted with the types
1212 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1213 self.item_inner(item)
1214 }
1215
1216 fn item_inner(&mut self, item: &Item) -> Result<(), String> {
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 16h ago1217 if !matches!(item, Item::Use(_) | Item::ExternCrate(_) | Item::Mod(_) | Item::Type(_)) {
1218 self.emitted += 1;
1219 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1220 match item {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago1221 Item::Fn(f) => {
1222 let nim = self.fn_name(&self.cur_mod, &f.sig.ident.to_string());
1223 self.func_named(&nim, &f.sig, &f.block, None)
1224 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1225 Item::Struct(s) => {
1226 let name = s.ident.to_string();
1227 let fields = self.structs[&name].clone();
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1228 let g = Self::gen_list(self.type_generics.get(&name).map(|v| &v[..]).unwrap_or(&[]));
1229 self.line(&format!("type {}*{} = object", ident(&name), g));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1230 self.indent += 1;
1231 if fields.is_empty() {
1232 self.line("discard");
1233 }
1234 for (fname, fty) in &fields {
1235 self.line(&format!("{}*: {}", ident(fname), fty.render()));
1236 }
1237 self.indent -= 1;
1238 self.blank();
1239 Ok(())
1240 }
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 15h ago1241 Item::Macro(m) if path_name(&m.mac.path) == "bitflags" => self.emit_bitflags(&m.mac),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1242 Item::Type(_) => Ok(()), // expanded at every use site
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago1243 Item::Trait(t) => {
1244 // We do not model trait resolution, so a declaration generates
1245 // nothing and a use that needed it is rejected where it
1246 // appears. A *default body*, though, is code: dropping it
1247 // would silently remove a method the impls inherit.
1248 for it in &t.items {
1249 if let syn::TraitItem::Fn(f) = it {
1250 if f.default.is_some() {
1251 return Err(format!(
1252 "`trait {}` gives `{}` a default body; trait \
1253 resolution is not modelled, so that body has no \
1254 impl to be emitted into and dropping it would \
1255 remove code",
1256 t.ident, f.sig.ident
1257 ));
1258 }
1259 }
1260 }
1261 Ok(())
1262 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1263 Item::Enum(e) => {
1264 let def = self.enums[&e.ident.to_string()].clone();
1265 self.emit_enum(&def);
1266 Ok(())
1267 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1268 Item::Const(c) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1269 let t = self.map_ty(&c.ty)?.owned();
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago1270 // The annotation types the initialiser, exactly as it does for
1271 // a `let`: `const MOD: u32 = 65521` is a u32 literal.
1272 let v = self.expr_at(&c.expr, Some(&t))?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1273 self.bind(&c.ident.to_string(), t.clone());
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago1274 // Only a top-level const is exported; `*` on a local is not
1275 // Nim syntax.
1276 let star = if self.indent == 0 { "*" } else { "" };
1277 let line = format!(
1278 "const {}{}: {} = {}",
1279 ident(&c.ident.to_string()),
1280 star,
1281 t.render(),
1282 v.code
1283 );
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1284 self.line(&line);
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago1285 if self.indent == 0 {
1286 self.blank();
1287 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1288 Ok(())
1289 }
1290 Item::Impl(im) => {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1291 let outer_g =
1292 std::mem::replace(&mut self.impl_generics, Self::generics_of(&im.generics));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1293 let self_ty = self.map_ty(&im.self_ty)?;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago1294 let outer = self.self_ty.replace(self_ty.clone());
1295 let r = self.impl_body(im, &self_ty);
1296 self.self_ty = outer;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1297 self.impl_generics = outer_g;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago1298 r
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1299 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1300 // `use` and `extern crate` are resolution directives with no Nim
1301 // analogue once everything is one module.
1302 Item::Use(_) | Item::ExternCrate(_) => Ok(()),
1303 Item::Mod(m) if m.content.is_some() => {
1304 // An inline `mod` is flattened; Nim has no nested modules in a
1305 // single file.
1306 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
1307 for i in &items {
1308 self.item(i)?;
1309 }
1310 Ok(())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1311 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1312 Item::Mod(m) => {
1313 // Satisfied if that file was passed in too; everything is one
1314 // Nim module, so the declaration itself emits nothing.
1315 if self.modules.iter().any(|x| *x == m.ident.to_string()) {
1316 return Ok(());
1317 }
1318 Err(format!(
1319 "`mod {};` refers to another file that was not passed to \
1320 rustnim; add it to the input list",
1321 m.ident
1322 ))
1323 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1324 other => Err(format!("unsupported item: {}", item_kind(other))),
1325 }
1326 }
1327
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1328 /// `None` carries no type of its own, so Nim needs the `Option[T]` named.
1329 fn none_of(&self, expect: Option<&Nim>) -> String {
1330 match expect {
1331 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => {
1332 format!("rsNone[{}]()", a[0].render())
1333 }
1334 _ => "rsNone()".to_string(),
1335 }
1336 }
1337
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago1338 fn impl_body(&mut self, im: &syn::ItemImpl, self_ty: &Nim) -> Result<(), String> {
1339 if let Some((path, _)) = &im.trait_ {
1340 let tr = path_name(path);
1341 if im.items.is_empty() {
1342 return Ok(());
1343 }
1344 if is_fmt_trait(&tr) {
1345 let syn::ImplItem::Fn(m) = &im.items[0] else {
1346 return Err(format!("unsupported item in `impl {tr}`"));
1347 };
1348 return self.fmt_impl(&tr, self_ty, &m.sig, &m.block);
1349 }
1350 if tr == "From" {
1351 let syn::ImplItem::Fn(m) = &im.items[0] else {
1352 return Err("`impl From` must contain `fn from`".into());
1353 };
1354 let name = {
1355 let (params, _) = self.signature(&m.sig)?;
1356 let src = params.first().cloned().ok_or("`fn from` takes one argument")?;
1357 self.from_impls[&(type_name(&src), type_name(self_ty))].clone()
1358 };
1359 return self.func_named(&name, &m.sig, &m.block, None);
1360 }
1361 let tyname = type_name(self_ty);
1362 for it in &im.items {
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago1363 if let syn::ImplItem::Const(c) = it {
1364 self.assoc_const(&tyname, c)?;
1365 continue;
1366 }
1367 if matches!(it, syn::ImplItem::Type(_)) {
1368 continue; // a type binding emits nothing
1369 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago1370 let syn::ImplItem::Fn(m) = it else {
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago1371 return Err(format!(
1372 "unsupported item in `impl {tr}`: only `fn`, `type` and \
1373 `const` are implemented"
1374 ));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago1375 };
1376 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
1377 let nim = trait_method_name(&tyname, &tr, &m.sig.ident.to_string());
1378 self.func_named(&nim, &m.sig, &m.block, recv)?;
1379 }
1380 return Ok(());
1381 }
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago1382 let tyname = type_name(self_ty);
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago1383 for it in &im.items {
1384 match it {
1385 syn::ImplItem::Fn(m) => {
1386 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
1387 let nim = self.fn_name(&self.cur_mod, &m.sig.ident.to_string());
1388 self.func_named(&nim, &m.sig, &m.block, recv)?;
1389 }
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago1390 syn::ImplItem::Type(_) => {}
1391 syn::ImplItem::Const(c) => self.assoc_const(&tyname, c)?,
1392 _ => {
1393 return Err("only `fn`, `type` and `const` items are supported \
1394 inside `impl`"
1395 .into())
1396 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago1397 }
1398 }
1399 Ok(())
1400 }
1401
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago1402 /// `const N: usize = 4;` inside an `impl`. Nim has no per-type constant
1403 /// namespace, so it becomes a module-level const named for both.
1404 fn assoc_const(&mut self, tyname: &str, c: &syn::ImplItemConst) -> Result<(), String> {
1405 let t = self.map_ty(&c.ty)?.owned();
1406 let v = self.expr_at(&c.expr, Some(&t))?;
1407 let name = format!("{}_{}", tyname, c.ident);
1408 self.line(&format!("const {}*: {} = {}", ident(&name), t.render(), v.code));
1409 self.blank();
1410 self.assoc_consts
1411 .insert((tyname.to_string(), c.ident.to_string()), (ident(&name), t));
1412 Ok(())
1413 }
1414
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago1415 /// The type an operator impl declares for its right-hand operand.
1416 fn op_param(&self, t: &Option<Nim>, op: &str) -> Option<Nim> {
1417 let n = type_name(t.as_ref()?);
1418 let sig = self.methods.get(&(n, op_method(op).to_string()))?;
1419 sig.params.get(1).cloned().map(|t| t.unvar())
1420 }
1421
1422 /// The proc implementing `op` for a user type, if there is one.
1423 fn op_proc(&self, t: &Option<Nim>, op: &str) -> Option<String> {
1424 let n = type_name(t.as_ref()?);
1425 let tr = OPERATOR_TRAITS.iter().find(|(_, o)| *o == op)?.0;
1426 if self.op_impls.contains_key(&(n.clone(), op.to_string())) {
1427 Some(trait_method_name(&n, tr, OP_METHOD.iter().find(|(o, _)| *o == op)?.1))
1428 } else {
1429 None
1430 }
1431 }
1432
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 15h ago1433 /// Register a `bitflags!` type's operations so call sites resolve.
1434 fn collect_bitflags(&mut self, mac: &syn::Macro) -> Result<(), String> {
1435 let input: crate::macros::BitflagsInput = mac
1436 .parse_body()
1437 .map_err(|e| format!("`bitflags!`: {e}"))?;
1438 for def in &input.0 {
1439 let name = def.name.to_string();
1440 let repr = self.map_ty(&def.repr)?;
1441 if !repr.is_integer() {
1442 return Err(format!("`bitflags! {name}` needs an integer representation"));
1443 }
1444 let me = Nim::Named(name.clone(), vec![]);
1445 let b = Nim::Prim("bool".into());
1446 self.structs
1447 .insert(name.clone(), vec![("bitsField".into(), repr.clone())]);
1448 self.type_generics.insert(name.clone(), Vec::new());
1449
1450 let mut m = |n: &str, params: Vec<Nim>, ret: Nim, nim: String| {
1451 self.methods.insert(
1452 (name.clone(), n.to_string()),
1453 Sig { params, ret, generics: Vec::new() },
1454 );
1455 self.statics.insert((name.clone(), n.to_string()), nim);
1456 };
1457 let s1 = vec![me.clone()];
1458 let s2 = vec![me.clone(), me.clone()];
1459 let vs2 = vec![Nim::Var(Box::new(me.clone())), me.clone()];
1460 m("bits", s1.clone(), repr.clone(), format!("{name}_bits"));
1461 m("is_empty", s1.clone(), b.clone(), format!("{name}_is_empty"));
1462 m("is_all", s1.clone(), b.clone(), format!("{name}_is_all"));
1463 m("contains", s2.clone(), b.clone(), format!("{name}_contains"));
1464 m("intersects", s2.clone(), b.clone(), format!("{name}_intersects"));
1465 for (rust, nim) in [
1466 ("union", "union"),
1467 ("intersection", "intersection"),
1468 ("difference", "difference"),
1469 ("symmetric_difference", "symmetric_difference"),
1470 ] {
1471 m(rust, s2.clone(), me.clone(), format!("{name}_{nim}"));
1472 }
1473 for n in ["insert", "remove", "toggle"] {
1474 m(n, vs2.clone(), Nim::Unit, format!("{name}_{n}"));
1475 }
1476 m(
1477 "set",
1478 vec![Nim::Var(Box::new(me.clone())), me.clone(), b.clone()],
1479 Nim::Unit,
1480 format!("{name}_set"),
1481 );
1482 m("empty", vec![], me.clone(), format!("{name}_empty"));
1483 m("all", vec![], me.clone(), format!("{name}_all"));
1484 m(
1485 "from_bits",
1486 vec![repr.clone()],
1487 Nim::Named("Option".into(), vec![me.clone()]),
1488 format!("{name}_from_bits"),
1489 );
1490 m(
1491 "from_bits_truncate",
1492 vec![repr.clone()],
1493 me.clone(),
1494 format!("{name}_from_bits_truncate"),
1495 );
1496 m("complement", s1.clone(), me.clone(), format!("{name}_complement"));
1497
1498 // The operator forms, routed through the same dispatch that a
1499 // hand-written `impl BitOr` would use.
1500 for (op, trait_name, method) in [
1501 ("|", "BitOr", "bitor"),
1502 ("&", "BitAnd", "bitand"),
1503 ("^", "BitXor", "bitxor"),
1504 ("-", "Sub", "sub"),
1505 ("not", "Not", "not"),
1506 ] {
1507 self.op_impls.insert((name.clone(), op.to_string()), ());
1508 let params = if op == "not" { s1.clone() } else { s2.clone() };
1509 self.methods.insert(
1510 (name.clone(), method.to_string()),
1511 Sig { params, ret: me.clone(), generics: Vec::new() },
1512 );
1513 let _ = trait_name;
1514 }
1515 self.bitflags.insert(name);
1516 }
1517 Ok(())
1518 }
1519
1520 /// Emit the Nim for a `bitflags!` type. See `src/macros.rs` for why this
1521 /// is lowered directly rather than by expanding the macro.
1522 fn emit_bitflags(&mut self, mac: &syn::Macro) -> Result<(), String> {
1523 let input: crate::macros::BitflagsInput = mac
1524 .parse_body()
1525 .map_err(|e| format!("`bitflags!`: {e}"))?;
1526 for def in &input.0 {
1527 let name = def.name.to_string();
1528 let repr = self.map_ty(&def.repr)?;
1529 let r = repr.render();
1530
1531 self.line(&format!("type {name}* = object"));
1532 self.line(&format!(" bitsField*: {r}"));
1533 self.blank();
1534 self.line(&format!("proc {name}_bits*(x: {name}): {r} = x.bitsField"));
1535
1536 // The constants. A flag's value may name earlier flags, as
1537 // `const ALL = Self::READ.bits() | ..` does, so they are emitted
1538 // in order and each is in scope for the next.
1539 self.push_scope();
1540 self.bind_static_type(&name, &repr);
1541 for (fname, value) in &def.flags {
1542 let v = self.expr_at(value, Some(&repr))?;
1543 self.line(&format!(
1544 "const {}{}* = {}(bitsField: {})",
1545 name, fname, name, v.code
1546 ));
1547 self.flag_consts
1548 .insert((name.clone(), fname.to_string()), format!("{name}{fname}"));
1549 }
1550 self.pop_scope();
1551
1552 let all: Vec<String> = def
1553 .flags
1554 .iter()
1555 .map(|(f, _)| format!("{name}{f}.bitsField"))
1556 .collect();
1557 let all_bits = if all.is_empty() {
1558 format!("{}(0)", r)
1559 } else {
1560 all.join(" or ")
1561 };
1562 self.blank();
1563 self.line(&format!("const {name}AllBits: {r} = {all_bits}"));
1564 self.blank();
1565
1566 for l in [
1567 format!("proc {name}_empty*(): {name} = {name}(bitsField: {r}(0))"),
1568 format!("proc {name}_all*(): {name} = {name}(bitsField: {name}AllBits)"),
1569 format!("proc {name}_is_empty*(x: {name}): bool = x.bitsField == {r}(0)"),
1570 format!("proc {name}_is_all*(x: {name}): bool = (x.bitsField and {name}AllBits) == {name}AllBits"),
1571 format!("proc {name}_contains*(a, b: {name}): bool = (a.bitsField and b.bitsField) == b.bitsField"),
1572 format!("proc {name}_intersects*(a, b: {name}): bool = (a.bitsField and b.bitsField) != {r}(0)"),
1573 format!("proc {name}_union*(a, b: {name}): {name} = {name}(bitsField: a.bitsField or b.bitsField)"),
1574 format!("proc {name}_intersection*(a, b: {name}): {name} = {name}(bitsField: a.bitsField and b.bitsField)"),
1575 format!("proc {name}_difference*(a, b: {name}): {name} = {name}(bitsField: a.bitsField and (not b.bitsField))"),
1576 format!("proc {name}_symmetric_difference*(a, b: {name}): {name} = {name}(bitsField: a.bitsField xor b.bitsField)"),
1577 // `!x` complements and then masks to `all()`, which is what
1578 // bitflags does and not what a plain `not` would give.
1579 format!("proc {name}_complement*(x: {name}): {name} = {name}(bitsField: (not x.bitsField) and {name}AllBits)"),
1580 format!("proc {name}_from_bits_truncate*(b: {r}): {name} = {name}(bitsField: b and {name}AllBits)"),
1581 format!("proc {name}_from_bits*(b: {r}): Option[{name}] ="),
1582 format!(" if (b and (not {name}AllBits)) != {r}(0): rsNone[{name}]() else: rsSome({name}(bitsField: b))"),
1583 format!("proc {name}_insert*(x: var {name}, o: {name}) = x.bitsField = x.bitsField or o.bitsField"),
1584 format!("proc {name}_remove*(x: var {name}, o: {name}) = x.bitsField = x.bitsField and (not o.bitsField)"),
1585 format!("proc {name}_toggle*(x: var {name}, o: {name}) = x.bitsField = x.bitsField xor o.bitsField"),
1586 format!("proc {name}_set*(x: var {name}, o: {name}, on: bool) ="),
1587 format!(" if on: {name}_insert(x, o) else: {name}_remove(x, o)"),
1588 format!("proc rsBitOr_{name}_bitor*(a, b: {name}): {name} = {name}_union(a, b)"),
1589 format!("proc rsBitAnd_{name}_bitand*(a, b: {name}): {name} = {name}_intersection(a, b)"),
1590 format!("proc rsBitXor_{name}_bitxor*(a, b: {name}): {name} = {name}_symmetric_difference(a, b)"),
1591 format!("proc rsSub_{name}_sub*(a, b: {name}): {name} = {name}_difference(a, b)"),
1592 format!("proc rsNot_{name}_not*(a: {name}): {name} = {name}_complement(a)"),
1593 ] {
1594 self.line(&l);
1595 }
1596
1597 // Debug prints the set flag names, or `0x0` when empty -- again
1598 // matching the crate rather than a guess.
1599 self.line(&format!("proc rsDebug*(x: {name}): string ="));
1600 self.line(&format!(" result = \"{name}(\""));
1601 self.line(" var first = true");
1602 for (fname, _) in &def.flags {
1603 self.line(&format!(
1604 " if (x.bitsField and {name}{f}.bitsField) == {name}{f}.bitsField and {name}{f}.bitsField != {r}(0):",
1605 f = fname
1606 ));
1607 self.line(" if not first: result.add(\" | \")");
1608 self.line(&format!(" result.add(\"{fname}\")"));
1609 self.line(" first = false");
1610 }
1611 self.line(" if first: result.add(\"0x0\")");
1612 self.line(" result.add(\")\")");
1613 self.blank();
1614 }
1615 Ok(())
1616 }
1617
1618 fn bind_static_type(&mut self, _name: &str, _repr: &Nim) {}
1619
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1620 fn emit_enum(&mut self, def: &EnumDef) {
1621 let name = ident(&def.name);
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1622 let g = Self::gen_list(
1623 self.type_generics.get(&def.name).map(|v| &v[..]).unwrap_or(&[]),
1624 );
1625 if def.simple && !g.is_empty() {
1626 // A Nim `enum` cannot take parameters; an all-unit generic enum
1627 // has no payload to be generic in anyway, so this would be a
1628 // parameter that never appears.
1629 // Fall through to the object-variant form instead.
1630 }
1631 if def.simple && g.is_empty() {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1632 // Every variant is a unit variant, so a plain Nim enum is an exact
1633 // fit: it compares, orders and `case`-checks like Rust's.
1634 self.line(&format!("type {name}* = enum"));
1635 self.indent += 1;
1636 for v in &def.variants {
1637 self.line(&format!("{}", ident(&v.name)));
1638 }
1639 self.indent -= 1;
1640 self.blank();
1641 self.line(&format!("proc rsDebug*(x: {name}): string ="));
1642 self.indent += 1;
1643 self.line("case x");
1644 for v in &def.variants {
1645 self.line(&format!("of {}.{}: \"{}\"", name, ident(&v.name), v.name));
1646 }
1647 self.indent -= 1;
1648 self.blank();
1649 return;
1650 }
1651
1652 // A data-carrying enum is a Nim object variant: one discriminant enum
1653 // plus a branch per variant. This is the same shape the prelude uses
1654 // for `Option` and `Result`.
1655 self.line("type");
1656 self.indent += 1;
1657 self.line(&format!("{}Kind* = enum", name));
1658 self.indent += 1;
1659 for v in &def.variants {
1660 self.line(&def.kind_ident(&v.name));
1661 }
1662 self.indent -= 1;
1663 self.blank();
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1664 self.line(&format!("{}*{} = object", name, g));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1665 self.indent += 1;
1666 self.line(&format!("case kind*: {}Kind", name));
1667 for v in &def.variants {
1668 if v.fields.is_empty() {
1669 self.line(&format!("of {}: discard", def.kind_ident(&v.name)));
1670 } else {
1671 self.line(&format!("of {}:", def.kind_ident(&v.name)));
1672 self.indent += 1;
1673 for (f, t) in &v.fields {
1674 self.line(&format!("{}*: {}", ident(f), t.render()));
1675 }
1676 self.indent -= 1;
1677 }
1678 }
1679 self.indent -= 2;
1680 self.blank();
1681
1682 for v in &def.variants {
1683 let args: Vec<String> = v
1684 .fields
1685 .iter()
1686 .enumerate()
1687 .map(|(i, (_, t))| format!("a{}: {}", i, t.render()))
1688 .collect();
1689 let inits: Vec<String> = v
1690 .fields
1691 .iter()
1692 .enumerate()
1693 .map(|(i, (f, _))| format!("{}: a{}", ident(f), i))
1694 .collect();
1695 let mut all = vec![format!("kind: {}", def.kind_ident(&v.name))];
1696 all.extend(inits);
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1697 let ret = format!("{}{}", name, g);
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1698 self.line(&format!(
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1699 "proc {}*{}({}): {} = {}({})",
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1700 def.ctor_ident(&v.name),
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1701 g,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1702 args.join(", "),
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1703 ret,
1704 ret,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1705 all.join(", ")
1706 ));
1707 }
1708 self.blank();
1709
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1710 self.line(&format!("proc rsDebug*{}(x: {}{}): string =", g, name, g));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1711 self.indent += 1;
1712 self.line("case x.kind");
1713 for v in &def.variants {
1714 if v.fields.is_empty() {
1715 self.line(&format!("of {}: \"{}\"", def.kind_ident(&v.name), v.name));
1716 } else {
1717 let parts: Vec<String> = v
1718 .fields
1719 .iter()
1720 .map(|(f, _)| format!("rsDebug(x.{})", ident(f)))
1721 .collect();
1722 self.line(&format!(
1723 "of {}: \"{}(\" & {} & \")\"",
1724 def.kind_ident(&v.name),
1725 v.name,
1726 parts.join(" & \", \" & ")
1727 ));
1728 }
1729 }
1730 self.indent -= 1;
1731 self.blank();
1732 }
1733
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1734 /// The concrete type an enum variant constructs, and the `[T]` list to
1735 /// spell at the constructor when the enum is generic.
1736 fn variant_type(
1737 &self,
1738 def: &EnumDef,
1739 expect: Option<&Nim>,
1740 ) -> Result<(Nim, String), String> {
1741 let params = self.type_generics.get(&def.name).cloned().unwrap_or_default();
1742 if params.is_empty() {
1743 return Ok((Nim::Named(def.name.clone(), vec![]), String::new()));
1744 }
1745 match expect {
1746 Some(Nim::Named(n, a)) if *n == def.name && a.len() == params.len() => Ok((
1747 Nim::Named(def.name.clone(), a.clone()),
1748 format!("[{}]", a.iter().map(|t| t.render()).collect::<Vec<_>>().join(", ")),
1749 )),
1750 _ => Err(format!(
1751 "`{}` is a variant of a generic enum, and its type parameters \
1752 cannot be inferred here; annotate the binding or the return type",
1753 def.name
1754 )),
1755 }
1756 }
1757
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago1758 /// Resolve a Rust path like `Error::InvalidLength` or a bare `InvalidLength`
1759 /// to the enum that declares it.
1760 fn resolve_variant(&self, path: &syn::Path) -> Option<(EnumDef, String)> {
1761 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
1762 let last = segs.last()?.clone();
1763 if segs.len() >= 2 {
1764 if let Some(def) = self.enums.get(&segs[segs.len() - 2]) {
1765 if def.get(&last).is_some() {
1766 return Some((def.clone(), last));
1767 }
1768 }
1769 }
1770 // Unqualified: only unambiguous if exactly one enum declares it.
1771 match self.variant_owner.get(&last) {
1772 Some(owners) if owners.len() == 1 => {
1773 let def = self.enums.get(&owners[0])?;
1774 Some((def.clone(), last))
1775 }
1776 _ => None,
1777 }
1778 }
1779
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1780 /// Lower `impl Display for T`'s `fn fmt` into a proc returning a string.
1781 ///
1782 /// Rust's `Formatter` is a sink that a `fmt` method writes into; the
1783 /// observable result of `{}` is exactly the bytes written. So the method
1784 /// becomes `proc rsDisplay(self: T): string` and every write through the
1785 /// formatter produces that string. A `fmt` body that does anything else
1786 /// with the formatter -- padding, precision, `debug_struct` -- is rejected,
1787 /// because those affect the output and this model does not carry them.
1788 /// The window an expression names, if it names one.
1789 fn window_of(&self, e: &Expr) -> Option<Alias> {
1790 match e {
1791 Expr::Path(p) => match self.lookup_alias(&path_name(&p.path)) {
1792 Some(a @ Alias::Window { .. }) => Some(a),
1793 _ => None,
1794 },
1795 Expr::Reference(r) => self.window_of(&r.expr),
1796 Expr::Paren(p) => self.window_of(&p.expr),
1797 Expr::Unary(u) if matches!(u.op, UnOp::Deref(_)) => self.window_of(&u.expr),
1798 _ => None,
1799 }
1800 }
1801
1802 /// Whether an expression is the `Formatter` parameter of the formatting
1803 /// impl currently being lowered.
1804 fn is_fmt_param(&self, e: &Expr) -> bool {
1805 let Some(f) = &self.fmt_param else { return false };
1806 match e {
1807 Expr::Path(p) => path_name(&p.path) == *f,
1808 Expr::Reference(r) => self.is_fmt_param(&r.expr),
1809 Expr::Paren(p) => self.is_fmt_param(&p.expr),
1810 _ => false,
1811 }
1812 }
1813
1814 fn fmt_impl(
1815 &mut self,
1816 tr: &str,
1817 self_ty: &Nim,
1818 sig: &syn::Signature,
1819 body: &syn::Block,
1820 ) -> Result<(), String> {
1821 let proc_name = fmt_proc(tr);
1822 // The formatter is the parameter after `self`.
1823 let f = sig
1824 .inputs
1825 .iter()
1826 .filter_map(|a| match a {
1827 FnArg::Typed(t) => match &*t.pat {
1828 Pat::Ident(i) => Some(i.ident.to_string()),
1829 _ => None,
1830 },
1831 _ => None,
1832 })
1833 .next()
1834 .ok_or("`fn fmt` needs a `Formatter` parameter")?;
1835
1836 self.push_scope();
1837 self.bind("self", self_ty.clone());
1838 let saved = self.fmt_param.replace(f);
1839 let outer_ret = self.ret.replace(Nim::Prim("string".into()));
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago1840 // No assignment target: a formatter write *appends*, because a `fmt`
1841 // body may write repeatedly -- `UpperHex` writes once per byte in a
1842 // loop -- and assigning would keep only the last one.
1843 let outer_target = self.target.take();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1844
1845 self.line(&format!(
1846 "proc {}*(self: {}): string =",
1847 proc_name,
1848 self_ty.render()
1849 ));
1850 self.indent += 1;
1851 let before = self.out.len();
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago1852 let tail = self.block_body(body)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1853 self.emit_tail(tail);
1854 if self.out.len() == before {
1855 self.line("discard");
1856 }
1857 self.indent -= 1;
1858
1859 self.target = outer_target;
1860 self.ret = outer_ret;
1861 self.fmt_param = saved;
1862 self.pop_scope();
1863 self.blank();
1864 Ok(())
1865 }
1866
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1867 fn func(
1868 &mut self,
1869 sig: &syn::Signature,
1870 body: &syn::Block,
1871 recv: Option<Nim>,
1872 ) -> Result<(), String> {
1873 let name = sig.ident.to_string();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1874 self.func_named(&name.clone(), sig, body, recv)
1875 }
1876
1877 fn func_named(
1878 &mut self,
1879 name: &str,
1880 sig: &syn::Signature,
1881 body: &syn::Block,
1882 recv: Option<Nim>,
1883 ) -> Result<(), String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1884 let (ptys, ret) = self.signature(sig)?;
1885
1886 self.push_scope();
1887 let mut rendered: Vec<String> = Vec::new();
1888
1889 if let Some(self_ty) = recv {
1890 // `&mut self` and `mut self` both mean the body may mutate the
1891 // receiver; only the former is observable by the caller, and a Nim
1892 // `var` parameter is the faithful spelling of that.
1893 let mutable = matches!(
1894 sig.inputs.first(),
1895 Some(FnArg::Receiver(r))
1896 if matches!(&r.kind, syn::ReceiverKind::Reference(_, _, m) if m.is_some())
1897 );
1898 let t = if mutable { Nim::Var(Box::new(self_ty.clone())) } else { self_ty.clone() };
1899 rendered.push(format!("self: {}", t.render()));
1900 self.bind("self", self_ty);
1901 }
1902
1903 let typed: Vec<&syn::PatType> = sig
1904 .inputs
1905 .iter()
1906 .filter_map(|a| match a {
1907 FnArg::Typed(t) => Some(t),
1908 _ => None,
1909 })
1910 .collect();
1911 for (p, t) in typed.iter().zip(ptys.iter()) {
1912 let pname = match &*p.pat {
1913 Pat::Ident(i) => i.ident.to_string(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago1914 // `fn from(_: Error) -> ..` — the parameter is unused, but Nim
1915 // still needs a name for it.
1916 Pat::Wild(_) => format!("unused{}", rendered.len()),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1917 _ => return Err("only plain identifier parameters are supported".into()),
1918 };
1919 rendered.push(format!("{}: {}", ident(&pname), t.render()));
1920 // Inside the body a `var T` parameter is used exactly like a `T`.
1921 self.bind(&pname, t.clone().owned());
1922 }
1923
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1924 let mut gparams = self.impl_generics.clone();
1925 for g in Self::generics_of(&sig.generics) {
1926 if !gparams.contains(&g) {
1927 gparams.push(g);
1928 }
1929 }
1930 let gens = Self::gen_list(&gparams);
1931 let outer_fg = std::mem::replace(&mut self.fn_generics, gparams.clone());
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1932 let head = if ret == Nim::Unit {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1933 format!("proc {}*{}({}) =", ident(name), gens, rendered.join(", "))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1934 } else {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1935 format!(
1936 "proc {}*{}({}): {} =",
1937 ident(name),
1938 gens,
1939 rendered.join(", "),
1940 ret.render()
1941 )
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1942 };
1943 self.line(&head);
1944 self.indent += 1;
1945 let outer_ret = self.ret.replace(ret.clone());
1946
1947 // A Rust fn's trailing expression is its return value. Naming Nim's
1948 // implicit `result` as the target makes that true whether the tail is
1949 // a plain expression or an `if`/`match` with statement arms.
1950 let outer_target = if ret == Nim::Unit {
1951 self.target.take()
1952 } else {
1953 self.target.replace(("result".to_string(), Some(ret.clone())))
1954 };
1955 let before = self.out.len();
1956 let tail = self.block_body_at(body, Some(&ret))?;
1957 self.target = outer_target;
1958 match tail {
1959 Some(v) if ret != Nim::Unit => {
1960 let code = v.code.clone();
1961 self.line(&format!("result = {code}"));
1962 }
1963 Some(v) => {
1964 // A trailing expression in a `()`-returning fn is evaluated for
1965 // its effect; Nim requires an explicit discard.
1966 let needs_discard = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
1967 if needs_discard && !v.code.is_empty() {
1968 let code = v.code.clone();
1969 self.line(&format!("discard {code}"));
1970 }
1971 }
1972 None => {}
1973 }
1974 if self.out.len() == before {
1975 self.line("discard");
1976 }
1977
1978 self.indent -= 1;
1979 self.ret = outer_ret;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago1980 self.fn_generics = outer_fg;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago1981 self.pop_scope();
1982 self.blank();
1983 Ok(())
1984 }
1985
1986 // ---------------------------------------------------------- statements
1987
1988 /// Lower a block's statements. Returns the block's trailing expression,
1989 /// if it has one, *without* emitting it — the caller decides whether that
1990 /// value is a return value, a binding, or discarded.
1991 fn block_body(&mut self, b: &syn::Block) -> Result<Option<Val>, String> {
1992 self.block_body_at(b, None)
1993 }
1994
1995 fn block_body_at(
1996 &mut self,
1997 b: &syn::Block,
1998 expect: Option<&Nim>,
1999 ) -> Result<Option<Val>, String> {
2000 // An assignment target belongs to *this* block's trailing expression
2001 // only. A non-final `if` is a statement and must not assign anything.
2002 let target = self.target.take();
2003 let n = b.stmts.len();
2004 let mut tail = None;
2005 for (i, st) in b.stmts.iter().enumerate() {
2006 let last = i + 1 == n;
2007 match st {
2008 Stmt::Expr(e, None) if last && expressible(e) => {
2009 tail = Some(self.expr_at(e, expect)?)
2010 }
2011 Stmt::Expr(e, None) if last => {
2012 // A trailing `if`/`match` with statement arms, or a loop.
2013 // Lower it as statements; if this block's value is wanted,
2014 // each arm assigns it.
2015 match &target {
2016 Some((t, ty)) => {
2017 let (t, ty) = (t.clone(), ty.clone());
2018 self.assign_from(e, &t, ty.as_ref())?;
2019 }
2020 None => self.stmt(st)?,
2021 }
2022 }
2023 _ => self.stmt(st)?,
2024 }
2025 }
2026 self.target = target;
2027 Ok(tail)
2028 }
2029
2030 /// Lower a block in statement position (loop bodies, `if` arms).
2031 fn nested_block(&mut self, b: &syn::Block) -> Result<(), String> {
2032 self.push_scope();
2033 self.indent += 1;
2034 let before = self.out.len();
2035 let want = self.target.clone().and_then(|(_, t)| t);
2036 let tail = self.block_body_at(b, want.as_ref())?;
2037 self.emit_tail(tail);
2038 if self.out.len() == before {
2039 self.line("discard");
2040 }
2041 self.indent -= 1;
2042 self.pop_scope();
2043 Ok(())
2044 }
2045
2046 fn stmt(&mut self, s: &Stmt) -> Result<(), String> {
2047 match s {
2048 Stmt::Local(l) => self.local(l),
2049 Stmt::Expr(e, _) => {
2050 let v = self.expr_stmt(e)?;
2051 if let Some(v) = v {
2052 // A bare expression with a value must be discarded in Nim.
2053 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
2054 let code = v.code.clone();
2055 if needs {
2056 self.line(&format!("discard {code}"));
2057 } else if !code.is_empty() {
2058 self.line(&code);
2059 }
2060 }
2061 Ok(())
2062 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago2063 // A `const` declared inside a function body is local to it, and
2064 // must be emitted here rather than skipped as an already-emitted
2065 // top-level type.
2066 Stmt::Item(i) => self.item_inner(i),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2067 Stmt::Macro(m) => {
2068 let line = self.macro_call(&m.mac)?;
2069 self.line(&line);
2070 Ok(())
2071 }
2072 }
2073 }
2074
2075 fn local(&mut self, l: &Local) -> Result<(), String> {
2076 let (name, mutable, ann): (String, bool, Option<Nim>) = match &l.pat {
2077 Pat::Ident(i) => (i.ident.to_string(), i.mutability.is_some(), None),
2078 Pat::Type(t) => match &*t.pat {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2079 Pat::Ident(i) => (i.ident.to_string(), i.mutability.is_some(), Some(self.map_ty(&t.ty)?)),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2080 _ => return Err("only `let <ident>` bindings are supported".into()),
2081 },
2082 Pat::Wild(_) => ("_".into(), false, None),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago2083 Pat::Tuple(t) => return self.local_tuple(l, t),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2084 _ => return Err("destructuring `let` is not implemented yet".into()),
2085 };
2086
2087 let Some(init) = &l.init else {
2088 // `let x: T;` — Nim's `var x: T` zero-initialises, which Rust does
2089 // not. Rust's own rules make reading it before assignment illegal,
2090 // so the two agree on every program rustc accepts.
2091 let t = ann.ok_or("`let` without an initialiser needs a type annotation")?;
2092 let t = t.owned();
2093 self.line(&format!("var {}: {}", ident(&name), t.render()));
2094 self.bind(&name, t);
2095 return Ok(());
2096 };
2097 if init.diverge.is_some() {
2098 return Err("`let ... else` is not implemented yet".into());
2099 }
2100
2101 if !expressible(&init.expr) && name != "_" {
2102 // The initialiser is an `if`/`match` whose arms are statements.
2103 // Declare first, then let each arm assign into the binding.
2104 let t = ann
2105 .clone()
2106 .ok_or_else(|| {
2107 format!(
2108 "`let {name} = match/if ...` needs a type annotation: \
2109 its arms are statements, so the binding must be \
2110 declared before they run"
2111 )
2112 })?
2113 .owned();
2114 self.line(&format!("var {}: {}", ident(&name), t.render()));
2115 self.bind(&name, t.clone());
2116 let target = ident(&name);
2117 return self.assign_from(&init.expr, &target, Some(&t));
2118 }
2119
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago2120 // `let it = xs.chunks_exact(k)` binds an iterator, not a value.
2121 if is_iterator_expr(&init.expr) {
2122 let it = self.resolve_iter(&init.expr)?;
2123 self.bind_alias(&name, Alias::Iterator(Box::new(it)));
2124 return Ok(());
2125 }
2126
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2127 let v = self.expr_at(&init.expr, ann.as_ref())?;
Prove byte-identity for base16ct by enumerating whole input domains 99b8376 nandithebull 16h ago2128
2129 // `let s = &buf[..n]` binds a view of a place that is already in
2130 // scope. Nim's borrow checker will not let a `let` borrow out of a
2131 // local, and there is nothing to materialise anyway -- a view is a
2132 // reference. Binding it as an alias substitutes the same expression at
2133 // each use, which re-evaluates nothing because the initialiser is a
2134 // place expression with no side effects.
2135 if v.window.is_none()
2136 && matches!(v.ty, Some(Nim::OpenArray(_)))
2137 && is_pure_place(&init.expr)
2138 {
2139 let t = v.ty.clone().unwrap();
2140 let elem = match &t {
2141 Nim::OpenArray(e) => Some((**e).clone()),
2142 _ => None,
2143 };
2144 self.bind_alias(&name, Alias::Value { code: v.code.clone(), ty: Some(t) });
2145 let _ = elem;
2146 return Ok(());
2147 }
2148
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2149 if let Some(w) = v.window.clone() {
2150 // `let dst = dst.get_mut(..n).ok_or(..)?;` -- the binding names a
2151 // view into the caller's buffer. Copying it into a `seq` would
2152 // still print the right bytes but would stop writes reaching the
2153 // caller, so it is bound as an alias.
2154 if v.guard.is_some() && v.guard_err.is_some() {
2155 return Err(format!(
2156 "`let {name} = ...get(..)` keeps an `Option` of a slice view, \
2157 which Nim cannot represent; apply `?` or `unwrap()` to it \
2158 in the same expression"
2159 ));
2160 }
2161 self.bind_alias(&name, w);
2162 return Ok(());
2163 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago2164 // A `let` binding a borrow keeps the view: `let res = encode(..)?`
2165 // names the caller's buffer, and copying it into a `seq` would still
2166 // print the right bytes while silently breaking the aliasing.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2167 let t = match (ann, &v.ty) {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago2168 (Some(a), _) => a.unvar(),
2169 (None, Some(t)) => t.clone().unvar(),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2170 (None, None) => {
2171 return Err(format!(
2172 "cannot infer the type of `let {name}`; annotate it — \
2173 guessing here would change integer width, and with it the \
2174 meaning of any arithmetic on `{name}`"
2175 ))
2176 }
2177 };
2178
2179 if name == "_" {
2180 let code = v.code.clone();
2181 self.line(&format!("discard {code}"));
2182 return Ok(());
2183 }
2184 // Rust's immutable `let` is Nim's `let`; `let mut` is `var`. Shadowing
2185 // works in both, so a re-`let` of the same name needs no rename.
Prove byte-identity for base16ct by enumerating whole input domains 99b8376 nandithebull 16h ago2186 //
2187 // `let x = &mut y[..n]` is an immutable binding of a *mutable* borrow:
2188 // Rust may write through it, and Nim only accepts a `var` where a
2189 // `var` parameter is wanted, so the binding has to be one.
2190 let mutable = mutable || is_mut_borrow(&init.expr);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2191 let kw = if mutable { "var" } else { "let" };
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago2192 // Inside a generic proc the binding's type may mention a parameter Nim
2193 // will infer; naming it in an annotation would not resolve.
2194 let line = if self.mentions_type_param(&t) {
2195 format!("{} {} = {}", kw, ident(&name), v.code)
2196 } else {
2197 format!("{} {}: {} = {}", kw, ident(&name), t.render(), v.code)
2198 };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2199 self.line(&line);
2200 self.bind(&name, t);
2201 Ok(())
2202 }
2203
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago2204 /// `let (a, b) = ..` — tuple destructuring.
2205 fn local_tuple(&mut self, l: &Local, t: &syn::PatTuple) -> Result<(), String> {
2206 let Some(init) = &l.init else {
2207 return Err("a destructuring `let` needs an initialiser".into());
2208 };
2209 let names: Vec<(String, bool)> = t
2210 .elems
2211 .iter()
2212 .map(|p| match p {
2213 Pat::Ident(i) => Ok((i.ident.to_string(), i.mutability.is_some())),
2214 Pat::Wild(_) => Ok(("_".to_string(), false)),
2215 _ => Err("only plain identifiers are supported in a destructuring `let`"),
2216 })
2217 .collect::<Result<_, _>>()?;
2218
2219 // `split_at` hands back two *views* of the same slice. Nim has no
2220 // tuple of views, and there is nothing to materialise anyway, so each
2221 // name becomes a window into the original.
2222 if let Expr::MethodCall(m) = &*init.expr {
2223 let mname = m.method.to_string();
2224 if (mname == "split_at" || mname == "split_at_mut")
2225 && m.args.len() == 1
2226 && names.len() == 2
2227 {
2228 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
2229 let at = self.expr(&m.args[0])?;
2230 let cut = self.fresh("Cut");
2231 self.line(&format!("let {}: int = int({})", cut, at.code));
2232 self.bind_alias(
2233 &names[0].0,
2234 Alias::Window {
2235 code: code.clone(),
2236 off: base.clone(),
2237 len: cut.clone(),
2238 elem: elem.clone(),
2239 },
2240 );
2241 self.bind_alias(
2242 &names[1].0,
2243 Alias::Window {
2244 code,
2245 off: format!("({} + {})", base, cut),
2246 len: format!("({} - {})", len, cut),
2247 elem,
2248 },
2249 );
2250 return Ok(());
2251 }
2252 }
2253
2254 let v = self.expr(&init.expr)?;
2255 let tys = match &v.ty {
2256 Some(Nim::Tuple(ts)) if ts.len() == names.len() => ts.clone(),
2257 _ => {
2258 return Err(format!(
2259 "cannot destructure this into {} bindings: its type is not a \
2260 tuple of that many elements",
2261 names.len()
2262 ))
2263 }
2264 };
2265 let kw = if names.iter().any(|(_, m)| *m) { "var" } else { "let" };
2266 let lhs: Vec<String> = names.iter().map(|(n, _)| ident(n)).collect();
2267 self.line(&format!("{} ({}) = {}", kw, lhs.join(", "), v.code));
2268 for ((n, _), t) in names.iter().zip(tys) {
2269 self.bind(n, t);
2270 }
2271 Ok(())
2272 }
2273
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2274 /// Expressions that are statements in Rust and statements in Nim too
2275 /// (control flow). Returns `None` when it emitted lines itself.
2276 fn expr_stmt(&mut self, e: &Expr) -> Result<Option<Val>, String> {
2277 match e {
2278 Expr::If(_) => {
2279 self.if_stmt(e)?;
2280 Ok(None)
2281 }
2282 Expr::While(w) => {
2283 if w.label.is_some() {
2284 return Err("loop labels are not implemented yet".into());
2285 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2286 self.in_loop_cond = true;
2287 let c = self.expr(&w.cond);
2288 self.in_loop_cond = false;
2289 let c = c?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2290 self.line(&format!("while {}:", c.code));
2291 let saved = self.target.take();
2292 self.nested_block(&w.body)?;
2293 self.target = saved;
2294 Ok(None)
2295 }
2296 Expr::Loop(l) => {
2297 if l.label.is_some() {
2298 return Err("loop labels are not implemented yet".into());
2299 }
2300 self.line("while true:");
2301 let saved = self.target.take();
2302 self.nested_block(&l.body)?;
2303 self.target = saved;
2304 Ok(None)
2305 }
2306 Expr::ForLoop(f) => {
2307 self.for_loop(f)?;
2308 Ok(None)
2309 }
2310 Expr::Block(b) => {
2311 if b.label.is_some() {
2312 return Err("block labels are not implemented yet".into());
2313 }
2314 self.line("block:");
2315 self.nested_block(&b.block)?;
2316 Ok(None)
2317 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2318 Expr::Unsafe(u) => {
2319 // Transparent in statement position too, for the same reason.
2320 self.nested_block_flat(&u.block)?;
2321 Ok(None)
2322 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2323 Expr::Match(_) => {
2324 self.match_stmt(e)?;
2325 Ok(None)
2326 }
2327 Expr::Return(r) => {
2328 match &r.expr {
2329 Some(e) => {
2330 let want = self.ret.clone();
2331 let v = self.expr_at(e, want.as_ref())?;
2332 self.line(&format!("return {}", v.code));
2333 }
2334 None => self.line("return"),
2335 }
2336 Ok(None)
2337 }
2338 Expr::Break(b) => {
2339 if b.expr.is_some() || b.label.is_some() {
2340 return Err("`break` with a value or a label is not implemented yet".into());
2341 }
2342 self.line("break");
2343 Ok(None)
2344 }
2345 Expr::Continue(c) => {
2346 if c.label.is_some() {
2347 return Err("labelled `continue` is not implemented yet".into());
2348 }
2349 self.line("continue");
2350 Ok(None)
2351 }
2352 Expr::Assign(a) => {
2353 let lhs = self.expr(&a.left)?;
2354 if !expressible(&a.right) {
2355 let target = lhs.code.clone();
2356 return self.assign_from(&a.right, &target, lhs.ty.as_ref()).map(|_| None);
2357 }
2358 let rhs = self.expr_at(&a.right, lhs.ty.as_ref())?;
2359 self.line(&format!("{} = {}", lhs.code, rhs.code));
2360 Ok(None)
2361 }
2362 Expr::Binary(b) if is_compound(&b.op) => {
2363 let lhs = self.expr(&b.left)?;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago2364 // A compound assignment on a user type goes to that type's own
2365 // `impl OpAssign`, not to Nim's built-in operator.
2366 if let Some(f) = self.op_proc(&lhs.ty, compound_symbol(&b.op)) {
2367 // The impl's own parameter type types the right operand,
2368 // so `b_vec *= 4` takes 4 at the width the impl declares.
2369 let want = self.op_param(&lhs.ty, compound_symbol(&b.op));
2370 let rhs = self.expr_at(&b.right, want.as_ref())?;
2371 self.line(&format!("{}({}, {})", f, lhs.code, rhs.code));
2372 return Ok(None);
2373 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2374 // `i += 1` must widen the literal to `i`'s type, not to the
2375 // i32 an unconstrained Rust literal would default to.
2376 let rhs = self.expr_at(&b.right, lhs.ty.as_ref())?;
2377 let op = self.bin_op(&b.op, &lhs, &rhs)?;
2378 // Nim has no `shl=` etc., and `+=` on a `let` is illegal in
2379 // both languages, so the expanded form is always correct.
2380 self.line(&format!("{} = {} {} {}", lhs.code, lhs.code, op, rhs.code));
2381 Ok(None)
2382 }
2383 Expr::Macro(m) => {
2384 let line = self.macro_call(&m.mac)?;
2385 self.line(&line);
2386 Ok(None)
2387 }
2388 _ => Ok(Some(self.expr(e)?)),
2389 }
2390 }
2391
2392 /// Lower `e` in statement position, assigning each arm's value to
2393 /// `target`. This is how Rust's expression-oriented `if`/`match` survive
2394 /// the trip when their arms are too big for a Nim `if`-expression.
2395 fn assign_from(
2396 &mut self,
2397 e: &Expr,
2398 target: &str,
2399 expect: Option<&Nim>,
2400 ) -> Result<(), String> {
2401 let saved = self.target.replace((target.to_string(), expect.cloned()));
2402 let r = match e {
2403 Expr::If(_) => self.if_stmt(e),
2404 Expr::Match(_) => self.match_stmt(e),
2405 other => {
2406 let v = self.expr_at(other, expect)?;
2407 self.line(&format!("{} = {}", target, v.code));
2408 Ok(())
2409 }
2410 };
2411 self.target = saved;
2412 r
2413 }
2414
2415 /// Emit a block's value into the active assignment target, if there is
2416 /// one, or discard it if there is not.
2417 fn emit_tail(&mut self, v: Option<Val>) {
2418 let Some(v) = v else { return };
2419 match self.target.clone() {
2420 Some((t, _)) => {
2421 let code = v.code.clone();
2422 self.line(&format!("{t} = {code}"));
2423 }
2424 None => {
2425 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
2426 let code = v.code.clone();
2427 if needs {
2428 self.line(&format!("discard {code}"));
2429 } else if !code.is_empty() {
2430 self.line(&code);
2431 }
2432 }
2433 }
2434 }
2435
2436 fn if_stmt(&mut self, e: &Expr) -> Result<(), String> {
2437 let Expr::If(i) = e else { unreachable!() };
2438 if let Expr::Let(_) = &*i.cond {
2439 return Err("`if let` is not implemented yet".into());
2440 }
2441 let c = self.expr(&i.cond)?;
2442 self.line(&format!("if {}:", c.code));
2443 self.nested_block(&i.then_branch)?;
2444 match &i.else_branch {
2445 None => {}
2446 Some((_, els)) => match &**els {
2447 Expr::If(_) => {
2448 // Nim needs `elif`; splice the nested `if` in as one.
2449 let mark = self.out.len();
2450 self.if_stmt(els)?;
2451 let tail = self.out.split_off(mark);
2452 let indent = " ".repeat(self.indent);
2453 self.out.push_str(&tail.replacen(&format!("{indent}if "), &format!("{indent}elif "), 1));
2454 }
2455 Expr::Block(b) => {
2456 self.line("else:");
2457 self.nested_block(&b.block)?;
2458 }
2459 _ => return Err("unsupported `else` form".into()),
2460 },
2461 }
2462 Ok(())
2463 }
2464
2465 fn for_loop(&mut self, f: &syn::ExprForLoop) -> Result<(), String> {
2466 if f.label.is_some() {
2467 return Err("loop labels are not implemented yet".into());
2468 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2469 let it = self.resolve_iter(&f.expr)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2470
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2471 // One index loop drives the whole chain. Rust's adaptors are lazy and
2472 // compose; resolving them to an index and binding each name to an
2473 // lvalue reproduces that without materialising anything.
2474 let i = self.fresh("Idx");
2475 self.line(&format!("for {} in 0 ..< int({}):", i, it.len()));
2476 self.indent += 1;
2477 self.push_scope();
2478 let before = self.out.len();
2479
2480 self.bind_pattern(&f.pat, &it, &i)?;
2481
2482 let saved = self.target.take();
2483 if let Some(v) = self.block_body(&f.body)? {
2484 let code = v.code.clone();
2485 self.line(&format!("discard {code}"));
2486 }
2487 self.target = saved;
2488 if self.out.len() == before {
2489 self.line("discard");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2490 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2491 self.pop_scope();
2492 self.indent -= 1;
2493 Ok(())
2494 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2495
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2496 /// Resolve a chain of iterator adaptors into a single `Iter`.
2497 ///
2498 /// Only adaptors with an exact index-loop equivalent are accepted. `map`,
2499 /// `filter`, `take_while` and friends are rejected rather than partially
2500 /// honoured: silently dropping an adaptor would change which elements the
2501 /// loop visits.
2502 fn resolve_iter(&mut self, e: &Expr) -> Result<Iter, String> {
2503 match e {
2504 Expr::Reference(r) => self.resolve_iter(&r.expr),
2505 Expr::Paren(p) => self.resolve_iter(&p.expr),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2506 Expr::Range(r) => {
2507 let lo = match &r.start {
2508 Some(e) => self.expr(e)?,
2509 None => return Err("a `for` over `..n` needs a start bound".into()),
2510 };
2511 let hi = match &r.end {
2512 Some(e) => self.expr(e)?,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2513 None => {
2514 return Err("a `for` over an unbounded range would not terminate".into())
2515 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2516 };
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2517 let ty = lo.ty.clone().or(hi.ty.clone());
2518 Ok(Iter::Range {
2519 lo: lo.code,
2520 hi: hi.code,
2521 closed: matches!(r.limits, syn::RangeLimits::Closed(_)),
2522 ty,
2523 })
2524 }
2525 Expr::MethodCall(m) => {
2526 let name = m.method.to_string();
2527 match name.as_str() {
2528 "iter" | "into_iter" | "iter_mut" if m.args.is_empty() => {
2529 let mut it = self.resolve_iter(&m.receiver)?;
2530 if name == "iter_mut" {
2531 if let Iter::Elems { mutable, .. } = &mut it {
2532 *mutable = true;
2533 }
2534 }
2535 Ok(it)
2536 }
2537 "enumerate" if m.args.is_empty() => {
2538 Ok(Iter::Enumerate(Box::new(self.resolve_iter(&m.receiver)?)))
2539 }
2540 "zip" if m.args.len() == 1 => {
2541 let a = self.resolve_iter(&m.receiver)?;
2542 let b = self.resolve_iter(&m.args[0])?;
2543 Ok(Iter::Zip(Box::new(a), Box::new(b)))
2544 }
2545 "chunks_exact" | "chunks_exact_mut" if m.args.len() == 1 => {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2546 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2547 let k = self.expr(&m.args[0])?;
2548 Ok(Iter::Chunks {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2549 code,
2550 base,
2551 len,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2552 k: k.code,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2553 elem,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2554 mutable: name.ends_with("_mut"),
2555 })
2556 }
2557 "windows" if m.args.len() == 1 => {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2558 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2559 let k = self.expr(&m.args[0])?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2560 Ok(Iter::Windows { code, base, len, k: k.code, elem })
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2561 }
2562 other => Err(format!(
2563 "iterator adaptor `.{other}()` is not implemented; it has \
2564 no index-loop equivalent here, and dropping it would \
2565 change which elements the loop visits"
2566 )),
2567 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2568 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago2569 Expr::Path(p) => {
2570 let n = path_name(&p.path);
2571 if let Some(Alias::Iterator(it)) = self.lookup_alias(&n) {
2572 return Ok((*it).clone());
2573 }
2574 if let Some(Alias::Window { code, off, len, elem }) = self.lookup_alias(&n) {
2575 return Ok(Iter::Elems { code, off, len, elem, mutable: false });
2576 }
2577 let v = self.expr(e)?;
2578 Ok(Iter::Elems {
2579 len: format!("{}.len", v.code),
2580 elem: elem_of(&v.ty),
2581 code: v.code,
2582 off: "0".into(),
2583 mutable: false,
2584 })
2585 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2586 other => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2587 // A `for` binding that is itself a window iterates that window,
2588 // not the whole container it points into.
2589 if let Some(Alias::Window { code, off, len, elem }) = self.window_of(other) {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2590 return Ok(Iter::Elems { code, off, len, elem, mutable: false });
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2591 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2592 let v = self.expr(other)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2593 Ok(Iter::Elems {
2594 len: format!("{}.len", v.code),
2595 elem: elem_of(&v.ty),
2596 code: v.code,
2597 off: "0".into(),
2598 mutable: false,
2599 })
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2600 }
2601 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2602 }
2603
2604 /// Bind a `for` pattern against a resolved iterator at index `i`.
2605 fn bind_pattern(&mut self, p: &Pat, it: &Iter, i: &str) -> Result<(), String> {
2606 match (p, it) {
2607 (Pat::Tuple(t), Iter::Zip(a, b)) if t.elems.len() == 2 => {
2608 self.bind_pattern(&t.elems[0], a, i)?;
2609 self.bind_pattern(&t.elems[1], b, i)
2610 }
2611 (Pat::Tuple(t), Iter::Enumerate(inner)) if t.elems.len() == 2 => {
2612 if let Pat::Ident(id) = &t.elems[0] {
2613 let n = id.ident.to_string();
2614 // Rust's `enumerate` counts in `usize`.
2615 self.line(&format!("let {}: uint = uint({})", ident(&n), i));
2616 self.bind(&n, Nim::Prim("uint".into()));
2617 }
2618 self.bind_pattern(&t.elems[1], inner, i)
2619 }
2620 (_, Iter::Zip(..) | Iter::Enumerate(..)) => Err(
2621 "a `zip`/`enumerate` loop needs a two-element tuple pattern".into(),
2622 ),
2623 (Pat::Wild(_), _) => Ok(()),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2624 // `for &byte in xs` — the `&` destructures the reference, which in
2625 // Nim is already the value.
2626 (Pat::Reference(r), _) => self.bind_pattern(&r.pat, it, i),
2627 (Pat::Paren(p), _) => self.bind_pattern(&p.pat, it, i),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2628 (Pat::Ident(id), _) => {
2629 let name = id.ident.to_string();
2630 match it {
2631 Iter::Range { lo, ty, .. } => {
2632 let t = ty.clone().unwrap_or(Nim::Prim("int".into()));
2633 // The loop counts from zero; the range's own start is
2634 // added back so the binding has Rust's value and type.
2635 self.line(&format!(
2636 "let {}: {} = {}({}) + {}",
2637 ident(&name),
2638 t.render(),
2639 t.render(),
2640 i,
2641 lo
2642 ));
2643 self.bind(&name, t);
2644 Ok(())
2645 }
2646 Iter::Elems { code, off, elem, mutable, .. } => {
2647 let access = if off == "0" {
2648 format!("{}[{}]", code, i)
2649 } else {
2650 format!("{}[{} + {}]", code, off, i)
2651 };
2652 if *mutable {
2653 // An alias, not a copy: assigning through the
2654 // binding must reach the original element.
2655 self.bind_alias(
2656 &name,
2657 Alias::Value { code: access, ty: elem.clone() },
2658 );
2659 } else {
2660 let t = elem
2661 .clone()
2662 .ok_or("cannot infer the element type of this `for`")?;
2663 self.line(&format!(
2664 "let {}: {} = {}",
2665 ident(&name),
2666 t.render(),
2667 access
2668 ));
2669 self.bind(&name, t);
2670 }
2671 Ok(())
2672 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2673 Iter::Chunks { code, base, k, elem, .. } => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2674 self.bind_alias(
2675 &name,
2676 Alias::Window {
2677 code: code.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2678 off: format!("({} + {} * int({}))", base, i, k),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2679 len: format!("int({})", k),
2680 elem: elem.clone(),
2681 },
2682 );
2683 Ok(())
2684 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2685 Iter::Windows { code, base, k, elem, .. } => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2686 self.bind_alias(
2687 &name,
2688 Alias::Window {
2689 code: code.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago2690 off: format!("({} + {})", base, i),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago2691 len: format!("int({})", k),
2692 elem: elem.clone(),
2693 },
2694 );
2695 Ok(())
2696 }
2697 // Handled above: a zip or enumerate needs a tuple pattern,
2698 // and binding one name to the pair is not supported.
2699 Iter::Zip(..) | Iter::Enumerate(..) => unreachable!(),
2700 }
2701 }
2702 _ => Err("unsupported `for` pattern".into()),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2703 }
2704 }
2705
2706 fn match_stmt(&mut self, e: &Expr) -> Result<(), String> {
2707 let Expr::Match(m) = e else { unreachable!() };
2708 let scrut = self.expr(&m.expr)?;
2709 let t = scrut
2710 .ty
2711 .clone()
2712 .ok_or("cannot infer the type of a `match` scrutinee")?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2713 let name = self.fresh("Match");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2714 self.line(&format!("let {}: {} = {}", name, t.render(), scrut.code));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2715
2716 // A `match` whose arms neither bind nor guard is a Nim `case`, which
2717 // is exhaustiveness-checked the way Rust's is. Anything richer becomes
2718 // an if/elif chain, because Nim's `case` cannot destructure.
2719 let plain = m.arms.iter().all(|a| {
2720 !matches!(a.pat, Pat::Guard(_)) && !binds(&a.pat) && !destructures(&a.pat)
2721 });
2722 if plain {
2723 self.match_case(m, &name, &t)
2724 } else {
2725 self.match_chain(m, &name, &t)
2726 }
2727 }
2728
2729 fn match_case(
2730 &mut self,
2731 m: &syn::ExprMatch,
2732 name: &str,
2733 t: &Nim,
2734 ) -> Result<(), String> {
2735 // A variant object is discriminated by its `kind` field.
2736 let on_kind = matches!(t, Nim::Named(n, _) if self.enums.get(n).is_some_and(|d| !d.simple));
2737 self.line(&format!("case {}{}", name, if on_kind { ".kind" } else { "" }));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2738
2739 let mut saw_wild = false;
2740 for arm in &m.arms {
2741 match &arm.pat {
2742 Pat::Wild(_) => {
2743 saw_wild = true;
2744 self.line("else:");
2745 }
2746 p => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2747 let labels = self.pat_labels(p, Some(t))?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2748 self.line(&format!("of {}:", labels.join(", ")));
2749 }
2750 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2751 self.arm_body(&arm.body)?;
2752 }
2753 if !saw_wild && !self.case_is_total(t, m) {
2754 // Rust checked exhaustiveness already, but Nim cannot always see
2755 // it -- an integer `case` needs every value covered -- so make the
2756 // unreachable arm explicit rather than leave a compile error.
2757 self.line("else:");
2758 self.line(" rsPanic(\"unreachable match arm\")");
2759 }
2760 Ok(())
2761 }
2762
2763 /// Whether a Nim `case` over this type is already total, in which case
2764 /// adding an `else` would be a compile error rather than a safety net.
2765 fn case_is_total(&self, t: &Nim, m: &syn::ExprMatch) -> bool {
2766 let Nim::Named(n, _) = t else { return false };
2767 let Some(def) = self.enums.get(n) else { return false };
2768 def.variants.len() == m.arms.len()
2769 }
2770
2771 /// The if/elif form, for arms that bind or destructure.
2772 fn match_chain(
2773 &mut self,
2774 m: &syn::ExprMatch,
2775 name: &str,
2776 t: &Nim,
2777 ) -> Result<(), String> {
2778 let mut first = true;
2779 let mut closed = false;
2780 for arm in &m.arms {
2781 let (pat, guard) = match &arm.pat {
2782 Pat::Guard(g) => (&*g.pat, Some(&*g.guard)),
2783 p => (p, None),
2784 };
2785 if guard.is_some() && binds(pat) {
2786 return Err("a `match` guard on a binding pattern is not \
2787 implemented yet"
2788 .into());
2789 }
2790 let test = self.pat_test(pat, name, t)?;
2791 let test = match (test, guard) {
2792 (Some(t), Some(g)) => {
2793 let g = self.expr(g)?;
2794 Some(format!("({}) and ({})", t, g.code))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2795 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2796 (None, Some(g)) => Some(self.expr(g)?.code),
2797 (t, None) => t,
2798 };
2799 match test {
2800 Some(test) => {
2801 self.line(&format!(
2802 "{} {}:",
2803 if first { "if" } else { "elif" },
2804 test
2805 ));
2806 first = false;
2807 }
2808 None => {
2809 // An irrefutable pattern: everything left falls here.
2810 if first {
2811 self.line("block:");
2812 } else {
2813 self.line("else:");
2814 }
2815 closed = true;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2816 }
2817 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2818 self.indent += 1;
2819 self.push_scope();
2820 let before = self.out.len();
2821 self.pat_bind(pat, name, t)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2822 self.indent -= 1;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2823 self.arm_body_at(&arm.body, before)?;
2824 self.pop_scope();
2825 if closed {
2826 break;
2827 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2828 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2829 if !closed {
2830 // Rust proved this unreachable; Nim cannot see that, and leaving
2831 // the chain open would silently fall through instead.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago2832 self.line("else:");
2833 self.line(" rsPanic(\"unreachable match arm\")");
2834 }
2835 Ok(())
2836 }
2837
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2838 /// The condition that selects this arm, or `None` if it always matches.
2839 fn pat_test(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<Option<String>, String> {
2840 Ok(match p {
2841 Pat::Wild(_) => None,
2842 Pat::Ident(i) if i.subpat.is_none() => None,
2843 Pat::Or(o) => {
2844 let mut parts = Vec::new();
2845 for c in &o.cases {
2846 match self.pat_test(c, name, t)? {
2847 Some(x) => parts.push(x),
2848 None => return Ok(None),
2849 }
2850 }
2851 Some(format!("({})", parts.join(" or ")))
2852 }
2853 Pat::Lit(_) | Pat::Range(_) => {
2854 let labels = self.pat_labels(p, Some(t))?;
2855 Some(match p {
2856 Pat::Range(_) => format!("({} in {})", name, labels[0]),
2857 _ => format!("({} == {})", name, labels[0]),
2858 })
2859 }
2860 Pat::Path(pp) => Some(self.variant_test(&pp.path, name, t)?),
2861 Pat::TupleStruct(ts) => Some(self.variant_test(&ts.path, name, t)?),
2862 Pat::Struct(st) => Some(self.variant_test(&st.path, name, t)?),
2863 Pat::Paren(pp) => return self.pat_test(&pp.pat, name, t),
2864 Pat::Reference(r) => return self.pat_test(&r.pat, name, t),
2865 _ => return Err("unsupported `match` pattern".into()),
2866 })
2867 }
2868
2869 /// The discriminant test for `Ok`/`Err`/`Some`/`None` or an enum variant.
2870 fn variant_test(&self, path: &syn::Path, name: &str, t: &Nim) -> Result<String, String> {
2871 let last = path_name(path);
2872 match last.as_str() {
2873 "Ok" => return Ok(format!("{name}.ok")),
2874 "Err" => return Ok(format!("(not {name}.ok)")),
2875 "Some" => return Ok(format!("{name}.has")),
2876 "None" => return Ok(format!("(not {name}.has)")),
2877 _ => {}
2878 }
2879 let Some((def, v)) = self.resolve_variant(path) else {
2880 return Err(format!(
2881 "`{last}` in a pattern is not a known enum variant; if it names \
2882 an enum declared in another module, that is not implemented yet"
2883 ));
2884 };
2885 if let Nim::Named(n, _) = t {
2886 if *n != def.name {
2887 return Err(format!(
2888 "pattern `{}::{}` does not match the scrutinee type `{}`",
2889 def.name, v, n
2890 ));
2891 }
2892 }
2893 Ok(if def.simple {
2894 format!("({} == {}.{})", name, ident(&def.name), ident(&v))
2895 } else {
2896 format!("({}.kind == {})", name, def.kind_ident(&v))
2897 })
2898 }
2899
2900 /// Emit the `let`s that a pattern's bindings introduce.
2901 fn pat_bind(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<(), String> {
2902 match p {
2903 Pat::Wild(_) | Pat::Lit(_) | Pat::Range(_) | Pat::Path(_) | Pat::Or(_) => Ok(()),
2904 Pat::Paren(pp) => self.pat_bind(&pp.pat, name, t),
2905 Pat::Reference(r) => self.pat_bind(&r.pat, name, t),
2906 Pat::Ident(i) if i.subpat.is_none() => {
2907 let b = i.ident.to_string();
2908 self.line(&format!("let {}: {} = {}", ident(&b), t.render(), name));
2909 self.bind(&b, t.clone());
2910 Ok(())
2911 }
2912 Pat::TupleStruct(ts) => {
2913 let fields = self.variant_fields(&ts.path, t)?;
2914 for (i, sub) in ts.elems.iter().enumerate() {
2915 let Some((fname, fty)) = fields.get(i) else {
2916 return Err(format!(
2917 "pattern binds {} field(s) but the variant has {}",
2918 ts.elems.len(),
2919 fields.len()
2920 ));
2921 };
2922 let access = format!("{}.{}", name, ident(fname));
2923 self.pat_bind(sub, &access, fty)?;
2924 }
2925 Ok(())
2926 }
2927 Pat::Struct(st) => {
2928 let fields = self.variant_fields(&st.path, t)?;
2929 for f in &st.fields {
2930 let syn::Member::Named(m) = &f.member else {
2931 return Err("unsupported struct pattern field".into());
2932 };
2933 let m = m.to_string();
2934 let Some((fname, fty)) = fields.iter().find(|(f, _)| f.ends_with(&m)) else {
2935 return Err(format!("unknown field `{m}` in pattern"));
2936 };
2937 let access = format!("{}.{}", name, ident(fname));
2938 self.pat_bind(&f.pat, &access, fty)?;
2939 }
2940 Ok(())
2941 }
2942 _ => Err("unsupported `match` pattern".into()),
2943 }
2944 }
2945
2946 /// The payload fields a variant pattern destructures.
2947 fn variant_fields(
2948 &self,
2949 path: &syn::Path,
2950 t: &Nim,
2951 ) -> Result<Vec<(String, Nim)>, String> {
2952 let last = path_name(path);
2953 // `Ok`/`Err`/`Some` read the prelude's own field names.
2954 if let Nim::Named(n, a) = t {
2955 match (n.as_str(), last.as_str()) {
2956 ("Result", "Ok") if a.len() == 2 => return Ok(vec![("val".into(), a[0].clone())]),
2957 ("Result", "Err") if a.len() == 2 => return Ok(vec![("err".into(), a[1].clone())]),
2958 ("Option", "Some") if a.len() == 1 => return Ok(vec![("val".into(), a[0].clone())]),
2959 _ => {}
2960 }
2961 }
2962 let Some((def, v)) = self.resolve_variant(path) else {
2963 return Err(format!("`{last}` is not a known enum variant"));
2964 };
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago2965 let fields = def.get(&v).map(|v| v.fields.clone()).unwrap_or_default();
2966 // The variant's payload is declared in the enum's own parameters; the
2967 // scrutinee says what they are here.
2968 Ok(fields
2969 .into_iter()
2970 .map(|(n, ft)| (n, self.subst_type_args(&def.name, t, ft)))
2971 .collect())
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago2972 }
2973
2974 fn arm_body(&mut self, body: &Expr) -> Result<(), String> {
2975 self.indent += 1;
2976 let before = self.out.len();
2977 self.indent -= 1;
2978 self.arm_body_at(body, before)
2979 }
2980
2981 fn arm_body_at(&mut self, body: &Expr, before: usize) -> Result<(), String> {
2982 match body {
2983 Expr::Block(b) => self.nested_block(&b.block)?,
2984 other => {
2985 self.indent += 1;
2986 // An arm's value is the `match`'s value, so it is typed by
2987 // whatever the `match` is being assigned to -- without which
2988 // an `Ok(..)` arm has no way to know its `Result<T, E>`.
2989 let want = self.target.clone().and_then(|(_, t)| t);
2990 let v = match (want, expressible(other)) {
2991 (Some(t), true) => Some(self.expr_at(other, Some(&t))?),
2992 _ => self.expr_stmt(other)?,
2993 };
2994 self.emit_tail(v);
2995 self.indent -= 1;
2996 }
2997 }
2998 if self.out.len() == before {
2999 self.indent += 1;
3000 self.line("discard");
3001 self.indent -= 1;
3002 }
3003 Ok(())
3004 }
3005
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3006 fn pat_labels(&mut self, p: &Pat, expect: Option<&Nim>) -> Result<Vec<String>, String> {
3007 match p {
3008 Pat::Lit(l) => Ok(vec![self.lit_at(&l.lit, expect)?.code]),
3009 Pat::Or(o) => {
3010 let mut out = Vec::new();
3011 for p in &o.cases {
3012 out.extend(self.pat_labels(p, expect)?);
3013 }
3014 Ok(out)
3015 }
3016 Pat::Range(r) => {
3017 let lo = r.start.as_ref().ok_or("open-ended range pattern")?;
3018 let hi = r.end.as_ref().ok_or("open-ended range pattern")?;
3019 let (lo, hi) = (self.expr_at(lo, expect)?, self.expr_at(hi, expect)?);
3020 let op = match r.limits {
3021 syn::RangeLimits::HalfOpen(_) => "..<",
3022 syn::RangeLimits::Closed(_) => "..",
3023 };
3024 Ok(vec![format!("{} {} {}", lo.code, op, hi.code)])
3025 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3026 Pat::Path(pp) => {
3027 if let Some((def, v)) = self.resolve_variant(&pp.path) {
3028 return Ok(vec![if def.simple {
3029 format!("{}.{}", ident(&def.name), ident(&v))
3030 } else {
3031 def.kind_ident(&v)
3032 }]);
3033 }
3034 Ok(vec![ident(&path_name(&pp.path))])
3035 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3036 _ => Err("unsupported `match` pattern; only literals, ranges, `|` \
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3037 alternatives, enum variants and `_` are implemented"
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3038 .into()),
3039 }
3040 }
3041
3042 // --------------------------------------------------------- expressions
3043
3044 fn expr(&mut self, e: &Expr) -> Result<Val, String> {
3045 self.expr_at(e, None)
3046 }
3047
3048 /// Lower `e`, with the type the surrounding code expects of it.
3049 ///
3050 /// Rust infers an unsuffixed integer literal's type from its context and
3051 /// falls back to `i32`; Nim falls back to 64-bit `int`. Carrying the
3052 /// expected type down to the literal is what makes `let x: u8 = 255` and
3053 /// `x.wrapping_add(100)` mean the same thing on both sides. Without it the
3054 /// widths silently diverge, which is exactly the class of bug this
3055 /// project refuses to ship.
3056 fn expr_at(&mut self, e: &Expr, expect: Option<&Nim>) -> Result<Val, String> {
3057 match e {
3058 Expr::Lit(l) => self.lit_at(&l.lit, expect),
3059 Expr::Path(p) => {
3060 let name = path_name(&p.path);
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3061 if name == "None" {
3062 return Ok(Val::new(self.none_of(expect), expect.cloned()));
3063 }
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 15h ago3064 // `Perms::READ`: a constant of a `bitflags!` type.
3065 if let Some(q) = p.path.segments.iter().rev().nth(1).map(|s| s.ident.to_string()) {
3066 let q = if q == "Self" {
3067 self.self_ty.as_ref().map(type_name).unwrap_or(q)
3068 } else {
3069 q
3070 };
3071 if let Some(c) = self.flag_consts.get(&(q.clone(), name.clone())) {
3072 return Ok(Val::new(c.clone(), Some(Nim::Named(q, vec![]))));
3073 }
3074 }
3075
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago3076 // `Grid::BORDER`: a `const` declared inside an `impl`.
3077 if let Some(q) = p.path.segments.iter().rev().nth(1).map(|s| s.ident.to_string()) {
3078 let q = if q == "Self" {
3079 self.self_ty.as_ref().map(type_name).unwrap_or(q)
3080 } else {
3081 q
3082 };
3083 if let Some((nim, t)) = self.assoc_consts.get(&(q, name.clone())) {
3084 return Ok(Val::new(nim.clone(), Some(t.clone())));
3085 }
3086 }
3087
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago3088 // `i32::MAX` and friends: an associated const on a primitive.
3089 if matches!(name.as_str(), "MAX" | "MIN") {
3090 if let Some(q) = p.path.segments.iter().rev().nth(1) {
3091 if let Some(t @ Nim::Prim(_)) = ty::prim(&q.ident.to_string()) {
3092 if t.is_integer() {
3093 let f = if name == "MAX" { "high" } else { "low" };
3094 return Ok(Val::new(
3095 format!("{}({})", f, t.render()),
3096 Some(t),
3097 ));
3098 }
3099 }
3100 }
3101 }
3102
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago3103 // A unit struct used as a value: `fmt::Error`, or a `struct S;`
3104 // declared here. In Nim that is a constructor call.
3105 if p.path.segments.len() > 1 {
3106 let ty = syn::Type::Path(syn::TypePath { attrs: Vec::new(), qself: None, path: p.path.clone() });
3107 if let Ok(Nim::Prim(n)) = ty::map(&ty) {
3108 if n == "FmtError" {
3109 return Ok(Val::new("FmtError()", Some(Nim::Prim(n))));
3110 }
3111 }
3112 }
3113 if self.structs.get(&name).is_some_and(|f| f.is_empty()) {
3114 return Ok(Val::new(
3115 format!("{}()", ident(&name)),
3116 Some(Nim::Named(name.clone(), vec![])),
3117 ));
3118 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3119 // A unit enum variant used as a value: `Error::InvalidLength`.
3120 if let Some((def, v)) = self.resolve_variant(&p.path) {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago3121 let (ty, targs) = self.variant_type(&def, expect)?;
3122 return Ok(if def.simple && targs.is_empty() {
3123 Val::new(format!("{}.{}", ident(&def.name), ident(&v)), Some(ty))
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3124 } else {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago3125 // A unit variant of a generic enum has no argument to
3126 // infer the parameters from, so they are written out.
3127 Val::new(
3128 format!("{}{}()", def.ctor_ident(&v), targs),
3129 Some(ty),
3130 )
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3131 });
3132 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago3133 // A `for` binding that stands for an element of the container
3134 // it came from: using it must read (and assigning through it
3135 // must write) that element, not a copy.
3136 if let Some(a) = self.lookup_alias(&name) {
3137 return Ok(match a {
3138 Alias::Value { code, ty } => Val::new(code, ty),
3139 // A window *is* a slice; as a value it is the view it
3140 // denotes, which is what Rust's `&[T]` means too.
3141 Alias::Window { code, off, len, elem } => Val::new(
3142 format!("{}.toOpenArray({}, {} + {} - 1)", code, off, off, len),
3143 elem.map(|e| Nim::OpenArray(Box::new(e))),
3144 ),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago3145 // An iterator is not a value here: it is consumed by a
3146 // `for`, or asked for its `.remainder()`.
3147 Alias::Iterator(_) => {
3148 return Err(format!(
3149 "`{name}` is an iterator; it can be iterated or asked \
3150 for its `remainder()`, but not used as a value"
3151 ))
3152 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago3153 });
3154 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3155 if let Some(t) = self.lookup(&name) {
3156 return Ok(Val::new(ident(&name), Some(t)));
3157 }
3158 // A top-level function used as a value, e.g. passed to a
3159 // parameter of `impl Fn(..)` type.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago3160 if let Some(k) = self.resolve_fn(&p.path) {
3161 let sig = &self.fns[&k];
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3162 let t = Nim::Proc(sig.params.clone(), Box::new(sig.ret.clone()));
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago3163 return Ok(Val::new(self.fn_name(&k.0, &k.1), Some(t)));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3164 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3165 Ok(Val::new(ident(&name), None))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3166 }
3167 Expr::Paren(p) => {
3168 let v = self.expr_at(&p.expr, expect)?;
3169 Ok(Val::new(format!("({})", v.code), v.ty))
3170 }
3171 Expr::Group(g) => self.expr_at(&g.expr, expect),
3172 // `&x` is a value in Nim; `&mut x` in an argument position binds to
3173 // a `var` parameter, which is also just `x` at the call site.
3174 Expr::Reference(r) => self.expr_at(&r.expr, expect),
3175 Expr::Unary(u) => self.unary(u, expect),
3176 Expr::Binary(b) => self.binary(b, expect),
3177 Expr::Cast(c) => self.cast(c),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago3178 Expr::Index(i) if matches!(&*i.index, Expr::Range(_)) => {
3179 let Expr::Range(r) = &*i.index else { unreachable!() };
3180 let base = self.expr(&i.expr)?;
3181 let lo = match &r.start {
3182 Some(e) => format!("int({})", self.expr(e)?.code),
3183 None => "0".into(),
3184 };
3185 // Nim's `toOpenArray` takes an inclusive upper bound.
3186 let hi = match (&r.end, r.limits) {
3187 (Some(e), syn::RangeLimits::HalfOpen(_)) => {
3188 format!("int({}) - 1", self.expr(e)?.code)
3189 }
3190 (Some(e), syn::RangeLimits::Closed(_)) => {
3191 format!("int({})", self.expr(e)?.code)
3192 }
3193 (None, _) => format!("{}.len - 1", base.code),
3194 };
3195 let elem = elem_of(&base.ty)
3196 .ok_or("cannot infer the element type of this slice")?;
3197 Ok(Val::new(
3198 format!("{}.toOpenArray({}, {})", base.code, lo, hi),
3199 Some(Nim::OpenArray(Box::new(elem))),
3200 ))
3201 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3202 Expr::Index(i) => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago3203 if let Some(Alias::Window { code, off, elem, .. }) = self.window_of(&i.expr) {
3204 let idx = self.expr(&i.index)?;
3205 return Ok(Val::new(
3206 format!("{}[{} + int({})]", code, off, idx.code),
3207 elem,
3208 ));
3209 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3210 let base = self.expr(&i.expr)?;
3211 let idx = self.expr(&i.index)?;
3212 // Rust indexes with usize; Nim wants an `int`, and a `uint`
3213 // index is a type error there rather than a silent conversion.
3214 let idx_code = match &idx.ty {
3215 Some(t) if t.is_unsigned() => format!("int({})", idx.code),
3216 _ => idx.code.clone(),
3217 };
3218 let elem = match base.ty.clone() {
3219 Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) | Some(Nim::Array(_, t)) => Some(*t),
3220 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
3221 _ => None,
3222 };
3223 Ok(Val::new(format!("{}[{}]", base.code, idx_code), elem))
3224 }
3225 Expr::Field(f) => {
3226 let base = self.expr(&f.base)?;
3227 let name = match &f.member {
3228 syn::Member::Named(n) => n.to_string(),
3229 syn::Member::Unnamed(i) => format!("f{}", i.index),
3230 };
3231 let t = match &base.ty {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago3232 Some(bt @ Nim::Named(s, _)) => self
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3233 .structs
3234 .get(s)
3235 .and_then(|fs| fs.iter().find(|(f, _)| *f == name))
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago3236 .map(|(_, t)| self.subst_type_args(s, bt, t.clone())),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3237 _ => None,
3238 };
3239 Ok(Val::new(format!("{}.{}", base.code, ident(&name)), t))
3240 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago3241 // `unsafe` is a permission marker, not a semantic change: it does
3242 // not alter what the enclosed operations mean. So the block is
3243 // transparent here, and each operation inside still goes through
3244 // the ordinary lowering -- and is still rejected if it has no
3245 // faithful mapping.
3246 Expr::Unsafe(u) => match single_expr(&u.block) {
3247 Some(e) => self.expr_at(e, expect),
3248 None => Err("an `unsafe` block used as a value must be a single \
3249 expression"
3250 .into()),
3251 },
3252 Expr::Closure(c) => self.closure(c, expect),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3253 Expr::Try(t) => self.try_op(t),
3254 Expr::Call(c) => self.call(c, expect),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago3255 Expr::MethodCall(m) => self.method(m, expect),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago3256 Expr::Macro(m) if path_name(&m.mac.path) == "vec" => {
3257 // `vec![..]`'s elements take their type from the annotation on
3258 // the binding, exactly as Rust's would.
3259 let want = match expect {
3260 Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) => Some((**e).clone()),
3261 _ => None,
3262 };
3263 let saved = std::mem::replace(&mut self.vec_expect, want.clone());
3264 let code = self.macro_call(&m.mac);
3265 self.vec_expect = saved;
3266 let code = code?;
3267 let ty = match want {
3268 Some(e) => Some(Nim::Seq(Box::new(e))),
3269 None => self.vec_elem(&m.mac)?.map(|e| Nim::Seq(Box::new(e))),
3270 };
3271 Ok(Val::new(code, ty))
3272 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3273 Expr::Macro(m) => {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago3274 let is_write = matches!(path_name(&m.mac.path).as_str(), "write" | "writeln");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3275 let code = self.macro_call(&m.mac)?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago3276 // A formatter write is a statement that appends, not a value.
3277 let ty = if is_write { Some(Nim::Unit) } else { None };
3278 Ok(Val::new(code, ty))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3279 }
3280 Expr::Struct(s) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3281 if s.rest.is_some() {
3282 return Err("struct update syntax `..rest` is not implemented yet".into());
3283 }
3284 // `Shape::Rect { w: 3, h: 5 }` is a struct-shaped *enum variant*,
3285 // which is constructed positionally in Nim.
3286 if let Some((def, v)) = self.resolve_variant(&s.path) {
3287 let fields = def.get(&v).map(|v| v.fields.clone()).unwrap_or_default();
3288 let mut args = vec![String::new(); fields.len()];
3289 for f in &s.fields {
3290 let syn::Member::Named(m) = &f.member else {
3291 return Err("unsupported enum variant field".into());
3292 };
3293 let want = format!("{}_{}", v, m);
3294 let i = fields
3295 .iter()
3296 .position(|(n, _)| *n == want)
3297 .ok_or_else(|| format!("`{}::{}` has no field `{m}`", def.name, v))?;
3298 args[i] = self.expr_at(&f.expr, Some(&fields[i].1))?.code;
3299 }
3300 if let Some(i) = args.iter().position(|a| a.is_empty()) {
3301 return Err(format!(
3302 "`{}::{}` is missing field `{}`",
3303 def.name, v, fields[i].0
3304 ));
3305 }
3306 return Ok(Val::new(
3307 format!("{}({})", def.ctor_ident(&v), args.join(", ")),
3308 Some(Nim::Named(def.name.clone(), vec![])),
3309 ));
3310 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago3311 // `Self { .. }` inside an `impl` names the type being
3312 // implemented, and its fields are that type's fields.
3313 let name = match path_name(&s.path).as_str() {
3314 "Self" => self
3315 .self_ty
3316 .as_ref()
3317 .map(type_name)
3318 .ok_or("`Self` outside an `impl` block")?,
3319 other => other.to_string(),
3320 };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3321 let mut parts = Vec::new();
3322 for f in &s.fields {
3323 let fname = match &f.member {
3324 syn::Member::Named(n) => n.to_string(),
3325 syn::Member::Unnamed(i) => format!("f{}", i.index),
3326 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3327 let want = self
3328 .structs
3329 .get(&name)
3330 .and_then(|fs| fs.iter().find(|(n, _)| *n == fname))
3331 .map(|(_, t)| t.clone());
3332 let v = self.expr_at(&f.expr, want.as_ref())?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3333 parts.push(format!("{}: {}", ident(&fname), v.code));
3334 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago3335 // Nim cannot infer an object's generic parameters from a
3336 // constructor's field values, so they are written out.
3337 let gp = self.type_generics.get(&name).cloned().unwrap_or_default();
3338 let ty = if gp.is_empty() {
3339 Nim::Named(name.clone(), vec![])
3340 } else {
3341 match expect {
3342 Some(Nim::Named(n, a)) if *n == name && a.len() == gp.len() => {
3343 Nim::Named(name.clone(), a.clone())
3344 }
3345 _ => {
3346 return Err(format!(
3347 "`{name} {{ .. }}` is generic, and Nim cannot infer \
3348 its parameters from the field values; annotate the \
3349 binding or the return type"
3350 ))
3351 }
3352 }
3353 };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3354 Ok(Val::new(
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago3355 format!("{}({})", ty.render(), parts.join(", ")),
3356 Some(ty),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3357 ))
3358 }
3359 Expr::Array(a) => {
3360 let mut parts = Vec::new();
3361 let mut elem = match expect {
3362 Some(Nim::Array(_, t)) | Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) => {
3363 Some((**t).clone())
3364 }
3365 _ => None,
3366 };
3367 for e in &a.elems {
3368 let want = elem.clone();
3369 let v = self.expr_at(e, want.as_ref())?;
3370 elem = elem.or(v.ty.clone());
3371 parts.push(v.code);
3372 }
3373 let t = elem.map(|t| Nim::Array(a.elems.len(), Box::new(t)));
3374 Ok(Val::new(format!("[{}]", parts.join(", ")), t))
3375 }
3376 Expr::Repeat(r) => {
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago3377 // `[0; 4]` is an array in Rust. Nim distinguishes a fixed-size
3378 // array from a `seq`, so the expected type decides which, and
3379 // an array needs its elements written out.
3380 let want_elem = match expect {
3381 Some(Nim::Array(_, e)) | Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) => {
3382 Some((**e).clone())
3383 }
3384 _ => None,
3385 };
3386 let v = self.expr_at(&r.expr, want_elem.as_ref())?;
3387 if let Some(Nim::Array(n, _)) = expect {
3388 let elems: Vec<String> = (0..*n).map(|_| v.code.clone()).collect();
3389 let t = v.ty.clone().map(|t| Nim::Array(*n, Box::new(t)));
3390 return Ok(Val::new(format!("[{}]", elems.join(", ")), t));
3391 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3392 let n = self.expr(&r.len)?;
3393 let t = v.ty.clone().map(|t| Nim::Seq(Box::new(t)));
3394 Ok(Val::new(format!("newSeqWith(int({}), {})", n.code, v.code), t))
3395 }
3396 Expr::Tuple(t) if t.elems.is_empty() => Ok(Val::new("", Some(Nim::Unit))),
3397 Expr::Tuple(t) => {
3398 let mut parts = Vec::new();
3399 let mut tys = Vec::new();
3400 for e in &t.elems {
3401 let v = self.expr(e)?;
3402 tys.push(v.ty.clone());
3403 parts.push(v.code);
3404 }
3405 let ty = tys
3406 .iter()
3407 .cloned()
3408 .collect::<Option<Vec<_>>>()
3409 .map(Nim::Tuple);
3410 Ok(Val::new(format!("({})", parts.join(", ")), ty))
3411 }
3412 // `if` and `match` are expressions in both languages, but only
3413 // when every arm is itself a single expression.
3414 Expr::If(i) => self.if_expr(i, expect),
3415 Expr::Block(b) if b.block.stmts.len() == 1 => {
3416 if let Some(Stmt::Expr(e, None)) = b.block.stmts.first() {
3417 self.expr_at(e, expect)
3418 } else {
3419 Err("block expression with statements in value position is not implemented yet".into())
3420 }
3421 }
3422 other => Err(format!(
3423 "unsupported expression in value position: {}",
3424 expr_kind(other)
3425 )),
3426 }
3427 }
3428
3429 fn if_expr(&mut self, i: &syn::ExprIf, expect: Option<&Nim>) -> Result<Val, String> {
3430 let (Some(then), Some((_, els))) = (single_expr(&i.then_branch), &i.else_branch) else {
3431 return Err(
3432 "an `if` used as a value must have an `else` and single-expression arms".into(),
3433 );
3434 };
3435 let c = self.expr(&i.cond)?;
3436 let t = self.expr_at(then, expect)?;
3437 let want = expect.cloned().or_else(|| t.ty.clone());
3438 let e = match &**els {
3439 Expr::Block(b) => match single_expr(&b.block) {
3440 Some(x) => self.expr_at(x, want.as_ref())?,
3441 None => return Err("an `if` used as a value must have single-expression arms".into()),
3442 },
3443 other => self.expr_at(other, want.as_ref())?,
3444 };
3445 let ty = t.ty.clone().or(e.ty.clone());
3446 Ok(Val::new(
3447 format!("(if {}: {} else: {})", c.code, t.code, e.code),
3448 ty,
3449 ))
3450 }
3451
3452 fn lit_at(&mut self, l: &Lit, expect: Option<&Nim>) -> Result<Val, String> {
3453 match l {
3454 Lit::Int(i) => {
3455 let suffix = i.suffix();
3456 if let Some(why) = ty::rejected(suffix) {
3457 return Err(format!("integer literal `{}`: {}", i, why));
3458 }
3459 let digits = i.base10_digits().to_string();
3460 // Rust's default for an unconstrained integer literal is i32.
3461 // Nim's is `int` (64-bit). Making the width explicit is what
3462 // keeps overflow behaviour the same on both sides.
3463 let t = if suffix.is_empty() {
3464 match expect {
3465 Some(t) if t.is_integer() => t.clone(),
3466 // Rust's fallback for an otherwise-unconstrained
3467 // integer literal.
3468 _ => Nim::Prim("int32".into()),
3469 }
3470 } else {
3471 ty::prim(suffix).ok_or_else(|| format!("unknown literal suffix `{suffix}`"))?
3472 };
3473 Ok(Val::new(format!("{}'{}", digits, nim_suffix(&t)?), Some(t)))
3474 }
3475 Lit::Float(f) => {
3476 let t = match f.suffix() {
3477 "" => match expect {
3478 Some(Nim::Prim(p)) if p == "float32" => Nim::Prim("float32".into()),
3479 _ => Nim::Prim("float64".into()),
3480 },
3481 "f64" => Nim::Prim("float64".into()),
3482 "f32" => Nim::Prim("float32".into()),
3483 s => return Err(format!("unknown float suffix `{s}`")),
3484 };
3485 let d = f.base10_digits();
3486 let d = if d.contains('.') || d.contains('e') { d.to_string() } else { format!("{d}.0") };
3487 Ok(Val::new(d, Some(t)))
3488 }
3489 Lit::Bool(b) => Ok(Val::new(b.value.to_string(), Some(Nim::Prim("bool".into())))),
3490 Lit::Str(s) => Ok(Val::new(
3491 fmt::nim_str(&s.value()),
3492 Some(Nim::Prim("string".into())),
3493 )),
3494 Lit::Char(c) => Ok(Val::new(
3495 format!("Rune({})", c.value() as u32),
3496 Some(Nim::Prim("Rune".into())),
3497 )),
3498 Lit::Byte(b) => Ok(Val::new(
3499 format!("{}'u8", b.value()),
3500 Some(Nim::Prim("uint8".into())),
3501 )),
3502 Lit::ByteStr(b) => {
3503 let bytes: Vec<String> = b.value().iter().map(|x| format!("{x}'u8")).collect();
3504 Ok(Val::new(
3505 format!("@[{}]", bytes.join(", ")),
3506 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
3507 ))
3508 }
3509 other => Err(format!("unsupported literal: {other:?}")),
3510 }
3511 }
3512
3513 fn unary(&mut self, u: &syn::ExprUnary, expect: Option<&Nim>) -> Result<Val, String> {
3514 // `-128i8` is a literal in Rust, but `-(128'i8)` in Nim would overflow
3515 // the positive half of the range before the negation runs. Folding the
3516 // sign into the literal keeps `i8::MIN` and friends expressible.
3517 if let (UnOp::Neg(_), Expr::Lit(l)) = (&u.op, &*u.expr) {
3518 if matches!(l.lit, Lit::Int(_) | Lit::Float(_)) {
3519 let v = self.lit_at(&l.lit, expect)?;
3520 return Ok(Val::new(format!("-{}", v.code), v.ty));
3521 }
3522 }
3523 let v = self.expr_at(&u.expr, expect)?;
3524 match u.op {
3525 UnOp::Neg(_) => Ok(Val::new(format!("(-{})", v.code), v.ty)),
3526 // Rust's `!` is logical on bool and bitwise-complement on integers.
3527 // Nim spells those `not` and `not` as well, so one mapping covers
3528 // both — but only because Nim overloads `not` the same way.
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 15h ago3529 UnOp::Not(_) => {
3530 if let Some(f) = self.op_proc(&v.ty, "not") {
3531 return Ok(Val::new(format!("{}({})", f, v.code), v.ty));
3532 }
3533 Ok(Val::new(format!("(not {})", v.code), v.ty))
3534 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3535 UnOp::Deref(_) => Ok(v),
3536 _ => Err("unsupported unary operator".into()),
3537 }
3538 }
3539
3540 fn binary(&mut self, b: &syn::ExprBinary, expect: Option<&Nim>) -> Result<Val, String> {
3541 // A comparison's operands are unrelated to the `bool` it produces, so
3542 // the outer expectation is not passed through to them.
3543 let down = match b.op {
3544 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
3545 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => None,
3546 _ => expect,
3547 };
3548 let mut l = self.expr_at(&b.left, down)?;
3549 // Rust unifies the two operand types; propagating whichever side is
3550 // known to the other reproduces that, and disagreement then surfaces
3551 // as a Nim type error rather than as a silent width change.
3552 let mut r = self.expr_at(&b.right, l.ty.as_ref().or(down))?;
3553 if l.ty.is_none() && r.ty.is_some() {
3554 l = self.expr_at(&b.left, r.ty.as_ref())?;
3555 }
3556 let r = std::mem::replace(&mut r, Val::untyped(""));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago3557 // A binary operator on a user type goes to that type's own impl.
3558 if let Some(f) = self.op_proc(&l.ty, binary_symbol(&b.op)) {
3559 let want = self.op_param(&l.ty, binary_symbol(&b.op));
3560 let r = self.expr_at(&b.right, want.as_ref())?;
3561 let ret = self
3562 .methods
3563 .get(&(
3564 type_name(l.ty.as_ref().unwrap()),
3565 op_method(binary_symbol(&b.op)).to_string(),
3566 ))
3567 .map(|s| s.ret.clone());
3568 return Ok(Val::new(format!("{}({}, {})", f, l.code, r.code), ret));
3569 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3570 let op = self.bin_op(&b.op, &l, &r)?;
3571 let ty = match b.op {
3572 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
3573 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => Some(Nim::Prim("bool".into())),
3574 // Rust's shift takes its result type from the *left* operand, and
3575 // the right may be a different width entirely.
3576 BinOp::Shl(_) | BinOp::Shr(_) => l.ty.clone(),
3577 _ => l.ty.clone().or(r.ty.clone()),
3578 };
3579 Ok(Val::new(format!("({} {} {})", l.code, op, r.code), ty))
3580 }
3581
3582 fn bin_op(&mut self, op: &BinOp, l: &Val, r: &Val) -> Result<&'static str, String> {
3583 Ok(match op {
3584 BinOp::Add(_) | BinOp::AddAssign(_) => "+",
3585 BinOp::Sub(_) | BinOp::SubAssign(_) => "-",
3586 BinOp::Mul(_) | BinOp::MulAssign(_) => "*",
3587 BinOp::Div(_) | BinOp::DivAssign(_) => {
3588 // Nim spells integer division `div`. Both languages truncate
3589 // toward zero, so once the right operator is chosen the
3590 // semantics match, including for negative operands.
3591 let t = l.ty.clone().or(r.ty.clone()).ok_or(
3592 "cannot tell integer from float division here; annotate the operands",
3593 )?;
3594 if t.is_integer() { "div" } else { "/" }
3595 }
3596 BinOp::Rem(_) | BinOp::RemAssign(_) => {
3597 let t = l.ty.clone().or(r.ty.clone()).ok_or(
3598 "cannot tell integer from float remainder here; annotate the operands",
3599 )?;
3600 if t.is_integer() { "mod" } else { return Err("float `%` is not implemented yet".into()) }
3601 }
3602 BinOp::And(_) => "and",
3603 BinOp::Or(_) => "or",
3604 // Nim's `and`/`or`/`xor` are bitwise on integers and logical on
3605 // bools, exactly as Rust's `&`/`|`/`^` are.
3606 BinOp::BitAnd(_) | BinOp::BitAndAssign(_) => "and",
3607 BinOp::BitOr(_) | BinOp::BitOrAssign(_) => "or",
3608 BinOp::BitXor(_) | BinOp::BitXorAssign(_) => "xor",
3609 // Settled empirically: Nim's `shr` on a signed integer is
3610 // arithmetic, matching Rust. See DESIGN.md.
3611 BinOp::Shl(_) | BinOp::ShlAssign(_) => "shl",
3612 BinOp::Shr(_) | BinOp::ShrAssign(_) => "shr",
3613 BinOp::Eq(_) => "==",
3614 BinOp::Ne(_) => "!=",
3615 BinOp::Lt(_) => "<",
3616 BinOp::Le(_) => "<=",
3617 BinOp::Gt(_) => ">",
3618 BinOp::Ge(_) => ">=",
3619 other => return Err(format!("unsupported binary operator {other:?}")),
3620 })
3621 }
3622
3623 fn cast(&mut self, c: &syn::ExprCast) -> Result<Val, String> {
3624 let v = self.expr(&c.expr)?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3625 let to = self.map_ty(&c.ty)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3626 let from = v.ty.clone().ok_or_else(|| {
3627 format!(
3628 "cannot lower `as {}`: the source type is unknown, and `as` \
3629 truncates, so the source width decides the result",
3630 to.render()
3631 )
3632 })?;
3633
3634 let code = match (&from, &to) {
3635 (f, t) if f.is_integer() && t.is_integer() => {
3636 // Rust's `as` between integers is a pure bit-width truncation
Prove byte-identity for base16ct by enumerating whole input domains 99b8376 nandithebull 16h ago3637 // or sign-extension, never a range check. `cast` says exactly
3638 // that. (Nim's `T(x)` turns out to truncate here as well --
3639 // see DESIGN.md item 5 -- but `cast` is the spelling that
3640 // means it rather than the one that happens to agree.)
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3641 format!("cast[{}]({})", t.render(), v.code)
3642 }
3643 (f, Nim::Prim(p)) if f.is_integer() && (p == "float64" || p == "float32") => {
3644 format!("{}({})", p, v.code)
3645 }
3646 (Nim::Prim(b), t) if b == "bool" && t.is_integer() => {
3647 format!("{}(ord({}))", t.render(), v.code)
3648 }
3649 (Nim::Prim(r), t) if r == "Rune" && t.is_integer() => {
3650 format!("cast[{}](int32({}))", t.render(), v.code)
3651 }
3652 (f, Nim::Prim(r)) if f.is_integer() && r == "Rune" => {
3653 format!("Rune(int32({}))", v.code)
3654 }
3655 (Nim::Prim(a), Nim::Prim(b)) if a == b => v.code.clone(),
3656 (f, t) if matches!(f, Nim::Prim(p) if p.starts_with("float")) && t.is_integer() => {
3657 // Rust saturates float->int casts; Nim rounds and range-errors.
3658 // Not the same operation, so it is refused rather than mapped.
3659 return Err(format!(
3660 "`as {}` from a float: Rust saturates, Nim rounds and range-checks; \
3661 no faithful mapping is implemented",
3662 t.render()
3663 ));
3664 }
3665 (f, t) => {
3666 return Err(format!(
3667 "unsupported cast from `{}` to `{}`",
3668 f.render(),
3669 t.render()
3670 ))
3671 }
3672 };
3673 Ok(Val::new(code, Some(to)))
3674 }
3675
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3676 /// Rust's `?`: return early on the error branch, otherwise yield the value.
3677 ///
3678 /// The early return is statements, not an expression, so they are emitted
3679 /// ahead of the line being built. Every caller lowers its sub-expressions
3680 /// before emitting its own line, which is what makes that ordering hold.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago3681 /// The container, start offset, length and element type an expression
3682 /// denotes as a slice. A window alias contributes its own offset, so
3683 /// `dst.get_mut(..n)` followed by `.chunks_exact_mut(2)` indexes straight
3684 /// into the original buffer rather than through a rebuilt view.
3685 fn slice_parts(
3686 &mut self,
3687 e: &Expr,
3688 ) -> Result<(String, String, String, Option<Nim>), String> {
3689 if let Some(Alias::Window { code, off, len, elem }) = self.window_of(e) {
3690 return Ok((code, off, len, elem));
3691 }
3692 let v = self.expr(e)?;
3693 let len = format!("{}.len", v.code);
3694 Ok((v.code, "0".to_string(), len, elem_of(&v.ty)))
3695 }
3696
3697 /// Expand `opt.map(|x| body)` / `res.and_then(|x| body)` inline.
3698 fn map_closure(
3699 &mut self,
3700 what: &str,
3701 recv: &Val,
3702 kind: &str,
3703 targs: &[Nim],
3704 c: &syn::ExprClosure,
3705 ) -> Result<Val, String> {
3706 if c.capture.is_some() {
3707 return Err("a `move` closure captures by value; Nim's closures \
3708 capture by reference, and the two are not the same"
3709 .into());
3710 }
3711 if c.inputs.len() != 1 {
3712 return Err(format!("`.{what}()` takes a one-argument closure"));
3713 }
3714 let pname = match &c.inputs[0] {
3715 Pat::Ident(i) => i.ident.to_string(),
3716 Pat::Wild(_) => "unused0".into(),
3717 _ => return Err("only plain identifier closure parameters are supported".into()),
3718 };
3719
3720 let is_opt = kind == "Option";
3721 let tmp = self.fresh("Map");
3722 let recv_ty = Nim::Named(kind.to_string(), targs.to_vec());
3723 self.line(&format!("let {}: {} = {}", tmp, recv_ty.render(), recv.code));
3724
3725 let body = match &*c.body {
3726 Expr::Block(b) => single_expr(&b.block)
3727 .ok_or("a closure body with statements is not implemented yet")?,
3728 other => other,
3729 };
3730 self.push_scope();
3731 // The parameter names the payload itself, so a view stays a view.
3732 self.bind_alias(
3733 &pname,
3734 Alias::Value {
3735 code: format!("{}.val", tmp),
3736 ty: Some(targs[0].clone()),
3737 },
3738 );
3739 let v = self.expr(body)?;
3740 self.pop_scope();
3741
3742 let inner = v
3743 .ty
3744 .clone()
3745 .ok_or_else(|| format!("cannot infer the result type of `.{what}()`"))?;
3746 // `and_then`'s closure already returns the wrapped type; `map`'s does
3747 // not and has to be re-wrapped.
3748 let (test, some_branch, none_branch, out_ty) = if is_opt {
3749 let out = if what == "map" {
3750 Nim::Named("Option".into(), vec![inner.clone()])
3751 } else {
3752 inner.clone()
3753 };
3754 let body_code = if what == "map" {
3755 format!("rsSome[{}]({})", inner.render(), v.code)
3756 } else {
3757 v.code.clone()
3758 };
3759 (
3760 format!("{}.has", tmp),
3761 body_code,
3762 format!("rsNone[{}]()", elem_arg(&out).render()),
3763 out,
3764 )
3765 } else {
3766 let e = targs[1].clone();
3767 let out = if what == "map" {
3768 Nim::Named("Result".into(), vec![inner.clone(), e.clone()])
3769 } else {
3770 inner.clone()
3771 };
3772 let ok_ty = elem_arg(&out);
3773 let body_code = if what == "map" {
3774 format!("rsOk[{}, {}]({})", inner.render(), e.render(), v.code)
3775 } else {
3776 v.code.clone()
3777 };
3778 (
3779 format!("{}.ok", tmp),
3780 body_code,
3781 format!("rsErr[{}, {}]({}.err)", ok_ty.render(), e.render(), tmp),
3782 out,
3783 )
3784 };
3785 Ok(Val::new(
3786 format!("(if {}: {} else: {})", test, some_branch, none_branch),
3787 Some(out_ty),
3788 ))
3789 }
3790
3791 /// `|x| x + 1` -> a Nim anonymous proc.
3792 ///
3793 /// Nim's closures capture by reference, as Rust's non-`move` closures do.
3794 /// A `move` closure captures by value, which is a different thing, so it
3795 /// is rejected rather than lowered to the same construct.
3796 fn closure(&mut self, c: &syn::ExprClosure, expect: Option<&Nim>) -> Result<Val, String> {
3797 if c.capture.is_some() {
3798 return Err("a `move` closure captures by value; Nim's closures \
3799 capture by reference, and the two are not the same"
3800 .into());
3801 }
3802 let want: Option<&Vec<Nim>> = match expect {
3803 Some(Nim::Proc(a, _)) => Some(a),
3804 _ => None,
3805 };
3806
3807 self.push_scope();
3808 let mut parts = Vec::new();
3809 let mut ptys = Vec::new();
3810 for (i, p) in c.inputs.iter().enumerate() {
3811 let (name, ann) = match p {
3812 Pat::Ident(id) => (id.ident.to_string(), None),
3813 Pat::Type(t) => match &*t.pat {
3814 Pat::Ident(id) => (id.ident.to_string(), Some(self.map_ty(&t.ty)?)),
3815 _ => return Err("only plain identifier closure parameters are supported".into()),
3816 },
3817 Pat::Wild(_) => (format!("unused{i}"), None),
3818 _ => return Err("only plain identifier closure parameters are supported".into()),
3819 };
3820 let t = ann
3821 .or_else(|| want.and_then(|w| w.get(i).cloned()))
3822 .ok_or_else(|| {
3823 format!(
3824 "cannot infer the type of closure parameter `{name}`; \
3825 annotate it"
3826 )
3827 })?;
3828 parts.push(format!("{}: {}", ident(&name), t.render()));
3829 self.bind(&name, t.clone());
3830 ptys.push(t);
3831 }
3832
3833 let ret_ann = match &c.output {
3834 ReturnType::Default => None,
3835 ReturnType::Type(_, t) => Some(self.map_ty(t)?.owned()),
3836 };
3837 let body = match &*c.body {
3838 Expr::Block(b) => single_expr(&b.block)
3839 .ok_or("a closure body with statements is not implemented yet")?,
3840 other => other,
3841 };
3842 let v = self.expr_at(body, ret_ann.as_ref())?;
3843 self.pop_scope();
3844
3845 let ret = ret_ann
3846 .or_else(|| v.ty.clone())
3847 .ok_or("cannot infer a closure's return type; annotate it")?;
3848 Ok(Val::new(
3849 format!("(proc ({}): {} = {})", parts.join(", "), ret.render(), v.code),
3850 Some(Nim::Proc(ptys, Box::new(ret))),
3851 ))
3852 }
3853
3854 /// Lower a block's statements at the current indentation, without opening
3855 /// a Nim `block:` -- used for `unsafe { .. }`, which introduces no scope
3856 /// of its own in the generated code.
3857 fn nested_block_flat(&mut self, b: &syn::Block) -> Result<(), String> {
3858 self.push_scope();
3859 let tail = self.block_body(b)?;
3860 self.emit_tail(tail);
3861 self.pop_scope();
3862 Ok(())
3863 }
3864
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3865 fn try_op(&mut self, t: &syn::ExprTry) -> Result<Val, String> {
3866 if self.in_loop_cond {
3867 return Err("`?` in a loop condition is not implemented yet: the \
3868 early-return it expands to would be evaluated once, \
3869 before the loop, rather than on each iteration"
3870 .into());
3871 }
3872 let v = self.expr(&t.expr)?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago3873 if self.fmt_param.is_some() {
3874 // Writing into a string cannot fail, so `?` on a formatter write
3875 // is a no-op. `?` on anything else can fail, and `format!` panics
3876 // when a formatting impl returns an error -- so that is what the
3877 // error branch does here, with std's own message.
3878 if v.ty.as_ref() == Some(&Nim::Unit) {
3879 return Ok(v);
3880 }
3881 if let Some(Nim::Named(n, a)) = v.ty.clone() {
3882 if n == "Result" && a.len() == 2 {
3883 let tmp = self.fresh("Fmt");
3884 self.line(&format!(
3885 "let {}: {} = {}",
3886 tmp,
3887 Nim::Named(n, a.clone()).render(),
3888 v.code
3889 ));
3890 self.line(&format!("if not {}.ok:", tmp));
3891 self.line(
3892 " rsPanic(\"a formatting trait implementation returned an error\")",
3893 );
3894 return Ok(Val::new(format!("{}.val", tmp), Some(a[0].clone())));
3895 }
3896 }
3897 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago3898 if let (Some(guard), Some(w)) = (v.guard.clone(), v.window.clone()) {
3899 // An `Option`/`Result` of a view: the check is emitted here and the
3900 // view itself survives as an alias, since it has no value form.
3901 let ret = self.ret.clone().ok_or("`?` outside a function with a return type")?;
3902 let err = v.guard_err.clone().ok_or(
3903 "`?` on a `get`/`get_mut` needs an `ok_or` to say what the error is",
3904 )?;
3905 let Nim::Named(n, ra) = &ret else {
3906 return Err(format!("`?` in a function returning `{}`", ret.render()));
3907 };
3908 if n != "Result" || ra.len() != 2 {
3909 return Err(format!("`?` in a function returning `{}`", ret.render()));
3910 }
3911 self.line(&format!("if not {}:", guard));
3912 self.line(&format!(
3913 " return rsErr[{}, {}]({})",
3914 ra[0].render(),
3915 ra[1].render(),
3916 err
3917 ));
3918 let mut out = Val::new(String::new(), None);
3919 out.window = Some(w);
3920 return Ok(out);
3921 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3922 let vt = v.ty.clone().ok_or(
3923 "`?` needs a known `Result`/`Option` type; annotate the expression it applies to",
3924 )?;
3925 let ret = self
3926 .ret
3927 .clone()
3928 .ok_or("`?` outside a function with a return type")?;
3929 let tmp = self.fresh("Try");
3930 self.line(&format!("let {}: {} = {}", tmp, vt.render(), v.code));
3931
3932 match (&vt, &ret) {
3933 (Nim::Named(a, ai), Nim::Named(b, bi))
3934 if a == "Result" && b == "Result" && ai.len() == 2 && bi.len() == 2 =>
3935 {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago3936 // Rust inserts a `From::from` on the error here. Where the
3937 // types differ we call the crate's own `impl From`; we never
3938 // assume the conversion is the identity.
3939 let err = if ai[1] == bi[1] {
3940 format!("{}.err", tmp)
3941 } else {
3942 let key = (type_name(&ai[1]), type_name(&bi[1]));
3943 let f = self.from_impls.get(&key).cloned().ok_or_else(|| {
3944 format!(
3945 "`?` needs `From<{}> for {}` to convert the error, and \
3946 no such `impl` is in scope; assuming the conversion is \
3947 the identity would be a guess",
3948 key.0, key.1
3949 )
3950 })?;
3951 format!("{}({}.err)", f, tmp)
3952 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3953 self.line(&format!("if not {}.ok:", tmp));
3954 self.line(&format!(
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago3955 " return rsErr[{}, {}]({})",
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3956 bi[0].render(),
3957 bi[1].render(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago3958 err
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3959 ));
3960 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
3961 }
3962 (Nim::Named(a, ai), Nim::Named(b, bi))
3963 if a == "Option" && b == "Option" && ai.len() == 1 && bi.len() == 1 =>
3964 {
3965 self.line(&format!("if not {}.has:", tmp));
3966 self.line(&format!(" return rsNone[{}]()", bi[0].render()));
3967 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
3968 }
3969 _ => Err(format!(
3970 "`?` on `{}` in a function returning `{}` is not a supported \
3971 combination",
3972 vt.render(),
3973 ret.render()
3974 )),
3975 }
3976 }
3977
3978 fn call(&mut self, c: &syn::ExprCall, expect: Option<&Nim>) -> Result<Val, String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3979 let Expr::Path(p) = &*c.func else {
3980 return Err("only calls to named functions are supported".into());
3981 };
3982 let name = path_name(&p.path);
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago3983 let target = self.resolve_fn(&p.path);
3984 let ptys: Vec<Nim> = target
3985 .as_ref()
3986 .and_then(|k| self.fns.get(k))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago3987 .map(|s| s.params.clone())
3988 .unwrap_or_default();
3989 let mut args = Vec::new();
3990 for (i, a) in c.args.iter().enumerate() {
3991 let want = ptys.get(i).cloned();
3992 args.push(self.expr_at(a, want.as_ref())?);
3993 }
3994 let codes: Vec<String> = args.iter().map(|a| a.code.clone()).collect();
3995
3996 // Constructors from the prelude.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago3997 // `Ok`/`Err` must name the *whole* Result type, not just the half
3998 // being constructed: Nim cannot infer `E` from an `Ok(v)` alone.
3999 match name.as_str() {
4000 "Some" => {
4001 let inner = match expect {
4002 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].render(),
4003 _ => {
4004 return Err("`Some(..)` needs a known `Option<T>` type here; \
4005 annotate the binding or the return type"
4006 .into())
4007 }
4008 };
4009 return Ok(Val::new(
4010 format!("rsSome[{}]({})", inner, codes.join(", ")),
4011 expect.cloned(),
4012 ));
4013 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4014 "Ok" if self.fmt_param.is_some()
4015 && matches!(c.args.first(), Some(Expr::Tuple(t)) if t.elems.is_empty()) =>
4016 {
4017 // `Ok(())` ends a `fmt` body: nothing more is written.
4018 return Ok(Val::new(String::new(), Some(Nim::Unit)));
4019 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago4020 "Ok" | "Err" => {
4021 let (t, e) = match expect {
4022 Some(Nim::Named(n, a)) if n == "Result" && a.len() == 2 => {
4023 (a[0].render(), a[1].render())
4024 }
4025 _ => {
4026 return Err(format!(
4027 "`{name}(..)` needs a known `Result<T, E>` type here; \
4028 annotate the binding or the return type"
4029 ))
4030 }
4031 };
4032 let ctor = if name == "Ok" { "rsOk" } else { "rsErr" };
4033 let arg = if codes.is_empty() { String::new() } else { codes.join(", ") };
4034 return Ok(Val::new(
4035 format!("{}[{}, {}]({})", ctor, t, e, arg),
4036 expect.cloned(),
4037 ));
4038 }
4039 _ => {}
4040 }
4041
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4042 // A tuple struct applied to arguments: `HexDisplay(bytes)`. Nim's
4043 // object constructor names its fields even when Rust's does not.
4044 if let Some(fields) = self.structs.get(&name).cloned() {
4045 if fields.len() == c.args.len() {
4046 let mut parts = Vec::new();
4047 for (i, a) in c.args.iter().enumerate() {
4048 let v = self.expr_at(a, Some(&fields[i].1))?;
4049 parts.push(format!("{}: {}", ident(&fields[i].0), v.code));
4050 }
4051 return Ok(Val::new(
4052 format!("{}({})", ident(&name), parts.join(", ")),
4053 Some(Nim::Named(name.clone(), vec![])),
4054 ));
4055 }
4056 }
4057
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago4058 // `Spacing::from(d)`: a `From` impl called through its target type.
4059 // Rust picks the impl by the argument's type, and so do we -- Nim
4060 // cannot overload on return type, so each impl has its own proc name.
4061 if name == "from" && codes.len() == 1 {
4062 if let Some(q) = p.path.segments.iter().rev().nth(1).map(|s| s.ident.to_string()) {
4063 let q = if q == "Self" {
4064 self.self_ty.as_ref().map(type_name).unwrap_or(q)
4065 } else {
4066 q
4067 };
4068 if let Some(src) = args[0].ty.as_ref().map(type_name) {
4069 if let Some(f) = self.from_impls.get(&(src, q.clone())).cloned() {
4070 return Ok(Val::new(
4071 format!("{}({})", f, codes[0]),
4072 Some(Nim::Named(q, vec![])),
4073 ));
4074 }
4075 }
4076 }
4077 }
4078
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago4079 // `u32::from(b)`: `From` between primitives is lossless by definition
4080 // -- it is the widening direction only -- so a plain Nim conversion is
4081 // exact. (The truncating direction is `as`, which is `cast`.)
4082 if name == "from" && codes.len() == 1 {
4083 if let Some(q) = p.path.segments.iter().rev().nth(1) {
4084 if let Some(Nim::Prim(t)) = ty::prim(&q.ident.to_string()) {
4085 return Ok(Val::new(
4086 format!("{}({})", t, codes[0]),
4087 Some(Nim::Prim(t)),
4088 ));
4089 }
4090 }
4091 }
4092
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4093 // `core::str::from_utf8_unchecked(b)` reinterprets a byte view as a
4094 // string view; no copy, no validation, same memory.
4095 if name == "from_utf8_unchecked" && codes.len() == 1 {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4096 // `String::from_utf8_unchecked(v)` takes ownership and yields an
4097 // owned `String`; `str::from_utf8_unchecked(b)` borrows and yields
4098 // a view. Same name, different operations -- the qualifier says
4099 // which, and an unqualified call is ambiguous.
4100 let q = p
4101 .path
4102 .segments
4103 .iter()
4104 .rev()
4105 .nth(1)
4106 .map(|s| s.ident.to_string());
4107 return match q.as_deref() {
4108 Some("String") => Ok(Val::new(
4109 format!("rsStringOf({})", codes[0]),
4110 Some(Nim::Prim("string".into())),
4111 )),
4112 Some("str") => Ok(Val::new(
4113 format!("rsStrView({})", codes[0]),
4114 Some(Nim::OpenArray(Box::new(Nim::Prim("char".into())))),
4115 )),
4116 _ => Err(
4117 "`from_utf8_unchecked` must be written as `str::..` (a \
4118 borrowed view) or `String::..` (an owned string); the two \
4119 are different operations"
4120 .into(),
4121 ),
4122 };
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4123 }
4124
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago4125 // A tuple enum variant applied to arguments: `Shape::Circle(1.0)`.
4126 if let Some((def, v)) = self.resolve_variant(&p.path) {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago4127 let (ty, _) = self.variant_type(&def, expect)?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago4128 return Ok(Val::new(
4129 format!("{}({})", def.ctor_ident(&v), codes.join(", ")),
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago4130 Some(ty),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago4131 ));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4132 }
4133
4134 // A bare path that names a primitive type is Rust's tuple-struct-like
4135 // conversion, e.g. `String::from(..)`; handled by the method path.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago4136 // Calling a proc-typed local, which is how an `impl Fn(..)` parameter
4137 // is invoked.
4138 if let Some(Nim::Proc(_, ret)) = self.lookup(&name) {
4139 return Ok(Val::new(
4140 format!("{}({})", ident(&name), codes.join(", ")),
4141 Some((*ret).clone()),
4142 ));
4143 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago4144 // `Adler32::new()` / `Adler32::default()`: a method called through
4145 // its type rather than through a receiver.
4146 if let Some(q) = p.path.segments.iter().rev().nth(1).map(|s| s.ident.to_string()) {
4147 // `Self::new()` inside an `impl` names the type being implemented.
4148 let q = if q == "Self" {
4149 self.self_ty.as_ref().map(type_name).unwrap_or(q)
4150 } else {
4151 q
4152 };
4153 if let Some(sig) = self.methods.get(&(q.clone(), name.clone())) {
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 15h ago4154 // Re-lower the arguments with the declared parameter types, so
4155 // a literal takes the width the signature asks for.
4156 let declared = sig.params.clone();
4157 let mut args = args.clone();
4158 let mut codes = codes.clone();
4159 for (i, a) in c.args.iter().enumerate() {
4160 if let Some(want) = declared.get(i) {
4161 let want = want.clone().unvar();
4162 args[i] = self.expr_at(a, Some(&want))?;
4163 codes[i] = args[i].code.clone();
4164 }
4165 }
4166 let sig = &self.methods[&(q.clone(), name.clone())];
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago4167 let arg_tys: Vec<Option<Nim>> = args.iter().map(|a| a.ty.clone()).collect();
4168 let ret = Self::instantiate(sig, &arg_tys);
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago4169 let nim = self
4170 .statics
4171 .get(&(q.clone(), name.clone()))
4172 .cloned()
4173 .unwrap_or_else(|| ident(&name));
4174 return Ok(Val::new(format!("{}({})", nim, codes.join(", ")), Some(ret)));
4175 }
4176 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago4177 let arg_tys: Vec<Option<Nim>> = args.iter().map(|a| a.ty.clone()).collect();
4178 let ret = target
4179 .as_ref()
4180 .and_then(|k| self.fns.get(k))
4181 .map(|sig| Self::instantiate(sig, &arg_tys));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago4182 if ret.is_none() && !self.structs.contains_key(&name) && !self.enums.contains_key(&name) {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4183 return Err(format!(
4184 "call to unknown function `{name}`; only functions defined in \
4185 this file and the supported standard-library subset can be lowered"
4186 ));
4187 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4188 let nim = match &target {
4189 Some((m, n)) => self.fn_name(m, n),
4190 None => ident(&name),
4191 };
4192 Ok(Val::new(format!("{}({})", nim, codes.join(", ")), ret))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4193 }
4194
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4195 fn method(&mut self, m: &syn::ExprMethodCall, expect: Option<&Nim>) -> Result<Val, String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4196 let name = m.method.to_string();
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago4197 // `chunk_iter.remainder()` — the tail `chunks_exact` will not yield.
4198 if name == "remainder" && m.args.is_empty() {
4199 if let Expr::Path(p) = &*m.receiver {
4200 if let Some(Alias::Iterator(it)) = self.lookup_alias(&path_name(&p.path)) {
4201 if let Iter::Chunks { code, base, len, k, elem, .. } = &*it {
4202 let kept = format!("(({} div int({})) * int({}))", len, k, k);
4203 let mut v = Val::new(
4204 String::new(),
4205 elem.clone().map(|e| Nim::OpenArray(Box::new(e))),
4206 );
4207 v.window = Some(Alias::Window {
4208 code: code.clone(),
4209 off: format!("({} + {})", base, kept),
4210 len: format!("({} - {})", len, kept),
4211 elem: elem.clone(),
4212 });
4213 return Ok(v);
4214 }
4215 return Err(
4216 "`.remainder()` is only defined for a `chunks_exact` iterator".into(),
4217 );
4218 }
4219 }
4220 return Err("`.remainder()` needs an iterator bound by `let`".into());
4221 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4222 if let Some(Alias::Window { len, .. }) = self.window_of(&m.receiver) {
4223 match name.as_str() {
4224 "len" => {
4225 return Ok(Val::new(format!("uint({})", len), Some(Nim::Prim("uint".into()))))
4226 }
4227 "is_empty" => {
4228 return Ok(Val::new(format!("({} == 0)", len), Some(Nim::Prim("bool".into()))))
4229 }
4230 other => {
4231 return Err(format!(
4232 "`.{other}()` on a slice window from `chunks_exact`/\
4233 `windows` is not implemented; only indexing and \
4234 `len()` are"
4235 ))
4236 }
4237 }
4238 }
4239 let recv = self.expr(&m.receiver)?;
4240 let rt0 = recv.ty.clone();
4241
4242// `s.get(a..b)` / `s.get_mut(a..b)`: an `Option<&[T]>`. Nim has no
4243 // way to put a view in an object, so instead of materialising an
4244 // Option the view and its validity condition travel together until
4245 // an `ok_or`/`?`/`unwrap` resolves them.
4246 if matches!(name.as_str(), "get" | "get_mut")
4247 && matches!(m.args.first(), Some(Expr::Range(_)))
4248 {
4249 let Some(Expr::Range(r)) = m.args.first() else { unreachable!() };
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4250 let (code, base, blen, belem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4251 let lo = match &r.start {
4252 Some(e) => format!("int({})", self.expr(e)?.code),
4253 None => "0".into(),
4254 };
4255 let len = match (&r.end, r.limits) {
4256 (Some(e), syn::RangeLimits::HalfOpen(_)) => {
4257 format!("(int({}) - {})", self.expr(e)?.code, lo)
4258 }
4259 (Some(e), syn::RangeLimits::Closed(_)) => {
4260 format!("(int({}) - {} + 1)", self.expr(e)?.code, lo)
4261 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4262 (None, _) => format!("({} - {})", blen, lo),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4263 };
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4264 // Hoisted, so the bounds are computed once -- as Rust computes
4265 // them once -- and cannot be re-evaluated later in a scope where
4266 // the names they mention have been shadowed by a loop pattern.
4267 let off_t = self.fresh("Off");
4268 let len_t = self.fresh("Len");
4269 self.line(&format!("let {}: int = {} + {}", off_t, base, lo));
4270 self.line(&format!("let {}: int = {}", len_t, len));
4271 let elem = belem
4272 .or_else(|| elem_of(&rt0))
4273 .ok_or("cannot infer the element type of this slice")?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4274 let mut v = Val::new(
4275 String::new(),
4276 Some(Nim::Named(
4277 "Option".into(),
4278 vec![Nim::OpenArray(Box::new(elem.clone()))],
4279 )),
4280 );
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4281 v.guard = Some(format!("({} + {} <= {})", off_t, len_t, blen));
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4282 v.window = Some(Alias::Window {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4283 code,
4284 off: off_t,
4285 len: len_t,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4286 elem: Some(elem),
4287 });
4288 return Ok(v);
4289 }
4290
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4291 // `.map`/`.and_then` over an `Option`/`Result` take a closure whose
4292 // parameter type comes from the receiver, so they are handled before
4293 // the arguments are lowered. The closure is expanded inline, with its
4294 // parameter aliased to the payload: that keeps the whole thing an
4295 // expression and avoids handing a view to a generic proc.
4296 if matches!(name.as_str(), "map" | "and_then") && m.args.len() == 1 {
4297 if let (Some(Nim::Named(kind, targs)), Expr::Closure(c)) =
4298 (recv.ty.clone(), &m.args[0])
4299 {
4300 if (kind == "Option" && targs.len() == 1) || (kind == "Result" && targs.len() == 2)
4301 {
4302 return self.map_closure(&name, &recv, &kind, &targs, c);
4303 }
4304 }
4305 }
4306
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4307 // `x.wrapping_add(1)` and `x.min(3)` take an argument of the receiver's
4308 // own type; `v.push(e)` takes the element type.
4309 let arg_want = match (name.as_str(), &recv.ty) {
4310 ("push", Some(Nim::Seq(t))) | ("push", Some(Nim::OpenArray(t))) => Some((**t).clone()),
4311 (_, t) => t.clone(),
4312 };
4313 let mut args = Vec::new();
4314 for a in &m.args {
4315 args.push(self.expr_at(a, arg_want.as_ref())?);
4316 }
4317 let a0 = args.first().map(|a| a.code.clone());
4318 let rt = recv.ty.clone();
4319
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 15h ago4320 // A method the input defines wins over our model of the standard
4321 // library: `is_empty` on a `bitflags!` type is that type's, not the
4322 // sequence one. Rust resolves inherent methods the same way.
4323 if let Some(t) = &rt {
4324 let key = (type_name(t), name.clone());
4325 if self.methods.contains_key(&key) {
4326 let declared = self.methods[&key].params.clone();
4327 let skip = usize::from(declared.len() == m.args.len() + 1);
4328 for (i, a) in m.args.iter().enumerate() {
4329 if let Some(want) = declared.get(i + skip) {
4330 let want = want.clone().unvar();
4331 args[i] = self.expr_at(a, Some(&want))?;
4332 }
4333 }
4334 let mut arg_tys: Vec<Option<Nim>> = vec![rt.clone()];
4335 arg_tys.extend(args.iter().map(|a| a.ty.clone()));
4336 let ret = Self::instantiate(&self.methods[&key], &arg_tys);
4337 let nim = self
4338 .statics
4339 .get(&key)
4340 .cloned()
4341 .unwrap_or_else(|| ident(&name));
4342 let mut all = vec![recv.code.clone()];
4343 all.extend(args.iter().map(|a| a.code.clone()));
4344 return Ok(Val::new(format!("{}({})", nim, all.join(", ")), Some(ret)));
4345 }
4346 }
4347
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4348 let (code, ty) = match name.as_str() {
4349 // Rust's `len()` is `usize`; Nim's is `int`. The conversion is
4350 // explicit so that a `usize` binding type-checks on the Nim side.
4351 "len" => (format!("uint({}.len)", recv.code), Some(Nim::Prim("uint".into()))),
4352 "is_empty" => (format!("({}.len == 0)", recv.code), Some(Nim::Prim("bool".into()))),
4353 "push" => (format!("{}.add({})", recv.code, a0.unwrap_or_default()), Some(Nim::Unit)),
4354 "clone" | "to_vec" | "to_owned" | "as_slice" | "as_ref" | "as_mut" | "iter"
4355 | "into_iter" => (recv.code.clone(), rt.clone()),
4356 "unwrap" | "expect" => {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4357 // Expanded inline rather than called as a generic proc: when
4358 // the payload is a view, Nim can only borrow from a path
4359 // expression, which a proc body containing the panic is not.
4360 let (kind, inner) = match &rt {
4361 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => {
4362 ("Option", a[0].clone())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4363 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4364 Some(Nim::Named(n, a)) if n == "Result" && a.len() == 2 => {
4365 ("Result", a[0].clone())
4366 }
4367 _ => {
4368 return Err(format!(
4369 "`.{name}()` needs a known `Option`/`Result` receiver type"
4370 ))
4371 }
4372 };
4373 if self.in_loop_cond {
4374 return Err(format!(
4375 "`.{name}()` in a loop condition is not implemented yet: the \
4376 check it expands to would run once, before the loop"
4377 ));
4378 }
4379 let tmp = self.fresh("Unwrap");
4380 let rty = rt.clone().unwrap();
4381 self.line(&format!("let {}: {} = {}", tmp, rty.render(), recv.code));
4382 let (test, msg) = if kind == "Option" {
4383 (format!("{}.has", tmp), "called `Option::unwrap()` on a `None` value")
4384 } else {
4385 (format!("{}.ok", tmp), "called `Result::unwrap()` on an `Err` value")
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4386 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4387 let msg = if name == "expect" {
4388 args.first().map(|a| a.code.clone()).unwrap_or_else(|| fmt::nim_str(msg))
4389 } else {
4390 fmt::nim_str(msg)
4391 };
4392 self.line(&format!("if not {}:", test));
4393 self.line(&format!(" rsPanic({})", msg));
4394 // If the payload is a view, hand back an alias rather than a
4395 // value: Nim will not let a `let` borrow out of a local, and a
4396 // view is a reference anyway, so there is nothing to bind.
4397 // `{tmp}.val` is a plain field access, so substituting it at
4398 // each use re-evaluates nothing.
4399 if matches!(inner, Nim::OpenArray(_)) {
4400 let mut v = Val::new(format!("{}.val", tmp), Some(inner.clone()));
4401 v.window = Some(Alias::Value {
4402 code: format!("{}.val", tmp),
4403 ty: Some(inner),
4404 });
4405 return Ok(v);
4406 }
4407 (format!("{}.val", tmp), Some(inner))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4408 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4409 "ok_or" if recv.guard.is_some() => {
4410 let e = args.first().ok_or("`ok_or` takes one argument")?;
4411 let ety = e.ty.clone();
4412 let mut v = recv.clone();
4413 v.guard_err = Some(e.code.clone());
4414 v.ty = match (&recv.ty, ety) {
4415 (Some(Nim::Named(_, a)), Some(et)) if a.len() == 1 => {
4416 Some(Nim::Named("Result".into(), vec![a[0].clone(), et]))
4417 }
4418 _ => None,
4419 };
4420 return Ok(v);
4421 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago4422 "ok_or" => {
4423 let inner = match &rt {
4424 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].clone(),
4425 _ => return Err("`ok_or` needs a known `Option<T>` receiver".into()),
4426 };
4427 let e = args.first().ok_or("`ok_or` takes one argument")?;
4428 let ety = e
4429 .ty
4430 .clone()
4431 .ok_or("`ok_or` needs a known error type for its argument")?;
4432 (
4433 format!(
4434 "rsOkOr[{}, {}]({}, {})",
4435 inner.render(),
4436 ety.render(),
4437 recv.code,
4438 e.code
4439 ),
4440 Some(Nim::Named("Result".into(), vec![inner, ety])),
4441 )
4442 }
4443 "unwrap_or" => {
4444 let inner = match &rt {
4445 Some(Nim::Named(n, a)) if (n == "Option" && a.len() == 1) || (n == "Result" && a.len() == 2) => {
4446 Some(a[0].clone())
4447 }
4448 _ => None,
4449 };
4450 (
4451 format!("unwrapOr({}, {})", recv.code, a0.unwrap_or_default()),
4452 inner,
4453 )
4454 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4455 "is_some" => (format!("{}.has", recv.code), Some(Nim::Prim("bool".into()))),
4456 "is_none" => (format!("(not {}.has)", recv.code), Some(Nim::Prim("bool".into()))),
4457 "is_ok" => (format!("{}.ok", recv.code), Some(Nim::Prim("bool".into()))),
4458 "is_err" => (format!("(not {}.ok)", recv.code), Some(Nim::Prim("bool".into()))),
4459
4460 // Settled empirically: Nim's fixed-width *unsigned* arithmetic
4461 // wraps silently, matching Rust's `wrapping_*`. For *signed* types
4462 // Nim raises OverflowDefect, so the operation is routed through
4463 // the unsigned view of the same width, which is what Rust's
4464 // wrapping_* is defined to compute.
4465 "wrapping_add" | "wrapping_sub" | "wrapping_mul" => {
4466 let op = match name.as_str() {
4467 "wrapping_add" => "+",
4468 "wrapping_sub" => "-",
4469 _ => "*",
4470 };
4471 let t = rt.clone().ok_or_else(|| {
4472 format!("`{name}` needs a known receiver type to pick the wrapping width")
4473 })?;
4474 if !t.is_integer() {
4475 return Err(format!("`{name}` on a non-integer type"));
4476 }
4477 let arg = a0.ok_or_else(|| format!("`{name}` takes one argument"))?;
4478 if t.is_unsigned() {
4479 (format!("({} {} {})", recv.code, op, arg), Some(t))
4480 } else {
4481 let u = unsigned_peer(&t)?;
4482 (
4483 format!(
4484 "cast[{}](cast[{}]({}) {} cast[{}]({}))",
4485 t.render(), u, recv.code, op, u, arg
4486 ),
4487 Some(t),
4488 )
4489 }
4490 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4491 // Inside a formatting impl, a write through the `Formatter` *is*
4492 // the value the proc returns, so it lowers to the string written.
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4493 "write_str" | "write_char" if self.is_fmt_param(&m.receiver) => {
4494 let a = args.first().ok_or("`write_str` takes one argument")?;
4495 // A `&str` argument is a character view, not a Nim string.
4496 let text = match &a.ty {
4497 Some(Nim::Prim(p)) if p == "string" => a.code.clone(),
4498 _ => format!("rsDisplay({})", a.code),
4499 };
4500 (format!("result.add({})", text), Some(Nim::Unit))
4501 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago4502 "saturating_add" | "saturating_sub" | "saturating_mul" | "checked_add"
4503 | "checked_sub" | "checked_mul" => {
4504 let t = rt
4505 .clone()
4506 .filter(|t| t.is_integer())
4507 .ok_or_else(|| format!("`{name}` needs a known integer receiver"))?;
4508 let arg = args
4509 .first()
4510 .ok_or_else(|| format!("`{name}` takes one argument"))?;
4511 let f = match name.as_str() {
4512 "saturating_add" => "rsSatAdd",
4513 "saturating_sub" => "rsSatSub",
4514 "saturating_mul" => "rsSatMul",
4515 "checked_add" => "rsChkAdd",
4516 "checked_sub" => "rsChkSub",
4517 _ => "rsChkMul",
4518 };
4519 let out = if name.starts_with("checked") {
4520 Nim::Named("Option".into(), vec![t])
4521 } else {
4522 t
4523 };
4524 (format!("{}({}, {})", f, recv.code, arg.code), Some(out))
4525 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4526 "abs" => (format!("abs({})", recv.code), rt.clone()),
4527 "min" => (format!("min({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
4528 "max" => (format!("max({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
4529 "to_string" => (format!("rsDisplay({})", recv.code), Some(Nim::Prim("string".into()))),
4530 "as_bytes" | "into_bytes" => (
4531 format!("rsBytes({})", recv.code),
4532 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
4533 ),
4534
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4535 "into" => {
4536 // `.into()` resolves through the `impl From` declarations, and
4537 // needs the target type to pick one.
4538 let from = rt
4539 .clone()
4540 .ok_or("`.into()` needs a known receiver type")?;
4541 let to = expect
4542 .ok_or("`.into()` needs a known target type; annotate the binding")?;
4543 let key = (type_name(&from), type_name(to));
4544 let f = self.from_impls.get(&key).cloned().ok_or_else(|| {
4545 format!(
4546 "no `impl From<{}> for {}` in this file, so `.into()` has \
4547 no conversion to call",
4548 key.0, key.1
4549 )
4550 })?;
4551 (format!("{}({})", f, recv.code), Some(to.clone()))
4552 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4553 _ => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4554 // A method defined in this file via `impl`, found by the
4555 // receiver's type rather than by name alone.
4556 let key = rt.as_ref().map(|t| (type_name(t), name.clone()));
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 15h ago4557 // Re-lower the arguments with the declared parameter types:
4558 // a method's own signature says what width its literals are,
4559 // which the receiver's type does not.
4560 let declared: Option<Vec<Nim>> = key
4561 .as_ref()
4562 .and_then(|k| self.methods.get(k))
4563 .map(|s| s.params.clone());
4564 if let Some(d) = &declared {
4565 // params[0] is the receiver for a method with `self`.
4566 let skip = usize::from(d.len() == m.args.len() + 1);
4567 for (i, a) in m.args.iter().enumerate() {
4568 if let Some(want) = d.get(i + skip) {
4569 let want = want.clone().unvar();
4570 args[i] = self.expr_at(a, Some(&want))?;
4571 }
4572 }
4573 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago4574 let mut arg_tys: Vec<Option<Nim>> = vec![recv.ty.clone()];
4575 arg_tys.extend(args.iter().map(|a| a.ty.clone()));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago4576 let sig = key
4577 .as_ref()
4578 .and_then(|k| self.methods.get(k))
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 15h ago4579 .map(|s| Self::instantiate(s, &arg_tys));
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4580 if let Some(ret) = sig {
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago4581 // Use the name the proc was actually emitted under: an
4582 // inherent method is qualified by its module, a trait
4583 // method by its trait.
4584 let nim = key
4585 .and_then(|k| self.statics.get(&k).cloned())
4586 .unwrap_or_else(|| ident(&name));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4587 let mut all = vec![recv.code.clone()];
4588 all.extend(args.iter().map(|a| a.code.clone()));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago4589 (format!("{}({})", nim, all.join(", ")), Some(ret))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4590 } else {
4591 return Err(format!(
4592 "unsupported method `.{name}()`; it is neither defined in \
4593 this file nor part of the standard-library subset that \
4594 has a verified Nim equivalent"
4595 ));
4596 }
4597 }
4598 };
4599 Ok(Val::new(code, ty))
4600 }
4601
4602 // -------------------------------------------------------------- macros
4603
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4604 /// The element type of a `vec![..]`, from its first element.
4605 fn vec_elem(&mut self, mac: &syn::Macro) -> Result<Option<Nim>, String> {
4606 let body = mac.tokens.to_string();
4607 if body.trim().is_empty() {
4608 return Ok(None);
4609 }
4610 let first: Option<Expr> = if body.contains(';') {
4611 // The whole body must be consumed or the parse fails, so the
4612 // length is parsed too even though only the element is wanted.
4613 mac.parse_body_with(|input: syn::parse::ParseStream| {
4614 let v: Expr = input.parse()?;
4615 input.parse::<syn::Token![;]>()?;
4616 let _len: Expr = input.parse()?;
4617 Ok(v)
4618 })
4619 .ok()
4620 } else {
4621 mac.parse_body_with(
4622 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
4623 )
4624 .ok()
4625 .and_then(|p| p.into_iter().next())
4626 };
4627 match first {
4628 Some(e) => Ok(self.expr(&e)?.ty),
4629 None => Ok(None),
4630 }
4631 }
4632
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4633 fn macro_call(&mut self, mac: &syn::Macro) -> Result<String, String> {
4634 let name = path_name(&mac.path);
4635 match name.as_str() {
4636 "println" | "print" | "eprintln" | "eprint" => {
4637 let s = self.format_args(mac)?;
4638 let nl = name.ends_with("ln");
4639 Ok(match (name.starts_with('e'), nl) {
4640 (false, true) => format!("echo {s}"),
4641 (false, false) => format!("stdout.write({s})"),
4642 (true, true) => format!("stderr.writeLine({s})"),
4643 (true, false) => format!("stderr.write({s})"),
4644 })
4645 }
4646 "format" => self.format_args(mac),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4647 "write" | "writeln" => {
4648 // `write!(f, "..", ..)` inside a formatting impl: the first
4649 // argument is the sink, the rest is an ordinary format call.
4650 let args: Vec<Expr> = mac
4651 .parse_body_with(syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated)
4652 .map_err(|e| format!("write!: {e}"))?
4653 .into_iter()
4654 .collect();
4655 let sink = args.first().ok_or("`write!` needs a sink")?;
4656 if !self.is_fmt_param(sink) {
4657 return Err("`write!` to anything but the `Formatter` of the \
4658 enclosing formatting impl is not implemented"
4659 .into());
4660 }
4661 let s = self.format_pieces(&args[1..])?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4662 let s = if name == "writeln" {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4663 format!("({} & \"\\n\")", s)
4664 } else {
4665 s
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4666 };
4667 Ok(format!("result.add({})", s))
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4668 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4669 "panic" => {
4670 let s = self.format_args(mac)?;
4671 Ok(format!("rsPanic({s})"))
4672 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4673 // `debug_assert*` fires in debug builds, which is the profile
4674 // this project models, so it lowers the same as `assert*`.
4675 "assert" | "debug_assert" => {
4676 let args: Vec<Expr> = mac
4677 .parse_body_with(
4678 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
4679 )
4680 .map_err(|e| format!("{name}!: {e}"))?
4681 .into_iter()
4682 .collect();
4683 let cond = args.first().ok_or("`assert!` needs a condition")?;
4684 let v = self.expr(cond)?;
4685 let msg = if args.len() > 1 {
4686 self.format_pieces(&args[1..])?
4687 } else {
4688 fmt::nim_str("assertion failed")
4689 };
4690 Ok(format!("(if not ({}): rsPanic({}))", v.code, msg))
4691 }
4692 "assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne" => {
4693 let args: Vec<Expr> = mac
4694 .parse_body_with(
4695 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
4696 )
4697 .map_err(|e| format!("{name}!: {e}"))?
4698 .into_iter()
4699 .collect();
4700 if args.len() < 2 {
4701 return Err(format!("`{name}!` takes two operands"));
4702 }
4703 let a = self.expr(&args[0])?;
4704 let b = self.expr_at(&args[1], a.ty.as_ref())?;
4705 let ne = name.ends_with("_ne");
4706 let op = if ne { "!=" } else { "==" };
4707 // Rust's message shows both sides; reproducing it keeps a
4708 // failing assertion as informative as the original.
4709 let label = if ne { "assertion failed: `(left != right)`" } else { "assertion failed: `(left == right)`" };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4710 Ok(format!(
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4711 "(if not (({}) {} ({})): rsPanic({} & \"\\n left: \" & rsDebug({}) & \"\\n right: \" & rsDebug({})))",
4712 a.code, op, b.code, fmt::nim_str(label), a.code, b.code
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4713 ))
4714 }
4715 "vec" => {
4716 let body = mac.tokens.to_string();
4717 if body.trim().is_empty() {
4718 return Ok("@[]".into());
4719 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago4720 // `vec![elem; n]` is the repeat form, not a list. The macro
4721 // body has no brackets, so it is parsed directly.
4722 if body.contains(';') {
4723 let (v, n) = mac
4724 .parse_body_with(|input: syn::parse::ParseStream| {
4725 let v: Expr = input.parse()?;
4726 input.parse::<syn::Token![;]>()?;
4727 let n: Expr = input.parse()?;
4728 Ok((v, n))
4729 })
4730 .map_err(|e| format!("vec![elem; n]: {e}"))?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4731 let want = self.vec_expect.clone();
4732 let v = self.expr_at(&v, want.as_ref())?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago4733 let n = self.expr(&n)?;
4734 return Ok(format!("newSeqWith(int({}), {})", n.code, v.code));
4735 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4736 let elems: syn::punctuated::Punctuated<Expr, syn::Token![,]> = mac
4737 .parse_body_with(syn::punctuated::Punctuated::parse_terminated)
4738 .map_err(|e| format!("vec!: {e}"))?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4739 let want = self.vec_expect.clone();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4740 let mut parts = Vec::new();
4741 for e in &elems {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4742 parts.push(self.expr_at(e, want.as_ref())?.code);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4743 }
4744 Ok(format!("@[{}]", parts.join(", ")))
4745 }
4746 other => Err(format!(
4747 "unsupported macro `{other}!`; a macro whose expansion is not \
4748 known cannot be lowered faithfully"
4749 )),
4750 }
4751 }
4752
4753 /// `println!("{} {}", a, b)` -> a Nim string-concatenation expression.
4754 fn format_args(&mut self, mac: &syn::Macro) -> Result<String, String> {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4755 let args: Vec<Expr> = mac
4756 .parse_body_with(syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated)
4757 .map_err(|e| format!("format arguments: {e}"))?
4758 .into_iter()
4759 .collect();
4760 self.format_pieces(&args)
4761 }
4762
4763 /// `["{} {}", a, b]` -> a Nim string-concatenation expression.
4764 fn format_pieces(&mut self, args: &[Expr]) -> Result<String, String> {
4765 let Some(Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. })) = args.first() else {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4766 if args.is_empty() {
4767 return Ok("\"\"".into());
4768 }
4769 return Err("the first argument must be a literal format string".into());
4770 };
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4771 let rest: Vec<&Expr> = args[1..].iter().collect();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4772
4773 let pieces = fmt::parse(&s.value())?;
4774 let mut parts: Vec<String> = Vec::new();
4775 let mut next = 0usize;
4776 let mut used = vec![false; rest.len()];
4777 for p in &pieces {
4778 match p {
4779 fmt::Piece::Lit(l) => parts.push(fmt::nim_str(l)),
4780 fmt::Piece::Arg { r#ref, spec } => {
4781 let v = match r#ref {
4782 fmt::Ref::Next => {
4783 let e = rest.get(next).ok_or("too few arguments for format string")?;
4784 used[next] = true;
4785 next += 1;
4786 self.expr(e)?
4787 }
4788 fmt::Ref::Index(i) => {
4789 let e = rest.get(*i).ok_or("format index out of range")?;
4790 used[*i] = true;
4791 self.expr(e)?
4792 }
4793 fmt::Ref::Named(n) => {
4794 let t = self.lookup(n).ok_or_else(|| {
4795 format!("`{{{n}}}` captures `{n}`, which is not in scope")
4796 })?;
4797 Val::new(ident(n), Some(t))
4798 }
4799 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago4800 let integer = v.ty.as_ref().is_some_and(|t| t.is_integer());
4801 if spec.radix.is_some() && !integer && v.ty.is_none() {
4802 return Err(
4803 "a radix format (`{:x}`, `{:b}`, ...) needs a known \
4804 argument type: on an integer it formats the bit \
4805 pattern, on anything else it calls that type's own \
4806 impl"
4807 .into(),
4808 );
4809 }
4810 parts.push(fmt::render_arg(&v.code, spec, integer));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4811 }
4812 }
4813 }
4814 // Rust rejects an argument that no `{}` consumes; so do we, rather
4815 // than dropping it from the output.
4816 if let Some(i) = used.iter().position(|u| !u) {
4817 return Err(format!(
4818 "argument {} is never used by the format string",
4819 i + 1
4820 ));
4821 }
4822 Ok(if parts.is_empty() { "\"\"".into() } else { parts.join(" & ") })
4823 }
4824}
4825
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago4826/// Whether a pattern introduces a binding.
4827fn binds(p: &Pat) -> bool {
4828 match p {
4829 Pat::Ident(_) => true,
4830 Pat::Guard(g) => binds(&g.pat),
4831 Pat::Paren(x) => binds(&x.pat),
4832 Pat::Reference(r) => binds(&r.pat),
4833 Pat::Or(o) => o.cases.iter().any(binds),
4834 Pat::TupleStruct(t) => t.elems.iter().any(|_| true),
4835 Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_) => true,
4836 _ => false,
4837 }
4838}
4839
4840/// Whether a pattern looks inside the value, which a Nim `case` cannot do.
4841fn destructures(p: &Pat) -> bool {
4842 matches!(
4843 p,
4844 Pat::TupleStruct(_) | Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_)
4845 ) || matches!(p, Pat::Guard(g) if destructures(&g.pat))
4846 || matches!(p, Pat::Paren(x) if destructures(&x.pat))
4847 || matches!(p, Pat::Reference(r) if destructures(&r.pat))
4848}
4849
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4850/// Whether an expression has a direct Nim expression form.
4851///
4852/// Nim's `if` is an expression only when every arm is a single expression, and
4853/// its `case` is never one here. Anything else has to be lowered as statements
4854/// that assign into a target.
4855fn expressible(e: &Expr) -> bool {
4856 match e {
4857 Expr::If(i) => {
4858 let Some(then) = single_expr(&i.then_branch) else { return false };
4859 if !expressible(then) {
4860 return false;
4861 }
4862 match &i.else_branch {
4863 None => false,
4864 Some((_, els)) => match &**els {
4865 Expr::Block(b) => single_expr(&b.block).is_some_and(expressible),
4866 other => expressible(other),
4867 },
4868 }
4869 }
4870 Expr::Match(_) | Expr::Block(_) | Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => false,
4871 _ => true,
4872 }
4873}
4874
4875/// The single expression a block consists of, if that is all it is. An `if`
4876/// can only be lowered as a Nim `if`-expression when both arms are this shape.
4877fn single_expr(b: &syn::Block) -> Option<&Expr> {
4878 match (b.stmts.len(), b.stmts.first()) {
4879 (1, Some(Stmt::Expr(e, None))) => Some(e),
4880 _ => None,
4881 }
4882}
4883
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago4884/// Substitute `params[i] -> args[i]` through a type. Enough of the type
4885/// grammar is covered to expand the aliases we accept; anything else is left
4886/// alone and will be reported by `ty::map` if it is unsupported.
4887fn substitute(t: &syn::Type, params: &[String], args: &[syn::Type]) -> syn::Type {
4888 use syn::Type;
4889 match t {
4890 Type::Path(p) => {
4891 if p.qself.is_none() && p.path.segments.len() == 1 {
4892 let seg = &p.path.segments[0];
4893 if seg.arguments.is_empty() {
4894 let name = seg.ident.to_string();
4895 if let Some(i) = params.iter().position(|x| *x == name) {
4896 return args[i].clone();
4897 }
4898 }
4899 }
4900 let mut p = p.clone();
4901 for seg in &mut p.path.segments {
4902 if let syn::PathArguments::AngleBracketed(a) = &mut seg.arguments {
4903 for g in &mut a.args {
4904 if let syn::GenericArgument::Type(t) = g {
4905 *t = substitute(t, params, args);
4906 }
4907 }
4908 }
4909 }
4910 Type::Path(p)
4911 }
4912 Type::Reference(r) => {
4913 let mut r = r.clone();
4914 r.elem = Box::new(substitute(&r.elem, params, args));
4915 Type::Reference(r)
4916 }
4917 Type::Slice(sl) => {
4918 let mut sl = sl.clone();
4919 sl.elem = Box::new(substitute(&sl.elem, params, args));
4920 Type::Slice(sl)
4921 }
4922 Type::Array(a) => {
4923 let mut a = a.clone();
4924 a.elem = Box::new(substitute(&a.elem, params, args));
4925 Type::Array(a)
4926 }
4927 Type::Tuple(tp) => {
4928 let mut tp = tp.clone();
4929 tp.elems = tp.elems.iter().map(|e| substitute(e, params, args)).collect();
4930 Type::Tuple(tp)
4931 }
4932 Type::Paren(p) => substitute(&p.elem, params, args),
4933 Type::Group(g) => substitute(&g.elem, params, args),
4934 other => other.clone(),
4935 }
4936}
4937
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago4938// --------------------------------------------------------------- utilities
4939
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4940/// Whether a return type is a borrow of one of the arguments, which Nim
4941/// models with a view rather than with an owned copy.
4942fn returns_borrow(t: &syn::Type) -> bool {
4943 match t {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4944 syn::Type::Reference(r) => match &*r.elem {
4945 syn::Type::Slice(_) => true,
4946 // `&str` is a borrow of someone else's bytes too, and returning it
4947 // means returning a view, not an owned string.
4948 syn::Type::Path(p) => p.path.is_ident("str"),
4949 _ => false,
4950 },
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4951 syn::Type::Paren(p) => returns_borrow(&p.elem),
4952 syn::Type::Group(g) => returns_borrow(&g.elem),
4953 _ => false,
4954 }
4955}
4956
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 17h ago4957/// The module a `use` prefix names. `crate`, `self` and `super` all resolve
4958/// to the crate root, which is where a flattened module's items live unless
4959/// they came from one of the extra input files.
4960fn module_of(prefix: &[String]) -> String {
4961 match prefix.last() {
4962 Some(m) if m != "crate" && m != "self" && m != "super" => m.clone(),
4963 _ => String::new(),
4964 }
4965}
4966
4967/// The first type argument of an `Option[T]` / `Result[T, E]`.
4968fn elem_arg(t: &Nim) -> Nim {
4969 match t {
4970 Nim::Named(_, a) if !a.is_empty() => a[0].clone(),
4971 other => other.clone(),
4972 }
4973}
4974
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago4975/// The element type of a sequence-like Nim type.
4976fn elem_of(t: &Option<Nim>) -> Option<Nim> {
4977 match t {
4978 Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) | Some(Nim::Array(_, e)) => Some((**e).clone()),
4979 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
4980 _ => None,
4981 }
4982}
4983
4984/// The short name a Nim type is known by, for keying method tables.
4985fn type_name(t: &Nim) -> String {
4986 match t {
4987 Nim::Named(n, _) => n.clone(),
4988 Nim::Prim(p) => p.clone(),
4989 other => other.render(),
4990 }
4991}
4992
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago4993/// `(trait, operator)` for every operator trait we dispatch.
4994const OPERATOR_TRAITS: &[(&str, &str)] = &[
4995 ("Add", "+"), ("Sub", "-"), ("Mul", "*"), ("Div", "/"), ("Rem", "%"),
4996 ("BitAnd", "&"), ("BitOr", "|"), ("BitXor", "^"), ("Shl", "<<"), ("Shr", ">>"),
4997 ("AddAssign", "+="), ("SubAssign", "-="), ("MulAssign", "*="), ("DivAssign", "/="),
4998 ("RemAssign", "%="), ("BitAndAssign", "&="), ("BitOrAssign", "|="),
4999 ("BitXorAssign", "^="), ("ShlAssign", "<<="), ("ShrAssign", ">>="),
5000 ("Neg", "neg"), ("Not", "not"),
5001];
5002
5003/// `(operator, trait method name)`.
5004const OP_METHOD: &[(&str, &str)] = &[
5005 ("+", "add"), ("-", "sub"), ("*", "mul"), ("/", "div"), ("%", "rem"),
5006 ("&", "bitand"), ("|", "bitor"), ("^", "bitxor"), ("<<", "shl"), (">>", "shr"),
5007 ("+=", "add_assign"), ("-=", "sub_assign"), ("*=", "mul_assign"),
5008 ("/=", "div_assign"), ("%=", "rem_assign"), ("&=", "bitand_assign"),
5009 ("|=", "bitor_assign"), ("^=", "bitxor_assign"), ("<<=", "shl_assign"),
5010 (">>=", "shr_assign"), ("neg", "neg"), ("not", "not"),
5011];
5012
5013fn op_method(op: &str) -> &'static str {
5014 OP_METHOD.iter().find(|(o, _)| *o == op).map(|(_, m)| *m).unwrap_or("")
5015}
5016
5017/// The operator symbol a compound assignment applies.
5018fn compound_symbol(op: &BinOp) -> &'static str {
5019 match op {
5020 BinOp::AddAssign(_) => "+=",
5021 BinOp::SubAssign(_) => "-=",
5022 BinOp::MulAssign(_) => "*=",
5023 BinOp::DivAssign(_) => "/=",
5024 BinOp::RemAssign(_) => "%=",
5025 BinOp::BitAndAssign(_) => "&=",
5026 BinOp::BitOrAssign(_) => "|=",
5027 BinOp::BitXorAssign(_) => "^=",
5028 BinOp::ShlAssign(_) => "<<=",
5029 BinOp::ShrAssign(_) => ">>=",
5030 _ => "",
5031 }
5032}
5033
5034fn binary_symbol(op: &BinOp) -> &'static str {
5035 match op {
5036 BinOp::Add(_) => "+",
5037 BinOp::Sub(_) => "-",
5038 BinOp::Mul(_) => "*",
5039 BinOp::Div(_) => "/",
5040 BinOp::Rem(_) => "%",
5041 BinOp::BitAnd(_) => "&",
5042 BinOp::BitOr(_) => "|",
5043 BinOp::BitXor(_) => "^",
5044 BinOp::Shl(_) => "<<",
5045 BinOp::Shr(_) => ">>",
5046 _ => "",
5047 }
5048}
5049
5050/// The operator a trait overloads, if it is one of the operator traits.
5051fn operator_trait(t: &str) -> Option<&'static str> {
5052 Some(match t {
5053 "Add" => "+",
5054 "Sub" => "-",
5055 "Mul" => "*",
5056 "Div" => "/",
5057 "Rem" => "%",
5058 "BitAnd" => "&",
5059 "BitOr" => "|",
5060 "BitXor" => "^",
5061 "Shl" => "<<",
5062 "Shr" => ">>",
5063 "AddAssign" => "+=",
5064 "SubAssign" => "-=",
5065 "MulAssign" => "*=",
5066 "DivAssign" => "/=",
5067 "RemAssign" => "%=",
5068 "BitAndAssign" => "&=",
5069 "BitOrAssign" => "|=",
5070 "BitXorAssign" => "^=",
5071 "ShlAssign" => "<<=",
5072 "ShrAssign" => ">>=",
5073 "Neg" => "neg",
5074 "Not" => "not",
5075 _ => return None,
5076 })
5077}
5078
5079/// The Nim proc name for a trait method, qualified by trait and type so that
5080/// two traits declaring the same method name cannot collide.
5081fn trait_method_name(ty: &str, tr: &str, m: &str) -> String {
5082 format!("rs{}_{}_{}", tr, ty, m)
5083}
5084
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago5085fn is_fmt_trait(t: &str) -> bool {
5086 matches!(t, "Display" | "Debug" | "LowerHex" | "UpperHex" | "Binary" | "Octal")
5087}
5088
5089/// The prelude proc a formatting trait's output is produced by.
5090fn fmt_proc(t: &str) -> &'static str {
5091 match t {
5092 "Display" => "rsDisplay",
5093 "Debug" => "rsDebug",
5094 "LowerHex" => "rsLowerHex",
5095 "UpperHex" => "rsUpperHex",
5096 "Binary" => "rsBinary",
5097 _ => "rsOctal",
5098 }
5099}
5100
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 16h ago5101/// Whether an expression is an iterator-producing chain rather than a value.
5102fn is_iterator_expr(e: &Expr) -> bool {
5103 match e {
5104 Expr::MethodCall(m) => matches!(
5105 m.method.to_string().as_str(),
5106 "iter" | "iter_mut" | "into_iter" | "enumerate" | "zip" | "chunks_exact"
5107 | "chunks_exact_mut" | "windows"
5108 ),
5109 Expr::Paren(p) => is_iterator_expr(&p.expr),
5110 _ => false,
5111 }
5112}
5113
Prove byte-identity for base16ct by enumerating whole input domains 99b8376 nandithebull 16h ago5114/// Whether an expression denotes a place -- a variable, a field, or an index
5115/// or slice of one -- and so may be re-evaluated with no side effect.
5116fn is_pure_place(e: &Expr) -> bool {
5117 match e {
5118 Expr::Path(_) => true,
5119 Expr::Field(f) => is_pure_place(&f.base),
5120 Expr::Index(i) => {
5121 is_pure_place(&i.expr)
5122 && match &*i.index {
5123 Expr::Range(r) => {
5124 r.start.as_deref().map_or(true, is_pure_place)
5125 && r.end.as_deref().map_or(true, is_pure_place)
5126 }
5127 other => is_pure_place(other),
5128 }
5129 }
5130 Expr::Lit(_) => true,
5131 Expr::Reference(r) => is_pure_place(&r.expr),
5132 Expr::Paren(p) => is_pure_place(&p.expr),
5133 Expr::Group(g) => is_pure_place(&g.expr),
5134 // Arithmetic on places is still side-effect free, so a bound like
5135 // `..want - 1` does not stop the binding being an alias.
5136 Expr::Binary(b) if !is_compound(&b.op) => {
5137 is_pure_place(&b.left) && is_pure_place(&b.right)
5138 }
5139 Expr::Unary(u) => is_pure_place(&u.expr),
5140 Expr::Cast(c) => is_pure_place(&c.expr),
5141 _ => false,
5142 }
5143}
5144
5145/// Whether an expression is a `&mut` borrow, directly or through parens.
5146fn is_mut_borrow(e: &Expr) -> bool {
5147 match e {
5148 Expr::Reference(r) => r.mutability.is_some(),
5149 Expr::Paren(p) => is_mut_borrow(&p.expr),
5150 Expr::Group(g) => is_mut_borrow(&g.expr),
5151 _ => false,
5152 }
5153}
5154
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago5155fn takes_self(sig: &syn::Signature) -> bool {
5156 matches!(sig.inputs.first(), Some(FnArg::Receiver(_)))
5157}
5158
5159fn path_name(p: &syn::Path) -> String {
5160 p.segments
5161 .last()
5162 .map(|s| s.ident.to_string())
5163 .unwrap_or_default()
5164}
5165
5166fn is_compound(op: &BinOp) -> bool {
5167 matches!(
5168 op,
5169 BinOp::AddAssign(_)
5170 | BinOp::SubAssign(_)
5171 | BinOp::MulAssign(_)
5172 | BinOp::DivAssign(_)
5173 | BinOp::RemAssign(_)
5174 | BinOp::BitAndAssign(_)
5175 | BinOp::BitOrAssign(_)
5176 | BinOp::BitXorAssign(_)
5177 | BinOp::ShlAssign(_)
5178 | BinOp::ShrAssign(_)
5179 )
5180}
5181
5182/// The Nim literal suffix for an integer type (`5'i32`).
5183fn nim_suffix(t: &Nim) -> Result<&'static str, String> {
5184 let Nim::Prim(p) = t else {
5185 return Err("not a primitive integer".into());
5186 };
5187 Ok(match p.as_str() {
5188 "int8" => "i8",
5189 "int16" => "i16",
5190 "int32" => "i32",
5191 "int64" => "i64",
5192 "int" => "i",
5193 "uint8" => "u8",
5194 "uint16" => "u16",
5195 "uint32" => "u32",
5196 "uint64" => "u64",
5197 "uint" => "u",
5198 other => return Err(format!("no Nim literal suffix for `{other}`")),
5199 })
5200}
5201
5202/// The unsigned integer type of the same width, used to spell `wrapping_*`.
5203fn unsigned_peer(t: &Nim) -> Result<&'static str, String> {
5204 let Nim::Prim(p) = t else {
5205 return Err("not a primitive integer".into());
5206 };
5207 Ok(match p.as_str() {
5208 "int8" => "uint8",
5209 "int16" => "uint16",
5210 "int32" => "uint32",
5211 "int64" => "uint64",
5212 "int" => "uint",
5213 other => return Err(format!("`{other}` has no unsigned peer")),
5214 })
5215}
5216
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 18h ago5217fn quote_meta(m: &syn::Meta) -> String {
5218 match m {
5219 syn::Meta::Path(p) => path_name(p),
5220 syn::Meta::List(l) => format!("{}(..)", path_name(&l.path)),
5221 syn::Meta::NameValue(nv) => format!("{} = ..", path_name(&nv.path)),
5222 }
5223}
5224
5225fn item_attrs(i: &Item) -> &[syn::Attribute] {
5226 match i {
5227 Item::Fn(f) => &f.attrs,
5228 Item::Struct(s) => &s.attrs,
5229 Item::Enum(e) => &e.attrs,
5230 Item::Impl(x) => &x.attrs,
5231 Item::Const(c) => &c.attrs,
5232 Item::Type(t) => &t.attrs,
5233 Item::Mod(m) => &m.attrs,
5234 Item::Use(u) => &u.attrs,
5235 Item::ExternCrate(e) => &e.attrs,
5236 Item::Static(s) => &s.attrs,
5237 _ => &[],
5238 }
5239}
5240
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 18h ago5241fn item_kind(i: &Item) -> &'static str {
5242 match i {
5243 Item::Trait(_) => "`trait`",
5244 Item::Static(_) => "`static`",
5245 Item::Macro(_) => "macro definition",
5246 Item::Union(_) => "`union`",
5247 Item::ForeignMod(_) => "`extern` block",
5248 _ => "item",
5249 }
5250}
5251
5252fn expr_kind(e: &Expr) -> &'static str {
5253 match e {
5254 Expr::Async(_) => "`async` block",
5255 Expr::Await(_) => "`.await`",
5256 Expr::Try(_) => "`?`",
5257 Expr::Range(_) => "range",
5258 Expr::Match(_) => "`match` (only statement position is implemented)",
5259 Expr::Let(_) => "`let` expression",
5260 Expr::Unsafe(_) => "`unsafe` block",
5261 Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => "loop (has no value in Nim)",
5262 _ => "expression",
5263 }
5264}