nandi/rustnimpublic Fork 0
0a375d8ec0bfffe1baadd340864ab1ffa92fdb98
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 · 3788 lines · 154.5 KBRust Blame HistoryRaw
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h 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 19h 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 19h 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 18h 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 18h 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 18h 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 18h 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 18h 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 18h 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 18h 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 19h ago103 }
104}
105
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h 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> },
113}
114
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago115/// A lowered expression: its Nim text, and its type where we know it.
116///
117/// The type is not decoration. Nim needs it to pick `div` over `/`, to size a
118/// `cast`, and to annotate every binding so that Nim's own type checker
119/// catches a mistake in this file rather than letting it through as output
120/// that runs and is wrong.
121#[derive(Clone, Debug)]
122struct Val {
123 code: String,
124 ty: Option<Nim>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago125 /// Set when the value *is* a slice view rather than a Nim value: binding
126 /// it introduces an alias, not a copy.
127 window: Option<Alias>,
128 /// For `get`/`get_mut`: the condition under which the `Option` is `Some`,
129 /// carried until an `ok_or`/`?` or an `unwrap` consumes it. Nim's view
130 /// types cannot live inside an object, so an `Option` of a view has no
131 /// runtime representation -- it is tracked here instead.
132 guard: Option<String>,
133 /// The error an `ok_or` attached to that guard.
134 guard_err: Option<String>,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago135}
136
137impl Val {
138 fn new(code: impl Into<String>, ty: Option<Nim>) -> Self {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago139 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 19h ago140 }
141 fn untyped(code: impl Into<String>) -> Self {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago142 Val::new(code, None)
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago143 }
144}
145
146struct Sig {
147 params: Vec<Nim>,
148 ret: Nim,
149}
150
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago151/// One variant of a Rust enum.
152#[derive(Clone)]
153struct Variant {
154 name: String,
155 /// `(nim field name, type)`. Empty for a unit variant. Tuple variants get
156 /// `f0`, `f1`, ...; every field is prefixed with the variant name because
157 /// Nim requires the branches of a variant object to have distinct fields.
158 fields: Vec<(String, Nim)>,
159}
160
161#[derive(Clone)]
162struct EnumDef {
163 name: String,
164 /// True when every variant is a unit variant, which Nim represents as a
165 /// plain `enum` rather than an object variant.
166 simple: bool,
167 variants: Vec<Variant>,
168}
169
170impl EnumDef {
171 fn kind_ident(&self, v: &str) -> String {
172 format!("k{}{}", self.name, v)
173 }
174 fn ctor_ident(&self, v: &str) -> String {
175 format!("{}{}", self.name, v)
176 }
177 fn get(&self, v: &str) -> Option<&Variant> {
178 self.variants.iter().find(|x| x.name == v)
179 }
180}
181
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago182pub struct Lowerer {
183 out: String,
184 indent: usize,
185 scopes: Vec<HashMap<String, Nim>>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago186 /// Names introduced by a `for` pattern that stand for an lvalue or a
187 /// window into a container, rather than for a variable of their own.
188 alias_scopes: Vec<HashMap<String, Alias>>,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago189 /// `(module, name) -> signature`. Rust keeps `lower::decode` and
190 /// `mixed::decode` apart by module; flattening into one Nim module would
191 /// merge them, so the module is part of the key and of the emitted name.
192 fns: HashMap<(String, String), Sig>,
193 /// Module being lowered: the file stem, or empty for the crate root.
194 cur_mod: String,
195 /// `use` brings a name into scope from another module. Flattening loses
196 /// the module structure, so the mapping is recorded and consulted when a
197 /// bare call is resolved.
198 use_map: HashMap<String, String>,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago199 /// struct name -> (field, type)
200 structs: HashMap<String, Vec<(String, Nim)>>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago201 enums: HashMap<String, EnumDef>,
202 /// variant name -> enums declaring it. A variant named by more than one
203 /// enum must be written qualified, or it is rejected as ambiguous.
204 variant_owner: HashMap<String, Vec<String>>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago205 /// `(receiver type, method) -> signature`. Keyed by type because two
206 /// types may define the same method name, and Nim tells them apart by
207 /// overload resolution on the first parameter.
208 methods: HashMap<(String, String), Sig>,
209 /// The formatting traits implemented for each type, so `{}`/`{:?}`/`{:x}`
210 /// on a user type can be checked rather than assumed.
211 fmt_impls: HashMap<(String, String), ()>,
212 /// `(from, to)` conversions declared by `impl From<A> for B`.
213 from_impls: HashMap<(String, String), String>,
214 /// Forward declarations, emitted between the type definitions and the
215 /// bodies. Rust has no declaration-before-use rule and Nim does, so every
216 /// proc is declared up front rather than the input being reordered --
217 /// which would not work for mutual recursion anyway.
218 forwards: Vec<String>,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago219 /// Element type a `vec![..]` should build, from the binding's annotation.
220 vec_expect: Option<Nim>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago221 /// While lowering a formatting impl: the `Formatter` parameter's name.
222 /// Writes through it produce the proc's string result.
223 fmt_param: Option<String>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago224 /// `type X<T> = ...`, expanded before any type is mapped.
225 aliases: HashMap<String, (Vec<String>, syn::Type)>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago226 /// Module names supplied as separate input files. A `mod x;` naming one
227 /// of these is satisfied by that file having been passed in.
228 pub modules: Vec<String>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago229 /// Cargo features that are on, as `--cfg feature=<name>`. `#[cfg]` is
230 /// evaluated against these exactly as rustc would, so an item that is
231 /// dropped here is genuinely not part of the program being compiled.
232 pub features: Vec<String>,
233 dropped_by_cfg: usize,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago234 /// Return type of the proc being lowered, so `return e` and a trailing
235 /// expression can type their literals the way Rust's inference would.
236 ret: Option<Nim>,
237 /// `(name, type)` that the arms of the `if`/`match` being lowered as a
238 /// statement must assign their value to.
239 target: Option<(String, Option<Nim>)>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago240 /// Set while lowering a `while` condition, which Nim re-evaluates each
241 /// iteration and so cannot have statements hoisted out of it.
242 in_loop_cond: bool,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago243 tmp: usize,
244}
245
246impl Lowerer {
247 pub fn new() -> Self {
248 Lowerer {
249 out: String::new(),
250 indent: 0,
251 scopes: vec![HashMap::new()],
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago252 alias_scopes: vec![HashMap::new()],
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago253 fns: HashMap::new(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago254 cur_mod: String::new(),
255 use_map: HashMap::new(),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago256 structs: HashMap::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago257 enums: HashMap::new(),
258 variant_owner: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago259 methods: HashMap::new(),
260 fmt_impls: HashMap::new(),
261 from_impls: HashMap::new(),
262 fmt_param: None,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago263 vec_expect: None,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago264 forwards: Vec::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago265 aliases: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago266 modules: Vec::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago267 features: Vec::new(),
268 dropped_by_cfg: 0,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago269 ret: None,
270 target: None,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago271 in_loop_cond: false,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago272 tmp: 0,
273 }
274 }
275
276 // ------------------------------------------------------------ emission
277
278 fn line(&mut self, s: &str) {
279 for _ in 0..self.indent {
280 self.out.push_str(" ");
281 }
282 self.out.push_str(s);
283 self.out.push('\n');
284 }
285
286 fn blank(&mut self) {
287 self.out.push('\n');
288 }
289
290 fn fresh(&mut self, hint: &str) -> String {
291 self.tmp += 1;
292 format!("rsTmp{}{}", hint, self.tmp)
293 }
294
295 // --------------------------------------------------------------- scope
296
297 fn push_scope(&mut self) {
298 self.scopes.push(HashMap::new());
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago299 self.alias_scopes.push(HashMap::new());
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago300 }
301 fn pop_scope(&mut self) {
302 self.scopes.pop();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago303 self.alias_scopes.pop();
304 }
305 fn bind_alias(&mut self, name: &str, a: Alias) {
306 self.alias_scopes
307 .last_mut()
308 .unwrap()
309 .insert(name.to_string(), a);
310 }
311 fn lookup_alias(&self, name: &str) -> Option<Alias> {
312 self.alias_scopes
313 .iter()
314 .rev()
315 .find_map(|s| s.get(name).cloned())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago316 }
317 fn bind(&mut self, name: &str, t: Nim) {
318 self.scopes.last_mut().unwrap().insert(name.to_string(), t);
319 }
320 fn lookup(&self, name: &str) -> Option<Nim> {
321 self.scopes.iter().rev().find_map(|s| s.get(name).cloned())
322 }
323
324 // ---------------------------------------------------------------- file
325
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago326 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 19h ago327 self.out.push_str(include_str!("prelude.nim"));
328 self.blank();
329
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago330 // Pass 0: type aliases. A signature in one file may use an alias
331 // declared in another, and inputs are given in whatever order suits
332 // 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 18h ago333 for (m, f) in files {
334 self.cur_mod = m.clone();
335 for item in &f.items {
336 self.collect_aliases(item)?;
337 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago338 }
339
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago340 // Pass 1: signatures and struct shapes, so that a call can be typed
341 // regardless of declaration order (Rust has no forward declarations).
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago342 for (m, f) in files {
343 self.cur_mod = m.clone();
344 for item in &f.items {
345 self.collect(item)?;
346 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago347 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago348 // Pass 2: type definitions, which every signature may mention.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago349 for (m, f) in files {
350 self.cur_mod = m.clone();
351 for item in &f.items {
352 self.item_types(item)?;
353 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago354 }
355
356 // Pass 3: forward declarations. Rust imposes no declaration order and
357 // Nim does, so everything is declared before any body is emitted;
358 // reordering the input would not handle mutual recursion anyway.
359 if !self.forwards.is_empty() {
360 for f in self.forwards.clone() {
361 self.line(&f);
362 }
363 self.blank();
364 }
365
366 // Pass 4: bodies.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago367 for (m, f) in files {
368 self.cur_mod = m.clone();
369 for item in &f.items {
370 self.item(item)?;
371 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago372 }
373
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago374 if self.fns.contains_key(&(String::new(), "main".to_string())) {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago375 self.blank();
376 self.line("when isMainModule:");
377 self.indent += 1;
378 self.line("try:");
379 self.line(" main()");
380 // Rust's panic exits 101 with a message on stderr. Nim's Defects
381 // exit 1. Mapping them here is what keeps the differential runner's
382 // exit-status comparison meaningful for panicking programs.
383 self.line("except RustPanic as e:");
384 self.line(" stderr.writeLine(\"thread 'main' panicked: \" & e.msg)");
385 self.line(" quit(101)");
386 self.line("except Defect as e:");
387 self.line(" stderr.writeLine(\"thread 'main' panicked: \" & e.msg)");
388 self.line(" quit(101)");
389 self.indent -= 1;
390 }
391 Ok(std::mem::take(&mut self.out))
392 }
393
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago394 fn collect_aliases(&mut self, item: &Item) -> Result<(), String> {
395 if !self.cfg_keeps(item_attrs(item))? {
396 return Ok(());
397 }
398 match item {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago399 Item::Use(u) => self.collect_use(&u.tree, &[]),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago400 Item::Type(t) => {
401 let params: Vec<String> = t
402 .generics
403 .params
404 .iter()
405 .filter_map(|g| match g {
406 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
407 _ => None,
408 })
409 .collect();
410 self.aliases
411 .insert(t.ident.to_string(), (params, (*t.ty).clone()));
412 }
413 Item::Mod(m) if m.content.is_some() => {
414 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
415 for i in &items {
416 self.collect_aliases(i)?;
417 }
418 }
419 _ => {}
420 }
421 Ok(())
422 }
423
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago424 /// Record what a `use` brings into scope, as `name -> module`.
425 fn collect_use(&mut self, t: &syn::UseTree, prefix: &[String]) {
426 use syn::UseTree;
427 match t {
428 UseTree::Path(p) => {
429 let mut pre = prefix.to_vec();
430 pre.push(p.ident.to_string());
431 self.collect_use(&p.tree, &pre);
432 }
433 UseTree::Group(g) => {
434 for t in &g.items {
435 self.collect_use(t, prefix);
436 }
437 }
438 UseTree::Name(n) => {
439 let m = module_of(prefix);
440 self.use_map.insert(n.ident.to_string(), m);
441 }
442 UseTree::Rename(r) => {
443 let m = module_of(prefix);
444 self.use_map.insert(r.rename.to_string(), m);
445 }
446 // A glob brings in an unknown set of names; resolution falls back
447 // to the current module and the root, as it would without it.
448 UseTree::Glob(_) => {}
449 }
450 }
451
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago452 fn collect(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago453 // A `#[cfg(..)]` item exists only under some feature set. Dropping it
454 // silently would change what the program does; picking a feature set
455 // on the user's behalf would be a guess. So it is reported, except on
456 // items that carry no runtime meaning here anyway.
457 if !self.cfg_keeps(item_attrs(item))? {
458 self.dropped_by_cfg += 1;
459 return Ok(());
460 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago461 match item {
462 Item::Fn(f) => {
463 let (params, ret) = self.signature(&f.sig)?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago464 let name = f.sig.ident.to_string();
465 let nim = self.fn_name(&self.cur_mod, &name);
466 self.forwards.push(self.head_of(&nim, &f.sig, None)?);
467 self.fns
468 .insert((self.cur_mod.clone(), name), Sig { params, ret });
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago469 }
470 Item::Struct(s) => {
471 let mut fields = Vec::new();
472 for (i, f) in s.fields.iter().enumerate() {
473 let name = match &f.ident {
474 Some(id) => id.to_string(),
475 None => format!("f{i}"), // tuple struct
476 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago477 fields.push((name, self.map_ty(&f.ty)?.owned()));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago478 }
479 self.structs.insert(s.ident.to_string(), fields);
480 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago481 Item::Mod(m) if m.content.is_some() => {
482 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
483 for i in &items {
484 self.collect(i)?;
485 }
486 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago487 Item::Type(t) => {
488 let params: Vec<String> = t
489 .generics
490 .params
491 .iter()
492 .filter_map(|g| match g {
493 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
494 _ => None,
495 })
496 .collect();
497 self.aliases
498 .insert(t.ident.to_string(), (params, (*t.ty).clone()));
499 }
500 Item::Enum(e) => {
501 let name = e.ident.to_string();
502 if e.generics.params.iter().any(|p| !matches!(p, syn::GenericParam::Lifetime(_))) {
503 return Err(format!("`enum {name}` is generic: not implemented yet"));
504 }
505 let mut variants = Vec::new();
506 for v in &e.variants {
507 let vname = v.ident.to_string();
508 if v.discriminant.is_some() {
509 return Err(format!(
510 "`{name}::{vname}` has an explicit discriminant; Rust's \
511 `as` on such an enum has a value this lowering does not \
512 yet preserve"
513 ));
514 }
515 let mut fields = Vec::new();
516 for (i, f) in v.fields.iter().enumerate() {
517 // Nim requires the branches of a variant object to have
518 // distinct field names, so each is prefixed.
519 let fname = match &f.ident {
520 Some(id) => format!("{vname}_{id}"),
521 None => format!("{vname}_f{i}"),
522 };
523 fields.push((fname, self.map_ty(&f.ty)?.owned()));
524 }
525 variants.push(Variant { name: vname, fields });
526 }
527 let simple = variants.iter().all(|v| v.fields.is_empty());
528 for v in &variants {
529 self.variant_owner
530 .entry(v.name.clone())
531 .or_default()
532 .push(name.clone());
533 }
534 self.enums.insert(
535 name.clone(),
536 EnumDef { name, simple, variants },
537 );
538 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago539 Item::Impl(im) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago540 let self_ty = self.map_ty(&im.self_ty)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago541 let tyname = type_name(&self_ty);
542 if let Some((path, _)) = &im.trait_ {
543 let tr = path_name(path);
544 if im.items.is_empty() {
545 // A marker trait with no items. We do not model trait
546 // resolution at all, so it generates nothing; any use
547 // that actually needed the trait (a `dyn`, a bound) is
548 // rejected where it appears.
549 return Ok(());
550 }
551 if is_fmt_trait(&tr) {
552 self.forwards.push(format!(
553 "proc {}*(self: {}): string",
554 fmt_proc(&tr),
555 self_ty.render()
556 ));
557 self.fmt_impls.insert((tyname, tr), ());
558 return Ok(());
559 }
560 if tr == "From" {
561 let syn::ImplItem::Fn(m) = &im.items[0] else {
562 return Err("`impl From` must contain `fn from`".into());
563 };
564 let (params, _) = self.signature(&m.sig)?;
565 let src = params
566 .first()
567 .ok_or("`fn from` takes one argument")?
568 .clone();
569 let name = format!("rsFrom{}{}", tyname, type_name(&src));
570 self.forwards.push(self.head_of(&name, &m.sig, None)?);
571 self.from_impls
572 .insert((type_name(&src), tyname), name);
573 return Ok(());
574 }
575 return Err(format!(
576 "`impl {tr} for {tyname}`: only formatting traits \
577 (Display, Debug, LowerHex, UpperHex, Binary, Octal), \
578 `From`, and marker traits with no items are implemented"
579 ));
580 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago581 for it in &im.items {
582 if let syn::ImplItem::Fn(m) = it {
583 let (mut params, ret) = self.signature(&m.sig)?;
584 if takes_self(&m.sig) {
585 params.insert(0, self_ty.clone());
586 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago587 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
588 let head = self.head_of(&m.sig.ident.to_string(), &m.sig, recv.as_ref())?;
589 self.forwards.push(head);
590 self.methods
591 .insert((tyname.clone(), m.sig.ident.to_string()), Sig { params, ret });
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago592 }
593 }
594 }
595 _ => {}
596 }
597 Ok(())
598 }
599
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago600 /// Whether `#[cfg(..)]` keeps this item, given the enabled features.
601 ///
602 /// This is evaluation, not approximation: rustc does the same thing, and
603 /// an item whose predicate is false is not part of the compiled program.
604 /// A predicate that cannot be evaluated is reported rather than assumed.
605 fn cfg_keeps(&self, attrs: &[syn::Attribute]) -> Result<bool, String> {
606 for a in attrs {
607 if a.path().is_ident("cfg") {
608 let pred: syn::Meta = a
609 .parse_args()
610 .map_err(|e| format!("cannot parse `#[cfg(..)]`: {e}"))?;
611 if !self.cfg_eval(&pred)? {
612 return Ok(false);
613 }
614 }
615 }
616 Ok(true)
617 }
618
619 fn cfg_eval(&self, m: &syn::Meta) -> Result<bool, String> {
620 match m {
621 syn::Meta::NameValue(nv) if nv.path.is_ident("feature") => {
622 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
623 return Err("`feature = ..` expects a string".into());
624 };
625 Ok(self.features.iter().any(|f| *f == s.value()))
626 }
627 syn::Meta::List(l) if l.path.is_ident("not") => {
628 let inner: syn::Meta = l.parse_args().map_err(|e| e.to_string())?;
629 Ok(!self.cfg_eval(&inner)?)
630 }
631 syn::Meta::List(l) if l.path.is_ident("all") || l.path.is_ident("any") => {
632 let items: syn::punctuated::Punctuated<syn::Meta, syn::Token![,]> = l
633 .parse_args_with(syn::punctuated::Punctuated::parse_terminated)
634 .map_err(|e| e.to_string())?;
635 let all = l.path.is_ident("all");
636 let mut acc = all;
637 for i in &items {
638 let v = self.cfg_eval(i)?;
639 acc = if all { acc && v } else { acc || v };
640 }
641 Ok(acc)
642 }
643 other => Err(format!(
644 "`#[cfg({})]` is not a predicate rustnim can evaluate; only \
645 `feature = \"..\"`, `not`, `all` and `any` are implemented",
646 quote_meta(other)
647 )),
648 }
649 }
650
651 /// Map a Rust type, expanding any `type` alias first. Every type in the
652 /// lowering goes through here rather than calling `ty::map` directly, so
653 /// an alias cannot be missed in one position and honoured in another.
654 fn map_ty(&self, t: &syn::Type) -> Result<Nim, String> {
655 ty::map(&self.expand(t, 0)?)
656 }
657
658 fn expand(&self, t: &syn::Type, depth: usize) -> Result<syn::Type, String> {
659 if depth > 16 {
660 return Err("type alias expansion did not terminate; is it cyclic?".into());
661 }
662 let syn::Type::Path(p) = t else { return Ok(t.clone()) };
663 // Only an unqualified name can be one of this file's aliases.
664 // `fmt::Result` and `core::result::Result` are different types that
665 // merely end in the same segment.
666 if p.path.segments.len() != 1 {
667 return Ok(t.clone());
668 }
669 let Some(seg) = p.path.segments.last() else { return Ok(t.clone()) };
670 let Some((params, target)) = self.aliases.get(&seg.ident.to_string()) else {
671 return Ok(t.clone());
672 };
673 let args: Vec<syn::Type> = match &seg.arguments {
674 syn::PathArguments::AngleBracketed(a) => a
675 .args
676 .iter()
677 .filter_map(|g| match g {
678 GenericArgument::Type(t) => Some(t.clone()),
679 _ => None,
680 })
681 .collect(),
682 _ => vec![],
683 };
684 if args.len() != params.len() {
685 // Flattening several files into one module can bring a crate's own
686 // alias (`type Result<T> = Result<T, Error>`) into scope at a site
687 // that meant the builtin (`Result<T, E>`). Rust kept them apart by
688 // module; here they are told apart by arity, and a use that fits
689 // neither is left for `ty::map` to report.
690 return Ok(t.clone());
691 }
692 self.expand(&substitute(target, params, &args), depth + 1)
693 }
694
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago695 /// The Nim name for a function, qualified by its module.
696 fn fn_name(&self, module: &str, name: &str) -> String {
697 if module.is_empty() {
698 ident(name)
699 } else {
700 format!("{}_{}", module, ident(name))
701 }
702 }
703
704 /// Resolve a call path to the module and name it refers to: an explicit
705 /// `mixed::decode`, then the current module, then the crate root.
706 fn resolve_fn(&self, path: &syn::Path) -> Option<(String, String)> {
707 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
708 let last = segs.last()?.clone();
709 if segs.len() >= 2 {
710 let q = &segs[segs.len() - 2];
711 if self.fns.contains_key(&(q.clone(), last.clone())) {
712 return Some((q.clone(), last));
713 }
714 }
715 let imported = self.use_map.get(&last).cloned();
716 for m in [Some(self.cur_mod.clone()), imported, Some(String::new())]
717 .into_iter()
718 .flatten()
719 {
720 if self.fns.contains_key(&(m.clone(), last.clone())) {
721 return Some((m, last));
722 }
723 }
724 None
725 }
726
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago727 /// The Nim `proc` head for a Rust signature, used both for the forward
728 /// declaration and for the definition, so the two cannot drift apart.
729 fn head_of(
730 &self,
731 name: &str,
732 sig: &syn::Signature,
733 recv: Option<&Nim>,
734 ) -> Result<String, String> {
735 let (ptys, ret) = self.signature(sig)?;
736 let mut parts = Vec::new();
737 if let Some(self_ty) = recv {
738 let mutable = matches!(
739 sig.inputs.first(),
740 Some(FnArg::Receiver(r))
741 if matches!(&r.kind, syn::ReceiverKind::Reference(_, _, m) if m.is_some())
742 );
743 let t = if mutable { Nim::Var(Box::new(self_ty.clone())) } else { self_ty.clone() };
744 parts.push(format!("self: {}", t.render()));
745 }
746 let typed: Vec<&syn::PatType> = sig
747 .inputs
748 .iter()
749 .filter_map(|a| match a {
750 FnArg::Typed(t) => Some(t),
751 _ => None,
752 })
753 .collect();
754 for (i, (p, t)) in typed.iter().zip(ptys.iter()).enumerate() {
755 let pname = match &*p.pat {
756 Pat::Ident(id) => id.ident.to_string(),
757 Pat::Wild(_) => format!("unused{}", parts.len()),
758 _ => return Err("only plain identifier parameters are supported".into()),
759 };
760 let _ = i;
761 parts.push(format!("{}: {}", ident(&pname), t.render()));
762 }
763 Ok(if ret == Nim::Unit {
764 format!("proc {}*({})", ident(name), parts.join(", "))
765 } else {
766 format!("proc {}*({}): {}", ident(name), parts.join(", "), ret.render())
767 })
768 }
769
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago770 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 18h ago771 // `unsafe fn` marks a contract for callers; it does not change what
772 // the body means, so it lowers like any other proc.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago773 if sig.asyncness.is_some() {
774 return Err(format!("`async fn {}`: Nim has no equivalent", sig.ident));
775 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago776 // Lifetime parameters carry no runtime meaning and Nim is GC'd, so
777 // `fn encode<'a>(..)` is not generic for our purposes. Type and const
778 // parameters genuinely are, and are rejected.
779 if let Some(p) = sig.generics.params.iter().find(|p| !matches!(p, syn::GenericParam::Lifetime(_))) {
780 let what = match p {
781 syn::GenericParam::Const(_) => "const",
782 _ => "type",
783 };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago784 return Err(format!(
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago785 "`fn {}` has a {what} parameter: generics are not implemented yet",
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago786 sig.ident
787 ));
788 }
789 let mut params = Vec::new();
790 for a in &sig.inputs {
791 if let FnArg::Typed(t) = a {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago792 params.push(self.map_ty(&t.ty)?);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago793 }
794 }
795 let ret = match &sig.output {
796 ReturnType::Default => Nim::Unit,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago797 // A returned `&[T]` is a borrow of the caller's buffer, so it
798 // stays an `openArray` view. Only an owned type (`Vec<T>`) becomes
799 // a `seq`, which `owned()` would do to both.
800 ReturnType::Type(_, t) => {
801 let n = self.map_ty(t)?;
802 if returns_borrow(t) { n } else { n.owned() }
803 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago804 };
805 Ok((params, ret))
806 }
807
808 // --------------------------------------------------------------- items
809
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago810 /// Emit the type definitions only: they must precede every signature.
811 fn item_types(&mut self, item: &Item) -> Result<(), String> {
812 if !self.cfg_keeps(item_attrs(item))? {
813 return Ok(());
814 }
815 match item {
816 Item::Struct(_) | Item::Enum(_) | Item::Const(_) => self.item_inner(item),
817 Item::Mod(m) if m.content.is_some() => {
818 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
819 for i in &items {
820 self.item_types(i)?;
821 }
822 Ok(())
823 }
824 _ => Ok(()),
825 }
826 }
827
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago828 fn item(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago829 if !self.cfg_keeps(item_attrs(item))? {
830 return Ok(());
831 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago832 // Types were emitted in their own pass.
833 if matches!(item, Item::Struct(_) | Item::Enum(_) | Item::Const(_)) {
834 return Ok(());
835 }
836 self.item_inner(item)
837 }
838
839 fn item_inner(&mut self, item: &Item) -> Result<(), String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago840 match item {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago841 Item::Fn(f) => {
842 let nim = self.fn_name(&self.cur_mod, &f.sig.ident.to_string());
843 self.func_named(&nim, &f.sig, &f.block, None)
844 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago845 Item::Struct(s) => {
846 let name = s.ident.to_string();
847 let fields = self.structs[&name].clone();
848 self.line(&format!("type {}* = object", ident(&name)));
849 self.indent += 1;
850 if fields.is_empty() {
851 self.line("discard");
852 }
853 for (fname, fty) in &fields {
854 self.line(&format!("{}*: {}", ident(fname), fty.render()));
855 }
856 self.indent -= 1;
857 self.blank();
858 Ok(())
859 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago860 Item::Type(_) => Ok(()), // expanded at every use site
861 Item::Enum(e) => {
862 let def = self.enums[&e.ident.to_string()].clone();
863 self.emit_enum(&def);
864 Ok(())
865 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago866 Item::Const(c) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago867 let t = self.map_ty(&c.ty)?.owned();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago868 let v = self.expr(&c.expr)?;
869 self.bind(&c.ident.to_string(), t.clone());
870 let line = format!("const {}*: {} = {}", ident(&c.ident.to_string()), t.render(), v.code);
871 self.line(&line);
872 self.blank();
873 Ok(())
874 }
875 Item::Impl(im) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago876 let self_ty = self.map_ty(&im.self_ty)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago877 if let Some((path, _)) = &im.trait_ {
878 let tr = path_name(path);
879 if im.items.is_empty() {
880 return Ok(());
881 }
882 let syn::ImplItem::Fn(m) = &im.items[0] else {
883 return Err(format!("unsupported item in `impl {tr}`"));
884 };
885 if is_fmt_trait(&tr) {
886 return self.fmt_impl(&tr, &self_ty, &m.sig, &m.block);
887 }
888 if tr == "From" {
889 let name = {
890 let (params, _) = self.signature(&m.sig)?;
891 let src = params.first().cloned().ok_or("`fn from` takes one argument")?;
892 self.from_impls[&(type_name(&src), type_name(&self_ty))].clone()
893 };
894 return self.func_named(&name, &m.sig, &m.block, None);
895 }
896 return Err(format!("`impl {tr}` is not implemented"));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago897 }
898 for it in &im.items {
899 match it {
900 syn::ImplItem::Fn(m) => {
901 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
902 self.func(&m.sig, &m.block, recv)?;
903 }
904 _ => return Err("only `fn` items are supported inside `impl`".into()),
905 }
906 }
907 Ok(())
908 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago909 // `use` and `extern crate` are resolution directives with no Nim
910 // analogue once everything is one module.
911 Item::Use(_) | Item::ExternCrate(_) => Ok(()),
912 Item::Mod(m) if m.content.is_some() => {
913 // An inline `mod` is flattened; Nim has no nested modules in a
914 // single file.
915 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
916 for i in &items {
917 self.item(i)?;
918 }
919 Ok(())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago920 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago921 Item::Mod(m) => {
922 // Satisfied if that file was passed in too; everything is one
923 // Nim module, so the declaration itself emits nothing.
924 if self.modules.iter().any(|x| *x == m.ident.to_string()) {
925 return Ok(());
926 }
927 Err(format!(
928 "`mod {};` refers to another file that was not passed to \
929 rustnim; add it to the input list",
930 m.ident
931 ))
932 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago933 other => Err(format!("unsupported item: {}", item_kind(other))),
934 }
935 }
936
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago937 /// `None` carries no type of its own, so Nim needs the `Option[T]` named.
938 fn none_of(&self, expect: Option<&Nim>) -> String {
939 match expect {
940 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => {
941 format!("rsNone[{}]()", a[0].render())
942 }
943 _ => "rsNone()".to_string(),
944 }
945 }
946
947 fn emit_enum(&mut self, def: &EnumDef) {
948 let name = ident(&def.name);
949 if def.simple {
950 // Every variant is a unit variant, so a plain Nim enum is an exact
951 // fit: it compares, orders and `case`-checks like Rust's.
952 self.line(&format!("type {name}* = enum"));
953 self.indent += 1;
954 for v in &def.variants {
955 self.line(&format!("{}", ident(&v.name)));
956 }
957 self.indent -= 1;
958 self.blank();
959 self.line(&format!("proc rsDebug*(x: {name}): string ="));
960 self.indent += 1;
961 self.line("case x");
962 for v in &def.variants {
963 self.line(&format!("of {}.{}: \"{}\"", name, ident(&v.name), v.name));
964 }
965 self.indent -= 1;
966 self.blank();
967 return;
968 }
969
970 // A data-carrying enum is a Nim object variant: one discriminant enum
971 // plus a branch per variant. This is the same shape the prelude uses
972 // for `Option` and `Result`.
973 self.line("type");
974 self.indent += 1;
975 self.line(&format!("{}Kind* = enum", name));
976 self.indent += 1;
977 for v in &def.variants {
978 self.line(&def.kind_ident(&v.name));
979 }
980 self.indent -= 1;
981 self.blank();
982 self.line(&format!("{}* = object", name));
983 self.indent += 1;
984 self.line(&format!("case kind*: {}Kind", name));
985 for v in &def.variants {
986 if v.fields.is_empty() {
987 self.line(&format!("of {}: discard", def.kind_ident(&v.name)));
988 } else {
989 self.line(&format!("of {}:", def.kind_ident(&v.name)));
990 self.indent += 1;
991 for (f, t) in &v.fields {
992 self.line(&format!("{}*: {}", ident(f), t.render()));
993 }
994 self.indent -= 1;
995 }
996 }
997 self.indent -= 2;
998 self.blank();
999
1000 for v in &def.variants {
1001 let args: Vec<String> = v
1002 .fields
1003 .iter()
1004 .enumerate()
1005 .map(|(i, (_, t))| format!("a{}: {}", i, t.render()))
1006 .collect();
1007 let inits: Vec<String> = v
1008 .fields
1009 .iter()
1010 .enumerate()
1011 .map(|(i, (f, _))| format!("{}: a{}", ident(f), i))
1012 .collect();
1013 let mut all = vec![format!("kind: {}", def.kind_ident(&v.name))];
1014 all.extend(inits);
1015 self.line(&format!(
1016 "proc {}*({}): {} = {}({})",
1017 def.ctor_ident(&v.name),
1018 args.join(", "),
1019 name,
1020 name,
1021 all.join(", ")
1022 ));
1023 }
1024 self.blank();
1025
1026 self.line(&format!("proc rsDebug*(x: {name}): string ="));
1027 self.indent += 1;
1028 self.line("case x.kind");
1029 for v in &def.variants {
1030 if v.fields.is_empty() {
1031 self.line(&format!("of {}: \"{}\"", def.kind_ident(&v.name), v.name));
1032 } else {
1033 let parts: Vec<String> = v
1034 .fields
1035 .iter()
1036 .map(|(f, _)| format!("rsDebug(x.{})", ident(f)))
1037 .collect();
1038 self.line(&format!(
1039 "of {}: \"{}(\" & {} & \")\"",
1040 def.kind_ident(&v.name),
1041 v.name,
1042 parts.join(" & \", \" & ")
1043 ));
1044 }
1045 }
1046 self.indent -= 1;
1047 self.blank();
1048 }
1049
1050 /// Resolve a Rust path like `Error::InvalidLength` or a bare `InvalidLength`
1051 /// to the enum that declares it.
1052 fn resolve_variant(&self, path: &syn::Path) -> Option<(EnumDef, String)> {
1053 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
1054 let last = segs.last()?.clone();
1055 if segs.len() >= 2 {
1056 if let Some(def) = self.enums.get(&segs[segs.len() - 2]) {
1057 if def.get(&last).is_some() {
1058 return Some((def.clone(), last));
1059 }
1060 }
1061 }
1062 // Unqualified: only unambiguous if exactly one enum declares it.
1063 match self.variant_owner.get(&last) {
1064 Some(owners) if owners.len() == 1 => {
1065 let def = self.enums.get(&owners[0])?;
1066 Some((def.clone(), last))
1067 }
1068 _ => None,
1069 }
1070 }
1071
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1072 /// Lower `impl Display for T`'s `fn fmt` into a proc returning a string.
1073 ///
1074 /// Rust's `Formatter` is a sink that a `fmt` method writes into; the
1075 /// observable result of `{}` is exactly the bytes written. So the method
1076 /// becomes `proc rsDisplay(self: T): string` and every write through the
1077 /// formatter produces that string. A `fmt` body that does anything else
1078 /// with the formatter -- padding, precision, `debug_struct` -- is rejected,
1079 /// because those affect the output and this model does not carry them.
1080 /// The window an expression names, if it names one.
1081 fn window_of(&self, e: &Expr) -> Option<Alias> {
1082 match e {
1083 Expr::Path(p) => match self.lookup_alias(&path_name(&p.path)) {
1084 Some(a @ Alias::Window { .. }) => Some(a),
1085 _ => None,
1086 },
1087 Expr::Reference(r) => self.window_of(&r.expr),
1088 Expr::Paren(p) => self.window_of(&p.expr),
1089 Expr::Unary(u) if matches!(u.op, UnOp::Deref(_)) => self.window_of(&u.expr),
1090 _ => None,
1091 }
1092 }
1093
1094 /// Whether an expression is the `Formatter` parameter of the formatting
1095 /// impl currently being lowered.
1096 fn is_fmt_param(&self, e: &Expr) -> bool {
1097 let Some(f) = &self.fmt_param else { return false };
1098 match e {
1099 Expr::Path(p) => path_name(&p.path) == *f,
1100 Expr::Reference(r) => self.is_fmt_param(&r.expr),
1101 Expr::Paren(p) => self.is_fmt_param(&p.expr),
1102 _ => false,
1103 }
1104 }
1105
1106 fn fmt_impl(
1107 &mut self,
1108 tr: &str,
1109 self_ty: &Nim,
1110 sig: &syn::Signature,
1111 body: &syn::Block,
1112 ) -> Result<(), String> {
1113 let proc_name = fmt_proc(tr);
1114 // The formatter is the parameter after `self`.
1115 let f = sig
1116 .inputs
1117 .iter()
1118 .filter_map(|a| match a {
1119 FnArg::Typed(t) => match &*t.pat {
1120 Pat::Ident(i) => Some(i.ident.to_string()),
1121 _ => None,
1122 },
1123 _ => None,
1124 })
1125 .next()
1126 .ok_or("`fn fmt` needs a `Formatter` parameter")?;
1127
1128 self.push_scope();
1129 self.bind("self", self_ty.clone());
1130 let saved = self.fmt_param.replace(f);
1131 let outer_ret = self.ret.replace(Nim::Prim("string".into()));
1132 let outer_target = self
1133 .target
1134 .replace(("result".to_string(), Some(Nim::Prim("string".into()))));
1135
1136 self.line(&format!(
1137 "proc {}*(self: {}): string =",
1138 proc_name,
1139 self_ty.render()
1140 ));
1141 self.indent += 1;
1142 let before = self.out.len();
1143 let want = Nim::Prim("string".into());
1144 let tail = self.block_body_at(body, Some(&want))?;
1145 self.emit_tail(tail);
1146 if self.out.len() == before {
1147 self.line("discard");
1148 }
1149 self.indent -= 1;
1150
1151 self.target = outer_target;
1152 self.ret = outer_ret;
1153 self.fmt_param = saved;
1154 self.pop_scope();
1155 self.blank();
1156 Ok(())
1157 }
1158
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1159 fn func(
1160 &mut self,
1161 sig: &syn::Signature,
1162 body: &syn::Block,
1163 recv: Option<Nim>,
1164 ) -> Result<(), String> {
1165 let name = sig.ident.to_string();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1166 self.func_named(&name.clone(), sig, body, recv)
1167 }
1168
1169 fn func_named(
1170 &mut self,
1171 name: &str,
1172 sig: &syn::Signature,
1173 body: &syn::Block,
1174 recv: Option<Nim>,
1175 ) -> Result<(), String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1176 let (ptys, ret) = self.signature(sig)?;
1177
1178 self.push_scope();
1179 let mut rendered: Vec<String> = Vec::new();
1180
1181 if let Some(self_ty) = recv {
1182 // `&mut self` and `mut self` both mean the body may mutate the
1183 // receiver; only the former is observable by the caller, and a Nim
1184 // `var` parameter is the faithful spelling of that.
1185 let mutable = matches!(
1186 sig.inputs.first(),
1187 Some(FnArg::Receiver(r))
1188 if matches!(&r.kind, syn::ReceiverKind::Reference(_, _, m) if m.is_some())
1189 );
1190 let t = if mutable { Nim::Var(Box::new(self_ty.clone())) } else { self_ty.clone() };
1191 rendered.push(format!("self: {}", t.render()));
1192 self.bind("self", self_ty);
1193 }
1194
1195 let typed: Vec<&syn::PatType> = sig
1196 .inputs
1197 .iter()
1198 .filter_map(|a| match a {
1199 FnArg::Typed(t) => Some(t),
1200 _ => None,
1201 })
1202 .collect();
1203 for (p, t) in typed.iter().zip(ptys.iter()) {
1204 let pname = match &*p.pat {
1205 Pat::Ident(i) => i.ident.to_string(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1206 // `fn from(_: Error) -> ..` — the parameter is unused, but Nim
1207 // still needs a name for it.
1208 Pat::Wild(_) => format!("unused{}", rendered.len()),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1209 _ => return Err("only plain identifier parameters are supported".into()),
1210 };
1211 rendered.push(format!("{}: {}", ident(&pname), t.render()));
1212 // Inside the body a `var T` parameter is used exactly like a `T`.
1213 self.bind(&pname, t.clone().owned());
1214 }
1215
1216 let head = if ret == Nim::Unit {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1217 format!("proc {}*({}) =", ident(name), rendered.join(", "))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1218 } else {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1219 format!("proc {}*({}): {} =", ident(name), rendered.join(", "), ret.render())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1220 };
1221 self.line(&head);
1222 self.indent += 1;
1223 let outer_ret = self.ret.replace(ret.clone());
1224
1225 // A Rust fn's trailing expression is its return value. Naming Nim's
1226 // implicit `result` as the target makes that true whether the tail is
1227 // a plain expression or an `if`/`match` with statement arms.
1228 let outer_target = if ret == Nim::Unit {
1229 self.target.take()
1230 } else {
1231 self.target.replace(("result".to_string(), Some(ret.clone())))
1232 };
1233 let before = self.out.len();
1234 let tail = self.block_body_at(body, Some(&ret))?;
1235 self.target = outer_target;
1236 match tail {
1237 Some(v) if ret != Nim::Unit => {
1238 let code = v.code.clone();
1239 self.line(&format!("result = {code}"));
1240 }
1241 Some(v) => {
1242 // A trailing expression in a `()`-returning fn is evaluated for
1243 // its effect; Nim requires an explicit discard.
1244 let needs_discard = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
1245 if needs_discard && !v.code.is_empty() {
1246 let code = v.code.clone();
1247 self.line(&format!("discard {code}"));
1248 }
1249 }
1250 None => {}
1251 }
1252 if self.out.len() == before {
1253 self.line("discard");
1254 }
1255
1256 self.indent -= 1;
1257 self.ret = outer_ret;
1258 self.pop_scope();
1259 self.blank();
1260 Ok(())
1261 }
1262
1263 // ---------------------------------------------------------- statements
1264
1265 /// Lower a block's statements. Returns the block's trailing expression,
1266 /// if it has one, *without* emitting it — the caller decides whether that
1267 /// value is a return value, a binding, or discarded.
1268 fn block_body(&mut self, b: &syn::Block) -> Result<Option<Val>, String> {
1269 self.block_body_at(b, None)
1270 }
1271
1272 fn block_body_at(
1273 &mut self,
1274 b: &syn::Block,
1275 expect: Option<&Nim>,
1276 ) -> Result<Option<Val>, String> {
1277 // An assignment target belongs to *this* block's trailing expression
1278 // only. A non-final `if` is a statement and must not assign anything.
1279 let target = self.target.take();
1280 let n = b.stmts.len();
1281 let mut tail = None;
1282 for (i, st) in b.stmts.iter().enumerate() {
1283 let last = i + 1 == n;
1284 match st {
1285 Stmt::Expr(e, None) if last && expressible(e) => {
1286 tail = Some(self.expr_at(e, expect)?)
1287 }
1288 Stmt::Expr(e, None) if last => {
1289 // A trailing `if`/`match` with statement arms, or a loop.
1290 // Lower it as statements; if this block's value is wanted,
1291 // each arm assigns it.
1292 match &target {
1293 Some((t, ty)) => {
1294 let (t, ty) = (t.clone(), ty.clone());
1295 self.assign_from(e, &t, ty.as_ref())?;
1296 }
1297 None => self.stmt(st)?,
1298 }
1299 }
1300 _ => self.stmt(st)?,
1301 }
1302 }
1303 self.target = target;
1304 Ok(tail)
1305 }
1306
1307 /// Lower a block in statement position (loop bodies, `if` arms).
1308 fn nested_block(&mut self, b: &syn::Block) -> Result<(), String> {
1309 self.push_scope();
1310 self.indent += 1;
1311 let before = self.out.len();
1312 let want = self.target.clone().and_then(|(_, t)| t);
1313 let tail = self.block_body_at(b, want.as_ref())?;
1314 self.emit_tail(tail);
1315 if self.out.len() == before {
1316 self.line("discard");
1317 }
1318 self.indent -= 1;
1319 self.pop_scope();
1320 Ok(())
1321 }
1322
1323 fn stmt(&mut self, s: &Stmt) -> Result<(), String> {
1324 match s {
1325 Stmt::Local(l) => self.local(l),
1326 Stmt::Expr(e, _) => {
1327 let v = self.expr_stmt(e)?;
1328 if let Some(v) = v {
1329 // A bare expression with a value must be discarded in Nim.
1330 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
1331 let code = v.code.clone();
1332 if needs {
1333 self.line(&format!("discard {code}"));
1334 } else if !code.is_empty() {
1335 self.line(&code);
1336 }
1337 }
1338 Ok(())
1339 }
1340 Stmt::Item(i) => self.item(i),
1341 Stmt::Macro(m) => {
1342 let line = self.macro_call(&m.mac)?;
1343 self.line(&line);
1344 Ok(())
1345 }
1346 }
1347 }
1348
1349 fn local(&mut self, l: &Local) -> Result<(), String> {
1350 let (name, mutable, ann): (String, bool, Option<Nim>) = match &l.pat {
1351 Pat::Ident(i) => (i.ident.to_string(), i.mutability.is_some(), None),
1352 Pat::Type(t) => match &*t.pat {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1353 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 19h ago1354 _ => return Err("only `let <ident>` bindings are supported".into()),
1355 },
1356 Pat::Wild(_) => ("_".into(), false, None),
1357 _ => return Err("destructuring `let` is not implemented yet".into()),
1358 };
1359
1360 let Some(init) = &l.init else {
1361 // `let x: T;` — Nim's `var x: T` zero-initialises, which Rust does
1362 // not. Rust's own rules make reading it before assignment illegal,
1363 // so the two agree on every program rustc accepts.
1364 let t = ann.ok_or("`let` without an initialiser needs a type annotation")?;
1365 let t = t.owned();
1366 self.line(&format!("var {}: {}", ident(&name), t.render()));
1367 self.bind(&name, t);
1368 return Ok(());
1369 };
1370 if init.diverge.is_some() {
1371 return Err("`let ... else` is not implemented yet".into());
1372 }
1373
1374 if !expressible(&init.expr) && name != "_" {
1375 // The initialiser is an `if`/`match` whose arms are statements.
1376 // Declare first, then let each arm assign into the binding.
1377 let t = ann
1378 .clone()
1379 .ok_or_else(|| {
1380 format!(
1381 "`let {name} = match/if ...` needs a type annotation: \
1382 its arms are statements, so the binding must be \
1383 declared before they run"
1384 )
1385 })?
1386 .owned();
1387 self.line(&format!("var {}: {}", ident(&name), t.render()));
1388 self.bind(&name, t.clone());
1389 let target = ident(&name);
1390 return self.assign_from(&init.expr, &target, Some(&t));
1391 }
1392
1393 let v = self.expr_at(&init.expr, ann.as_ref())?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1394 if let Some(w) = v.window.clone() {
1395 // `let dst = dst.get_mut(..n).ok_or(..)?;` -- the binding names a
1396 // view into the caller's buffer. Copying it into a `seq` would
1397 // still print the right bytes but would stop writes reaching the
1398 // caller, so it is bound as an alias.
1399 if v.guard.is_some() && v.guard_err.is_some() {
1400 return Err(format!(
1401 "`let {name} = ...get(..)` keeps an `Option` of a slice view, \
1402 which Nim cannot represent; apply `?` or `unwrap()` to it \
1403 in the same expression"
1404 ));
1405 }
1406 self.bind_alias(&name, w);
1407 return Ok(());
1408 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1409 let t = match (ann, &v.ty) {
1410 (Some(a), _) => a.owned(),
1411 (None, Some(t)) => t.clone().owned(),
1412 (None, None) => {
1413 return Err(format!(
1414 "cannot infer the type of `let {name}`; annotate it — \
1415 guessing here would change integer width, and with it the \
1416 meaning of any arithmetic on `{name}`"
1417 ))
1418 }
1419 };
1420
1421 if name == "_" {
1422 let code = v.code.clone();
1423 self.line(&format!("discard {code}"));
1424 return Ok(());
1425 }
1426 // Rust's immutable `let` is Nim's `let`; `let mut` is `var`. Shadowing
1427 // works in both, so a re-`let` of the same name needs no rename.
1428 let kw = if mutable { "var" } else { "let" };
1429 let line = format!("{} {}: {} = {}", kw, ident(&name), t.render(), v.code);
1430 self.line(&line);
1431 self.bind(&name, t);
1432 Ok(())
1433 }
1434
1435 /// Expressions that are statements in Rust and statements in Nim too
1436 /// (control flow). Returns `None` when it emitted lines itself.
1437 fn expr_stmt(&mut self, e: &Expr) -> Result<Option<Val>, String> {
1438 match e {
1439 Expr::If(_) => {
1440 self.if_stmt(e)?;
1441 Ok(None)
1442 }
1443 Expr::While(w) => {
1444 if w.label.is_some() {
1445 return Err("loop labels are not implemented yet".into());
1446 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1447 self.in_loop_cond = true;
1448 let c = self.expr(&w.cond);
1449 self.in_loop_cond = false;
1450 let c = c?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1451 self.line(&format!("while {}:", c.code));
1452 let saved = self.target.take();
1453 self.nested_block(&w.body)?;
1454 self.target = saved;
1455 Ok(None)
1456 }
1457 Expr::Loop(l) => {
1458 if l.label.is_some() {
1459 return Err("loop labels are not implemented yet".into());
1460 }
1461 self.line("while true:");
1462 let saved = self.target.take();
1463 self.nested_block(&l.body)?;
1464 self.target = saved;
1465 Ok(None)
1466 }
1467 Expr::ForLoop(f) => {
1468 self.for_loop(f)?;
1469 Ok(None)
1470 }
1471 Expr::Block(b) => {
1472 if b.label.is_some() {
1473 return Err("block labels are not implemented yet".into());
1474 }
1475 self.line("block:");
1476 self.nested_block(&b.block)?;
1477 Ok(None)
1478 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1479 Expr::Unsafe(u) => {
1480 // Transparent in statement position too, for the same reason.
1481 self.nested_block_flat(&u.block)?;
1482 Ok(None)
1483 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1484 Expr::Match(_) => {
1485 self.match_stmt(e)?;
1486 Ok(None)
1487 }
1488 Expr::Return(r) => {
1489 match &r.expr {
1490 Some(e) => {
1491 let want = self.ret.clone();
1492 let v = self.expr_at(e, want.as_ref())?;
1493 self.line(&format!("return {}", v.code));
1494 }
1495 None => self.line("return"),
1496 }
1497 Ok(None)
1498 }
1499 Expr::Break(b) => {
1500 if b.expr.is_some() || b.label.is_some() {
1501 return Err("`break` with a value or a label is not implemented yet".into());
1502 }
1503 self.line("break");
1504 Ok(None)
1505 }
1506 Expr::Continue(c) => {
1507 if c.label.is_some() {
1508 return Err("labelled `continue` is not implemented yet".into());
1509 }
1510 self.line("continue");
1511 Ok(None)
1512 }
1513 Expr::Assign(a) => {
1514 let lhs = self.expr(&a.left)?;
1515 if !expressible(&a.right) {
1516 let target = lhs.code.clone();
1517 return self.assign_from(&a.right, &target, lhs.ty.as_ref()).map(|_| None);
1518 }
1519 let rhs = self.expr_at(&a.right, lhs.ty.as_ref())?;
1520 self.line(&format!("{} = {}", lhs.code, rhs.code));
1521 Ok(None)
1522 }
1523 Expr::Binary(b) if is_compound(&b.op) => {
1524 let lhs = self.expr(&b.left)?;
1525 // `i += 1` must widen the literal to `i`'s type, not to the
1526 // i32 an unconstrained Rust literal would default to.
1527 let rhs = self.expr_at(&b.right, lhs.ty.as_ref())?;
1528 let op = self.bin_op(&b.op, &lhs, &rhs)?;
1529 // Nim has no `shl=` etc., and `+=` on a `let` is illegal in
1530 // both languages, so the expanded form is always correct.
1531 self.line(&format!("{} = {} {} {}", lhs.code, lhs.code, op, rhs.code));
1532 Ok(None)
1533 }
1534 Expr::Macro(m) => {
1535 let line = self.macro_call(&m.mac)?;
1536 self.line(&line);
1537 Ok(None)
1538 }
1539 _ => Ok(Some(self.expr(e)?)),
1540 }
1541 }
1542
1543 /// Lower `e` in statement position, assigning each arm's value to
1544 /// `target`. This is how Rust's expression-oriented `if`/`match` survive
1545 /// the trip when their arms are too big for a Nim `if`-expression.
1546 fn assign_from(
1547 &mut self,
1548 e: &Expr,
1549 target: &str,
1550 expect: Option<&Nim>,
1551 ) -> Result<(), String> {
1552 let saved = self.target.replace((target.to_string(), expect.cloned()));
1553 let r = match e {
1554 Expr::If(_) => self.if_stmt(e),
1555 Expr::Match(_) => self.match_stmt(e),
1556 other => {
1557 let v = self.expr_at(other, expect)?;
1558 self.line(&format!("{} = {}", target, v.code));
1559 Ok(())
1560 }
1561 };
1562 self.target = saved;
1563 r
1564 }
1565
1566 /// Emit a block's value into the active assignment target, if there is
1567 /// one, or discard it if there is not.
1568 fn emit_tail(&mut self, v: Option<Val>) {
1569 let Some(v) = v else { return };
1570 match self.target.clone() {
1571 Some((t, _)) => {
1572 let code = v.code.clone();
1573 self.line(&format!("{t} = {code}"));
1574 }
1575 None => {
1576 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
1577 let code = v.code.clone();
1578 if needs {
1579 self.line(&format!("discard {code}"));
1580 } else if !code.is_empty() {
1581 self.line(&code);
1582 }
1583 }
1584 }
1585 }
1586
1587 fn if_stmt(&mut self, e: &Expr) -> Result<(), String> {
1588 let Expr::If(i) = e else { unreachable!() };
1589 if let Expr::Let(_) = &*i.cond {
1590 return Err("`if let` is not implemented yet".into());
1591 }
1592 let c = self.expr(&i.cond)?;
1593 self.line(&format!("if {}:", c.code));
1594 self.nested_block(&i.then_branch)?;
1595 match &i.else_branch {
1596 None => {}
1597 Some((_, els)) => match &**els {
1598 Expr::If(_) => {
1599 // Nim needs `elif`; splice the nested `if` in as one.
1600 let mark = self.out.len();
1601 self.if_stmt(els)?;
1602 let tail = self.out.split_off(mark);
1603 let indent = " ".repeat(self.indent);
1604 self.out.push_str(&tail.replacen(&format!("{indent}if "), &format!("{indent}elif "), 1));
1605 }
1606 Expr::Block(b) => {
1607 self.line("else:");
1608 self.nested_block(&b.block)?;
1609 }
1610 _ => return Err("unsupported `else` form".into()),
1611 },
1612 }
1613 Ok(())
1614 }
1615
1616 fn for_loop(&mut self, f: &syn::ExprForLoop) -> Result<(), String> {
1617 if f.label.is_some() {
1618 return Err("loop labels are not implemented yet".into());
1619 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1620 let it = self.resolve_iter(&f.expr)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1621
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1622 // One index loop drives the whole chain. Rust's adaptors are lazy and
1623 // compose; resolving them to an index and binding each name to an
1624 // lvalue reproduces that without materialising anything.
1625 let i = self.fresh("Idx");
1626 self.line(&format!("for {} in 0 ..< int({}):", i, it.len()));
1627 self.indent += 1;
1628 self.push_scope();
1629 let before = self.out.len();
1630
1631 self.bind_pattern(&f.pat, &it, &i)?;
1632
1633 let saved = self.target.take();
1634 if let Some(v) = self.block_body(&f.body)? {
1635 let code = v.code.clone();
1636 self.line(&format!("discard {code}"));
1637 }
1638 self.target = saved;
1639 if self.out.len() == before {
1640 self.line("discard");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1641 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1642 self.pop_scope();
1643 self.indent -= 1;
1644 Ok(())
1645 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1646
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1647 /// Resolve a chain of iterator adaptors into a single `Iter`.
1648 ///
1649 /// Only adaptors with an exact index-loop equivalent are accepted. `map`,
1650 /// `filter`, `take_while` and friends are rejected rather than partially
1651 /// honoured: silently dropping an adaptor would change which elements the
1652 /// loop visits.
1653 fn resolve_iter(&mut self, e: &Expr) -> Result<Iter, String> {
1654 match e {
1655 Expr::Reference(r) => self.resolve_iter(&r.expr),
1656 Expr::Paren(p) => self.resolve_iter(&p.expr),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1657 Expr::Range(r) => {
1658 let lo = match &r.start {
1659 Some(e) => self.expr(e)?,
1660 None => return Err("a `for` over `..n` needs a start bound".into()),
1661 };
1662 let hi = match &r.end {
1663 Some(e) => self.expr(e)?,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1664 None => {
1665 return Err("a `for` over an unbounded range would not terminate".into())
1666 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1667 };
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1668 let ty = lo.ty.clone().or(hi.ty.clone());
1669 Ok(Iter::Range {
1670 lo: lo.code,
1671 hi: hi.code,
1672 closed: matches!(r.limits, syn::RangeLimits::Closed(_)),
1673 ty,
1674 })
1675 }
1676 Expr::MethodCall(m) => {
1677 let name = m.method.to_string();
1678 match name.as_str() {
1679 "iter" | "into_iter" | "iter_mut" if m.args.is_empty() => {
1680 let mut it = self.resolve_iter(&m.receiver)?;
1681 if name == "iter_mut" {
1682 if let Iter::Elems { mutable, .. } = &mut it {
1683 *mutable = true;
1684 }
1685 }
1686 Ok(it)
1687 }
1688 "enumerate" if m.args.is_empty() => {
1689 Ok(Iter::Enumerate(Box::new(self.resolve_iter(&m.receiver)?)))
1690 }
1691 "zip" if m.args.len() == 1 => {
1692 let a = self.resolve_iter(&m.receiver)?;
1693 let b = self.resolve_iter(&m.args[0])?;
1694 Ok(Iter::Zip(Box::new(a), Box::new(b)))
1695 }
1696 "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 18h ago1697 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1698 let k = self.expr(&m.args[0])?;
1699 Ok(Iter::Chunks {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1700 code,
1701 base,
1702 len,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1703 k: k.code,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1704 elem,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1705 mutable: name.ends_with("_mut"),
1706 })
1707 }
1708 "windows" if m.args.len() == 1 => {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1709 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1710 let k = self.expr(&m.args[0])?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1711 Ok(Iter::Windows { code, base, len, k: k.code, elem })
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1712 }
1713 other => Err(format!(
1714 "iterator adaptor `.{other}()` is not implemented; it has \
1715 no index-loop equivalent here, and dropping it would \
1716 change which elements the loop visits"
1717 )),
1718 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1719 }
1720 other => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1721 // A `for` binding that is itself a window iterates that window,
1722 // not the whole container it points into.
1723 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 18h ago1724 return Ok(Iter::Elems { code, off, len, elem, mutable: false });
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1725 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1726 let v = self.expr(other)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1727 Ok(Iter::Elems {
1728 len: format!("{}.len", v.code),
1729 elem: elem_of(&v.ty),
1730 code: v.code,
1731 off: "0".into(),
1732 mutable: false,
1733 })
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1734 }
1735 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1736 }
1737
1738 /// Bind a `for` pattern against a resolved iterator at index `i`.
1739 fn bind_pattern(&mut self, p: &Pat, it: &Iter, i: &str) -> Result<(), String> {
1740 match (p, it) {
1741 (Pat::Tuple(t), Iter::Zip(a, b)) if t.elems.len() == 2 => {
1742 self.bind_pattern(&t.elems[0], a, i)?;
1743 self.bind_pattern(&t.elems[1], b, i)
1744 }
1745 (Pat::Tuple(t), Iter::Enumerate(inner)) if t.elems.len() == 2 => {
1746 if let Pat::Ident(id) = &t.elems[0] {
1747 let n = id.ident.to_string();
1748 // Rust's `enumerate` counts in `usize`.
1749 self.line(&format!("let {}: uint = uint({})", ident(&n), i));
1750 self.bind(&n, Nim::Prim("uint".into()));
1751 }
1752 self.bind_pattern(&t.elems[1], inner, i)
1753 }
1754 (_, Iter::Zip(..) | Iter::Enumerate(..)) => Err(
1755 "a `zip`/`enumerate` loop needs a two-element tuple pattern".into(),
1756 ),
1757 (Pat::Wild(_), _) => Ok(()),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1758 // `for &byte in xs` — the `&` destructures the reference, which in
1759 // Nim is already the value.
1760 (Pat::Reference(r), _) => self.bind_pattern(&r.pat, it, i),
1761 (Pat::Paren(p), _) => self.bind_pattern(&p.pat, it, i),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1762 (Pat::Ident(id), _) => {
1763 let name = id.ident.to_string();
1764 match it {
1765 Iter::Range { lo, ty, .. } => {
1766 let t = ty.clone().unwrap_or(Nim::Prim("int".into()));
1767 // The loop counts from zero; the range's own start is
1768 // added back so the binding has Rust's value and type.
1769 self.line(&format!(
1770 "let {}: {} = {}({}) + {}",
1771 ident(&name),
1772 t.render(),
1773 t.render(),
1774 i,
1775 lo
1776 ));
1777 self.bind(&name, t);
1778 Ok(())
1779 }
1780 Iter::Elems { code, off, elem, mutable, .. } => {
1781 let access = if off == "0" {
1782 format!("{}[{}]", code, i)
1783 } else {
1784 format!("{}[{} + {}]", code, off, i)
1785 };
1786 if *mutable {
1787 // An alias, not a copy: assigning through the
1788 // binding must reach the original element.
1789 self.bind_alias(
1790 &name,
1791 Alias::Value { code: access, ty: elem.clone() },
1792 );
1793 } else {
1794 let t = elem
1795 .clone()
1796 .ok_or("cannot infer the element type of this `for`")?;
1797 self.line(&format!(
1798 "let {}: {} = {}",
1799 ident(&name),
1800 t.render(),
1801 access
1802 ));
1803 self.bind(&name, t);
1804 }
1805 Ok(())
1806 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1807 Iter::Chunks { code, base, k, elem, .. } => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1808 self.bind_alias(
1809 &name,
1810 Alias::Window {
1811 code: code.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1812 off: format!("({} + {} * int({}))", base, i, k),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1813 len: format!("int({})", k),
1814 elem: elem.clone(),
1815 },
1816 );
1817 Ok(())
1818 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1819 Iter::Windows { code, base, k, elem, .. } => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1820 self.bind_alias(
1821 &name,
1822 Alias::Window {
1823 code: code.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1824 off: format!("({} + {})", base, i),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1825 len: format!("int({})", k),
1826 elem: elem.clone(),
1827 },
1828 );
1829 Ok(())
1830 }
1831 // Handled above: a zip or enumerate needs a tuple pattern,
1832 // and binding one name to the pair is not supported.
1833 Iter::Zip(..) | Iter::Enumerate(..) => unreachable!(),
1834 }
1835 }
1836 _ => Err("unsupported `for` pattern".into()),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1837 }
1838 }
1839
1840 fn match_stmt(&mut self, e: &Expr) -> Result<(), String> {
1841 let Expr::Match(m) = e else { unreachable!() };
1842 let scrut = self.expr(&m.expr)?;
1843 let t = scrut
1844 .ty
1845 .clone()
1846 .ok_or("cannot infer the type of a `match` scrutinee")?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1847 let name = self.fresh("Match");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1848 self.line(&format!("let {}: {} = {}", name, t.render(), scrut.code));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1849
1850 // A `match` whose arms neither bind nor guard is a Nim `case`, which
1851 // is exhaustiveness-checked the way Rust's is. Anything richer becomes
1852 // an if/elif chain, because Nim's `case` cannot destructure.
1853 let plain = m.arms.iter().all(|a| {
1854 !matches!(a.pat, Pat::Guard(_)) && !binds(&a.pat) && !destructures(&a.pat)
1855 });
1856 if plain {
1857 self.match_case(m, &name, &t)
1858 } else {
1859 self.match_chain(m, &name, &t)
1860 }
1861 }
1862
1863 fn match_case(
1864 &mut self,
1865 m: &syn::ExprMatch,
1866 name: &str,
1867 t: &Nim,
1868 ) -> Result<(), String> {
1869 // A variant object is discriminated by its `kind` field.
1870 let on_kind = matches!(t, Nim::Named(n, _) if self.enums.get(n).is_some_and(|d| !d.simple));
1871 self.line(&format!("case {}{}", name, if on_kind { ".kind" } else { "" }));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1872
1873 let mut saw_wild = false;
1874 for arm in &m.arms {
1875 match &arm.pat {
1876 Pat::Wild(_) => {
1877 saw_wild = true;
1878 self.line("else:");
1879 }
1880 p => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1881 let labels = self.pat_labels(p, Some(t))?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1882 self.line(&format!("of {}:", labels.join(", ")));
1883 }
1884 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1885 self.arm_body(&arm.body)?;
1886 }
1887 if !saw_wild && !self.case_is_total(t, m) {
1888 // Rust checked exhaustiveness already, but Nim cannot always see
1889 // it -- an integer `case` needs every value covered -- so make the
1890 // unreachable arm explicit rather than leave a compile error.
1891 self.line("else:");
1892 self.line(" rsPanic(\"unreachable match arm\")");
1893 }
1894 Ok(())
1895 }
1896
1897 /// Whether a Nim `case` over this type is already total, in which case
1898 /// adding an `else` would be a compile error rather than a safety net.
1899 fn case_is_total(&self, t: &Nim, m: &syn::ExprMatch) -> bool {
1900 let Nim::Named(n, _) = t else { return false };
1901 let Some(def) = self.enums.get(n) else { return false };
1902 def.variants.len() == m.arms.len()
1903 }
1904
1905 /// The if/elif form, for arms that bind or destructure.
1906 fn match_chain(
1907 &mut self,
1908 m: &syn::ExprMatch,
1909 name: &str,
1910 t: &Nim,
1911 ) -> Result<(), String> {
1912 let mut first = true;
1913 let mut closed = false;
1914 for arm in &m.arms {
1915 let (pat, guard) = match &arm.pat {
1916 Pat::Guard(g) => (&*g.pat, Some(&*g.guard)),
1917 p => (p, None),
1918 };
1919 if guard.is_some() && binds(pat) {
1920 return Err("a `match` guard on a binding pattern is not \
1921 implemented yet"
1922 .into());
1923 }
1924 let test = self.pat_test(pat, name, t)?;
1925 let test = match (test, guard) {
1926 (Some(t), Some(g)) => {
1927 let g = self.expr(g)?;
1928 Some(format!("({}) and ({})", t, g.code))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1929 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1930 (None, Some(g)) => Some(self.expr(g)?.code),
1931 (t, None) => t,
1932 };
1933 match test {
1934 Some(test) => {
1935 self.line(&format!(
1936 "{} {}:",
1937 if first { "if" } else { "elif" },
1938 test
1939 ));
1940 first = false;
1941 }
1942 None => {
1943 // An irrefutable pattern: everything left falls here.
1944 if first {
1945 self.line("block:");
1946 } else {
1947 self.line("else:");
1948 }
1949 closed = true;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1950 }
1951 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1952 self.indent += 1;
1953 self.push_scope();
1954 let before = self.out.len();
1955 self.pat_bind(pat, name, t)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1956 self.indent -= 1;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1957 self.arm_body_at(&arm.body, before)?;
1958 self.pop_scope();
1959 if closed {
1960 break;
1961 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1962 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1963 if !closed {
1964 // Rust proved this unreachable; Nim cannot see that, and leaving
1965 // the chain open would silently fall through instead.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1966 self.line("else:");
1967 self.line(" rsPanic(\"unreachable match arm\")");
1968 }
1969 Ok(())
1970 }
1971
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1972 /// The condition that selects this arm, or `None` if it always matches.
1973 fn pat_test(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<Option<String>, String> {
1974 Ok(match p {
1975 Pat::Wild(_) => None,
1976 Pat::Ident(i) if i.subpat.is_none() => None,
1977 Pat::Or(o) => {
1978 let mut parts = Vec::new();
1979 for c in &o.cases {
1980 match self.pat_test(c, name, t)? {
1981 Some(x) => parts.push(x),
1982 None => return Ok(None),
1983 }
1984 }
1985 Some(format!("({})", parts.join(" or ")))
1986 }
1987 Pat::Lit(_) | Pat::Range(_) => {
1988 let labels = self.pat_labels(p, Some(t))?;
1989 Some(match p {
1990 Pat::Range(_) => format!("({} in {})", name, labels[0]),
1991 _ => format!("({} == {})", name, labels[0]),
1992 })
1993 }
1994 Pat::Path(pp) => Some(self.variant_test(&pp.path, name, t)?),
1995 Pat::TupleStruct(ts) => Some(self.variant_test(&ts.path, name, t)?),
1996 Pat::Struct(st) => Some(self.variant_test(&st.path, name, t)?),
1997 Pat::Paren(pp) => return self.pat_test(&pp.pat, name, t),
1998 Pat::Reference(r) => return self.pat_test(&r.pat, name, t),
1999 _ => return Err("unsupported `match` pattern".into()),
2000 })
2001 }
2002
2003 /// The discriminant test for `Ok`/`Err`/`Some`/`None` or an enum variant.
2004 fn variant_test(&self, path: &syn::Path, name: &str, t: &Nim) -> Result<String, String> {
2005 let last = path_name(path);
2006 match last.as_str() {
2007 "Ok" => return Ok(format!("{name}.ok")),
2008 "Err" => return Ok(format!("(not {name}.ok)")),
2009 "Some" => return Ok(format!("{name}.has")),
2010 "None" => return Ok(format!("(not {name}.has)")),
2011 _ => {}
2012 }
2013 let Some((def, v)) = self.resolve_variant(path) else {
2014 return Err(format!(
2015 "`{last}` in a pattern is not a known enum variant; if it names \
2016 an enum declared in another module, that is not implemented yet"
2017 ));
2018 };
2019 if let Nim::Named(n, _) = t {
2020 if *n != def.name {
2021 return Err(format!(
2022 "pattern `{}::{}` does not match the scrutinee type `{}`",
2023 def.name, v, n
2024 ));
2025 }
2026 }
2027 Ok(if def.simple {
2028 format!("({} == {}.{})", name, ident(&def.name), ident(&v))
2029 } else {
2030 format!("({}.kind == {})", name, def.kind_ident(&v))
2031 })
2032 }
2033
2034 /// Emit the `let`s that a pattern's bindings introduce.
2035 fn pat_bind(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<(), String> {
2036 match p {
2037 Pat::Wild(_) | Pat::Lit(_) | Pat::Range(_) | Pat::Path(_) | Pat::Or(_) => Ok(()),
2038 Pat::Paren(pp) => self.pat_bind(&pp.pat, name, t),
2039 Pat::Reference(r) => self.pat_bind(&r.pat, name, t),
2040 Pat::Ident(i) if i.subpat.is_none() => {
2041 let b = i.ident.to_string();
2042 self.line(&format!("let {}: {} = {}", ident(&b), t.render(), name));
2043 self.bind(&b, t.clone());
2044 Ok(())
2045 }
2046 Pat::TupleStruct(ts) => {
2047 let fields = self.variant_fields(&ts.path, t)?;
2048 for (i, sub) in ts.elems.iter().enumerate() {
2049 let Some((fname, fty)) = fields.get(i) else {
2050 return Err(format!(
2051 "pattern binds {} field(s) but the variant has {}",
2052 ts.elems.len(),
2053 fields.len()
2054 ));
2055 };
2056 let access = format!("{}.{}", name, ident(fname));
2057 self.pat_bind(sub, &access, fty)?;
2058 }
2059 Ok(())
2060 }
2061 Pat::Struct(st) => {
2062 let fields = self.variant_fields(&st.path, t)?;
2063 for f in &st.fields {
2064 let syn::Member::Named(m) = &f.member else {
2065 return Err("unsupported struct pattern field".into());
2066 };
2067 let m = m.to_string();
2068 let Some((fname, fty)) = fields.iter().find(|(f, _)| f.ends_with(&m)) else {
2069 return Err(format!("unknown field `{m}` in pattern"));
2070 };
2071 let access = format!("{}.{}", name, ident(fname));
2072 self.pat_bind(&f.pat, &access, fty)?;
2073 }
2074 Ok(())
2075 }
2076 _ => Err("unsupported `match` pattern".into()),
2077 }
2078 }
2079
2080 /// The payload fields a variant pattern destructures.
2081 fn variant_fields(
2082 &self,
2083 path: &syn::Path,
2084 t: &Nim,
2085 ) -> Result<Vec<(String, Nim)>, String> {
2086 let last = path_name(path);
2087 // `Ok`/`Err`/`Some` read the prelude's own field names.
2088 if let Nim::Named(n, a) = t {
2089 match (n.as_str(), last.as_str()) {
2090 ("Result", "Ok") if a.len() == 2 => return Ok(vec![("val".into(), a[0].clone())]),
2091 ("Result", "Err") if a.len() == 2 => return Ok(vec![("err".into(), a[1].clone())]),
2092 ("Option", "Some") if a.len() == 1 => return Ok(vec![("val".into(), a[0].clone())]),
2093 _ => {}
2094 }
2095 }
2096 let Some((def, v)) = self.resolve_variant(path) else {
2097 return Err(format!("`{last}` is not a known enum variant"));
2098 };
2099 Ok(def.get(&v).map(|v| v.fields.clone()).unwrap_or_default())
2100 }
2101
2102 fn arm_body(&mut self, body: &Expr) -> Result<(), String> {
2103 self.indent += 1;
2104 let before = self.out.len();
2105 self.indent -= 1;
2106 self.arm_body_at(body, before)
2107 }
2108
2109 fn arm_body_at(&mut self, body: &Expr, before: usize) -> Result<(), String> {
2110 match body {
2111 Expr::Block(b) => self.nested_block(&b.block)?,
2112 other => {
2113 self.indent += 1;
2114 // An arm's value is the `match`'s value, so it is typed by
2115 // whatever the `match` is being assigned to -- without which
2116 // an `Ok(..)` arm has no way to know its `Result<T, E>`.
2117 let want = self.target.clone().and_then(|(_, t)| t);
2118 let v = match (want, expressible(other)) {
2119 (Some(t), true) => Some(self.expr_at(other, Some(&t))?),
2120 _ => self.expr_stmt(other)?,
2121 };
2122 self.emit_tail(v);
2123 self.indent -= 1;
2124 }
2125 }
2126 if self.out.len() == before {
2127 self.indent += 1;
2128 self.line("discard");
2129 self.indent -= 1;
2130 }
2131 Ok(())
2132 }
2133
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2134 fn pat_labels(&mut self, p: &Pat, expect: Option<&Nim>) -> Result<Vec<String>, String> {
2135 match p {
2136 Pat::Lit(l) => Ok(vec![self.lit_at(&l.lit, expect)?.code]),
2137 Pat::Or(o) => {
2138 let mut out = Vec::new();
2139 for p in &o.cases {
2140 out.extend(self.pat_labels(p, expect)?);
2141 }
2142 Ok(out)
2143 }
2144 Pat::Range(r) => {
2145 let lo = r.start.as_ref().ok_or("open-ended range pattern")?;
2146 let hi = r.end.as_ref().ok_or("open-ended range pattern")?;
2147 let (lo, hi) = (self.expr_at(lo, expect)?, self.expr_at(hi, expect)?);
2148 let op = match r.limits {
2149 syn::RangeLimits::HalfOpen(_) => "..<",
2150 syn::RangeLimits::Closed(_) => "..",
2151 };
2152 Ok(vec![format!("{} {} {}", lo.code, op, hi.code)])
2153 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2154 Pat::Path(pp) => {
2155 if let Some((def, v)) = self.resolve_variant(&pp.path) {
2156 return Ok(vec![if def.simple {
2157 format!("{}.{}", ident(&def.name), ident(&v))
2158 } else {
2159 def.kind_ident(&v)
2160 }]);
2161 }
2162 Ok(vec![ident(&path_name(&pp.path))])
2163 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2164 _ => Err("unsupported `match` pattern; only literals, ranges, `|` \
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2165 alternatives, enum variants and `_` are implemented"
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2166 .into()),
2167 }
2168 }
2169
2170 // --------------------------------------------------------- expressions
2171
2172 fn expr(&mut self, e: &Expr) -> Result<Val, String> {
2173 self.expr_at(e, None)
2174 }
2175
2176 /// Lower `e`, with the type the surrounding code expects of it.
2177 ///
2178 /// Rust infers an unsuffixed integer literal's type from its context and
2179 /// falls back to `i32`; Nim falls back to 64-bit `int`. Carrying the
2180 /// expected type down to the literal is what makes `let x: u8 = 255` and
2181 /// `x.wrapping_add(100)` mean the same thing on both sides. Without it the
2182 /// widths silently diverge, which is exactly the class of bug this
2183 /// project refuses to ship.
2184 fn expr_at(&mut self, e: &Expr, expect: Option<&Nim>) -> Result<Val, String> {
2185 match e {
2186 Expr::Lit(l) => self.lit_at(&l.lit, expect),
2187 Expr::Path(p) => {
2188 let name = path_name(&p.path);
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2189 if name == "None" {
2190 return Ok(Val::new(self.none_of(expect), expect.cloned()));
2191 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2192 // A unit struct used as a value: `fmt::Error`, or a `struct S;`
2193 // declared here. In Nim that is a constructor call.
2194 if p.path.segments.len() > 1 {
2195 let ty = syn::Type::Path(syn::TypePath { attrs: Vec::new(), qself: None, path: p.path.clone() });
2196 if let Ok(Nim::Prim(n)) = ty::map(&ty) {
2197 if n == "FmtError" {
2198 return Ok(Val::new("FmtError()", Some(Nim::Prim(n))));
2199 }
2200 }
2201 }
2202 if self.structs.get(&name).is_some_and(|f| f.is_empty()) {
2203 return Ok(Val::new(
2204 format!("{}()", ident(&name)),
2205 Some(Nim::Named(name.clone(), vec![])),
2206 ));
2207 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2208 // A unit enum variant used as a value: `Error::InvalidLength`.
2209 if let Some((def, v)) = self.resolve_variant(&p.path) {
2210 let ty = Some(Nim::Named(def.name.clone(), vec![]));
2211 return Ok(if def.simple {
2212 Val::new(format!("{}.{}", ident(&def.name), ident(&v)), ty)
2213 } else {
2214 Val::new(format!("{}()", def.ctor_ident(&v)), ty)
2215 });
2216 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2217 // A `for` binding that stands for an element of the container
2218 // it came from: using it must read (and assigning through it
2219 // must write) that element, not a copy.
2220 if let Some(a) = self.lookup_alias(&name) {
2221 return Ok(match a {
2222 Alias::Value { code, ty } => Val::new(code, ty),
2223 // A window *is* a slice; as a value it is the view it
2224 // denotes, which is what Rust's `&[T]` means too.
2225 Alias::Window { code, off, len, elem } => Val::new(
2226 format!("{}.toOpenArray({}, {} + {} - 1)", code, off, off, len),
2227 elem.map(|e| Nim::OpenArray(Box::new(e))),
2228 ),
2229 });
2230 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2231 if let Some(t) = self.lookup(&name) {
2232 return Ok(Val::new(ident(&name), Some(t)));
2233 }
2234 // A top-level function used as a value, e.g. passed to a
2235 // parameter of `impl Fn(..)` type.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2236 if let Some(k) = self.resolve_fn(&p.path) {
2237 let sig = &self.fns[&k];
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2238 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 18h ago2239 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 19h ago2240 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2241 Ok(Val::new(ident(&name), None))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2242 }
2243 Expr::Paren(p) => {
2244 let v = self.expr_at(&p.expr, expect)?;
2245 Ok(Val::new(format!("({})", v.code), v.ty))
2246 }
2247 Expr::Group(g) => self.expr_at(&g.expr, expect),
2248 // `&x` is a value in Nim; `&mut x` in an argument position binds to
2249 // a `var` parameter, which is also just `x` at the call site.
2250 Expr::Reference(r) => self.expr_at(&r.expr, expect),
2251 Expr::Unary(u) => self.unary(u, expect),
2252 Expr::Binary(b) => self.binary(b, expect),
2253 Expr::Cast(c) => self.cast(c),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2254 Expr::Index(i) if matches!(&*i.index, Expr::Range(_)) => {
2255 let Expr::Range(r) = &*i.index else { unreachable!() };
2256 let base = self.expr(&i.expr)?;
2257 let lo = match &r.start {
2258 Some(e) => format!("int({})", self.expr(e)?.code),
2259 None => "0".into(),
2260 };
2261 // Nim's `toOpenArray` takes an inclusive upper bound.
2262 let hi = match (&r.end, r.limits) {
2263 (Some(e), syn::RangeLimits::HalfOpen(_)) => {
2264 format!("int({}) - 1", self.expr(e)?.code)
2265 }
2266 (Some(e), syn::RangeLimits::Closed(_)) => {
2267 format!("int({})", self.expr(e)?.code)
2268 }
2269 (None, _) => format!("{}.len - 1", base.code),
2270 };
2271 let elem = elem_of(&base.ty)
2272 .ok_or("cannot infer the element type of this slice")?;
2273 Ok(Val::new(
2274 format!("{}.toOpenArray({}, {})", base.code, lo, hi),
2275 Some(Nim::OpenArray(Box::new(elem))),
2276 ))
2277 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2278 Expr::Index(i) => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2279 if let Some(Alias::Window { code, off, elem, .. }) = self.window_of(&i.expr) {
2280 let idx = self.expr(&i.index)?;
2281 return Ok(Val::new(
2282 format!("{}[{} + int({})]", code, off, idx.code),
2283 elem,
2284 ));
2285 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2286 let base = self.expr(&i.expr)?;
2287 let idx = self.expr(&i.index)?;
2288 // Rust indexes with usize; Nim wants an `int`, and a `uint`
2289 // index is a type error there rather than a silent conversion.
2290 let idx_code = match &idx.ty {
2291 Some(t) if t.is_unsigned() => format!("int({})", idx.code),
2292 _ => idx.code.clone(),
2293 };
2294 let elem = match base.ty.clone() {
2295 Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) | Some(Nim::Array(_, t)) => Some(*t),
2296 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
2297 _ => None,
2298 };
2299 Ok(Val::new(format!("{}[{}]", base.code, idx_code), elem))
2300 }
2301 Expr::Field(f) => {
2302 let base = self.expr(&f.base)?;
2303 let name = match &f.member {
2304 syn::Member::Named(n) => n.to_string(),
2305 syn::Member::Unnamed(i) => format!("f{}", i.index),
2306 };
2307 let t = match &base.ty {
2308 Some(Nim::Named(s, _)) => self
2309 .structs
2310 .get(s)
2311 .and_then(|fs| fs.iter().find(|(f, _)| *f == name))
2312 .map(|(_, t)| t.clone()),
2313 _ => None,
2314 };
2315 Ok(Val::new(format!("{}.{}", base.code, ident(&name)), t))
2316 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2317 // `unsafe` is a permission marker, not a semantic change: it does
2318 // not alter what the enclosed operations mean. So the block is
2319 // transparent here, and each operation inside still goes through
2320 // the ordinary lowering -- and is still rejected if it has no
2321 // faithful mapping.
2322 Expr::Unsafe(u) => match single_expr(&u.block) {
2323 Some(e) => self.expr_at(e, expect),
2324 None => Err("an `unsafe` block used as a value must be a single \
2325 expression"
2326 .into()),
2327 },
2328 Expr::Closure(c) => self.closure(c, expect),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2329 Expr::Try(t) => self.try_op(t),
2330 Expr::Call(c) => self.call(c, expect),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2331 Expr::MethodCall(m) => self.method(m, expect),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2332 Expr::Macro(m) if path_name(&m.mac.path) == "vec" => {
2333 // `vec![..]`'s elements take their type from the annotation on
2334 // the binding, exactly as Rust's would.
2335 let want = match expect {
2336 Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) => Some((**e).clone()),
2337 _ => None,
2338 };
2339 let saved = std::mem::replace(&mut self.vec_expect, want.clone());
2340 let code = self.macro_call(&m.mac);
2341 self.vec_expect = saved;
2342 let code = code?;
2343 let ty = match want {
2344 Some(e) => Some(Nim::Seq(Box::new(e))),
2345 None => self.vec_elem(&m.mac)?.map(|e| Nim::Seq(Box::new(e))),
2346 };
2347 Ok(Val::new(code, ty))
2348 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2349 Expr::Macro(m) => {
2350 let code = self.macro_call(&m.mac)?;
2351 Ok(Val::new(code, None))
2352 }
2353 Expr::Struct(s) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2354 if s.rest.is_some() {
2355 return Err("struct update syntax `..rest` is not implemented yet".into());
2356 }
2357 // `Shape::Rect { w: 3, h: 5 }` is a struct-shaped *enum variant*,
2358 // which is constructed positionally in Nim.
2359 if let Some((def, v)) = self.resolve_variant(&s.path) {
2360 let fields = def.get(&v).map(|v| v.fields.clone()).unwrap_or_default();
2361 let mut args = vec![String::new(); fields.len()];
2362 for f in &s.fields {
2363 let syn::Member::Named(m) = &f.member else {
2364 return Err("unsupported enum variant field".into());
2365 };
2366 let want = format!("{}_{}", v, m);
2367 let i = fields
2368 .iter()
2369 .position(|(n, _)| *n == want)
2370 .ok_or_else(|| format!("`{}::{}` has no field `{m}`", def.name, v))?;
2371 args[i] = self.expr_at(&f.expr, Some(&fields[i].1))?.code;
2372 }
2373 if let Some(i) = args.iter().position(|a| a.is_empty()) {
2374 return Err(format!(
2375 "`{}::{}` is missing field `{}`",
2376 def.name, v, fields[i].0
2377 ));
2378 }
2379 return Ok(Val::new(
2380 format!("{}({})", def.ctor_ident(&v), args.join(", ")),
2381 Some(Nim::Named(def.name.clone(), vec![])),
2382 ));
2383 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2384 let name = path_name(&s.path);
2385 let mut parts = Vec::new();
2386 for f in &s.fields {
2387 let fname = match &f.member {
2388 syn::Member::Named(n) => n.to_string(),
2389 syn::Member::Unnamed(i) => format!("f{}", i.index),
2390 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2391 let want = self
2392 .structs
2393 .get(&name)
2394 .and_then(|fs| fs.iter().find(|(n, _)| *n == fname))
2395 .map(|(_, t)| t.clone());
2396 let v = self.expr_at(&f.expr, want.as_ref())?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2397 parts.push(format!("{}: {}", ident(&fname), v.code));
2398 }
2399 Ok(Val::new(
2400 format!("{}({})", ident(&name), parts.join(", ")),
2401 Some(Nim::Named(name, vec![])),
2402 ))
2403 }
2404 Expr::Array(a) => {
2405 let mut parts = Vec::new();
2406 let mut elem = match expect {
2407 Some(Nim::Array(_, t)) | Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) => {
2408 Some((**t).clone())
2409 }
2410 _ => None,
2411 };
2412 for e in &a.elems {
2413 let want = elem.clone();
2414 let v = self.expr_at(e, want.as_ref())?;
2415 elem = elem.or(v.ty.clone());
2416 parts.push(v.code);
2417 }
2418 let t = elem.map(|t| Nim::Array(a.elems.len(), Box::new(t)));
2419 Ok(Val::new(format!("[{}]", parts.join(", ")), t))
2420 }
2421 Expr::Repeat(r) => {
2422 let v = self.expr(&r.expr)?;
2423 let n = self.expr(&r.len)?;
2424 let t = v.ty.clone().map(|t| Nim::Seq(Box::new(t)));
2425 Ok(Val::new(format!("newSeqWith(int({}), {})", n.code, v.code), t))
2426 }
2427 Expr::Tuple(t) if t.elems.is_empty() => Ok(Val::new("", Some(Nim::Unit))),
2428 Expr::Tuple(t) => {
2429 let mut parts = Vec::new();
2430 let mut tys = Vec::new();
2431 for e in &t.elems {
2432 let v = self.expr(e)?;
2433 tys.push(v.ty.clone());
2434 parts.push(v.code);
2435 }
2436 let ty = tys
2437 .iter()
2438 .cloned()
2439 .collect::<Option<Vec<_>>>()
2440 .map(Nim::Tuple);
2441 Ok(Val::new(format!("({})", parts.join(", ")), ty))
2442 }
2443 // `if` and `match` are expressions in both languages, but only
2444 // when every arm is itself a single expression.
2445 Expr::If(i) => self.if_expr(i, expect),
2446 Expr::Block(b) if b.block.stmts.len() == 1 => {
2447 if let Some(Stmt::Expr(e, None)) = b.block.stmts.first() {
2448 self.expr_at(e, expect)
2449 } else {
2450 Err("block expression with statements in value position is not implemented yet".into())
2451 }
2452 }
2453 other => Err(format!(
2454 "unsupported expression in value position: {}",
2455 expr_kind(other)
2456 )),
2457 }
2458 }
2459
2460 fn if_expr(&mut self, i: &syn::ExprIf, expect: Option<&Nim>) -> Result<Val, String> {
2461 let (Some(then), Some((_, els))) = (single_expr(&i.then_branch), &i.else_branch) else {
2462 return Err(
2463 "an `if` used as a value must have an `else` and single-expression arms".into(),
2464 );
2465 };
2466 let c = self.expr(&i.cond)?;
2467 let t = self.expr_at(then, expect)?;
2468 let want = expect.cloned().or_else(|| t.ty.clone());
2469 let e = match &**els {
2470 Expr::Block(b) => match single_expr(&b.block) {
2471 Some(x) => self.expr_at(x, want.as_ref())?,
2472 None => return Err("an `if` used as a value must have single-expression arms".into()),
2473 },
2474 other => self.expr_at(other, want.as_ref())?,
2475 };
2476 let ty = t.ty.clone().or(e.ty.clone());
2477 Ok(Val::new(
2478 format!("(if {}: {} else: {})", c.code, t.code, e.code),
2479 ty,
2480 ))
2481 }
2482
2483 fn lit_at(&mut self, l: &Lit, expect: Option<&Nim>) -> Result<Val, String> {
2484 match l {
2485 Lit::Int(i) => {
2486 let suffix = i.suffix();
2487 if let Some(why) = ty::rejected(suffix) {
2488 return Err(format!("integer literal `{}`: {}", i, why));
2489 }
2490 let digits = i.base10_digits().to_string();
2491 // Rust's default for an unconstrained integer literal is i32.
2492 // Nim's is `int` (64-bit). Making the width explicit is what
2493 // keeps overflow behaviour the same on both sides.
2494 let t = if suffix.is_empty() {
2495 match expect {
2496 Some(t) if t.is_integer() => t.clone(),
2497 // Rust's fallback for an otherwise-unconstrained
2498 // integer literal.
2499 _ => Nim::Prim("int32".into()),
2500 }
2501 } else {
2502 ty::prim(suffix).ok_or_else(|| format!("unknown literal suffix `{suffix}`"))?
2503 };
2504 Ok(Val::new(format!("{}'{}", digits, nim_suffix(&t)?), Some(t)))
2505 }
2506 Lit::Float(f) => {
2507 let t = match f.suffix() {
2508 "" => match expect {
2509 Some(Nim::Prim(p)) if p == "float32" => Nim::Prim("float32".into()),
2510 _ => Nim::Prim("float64".into()),
2511 },
2512 "f64" => Nim::Prim("float64".into()),
2513 "f32" => Nim::Prim("float32".into()),
2514 s => return Err(format!("unknown float suffix `{s}`")),
2515 };
2516 let d = f.base10_digits();
2517 let d = if d.contains('.') || d.contains('e') { d.to_string() } else { format!("{d}.0") };
2518 Ok(Val::new(d, Some(t)))
2519 }
2520 Lit::Bool(b) => Ok(Val::new(b.value.to_string(), Some(Nim::Prim("bool".into())))),
2521 Lit::Str(s) => Ok(Val::new(
2522 fmt::nim_str(&s.value()),
2523 Some(Nim::Prim("string".into())),
2524 )),
2525 Lit::Char(c) => Ok(Val::new(
2526 format!("Rune({})", c.value() as u32),
2527 Some(Nim::Prim("Rune".into())),
2528 )),
2529 Lit::Byte(b) => Ok(Val::new(
2530 format!("{}'u8", b.value()),
2531 Some(Nim::Prim("uint8".into())),
2532 )),
2533 Lit::ByteStr(b) => {
2534 let bytes: Vec<String> = b.value().iter().map(|x| format!("{x}'u8")).collect();
2535 Ok(Val::new(
2536 format!("@[{}]", bytes.join(", ")),
2537 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
2538 ))
2539 }
2540 other => Err(format!("unsupported literal: {other:?}")),
2541 }
2542 }
2543
2544 fn unary(&mut self, u: &syn::ExprUnary, expect: Option<&Nim>) -> Result<Val, String> {
2545 // `-128i8` is a literal in Rust, but `-(128'i8)` in Nim would overflow
2546 // the positive half of the range before the negation runs. Folding the
2547 // sign into the literal keeps `i8::MIN` and friends expressible.
2548 if let (UnOp::Neg(_), Expr::Lit(l)) = (&u.op, &*u.expr) {
2549 if matches!(l.lit, Lit::Int(_) | Lit::Float(_)) {
2550 let v = self.lit_at(&l.lit, expect)?;
2551 return Ok(Val::new(format!("-{}", v.code), v.ty));
2552 }
2553 }
2554 let v = self.expr_at(&u.expr, expect)?;
2555 match u.op {
2556 UnOp::Neg(_) => Ok(Val::new(format!("(-{})", v.code), v.ty)),
2557 // Rust's `!` is logical on bool and bitwise-complement on integers.
2558 // Nim spells those `not` and `not` as well, so one mapping covers
2559 // both — but only because Nim overloads `not` the same way.
2560 UnOp::Not(_) => Ok(Val::new(format!("(not {})", v.code), v.ty)),
2561 UnOp::Deref(_) => Ok(v),
2562 _ => Err("unsupported unary operator".into()),
2563 }
2564 }
2565
2566 fn binary(&mut self, b: &syn::ExprBinary, expect: Option<&Nim>) -> Result<Val, String> {
2567 // A comparison's operands are unrelated to the `bool` it produces, so
2568 // the outer expectation is not passed through to them.
2569 let down = match b.op {
2570 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
2571 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => None,
2572 _ => expect,
2573 };
2574 let mut l = self.expr_at(&b.left, down)?;
2575 // Rust unifies the two operand types; propagating whichever side is
2576 // known to the other reproduces that, and disagreement then surfaces
2577 // as a Nim type error rather than as a silent width change.
2578 let mut r = self.expr_at(&b.right, l.ty.as_ref().or(down))?;
2579 if l.ty.is_none() && r.ty.is_some() {
2580 l = self.expr_at(&b.left, r.ty.as_ref())?;
2581 }
2582 let r = std::mem::replace(&mut r, Val::untyped(""));
2583 let op = self.bin_op(&b.op, &l, &r)?;
2584 let ty = match b.op {
2585 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
2586 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => Some(Nim::Prim("bool".into())),
2587 // Rust's shift takes its result type from the *left* operand, and
2588 // the right may be a different width entirely.
2589 BinOp::Shl(_) | BinOp::Shr(_) => l.ty.clone(),
2590 _ => l.ty.clone().or(r.ty.clone()),
2591 };
2592 Ok(Val::new(format!("({} {} {})", l.code, op, r.code), ty))
2593 }
2594
2595 fn bin_op(&mut self, op: &BinOp, l: &Val, r: &Val) -> Result<&'static str, String> {
2596 Ok(match op {
2597 BinOp::Add(_) | BinOp::AddAssign(_) => "+",
2598 BinOp::Sub(_) | BinOp::SubAssign(_) => "-",
2599 BinOp::Mul(_) | BinOp::MulAssign(_) => "*",
2600 BinOp::Div(_) | BinOp::DivAssign(_) => {
2601 // Nim spells integer division `div`. Both languages truncate
2602 // toward zero, so once the right operator is chosen the
2603 // semantics match, including for negative operands.
2604 let t = l.ty.clone().or(r.ty.clone()).ok_or(
2605 "cannot tell integer from float division here; annotate the operands",
2606 )?;
2607 if t.is_integer() { "div" } else { "/" }
2608 }
2609 BinOp::Rem(_) | BinOp::RemAssign(_) => {
2610 let t = l.ty.clone().or(r.ty.clone()).ok_or(
2611 "cannot tell integer from float remainder here; annotate the operands",
2612 )?;
2613 if t.is_integer() { "mod" } else { return Err("float `%` is not implemented yet".into()) }
2614 }
2615 BinOp::And(_) => "and",
2616 BinOp::Or(_) => "or",
2617 // Nim's `and`/`or`/`xor` are bitwise on integers and logical on
2618 // bools, exactly as Rust's `&`/`|`/`^` are.
2619 BinOp::BitAnd(_) | BinOp::BitAndAssign(_) => "and",
2620 BinOp::BitOr(_) | BinOp::BitOrAssign(_) => "or",
2621 BinOp::BitXor(_) | BinOp::BitXorAssign(_) => "xor",
2622 // Settled empirically: Nim's `shr` on a signed integer is
2623 // arithmetic, matching Rust. See DESIGN.md.
2624 BinOp::Shl(_) | BinOp::ShlAssign(_) => "shl",
2625 BinOp::Shr(_) | BinOp::ShrAssign(_) => "shr",
2626 BinOp::Eq(_) => "==",
2627 BinOp::Ne(_) => "!=",
2628 BinOp::Lt(_) => "<",
2629 BinOp::Le(_) => "<=",
2630 BinOp::Gt(_) => ">",
2631 BinOp::Ge(_) => ">=",
2632 other => return Err(format!("unsupported binary operator {other:?}")),
2633 })
2634 }
2635
2636 fn cast(&mut self, c: &syn::ExprCast) -> Result<Val, String> {
2637 let v = self.expr(&c.expr)?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2638 let to = self.map_ty(&c.ty)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2639 let from = v.ty.clone().ok_or_else(|| {
2640 format!(
2641 "cannot lower `as {}`: the source type is unknown, and `as` \
2642 truncates, so the source width decides the result",
2643 to.render()
2644 )
2645 })?;
2646
2647 let code = match (&from, &to) {
2648 (f, t) if f.is_integer() && t.is_integer() => {
2649 // Rust's `as` between integers is a pure bit-width truncation
2650 // or sign-extension — never a range check. Nim's `T(x)` *does*
2651 // range-check and would raise where Rust wraps, so `cast` is
2652 // the only faithful spelling. Probed against both compilers.
2653 format!("cast[{}]({})", t.render(), v.code)
2654 }
2655 (f, Nim::Prim(p)) if f.is_integer() && (p == "float64" || p == "float32") => {
2656 format!("{}({})", p, v.code)
2657 }
2658 (Nim::Prim(b), t) if b == "bool" && t.is_integer() => {
2659 format!("{}(ord({}))", t.render(), v.code)
2660 }
2661 (Nim::Prim(r), t) if r == "Rune" && t.is_integer() => {
2662 format!("cast[{}](int32({}))", t.render(), v.code)
2663 }
2664 (f, Nim::Prim(r)) if f.is_integer() && r == "Rune" => {
2665 format!("Rune(int32({}))", v.code)
2666 }
2667 (Nim::Prim(a), Nim::Prim(b)) if a == b => v.code.clone(),
2668 (f, t) if matches!(f, Nim::Prim(p) if p.starts_with("float")) && t.is_integer() => {
2669 // Rust saturates float->int casts; Nim rounds and range-errors.
2670 // Not the same operation, so it is refused rather than mapped.
2671 return Err(format!(
2672 "`as {}` from a float: Rust saturates, Nim rounds and range-checks; \
2673 no faithful mapping is implemented",
2674 t.render()
2675 ));
2676 }
2677 (f, t) => {
2678 return Err(format!(
2679 "unsupported cast from `{}` to `{}`",
2680 f.render(),
2681 t.render()
2682 ))
2683 }
2684 };
2685 Ok(Val::new(code, Some(to)))
2686 }
2687
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2688 /// Rust's `?`: return early on the error branch, otherwise yield the value.
2689 ///
2690 /// The early return is statements, not an expression, so they are emitted
2691 /// ahead of the line being built. Every caller lowers its sub-expressions
2692 /// 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 18h ago2693 /// The container, start offset, length and element type an expression
2694 /// denotes as a slice. A window alias contributes its own offset, so
2695 /// `dst.get_mut(..n)` followed by `.chunks_exact_mut(2)` indexes straight
2696 /// into the original buffer rather than through a rebuilt view.
2697 fn slice_parts(
2698 &mut self,
2699 e: &Expr,
2700 ) -> Result<(String, String, String, Option<Nim>), String> {
2701 if let Some(Alias::Window { code, off, len, elem }) = self.window_of(e) {
2702 return Ok((code, off, len, elem));
2703 }
2704 let v = self.expr(e)?;
2705 let len = format!("{}.len", v.code);
2706 Ok((v.code, "0".to_string(), len, elem_of(&v.ty)))
2707 }
2708
2709 /// Expand `opt.map(|x| body)` / `res.and_then(|x| body)` inline.
2710 fn map_closure(
2711 &mut self,
2712 what: &str,
2713 recv: &Val,
2714 kind: &str,
2715 targs: &[Nim],
2716 c: &syn::ExprClosure,
2717 ) -> Result<Val, String> {
2718 if c.capture.is_some() {
2719 return Err("a `move` closure captures by value; Nim's closures \
2720 capture by reference, and the two are not the same"
2721 .into());
2722 }
2723 if c.inputs.len() != 1 {
2724 return Err(format!("`.{what}()` takes a one-argument closure"));
2725 }
2726 let pname = match &c.inputs[0] {
2727 Pat::Ident(i) => i.ident.to_string(),
2728 Pat::Wild(_) => "unused0".into(),
2729 _ => return Err("only plain identifier closure parameters are supported".into()),
2730 };
2731
2732 let is_opt = kind == "Option";
2733 let tmp = self.fresh("Map");
2734 let recv_ty = Nim::Named(kind.to_string(), targs.to_vec());
2735 self.line(&format!("let {}: {} = {}", tmp, recv_ty.render(), recv.code));
2736
2737 let body = match &*c.body {
2738 Expr::Block(b) => single_expr(&b.block)
2739 .ok_or("a closure body with statements is not implemented yet")?,
2740 other => other,
2741 };
2742 self.push_scope();
2743 // The parameter names the payload itself, so a view stays a view.
2744 self.bind_alias(
2745 &pname,
2746 Alias::Value {
2747 code: format!("{}.val", tmp),
2748 ty: Some(targs[0].clone()),
2749 },
2750 );
2751 let v = self.expr(body)?;
2752 self.pop_scope();
2753
2754 let inner = v
2755 .ty
2756 .clone()
2757 .ok_or_else(|| format!("cannot infer the result type of `.{what}()`"))?;
2758 // `and_then`'s closure already returns the wrapped type; `map`'s does
2759 // not and has to be re-wrapped.
2760 let (test, some_branch, none_branch, out_ty) = if is_opt {
2761 let out = if what == "map" {
2762 Nim::Named("Option".into(), vec![inner.clone()])
2763 } else {
2764 inner.clone()
2765 };
2766 let body_code = if what == "map" {
2767 format!("rsSome[{}]({})", inner.render(), v.code)
2768 } else {
2769 v.code.clone()
2770 };
2771 (
2772 format!("{}.has", tmp),
2773 body_code,
2774 format!("rsNone[{}]()", elem_arg(&out).render()),
2775 out,
2776 )
2777 } else {
2778 let e = targs[1].clone();
2779 let out = if what == "map" {
2780 Nim::Named("Result".into(), vec![inner.clone(), e.clone()])
2781 } else {
2782 inner.clone()
2783 };
2784 let ok_ty = elem_arg(&out);
2785 let body_code = if what == "map" {
2786 format!("rsOk[{}, {}]({})", inner.render(), e.render(), v.code)
2787 } else {
2788 v.code.clone()
2789 };
2790 (
2791 format!("{}.ok", tmp),
2792 body_code,
2793 format!("rsErr[{}, {}]({}.err)", ok_ty.render(), e.render(), tmp),
2794 out,
2795 )
2796 };
2797 Ok(Val::new(
2798 format!("(if {}: {} else: {})", test, some_branch, none_branch),
2799 Some(out_ty),
2800 ))
2801 }
2802
2803 /// `|x| x + 1` -> a Nim anonymous proc.
2804 ///
2805 /// Nim's closures capture by reference, as Rust's non-`move` closures do.
2806 /// A `move` closure captures by value, which is a different thing, so it
2807 /// is rejected rather than lowered to the same construct.
2808 fn closure(&mut self, c: &syn::ExprClosure, expect: Option<&Nim>) -> Result<Val, String> {
2809 if c.capture.is_some() {
2810 return Err("a `move` closure captures by value; Nim's closures \
2811 capture by reference, and the two are not the same"
2812 .into());
2813 }
2814 let want: Option<&Vec<Nim>> = match expect {
2815 Some(Nim::Proc(a, _)) => Some(a),
2816 _ => None,
2817 };
2818
2819 self.push_scope();
2820 let mut parts = Vec::new();
2821 let mut ptys = Vec::new();
2822 for (i, p) in c.inputs.iter().enumerate() {
2823 let (name, ann) = match p {
2824 Pat::Ident(id) => (id.ident.to_string(), None),
2825 Pat::Type(t) => match &*t.pat {
2826 Pat::Ident(id) => (id.ident.to_string(), Some(self.map_ty(&t.ty)?)),
2827 _ => return Err("only plain identifier closure parameters are supported".into()),
2828 },
2829 Pat::Wild(_) => (format!("unused{i}"), None),
2830 _ => return Err("only plain identifier closure parameters are supported".into()),
2831 };
2832 let t = ann
2833 .or_else(|| want.and_then(|w| w.get(i).cloned()))
2834 .ok_or_else(|| {
2835 format!(
2836 "cannot infer the type of closure parameter `{name}`; \
2837 annotate it"
2838 )
2839 })?;
2840 parts.push(format!("{}: {}", ident(&name), t.render()));
2841 self.bind(&name, t.clone());
2842 ptys.push(t);
2843 }
2844
2845 let ret_ann = match &c.output {
2846 ReturnType::Default => None,
2847 ReturnType::Type(_, t) => Some(self.map_ty(t)?.owned()),
2848 };
2849 let body = match &*c.body {
2850 Expr::Block(b) => single_expr(&b.block)
2851 .ok_or("a closure body with statements is not implemented yet")?,
2852 other => other,
2853 };
2854 let v = self.expr_at(body, ret_ann.as_ref())?;
2855 self.pop_scope();
2856
2857 let ret = ret_ann
2858 .or_else(|| v.ty.clone())
2859 .ok_or("cannot infer a closure's return type; annotate it")?;
2860 Ok(Val::new(
2861 format!("(proc ({}): {} = {})", parts.join(", "), ret.render(), v.code),
2862 Some(Nim::Proc(ptys, Box::new(ret))),
2863 ))
2864 }
2865
2866 /// Lower a block's statements at the current indentation, without opening
2867 /// a Nim `block:` -- used for `unsafe { .. }`, which introduces no scope
2868 /// of its own in the generated code.
2869 fn nested_block_flat(&mut self, b: &syn::Block) -> Result<(), String> {
2870 self.push_scope();
2871 let tail = self.block_body(b)?;
2872 self.emit_tail(tail);
2873 self.pop_scope();
2874 Ok(())
2875 }
2876
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2877 fn try_op(&mut self, t: &syn::ExprTry) -> Result<Val, String> {
2878 if self.in_loop_cond {
2879 return Err("`?` in a loop condition is not implemented yet: the \
2880 early-return it expands to would be evaluated once, \
2881 before the loop, rather than on each iteration"
2882 .into());
2883 }
2884 let v = self.expr(&t.expr)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2885 if let (Some(guard), Some(w)) = (v.guard.clone(), v.window.clone()) {
2886 // An `Option`/`Result` of a view: the check is emitted here and the
2887 // view itself survives as an alias, since it has no value form.
2888 let ret = self.ret.clone().ok_or("`?` outside a function with a return type")?;
2889 let err = v.guard_err.clone().ok_or(
2890 "`?` on a `get`/`get_mut` needs an `ok_or` to say what the error is",
2891 )?;
2892 let Nim::Named(n, ra) = &ret else {
2893 return Err(format!("`?` in a function returning `{}`", ret.render()));
2894 };
2895 if n != "Result" || ra.len() != 2 {
2896 return Err(format!("`?` in a function returning `{}`", ret.render()));
2897 }
2898 self.line(&format!("if not {}:", guard));
2899 self.line(&format!(
2900 " return rsErr[{}, {}]({})",
2901 ra[0].render(),
2902 ra[1].render(),
2903 err
2904 ));
2905 let mut out = Val::new(String::new(), None);
2906 out.window = Some(w);
2907 return Ok(out);
2908 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2909 let vt = v.ty.clone().ok_or(
2910 "`?` needs a known `Result`/`Option` type; annotate the expression it applies to",
2911 )?;
2912 let ret = self
2913 .ret
2914 .clone()
2915 .ok_or("`?` outside a function with a return type")?;
2916 let tmp = self.fresh("Try");
2917 self.line(&format!("let {}: {} = {}", tmp, vt.render(), v.code));
2918
2919 match (&vt, &ret) {
2920 (Nim::Named(a, ai), Nim::Named(b, bi))
2921 if a == "Result" && b == "Result" && ai.len() == 2 && bi.len() == 2 =>
2922 {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2923 // Rust inserts a `From::from` on the error here. Where the
2924 // types differ we call the crate's own `impl From`; we never
2925 // assume the conversion is the identity.
2926 let err = if ai[1] == bi[1] {
2927 format!("{}.err", tmp)
2928 } else {
2929 let key = (type_name(&ai[1]), type_name(&bi[1]));
2930 let f = self.from_impls.get(&key).cloned().ok_or_else(|| {
2931 format!(
2932 "`?` needs `From<{}> for {}` to convert the error, and \
2933 no such `impl` is in scope; assuming the conversion is \
2934 the identity would be a guess",
2935 key.0, key.1
2936 )
2937 })?;
2938 format!("{}({}.err)", f, tmp)
2939 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2940 self.line(&format!("if not {}.ok:", tmp));
2941 self.line(&format!(
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2942 " return rsErr[{}, {}]({})",
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2943 bi[0].render(),
2944 bi[1].render(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2945 err
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2946 ));
2947 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
2948 }
2949 (Nim::Named(a, ai), Nim::Named(b, bi))
2950 if a == "Option" && b == "Option" && ai.len() == 1 && bi.len() == 1 =>
2951 {
2952 self.line(&format!("if not {}.has:", tmp));
2953 self.line(&format!(" return rsNone[{}]()", bi[0].render()));
2954 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
2955 }
2956 _ => Err(format!(
2957 "`?` on `{}` in a function returning `{}` is not a supported \
2958 combination",
2959 vt.render(),
2960 ret.render()
2961 )),
2962 }
2963 }
2964
2965 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 19h ago2966 let Expr::Path(p) = &*c.func else {
2967 return Err("only calls to named functions are supported".into());
2968 };
2969 let name = path_name(&p.path);
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2970 let target = self.resolve_fn(&p.path);
2971 let ptys: Vec<Nim> = target
2972 .as_ref()
2973 .and_then(|k| self.fns.get(k))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2974 .map(|s| s.params.clone())
2975 .unwrap_or_default();
2976 let mut args = Vec::new();
2977 for (i, a) in c.args.iter().enumerate() {
2978 let want = ptys.get(i).cloned();
2979 args.push(self.expr_at(a, want.as_ref())?);
2980 }
2981 let codes: Vec<String> = args.iter().map(|a| a.code.clone()).collect();
2982
2983 // Constructors from the prelude.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2984 // `Ok`/`Err` must name the *whole* Result type, not just the half
2985 // being constructed: Nim cannot infer `E` from an `Ok(v)` alone.
2986 match name.as_str() {
2987 "Some" => {
2988 let inner = match expect {
2989 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].render(),
2990 _ => {
2991 return Err("`Some(..)` needs a known `Option<T>` type here; \
2992 annotate the binding or the return type"
2993 .into())
2994 }
2995 };
2996 return Ok(Val::new(
2997 format!("rsSome[{}]({})", inner, codes.join(", ")),
2998 expect.cloned(),
2999 ));
3000 }
3001 "Ok" | "Err" => {
3002 let (t, e) = match expect {
3003 Some(Nim::Named(n, a)) if n == "Result" && a.len() == 2 => {
3004 (a[0].render(), a[1].render())
3005 }
3006 _ => {
3007 return Err(format!(
3008 "`{name}(..)` needs a known `Result<T, E>` type here; \
3009 annotate the binding or the return type"
3010 ))
3011 }
3012 };
3013 let ctor = if name == "Ok" { "rsOk" } else { "rsErr" };
3014 let arg = if codes.is_empty() { String::new() } else { codes.join(", ") };
3015 return Ok(Val::new(
3016 format!("{}[{}, {}]({})", ctor, t, e, arg),
3017 expect.cloned(),
3018 ));
3019 }
3020 _ => {}
3021 }
3022
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3023 // `core::str::from_utf8_unchecked(b)` reinterprets a byte view as a
3024 // string view; no copy, no validation, same memory.
3025 if name == "from_utf8_unchecked" && codes.len() == 1 {
3026 return Ok(Val::new(
3027 format!("rsStrView({})", codes[0]),
3028 Some(Nim::OpenArray(Box::new(Nim::Prim("char".into())))),
3029 ));
3030 }
3031
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3032 // A tuple enum variant applied to arguments: `Shape::Circle(1.0)`.
3033 if let Some((def, v)) = self.resolve_variant(&p.path) {
3034 return Ok(Val::new(
3035 format!("{}({})", def.ctor_ident(&v), codes.join(", ")),
3036 Some(Nim::Named(def.name.clone(), vec![])),
3037 ));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3038 }
3039
3040 // A bare path that names a primitive type is Rust's tuple-struct-like
3041 // conversion, e.g. `String::from(..)`; handled by the method path.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3042 // Calling a proc-typed local, which is how an `impl Fn(..)` parameter
3043 // is invoked.
3044 if let Some(Nim::Proc(_, ret)) = self.lookup(&name) {
3045 return Ok(Val::new(
3046 format!("{}({})", ident(&name), codes.join(", ")),
3047 Some((*ret).clone()),
3048 ));
3049 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3050 let ret = target.as_ref().and_then(|k| self.fns.get(k)).map(|s| s.ret.clone());
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3051 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 19h ago3052 return Err(format!(
3053 "call to unknown function `{name}`; only functions defined in \
3054 this file and the supported standard-library subset can be lowered"
3055 ));
3056 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3057 let nim = match &target {
3058 Some((m, n)) => self.fn_name(m, n),
3059 None => ident(&name),
3060 };
3061 Ok(Val::new(format!("{}({})", nim, codes.join(", ")), ret))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3062 }
3063
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3064 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 19h ago3065 let name = m.method.to_string();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3066 if let Some(Alias::Window { len, .. }) = self.window_of(&m.receiver) {
3067 match name.as_str() {
3068 "len" => {
3069 return Ok(Val::new(format!("uint({})", len), Some(Nim::Prim("uint".into()))))
3070 }
3071 "is_empty" => {
3072 return Ok(Val::new(format!("({} == 0)", len), Some(Nim::Prim("bool".into()))))
3073 }
3074 other => {
3075 return Err(format!(
3076 "`.{other}()` on a slice window from `chunks_exact`/\
3077 `windows` is not implemented; only indexing and \
3078 `len()` are"
3079 ))
3080 }
3081 }
3082 }
3083 let recv = self.expr(&m.receiver)?;
3084 let rt0 = recv.ty.clone();
3085
3086// `s.get(a..b)` / `s.get_mut(a..b)`: an `Option<&[T]>`. Nim has no
3087 // way to put a view in an object, so instead of materialising an
3088 // Option the view and its validity condition travel together until
3089 // an `ok_or`/`?`/`unwrap` resolves them.
3090 if matches!(name.as_str(), "get" | "get_mut")
3091 && matches!(m.args.first(), Some(Expr::Range(_)))
3092 {
3093 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 18h ago3094 let (code, base, blen, belem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3095 let lo = match &r.start {
3096 Some(e) => format!("int({})", self.expr(e)?.code),
3097 None => "0".into(),
3098 };
3099 let len = match (&r.end, r.limits) {
3100 (Some(e), syn::RangeLimits::HalfOpen(_)) => {
3101 format!("(int({}) - {})", self.expr(e)?.code, lo)
3102 }
3103 (Some(e), syn::RangeLimits::Closed(_)) => {
3104 format!("(int({}) - {} + 1)", self.expr(e)?.code, lo)
3105 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3106 (None, _) => format!("({} - {})", blen, lo),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3107 };
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3108 // Hoisted, so the bounds are computed once -- as Rust computes
3109 // them once -- and cannot be re-evaluated later in a scope where
3110 // the names they mention have been shadowed by a loop pattern.
3111 let off_t = self.fresh("Off");
3112 let len_t = self.fresh("Len");
3113 self.line(&format!("let {}: int = {} + {}", off_t, base, lo));
3114 self.line(&format!("let {}: int = {}", len_t, len));
3115 let elem = belem
3116 .or_else(|| elem_of(&rt0))
3117 .ok_or("cannot infer the element type of this slice")?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3118 let mut v = Val::new(
3119 String::new(),
3120 Some(Nim::Named(
3121 "Option".into(),
3122 vec![Nim::OpenArray(Box::new(elem.clone()))],
3123 )),
3124 );
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3125 v.guard = Some(format!("({} + {} <= {})", off_t, len_t, blen));
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3126 v.window = Some(Alias::Window {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3127 code,
3128 off: off_t,
3129 len: len_t,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3130 elem: Some(elem),
3131 });
3132 return Ok(v);
3133 }
3134
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3135 // `.map`/`.and_then` over an `Option`/`Result` take a closure whose
3136 // parameter type comes from the receiver, so they are handled before
3137 // the arguments are lowered. The closure is expanded inline, with its
3138 // parameter aliased to the payload: that keeps the whole thing an
3139 // expression and avoids handing a view to a generic proc.
3140 if matches!(name.as_str(), "map" | "and_then") && m.args.len() == 1 {
3141 if let (Some(Nim::Named(kind, targs)), Expr::Closure(c)) =
3142 (recv.ty.clone(), &m.args[0])
3143 {
3144 if (kind == "Option" && targs.len() == 1) || (kind == "Result" && targs.len() == 2)
3145 {
3146 return self.map_closure(&name, &recv, &kind, &targs, c);
3147 }
3148 }
3149 }
3150
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3151 // `x.wrapping_add(1)` and `x.min(3)` take an argument of the receiver's
3152 // own type; `v.push(e)` takes the element type.
3153 let arg_want = match (name.as_str(), &recv.ty) {
3154 ("push", Some(Nim::Seq(t))) | ("push", Some(Nim::OpenArray(t))) => Some((**t).clone()),
3155 (_, t) => t.clone(),
3156 };
3157 let mut args = Vec::new();
3158 for a in &m.args {
3159 args.push(self.expr_at(a, arg_want.as_ref())?);
3160 }
3161 let a0 = args.first().map(|a| a.code.clone());
3162 let rt = recv.ty.clone();
3163
3164 let (code, ty) = match name.as_str() {
3165 // Rust's `len()` is `usize`; Nim's is `int`. The conversion is
3166 // explicit so that a `usize` binding type-checks on the Nim side.
3167 "len" => (format!("uint({}.len)", recv.code), Some(Nim::Prim("uint".into()))),
3168 "is_empty" => (format!("({}.len == 0)", recv.code), Some(Nim::Prim("bool".into()))),
3169 "push" => (format!("{}.add({})", recv.code, a0.unwrap_or_default()), Some(Nim::Unit)),
3170 "clone" | "to_vec" | "to_owned" | "as_slice" | "as_ref" | "as_mut" | "iter"
3171 | "into_iter" => (recv.code.clone(), rt.clone()),
3172 "unwrap" | "expect" => {
3173 let inner = match &rt {
3174 Some(Nim::Named(n, a)) if (n == "Option" && a.len() == 1) || (n == "Result" && a.len() == 2) => {
3175 Some(a[0].clone())
3176 }
3177 _ => None,
3178 };
3179 (format!("unwrap({})", recv.code), inner)
3180 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3181 "ok_or" if recv.guard.is_some() => {
3182 let e = args.first().ok_or("`ok_or` takes one argument")?;
3183 let ety = e.ty.clone();
3184 let mut v = recv.clone();
3185 v.guard_err = Some(e.code.clone());
3186 v.ty = match (&recv.ty, ety) {
3187 (Some(Nim::Named(_, a)), Some(et)) if a.len() == 1 => {
3188 Some(Nim::Named("Result".into(), vec![a[0].clone(), et]))
3189 }
3190 _ => None,
3191 };
3192 return Ok(v);
3193 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3194 "ok_or" => {
3195 let inner = match &rt {
3196 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].clone(),
3197 _ => return Err("`ok_or` needs a known `Option<T>` receiver".into()),
3198 };
3199 let e = args.first().ok_or("`ok_or` takes one argument")?;
3200 let ety = e
3201 .ty
3202 .clone()
3203 .ok_or("`ok_or` needs a known error type for its argument")?;
3204 (
3205 format!(
3206 "rsOkOr[{}, {}]({}, {})",
3207 inner.render(),
3208 ety.render(),
3209 recv.code,
3210 e.code
3211 ),
3212 Some(Nim::Named("Result".into(), vec![inner, ety])),
3213 )
3214 }
3215 "unwrap_or" => {
3216 let inner = match &rt {
3217 Some(Nim::Named(n, a)) if (n == "Option" && a.len() == 1) || (n == "Result" && a.len() == 2) => {
3218 Some(a[0].clone())
3219 }
3220 _ => None,
3221 };
3222 (
3223 format!("unwrapOr({}, {})", recv.code, a0.unwrap_or_default()),
3224 inner,
3225 )
3226 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3227 "is_some" => (format!("{}.has", recv.code), Some(Nim::Prim("bool".into()))),
3228 "is_none" => (format!("(not {}.has)", recv.code), Some(Nim::Prim("bool".into()))),
3229 "is_ok" => (format!("{}.ok", recv.code), Some(Nim::Prim("bool".into()))),
3230 "is_err" => (format!("(not {}.ok)", recv.code), Some(Nim::Prim("bool".into()))),
3231
3232 // Settled empirically: Nim's fixed-width *unsigned* arithmetic
3233 // wraps silently, matching Rust's `wrapping_*`. For *signed* types
3234 // Nim raises OverflowDefect, so the operation is routed through
3235 // the unsigned view of the same width, which is what Rust's
3236 // wrapping_* is defined to compute.
3237 "wrapping_add" | "wrapping_sub" | "wrapping_mul" => {
3238 let op = match name.as_str() {
3239 "wrapping_add" => "+",
3240 "wrapping_sub" => "-",
3241 _ => "*",
3242 };
3243 let t = rt.clone().ok_or_else(|| {
3244 format!("`{name}` needs a known receiver type to pick the wrapping width")
3245 })?;
3246 if !t.is_integer() {
3247 return Err(format!("`{name}` on a non-integer type"));
3248 }
3249 let arg = a0.ok_or_else(|| format!("`{name}` takes one argument"))?;
3250 if t.is_unsigned() {
3251 (format!("({} {} {})", recv.code, op, arg), Some(t))
3252 } else {
3253 let u = unsigned_peer(&t)?;
3254 (
3255 format!(
3256 "cast[{}](cast[{}]({}) {} cast[{}]({}))",
3257 t.render(), u, recv.code, op, u, arg
3258 ),
3259 Some(t),
3260 )
3261 }
3262 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3263 // Inside a formatting impl, a write through the `Formatter` *is*
3264 // the value the proc returns, so it lowers to the string written.
3265 "write_str" | "write_char" if self.is_fmt_param(&m.receiver) => (
3266 a0.ok_or("`write_str` takes one argument")?,
3267 Some(Nim::Prim("string".into())),
3268 ),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3269 "abs" => (format!("abs({})", recv.code), rt.clone()),
3270 "min" => (format!("min({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
3271 "max" => (format!("max({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
3272 "to_string" => (format!("rsDisplay({})", recv.code), Some(Nim::Prim("string".into()))),
3273 "as_bytes" | "into_bytes" => (
3274 format!("rsBytes({})", recv.code),
3275 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
3276 ),
3277
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3278 "into" => {
3279 // `.into()` resolves through the `impl From` declarations, and
3280 // needs the target type to pick one.
3281 let from = rt
3282 .clone()
3283 .ok_or("`.into()` needs a known receiver type")?;
3284 let to = expect
3285 .ok_or("`.into()` needs a known target type; annotate the binding")?;
3286 let key = (type_name(&from), type_name(to));
3287 let f = self.from_impls.get(&key).cloned().ok_or_else(|| {
3288 format!(
3289 "no `impl From<{}> for {}` in this file, so `.into()` has \
3290 no conversion to call",
3291 key.0, key.1
3292 )
3293 })?;
3294 (format!("{}({})", f, recv.code), Some(to.clone()))
3295 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3296 _ => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3297 // A method defined in this file via `impl`, found by the
3298 // receiver's type rather than by name alone.
3299 let key = rt.as_ref().map(|t| (type_name(t), name.clone()));
3300 let sig = key.and_then(|k| self.methods.get(&k)).map(|s| s.ret.clone());
3301 if let Some(ret) = sig {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3302 let mut all = vec![recv.code.clone()];
3303 all.extend(args.iter().map(|a| a.code.clone()));
3304 (format!("{}({})", ident(&name), all.join(", ")), Some(ret))
3305 } else {
3306 return Err(format!(
3307 "unsupported method `.{name}()`; it is neither defined in \
3308 this file nor part of the standard-library subset that \
3309 has a verified Nim equivalent"
3310 ));
3311 }
3312 }
3313 };
3314 Ok(Val::new(code, ty))
3315 }
3316
3317 // -------------------------------------------------------------- macros
3318
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3319 /// The element type of a `vec![..]`, from its first element.
3320 fn vec_elem(&mut self, mac: &syn::Macro) -> Result<Option<Nim>, String> {
3321 let body = mac.tokens.to_string();
3322 if body.trim().is_empty() {
3323 return Ok(None);
3324 }
3325 let first: Option<Expr> = if body.contains(';') {
3326 // The whole body must be consumed or the parse fails, so the
3327 // length is parsed too even though only the element is wanted.
3328 mac.parse_body_with(|input: syn::parse::ParseStream| {
3329 let v: Expr = input.parse()?;
3330 input.parse::<syn::Token![;]>()?;
3331 let _len: Expr = input.parse()?;
3332 Ok(v)
3333 })
3334 .ok()
3335 } else {
3336 mac.parse_body_with(
3337 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
3338 )
3339 .ok()
3340 .and_then(|p| p.into_iter().next())
3341 };
3342 match first {
3343 Some(e) => Ok(self.expr(&e)?.ty),
3344 None => Ok(None),
3345 }
3346 }
3347
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3348 fn macro_call(&mut self, mac: &syn::Macro) -> Result<String, String> {
3349 let name = path_name(&mac.path);
3350 match name.as_str() {
3351 "println" | "print" | "eprintln" | "eprint" => {
3352 let s = self.format_args(mac)?;
3353 let nl = name.ends_with("ln");
3354 Ok(match (name.starts_with('e'), nl) {
3355 (false, true) => format!("echo {s}"),
3356 (false, false) => format!("stdout.write({s})"),
3357 (true, true) => format!("stderr.writeLine({s})"),
3358 (true, false) => format!("stderr.write({s})"),
3359 })
3360 }
3361 "format" => self.format_args(mac),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3362 "write" | "writeln" => {
3363 // `write!(f, "..", ..)` inside a formatting impl: the first
3364 // argument is the sink, the rest is an ordinary format call.
3365 let args: Vec<Expr> = mac
3366 .parse_body_with(syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated)
3367 .map_err(|e| format!("write!: {e}"))?
3368 .into_iter()
3369 .collect();
3370 let sink = args.first().ok_or("`write!` needs a sink")?;
3371 if !self.is_fmt_param(sink) {
3372 return Err("`write!` to anything but the `Formatter` of the \
3373 enclosing formatting impl is not implemented"
3374 .into());
3375 }
3376 let s = self.format_pieces(&args[1..])?;
3377 Ok(if name == "writeln" {
3378 format!("({} & \"\\n\")", s)
3379 } else {
3380 s
3381 })
3382 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3383 "panic" => {
3384 let s = self.format_args(mac)?;
3385 Ok(format!("rsPanic({s})"))
3386 }
3387 "assert" => {
3388 let e: Expr = mac.parse_body().map_err(|e| format!("assert!: {e}"))?;
3389 let v = self.expr(&e)?;
3390 Ok(format!(
3391 "(if not ({}): rsPanic(\"assertion failed\"))",
3392 v.code
3393 ))
3394 }
3395 "vec" => {
3396 let body = mac.tokens.to_string();
3397 if body.trim().is_empty() {
3398 return Ok("@[]".into());
3399 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3400 // `vec![elem; n]` is the repeat form, not a list. The macro
3401 // body has no brackets, so it is parsed directly.
3402 if body.contains(';') {
3403 let (v, n) = mac
3404 .parse_body_with(|input: syn::parse::ParseStream| {
3405 let v: Expr = input.parse()?;
3406 input.parse::<syn::Token![;]>()?;
3407 let n: Expr = input.parse()?;
3408 Ok((v, n))
3409 })
3410 .map_err(|e| format!("vec![elem; n]: {e}"))?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3411 let want = self.vec_expect.clone();
3412 let v = self.expr_at(&v, want.as_ref())?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3413 let n = self.expr(&n)?;
3414 return Ok(format!("newSeqWith(int({}), {})", n.code, v.code));
3415 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3416 let elems: syn::punctuated::Punctuated<Expr, syn::Token![,]> = mac
3417 .parse_body_with(syn::punctuated::Punctuated::parse_terminated)
3418 .map_err(|e| format!("vec!: {e}"))?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3419 let want = self.vec_expect.clone();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3420 let mut parts = Vec::new();
3421 for e in &elems {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3422 parts.push(self.expr_at(e, want.as_ref())?.code);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3423 }
3424 Ok(format!("@[{}]", parts.join(", ")))
3425 }
3426 other => Err(format!(
3427 "unsupported macro `{other}!`; a macro whose expansion is not \
3428 known cannot be lowered faithfully"
3429 )),
3430 }
3431 }
3432
3433 /// `println!("{} {}", a, b)` -> a Nim string-concatenation expression.
3434 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 18h ago3435 let args: Vec<Expr> = mac
3436 .parse_body_with(syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated)
3437 .map_err(|e| format!("format arguments: {e}"))?
3438 .into_iter()
3439 .collect();
3440 self.format_pieces(&args)
3441 }
3442
3443 /// `["{} {}", a, b]` -> a Nim string-concatenation expression.
3444 fn format_pieces(&mut self, args: &[Expr]) -> Result<String, String> {
3445 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 19h ago3446 if args.is_empty() {
3447 return Ok("\"\"".into());
3448 }
3449 return Err("the first argument must be a literal format string".into());
3450 };
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3451 let rest: Vec<&Expr> = args[1..].iter().collect();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3452
3453 let pieces = fmt::parse(&s.value())?;
3454 let mut parts: Vec<String> = Vec::new();
3455 let mut next = 0usize;
3456 let mut used = vec![false; rest.len()];
3457 for p in &pieces {
3458 match p {
3459 fmt::Piece::Lit(l) => parts.push(fmt::nim_str(l)),
3460 fmt::Piece::Arg { r#ref, spec } => {
3461 let v = match r#ref {
3462 fmt::Ref::Next => {
3463 let e = rest.get(next).ok_or("too few arguments for format string")?;
3464 used[next] = true;
3465 next += 1;
3466 self.expr(e)?
3467 }
3468 fmt::Ref::Index(i) => {
3469 let e = rest.get(*i).ok_or("format index out of range")?;
3470 used[*i] = true;
3471 self.expr(e)?
3472 }
3473 fmt::Ref::Named(n) => {
3474 let t = self.lookup(n).ok_or_else(|| {
3475 format!("`{{{n}}}` captures `{n}`, which is not in scope")
3476 })?;
3477 Val::new(ident(n), Some(t))
3478 }
3479 };
3480 parts.push(fmt::render_arg(&v.code, spec));
3481 }
3482 }
3483 }
3484 // Rust rejects an argument that no `{}` consumes; so do we, rather
3485 // than dropping it from the output.
3486 if let Some(i) = used.iter().position(|u| !u) {
3487 return Err(format!(
3488 "argument {} is never used by the format string",
3489 i + 1
3490 ));
3491 }
3492 Ok(if parts.is_empty() { "\"\"".into() } else { parts.join(" & ") })
3493 }
3494}
3495
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3496/// Whether a pattern introduces a binding.
3497fn binds(p: &Pat) -> bool {
3498 match p {
3499 Pat::Ident(_) => true,
3500 Pat::Guard(g) => binds(&g.pat),
3501 Pat::Paren(x) => binds(&x.pat),
3502 Pat::Reference(r) => binds(&r.pat),
3503 Pat::Or(o) => o.cases.iter().any(binds),
3504 Pat::TupleStruct(t) => t.elems.iter().any(|_| true),
3505 Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_) => true,
3506 _ => false,
3507 }
3508}
3509
3510/// Whether a pattern looks inside the value, which a Nim `case` cannot do.
3511fn destructures(p: &Pat) -> bool {
3512 matches!(
3513 p,
3514 Pat::TupleStruct(_) | Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_)
3515 ) || matches!(p, Pat::Guard(g) if destructures(&g.pat))
3516 || matches!(p, Pat::Paren(x) if destructures(&x.pat))
3517 || matches!(p, Pat::Reference(r) if destructures(&r.pat))
3518}
3519
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3520/// Whether an expression has a direct Nim expression form.
3521///
3522/// Nim's `if` is an expression only when every arm is a single expression, and
3523/// its `case` is never one here. Anything else has to be lowered as statements
3524/// that assign into a target.
3525fn expressible(e: &Expr) -> bool {
3526 match e {
3527 Expr::If(i) => {
3528 let Some(then) = single_expr(&i.then_branch) else { return false };
3529 if !expressible(then) {
3530 return false;
3531 }
3532 match &i.else_branch {
3533 None => false,
3534 Some((_, els)) => match &**els {
3535 Expr::Block(b) => single_expr(&b.block).is_some_and(expressible),
3536 other => expressible(other),
3537 },
3538 }
3539 }
3540 Expr::Match(_) | Expr::Block(_) | Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => false,
3541 _ => true,
3542 }
3543}
3544
3545/// The single expression a block consists of, if that is all it is. An `if`
3546/// can only be lowered as a Nim `if`-expression when both arms are this shape.
3547fn single_expr(b: &syn::Block) -> Option<&Expr> {
3548 match (b.stmts.len(), b.stmts.first()) {
3549 (1, Some(Stmt::Expr(e, None))) => Some(e),
3550 _ => None,
3551 }
3552}
3553
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3554/// Substitute `params[i] -> args[i]` through a type. Enough of the type
3555/// grammar is covered to expand the aliases we accept; anything else is left
3556/// alone and will be reported by `ty::map` if it is unsupported.
3557fn substitute(t: &syn::Type, params: &[String], args: &[syn::Type]) -> syn::Type {
3558 use syn::Type;
3559 match t {
3560 Type::Path(p) => {
3561 if p.qself.is_none() && p.path.segments.len() == 1 {
3562 let seg = &p.path.segments[0];
3563 if seg.arguments.is_empty() {
3564 let name = seg.ident.to_string();
3565 if let Some(i) = params.iter().position(|x| *x == name) {
3566 return args[i].clone();
3567 }
3568 }
3569 }
3570 let mut p = p.clone();
3571 for seg in &mut p.path.segments {
3572 if let syn::PathArguments::AngleBracketed(a) = &mut seg.arguments {
3573 for g in &mut a.args {
3574 if let syn::GenericArgument::Type(t) = g {
3575 *t = substitute(t, params, args);
3576 }
3577 }
3578 }
3579 }
3580 Type::Path(p)
3581 }
3582 Type::Reference(r) => {
3583 let mut r = r.clone();
3584 r.elem = Box::new(substitute(&r.elem, params, args));
3585 Type::Reference(r)
3586 }
3587 Type::Slice(sl) => {
3588 let mut sl = sl.clone();
3589 sl.elem = Box::new(substitute(&sl.elem, params, args));
3590 Type::Slice(sl)
3591 }
3592 Type::Array(a) => {
3593 let mut a = a.clone();
3594 a.elem = Box::new(substitute(&a.elem, params, args));
3595 Type::Array(a)
3596 }
3597 Type::Tuple(tp) => {
3598 let mut tp = tp.clone();
3599 tp.elems = tp.elems.iter().map(|e| substitute(e, params, args)).collect();
3600 Type::Tuple(tp)
3601 }
3602 Type::Paren(p) => substitute(&p.elem, params, args),
3603 Type::Group(g) => substitute(&g.elem, params, args),
3604 other => other.clone(),
3605 }
3606}
3607
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3608// --------------------------------------------------------------- utilities
3609
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3610/// Whether a return type is a borrow of one of the arguments, which Nim
3611/// models with a view rather than with an owned copy.
3612fn returns_borrow(t: &syn::Type) -> bool {
3613 match t {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3614 syn::Type::Reference(r) => match &*r.elem {
3615 syn::Type::Slice(_) => true,
3616 // `&str` is a borrow of someone else's bytes too, and returning it
3617 // means returning a view, not an owned string.
3618 syn::Type::Path(p) => p.path.is_ident("str"),
3619 _ => false,
3620 },
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3621 syn::Type::Paren(p) => returns_borrow(&p.elem),
3622 syn::Type::Group(g) => returns_borrow(&g.elem),
3623 _ => false,
3624 }
3625}
3626
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3627/// The module a `use` prefix names. `crate`, `self` and `super` all resolve
3628/// to the crate root, which is where a flattened module's items live unless
3629/// they came from one of the extra input files.
3630fn module_of(prefix: &[String]) -> String {
3631 match prefix.last() {
3632 Some(m) if m != "crate" && m != "self" && m != "super" => m.clone(),
3633 _ => String::new(),
3634 }
3635}
3636
3637/// The first type argument of an `Option[T]` / `Result[T, E]`.
3638fn elem_arg(t: &Nim) -> Nim {
3639 match t {
3640 Nim::Named(_, a) if !a.is_empty() => a[0].clone(),
3641 other => other.clone(),
3642 }
3643}
3644
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3645/// The element type of a sequence-like Nim type.
3646fn elem_of(t: &Option<Nim>) -> Option<Nim> {
3647 match t {
3648 Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) | Some(Nim::Array(_, e)) => Some((**e).clone()),
3649 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
3650 _ => None,
3651 }
3652}
3653
3654/// The short name a Nim type is known by, for keying method tables.
3655fn type_name(t: &Nim) -> String {
3656 match t {
3657 Nim::Named(n, _) => n.clone(),
3658 Nim::Prim(p) => p.clone(),
3659 other => other.render(),
3660 }
3661}
3662
3663fn is_fmt_trait(t: &str) -> bool {
3664 matches!(t, "Display" | "Debug" | "LowerHex" | "UpperHex" | "Binary" | "Octal")
3665}
3666
3667/// The prelude proc a formatting trait's output is produced by.
3668fn fmt_proc(t: &str) -> &'static str {
3669 match t {
3670 "Display" => "rsDisplay",
3671 "Debug" => "rsDebug",
3672 "LowerHex" => "rsLowerHex",
3673 "UpperHex" => "rsUpperHex",
3674 "Binary" => "rsBinary",
3675 _ => "rsOctal",
3676 }
3677}
3678
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3679fn takes_self(sig: &syn::Signature) -> bool {
3680 matches!(sig.inputs.first(), Some(FnArg::Receiver(_)))
3681}
3682
3683fn path_name(p: &syn::Path) -> String {
3684 p.segments
3685 .last()
3686 .map(|s| s.ident.to_string())
3687 .unwrap_or_default()
3688}
3689
3690fn is_compound(op: &BinOp) -> bool {
3691 matches!(
3692 op,
3693 BinOp::AddAssign(_)
3694 | BinOp::SubAssign(_)
3695 | BinOp::MulAssign(_)
3696 | BinOp::DivAssign(_)
3697 | BinOp::RemAssign(_)
3698 | BinOp::BitAndAssign(_)
3699 | BinOp::BitOrAssign(_)
3700 | BinOp::BitXorAssign(_)
3701 | BinOp::ShlAssign(_)
3702 | BinOp::ShrAssign(_)
3703 )
3704}
3705
3706/// The Nim literal suffix for an integer type (`5'i32`).
3707fn nim_suffix(t: &Nim) -> Result<&'static str, String> {
3708 let Nim::Prim(p) = t else {
3709 return Err("not a primitive integer".into());
3710 };
3711 Ok(match p.as_str() {
3712 "int8" => "i8",
3713 "int16" => "i16",
3714 "int32" => "i32",
3715 "int64" => "i64",
3716 "int" => "i",
3717 "uint8" => "u8",
3718 "uint16" => "u16",
3719 "uint32" => "u32",
3720 "uint64" => "u64",
3721 "uint" => "u",
3722 other => return Err(format!("no Nim literal suffix for `{other}`")),
3723 })
3724}
3725
3726/// The unsigned integer type of the same width, used to spell `wrapping_*`.
3727fn unsigned_peer(t: &Nim) -> Result<&'static str, String> {
3728 let Nim::Prim(p) = t else {
3729 return Err("not a primitive integer".into());
3730 };
3731 Ok(match p.as_str() {
3732 "int8" => "uint8",
3733 "int16" => "uint16",
3734 "int32" => "uint32",
3735 "int64" => "uint64",
3736 "int" => "uint",
3737 other => return Err(format!("`{other}` has no unsigned peer")),
3738 })
3739}
3740
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3741fn quote_meta(m: &syn::Meta) -> String {
3742 match m {
3743 syn::Meta::Path(p) => path_name(p),
3744 syn::Meta::List(l) => format!("{}(..)", path_name(&l.path)),
3745 syn::Meta::NameValue(nv) => format!("{} = ..", path_name(&nv.path)),
3746 }
3747}
3748
3749fn item_attrs(i: &Item) -> &[syn::Attribute] {
3750 match i {
3751 Item::Fn(f) => &f.attrs,
3752 Item::Struct(s) => &s.attrs,
3753 Item::Enum(e) => &e.attrs,
3754 Item::Impl(x) => &x.attrs,
3755 Item::Const(c) => &c.attrs,
3756 Item::Type(t) => &t.attrs,
3757 Item::Mod(m) => &m.attrs,
3758 Item::Use(u) => &u.attrs,
3759 Item::ExternCrate(e) => &e.attrs,
3760 Item::Static(s) => &s.attrs,
3761 _ => &[],
3762 }
3763}
3764
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3765fn item_kind(i: &Item) -> &'static str {
3766 match i {
3767 Item::Trait(_) => "`trait`",
3768 Item::Static(_) => "`static`",
3769 Item::Macro(_) => "macro definition",
3770 Item::Union(_) => "`union`",
3771 Item::ForeignMod(_) => "`extern` block",
3772 _ => "item",
3773 }
3774}
3775
3776fn expr_kind(e: &Expr) -> &'static str {
3777 match e {
3778 Expr::Async(_) => "`async` block",
3779 Expr::Await(_) => "`.await`",
3780 Expr::Try(_) => "`?`",
3781 Expr::Range(_) => "range",
3782 Expr::Match(_) => "`match` (only statement position is implemented)",
3783 Expr::Let(_) => "`let` expression",
3784 Expr::Unsafe(_) => "`unsafe` block",
3785 Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => "loop (has no value in Nim)",
3786 _ => "expression",
3787 }
3788}