nandi/rustnimpublic Fork 0
afb2a6e152356d5a78d536ad75f005bb1fc7ed63
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 · 3965 lines · 163.6 KBRust Blame HistoryRaw
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h 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 8h 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 8h 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 8h 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 7h 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 8h 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 7h 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 8h 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 7h 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 8h 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 8h ago103 }
104}
105
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h 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 8h 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 8h 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 8h 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 8h 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 8h ago140 }
141 fn untyped(code: impl Into<String>) -> Self {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago142 Val::new(code, None)
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h 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 8h 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 8h 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 8h 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 7h 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 8h 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 8h 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 8h 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 7h 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 8h 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 8h 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 8h 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 8h 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 8h 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 8h 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 8h 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 8h ago252 alias_scopes: vec![HashMap::new()],
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago253 fns: HashMap::new(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago254 cur_mod: String::new(),
255 use_map: HashMap::new(),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago256 structs: HashMap::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago257 enums: HashMap::new(),
258 variant_owner: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h 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 7h ago263 vec_expect: None,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago264 forwards: Vec::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago265 aliases: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago266 modules: Vec::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago267 features: Vec::new(),
268 dropped_by_cfg: 0,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago269 ret: None,
270 target: None,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago271 in_loop_cond: false,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h 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 8h ago299 self.alias_scopes.push(HashMap::new());
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h 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 8h 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 8h 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 7h 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 8h 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 8h 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 7h 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 8h ago338 }
339
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h 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 7h 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 8h ago347 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h 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 7h 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 8h 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 7h 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 8h ago372 }
373
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h 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 8h 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 8h 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 7h ago399 Item::Use(u) => self.collect_use(&u.tree, &[]),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h 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 7h 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 8h ago452 fn collect(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h 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 8h 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 7h 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 8h 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 display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago477 // A field of `&[T]` / `&str` type is a borrow, and Nim's
478 // view types allow it as an object field, so it stays a
479 // view rather than being copied into a `seq`.
480 let t = self.map_ty(&f.ty)?;
481 let t = if returns_borrow(&f.ty) { t.unvar() } else { t.owned() };
482 fields.push((name, t));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago483 }
484 self.structs.insert(s.ident.to_string(), fields);
485 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago486 Item::Mod(m) if m.content.is_some() => {
487 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
488 for i in &items {
489 self.collect(i)?;
490 }
491 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago492 Item::Type(t) => {
493 let params: Vec<String> = t
494 .generics
495 .params
496 .iter()
497 .filter_map(|g| match g {
498 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
499 _ => None,
500 })
501 .collect();
502 self.aliases
503 .insert(t.ident.to_string(), (params, (*t.ty).clone()));
504 }
505 Item::Enum(e) => {
506 let name = e.ident.to_string();
507 if e.generics.params.iter().any(|p| !matches!(p, syn::GenericParam::Lifetime(_))) {
508 return Err(format!("`enum {name}` is generic: not implemented yet"));
509 }
510 let mut variants = Vec::new();
511 for v in &e.variants {
512 let vname = v.ident.to_string();
513 if v.discriminant.is_some() {
514 return Err(format!(
515 "`{name}::{vname}` has an explicit discriminant; Rust's \
516 `as` on such an enum has a value this lowering does not \
517 yet preserve"
518 ));
519 }
520 let mut fields = Vec::new();
521 for (i, f) in v.fields.iter().enumerate() {
522 // Nim requires the branches of a variant object to have
523 // distinct field names, so each is prefixed.
524 let fname = match &f.ident {
525 Some(id) => format!("{vname}_{id}"),
526 None => format!("{vname}_f{i}"),
527 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago528 let t = self.map_ty(&f.ty)?;
529 let t = if returns_borrow(&f.ty) { t.unvar() } else { t.owned() };
530 fields.push((fname, t));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago531 }
532 variants.push(Variant { name: vname, fields });
533 }
534 let simple = variants.iter().all(|v| v.fields.is_empty());
535 for v in &variants {
536 self.variant_owner
537 .entry(v.name.clone())
538 .or_default()
539 .push(name.clone());
540 }
541 self.enums.insert(
542 name.clone(),
543 EnumDef { name, simple, variants },
544 );
545 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago546 Item::Impl(im) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago547 let self_ty = self.map_ty(&im.self_ty)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago548 let tyname = type_name(&self_ty);
549 if let Some((path, _)) = &im.trait_ {
550 let tr = path_name(path);
551 if im.items.is_empty() {
552 // A marker trait with no items. We do not model trait
553 // resolution at all, so it generates nothing; any use
554 // that actually needed the trait (a `dyn`, a bound) is
555 // rejected where it appears.
556 return Ok(());
557 }
558 if is_fmt_trait(&tr) {
559 self.forwards.push(format!(
560 "proc {}*(self: {}): string",
561 fmt_proc(&tr),
562 self_ty.render()
563 ));
564 self.fmt_impls.insert((tyname, tr), ());
565 return Ok(());
566 }
567 if tr == "From" {
568 let syn::ImplItem::Fn(m) = &im.items[0] else {
569 return Err("`impl From` must contain `fn from`".into());
570 };
571 let (params, _) = self.signature(&m.sig)?;
572 let src = params
573 .first()
574 .ok_or("`fn from` takes one argument")?
575 .clone();
576 let name = format!("rsFrom{}{}", tyname, type_name(&src));
577 self.forwards.push(self.head_of(&name, &m.sig, None)?);
578 self.from_impls
579 .insert((type_name(&src), tyname), name);
580 return Ok(());
581 }
582 return Err(format!(
583 "`impl {tr} for {tyname}`: only formatting traits \
584 (Display, Debug, LowerHex, UpperHex, Binary, Octal), \
585 `From`, and marker traits with no items are implemented"
586 ));
587 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago588 for it in &im.items {
589 if let syn::ImplItem::Fn(m) = it {
590 let (mut params, ret) = self.signature(&m.sig)?;
591 if takes_self(&m.sig) {
592 params.insert(0, self_ty.clone());
593 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago594 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
595 let head = self.head_of(&m.sig.ident.to_string(), &m.sig, recv.as_ref())?;
596 self.forwards.push(head);
597 self.methods
598 .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 8h ago599 }
600 }
601 }
602 _ => {}
603 }
604 Ok(())
605 }
606
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago607 /// Whether `#[cfg(..)]` keeps this item, given the enabled features.
608 ///
609 /// This is evaluation, not approximation: rustc does the same thing, and
610 /// an item whose predicate is false is not part of the compiled program.
611 /// A predicate that cannot be evaluated is reported rather than assumed.
612 fn cfg_keeps(&self, attrs: &[syn::Attribute]) -> Result<bool, String> {
613 for a in attrs {
614 if a.path().is_ident("cfg") {
615 let pred: syn::Meta = a
616 .parse_args()
617 .map_err(|e| format!("cannot parse `#[cfg(..)]`: {e}"))?;
618 if !self.cfg_eval(&pred)? {
619 return Ok(false);
620 }
621 }
622 }
623 Ok(true)
624 }
625
626 fn cfg_eval(&self, m: &syn::Meta) -> Result<bool, String> {
627 match m {
628 syn::Meta::NameValue(nv) if nv.path.is_ident("feature") => {
629 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
630 return Err("`feature = ..` expects a string".into());
631 };
632 Ok(self.features.iter().any(|f| *f == s.value()))
633 }
634 syn::Meta::List(l) if l.path.is_ident("not") => {
635 let inner: syn::Meta = l.parse_args().map_err(|e| e.to_string())?;
636 Ok(!self.cfg_eval(&inner)?)
637 }
638 syn::Meta::List(l) if l.path.is_ident("all") || l.path.is_ident("any") => {
639 let items: syn::punctuated::Punctuated<syn::Meta, syn::Token![,]> = l
640 .parse_args_with(syn::punctuated::Punctuated::parse_terminated)
641 .map_err(|e| e.to_string())?;
642 let all = l.path.is_ident("all");
643 let mut acc = all;
644 for i in &items {
645 let v = self.cfg_eval(i)?;
646 acc = if all { acc && v } else { acc || v };
647 }
648 Ok(acc)
649 }
650 other => Err(format!(
651 "`#[cfg({})]` is not a predicate rustnim can evaluate; only \
652 `feature = \"..\"`, `not`, `all` and `any` are implemented",
653 quote_meta(other)
654 )),
655 }
656 }
657
658 /// Map a Rust type, expanding any `type` alias first. Every type in the
659 /// lowering goes through here rather than calling `ty::map` directly, so
660 /// an alias cannot be missed in one position and honoured in another.
661 fn map_ty(&self, t: &syn::Type) -> Result<Nim, String> {
662 ty::map(&self.expand(t, 0)?)
663 }
664
665 fn expand(&self, t: &syn::Type, depth: usize) -> Result<syn::Type, String> {
666 if depth > 16 {
667 return Err("type alias expansion did not terminate; is it cyclic?".into());
668 }
669 let syn::Type::Path(p) = t else { return Ok(t.clone()) };
670 // Only an unqualified name can be one of this file's aliases.
671 // `fmt::Result` and `core::result::Result` are different types that
672 // merely end in the same segment.
673 if p.path.segments.len() != 1 {
674 return Ok(t.clone());
675 }
676 let Some(seg) = p.path.segments.last() else { return Ok(t.clone()) };
677 let Some((params, target)) = self.aliases.get(&seg.ident.to_string()) else {
678 return Ok(t.clone());
679 };
680 let args: Vec<syn::Type> = match &seg.arguments {
681 syn::PathArguments::AngleBracketed(a) => a
682 .args
683 .iter()
684 .filter_map(|g| match g {
685 GenericArgument::Type(t) => Some(t.clone()),
686 _ => None,
687 })
688 .collect(),
689 _ => vec![],
690 };
691 if args.len() != params.len() {
692 // Flattening several files into one module can bring a crate's own
693 // alias (`type Result<T> = Result<T, Error>`) into scope at a site
694 // that meant the builtin (`Result<T, E>`). Rust kept them apart by
695 // module; here they are told apart by arity, and a use that fits
696 // neither is left for `ty::map` to report.
697 return Ok(t.clone());
698 }
699 self.expand(&substitute(target, params, &args), depth + 1)
700 }
701
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago702 /// The Nim name for a function, qualified by its module.
703 fn fn_name(&self, module: &str, name: &str) -> String {
704 if module.is_empty() {
705 ident(name)
706 } else {
707 format!("{}_{}", module, ident(name))
708 }
709 }
710
711 /// Resolve a call path to the module and name it refers to: an explicit
712 /// `mixed::decode`, then the current module, then the crate root.
713 fn resolve_fn(&self, path: &syn::Path) -> Option<(String, String)> {
714 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
715 let last = segs.last()?.clone();
716 if segs.len() >= 2 {
717 let q = &segs[segs.len() - 2];
718 if self.fns.contains_key(&(q.clone(), last.clone())) {
719 return Some((q.clone(), last));
720 }
721 }
722 let imported = self.use_map.get(&last).cloned();
723 for m in [Some(self.cur_mod.clone()), imported, Some(String::new())]
724 .into_iter()
725 .flatten()
726 {
727 if self.fns.contains_key(&(m.clone(), last.clone())) {
728 return Some((m, last));
729 }
730 }
731 None
732 }
733
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago734 /// The Nim `proc` head for a Rust signature, used both for the forward
735 /// declaration and for the definition, so the two cannot drift apart.
736 fn head_of(
737 &self,
738 name: &str,
739 sig: &syn::Signature,
740 recv: Option<&Nim>,
741 ) -> Result<String, String> {
742 let (ptys, ret) = self.signature(sig)?;
743 let mut parts = Vec::new();
744 if let Some(self_ty) = recv {
745 let mutable = matches!(
746 sig.inputs.first(),
747 Some(FnArg::Receiver(r))
748 if matches!(&r.kind, syn::ReceiverKind::Reference(_, _, m) if m.is_some())
749 );
750 let t = if mutable { Nim::Var(Box::new(self_ty.clone())) } else { self_ty.clone() };
751 parts.push(format!("self: {}", t.render()));
752 }
753 let typed: Vec<&syn::PatType> = sig
754 .inputs
755 .iter()
756 .filter_map(|a| match a {
757 FnArg::Typed(t) => Some(t),
758 _ => None,
759 })
760 .collect();
761 for (i, (p, t)) in typed.iter().zip(ptys.iter()).enumerate() {
762 let pname = match &*p.pat {
763 Pat::Ident(id) => id.ident.to_string(),
764 Pat::Wild(_) => format!("unused{}", parts.len()),
765 _ => return Err("only plain identifier parameters are supported".into()),
766 };
767 let _ = i;
768 parts.push(format!("{}: {}", ident(&pname), t.render()));
769 }
770 Ok(if ret == Nim::Unit {
771 format!("proc {}*({})", ident(name), parts.join(", "))
772 } else {
773 format!("proc {}*({}): {}", ident(name), parts.join(", "), ret.render())
774 })
775 }
776
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago777 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 7h ago778 // `unsafe fn` marks a contract for callers; it does not change what
779 // the body means, so it lowers like any other proc.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago780 if sig.asyncness.is_some() {
781 return Err(format!("`async fn {}`: Nim has no equivalent", sig.ident));
782 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago783 // Lifetime parameters carry no runtime meaning and Nim is GC'd, so
784 // `fn encode<'a>(..)` is not generic for our purposes. Type and const
785 // parameters genuinely are, and are rejected.
786 if let Some(p) = sig.generics.params.iter().find(|p| !matches!(p, syn::GenericParam::Lifetime(_))) {
787 let what = match p {
788 syn::GenericParam::Const(_) => "const",
789 _ => "type",
790 };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago791 return Err(format!(
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago792 "`fn {}` has a {what} parameter: generics are not implemented yet",
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago793 sig.ident
794 ));
795 }
796 let mut params = Vec::new();
797 for a in &sig.inputs {
798 if let FnArg::Typed(t) = a {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago799 params.push(self.map_ty(&t.ty)?);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago800 }
801 }
802 let ret = match &sig.output {
803 ReturnType::Default => Nim::Unit,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago804 // A returned `&[T]` is a borrow of the caller's buffer, so it
805 // stays an `openArray` view. Only an owned type (`Vec<T>`) becomes
806 // a `seq`, which `owned()` would do to both.
807 ReturnType::Type(_, t) => {
808 let n = self.map_ty(t)?;
809 if returns_borrow(t) { n } else { n.owned() }
810 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago811 };
812 Ok((params, ret))
813 }
814
815 // --------------------------------------------------------------- items
816
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago817 /// Emit the type definitions only: they must precede every signature.
818 fn item_types(&mut self, item: &Item) -> Result<(), String> {
819 if !self.cfg_keeps(item_attrs(item))? {
820 return Ok(());
821 }
822 match item {
823 Item::Struct(_) | Item::Enum(_) | Item::Const(_) => self.item_inner(item),
824 Item::Mod(m) if m.content.is_some() => {
825 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
826 for i in &items {
827 self.item_types(i)?;
828 }
829 Ok(())
830 }
831 _ => Ok(()),
832 }
833 }
834
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago835 fn item(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago836 if !self.cfg_keeps(item_attrs(item))? {
837 return Ok(());
838 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago839 // Types were emitted in their own pass.
840 if matches!(item, Item::Struct(_) | Item::Enum(_) | Item::Const(_)) {
841 return Ok(());
842 }
843 self.item_inner(item)
844 }
845
846 fn item_inner(&mut self, item: &Item) -> Result<(), String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago847 match item {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago848 Item::Fn(f) => {
849 let nim = self.fn_name(&self.cur_mod, &f.sig.ident.to_string());
850 self.func_named(&nim, &f.sig, &f.block, None)
851 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago852 Item::Struct(s) => {
853 let name = s.ident.to_string();
854 let fields = self.structs[&name].clone();
855 self.line(&format!("type {}* = object", ident(&name)));
856 self.indent += 1;
857 if fields.is_empty() {
858 self.line("discard");
859 }
860 for (fname, fty) in &fields {
861 self.line(&format!("{}*: {}", ident(fname), fty.render()));
862 }
863 self.indent -= 1;
864 self.blank();
865 Ok(())
866 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago867 Item::Type(_) => Ok(()), // expanded at every use site
868 Item::Enum(e) => {
869 let def = self.enums[&e.ident.to_string()].clone();
870 self.emit_enum(&def);
871 Ok(())
872 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago873 Item::Const(c) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago874 let t = self.map_ty(&c.ty)?.owned();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago875 let v = self.expr(&c.expr)?;
876 self.bind(&c.ident.to_string(), t.clone());
877 let line = format!("const {}*: {} = {}", ident(&c.ident.to_string()), t.render(), v.code);
878 self.line(&line);
879 self.blank();
880 Ok(())
881 }
882 Item::Impl(im) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago883 let self_ty = self.map_ty(&im.self_ty)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago884 if let Some((path, _)) = &im.trait_ {
885 let tr = path_name(path);
886 if im.items.is_empty() {
887 return Ok(());
888 }
889 let syn::ImplItem::Fn(m) = &im.items[0] else {
890 return Err(format!("unsupported item in `impl {tr}`"));
891 };
892 if is_fmt_trait(&tr) {
893 return self.fmt_impl(&tr, &self_ty, &m.sig, &m.block);
894 }
895 if tr == "From" {
896 let name = {
897 let (params, _) = self.signature(&m.sig)?;
898 let src = params.first().cloned().ok_or("`fn from` takes one argument")?;
899 self.from_impls[&(type_name(&src), type_name(&self_ty))].clone()
900 };
901 return self.func_named(&name, &m.sig, &m.block, None);
902 }
903 return Err(format!("`impl {tr}` is not implemented"));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago904 }
905 for it in &im.items {
906 match it {
907 syn::ImplItem::Fn(m) => {
908 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
909 self.func(&m.sig, &m.block, recv)?;
910 }
911 _ => return Err("only `fn` items are supported inside `impl`".into()),
912 }
913 }
914 Ok(())
915 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago916 // `use` and `extern crate` are resolution directives with no Nim
917 // analogue once everything is one module.
918 Item::Use(_) | Item::ExternCrate(_) => Ok(()),
919 Item::Mod(m) if m.content.is_some() => {
920 // An inline `mod` is flattened; Nim has no nested modules in a
921 // single file.
922 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
923 for i in &items {
924 self.item(i)?;
925 }
926 Ok(())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago927 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago928 Item::Mod(m) => {
929 // Satisfied if that file was passed in too; everything is one
930 // Nim module, so the declaration itself emits nothing.
931 if self.modules.iter().any(|x| *x == m.ident.to_string()) {
932 return Ok(());
933 }
934 Err(format!(
935 "`mod {};` refers to another file that was not passed to \
936 rustnim; add it to the input list",
937 m.ident
938 ))
939 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago940 other => Err(format!("unsupported item: {}", item_kind(other))),
941 }
942 }
943
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago944 /// `None` carries no type of its own, so Nim needs the `Option[T]` named.
945 fn none_of(&self, expect: Option<&Nim>) -> String {
946 match expect {
947 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => {
948 format!("rsNone[{}]()", a[0].render())
949 }
950 _ => "rsNone()".to_string(),
951 }
952 }
953
954 fn emit_enum(&mut self, def: &EnumDef) {
955 let name = ident(&def.name);
956 if def.simple {
957 // Every variant is a unit variant, so a plain Nim enum is an exact
958 // fit: it compares, orders and `case`-checks like Rust's.
959 self.line(&format!("type {name}* = enum"));
960 self.indent += 1;
961 for v in &def.variants {
962 self.line(&format!("{}", ident(&v.name)));
963 }
964 self.indent -= 1;
965 self.blank();
966 self.line(&format!("proc rsDebug*(x: {name}): string ="));
967 self.indent += 1;
968 self.line("case x");
969 for v in &def.variants {
970 self.line(&format!("of {}.{}: \"{}\"", name, ident(&v.name), v.name));
971 }
972 self.indent -= 1;
973 self.blank();
974 return;
975 }
976
977 // A data-carrying enum is a Nim object variant: one discriminant enum
978 // plus a branch per variant. This is the same shape the prelude uses
979 // for `Option` and `Result`.
980 self.line("type");
981 self.indent += 1;
982 self.line(&format!("{}Kind* = enum", name));
983 self.indent += 1;
984 for v in &def.variants {
985 self.line(&def.kind_ident(&v.name));
986 }
987 self.indent -= 1;
988 self.blank();
989 self.line(&format!("{}* = object", name));
990 self.indent += 1;
991 self.line(&format!("case kind*: {}Kind", name));
992 for v in &def.variants {
993 if v.fields.is_empty() {
994 self.line(&format!("of {}: discard", def.kind_ident(&v.name)));
995 } else {
996 self.line(&format!("of {}:", def.kind_ident(&v.name)));
997 self.indent += 1;
998 for (f, t) in &v.fields {
999 self.line(&format!("{}*: {}", ident(f), t.render()));
1000 }
1001 self.indent -= 1;
1002 }
1003 }
1004 self.indent -= 2;
1005 self.blank();
1006
1007 for v in &def.variants {
1008 let args: Vec<String> = v
1009 .fields
1010 .iter()
1011 .enumerate()
1012 .map(|(i, (_, t))| format!("a{}: {}", i, t.render()))
1013 .collect();
1014 let inits: Vec<String> = v
1015 .fields
1016 .iter()
1017 .enumerate()
1018 .map(|(i, (f, _))| format!("{}: a{}", ident(f), i))
1019 .collect();
1020 let mut all = vec![format!("kind: {}", def.kind_ident(&v.name))];
1021 all.extend(inits);
1022 self.line(&format!(
1023 "proc {}*({}): {} = {}({})",
1024 def.ctor_ident(&v.name),
1025 args.join(", "),
1026 name,
1027 name,
1028 all.join(", ")
1029 ));
1030 }
1031 self.blank();
1032
1033 self.line(&format!("proc rsDebug*(x: {name}): string ="));
1034 self.indent += 1;
1035 self.line("case x.kind");
1036 for v in &def.variants {
1037 if v.fields.is_empty() {
1038 self.line(&format!("of {}: \"{}\"", def.kind_ident(&v.name), v.name));
1039 } else {
1040 let parts: Vec<String> = v
1041 .fields
1042 .iter()
1043 .map(|(f, _)| format!("rsDebug(x.{})", ident(f)))
1044 .collect();
1045 self.line(&format!(
1046 "of {}: \"{}(\" & {} & \")\"",
1047 def.kind_ident(&v.name),
1048 v.name,
1049 parts.join(" & \", \" & ")
1050 ));
1051 }
1052 }
1053 self.indent -= 1;
1054 self.blank();
1055 }
1056
1057 /// Resolve a Rust path like `Error::InvalidLength` or a bare `InvalidLength`
1058 /// to the enum that declares it.
1059 fn resolve_variant(&self, path: &syn::Path) -> Option<(EnumDef, String)> {
1060 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
1061 let last = segs.last()?.clone();
1062 if segs.len() >= 2 {
1063 if let Some(def) = self.enums.get(&segs[segs.len() - 2]) {
1064 if def.get(&last).is_some() {
1065 return Some((def.clone(), last));
1066 }
1067 }
1068 }
1069 // Unqualified: only unambiguous if exactly one enum declares it.
1070 match self.variant_owner.get(&last) {
1071 Some(owners) if owners.len() == 1 => {
1072 let def = self.enums.get(&owners[0])?;
1073 Some((def.clone(), last))
1074 }
1075 _ => None,
1076 }
1077 }
1078
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1079 /// Lower `impl Display for T`'s `fn fmt` into a proc returning a string.
1080 ///
1081 /// Rust's `Formatter` is a sink that a `fmt` method writes into; the
1082 /// observable result of `{}` is exactly the bytes written. So the method
1083 /// becomes `proc rsDisplay(self: T): string` and every write through the
1084 /// formatter produces that string. A `fmt` body that does anything else
1085 /// with the formatter -- padding, precision, `debug_struct` -- is rejected,
1086 /// because those affect the output and this model does not carry them.
1087 /// The window an expression names, if it names one.
1088 fn window_of(&self, e: &Expr) -> Option<Alias> {
1089 match e {
1090 Expr::Path(p) => match self.lookup_alias(&path_name(&p.path)) {
1091 Some(a @ Alias::Window { .. }) => Some(a),
1092 _ => None,
1093 },
1094 Expr::Reference(r) => self.window_of(&r.expr),
1095 Expr::Paren(p) => self.window_of(&p.expr),
1096 Expr::Unary(u) if matches!(u.op, UnOp::Deref(_)) => self.window_of(&u.expr),
1097 _ => None,
1098 }
1099 }
1100
1101 /// Whether an expression is the `Formatter` parameter of the formatting
1102 /// impl currently being lowered.
1103 fn is_fmt_param(&self, e: &Expr) -> bool {
1104 let Some(f) = &self.fmt_param else { return false };
1105 match e {
1106 Expr::Path(p) => path_name(&p.path) == *f,
1107 Expr::Reference(r) => self.is_fmt_param(&r.expr),
1108 Expr::Paren(p) => self.is_fmt_param(&p.expr),
1109 _ => false,
1110 }
1111 }
1112
1113 fn fmt_impl(
1114 &mut self,
1115 tr: &str,
1116 self_ty: &Nim,
1117 sig: &syn::Signature,
1118 body: &syn::Block,
1119 ) -> Result<(), String> {
1120 let proc_name = fmt_proc(tr);
1121 // The formatter is the parameter after `self`.
1122 let f = sig
1123 .inputs
1124 .iter()
1125 .filter_map(|a| match a {
1126 FnArg::Typed(t) => match &*t.pat {
1127 Pat::Ident(i) => Some(i.ident.to_string()),
1128 _ => None,
1129 },
1130 _ => None,
1131 })
1132 .next()
1133 .ok_or("`fn fmt` needs a `Formatter` parameter")?;
1134
1135 self.push_scope();
1136 self.bind("self", self_ty.clone());
1137 let saved = self.fmt_param.replace(f);
1138 let outer_ret = self.ret.replace(Nim::Prim("string".into()));
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago1139 // No assignment target: a formatter write *appends*, because a `fmt`
1140 // body may write repeatedly -- `UpperHex` writes once per byte in a
1141 // loop -- and assigning would keep only the last one.
1142 let outer_target = self.target.take();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1143
1144 self.line(&format!(
1145 "proc {}*(self: {}): string =",
1146 proc_name,
1147 self_ty.render()
1148 ));
1149 self.indent += 1;
1150 let before = self.out.len();
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago1151 let tail = self.block_body(body)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1152 self.emit_tail(tail);
1153 if self.out.len() == before {
1154 self.line("discard");
1155 }
1156 self.indent -= 1;
1157
1158 self.target = outer_target;
1159 self.ret = outer_ret;
1160 self.fmt_param = saved;
1161 self.pop_scope();
1162 self.blank();
1163 Ok(())
1164 }
1165
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1166 fn func(
1167 &mut self,
1168 sig: &syn::Signature,
1169 body: &syn::Block,
1170 recv: Option<Nim>,
1171 ) -> Result<(), String> {
1172 let name = sig.ident.to_string();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1173 self.func_named(&name.clone(), sig, body, recv)
1174 }
1175
1176 fn func_named(
1177 &mut self,
1178 name: &str,
1179 sig: &syn::Signature,
1180 body: &syn::Block,
1181 recv: Option<Nim>,
1182 ) -> Result<(), String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1183 let (ptys, ret) = self.signature(sig)?;
1184
1185 self.push_scope();
1186 let mut rendered: Vec<String> = Vec::new();
1187
1188 if let Some(self_ty) = recv {
1189 // `&mut self` and `mut self` both mean the body may mutate the
1190 // receiver; only the former is observable by the caller, and a Nim
1191 // `var` parameter is the faithful spelling of that.
1192 let mutable = matches!(
1193 sig.inputs.first(),
1194 Some(FnArg::Receiver(r))
1195 if matches!(&r.kind, syn::ReceiverKind::Reference(_, _, m) if m.is_some())
1196 );
1197 let t = if mutable { Nim::Var(Box::new(self_ty.clone())) } else { self_ty.clone() };
1198 rendered.push(format!("self: {}", t.render()));
1199 self.bind("self", self_ty);
1200 }
1201
1202 let typed: Vec<&syn::PatType> = sig
1203 .inputs
1204 .iter()
1205 .filter_map(|a| match a {
1206 FnArg::Typed(t) => Some(t),
1207 _ => None,
1208 })
1209 .collect();
1210 for (p, t) in typed.iter().zip(ptys.iter()) {
1211 let pname = match &*p.pat {
1212 Pat::Ident(i) => i.ident.to_string(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1213 // `fn from(_: Error) -> ..` — the parameter is unused, but Nim
1214 // still needs a name for it.
1215 Pat::Wild(_) => format!("unused{}", rendered.len()),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1216 _ => return Err("only plain identifier parameters are supported".into()),
1217 };
1218 rendered.push(format!("{}: {}", ident(&pname), t.render()));
1219 // Inside the body a `var T` parameter is used exactly like a `T`.
1220 self.bind(&pname, t.clone().owned());
1221 }
1222
1223 let head = if ret == Nim::Unit {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1224 format!("proc {}*({}) =", ident(name), rendered.join(", "))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1225 } else {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1226 format!("proc {}*({}): {} =", ident(name), rendered.join(", "), ret.render())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1227 };
1228 self.line(&head);
1229 self.indent += 1;
1230 let outer_ret = self.ret.replace(ret.clone());
1231
1232 // A Rust fn's trailing expression is its return value. Naming Nim's
1233 // implicit `result` as the target makes that true whether the tail is
1234 // a plain expression or an `if`/`match` with statement arms.
1235 let outer_target = if ret == Nim::Unit {
1236 self.target.take()
1237 } else {
1238 self.target.replace(("result".to_string(), Some(ret.clone())))
1239 };
1240 let before = self.out.len();
1241 let tail = self.block_body_at(body, Some(&ret))?;
1242 self.target = outer_target;
1243 match tail {
1244 Some(v) if ret != Nim::Unit => {
1245 let code = v.code.clone();
1246 self.line(&format!("result = {code}"));
1247 }
1248 Some(v) => {
1249 // A trailing expression in a `()`-returning fn is evaluated for
1250 // its effect; Nim requires an explicit discard.
1251 let needs_discard = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
1252 if needs_discard && !v.code.is_empty() {
1253 let code = v.code.clone();
1254 self.line(&format!("discard {code}"));
1255 }
1256 }
1257 None => {}
1258 }
1259 if self.out.len() == before {
1260 self.line("discard");
1261 }
1262
1263 self.indent -= 1;
1264 self.ret = outer_ret;
1265 self.pop_scope();
1266 self.blank();
1267 Ok(())
1268 }
1269
1270 // ---------------------------------------------------------- statements
1271
1272 /// Lower a block's statements. Returns the block's trailing expression,
1273 /// if it has one, *without* emitting it — the caller decides whether that
1274 /// value is a return value, a binding, or discarded.
1275 fn block_body(&mut self, b: &syn::Block) -> Result<Option<Val>, String> {
1276 self.block_body_at(b, None)
1277 }
1278
1279 fn block_body_at(
1280 &mut self,
1281 b: &syn::Block,
1282 expect: Option<&Nim>,
1283 ) -> Result<Option<Val>, String> {
1284 // An assignment target belongs to *this* block's trailing expression
1285 // only. A non-final `if` is a statement and must not assign anything.
1286 let target = self.target.take();
1287 let n = b.stmts.len();
1288 let mut tail = None;
1289 for (i, st) in b.stmts.iter().enumerate() {
1290 let last = i + 1 == n;
1291 match st {
1292 Stmt::Expr(e, None) if last && expressible(e) => {
1293 tail = Some(self.expr_at(e, expect)?)
1294 }
1295 Stmt::Expr(e, None) if last => {
1296 // A trailing `if`/`match` with statement arms, or a loop.
1297 // Lower it as statements; if this block's value is wanted,
1298 // each arm assigns it.
1299 match &target {
1300 Some((t, ty)) => {
1301 let (t, ty) = (t.clone(), ty.clone());
1302 self.assign_from(e, &t, ty.as_ref())?;
1303 }
1304 None => self.stmt(st)?,
1305 }
1306 }
1307 _ => self.stmt(st)?,
1308 }
1309 }
1310 self.target = target;
1311 Ok(tail)
1312 }
1313
1314 /// Lower a block in statement position (loop bodies, `if` arms).
1315 fn nested_block(&mut self, b: &syn::Block) -> Result<(), String> {
1316 self.push_scope();
1317 self.indent += 1;
1318 let before = self.out.len();
1319 let want = self.target.clone().and_then(|(_, t)| t);
1320 let tail = self.block_body_at(b, want.as_ref())?;
1321 self.emit_tail(tail);
1322 if self.out.len() == before {
1323 self.line("discard");
1324 }
1325 self.indent -= 1;
1326 self.pop_scope();
1327 Ok(())
1328 }
1329
1330 fn stmt(&mut self, s: &Stmt) -> Result<(), String> {
1331 match s {
1332 Stmt::Local(l) => self.local(l),
1333 Stmt::Expr(e, _) => {
1334 let v = self.expr_stmt(e)?;
1335 if let Some(v) = v {
1336 // A bare expression with a value must be discarded in Nim.
1337 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
1338 let code = v.code.clone();
1339 if needs {
1340 self.line(&format!("discard {code}"));
1341 } else if !code.is_empty() {
1342 self.line(&code);
1343 }
1344 }
1345 Ok(())
1346 }
1347 Stmt::Item(i) => self.item(i),
1348 Stmt::Macro(m) => {
1349 let line = self.macro_call(&m.mac)?;
1350 self.line(&line);
1351 Ok(())
1352 }
1353 }
1354 }
1355
1356 fn local(&mut self, l: &Local) -> Result<(), String> {
1357 let (name, mutable, ann): (String, bool, Option<Nim>) = match &l.pat {
1358 Pat::Ident(i) => (i.ident.to_string(), i.mutability.is_some(), None),
1359 Pat::Type(t) => match &*t.pat {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago1360 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 8h ago1361 _ => return Err("only `let <ident>` bindings are supported".into()),
1362 },
1363 Pat::Wild(_) => ("_".into(), false, None),
1364 _ => return Err("destructuring `let` is not implemented yet".into()),
1365 };
1366
1367 let Some(init) = &l.init else {
1368 // `let x: T;` — Nim's `var x: T` zero-initialises, which Rust does
1369 // not. Rust's own rules make reading it before assignment illegal,
1370 // so the two agree on every program rustc accepts.
1371 let t = ann.ok_or("`let` without an initialiser needs a type annotation")?;
1372 let t = t.owned();
1373 self.line(&format!("var {}: {}", ident(&name), t.render()));
1374 self.bind(&name, t);
1375 return Ok(());
1376 };
1377 if init.diverge.is_some() {
1378 return Err("`let ... else` is not implemented yet".into());
1379 }
1380
1381 if !expressible(&init.expr) && name != "_" {
1382 // The initialiser is an `if`/`match` whose arms are statements.
1383 // Declare first, then let each arm assign into the binding.
1384 let t = ann
1385 .clone()
1386 .ok_or_else(|| {
1387 format!(
1388 "`let {name} = match/if ...` needs a type annotation: \
1389 its arms are statements, so the binding must be \
1390 declared before they run"
1391 )
1392 })?
1393 .owned();
1394 self.line(&format!("var {}: {}", ident(&name), t.render()));
1395 self.bind(&name, t.clone());
1396 let target = ident(&name);
1397 return self.assign_from(&init.expr, &target, Some(&t));
1398 }
1399
1400 let v = self.expr_at(&init.expr, ann.as_ref())?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1401 if let Some(w) = v.window.clone() {
1402 // `let dst = dst.get_mut(..n).ok_or(..)?;` -- the binding names a
1403 // view into the caller's buffer. Copying it into a `seq` would
1404 // still print the right bytes but would stop writes reaching the
1405 // caller, so it is bound as an alias.
1406 if v.guard.is_some() && v.guard_err.is_some() {
1407 return Err(format!(
1408 "`let {name} = ...get(..)` keeps an `Option` of a slice view, \
1409 which Nim cannot represent; apply `?` or `unwrap()` to it \
1410 in the same expression"
1411 ));
1412 }
1413 self.bind_alias(&name, w);
1414 return Ok(());
1415 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago1416 // A `let` binding a borrow keeps the view: `let res = encode(..)?`
1417 // names the caller's buffer, and copying it into a `seq` would still
1418 // print the right bytes while silently breaking the aliasing.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1419 let t = match (ann, &v.ty) {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago1420 (Some(a), _) => a.unvar(),
1421 (None, Some(t)) => t.clone().unvar(),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1422 (None, None) => {
1423 return Err(format!(
1424 "cannot infer the type of `let {name}`; annotate it — \
1425 guessing here would change integer width, and with it the \
1426 meaning of any arithmetic on `{name}`"
1427 ))
1428 }
1429 };
1430
1431 if name == "_" {
1432 let code = v.code.clone();
1433 self.line(&format!("discard {code}"));
1434 return Ok(());
1435 }
1436 // Rust's immutable `let` is Nim's `let`; `let mut` is `var`. Shadowing
1437 // works in both, so a re-`let` of the same name needs no rename.
1438 let kw = if mutable { "var" } else { "let" };
1439 let line = format!("{} {}: {} = {}", kw, ident(&name), t.render(), v.code);
1440 self.line(&line);
1441 self.bind(&name, t);
1442 Ok(())
1443 }
1444
1445 /// Expressions that are statements in Rust and statements in Nim too
1446 /// (control flow). Returns `None` when it emitted lines itself.
1447 fn expr_stmt(&mut self, e: &Expr) -> Result<Option<Val>, String> {
1448 match e {
1449 Expr::If(_) => {
1450 self.if_stmt(e)?;
1451 Ok(None)
1452 }
1453 Expr::While(w) => {
1454 if w.label.is_some() {
1455 return Err("loop labels are not implemented yet".into());
1456 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago1457 self.in_loop_cond = true;
1458 let c = self.expr(&w.cond);
1459 self.in_loop_cond = false;
1460 let c = c?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1461 self.line(&format!("while {}:", c.code));
1462 let saved = self.target.take();
1463 self.nested_block(&w.body)?;
1464 self.target = saved;
1465 Ok(None)
1466 }
1467 Expr::Loop(l) => {
1468 if l.label.is_some() {
1469 return Err("loop labels are not implemented yet".into());
1470 }
1471 self.line("while true:");
1472 let saved = self.target.take();
1473 self.nested_block(&l.body)?;
1474 self.target = saved;
1475 Ok(None)
1476 }
1477 Expr::ForLoop(f) => {
1478 self.for_loop(f)?;
1479 Ok(None)
1480 }
1481 Expr::Block(b) => {
1482 if b.label.is_some() {
1483 return Err("block labels are not implemented yet".into());
1484 }
1485 self.line("block:");
1486 self.nested_block(&b.block)?;
1487 Ok(None)
1488 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago1489 Expr::Unsafe(u) => {
1490 // Transparent in statement position too, for the same reason.
1491 self.nested_block_flat(&u.block)?;
1492 Ok(None)
1493 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1494 Expr::Match(_) => {
1495 self.match_stmt(e)?;
1496 Ok(None)
1497 }
1498 Expr::Return(r) => {
1499 match &r.expr {
1500 Some(e) => {
1501 let want = self.ret.clone();
1502 let v = self.expr_at(e, want.as_ref())?;
1503 self.line(&format!("return {}", v.code));
1504 }
1505 None => self.line("return"),
1506 }
1507 Ok(None)
1508 }
1509 Expr::Break(b) => {
1510 if b.expr.is_some() || b.label.is_some() {
1511 return Err("`break` with a value or a label is not implemented yet".into());
1512 }
1513 self.line("break");
1514 Ok(None)
1515 }
1516 Expr::Continue(c) => {
1517 if c.label.is_some() {
1518 return Err("labelled `continue` is not implemented yet".into());
1519 }
1520 self.line("continue");
1521 Ok(None)
1522 }
1523 Expr::Assign(a) => {
1524 let lhs = self.expr(&a.left)?;
1525 if !expressible(&a.right) {
1526 let target = lhs.code.clone();
1527 return self.assign_from(&a.right, &target, lhs.ty.as_ref()).map(|_| None);
1528 }
1529 let rhs = self.expr_at(&a.right, lhs.ty.as_ref())?;
1530 self.line(&format!("{} = {}", lhs.code, rhs.code));
1531 Ok(None)
1532 }
1533 Expr::Binary(b) if is_compound(&b.op) => {
1534 let lhs = self.expr(&b.left)?;
1535 // `i += 1` must widen the literal to `i`'s type, not to the
1536 // i32 an unconstrained Rust literal would default to.
1537 let rhs = self.expr_at(&b.right, lhs.ty.as_ref())?;
1538 let op = self.bin_op(&b.op, &lhs, &rhs)?;
1539 // Nim has no `shl=` etc., and `+=` on a `let` is illegal in
1540 // both languages, so the expanded form is always correct.
1541 self.line(&format!("{} = {} {} {}", lhs.code, lhs.code, op, rhs.code));
1542 Ok(None)
1543 }
1544 Expr::Macro(m) => {
1545 let line = self.macro_call(&m.mac)?;
1546 self.line(&line);
1547 Ok(None)
1548 }
1549 _ => Ok(Some(self.expr(e)?)),
1550 }
1551 }
1552
1553 /// Lower `e` in statement position, assigning each arm's value to
1554 /// `target`. This is how Rust's expression-oriented `if`/`match` survive
1555 /// the trip when their arms are too big for a Nim `if`-expression.
1556 fn assign_from(
1557 &mut self,
1558 e: &Expr,
1559 target: &str,
1560 expect: Option<&Nim>,
1561 ) -> Result<(), String> {
1562 let saved = self.target.replace((target.to_string(), expect.cloned()));
1563 let r = match e {
1564 Expr::If(_) => self.if_stmt(e),
1565 Expr::Match(_) => self.match_stmt(e),
1566 other => {
1567 let v = self.expr_at(other, expect)?;
1568 self.line(&format!("{} = {}", target, v.code));
1569 Ok(())
1570 }
1571 };
1572 self.target = saved;
1573 r
1574 }
1575
1576 /// Emit a block's value into the active assignment target, if there is
1577 /// one, or discard it if there is not.
1578 fn emit_tail(&mut self, v: Option<Val>) {
1579 let Some(v) = v else { return };
1580 match self.target.clone() {
1581 Some((t, _)) => {
1582 let code = v.code.clone();
1583 self.line(&format!("{t} = {code}"));
1584 }
1585 None => {
1586 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
1587 let code = v.code.clone();
1588 if needs {
1589 self.line(&format!("discard {code}"));
1590 } else if !code.is_empty() {
1591 self.line(&code);
1592 }
1593 }
1594 }
1595 }
1596
1597 fn if_stmt(&mut self, e: &Expr) -> Result<(), String> {
1598 let Expr::If(i) = e else { unreachable!() };
1599 if let Expr::Let(_) = &*i.cond {
1600 return Err("`if let` is not implemented yet".into());
1601 }
1602 let c = self.expr(&i.cond)?;
1603 self.line(&format!("if {}:", c.code));
1604 self.nested_block(&i.then_branch)?;
1605 match &i.else_branch {
1606 None => {}
1607 Some((_, els)) => match &**els {
1608 Expr::If(_) => {
1609 // Nim needs `elif`; splice the nested `if` in as one.
1610 let mark = self.out.len();
1611 self.if_stmt(els)?;
1612 let tail = self.out.split_off(mark);
1613 let indent = " ".repeat(self.indent);
1614 self.out.push_str(&tail.replacen(&format!("{indent}if "), &format!("{indent}elif "), 1));
1615 }
1616 Expr::Block(b) => {
1617 self.line("else:");
1618 self.nested_block(&b.block)?;
1619 }
1620 _ => return Err("unsupported `else` form".into()),
1621 },
1622 }
1623 Ok(())
1624 }
1625
1626 fn for_loop(&mut self, f: &syn::ExprForLoop) -> Result<(), String> {
1627 if f.label.is_some() {
1628 return Err("loop labels are not implemented yet".into());
1629 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1630 let it = self.resolve_iter(&f.expr)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1631
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1632 // One index loop drives the whole chain. Rust's adaptors are lazy and
1633 // compose; resolving them to an index and binding each name to an
1634 // lvalue reproduces that without materialising anything.
1635 let i = self.fresh("Idx");
1636 self.line(&format!("for {} in 0 ..< int({}):", i, it.len()));
1637 self.indent += 1;
1638 self.push_scope();
1639 let before = self.out.len();
1640
1641 self.bind_pattern(&f.pat, &it, &i)?;
1642
1643 let saved = self.target.take();
1644 if let Some(v) = self.block_body(&f.body)? {
1645 let code = v.code.clone();
1646 self.line(&format!("discard {code}"));
1647 }
1648 self.target = saved;
1649 if self.out.len() == before {
1650 self.line("discard");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1651 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1652 self.pop_scope();
1653 self.indent -= 1;
1654 Ok(())
1655 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1656
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1657 /// Resolve a chain of iterator adaptors into a single `Iter`.
1658 ///
1659 /// Only adaptors with an exact index-loop equivalent are accepted. `map`,
1660 /// `filter`, `take_while` and friends are rejected rather than partially
1661 /// honoured: silently dropping an adaptor would change which elements the
1662 /// loop visits.
1663 fn resolve_iter(&mut self, e: &Expr) -> Result<Iter, String> {
1664 match e {
1665 Expr::Reference(r) => self.resolve_iter(&r.expr),
1666 Expr::Paren(p) => self.resolve_iter(&p.expr),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1667 Expr::Range(r) => {
1668 let lo = match &r.start {
1669 Some(e) => self.expr(e)?,
1670 None => return Err("a `for` over `..n` needs a start bound".into()),
1671 };
1672 let hi = match &r.end {
1673 Some(e) => self.expr(e)?,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1674 None => {
1675 return Err("a `for` over an unbounded range would not terminate".into())
1676 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1677 };
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1678 let ty = lo.ty.clone().or(hi.ty.clone());
1679 Ok(Iter::Range {
1680 lo: lo.code,
1681 hi: hi.code,
1682 closed: matches!(r.limits, syn::RangeLimits::Closed(_)),
1683 ty,
1684 })
1685 }
1686 Expr::MethodCall(m) => {
1687 let name = m.method.to_string();
1688 match name.as_str() {
1689 "iter" | "into_iter" | "iter_mut" if m.args.is_empty() => {
1690 let mut it = self.resolve_iter(&m.receiver)?;
1691 if name == "iter_mut" {
1692 if let Iter::Elems { mutable, .. } = &mut it {
1693 *mutable = true;
1694 }
1695 }
1696 Ok(it)
1697 }
1698 "enumerate" if m.args.is_empty() => {
1699 Ok(Iter::Enumerate(Box::new(self.resolve_iter(&m.receiver)?)))
1700 }
1701 "zip" if m.args.len() == 1 => {
1702 let a = self.resolve_iter(&m.receiver)?;
1703 let b = self.resolve_iter(&m.args[0])?;
1704 Ok(Iter::Zip(Box::new(a), Box::new(b)))
1705 }
1706 "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 7h ago1707 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1708 let k = self.expr(&m.args[0])?;
1709 Ok(Iter::Chunks {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago1710 code,
1711 base,
1712 len,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1713 k: k.code,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago1714 elem,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1715 mutable: name.ends_with("_mut"),
1716 })
1717 }
1718 "windows" if m.args.len() == 1 => {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago1719 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1720 let k = self.expr(&m.args[0])?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago1721 Ok(Iter::Windows { code, base, len, k: k.code, elem })
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1722 }
1723 other => Err(format!(
1724 "iterator adaptor `.{other}()` is not implemented; it has \
1725 no index-loop equivalent here, and dropping it would \
1726 change which elements the loop visits"
1727 )),
1728 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1729 }
1730 other => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1731 // A `for` binding that is itself a window iterates that window,
1732 // not the whole container it points into.
1733 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 7h ago1734 return Ok(Iter::Elems { code, off, len, elem, mutable: false });
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1735 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1736 let v = self.expr(other)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1737 Ok(Iter::Elems {
1738 len: format!("{}.len", v.code),
1739 elem: elem_of(&v.ty),
1740 code: v.code,
1741 off: "0".into(),
1742 mutable: false,
1743 })
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1744 }
1745 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1746 }
1747
1748 /// Bind a `for` pattern against a resolved iterator at index `i`.
1749 fn bind_pattern(&mut self, p: &Pat, it: &Iter, i: &str) -> Result<(), String> {
1750 match (p, it) {
1751 (Pat::Tuple(t), Iter::Zip(a, b)) if t.elems.len() == 2 => {
1752 self.bind_pattern(&t.elems[0], a, i)?;
1753 self.bind_pattern(&t.elems[1], b, i)
1754 }
1755 (Pat::Tuple(t), Iter::Enumerate(inner)) if t.elems.len() == 2 => {
1756 if let Pat::Ident(id) = &t.elems[0] {
1757 let n = id.ident.to_string();
1758 // Rust's `enumerate` counts in `usize`.
1759 self.line(&format!("let {}: uint = uint({})", ident(&n), i));
1760 self.bind(&n, Nim::Prim("uint".into()));
1761 }
1762 self.bind_pattern(&t.elems[1], inner, i)
1763 }
1764 (_, Iter::Zip(..) | Iter::Enumerate(..)) => Err(
1765 "a `zip`/`enumerate` loop needs a two-element tuple pattern".into(),
1766 ),
1767 (Pat::Wild(_), _) => Ok(()),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago1768 // `for &byte in xs` — the `&` destructures the reference, which in
1769 // Nim is already the value.
1770 (Pat::Reference(r), _) => self.bind_pattern(&r.pat, it, i),
1771 (Pat::Paren(p), _) => self.bind_pattern(&p.pat, it, i),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1772 (Pat::Ident(id), _) => {
1773 let name = id.ident.to_string();
1774 match it {
1775 Iter::Range { lo, ty, .. } => {
1776 let t = ty.clone().unwrap_or(Nim::Prim("int".into()));
1777 // The loop counts from zero; the range's own start is
1778 // added back so the binding has Rust's value and type.
1779 self.line(&format!(
1780 "let {}: {} = {}({}) + {}",
1781 ident(&name),
1782 t.render(),
1783 t.render(),
1784 i,
1785 lo
1786 ));
1787 self.bind(&name, t);
1788 Ok(())
1789 }
1790 Iter::Elems { code, off, elem, mutable, .. } => {
1791 let access = if off == "0" {
1792 format!("{}[{}]", code, i)
1793 } else {
1794 format!("{}[{} + {}]", code, off, i)
1795 };
1796 if *mutable {
1797 // An alias, not a copy: assigning through the
1798 // binding must reach the original element.
1799 self.bind_alias(
1800 &name,
1801 Alias::Value { code: access, ty: elem.clone() },
1802 );
1803 } else {
1804 let t = elem
1805 .clone()
1806 .ok_or("cannot infer the element type of this `for`")?;
1807 self.line(&format!(
1808 "let {}: {} = {}",
1809 ident(&name),
1810 t.render(),
1811 access
1812 ));
1813 self.bind(&name, t);
1814 }
1815 Ok(())
1816 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago1817 Iter::Chunks { code, base, k, elem, .. } => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1818 self.bind_alias(
1819 &name,
1820 Alias::Window {
1821 code: code.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago1822 off: format!("({} + {} * int({}))", base, i, k),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1823 len: format!("int({})", k),
1824 elem: elem.clone(),
1825 },
1826 );
1827 Ok(())
1828 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago1829 Iter::Windows { code, base, k, elem, .. } => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1830 self.bind_alias(
1831 &name,
1832 Alias::Window {
1833 code: code.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago1834 off: format!("({} + {})", base, i),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago1835 len: format!("int({})", k),
1836 elem: elem.clone(),
1837 },
1838 );
1839 Ok(())
1840 }
1841 // Handled above: a zip or enumerate needs a tuple pattern,
1842 // and binding one name to the pair is not supported.
1843 Iter::Zip(..) | Iter::Enumerate(..) => unreachable!(),
1844 }
1845 }
1846 _ => Err("unsupported `for` pattern".into()),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1847 }
1848 }
1849
1850 fn match_stmt(&mut self, e: &Expr) -> Result<(), String> {
1851 let Expr::Match(m) = e else { unreachable!() };
1852 let scrut = self.expr(&m.expr)?;
1853 let t = scrut
1854 .ty
1855 .clone()
1856 .ok_or("cannot infer the type of a `match` scrutinee")?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago1857 let name = self.fresh("Match");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1858 self.line(&format!("let {}: {} = {}", name, t.render(), scrut.code));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago1859
1860 // A `match` whose arms neither bind nor guard is a Nim `case`, which
1861 // is exhaustiveness-checked the way Rust's is. Anything richer becomes
1862 // an if/elif chain, because Nim's `case` cannot destructure.
1863 let plain = m.arms.iter().all(|a| {
1864 !matches!(a.pat, Pat::Guard(_)) && !binds(&a.pat) && !destructures(&a.pat)
1865 });
1866 if plain {
1867 self.match_case(m, &name, &t)
1868 } else {
1869 self.match_chain(m, &name, &t)
1870 }
1871 }
1872
1873 fn match_case(
1874 &mut self,
1875 m: &syn::ExprMatch,
1876 name: &str,
1877 t: &Nim,
1878 ) -> Result<(), String> {
1879 // A variant object is discriminated by its `kind` field.
1880 let on_kind = matches!(t, Nim::Named(n, _) if self.enums.get(n).is_some_and(|d| !d.simple));
1881 self.line(&format!("case {}{}", name, if on_kind { ".kind" } else { "" }));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1882
1883 let mut saw_wild = false;
1884 for arm in &m.arms {
1885 match &arm.pat {
1886 Pat::Wild(_) => {
1887 saw_wild = true;
1888 self.line("else:");
1889 }
1890 p => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago1891 let labels = self.pat_labels(p, Some(t))?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1892 self.line(&format!("of {}:", labels.join(", ")));
1893 }
1894 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago1895 self.arm_body(&arm.body)?;
1896 }
1897 if !saw_wild && !self.case_is_total(t, m) {
1898 // Rust checked exhaustiveness already, but Nim cannot always see
1899 // it -- an integer `case` needs every value covered -- so make the
1900 // unreachable arm explicit rather than leave a compile error.
1901 self.line("else:");
1902 self.line(" rsPanic(\"unreachable match arm\")");
1903 }
1904 Ok(())
1905 }
1906
1907 /// Whether a Nim `case` over this type is already total, in which case
1908 /// adding an `else` would be a compile error rather than a safety net.
1909 fn case_is_total(&self, t: &Nim, m: &syn::ExprMatch) -> bool {
1910 let Nim::Named(n, _) = t else { return false };
1911 let Some(def) = self.enums.get(n) else { return false };
1912 def.variants.len() == m.arms.len()
1913 }
1914
1915 /// The if/elif form, for arms that bind or destructure.
1916 fn match_chain(
1917 &mut self,
1918 m: &syn::ExprMatch,
1919 name: &str,
1920 t: &Nim,
1921 ) -> Result<(), String> {
1922 let mut first = true;
1923 let mut closed = false;
1924 for arm in &m.arms {
1925 let (pat, guard) = match &arm.pat {
1926 Pat::Guard(g) => (&*g.pat, Some(&*g.guard)),
1927 p => (p, None),
1928 };
1929 if guard.is_some() && binds(pat) {
1930 return Err("a `match` guard on a binding pattern is not \
1931 implemented yet"
1932 .into());
1933 }
1934 let test = self.pat_test(pat, name, t)?;
1935 let test = match (test, guard) {
1936 (Some(t), Some(g)) => {
1937 let g = self.expr(g)?;
1938 Some(format!("({}) and ({})", t, g.code))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1939 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago1940 (None, Some(g)) => Some(self.expr(g)?.code),
1941 (t, None) => t,
1942 };
1943 match test {
1944 Some(test) => {
1945 self.line(&format!(
1946 "{} {}:",
1947 if first { "if" } else { "elif" },
1948 test
1949 ));
1950 first = false;
1951 }
1952 None => {
1953 // An irrefutable pattern: everything left falls here.
1954 if first {
1955 self.line("block:");
1956 } else {
1957 self.line("else:");
1958 }
1959 closed = true;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1960 }
1961 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago1962 self.indent += 1;
1963 self.push_scope();
1964 let before = self.out.len();
1965 self.pat_bind(pat, name, t)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1966 self.indent -= 1;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago1967 self.arm_body_at(&arm.body, before)?;
1968 self.pop_scope();
1969 if closed {
1970 break;
1971 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1972 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago1973 if !closed {
1974 // Rust proved this unreachable; Nim cannot see that, and leaving
1975 // the chain open would silently fall through instead.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago1976 self.line("else:");
1977 self.line(" rsPanic(\"unreachable match arm\")");
1978 }
1979 Ok(())
1980 }
1981
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago1982 /// The condition that selects this arm, or `None` if it always matches.
1983 fn pat_test(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<Option<String>, String> {
1984 Ok(match p {
1985 Pat::Wild(_) => None,
1986 Pat::Ident(i) if i.subpat.is_none() => None,
1987 Pat::Or(o) => {
1988 let mut parts = Vec::new();
1989 for c in &o.cases {
1990 match self.pat_test(c, name, t)? {
1991 Some(x) => parts.push(x),
1992 None => return Ok(None),
1993 }
1994 }
1995 Some(format!("({})", parts.join(" or ")))
1996 }
1997 Pat::Lit(_) | Pat::Range(_) => {
1998 let labels = self.pat_labels(p, Some(t))?;
1999 Some(match p {
2000 Pat::Range(_) => format!("({} in {})", name, labels[0]),
2001 _ => format!("({} == {})", name, labels[0]),
2002 })
2003 }
2004 Pat::Path(pp) => Some(self.variant_test(&pp.path, name, t)?),
2005 Pat::TupleStruct(ts) => Some(self.variant_test(&ts.path, name, t)?),
2006 Pat::Struct(st) => Some(self.variant_test(&st.path, name, t)?),
2007 Pat::Paren(pp) => return self.pat_test(&pp.pat, name, t),
2008 Pat::Reference(r) => return self.pat_test(&r.pat, name, t),
2009 _ => return Err("unsupported `match` pattern".into()),
2010 })
2011 }
2012
2013 /// The discriminant test for `Ok`/`Err`/`Some`/`None` or an enum variant.
2014 fn variant_test(&self, path: &syn::Path, name: &str, t: &Nim) -> Result<String, String> {
2015 let last = path_name(path);
2016 match last.as_str() {
2017 "Ok" => return Ok(format!("{name}.ok")),
2018 "Err" => return Ok(format!("(not {name}.ok)")),
2019 "Some" => return Ok(format!("{name}.has")),
2020 "None" => return Ok(format!("(not {name}.has)")),
2021 _ => {}
2022 }
2023 let Some((def, v)) = self.resolve_variant(path) else {
2024 return Err(format!(
2025 "`{last}` in a pattern is not a known enum variant; if it names \
2026 an enum declared in another module, that is not implemented yet"
2027 ));
2028 };
2029 if let Nim::Named(n, _) = t {
2030 if *n != def.name {
2031 return Err(format!(
2032 "pattern `{}::{}` does not match the scrutinee type `{}`",
2033 def.name, v, n
2034 ));
2035 }
2036 }
2037 Ok(if def.simple {
2038 format!("({} == {}.{})", name, ident(&def.name), ident(&v))
2039 } else {
2040 format!("({}.kind == {})", name, def.kind_ident(&v))
2041 })
2042 }
2043
2044 /// Emit the `let`s that a pattern's bindings introduce.
2045 fn pat_bind(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<(), String> {
2046 match p {
2047 Pat::Wild(_) | Pat::Lit(_) | Pat::Range(_) | Pat::Path(_) | Pat::Or(_) => Ok(()),
2048 Pat::Paren(pp) => self.pat_bind(&pp.pat, name, t),
2049 Pat::Reference(r) => self.pat_bind(&r.pat, name, t),
2050 Pat::Ident(i) if i.subpat.is_none() => {
2051 let b = i.ident.to_string();
2052 self.line(&format!("let {}: {} = {}", ident(&b), t.render(), name));
2053 self.bind(&b, t.clone());
2054 Ok(())
2055 }
2056 Pat::TupleStruct(ts) => {
2057 let fields = self.variant_fields(&ts.path, t)?;
2058 for (i, sub) in ts.elems.iter().enumerate() {
2059 let Some((fname, fty)) = fields.get(i) else {
2060 return Err(format!(
2061 "pattern binds {} field(s) but the variant has {}",
2062 ts.elems.len(),
2063 fields.len()
2064 ));
2065 };
2066 let access = format!("{}.{}", name, ident(fname));
2067 self.pat_bind(sub, &access, fty)?;
2068 }
2069 Ok(())
2070 }
2071 Pat::Struct(st) => {
2072 let fields = self.variant_fields(&st.path, t)?;
2073 for f in &st.fields {
2074 let syn::Member::Named(m) = &f.member else {
2075 return Err("unsupported struct pattern field".into());
2076 };
2077 let m = m.to_string();
2078 let Some((fname, fty)) = fields.iter().find(|(f, _)| f.ends_with(&m)) else {
2079 return Err(format!("unknown field `{m}` in pattern"));
2080 };
2081 let access = format!("{}.{}", name, ident(fname));
2082 self.pat_bind(&f.pat, &access, fty)?;
2083 }
2084 Ok(())
2085 }
2086 _ => Err("unsupported `match` pattern".into()),
2087 }
2088 }
2089
2090 /// The payload fields a variant pattern destructures.
2091 fn variant_fields(
2092 &self,
2093 path: &syn::Path,
2094 t: &Nim,
2095 ) -> Result<Vec<(String, Nim)>, String> {
2096 let last = path_name(path);
2097 // `Ok`/`Err`/`Some` read the prelude's own field names.
2098 if let Nim::Named(n, a) = t {
2099 match (n.as_str(), last.as_str()) {
2100 ("Result", "Ok") if a.len() == 2 => return Ok(vec![("val".into(), a[0].clone())]),
2101 ("Result", "Err") if a.len() == 2 => return Ok(vec![("err".into(), a[1].clone())]),
2102 ("Option", "Some") if a.len() == 1 => return Ok(vec![("val".into(), a[0].clone())]),
2103 _ => {}
2104 }
2105 }
2106 let Some((def, v)) = self.resolve_variant(path) else {
2107 return Err(format!("`{last}` is not a known enum variant"));
2108 };
2109 Ok(def.get(&v).map(|v| v.fields.clone()).unwrap_or_default())
2110 }
2111
2112 fn arm_body(&mut self, body: &Expr) -> Result<(), String> {
2113 self.indent += 1;
2114 let before = self.out.len();
2115 self.indent -= 1;
2116 self.arm_body_at(body, before)
2117 }
2118
2119 fn arm_body_at(&mut self, body: &Expr, before: usize) -> Result<(), String> {
2120 match body {
2121 Expr::Block(b) => self.nested_block(&b.block)?,
2122 other => {
2123 self.indent += 1;
2124 // An arm's value is the `match`'s value, so it is typed by
2125 // whatever the `match` is being assigned to -- without which
2126 // an `Ok(..)` arm has no way to know its `Result<T, E>`.
2127 let want = self.target.clone().and_then(|(_, t)| t);
2128 let v = match (want, expressible(other)) {
2129 (Some(t), true) => Some(self.expr_at(other, Some(&t))?),
2130 _ => self.expr_stmt(other)?,
2131 };
2132 self.emit_tail(v);
2133 self.indent -= 1;
2134 }
2135 }
2136 if self.out.len() == before {
2137 self.indent += 1;
2138 self.line("discard");
2139 self.indent -= 1;
2140 }
2141 Ok(())
2142 }
2143
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2144 fn pat_labels(&mut self, p: &Pat, expect: Option<&Nim>) -> Result<Vec<String>, String> {
2145 match p {
2146 Pat::Lit(l) => Ok(vec![self.lit_at(&l.lit, expect)?.code]),
2147 Pat::Or(o) => {
2148 let mut out = Vec::new();
2149 for p in &o.cases {
2150 out.extend(self.pat_labels(p, expect)?);
2151 }
2152 Ok(out)
2153 }
2154 Pat::Range(r) => {
2155 let lo = r.start.as_ref().ok_or("open-ended range pattern")?;
2156 let hi = r.end.as_ref().ok_or("open-ended range pattern")?;
2157 let (lo, hi) = (self.expr_at(lo, expect)?, self.expr_at(hi, expect)?);
2158 let op = match r.limits {
2159 syn::RangeLimits::HalfOpen(_) => "..<",
2160 syn::RangeLimits::Closed(_) => "..",
2161 };
2162 Ok(vec![format!("{} {} {}", lo.code, op, hi.code)])
2163 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2164 Pat::Path(pp) => {
2165 if let Some((def, v)) = self.resolve_variant(&pp.path) {
2166 return Ok(vec![if def.simple {
2167 format!("{}.{}", ident(&def.name), ident(&v))
2168 } else {
2169 def.kind_ident(&v)
2170 }]);
2171 }
2172 Ok(vec![ident(&path_name(&pp.path))])
2173 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2174 _ => Err("unsupported `match` pattern; only literals, ranges, `|` \
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2175 alternatives, enum variants and `_` are implemented"
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2176 .into()),
2177 }
2178 }
2179
2180 // --------------------------------------------------------- expressions
2181
2182 fn expr(&mut self, e: &Expr) -> Result<Val, String> {
2183 self.expr_at(e, None)
2184 }
2185
2186 /// Lower `e`, with the type the surrounding code expects of it.
2187 ///
2188 /// Rust infers an unsuffixed integer literal's type from its context and
2189 /// falls back to `i32`; Nim falls back to 64-bit `int`. Carrying the
2190 /// expected type down to the literal is what makes `let x: u8 = 255` and
2191 /// `x.wrapping_add(100)` mean the same thing on both sides. Without it the
2192 /// widths silently diverge, which is exactly the class of bug this
2193 /// project refuses to ship.
2194 fn expr_at(&mut self, e: &Expr, expect: Option<&Nim>) -> Result<Val, String> {
2195 match e {
2196 Expr::Lit(l) => self.lit_at(&l.lit, expect),
2197 Expr::Path(p) => {
2198 let name = path_name(&p.path);
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2199 if name == "None" {
2200 return Ok(Val::new(self.none_of(expect), expect.cloned()));
2201 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago2202 // A unit struct used as a value: `fmt::Error`, or a `struct S;`
2203 // declared here. In Nim that is a constructor call.
2204 if p.path.segments.len() > 1 {
2205 let ty = syn::Type::Path(syn::TypePath { attrs: Vec::new(), qself: None, path: p.path.clone() });
2206 if let Ok(Nim::Prim(n)) = ty::map(&ty) {
2207 if n == "FmtError" {
2208 return Ok(Val::new("FmtError()", Some(Nim::Prim(n))));
2209 }
2210 }
2211 }
2212 if self.structs.get(&name).is_some_and(|f| f.is_empty()) {
2213 return Ok(Val::new(
2214 format!("{}()", ident(&name)),
2215 Some(Nim::Named(name.clone(), vec![])),
2216 ));
2217 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2218 // A unit enum variant used as a value: `Error::InvalidLength`.
2219 if let Some((def, v)) = self.resolve_variant(&p.path) {
2220 let ty = Some(Nim::Named(def.name.clone(), vec![]));
2221 return Ok(if def.simple {
2222 Val::new(format!("{}.{}", ident(&def.name), ident(&v)), ty)
2223 } else {
2224 Val::new(format!("{}()", def.ctor_ident(&v)), ty)
2225 });
2226 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago2227 // A `for` binding that stands for an element of the container
2228 // it came from: using it must read (and assigning through it
2229 // must write) that element, not a copy.
2230 if let Some(a) = self.lookup_alias(&name) {
2231 return Ok(match a {
2232 Alias::Value { code, ty } => Val::new(code, ty),
2233 // A window *is* a slice; as a value it is the view it
2234 // denotes, which is what Rust's `&[T]` means too.
2235 Alias::Window { code, off, len, elem } => Val::new(
2236 format!("{}.toOpenArray({}, {} + {} - 1)", code, off, off, len),
2237 elem.map(|e| Nim::OpenArray(Box::new(e))),
2238 ),
2239 });
2240 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2241 if let Some(t) = self.lookup(&name) {
2242 return Ok(Val::new(ident(&name), Some(t)));
2243 }
2244 // A top-level function used as a value, e.g. passed to a
2245 // parameter of `impl Fn(..)` type.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago2246 if let Some(k) = self.resolve_fn(&p.path) {
2247 let sig = &self.fns[&k];
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2248 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 7h ago2249 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 8h ago2250 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2251 Ok(Val::new(ident(&name), None))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2252 }
2253 Expr::Paren(p) => {
2254 let v = self.expr_at(&p.expr, expect)?;
2255 Ok(Val::new(format!("({})", v.code), v.ty))
2256 }
2257 Expr::Group(g) => self.expr_at(&g.expr, expect),
2258 // `&x` is a value in Nim; `&mut x` in an argument position binds to
2259 // a `var` parameter, which is also just `x` at the call site.
2260 Expr::Reference(r) => self.expr_at(&r.expr, expect),
2261 Expr::Unary(u) => self.unary(u, expect),
2262 Expr::Binary(b) => self.binary(b, expect),
2263 Expr::Cast(c) => self.cast(c),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago2264 Expr::Index(i) if matches!(&*i.index, Expr::Range(_)) => {
2265 let Expr::Range(r) = &*i.index else { unreachable!() };
2266 let base = self.expr(&i.expr)?;
2267 let lo = match &r.start {
2268 Some(e) => format!("int({})", self.expr(e)?.code),
2269 None => "0".into(),
2270 };
2271 // Nim's `toOpenArray` takes an inclusive upper bound.
2272 let hi = match (&r.end, r.limits) {
2273 (Some(e), syn::RangeLimits::HalfOpen(_)) => {
2274 format!("int({}) - 1", self.expr(e)?.code)
2275 }
2276 (Some(e), syn::RangeLimits::Closed(_)) => {
2277 format!("int({})", self.expr(e)?.code)
2278 }
2279 (None, _) => format!("{}.len - 1", base.code),
2280 };
2281 let elem = elem_of(&base.ty)
2282 .ok_or("cannot infer the element type of this slice")?;
2283 Ok(Val::new(
2284 format!("{}.toOpenArray({}, {})", base.code, lo, hi),
2285 Some(Nim::OpenArray(Box::new(elem))),
2286 ))
2287 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2288 Expr::Index(i) => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago2289 if let Some(Alias::Window { code, off, elem, .. }) = self.window_of(&i.expr) {
2290 let idx = self.expr(&i.index)?;
2291 return Ok(Val::new(
2292 format!("{}[{} + int({})]", code, off, idx.code),
2293 elem,
2294 ));
2295 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2296 let base = self.expr(&i.expr)?;
2297 let idx = self.expr(&i.index)?;
2298 // Rust indexes with usize; Nim wants an `int`, and a `uint`
2299 // index is a type error there rather than a silent conversion.
2300 let idx_code = match &idx.ty {
2301 Some(t) if t.is_unsigned() => format!("int({})", idx.code),
2302 _ => idx.code.clone(),
2303 };
2304 let elem = match base.ty.clone() {
2305 Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) | Some(Nim::Array(_, t)) => Some(*t),
2306 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
2307 _ => None,
2308 };
2309 Ok(Val::new(format!("{}[{}]", base.code, idx_code), elem))
2310 }
2311 Expr::Field(f) => {
2312 let base = self.expr(&f.base)?;
2313 let name = match &f.member {
2314 syn::Member::Named(n) => n.to_string(),
2315 syn::Member::Unnamed(i) => format!("f{}", i.index),
2316 };
2317 let t = match &base.ty {
2318 Some(Nim::Named(s, _)) => self
2319 .structs
2320 .get(s)
2321 .and_then(|fs| fs.iter().find(|(f, _)| *f == name))
2322 .map(|(_, t)| t.clone()),
2323 _ => None,
2324 };
2325 Ok(Val::new(format!("{}.{}", base.code, ident(&name)), t))
2326 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago2327 // `unsafe` is a permission marker, not a semantic change: it does
2328 // not alter what the enclosed operations mean. So the block is
2329 // transparent here, and each operation inside still goes through
2330 // the ordinary lowering -- and is still rejected if it has no
2331 // faithful mapping.
2332 Expr::Unsafe(u) => match single_expr(&u.block) {
2333 Some(e) => self.expr_at(e, expect),
2334 None => Err("an `unsafe` block used as a value must be a single \
2335 expression"
2336 .into()),
2337 },
2338 Expr::Closure(c) => self.closure(c, expect),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2339 Expr::Try(t) => self.try_op(t),
2340 Expr::Call(c) => self.call(c, expect),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago2341 Expr::MethodCall(m) => self.method(m, expect),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago2342 Expr::Macro(m) if path_name(&m.mac.path) == "vec" => {
2343 // `vec![..]`'s elements take their type from the annotation on
2344 // the binding, exactly as Rust's would.
2345 let want = match expect {
2346 Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) => Some((**e).clone()),
2347 _ => None,
2348 };
2349 let saved = std::mem::replace(&mut self.vec_expect, want.clone());
2350 let code = self.macro_call(&m.mac);
2351 self.vec_expect = saved;
2352 let code = code?;
2353 let ty = match want {
2354 Some(e) => Some(Nim::Seq(Box::new(e))),
2355 None => self.vec_elem(&m.mac)?.map(|e| Nim::Seq(Box::new(e))),
2356 };
2357 Ok(Val::new(code, ty))
2358 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2359 Expr::Macro(m) => {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago2360 let is_write = matches!(path_name(&m.mac.path).as_str(), "write" | "writeln");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2361 let code = self.macro_call(&m.mac)?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago2362 // A formatter write is a statement that appends, not a value.
2363 let ty = if is_write { Some(Nim::Unit) } else { None };
2364 Ok(Val::new(code, ty))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2365 }
2366 Expr::Struct(s) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2367 if s.rest.is_some() {
2368 return Err("struct update syntax `..rest` is not implemented yet".into());
2369 }
2370 // `Shape::Rect { w: 3, h: 5 }` is a struct-shaped *enum variant*,
2371 // which is constructed positionally in Nim.
2372 if let Some((def, v)) = self.resolve_variant(&s.path) {
2373 let fields = def.get(&v).map(|v| v.fields.clone()).unwrap_or_default();
2374 let mut args = vec![String::new(); fields.len()];
2375 for f in &s.fields {
2376 let syn::Member::Named(m) = &f.member else {
2377 return Err("unsupported enum variant field".into());
2378 };
2379 let want = format!("{}_{}", v, m);
2380 let i = fields
2381 .iter()
2382 .position(|(n, _)| *n == want)
2383 .ok_or_else(|| format!("`{}::{}` has no field `{m}`", def.name, v))?;
2384 args[i] = self.expr_at(&f.expr, Some(&fields[i].1))?.code;
2385 }
2386 if let Some(i) = args.iter().position(|a| a.is_empty()) {
2387 return Err(format!(
2388 "`{}::{}` is missing field `{}`",
2389 def.name, v, fields[i].0
2390 ));
2391 }
2392 return Ok(Val::new(
2393 format!("{}({})", def.ctor_ident(&v), args.join(", ")),
2394 Some(Nim::Named(def.name.clone(), vec![])),
2395 ));
2396 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2397 let name = path_name(&s.path);
2398 let mut parts = Vec::new();
2399 for f in &s.fields {
2400 let fname = match &f.member {
2401 syn::Member::Named(n) => n.to_string(),
2402 syn::Member::Unnamed(i) => format!("f{}", i.index),
2403 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2404 let want = self
2405 .structs
2406 .get(&name)
2407 .and_then(|fs| fs.iter().find(|(n, _)| *n == fname))
2408 .map(|(_, t)| t.clone());
2409 let v = self.expr_at(&f.expr, want.as_ref())?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2410 parts.push(format!("{}: {}", ident(&fname), v.code));
2411 }
2412 Ok(Val::new(
2413 format!("{}({})", ident(&name), parts.join(", ")),
2414 Some(Nim::Named(name, vec![])),
2415 ))
2416 }
2417 Expr::Array(a) => {
2418 let mut parts = Vec::new();
2419 let mut elem = match expect {
2420 Some(Nim::Array(_, t)) | Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) => {
2421 Some((**t).clone())
2422 }
2423 _ => None,
2424 };
2425 for e in &a.elems {
2426 let want = elem.clone();
2427 let v = self.expr_at(e, want.as_ref())?;
2428 elem = elem.or(v.ty.clone());
2429 parts.push(v.code);
2430 }
2431 let t = elem.map(|t| Nim::Array(a.elems.len(), Box::new(t)));
2432 Ok(Val::new(format!("[{}]", parts.join(", ")), t))
2433 }
2434 Expr::Repeat(r) => {
2435 let v = self.expr(&r.expr)?;
2436 let n = self.expr(&r.len)?;
2437 let t = v.ty.clone().map(|t| Nim::Seq(Box::new(t)));
2438 Ok(Val::new(format!("newSeqWith(int({}), {})", n.code, v.code), t))
2439 }
2440 Expr::Tuple(t) if t.elems.is_empty() => Ok(Val::new("", Some(Nim::Unit))),
2441 Expr::Tuple(t) => {
2442 let mut parts = Vec::new();
2443 let mut tys = Vec::new();
2444 for e in &t.elems {
2445 let v = self.expr(e)?;
2446 tys.push(v.ty.clone());
2447 parts.push(v.code);
2448 }
2449 let ty = tys
2450 .iter()
2451 .cloned()
2452 .collect::<Option<Vec<_>>>()
2453 .map(Nim::Tuple);
2454 Ok(Val::new(format!("({})", parts.join(", ")), ty))
2455 }
2456 // `if` and `match` are expressions in both languages, but only
2457 // when every arm is itself a single expression.
2458 Expr::If(i) => self.if_expr(i, expect),
2459 Expr::Block(b) if b.block.stmts.len() == 1 => {
2460 if let Some(Stmt::Expr(e, None)) = b.block.stmts.first() {
2461 self.expr_at(e, expect)
2462 } else {
2463 Err("block expression with statements in value position is not implemented yet".into())
2464 }
2465 }
2466 other => Err(format!(
2467 "unsupported expression in value position: {}",
2468 expr_kind(other)
2469 )),
2470 }
2471 }
2472
2473 fn if_expr(&mut self, i: &syn::ExprIf, expect: Option<&Nim>) -> Result<Val, String> {
2474 let (Some(then), Some((_, els))) = (single_expr(&i.then_branch), &i.else_branch) else {
2475 return Err(
2476 "an `if` used as a value must have an `else` and single-expression arms".into(),
2477 );
2478 };
2479 let c = self.expr(&i.cond)?;
2480 let t = self.expr_at(then, expect)?;
2481 let want = expect.cloned().or_else(|| t.ty.clone());
2482 let e = match &**els {
2483 Expr::Block(b) => match single_expr(&b.block) {
2484 Some(x) => self.expr_at(x, want.as_ref())?,
2485 None => return Err("an `if` used as a value must have single-expression arms".into()),
2486 },
2487 other => self.expr_at(other, want.as_ref())?,
2488 };
2489 let ty = t.ty.clone().or(e.ty.clone());
2490 Ok(Val::new(
2491 format!("(if {}: {} else: {})", c.code, t.code, e.code),
2492 ty,
2493 ))
2494 }
2495
2496 fn lit_at(&mut self, l: &Lit, expect: Option<&Nim>) -> Result<Val, String> {
2497 match l {
2498 Lit::Int(i) => {
2499 let suffix = i.suffix();
2500 if let Some(why) = ty::rejected(suffix) {
2501 return Err(format!("integer literal `{}`: {}", i, why));
2502 }
2503 let digits = i.base10_digits().to_string();
2504 // Rust's default for an unconstrained integer literal is i32.
2505 // Nim's is `int` (64-bit). Making the width explicit is what
2506 // keeps overflow behaviour the same on both sides.
2507 let t = if suffix.is_empty() {
2508 match expect {
2509 Some(t) if t.is_integer() => t.clone(),
2510 // Rust's fallback for an otherwise-unconstrained
2511 // integer literal.
2512 _ => Nim::Prim("int32".into()),
2513 }
2514 } else {
2515 ty::prim(suffix).ok_or_else(|| format!("unknown literal suffix `{suffix}`"))?
2516 };
2517 Ok(Val::new(format!("{}'{}", digits, nim_suffix(&t)?), Some(t)))
2518 }
2519 Lit::Float(f) => {
2520 let t = match f.suffix() {
2521 "" => match expect {
2522 Some(Nim::Prim(p)) if p == "float32" => Nim::Prim("float32".into()),
2523 _ => Nim::Prim("float64".into()),
2524 },
2525 "f64" => Nim::Prim("float64".into()),
2526 "f32" => Nim::Prim("float32".into()),
2527 s => return Err(format!("unknown float suffix `{s}`")),
2528 };
2529 let d = f.base10_digits();
2530 let d = if d.contains('.') || d.contains('e') { d.to_string() } else { format!("{d}.0") };
2531 Ok(Val::new(d, Some(t)))
2532 }
2533 Lit::Bool(b) => Ok(Val::new(b.value.to_string(), Some(Nim::Prim("bool".into())))),
2534 Lit::Str(s) => Ok(Val::new(
2535 fmt::nim_str(&s.value()),
2536 Some(Nim::Prim("string".into())),
2537 )),
2538 Lit::Char(c) => Ok(Val::new(
2539 format!("Rune({})", c.value() as u32),
2540 Some(Nim::Prim("Rune".into())),
2541 )),
2542 Lit::Byte(b) => Ok(Val::new(
2543 format!("{}'u8", b.value()),
2544 Some(Nim::Prim("uint8".into())),
2545 )),
2546 Lit::ByteStr(b) => {
2547 let bytes: Vec<String> = b.value().iter().map(|x| format!("{x}'u8")).collect();
2548 Ok(Val::new(
2549 format!("@[{}]", bytes.join(", ")),
2550 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
2551 ))
2552 }
2553 other => Err(format!("unsupported literal: {other:?}")),
2554 }
2555 }
2556
2557 fn unary(&mut self, u: &syn::ExprUnary, expect: Option<&Nim>) -> Result<Val, String> {
2558 // `-128i8` is a literal in Rust, but `-(128'i8)` in Nim would overflow
2559 // the positive half of the range before the negation runs. Folding the
2560 // sign into the literal keeps `i8::MIN` and friends expressible.
2561 if let (UnOp::Neg(_), Expr::Lit(l)) = (&u.op, &*u.expr) {
2562 if matches!(l.lit, Lit::Int(_) | Lit::Float(_)) {
2563 let v = self.lit_at(&l.lit, expect)?;
2564 return Ok(Val::new(format!("-{}", v.code), v.ty));
2565 }
2566 }
2567 let v = self.expr_at(&u.expr, expect)?;
2568 match u.op {
2569 UnOp::Neg(_) => Ok(Val::new(format!("(-{})", v.code), v.ty)),
2570 // Rust's `!` is logical on bool and bitwise-complement on integers.
2571 // Nim spells those `not` and `not` as well, so one mapping covers
2572 // both — but only because Nim overloads `not` the same way.
2573 UnOp::Not(_) => Ok(Val::new(format!("(not {})", v.code), v.ty)),
2574 UnOp::Deref(_) => Ok(v),
2575 _ => Err("unsupported unary operator".into()),
2576 }
2577 }
2578
2579 fn binary(&mut self, b: &syn::ExprBinary, expect: Option<&Nim>) -> Result<Val, String> {
2580 // A comparison's operands are unrelated to the `bool` it produces, so
2581 // the outer expectation is not passed through to them.
2582 let down = match b.op {
2583 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
2584 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => None,
2585 _ => expect,
2586 };
2587 let mut l = self.expr_at(&b.left, down)?;
2588 // Rust unifies the two operand types; propagating whichever side is
2589 // known to the other reproduces that, and disagreement then surfaces
2590 // as a Nim type error rather than as a silent width change.
2591 let mut r = self.expr_at(&b.right, l.ty.as_ref().or(down))?;
2592 if l.ty.is_none() && r.ty.is_some() {
2593 l = self.expr_at(&b.left, r.ty.as_ref())?;
2594 }
2595 let r = std::mem::replace(&mut r, Val::untyped(""));
2596 let op = self.bin_op(&b.op, &l, &r)?;
2597 let ty = match b.op {
2598 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
2599 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => Some(Nim::Prim("bool".into())),
2600 // Rust's shift takes its result type from the *left* operand, and
2601 // the right may be a different width entirely.
2602 BinOp::Shl(_) | BinOp::Shr(_) => l.ty.clone(),
2603 _ => l.ty.clone().or(r.ty.clone()),
2604 };
2605 Ok(Val::new(format!("({} {} {})", l.code, op, r.code), ty))
2606 }
2607
2608 fn bin_op(&mut self, op: &BinOp, l: &Val, r: &Val) -> Result<&'static str, String> {
2609 Ok(match op {
2610 BinOp::Add(_) | BinOp::AddAssign(_) => "+",
2611 BinOp::Sub(_) | BinOp::SubAssign(_) => "-",
2612 BinOp::Mul(_) | BinOp::MulAssign(_) => "*",
2613 BinOp::Div(_) | BinOp::DivAssign(_) => {
2614 // Nim spells integer division `div`. Both languages truncate
2615 // toward zero, so once the right operator is chosen the
2616 // semantics match, including for negative operands.
2617 let t = l.ty.clone().or(r.ty.clone()).ok_or(
2618 "cannot tell integer from float division here; annotate the operands",
2619 )?;
2620 if t.is_integer() { "div" } else { "/" }
2621 }
2622 BinOp::Rem(_) | BinOp::RemAssign(_) => {
2623 let t = l.ty.clone().or(r.ty.clone()).ok_or(
2624 "cannot tell integer from float remainder here; annotate the operands",
2625 )?;
2626 if t.is_integer() { "mod" } else { return Err("float `%` is not implemented yet".into()) }
2627 }
2628 BinOp::And(_) => "and",
2629 BinOp::Or(_) => "or",
2630 // Nim's `and`/`or`/`xor` are bitwise on integers and logical on
2631 // bools, exactly as Rust's `&`/`|`/`^` are.
2632 BinOp::BitAnd(_) | BinOp::BitAndAssign(_) => "and",
2633 BinOp::BitOr(_) | BinOp::BitOrAssign(_) => "or",
2634 BinOp::BitXor(_) | BinOp::BitXorAssign(_) => "xor",
2635 // Settled empirically: Nim's `shr` on a signed integer is
2636 // arithmetic, matching Rust. See DESIGN.md.
2637 BinOp::Shl(_) | BinOp::ShlAssign(_) => "shl",
2638 BinOp::Shr(_) | BinOp::ShrAssign(_) => "shr",
2639 BinOp::Eq(_) => "==",
2640 BinOp::Ne(_) => "!=",
2641 BinOp::Lt(_) => "<",
2642 BinOp::Le(_) => "<=",
2643 BinOp::Gt(_) => ">",
2644 BinOp::Ge(_) => ">=",
2645 other => return Err(format!("unsupported binary operator {other:?}")),
2646 })
2647 }
2648
2649 fn cast(&mut self, c: &syn::ExprCast) -> Result<Val, String> {
2650 let v = self.expr(&c.expr)?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2651 let to = self.map_ty(&c.ty)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago2652 let from = v.ty.clone().ok_or_else(|| {
2653 format!(
2654 "cannot lower `as {}`: the source type is unknown, and `as` \
2655 truncates, so the source width decides the result",
2656 to.render()
2657 )
2658 })?;
2659
2660 let code = match (&from, &to) {
2661 (f, t) if f.is_integer() && t.is_integer() => {
2662 // Rust's `as` between integers is a pure bit-width truncation
2663 // or sign-extension — never a range check. Nim's `T(x)` *does*
2664 // range-check and would raise where Rust wraps, so `cast` is
2665 // the only faithful spelling. Probed against both compilers.
2666 format!("cast[{}]({})", t.render(), v.code)
2667 }
2668 (f, Nim::Prim(p)) if f.is_integer() && (p == "float64" || p == "float32") => {
2669 format!("{}({})", p, v.code)
2670 }
2671 (Nim::Prim(b), t) if b == "bool" && t.is_integer() => {
2672 format!("{}(ord({}))", t.render(), v.code)
2673 }
2674 (Nim::Prim(r), t) if r == "Rune" && t.is_integer() => {
2675 format!("cast[{}](int32({}))", t.render(), v.code)
2676 }
2677 (f, Nim::Prim(r)) if f.is_integer() && r == "Rune" => {
2678 format!("Rune(int32({}))", v.code)
2679 }
2680 (Nim::Prim(a), Nim::Prim(b)) if a == b => v.code.clone(),
2681 (f, t) if matches!(f, Nim::Prim(p) if p.starts_with("float")) && t.is_integer() => {
2682 // Rust saturates float->int casts; Nim rounds and range-errors.
2683 // Not the same operation, so it is refused rather than mapped.
2684 return Err(format!(
2685 "`as {}` from a float: Rust saturates, Nim rounds and range-checks; \
2686 no faithful mapping is implemented",
2687 t.render()
2688 ));
2689 }
2690 (f, t) => {
2691 return Err(format!(
2692 "unsupported cast from `{}` to `{}`",
2693 f.render(),
2694 t.render()
2695 ))
2696 }
2697 };
2698 Ok(Val::new(code, Some(to)))
2699 }
2700
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2701 /// Rust's `?`: return early on the error branch, otherwise yield the value.
2702 ///
2703 /// The early return is statements, not an expression, so they are emitted
2704 /// ahead of the line being built. Every caller lowers its sub-expressions
2705 /// 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 7h ago2706 /// The container, start offset, length and element type an expression
2707 /// denotes as a slice. A window alias contributes its own offset, so
2708 /// `dst.get_mut(..n)` followed by `.chunks_exact_mut(2)` indexes straight
2709 /// into the original buffer rather than through a rebuilt view.
2710 fn slice_parts(
2711 &mut self,
2712 e: &Expr,
2713 ) -> Result<(String, String, String, Option<Nim>), String> {
2714 if let Some(Alias::Window { code, off, len, elem }) = self.window_of(e) {
2715 return Ok((code, off, len, elem));
2716 }
2717 let v = self.expr(e)?;
2718 let len = format!("{}.len", v.code);
2719 Ok((v.code, "0".to_string(), len, elem_of(&v.ty)))
2720 }
2721
2722 /// Expand `opt.map(|x| body)` / `res.and_then(|x| body)` inline.
2723 fn map_closure(
2724 &mut self,
2725 what: &str,
2726 recv: &Val,
2727 kind: &str,
2728 targs: &[Nim],
2729 c: &syn::ExprClosure,
2730 ) -> Result<Val, String> {
2731 if c.capture.is_some() {
2732 return Err("a `move` closure captures by value; Nim's closures \
2733 capture by reference, and the two are not the same"
2734 .into());
2735 }
2736 if c.inputs.len() != 1 {
2737 return Err(format!("`.{what}()` takes a one-argument closure"));
2738 }
2739 let pname = match &c.inputs[0] {
2740 Pat::Ident(i) => i.ident.to_string(),
2741 Pat::Wild(_) => "unused0".into(),
2742 _ => return Err("only plain identifier closure parameters are supported".into()),
2743 };
2744
2745 let is_opt = kind == "Option";
2746 let tmp = self.fresh("Map");
2747 let recv_ty = Nim::Named(kind.to_string(), targs.to_vec());
2748 self.line(&format!("let {}: {} = {}", tmp, recv_ty.render(), recv.code));
2749
2750 let body = match &*c.body {
2751 Expr::Block(b) => single_expr(&b.block)
2752 .ok_or("a closure body with statements is not implemented yet")?,
2753 other => other,
2754 };
2755 self.push_scope();
2756 // The parameter names the payload itself, so a view stays a view.
2757 self.bind_alias(
2758 &pname,
2759 Alias::Value {
2760 code: format!("{}.val", tmp),
2761 ty: Some(targs[0].clone()),
2762 },
2763 );
2764 let v = self.expr(body)?;
2765 self.pop_scope();
2766
2767 let inner = v
2768 .ty
2769 .clone()
2770 .ok_or_else(|| format!("cannot infer the result type of `.{what}()`"))?;
2771 // `and_then`'s closure already returns the wrapped type; `map`'s does
2772 // not and has to be re-wrapped.
2773 let (test, some_branch, none_branch, out_ty) = if is_opt {
2774 let out = if what == "map" {
2775 Nim::Named("Option".into(), vec![inner.clone()])
2776 } else {
2777 inner.clone()
2778 };
2779 let body_code = if what == "map" {
2780 format!("rsSome[{}]({})", inner.render(), v.code)
2781 } else {
2782 v.code.clone()
2783 };
2784 (
2785 format!("{}.has", tmp),
2786 body_code,
2787 format!("rsNone[{}]()", elem_arg(&out).render()),
2788 out,
2789 )
2790 } else {
2791 let e = targs[1].clone();
2792 let out = if what == "map" {
2793 Nim::Named("Result".into(), vec![inner.clone(), e.clone()])
2794 } else {
2795 inner.clone()
2796 };
2797 let ok_ty = elem_arg(&out);
2798 let body_code = if what == "map" {
2799 format!("rsOk[{}, {}]({})", inner.render(), e.render(), v.code)
2800 } else {
2801 v.code.clone()
2802 };
2803 (
2804 format!("{}.ok", tmp),
2805 body_code,
2806 format!("rsErr[{}, {}]({}.err)", ok_ty.render(), e.render(), tmp),
2807 out,
2808 )
2809 };
2810 Ok(Val::new(
2811 format!("(if {}: {} else: {})", test, some_branch, none_branch),
2812 Some(out_ty),
2813 ))
2814 }
2815
2816 /// `|x| x + 1` -> a Nim anonymous proc.
2817 ///
2818 /// Nim's closures capture by reference, as Rust's non-`move` closures do.
2819 /// A `move` closure captures by value, which is a different thing, so it
2820 /// is rejected rather than lowered to the same construct.
2821 fn closure(&mut self, c: &syn::ExprClosure, expect: Option<&Nim>) -> Result<Val, String> {
2822 if c.capture.is_some() {
2823 return Err("a `move` closure captures by value; Nim's closures \
2824 capture by reference, and the two are not the same"
2825 .into());
2826 }
2827 let want: Option<&Vec<Nim>> = match expect {
2828 Some(Nim::Proc(a, _)) => Some(a),
2829 _ => None,
2830 };
2831
2832 self.push_scope();
2833 let mut parts = Vec::new();
2834 let mut ptys = Vec::new();
2835 for (i, p) in c.inputs.iter().enumerate() {
2836 let (name, ann) = match p {
2837 Pat::Ident(id) => (id.ident.to_string(), None),
2838 Pat::Type(t) => match &*t.pat {
2839 Pat::Ident(id) => (id.ident.to_string(), Some(self.map_ty(&t.ty)?)),
2840 _ => return Err("only plain identifier closure parameters are supported".into()),
2841 },
2842 Pat::Wild(_) => (format!("unused{i}"), None),
2843 _ => return Err("only plain identifier closure parameters are supported".into()),
2844 };
2845 let t = ann
2846 .or_else(|| want.and_then(|w| w.get(i).cloned()))
2847 .ok_or_else(|| {
2848 format!(
2849 "cannot infer the type of closure parameter `{name}`; \
2850 annotate it"
2851 )
2852 })?;
2853 parts.push(format!("{}: {}", ident(&name), t.render()));
2854 self.bind(&name, t.clone());
2855 ptys.push(t);
2856 }
2857
2858 let ret_ann = match &c.output {
2859 ReturnType::Default => None,
2860 ReturnType::Type(_, t) => Some(self.map_ty(t)?.owned()),
2861 };
2862 let body = match &*c.body {
2863 Expr::Block(b) => single_expr(&b.block)
2864 .ok_or("a closure body with statements is not implemented yet")?,
2865 other => other,
2866 };
2867 let v = self.expr_at(body, ret_ann.as_ref())?;
2868 self.pop_scope();
2869
2870 let ret = ret_ann
2871 .or_else(|| v.ty.clone())
2872 .ok_or("cannot infer a closure's return type; annotate it")?;
2873 Ok(Val::new(
2874 format!("(proc ({}): {} = {})", parts.join(", "), ret.render(), v.code),
2875 Some(Nim::Proc(ptys, Box::new(ret))),
2876 ))
2877 }
2878
2879 /// Lower a block's statements at the current indentation, without opening
2880 /// a Nim `block:` -- used for `unsafe { .. }`, which introduces no scope
2881 /// of its own in the generated code.
2882 fn nested_block_flat(&mut self, b: &syn::Block) -> Result<(), String> {
2883 self.push_scope();
2884 let tail = self.block_body(b)?;
2885 self.emit_tail(tail);
2886 self.pop_scope();
2887 Ok(())
2888 }
2889
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2890 fn try_op(&mut self, t: &syn::ExprTry) -> Result<Val, String> {
2891 if self.in_loop_cond {
2892 return Err("`?` in a loop condition is not implemented yet: the \
2893 early-return it expands to would be evaluated once, \
2894 before the loop, rather than on each iteration"
2895 .into());
2896 }
2897 let v = self.expr(&t.expr)?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago2898 if self.fmt_param.is_some() {
2899 // Writing into a string cannot fail, so `?` on a formatter write
2900 // is a no-op. `?` on anything else can fail, and `format!` panics
2901 // when a formatting impl returns an error -- so that is what the
2902 // error branch does here, with std's own message.
2903 if v.ty.as_ref() == Some(&Nim::Unit) {
2904 return Ok(v);
2905 }
2906 if let Some(Nim::Named(n, a)) = v.ty.clone() {
2907 if n == "Result" && a.len() == 2 {
2908 let tmp = self.fresh("Fmt");
2909 self.line(&format!(
2910 "let {}: {} = {}",
2911 tmp,
2912 Nim::Named(n, a.clone()).render(),
2913 v.code
2914 ));
2915 self.line(&format!("if not {}.ok:", tmp));
2916 self.line(
2917 " rsPanic(\"a formatting trait implementation returned an error\")",
2918 );
2919 return Ok(Val::new(format!("{}.val", tmp), Some(a[0].clone())));
2920 }
2921 }
2922 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago2923 if let (Some(guard), Some(w)) = (v.guard.clone(), v.window.clone()) {
2924 // An `Option`/`Result` of a view: the check is emitted here and the
2925 // view itself survives as an alias, since it has no value form.
2926 let ret = self.ret.clone().ok_or("`?` outside a function with a return type")?;
2927 let err = v.guard_err.clone().ok_or(
2928 "`?` on a `get`/`get_mut` needs an `ok_or` to say what the error is",
2929 )?;
2930 let Nim::Named(n, ra) = &ret else {
2931 return Err(format!("`?` in a function returning `{}`", ret.render()));
2932 };
2933 if n != "Result" || ra.len() != 2 {
2934 return Err(format!("`?` in a function returning `{}`", ret.render()));
2935 }
2936 self.line(&format!("if not {}:", guard));
2937 self.line(&format!(
2938 " return rsErr[{}, {}]({})",
2939 ra[0].render(),
2940 ra[1].render(),
2941 err
2942 ));
2943 let mut out = Val::new(String::new(), None);
2944 out.window = Some(w);
2945 return Ok(out);
2946 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2947 let vt = v.ty.clone().ok_or(
2948 "`?` needs a known `Result`/`Option` type; annotate the expression it applies to",
2949 )?;
2950 let ret = self
2951 .ret
2952 .clone()
2953 .ok_or("`?` outside a function with a return type")?;
2954 let tmp = self.fresh("Try");
2955 self.line(&format!("let {}: {} = {}", tmp, vt.render(), v.code));
2956
2957 match (&vt, &ret) {
2958 (Nim::Named(a, ai), Nim::Named(b, bi))
2959 if a == "Result" && b == "Result" && ai.len() == 2 && bi.len() == 2 =>
2960 {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago2961 // Rust inserts a `From::from` on the error here. Where the
2962 // types differ we call the crate's own `impl From`; we never
2963 // assume the conversion is the identity.
2964 let err = if ai[1] == bi[1] {
2965 format!("{}.err", tmp)
2966 } else {
2967 let key = (type_name(&ai[1]), type_name(&bi[1]));
2968 let f = self.from_impls.get(&key).cloned().ok_or_else(|| {
2969 format!(
2970 "`?` needs `From<{}> for {}` to convert the error, and \
2971 no such `impl` is in scope; assuming the conversion is \
2972 the identity would be a guess",
2973 key.0, key.1
2974 )
2975 })?;
2976 format!("{}({}.err)", f, tmp)
2977 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2978 self.line(&format!("if not {}.ok:", tmp));
2979 self.line(&format!(
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago2980 " return rsErr[{}, {}]({})",
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2981 bi[0].render(),
2982 bi[1].render(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago2983 err
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago2984 ));
2985 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
2986 }
2987 (Nim::Named(a, ai), Nim::Named(b, bi))
2988 if a == "Option" && b == "Option" && ai.len() == 1 && bi.len() == 1 =>
2989 {
2990 self.line(&format!("if not {}.has:", tmp));
2991 self.line(&format!(" return rsNone[{}]()", bi[0].render()));
2992 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
2993 }
2994 _ => Err(format!(
2995 "`?` on `{}` in a function returning `{}` is not a supported \
2996 combination",
2997 vt.render(),
2998 ret.render()
2999 )),
3000 }
3001 }
3002
3003 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 8h ago3004 let Expr::Path(p) = &*c.func else {
3005 return Err("only calls to named functions are supported".into());
3006 };
3007 let name = path_name(&p.path);
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3008 let target = self.resolve_fn(&p.path);
3009 let ptys: Vec<Nim> = target
3010 .as_ref()
3011 .and_then(|k| self.fns.get(k))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3012 .map(|s| s.params.clone())
3013 .unwrap_or_default();
3014 let mut args = Vec::new();
3015 for (i, a) in c.args.iter().enumerate() {
3016 let want = ptys.get(i).cloned();
3017 args.push(self.expr_at(a, want.as_ref())?);
3018 }
3019 let codes: Vec<String> = args.iter().map(|a| a.code.clone()).collect();
3020
3021 // Constructors from the prelude.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago3022 // `Ok`/`Err` must name the *whole* Result type, not just the half
3023 // being constructed: Nim cannot infer `E` from an `Ok(v)` alone.
3024 match name.as_str() {
3025 "Some" => {
3026 let inner = match expect {
3027 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].render(),
3028 _ => {
3029 return Err("`Some(..)` needs a known `Option<T>` type here; \
3030 annotate the binding or the return type"
3031 .into())
3032 }
3033 };
3034 return Ok(Val::new(
3035 format!("rsSome[{}]({})", inner, codes.join(", ")),
3036 expect.cloned(),
3037 ));
3038 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3039 "Ok" if self.fmt_param.is_some()
3040 && matches!(c.args.first(), Some(Expr::Tuple(t)) if t.elems.is_empty()) =>
3041 {
3042 // `Ok(())` ends a `fmt` body: nothing more is written.
3043 return Ok(Val::new(String::new(), Some(Nim::Unit)));
3044 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago3045 "Ok" | "Err" => {
3046 let (t, e) = match expect {
3047 Some(Nim::Named(n, a)) if n == "Result" && a.len() == 2 => {
3048 (a[0].render(), a[1].render())
3049 }
3050 _ => {
3051 return Err(format!(
3052 "`{name}(..)` needs a known `Result<T, E>` type here; \
3053 annotate the binding or the return type"
3054 ))
3055 }
3056 };
3057 let ctor = if name == "Ok" { "rsOk" } else { "rsErr" };
3058 let arg = if codes.is_empty() { String::new() } else { codes.join(", ") };
3059 return Ok(Val::new(
3060 format!("{}[{}, {}]({})", ctor, t, e, arg),
3061 expect.cloned(),
3062 ));
3063 }
3064 _ => {}
3065 }
3066
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3067 // A tuple struct applied to arguments: `HexDisplay(bytes)`. Nim's
3068 // object constructor names its fields even when Rust's does not.
3069 if let Some(fields) = self.structs.get(&name).cloned() {
3070 if fields.len() == c.args.len() {
3071 let mut parts = Vec::new();
3072 for (i, a) in c.args.iter().enumerate() {
3073 let v = self.expr_at(a, Some(&fields[i].1))?;
3074 parts.push(format!("{}: {}", ident(&fields[i].0), v.code));
3075 }
3076 return Ok(Val::new(
3077 format!("{}({})", ident(&name), parts.join(", ")),
3078 Some(Nim::Named(name.clone(), vec![])),
3079 ));
3080 }
3081 }
3082
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3083 // `core::str::from_utf8_unchecked(b)` reinterprets a byte view as a
3084 // string view; no copy, no validation, same memory.
3085 if name == "from_utf8_unchecked" && codes.len() == 1 {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3086 // `String::from_utf8_unchecked(v)` takes ownership and yields an
3087 // owned `String`; `str::from_utf8_unchecked(b)` borrows and yields
3088 // a view. Same name, different operations -- the qualifier says
3089 // which, and an unqualified call is ambiguous.
3090 let q = p
3091 .path
3092 .segments
3093 .iter()
3094 .rev()
3095 .nth(1)
3096 .map(|s| s.ident.to_string());
3097 return match q.as_deref() {
3098 Some("String") => Ok(Val::new(
3099 format!("rsStringOf({})", codes[0]),
3100 Some(Nim::Prim("string".into())),
3101 )),
3102 Some("str") => Ok(Val::new(
3103 format!("rsStrView({})", codes[0]),
3104 Some(Nim::OpenArray(Box::new(Nim::Prim("char".into())))),
3105 )),
3106 _ => Err(
3107 "`from_utf8_unchecked` must be written as `str::..` (a \
3108 borrowed view) or `String::..` (an owned string); the two \
3109 are different operations"
3110 .into(),
3111 ),
3112 };
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3113 }
3114
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago3115 // A tuple enum variant applied to arguments: `Shape::Circle(1.0)`.
3116 if let Some((def, v)) = self.resolve_variant(&p.path) {
3117 return Ok(Val::new(
3118 format!("{}({})", def.ctor_ident(&v), codes.join(", ")),
3119 Some(Nim::Named(def.name.clone(), vec![])),
3120 ));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3121 }
3122
3123 // A bare path that names a primitive type is Rust's tuple-struct-like
3124 // conversion, e.g. `String::from(..)`; handled by the method path.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago3125 // Calling a proc-typed local, which is how an `impl Fn(..)` parameter
3126 // is invoked.
3127 if let Some(Nim::Proc(_, ret)) = self.lookup(&name) {
3128 return Ok(Val::new(
3129 format!("{}({})", ident(&name), codes.join(", ")),
3130 Some((*ret).clone()),
3131 ));
3132 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3133 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 8h ago3134 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 8h ago3135 return Err(format!(
3136 "call to unknown function `{name}`; only functions defined in \
3137 this file and the supported standard-library subset can be lowered"
3138 ));
3139 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3140 let nim = match &target {
3141 Some((m, n)) => self.fn_name(m, n),
3142 None => ident(&name),
3143 };
3144 Ok(Val::new(format!("{}({})", nim, codes.join(", ")), ret))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3145 }
3146
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3147 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 8h ago3148 let name = m.method.to_string();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3149 if let Some(Alias::Window { len, .. }) = self.window_of(&m.receiver) {
3150 match name.as_str() {
3151 "len" => {
3152 return Ok(Val::new(format!("uint({})", len), Some(Nim::Prim("uint".into()))))
3153 }
3154 "is_empty" => {
3155 return Ok(Val::new(format!("({} == 0)", len), Some(Nim::Prim("bool".into()))))
3156 }
3157 other => {
3158 return Err(format!(
3159 "`.{other}()` on a slice window from `chunks_exact`/\
3160 `windows` is not implemented; only indexing and \
3161 `len()` are"
3162 ))
3163 }
3164 }
3165 }
3166 let recv = self.expr(&m.receiver)?;
3167 let rt0 = recv.ty.clone();
3168
3169// `s.get(a..b)` / `s.get_mut(a..b)`: an `Option<&[T]>`. Nim has no
3170 // way to put a view in an object, so instead of materialising an
3171 // Option the view and its validity condition travel together until
3172 // an `ok_or`/`?`/`unwrap` resolves them.
3173 if matches!(name.as_str(), "get" | "get_mut")
3174 && matches!(m.args.first(), Some(Expr::Range(_)))
3175 {
3176 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 7h ago3177 let (code, base, blen, belem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3178 let lo = match &r.start {
3179 Some(e) => format!("int({})", self.expr(e)?.code),
3180 None => "0".into(),
3181 };
3182 let len = match (&r.end, r.limits) {
3183 (Some(e), syn::RangeLimits::HalfOpen(_)) => {
3184 format!("(int({}) - {})", self.expr(e)?.code, lo)
3185 }
3186 (Some(e), syn::RangeLimits::Closed(_)) => {
3187 format!("(int({}) - {} + 1)", self.expr(e)?.code, lo)
3188 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3189 (None, _) => format!("({} - {})", blen, lo),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3190 };
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3191 // Hoisted, so the bounds are computed once -- as Rust computes
3192 // them once -- and cannot be re-evaluated later in a scope where
3193 // the names they mention have been shadowed by a loop pattern.
3194 let off_t = self.fresh("Off");
3195 let len_t = self.fresh("Len");
3196 self.line(&format!("let {}: int = {} + {}", off_t, base, lo));
3197 self.line(&format!("let {}: int = {}", len_t, len));
3198 let elem = belem
3199 .or_else(|| elem_of(&rt0))
3200 .ok_or("cannot infer the element type of this slice")?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3201 let mut v = Val::new(
3202 String::new(),
3203 Some(Nim::Named(
3204 "Option".into(),
3205 vec![Nim::OpenArray(Box::new(elem.clone()))],
3206 )),
3207 );
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3208 v.guard = Some(format!("({} + {} <= {})", off_t, len_t, blen));
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3209 v.window = Some(Alias::Window {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3210 code,
3211 off: off_t,
3212 len: len_t,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3213 elem: Some(elem),
3214 });
3215 return Ok(v);
3216 }
3217
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3218 // `.map`/`.and_then` over an `Option`/`Result` take a closure whose
3219 // parameter type comes from the receiver, so they are handled before
3220 // the arguments are lowered. The closure is expanded inline, with its
3221 // parameter aliased to the payload: that keeps the whole thing an
3222 // expression and avoids handing a view to a generic proc.
3223 if matches!(name.as_str(), "map" | "and_then") && m.args.len() == 1 {
3224 if let (Some(Nim::Named(kind, targs)), Expr::Closure(c)) =
3225 (recv.ty.clone(), &m.args[0])
3226 {
3227 if (kind == "Option" && targs.len() == 1) || (kind == "Result" && targs.len() == 2)
3228 {
3229 return self.map_closure(&name, &recv, &kind, &targs, c);
3230 }
3231 }
3232 }
3233
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3234 // `x.wrapping_add(1)` and `x.min(3)` take an argument of the receiver's
3235 // own type; `v.push(e)` takes the element type.
3236 let arg_want = match (name.as_str(), &recv.ty) {
3237 ("push", Some(Nim::Seq(t))) | ("push", Some(Nim::OpenArray(t))) => Some((**t).clone()),
3238 (_, t) => t.clone(),
3239 };
3240 let mut args = Vec::new();
3241 for a in &m.args {
3242 args.push(self.expr_at(a, arg_want.as_ref())?);
3243 }
3244 let a0 = args.first().map(|a| a.code.clone());
3245 let rt = recv.ty.clone();
3246
3247 let (code, ty) = match name.as_str() {
3248 // Rust's `len()` is `usize`; Nim's is `int`. The conversion is
3249 // explicit so that a `usize` binding type-checks on the Nim side.
3250 "len" => (format!("uint({}.len)", recv.code), Some(Nim::Prim("uint".into()))),
3251 "is_empty" => (format!("({}.len == 0)", recv.code), Some(Nim::Prim("bool".into()))),
3252 "push" => (format!("{}.add({})", recv.code, a0.unwrap_or_default()), Some(Nim::Unit)),
3253 "clone" | "to_vec" | "to_owned" | "as_slice" | "as_ref" | "as_mut" | "iter"
3254 | "into_iter" => (recv.code.clone(), rt.clone()),
3255 "unwrap" | "expect" => {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3256 // Expanded inline rather than called as a generic proc: when
3257 // the payload is a view, Nim can only borrow from a path
3258 // expression, which a proc body containing the panic is not.
3259 let (kind, inner) = match &rt {
3260 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => {
3261 ("Option", a[0].clone())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3262 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3263 Some(Nim::Named(n, a)) if n == "Result" && a.len() == 2 => {
3264 ("Result", a[0].clone())
3265 }
3266 _ => {
3267 return Err(format!(
3268 "`.{name}()` needs a known `Option`/`Result` receiver type"
3269 ))
3270 }
3271 };
3272 if self.in_loop_cond {
3273 return Err(format!(
3274 "`.{name}()` in a loop condition is not implemented yet: the \
3275 check it expands to would run once, before the loop"
3276 ));
3277 }
3278 let tmp = self.fresh("Unwrap");
3279 let rty = rt.clone().unwrap();
3280 self.line(&format!("let {}: {} = {}", tmp, rty.render(), recv.code));
3281 let (test, msg) = if kind == "Option" {
3282 (format!("{}.has", tmp), "called `Option::unwrap()` on a `None` value")
3283 } else {
3284 (format!("{}.ok", tmp), "called `Result::unwrap()` on an `Err` value")
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3285 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3286 let msg = if name == "expect" {
3287 args.first().map(|a| a.code.clone()).unwrap_or_else(|| fmt::nim_str(msg))
3288 } else {
3289 fmt::nim_str(msg)
3290 };
3291 self.line(&format!("if not {}:", test));
3292 self.line(&format!(" rsPanic({})", msg));
3293 // If the payload is a view, hand back an alias rather than a
3294 // value: Nim will not let a `let` borrow out of a local, and a
3295 // view is a reference anyway, so there is nothing to bind.
3296 // `{tmp}.val` is a plain field access, so substituting it at
3297 // each use re-evaluates nothing.
3298 if matches!(inner, Nim::OpenArray(_)) {
3299 let mut v = Val::new(format!("{}.val", tmp), Some(inner.clone()));
3300 v.window = Some(Alias::Value {
3301 code: format!("{}.val", tmp),
3302 ty: Some(inner),
3303 });
3304 return Ok(v);
3305 }
3306 (format!("{}.val", tmp), Some(inner))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3307 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3308 "ok_or" if recv.guard.is_some() => {
3309 let e = args.first().ok_or("`ok_or` takes one argument")?;
3310 let ety = e.ty.clone();
3311 let mut v = recv.clone();
3312 v.guard_err = Some(e.code.clone());
3313 v.ty = match (&recv.ty, ety) {
3314 (Some(Nim::Named(_, a)), Some(et)) if a.len() == 1 => {
3315 Some(Nim::Named("Result".into(), vec![a[0].clone(), et]))
3316 }
3317 _ => None,
3318 };
3319 return Ok(v);
3320 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago3321 "ok_or" => {
3322 let inner = match &rt {
3323 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].clone(),
3324 _ => return Err("`ok_or` needs a known `Option<T>` receiver".into()),
3325 };
3326 let e = args.first().ok_or("`ok_or` takes one argument")?;
3327 let ety = e
3328 .ty
3329 .clone()
3330 .ok_or("`ok_or` needs a known error type for its argument")?;
3331 (
3332 format!(
3333 "rsOkOr[{}, {}]({}, {})",
3334 inner.render(),
3335 ety.render(),
3336 recv.code,
3337 e.code
3338 ),
3339 Some(Nim::Named("Result".into(), vec![inner, ety])),
3340 )
3341 }
3342 "unwrap_or" => {
3343 let inner = match &rt {
3344 Some(Nim::Named(n, a)) if (n == "Option" && a.len() == 1) || (n == "Result" && a.len() == 2) => {
3345 Some(a[0].clone())
3346 }
3347 _ => None,
3348 };
3349 (
3350 format!("unwrapOr({}, {})", recv.code, a0.unwrap_or_default()),
3351 inner,
3352 )
3353 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3354 "is_some" => (format!("{}.has", recv.code), Some(Nim::Prim("bool".into()))),
3355 "is_none" => (format!("(not {}.has)", recv.code), Some(Nim::Prim("bool".into()))),
3356 "is_ok" => (format!("{}.ok", recv.code), Some(Nim::Prim("bool".into()))),
3357 "is_err" => (format!("(not {}.ok)", recv.code), Some(Nim::Prim("bool".into()))),
3358
3359 // Settled empirically: Nim's fixed-width *unsigned* arithmetic
3360 // wraps silently, matching Rust's `wrapping_*`. For *signed* types
3361 // Nim raises OverflowDefect, so the operation is routed through
3362 // the unsigned view of the same width, which is what Rust's
3363 // wrapping_* is defined to compute.
3364 "wrapping_add" | "wrapping_sub" | "wrapping_mul" => {
3365 let op = match name.as_str() {
3366 "wrapping_add" => "+",
3367 "wrapping_sub" => "-",
3368 _ => "*",
3369 };
3370 let t = rt.clone().ok_or_else(|| {
3371 format!("`{name}` needs a known receiver type to pick the wrapping width")
3372 })?;
3373 if !t.is_integer() {
3374 return Err(format!("`{name}` on a non-integer type"));
3375 }
3376 let arg = a0.ok_or_else(|| format!("`{name}` takes one argument"))?;
3377 if t.is_unsigned() {
3378 (format!("({} {} {})", recv.code, op, arg), Some(t))
3379 } else {
3380 let u = unsigned_peer(&t)?;
3381 (
3382 format!(
3383 "cast[{}](cast[{}]({}) {} cast[{}]({}))",
3384 t.render(), u, recv.code, op, u, arg
3385 ),
3386 Some(t),
3387 )
3388 }
3389 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3390 // Inside a formatting impl, a write through the `Formatter` *is*
3391 // the value the proc returns, so it lowers to the string written.
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3392 "write_str" | "write_char" if self.is_fmt_param(&m.receiver) => {
3393 let a = args.first().ok_or("`write_str` takes one argument")?;
3394 // A `&str` argument is a character view, not a Nim string.
3395 let text = match &a.ty {
3396 Some(Nim::Prim(p)) if p == "string" => a.code.clone(),
3397 _ => format!("rsDisplay({})", a.code),
3398 };
3399 (format!("result.add({})", text), Some(Nim::Unit))
3400 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3401 "abs" => (format!("abs({})", recv.code), rt.clone()),
3402 "min" => (format!("min({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
3403 "max" => (format!("max({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
3404 "to_string" => (format!("rsDisplay({})", recv.code), Some(Nim::Prim("string".into()))),
3405 "as_bytes" | "into_bytes" => (
3406 format!("rsBytes({})", recv.code),
3407 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
3408 ),
3409
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3410 "into" => {
3411 // `.into()` resolves through the `impl From` declarations, and
3412 // needs the target type to pick one.
3413 let from = rt
3414 .clone()
3415 .ok_or("`.into()` needs a known receiver type")?;
3416 let to = expect
3417 .ok_or("`.into()` needs a known target type; annotate the binding")?;
3418 let key = (type_name(&from), type_name(to));
3419 let f = self.from_impls.get(&key).cloned().ok_or_else(|| {
3420 format!(
3421 "no `impl From<{}> for {}` in this file, so `.into()` has \
3422 no conversion to call",
3423 key.0, key.1
3424 )
3425 })?;
3426 (format!("{}({})", f, recv.code), Some(to.clone()))
3427 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3428 _ => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3429 // A method defined in this file via `impl`, found by the
3430 // receiver's type rather than by name alone.
3431 let key = rt.as_ref().map(|t| (type_name(t), name.clone()));
3432 let sig = key.and_then(|k| self.methods.get(&k)).map(|s| s.ret.clone());
3433 if let Some(ret) = sig {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3434 let mut all = vec![recv.code.clone()];
3435 all.extend(args.iter().map(|a| a.code.clone()));
3436 (format!("{}({})", ident(&name), all.join(", ")), Some(ret))
3437 } else {
3438 return Err(format!(
3439 "unsupported method `.{name}()`; it is neither defined in \
3440 this file nor part of the standard-library subset that \
3441 has a verified Nim equivalent"
3442 ));
3443 }
3444 }
3445 };
3446 Ok(Val::new(code, ty))
3447 }
3448
3449 // -------------------------------------------------------------- macros
3450
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3451 /// The element type of a `vec![..]`, from its first element.
3452 fn vec_elem(&mut self, mac: &syn::Macro) -> Result<Option<Nim>, String> {
3453 let body = mac.tokens.to_string();
3454 if body.trim().is_empty() {
3455 return Ok(None);
3456 }
3457 let first: Option<Expr> = if body.contains(';') {
3458 // The whole body must be consumed or the parse fails, so the
3459 // length is parsed too even though only the element is wanted.
3460 mac.parse_body_with(|input: syn::parse::ParseStream| {
3461 let v: Expr = input.parse()?;
3462 input.parse::<syn::Token![;]>()?;
3463 let _len: Expr = input.parse()?;
3464 Ok(v)
3465 })
3466 .ok()
3467 } else {
3468 mac.parse_body_with(
3469 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
3470 )
3471 .ok()
3472 .and_then(|p| p.into_iter().next())
3473 };
3474 match first {
3475 Some(e) => Ok(self.expr(&e)?.ty),
3476 None => Ok(None),
3477 }
3478 }
3479
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3480 fn macro_call(&mut self, mac: &syn::Macro) -> Result<String, String> {
3481 let name = path_name(&mac.path);
3482 match name.as_str() {
3483 "println" | "print" | "eprintln" | "eprint" => {
3484 let s = self.format_args(mac)?;
3485 let nl = name.ends_with("ln");
3486 Ok(match (name.starts_with('e'), nl) {
3487 (false, true) => format!("echo {s}"),
3488 (false, false) => format!("stdout.write({s})"),
3489 (true, true) => format!("stderr.writeLine({s})"),
3490 (true, false) => format!("stderr.write({s})"),
3491 })
3492 }
3493 "format" => self.format_args(mac),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3494 "write" | "writeln" => {
3495 // `write!(f, "..", ..)` inside a formatting impl: the first
3496 // argument is the sink, the rest is an ordinary format call.
3497 let args: Vec<Expr> = mac
3498 .parse_body_with(syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated)
3499 .map_err(|e| format!("write!: {e}"))?
3500 .into_iter()
3501 .collect();
3502 let sink = args.first().ok_or("`write!` needs a sink")?;
3503 if !self.is_fmt_param(sink) {
3504 return Err("`write!` to anything but the `Formatter` of the \
3505 enclosing formatting impl is not implemented"
3506 .into());
3507 }
3508 let s = self.format_pieces(&args[1..])?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3509 let s = if name == "writeln" {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3510 format!("({} & \"\\n\")", s)
3511 } else {
3512 s
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3513 };
3514 Ok(format!("result.add({})", s))
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3515 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3516 "panic" => {
3517 let s = self.format_args(mac)?;
3518 Ok(format!("rsPanic({s})"))
3519 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3520 // `debug_assert*` fires in debug builds, which is the profile
3521 // this project models, so it lowers the same as `assert*`.
3522 "assert" | "debug_assert" => {
3523 let args: Vec<Expr> = mac
3524 .parse_body_with(
3525 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
3526 )
3527 .map_err(|e| format!("{name}!: {e}"))?
3528 .into_iter()
3529 .collect();
3530 let cond = args.first().ok_or("`assert!` needs a condition")?;
3531 let v = self.expr(cond)?;
3532 let msg = if args.len() > 1 {
3533 self.format_pieces(&args[1..])?
3534 } else {
3535 fmt::nim_str("assertion failed")
3536 };
3537 Ok(format!("(if not ({}): rsPanic({}))", v.code, msg))
3538 }
3539 "assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne" => {
3540 let args: Vec<Expr> = mac
3541 .parse_body_with(
3542 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
3543 )
3544 .map_err(|e| format!("{name}!: {e}"))?
3545 .into_iter()
3546 .collect();
3547 if args.len() < 2 {
3548 return Err(format!("`{name}!` takes two operands"));
3549 }
3550 let a = self.expr(&args[0])?;
3551 let b = self.expr_at(&args[1], a.ty.as_ref())?;
3552 let ne = name.ends_with("_ne");
3553 let op = if ne { "!=" } else { "==" };
3554 // Rust's message shows both sides; reproducing it keeps a
3555 // failing assertion as informative as the original.
3556 let label = if ne { "assertion failed: `(left != right)`" } else { "assertion failed: `(left == right)`" };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3557 Ok(format!(
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3558 "(if not (({}) {} ({})): rsPanic({} & \"\\n left: \" & rsDebug({}) & \"\\n right: \" & rsDebug({})))",
3559 a.code, op, b.code, fmt::nim_str(label), a.code, b.code
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3560 ))
3561 }
3562 "vec" => {
3563 let body = mac.tokens.to_string();
3564 if body.trim().is_empty() {
3565 return Ok("@[]".into());
3566 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago3567 // `vec![elem; n]` is the repeat form, not a list. The macro
3568 // body has no brackets, so it is parsed directly.
3569 if body.contains(';') {
3570 let (v, n) = mac
3571 .parse_body_with(|input: syn::parse::ParseStream| {
3572 let v: Expr = input.parse()?;
3573 input.parse::<syn::Token![;]>()?;
3574 let n: Expr = input.parse()?;
3575 Ok((v, n))
3576 })
3577 .map_err(|e| format!("vec![elem; n]: {e}"))?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3578 let want = self.vec_expect.clone();
3579 let v = self.expr_at(&v, want.as_ref())?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago3580 let n = self.expr(&n)?;
3581 return Ok(format!("newSeqWith(int({}), {})", n.code, v.code));
3582 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3583 let elems: syn::punctuated::Punctuated<Expr, syn::Token![,]> = mac
3584 .parse_body_with(syn::punctuated::Punctuated::parse_terminated)
3585 .map_err(|e| format!("vec!: {e}"))?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3586 let want = self.vec_expect.clone();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3587 let mut parts = Vec::new();
3588 for e in &elems {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3589 parts.push(self.expr_at(e, want.as_ref())?.code);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3590 }
3591 Ok(format!("@[{}]", parts.join(", ")))
3592 }
3593 other => Err(format!(
3594 "unsupported macro `{other}!`; a macro whose expansion is not \
3595 known cannot be lowered faithfully"
3596 )),
3597 }
3598 }
3599
3600 /// `println!("{} {}", a, b)` -> a Nim string-concatenation expression.
3601 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 8h ago3602 let args: Vec<Expr> = mac
3603 .parse_body_with(syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated)
3604 .map_err(|e| format!("format arguments: {e}"))?
3605 .into_iter()
3606 .collect();
3607 self.format_pieces(&args)
3608 }
3609
3610 /// `["{} {}", a, b]` -> a Nim string-concatenation expression.
3611 fn format_pieces(&mut self, args: &[Expr]) -> Result<String, String> {
3612 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 8h ago3613 if args.is_empty() {
3614 return Ok("\"\"".into());
3615 }
3616 return Err("the first argument must be a literal format string".into());
3617 };
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3618 let rest: Vec<&Expr> = args[1..].iter().collect();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3619
3620 let pieces = fmt::parse(&s.value())?;
3621 let mut parts: Vec<String> = Vec::new();
3622 let mut next = 0usize;
3623 let mut used = vec![false; rest.len()];
3624 for p in &pieces {
3625 match p {
3626 fmt::Piece::Lit(l) => parts.push(fmt::nim_str(l)),
3627 fmt::Piece::Arg { r#ref, spec } => {
3628 let v = match r#ref {
3629 fmt::Ref::Next => {
3630 let e = rest.get(next).ok_or("too few arguments for format string")?;
3631 used[next] = true;
3632 next += 1;
3633 self.expr(e)?
3634 }
3635 fmt::Ref::Index(i) => {
3636 let e = rest.get(*i).ok_or("format index out of range")?;
3637 used[*i] = true;
3638 self.expr(e)?
3639 }
3640 fmt::Ref::Named(n) => {
3641 let t = self.lookup(n).ok_or_else(|| {
3642 format!("`{{{n}}}` captures `{n}`, which is not in scope")
3643 })?;
3644 Val::new(ident(n), Some(t))
3645 }
3646 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 7h ago3647 let integer = v.ty.as_ref().is_some_and(|t| t.is_integer());
3648 if spec.radix.is_some() && !integer && v.ty.is_none() {
3649 return Err(
3650 "a radix format (`{:x}`, `{:b}`, ...) needs a known \
3651 argument type: on an integer it formats the bit \
3652 pattern, on anything else it calls that type's own \
3653 impl"
3654 .into(),
3655 );
3656 }
3657 parts.push(fmt::render_arg(&v.code, spec, integer));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3658 }
3659 }
3660 }
3661 // Rust rejects an argument that no `{}` consumes; so do we, rather
3662 // than dropping it from the output.
3663 if let Some(i) = used.iter().position(|u| !u) {
3664 return Err(format!(
3665 "argument {} is never used by the format string",
3666 i + 1
3667 ));
3668 }
3669 Ok(if parts.is_empty() { "\"\"".into() } else { parts.join(" & ") })
3670 }
3671}
3672
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago3673/// Whether a pattern introduces a binding.
3674fn binds(p: &Pat) -> bool {
3675 match p {
3676 Pat::Ident(_) => true,
3677 Pat::Guard(g) => binds(&g.pat),
3678 Pat::Paren(x) => binds(&x.pat),
3679 Pat::Reference(r) => binds(&r.pat),
3680 Pat::Or(o) => o.cases.iter().any(binds),
3681 Pat::TupleStruct(t) => t.elems.iter().any(|_| true),
3682 Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_) => true,
3683 _ => false,
3684 }
3685}
3686
3687/// Whether a pattern looks inside the value, which a Nim `case` cannot do.
3688fn destructures(p: &Pat) -> bool {
3689 matches!(
3690 p,
3691 Pat::TupleStruct(_) | Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_)
3692 ) || matches!(p, Pat::Guard(g) if destructures(&g.pat))
3693 || matches!(p, Pat::Paren(x) if destructures(&x.pat))
3694 || matches!(p, Pat::Reference(r) if destructures(&r.pat))
3695}
3696
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3697/// Whether an expression has a direct Nim expression form.
3698///
3699/// Nim's `if` is an expression only when every arm is a single expression, and
3700/// its `case` is never one here. Anything else has to be lowered as statements
3701/// that assign into a target.
3702fn expressible(e: &Expr) -> bool {
3703 match e {
3704 Expr::If(i) => {
3705 let Some(then) = single_expr(&i.then_branch) else { return false };
3706 if !expressible(then) {
3707 return false;
3708 }
3709 match &i.else_branch {
3710 None => false,
3711 Some((_, els)) => match &**els {
3712 Expr::Block(b) => single_expr(&b.block).is_some_and(expressible),
3713 other => expressible(other),
3714 },
3715 }
3716 }
3717 Expr::Match(_) | Expr::Block(_) | Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => false,
3718 _ => true,
3719 }
3720}
3721
3722/// The single expression a block consists of, if that is all it is. An `if`
3723/// can only be lowered as a Nim `if`-expression when both arms are this shape.
3724fn single_expr(b: &syn::Block) -> Option<&Expr> {
3725 match (b.stmts.len(), b.stmts.first()) {
3726 (1, Some(Stmt::Expr(e, None))) => Some(e),
3727 _ => None,
3728 }
3729}
3730
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago3731/// Substitute `params[i] -> args[i]` through a type. Enough of the type
3732/// grammar is covered to expand the aliases we accept; anything else is left
3733/// alone and will be reported by `ty::map` if it is unsupported.
3734fn substitute(t: &syn::Type, params: &[String], args: &[syn::Type]) -> syn::Type {
3735 use syn::Type;
3736 match t {
3737 Type::Path(p) => {
3738 if p.qself.is_none() && p.path.segments.len() == 1 {
3739 let seg = &p.path.segments[0];
3740 if seg.arguments.is_empty() {
3741 let name = seg.ident.to_string();
3742 if let Some(i) = params.iter().position(|x| *x == name) {
3743 return args[i].clone();
3744 }
3745 }
3746 }
3747 let mut p = p.clone();
3748 for seg in &mut p.path.segments {
3749 if let syn::PathArguments::AngleBracketed(a) = &mut seg.arguments {
3750 for g in &mut a.args {
3751 if let syn::GenericArgument::Type(t) = g {
3752 *t = substitute(t, params, args);
3753 }
3754 }
3755 }
3756 }
3757 Type::Path(p)
3758 }
3759 Type::Reference(r) => {
3760 let mut r = r.clone();
3761 r.elem = Box::new(substitute(&r.elem, params, args));
3762 Type::Reference(r)
3763 }
3764 Type::Slice(sl) => {
3765 let mut sl = sl.clone();
3766 sl.elem = Box::new(substitute(&sl.elem, params, args));
3767 Type::Slice(sl)
3768 }
3769 Type::Array(a) => {
3770 let mut a = a.clone();
3771 a.elem = Box::new(substitute(&a.elem, params, args));
3772 Type::Array(a)
3773 }
3774 Type::Tuple(tp) => {
3775 let mut tp = tp.clone();
3776 tp.elems = tp.elems.iter().map(|e| substitute(e, params, args)).collect();
3777 Type::Tuple(tp)
3778 }
3779 Type::Paren(p) => substitute(&p.elem, params, args),
3780 Type::Group(g) => substitute(&g.elem, params, args),
3781 other => other.clone(),
3782 }
3783}
3784
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3785// --------------------------------------------------------------- utilities
3786
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3787/// Whether a return type is a borrow of one of the arguments, which Nim
3788/// models with a view rather than with an owned copy.
3789fn returns_borrow(t: &syn::Type) -> bool {
3790 match t {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3791 syn::Type::Reference(r) => match &*r.elem {
3792 syn::Type::Slice(_) => true,
3793 // `&str` is a borrow of someone else's bytes too, and returning it
3794 // means returning a view, not an owned string.
3795 syn::Type::Path(p) => p.path.is_ident("str"),
3796 _ => false,
3797 },
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3798 syn::Type::Paren(p) => returns_borrow(&p.elem),
3799 syn::Type::Group(g) => returns_borrow(&g.elem),
3800 _ => false,
3801 }
3802}
3803
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 7h ago3804/// The module a `use` prefix names. `crate`, `self` and `super` all resolve
3805/// to the crate root, which is where a flattened module's items live unless
3806/// they came from one of the extra input files.
3807fn module_of(prefix: &[String]) -> String {
3808 match prefix.last() {
3809 Some(m) if m != "crate" && m != "self" && m != "super" => m.clone(),
3810 _ => String::new(),
3811 }
3812}
3813
3814/// The first type argument of an `Option[T]` / `Result[T, E]`.
3815fn elem_arg(t: &Nim) -> Nim {
3816 match t {
3817 Nim::Named(_, a) if !a.is_empty() => a[0].clone(),
3818 other => other.clone(),
3819 }
3820}
3821
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 8h ago3822/// The element type of a sequence-like Nim type.
3823fn elem_of(t: &Option<Nim>) -> Option<Nim> {
3824 match t {
3825 Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) | Some(Nim::Array(_, e)) => Some((**e).clone()),
3826 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
3827 _ => None,
3828 }
3829}
3830
3831/// The short name a Nim type is known by, for keying method tables.
3832fn type_name(t: &Nim) -> String {
3833 match t {
3834 Nim::Named(n, _) => n.clone(),
3835 Nim::Prim(p) => p.clone(),
3836 other => other.render(),
3837 }
3838}
3839
3840fn is_fmt_trait(t: &str) -> bool {
3841 matches!(t, "Display" | "Debug" | "LowerHex" | "UpperHex" | "Binary" | "Octal")
3842}
3843
3844/// The prelude proc a formatting trait's output is produced by.
3845fn fmt_proc(t: &str) -> &'static str {
3846 match t {
3847 "Display" => "rsDisplay",
3848 "Debug" => "rsDebug",
3849 "LowerHex" => "rsLowerHex",
3850 "UpperHex" => "rsUpperHex",
3851 "Binary" => "rsBinary",
3852 _ => "rsOctal",
3853 }
3854}
3855
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3856fn takes_self(sig: &syn::Signature) -> bool {
3857 matches!(sig.inputs.first(), Some(FnArg::Receiver(_)))
3858}
3859
3860fn path_name(p: &syn::Path) -> String {
3861 p.segments
3862 .last()
3863 .map(|s| s.ident.to_string())
3864 .unwrap_or_default()
3865}
3866
3867fn is_compound(op: &BinOp) -> bool {
3868 matches!(
3869 op,
3870 BinOp::AddAssign(_)
3871 | BinOp::SubAssign(_)
3872 | BinOp::MulAssign(_)
3873 | BinOp::DivAssign(_)
3874 | BinOp::RemAssign(_)
3875 | BinOp::BitAndAssign(_)
3876 | BinOp::BitOrAssign(_)
3877 | BinOp::BitXorAssign(_)
3878 | BinOp::ShlAssign(_)
3879 | BinOp::ShrAssign(_)
3880 )
3881}
3882
3883/// The Nim literal suffix for an integer type (`5'i32`).
3884fn nim_suffix(t: &Nim) -> Result<&'static str, String> {
3885 let Nim::Prim(p) = t else {
3886 return Err("not a primitive integer".into());
3887 };
3888 Ok(match p.as_str() {
3889 "int8" => "i8",
3890 "int16" => "i16",
3891 "int32" => "i32",
3892 "int64" => "i64",
3893 "int" => "i",
3894 "uint8" => "u8",
3895 "uint16" => "u16",
3896 "uint32" => "u32",
3897 "uint64" => "u64",
3898 "uint" => "u",
3899 other => return Err(format!("no Nim literal suffix for `{other}`")),
3900 })
3901}
3902
3903/// The unsigned integer type of the same width, used to spell `wrapping_*`.
3904fn unsigned_peer(t: &Nim) -> Result<&'static str, String> {
3905 let Nim::Prim(p) = t else {
3906 return Err("not a primitive integer".into());
3907 };
3908 Ok(match p.as_str() {
3909 "int8" => "uint8",
3910 "int16" => "uint16",
3911 "int32" => "uint32",
3912 "int64" => "uint64",
3913 "int" => "uint",
3914 other => return Err(format!("`{other}` has no unsigned peer")),
3915 })
3916}
3917
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 8h ago3918fn quote_meta(m: &syn::Meta) -> String {
3919 match m {
3920 syn::Meta::Path(p) => path_name(p),
3921 syn::Meta::List(l) => format!("{}(..)", path_name(&l.path)),
3922 syn::Meta::NameValue(nv) => format!("{} = ..", path_name(&nv.path)),
3923 }
3924}
3925
3926fn item_attrs(i: &Item) -> &[syn::Attribute] {
3927 match i {
3928 Item::Fn(f) => &f.attrs,
3929 Item::Struct(s) => &s.attrs,
3930 Item::Enum(e) => &e.attrs,
3931 Item::Impl(x) => &x.attrs,
3932 Item::Const(c) => &c.attrs,
3933 Item::Type(t) => &t.attrs,
3934 Item::Mod(m) => &m.attrs,
3935 Item::Use(u) => &u.attrs,
3936 Item::ExternCrate(e) => &e.attrs,
3937 Item::Static(s) => &s.attrs,
3938 _ => &[],
3939 }
3940}
3941
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 8h ago3942fn item_kind(i: &Item) -> &'static str {
3943 match i {
3944 Item::Trait(_) => "`trait`",
3945 Item::Static(_) => "`static`",
3946 Item::Macro(_) => "macro definition",
3947 Item::Union(_) => "`union`",
3948 Item::ForeignMod(_) => "`extern` block",
3949 _ => "item",
3950 }
3951}
3952
3953fn expr_kind(e: &Expr) -> &'static str {
3954 match e {
3955 Expr::Async(_) => "`async` block",
3956 Expr::Await(_) => "`.await`",
3957 Expr::Try(_) => "`?`",
3958 Expr::Range(_) => "range",
3959 Expr::Match(_) => "`match` (only statement position is implemented)",
3960 Expr::Let(_) => "`let` expression",
3961 Expr::Unsafe(_) => "`unsafe` block",
3962 Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => "loop (has no value in Nim)",
3963 _ => "expression",
3964 }
3965}