nandi/rustnimpublic Fork 0
0777223e3297e14f05bedeb07c87c7ff694732e2
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 · 4516 lines · 187.5 KBRust Blame HistoryRaw
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1//! Rust AST -> Nim source.
2//!
3//! The governing rule is in DESIGN.md and it shapes every function here:
4//! anything whose Rust semantics cannot be reproduced exactly in Nim returns
5//! `Err` with a reason. Nothing is emitted on a guess. Where a construct maps
6//! one-to-one (signed `shr`, unsigned wrapping, truncating `div`/`mod`) the
7//! mapping is direct and there is a comment saying why that is safe.
8
9use crate::fmt;
10use crate::ty::{self, Nim};
11use std::collections::HashMap;
12use syn::{
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago13 BinOp, Expr, FnArg, GenericArgument, Item, Lit, Local, Pat, ReturnType, Stmt, UnOp,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago14};
15
16// --------------------------------------------------------------- vocabulary
17
18/// Nim keywords. Rust code may legally use any of these as an identifier.
19const NIM_KEYWORDS: &[&str] = &[
20 "addr", "and", "as", "asm", "bind", "block", "break", "case", "cast",
21 "concept", "const", "continue", "converter", "defer", "discard", "distinct",
22 "div", "do", "elif", "else", "end", "enum", "except", "export", "finally",
23 "for", "from", "func", "if", "import", "in", "include", "interface", "is",
24 "isnot", "iterator", "let", "macro", "method", "mixin", "mod", "nil", "not",
25 "notin", "object", "of", "or", "out", "proc", "ptr", "raise", "ref",
26 "return", "shl", "shr", "static", "template", "try", "tuple", "type",
27 "using", "var", "when", "while", "xor", "result", "echo",
28];
29
30fn ident(name: &str) -> String {
31 if NIM_KEYWORDS.contains(&name) {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago32 return format!("{name}_r");
33 }
34 // Nim identifiers may not begin with an underscore, and may not contain
35 // two in a row. Rust uses both freely (`_unused`, `__private`).
36 let mut out = String::new();
37 let mut last_us = false;
38 for (i, c) in name.chars().enumerate() {
39 if c == '_' {
40 if i == 0 {
41 out.push('u');
42 out.push('_');
43 last_us = true;
44 continue;
45 }
46 if last_us {
47 continue;
48 }
49 last_us = true;
50 out.push('_');
51 } else {
52 last_us = false;
53 out.push(c);
54 }
55 }
56 if out.ends_with('_') {
57 out.push('x');
58 }
59 out
60}
61
62/// A `for`-loop source, resolved from a chain of iterator adaptors.
63///
64/// Rust's slice iterators are lazy and compose; Nim's `for` is over one
65/// sequence. So a chain is resolved into this shape and then emitted as a
66/// single index loop, with each binding becoming an *lvalue* into the original
67/// container. That is what makes `*dst = v` through `iter_mut()` write back to
68/// the caller's slice rather than to a copy.
69#[derive(Clone, Debug)]
70enum Iter {
71 /// `a..b` / `a..=b`.
72 Range { lo: String, hi: String, closed: bool, ty: Option<Nim> },
73 /// `for x in a`, `a.iter()`, `a.iter_mut()`. `off`/`len` let the same
74 /// shape cover a subslice view. `mutable` only affects whether the binding
75 /// may be assigned through.
76 Elems { code: String, off: String, len: String, elem: Option<Nim>, mutable: bool },
77 /// `a.chunks_exact(k)` / `chunks_exact_mut(k)`: the binding is a window of
78 /// `k` elements starting at `k * i`.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago79 Chunks { code: String, base: String, len: String, k: String, elem: Option<Nim>, mutable: bool },
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago80 /// `a.windows(k)`: like `Chunks` but advancing one element at a time.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago81 Windows { code: String, base: String, len: String, k: String, elem: Option<Nim> },
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago82 /// `.enumerate()` — the index is the first half of the pair.
83 Enumerate(Box<Iter>),
84 /// `.zip(other)` — stops at the shorter, as Rust's does.
85 Zip(Box<Iter>, Box<Iter>),
86}
87
88impl Iter {
89 /// The number of iterations, as a Nim expression in terms of the loop's
90 /// own containers.
91 fn len(&self) -> String {
92 match self {
93 Iter::Range { lo, hi, closed, .. } => {
94 let n = format!("(int({hi}) - int({lo}))");
95 if *closed { format!("({n} + 1)") } else { n }
96 }
97 Iter::Elems { len, .. } => len.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago98 Iter::Chunks { k, len, .. } => format!("({} div int({}))", len, k),
99 Iter::Windows { len, k, .. } => format!("(max(0, {} - int({}) + 1))", len, k),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago100 Iter::Enumerate(i) => i.len(),
101 Iter::Zip(a, b) => format!("min({}, {})", a.len(), b.len()),
102 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago103 }
104}
105
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago106/// How a `for`-loop pattern name refers back into the container it came from.
107#[derive(Clone, Debug)]
108enum Alias {
109 /// The name stands for this Nim lvalue expression.
110 Value { code: String, ty: Option<Nim> },
111 /// The name stands for a window: `code[off .. off + len - 1]`.
112 Window { code: String, off: String, len: String, elem: Option<Nim> },
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago113 /// The name stands for an iterator that has not been consumed yet, as in
114 /// `let it = xs.chunks_exact(k);`. Rust's iterators are values; ours are
115 /// resolved chains, so the chain is carried until a `for` consumes it.
116 Iterator(Box<Iter>),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago117}
118
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago119/// A lowered expression: its Nim text, and its type where we know it.
120///
121/// The type is not decoration. Nim needs it to pick `div` over `/`, to size a
122/// `cast`, and to annotate every binding so that Nim's own type checker
123/// catches a mistake in this file rather than letting it through as output
124/// that runs and is wrong.
125#[derive(Clone, Debug)]
126struct Val {
127 code: String,
128 ty: Option<Nim>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago129 /// Set when the value *is* a slice view rather than a Nim value: binding
130 /// it introduces an alias, not a copy.
131 window: Option<Alias>,
132 /// For `get`/`get_mut`: the condition under which the `Option` is `Some`,
133 /// carried until an `ok_or`/`?` or an `unwrap` consumes it. Nim's view
134 /// types cannot live inside an object, so an `Option` of a view has no
135 /// runtime representation -- it is tracked here instead.
136 guard: Option<String>,
137 /// The error an `ok_or` attached to that guard.
138 guard_err: Option<String>,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago139}
140
141impl Val {
142 fn new(code: impl Into<String>, ty: Option<Nim>) -> Self {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago143 Val { code: code.into(), ty, window: None, guard: None, guard_err: None }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago144 }
145 fn untyped(code: impl Into<String>) -> Self {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago146 Val::new(code, None)
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago147 }
148}
149
150struct Sig {
151 params: Vec<Nim>,
152 ret: Nim,
153}
154
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago155/// One variant of a Rust enum.
156#[derive(Clone)]
157struct Variant {
158 name: String,
159 /// `(nim field name, type)`. Empty for a unit variant. Tuple variants get
160 /// `f0`, `f1`, ...; every field is prefixed with the variant name because
161 /// Nim requires the branches of a variant object to have distinct fields.
162 fields: Vec<(String, Nim)>,
163}
164
165#[derive(Clone)]
166struct EnumDef {
167 name: String,
168 /// True when every variant is a unit variant, which Nim represents as a
169 /// plain `enum` rather than an object variant.
170 simple: bool,
171 variants: Vec<Variant>,
172}
173
174impl EnumDef {
175 fn kind_ident(&self, v: &str) -> String {
176 format!("k{}{}", self.name, v)
177 }
178 fn ctor_ident(&self, v: &str) -> String {
179 format!("{}{}", self.name, v)
180 }
181 fn get(&self, v: &str) -> Option<&Variant> {
182 self.variants.iter().find(|x| x.name == v)
183 }
184}
185
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago186pub struct Lowerer {
187 out: String,
188 indent: usize,
189 scopes: Vec<HashMap<String, Nim>>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago190 /// Names introduced by a `for` pattern that stand for an lvalue or a
191 /// window into a container, rather than for a variable of their own.
192 alias_scopes: Vec<HashMap<String, Alias>>,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago193 /// `(module, name) -> signature`. Rust keeps `lower::decode` and
194 /// `mixed::decode` apart by module; flattening into one Nim module would
195 /// merge them, so the module is part of the key and of the emitted name.
196 fns: HashMap<(String, String), Sig>,
197 /// Module being lowered: the file stem, or empty for the crate root.
198 cur_mod: String,
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago199 /// The type of the `impl` block being lowered, which `Self` names.
200 self_ty: Option<Nim>,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago201 /// `use` brings a name into scope from another module. Flattening loses
202 /// the module structure, so the mapping is recorded and consulted when a
203 /// bare call is resolved.
204 use_map: HashMap<String, String>,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago205 /// struct name -> (field, type)
206 structs: HashMap<String, Vec<(String, Nim)>>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago207 enums: HashMap<String, EnumDef>,
208 /// variant name -> enums declaring it. A variant named by more than one
209 /// enum must be written qualified, or it is rejected as ambiguous.
210 variant_owner: HashMap<String, Vec<String>>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago211 /// `(receiver type, method) -> signature`. Keyed by type because two
212 /// types may define the same method name, and Nim tells them apart by
213 /// overload resolution on the first parameter.
214 methods: HashMap<(String, String), Sig>,
215 /// The formatting traits implemented for each type, so `{}`/`{:?}`/`{:x}`
216 /// on a user type can be checked rather than assumed.
217 fmt_impls: HashMap<(String, String), ()>,
218 /// `(from, to)` conversions declared by `impl From<A> for B`.
219 from_impls: HashMap<(String, String), String>,
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago220 /// Operator traits implemented for a type, so `a += b` on a user type can
221 /// be dispatched to the impl rather than to Nim's built-in operator.
222 op_impls: HashMap<(String, String), ()>,
223 /// `(type, method) -> nim name`, for calls written as `Type::method(..)`.
224 statics: HashMap<(String, String), String>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago225 /// Forward declarations, emitted between the type definitions and the
226 /// bodies. Rust has no declaration-before-use rule and Nim does, so every
227 /// proc is declared up front rather than the input being reordered --
228 /// which would not work for mutual recursion anyway.
229 forwards: Vec<String>,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago230 /// Element type a `vec![..]` should build, from the binding's annotation.
231 vec_expect: Option<Nim>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago232 /// While lowering a formatting impl: the `Formatter` parameter's name.
233 /// Writes through it produce the proc's string result.
234 fmt_param: Option<String>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago235 /// `type X<T> = ...`, expanded before any type is mapped.
236 aliases: HashMap<String, (Vec<String>, syn::Type)>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago237 /// Module names supplied as separate input files. A `mod x;` naming one
238 /// of these is satisfied by that file having been passed in.
239 pub modules: Vec<String>,
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 17h ago240 /// How many items were actually translated. If this is zero the input
241 /// produced nothing but the prelude, and reporting success for that is
242 /// the precise failure this project exists to avoid -- see `findings/`.
243 emitted: usize,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago244 /// Cargo features that are on, as `--cfg feature=<name>`. `#[cfg]` is
245 /// evaluated against these exactly as rustc would, so an item that is
246 /// dropped here is genuinely not part of the program being compiled.
247 pub features: Vec<String>,
248 dropped_by_cfg: usize,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago249 /// Return type of the proc being lowered, so `return e` and a trailing
250 /// expression can type their literals the way Rust's inference would.
251 ret: Option<Nim>,
252 /// `(name, type)` that the arms of the `if`/`match` being lowered as a
253 /// statement must assign their value to.
254 target: Option<(String, Option<Nim>)>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago255 /// Set while lowering a `while` condition, which Nim re-evaluates each
256 /// iteration and so cannot have statements hoisted out of it.
257 in_loop_cond: bool,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago258 tmp: usize,
259}
260
261impl Lowerer {
262 pub fn new() -> Self {
263 Lowerer {
264 out: String::new(),
265 indent: 0,
266 scopes: vec![HashMap::new()],
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago267 alias_scopes: vec![HashMap::new()],
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago268 fns: HashMap::new(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago269 cur_mod: String::new(),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago270 self_ty: None,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago271 use_map: HashMap::new(),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago272 structs: HashMap::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago273 enums: HashMap::new(),
274 variant_owner: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago275 methods: HashMap::new(),
276 fmt_impls: HashMap::new(),
277 from_impls: HashMap::new(),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago278 op_impls: HashMap::new(),
279 statics: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago280 fmt_param: None,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago281 vec_expect: None,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago282 forwards: Vec::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago283 aliases: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago284 modules: Vec::new(),
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 17h ago285 emitted: 0,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago286 features: Vec::new(),
287 dropped_by_cfg: 0,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago288 ret: None,
289 target: None,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago290 in_loop_cond: false,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago291 tmp: 0,
292 }
293 }
294
295 // ------------------------------------------------------------ emission
296
297 fn line(&mut self, s: &str) {
298 for _ in 0..self.indent {
299 self.out.push_str(" ");
300 }
301 self.out.push_str(s);
302 self.out.push('\n');
303 }
304
305 fn blank(&mut self) {
306 self.out.push('\n');
307 }
308
309 fn fresh(&mut self, hint: &str) -> String {
310 self.tmp += 1;
311 format!("rsTmp{}{}", hint, self.tmp)
312 }
313
314 // --------------------------------------------------------------- scope
315
316 fn push_scope(&mut self) {
317 self.scopes.push(HashMap::new());
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago318 self.alias_scopes.push(HashMap::new());
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago319 }
320 fn pop_scope(&mut self) {
321 self.scopes.pop();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago322 self.alias_scopes.pop();
323 }
324 fn bind_alias(&mut self, name: &str, a: Alias) {
325 self.alias_scopes
326 .last_mut()
327 .unwrap()
328 .insert(name.to_string(), a);
329 }
330 fn lookup_alias(&self, name: &str) -> Option<Alias> {
331 self.alias_scopes
332 .iter()
333 .rev()
334 .find_map(|s| s.get(name).cloned())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago335 }
336 fn bind(&mut self, name: &str, t: Nim) {
337 self.scopes.last_mut().unwrap().insert(name.to_string(), t);
338 }
339 fn lookup(&self, name: &str) -> Option<Nim> {
340 self.scopes.iter().rev().find_map(|s| s.get(name).cloned())
341 }
342
343 // ---------------------------------------------------------------- file
344
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago345 pub fn lower_file(&mut self, files: &[(String, syn::File)]) -> Result<String, String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago346 self.out.push_str(include_str!("prelude.nim"));
347 self.blank();
348
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago349 // Pass 0: type aliases. A signature in one file may use an alias
350 // declared in another, and inputs are given in whatever order suits
351 // the caller, so aliases are registered before anything is mapped.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago352 for (m, f) in files {
353 self.cur_mod = m.clone();
354 for item in &f.items {
355 self.collect_aliases(item)?;
356 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago357 }
358
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago359 // Pass 1: signatures and struct shapes, so that a call can be typed
360 // regardless of declaration order (Rust has no forward declarations).
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago361 for (m, f) in files {
362 self.cur_mod = m.clone();
363 for item in &f.items {
364 self.collect(item)?;
365 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago366 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago367 // Pass 2: type definitions, which every signature may mention.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago368 for (m, f) in files {
369 self.cur_mod = m.clone();
370 for item in &f.items {
371 self.item_types(item)?;
372 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago373 }
374
375 // Pass 3: forward declarations. Rust imposes no declaration order and
376 // Nim does, so everything is declared before any body is emitted;
377 // reordering the input would not handle mutual recursion anyway.
378 if !self.forwards.is_empty() {
379 for f in self.forwards.clone() {
380 self.line(&f);
381 }
382 self.blank();
383 }
384
385 // Pass 4: bodies.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago386 for (m, f) in files {
387 self.cur_mod = m.clone();
388 for item in &f.items {
389 self.item(item)?;
390 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago391 }
392
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 17h ago393 // An input that translates to nothing is a failure, however plausible
394 // the output file looks. The prelude alone is not a translation.
395 if self.emitted == 0 {
396 return Err(format!(
397 "nothing was translated: the input has no items this lowering \
398 emits{}. Writing a file containing only the prelude would \
399 report success for work that was not done",
400 if self.dropped_by_cfg > 0 {
401 format!(
402 " ({} item(s) were dropped by `#[cfg]`; enable them with \
403 `--cfg feature=<name>`)",
404 self.dropped_by_cfg
405 )
406 } else {
407 String::new()
408 }
409 ));
410 }
411
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago412 if self.fns.contains_key(&(String::new(), "main".to_string())) {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago413 self.blank();
414 self.line("when isMainModule:");
415 self.indent += 1;
416 self.line("try:");
417 self.line(" main()");
418 // Rust's panic exits 101 with a message on stderr. Nim's Defects
419 // exit 1. Mapping them here is what keeps the differential runner's
420 // exit-status comparison meaningful for panicking programs.
421 self.line("except RustPanic as e:");
422 self.line(" stderr.writeLine(\"thread 'main' panicked: \" & e.msg)");
423 self.line(" quit(101)");
424 self.line("except Defect as e:");
425 self.line(" stderr.writeLine(\"thread 'main' panicked: \" & e.msg)");
426 self.line(" quit(101)");
427 self.indent -= 1;
428 }
429 Ok(std::mem::take(&mut self.out))
430 }
431
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago432 fn collect_aliases(&mut self, item: &Item) -> Result<(), String> {
433 if !self.cfg_keeps(item_attrs(item))? {
434 return Ok(());
435 }
436 match item {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago437 Item::Use(u) => self.collect_use(&u.tree, &[]),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago438 Item::Type(t) => {
439 let params: Vec<String> = t
440 .generics
441 .params
442 .iter()
443 .filter_map(|g| match g {
444 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
445 _ => None,
446 })
447 .collect();
448 self.aliases
449 .insert(t.ident.to_string(), (params, (*t.ty).clone()));
450 }
451 Item::Mod(m) if m.content.is_some() => {
452 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
453 for i in &items {
454 self.collect_aliases(i)?;
455 }
456 }
457 _ => {}
458 }
459 Ok(())
460 }
461
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago462 /// Record what a `use` brings into scope, as `name -> module`.
463 fn collect_use(&mut self, t: &syn::UseTree, prefix: &[String]) {
464 use syn::UseTree;
465 match t {
466 UseTree::Path(p) => {
467 let mut pre = prefix.to_vec();
468 pre.push(p.ident.to_string());
469 self.collect_use(&p.tree, &pre);
470 }
471 UseTree::Group(g) => {
472 for t in &g.items {
473 self.collect_use(t, prefix);
474 }
475 }
476 UseTree::Name(n) => {
477 let m = module_of(prefix);
478 self.use_map.insert(n.ident.to_string(), m);
479 }
480 UseTree::Rename(r) => {
481 let m = module_of(prefix);
482 self.use_map.insert(r.rename.to_string(), m);
483 }
484 // A glob brings in an unknown set of names; resolution falls back
485 // to the current module and the root, as it would without it.
486 UseTree::Glob(_) => {}
487 }
488 }
489
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago490 fn collect(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago491 // A `#[cfg(..)]` item exists only under some feature set. Dropping it
492 // silently would change what the program does; picking a feature set
493 // on the user's behalf would be a guess. So it is reported, except on
494 // items that carry no runtime meaning here anyway.
495 if !self.cfg_keeps(item_attrs(item))? {
496 self.dropped_by_cfg += 1;
497 return Ok(());
498 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago499 match item {
500 Item::Fn(f) => {
501 let (params, ret) = self.signature(&f.sig)?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago502 let name = f.sig.ident.to_string();
503 let nim = self.fn_name(&self.cur_mod, &name);
504 self.forwards.push(self.head_of(&nim, &f.sig, None)?);
505 self.fns
506 .insert((self.cur_mod.clone(), name), Sig { params, ret });
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago507 }
508 Item::Struct(s) => {
509 let mut fields = Vec::new();
510 for (i, f) in s.fields.iter().enumerate() {
511 let name = match &f.ident {
512 Some(id) => id.to_string(),
513 None => format!("f{i}"), // tuple struct
514 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago515 // A field of `&[T]` / `&str` type is a borrow, and Nim's
516 // view types allow it as an object field, so it stays a
517 // view rather than being copied into a `seq`.
518 let t = self.map_ty(&f.ty)?;
519 let t = if returns_borrow(&f.ty) { t.unvar() } else { t.owned() };
520 fields.push((name, t));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago521 }
522 self.structs.insert(s.ident.to_string(), fields);
523 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago524 Item::Mod(m) if m.content.is_some() => {
525 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
526 for i in &items {
527 self.collect(i)?;
528 }
529 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago530 Item::Type(t) => {
531 let params: Vec<String> = t
532 .generics
533 .params
534 .iter()
535 .filter_map(|g| match g {
536 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
537 _ => None,
538 })
539 .collect();
540 self.aliases
541 .insert(t.ident.to_string(), (params, (*t.ty).clone()));
542 }
543 Item::Enum(e) => {
544 let name = e.ident.to_string();
545 if e.generics.params.iter().any(|p| !matches!(p, syn::GenericParam::Lifetime(_))) {
546 return Err(format!("`enum {name}` is generic: not implemented yet"));
547 }
548 let mut variants = Vec::new();
549 for v in &e.variants {
550 let vname = v.ident.to_string();
551 if v.discriminant.is_some() {
552 return Err(format!(
553 "`{name}::{vname}` has an explicit discriminant; Rust's \
554 `as` on such an enum has a value this lowering does not \
555 yet preserve"
556 ));
557 }
558 let mut fields = Vec::new();
559 for (i, f) in v.fields.iter().enumerate() {
560 // Nim requires the branches of a variant object to have
561 // distinct field names, so each is prefixed.
562 let fname = match &f.ident {
563 Some(id) => format!("{vname}_{id}"),
564 None => format!("{vname}_f{i}"),
565 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago566 let t = self.map_ty(&f.ty)?;
567 let t = if returns_borrow(&f.ty) { t.unvar() } else { t.owned() };
568 fields.push((fname, t));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago569 }
570 variants.push(Variant { name: vname, fields });
571 }
572 let simple = variants.iter().all(|v| v.fields.is_empty());
573 for v in &variants {
574 self.variant_owner
575 .entry(v.name.clone())
576 .or_default()
577 .push(name.clone());
578 }
579 self.enums.insert(
580 name.clone(),
581 EnumDef { name, simple, variants },
582 );
583 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago584 Item::Impl(im) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago585 let self_ty = self.map_ty(&im.self_ty)?;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago586 let outer_self = self.self_ty.replace(self_ty.clone());
587 let r = self.collect_impl(im, &self_ty);
588 self.self_ty = outer_self;
589 return r;
590 }
591 _ => {}
592 }
593 Ok(())
594 }
595
596 fn collect_impl(&mut self, im: &syn::ItemImpl, self_ty: &Nim) -> Result<(), String> {
597 {
598 let self_ty = self_ty.clone();
599 let tyname = type_name(&self_ty);
600 if let Some((path, _)) = &im.trait_ {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago601 let tr = path_name(path);
602 if im.items.is_empty() {
603 // A marker trait with no items. We do not model trait
604 // resolution at all, so it generates nothing; any use
605 // that actually needed the trait (a `dyn`, a bound) is
606 // rejected where it appears.
607 return Ok(());
608 }
609 if is_fmt_trait(&tr) {
610 self.forwards.push(format!(
611 "proc {}*(self: {}): string",
612 fmt_proc(&tr),
613 self_ty.render()
614 ));
615 self.fmt_impls.insert((tyname, tr), ());
616 return Ok(());
617 }
618 if tr == "From" {
619 let syn::ImplItem::Fn(m) = &im.items[0] else {
620 return Err("`impl From` must contain `fn from`".into());
621 };
622 let (params, _) = self.signature(&m.sig)?;
623 let src = params
624 .first()
625 .ok_or("`fn from` takes one argument")?
626 .clone();
627 let name = format!("rsFrom{}{}", tyname, type_name(&src));
628 self.forwards.push(self.head_of(&name, &m.sig, None)?);
629 self.from_impls
630 .insert((type_name(&src), tyname), name);
631 return Ok(());
632 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago633 // Any other trait: its methods are emitted as procs on
634 // the type, named after the trait so two traits declaring
635 // the same method name do not collide. The *trait* is not
636 // modelled -- no dynamic dispatch, no bounds -- and a use
637 // that needs it is rejected where it appears.
638 if let Some(op) = operator_trait(&tr) {
639 self.op_impls.insert((tyname.clone(), op.to_string()), ());
640 }
641 for it in &im.items {
642 let syn::ImplItem::Fn(m) = it else {
643 return Err(format!("unsupported item in `impl {tr}`"));
644 };
645 let mname = m.sig.ident.to_string();
646 let (mut params, ret) = self.signature(&m.sig)?;
647 let recv = if takes_self(&m.sig) {
648 params.insert(0, self_ty.clone());
649 Some(self_ty.clone())
650 } else {
651 None
652 };
653 let nim = trait_method_name(&tyname, &tr, &mname);
654 self.forwards.push(self.head_of(&nim, &m.sig, recv.as_ref())?);
655 self.methods
656 .insert((tyname.clone(), mname.clone()), Sig { params, ret });
657 self.statics.insert((tyname.clone(), mname), nim);
658 }
659 return Ok(());
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago660 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago661 for it in &im.items {
662 if let syn::ImplItem::Fn(m) = it {
663 let (mut params, ret) = self.signature(&m.sig)?;
664 if takes_self(&m.sig) {
665 params.insert(0, self_ty.clone());
666 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago667 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago668 let nim = self.fn_name(&self.cur_mod, &m.sig.ident.to_string());
669 let head = self.head_of(&nim, &m.sig, recv.as_ref())?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago670 self.forwards.push(head);
671 self.methods
672 .insert((tyname.clone(), m.sig.ident.to_string()), Sig { params, ret });
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago673 self.statics
674 .insert((tyname.clone(), m.sig.ident.to_string()), nim);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago675 }
676 }
677 }
678 Ok(())
679 }
680
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago681 /// Whether `#[cfg(..)]` keeps this item, given the enabled features.
682 ///
683 /// This is evaluation, not approximation: rustc does the same thing, and
684 /// an item whose predicate is false is not part of the compiled program.
685 /// A predicate that cannot be evaluated is reported rather than assumed.
686 fn cfg_keeps(&self, attrs: &[syn::Attribute]) -> Result<bool, String> {
687 for a in attrs {
688 if a.path().is_ident("cfg") {
689 let pred: syn::Meta = a
690 .parse_args()
691 .map_err(|e| format!("cannot parse `#[cfg(..)]`: {e}"))?;
692 if !self.cfg_eval(&pred)? {
693 return Ok(false);
694 }
695 }
696 }
697 Ok(true)
698 }
699
700 fn cfg_eval(&self, m: &syn::Meta) -> Result<bool, String> {
701 match m {
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago702 // Bare flags whose value is determined by the profile this project
703 // models: a normal (non-`--test`) debug build, not a docs build.
704 // Anything platform-specific stays rejected, since we would be
705 // picking a target on the user's behalf.
706 syn::Meta::Path(p) if p.is_ident("test") => Ok(false),
707 syn::Meta::Path(p) if p.is_ident("debug_assertions") => Ok(true),
708 syn::Meta::Path(p) if p.is_ident("docsrs") || p.is_ident("doc") => Ok(false),
709 // The generated Nim is compiled for the same machine, so the
710 // target's word size and endianness are known rather than
711 // guessed. This does mean the output is host-shaped: a crate that
712 // branches on pointer width has had that branch decided here.
713 syn::Meta::NameValue(nv) if nv.path.is_ident("target_pointer_width") => {
714 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
715 return Err("`target_pointer_width = ..` expects a string".into());
716 };
717 Ok(s.value() == (usize::BITS).to_string())
718 }
719 syn::Meta::NameValue(nv) if nv.path.is_ident("target_endian") => {
720 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
721 return Err("`target_endian = ..` expects a string".into());
722 };
723 Ok(s.value() == if cfg!(target_endian = "big") { "big" } else { "little" })
724 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago725 syn::Meta::NameValue(nv) if nv.path.is_ident("feature") => {
726 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
727 return Err("`feature = ..` expects a string".into());
728 };
729 Ok(self.features.iter().any(|f| *f == s.value()))
730 }
731 syn::Meta::List(l) if l.path.is_ident("not") => {
732 let inner: syn::Meta = l.parse_args().map_err(|e| e.to_string())?;
733 Ok(!self.cfg_eval(&inner)?)
734 }
735 syn::Meta::List(l) if l.path.is_ident("all") || l.path.is_ident("any") => {
736 let items: syn::punctuated::Punctuated<syn::Meta, syn::Token![,]> = l
737 .parse_args_with(syn::punctuated::Punctuated::parse_terminated)
738 .map_err(|e| e.to_string())?;
739 let all = l.path.is_ident("all");
740 let mut acc = all;
741 for i in &items {
742 let v = self.cfg_eval(i)?;
743 acc = if all { acc && v } else { acc || v };
744 }
745 Ok(acc)
746 }
747 other => Err(format!(
748 "`#[cfg({})]` is not a predicate rustnim can evaluate; only \
749 `feature = \"..\"`, `not`, `all` and `any` are implemented",
750 quote_meta(other)
751 )),
752 }
753 }
754
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago755 /// Map a Rust type, resolving `Self` and expanding any `type` alias. Every type in the
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago756 /// lowering goes through here rather than calling `ty::map` directly, so
757 /// an alias cannot be missed in one position and honoured in another.
758 fn map_ty(&self, t: &syn::Type) -> Result<Nim, String> {
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago759 let n = ty::map(&self.expand(t, 0)?)?;
760 Ok(self.subst_self(n))
761 }
762
763 /// `Self` inside an `impl` block names the type being implemented.
764 fn subst_self(&self, t: Nim) -> Nim {
765 let Some(me) = &self.self_ty else { return t };
766 match t {
767 Nim::Named(n, _) if n == "Self" => me.clone(),
768 Nim::Seq(e) => Nim::Seq(Box::new(self.subst_self(*e))),
769 Nim::OpenArray(e) => Nim::OpenArray(Box::new(self.subst_self(*e))),
770 Nim::Array(n, e) => Nim::Array(n, Box::new(self.subst_self(*e))),
771 Nim::Var(e) => Nim::Var(Box::new(self.subst_self(*e))),
772 Nim::Named(n, a) => {
773 Nim::Named(n, a.into_iter().map(|x| self.subst_self(x)).collect())
774 }
775 other => other,
776 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago777 }
778
779 fn expand(&self, t: &syn::Type, depth: usize) -> Result<syn::Type, String> {
780 if depth > 16 {
781 return Err("type alias expansion did not terminate; is it cyclic?".into());
782 }
783 let syn::Type::Path(p) = t else { return Ok(t.clone()) };
784 // Only an unqualified name can be one of this file's aliases.
785 // `fmt::Result` and `core::result::Result` are different types that
786 // merely end in the same segment.
787 if p.path.segments.len() != 1 {
788 return Ok(t.clone());
789 }
790 let Some(seg) = p.path.segments.last() else { return Ok(t.clone()) };
791 let Some((params, target)) = self.aliases.get(&seg.ident.to_string()) else {
792 return Ok(t.clone());
793 };
794 let args: Vec<syn::Type> = match &seg.arguments {
795 syn::PathArguments::AngleBracketed(a) => a
796 .args
797 .iter()
798 .filter_map(|g| match g {
799 GenericArgument::Type(t) => Some(t.clone()),
800 _ => None,
801 })
802 .collect(),
803 _ => vec![],
804 };
805 if args.len() != params.len() {
806 // Flattening several files into one module can bring a crate's own
807 // alias (`type Result<T> = Result<T, Error>`) into scope at a site
808 // that meant the builtin (`Result<T, E>`). Rust kept them apart by
809 // module; here they are told apart by arity, and a use that fits
810 // neither is left for `ty::map` to report.
811 return Ok(t.clone());
812 }
813 self.expand(&substitute(target, params, &args), depth + 1)
814 }
815
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago816 /// The Nim name for a function, qualified by its module.
817 fn fn_name(&self, module: &str, name: &str) -> String {
818 if module.is_empty() {
819 ident(name)
820 } else {
821 format!("{}_{}", module, ident(name))
822 }
823 }
824
825 /// Resolve a call path to the module and name it refers to: an explicit
826 /// `mixed::decode`, then the current module, then the crate root.
827 fn resolve_fn(&self, path: &syn::Path) -> Option<(String, String)> {
828 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
829 let last = segs.last()?.clone();
830 if segs.len() >= 2 {
831 let q = &segs[segs.len() - 2];
832 if self.fns.contains_key(&(q.clone(), last.clone())) {
833 return Some((q.clone(), last));
834 }
835 }
836 let imported = self.use_map.get(&last).cloned();
837 for m in [Some(self.cur_mod.clone()), imported, Some(String::new())]
838 .into_iter()
839 .flatten()
840 {
841 if self.fns.contains_key(&(m.clone(), last.clone())) {
842 return Some((m, last));
843 }
844 }
845 None
846 }
847
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago848 /// The Nim `proc` head for a Rust signature, used both for the forward
849 /// declaration and for the definition, so the two cannot drift apart.
850 fn head_of(
851 &self,
852 name: &str,
853 sig: &syn::Signature,
854 recv: Option<&Nim>,
855 ) -> Result<String, String> {
856 let (ptys, ret) = self.signature(sig)?;
857 let mut parts = Vec::new();
858 if let Some(self_ty) = recv {
859 let mutable = matches!(
860 sig.inputs.first(),
861 Some(FnArg::Receiver(r))
862 if matches!(&r.kind, syn::ReceiverKind::Reference(_, _, m) if m.is_some())
863 );
864 let t = if mutable { Nim::Var(Box::new(self_ty.clone())) } else { self_ty.clone() };
865 parts.push(format!("self: {}", t.render()));
866 }
867 let typed: Vec<&syn::PatType> = sig
868 .inputs
869 .iter()
870 .filter_map(|a| match a {
871 FnArg::Typed(t) => Some(t),
872 _ => None,
873 })
874 .collect();
875 for (i, (p, t)) in typed.iter().zip(ptys.iter()).enumerate() {
876 let pname = match &*p.pat {
877 Pat::Ident(id) => id.ident.to_string(),
878 Pat::Wild(_) => format!("unused{}", parts.len()),
879 _ => return Err("only plain identifier parameters are supported".into()),
880 };
881 let _ = i;
882 parts.push(format!("{}: {}", ident(&pname), t.render()));
883 }
884 Ok(if ret == Nim::Unit {
885 format!("proc {}*({})", ident(name), parts.join(", "))
886 } else {
887 format!("proc {}*({}): {}", ident(name), parts.join(", "), ret.render())
888 })
889 }
890
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago891 fn signature(&self, sig: &syn::Signature) -> Result<(Vec<Nim>, Nim), String> {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago892 // `unsafe fn` marks a contract for callers; it does not change what
893 // the body means, so it lowers like any other proc.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago894 if sig.asyncness.is_some() {
895 return Err(format!("`async fn {}`: Nim has no equivalent", sig.ident));
896 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago897 // Lifetime parameters carry no runtime meaning and Nim is GC'd, so
898 // `fn encode<'a>(..)` is not generic for our purposes. Type and const
899 // parameters genuinely are, and are rejected.
900 if let Some(p) = sig.generics.params.iter().find(|p| !matches!(p, syn::GenericParam::Lifetime(_))) {
901 let what = match p {
902 syn::GenericParam::Const(_) => "const",
903 _ => "type",
904 };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago905 return Err(format!(
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago906 "`fn {}` has a {what} parameter: generics are not implemented yet",
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago907 sig.ident
908 ));
909 }
910 let mut params = Vec::new();
911 for a in &sig.inputs {
912 if let FnArg::Typed(t) = a {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago913 params.push(self.map_ty(&t.ty)?);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago914 }
915 }
916 let ret = match &sig.output {
917 ReturnType::Default => Nim::Unit,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago918 // A returned `&[T]` is a borrow of the caller's buffer, so it
919 // stays an `openArray` view. Only an owned type (`Vec<T>`) becomes
920 // a `seq`, which `owned()` would do to both.
921 ReturnType::Type(_, t) => {
922 let n = self.map_ty(t)?;
923 if returns_borrow(t) { n } else { n.owned() }
924 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago925 };
926 Ok((params, ret))
927 }
928
929 // --------------------------------------------------------------- items
930
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago931 /// Emit the type definitions only: they must precede every signature.
932 fn item_types(&mut self, item: &Item) -> Result<(), String> {
933 if !self.cfg_keeps(item_attrs(item))? {
934 return Ok(());
935 }
936 match item {
937 Item::Struct(_) | Item::Enum(_) | Item::Const(_) => self.item_inner(item),
938 Item::Mod(m) if m.content.is_some() => {
939 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
940 for i in &items {
941 self.item_types(i)?;
942 }
943 Ok(())
944 }
945 _ => Ok(()),
946 }
947 }
948
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago949 fn item(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago950 if !self.cfg_keeps(item_attrs(item))? {
951 return Ok(());
952 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago953 // Types were emitted in their own pass.
954 if matches!(item, Item::Struct(_) | Item::Enum(_) | Item::Const(_)) {
955 return Ok(());
956 }
957 self.item_inner(item)
958 }
959
960 fn item_inner(&mut self, item: &Item) -> Result<(), String> {
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 17h ago961 if !matches!(item, Item::Use(_) | Item::ExternCrate(_) | Item::Mod(_) | Item::Type(_)) {
962 self.emitted += 1;
963 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago964 match item {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago965 Item::Fn(f) => {
966 let nim = self.fn_name(&self.cur_mod, &f.sig.ident.to_string());
967 self.func_named(&nim, &f.sig, &f.block, None)
968 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago969 Item::Struct(s) => {
970 let name = s.ident.to_string();
971 let fields = self.structs[&name].clone();
972 self.line(&format!("type {}* = object", ident(&name)));
973 self.indent += 1;
974 if fields.is_empty() {
975 self.line("discard");
976 }
977 for (fname, fty) in &fields {
978 self.line(&format!("{}*: {}", ident(fname), fty.render()));
979 }
980 self.indent -= 1;
981 self.blank();
982 Ok(())
983 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago984 Item::Type(_) => Ok(()), // expanded at every use site
985 Item::Enum(e) => {
986 let def = self.enums[&e.ident.to_string()].clone();
987 self.emit_enum(&def);
988 Ok(())
989 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago990 Item::Const(c) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago991 let t = self.map_ty(&c.ty)?.owned();
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago992 // The annotation types the initialiser, exactly as it does for
993 // a `let`: `const MOD: u32 = 65521` is a u32 literal.
994 let v = self.expr_at(&c.expr, Some(&t))?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago995 self.bind(&c.ident.to_string(), t.clone());
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago996 // Only a top-level const is exported; `*` on a local is not
997 // Nim syntax.
998 let star = if self.indent == 0 { "*" } else { "" };
999 let line = format!(
1000 "const {}{}: {} = {}",
1001 ident(&c.ident.to_string()),
1002 star,
1003 t.render(),
1004 v.code
1005 );
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1006 self.line(&line);
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago1007 if self.indent == 0 {
1008 self.blank();
1009 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1010 Ok(())
1011 }
1012 Item::Impl(im) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1013 let self_ty = self.map_ty(&im.self_ty)?;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago1014 let outer = self.self_ty.replace(self_ty.clone());
1015 let r = self.impl_body(im, &self_ty);
1016 self.self_ty = outer;
1017 r
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1018 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1019 // `use` and `extern crate` are resolution directives with no Nim
1020 // analogue once everything is one module.
1021 Item::Use(_) | Item::ExternCrate(_) => Ok(()),
1022 Item::Mod(m) if m.content.is_some() => {
1023 // An inline `mod` is flattened; Nim has no nested modules in a
1024 // single file.
1025 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
1026 for i in &items {
1027 self.item(i)?;
1028 }
1029 Ok(())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1030 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1031 Item::Mod(m) => {
1032 // Satisfied if that file was passed in too; everything is one
1033 // Nim module, so the declaration itself emits nothing.
1034 if self.modules.iter().any(|x| *x == m.ident.to_string()) {
1035 return Ok(());
1036 }
1037 Err(format!(
1038 "`mod {};` refers to another file that was not passed to \
1039 rustnim; add it to the input list",
1040 m.ident
1041 ))
1042 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1043 other => Err(format!("unsupported item: {}", item_kind(other))),
1044 }
1045 }
1046
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1047 /// `None` carries no type of its own, so Nim needs the `Option[T]` named.
1048 fn none_of(&self, expect: Option<&Nim>) -> String {
1049 match expect {
1050 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => {
1051 format!("rsNone[{}]()", a[0].render())
1052 }
1053 _ => "rsNone()".to_string(),
1054 }
1055 }
1056
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago1057 fn impl_body(&mut self, im: &syn::ItemImpl, self_ty: &Nim) -> Result<(), String> {
1058 if let Some((path, _)) = &im.trait_ {
1059 let tr = path_name(path);
1060 if im.items.is_empty() {
1061 return Ok(());
1062 }
1063 if is_fmt_trait(&tr) {
1064 let syn::ImplItem::Fn(m) = &im.items[0] else {
1065 return Err(format!("unsupported item in `impl {tr}`"));
1066 };
1067 return self.fmt_impl(&tr, self_ty, &m.sig, &m.block);
1068 }
1069 if tr == "From" {
1070 let syn::ImplItem::Fn(m) = &im.items[0] else {
1071 return Err("`impl From` must contain `fn from`".into());
1072 };
1073 let name = {
1074 let (params, _) = self.signature(&m.sig)?;
1075 let src = params.first().cloned().ok_or("`fn from` takes one argument")?;
1076 self.from_impls[&(type_name(&src), type_name(self_ty))].clone()
1077 };
1078 return self.func_named(&name, &m.sig, &m.block, None);
1079 }
1080 let tyname = type_name(self_ty);
1081 for it in &im.items {
1082 let syn::ImplItem::Fn(m) = it else {
1083 return Err(format!("unsupported item in `impl {tr}`"));
1084 };
1085 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
1086 let nim = trait_method_name(&tyname, &tr, &m.sig.ident.to_string());
1087 self.func_named(&nim, &m.sig, &m.block, recv)?;
1088 }
1089 return Ok(());
1090 }
1091 for it in &im.items {
1092 match it {
1093 syn::ImplItem::Fn(m) => {
1094 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
1095 let nim = self.fn_name(&self.cur_mod, &m.sig.ident.to_string());
1096 self.func_named(&nim, &m.sig, &m.block, recv)?;
1097 }
1098 _ => return Err("only `fn` items are supported inside `impl`".into()),
1099 }
1100 }
1101 Ok(())
1102 }
1103
1104 /// The type an operator impl declares for its right-hand operand.
1105 fn op_param(&self, t: &Option<Nim>, op: &str) -> Option<Nim> {
1106 let n = type_name(t.as_ref()?);
1107 let sig = self.methods.get(&(n, op_method(op).to_string()))?;
1108 sig.params.get(1).cloned().map(|t| t.unvar())
1109 }
1110
1111 /// The proc implementing `op` for a user type, if there is one.
1112 fn op_proc(&self, t: &Option<Nim>, op: &str) -> Option<String> {
1113 let n = type_name(t.as_ref()?);
1114 let tr = OPERATOR_TRAITS.iter().find(|(_, o)| *o == op)?.0;
1115 if self.op_impls.contains_key(&(n.clone(), op.to_string())) {
1116 Some(trait_method_name(&n, tr, OP_METHOD.iter().find(|(o, _)| *o == op)?.1))
1117 } else {
1118 None
1119 }
1120 }
1121
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1122 fn emit_enum(&mut self, def: &EnumDef) {
1123 let name = ident(&def.name);
1124 if def.simple {
1125 // Every variant is a unit variant, so a plain Nim enum is an exact
1126 // fit: it compares, orders and `case`-checks like Rust's.
1127 self.line(&format!("type {name}* = enum"));
1128 self.indent += 1;
1129 for v in &def.variants {
1130 self.line(&format!("{}", ident(&v.name)));
1131 }
1132 self.indent -= 1;
1133 self.blank();
1134 self.line(&format!("proc rsDebug*(x: {name}): string ="));
1135 self.indent += 1;
1136 self.line("case x");
1137 for v in &def.variants {
1138 self.line(&format!("of {}.{}: \"{}\"", name, ident(&v.name), v.name));
1139 }
1140 self.indent -= 1;
1141 self.blank();
1142 return;
1143 }
1144
1145 // A data-carrying enum is a Nim object variant: one discriminant enum
1146 // plus a branch per variant. This is the same shape the prelude uses
1147 // for `Option` and `Result`.
1148 self.line("type");
1149 self.indent += 1;
1150 self.line(&format!("{}Kind* = enum", name));
1151 self.indent += 1;
1152 for v in &def.variants {
1153 self.line(&def.kind_ident(&v.name));
1154 }
1155 self.indent -= 1;
1156 self.blank();
1157 self.line(&format!("{}* = object", name));
1158 self.indent += 1;
1159 self.line(&format!("case kind*: {}Kind", name));
1160 for v in &def.variants {
1161 if v.fields.is_empty() {
1162 self.line(&format!("of {}: discard", def.kind_ident(&v.name)));
1163 } else {
1164 self.line(&format!("of {}:", def.kind_ident(&v.name)));
1165 self.indent += 1;
1166 for (f, t) in &v.fields {
1167 self.line(&format!("{}*: {}", ident(f), t.render()));
1168 }
1169 self.indent -= 1;
1170 }
1171 }
1172 self.indent -= 2;
1173 self.blank();
1174
1175 for v in &def.variants {
1176 let args: Vec<String> = v
1177 .fields
1178 .iter()
1179 .enumerate()
1180 .map(|(i, (_, t))| format!("a{}: {}", i, t.render()))
1181 .collect();
1182 let inits: Vec<String> = v
1183 .fields
1184 .iter()
1185 .enumerate()
1186 .map(|(i, (f, _))| format!("{}: a{}", ident(f), i))
1187 .collect();
1188 let mut all = vec![format!("kind: {}", def.kind_ident(&v.name))];
1189 all.extend(inits);
1190 self.line(&format!(
1191 "proc {}*({}): {} = {}({})",
1192 def.ctor_ident(&v.name),
1193 args.join(", "),
1194 name,
1195 name,
1196 all.join(", ")
1197 ));
1198 }
1199 self.blank();
1200
1201 self.line(&format!("proc rsDebug*(x: {name}): string ="));
1202 self.indent += 1;
1203 self.line("case x.kind");
1204 for v in &def.variants {
1205 if v.fields.is_empty() {
1206 self.line(&format!("of {}: \"{}\"", def.kind_ident(&v.name), v.name));
1207 } else {
1208 let parts: Vec<String> = v
1209 .fields
1210 .iter()
1211 .map(|(f, _)| format!("rsDebug(x.{})", ident(f)))
1212 .collect();
1213 self.line(&format!(
1214 "of {}: \"{}(\" & {} & \")\"",
1215 def.kind_ident(&v.name),
1216 v.name,
1217 parts.join(" & \", \" & ")
1218 ));
1219 }
1220 }
1221 self.indent -= 1;
1222 self.blank();
1223 }
1224
1225 /// Resolve a Rust path like `Error::InvalidLength` or a bare `InvalidLength`
1226 /// to the enum that declares it.
1227 fn resolve_variant(&self, path: &syn::Path) -> Option<(EnumDef, String)> {
1228 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
1229 let last = segs.last()?.clone();
1230 if segs.len() >= 2 {
1231 if let Some(def) = self.enums.get(&segs[segs.len() - 2]) {
1232 if def.get(&last).is_some() {
1233 return Some((def.clone(), last));
1234 }
1235 }
1236 }
1237 // Unqualified: only unambiguous if exactly one enum declares it.
1238 match self.variant_owner.get(&last) {
1239 Some(owners) if owners.len() == 1 => {
1240 let def = self.enums.get(&owners[0])?;
1241 Some((def.clone(), last))
1242 }
1243 _ => None,
1244 }
1245 }
1246
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1247 /// Lower `impl Display for T`'s `fn fmt` into a proc returning a string.
1248 ///
1249 /// Rust's `Formatter` is a sink that a `fmt` method writes into; the
1250 /// observable result of `{}` is exactly the bytes written. So the method
1251 /// becomes `proc rsDisplay(self: T): string` and every write through the
1252 /// formatter produces that string. A `fmt` body that does anything else
1253 /// with the formatter -- padding, precision, `debug_struct` -- is rejected,
1254 /// because those affect the output and this model does not carry them.
1255 /// The window an expression names, if it names one.
1256 fn window_of(&self, e: &Expr) -> Option<Alias> {
1257 match e {
1258 Expr::Path(p) => match self.lookup_alias(&path_name(&p.path)) {
1259 Some(a @ Alias::Window { .. }) => Some(a),
1260 _ => None,
1261 },
1262 Expr::Reference(r) => self.window_of(&r.expr),
1263 Expr::Paren(p) => self.window_of(&p.expr),
1264 Expr::Unary(u) if matches!(u.op, UnOp::Deref(_)) => self.window_of(&u.expr),
1265 _ => None,
1266 }
1267 }
1268
1269 /// Whether an expression is the `Formatter` parameter of the formatting
1270 /// impl currently being lowered.
1271 fn is_fmt_param(&self, e: &Expr) -> bool {
1272 let Some(f) = &self.fmt_param else { return false };
1273 match e {
1274 Expr::Path(p) => path_name(&p.path) == *f,
1275 Expr::Reference(r) => self.is_fmt_param(&r.expr),
1276 Expr::Paren(p) => self.is_fmt_param(&p.expr),
1277 _ => false,
1278 }
1279 }
1280
1281 fn fmt_impl(
1282 &mut self,
1283 tr: &str,
1284 self_ty: &Nim,
1285 sig: &syn::Signature,
1286 body: &syn::Block,
1287 ) -> Result<(), String> {
1288 let proc_name = fmt_proc(tr);
1289 // The formatter is the parameter after `self`.
1290 let f = sig
1291 .inputs
1292 .iter()
1293 .filter_map(|a| match a {
1294 FnArg::Typed(t) => match &*t.pat {
1295 Pat::Ident(i) => Some(i.ident.to_string()),
1296 _ => None,
1297 },
1298 _ => None,
1299 })
1300 .next()
1301 .ok_or("`fn fmt` needs a `Formatter` parameter")?;
1302
1303 self.push_scope();
1304 self.bind("self", self_ty.clone());
1305 let saved = self.fmt_param.replace(f);
1306 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 18h ago1307 // No assignment target: a formatter write *appends*, because a `fmt`
1308 // body may write repeatedly -- `UpperHex` writes once per byte in a
1309 // loop -- and assigning would keep only the last one.
1310 let outer_target = self.target.take();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1311
1312 self.line(&format!(
1313 "proc {}*(self: {}): string =",
1314 proc_name,
1315 self_ty.render()
1316 ));
1317 self.indent += 1;
1318 let before = self.out.len();
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago1319 let tail = self.block_body(body)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1320 self.emit_tail(tail);
1321 if self.out.len() == before {
1322 self.line("discard");
1323 }
1324 self.indent -= 1;
1325
1326 self.target = outer_target;
1327 self.ret = outer_ret;
1328 self.fmt_param = saved;
1329 self.pop_scope();
1330 self.blank();
1331 Ok(())
1332 }
1333
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1334 fn func(
1335 &mut self,
1336 sig: &syn::Signature,
1337 body: &syn::Block,
1338 recv: Option<Nim>,
1339 ) -> Result<(), String> {
1340 let name = sig.ident.to_string();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1341 self.func_named(&name.clone(), sig, body, recv)
1342 }
1343
1344 fn func_named(
1345 &mut self,
1346 name: &str,
1347 sig: &syn::Signature,
1348 body: &syn::Block,
1349 recv: Option<Nim>,
1350 ) -> Result<(), String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1351 let (ptys, ret) = self.signature(sig)?;
1352
1353 self.push_scope();
1354 let mut rendered: Vec<String> = Vec::new();
1355
1356 if let Some(self_ty) = recv {
1357 // `&mut self` and `mut self` both mean the body may mutate the
1358 // receiver; only the former is observable by the caller, and a Nim
1359 // `var` parameter is the faithful spelling of that.
1360 let mutable = matches!(
1361 sig.inputs.first(),
1362 Some(FnArg::Receiver(r))
1363 if matches!(&r.kind, syn::ReceiverKind::Reference(_, _, m) if m.is_some())
1364 );
1365 let t = if mutable { Nim::Var(Box::new(self_ty.clone())) } else { self_ty.clone() };
1366 rendered.push(format!("self: {}", t.render()));
1367 self.bind("self", self_ty);
1368 }
1369
1370 let typed: Vec<&syn::PatType> = sig
1371 .inputs
1372 .iter()
1373 .filter_map(|a| match a {
1374 FnArg::Typed(t) => Some(t),
1375 _ => None,
1376 })
1377 .collect();
1378 for (p, t) in typed.iter().zip(ptys.iter()) {
1379 let pname = match &*p.pat {
1380 Pat::Ident(i) => i.ident.to_string(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1381 // `fn from(_: Error) -> ..` — the parameter is unused, but Nim
1382 // still needs a name for it.
1383 Pat::Wild(_) => format!("unused{}", rendered.len()),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1384 _ => return Err("only plain identifier parameters are supported".into()),
1385 };
1386 rendered.push(format!("{}: {}", ident(&pname), t.render()));
1387 // Inside the body a `var T` parameter is used exactly like a `T`.
1388 self.bind(&pname, t.clone().owned());
1389 }
1390
1391 let head = if ret == Nim::Unit {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1392 format!("proc {}*({}) =", ident(name), rendered.join(", "))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1393 } else {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1394 format!("proc {}*({}): {} =", ident(name), rendered.join(", "), ret.render())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1395 };
1396 self.line(&head);
1397 self.indent += 1;
1398 let outer_ret = self.ret.replace(ret.clone());
1399
1400 // A Rust fn's trailing expression is its return value. Naming Nim's
1401 // implicit `result` as the target makes that true whether the tail is
1402 // a plain expression or an `if`/`match` with statement arms.
1403 let outer_target = if ret == Nim::Unit {
1404 self.target.take()
1405 } else {
1406 self.target.replace(("result".to_string(), Some(ret.clone())))
1407 };
1408 let before = self.out.len();
1409 let tail = self.block_body_at(body, Some(&ret))?;
1410 self.target = outer_target;
1411 match tail {
1412 Some(v) if ret != Nim::Unit => {
1413 let code = v.code.clone();
1414 self.line(&format!("result = {code}"));
1415 }
1416 Some(v) => {
1417 // A trailing expression in a `()`-returning fn is evaluated for
1418 // its effect; Nim requires an explicit discard.
1419 let needs_discard = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
1420 if needs_discard && !v.code.is_empty() {
1421 let code = v.code.clone();
1422 self.line(&format!("discard {code}"));
1423 }
1424 }
1425 None => {}
1426 }
1427 if self.out.len() == before {
1428 self.line("discard");
1429 }
1430
1431 self.indent -= 1;
1432 self.ret = outer_ret;
1433 self.pop_scope();
1434 self.blank();
1435 Ok(())
1436 }
1437
1438 // ---------------------------------------------------------- statements
1439
1440 /// Lower a block's statements. Returns the block's trailing expression,
1441 /// if it has one, *without* emitting it — the caller decides whether that
1442 /// value is a return value, a binding, or discarded.
1443 fn block_body(&mut self, b: &syn::Block) -> Result<Option<Val>, String> {
1444 self.block_body_at(b, None)
1445 }
1446
1447 fn block_body_at(
1448 &mut self,
1449 b: &syn::Block,
1450 expect: Option<&Nim>,
1451 ) -> Result<Option<Val>, String> {
1452 // An assignment target belongs to *this* block's trailing expression
1453 // only. A non-final `if` is a statement and must not assign anything.
1454 let target = self.target.take();
1455 let n = b.stmts.len();
1456 let mut tail = None;
1457 for (i, st) in b.stmts.iter().enumerate() {
1458 let last = i + 1 == n;
1459 match st {
1460 Stmt::Expr(e, None) if last && expressible(e) => {
1461 tail = Some(self.expr_at(e, expect)?)
1462 }
1463 Stmt::Expr(e, None) if last => {
1464 // A trailing `if`/`match` with statement arms, or a loop.
1465 // Lower it as statements; if this block's value is wanted,
1466 // each arm assigns it.
1467 match &target {
1468 Some((t, ty)) => {
1469 let (t, ty) = (t.clone(), ty.clone());
1470 self.assign_from(e, &t, ty.as_ref())?;
1471 }
1472 None => self.stmt(st)?,
1473 }
1474 }
1475 _ => self.stmt(st)?,
1476 }
1477 }
1478 self.target = target;
1479 Ok(tail)
1480 }
1481
1482 /// Lower a block in statement position (loop bodies, `if` arms).
1483 fn nested_block(&mut self, b: &syn::Block) -> Result<(), String> {
1484 self.push_scope();
1485 self.indent += 1;
1486 let before = self.out.len();
1487 let want = self.target.clone().and_then(|(_, t)| t);
1488 let tail = self.block_body_at(b, want.as_ref())?;
1489 self.emit_tail(tail);
1490 if self.out.len() == before {
1491 self.line("discard");
1492 }
1493 self.indent -= 1;
1494 self.pop_scope();
1495 Ok(())
1496 }
1497
1498 fn stmt(&mut self, s: &Stmt) -> Result<(), String> {
1499 match s {
1500 Stmt::Local(l) => self.local(l),
1501 Stmt::Expr(e, _) => {
1502 let v = self.expr_stmt(e)?;
1503 if let Some(v) = v {
1504 // A bare expression with a value must be discarded in Nim.
1505 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
1506 let code = v.code.clone();
1507 if needs {
1508 self.line(&format!("discard {code}"));
1509 } else if !code.is_empty() {
1510 self.line(&code);
1511 }
1512 }
1513 Ok(())
1514 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago1515 // A `const` declared inside a function body is local to it, and
1516 // must be emitted here rather than skipped as an already-emitted
1517 // top-level type.
1518 Stmt::Item(i) => self.item_inner(i),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1519 Stmt::Macro(m) => {
1520 let line = self.macro_call(&m.mac)?;
1521 self.line(&line);
1522 Ok(())
1523 }
1524 }
1525 }
1526
1527 fn local(&mut self, l: &Local) -> Result<(), String> {
1528 let (name, mutable, ann): (String, bool, Option<Nim>) = match &l.pat {
1529 Pat::Ident(i) => (i.ident.to_string(), i.mutability.is_some(), None),
1530 Pat::Type(t) => match &*t.pat {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1531 Pat::Ident(i) => (i.ident.to_string(), i.mutability.is_some(), Some(self.map_ty(&t.ty)?)),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1532 _ => return Err("only `let <ident>` bindings are supported".into()),
1533 },
1534 Pat::Wild(_) => ("_".into(), false, None),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago1535 Pat::Tuple(t) => return self.local_tuple(l, t),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1536 _ => return Err("destructuring `let` is not implemented yet".into()),
1537 };
1538
1539 let Some(init) = &l.init else {
1540 // `let x: T;` — Nim's `var x: T` zero-initialises, which Rust does
1541 // not. Rust's own rules make reading it before assignment illegal,
1542 // so the two agree on every program rustc accepts.
1543 let t = ann.ok_or("`let` without an initialiser needs a type annotation")?;
1544 let t = t.owned();
1545 self.line(&format!("var {}: {}", ident(&name), t.render()));
1546 self.bind(&name, t);
1547 return Ok(());
1548 };
1549 if init.diverge.is_some() {
1550 return Err("`let ... else` is not implemented yet".into());
1551 }
1552
1553 if !expressible(&init.expr) && name != "_" {
1554 // The initialiser is an `if`/`match` whose arms are statements.
1555 // Declare first, then let each arm assign into the binding.
1556 let t = ann
1557 .clone()
1558 .ok_or_else(|| {
1559 format!(
1560 "`let {name} = match/if ...` needs a type annotation: \
1561 its arms are statements, so the binding must be \
1562 declared before they run"
1563 )
1564 })?
1565 .owned();
1566 self.line(&format!("var {}: {}", ident(&name), t.render()));
1567 self.bind(&name, t.clone());
1568 let target = ident(&name);
1569 return self.assign_from(&init.expr, &target, Some(&t));
1570 }
1571
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago1572 // `let it = xs.chunks_exact(k)` binds an iterator, not a value.
1573 if is_iterator_expr(&init.expr) {
1574 let it = self.resolve_iter(&init.expr)?;
1575 self.bind_alias(&name, Alias::Iterator(Box::new(it)));
1576 return Ok(());
1577 }
1578
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1579 let v = self.expr_at(&init.expr, ann.as_ref())?;
Prove byte-identity for base16ct by enumerating whole input domains 99b8376 nandithebull 17h ago1580
1581 // `let s = &buf[..n]` binds a view of a place that is already in
1582 // scope. Nim's borrow checker will not let a `let` borrow out of a
1583 // local, and there is nothing to materialise anyway -- a view is a
1584 // reference. Binding it as an alias substitutes the same expression at
1585 // each use, which re-evaluates nothing because the initialiser is a
1586 // place expression with no side effects.
1587 if v.window.is_none()
1588 && matches!(v.ty, Some(Nim::OpenArray(_)))
1589 && is_pure_place(&init.expr)
1590 {
1591 let t = v.ty.clone().unwrap();
1592 let elem = match &t {
1593 Nim::OpenArray(e) => Some((**e).clone()),
1594 _ => None,
1595 };
1596 self.bind_alias(&name, Alias::Value { code: v.code.clone(), ty: Some(t) });
1597 let _ = elem;
1598 return Ok(());
1599 }
1600
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1601 if let Some(w) = v.window.clone() {
1602 // `let dst = dst.get_mut(..n).ok_or(..)?;` -- the binding names a
1603 // view into the caller's buffer. Copying it into a `seq` would
1604 // still print the right bytes but would stop writes reaching the
1605 // caller, so it is bound as an alias.
1606 if v.guard.is_some() && v.guard_err.is_some() {
1607 return Err(format!(
1608 "`let {name} = ...get(..)` keeps an `Option` of a slice view, \
1609 which Nim cannot represent; apply `?` or `unwrap()` to it \
1610 in the same expression"
1611 ));
1612 }
1613 self.bind_alias(&name, w);
1614 return Ok(());
1615 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago1616 // A `let` binding a borrow keeps the view: `let res = encode(..)?`
1617 // names the caller's buffer, and copying it into a `seq` would still
1618 // print the right bytes while silently breaking the aliasing.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1619 let t = match (ann, &v.ty) {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago1620 (Some(a), _) => a.unvar(),
1621 (None, Some(t)) => t.clone().unvar(),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1622 (None, None) => {
1623 return Err(format!(
1624 "cannot infer the type of `let {name}`; annotate it — \
1625 guessing here would change integer width, and with it the \
1626 meaning of any arithmetic on `{name}`"
1627 ))
1628 }
1629 };
1630
1631 if name == "_" {
1632 let code = v.code.clone();
1633 self.line(&format!("discard {code}"));
1634 return Ok(());
1635 }
1636 // Rust's immutable `let` is Nim's `let`; `let mut` is `var`. Shadowing
1637 // works in both, so a re-`let` of the same name needs no rename.
Prove byte-identity for base16ct by enumerating whole input domains 99b8376 nandithebull 17h ago1638 //
1639 // `let x = &mut y[..n]` is an immutable binding of a *mutable* borrow:
1640 // Rust may write through it, and Nim only accepts a `var` where a
1641 // `var` parameter is wanted, so the binding has to be one.
1642 let mutable = mutable || is_mut_borrow(&init.expr);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1643 let kw = if mutable { "var" } else { "let" };
1644 let line = format!("{} {}: {} = {}", kw, ident(&name), t.render(), v.code);
1645 self.line(&line);
1646 self.bind(&name, t);
1647 Ok(())
1648 }
1649
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago1650 /// `let (a, b) = ..` — tuple destructuring.
1651 fn local_tuple(&mut self, l: &Local, t: &syn::PatTuple) -> Result<(), String> {
1652 let Some(init) = &l.init else {
1653 return Err("a destructuring `let` needs an initialiser".into());
1654 };
1655 let names: Vec<(String, bool)> = t
1656 .elems
1657 .iter()
1658 .map(|p| match p {
1659 Pat::Ident(i) => Ok((i.ident.to_string(), i.mutability.is_some())),
1660 Pat::Wild(_) => Ok(("_".to_string(), false)),
1661 _ => Err("only plain identifiers are supported in a destructuring `let`"),
1662 })
1663 .collect::<Result<_, _>>()?;
1664
1665 // `split_at` hands back two *views* of the same slice. Nim has no
1666 // tuple of views, and there is nothing to materialise anyway, so each
1667 // name becomes a window into the original.
1668 if let Expr::MethodCall(m) = &*init.expr {
1669 let mname = m.method.to_string();
1670 if (mname == "split_at" || mname == "split_at_mut")
1671 && m.args.len() == 1
1672 && names.len() == 2
1673 {
1674 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
1675 let at = self.expr(&m.args[0])?;
1676 let cut = self.fresh("Cut");
1677 self.line(&format!("let {}: int = int({})", cut, at.code));
1678 self.bind_alias(
1679 &names[0].0,
1680 Alias::Window {
1681 code: code.clone(),
1682 off: base.clone(),
1683 len: cut.clone(),
1684 elem: elem.clone(),
1685 },
1686 );
1687 self.bind_alias(
1688 &names[1].0,
1689 Alias::Window {
1690 code,
1691 off: format!("({} + {})", base, cut),
1692 len: format!("({} - {})", len, cut),
1693 elem,
1694 },
1695 );
1696 return Ok(());
1697 }
1698 }
1699
1700 let v = self.expr(&init.expr)?;
1701 let tys = match &v.ty {
1702 Some(Nim::Tuple(ts)) if ts.len() == names.len() => ts.clone(),
1703 _ => {
1704 return Err(format!(
1705 "cannot destructure this into {} bindings: its type is not a \
1706 tuple of that many elements",
1707 names.len()
1708 ))
1709 }
1710 };
1711 let kw = if names.iter().any(|(_, m)| *m) { "var" } else { "let" };
1712 let lhs: Vec<String> = names.iter().map(|(n, _)| ident(n)).collect();
1713 self.line(&format!("{} ({}) = {}", kw, lhs.join(", "), v.code));
1714 for ((n, _), t) in names.iter().zip(tys) {
1715 self.bind(n, t);
1716 }
1717 Ok(())
1718 }
1719
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1720 /// Expressions that are statements in Rust and statements in Nim too
1721 /// (control flow). Returns `None` when it emitted lines itself.
1722 fn expr_stmt(&mut self, e: &Expr) -> Result<Option<Val>, String> {
1723 match e {
1724 Expr::If(_) => {
1725 self.if_stmt(e)?;
1726 Ok(None)
1727 }
1728 Expr::While(w) => {
1729 if w.label.is_some() {
1730 return Err("loop labels are not implemented yet".into());
1731 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1732 self.in_loop_cond = true;
1733 let c = self.expr(&w.cond);
1734 self.in_loop_cond = false;
1735 let c = c?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1736 self.line(&format!("while {}:", c.code));
1737 let saved = self.target.take();
1738 self.nested_block(&w.body)?;
1739 self.target = saved;
1740 Ok(None)
1741 }
1742 Expr::Loop(l) => {
1743 if l.label.is_some() {
1744 return Err("loop labels are not implemented yet".into());
1745 }
1746 self.line("while true:");
1747 let saved = self.target.take();
1748 self.nested_block(&l.body)?;
1749 self.target = saved;
1750 Ok(None)
1751 }
1752 Expr::ForLoop(f) => {
1753 self.for_loop(f)?;
1754 Ok(None)
1755 }
1756 Expr::Block(b) => {
1757 if b.label.is_some() {
1758 return Err("block labels are not implemented yet".into());
1759 }
1760 self.line("block:");
1761 self.nested_block(&b.block)?;
1762 Ok(None)
1763 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1764 Expr::Unsafe(u) => {
1765 // Transparent in statement position too, for the same reason.
1766 self.nested_block_flat(&u.block)?;
1767 Ok(None)
1768 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1769 Expr::Match(_) => {
1770 self.match_stmt(e)?;
1771 Ok(None)
1772 }
1773 Expr::Return(r) => {
1774 match &r.expr {
1775 Some(e) => {
1776 let want = self.ret.clone();
1777 let v = self.expr_at(e, want.as_ref())?;
1778 self.line(&format!("return {}", v.code));
1779 }
1780 None => self.line("return"),
1781 }
1782 Ok(None)
1783 }
1784 Expr::Break(b) => {
1785 if b.expr.is_some() || b.label.is_some() {
1786 return Err("`break` with a value or a label is not implemented yet".into());
1787 }
1788 self.line("break");
1789 Ok(None)
1790 }
1791 Expr::Continue(c) => {
1792 if c.label.is_some() {
1793 return Err("labelled `continue` is not implemented yet".into());
1794 }
1795 self.line("continue");
1796 Ok(None)
1797 }
1798 Expr::Assign(a) => {
1799 let lhs = self.expr(&a.left)?;
1800 if !expressible(&a.right) {
1801 let target = lhs.code.clone();
1802 return self.assign_from(&a.right, &target, lhs.ty.as_ref()).map(|_| None);
1803 }
1804 let rhs = self.expr_at(&a.right, lhs.ty.as_ref())?;
1805 self.line(&format!("{} = {}", lhs.code, rhs.code));
1806 Ok(None)
1807 }
1808 Expr::Binary(b) if is_compound(&b.op) => {
1809 let lhs = self.expr(&b.left)?;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago1810 // A compound assignment on a user type goes to that type's own
1811 // `impl OpAssign`, not to Nim's built-in operator.
1812 if let Some(f) = self.op_proc(&lhs.ty, compound_symbol(&b.op)) {
1813 // The impl's own parameter type types the right operand,
1814 // so `b_vec *= 4` takes 4 at the width the impl declares.
1815 let want = self.op_param(&lhs.ty, compound_symbol(&b.op));
1816 let rhs = self.expr_at(&b.right, want.as_ref())?;
1817 self.line(&format!("{}({}, {})", f, lhs.code, rhs.code));
1818 return Ok(None);
1819 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1820 // `i += 1` must widen the literal to `i`'s type, not to the
1821 // i32 an unconstrained Rust literal would default to.
1822 let rhs = self.expr_at(&b.right, lhs.ty.as_ref())?;
1823 let op = self.bin_op(&b.op, &lhs, &rhs)?;
1824 // Nim has no `shl=` etc., and `+=` on a `let` is illegal in
1825 // both languages, so the expanded form is always correct.
1826 self.line(&format!("{} = {} {} {}", lhs.code, lhs.code, op, rhs.code));
1827 Ok(None)
1828 }
1829 Expr::Macro(m) => {
1830 let line = self.macro_call(&m.mac)?;
1831 self.line(&line);
1832 Ok(None)
1833 }
1834 _ => Ok(Some(self.expr(e)?)),
1835 }
1836 }
1837
1838 /// Lower `e` in statement position, assigning each arm's value to
1839 /// `target`. This is how Rust's expression-oriented `if`/`match` survive
1840 /// the trip when their arms are too big for a Nim `if`-expression.
1841 fn assign_from(
1842 &mut self,
1843 e: &Expr,
1844 target: &str,
1845 expect: Option<&Nim>,
1846 ) -> Result<(), String> {
1847 let saved = self.target.replace((target.to_string(), expect.cloned()));
1848 let r = match e {
1849 Expr::If(_) => self.if_stmt(e),
1850 Expr::Match(_) => self.match_stmt(e),
1851 other => {
1852 let v = self.expr_at(other, expect)?;
1853 self.line(&format!("{} = {}", target, v.code));
1854 Ok(())
1855 }
1856 };
1857 self.target = saved;
1858 r
1859 }
1860
1861 /// Emit a block's value into the active assignment target, if there is
1862 /// one, or discard it if there is not.
1863 fn emit_tail(&mut self, v: Option<Val>) {
1864 let Some(v) = v else { return };
1865 match self.target.clone() {
1866 Some((t, _)) => {
1867 let code = v.code.clone();
1868 self.line(&format!("{t} = {code}"));
1869 }
1870 None => {
1871 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
1872 let code = v.code.clone();
1873 if needs {
1874 self.line(&format!("discard {code}"));
1875 } else if !code.is_empty() {
1876 self.line(&code);
1877 }
1878 }
1879 }
1880 }
1881
1882 fn if_stmt(&mut self, e: &Expr) -> Result<(), String> {
1883 let Expr::If(i) = e else { unreachable!() };
1884 if let Expr::Let(_) = &*i.cond {
1885 return Err("`if let` is not implemented yet".into());
1886 }
1887 let c = self.expr(&i.cond)?;
1888 self.line(&format!("if {}:", c.code));
1889 self.nested_block(&i.then_branch)?;
1890 match &i.else_branch {
1891 None => {}
1892 Some((_, els)) => match &**els {
1893 Expr::If(_) => {
1894 // Nim needs `elif`; splice the nested `if` in as one.
1895 let mark = self.out.len();
1896 self.if_stmt(els)?;
1897 let tail = self.out.split_off(mark);
1898 let indent = " ".repeat(self.indent);
1899 self.out.push_str(&tail.replacen(&format!("{indent}if "), &format!("{indent}elif "), 1));
1900 }
1901 Expr::Block(b) => {
1902 self.line("else:");
1903 self.nested_block(&b.block)?;
1904 }
1905 _ => return Err("unsupported `else` form".into()),
1906 },
1907 }
1908 Ok(())
1909 }
1910
1911 fn for_loop(&mut self, f: &syn::ExprForLoop) -> Result<(), String> {
1912 if f.label.is_some() {
1913 return Err("loop labels are not implemented yet".into());
1914 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1915 let it = self.resolve_iter(&f.expr)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1916
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1917 // One index loop drives the whole chain. Rust's adaptors are lazy and
1918 // compose; resolving them to an index and binding each name to an
1919 // lvalue reproduces that without materialising anything.
1920 let i = self.fresh("Idx");
1921 self.line(&format!("for {} in 0 ..< int({}):", i, it.len()));
1922 self.indent += 1;
1923 self.push_scope();
1924 let before = self.out.len();
1925
1926 self.bind_pattern(&f.pat, &it, &i)?;
1927
1928 let saved = self.target.take();
1929 if let Some(v) = self.block_body(&f.body)? {
1930 let code = v.code.clone();
1931 self.line(&format!("discard {code}"));
1932 }
1933 self.target = saved;
1934 if self.out.len() == before {
1935 self.line("discard");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1936 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1937 self.pop_scope();
1938 self.indent -= 1;
1939 Ok(())
1940 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1941
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1942 /// Resolve a chain of iterator adaptors into a single `Iter`.
1943 ///
1944 /// Only adaptors with an exact index-loop equivalent are accepted. `map`,
1945 /// `filter`, `take_while` and friends are rejected rather than partially
1946 /// honoured: silently dropping an adaptor would change which elements the
1947 /// loop visits.
1948 fn resolve_iter(&mut self, e: &Expr) -> Result<Iter, String> {
1949 match e {
1950 Expr::Reference(r) => self.resolve_iter(&r.expr),
1951 Expr::Paren(p) => self.resolve_iter(&p.expr),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1952 Expr::Range(r) => {
1953 let lo = match &r.start {
1954 Some(e) => self.expr(e)?,
1955 None => return Err("a `for` over `..n` needs a start bound".into()),
1956 };
1957 let hi = match &r.end {
1958 Some(e) => self.expr(e)?,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1959 None => {
1960 return Err("a `for` over an unbounded range would not terminate".into())
1961 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1962 };
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1963 let ty = lo.ty.clone().or(hi.ty.clone());
1964 Ok(Iter::Range {
1965 lo: lo.code,
1966 hi: hi.code,
1967 closed: matches!(r.limits, syn::RangeLimits::Closed(_)),
1968 ty,
1969 })
1970 }
1971 Expr::MethodCall(m) => {
1972 let name = m.method.to_string();
1973 match name.as_str() {
1974 "iter" | "into_iter" | "iter_mut" if m.args.is_empty() => {
1975 let mut it = self.resolve_iter(&m.receiver)?;
1976 if name == "iter_mut" {
1977 if let Iter::Elems { mutable, .. } = &mut it {
1978 *mutable = true;
1979 }
1980 }
1981 Ok(it)
1982 }
1983 "enumerate" if m.args.is_empty() => {
1984 Ok(Iter::Enumerate(Box::new(self.resolve_iter(&m.receiver)?)))
1985 }
1986 "zip" if m.args.len() == 1 => {
1987 let a = self.resolve_iter(&m.receiver)?;
1988 let b = self.resolve_iter(&m.args[0])?;
1989 Ok(Iter::Zip(Box::new(a), Box::new(b)))
1990 }
1991 "chunks_exact" | "chunks_exact_mut" if m.args.len() == 1 => {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1992 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1993 let k = self.expr(&m.args[0])?;
1994 Ok(Iter::Chunks {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1995 code,
1996 base,
1997 len,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago1998 k: k.code,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago1999 elem,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2000 mutable: name.ends_with("_mut"),
2001 })
2002 }
2003 "windows" if m.args.len() == 1 => {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2004 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2005 let k = self.expr(&m.args[0])?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2006 Ok(Iter::Windows { code, base, len, k: k.code, elem })
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2007 }
2008 other => Err(format!(
2009 "iterator adaptor `.{other}()` is not implemented; it has \
2010 no index-loop equivalent here, and dropping it would \
2011 change which elements the loop visits"
2012 )),
2013 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2014 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago2015 Expr::Path(p) => {
2016 let n = path_name(&p.path);
2017 if let Some(Alias::Iterator(it)) = self.lookup_alias(&n) {
2018 return Ok((*it).clone());
2019 }
2020 if let Some(Alias::Window { code, off, len, elem }) = self.lookup_alias(&n) {
2021 return Ok(Iter::Elems { code, off, len, elem, mutable: false });
2022 }
2023 let v = self.expr(e)?;
2024 Ok(Iter::Elems {
2025 len: format!("{}.len", v.code),
2026 elem: elem_of(&v.ty),
2027 code: v.code,
2028 off: "0".into(),
2029 mutable: false,
2030 })
2031 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2032 other => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2033 // A `for` binding that is itself a window iterates that window,
2034 // not the whole container it points into.
2035 if let Some(Alias::Window { code, off, len, elem }) = self.window_of(other) {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2036 return Ok(Iter::Elems { code, off, len, elem, mutable: false });
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2037 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2038 let v = self.expr(other)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2039 Ok(Iter::Elems {
2040 len: format!("{}.len", v.code),
2041 elem: elem_of(&v.ty),
2042 code: v.code,
2043 off: "0".into(),
2044 mutable: false,
2045 })
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2046 }
2047 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2048 }
2049
2050 /// Bind a `for` pattern against a resolved iterator at index `i`.
2051 fn bind_pattern(&mut self, p: &Pat, it: &Iter, i: &str) -> Result<(), String> {
2052 match (p, it) {
2053 (Pat::Tuple(t), Iter::Zip(a, b)) if t.elems.len() == 2 => {
2054 self.bind_pattern(&t.elems[0], a, i)?;
2055 self.bind_pattern(&t.elems[1], b, i)
2056 }
2057 (Pat::Tuple(t), Iter::Enumerate(inner)) if t.elems.len() == 2 => {
2058 if let Pat::Ident(id) = &t.elems[0] {
2059 let n = id.ident.to_string();
2060 // Rust's `enumerate` counts in `usize`.
2061 self.line(&format!("let {}: uint = uint({})", ident(&n), i));
2062 self.bind(&n, Nim::Prim("uint".into()));
2063 }
2064 self.bind_pattern(&t.elems[1], inner, i)
2065 }
2066 (_, Iter::Zip(..) | Iter::Enumerate(..)) => Err(
2067 "a `zip`/`enumerate` loop needs a two-element tuple pattern".into(),
2068 ),
2069 (Pat::Wild(_), _) => Ok(()),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2070 // `for &byte in xs` — the `&` destructures the reference, which in
2071 // Nim is already the value.
2072 (Pat::Reference(r), _) => self.bind_pattern(&r.pat, it, i),
2073 (Pat::Paren(p), _) => self.bind_pattern(&p.pat, it, i),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2074 (Pat::Ident(id), _) => {
2075 let name = id.ident.to_string();
2076 match it {
2077 Iter::Range { lo, ty, .. } => {
2078 let t = ty.clone().unwrap_or(Nim::Prim("int".into()));
2079 // The loop counts from zero; the range's own start is
2080 // added back so the binding has Rust's value and type.
2081 self.line(&format!(
2082 "let {}: {} = {}({}) + {}",
2083 ident(&name),
2084 t.render(),
2085 t.render(),
2086 i,
2087 lo
2088 ));
2089 self.bind(&name, t);
2090 Ok(())
2091 }
2092 Iter::Elems { code, off, elem, mutable, .. } => {
2093 let access = if off == "0" {
2094 format!("{}[{}]", code, i)
2095 } else {
2096 format!("{}[{} + {}]", code, off, i)
2097 };
2098 if *mutable {
2099 // An alias, not a copy: assigning through the
2100 // binding must reach the original element.
2101 self.bind_alias(
2102 &name,
2103 Alias::Value { code: access, ty: elem.clone() },
2104 );
2105 } else {
2106 let t = elem
2107 .clone()
2108 .ok_or("cannot infer the element type of this `for`")?;
2109 self.line(&format!(
2110 "let {}: {} = {}",
2111 ident(&name),
2112 t.render(),
2113 access
2114 ));
2115 self.bind(&name, t);
2116 }
2117 Ok(())
2118 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2119 Iter::Chunks { code, base, k, elem, .. } => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2120 self.bind_alias(
2121 &name,
2122 Alias::Window {
2123 code: code.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2124 off: format!("({} + {} * int({}))", base, i, k),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2125 len: format!("int({})", k),
2126 elem: elem.clone(),
2127 },
2128 );
2129 Ok(())
2130 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2131 Iter::Windows { code, base, k, elem, .. } => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2132 self.bind_alias(
2133 &name,
2134 Alias::Window {
2135 code: code.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2136 off: format!("({} + {})", base, i),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2137 len: format!("int({})", k),
2138 elem: elem.clone(),
2139 },
2140 );
2141 Ok(())
2142 }
2143 // Handled above: a zip or enumerate needs a tuple pattern,
2144 // and binding one name to the pair is not supported.
2145 Iter::Zip(..) | Iter::Enumerate(..) => unreachable!(),
2146 }
2147 }
2148 _ => Err("unsupported `for` pattern".into()),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2149 }
2150 }
2151
2152 fn match_stmt(&mut self, e: &Expr) -> Result<(), String> {
2153 let Expr::Match(m) = e else { unreachable!() };
2154 let scrut = self.expr(&m.expr)?;
2155 let t = scrut
2156 .ty
2157 .clone()
2158 .ok_or("cannot infer the type of a `match` scrutinee")?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2159 let name = self.fresh("Match");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2160 self.line(&format!("let {}: {} = {}", name, t.render(), scrut.code));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2161
2162 // A `match` whose arms neither bind nor guard is a Nim `case`, which
2163 // is exhaustiveness-checked the way Rust's is. Anything richer becomes
2164 // an if/elif chain, because Nim's `case` cannot destructure.
2165 let plain = m.arms.iter().all(|a| {
2166 !matches!(a.pat, Pat::Guard(_)) && !binds(&a.pat) && !destructures(&a.pat)
2167 });
2168 if plain {
2169 self.match_case(m, &name, &t)
2170 } else {
2171 self.match_chain(m, &name, &t)
2172 }
2173 }
2174
2175 fn match_case(
2176 &mut self,
2177 m: &syn::ExprMatch,
2178 name: &str,
2179 t: &Nim,
2180 ) -> Result<(), String> {
2181 // A variant object is discriminated by its `kind` field.
2182 let on_kind = matches!(t, Nim::Named(n, _) if self.enums.get(n).is_some_and(|d| !d.simple));
2183 self.line(&format!("case {}{}", name, if on_kind { ".kind" } else { "" }));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2184
2185 let mut saw_wild = false;
2186 for arm in &m.arms {
2187 match &arm.pat {
2188 Pat::Wild(_) => {
2189 saw_wild = true;
2190 self.line("else:");
2191 }
2192 p => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2193 let labels = self.pat_labels(p, Some(t))?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2194 self.line(&format!("of {}:", labels.join(", ")));
2195 }
2196 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2197 self.arm_body(&arm.body)?;
2198 }
2199 if !saw_wild && !self.case_is_total(t, m) {
2200 // Rust checked exhaustiveness already, but Nim cannot always see
2201 // it -- an integer `case` needs every value covered -- so make the
2202 // unreachable arm explicit rather than leave a compile error.
2203 self.line("else:");
2204 self.line(" rsPanic(\"unreachable match arm\")");
2205 }
2206 Ok(())
2207 }
2208
2209 /// Whether a Nim `case` over this type is already total, in which case
2210 /// adding an `else` would be a compile error rather than a safety net.
2211 fn case_is_total(&self, t: &Nim, m: &syn::ExprMatch) -> bool {
2212 let Nim::Named(n, _) = t else { return false };
2213 let Some(def) = self.enums.get(n) else { return false };
2214 def.variants.len() == m.arms.len()
2215 }
2216
2217 /// The if/elif form, for arms that bind or destructure.
2218 fn match_chain(
2219 &mut self,
2220 m: &syn::ExprMatch,
2221 name: &str,
2222 t: &Nim,
2223 ) -> Result<(), String> {
2224 let mut first = true;
2225 let mut closed = false;
2226 for arm in &m.arms {
2227 let (pat, guard) = match &arm.pat {
2228 Pat::Guard(g) => (&*g.pat, Some(&*g.guard)),
2229 p => (p, None),
2230 };
2231 if guard.is_some() && binds(pat) {
2232 return Err("a `match` guard on a binding pattern is not \
2233 implemented yet"
2234 .into());
2235 }
2236 let test = self.pat_test(pat, name, t)?;
2237 let test = match (test, guard) {
2238 (Some(t), Some(g)) => {
2239 let g = self.expr(g)?;
2240 Some(format!("({}) and ({})", t, g.code))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2241 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2242 (None, Some(g)) => Some(self.expr(g)?.code),
2243 (t, None) => t,
2244 };
2245 match test {
2246 Some(test) => {
2247 self.line(&format!(
2248 "{} {}:",
2249 if first { "if" } else { "elif" },
2250 test
2251 ));
2252 first = false;
2253 }
2254 None => {
2255 // An irrefutable pattern: everything left falls here.
2256 if first {
2257 self.line("block:");
2258 } else {
2259 self.line("else:");
2260 }
2261 closed = true;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2262 }
2263 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2264 self.indent += 1;
2265 self.push_scope();
2266 let before = self.out.len();
2267 self.pat_bind(pat, name, t)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2268 self.indent -= 1;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2269 self.arm_body_at(&arm.body, before)?;
2270 self.pop_scope();
2271 if closed {
2272 break;
2273 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2274 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2275 if !closed {
2276 // Rust proved this unreachable; Nim cannot see that, and leaving
2277 // the chain open would silently fall through instead.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2278 self.line("else:");
2279 self.line(" rsPanic(\"unreachable match arm\")");
2280 }
2281 Ok(())
2282 }
2283
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2284 /// The condition that selects this arm, or `None` if it always matches.
2285 fn pat_test(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<Option<String>, String> {
2286 Ok(match p {
2287 Pat::Wild(_) => None,
2288 Pat::Ident(i) if i.subpat.is_none() => None,
2289 Pat::Or(o) => {
2290 let mut parts = Vec::new();
2291 for c in &o.cases {
2292 match self.pat_test(c, name, t)? {
2293 Some(x) => parts.push(x),
2294 None => return Ok(None),
2295 }
2296 }
2297 Some(format!("({})", parts.join(" or ")))
2298 }
2299 Pat::Lit(_) | Pat::Range(_) => {
2300 let labels = self.pat_labels(p, Some(t))?;
2301 Some(match p {
2302 Pat::Range(_) => format!("({} in {})", name, labels[0]),
2303 _ => format!("({} == {})", name, labels[0]),
2304 })
2305 }
2306 Pat::Path(pp) => Some(self.variant_test(&pp.path, name, t)?),
2307 Pat::TupleStruct(ts) => Some(self.variant_test(&ts.path, name, t)?),
2308 Pat::Struct(st) => Some(self.variant_test(&st.path, name, t)?),
2309 Pat::Paren(pp) => return self.pat_test(&pp.pat, name, t),
2310 Pat::Reference(r) => return self.pat_test(&r.pat, name, t),
2311 _ => return Err("unsupported `match` pattern".into()),
2312 })
2313 }
2314
2315 /// The discriminant test for `Ok`/`Err`/`Some`/`None` or an enum variant.
2316 fn variant_test(&self, path: &syn::Path, name: &str, t: &Nim) -> Result<String, String> {
2317 let last = path_name(path);
2318 match last.as_str() {
2319 "Ok" => return Ok(format!("{name}.ok")),
2320 "Err" => return Ok(format!("(not {name}.ok)")),
2321 "Some" => return Ok(format!("{name}.has")),
2322 "None" => return Ok(format!("(not {name}.has)")),
2323 _ => {}
2324 }
2325 let Some((def, v)) = self.resolve_variant(path) else {
2326 return Err(format!(
2327 "`{last}` in a pattern is not a known enum variant; if it names \
2328 an enum declared in another module, that is not implemented yet"
2329 ));
2330 };
2331 if let Nim::Named(n, _) = t {
2332 if *n != def.name {
2333 return Err(format!(
2334 "pattern `{}::{}` does not match the scrutinee type `{}`",
2335 def.name, v, n
2336 ));
2337 }
2338 }
2339 Ok(if def.simple {
2340 format!("({} == {}.{})", name, ident(&def.name), ident(&v))
2341 } else {
2342 format!("({}.kind == {})", name, def.kind_ident(&v))
2343 })
2344 }
2345
2346 /// Emit the `let`s that a pattern's bindings introduce.
2347 fn pat_bind(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<(), String> {
2348 match p {
2349 Pat::Wild(_) | Pat::Lit(_) | Pat::Range(_) | Pat::Path(_) | Pat::Or(_) => Ok(()),
2350 Pat::Paren(pp) => self.pat_bind(&pp.pat, name, t),
2351 Pat::Reference(r) => self.pat_bind(&r.pat, name, t),
2352 Pat::Ident(i) if i.subpat.is_none() => {
2353 let b = i.ident.to_string();
2354 self.line(&format!("let {}: {} = {}", ident(&b), t.render(), name));
2355 self.bind(&b, t.clone());
2356 Ok(())
2357 }
2358 Pat::TupleStruct(ts) => {
2359 let fields = self.variant_fields(&ts.path, t)?;
2360 for (i, sub) in ts.elems.iter().enumerate() {
2361 let Some((fname, fty)) = fields.get(i) else {
2362 return Err(format!(
2363 "pattern binds {} field(s) but the variant has {}",
2364 ts.elems.len(),
2365 fields.len()
2366 ));
2367 };
2368 let access = format!("{}.{}", name, ident(fname));
2369 self.pat_bind(sub, &access, fty)?;
2370 }
2371 Ok(())
2372 }
2373 Pat::Struct(st) => {
2374 let fields = self.variant_fields(&st.path, t)?;
2375 for f in &st.fields {
2376 let syn::Member::Named(m) = &f.member else {
2377 return Err("unsupported struct pattern field".into());
2378 };
2379 let m = m.to_string();
2380 let Some((fname, fty)) = fields.iter().find(|(f, _)| f.ends_with(&m)) else {
2381 return Err(format!("unknown field `{m}` in pattern"));
2382 };
2383 let access = format!("{}.{}", name, ident(fname));
2384 self.pat_bind(&f.pat, &access, fty)?;
2385 }
2386 Ok(())
2387 }
2388 _ => Err("unsupported `match` pattern".into()),
2389 }
2390 }
2391
2392 /// The payload fields a variant pattern destructures.
2393 fn variant_fields(
2394 &self,
2395 path: &syn::Path,
2396 t: &Nim,
2397 ) -> Result<Vec<(String, Nim)>, String> {
2398 let last = path_name(path);
2399 // `Ok`/`Err`/`Some` read the prelude's own field names.
2400 if let Nim::Named(n, a) = t {
2401 match (n.as_str(), last.as_str()) {
2402 ("Result", "Ok") if a.len() == 2 => return Ok(vec![("val".into(), a[0].clone())]),
2403 ("Result", "Err") if a.len() == 2 => return Ok(vec![("err".into(), a[1].clone())]),
2404 ("Option", "Some") if a.len() == 1 => return Ok(vec![("val".into(), a[0].clone())]),
2405 _ => {}
2406 }
2407 }
2408 let Some((def, v)) = self.resolve_variant(path) else {
2409 return Err(format!("`{last}` is not a known enum variant"));
2410 };
2411 Ok(def.get(&v).map(|v| v.fields.clone()).unwrap_or_default())
2412 }
2413
2414 fn arm_body(&mut self, body: &Expr) -> Result<(), String> {
2415 self.indent += 1;
2416 let before = self.out.len();
2417 self.indent -= 1;
2418 self.arm_body_at(body, before)
2419 }
2420
2421 fn arm_body_at(&mut self, body: &Expr, before: usize) -> Result<(), String> {
2422 match body {
2423 Expr::Block(b) => self.nested_block(&b.block)?,
2424 other => {
2425 self.indent += 1;
2426 // An arm's value is the `match`'s value, so it is typed by
2427 // whatever the `match` is being assigned to -- without which
2428 // an `Ok(..)` arm has no way to know its `Result<T, E>`.
2429 let want = self.target.clone().and_then(|(_, t)| t);
2430 let v = match (want, expressible(other)) {
2431 (Some(t), true) => Some(self.expr_at(other, Some(&t))?),
2432 _ => self.expr_stmt(other)?,
2433 };
2434 self.emit_tail(v);
2435 self.indent -= 1;
2436 }
2437 }
2438 if self.out.len() == before {
2439 self.indent += 1;
2440 self.line("discard");
2441 self.indent -= 1;
2442 }
2443 Ok(())
2444 }
2445
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2446 fn pat_labels(&mut self, p: &Pat, expect: Option<&Nim>) -> Result<Vec<String>, String> {
2447 match p {
2448 Pat::Lit(l) => Ok(vec![self.lit_at(&l.lit, expect)?.code]),
2449 Pat::Or(o) => {
2450 let mut out = Vec::new();
2451 for p in &o.cases {
2452 out.extend(self.pat_labels(p, expect)?);
2453 }
2454 Ok(out)
2455 }
2456 Pat::Range(r) => {
2457 let lo = r.start.as_ref().ok_or("open-ended range pattern")?;
2458 let hi = r.end.as_ref().ok_or("open-ended range pattern")?;
2459 let (lo, hi) = (self.expr_at(lo, expect)?, self.expr_at(hi, expect)?);
2460 let op = match r.limits {
2461 syn::RangeLimits::HalfOpen(_) => "..<",
2462 syn::RangeLimits::Closed(_) => "..",
2463 };
2464 Ok(vec![format!("{} {} {}", lo.code, op, hi.code)])
2465 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2466 Pat::Path(pp) => {
2467 if let Some((def, v)) = self.resolve_variant(&pp.path) {
2468 return Ok(vec![if def.simple {
2469 format!("{}.{}", ident(&def.name), ident(&v))
2470 } else {
2471 def.kind_ident(&v)
2472 }]);
2473 }
2474 Ok(vec![ident(&path_name(&pp.path))])
2475 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2476 _ => Err("unsupported `match` pattern; only literals, ranges, `|` \
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2477 alternatives, enum variants and `_` are implemented"
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2478 .into()),
2479 }
2480 }
2481
2482 // --------------------------------------------------------- expressions
2483
2484 fn expr(&mut self, e: &Expr) -> Result<Val, String> {
2485 self.expr_at(e, None)
2486 }
2487
2488 /// Lower `e`, with the type the surrounding code expects of it.
2489 ///
2490 /// Rust infers an unsuffixed integer literal's type from its context and
2491 /// falls back to `i32`; Nim falls back to 64-bit `int`. Carrying the
2492 /// expected type down to the literal is what makes `let x: u8 = 255` and
2493 /// `x.wrapping_add(100)` mean the same thing on both sides. Without it the
2494 /// widths silently diverge, which is exactly the class of bug this
2495 /// project refuses to ship.
2496 fn expr_at(&mut self, e: &Expr, expect: Option<&Nim>) -> Result<Val, String> {
2497 match e {
2498 Expr::Lit(l) => self.lit_at(&l.lit, expect),
2499 Expr::Path(p) => {
2500 let name = path_name(&p.path);
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2501 if name == "None" {
2502 return Ok(Val::new(self.none_of(expect), expect.cloned()));
2503 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2504 // A unit struct used as a value: `fmt::Error`, or a `struct S;`
2505 // declared here. In Nim that is a constructor call.
2506 if p.path.segments.len() > 1 {
2507 let ty = syn::Type::Path(syn::TypePath { attrs: Vec::new(), qself: None, path: p.path.clone() });
2508 if let Ok(Nim::Prim(n)) = ty::map(&ty) {
2509 if n == "FmtError" {
2510 return Ok(Val::new("FmtError()", Some(Nim::Prim(n))));
2511 }
2512 }
2513 }
2514 if self.structs.get(&name).is_some_and(|f| f.is_empty()) {
2515 return Ok(Val::new(
2516 format!("{}()", ident(&name)),
2517 Some(Nim::Named(name.clone(), vec![])),
2518 ));
2519 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2520 // A unit enum variant used as a value: `Error::InvalidLength`.
2521 if let Some((def, v)) = self.resolve_variant(&p.path) {
2522 let ty = Some(Nim::Named(def.name.clone(), vec![]));
2523 return Ok(if def.simple {
2524 Val::new(format!("{}.{}", ident(&def.name), ident(&v)), ty)
2525 } else {
2526 Val::new(format!("{}()", def.ctor_ident(&v)), ty)
2527 });
2528 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2529 // A `for` binding that stands for an element of the container
2530 // it came from: using it must read (and assigning through it
2531 // must write) that element, not a copy.
2532 if let Some(a) = self.lookup_alias(&name) {
2533 return Ok(match a {
2534 Alias::Value { code, ty } => Val::new(code, ty),
2535 // A window *is* a slice; as a value it is the view it
2536 // denotes, which is what Rust's `&[T]` means too.
2537 Alias::Window { code, off, len, elem } => Val::new(
2538 format!("{}.toOpenArray({}, {} + {} - 1)", code, off, off, len),
2539 elem.map(|e| Nim::OpenArray(Box::new(e))),
2540 ),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago2541 // An iterator is not a value here: it is consumed by a
2542 // `for`, or asked for its `.remainder()`.
2543 Alias::Iterator(_) => {
2544 return Err(format!(
2545 "`{name}` is an iterator; it can be iterated or asked \
2546 for its `remainder()`, but not used as a value"
2547 ))
2548 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2549 });
2550 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2551 if let Some(t) = self.lookup(&name) {
2552 return Ok(Val::new(ident(&name), Some(t)));
2553 }
2554 // A top-level function used as a value, e.g. passed to a
2555 // parameter of `impl Fn(..)` type.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2556 if let Some(k) = self.resolve_fn(&p.path) {
2557 let sig = &self.fns[&k];
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2558 let t = Nim::Proc(sig.params.clone(), Box::new(sig.ret.clone()));
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2559 return Ok(Val::new(self.fn_name(&k.0, &k.1), Some(t)));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2560 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2561 Ok(Val::new(ident(&name), None))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2562 }
2563 Expr::Paren(p) => {
2564 let v = self.expr_at(&p.expr, expect)?;
2565 Ok(Val::new(format!("({})", v.code), v.ty))
2566 }
2567 Expr::Group(g) => self.expr_at(&g.expr, expect),
2568 // `&x` is a value in Nim; `&mut x` in an argument position binds to
2569 // a `var` parameter, which is also just `x` at the call site.
2570 Expr::Reference(r) => self.expr_at(&r.expr, expect),
2571 Expr::Unary(u) => self.unary(u, expect),
2572 Expr::Binary(b) => self.binary(b, expect),
2573 Expr::Cast(c) => self.cast(c),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2574 Expr::Index(i) if matches!(&*i.index, Expr::Range(_)) => {
2575 let Expr::Range(r) = &*i.index else { unreachable!() };
2576 let base = self.expr(&i.expr)?;
2577 let lo = match &r.start {
2578 Some(e) => format!("int({})", self.expr(e)?.code),
2579 None => "0".into(),
2580 };
2581 // Nim's `toOpenArray` takes an inclusive upper bound.
2582 let hi = match (&r.end, r.limits) {
2583 (Some(e), syn::RangeLimits::HalfOpen(_)) => {
2584 format!("int({}) - 1", self.expr(e)?.code)
2585 }
2586 (Some(e), syn::RangeLimits::Closed(_)) => {
2587 format!("int({})", self.expr(e)?.code)
2588 }
2589 (None, _) => format!("{}.len - 1", base.code),
2590 };
2591 let elem = elem_of(&base.ty)
2592 .ok_or("cannot infer the element type of this slice")?;
2593 Ok(Val::new(
2594 format!("{}.toOpenArray({}, {})", base.code, lo, hi),
2595 Some(Nim::OpenArray(Box::new(elem))),
2596 ))
2597 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2598 Expr::Index(i) => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2599 if let Some(Alias::Window { code, off, elem, .. }) = self.window_of(&i.expr) {
2600 let idx = self.expr(&i.index)?;
2601 return Ok(Val::new(
2602 format!("{}[{} + int({})]", code, off, idx.code),
2603 elem,
2604 ));
2605 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2606 let base = self.expr(&i.expr)?;
2607 let idx = self.expr(&i.index)?;
2608 // Rust indexes with usize; Nim wants an `int`, and a `uint`
2609 // index is a type error there rather than a silent conversion.
2610 let idx_code = match &idx.ty {
2611 Some(t) if t.is_unsigned() => format!("int({})", idx.code),
2612 _ => idx.code.clone(),
2613 };
2614 let elem = match base.ty.clone() {
2615 Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) | Some(Nim::Array(_, t)) => Some(*t),
2616 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
2617 _ => None,
2618 };
2619 Ok(Val::new(format!("{}[{}]", base.code, idx_code), elem))
2620 }
2621 Expr::Field(f) => {
2622 let base = self.expr(&f.base)?;
2623 let name = match &f.member {
2624 syn::Member::Named(n) => n.to_string(),
2625 syn::Member::Unnamed(i) => format!("f{}", i.index),
2626 };
2627 let t = match &base.ty {
2628 Some(Nim::Named(s, _)) => self
2629 .structs
2630 .get(s)
2631 .and_then(|fs| fs.iter().find(|(f, _)| *f == name))
2632 .map(|(_, t)| t.clone()),
2633 _ => None,
2634 };
2635 Ok(Val::new(format!("{}.{}", base.code, ident(&name)), t))
2636 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2637 // `unsafe` is a permission marker, not a semantic change: it does
2638 // not alter what the enclosed operations mean. So the block is
2639 // transparent here, and each operation inside still goes through
2640 // the ordinary lowering -- and is still rejected if it has no
2641 // faithful mapping.
2642 Expr::Unsafe(u) => match single_expr(&u.block) {
2643 Some(e) => self.expr_at(e, expect),
2644 None => Err("an `unsafe` block used as a value must be a single \
2645 expression"
2646 .into()),
2647 },
2648 Expr::Closure(c) => self.closure(c, expect),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2649 Expr::Try(t) => self.try_op(t),
2650 Expr::Call(c) => self.call(c, expect),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago2651 Expr::MethodCall(m) => self.method(m, expect),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago2652 Expr::Macro(m) if path_name(&m.mac.path) == "vec" => {
2653 // `vec![..]`'s elements take their type from the annotation on
2654 // the binding, exactly as Rust's would.
2655 let want = match expect {
2656 Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) => Some((**e).clone()),
2657 _ => None,
2658 };
2659 let saved = std::mem::replace(&mut self.vec_expect, want.clone());
2660 let code = self.macro_call(&m.mac);
2661 self.vec_expect = saved;
2662 let code = code?;
2663 let ty = match want {
2664 Some(e) => Some(Nim::Seq(Box::new(e))),
2665 None => self.vec_elem(&m.mac)?.map(|e| Nim::Seq(Box::new(e))),
2666 };
2667 Ok(Val::new(code, ty))
2668 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2669 Expr::Macro(m) => {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago2670 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 19h ago2671 let code = self.macro_call(&m.mac)?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago2672 // A formatter write is a statement that appends, not a value.
2673 let ty = if is_write { Some(Nim::Unit) } else { None };
2674 Ok(Val::new(code, ty))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2675 }
2676 Expr::Struct(s) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2677 if s.rest.is_some() {
2678 return Err("struct update syntax `..rest` is not implemented yet".into());
2679 }
2680 // `Shape::Rect { w: 3, h: 5 }` is a struct-shaped *enum variant*,
2681 // which is constructed positionally in Nim.
2682 if let Some((def, v)) = self.resolve_variant(&s.path) {
2683 let fields = def.get(&v).map(|v| v.fields.clone()).unwrap_or_default();
2684 let mut args = vec![String::new(); fields.len()];
2685 for f in &s.fields {
2686 let syn::Member::Named(m) = &f.member else {
2687 return Err("unsupported enum variant field".into());
2688 };
2689 let want = format!("{}_{}", v, m);
2690 let i = fields
2691 .iter()
2692 .position(|(n, _)| *n == want)
2693 .ok_or_else(|| format!("`{}::{}` has no field `{m}`", def.name, v))?;
2694 args[i] = self.expr_at(&f.expr, Some(&fields[i].1))?.code;
2695 }
2696 if let Some(i) = args.iter().position(|a| a.is_empty()) {
2697 return Err(format!(
2698 "`{}::{}` is missing field `{}`",
2699 def.name, v, fields[i].0
2700 ));
2701 }
2702 return Ok(Val::new(
2703 format!("{}({})", def.ctor_ident(&v), args.join(", ")),
2704 Some(Nim::Named(def.name.clone(), vec![])),
2705 ));
2706 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2707 let name = path_name(&s.path);
2708 let mut parts = Vec::new();
2709 for f in &s.fields {
2710 let fname = match &f.member {
2711 syn::Member::Named(n) => n.to_string(),
2712 syn::Member::Unnamed(i) => format!("f{}", i.index),
2713 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2714 let want = self
2715 .structs
2716 .get(&name)
2717 .and_then(|fs| fs.iter().find(|(n, _)| *n == fname))
2718 .map(|(_, t)| t.clone());
2719 let v = self.expr_at(&f.expr, want.as_ref())?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2720 parts.push(format!("{}: {}", ident(&fname), v.code));
2721 }
2722 Ok(Val::new(
2723 format!("{}({})", ident(&name), parts.join(", ")),
2724 Some(Nim::Named(name, vec![])),
2725 ))
2726 }
2727 Expr::Array(a) => {
2728 let mut parts = Vec::new();
2729 let mut elem = match expect {
2730 Some(Nim::Array(_, t)) | Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) => {
2731 Some((**t).clone())
2732 }
2733 _ => None,
2734 };
2735 for e in &a.elems {
2736 let want = elem.clone();
2737 let v = self.expr_at(e, want.as_ref())?;
2738 elem = elem.or(v.ty.clone());
2739 parts.push(v.code);
2740 }
2741 let t = elem.map(|t| Nim::Array(a.elems.len(), Box::new(t)));
2742 Ok(Val::new(format!("[{}]", parts.join(", ")), t))
2743 }
2744 Expr::Repeat(r) => {
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago2745 // `[0; 4]` is an array in Rust. Nim distinguishes a fixed-size
2746 // array from a `seq`, so the expected type decides which, and
2747 // an array needs its elements written out.
2748 let want_elem = match expect {
2749 Some(Nim::Array(_, e)) | Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) => {
2750 Some((**e).clone())
2751 }
2752 _ => None,
2753 };
2754 let v = self.expr_at(&r.expr, want_elem.as_ref())?;
2755 if let Some(Nim::Array(n, _)) = expect {
2756 let elems: Vec<String> = (0..*n).map(|_| v.code.clone()).collect();
2757 let t = v.ty.clone().map(|t| Nim::Array(*n, Box::new(t)));
2758 return Ok(Val::new(format!("[{}]", elems.join(", ")), t));
2759 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2760 let n = self.expr(&r.len)?;
2761 let t = v.ty.clone().map(|t| Nim::Seq(Box::new(t)));
2762 Ok(Val::new(format!("newSeqWith(int({}), {})", n.code, v.code), t))
2763 }
2764 Expr::Tuple(t) if t.elems.is_empty() => Ok(Val::new("", Some(Nim::Unit))),
2765 Expr::Tuple(t) => {
2766 let mut parts = Vec::new();
2767 let mut tys = Vec::new();
2768 for e in &t.elems {
2769 let v = self.expr(e)?;
2770 tys.push(v.ty.clone());
2771 parts.push(v.code);
2772 }
2773 let ty = tys
2774 .iter()
2775 .cloned()
2776 .collect::<Option<Vec<_>>>()
2777 .map(Nim::Tuple);
2778 Ok(Val::new(format!("({})", parts.join(", ")), ty))
2779 }
2780 // `if` and `match` are expressions in both languages, but only
2781 // when every arm is itself a single expression.
2782 Expr::If(i) => self.if_expr(i, expect),
2783 Expr::Block(b) if b.block.stmts.len() == 1 => {
2784 if let Some(Stmt::Expr(e, None)) = b.block.stmts.first() {
2785 self.expr_at(e, expect)
2786 } else {
2787 Err("block expression with statements in value position is not implemented yet".into())
2788 }
2789 }
2790 other => Err(format!(
2791 "unsupported expression in value position: {}",
2792 expr_kind(other)
2793 )),
2794 }
2795 }
2796
2797 fn if_expr(&mut self, i: &syn::ExprIf, expect: Option<&Nim>) -> Result<Val, String> {
2798 let (Some(then), Some((_, els))) = (single_expr(&i.then_branch), &i.else_branch) else {
2799 return Err(
2800 "an `if` used as a value must have an `else` and single-expression arms".into(),
2801 );
2802 };
2803 let c = self.expr(&i.cond)?;
2804 let t = self.expr_at(then, expect)?;
2805 let want = expect.cloned().or_else(|| t.ty.clone());
2806 let e = match &**els {
2807 Expr::Block(b) => match single_expr(&b.block) {
2808 Some(x) => self.expr_at(x, want.as_ref())?,
2809 None => return Err("an `if` used as a value must have single-expression arms".into()),
2810 },
2811 other => self.expr_at(other, want.as_ref())?,
2812 };
2813 let ty = t.ty.clone().or(e.ty.clone());
2814 Ok(Val::new(
2815 format!("(if {}: {} else: {})", c.code, t.code, e.code),
2816 ty,
2817 ))
2818 }
2819
2820 fn lit_at(&mut self, l: &Lit, expect: Option<&Nim>) -> Result<Val, String> {
2821 match l {
2822 Lit::Int(i) => {
2823 let suffix = i.suffix();
2824 if let Some(why) = ty::rejected(suffix) {
2825 return Err(format!("integer literal `{}`: {}", i, why));
2826 }
2827 let digits = i.base10_digits().to_string();
2828 // Rust's default for an unconstrained integer literal is i32.
2829 // Nim's is `int` (64-bit). Making the width explicit is what
2830 // keeps overflow behaviour the same on both sides.
2831 let t = if suffix.is_empty() {
2832 match expect {
2833 Some(t) if t.is_integer() => t.clone(),
2834 // Rust's fallback for an otherwise-unconstrained
2835 // integer literal.
2836 _ => Nim::Prim("int32".into()),
2837 }
2838 } else {
2839 ty::prim(suffix).ok_or_else(|| format!("unknown literal suffix `{suffix}`"))?
2840 };
2841 Ok(Val::new(format!("{}'{}", digits, nim_suffix(&t)?), Some(t)))
2842 }
2843 Lit::Float(f) => {
2844 let t = match f.suffix() {
2845 "" => match expect {
2846 Some(Nim::Prim(p)) if p == "float32" => Nim::Prim("float32".into()),
2847 _ => Nim::Prim("float64".into()),
2848 },
2849 "f64" => Nim::Prim("float64".into()),
2850 "f32" => Nim::Prim("float32".into()),
2851 s => return Err(format!("unknown float suffix `{s}`")),
2852 };
2853 let d = f.base10_digits();
2854 let d = if d.contains('.') || d.contains('e') { d.to_string() } else { format!("{d}.0") };
2855 Ok(Val::new(d, Some(t)))
2856 }
2857 Lit::Bool(b) => Ok(Val::new(b.value.to_string(), Some(Nim::Prim("bool".into())))),
2858 Lit::Str(s) => Ok(Val::new(
2859 fmt::nim_str(&s.value()),
2860 Some(Nim::Prim("string".into())),
2861 )),
2862 Lit::Char(c) => Ok(Val::new(
2863 format!("Rune({})", c.value() as u32),
2864 Some(Nim::Prim("Rune".into())),
2865 )),
2866 Lit::Byte(b) => Ok(Val::new(
2867 format!("{}'u8", b.value()),
2868 Some(Nim::Prim("uint8".into())),
2869 )),
2870 Lit::ByteStr(b) => {
2871 let bytes: Vec<String> = b.value().iter().map(|x| format!("{x}'u8")).collect();
2872 Ok(Val::new(
2873 format!("@[{}]", bytes.join(", ")),
2874 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
2875 ))
2876 }
2877 other => Err(format!("unsupported literal: {other:?}")),
2878 }
2879 }
2880
2881 fn unary(&mut self, u: &syn::ExprUnary, expect: Option<&Nim>) -> Result<Val, String> {
2882 // `-128i8` is a literal in Rust, but `-(128'i8)` in Nim would overflow
2883 // the positive half of the range before the negation runs. Folding the
2884 // sign into the literal keeps `i8::MIN` and friends expressible.
2885 if let (UnOp::Neg(_), Expr::Lit(l)) = (&u.op, &*u.expr) {
2886 if matches!(l.lit, Lit::Int(_) | Lit::Float(_)) {
2887 let v = self.lit_at(&l.lit, expect)?;
2888 return Ok(Val::new(format!("-{}", v.code), v.ty));
2889 }
2890 }
2891 let v = self.expr_at(&u.expr, expect)?;
2892 match u.op {
2893 UnOp::Neg(_) => Ok(Val::new(format!("(-{})", v.code), v.ty)),
2894 // Rust's `!` is logical on bool and bitwise-complement on integers.
2895 // Nim spells those `not` and `not` as well, so one mapping covers
2896 // both — but only because Nim overloads `not` the same way.
2897 UnOp::Not(_) => Ok(Val::new(format!("(not {})", v.code), v.ty)),
2898 UnOp::Deref(_) => Ok(v),
2899 _ => Err("unsupported unary operator".into()),
2900 }
2901 }
2902
2903 fn binary(&mut self, b: &syn::ExprBinary, expect: Option<&Nim>) -> Result<Val, String> {
2904 // A comparison's operands are unrelated to the `bool` it produces, so
2905 // the outer expectation is not passed through to them.
2906 let down = match b.op {
2907 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
2908 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => None,
2909 _ => expect,
2910 };
2911 let mut l = self.expr_at(&b.left, down)?;
2912 // Rust unifies the two operand types; propagating whichever side is
2913 // known to the other reproduces that, and disagreement then surfaces
2914 // as a Nim type error rather than as a silent width change.
2915 let mut r = self.expr_at(&b.right, l.ty.as_ref().or(down))?;
2916 if l.ty.is_none() && r.ty.is_some() {
2917 l = self.expr_at(&b.left, r.ty.as_ref())?;
2918 }
2919 let r = std::mem::replace(&mut r, Val::untyped(""));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago2920 // A binary operator on a user type goes to that type's own impl.
2921 if let Some(f) = self.op_proc(&l.ty, binary_symbol(&b.op)) {
2922 let want = self.op_param(&l.ty, binary_symbol(&b.op));
2923 let r = self.expr_at(&b.right, want.as_ref())?;
2924 let ret = self
2925 .methods
2926 .get(&(
2927 type_name(l.ty.as_ref().unwrap()),
2928 op_method(binary_symbol(&b.op)).to_string(),
2929 ))
2930 .map(|s| s.ret.clone());
2931 return Ok(Val::new(format!("{}({}, {})", f, l.code, r.code), ret));
2932 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2933 let op = self.bin_op(&b.op, &l, &r)?;
2934 let ty = match b.op {
2935 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
2936 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => Some(Nim::Prim("bool".into())),
2937 // Rust's shift takes its result type from the *left* operand, and
2938 // the right may be a different width entirely.
2939 BinOp::Shl(_) | BinOp::Shr(_) => l.ty.clone(),
2940 _ => l.ty.clone().or(r.ty.clone()),
2941 };
2942 Ok(Val::new(format!("({} {} {})", l.code, op, r.code), ty))
2943 }
2944
2945 fn bin_op(&mut self, op: &BinOp, l: &Val, r: &Val) -> Result<&'static str, String> {
2946 Ok(match op {
2947 BinOp::Add(_) | BinOp::AddAssign(_) => "+",
2948 BinOp::Sub(_) | BinOp::SubAssign(_) => "-",
2949 BinOp::Mul(_) | BinOp::MulAssign(_) => "*",
2950 BinOp::Div(_) | BinOp::DivAssign(_) => {
2951 // Nim spells integer division `div`. Both languages truncate
2952 // toward zero, so once the right operator is chosen the
2953 // semantics match, including for negative operands.
2954 let t = l.ty.clone().or(r.ty.clone()).ok_or(
2955 "cannot tell integer from float division here; annotate the operands",
2956 )?;
2957 if t.is_integer() { "div" } else { "/" }
2958 }
2959 BinOp::Rem(_) | BinOp::RemAssign(_) => {
2960 let t = l.ty.clone().or(r.ty.clone()).ok_or(
2961 "cannot tell integer from float remainder here; annotate the operands",
2962 )?;
2963 if t.is_integer() { "mod" } else { return Err("float `%` is not implemented yet".into()) }
2964 }
2965 BinOp::And(_) => "and",
2966 BinOp::Or(_) => "or",
2967 // Nim's `and`/`or`/`xor` are bitwise on integers and logical on
2968 // bools, exactly as Rust's `&`/`|`/`^` are.
2969 BinOp::BitAnd(_) | BinOp::BitAndAssign(_) => "and",
2970 BinOp::BitOr(_) | BinOp::BitOrAssign(_) => "or",
2971 BinOp::BitXor(_) | BinOp::BitXorAssign(_) => "xor",
2972 // Settled empirically: Nim's `shr` on a signed integer is
2973 // arithmetic, matching Rust. See DESIGN.md.
2974 BinOp::Shl(_) | BinOp::ShlAssign(_) => "shl",
2975 BinOp::Shr(_) | BinOp::ShrAssign(_) => "shr",
2976 BinOp::Eq(_) => "==",
2977 BinOp::Ne(_) => "!=",
2978 BinOp::Lt(_) => "<",
2979 BinOp::Le(_) => "<=",
2980 BinOp::Gt(_) => ">",
2981 BinOp::Ge(_) => ">=",
2982 other => return Err(format!("unsupported binary operator {other:?}")),
2983 })
2984 }
2985
2986 fn cast(&mut self, c: &syn::ExprCast) -> Result<Val, String> {
2987 let v = self.expr(&c.expr)?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2988 let to = self.map_ty(&c.ty)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2989 let from = v.ty.clone().ok_or_else(|| {
2990 format!(
2991 "cannot lower `as {}`: the source type is unknown, and `as` \
2992 truncates, so the source width decides the result",
2993 to.render()
2994 )
2995 })?;
2996
2997 let code = match (&from, &to) {
2998 (f, t) if f.is_integer() && t.is_integer() => {
2999 // Rust's `as` between integers is a pure bit-width truncation
Prove byte-identity for base16ct by enumerating whole input domains 99b8376 nandithebull 17h ago3000 // or sign-extension, never a range check. `cast` says exactly
3001 // that. (Nim's `T(x)` turns out to truncate here as well --
3002 // see DESIGN.md item 5 -- but `cast` is the spelling that
3003 // means it rather than the one that happens to agree.)
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3004 format!("cast[{}]({})", t.render(), v.code)
3005 }
3006 (f, Nim::Prim(p)) if f.is_integer() && (p == "float64" || p == "float32") => {
3007 format!("{}({})", p, v.code)
3008 }
3009 (Nim::Prim(b), t) if b == "bool" && t.is_integer() => {
3010 format!("{}(ord({}))", t.render(), v.code)
3011 }
3012 (Nim::Prim(r), t) if r == "Rune" && t.is_integer() => {
3013 format!("cast[{}](int32({}))", t.render(), v.code)
3014 }
3015 (f, Nim::Prim(r)) if f.is_integer() && r == "Rune" => {
3016 format!("Rune(int32({}))", v.code)
3017 }
3018 (Nim::Prim(a), Nim::Prim(b)) if a == b => v.code.clone(),
3019 (f, t) if matches!(f, Nim::Prim(p) if p.starts_with("float")) && t.is_integer() => {
3020 // Rust saturates float->int casts; Nim rounds and range-errors.
3021 // Not the same operation, so it is refused rather than mapped.
3022 return Err(format!(
3023 "`as {}` from a float: Rust saturates, Nim rounds and range-checks; \
3024 no faithful mapping is implemented",
3025 t.render()
3026 ));
3027 }
3028 (f, t) => {
3029 return Err(format!(
3030 "unsupported cast from `{}` to `{}`",
3031 f.render(),
3032 t.render()
3033 ))
3034 }
3035 };
3036 Ok(Val::new(code, Some(to)))
3037 }
3038
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3039 /// Rust's `?`: return early on the error branch, otherwise yield the value.
3040 ///
3041 /// The early return is statements, not an expression, so they are emitted
3042 /// ahead of the line being built. Every caller lowers its sub-expressions
3043 /// before emitting its own line, which is what makes that ordering hold.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3044 /// The container, start offset, length and element type an expression
3045 /// denotes as a slice. A window alias contributes its own offset, so
3046 /// `dst.get_mut(..n)` followed by `.chunks_exact_mut(2)` indexes straight
3047 /// into the original buffer rather than through a rebuilt view.
3048 fn slice_parts(
3049 &mut self,
3050 e: &Expr,
3051 ) -> Result<(String, String, String, Option<Nim>), String> {
3052 if let Some(Alias::Window { code, off, len, elem }) = self.window_of(e) {
3053 return Ok((code, off, len, elem));
3054 }
3055 let v = self.expr(e)?;
3056 let len = format!("{}.len", v.code);
3057 Ok((v.code, "0".to_string(), len, elem_of(&v.ty)))
3058 }
3059
3060 /// Expand `opt.map(|x| body)` / `res.and_then(|x| body)` inline.
3061 fn map_closure(
3062 &mut self,
3063 what: &str,
3064 recv: &Val,
3065 kind: &str,
3066 targs: &[Nim],
3067 c: &syn::ExprClosure,
3068 ) -> Result<Val, String> {
3069 if c.capture.is_some() {
3070 return Err("a `move` closure captures by value; Nim's closures \
3071 capture by reference, and the two are not the same"
3072 .into());
3073 }
3074 if c.inputs.len() != 1 {
3075 return Err(format!("`.{what}()` takes a one-argument closure"));
3076 }
3077 let pname = match &c.inputs[0] {
3078 Pat::Ident(i) => i.ident.to_string(),
3079 Pat::Wild(_) => "unused0".into(),
3080 _ => return Err("only plain identifier closure parameters are supported".into()),
3081 };
3082
3083 let is_opt = kind == "Option";
3084 let tmp = self.fresh("Map");
3085 let recv_ty = Nim::Named(kind.to_string(), targs.to_vec());
3086 self.line(&format!("let {}: {} = {}", tmp, recv_ty.render(), recv.code));
3087
3088 let body = match &*c.body {
3089 Expr::Block(b) => single_expr(&b.block)
3090 .ok_or("a closure body with statements is not implemented yet")?,
3091 other => other,
3092 };
3093 self.push_scope();
3094 // The parameter names the payload itself, so a view stays a view.
3095 self.bind_alias(
3096 &pname,
3097 Alias::Value {
3098 code: format!("{}.val", tmp),
3099 ty: Some(targs[0].clone()),
3100 },
3101 );
3102 let v = self.expr(body)?;
3103 self.pop_scope();
3104
3105 let inner = v
3106 .ty
3107 .clone()
3108 .ok_or_else(|| format!("cannot infer the result type of `.{what}()`"))?;
3109 // `and_then`'s closure already returns the wrapped type; `map`'s does
3110 // not and has to be re-wrapped.
3111 let (test, some_branch, none_branch, out_ty) = if is_opt {
3112 let out = if what == "map" {
3113 Nim::Named("Option".into(), vec![inner.clone()])
3114 } else {
3115 inner.clone()
3116 };
3117 let body_code = if what == "map" {
3118 format!("rsSome[{}]({})", inner.render(), v.code)
3119 } else {
3120 v.code.clone()
3121 };
3122 (
3123 format!("{}.has", tmp),
3124 body_code,
3125 format!("rsNone[{}]()", elem_arg(&out).render()),
3126 out,
3127 )
3128 } else {
3129 let e = targs[1].clone();
3130 let out = if what == "map" {
3131 Nim::Named("Result".into(), vec![inner.clone(), e.clone()])
3132 } else {
3133 inner.clone()
3134 };
3135 let ok_ty = elem_arg(&out);
3136 let body_code = if what == "map" {
3137 format!("rsOk[{}, {}]({})", inner.render(), e.render(), v.code)
3138 } else {
3139 v.code.clone()
3140 };
3141 (
3142 format!("{}.ok", tmp),
3143 body_code,
3144 format!("rsErr[{}, {}]({}.err)", ok_ty.render(), e.render(), tmp),
3145 out,
3146 )
3147 };
3148 Ok(Val::new(
3149 format!("(if {}: {} else: {})", test, some_branch, none_branch),
3150 Some(out_ty),
3151 ))
3152 }
3153
3154 /// `|x| x + 1` -> a Nim anonymous proc.
3155 ///
3156 /// Nim's closures capture by reference, as Rust's non-`move` closures do.
3157 /// A `move` closure captures by value, which is a different thing, so it
3158 /// is rejected rather than lowered to the same construct.
3159 fn closure(&mut self, c: &syn::ExprClosure, expect: Option<&Nim>) -> Result<Val, String> {
3160 if c.capture.is_some() {
3161 return Err("a `move` closure captures by value; Nim's closures \
3162 capture by reference, and the two are not the same"
3163 .into());
3164 }
3165 let want: Option<&Vec<Nim>> = match expect {
3166 Some(Nim::Proc(a, _)) => Some(a),
3167 _ => None,
3168 };
3169
3170 self.push_scope();
3171 let mut parts = Vec::new();
3172 let mut ptys = Vec::new();
3173 for (i, p) in c.inputs.iter().enumerate() {
3174 let (name, ann) = match p {
3175 Pat::Ident(id) => (id.ident.to_string(), None),
3176 Pat::Type(t) => match &*t.pat {
3177 Pat::Ident(id) => (id.ident.to_string(), Some(self.map_ty(&t.ty)?)),
3178 _ => return Err("only plain identifier closure parameters are supported".into()),
3179 },
3180 Pat::Wild(_) => (format!("unused{i}"), None),
3181 _ => return Err("only plain identifier closure parameters are supported".into()),
3182 };
3183 let t = ann
3184 .or_else(|| want.and_then(|w| w.get(i).cloned()))
3185 .ok_or_else(|| {
3186 format!(
3187 "cannot infer the type of closure parameter `{name}`; \
3188 annotate it"
3189 )
3190 })?;
3191 parts.push(format!("{}: {}", ident(&name), t.render()));
3192 self.bind(&name, t.clone());
3193 ptys.push(t);
3194 }
3195
3196 let ret_ann = match &c.output {
3197 ReturnType::Default => None,
3198 ReturnType::Type(_, t) => Some(self.map_ty(t)?.owned()),
3199 };
3200 let body = match &*c.body {
3201 Expr::Block(b) => single_expr(&b.block)
3202 .ok_or("a closure body with statements is not implemented yet")?,
3203 other => other,
3204 };
3205 let v = self.expr_at(body, ret_ann.as_ref())?;
3206 self.pop_scope();
3207
3208 let ret = ret_ann
3209 .or_else(|| v.ty.clone())
3210 .ok_or("cannot infer a closure's return type; annotate it")?;
3211 Ok(Val::new(
3212 format!("(proc ({}): {} = {})", parts.join(", "), ret.render(), v.code),
3213 Some(Nim::Proc(ptys, Box::new(ret))),
3214 ))
3215 }
3216
3217 /// Lower a block's statements at the current indentation, without opening
3218 /// a Nim `block:` -- used for `unsafe { .. }`, which introduces no scope
3219 /// of its own in the generated code.
3220 fn nested_block_flat(&mut self, b: &syn::Block) -> Result<(), String> {
3221 self.push_scope();
3222 let tail = self.block_body(b)?;
3223 self.emit_tail(tail);
3224 self.pop_scope();
3225 Ok(())
3226 }
3227
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3228 fn try_op(&mut self, t: &syn::ExprTry) -> Result<Val, String> {
3229 if self.in_loop_cond {
3230 return Err("`?` in a loop condition is not implemented yet: the \
3231 early-return it expands to would be evaluated once, \
3232 before the loop, rather than on each iteration"
3233 .into());
3234 }
3235 let v = self.expr(&t.expr)?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago3236 if self.fmt_param.is_some() {
3237 // Writing into a string cannot fail, so `?` on a formatter write
3238 // is a no-op. `?` on anything else can fail, and `format!` panics
3239 // when a formatting impl returns an error -- so that is what the
3240 // error branch does here, with std's own message.
3241 if v.ty.as_ref() == Some(&Nim::Unit) {
3242 return Ok(v);
3243 }
3244 if let Some(Nim::Named(n, a)) = v.ty.clone() {
3245 if n == "Result" && a.len() == 2 {
3246 let tmp = self.fresh("Fmt");
3247 self.line(&format!(
3248 "let {}: {} = {}",
3249 tmp,
3250 Nim::Named(n, a.clone()).render(),
3251 v.code
3252 ));
3253 self.line(&format!("if not {}.ok:", tmp));
3254 self.line(
3255 " rsPanic(\"a formatting trait implementation returned an error\")",
3256 );
3257 return Ok(Val::new(format!("{}.val", tmp), Some(a[0].clone())));
3258 }
3259 }
3260 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3261 if let (Some(guard), Some(w)) = (v.guard.clone(), v.window.clone()) {
3262 // An `Option`/`Result` of a view: the check is emitted here and the
3263 // view itself survives as an alias, since it has no value form.
3264 let ret = self.ret.clone().ok_or("`?` outside a function with a return type")?;
3265 let err = v.guard_err.clone().ok_or(
3266 "`?` on a `get`/`get_mut` needs an `ok_or` to say what the error is",
3267 )?;
3268 let Nim::Named(n, ra) = &ret else {
3269 return Err(format!("`?` in a function returning `{}`", ret.render()));
3270 };
3271 if n != "Result" || ra.len() != 2 {
3272 return Err(format!("`?` in a function returning `{}`", ret.render()));
3273 }
3274 self.line(&format!("if not {}:", guard));
3275 self.line(&format!(
3276 " return rsErr[{}, {}]({})",
3277 ra[0].render(),
3278 ra[1].render(),
3279 err
3280 ));
3281 let mut out = Val::new(String::new(), None);
3282 out.window = Some(w);
3283 return Ok(out);
3284 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3285 let vt = v.ty.clone().ok_or(
3286 "`?` needs a known `Result`/`Option` type; annotate the expression it applies to",
3287 )?;
3288 let ret = self
3289 .ret
3290 .clone()
3291 .ok_or("`?` outside a function with a return type")?;
3292 let tmp = self.fresh("Try");
3293 self.line(&format!("let {}: {} = {}", tmp, vt.render(), v.code));
3294
3295 match (&vt, &ret) {
3296 (Nim::Named(a, ai), Nim::Named(b, bi))
3297 if a == "Result" && b == "Result" && ai.len() == 2 && bi.len() == 2 =>
3298 {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3299 // Rust inserts a `From::from` on the error here. Where the
3300 // types differ we call the crate's own `impl From`; we never
3301 // assume the conversion is the identity.
3302 let err = if ai[1] == bi[1] {
3303 format!("{}.err", tmp)
3304 } else {
3305 let key = (type_name(&ai[1]), type_name(&bi[1]));
3306 let f = self.from_impls.get(&key).cloned().ok_or_else(|| {
3307 format!(
3308 "`?` needs `From<{}> for {}` to convert the error, and \
3309 no such `impl` is in scope; assuming the conversion is \
3310 the identity would be a guess",
3311 key.0, key.1
3312 )
3313 })?;
3314 format!("{}({}.err)", f, tmp)
3315 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3316 self.line(&format!("if not {}.ok:", tmp));
3317 self.line(&format!(
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3318 " return rsErr[{}, {}]({})",
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3319 bi[0].render(),
3320 bi[1].render(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3321 err
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3322 ));
3323 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
3324 }
3325 (Nim::Named(a, ai), Nim::Named(b, bi))
3326 if a == "Option" && b == "Option" && ai.len() == 1 && bi.len() == 1 =>
3327 {
3328 self.line(&format!("if not {}.has:", tmp));
3329 self.line(&format!(" return rsNone[{}]()", bi[0].render()));
3330 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
3331 }
3332 _ => Err(format!(
3333 "`?` on `{}` in a function returning `{}` is not a supported \
3334 combination",
3335 vt.render(),
3336 ret.render()
3337 )),
3338 }
3339 }
3340
3341 fn call(&mut self, c: &syn::ExprCall, expect: Option<&Nim>) -> Result<Val, String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3342 let Expr::Path(p) = &*c.func else {
3343 return Err("only calls to named functions are supported".into());
3344 };
3345 let name = path_name(&p.path);
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3346 let target = self.resolve_fn(&p.path);
3347 let ptys: Vec<Nim> = target
3348 .as_ref()
3349 .and_then(|k| self.fns.get(k))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3350 .map(|s| s.params.clone())
3351 .unwrap_or_default();
3352 let mut args = Vec::new();
3353 for (i, a) in c.args.iter().enumerate() {
3354 let want = ptys.get(i).cloned();
3355 args.push(self.expr_at(a, want.as_ref())?);
3356 }
3357 let codes: Vec<String> = args.iter().map(|a| a.code.clone()).collect();
3358
3359 // Constructors from the prelude.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3360 // `Ok`/`Err` must name the *whole* Result type, not just the half
3361 // being constructed: Nim cannot infer `E` from an `Ok(v)` alone.
3362 match name.as_str() {
3363 "Some" => {
3364 let inner = match expect {
3365 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].render(),
3366 _ => {
3367 return Err("`Some(..)` needs a known `Option<T>` type here; \
3368 annotate the binding or the return type"
3369 .into())
3370 }
3371 };
3372 return Ok(Val::new(
3373 format!("rsSome[{}]({})", inner, codes.join(", ")),
3374 expect.cloned(),
3375 ));
3376 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago3377 "Ok" if self.fmt_param.is_some()
3378 && matches!(c.args.first(), Some(Expr::Tuple(t)) if t.elems.is_empty()) =>
3379 {
3380 // `Ok(())` ends a `fmt` body: nothing more is written.
3381 return Ok(Val::new(String::new(), Some(Nim::Unit)));
3382 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3383 "Ok" | "Err" => {
3384 let (t, e) = match expect {
3385 Some(Nim::Named(n, a)) if n == "Result" && a.len() == 2 => {
3386 (a[0].render(), a[1].render())
3387 }
3388 _ => {
3389 return Err(format!(
3390 "`{name}(..)` needs a known `Result<T, E>` type here; \
3391 annotate the binding or the return type"
3392 ))
3393 }
3394 };
3395 let ctor = if name == "Ok" { "rsOk" } else { "rsErr" };
3396 let arg = if codes.is_empty() { String::new() } else { codes.join(", ") };
3397 return Ok(Val::new(
3398 format!("{}[{}, {}]({})", ctor, t, e, arg),
3399 expect.cloned(),
3400 ));
3401 }
3402 _ => {}
3403 }
3404
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago3405 // A tuple struct applied to arguments: `HexDisplay(bytes)`. Nim's
3406 // object constructor names its fields even when Rust's does not.
3407 if let Some(fields) = self.structs.get(&name).cloned() {
3408 if fields.len() == c.args.len() {
3409 let mut parts = Vec::new();
3410 for (i, a) in c.args.iter().enumerate() {
3411 let v = self.expr_at(a, Some(&fields[i].1))?;
3412 parts.push(format!("{}: {}", ident(&fields[i].0), v.code));
3413 }
3414 return Ok(Val::new(
3415 format!("{}({})", ident(&name), parts.join(", ")),
3416 Some(Nim::Named(name.clone(), vec![])),
3417 ));
3418 }
3419 }
3420
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago3421 // `u32::from(b)`: `From` between primitives is lossless by definition
3422 // -- it is the widening direction only -- so a plain Nim conversion is
3423 // exact. (The truncating direction is `as`, which is `cast`.)
3424 if name == "from" && codes.len() == 1 {
3425 if let Some(q) = p.path.segments.iter().rev().nth(1) {
3426 if let Some(Nim::Prim(t)) = ty::prim(&q.ident.to_string()) {
3427 return Ok(Val::new(
3428 format!("{}({})", t, codes[0]),
3429 Some(Nim::Prim(t)),
3430 ));
3431 }
3432 }
3433 }
3434
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3435 // `core::str::from_utf8_unchecked(b)` reinterprets a byte view as a
3436 // string view; no copy, no validation, same memory.
3437 if name == "from_utf8_unchecked" && codes.len() == 1 {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago3438 // `String::from_utf8_unchecked(v)` takes ownership and yields an
3439 // owned `String`; `str::from_utf8_unchecked(b)` borrows and yields
3440 // a view. Same name, different operations -- the qualifier says
3441 // which, and an unqualified call is ambiguous.
3442 let q = p
3443 .path
3444 .segments
3445 .iter()
3446 .rev()
3447 .nth(1)
3448 .map(|s| s.ident.to_string());
3449 return match q.as_deref() {
3450 Some("String") => Ok(Val::new(
3451 format!("rsStringOf({})", codes[0]),
3452 Some(Nim::Prim("string".into())),
3453 )),
3454 Some("str") => Ok(Val::new(
3455 format!("rsStrView({})", codes[0]),
3456 Some(Nim::OpenArray(Box::new(Nim::Prim("char".into())))),
3457 )),
3458 _ => Err(
3459 "`from_utf8_unchecked` must be written as `str::..` (a \
3460 borrowed view) or `String::..` (an owned string); the two \
3461 are different operations"
3462 .into(),
3463 ),
3464 };
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3465 }
3466
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3467 // A tuple enum variant applied to arguments: `Shape::Circle(1.0)`.
3468 if let Some((def, v)) = self.resolve_variant(&p.path) {
3469 return Ok(Val::new(
3470 format!("{}({})", def.ctor_ident(&v), codes.join(", ")),
3471 Some(Nim::Named(def.name.clone(), vec![])),
3472 ));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3473 }
3474
3475 // A bare path that names a primitive type is Rust's tuple-struct-like
3476 // conversion, e.g. `String::from(..)`; handled by the method path.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3477 // Calling a proc-typed local, which is how an `impl Fn(..)` parameter
3478 // is invoked.
3479 if let Some(Nim::Proc(_, ret)) = self.lookup(&name) {
3480 return Ok(Val::new(
3481 format!("{}({})", ident(&name), codes.join(", ")),
3482 Some((*ret).clone()),
3483 ));
3484 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago3485 // `Adler32::new()` / `Adler32::default()`: a method called through
3486 // its type rather than through a receiver.
3487 if let Some(q) = p.path.segments.iter().rev().nth(1).map(|s| s.ident.to_string()) {
3488 // `Self::new()` inside an `impl` names the type being implemented.
3489 let q = if q == "Self" {
3490 self.self_ty.as_ref().map(type_name).unwrap_or(q)
3491 } else {
3492 q
3493 };
3494 if let Some(sig) = self.methods.get(&(q.clone(), name.clone())) {
3495 let ret = sig.ret.clone();
3496 let nim = self
3497 .statics
3498 .get(&(q.clone(), name.clone()))
3499 .cloned()
3500 .unwrap_or_else(|| ident(&name));
3501 return Ok(Val::new(format!("{}({})", nim, codes.join(", ")), Some(ret)));
3502 }
3503 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3504 let ret = target.as_ref().and_then(|k| self.fns.get(k)).map(|s| s.ret.clone());
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3505 if ret.is_none() && !self.structs.contains_key(&name) && !self.enums.contains_key(&name) {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3506 return Err(format!(
3507 "call to unknown function `{name}`; only functions defined in \
3508 this file and the supported standard-library subset can be lowered"
3509 ));
3510 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3511 let nim = match &target {
3512 Some((m, n)) => self.fn_name(m, n),
3513 None => ident(&name),
3514 };
3515 Ok(Val::new(format!("{}({})", nim, codes.join(", ")), ret))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3516 }
3517
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3518 fn method(&mut self, m: &syn::ExprMethodCall, expect: Option<&Nim>) -> Result<Val, String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3519 let name = m.method.to_string();
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago3520 // `chunk_iter.remainder()` — the tail `chunks_exact` will not yield.
3521 if name == "remainder" && m.args.is_empty() {
3522 if let Expr::Path(p) = &*m.receiver {
3523 if let Some(Alias::Iterator(it)) = self.lookup_alias(&path_name(&p.path)) {
3524 if let Iter::Chunks { code, base, len, k, elem, .. } = &*it {
3525 let kept = format!("(({} div int({})) * int({}))", len, k, k);
3526 let mut v = Val::new(
3527 String::new(),
3528 elem.clone().map(|e| Nim::OpenArray(Box::new(e))),
3529 );
3530 v.window = Some(Alias::Window {
3531 code: code.clone(),
3532 off: format!("({} + {})", base, kept),
3533 len: format!("({} - {})", len, kept),
3534 elem: elem.clone(),
3535 });
3536 return Ok(v);
3537 }
3538 return Err(
3539 "`.remainder()` is only defined for a `chunks_exact` iterator".into(),
3540 );
3541 }
3542 }
3543 return Err("`.remainder()` needs an iterator bound by `let`".into());
3544 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3545 if let Some(Alias::Window { len, .. }) = self.window_of(&m.receiver) {
3546 match name.as_str() {
3547 "len" => {
3548 return Ok(Val::new(format!("uint({})", len), Some(Nim::Prim("uint".into()))))
3549 }
3550 "is_empty" => {
3551 return Ok(Val::new(format!("({} == 0)", len), Some(Nim::Prim("bool".into()))))
3552 }
3553 other => {
3554 return Err(format!(
3555 "`.{other}()` on a slice window from `chunks_exact`/\
3556 `windows` is not implemented; only indexing and \
3557 `len()` are"
3558 ))
3559 }
3560 }
3561 }
3562 let recv = self.expr(&m.receiver)?;
3563 let rt0 = recv.ty.clone();
3564
3565// `s.get(a..b)` / `s.get_mut(a..b)`: an `Option<&[T]>`. Nim has no
3566 // way to put a view in an object, so instead of materialising an
3567 // Option the view and its validity condition travel together until
3568 // an `ok_or`/`?`/`unwrap` resolves them.
3569 if matches!(name.as_str(), "get" | "get_mut")
3570 && matches!(m.args.first(), Some(Expr::Range(_)))
3571 {
3572 let Some(Expr::Range(r)) = m.args.first() else { unreachable!() };
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3573 let (code, base, blen, belem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3574 let lo = match &r.start {
3575 Some(e) => format!("int({})", self.expr(e)?.code),
3576 None => "0".into(),
3577 };
3578 let len = match (&r.end, r.limits) {
3579 (Some(e), syn::RangeLimits::HalfOpen(_)) => {
3580 format!("(int({}) - {})", self.expr(e)?.code, lo)
3581 }
3582 (Some(e), syn::RangeLimits::Closed(_)) => {
3583 format!("(int({}) - {} + 1)", self.expr(e)?.code, lo)
3584 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3585 (None, _) => format!("({} - {})", blen, lo),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3586 };
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3587 // Hoisted, so the bounds are computed once -- as Rust computes
3588 // them once -- and cannot be re-evaluated later in a scope where
3589 // the names they mention have been shadowed by a loop pattern.
3590 let off_t = self.fresh("Off");
3591 let len_t = self.fresh("Len");
3592 self.line(&format!("let {}: int = {} + {}", off_t, base, lo));
3593 self.line(&format!("let {}: int = {}", len_t, len));
3594 let elem = belem
3595 .or_else(|| elem_of(&rt0))
3596 .ok_or("cannot infer the element type of this slice")?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3597 let mut v = Val::new(
3598 String::new(),
3599 Some(Nim::Named(
3600 "Option".into(),
3601 vec![Nim::OpenArray(Box::new(elem.clone()))],
3602 )),
3603 );
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3604 v.guard = Some(format!("({} + {} <= {})", off_t, len_t, blen));
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3605 v.window = Some(Alias::Window {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3606 code,
3607 off: off_t,
3608 len: len_t,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3609 elem: Some(elem),
3610 });
3611 return Ok(v);
3612 }
3613
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3614 // `.map`/`.and_then` over an `Option`/`Result` take a closure whose
3615 // parameter type comes from the receiver, so they are handled before
3616 // the arguments are lowered. The closure is expanded inline, with its
3617 // parameter aliased to the payload: that keeps the whole thing an
3618 // expression and avoids handing a view to a generic proc.
3619 if matches!(name.as_str(), "map" | "and_then") && m.args.len() == 1 {
3620 if let (Some(Nim::Named(kind, targs)), Expr::Closure(c)) =
3621 (recv.ty.clone(), &m.args[0])
3622 {
3623 if (kind == "Option" && targs.len() == 1) || (kind == "Result" && targs.len() == 2)
3624 {
3625 return self.map_closure(&name, &recv, &kind, &targs, c);
3626 }
3627 }
3628 }
3629
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3630 // `x.wrapping_add(1)` and `x.min(3)` take an argument of the receiver's
3631 // own type; `v.push(e)` takes the element type.
3632 let arg_want = match (name.as_str(), &recv.ty) {
3633 ("push", Some(Nim::Seq(t))) | ("push", Some(Nim::OpenArray(t))) => Some((**t).clone()),
3634 (_, t) => t.clone(),
3635 };
3636 let mut args = Vec::new();
3637 for a in &m.args {
3638 args.push(self.expr_at(a, arg_want.as_ref())?);
3639 }
3640 let a0 = args.first().map(|a| a.code.clone());
3641 let rt = recv.ty.clone();
3642
3643 let (code, ty) = match name.as_str() {
3644 // Rust's `len()` is `usize`; Nim's is `int`. The conversion is
3645 // explicit so that a `usize` binding type-checks on the Nim side.
3646 "len" => (format!("uint({}.len)", recv.code), Some(Nim::Prim("uint".into()))),
3647 "is_empty" => (format!("({}.len == 0)", recv.code), Some(Nim::Prim("bool".into()))),
3648 "push" => (format!("{}.add({})", recv.code, a0.unwrap_or_default()), Some(Nim::Unit)),
3649 "clone" | "to_vec" | "to_owned" | "as_slice" | "as_ref" | "as_mut" | "iter"
3650 | "into_iter" => (recv.code.clone(), rt.clone()),
3651 "unwrap" | "expect" => {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago3652 // Expanded inline rather than called as a generic proc: when
3653 // the payload is a view, Nim can only borrow from a path
3654 // expression, which a proc body containing the panic is not.
3655 let (kind, inner) = match &rt {
3656 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => {
3657 ("Option", a[0].clone())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3658 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago3659 Some(Nim::Named(n, a)) if n == "Result" && a.len() == 2 => {
3660 ("Result", a[0].clone())
3661 }
3662 _ => {
3663 return Err(format!(
3664 "`.{name}()` needs a known `Option`/`Result` receiver type"
3665 ))
3666 }
3667 };
3668 if self.in_loop_cond {
3669 return Err(format!(
3670 "`.{name}()` in a loop condition is not implemented yet: the \
3671 check it expands to would run once, before the loop"
3672 ));
3673 }
3674 let tmp = self.fresh("Unwrap");
3675 let rty = rt.clone().unwrap();
3676 self.line(&format!("let {}: {} = {}", tmp, rty.render(), recv.code));
3677 let (test, msg) = if kind == "Option" {
3678 (format!("{}.has", tmp), "called `Option::unwrap()` on a `None` value")
3679 } else {
3680 (format!("{}.ok", tmp), "called `Result::unwrap()` on an `Err` value")
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3681 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago3682 let msg = if name == "expect" {
3683 args.first().map(|a| a.code.clone()).unwrap_or_else(|| fmt::nim_str(msg))
3684 } else {
3685 fmt::nim_str(msg)
3686 };
3687 self.line(&format!("if not {}:", test));
3688 self.line(&format!(" rsPanic({})", msg));
3689 // If the payload is a view, hand back an alias rather than a
3690 // value: Nim will not let a `let` borrow out of a local, and a
3691 // view is a reference anyway, so there is nothing to bind.
3692 // `{tmp}.val` is a plain field access, so substituting it at
3693 // each use re-evaluates nothing.
3694 if matches!(inner, Nim::OpenArray(_)) {
3695 let mut v = Val::new(format!("{}.val", tmp), Some(inner.clone()));
3696 v.window = Some(Alias::Value {
3697 code: format!("{}.val", tmp),
3698 ty: Some(inner),
3699 });
3700 return Ok(v);
3701 }
3702 (format!("{}.val", tmp), Some(inner))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3703 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3704 "ok_or" if recv.guard.is_some() => {
3705 let e = args.first().ok_or("`ok_or` takes one argument")?;
3706 let ety = e.ty.clone();
3707 let mut v = recv.clone();
3708 v.guard_err = Some(e.code.clone());
3709 v.ty = match (&recv.ty, ety) {
3710 (Some(Nim::Named(_, a)), Some(et)) if a.len() == 1 => {
3711 Some(Nim::Named("Result".into(), vec![a[0].clone(), et]))
3712 }
3713 _ => None,
3714 };
3715 return Ok(v);
3716 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3717 "ok_or" => {
3718 let inner = match &rt {
3719 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].clone(),
3720 _ => return Err("`ok_or` needs a known `Option<T>` receiver".into()),
3721 };
3722 let e = args.first().ok_or("`ok_or` takes one argument")?;
3723 let ety = e
3724 .ty
3725 .clone()
3726 .ok_or("`ok_or` needs a known error type for its argument")?;
3727 (
3728 format!(
3729 "rsOkOr[{}, {}]({}, {})",
3730 inner.render(),
3731 ety.render(),
3732 recv.code,
3733 e.code
3734 ),
3735 Some(Nim::Named("Result".into(), vec![inner, ety])),
3736 )
3737 }
3738 "unwrap_or" => {
3739 let inner = match &rt {
3740 Some(Nim::Named(n, a)) if (n == "Option" && a.len() == 1) || (n == "Result" && a.len() == 2) => {
3741 Some(a[0].clone())
3742 }
3743 _ => None,
3744 };
3745 (
3746 format!("unwrapOr({}, {})", recv.code, a0.unwrap_or_default()),
3747 inner,
3748 )
3749 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3750 "is_some" => (format!("{}.has", recv.code), Some(Nim::Prim("bool".into()))),
3751 "is_none" => (format!("(not {}.has)", recv.code), Some(Nim::Prim("bool".into()))),
3752 "is_ok" => (format!("{}.ok", recv.code), Some(Nim::Prim("bool".into()))),
3753 "is_err" => (format!("(not {}.ok)", recv.code), Some(Nim::Prim("bool".into()))),
3754
3755 // Settled empirically: Nim's fixed-width *unsigned* arithmetic
3756 // wraps silently, matching Rust's `wrapping_*`. For *signed* types
3757 // Nim raises OverflowDefect, so the operation is routed through
3758 // the unsigned view of the same width, which is what Rust's
3759 // wrapping_* is defined to compute.
3760 "wrapping_add" | "wrapping_sub" | "wrapping_mul" => {
3761 let op = match name.as_str() {
3762 "wrapping_add" => "+",
3763 "wrapping_sub" => "-",
3764 _ => "*",
3765 };
3766 let t = rt.clone().ok_or_else(|| {
3767 format!("`{name}` needs a known receiver type to pick the wrapping width")
3768 })?;
3769 if !t.is_integer() {
3770 return Err(format!("`{name}` on a non-integer type"));
3771 }
3772 let arg = a0.ok_or_else(|| format!("`{name}` takes one argument"))?;
3773 if t.is_unsigned() {
3774 (format!("({} {} {})", recv.code, op, arg), Some(t))
3775 } else {
3776 let u = unsigned_peer(&t)?;
3777 (
3778 format!(
3779 "cast[{}](cast[{}]({}) {} cast[{}]({}))",
3780 t.render(), u, recv.code, op, u, arg
3781 ),
3782 Some(t),
3783 )
3784 }
3785 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3786 // Inside a formatting impl, a write through the `Formatter` *is*
3787 // 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 18h ago3788 "write_str" | "write_char" if self.is_fmt_param(&m.receiver) => {
3789 let a = args.first().ok_or("`write_str` takes one argument")?;
3790 // A `&str` argument is a character view, not a Nim string.
3791 let text = match &a.ty {
3792 Some(Nim::Prim(p)) if p == "string" => a.code.clone(),
3793 _ => format!("rsDisplay({})", a.code),
3794 };
3795 (format!("result.add({})", text), Some(Nim::Unit))
3796 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3797 "abs" => (format!("abs({})", recv.code), rt.clone()),
3798 "min" => (format!("min({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
3799 "max" => (format!("max({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
3800 "to_string" => (format!("rsDisplay({})", recv.code), Some(Nim::Prim("string".into()))),
3801 "as_bytes" | "into_bytes" => (
3802 format!("rsBytes({})", recv.code),
3803 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
3804 ),
3805
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3806 "into" => {
3807 // `.into()` resolves through the `impl From` declarations, and
3808 // needs the target type to pick one.
3809 let from = rt
3810 .clone()
3811 .ok_or("`.into()` needs a known receiver type")?;
3812 let to = expect
3813 .ok_or("`.into()` needs a known target type; annotate the binding")?;
3814 let key = (type_name(&from), type_name(to));
3815 let f = self.from_impls.get(&key).cloned().ok_or_else(|| {
3816 format!(
3817 "no `impl From<{}> for {}` in this file, so `.into()` has \
3818 no conversion to call",
3819 key.0, key.1
3820 )
3821 })?;
3822 (format!("{}({})", f, recv.code), Some(to.clone()))
3823 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3824 _ => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3825 // A method defined in this file via `impl`, found by the
3826 // receiver's type rather than by name alone.
3827 let key = rt.as_ref().map(|t| (type_name(t), name.clone()));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago3828 let sig = key
3829 .as_ref()
3830 .and_then(|k| self.methods.get(k))
3831 .map(|s| s.ret.clone());
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3832 if let Some(ret) = sig {
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago3833 // Use the name the proc was actually emitted under: an
3834 // inherent method is qualified by its module, a trait
3835 // method by its trait.
3836 let nim = key
3837 .and_then(|k| self.statics.get(&k).cloned())
3838 .unwrap_or_else(|| ident(&name));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3839 let mut all = vec![recv.code.clone()];
3840 all.extend(args.iter().map(|a| a.code.clone()));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago3841 (format!("{}({})", nim, all.join(", ")), Some(ret))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3842 } else {
3843 return Err(format!(
3844 "unsupported method `.{name}()`; it is neither defined in \
3845 this file nor part of the standard-library subset that \
3846 has a verified Nim equivalent"
3847 ));
3848 }
3849 }
3850 };
3851 Ok(Val::new(code, ty))
3852 }
3853
3854 // -------------------------------------------------------------- macros
3855
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3856 /// The element type of a `vec![..]`, from its first element.
3857 fn vec_elem(&mut self, mac: &syn::Macro) -> Result<Option<Nim>, String> {
3858 let body = mac.tokens.to_string();
3859 if body.trim().is_empty() {
3860 return Ok(None);
3861 }
3862 let first: Option<Expr> = if body.contains(';') {
3863 // The whole body must be consumed or the parse fails, so the
3864 // length is parsed too even though only the element is wanted.
3865 mac.parse_body_with(|input: syn::parse::ParseStream| {
3866 let v: Expr = input.parse()?;
3867 input.parse::<syn::Token![;]>()?;
3868 let _len: Expr = input.parse()?;
3869 Ok(v)
3870 })
3871 .ok()
3872 } else {
3873 mac.parse_body_with(
3874 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
3875 )
3876 .ok()
3877 .and_then(|p| p.into_iter().next())
3878 };
3879 match first {
3880 Some(e) => Ok(self.expr(&e)?.ty),
3881 None => Ok(None),
3882 }
3883 }
3884
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3885 fn macro_call(&mut self, mac: &syn::Macro) -> Result<String, String> {
3886 let name = path_name(&mac.path);
3887 match name.as_str() {
3888 "println" | "print" | "eprintln" | "eprint" => {
3889 let s = self.format_args(mac)?;
3890 let nl = name.ends_with("ln");
3891 Ok(match (name.starts_with('e'), nl) {
3892 (false, true) => format!("echo {s}"),
3893 (false, false) => format!("stdout.write({s})"),
3894 (true, true) => format!("stderr.writeLine({s})"),
3895 (true, false) => format!("stderr.write({s})"),
3896 })
3897 }
3898 "format" => self.format_args(mac),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3899 "write" | "writeln" => {
3900 // `write!(f, "..", ..)` inside a formatting impl: the first
3901 // argument is the sink, the rest is an ordinary format call.
3902 let args: Vec<Expr> = mac
3903 .parse_body_with(syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated)
3904 .map_err(|e| format!("write!: {e}"))?
3905 .into_iter()
3906 .collect();
3907 let sink = args.first().ok_or("`write!` needs a sink")?;
3908 if !self.is_fmt_param(sink) {
3909 return Err("`write!` to anything but the `Formatter` of the \
3910 enclosing formatting impl is not implemented"
3911 .into());
3912 }
3913 let s = self.format_pieces(&args[1..])?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago3914 let s = if name == "writeln" {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3915 format!("({} & \"\\n\")", s)
3916 } else {
3917 s
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago3918 };
3919 Ok(format!("result.add({})", s))
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago3920 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3921 "panic" => {
3922 let s = self.format_args(mac)?;
3923 Ok(format!("rsPanic({s})"))
3924 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago3925 // `debug_assert*` fires in debug builds, which is the profile
3926 // this project models, so it lowers the same as `assert*`.
3927 "assert" | "debug_assert" => {
3928 let args: Vec<Expr> = mac
3929 .parse_body_with(
3930 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
3931 )
3932 .map_err(|e| format!("{name}!: {e}"))?
3933 .into_iter()
3934 .collect();
3935 let cond = args.first().ok_or("`assert!` needs a condition")?;
3936 let v = self.expr(cond)?;
3937 let msg = if args.len() > 1 {
3938 self.format_pieces(&args[1..])?
3939 } else {
3940 fmt::nim_str("assertion failed")
3941 };
3942 Ok(format!("(if not ({}): rsPanic({}))", v.code, msg))
3943 }
3944 "assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne" => {
3945 let args: Vec<Expr> = mac
3946 .parse_body_with(
3947 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
3948 )
3949 .map_err(|e| format!("{name}!: {e}"))?
3950 .into_iter()
3951 .collect();
3952 if args.len() < 2 {
3953 return Err(format!("`{name}!` takes two operands"));
3954 }
3955 let a = self.expr(&args[0])?;
3956 let b = self.expr_at(&args[1], a.ty.as_ref())?;
3957 let ne = name.ends_with("_ne");
3958 let op = if ne { "!=" } else { "==" };
3959 // Rust's message shows both sides; reproducing it keeps a
3960 // failing assertion as informative as the original.
3961 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 19h ago3962 Ok(format!(
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago3963 "(if not (({}) {} ({})): rsPanic({} & \"\\n left: \" & rsDebug({}) & \"\\n right: \" & rsDebug({})))",
3964 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 19h ago3965 ))
3966 }
3967 "vec" => {
3968 let body = mac.tokens.to_string();
3969 if body.trim().is_empty() {
3970 return Ok("@[]".into());
3971 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3972 // `vec![elem; n]` is the repeat form, not a list. The macro
3973 // body has no brackets, so it is parsed directly.
3974 if body.contains(';') {
3975 let (v, n) = mac
3976 .parse_body_with(|input: syn::parse::ParseStream| {
3977 let v: Expr = input.parse()?;
3978 input.parse::<syn::Token![;]>()?;
3979 let n: Expr = input.parse()?;
3980 Ok((v, n))
3981 })
3982 .map_err(|e| format!("vec![elem; n]: {e}"))?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3983 let want = self.vec_expect.clone();
3984 let v = self.expr_at(&v, want.as_ref())?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago3985 let n = self.expr(&n)?;
3986 return Ok(format!("newSeqWith(int({}), {})", n.code, v.code));
3987 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3988 let elems: syn::punctuated::Punctuated<Expr, syn::Token![,]> = mac
3989 .parse_body_with(syn::punctuated::Punctuated::parse_terminated)
3990 .map_err(|e| format!("vec!: {e}"))?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3991 let want = self.vec_expect.clone();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3992 let mut parts = Vec::new();
3993 for e in &elems {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago3994 parts.push(self.expr_at(e, want.as_ref())?.code);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago3995 }
3996 Ok(format!("@[{}]", parts.join(", ")))
3997 }
3998 other => Err(format!(
3999 "unsupported macro `{other}!`; a macro whose expansion is not \
4000 known cannot be lowered faithfully"
4001 )),
4002 }
4003 }
4004
4005 /// `println!("{} {}", a, b)` -> a Nim string-concatenation expression.
4006 fn format_args(&mut self, mac: &syn::Macro) -> Result<String, String> {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago4007 let args: Vec<Expr> = mac
4008 .parse_body_with(syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated)
4009 .map_err(|e| format!("format arguments: {e}"))?
4010 .into_iter()
4011 .collect();
4012 self.format_pieces(&args)
4013 }
4014
4015 /// `["{} {}", a, b]` -> a Nim string-concatenation expression.
4016 fn format_pieces(&mut self, args: &[Expr]) -> Result<String, String> {
4017 let Some(Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. })) = args.first() else {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago4018 if args.is_empty() {
4019 return Ok("\"\"".into());
4020 }
4021 return Err("the first argument must be a literal format string".into());
4022 };
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago4023 let rest: Vec<&Expr> = args[1..].iter().collect();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago4024
4025 let pieces = fmt::parse(&s.value())?;
4026 let mut parts: Vec<String> = Vec::new();
4027 let mut next = 0usize;
4028 let mut used = vec![false; rest.len()];
4029 for p in &pieces {
4030 match p {
4031 fmt::Piece::Lit(l) => parts.push(fmt::nim_str(l)),
4032 fmt::Piece::Arg { r#ref, spec } => {
4033 let v = match r#ref {
4034 fmt::Ref::Next => {
4035 let e = rest.get(next).ok_or("too few arguments for format string")?;
4036 used[next] = true;
4037 next += 1;
4038 self.expr(e)?
4039 }
4040 fmt::Ref::Index(i) => {
4041 let e = rest.get(*i).ok_or("format index out of range")?;
4042 used[*i] = true;
4043 self.expr(e)?
4044 }
4045 fmt::Ref::Named(n) => {
4046 let t = self.lookup(n).ok_or_else(|| {
4047 format!("`{{{n}}}` captures `{n}`, which is not in scope")
4048 })?;
4049 Val::new(ident(n), Some(t))
4050 }
4051 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 18h ago4052 let integer = v.ty.as_ref().is_some_and(|t| t.is_integer());
4053 if spec.radix.is_some() && !integer && v.ty.is_none() {
4054 return Err(
4055 "a radix format (`{:x}`, `{:b}`, ...) needs a known \
4056 argument type: on an integer it formats the bit \
4057 pattern, on anything else it calls that type's own \
4058 impl"
4059 .into(),
4060 );
4061 }
4062 parts.push(fmt::render_arg(&v.code, spec, integer));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago4063 }
4064 }
4065 }
4066 // Rust rejects an argument that no `{}` consumes; so do we, rather
4067 // than dropping it from the output.
4068 if let Some(i) = used.iter().position(|u| !u) {
4069 return Err(format!(
4070 "argument {} is never used by the format string",
4071 i + 1
4072 ));
4073 }
4074 Ok(if parts.is_empty() { "\"\"".into() } else { parts.join(" & ") })
4075 }
4076}
4077
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago4078/// Whether a pattern introduces a binding.
4079fn binds(p: &Pat) -> bool {
4080 match p {
4081 Pat::Ident(_) => true,
4082 Pat::Guard(g) => binds(&g.pat),
4083 Pat::Paren(x) => binds(&x.pat),
4084 Pat::Reference(r) => binds(&r.pat),
4085 Pat::Or(o) => o.cases.iter().any(binds),
4086 Pat::TupleStruct(t) => t.elems.iter().any(|_| true),
4087 Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_) => true,
4088 _ => false,
4089 }
4090}
4091
4092/// Whether a pattern looks inside the value, which a Nim `case` cannot do.
4093fn destructures(p: &Pat) -> bool {
4094 matches!(
4095 p,
4096 Pat::TupleStruct(_) | Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_)
4097 ) || matches!(p, Pat::Guard(g) if destructures(&g.pat))
4098 || matches!(p, Pat::Paren(x) if destructures(&x.pat))
4099 || matches!(p, Pat::Reference(r) if destructures(&r.pat))
4100}
4101
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago4102/// Whether an expression has a direct Nim expression form.
4103///
4104/// Nim's `if` is an expression only when every arm is a single expression, and
4105/// its `case` is never one here. Anything else has to be lowered as statements
4106/// that assign into a target.
4107fn expressible(e: &Expr) -> bool {
4108 match e {
4109 Expr::If(i) => {
4110 let Some(then) = single_expr(&i.then_branch) else { return false };
4111 if !expressible(then) {
4112 return false;
4113 }
4114 match &i.else_branch {
4115 None => false,
4116 Some((_, els)) => match &**els {
4117 Expr::Block(b) => single_expr(&b.block).is_some_and(expressible),
4118 other => expressible(other),
4119 },
4120 }
4121 }
4122 Expr::Match(_) | Expr::Block(_) | Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => false,
4123 _ => true,
4124 }
4125}
4126
4127/// The single expression a block consists of, if that is all it is. An `if`
4128/// can only be lowered as a Nim `if`-expression when both arms are this shape.
4129fn single_expr(b: &syn::Block) -> Option<&Expr> {
4130 match (b.stmts.len(), b.stmts.first()) {
4131 (1, Some(Stmt::Expr(e, None))) => Some(e),
4132 _ => None,
4133 }
4134}
4135
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago4136/// Substitute `params[i] -> args[i]` through a type. Enough of the type
4137/// grammar is covered to expand the aliases we accept; anything else is left
4138/// alone and will be reported by `ty::map` if it is unsupported.
4139fn substitute(t: &syn::Type, params: &[String], args: &[syn::Type]) -> syn::Type {
4140 use syn::Type;
4141 match t {
4142 Type::Path(p) => {
4143 if p.qself.is_none() && p.path.segments.len() == 1 {
4144 let seg = &p.path.segments[0];
4145 if seg.arguments.is_empty() {
4146 let name = seg.ident.to_string();
4147 if let Some(i) = params.iter().position(|x| *x == name) {
4148 return args[i].clone();
4149 }
4150 }
4151 }
4152 let mut p = p.clone();
4153 for seg in &mut p.path.segments {
4154 if let syn::PathArguments::AngleBracketed(a) = &mut seg.arguments {
4155 for g in &mut a.args {
4156 if let syn::GenericArgument::Type(t) = g {
4157 *t = substitute(t, params, args);
4158 }
4159 }
4160 }
4161 }
4162 Type::Path(p)
4163 }
4164 Type::Reference(r) => {
4165 let mut r = r.clone();
4166 r.elem = Box::new(substitute(&r.elem, params, args));
4167 Type::Reference(r)
4168 }
4169 Type::Slice(sl) => {
4170 let mut sl = sl.clone();
4171 sl.elem = Box::new(substitute(&sl.elem, params, args));
4172 Type::Slice(sl)
4173 }
4174 Type::Array(a) => {
4175 let mut a = a.clone();
4176 a.elem = Box::new(substitute(&a.elem, params, args));
4177 Type::Array(a)
4178 }
4179 Type::Tuple(tp) => {
4180 let mut tp = tp.clone();
4181 tp.elems = tp.elems.iter().map(|e| substitute(e, params, args)).collect();
4182 Type::Tuple(tp)
4183 }
4184 Type::Paren(p) => substitute(&p.elem, params, args),
4185 Type::Group(g) => substitute(&g.elem, params, args),
4186 other => other.clone(),
4187 }
4188}
4189
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago4190// --------------------------------------------------------------- utilities
4191
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago4192/// Whether a return type is a borrow of one of the arguments, which Nim
4193/// models with a view rather than with an owned copy.
4194fn returns_borrow(t: &syn::Type) -> bool {
4195 match t {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago4196 syn::Type::Reference(r) => match &*r.elem {
4197 syn::Type::Slice(_) => true,
4198 // `&str` is a borrow of someone else's bytes too, and returning it
4199 // means returning a view, not an owned string.
4200 syn::Type::Path(p) => p.path.is_ident("str"),
4201 _ => false,
4202 },
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago4203 syn::Type::Paren(p) => returns_borrow(&p.elem),
4204 syn::Type::Group(g) => returns_borrow(&g.elem),
4205 _ => false,
4206 }
4207}
4208
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 18h ago4209/// The module a `use` prefix names. `crate`, `self` and `super` all resolve
4210/// to the crate root, which is where a flattened module's items live unless
4211/// they came from one of the extra input files.
4212fn module_of(prefix: &[String]) -> String {
4213 match prefix.last() {
4214 Some(m) if m != "crate" && m != "self" && m != "super" => m.clone(),
4215 _ => String::new(),
4216 }
4217}
4218
4219/// The first type argument of an `Option[T]` / `Result[T, E]`.
4220fn elem_arg(t: &Nim) -> Nim {
4221 match t {
4222 Nim::Named(_, a) if !a.is_empty() => a[0].clone(),
4223 other => other.clone(),
4224 }
4225}
4226
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago4227/// The element type of a sequence-like Nim type.
4228fn elem_of(t: &Option<Nim>) -> Option<Nim> {
4229 match t {
4230 Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) | Some(Nim::Array(_, e)) => Some((**e).clone()),
4231 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
4232 _ => None,
4233 }
4234}
4235
4236/// The short name a Nim type is known by, for keying method tables.
4237fn type_name(t: &Nim) -> String {
4238 match t {
4239 Nim::Named(n, _) => n.clone(),
4240 Nim::Prim(p) => p.clone(),
4241 other => other.render(),
4242 }
4243}
4244
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago4245/// `(trait, operator)` for every operator trait we dispatch.
4246const OPERATOR_TRAITS: &[(&str, &str)] = &[
4247 ("Add", "+"), ("Sub", "-"), ("Mul", "*"), ("Div", "/"), ("Rem", "%"),
4248 ("BitAnd", "&"), ("BitOr", "|"), ("BitXor", "^"), ("Shl", "<<"), ("Shr", ">>"),
4249 ("AddAssign", "+="), ("SubAssign", "-="), ("MulAssign", "*="), ("DivAssign", "/="),
4250 ("RemAssign", "%="), ("BitAndAssign", "&="), ("BitOrAssign", "|="),
4251 ("BitXorAssign", "^="), ("ShlAssign", "<<="), ("ShrAssign", ">>="),
4252 ("Neg", "neg"), ("Not", "not"),
4253];
4254
4255/// `(operator, trait method name)`.
4256const OP_METHOD: &[(&str, &str)] = &[
4257 ("+", "add"), ("-", "sub"), ("*", "mul"), ("/", "div"), ("%", "rem"),
4258 ("&", "bitand"), ("|", "bitor"), ("^", "bitxor"), ("<<", "shl"), (">>", "shr"),
4259 ("+=", "add_assign"), ("-=", "sub_assign"), ("*=", "mul_assign"),
4260 ("/=", "div_assign"), ("%=", "rem_assign"), ("&=", "bitand_assign"),
4261 ("|=", "bitor_assign"), ("^=", "bitxor_assign"), ("<<=", "shl_assign"),
4262 (">>=", "shr_assign"), ("neg", "neg"), ("not", "not"),
4263];
4264
4265fn op_method(op: &str) -> &'static str {
4266 OP_METHOD.iter().find(|(o, _)| *o == op).map(|(_, m)| *m).unwrap_or("")
4267}
4268
4269/// The operator symbol a compound assignment applies.
4270fn compound_symbol(op: &BinOp) -> &'static str {
4271 match op {
4272 BinOp::AddAssign(_) => "+=",
4273 BinOp::SubAssign(_) => "-=",
4274 BinOp::MulAssign(_) => "*=",
4275 BinOp::DivAssign(_) => "/=",
4276 BinOp::RemAssign(_) => "%=",
4277 BinOp::BitAndAssign(_) => "&=",
4278 BinOp::BitOrAssign(_) => "|=",
4279 BinOp::BitXorAssign(_) => "^=",
4280 BinOp::ShlAssign(_) => "<<=",
4281 BinOp::ShrAssign(_) => ">>=",
4282 _ => "",
4283 }
4284}
4285
4286fn binary_symbol(op: &BinOp) -> &'static str {
4287 match op {
4288 BinOp::Add(_) => "+",
4289 BinOp::Sub(_) => "-",
4290 BinOp::Mul(_) => "*",
4291 BinOp::Div(_) => "/",
4292 BinOp::Rem(_) => "%",
4293 BinOp::BitAnd(_) => "&",
4294 BinOp::BitOr(_) => "|",
4295 BinOp::BitXor(_) => "^",
4296 BinOp::Shl(_) => "<<",
4297 BinOp::Shr(_) => ">>",
4298 _ => "",
4299 }
4300}
4301
4302/// The operator a trait overloads, if it is one of the operator traits.
4303fn operator_trait(t: &str) -> Option<&'static str> {
4304 Some(match t {
4305 "Add" => "+",
4306 "Sub" => "-",
4307 "Mul" => "*",
4308 "Div" => "/",
4309 "Rem" => "%",
4310 "BitAnd" => "&",
4311 "BitOr" => "|",
4312 "BitXor" => "^",
4313 "Shl" => "<<",
4314 "Shr" => ">>",
4315 "AddAssign" => "+=",
4316 "SubAssign" => "-=",
4317 "MulAssign" => "*=",
4318 "DivAssign" => "/=",
4319 "RemAssign" => "%=",
4320 "BitAndAssign" => "&=",
4321 "BitOrAssign" => "|=",
4322 "BitXorAssign" => "^=",
4323 "ShlAssign" => "<<=",
4324 "ShrAssign" => ">>=",
4325 "Neg" => "neg",
4326 "Not" => "not",
4327 _ => return None,
4328 })
4329}
4330
4331/// The Nim proc name for a trait method, qualified by trait and type so that
4332/// two traits declaring the same method name cannot collide.
4333fn trait_method_name(ty: &str, tr: &str, m: &str) -> String {
4334 format!("rs{}_{}_{}", tr, ty, m)
4335}
4336
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 18h ago4337fn is_fmt_trait(t: &str) -> bool {
4338 matches!(t, "Display" | "Debug" | "LowerHex" | "UpperHex" | "Binary" | "Octal")
4339}
4340
4341/// The prelude proc a formatting trait's output is produced by.
4342fn fmt_proc(t: &str) -> &'static str {
4343 match t {
4344 "Display" => "rsDisplay",
4345 "Debug" => "rsDebug",
4346 "LowerHex" => "rsLowerHex",
4347 "UpperHex" => "rsUpperHex",
4348 "Binary" => "rsBinary",
4349 _ => "rsOctal",
4350 }
4351}
4352
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 17h ago4353/// Whether an expression is an iterator-producing chain rather than a value.
4354fn is_iterator_expr(e: &Expr) -> bool {
4355 match e {
4356 Expr::MethodCall(m) => matches!(
4357 m.method.to_string().as_str(),
4358 "iter" | "iter_mut" | "into_iter" | "enumerate" | "zip" | "chunks_exact"
4359 | "chunks_exact_mut" | "windows"
4360 ),
4361 Expr::Paren(p) => is_iterator_expr(&p.expr),
4362 _ => false,
4363 }
4364}
4365
Prove byte-identity for base16ct by enumerating whole input domains 99b8376 nandithebull 17h ago4366/// Whether an expression denotes a place -- a variable, a field, or an index
4367/// or slice of one -- and so may be re-evaluated with no side effect.
4368fn is_pure_place(e: &Expr) -> bool {
4369 match e {
4370 Expr::Path(_) => true,
4371 Expr::Field(f) => is_pure_place(&f.base),
4372 Expr::Index(i) => {
4373 is_pure_place(&i.expr)
4374 && match &*i.index {
4375 Expr::Range(r) => {
4376 r.start.as_deref().map_or(true, is_pure_place)
4377 && r.end.as_deref().map_or(true, is_pure_place)
4378 }
4379 other => is_pure_place(other),
4380 }
4381 }
4382 Expr::Lit(_) => true,
4383 Expr::Reference(r) => is_pure_place(&r.expr),
4384 Expr::Paren(p) => is_pure_place(&p.expr),
4385 Expr::Group(g) => is_pure_place(&g.expr),
4386 // Arithmetic on places is still side-effect free, so a bound like
4387 // `..want - 1` does not stop the binding being an alias.
4388 Expr::Binary(b) if !is_compound(&b.op) => {
4389 is_pure_place(&b.left) && is_pure_place(&b.right)
4390 }
4391 Expr::Unary(u) => is_pure_place(&u.expr),
4392 Expr::Cast(c) => is_pure_place(&c.expr),
4393 _ => false,
4394 }
4395}
4396
4397/// Whether an expression is a `&mut` borrow, directly or through parens.
4398fn is_mut_borrow(e: &Expr) -> bool {
4399 match e {
4400 Expr::Reference(r) => r.mutability.is_some(),
4401 Expr::Paren(p) => is_mut_borrow(&p.expr),
4402 Expr::Group(g) => is_mut_borrow(&g.expr),
4403 _ => false,
4404 }
4405}
4406
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago4407fn takes_self(sig: &syn::Signature) -> bool {
4408 matches!(sig.inputs.first(), Some(FnArg::Receiver(_)))
4409}
4410
4411fn path_name(p: &syn::Path) -> String {
4412 p.segments
4413 .last()
4414 .map(|s| s.ident.to_string())
4415 .unwrap_or_default()
4416}
4417
4418fn is_compound(op: &BinOp) -> bool {
4419 matches!(
4420 op,
4421 BinOp::AddAssign(_)
4422 | BinOp::SubAssign(_)
4423 | BinOp::MulAssign(_)
4424 | BinOp::DivAssign(_)
4425 | BinOp::RemAssign(_)
4426 | BinOp::BitAndAssign(_)
4427 | BinOp::BitOrAssign(_)
4428 | BinOp::BitXorAssign(_)
4429 | BinOp::ShlAssign(_)
4430 | BinOp::ShrAssign(_)
4431 )
4432}
4433
4434/// The Nim literal suffix for an integer type (`5'i32`).
4435fn nim_suffix(t: &Nim) -> Result<&'static str, String> {
4436 let Nim::Prim(p) = t else {
4437 return Err("not a primitive integer".into());
4438 };
4439 Ok(match p.as_str() {
4440 "int8" => "i8",
4441 "int16" => "i16",
4442 "int32" => "i32",
4443 "int64" => "i64",
4444 "int" => "i",
4445 "uint8" => "u8",
4446 "uint16" => "u16",
4447 "uint32" => "u32",
4448 "uint64" => "u64",
4449 "uint" => "u",
4450 other => return Err(format!("no Nim literal suffix for `{other}`")),
4451 })
4452}
4453
4454/// The unsigned integer type of the same width, used to spell `wrapping_*`.
4455fn unsigned_peer(t: &Nim) -> Result<&'static str, String> {
4456 let Nim::Prim(p) = t else {
4457 return Err("not a primitive integer".into());
4458 };
4459 Ok(match p.as_str() {
4460 "int8" => "uint8",
4461 "int16" => "uint16",
4462 "int32" => "uint32",
4463 "int64" => "uint64",
4464 "int" => "uint",
4465 other => return Err(format!("`{other}` has no unsigned peer")),
4466 })
4467}
4468
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago4469fn quote_meta(m: &syn::Meta) -> String {
4470 match m {
4471 syn::Meta::Path(p) => path_name(p),
4472 syn::Meta::List(l) => format!("{}(..)", path_name(&l.path)),
4473 syn::Meta::NameValue(nv) => format!("{} = ..", path_name(&nv.path)),
4474 }
4475}
4476
4477fn item_attrs(i: &Item) -> &[syn::Attribute] {
4478 match i {
4479 Item::Fn(f) => &f.attrs,
4480 Item::Struct(s) => &s.attrs,
4481 Item::Enum(e) => &e.attrs,
4482 Item::Impl(x) => &x.attrs,
4483 Item::Const(c) => &c.attrs,
4484 Item::Type(t) => &t.attrs,
4485 Item::Mod(m) => &m.attrs,
4486 Item::Use(u) => &u.attrs,
4487 Item::ExternCrate(e) => &e.attrs,
4488 Item::Static(s) => &s.attrs,
4489 _ => &[],
4490 }
4491}
4492
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago4493fn item_kind(i: &Item) -> &'static str {
4494 match i {
4495 Item::Trait(_) => "`trait`",
4496 Item::Static(_) => "`static`",
4497 Item::Macro(_) => "macro definition",
4498 Item::Union(_) => "`union`",
4499 Item::ForeignMod(_) => "`extern` block",
4500 _ => "item",
4501 }
4502}
4503
4504fn expr_kind(e: &Expr) -> &'static str {
4505 match e {
4506 Expr::Async(_) => "`async` block",
4507 Expr::Await(_) => "`.await`",
4508 Expr::Try(_) => "`?`",
4509 Expr::Range(_) => "range",
4510 Expr::Match(_) => "`match` (only statement position is implemented)",
4511 Expr::Let(_) => "`let` expression",
4512 Expr::Unsafe(_) => "`unsafe` block",
4513 Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => "loop (has no value in Nim)",
4514 _ => "expression",
4515 }
4516}