nandi/rustnimpublic Fork 0
d4592812fae6b652d94be442f5b3a408d3ab21b6
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 · 5641 lines · 239.6 KBRust Blame HistoryRaw
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h 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 10h 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 10h 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 9h 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 9h 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 9h 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 9h 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 9h 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 9h 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 9h 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 10h ago103 }
104}
105
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h 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 8h 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 9h ago117}
118
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h 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 9h 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 10h 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 9h 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 10h ago144 }
145 fn untyped(code: impl Into<String>) -> Self {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago146 Val::new(code, None)
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago147 }
148}
149
150struct Sig {
151 params: Vec<Nim>,
152 ret: Nim,
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago153 /// Type parameters this signature is generic in, so a call site can bind
154 /// them from its argument types.
155 generics: Vec<String>,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago156}
157
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago158/// One variant of a Rust enum.
159#[derive(Clone)]
160struct Variant {
161 name: String,
Lower the `log` facade, and add explicit enum discriminants 12c0a01 nandithebull 6h ago162 /// `Error = 1` — Nim enums take explicit ordinals too, so the value is
163 /// preserved rather than the variant being renumbered.
164 discriminant: Option<String>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago165 /// `(nim field name, type)`. Empty for a unit variant. Tuple variants get
166 /// `f0`, `f1`, ...; every field is prefixed with the variant name because
167 /// Nim requires the branches of a variant object to have distinct fields.
168 fields: Vec<(String, Nim)>,
169}
170
171#[derive(Clone)]
172struct EnumDef {
173 name: String,
174 /// True when every variant is a unit variant, which Nim represents as a
175 /// plain `enum` rather than an object variant.
176 simple: bool,
177 variants: Vec<Variant>,
178}
179
180impl EnumDef {
181 fn kind_ident(&self, v: &str) -> String {
182 format!("k{}{}", self.name, v)
183 }
184 fn ctor_ident(&self, v: &str) -> String {
185 format!("{}{}", self.name, v)
186 }
187 fn get(&self, v: &str) -> Option<&Variant> {
188 self.variants.iter().find(|x| x.name == v)
189 }
190}
191
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago192pub struct Lowerer {
193 out: String,
194 indent: usize,
195 scopes: Vec<HashMap<String, Nim>>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago196 /// Names introduced by a `for` pattern that stand for an lvalue or a
197 /// window into a container, rather than for a variable of their own.
198 alias_scopes: Vec<HashMap<String, Alias>>,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago199 /// `(module, name) -> signature`. Rust keeps `lower::decode` and
200 /// `mixed::decode` apart by module; flattening into one Nim module would
201 /// merge them, so the module is part of the key and of the emitted name.
202 fns: HashMap<(String, String), Sig>,
203 /// Module being lowered: the file stem, or empty for the crate root.
204 cur_mod: String,
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago205 /// The type of the `impl` block being lowered, which `Self` names.
206 self_ty: Option<Nim>,
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago207 /// Type parameters of the enclosing `impl`, which its methods share.
208 impl_generics: Vec<String>,
209 /// Type parameters of the proc being lowered, impl's included.
210 fn_generics: Vec<String>,
211 /// Type parameters declared by each generic struct or enum.
212 type_generics: HashMap<String, Vec<String>>,
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago213 /// `(type, name) -> type` for `type Item = ..;` inside an `impl`. Rust
214 /// writes those as `Self::Item`, which has to resolve before any
215 /// signature mentioning it is mapped.
216 assoc: HashMap<(String, String), Nim>,
217 /// `(type, name) -> (nim name, type)` for `const` items inside an `impl`.
218 assoc_consts: HashMap<(String, String), (String, Nim)>,
Lower `extern "C"` blocks to Nim importc; do not transpile libc 7db7991 nandithebull 6h ago219 /// Symbols declared by an `extern "C"` block.
220 foreign: std::collections::HashSet<String>,
221 /// Const-qualified C pointer aliases already declared.
222 const_ptrs: std::collections::HashSet<String>,
Expand `macro_rules!` rather than translating it to a Nim template 04eb29f nandithebull 6h ago223 /// `macro_rules!` definitions we can expand, and the reasons for those we
224 /// cannot, so a call site can say *why* rather than "unknown macro".
225 mrules: HashMap<String, crate::mrules::MacroDef>,
226 mrules_bad: HashMap<String, String>,
Expand multi-rule and recursive macro_rules d459281 nandithebull 5h ago227 macro_depth: usize,
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 7h ago228 /// Types declared by a `bitflags!` invocation.
229 bitflags: std::collections::HashSet<String>,
230 /// `(type, flag) -> nim const name`.
231 flag_consts: HashMap<(String, String), String>,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago232 /// `use` brings a name into scope from another module. Flattening loses
233 /// the module structure, so the mapping is recorded and consulted when a
234 /// bare call is resolved.
235 use_map: HashMap<String, String>,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago236 /// struct name -> (field, type)
237 structs: HashMap<String, Vec<(String, Nim)>>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago238 enums: HashMap<String, EnumDef>,
239 /// variant name -> enums declaring it. A variant named by more than one
240 /// enum must be written qualified, or it is rejected as ambiguous.
241 variant_owner: HashMap<String, Vec<String>>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago242 /// `(receiver type, method) -> signature`. Keyed by type because two
243 /// types may define the same method name, and Nim tells them apart by
244 /// overload resolution on the first parameter.
245 methods: HashMap<(String, String), Sig>,
246 /// The formatting traits implemented for each type, so `{}`/`{:?}`/`{:x}`
247 /// on a user type can be checked rather than assumed.
248 fmt_impls: HashMap<(String, String), ()>,
249 /// `(from, to)` conversions declared by `impl From<A> for B`.
250 from_impls: HashMap<(String, String), String>,
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago251 /// Operator traits implemented for a type, so `a += b` on a user type can
252 /// be dispatched to the impl rather than to Nim's built-in operator.
253 op_impls: HashMap<(String, String), ()>,
254 /// `(type, method) -> nim name`, for calls written as `Type::method(..)`.
255 statics: HashMap<(String, String), String>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago256 /// Forward declarations, emitted between the type definitions and the
257 /// bodies. Rust has no declaration-before-use rule and Nim does, so every
258 /// proc is declared up front rather than the input being reordered --
259 /// which would not work for mutual recursion anyway.
260 forwards: Vec<String>,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago261 /// Element type a `vec![..]` should build, from the binding's annotation.
262 vec_expect: Option<Nim>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago263 /// While lowering a formatting impl: the `Formatter` parameter's name.
264 /// Writes through it produce the proc's string result.
265 fmt_param: Option<String>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago266 /// `type X<T> = ...`, expanded before any type is mapped.
267 aliases: HashMap<String, (Vec<String>, syn::Type)>,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago268 /// Module names supplied as separate input files. A `mod x;` naming one
269 /// of these is satisfied by that file having been passed in.
270 pub modules: Vec<String>,
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 8h ago271 /// How many items were actually translated. If this is zero the input
272 /// produced nothing but the prelude, and reporting success for that is
273 /// the precise failure this project exists to avoid -- see `findings/`.
274 emitted: usize,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago275 /// Cargo features that are on, as `--cfg feature=<name>`. `#[cfg]` is
276 /// evaluated against these exactly as rustc would, so an item that is
277 /// dropped here is genuinely not part of the program being compiled.
278 pub features: Vec<String>,
279 dropped_by_cfg: usize,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago280 /// Return type of the proc being lowered, so `return e` and a trailing
281 /// expression can type their literals the way Rust's inference would.
282 ret: Option<Nim>,
283 /// `(name, type)` that the arms of the `if`/`match` being lowered as a
284 /// statement must assign their value to.
285 target: Option<(String, Option<Nim>)>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago286 /// Set while lowering a `while` condition, which Nim re-evaluates each
287 /// iteration and so cannot have statements hoisted out of it.
288 in_loop_cond: bool,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago289 tmp: usize,
290}
291
292impl Lowerer {
293 pub fn new() -> Self {
294 Lowerer {
295 out: String::new(),
296 indent: 0,
297 scopes: vec![HashMap::new()],
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago298 alias_scopes: vec![HashMap::new()],
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago299 fns: HashMap::new(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago300 cur_mod: String::new(),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago301 self_ty: None,
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago302 impl_generics: Vec::new(),
303 fn_generics: Vec::new(),
304 type_generics: HashMap::new(),
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago305 assoc: HashMap::new(),
306 assoc_consts: HashMap::new(),
Lower `extern "C"` blocks to Nim importc; do not transpile libc 7db7991 nandithebull 6h ago307 foreign: std::collections::HashSet::new(),
308 const_ptrs: std::collections::HashSet::new(),
Expand `macro_rules!` rather than translating it to a Nim template 04eb29f nandithebull 6h ago309 mrules: HashMap::new(),
310 mrules_bad: HashMap::new(),
Expand multi-rule and recursive macro_rules d459281 nandithebull 5h ago311 macro_depth: 0,
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 7h ago312 bitflags: std::collections::HashSet::new(),
313 flag_consts: HashMap::new(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago314 use_map: HashMap::new(),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago315 structs: HashMap::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago316 enums: HashMap::new(),
317 variant_owner: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago318 methods: HashMap::new(),
319 fmt_impls: HashMap::new(),
320 from_impls: HashMap::new(),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago321 op_impls: HashMap::new(),
322 statics: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago323 fmt_param: None,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago324 vec_expect: None,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago325 forwards: Vec::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago326 aliases: HashMap::new(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago327 modules: Vec::new(),
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 8h ago328 emitted: 0,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago329 features: Vec::new(),
330 dropped_by_cfg: 0,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago331 ret: None,
332 target: None,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago333 in_loop_cond: false,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago334 tmp: 0,
335 }
336 }
337
338 // ------------------------------------------------------------ emission
339
340 fn line(&mut self, s: &str) {
341 for _ in 0..self.indent {
342 self.out.push_str(" ");
343 }
344 self.out.push_str(s);
345 self.out.push('\n');
346 }
347
348 fn blank(&mut self) {
349 self.out.push('\n');
350 }
351
352 fn fresh(&mut self, hint: &str) -> String {
353 self.tmp += 1;
354 format!("rsTmp{}{}", hint, self.tmp)
355 }
356
357 // --------------------------------------------------------------- scope
358
359 fn push_scope(&mut self) {
360 self.scopes.push(HashMap::new());
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago361 self.alias_scopes.push(HashMap::new());
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago362 }
363 fn pop_scope(&mut self) {
364 self.scopes.pop();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago365 self.alias_scopes.pop();
366 }
367 fn bind_alias(&mut self, name: &str, a: Alias) {
368 self.alias_scopes
369 .last_mut()
370 .unwrap()
371 .insert(name.to_string(), a);
372 }
373 fn lookup_alias(&self, name: &str) -> Option<Alias> {
374 self.alias_scopes
375 .iter()
376 .rev()
377 .find_map(|s| s.get(name).cloned())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago378 }
379 fn bind(&mut self, name: &str, t: Nim) {
380 self.scopes.last_mut().unwrap().insert(name.to_string(), t);
381 }
382 fn lookup(&self, name: &str) -> Option<Nim> {
383 self.scopes.iter().rev().find_map(|s| s.get(name).cloned())
384 }
385
386 // ---------------------------------------------------------------- file
387
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago388 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 10h ago389 self.out.push_str(include_str!("prelude.nim"));
390 self.blank();
391
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago392 // Pass 0: type aliases. A signature in one file may use an alias
393 // declared in another, and inputs are given in whatever order suits
394 // 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 9h ago395 for (m, f) in files {
396 self.cur_mod = m.clone();
397 for item in &f.items {
398 self.collect_aliases(item)?;
399 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago400 }
401
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago402 // Pass 1: signatures and struct shapes, so that a call can be typed
403 // regardless of declaration order (Rust has no forward declarations).
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago404 for (m, f) in files {
405 self.cur_mod = m.clone();
406 for item in &f.items {
407 self.collect(item)?;
408 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago409 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago410 // Pass 2: type definitions, which every signature may mention.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago411 for (m, f) in files {
412 self.cur_mod = m.clone();
413 for item in &f.items {
414 self.item_types(item)?;
415 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago416 }
417
418 // Pass 3: forward declarations. Rust imposes no declaration order and
419 // Nim does, so everything is declared before any body is emitted;
420 // reordering the input would not handle mutual recursion anyway.
421 if !self.forwards.is_empty() {
422 for f in self.forwards.clone() {
423 self.line(&f);
424 }
425 self.blank();
426 }
427
428 // Pass 4: bodies.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago429 for (m, f) in files {
430 self.cur_mod = m.clone();
431 for item in &f.items {
432 self.item(item)?;
433 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago434 }
435
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 8h ago436 // An input that translates to nothing is a failure, however plausible
437 // the output file looks. The prelude alone is not a translation.
438 if self.emitted == 0 {
439 return Err(format!(
440 "nothing was translated: the input has no items this lowering \
441 emits{}. Writing a file containing only the prelude would \
442 report success for work that was not done",
443 if self.dropped_by_cfg > 0 {
444 format!(
445 " ({} item(s) were dropped by `#[cfg]`; enable them with \
446 `--cfg feature=<name>`)",
447 self.dropped_by_cfg
448 )
449 } else {
450 String::new()
451 }
452 ));
453 }
454
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago455 if self.fns.contains_key(&(String::new(), "main".to_string())) {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago456 self.blank();
457 self.line("when isMainModule:");
458 self.indent += 1;
459 self.line("try:");
460 self.line(" main()");
461 // Rust's panic exits 101 with a message on stderr. Nim's Defects
462 // exit 1. Mapping them here is what keeps the differential runner's
463 // exit-status comparison meaningful for panicking programs.
464 self.line("except RustPanic as e:");
465 self.line(" stderr.writeLine(\"thread 'main' panicked: \" & e.msg)");
466 self.line(" quit(101)");
467 self.line("except Defect as e:");
468 self.line(" stderr.writeLine(\"thread 'main' panicked: \" & e.msg)");
469 self.line(" quit(101)");
470 self.indent -= 1;
471 }
472 Ok(std::mem::take(&mut self.out))
473 }
474
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago475 fn collect_aliases(&mut self, item: &Item) -> Result<(), String> {
476 if !self.cfg_keeps(item_attrs(item))? {
477 return Ok(());
478 }
479 match item {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago480 Item::Use(u) => self.collect_use(&u.tree, &[]),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago481 Item::Type(t) => {
482 let params: Vec<String> = t
483 .generics
484 .params
485 .iter()
486 .filter_map(|g| match g {
487 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
488 _ => None,
489 })
490 .collect();
491 self.aliases
492 .insert(t.ident.to_string(), (params, (*t.ty).clone()));
493 }
494 Item::Mod(m) if m.content.is_some() => {
495 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
496 for i in &items {
497 self.collect_aliases(i)?;
498 }
499 }
500 _ => {}
501 }
502 Ok(())
503 }
504
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago505 /// Record what a `use` brings into scope, as `name -> module`.
506 fn collect_use(&mut self, t: &syn::UseTree, prefix: &[String]) {
507 use syn::UseTree;
508 match t {
509 UseTree::Path(p) => {
510 let mut pre = prefix.to_vec();
511 pre.push(p.ident.to_string());
512 self.collect_use(&p.tree, &pre);
513 }
514 UseTree::Group(g) => {
515 for t in &g.items {
516 self.collect_use(t, prefix);
517 }
518 }
519 UseTree::Name(n) => {
520 let m = module_of(prefix);
521 self.use_map.insert(n.ident.to_string(), m);
522 }
523 UseTree::Rename(r) => {
524 let m = module_of(prefix);
525 self.use_map.insert(r.rename.to_string(), m);
526 }
527 // A glob brings in an unknown set of names; resolution falls back
528 // to the current module and the root, as it would without it.
529 UseTree::Glob(_) => {}
530 }
531 }
532
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago533 fn collect(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago534 // A `#[cfg(..)]` item exists only under some feature set. Dropping it
535 // silently would change what the program does; picking a feature set
536 // on the user's behalf would be a guess. So it is reported, except on
537 // items that carry no runtime meaning here anyway.
538 if !self.cfg_keeps(item_attrs(item))? {
539 self.dropped_by_cfg += 1;
540 return Ok(());
541 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago542 match item {
543 Item::Fn(f) => {
544 let (params, ret) = self.signature(&f.sig)?;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago545 let gen_names = Self::generics_of(&f.sig.generics);
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago546 let name = f.sig.ident.to_string();
547 let nim = self.fn_name(&self.cur_mod, &name);
548 self.forwards.push(self.head_of(&nim, &f.sig, None)?);
549 self.fns
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago550 .insert((self.cur_mod.clone(), name), Sig { params, ret, generics: gen_names.clone() });
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago551 }
552 Item::Struct(s) => {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago553 if s.generics.params.iter().any(|p| matches!(p, syn::GenericParam::Const(_))) {
554 return Err(format!(
555 "`struct {}` has a const generic parameter, which Nim has \
556 no equivalent for",
557 s.ident
558 ));
559 }
560 let g = Self::generics_of(&s.generics);
561 // The parameters must be in scope while the field types are
562 // mapped, so that `T` resolves to itself rather than to an
563 // unknown named type.
564 self.type_generics.insert(s.ident.to_string(), g);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago565 let mut fields = Vec::new();
566 for (i, f) in s.fields.iter().enumerate() {
567 let name = match &f.ident {
568 Some(id) => id.to_string(),
569 None => format!("f{i}"), // tuple struct
570 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago571 // A field of `&[T]` / `&str` type is a borrow, and Nim's
572 // view types allow it as an object field, so it stays a
573 // view rather than being copied into a `seq`.
574 let t = self.map_ty(&f.ty)?;
575 let t = if returns_borrow(&f.ty) { t.unvar() } else { t.owned() };
576 fields.push((name, t));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago577 }
578 self.structs.insert(s.ident.to_string(), fields);
579 }
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 7h ago580 Item::Macro(m) if path_name(&m.mac.path) == "bitflags" => {
581 self.collect_bitflags(&m.mac)?;
582 }
Expand `macro_rules!` rather than translating it to a Nim template 04eb29f nandithebull 6h ago583 // A `macro_rules!` definition is recorded, not emitted: it is
584 // expanded at each call site, where the types its body needs are
585 // known. See `src/mrules.rs` for why that beats translating it
586 // into a Nim template.
587 Item::Macro(m) if path_name(&m.mac.path) == "macro_rules" => {
588 if let Some(name) = &m.ident {
589 match crate::mrules::parse(m.mac.tokens.clone()) {
590 Ok(def) => {
591 self.mrules.insert(name.to_string(), def);
592 }
593 Err(why) => {
594 // Recorded as unusable rather than silently absent:
595 // a call site gets this reason instead of "unknown
596 // macro".
597 self.mrules_bad.insert(name.to_string(), why);
598 }
599 }
600 }
601 }
Lower `extern "C"` blocks to Nim importc; do not transpile libc 7db7991 nandithebull 6h ago602 Item::ForeignMod(f) => {
603 for it in &f.items {
604 if let syn::ForeignItem::Fn(fi) = it {
605 let (params, ret) = self.signature(&fi.sig)?;
606 self.fns.insert(
607 (self.cur_mod.clone(), fi.sig.ident.to_string()),
608 Sig { params, ret, generics: Vec::new() },
609 );
610 }
611 }
612 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago613 Item::Mod(m) if m.content.is_some() => {
614 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
615 for i in &items {
616 self.collect(i)?;
617 }
618 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago619 Item::Type(t) => {
620 let params: Vec<String> = t
621 .generics
622 .params
623 .iter()
624 .filter_map(|g| match g {
625 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
626 _ => None,
627 })
628 .collect();
629 self.aliases
630 .insert(t.ident.to_string(), (params, (*t.ty).clone()));
631 }
632 Item::Enum(e) => {
633 let name = e.ident.to_string();
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago634 if e.generics.params.iter().any(|p| matches!(p, syn::GenericParam::Const(_))) {
635 return Err(format!(
636 "`enum {name}` has a const generic parameter, which Nim \
637 has no equivalent for"
638 ));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago639 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago640 self.type_generics
641 .insert(name.clone(), Self::generics_of(&e.generics));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago642 let mut variants = Vec::new();
643 for v in &e.variants {
644 let vname = v.ident.to_string();
Lower the `log` facade, and add explicit enum discriminants 12c0a01 nandithebull 6h ago645 let discriminant = match &v.discriminant {
646 Some((_, e)) => Some(self.expr(e)?.code),
647 None => None,
648 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago649 let mut fields = Vec::new();
650 for (i, f) in v.fields.iter().enumerate() {
651 // Nim requires the branches of a variant object to have
652 // distinct field names, so each is prefixed.
653 let fname = match &f.ident {
654 Some(id) => format!("{vname}_{id}"),
655 None => format!("{vname}_f{i}"),
656 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago657 let t = self.map_ty(&f.ty)?;
658 let t = if returns_borrow(&f.ty) { t.unvar() } else { t.owned() };
659 fields.push((fname, t));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago660 }
Lower the `log` facade, and add explicit enum discriminants 12c0a01 nandithebull 6h ago661 variants.push(Variant { name: vname, discriminant, fields });
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago662 }
663 let simple = variants.iter().all(|v| v.fields.is_empty());
664 for v in &variants {
665 self.variant_owner
666 .entry(v.name.clone())
667 .or_default()
668 .push(name.clone());
669 }
670 self.enums.insert(
671 name.clone(),
672 EnumDef { name, simple, variants },
673 );
674 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago675 Item::Impl(im) => {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago676 let outer_g =
677 std::mem::replace(&mut self.impl_generics, Self::generics_of(&im.generics));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago678 let self_ty = self.map_ty(&im.self_ty)?;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago679 let outer_self = self.self_ty.replace(self_ty.clone());
680 let r = self.collect_impl(im, &self_ty);
681 self.self_ty = outer_self;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago682 self.impl_generics = outer_g;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago683 return r;
684 }
685 _ => {}
686 }
687 Ok(())
688 }
689
690 fn collect_impl(&mut self, im: &syn::ItemImpl, self_ty: &Nim) -> Result<(), String> {
691 {
692 let self_ty = self_ty.clone();
693 let tyname = type_name(&self_ty);
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago694 // Associated types first: a signature in the same block may name
695 // one, and it has to resolve by the time that signature is mapped.
696 for it in &im.items {
697 if let syn::ImplItem::Type(t) = it {
698 let v = self.map_ty(&t.ty)?;
699 self.assoc.insert((tyname.clone(), t.ident.to_string()), v);
700 }
701 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago702 if let Some((path, _)) = &im.trait_ {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago703 let tr = path_name(path);
704 if im.items.is_empty() {
705 // A marker trait with no items. We do not model trait
706 // resolution at all, so it generates nothing; any use
707 // that actually needed the trait (a `dyn`, a bound) is
708 // rejected where it appears.
709 return Ok(());
710 }
711 if is_fmt_trait(&tr) {
712 self.forwards.push(format!(
713 "proc {}*(self: {}): string",
714 fmt_proc(&tr),
715 self_ty.render()
716 ));
717 self.fmt_impls.insert((tyname, tr), ());
718 return Ok(());
719 }
720 if tr == "From" {
721 let syn::ImplItem::Fn(m) = &im.items[0] else {
722 return Err("`impl From` must contain `fn from`".into());
723 };
724 let (params, _) = self.signature(&m.sig)?;
725 let src = params
726 .first()
727 .ok_or("`fn from` takes one argument")?
728 .clone();
729 let name = format!("rsFrom{}{}", tyname, type_name(&src));
730 self.forwards.push(self.head_of(&name, &m.sig, None)?);
731 self.from_impls
732 .insert((type_name(&src), tyname), name);
733 return Ok(());
734 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago735 // Any other trait: its methods are emitted as procs on
736 // the type, named after the trait so two traits declaring
737 // the same method name do not collide. The *trait* is not
738 // modelled -- no dynamic dispatch, no bounds -- and a use
739 // that needs it is rejected where it appears.
740 if let Some(op) = operator_trait(&tr) {
741 self.op_impls.insert((tyname.clone(), op.to_string()), ());
742 }
743 for it in &im.items {
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago744 // Already recorded above; a const is emitted with the
745 // bodies.
746 if matches!(it, syn::ImplItem::Type(_) | syn::ImplItem::Const(_)) {
747 continue;
748 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago749 let syn::ImplItem::Fn(m) = it else {
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago750 return Err(format!(
751 "unsupported item in `impl {tr}`: only `fn`, \
752 `type` and `const` are implemented"
753 ));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago754 };
755 let mname = m.sig.ident.to_string();
756 let (mut params, ret) = self.signature(&m.sig)?;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago757 let mut gen_names = self.impl_generics.clone();
758 gen_names.extend(Self::generics_of(&m.sig.generics));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago759 let recv = if takes_self(&m.sig) {
760 params.insert(0, self_ty.clone());
761 Some(self_ty.clone())
762 } else {
763 None
764 };
765 let nim = trait_method_name(&tyname, &tr, &mname);
766 self.forwards.push(self.head_of(&nim, &m.sig, recv.as_ref())?);
767 self.methods
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago768 .insert((tyname.clone(), mname.clone()), Sig { params, ret, generics: gen_names.clone() });
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago769 self.statics.insert((tyname.clone(), mname), nim);
770 }
771 return Ok(());
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago772 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago773 for it in &im.items {
774 if let syn::ImplItem::Fn(m) = it {
775 let (mut params, ret) = self.signature(&m.sig)?;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago776 let mut gen_names = self.impl_generics.clone();
777 gen_names.extend(Self::generics_of(&m.sig.generics));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago778 if takes_self(&m.sig) {
779 params.insert(0, self_ty.clone());
780 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago781 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 8h ago782 let nim = self.fn_name(&self.cur_mod, &m.sig.ident.to_string());
783 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 9h ago784 self.forwards.push(head);
785 self.methods
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago786 .insert((tyname.clone(), m.sig.ident.to_string()), Sig { params, ret, generics: gen_names.clone() });
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago787 self.statics
788 .insert((tyname.clone(), m.sig.ident.to_string()), nim);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago789 }
790 }
791 }
792 Ok(())
793 }
794
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago795 /// Whether `#[cfg(..)]` keeps this item, given the enabled features.
796 ///
797 /// This is evaluation, not approximation: rustc does the same thing, and
798 /// an item whose predicate is false is not part of the compiled program.
799 /// A predicate that cannot be evaluated is reported rather than assumed.
800 fn cfg_keeps(&self, attrs: &[syn::Attribute]) -> Result<bool, String> {
801 for a in attrs {
802 if a.path().is_ident("cfg") {
803 let pred: syn::Meta = a
804 .parse_args()
805 .map_err(|e| format!("cannot parse `#[cfg(..)]`: {e}"))?;
806 if !self.cfg_eval(&pred)? {
807 return Ok(false);
808 }
809 }
810 }
811 Ok(true)
812 }
813
814 fn cfg_eval(&self, m: &syn::Meta) -> Result<bool, String> {
815 match m {
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago816 // Bare flags whose value is determined by the profile this project
817 // models: a normal (non-`--test`) debug build, not a docs build.
818 // Anything platform-specific stays rejected, since we would be
819 // picking a target on the user's behalf.
820 syn::Meta::Path(p) if p.is_ident("test") => Ok(false),
821 syn::Meta::Path(p) if p.is_ident("debug_assertions") => Ok(true),
822 syn::Meta::Path(p) if p.is_ident("docsrs") || p.is_ident("doc") => Ok(false),
Evaluate host cfg predicates, and measure what that actually buys 0e6c394 nandithebull 8h ago823 syn::Meta::Path(p) if p.is_ident("doctest") || p.is_ident("miri") => Ok(false),
824 // Host facts. The generated Nim is compiled for this machine, so
825 // these are known rather than chosen. See DESIGN.md item 10: it
826 // does make the output host-shaped.
827 syn::Meta::Path(p) if p.is_ident("unix") => Ok(cfg!(unix)),
828 syn::Meta::Path(p) if p.is_ident("windows") => Ok(cfg!(windows)),
829 syn::Meta::NameValue(nv)
830 if nv.path.is_ident("target_os")
831 || nv.path.is_ident("target_arch")
832 || nv.path.is_ident("target_family")
833 || nv.path.is_ident("target_vendor") =>
834 {
835 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
836 return Err("this `cfg` key expects a string".into());
837 };
838 let key = nv.path.get_ident().map(|i| i.to_string()).unwrap_or_default();
839 Ok(s.value()
840 == match key.as_str() {
841 "target_os" => std::env::consts::OS,
842 "target_arch" => std::env::consts::ARCH,
843 "target_family" => std::env::consts::FAMILY,
844 _ => "unknown",
845 })
846 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago847 // The generated Nim is compiled for the same machine, so the
848 // target's word size and endianness are known rather than
849 // guessed. This does mean the output is host-shaped: a crate that
850 // branches on pointer width has had that branch decided here.
851 syn::Meta::NameValue(nv) if nv.path.is_ident("target_pointer_width") => {
852 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
853 return Err("`target_pointer_width = ..` expects a string".into());
854 };
855 Ok(s.value() == (usize::BITS).to_string())
856 }
Lower the `log` facade, and add explicit enum discriminants 12c0a01 nandithebull 6h ago857 // Every integer width and pointer-sized atomic exists on the
858 // targets Nim builds for here; like the other host facts this is
859 // read off the machine rather than chosen.
860 syn::Meta::NameValue(nv) if nv.path.is_ident("target_has_atomic") => {
861 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
862 return Err("`target_has_atomic = ..` expects a string".into());
863 };
864 Ok(matches!(
865 s.value().as_str(),
866 "8" | "16" | "32" | "64" | "ptr"
867 ))
868 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago869 syn::Meta::NameValue(nv) if nv.path.is_ident("target_endian") => {
870 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
871 return Err("`target_endian = ..` expects a string".into());
872 };
873 Ok(s.value() == if cfg!(target_endian = "big") { "big" } else { "little" })
874 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago875 syn::Meta::NameValue(nv) if nv.path.is_ident("feature") => {
876 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
877 return Err("`feature = ..` expects a string".into());
878 };
879 Ok(self.features.iter().any(|f| *f == s.value()))
880 }
881 syn::Meta::List(l) if l.path.is_ident("not") => {
882 let inner: syn::Meta = l.parse_args().map_err(|e| e.to_string())?;
883 Ok(!self.cfg_eval(&inner)?)
884 }
885 syn::Meta::List(l) if l.path.is_ident("all") || l.path.is_ident("any") => {
886 let items: syn::punctuated::Punctuated<syn::Meta, syn::Token![,]> = l
887 .parse_args_with(syn::punctuated::Punctuated::parse_terminated)
888 .map_err(|e| e.to_string())?;
889 let all = l.path.is_ident("all");
890 let mut acc = all;
891 for i in &items {
892 let v = self.cfg_eval(i)?;
893 acc = if all { acc && v } else { acc || v };
894 }
895 Ok(acc)
896 }
897 other => Err(format!(
Evaluate host cfg predicates, and measure what that actually buys 0e6c394 nandithebull 8h ago898 "`#[cfg({})]` is not a predicate rustnim can evaluate. \
899 Features (`--cfg feature=..`), host facts (`unix`, `windows`, \
900 `target_os`, `target_arch`, `target_family`, \
901 `target_pointer_width`, `target_endian`), `doc`/`doctest`/\
902 `miri`, and `not`/`all`/`any` over those are. A custom or \
903 build-script `cfg` has no value we could know",
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago904 quote_meta(other)
905 )),
906 }
907 }
908
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago909 /// 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 10h ago910 /// lowering goes through here rather than calling `ty::map` directly, so
911 /// an alias cannot be missed in one position and honoured in another.
912 fn map_ty(&self, t: &syn::Type) -> Result<Nim, String> {
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago913 // `Self::Item` names an associated type of the enclosing `impl`.
914 if let syn::Type::Path(p) = t {
915 let segs: Vec<String> =
916 p.path.segments.iter().map(|s| s.ident.to_string()).collect();
917 if segs.len() == 2 {
918 let owner = if segs[0] == "Self" {
919 self.self_ty.as_ref().map(type_name)
920 } else {
921 Some(segs[0].clone())
922 };
923 if let Some(o) = owner {
924 if let Some(a) = self.assoc.get(&(o, segs[1].clone())) {
925 return Ok(a.clone());
926 }
927 }
928 }
929 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago930 let n = ty::map(&self.expand(t, 0)?)?;
931 Ok(self.subst_self(n))
932 }
933
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago934 /// Substitute a generic type's parameters with the arguments the use site
935 /// supplies: a field of `Holder<T>` read through a `Holder<i32>` is `i32`.
936 fn subst_type_args(&self, name: &str, used_as: &Nim, field: Nim) -> Nim {
937 let Some(params) = self.type_generics.get(name) else { return field };
938 if params.is_empty() {
939 return field;
940 }
941 let Nim::Named(n, args) = used_as else { return field };
942 if n != name || args.len() != params.len() {
943 return field;
944 }
945 let map: HashMap<String, Nim> =
946 params.iter().cloned().zip(args.iter().cloned()).collect();
947 Self::subst(&field, &map)
948 }
949
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago950 /// `Self` inside an `impl` block names the type being implemented.
951 fn subst_self(&self, t: Nim) -> Nim {
952 let Some(me) = &self.self_ty else { return t };
953 match t {
954 Nim::Named(n, _) if n == "Self" => me.clone(),
955 Nim::Seq(e) => Nim::Seq(Box::new(self.subst_self(*e))),
956 Nim::OpenArray(e) => Nim::OpenArray(Box::new(self.subst_self(*e))),
957 Nim::Array(n, e) => Nim::Array(n, Box::new(self.subst_self(*e))),
958 Nim::Var(e) => Nim::Var(Box::new(self.subst_self(*e))),
959 Nim::Named(n, a) => {
960 Nim::Named(n, a.into_iter().map(|x| self.subst_self(x)).collect())
961 }
962 other => other,
963 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago964 }
965
966 fn expand(&self, t: &syn::Type, depth: usize) -> Result<syn::Type, String> {
967 if depth > 16 {
968 return Err("type alias expansion did not terminate; is it cyclic?".into());
969 }
970 let syn::Type::Path(p) = t else { return Ok(t.clone()) };
971 // Only an unqualified name can be one of this file's aliases.
972 // `fmt::Result` and `core::result::Result` are different types that
973 // merely end in the same segment.
974 if p.path.segments.len() != 1 {
975 return Ok(t.clone());
976 }
977 let Some(seg) = p.path.segments.last() else { return Ok(t.clone()) };
978 let Some((params, target)) = self.aliases.get(&seg.ident.to_string()) else {
979 return Ok(t.clone());
980 };
981 let args: Vec<syn::Type> = match &seg.arguments {
982 syn::PathArguments::AngleBracketed(a) => a
983 .args
984 .iter()
985 .filter_map(|g| match g {
986 GenericArgument::Type(t) => Some(t.clone()),
987 _ => None,
988 })
989 .collect(),
990 _ => vec![],
991 };
992 if args.len() != params.len() {
993 // Flattening several files into one module can bring a crate's own
994 // alias (`type Result<T> = Result<T, Error>`) into scope at a site
995 // that meant the builtin (`Result<T, E>`). Rust kept them apart by
996 // module; here they are told apart by arity, and a use that fits
997 // neither is left for `ty::map` to report.
998 return Ok(t.clone());
999 }
1000 self.expand(&substitute(target, params, &args), depth + 1)
1001 }
1002
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1003 /// The type parameters a generic item declares.
1004 ///
1005 /// Trait bounds and `where` clauses are dropped. Nim instantiates a
1006 /// generic structurally: an operation the bound would have permitted
1007 /// either exists for the instantiated type or is a compile error at the
1008 /// instantiation site. So dropping a bound cannot make an accepted
1009 /// program mean something different — it only makes rustnim accept some
1010 /// programs rustc would have rejected, which does not matter when the
1011 /// input is known-good Rust.
1012 fn generics_of(g: &syn::Generics) -> Vec<String> {
1013 g.params
1014 .iter()
1015 .filter_map(|p| match p {
1016 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
1017 _ => None,
1018 })
1019 .collect()
1020 }
1021
1022 /// Bind a signature's type parameters by matching its declared parameter
1023 /// types against the actual argument types, then substitute into `ret`.
1024 ///
1025 /// This is the small amount of inference a call site needs: Nim will
1026 /// resolve the instantiation itself, but the *binding* still has to be
1027 /// annotated with a concrete type, and `T` is not one.
1028 fn instantiate(sig: &Sig, args: &[Option<Nim>]) -> Nim {
1029 if sig.generics.is_empty() {
1030 return sig.ret.clone();
1031 }
1032 let mut bound: HashMap<String, Nim> = HashMap::new();
1033 for (decl, actual) in sig.params.iter().zip(args) {
1034 if let Some(a) = actual {
1035 Self::unify(decl, a, &sig.generics, &mut bound);
1036 }
1037 }
1038 Self::subst(&sig.ret, &bound)
1039 }
1040
1041 fn unify(decl: &Nim, actual: &Nim, params: &[String], out: &mut HashMap<String, Nim>) {
1042 match (decl, actual) {
1043 (Nim::Named(n, da), _) if params.iter().any(|p| p == n) && da.is_empty() => {
1044 out.entry(n.clone()).or_insert_with(|| actual.clone());
1045 }
1046 (Nim::Named(_, da), Nim::Named(_, aa)) if da.len() == aa.len() => {
1047 for (d, a) in da.iter().zip(aa) {
1048 Self::unify(d, a, params, out);
1049 }
1050 }
1051 (Nim::Seq(d), Nim::Seq(a))
1052 | (Nim::OpenArray(d), Nim::OpenArray(a))
1053 | (Nim::Seq(d), Nim::OpenArray(a))
1054 | (Nim::OpenArray(d), Nim::Seq(a))
1055 | (Nim::Var(d), Nim::Var(a))
1056 | (Nim::Array(_, d), Nim::Array(_, a)) => Self::unify(d, a, params, out),
1057 (Nim::Var(d), a) => Self::unify(d, a, params, out),
1058 (d, Nim::Var(a)) => Self::unify(d, a, params, out),
1059 (Nim::Tuple(d), Nim::Tuple(a)) if d.len() == a.len() => {
1060 for (d, a) in d.iter().zip(a) {
1061 Self::unify(d, a, params, out);
1062 }
1063 }
1064 _ => {}
1065 }
1066 }
1067
1068 fn subst(t: &Nim, m: &HashMap<String, Nim>) -> Nim {
1069 match t {
1070 Nim::Named(n, a) if a.is_empty() => m.get(n).cloned().unwrap_or_else(|| t.clone()),
1071 Nim::Named(n, a) => {
1072 Nim::Named(n.clone(), a.iter().map(|x| Self::subst(x, m)).collect())
1073 }
1074 Nim::Seq(e) => Nim::Seq(Box::new(Self::subst(e, m))),
1075 Nim::OpenArray(e) => Nim::OpenArray(Box::new(Self::subst(e, m))),
1076 Nim::Array(n, e) => Nim::Array(*n, Box::new(Self::subst(e, m))),
1077 Nim::Var(e) => Nim::Var(Box::new(Self::subst(e, m))),
1078 Nim::Tuple(ts) => Nim::Tuple(ts.iter().map(|x| Self::subst(x, m)).collect()),
1079 other => other.clone(),
1080 }
1081 }
1082
1083 /// Whether a type mentions a type parameter that is in scope here. Such a
1084 /// type cannot be used as a Nim annotation at an instantiation site: Nim
1085 /// infers it, and writing `T` would name something that is not bound.
1086 fn mentions_type_param(&self, t: &Nim) -> bool {
1087 match t {
1088 Nim::Named(n, a) => {
1089 self.fn_generics.iter().any(|g| g == n)
1090 || a.iter().any(|x| self.mentions_type_param(x))
1091 }
1092 Nim::Seq(e) | Nim::OpenArray(e) | Nim::Var(e) | Nim::Array(_, e) => {
1093 self.mentions_type_param(e)
1094 }
1095 Nim::Tuple(ts) => ts.iter().any(|x| self.mentions_type_param(x)),
1096 Nim::Proc(a, r) => {
1097 a.iter().any(|x| self.mentions_type_param(x)) || self.mentions_type_param(r)
1098 }
1099 _ => false,
1100 }
1101 }
1102
Lower the `log` facade, and add explicit enum discriminants 12c0a01 nandithebull 6h ago1103 /// The Nim name of a `log::Level` written as a path.
1104 fn log_level_of(&mut self, e: &Expr) -> Result<String, String> {
1105 let Expr::Path(p) = e else {
1106 return Err("a log level must be written as `Level::Info`".into());
1107 };
1108 let last = path_name(&p.path);
1109 Ok(match last.as_str() {
1110 "Error" => "rsLvlError",
1111 "Warn" => "rsLvlWarn",
1112 "Info" => "rsLvlInfo",
1113 "Debug" => "rsLvlDebug",
1114 "Trace" => "rsLvlTrace",
1115 other => return Err(format!("`Level::{other}` is not a log level")),
1116 }
1117 .to_string())
1118 }
1119
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1120 /// `[T, U]`, or empty.
1121 fn gen_list(params: &[String]) -> String {
1122 if params.is_empty() {
1123 String::new()
1124 } else {
1125 format!("[{}]", params.join(", "))
1126 }
1127 }
1128
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago1129 /// The Nim name for a function, qualified by its module.
1130 fn fn_name(&self, module: &str, name: &str) -> String {
1131 if module.is_empty() {
1132 ident(name)
1133 } else {
1134 format!("{}_{}", module, ident(name))
1135 }
1136 }
1137
1138 /// Resolve a call path to the module and name it refers to: an explicit
1139 /// `mixed::decode`, then the current module, then the crate root.
1140 fn resolve_fn(&self, path: &syn::Path) -> Option<(String, String)> {
1141 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
1142 let last = segs.last()?.clone();
1143 if segs.len() >= 2 {
1144 let q = &segs[segs.len() - 2];
1145 if self.fns.contains_key(&(q.clone(), last.clone())) {
1146 return Some((q.clone(), last));
1147 }
1148 }
1149 let imported = self.use_map.get(&last).cloned();
1150 for m in [Some(self.cur_mod.clone()), imported, Some(String::new())]
1151 .into_iter()
1152 .flatten()
1153 {
1154 if self.fns.contains_key(&(m.clone(), last.clone())) {
1155 return Some((m, last));
1156 }
1157 }
1158 None
1159 }
1160
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago1161 /// The Nim `proc` head for a Rust signature, used both for the forward
1162 /// declaration and for the definition, so the two cannot drift apart.
1163 fn head_of(
1164 &self,
1165 name: &str,
1166 sig: &syn::Signature,
1167 recv: Option<&Nim>,
1168 ) -> Result<String, String> {
1169 let (ptys, ret) = self.signature(sig)?;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1170 // A method inside `impl<T> Foo<T>` is generic in the impl's
1171 // parameters as well as its own.
1172 let mut params = self.impl_generics.clone();
1173 for g in Self::generics_of(&sig.generics) {
1174 if !params.contains(&g) {
1175 params.push(g);
1176 }
1177 }
1178 let gens = Self::gen_list(&params);
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago1179 let mut parts = Vec::new();
1180 if let Some(self_ty) = recv {
1181 let mutable = matches!(
1182 sig.inputs.first(),
1183 Some(FnArg::Receiver(r))
1184 if matches!(&r.kind, syn::ReceiverKind::Reference(_, _, m) if m.is_some())
1185 );
1186 let t = if mutable { Nim::Var(Box::new(self_ty.clone())) } else { self_ty.clone() };
1187 parts.push(format!("self: {}", t.render()));
1188 }
1189 let typed: Vec<&syn::PatType> = sig
1190 .inputs
1191 .iter()
1192 .filter_map(|a| match a {
1193 FnArg::Typed(t) => Some(t),
1194 _ => None,
1195 })
1196 .collect();
1197 for (i, (p, t)) in typed.iter().zip(ptys.iter()).enumerate() {
1198 let pname = match &*p.pat {
1199 Pat::Ident(id) => id.ident.to_string(),
1200 Pat::Wild(_) => format!("unused{}", parts.len()),
1201 _ => return Err("only plain identifier parameters are supported".into()),
1202 };
1203 let _ = i;
1204 parts.push(format!("{}: {}", ident(&pname), t.render()));
1205 }
1206 Ok(if ret == Nim::Unit {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1207 format!("proc {}*{}({})", ident(name), gens, parts.join(", "))
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago1208 } else {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1209 format!(
1210 "proc {}*{}({}): {}",
1211 ident(name),
1212 gens,
1213 parts.join(", "),
1214 ret.render()
1215 )
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago1216 })
1217 }
1218
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1219 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 9h ago1220 // `unsafe fn` marks a contract for callers; it does not change what
1221 // the body means, so it lowers like any other proc.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1222 if sig.asyncness.is_some() {
1223 return Err(format!("`async fn {}`: Nim has no equivalent", sig.ident));
1224 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1225 // Lifetime parameters carry no runtime meaning and Nim is GC'd, so
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1226 // they disappear. Type parameters become Nim generic parameters.
1227 // Const parameters have no Nim equivalent and are still rejected.
1228 if sig.generics.params.iter().any(|p| matches!(p, syn::GenericParam::Const(_))) {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1229 return Err(format!(
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1230 "`fn {}` has a const generic parameter, which Nim has no \
1231 equivalent for",
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1232 sig.ident
1233 ));
1234 }
1235 let mut params = Vec::new();
1236 for a in &sig.inputs {
1237 if let FnArg::Typed(t) = a {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1238 params.push(self.map_ty(&t.ty)?);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1239 }
1240 }
1241 let ret = match &sig.output {
1242 ReturnType::Default => Nim::Unit,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago1243 // A returned `&[T]` is a borrow of the caller's buffer, so it
1244 // stays an `openArray` view. Only an owned type (`Vec<T>`) becomes
1245 // a `seq`, which `owned()` would do to both.
1246 ReturnType::Type(_, t) => {
1247 let n = self.map_ty(t)?;
1248 if returns_borrow(t) { n } else { n.owned() }
1249 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1250 };
1251 Ok((params, ret))
1252 }
1253
1254 // --------------------------------------------------------------- items
1255
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago1256 /// Emit the type definitions only: they must precede every signature.
1257 fn item_types(&mut self, item: &Item) -> Result<(), String> {
1258 if !self.cfg_keeps(item_attrs(item))? {
1259 return Ok(());
1260 }
1261 match item {
1262 Item::Struct(_) | Item::Enum(_) | Item::Const(_) => self.item_inner(item),
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 7h ago1263 Item::Macro(m) if path_name(&m.mac.path) == "bitflags" => self.item_inner(item),
Lower `extern "C"` blocks to Nim importc; do not transpile libc 7db7991 nandithebull 6h ago1264 Item::ForeignMod(_) => self.item_inner(item),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago1265 Item::Mod(m) if m.content.is_some() => {
1266 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
1267 for i in &items {
1268 self.item_types(i)?;
1269 }
1270 Ok(())
1271 }
1272 _ => Ok(()),
1273 }
1274 }
1275
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1276 fn item(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1277 if !self.cfg_keeps(item_attrs(item))? {
1278 return Ok(());
1279 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago1280 // Types were emitted in their own pass.
1281 if matches!(item, Item::Struct(_) | Item::Enum(_) | Item::Const(_)) {
1282 return Ok(());
1283 }
Lower `extern "C"` blocks to Nim importc; do not transpile libc 7db7991 nandithebull 6h ago1284 if matches!(item, Item::Macro(m) if path_name(&m.mac.path) == "bitflags")
1285 || matches!(item, Item::ForeignMod(_))
1286 {
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 7h ago1287 return Ok(()); // emitted with the types
1288 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago1289 self.item_inner(item)
1290 }
1291
1292 fn item_inner(&mut self, item: &Item) -> Result<(), String> {
Fail when nothing was translated, not just when the file is empty 0777223 nandithebull 8h ago1293 if !matches!(item, Item::Use(_) | Item::ExternCrate(_) | Item::Mod(_) | Item::Type(_)) {
1294 self.emitted += 1;
1295 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1296 match item {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago1297 Item::Fn(f) => {
1298 let nim = self.fn_name(&self.cur_mod, &f.sig.ident.to_string());
1299 self.func_named(&nim, &f.sig, &f.block, None)
1300 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1301 Item::Struct(s) => {
1302 let name = s.ident.to_string();
1303 let fields = self.structs[&name].clone();
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1304 let g = Self::gen_list(self.type_generics.get(&name).map(|v| &v[..]).unwrap_or(&[]));
1305 self.line(&format!("type {}*{} = object", ident(&name), g));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1306 self.indent += 1;
1307 if fields.is_empty() {
1308 self.line("discard");
1309 }
1310 for (fname, fty) in &fields {
1311 self.line(&format!("{}*: {}", ident(fname), fty.render()));
1312 }
1313 self.indent -= 1;
1314 self.blank();
1315 Ok(())
1316 }
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 7h ago1317 Item::Macro(m) if path_name(&m.mac.path) == "bitflags" => self.emit_bitflags(&m.mac),
Expand `macro_rules!` rather than translating it to a Nim template 04eb29f nandithebull 6h ago1318 Item::Macro(m) if path_name(&m.mac.path) == "macro_rules" => Ok(()),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1319 Item::Type(_) => Ok(()), // expanded at every use site
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago1320 Item::Trait(t) => {
1321 // We do not model trait resolution, so a declaration generates
1322 // nothing and a use that needed it is rejected where it
1323 // appears. A *default body*, though, is code: dropping it
1324 // would silently remove a method the impls inherit.
1325 for it in &t.items {
1326 if let syn::TraitItem::Fn(f) = it {
1327 if f.default.is_some() {
1328 return Err(format!(
1329 "`trait {}` gives `{}` a default body; trait \
1330 resolution is not modelled, so that body has no \
1331 impl to be emitted into and dropping it would \
1332 remove code",
1333 t.ident, f.sig.ident
1334 ));
1335 }
1336 }
1337 }
1338 Ok(())
1339 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1340 Item::Enum(e) => {
1341 let def = self.enums[&e.ident.to_string()].clone();
1342 self.emit_enum(&def);
1343 Ok(())
1344 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1345 Item::Const(c) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1346 let t = self.map_ty(&c.ty)?.owned();
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago1347 // The annotation types the initialiser, exactly as it does for
1348 // a `let`: `const MOD: u32 = 65521` is a u32 literal.
1349 let v = self.expr_at(&c.expr, Some(&t))?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1350 self.bind(&c.ident.to_string(), t.clone());
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago1351 // Only a top-level const is exported; `*` on a local is not
1352 // Nim syntax.
1353 let star = if self.indent == 0 { "*" } else { "" };
1354 let line = format!(
1355 "const {}{}: {} = {}",
1356 ident(&c.ident.to_string()),
1357 star,
1358 t.render(),
1359 v.code
1360 );
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1361 self.line(&line);
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago1362 if self.indent == 0 {
1363 self.blank();
1364 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1365 Ok(())
1366 }
1367 Item::Impl(im) => {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1368 let outer_g =
1369 std::mem::replace(&mut self.impl_generics, Self::generics_of(&im.generics));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1370 let self_ty = self.map_ty(&im.self_ty)?;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago1371 let outer = self.self_ty.replace(self_ty.clone());
1372 let r = self.impl_body(im, &self_ty);
1373 self.self_ty = outer;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1374 self.impl_generics = outer_g;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago1375 r
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1376 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1377 // `use` and `extern crate` are resolution directives with no Nim
1378 // analogue once everything is one module.
1379 Item::Use(_) | Item::ExternCrate(_) => Ok(()),
Lower `extern "C"` blocks to Nim importc; do not transpile libc 7db7991 nandithebull 6h ago1380 Item::ForeignMod(f) => self.foreign_mod(f),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1381 Item::Mod(m) if m.content.is_some() => {
1382 // An inline `mod` is flattened; Nim has no nested modules in a
1383 // single file.
1384 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
1385 for i in &items {
1386 self.item(i)?;
1387 }
1388 Ok(())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1389 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago1390 Item::Mod(m) => {
1391 // Satisfied if that file was passed in too; everything is one
1392 // Nim module, so the declaration itself emits nothing.
1393 if self.modules.iter().any(|x| *x == m.ident.to_string()) {
1394 return Ok(());
1395 }
1396 Err(format!(
1397 "`mod {};` refers to another file that was not passed to \
1398 rustnim; add it to the input list",
1399 m.ident
1400 ))
1401 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago1402 other => Err(format!("unsupported item: {}", item_kind(other))),
1403 }
1404 }
1405
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1406 /// `None` carries no type of its own, so Nim needs the `Option[T]` named.
1407 fn none_of(&self, expect: Option<&Nim>) -> String {
1408 match expect {
1409 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => {
1410 format!("rsNone[{}]()", a[0].render())
1411 }
1412 _ => "rsNone()".to_string(),
1413 }
1414 }
1415
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago1416 fn impl_body(&mut self, im: &syn::ItemImpl, self_ty: &Nim) -> Result<(), String> {
1417 if let Some((path, _)) = &im.trait_ {
1418 let tr = path_name(path);
1419 if im.items.is_empty() {
1420 return Ok(());
1421 }
1422 if is_fmt_trait(&tr) {
1423 let syn::ImplItem::Fn(m) = &im.items[0] else {
1424 return Err(format!("unsupported item in `impl {tr}`"));
1425 };
1426 return self.fmt_impl(&tr, self_ty, &m.sig, &m.block);
1427 }
1428 if tr == "From" {
1429 let syn::ImplItem::Fn(m) = &im.items[0] else {
1430 return Err("`impl From` must contain `fn from`".into());
1431 };
1432 let name = {
1433 let (params, _) = self.signature(&m.sig)?;
1434 let src = params.first().cloned().ok_or("`fn from` takes one argument")?;
1435 self.from_impls[&(type_name(&src), type_name(self_ty))].clone()
1436 };
1437 return self.func_named(&name, &m.sig, &m.block, None);
1438 }
1439 let tyname = type_name(self_ty);
1440 for it in &im.items {
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago1441 if let syn::ImplItem::Const(c) = it {
1442 self.assoc_const(&tyname, c)?;
1443 continue;
1444 }
1445 if matches!(it, syn::ImplItem::Type(_)) {
1446 continue; // a type binding emits nothing
1447 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago1448 let syn::ImplItem::Fn(m) = it else {
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago1449 return Err(format!(
1450 "unsupported item in `impl {tr}`: only `fn`, `type` and \
1451 `const` are implemented"
1452 ));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago1453 };
1454 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
1455 let nim = trait_method_name(&tyname, &tr, &m.sig.ident.to_string());
1456 self.func_named(&nim, &m.sig, &m.block, recv)?;
1457 }
1458 return Ok(());
1459 }
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago1460 let tyname = type_name(self_ty);
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago1461 for it in &im.items {
1462 match it {
1463 syn::ImplItem::Fn(m) => {
1464 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
1465 let nim = self.fn_name(&self.cur_mod, &m.sig.ident.to_string());
1466 self.func_named(&nim, &m.sig, &m.block, recv)?;
1467 }
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago1468 syn::ImplItem::Type(_) => {}
1469 syn::ImplItem::Const(c) => self.assoc_const(&tyname, c)?,
1470 _ => {
1471 return Err("only `fn`, `type` and `const` items are supported \
1472 inside `impl`"
1473 .into())
1474 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago1475 }
1476 }
1477 Ok(())
1478 }
1479
Lower `extern "C"` blocks to Nim importc; do not transpile libc 7db7991 nandithebull 6h ago1480 /// An `extern "C" { .. }` block: declarations of symbols someone else
1481 /// defines. Nim's `importc` is the same statement, and both are bound by
1482 /// the C ABI, so the two declarations describe one symbol rather than one
1483 /// being a translation of the other.
1484 fn foreign_mod(&mut self, f: &syn::ItemForeignMod) -> Result<(), String> {
1485 let abi = f
1486 .abi
1487 .name
1488 .as_ref()
1489 .map(|s| s.value())
1490 .unwrap_or_else(|| "C".into());
1491 if abi != "C" {
1492 return Err(format!(
1493 "`extern \"{abi}\"` is not the C ABI; only that one has a Nim \
1494 equivalent"
1495 ));
1496 }
1497 // A const-qualified C pointer needs a type whose C spelling carries
1498 // the `const`; Nim has no such type built in, so one is declared per
1499 // element type actually used.
1500 let mut needed: Vec<Nim> = Vec::new();
1501 for it in &f.items {
1502 if let syn::ForeignItem::Fn(fi) = it {
1503 let (params, ret) = self.signature(&fi.sig)?;
1504 for t in params.iter().chain(std::iter::once(&ret)) {
1505 if let Nim::ConstPtr(inner) = t {
1506 if !matches!(&**inner, Nim::Prim(p) if p == "void")
1507 && !needed.contains(t)
1508 {
1509 needed.push(t.clone());
1510 }
1511 }
1512 }
1513 }
1514 }
1515 for t in &needed {
1516 let Nim::ConstPtr(inner) = t else { continue };
1517 let alias = ty::const_ptr_alias(inner);
1518 if !self.const_ptrs.insert(alias.clone()) {
1519 continue;
1520 }
1521 let c = ty::c_spelling(inner).ok_or_else(|| {
1522 format!(
1523 "`*const {}` has no C spelling we know, so a const-qualified \
1524 declaration cannot be emitted for it",
1525 inner.render()
1526 )
1527 })?;
1528 self.line(&format!(
1529 "type {}* {{.importc: \"const {} *\", nodecl.}} = distinct pointer",
1530 alias, c
1531 ));
1532 }
1533
1534 for it in &f.items {
1535 match it {
1536 syn::ForeignItem::Fn(fi) => {
1537 if fi.sig.variadic.is_some() {
1538 return Err(format!(
1539 "`{}` is variadic; Nim needs `varargs` with a fixed \
1540 calling shape, which this does not give us",
1541 fi.sig.ident
1542 ));
1543 }
1544 let name = fi.sig.ident.to_string();
1545 let head = self.head_of(&name, &fi.sig, None)?;
1546 // `importc` names the C symbol, so the Nim name may differ
1547 // from it without changing what is linked.
1548 self.line(&format!(
1549 "{} {{.importc: \"{}\", cdecl.}}",
1550 head, name
1551 ));
1552 let (params, ret) = self.signature(&fi.sig)?;
1553 self.fns.insert(
1554 (self.cur_mod.clone(), name.clone()),
1555 Sig { params, ret, generics: Vec::new() },
1556 );
1557 self.foreign.insert(name);
1558 }
1559 syn::ForeignItem::Static(st) => {
1560 let t = self.map_ty(&st.ty)?;
1561 let name = st.ident.to_string();
1562 self.line(&format!(
1563 "var {}* {{.importc: \"{}\".}}: {}",
1564 ident(&name),
1565 name,
1566 t.render()
1567 ));
1568 self.bind(&name, t);
1569 }
1570 syn::ForeignItem::Type(_) => {
1571 // An opaque C type: Nim spells it as a distinct object.
1572 continue;
1573 }
1574 _ => return Err("unsupported item in an `extern` block".into()),
1575 }
1576 }
1577 self.blank();
1578 Ok(())
1579 }
1580
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago1581 /// `const N: usize = 4;` inside an `impl`. Nim has no per-type constant
1582 /// namespace, so it becomes a module-level const named for both.
1583 fn assoc_const(&mut self, tyname: &str, c: &syn::ImplItemConst) -> Result<(), String> {
1584 let t = self.map_ty(&c.ty)?.owned();
1585 let v = self.expr_at(&c.expr, Some(&t))?;
1586 let name = format!("{}_{}", tyname, c.ident);
1587 self.line(&format!("const {}*: {} = {}", ident(&name), t.render(), v.code));
1588 self.blank();
1589 self.assoc_consts
1590 .insert((tyname.to_string(), c.ident.to_string()), (ident(&name), t));
1591 Ok(())
1592 }
1593
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago1594 /// The type an operator impl declares for its right-hand operand.
1595 fn op_param(&self, t: &Option<Nim>, op: &str) -> Option<Nim> {
1596 let n = type_name(t.as_ref()?);
1597 let sig = self.methods.get(&(n, op_method(op).to_string()))?;
1598 sig.params.get(1).cloned().map(|t| t.unvar())
1599 }
1600
1601 /// The proc implementing `op` for a user type, if there is one.
1602 fn op_proc(&self, t: &Option<Nim>, op: &str) -> Option<String> {
1603 let n = type_name(t.as_ref()?);
1604 let tr = OPERATOR_TRAITS.iter().find(|(_, o)| *o == op)?.0;
1605 if self.op_impls.contains_key(&(n.clone(), op.to_string())) {
1606 Some(trait_method_name(&n, tr, OP_METHOD.iter().find(|(o, _)| *o == op)?.1))
1607 } else {
1608 None
1609 }
1610 }
1611
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 7h ago1612 /// Register a `bitflags!` type's operations so call sites resolve.
1613 fn collect_bitflags(&mut self, mac: &syn::Macro) -> Result<(), String> {
1614 let input: crate::macros::BitflagsInput = mac
1615 .parse_body()
1616 .map_err(|e| format!("`bitflags!`: {e}"))?;
1617 for def in &input.0 {
1618 let name = def.name.to_string();
1619 let repr = self.map_ty(&def.repr)?;
1620 if !repr.is_integer() {
1621 return Err(format!("`bitflags! {name}` needs an integer representation"));
1622 }
1623 let me = Nim::Named(name.clone(), vec![]);
1624 let b = Nim::Prim("bool".into());
1625 self.structs
1626 .insert(name.clone(), vec![("bitsField".into(), repr.clone())]);
1627 self.type_generics.insert(name.clone(), Vec::new());
1628
1629 let mut m = |n: &str, params: Vec<Nim>, ret: Nim, nim: String| {
1630 self.methods.insert(
1631 (name.clone(), n.to_string()),
1632 Sig { params, ret, generics: Vec::new() },
1633 );
1634 self.statics.insert((name.clone(), n.to_string()), nim);
1635 };
1636 let s1 = vec![me.clone()];
1637 let s2 = vec![me.clone(), me.clone()];
1638 let vs2 = vec![Nim::Var(Box::new(me.clone())), me.clone()];
1639 m("bits", s1.clone(), repr.clone(), format!("{name}_bits"));
1640 m("is_empty", s1.clone(), b.clone(), format!("{name}_is_empty"));
1641 m("is_all", s1.clone(), b.clone(), format!("{name}_is_all"));
1642 m("contains", s2.clone(), b.clone(), format!("{name}_contains"));
1643 m("intersects", s2.clone(), b.clone(), format!("{name}_intersects"));
1644 for (rust, nim) in [
1645 ("union", "union"),
1646 ("intersection", "intersection"),
1647 ("difference", "difference"),
1648 ("symmetric_difference", "symmetric_difference"),
1649 ] {
1650 m(rust, s2.clone(), me.clone(), format!("{name}_{nim}"));
1651 }
1652 for n in ["insert", "remove", "toggle"] {
1653 m(n, vs2.clone(), Nim::Unit, format!("{name}_{n}"));
1654 }
1655 m(
1656 "set",
1657 vec![Nim::Var(Box::new(me.clone())), me.clone(), b.clone()],
1658 Nim::Unit,
1659 format!("{name}_set"),
1660 );
1661 m("empty", vec![], me.clone(), format!("{name}_empty"));
1662 m("all", vec![], me.clone(), format!("{name}_all"));
1663 m(
1664 "from_bits",
1665 vec![repr.clone()],
1666 Nim::Named("Option".into(), vec![me.clone()]),
1667 format!("{name}_from_bits"),
1668 );
1669 m(
1670 "from_bits_truncate",
1671 vec![repr.clone()],
1672 me.clone(),
1673 format!("{name}_from_bits_truncate"),
1674 );
1675 m("complement", s1.clone(), me.clone(), format!("{name}_complement"));
1676
1677 // The operator forms, routed through the same dispatch that a
1678 // hand-written `impl BitOr` would use.
1679 for (op, trait_name, method) in [
1680 ("|", "BitOr", "bitor"),
1681 ("&", "BitAnd", "bitand"),
1682 ("^", "BitXor", "bitxor"),
1683 ("-", "Sub", "sub"),
1684 ("not", "Not", "not"),
1685 ] {
1686 self.op_impls.insert((name.clone(), op.to_string()), ());
1687 let params = if op == "not" { s1.clone() } else { s2.clone() };
1688 self.methods.insert(
1689 (name.clone(), method.to_string()),
1690 Sig { params, ret: me.clone(), generics: Vec::new() },
1691 );
1692 let _ = trait_name;
1693 }
1694 self.bitflags.insert(name);
1695 }
1696 Ok(())
1697 }
1698
1699 /// Emit the Nim for a `bitflags!` type. See `src/macros.rs` for why this
1700 /// is lowered directly rather than by expanding the macro.
1701 fn emit_bitflags(&mut self, mac: &syn::Macro) -> Result<(), String> {
1702 let input: crate::macros::BitflagsInput = mac
1703 .parse_body()
1704 .map_err(|e| format!("`bitflags!`: {e}"))?;
1705 for def in &input.0 {
1706 let name = def.name.to_string();
1707 let repr = self.map_ty(&def.repr)?;
1708 let r = repr.render();
1709
1710 self.line(&format!("type {name}* = object"));
1711 self.line(&format!(" bitsField*: {r}"));
1712 self.blank();
1713 self.line(&format!("proc {name}_bits*(x: {name}): {r} = x.bitsField"));
1714
1715 // The constants. A flag's value may name earlier flags, as
1716 // `const ALL = Self::READ.bits() | ..` does, so they are emitted
1717 // in order and each is in scope for the next.
1718 self.push_scope();
1719 self.bind_static_type(&name, &repr);
1720 for (fname, value) in &def.flags {
1721 let v = self.expr_at(value, Some(&repr))?;
1722 self.line(&format!(
1723 "const {}{}* = {}(bitsField: {})",
1724 name, fname, name, v.code
1725 ));
1726 self.flag_consts
1727 .insert((name.clone(), fname.to_string()), format!("{name}{fname}"));
1728 }
1729 self.pop_scope();
1730
1731 let all: Vec<String> = def
1732 .flags
1733 .iter()
1734 .map(|(f, _)| format!("{name}{f}.bitsField"))
1735 .collect();
1736 let all_bits = if all.is_empty() {
1737 format!("{}(0)", r)
1738 } else {
1739 all.join(" or ")
1740 };
1741 self.blank();
1742 self.line(&format!("const {name}AllBits: {r} = {all_bits}"));
1743 self.blank();
1744
1745 for l in [
1746 format!("proc {name}_empty*(): {name} = {name}(bitsField: {r}(0))"),
1747 format!("proc {name}_all*(): {name} = {name}(bitsField: {name}AllBits)"),
1748 format!("proc {name}_is_empty*(x: {name}): bool = x.bitsField == {r}(0)"),
1749 format!("proc {name}_is_all*(x: {name}): bool = (x.bitsField and {name}AllBits) == {name}AllBits"),
1750 format!("proc {name}_contains*(a, b: {name}): bool = (a.bitsField and b.bitsField) == b.bitsField"),
1751 format!("proc {name}_intersects*(a, b: {name}): bool = (a.bitsField and b.bitsField) != {r}(0)"),
1752 format!("proc {name}_union*(a, b: {name}): {name} = {name}(bitsField: a.bitsField or b.bitsField)"),
1753 format!("proc {name}_intersection*(a, b: {name}): {name} = {name}(bitsField: a.bitsField and b.bitsField)"),
1754 format!("proc {name}_difference*(a, b: {name}): {name} = {name}(bitsField: a.bitsField and (not b.bitsField))"),
1755 format!("proc {name}_symmetric_difference*(a, b: {name}): {name} = {name}(bitsField: a.bitsField xor b.bitsField)"),
1756 // `!x` complements and then masks to `all()`, which is what
1757 // bitflags does and not what a plain `not` would give.
1758 format!("proc {name}_complement*(x: {name}): {name} = {name}(bitsField: (not x.bitsField) and {name}AllBits)"),
1759 format!("proc {name}_from_bits_truncate*(b: {r}): {name} = {name}(bitsField: b and {name}AllBits)"),
1760 format!("proc {name}_from_bits*(b: {r}): Option[{name}] ="),
1761 format!(" if (b and (not {name}AllBits)) != {r}(0): rsNone[{name}]() else: rsSome({name}(bitsField: b))"),
1762 format!("proc {name}_insert*(x: var {name}, o: {name}) = x.bitsField = x.bitsField or o.bitsField"),
1763 format!("proc {name}_remove*(x: var {name}, o: {name}) = x.bitsField = x.bitsField and (not o.bitsField)"),
1764 format!("proc {name}_toggle*(x: var {name}, o: {name}) = x.bitsField = x.bitsField xor o.bitsField"),
1765 format!("proc {name}_set*(x: var {name}, o: {name}, on: bool) ="),
1766 format!(" if on: {name}_insert(x, o) else: {name}_remove(x, o)"),
1767 format!("proc rsBitOr_{name}_bitor*(a, b: {name}): {name} = {name}_union(a, b)"),
1768 format!("proc rsBitAnd_{name}_bitand*(a, b: {name}): {name} = {name}_intersection(a, b)"),
1769 format!("proc rsBitXor_{name}_bitxor*(a, b: {name}): {name} = {name}_symmetric_difference(a, b)"),
1770 format!("proc rsSub_{name}_sub*(a, b: {name}): {name} = {name}_difference(a, b)"),
1771 format!("proc rsNot_{name}_not*(a: {name}): {name} = {name}_complement(a)"),
1772 ] {
1773 self.line(&l);
1774 }
1775
1776 // Debug prints the set flag names, or `0x0` when empty -- again
1777 // matching the crate rather than a guess.
1778 self.line(&format!("proc rsDebug*(x: {name}): string ="));
1779 self.line(&format!(" result = \"{name}(\""));
1780 self.line(" var first = true");
1781 for (fname, _) in &def.flags {
1782 self.line(&format!(
1783 " if (x.bitsField and {name}{f}.bitsField) == {name}{f}.bitsField and {name}{f}.bitsField != {r}(0):",
1784 f = fname
1785 ));
1786 self.line(" if not first: result.add(\" | \")");
1787 self.line(&format!(" result.add(\"{fname}\")"));
1788 self.line(" first = false");
1789 }
1790 self.line(" if first: result.add(\"0x0\")");
1791 self.line(" result.add(\")\")");
1792 self.blank();
1793 }
1794 Ok(())
1795 }
1796
1797 fn bind_static_type(&mut self, _name: &str, _repr: &Nim) {}
1798
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1799 fn emit_enum(&mut self, def: &EnumDef) {
1800 let name = ident(&def.name);
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1801 let g = Self::gen_list(
1802 self.type_generics.get(&def.name).map(|v| &v[..]).unwrap_or(&[]),
1803 );
1804 if def.simple && !g.is_empty() {
1805 // A Nim `enum` cannot take parameters; an all-unit generic enum
1806 // has no payload to be generic in anyway, so this would be a
1807 // parameter that never appears.
1808 // Fall through to the object-variant form instead.
1809 }
1810 if def.simple && g.is_empty() {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1811 // Every variant is a unit variant, so a plain Nim enum is an exact
1812 // fit: it compares, orders and `case`-checks like Rust's.
1813 self.line(&format!("type {name}* = enum"));
1814 self.indent += 1;
1815 for v in &def.variants {
Lower the `log` facade, and add explicit enum discriminants 12c0a01 nandithebull 6h ago1816 match &v.discriminant {
1817 Some(d) => self.line(&format!("{} = {}", ident(&v.name), d)),
1818 None => self.line(&ident(&v.name)),
1819 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1820 }
1821 self.indent -= 1;
1822 self.blank();
1823 self.line(&format!("proc rsDebug*(x: {name}): string ="));
1824 self.indent += 1;
1825 self.line("case x");
1826 for v in &def.variants {
1827 self.line(&format!("of {}.{}: \"{}\"", name, ident(&v.name), v.name));
1828 }
1829 self.indent -= 1;
1830 self.blank();
1831 return;
1832 }
1833
1834 // A data-carrying enum is a Nim object variant: one discriminant enum
1835 // plus a branch per variant. This is the same shape the prelude uses
1836 // for `Option` and `Result`.
1837 self.line("type");
1838 self.indent += 1;
1839 self.line(&format!("{}Kind* = enum", name));
1840 self.indent += 1;
1841 for v in &def.variants {
1842 self.line(&def.kind_ident(&v.name));
1843 }
1844 self.indent -= 1;
1845 self.blank();
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1846 self.line(&format!("{}*{} = object", name, g));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1847 self.indent += 1;
1848 self.line(&format!("case kind*: {}Kind", name));
1849 for v in &def.variants {
1850 if v.fields.is_empty() {
1851 self.line(&format!("of {}: discard", def.kind_ident(&v.name)));
1852 } else {
1853 self.line(&format!("of {}:", def.kind_ident(&v.name)));
1854 self.indent += 1;
1855 for (f, t) in &v.fields {
1856 self.line(&format!("{}*: {}", ident(f), t.render()));
1857 }
1858 self.indent -= 1;
1859 }
1860 }
1861 self.indent -= 2;
1862 self.blank();
1863
1864 for v in &def.variants {
1865 let args: Vec<String> = v
1866 .fields
1867 .iter()
1868 .enumerate()
1869 .map(|(i, (_, t))| format!("a{}: {}", i, t.render()))
1870 .collect();
1871 let inits: Vec<String> = v
1872 .fields
1873 .iter()
1874 .enumerate()
1875 .map(|(i, (f, _))| format!("{}: a{}", ident(f), i))
1876 .collect();
1877 let mut all = vec![format!("kind: {}", def.kind_ident(&v.name))];
1878 all.extend(inits);
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1879 let ret = format!("{}{}", name, g);
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1880 self.line(&format!(
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1881 "proc {}*{}({}): {} = {}({})",
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1882 def.ctor_ident(&v.name),
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1883 g,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1884 args.join(", "),
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1885 ret,
1886 ret,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1887 all.join(", ")
1888 ));
1889 }
1890 self.blank();
1891
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1892 self.line(&format!("proc rsDebug*{}(x: {}{}): string =", g, name, g));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1893 self.indent += 1;
1894 self.line("case x.kind");
1895 for v in &def.variants {
1896 if v.fields.is_empty() {
1897 self.line(&format!("of {}: \"{}\"", def.kind_ident(&v.name), v.name));
1898 } else {
1899 let parts: Vec<String> = v
1900 .fields
1901 .iter()
1902 .map(|(f, _)| format!("rsDebug(x.{})", ident(f)))
1903 .collect();
1904 self.line(&format!(
1905 "of {}: \"{}(\" & {} & \")\"",
1906 def.kind_ident(&v.name),
1907 v.name,
1908 parts.join(" & \", \" & ")
1909 ));
1910 }
1911 }
1912 self.indent -= 1;
1913 self.blank();
1914 }
1915
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago1916 /// The concrete type an enum variant constructs, and the `[T]` list to
1917 /// spell at the constructor when the enum is generic.
1918 fn variant_type(
1919 &self,
1920 def: &EnumDef,
1921 expect: Option<&Nim>,
1922 ) -> Result<(Nim, String), String> {
1923 let params = self.type_generics.get(&def.name).cloned().unwrap_or_default();
1924 if params.is_empty() {
1925 return Ok((Nim::Named(def.name.clone(), vec![]), String::new()));
1926 }
1927 match expect {
1928 Some(Nim::Named(n, a)) if *n == def.name && a.len() == params.len() => Ok((
1929 Nim::Named(def.name.clone(), a.clone()),
1930 format!("[{}]", a.iter().map(|t| t.render()).collect::<Vec<_>>().join(", ")),
1931 )),
1932 _ => Err(format!(
1933 "`{}` is a variant of a generic enum, and its type parameters \
1934 cannot be inferred here; annotate the binding or the return type",
1935 def.name
1936 )),
1937 }
1938 }
1939
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago1940 /// Resolve a Rust path like `Error::InvalidLength` or a bare `InvalidLength`
1941 /// to the enum that declares it.
1942 fn resolve_variant(&self, path: &syn::Path) -> Option<(EnumDef, String)> {
1943 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
1944 let last = segs.last()?.clone();
1945 if segs.len() >= 2 {
1946 if let Some(def) = self.enums.get(&segs[segs.len() - 2]) {
1947 if def.get(&last).is_some() {
1948 return Some((def.clone(), last));
1949 }
1950 }
1951 }
1952 // Unqualified: only unambiguous if exactly one enum declares it.
1953 match self.variant_owner.get(&last) {
1954 Some(owners) if owners.len() == 1 => {
1955 let def = self.enums.get(&owners[0])?;
1956 Some((def.clone(), last))
1957 }
1958 _ => None,
1959 }
1960 }
1961
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago1962 /// Lower `impl Display for T`'s `fn fmt` into a proc returning a string.
1963 ///
1964 /// Rust's `Formatter` is a sink that a `fmt` method writes into; the
1965 /// observable result of `{}` is exactly the bytes written. So the method
1966 /// becomes `proc rsDisplay(self: T): string` and every write through the
1967 /// formatter produces that string. A `fmt` body that does anything else
1968 /// with the formatter -- padding, precision, `debug_struct` -- is rejected,
1969 /// because those affect the output and this model does not carry them.
1970 /// The window an expression names, if it names one.
1971 fn window_of(&self, e: &Expr) -> Option<Alias> {
1972 match e {
1973 Expr::Path(p) => match self.lookup_alias(&path_name(&p.path)) {
1974 Some(a @ Alias::Window { .. }) => Some(a),
1975 _ => None,
1976 },
1977 Expr::Reference(r) => self.window_of(&r.expr),
1978 Expr::Paren(p) => self.window_of(&p.expr),
1979 Expr::Unary(u) if matches!(u.op, UnOp::Deref(_)) => self.window_of(&u.expr),
1980 _ => None,
1981 }
1982 }
1983
1984 /// Whether an expression is the `Formatter` parameter of the formatting
1985 /// impl currently being lowered.
1986 fn is_fmt_param(&self, e: &Expr) -> bool {
1987 let Some(f) = &self.fmt_param else { return false };
1988 match e {
1989 Expr::Path(p) => path_name(&p.path) == *f,
1990 Expr::Reference(r) => self.is_fmt_param(&r.expr),
1991 Expr::Paren(p) => self.is_fmt_param(&p.expr),
1992 _ => false,
1993 }
1994 }
1995
1996 fn fmt_impl(
1997 &mut self,
1998 tr: &str,
1999 self_ty: &Nim,
2000 sig: &syn::Signature,
2001 body: &syn::Block,
2002 ) -> Result<(), String> {
2003 let proc_name = fmt_proc(tr);
2004 // The formatter is the parameter after `self`.
2005 let f = sig
2006 .inputs
2007 .iter()
2008 .filter_map(|a| match a {
2009 FnArg::Typed(t) => match &*t.pat {
2010 Pat::Ident(i) => Some(i.ident.to_string()),
2011 _ => None,
2012 },
2013 _ => None,
2014 })
2015 .next()
2016 .ok_or("`fn fmt` needs a `Formatter` parameter")?;
2017
2018 self.push_scope();
2019 self.bind("self", self_ty.clone());
2020 let saved = self.fmt_param.replace(f);
2021 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 9h ago2022 // No assignment target: a formatter write *appends*, because a `fmt`
2023 // body may write repeatedly -- `UpperHex` writes once per byte in a
2024 // loop -- and assigning would keep only the last one.
2025 let outer_target = self.target.take();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2026
2027 self.line(&format!(
2028 "proc {}*(self: {}): string =",
2029 proc_name,
2030 self_ty.render()
2031 ));
2032 self.indent += 1;
2033 let before = self.out.len();
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago2034 let tail = self.block_body(body)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2035 self.emit_tail(tail);
2036 if self.out.len() == before {
2037 self.line("discard");
2038 }
2039 self.indent -= 1;
2040
2041 self.target = outer_target;
2042 self.ret = outer_ret;
2043 self.fmt_param = saved;
2044 self.pop_scope();
2045 self.blank();
2046 Ok(())
2047 }
2048
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2049 fn func(
2050 &mut self,
2051 sig: &syn::Signature,
2052 body: &syn::Block,
2053 recv: Option<Nim>,
2054 ) -> Result<(), String> {
2055 let name = sig.ident.to_string();
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2056 self.func_named(&name.clone(), sig, body, recv)
2057 }
2058
2059 fn func_named(
2060 &mut self,
2061 name: &str,
2062 sig: &syn::Signature,
2063 body: &syn::Block,
2064 recv: Option<Nim>,
2065 ) -> Result<(), String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2066 let (ptys, ret) = self.signature(sig)?;
2067
2068 self.push_scope();
2069 let mut rendered: Vec<String> = Vec::new();
2070
2071 if let Some(self_ty) = recv {
2072 // `&mut self` and `mut self` both mean the body may mutate the
2073 // receiver; only the former is observable by the caller, and a Nim
2074 // `var` parameter is the faithful spelling of that.
2075 let mutable = matches!(
2076 sig.inputs.first(),
2077 Some(FnArg::Receiver(r))
2078 if matches!(&r.kind, syn::ReceiverKind::Reference(_, _, m) if m.is_some())
2079 );
2080 let t = if mutable { Nim::Var(Box::new(self_ty.clone())) } else { self_ty.clone() };
2081 rendered.push(format!("self: {}", t.render()));
2082 self.bind("self", self_ty);
2083 }
2084
2085 let typed: Vec<&syn::PatType> = sig
2086 .inputs
2087 .iter()
2088 .filter_map(|a| match a {
2089 FnArg::Typed(t) => Some(t),
2090 _ => None,
2091 })
2092 .collect();
2093 for (p, t) in typed.iter().zip(ptys.iter()) {
2094 let pname = match &*p.pat {
2095 Pat::Ident(i) => i.ident.to_string(),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2096 // `fn from(_: Error) -> ..` — the parameter is unused, but Nim
2097 // still needs a name for it.
2098 Pat::Wild(_) => format!("unused{}", rendered.len()),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2099 _ => return Err("only plain identifier parameters are supported".into()),
2100 };
2101 rendered.push(format!("{}: {}", ident(&pname), t.render()));
2102 // Inside the body a `var T` parameter is used exactly like a `T`.
2103 self.bind(&pname, t.clone().owned());
2104 }
2105
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago2106 let mut gparams = self.impl_generics.clone();
2107 for g in Self::generics_of(&sig.generics) {
2108 if !gparams.contains(&g) {
2109 gparams.push(g);
2110 }
2111 }
2112 let gens = Self::gen_list(&gparams);
2113 let outer_fg = std::mem::replace(&mut self.fn_generics, gparams.clone());
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2114 let head = if ret == Nim::Unit {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago2115 format!("proc {}*{}({}) =", ident(name), gens, rendered.join(", "))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2116 } else {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago2117 format!(
2118 "proc {}*{}({}): {} =",
2119 ident(name),
2120 gens,
2121 rendered.join(", "),
2122 ret.render()
2123 )
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2124 };
2125 self.line(&head);
2126 self.indent += 1;
2127 let outer_ret = self.ret.replace(ret.clone());
2128
2129 // A Rust fn's trailing expression is its return value. Naming Nim's
2130 // implicit `result` as the target makes that true whether the tail is
2131 // a plain expression or an `if`/`match` with statement arms.
2132 let outer_target = if ret == Nim::Unit {
2133 self.target.take()
2134 } else {
2135 self.target.replace(("result".to_string(), Some(ret.clone())))
2136 };
2137 let before = self.out.len();
2138 let tail = self.block_body_at(body, Some(&ret))?;
2139 self.target = outer_target;
2140 match tail {
2141 Some(v) if ret != Nim::Unit => {
2142 let code = v.code.clone();
2143 self.line(&format!("result = {code}"));
2144 }
2145 Some(v) => {
2146 // A trailing expression in a `()`-returning fn is evaluated for
2147 // its effect; Nim requires an explicit discard.
2148 let needs_discard = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
2149 if needs_discard && !v.code.is_empty() {
2150 let code = v.code.clone();
2151 self.line(&format!("discard {code}"));
2152 }
2153 }
2154 None => {}
2155 }
2156 if self.out.len() == before {
2157 self.line("discard");
2158 }
2159
2160 self.indent -= 1;
2161 self.ret = outer_ret;
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago2162 self.fn_generics = outer_fg;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2163 self.pop_scope();
2164 self.blank();
2165 Ok(())
2166 }
2167
2168 // ---------------------------------------------------------- statements
2169
2170 /// Lower a block's statements. Returns the block's trailing expression,
2171 /// if it has one, *without* emitting it — the caller decides whether that
2172 /// value is a return value, a binding, or discarded.
2173 fn block_body(&mut self, b: &syn::Block) -> Result<Option<Val>, String> {
2174 self.block_body_at(b, None)
2175 }
2176
2177 fn block_body_at(
2178 &mut self,
2179 b: &syn::Block,
2180 expect: Option<&Nim>,
2181 ) -> Result<Option<Val>, String> {
2182 // An assignment target belongs to *this* block's trailing expression
2183 // only. A non-final `if` is a statement and must not assign anything.
2184 let target = self.target.take();
2185 let n = b.stmts.len();
2186 let mut tail = None;
2187 for (i, st) in b.stmts.iter().enumerate() {
2188 let last = i + 1 == n;
2189 match st {
2190 Stmt::Expr(e, None) if last && expressible(e) => {
2191 tail = Some(self.expr_at(e, expect)?)
2192 }
2193 Stmt::Expr(e, None) if last => {
2194 // A trailing `if`/`match` with statement arms, or a loop.
2195 // Lower it as statements; if this block's value is wanted,
2196 // each arm assigns it.
2197 match &target {
2198 Some((t, ty)) => {
2199 let (t, ty) = (t.clone(), ty.clone());
2200 self.assign_from(e, &t, ty.as_ref())?;
2201 }
2202 None => self.stmt(st)?,
2203 }
2204 }
2205 _ => self.stmt(st)?,
2206 }
2207 }
2208 self.target = target;
2209 Ok(tail)
2210 }
2211
2212 /// Lower a block in statement position (loop bodies, `if` arms).
2213 fn nested_block(&mut self, b: &syn::Block) -> Result<(), String> {
2214 self.push_scope();
2215 self.indent += 1;
2216 let before = self.out.len();
2217 let want = self.target.clone().and_then(|(_, t)| t);
2218 let tail = self.block_body_at(b, want.as_ref())?;
2219 self.emit_tail(tail);
2220 if self.out.len() == before {
2221 self.line("discard");
2222 }
2223 self.indent -= 1;
2224 self.pop_scope();
2225 Ok(())
2226 }
2227
2228 fn stmt(&mut self, s: &Stmt) -> Result<(), String> {
2229 match s {
2230 Stmt::Local(l) => self.local(l),
2231 Stmt::Expr(e, _) => {
2232 let v = self.expr_stmt(e)?;
2233 if let Some(v) = v {
2234 // A bare expression with a value must be discarded in Nim.
2235 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
2236 let code = v.code.clone();
2237 if needs {
2238 self.line(&format!("discard {code}"));
2239 } else if !code.is_empty() {
2240 self.line(&code);
2241 }
2242 }
2243 Ok(())
2244 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago2245 // A `const` declared inside a function body is local to it, and
2246 // must be emitted here rather than skipped as an already-emitted
2247 // top-level type.
2248 Stmt::Item(i) => self.item_inner(i),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2249 Stmt::Macro(m) => {
2250 let line = self.macro_call(&m.mac)?;
2251 self.line(&line);
2252 Ok(())
2253 }
2254 }
2255 }
2256
2257 fn local(&mut self, l: &Local) -> Result<(), String> {
2258 let (name, mutable, ann): (String, bool, Option<Nim>) = match &l.pat {
2259 Pat::Ident(i) => (i.ident.to_string(), i.mutability.is_some(), None),
2260 Pat::Type(t) => match &*t.pat {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago2261 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 10h ago2262 _ => return Err("only `let <ident>` bindings are supported".into()),
2263 },
2264 Pat::Wild(_) => ("_".into(), false, None),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago2265 Pat::Tuple(t) => return self.local_tuple(l, t),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2266 _ => return Err("destructuring `let` is not implemented yet".into()),
2267 };
2268
2269 let Some(init) = &l.init else {
2270 // `let x: T;` — Nim's `var x: T` zero-initialises, which Rust does
2271 // not. Rust's own rules make reading it before assignment illegal,
2272 // so the two agree on every program rustc accepts.
2273 let t = ann.ok_or("`let` without an initialiser needs a type annotation")?;
2274 let t = t.owned();
2275 self.line(&format!("var {}: {}", ident(&name), t.render()));
2276 self.bind(&name, t);
2277 return Ok(());
2278 };
2279 if init.diverge.is_some() {
2280 return Err("`let ... else` is not implemented yet".into());
2281 }
2282
2283 if !expressible(&init.expr) && name != "_" {
2284 // The initialiser is an `if`/`match` whose arms are statements.
2285 // Declare first, then let each arm assign into the binding.
2286 let t = ann
2287 .clone()
2288 .ok_or_else(|| {
2289 format!(
2290 "`let {name} = match/if ...` needs a type annotation: \
2291 its arms are statements, so the binding must be \
2292 declared before they run"
2293 )
2294 })?
2295 .owned();
2296 self.line(&format!("var {}: {}", ident(&name), t.render()));
2297 self.bind(&name, t.clone());
2298 let target = ident(&name);
2299 return self.assign_from(&init.expr, &target, Some(&t));
2300 }
2301
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago2302 // `let it = xs.chunks_exact(k)` binds an iterator, not a value.
2303 if is_iterator_expr(&init.expr) {
2304 let it = self.resolve_iter(&init.expr)?;
2305 self.bind_alias(&name, Alias::Iterator(Box::new(it)));
2306 return Ok(());
2307 }
2308
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2309 let v = self.expr_at(&init.expr, ann.as_ref())?;
Prove byte-identity for base16ct by enumerating whole input domains 99b8376 nandithebull 8h ago2310
2311 // `let s = &buf[..n]` binds a view of a place that is already in
2312 // scope. Nim's borrow checker will not let a `let` borrow out of a
2313 // local, and there is nothing to materialise anyway -- a view is a
2314 // reference. Binding it as an alias substitutes the same expression at
2315 // each use, which re-evaluates nothing because the initialiser is a
2316 // place expression with no side effects.
2317 if v.window.is_none()
2318 && matches!(v.ty, Some(Nim::OpenArray(_)))
2319 && is_pure_place(&init.expr)
2320 {
2321 let t = v.ty.clone().unwrap();
2322 let elem = match &t {
2323 Nim::OpenArray(e) => Some((**e).clone()),
2324 _ => None,
2325 };
2326 self.bind_alias(&name, Alias::Value { code: v.code.clone(), ty: Some(t) });
2327 let _ = elem;
2328 return Ok(());
2329 }
2330
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2331 if let Some(w) = v.window.clone() {
2332 // `let dst = dst.get_mut(..n).ok_or(..)?;` -- the binding names a
2333 // view into the caller's buffer. Copying it into a `seq` would
2334 // still print the right bytes but would stop writes reaching the
2335 // caller, so it is bound as an alias.
2336 if v.guard.is_some() && v.guard_err.is_some() {
2337 return Err(format!(
2338 "`let {name} = ...get(..)` keeps an `Option` of a slice view, \
2339 which Nim cannot represent; apply `?` or `unwrap()` to it \
2340 in the same expression"
2341 ));
2342 }
2343 self.bind_alias(&name, w);
2344 return Ok(());
2345 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago2346 // A `let` binding a borrow keeps the view: `let res = encode(..)?`
2347 // names the caller's buffer, and copying it into a `seq` would still
2348 // print the right bytes while silently breaking the aliasing.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2349 let t = match (ann, &v.ty) {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago2350 (Some(a), _) => a.unvar(),
2351 (None, Some(t)) => t.clone().unvar(),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2352 (None, None) => {
2353 return Err(format!(
2354 "cannot infer the type of `let {name}`; annotate it — \
2355 guessing here would change integer width, and with it the \
2356 meaning of any arithmetic on `{name}`"
2357 ))
2358 }
2359 };
2360
2361 if name == "_" {
2362 let code = v.code.clone();
2363 self.line(&format!("discard {code}"));
2364 return Ok(());
2365 }
2366 // Rust's immutable `let` is Nim's `let`; `let mut` is `var`. Shadowing
2367 // 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 8h ago2368 //
2369 // `let x = &mut y[..n]` is an immutable binding of a *mutable* borrow:
2370 // Rust may write through it, and Nim only accepts a `var` where a
2371 // `var` parameter is wanted, so the binding has to be one.
2372 let mutable = mutable || is_mut_borrow(&init.expr);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2373 let kw = if mutable { "var" } else { "let" };
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago2374 // Inside a generic proc the binding's type may mention a parameter Nim
2375 // will infer; naming it in an annotation would not resolve.
2376 let line = if self.mentions_type_param(&t) {
2377 format!("{} {} = {}", kw, ident(&name), v.code)
2378 } else {
2379 format!("{} {}: {} = {}", kw, ident(&name), t.render(), v.code)
2380 };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2381 self.line(&line);
2382 self.bind(&name, t);
2383 Ok(())
2384 }
2385
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago2386 /// `let (a, b) = ..` — tuple destructuring.
2387 fn local_tuple(&mut self, l: &Local, t: &syn::PatTuple) -> Result<(), String> {
2388 let Some(init) = &l.init else {
2389 return Err("a destructuring `let` needs an initialiser".into());
2390 };
2391 let names: Vec<(String, bool)> = t
2392 .elems
2393 .iter()
2394 .map(|p| match p {
2395 Pat::Ident(i) => Ok((i.ident.to_string(), i.mutability.is_some())),
2396 Pat::Wild(_) => Ok(("_".to_string(), false)),
2397 _ => Err("only plain identifiers are supported in a destructuring `let`"),
2398 })
2399 .collect::<Result<_, _>>()?;
2400
2401 // `split_at` hands back two *views* of the same slice. Nim has no
2402 // tuple of views, and there is nothing to materialise anyway, so each
2403 // name becomes a window into the original.
2404 if let Expr::MethodCall(m) = &*init.expr {
2405 let mname = m.method.to_string();
2406 if (mname == "split_at" || mname == "split_at_mut")
2407 && m.args.len() == 1
2408 && names.len() == 2
2409 {
2410 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
2411 let at = self.expr(&m.args[0])?;
2412 let cut = self.fresh("Cut");
2413 self.line(&format!("let {}: int = int({})", cut, at.code));
2414 self.bind_alias(
2415 &names[0].0,
2416 Alias::Window {
2417 code: code.clone(),
2418 off: base.clone(),
2419 len: cut.clone(),
2420 elem: elem.clone(),
2421 },
2422 );
2423 self.bind_alias(
2424 &names[1].0,
2425 Alias::Window {
2426 code,
2427 off: format!("({} + {})", base, cut),
2428 len: format!("({} - {})", len, cut),
2429 elem,
2430 },
2431 );
2432 return Ok(());
2433 }
2434 }
2435
2436 let v = self.expr(&init.expr)?;
2437 let tys = match &v.ty {
2438 Some(Nim::Tuple(ts)) if ts.len() == names.len() => ts.clone(),
2439 _ => {
2440 return Err(format!(
2441 "cannot destructure this into {} bindings: its type is not a \
2442 tuple of that many elements",
2443 names.len()
2444 ))
2445 }
2446 };
2447 let kw = if names.iter().any(|(_, m)| *m) { "var" } else { "let" };
2448 let lhs: Vec<String> = names.iter().map(|(n, _)| ident(n)).collect();
2449 self.line(&format!("{} ({}) = {}", kw, lhs.join(", "), v.code));
2450 for ((n, _), t) in names.iter().zip(tys) {
2451 self.bind(n, t);
2452 }
2453 Ok(())
2454 }
2455
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2456 /// Expressions that are statements in Rust and statements in Nim too
2457 /// (control flow). Returns `None` when it emitted lines itself.
2458 fn expr_stmt(&mut self, e: &Expr) -> Result<Option<Val>, String> {
2459 match e {
2460 Expr::If(_) => {
2461 self.if_stmt(e)?;
2462 Ok(None)
2463 }
2464 Expr::While(w) => {
2465 if w.label.is_some() {
2466 return Err("loop labels are not implemented yet".into());
2467 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago2468 self.in_loop_cond = true;
2469 let c = self.expr(&w.cond);
2470 self.in_loop_cond = false;
2471 let c = c?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2472 self.line(&format!("while {}:", c.code));
2473 let saved = self.target.take();
2474 self.nested_block(&w.body)?;
2475 self.target = saved;
2476 Ok(None)
2477 }
2478 Expr::Loop(l) => {
2479 if l.label.is_some() {
2480 return Err("loop labels are not implemented yet".into());
2481 }
2482 self.line("while true:");
2483 let saved = self.target.take();
2484 self.nested_block(&l.body)?;
2485 self.target = saved;
2486 Ok(None)
2487 }
2488 Expr::ForLoop(f) => {
2489 self.for_loop(f)?;
2490 Ok(None)
2491 }
2492 Expr::Block(b) => {
2493 if b.label.is_some() {
2494 return Err("block labels are not implemented yet".into());
2495 }
2496 self.line("block:");
2497 self.nested_block(&b.block)?;
2498 Ok(None)
2499 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago2500 Expr::Unsafe(u) => {
2501 // Transparent in statement position too, for the same reason.
2502 self.nested_block_flat(&u.block)?;
2503 Ok(None)
2504 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2505 Expr::Match(_) => {
2506 self.match_stmt(e)?;
2507 Ok(None)
2508 }
2509 Expr::Return(r) => {
2510 match &r.expr {
2511 Some(e) => {
2512 let want = self.ret.clone();
2513 let v = self.expr_at(e, want.as_ref())?;
2514 self.line(&format!("return {}", v.code));
2515 }
2516 None => self.line("return"),
2517 }
2518 Ok(None)
2519 }
2520 Expr::Break(b) => {
2521 if b.expr.is_some() || b.label.is_some() {
2522 return Err("`break` with a value or a label is not implemented yet".into());
2523 }
2524 self.line("break");
2525 Ok(None)
2526 }
2527 Expr::Continue(c) => {
2528 if c.label.is_some() {
2529 return Err("labelled `continue` is not implemented yet".into());
2530 }
2531 self.line("continue");
2532 Ok(None)
2533 }
2534 Expr::Assign(a) => {
2535 let lhs = self.expr(&a.left)?;
2536 if !expressible(&a.right) {
2537 let target = lhs.code.clone();
2538 return self.assign_from(&a.right, &target, lhs.ty.as_ref()).map(|_| None);
2539 }
2540 let rhs = self.expr_at(&a.right, lhs.ty.as_ref())?;
2541 self.line(&format!("{} = {}", lhs.code, rhs.code));
2542 Ok(None)
2543 }
2544 Expr::Binary(b) if is_compound(&b.op) => {
2545 let lhs = self.expr(&b.left)?;
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago2546 // A compound assignment on a user type goes to that type's own
2547 // `impl OpAssign`, not to Nim's built-in operator.
2548 if let Some(f) = self.op_proc(&lhs.ty, compound_symbol(&b.op)) {
2549 // The impl's own parameter type types the right operand,
2550 // so `b_vec *= 4` takes 4 at the width the impl declares.
2551 let want = self.op_param(&lhs.ty, compound_symbol(&b.op));
2552 let rhs = self.expr_at(&b.right, want.as_ref())?;
2553 self.line(&format!("{}({}, {})", f, lhs.code, rhs.code));
2554 return Ok(None);
2555 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2556 // `i += 1` must widen the literal to `i`'s type, not to the
2557 // i32 an unconstrained Rust literal would default to.
2558 let rhs = self.expr_at(&b.right, lhs.ty.as_ref())?;
2559 let op = self.bin_op(&b.op, &lhs, &rhs)?;
2560 // Nim has no `shl=` etc., and `+=` on a `let` is illegal in
2561 // both languages, so the expanded form is always correct.
2562 self.line(&format!("{} = {} {} {}", lhs.code, lhs.code, op, rhs.code));
2563 Ok(None)
2564 }
2565 Expr::Macro(m) => {
2566 let line = self.macro_call(&m.mac)?;
2567 self.line(&line);
2568 Ok(None)
2569 }
2570 _ => Ok(Some(self.expr(e)?)),
2571 }
2572 }
2573
2574 /// Lower `e` in statement position, assigning each arm's value to
2575 /// `target`. This is how Rust's expression-oriented `if`/`match` survive
2576 /// the trip when their arms are too big for a Nim `if`-expression.
2577 fn assign_from(
2578 &mut self,
2579 e: &Expr,
2580 target: &str,
2581 expect: Option<&Nim>,
2582 ) -> Result<(), String> {
2583 let saved = self.target.replace((target.to_string(), expect.cloned()));
2584 let r = match e {
2585 Expr::If(_) => self.if_stmt(e),
2586 Expr::Match(_) => self.match_stmt(e),
2587 other => {
2588 let v = self.expr_at(other, expect)?;
2589 self.line(&format!("{} = {}", target, v.code));
2590 Ok(())
2591 }
2592 };
2593 self.target = saved;
2594 r
2595 }
2596
2597 /// Emit a block's value into the active assignment target, if there is
2598 /// one, or discard it if there is not.
2599 fn emit_tail(&mut self, v: Option<Val>) {
2600 let Some(v) = v else { return };
2601 match self.target.clone() {
2602 Some((t, _)) => {
2603 let code = v.code.clone();
2604 self.line(&format!("{t} = {code}"));
2605 }
2606 None => {
2607 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
2608 let code = v.code.clone();
2609 if needs {
2610 self.line(&format!("discard {code}"));
2611 } else if !code.is_empty() {
2612 self.line(&code);
2613 }
2614 }
2615 }
2616 }
2617
2618 fn if_stmt(&mut self, e: &Expr) -> Result<(), String> {
2619 let Expr::If(i) = e else { unreachable!() };
2620 if let Expr::Let(_) = &*i.cond {
2621 return Err("`if let` is not implemented yet".into());
2622 }
2623 let c = self.expr(&i.cond)?;
2624 self.line(&format!("if {}:", c.code));
2625 self.nested_block(&i.then_branch)?;
2626 match &i.else_branch {
2627 None => {}
2628 Some((_, els)) => match &**els {
2629 Expr::If(_) => {
2630 // Nim needs `elif`; splice the nested `if` in as one.
2631 let mark = self.out.len();
2632 self.if_stmt(els)?;
2633 let tail = self.out.split_off(mark);
2634 let indent = " ".repeat(self.indent);
2635 self.out.push_str(&tail.replacen(&format!("{indent}if "), &format!("{indent}elif "), 1));
2636 }
2637 Expr::Block(b) => {
2638 self.line("else:");
2639 self.nested_block(&b.block)?;
2640 }
2641 _ => return Err("unsupported `else` form".into()),
2642 },
2643 }
2644 Ok(())
2645 }
2646
2647 fn for_loop(&mut self, f: &syn::ExprForLoop) -> Result<(), String> {
2648 if f.label.is_some() {
2649 return Err("loop labels are not implemented yet".into());
2650 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2651 let it = self.resolve_iter(&f.expr)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2652
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2653 // One index loop drives the whole chain. Rust's adaptors are lazy and
2654 // compose; resolving them to an index and binding each name to an
2655 // lvalue reproduces that without materialising anything.
2656 let i = self.fresh("Idx");
2657 self.line(&format!("for {} in 0 ..< int({}):", i, it.len()));
2658 self.indent += 1;
2659 self.push_scope();
2660 let before = self.out.len();
2661
2662 self.bind_pattern(&f.pat, &it, &i)?;
2663
2664 let saved = self.target.take();
2665 if let Some(v) = self.block_body(&f.body)? {
2666 let code = v.code.clone();
2667 self.line(&format!("discard {code}"));
2668 }
2669 self.target = saved;
2670 if self.out.len() == before {
2671 self.line("discard");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2672 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2673 self.pop_scope();
2674 self.indent -= 1;
2675 Ok(())
2676 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2677
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2678 /// Resolve a chain of iterator adaptors into a single `Iter`.
2679 ///
2680 /// Only adaptors with an exact index-loop equivalent are accepted. `map`,
2681 /// `filter`, `take_while` and friends are rejected rather than partially
2682 /// honoured: silently dropping an adaptor would change which elements the
2683 /// loop visits.
2684 fn resolve_iter(&mut self, e: &Expr) -> Result<Iter, String> {
2685 match e {
2686 Expr::Reference(r) => self.resolve_iter(&r.expr),
2687 Expr::Paren(p) => self.resolve_iter(&p.expr),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2688 Expr::Range(r) => {
2689 let lo = match &r.start {
2690 Some(e) => self.expr(e)?,
2691 None => return Err("a `for` over `..n` needs a start bound".into()),
2692 };
2693 let hi = match &r.end {
2694 Some(e) => self.expr(e)?,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2695 None => {
2696 return Err("a `for` over an unbounded range would not terminate".into())
2697 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2698 };
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2699 let ty = lo.ty.clone().or(hi.ty.clone());
2700 Ok(Iter::Range {
2701 lo: lo.code,
2702 hi: hi.code,
2703 closed: matches!(r.limits, syn::RangeLimits::Closed(_)),
2704 ty,
2705 })
2706 }
2707 Expr::MethodCall(m) => {
2708 let name = m.method.to_string();
2709 match name.as_str() {
2710 "iter" | "into_iter" | "iter_mut" if m.args.is_empty() => {
2711 let mut it = self.resolve_iter(&m.receiver)?;
2712 if name == "iter_mut" {
2713 if let Iter::Elems { mutable, .. } = &mut it {
2714 *mutable = true;
2715 }
2716 }
2717 Ok(it)
2718 }
2719 "enumerate" if m.args.is_empty() => {
2720 Ok(Iter::Enumerate(Box::new(self.resolve_iter(&m.receiver)?)))
2721 }
2722 "zip" if m.args.len() == 1 => {
2723 let a = self.resolve_iter(&m.receiver)?;
2724 let b = self.resolve_iter(&m.args[0])?;
2725 Ok(Iter::Zip(Box::new(a), Box::new(b)))
2726 }
2727 "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 9h ago2728 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2729 let k = self.expr(&m.args[0])?;
2730 Ok(Iter::Chunks {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago2731 code,
2732 base,
2733 len,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2734 k: k.code,
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago2735 elem,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2736 mutable: name.ends_with("_mut"),
2737 })
2738 }
2739 "windows" if m.args.len() == 1 => {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago2740 let (code, base, len, elem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2741 let k = self.expr(&m.args[0])?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago2742 Ok(Iter::Windows { code, base, len, k: k.code, elem })
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2743 }
2744 other => Err(format!(
2745 "iterator adaptor `.{other}()` is not implemented; it has \
2746 no index-loop equivalent here, and dropping it would \
2747 change which elements the loop visits"
2748 )),
2749 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2750 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago2751 Expr::Path(p) => {
2752 let n = path_name(&p.path);
2753 if let Some(Alias::Iterator(it)) = self.lookup_alias(&n) {
2754 return Ok((*it).clone());
2755 }
2756 if let Some(Alias::Window { code, off, len, elem }) = self.lookup_alias(&n) {
2757 return Ok(Iter::Elems { code, off, len, elem, mutable: false });
2758 }
2759 let v = self.expr(e)?;
2760 Ok(Iter::Elems {
2761 len: format!("{}.len", v.code),
2762 elem: elem_of(&v.ty),
2763 code: v.code,
2764 off: "0".into(),
2765 mutable: false,
2766 })
2767 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2768 other => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2769 // A `for` binding that is itself a window iterates that window,
2770 // not the whole container it points into.
2771 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 9h ago2772 return Ok(Iter::Elems { code, off, len, elem, mutable: false });
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2773 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2774 let v = self.expr(other)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2775 Ok(Iter::Elems {
2776 len: format!("{}.len", v.code),
2777 elem: elem_of(&v.ty),
2778 code: v.code,
2779 off: "0".into(),
2780 mutable: false,
2781 })
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2782 }
2783 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2784 }
2785
2786 /// Bind a `for` pattern against a resolved iterator at index `i`.
2787 fn bind_pattern(&mut self, p: &Pat, it: &Iter, i: &str) -> Result<(), String> {
2788 match (p, it) {
2789 (Pat::Tuple(t), Iter::Zip(a, b)) if t.elems.len() == 2 => {
2790 self.bind_pattern(&t.elems[0], a, i)?;
2791 self.bind_pattern(&t.elems[1], b, i)
2792 }
2793 (Pat::Tuple(t), Iter::Enumerate(inner)) if t.elems.len() == 2 => {
2794 if let Pat::Ident(id) = &t.elems[0] {
2795 let n = id.ident.to_string();
2796 // Rust's `enumerate` counts in `usize`.
2797 self.line(&format!("let {}: uint = uint({})", ident(&n), i));
2798 self.bind(&n, Nim::Prim("uint".into()));
2799 }
2800 self.bind_pattern(&t.elems[1], inner, i)
2801 }
2802 (_, Iter::Zip(..) | Iter::Enumerate(..)) => Err(
2803 "a `zip`/`enumerate` loop needs a two-element tuple pattern".into(),
2804 ),
2805 (Pat::Wild(_), _) => Ok(()),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago2806 // `for &byte in xs` — the `&` destructures the reference, which in
2807 // Nim is already the value.
2808 (Pat::Reference(r), _) => self.bind_pattern(&r.pat, it, i),
2809 (Pat::Paren(p), _) => self.bind_pattern(&p.pat, it, i),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2810 (Pat::Ident(id), _) => {
2811 let name = id.ident.to_string();
2812 match it {
2813 Iter::Range { lo, ty, .. } => {
2814 let t = ty.clone().unwrap_or(Nim::Prim("int".into()));
2815 // The loop counts from zero; the range's own start is
2816 // added back so the binding has Rust's value and type.
2817 self.line(&format!(
2818 "let {}: {} = {}({}) + {}",
2819 ident(&name),
2820 t.render(),
2821 t.render(),
2822 i,
2823 lo
2824 ));
2825 self.bind(&name, t);
2826 Ok(())
2827 }
2828 Iter::Elems { code, off, elem, mutable, .. } => {
2829 let access = if off == "0" {
2830 format!("{}[{}]", code, i)
2831 } else {
2832 format!("{}[{} + {}]", code, off, i)
2833 };
2834 if *mutable {
2835 // An alias, not a copy: assigning through the
2836 // binding must reach the original element.
2837 self.bind_alias(
2838 &name,
2839 Alias::Value { code: access, ty: elem.clone() },
2840 );
2841 } else {
2842 let t = elem
2843 .clone()
2844 .ok_or("cannot infer the element type of this `for`")?;
2845 self.line(&format!(
2846 "let {}: {} = {}",
2847 ident(&name),
2848 t.render(),
2849 access
2850 ));
2851 self.bind(&name, t);
2852 }
2853 Ok(())
2854 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago2855 Iter::Chunks { code, base, k, elem, .. } => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2856 self.bind_alias(
2857 &name,
2858 Alias::Window {
2859 code: code.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago2860 off: format!("({} + {} * int({}))", base, i, k),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2861 len: format!("int({})", k),
2862 elem: elem.clone(),
2863 },
2864 );
2865 Ok(())
2866 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago2867 Iter::Windows { code, base, k, elem, .. } => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2868 self.bind_alias(
2869 &name,
2870 Alias::Window {
2871 code: code.clone(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago2872 off: format!("({} + {})", base, i),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago2873 len: format!("int({})", k),
2874 elem: elem.clone(),
2875 },
2876 );
2877 Ok(())
2878 }
2879 // Handled above: a zip or enumerate needs a tuple pattern,
2880 // and binding one name to the pair is not supported.
2881 Iter::Zip(..) | Iter::Enumerate(..) => unreachable!(),
2882 }
2883 }
2884 _ => Err("unsupported `for` pattern".into()),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2885 }
2886 }
2887
2888 fn match_stmt(&mut self, e: &Expr) -> Result<(), String> {
2889 let Expr::Match(m) = e else { unreachable!() };
2890 let scrut = self.expr(&m.expr)?;
2891 let t = scrut
2892 .ty
2893 .clone()
2894 .ok_or("cannot infer the type of a `match` scrutinee")?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago2895 let name = self.fresh("Match");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2896 self.line(&format!("let {}: {} = {}", name, t.render(), scrut.code));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago2897
2898 // A `match` whose arms neither bind nor guard is a Nim `case`, which
2899 // is exhaustiveness-checked the way Rust's is. Anything richer becomes
2900 // an if/elif chain, because Nim's `case` cannot destructure.
2901 let plain = m.arms.iter().all(|a| {
2902 !matches!(a.pat, Pat::Guard(_)) && !binds(&a.pat) && !destructures(&a.pat)
2903 });
2904 if plain {
2905 self.match_case(m, &name, &t)
2906 } else {
2907 self.match_chain(m, &name, &t)
2908 }
2909 }
2910
2911 fn match_case(
2912 &mut self,
2913 m: &syn::ExprMatch,
2914 name: &str,
2915 t: &Nim,
2916 ) -> Result<(), String> {
2917 // A variant object is discriminated by its `kind` field.
2918 let on_kind = matches!(t, Nim::Named(n, _) if self.enums.get(n).is_some_and(|d| !d.simple));
2919 self.line(&format!("case {}{}", name, if on_kind { ".kind" } else { "" }));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2920
2921 let mut saw_wild = false;
2922 for arm in &m.arms {
2923 match &arm.pat {
2924 Pat::Wild(_) => {
2925 saw_wild = true;
2926 self.line("else:");
2927 }
2928 p => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago2929 let labels = self.pat_labels(p, Some(t))?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2930 self.line(&format!("of {}:", labels.join(", ")));
2931 }
2932 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago2933 self.arm_body(&arm.body)?;
2934 }
2935 if !saw_wild && !self.case_is_total(t, m) {
2936 // Rust checked exhaustiveness already, but Nim cannot always see
2937 // it -- an integer `case` needs every value covered -- so make the
2938 // unreachable arm explicit rather than leave a compile error.
2939 self.line("else:");
2940 self.line(" rsPanic(\"unreachable match arm\")");
2941 }
2942 Ok(())
2943 }
2944
2945 /// Whether a Nim `case` over this type is already total, in which case
2946 /// adding an `else` would be a compile error rather than a safety net.
2947 fn case_is_total(&self, t: &Nim, m: &syn::ExprMatch) -> bool {
2948 let Nim::Named(n, _) = t else { return false };
2949 let Some(def) = self.enums.get(n) else { return false };
2950 def.variants.len() == m.arms.len()
2951 }
2952
2953 /// The if/elif form, for arms that bind or destructure.
2954 fn match_chain(
2955 &mut self,
2956 m: &syn::ExprMatch,
2957 name: &str,
2958 t: &Nim,
2959 ) -> Result<(), String> {
2960 let mut first = true;
2961 let mut closed = false;
2962 for arm in &m.arms {
2963 let (pat, guard) = match &arm.pat {
2964 Pat::Guard(g) => (&*g.pat, Some(&*g.guard)),
2965 p => (p, None),
2966 };
2967 if guard.is_some() && binds(pat) {
2968 return Err("a `match` guard on a binding pattern is not \
2969 implemented yet"
2970 .into());
2971 }
2972 let test = self.pat_test(pat, name, t)?;
2973 let test = match (test, guard) {
2974 (Some(t), Some(g)) => {
2975 let g = self.expr(g)?;
2976 Some(format!("({}) and ({})", t, g.code))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2977 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago2978 (None, Some(g)) => Some(self.expr(g)?.code),
2979 (t, None) => t,
2980 };
2981 match test {
2982 Some(test) => {
2983 self.line(&format!(
2984 "{} {}:",
2985 if first { "if" } else { "elif" },
2986 test
2987 ));
2988 first = false;
2989 }
2990 None => {
2991 // An irrefutable pattern: everything left falls here.
2992 if first {
2993 self.line("block:");
2994 } else {
2995 self.line("else:");
2996 }
2997 closed = true;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago2998 }
2999 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3000 self.indent += 1;
3001 self.push_scope();
3002 let before = self.out.len();
3003 self.pat_bind(pat, name, t)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3004 self.indent -= 1;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3005 self.arm_body_at(&arm.body, before)?;
3006 self.pop_scope();
3007 if closed {
3008 break;
3009 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3010 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3011 if !closed {
3012 // Rust proved this unreachable; Nim cannot see that, and leaving
3013 // the chain open would silently fall through instead.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3014 self.line("else:");
3015 self.line(" rsPanic(\"unreachable match arm\")");
3016 }
3017 Ok(())
3018 }
3019
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3020 /// The condition that selects this arm, or `None` if it always matches.
3021 fn pat_test(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<Option<String>, String> {
3022 Ok(match p {
3023 Pat::Wild(_) => None,
3024 Pat::Ident(i) if i.subpat.is_none() => None,
3025 Pat::Or(o) => {
3026 let mut parts = Vec::new();
3027 for c in &o.cases {
3028 match self.pat_test(c, name, t)? {
3029 Some(x) => parts.push(x),
3030 None => return Ok(None),
3031 }
3032 }
3033 Some(format!("({})", parts.join(" or ")))
3034 }
3035 Pat::Lit(_) | Pat::Range(_) => {
3036 let labels = self.pat_labels(p, Some(t))?;
3037 Some(match p {
3038 Pat::Range(_) => format!("({} in {})", name, labels[0]),
3039 _ => format!("({} == {})", name, labels[0]),
3040 })
3041 }
3042 Pat::Path(pp) => Some(self.variant_test(&pp.path, name, t)?),
3043 Pat::TupleStruct(ts) => Some(self.variant_test(&ts.path, name, t)?),
3044 Pat::Struct(st) => Some(self.variant_test(&st.path, name, t)?),
3045 Pat::Paren(pp) => return self.pat_test(&pp.pat, name, t),
3046 Pat::Reference(r) => return self.pat_test(&r.pat, name, t),
3047 _ => return Err("unsupported `match` pattern".into()),
3048 })
3049 }
3050
3051 /// The discriminant test for `Ok`/`Err`/`Some`/`None` or an enum variant.
3052 fn variant_test(&self, path: &syn::Path, name: &str, t: &Nim) -> Result<String, String> {
3053 let last = path_name(path);
3054 match last.as_str() {
3055 "Ok" => return Ok(format!("{name}.ok")),
3056 "Err" => return Ok(format!("(not {name}.ok)")),
3057 "Some" => return Ok(format!("{name}.has")),
3058 "None" => return Ok(format!("(not {name}.has)")),
3059 _ => {}
3060 }
3061 let Some((def, v)) = self.resolve_variant(path) else {
3062 return Err(format!(
3063 "`{last}` in a pattern is not a known enum variant; if it names \
3064 an enum declared in another module, that is not implemented yet"
3065 ));
3066 };
3067 if let Nim::Named(n, _) = t {
3068 if *n != def.name {
3069 return Err(format!(
3070 "pattern `{}::{}` does not match the scrutinee type `{}`",
3071 def.name, v, n
3072 ));
3073 }
3074 }
3075 Ok(if def.simple {
3076 format!("({} == {}.{})", name, ident(&def.name), ident(&v))
3077 } else {
3078 format!("({}.kind == {})", name, def.kind_ident(&v))
3079 })
3080 }
3081
3082 /// Emit the `let`s that a pattern's bindings introduce.
3083 fn pat_bind(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<(), String> {
3084 match p {
3085 Pat::Wild(_) | Pat::Lit(_) | Pat::Range(_) | Pat::Path(_) | Pat::Or(_) => Ok(()),
3086 Pat::Paren(pp) => self.pat_bind(&pp.pat, name, t),
3087 Pat::Reference(r) => self.pat_bind(&r.pat, name, t),
3088 Pat::Ident(i) if i.subpat.is_none() => {
3089 let b = i.ident.to_string();
3090 self.line(&format!("let {}: {} = {}", ident(&b), t.render(), name));
3091 self.bind(&b, t.clone());
3092 Ok(())
3093 }
3094 Pat::TupleStruct(ts) => {
3095 let fields = self.variant_fields(&ts.path, t)?;
3096 for (i, sub) in ts.elems.iter().enumerate() {
3097 let Some((fname, fty)) = fields.get(i) else {
3098 return Err(format!(
3099 "pattern binds {} field(s) but the variant has {}",
3100 ts.elems.len(),
3101 fields.len()
3102 ));
3103 };
3104 let access = format!("{}.{}", name, ident(fname));
3105 self.pat_bind(sub, &access, fty)?;
3106 }
3107 Ok(())
3108 }
3109 Pat::Struct(st) => {
3110 let fields = self.variant_fields(&st.path, t)?;
3111 for f in &st.fields {
3112 let syn::Member::Named(m) = &f.member else {
3113 return Err("unsupported struct pattern field".into());
3114 };
3115 let m = m.to_string();
3116 let Some((fname, fty)) = fields.iter().find(|(f, _)| f.ends_with(&m)) else {
3117 return Err(format!("unknown field `{m}` in pattern"));
3118 };
3119 let access = format!("{}.{}", name, ident(fname));
3120 self.pat_bind(&f.pat, &access, fty)?;
3121 }
3122 Ok(())
3123 }
3124 _ => Err("unsupported `match` pattern".into()),
3125 }
3126 }
3127
3128 /// The payload fields a variant pattern destructures.
3129 fn variant_fields(
3130 &self,
3131 path: &syn::Path,
3132 t: &Nim,
3133 ) -> Result<Vec<(String, Nim)>, String> {
3134 let last = path_name(path);
3135 // `Ok`/`Err`/`Some` read the prelude's own field names.
3136 if let Nim::Named(n, a) = t {
3137 match (n.as_str(), last.as_str()) {
3138 ("Result", "Ok") if a.len() == 2 => return Ok(vec![("val".into(), a[0].clone())]),
3139 ("Result", "Err") if a.len() == 2 => return Ok(vec![("err".into(), a[1].clone())]),
3140 ("Option", "Some") if a.len() == 1 => return Ok(vec![("val".into(), a[0].clone())]),
3141 _ => {}
3142 }
3143 }
3144 let Some((def, v)) = self.resolve_variant(path) else {
3145 return Err(format!("`{last}` is not a known enum variant"));
3146 };
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago3147 let fields = def.get(&v).map(|v| v.fields.clone()).unwrap_or_default();
3148 // The variant's payload is declared in the enum's own parameters; the
3149 // scrutinee says what they are here.
3150 Ok(fields
3151 .into_iter()
3152 .map(|(n, ft)| (n, self.subst_type_args(&def.name, t, ft)))
3153 .collect())
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3154 }
3155
3156 fn arm_body(&mut self, body: &Expr) -> Result<(), String> {
3157 self.indent += 1;
3158 let before = self.out.len();
3159 self.indent -= 1;
3160 self.arm_body_at(body, before)
3161 }
3162
3163 fn arm_body_at(&mut self, body: &Expr, before: usize) -> Result<(), String> {
3164 match body {
3165 Expr::Block(b) => self.nested_block(&b.block)?,
3166 other => {
3167 self.indent += 1;
3168 // An arm's value is the `match`'s value, so it is typed by
3169 // whatever the `match` is being assigned to -- without which
3170 // an `Ok(..)` arm has no way to know its `Result<T, E>`.
3171 let want = self.target.clone().and_then(|(_, t)| t);
3172 let v = match (want, expressible(other)) {
3173 (Some(t), true) => Some(self.expr_at(other, Some(&t))?),
3174 _ => self.expr_stmt(other)?,
3175 };
3176 self.emit_tail(v);
3177 self.indent -= 1;
3178 }
3179 }
3180 if self.out.len() == before {
3181 self.indent += 1;
3182 self.line("discard");
3183 self.indent -= 1;
3184 }
3185 Ok(())
3186 }
3187
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3188 fn pat_labels(&mut self, p: &Pat, expect: Option<&Nim>) -> Result<Vec<String>, String> {
3189 match p {
3190 Pat::Lit(l) => Ok(vec![self.lit_at(&l.lit, expect)?.code]),
3191 Pat::Or(o) => {
3192 let mut out = Vec::new();
3193 for p in &o.cases {
3194 out.extend(self.pat_labels(p, expect)?);
3195 }
3196 Ok(out)
3197 }
3198 Pat::Range(r) => {
3199 let lo = r.start.as_ref().ok_or("open-ended range pattern")?;
3200 let hi = r.end.as_ref().ok_or("open-ended range pattern")?;
3201 let (lo, hi) = (self.expr_at(lo, expect)?, self.expr_at(hi, expect)?);
3202 let op = match r.limits {
3203 syn::RangeLimits::HalfOpen(_) => "..<",
3204 syn::RangeLimits::Closed(_) => "..",
3205 };
3206 Ok(vec![format!("{} {} {}", lo.code, op, hi.code)])
3207 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3208 Pat::Path(pp) => {
3209 if let Some((def, v)) = self.resolve_variant(&pp.path) {
3210 return Ok(vec![if def.simple {
3211 format!("{}.{}", ident(&def.name), ident(&v))
3212 } else {
3213 def.kind_ident(&v)
3214 }]);
3215 }
3216 Ok(vec![ident(&path_name(&pp.path))])
3217 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3218 _ => Err("unsupported `match` pattern; only literals, ranges, `|` \
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3219 alternatives, enum variants and `_` are implemented"
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3220 .into()),
3221 }
3222 }
3223
3224 // --------------------------------------------------------- expressions
3225
3226 fn expr(&mut self, e: &Expr) -> Result<Val, String> {
3227 self.expr_at(e, None)
3228 }
3229
3230 /// Lower `e`, with the type the surrounding code expects of it.
3231 ///
3232 /// Rust infers an unsuffixed integer literal's type from its context and
3233 /// falls back to `i32`; Nim falls back to 64-bit `int`. Carrying the
3234 /// expected type down to the literal is what makes `let x: u8 = 255` and
3235 /// `x.wrapping_add(100)` mean the same thing on both sides. Without it the
3236 /// widths silently diverge, which is exactly the class of bug this
3237 /// project refuses to ship.
3238 fn expr_at(&mut self, e: &Expr, expect: Option<&Nim>) -> Result<Val, String> {
3239 match e {
3240 Expr::Lit(l) => self.lit_at(&l.lit, expect),
3241 Expr::Path(p) => {
3242 let name = path_name(&p.path);
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3243 if name == "None" {
3244 return Ok(Val::new(self.none_of(expect), expect.cloned()));
3245 }
Lower the `log` facade, and add explicit enum discriminants 12c0a01 nandithebull 6h ago3246 // `log::Level` and `log::LevelFilter` come from the facade
3247 // shim, under names no crate can collide with.
3248 if let Some(q) = p.path.segments.iter().rev().nth(1).map(|s| s.ident.to_string()) {
3249 if (q == "Level" || q == "LevelFilter") && !self.enums.contains_key(&q) {
3250 let pre = if q == "Level" { "rsLvl" } else { "rsFlt" };
3251 let t = if q == "Level" { "RsLogLevel" } else { "RsLogFilter" };
3252 if q == "LevelFilter" && name == "Off" {
3253 return Ok(Val::new("rsFltOff", Some(Nim::Prim(t.into()))));
3254 }
3255 if matches!(name.as_str(), "Error" | "Warn" | "Info" | "Debug" | "Trace") {
3256 return Ok(Val::new(
3257 format!("{pre}{name}"),
3258 Some(Nim::Prim(t.into())),
3259 ));
3260 }
3261 }
3262 }
3263
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 7h ago3264 // `Perms::READ`: a constant of a `bitflags!` type.
3265 if let Some(q) = p.path.segments.iter().rev().nth(1).map(|s| s.ident.to_string()) {
3266 let q = if q == "Self" {
3267 self.self_ty.as_ref().map(type_name).unwrap_or(q)
3268 } else {
3269 q
3270 };
3271 if let Some(c) = self.flag_consts.get(&(q.clone(), name.clone())) {
3272 return Ok(Val::new(c.clone(), Some(Nim::Named(q, vec![]))));
3273 }
3274 }
3275
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago3276 // `Grid::BORDER`: a `const` declared inside an `impl`.
3277 if let Some(q) = p.path.segments.iter().rev().nth(1).map(|s| s.ident.to_string()) {
3278 let q = if q == "Self" {
3279 self.self_ty.as_ref().map(type_name).unwrap_or(q)
3280 } else {
3281 q
3282 };
3283 if let Some((nim, t)) = self.assoc_consts.get(&(q, name.clone())) {
3284 return Ok(Val::new(nim.clone(), Some(t.clone())));
3285 }
3286 }
3287
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago3288 // `i32::MAX` and friends: an associated const on a primitive.
3289 if matches!(name.as_str(), "MAX" | "MIN") {
3290 if let Some(q) = p.path.segments.iter().rev().nth(1) {
3291 if let Some(t @ Nim::Prim(_)) = ty::prim(&q.ident.to_string()) {
3292 if t.is_integer() {
3293 let f = if name == "MAX" { "high" } else { "low" };
3294 return Ok(Val::new(
3295 format!("{}({})", f, t.render()),
3296 Some(t),
3297 ));
3298 }
3299 }
3300 }
3301 }
3302
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago3303 // A unit struct used as a value: `fmt::Error`, or a `struct S;`
3304 // declared here. In Nim that is a constructor call.
3305 if p.path.segments.len() > 1 {
3306 let ty = syn::Type::Path(syn::TypePath { attrs: Vec::new(), qself: None, path: p.path.clone() });
3307 if let Ok(Nim::Prim(n)) = ty::map(&ty) {
3308 if n == "FmtError" {
3309 return Ok(Val::new("FmtError()", Some(Nim::Prim(n))));
3310 }
3311 }
3312 }
3313 if self.structs.get(&name).is_some_and(|f| f.is_empty()) {
3314 return Ok(Val::new(
3315 format!("{}()", ident(&name)),
3316 Some(Nim::Named(name.clone(), vec![])),
3317 ));
3318 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3319 // A unit enum variant used as a value: `Error::InvalidLength`.
3320 if let Some((def, v)) = self.resolve_variant(&p.path) {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago3321 let (ty, targs) = self.variant_type(&def, expect)?;
3322 return Ok(if def.simple && targs.is_empty() {
3323 Val::new(format!("{}.{}", ident(&def.name), ident(&v)), Some(ty))
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3324 } else {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago3325 // A unit variant of a generic enum has no argument to
3326 // infer the parameters from, so they are written out.
3327 Val::new(
3328 format!("{}{}()", def.ctor_ident(&v), targs),
3329 Some(ty),
3330 )
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3331 });
3332 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago3333 // A `for` binding that stands for an element of the container
3334 // it came from: using it must read (and assigning through it
3335 // must write) that element, not a copy.
3336 if let Some(a) = self.lookup_alias(&name) {
3337 return Ok(match a {
3338 Alias::Value { code, ty } => Val::new(code, ty),
3339 // A window *is* a slice; as a value it is the view it
3340 // denotes, which is what Rust's `&[T]` means too.
3341 Alias::Window { code, off, len, elem } => Val::new(
3342 format!("{}.toOpenArray({}, {} + {} - 1)", code, off, off, len),
3343 elem.map(|e| Nim::OpenArray(Box::new(e))),
3344 ),
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago3345 // An iterator is not a value here: it is consumed by a
3346 // `for`, or asked for its `.remainder()`.
3347 Alias::Iterator(_) => {
3348 return Err(format!(
3349 "`{name}` is an iterator; it can be iterated or asked \
3350 for its `remainder()`, but not used as a value"
3351 ))
3352 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago3353 });
3354 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3355 if let Some(t) = self.lookup(&name) {
3356 return Ok(Val::new(ident(&name), Some(t)));
3357 }
3358 // A top-level function used as a value, e.g. passed to a
3359 // parameter of `impl Fn(..)` type.
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago3360 if let Some(k) = self.resolve_fn(&p.path) {
3361 let sig = &self.fns[&k];
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3362 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 9h ago3363 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 10h ago3364 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3365 Ok(Val::new(ident(&name), None))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3366 }
3367 Expr::Paren(p) => {
3368 let v = self.expr_at(&p.expr, expect)?;
3369 Ok(Val::new(format!("({})", v.code), v.ty))
3370 }
3371 Expr::Group(g) => self.expr_at(&g.expr, expect),
3372 // `&x` is a value in Nim; `&mut x` in an argument position binds to
3373 // a `var` parameter, which is also just `x` at the call site.
3374 Expr::Reference(r) => self.expr_at(&r.expr, expect),
3375 Expr::Unary(u) => self.unary(u, expect),
3376 Expr::Binary(b) => self.binary(b, expect),
3377 Expr::Cast(c) => self.cast(c),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago3378 Expr::Index(i) if matches!(&*i.index, Expr::Range(_)) => {
3379 let Expr::Range(r) = &*i.index else { unreachable!() };
3380 let base = self.expr(&i.expr)?;
3381 let lo = match &r.start {
3382 Some(e) => format!("int({})", self.expr(e)?.code),
3383 None => "0".into(),
3384 };
3385 // Nim's `toOpenArray` takes an inclusive upper bound.
3386 let hi = match (&r.end, r.limits) {
3387 (Some(e), syn::RangeLimits::HalfOpen(_)) => {
3388 format!("int({}) - 1", self.expr(e)?.code)
3389 }
3390 (Some(e), syn::RangeLimits::Closed(_)) => {
3391 format!("int({})", self.expr(e)?.code)
3392 }
3393 (None, _) => format!("{}.len - 1", base.code),
3394 };
3395 let elem = elem_of(&base.ty)
3396 .ok_or("cannot infer the element type of this slice")?;
3397 Ok(Val::new(
3398 format!("{}.toOpenArray({}, {})", base.code, lo, hi),
3399 Some(Nim::OpenArray(Box::new(elem))),
3400 ))
3401 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3402 Expr::Index(i) => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago3403 if let Some(Alias::Window { code, off, elem, .. }) = self.window_of(&i.expr) {
3404 let idx = self.expr(&i.index)?;
3405 return Ok(Val::new(
3406 format!("{}[{} + int({})]", code, off, idx.code),
3407 elem,
3408 ));
3409 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3410 let base = self.expr(&i.expr)?;
3411 let idx = self.expr(&i.index)?;
3412 // Rust indexes with usize; Nim wants an `int`, and a `uint`
3413 // index is a type error there rather than a silent conversion.
3414 let idx_code = match &idx.ty {
3415 Some(t) if t.is_unsigned() => format!("int({})", idx.code),
3416 _ => idx.code.clone(),
3417 };
3418 let elem = match base.ty.clone() {
3419 Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) | Some(Nim::Array(_, t)) => Some(*t),
3420 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
3421 _ => None,
3422 };
3423 Ok(Val::new(format!("{}[{}]", base.code, idx_code), elem))
3424 }
3425 Expr::Field(f) => {
3426 let base = self.expr(&f.base)?;
3427 let name = match &f.member {
3428 syn::Member::Named(n) => n.to_string(),
3429 syn::Member::Unnamed(i) => format!("f{}", i.index),
3430 };
3431 let t = match &base.ty {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago3432 Some(bt @ Nim::Named(s, _)) => self
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3433 .structs
3434 .get(s)
3435 .and_then(|fs| fs.iter().find(|(f, _)| *f == name))
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago3436 .map(|(_, t)| self.subst_type_args(s, bt, t.clone())),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3437 _ => None,
3438 };
3439 Ok(Val::new(format!("{}.{}", base.code, ident(&name)), t))
3440 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago3441 // `unsafe` is a permission marker, not a semantic change: it does
3442 // not alter what the enclosed operations mean. So the block is
3443 // transparent here, and each operation inside still goes through
3444 // the ordinary lowering -- and is still rejected if it has no
3445 // faithful mapping.
3446 Expr::Unsafe(u) => match single_expr(&u.block) {
3447 Some(e) => self.expr_at(e, expect),
3448 None => Err("an `unsafe` block used as a value must be a single \
3449 expression"
3450 .into()),
3451 },
3452 Expr::Closure(c) => self.closure(c, expect),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3453 Expr::Try(t) => self.try_op(t),
3454 Expr::Call(c) => self.call(c, expect),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago3455 Expr::MethodCall(m) => self.method(m, expect),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago3456 Expr::Macro(m) if path_name(&m.mac.path) == "vec" => {
3457 // `vec![..]`'s elements take their type from the annotation on
3458 // the binding, exactly as Rust's would.
3459 let want = match expect {
3460 Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) => Some((**e).clone()),
3461 _ => None,
3462 };
3463 let saved = std::mem::replace(&mut self.vec_expect, want.clone());
3464 let code = self.macro_call(&m.mac);
3465 self.vec_expect = saved;
3466 let code = code?;
3467 let ty = match want {
3468 Some(e) => Some(Nim::Seq(Box::new(e))),
3469 None => self.vec_elem(&m.mac)?.map(|e| Nim::Seq(Box::new(e))),
3470 };
3471 Ok(Val::new(code, ty))
3472 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3473 Expr::Macro(m) => {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago3474 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 10h ago3475 let code = self.macro_call(&m.mac)?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago3476 // A formatter write is a statement that appends, not a value.
3477 let ty = if is_write { Some(Nim::Unit) } else { None };
3478 Ok(Val::new(code, ty))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3479 }
3480 Expr::Struct(s) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3481 if s.rest.is_some() {
3482 return Err("struct update syntax `..rest` is not implemented yet".into());
3483 }
3484 // `Shape::Rect { w: 3, h: 5 }` is a struct-shaped *enum variant*,
3485 // which is constructed positionally in Nim.
3486 if let Some((def, v)) = self.resolve_variant(&s.path) {
3487 let fields = def.get(&v).map(|v| v.fields.clone()).unwrap_or_default();
3488 let mut args = vec![String::new(); fields.len()];
3489 for f in &s.fields {
3490 let syn::Member::Named(m) = &f.member else {
3491 return Err("unsupported enum variant field".into());
3492 };
3493 let want = format!("{}_{}", v, m);
3494 let i = fields
3495 .iter()
3496 .position(|(n, _)| *n == want)
3497 .ok_or_else(|| format!("`{}::{}` has no field `{m}`", def.name, v))?;
3498 args[i] = self.expr_at(&f.expr, Some(&fields[i].1))?.code;
3499 }
3500 if let Some(i) = args.iter().position(|a| a.is_empty()) {
3501 return Err(format!(
3502 "`{}::{}` is missing field `{}`",
3503 def.name, v, fields[i].0
3504 ));
3505 }
3506 return Ok(Val::new(
3507 format!("{}({})", def.ctor_ident(&v), args.join(", ")),
3508 Some(Nim::Named(def.name.clone(), vec![])),
3509 ));
3510 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago3511 // `Self { .. }` inside an `impl` names the type being
3512 // implemented, and its fields are that type's fields.
3513 let name = match path_name(&s.path).as_str() {
3514 "Self" => self
3515 .self_ty
3516 .as_ref()
3517 .map(type_name)
3518 .ok_or("`Self` outside an `impl` block")?,
3519 other => other.to_string(),
3520 };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3521 let mut parts = Vec::new();
3522 for f in &s.fields {
3523 let fname = match &f.member {
3524 syn::Member::Named(n) => n.to_string(),
3525 syn::Member::Unnamed(i) => format!("f{}", i.index),
3526 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3527 let want = self
3528 .structs
3529 .get(&name)
3530 .and_then(|fs| fs.iter().find(|(n, _)| *n == fname))
3531 .map(|(_, t)| t.clone());
3532 let v = self.expr_at(&f.expr, want.as_ref())?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3533 parts.push(format!("{}: {}", ident(&fname), v.code));
3534 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago3535 // Nim cannot infer an object's generic parameters from a
3536 // constructor's field values, so they are written out.
3537 let gp = self.type_generics.get(&name).cloned().unwrap_or_default();
3538 let ty = if gp.is_empty() {
3539 Nim::Named(name.clone(), vec![])
3540 } else {
3541 match expect {
3542 Some(Nim::Named(n, a)) if *n == name && a.len() == gp.len() => {
3543 Nim::Named(name.clone(), a.clone())
3544 }
3545 _ => {
3546 return Err(format!(
3547 "`{name} {{ .. }}` is generic, and Nim cannot infer \
3548 its parameters from the field values; annotate the \
3549 binding or the return type"
3550 ))
3551 }
3552 }
3553 };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3554 Ok(Val::new(
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago3555 format!("{}({})", ty.render(), parts.join(", ")),
3556 Some(ty),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3557 ))
3558 }
3559 Expr::Array(a) => {
3560 let mut parts = Vec::new();
3561 let mut elem = match expect {
3562 Some(Nim::Array(_, t)) | Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) => {
3563 Some((**t).clone())
3564 }
3565 _ => None,
3566 };
3567 for e in &a.elems {
3568 let want = elem.clone();
3569 let v = self.expr_at(e, want.as_ref())?;
3570 elem = elem.or(v.ty.clone());
3571 parts.push(v.code);
3572 }
3573 let t = elem.map(|t| Nim::Array(a.elems.len(), Box::new(t)));
3574 Ok(Val::new(format!("[{}]", parts.join(", ")), t))
3575 }
3576 Expr::Repeat(r) => {
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago3577 // `[0; 4]` is an array in Rust. Nim distinguishes a fixed-size
3578 // array from a `seq`, so the expected type decides which, and
3579 // an array needs its elements written out.
3580 let want_elem = match expect {
3581 Some(Nim::Array(_, e)) | Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) => {
3582 Some((**e).clone())
3583 }
3584 _ => None,
3585 };
3586 let v = self.expr_at(&r.expr, want_elem.as_ref())?;
3587 if let Some(Nim::Array(n, _)) = expect {
3588 let elems: Vec<String> = (0..*n).map(|_| v.code.clone()).collect();
3589 let t = v.ty.clone().map(|t| Nim::Array(*n, Box::new(t)));
3590 return Ok(Val::new(format!("[{}]", elems.join(", ")), t));
3591 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3592 let n = self.expr(&r.len)?;
3593 let t = v.ty.clone().map(|t| Nim::Seq(Box::new(t)));
3594 Ok(Val::new(format!("newSeqWith(int({}), {})", n.code, v.code), t))
3595 }
3596 Expr::Tuple(t) if t.elems.is_empty() => Ok(Val::new("", Some(Nim::Unit))),
3597 Expr::Tuple(t) => {
3598 let mut parts = Vec::new();
3599 let mut tys = Vec::new();
3600 for e in &t.elems {
3601 let v = self.expr(e)?;
3602 tys.push(v.ty.clone());
3603 parts.push(v.code);
3604 }
3605 let ty = tys
3606 .iter()
3607 .cloned()
3608 .collect::<Option<Vec<_>>>()
3609 .map(Nim::Tuple);
3610 Ok(Val::new(format!("({})", parts.join(", ")), ty))
3611 }
3612 // `if` and `match` are expressions in both languages, but only
3613 // when every arm is itself a single expression.
3614 Expr::If(i) => self.if_expr(i, expect),
Expand `$(..)` repetition in macro_rules 3d4a7d2 nandithebull 6h ago3615 // A block with statements used as a value: the statements are
3616 // emitted ahead of the line being built and the block's trailing
3617 // expression becomes the value. Every caller lowers its
3618 // sub-expressions before emitting its own line, which is what
3619 // makes that ordering hold.
3620 Expr::Block(b)
3621 if b.label.is_none()
3622 && b.block.stmts.len() > 1
3623 && matches!(b.block.stmts.last(), Some(Stmt::Expr(_, None))) =>
3624 {
3625 if self.in_loop_cond {
3626 return Err("a block expression in a loop condition is not \
3627 implemented yet: its statements would run once, \
3628 before the loop"
3629 .into());
3630 }
3631 // Nim's `block:` is an expression too, so the statements get
3632 // their own scope rather than being hoisted into the enclosing
3633 // one -- which would collide if the same block is written
3634 // twice, as a macro expanded at two call sites is.
3635 let tmp = self.fresh("Blk");
3636 self.line(&format!("let {} = block:", tmp));
3637 self.indent += 1;
3638 self.push_scope();
3639 let saved = self.target.take();
3640 let before = self.out.len();
3641 let tail = self.block_body_at(&b.block, expect)?;
3642 let ty = tail.as_ref().and_then(|v| v.ty.clone());
3643 match tail {
3644 Some(v) => {
3645 let code = v.code.clone();
3646 self.line(&code);
3647 }
3648 None => {
3649 return Err(
3650 "a block used as a value needs a trailing expression".into()
3651 )
3652 }
3653 }
3654 let _ = before;
3655 self.target = saved;
3656 self.pop_scope();
3657 self.indent -= 1;
3658 Ok(Val::new(tmp, ty))
3659 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3660 Expr::Block(b) if b.block.stmts.len() == 1 => {
3661 if let Some(Stmt::Expr(e, None)) = b.block.stmts.first() {
3662 self.expr_at(e, expect)
3663 } else {
3664 Err("block expression with statements in value position is not implemented yet".into())
3665 }
3666 }
3667 other => Err(format!(
3668 "unsupported expression in value position: {}",
3669 expr_kind(other)
3670 )),
3671 }
3672 }
3673
3674 fn if_expr(&mut self, i: &syn::ExprIf, expect: Option<&Nim>) -> Result<Val, String> {
3675 let (Some(then), Some((_, els))) = (single_expr(&i.then_branch), &i.else_branch) else {
3676 return Err(
3677 "an `if` used as a value must have an `else` and single-expression arms".into(),
3678 );
3679 };
3680 let c = self.expr(&i.cond)?;
3681 let t = self.expr_at(then, expect)?;
3682 let want = expect.cloned().or_else(|| t.ty.clone());
3683 let e = match &**els {
3684 Expr::Block(b) => match single_expr(&b.block) {
3685 Some(x) => self.expr_at(x, want.as_ref())?,
3686 None => return Err("an `if` used as a value must have single-expression arms".into()),
3687 },
3688 other => self.expr_at(other, want.as_ref())?,
3689 };
3690 let ty = t.ty.clone().or(e.ty.clone());
3691 Ok(Val::new(
3692 format!("(if {}: {} else: {})", c.code, t.code, e.code),
3693 ty,
3694 ))
3695 }
3696
3697 fn lit_at(&mut self, l: &Lit, expect: Option<&Nim>) -> Result<Val, String> {
3698 match l {
3699 Lit::Int(i) => {
3700 let suffix = i.suffix();
3701 if let Some(why) = ty::rejected(suffix) {
3702 return Err(format!("integer literal `{}`: {}", i, why));
3703 }
3704 let digits = i.base10_digits().to_string();
3705 // Rust's default for an unconstrained integer literal is i32.
3706 // Nim's is `int` (64-bit). Making the width explicit is what
3707 // keeps overflow behaviour the same on both sides.
3708 let t = if suffix.is_empty() {
3709 match expect {
3710 Some(t) if t.is_integer() => t.clone(),
3711 // Rust's fallback for an otherwise-unconstrained
3712 // integer literal.
3713 _ => Nim::Prim("int32".into()),
3714 }
3715 } else {
3716 ty::prim(suffix).ok_or_else(|| format!("unknown literal suffix `{suffix}`"))?
3717 };
3718 Ok(Val::new(format!("{}'{}", digits, nim_suffix(&t)?), Some(t)))
3719 }
3720 Lit::Float(f) => {
3721 let t = match f.suffix() {
3722 "" => match expect {
3723 Some(Nim::Prim(p)) if p == "float32" => Nim::Prim("float32".into()),
3724 _ => Nim::Prim("float64".into()),
3725 },
3726 "f64" => Nim::Prim("float64".into()),
3727 "f32" => Nim::Prim("float32".into()),
3728 s => return Err(format!("unknown float suffix `{s}`")),
3729 };
3730 let d = f.base10_digits();
3731 let d = if d.contains('.') || d.contains('e') { d.to_string() } else { format!("{d}.0") };
3732 Ok(Val::new(d, Some(t)))
3733 }
3734 Lit::Bool(b) => Ok(Val::new(b.value.to_string(), Some(Nim::Prim("bool".into())))),
3735 Lit::Str(s) => Ok(Val::new(
3736 fmt::nim_str(&s.value()),
3737 Some(Nim::Prim("string".into())),
3738 )),
3739 Lit::Char(c) => Ok(Val::new(
3740 format!("Rune({})", c.value() as u32),
3741 Some(Nim::Prim("Rune".into())),
3742 )),
3743 Lit::Byte(b) => Ok(Val::new(
3744 format!("{}'u8", b.value()),
3745 Some(Nim::Prim("uint8".into())),
3746 )),
3747 Lit::ByteStr(b) => {
3748 let bytes: Vec<String> = b.value().iter().map(|x| format!("{x}'u8")).collect();
3749 Ok(Val::new(
3750 format!("@[{}]", bytes.join(", ")),
3751 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
3752 ))
3753 }
3754 other => Err(format!("unsupported literal: {other:?}")),
3755 }
3756 }
3757
3758 fn unary(&mut self, u: &syn::ExprUnary, expect: Option<&Nim>) -> Result<Val, String> {
3759 // `-128i8` is a literal in Rust, but `-(128'i8)` in Nim would overflow
3760 // the positive half of the range before the negation runs. Folding the
3761 // sign into the literal keeps `i8::MIN` and friends expressible.
3762 if let (UnOp::Neg(_), Expr::Lit(l)) = (&u.op, &*u.expr) {
3763 if matches!(l.lit, Lit::Int(_) | Lit::Float(_)) {
3764 let v = self.lit_at(&l.lit, expect)?;
3765 return Ok(Val::new(format!("-{}", v.code), v.ty));
3766 }
3767 }
3768 let v = self.expr_at(&u.expr, expect)?;
3769 match u.op {
3770 UnOp::Neg(_) => Ok(Val::new(format!("(-{})", v.code), v.ty)),
3771 // Rust's `!` is logical on bool and bitwise-complement on integers.
3772 // Nim spells those `not` and `not` as well, so one mapping covers
3773 // both — but only because Nim overloads `not` the same way.
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 7h ago3774 UnOp::Not(_) => {
3775 if let Some(f) = self.op_proc(&v.ty, "not") {
3776 return Ok(Val::new(format!("{}({})", f, v.code), v.ty));
3777 }
3778 Ok(Val::new(format!("(not {})", v.code), v.ty))
3779 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3780 UnOp::Deref(_) => Ok(v),
3781 _ => Err("unsupported unary operator".into()),
3782 }
3783 }
3784
3785 fn binary(&mut self, b: &syn::ExprBinary, expect: Option<&Nim>) -> Result<Val, String> {
3786 // A comparison's operands are unrelated to the `bool` it produces, so
3787 // the outer expectation is not passed through to them.
3788 let down = match b.op {
3789 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
3790 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => None,
3791 _ => expect,
3792 };
3793 let mut l = self.expr_at(&b.left, down)?;
3794 // Rust unifies the two operand types; propagating whichever side is
3795 // known to the other reproduces that, and disagreement then surfaces
3796 // as a Nim type error rather than as a silent width change.
3797 let mut r = self.expr_at(&b.right, l.ty.as_ref().or(down))?;
3798 if l.ty.is_none() && r.ty.is_some() {
3799 l = self.expr_at(&b.left, r.ty.as_ref())?;
3800 }
3801 let r = std::mem::replace(&mut r, Val::untyped(""));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago3802 // A binary operator on a user type goes to that type's own impl.
3803 if let Some(f) = self.op_proc(&l.ty, binary_symbol(&b.op)) {
3804 let want = self.op_param(&l.ty, binary_symbol(&b.op));
3805 let r = self.expr_at(&b.right, want.as_ref())?;
3806 let ret = self
3807 .methods
3808 .get(&(
3809 type_name(l.ty.as_ref().unwrap()),
3810 op_method(binary_symbol(&b.op)).to_string(),
3811 ))
3812 .map(|s| s.ret.clone());
3813 return Ok(Val::new(format!("{}({}, {})", f, l.code, r.code), ret));
3814 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3815 let op = self.bin_op(&b.op, &l, &r)?;
3816 let ty = match b.op {
3817 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
3818 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => Some(Nim::Prim("bool".into())),
3819 // Rust's shift takes its result type from the *left* operand, and
3820 // the right may be a different width entirely.
3821 BinOp::Shl(_) | BinOp::Shr(_) => l.ty.clone(),
3822 _ => l.ty.clone().or(r.ty.clone()),
3823 };
3824 Ok(Val::new(format!("({} {} {})", l.code, op, r.code), ty))
3825 }
3826
3827 fn bin_op(&mut self, op: &BinOp, l: &Val, r: &Val) -> Result<&'static str, String> {
3828 Ok(match op {
3829 BinOp::Add(_) | BinOp::AddAssign(_) => "+",
3830 BinOp::Sub(_) | BinOp::SubAssign(_) => "-",
3831 BinOp::Mul(_) | BinOp::MulAssign(_) => "*",
3832 BinOp::Div(_) | BinOp::DivAssign(_) => {
3833 // Nim spells integer division `div`. Both languages truncate
3834 // toward zero, so once the right operator is chosen the
3835 // semantics match, including for negative operands.
3836 let t = l.ty.clone().or(r.ty.clone()).ok_or(
3837 "cannot tell integer from float division here; annotate the operands",
3838 )?;
3839 if t.is_integer() { "div" } else { "/" }
3840 }
3841 BinOp::Rem(_) | BinOp::RemAssign(_) => {
3842 let t = l.ty.clone().or(r.ty.clone()).ok_or(
3843 "cannot tell integer from float remainder here; annotate the operands",
3844 )?;
3845 if t.is_integer() { "mod" } else { return Err("float `%` is not implemented yet".into()) }
3846 }
3847 BinOp::And(_) => "and",
3848 BinOp::Or(_) => "or",
3849 // Nim's `and`/`or`/`xor` are bitwise on integers and logical on
3850 // bools, exactly as Rust's `&`/`|`/`^` are.
3851 BinOp::BitAnd(_) | BinOp::BitAndAssign(_) => "and",
3852 BinOp::BitOr(_) | BinOp::BitOrAssign(_) => "or",
3853 BinOp::BitXor(_) | BinOp::BitXorAssign(_) => "xor",
3854 // Settled empirically: Nim's `shr` on a signed integer is
3855 // arithmetic, matching Rust. See DESIGN.md.
3856 BinOp::Shl(_) | BinOp::ShlAssign(_) => "shl",
3857 BinOp::Shr(_) | BinOp::ShrAssign(_) => "shr",
3858 BinOp::Eq(_) => "==",
3859 BinOp::Ne(_) => "!=",
3860 BinOp::Lt(_) => "<",
3861 BinOp::Le(_) => "<=",
3862 BinOp::Gt(_) => ">",
3863 BinOp::Ge(_) => ">=",
3864 other => return Err(format!("unsupported binary operator {other:?}")),
3865 })
3866 }
3867
3868 fn cast(&mut self, c: &syn::ExprCast) -> Result<Val, String> {
3869 let v = self.expr(&c.expr)?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3870 let to = self.map_ty(&c.ty)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3871 let from = v.ty.clone().ok_or_else(|| {
3872 format!(
3873 "cannot lower `as {}`: the source type is unknown, and `as` \
3874 truncates, so the source width decides the result",
3875 to.render()
3876 )
3877 })?;
3878
3879 let code = match (&from, &to) {
3880 (f, t) if f.is_integer() && t.is_integer() => {
3881 // Rust's `as` between integers is a pure bit-width truncation
Prove byte-identity for base16ct by enumerating whole input domains 99b8376 nandithebull 8h ago3882 // or sign-extension, never a range check. `cast` says exactly
3883 // that. (Nim's `T(x)` turns out to truncate here as well --
3884 // see DESIGN.md item 5 -- but `cast` is the spelling that
3885 // means it rather than the one that happens to agree.)
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3886 format!("cast[{}]({})", t.render(), v.code)
3887 }
3888 (f, Nim::Prim(p)) if f.is_integer() && (p == "float64" || p == "float32") => {
3889 format!("{}({})", p, v.code)
3890 }
Lower the `log` facade, and add explicit enum discriminants 12c0a01 nandithebull 6h ago3891 // The facade's level enums carry their Rust discriminants, so
3892 // `Level::Info as usize` is the ordinal.
3893 (Nim::Prim(p), t)
3894 if t.is_integer() && (p == "RsLogLevel" || p == "RsLogFilter") =>
3895 {
3896 format!("{}(ord({}))", t.render(), v.code)
3897 }
3898 // A C-like enum's `as` yields its discriminant, which is its
3899 // ordinal in Nim.
3900 (Nim::Named(n, _), t) if t.is_integer() && self.enums.get(n).is_some_and(|d| d.simple) => {
3901 format!("{}(ord({}))", t.render(), v.code)
3902 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3903 (Nim::Prim(b), t) if b == "bool" && t.is_integer() => {
3904 format!("{}(ord({}))", t.render(), v.code)
3905 }
3906 (Nim::Prim(r), t) if r == "Rune" && t.is_integer() => {
3907 format!("cast[{}](int32({}))", t.render(), v.code)
3908 }
3909 (f, Nim::Prim(r)) if f.is_integer() && r == "Rune" => {
3910 format!("Rune(int32({}))", v.code)
3911 }
Lower `extern "C"` blocks to Nim importc; do not transpile libc 7db7991 nandithebull 6h ago3912 // Pointer-to-pointer, and integer-to-pointer, are reinterpretations
3913 // in both languages.
3914 (Nim::Ptr(_) | Nim::ConstPtr(_), Nim::Ptr(_) | Nim::ConstPtr(_)) => {
3915 format!("cast[{}]({})", to.render(), v.code)
3916 }
3917 (f, Nim::Ptr(_) | Nim::ConstPtr(_)) if f.is_integer() => {
3918 format!("cast[{}]({})", to.render(), v.code)
3919 }
3920 (Nim::Ptr(_) | Nim::ConstPtr(_), t) if t.is_integer() => {
3921 format!("cast[{}]({})", t.render(), v.code)
3922 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago3923 (Nim::Prim(a), Nim::Prim(b)) if a == b => v.code.clone(),
3924 (f, t) if matches!(f, Nim::Prim(p) if p.starts_with("float")) && t.is_integer() => {
3925 // Rust saturates float->int casts; Nim rounds and range-errors.
3926 // Not the same operation, so it is refused rather than mapped.
3927 return Err(format!(
3928 "`as {}` from a float: Rust saturates, Nim rounds and range-checks; \
3929 no faithful mapping is implemented",
3930 t.render()
3931 ));
3932 }
3933 (f, t) => {
3934 return Err(format!(
3935 "unsupported cast from `{}` to `{}`",
3936 f.render(),
3937 t.render()
3938 ))
3939 }
3940 };
3941 Ok(Val::new(code, Some(to)))
3942 }
3943
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago3944 /// Rust's `?`: return early on the error branch, otherwise yield the value.
3945 ///
3946 /// The early return is statements, not an expression, so they are emitted
3947 /// ahead of the line being built. Every caller lowers its sub-expressions
3948 /// 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 9h ago3949 /// The container, start offset, length and element type an expression
3950 /// denotes as a slice. A window alias contributes its own offset, so
3951 /// `dst.get_mut(..n)` followed by `.chunks_exact_mut(2)` indexes straight
3952 /// into the original buffer rather than through a rebuilt view.
3953 fn slice_parts(
3954 &mut self,
3955 e: &Expr,
3956 ) -> Result<(String, String, String, Option<Nim>), String> {
3957 if let Some(Alias::Window { code, off, len, elem }) = self.window_of(e) {
3958 return Ok((code, off, len, elem));
3959 }
3960 let v = self.expr(e)?;
3961 let len = format!("{}.len", v.code);
3962 Ok((v.code, "0".to_string(), len, elem_of(&v.ty)))
3963 }
3964
3965 /// Expand `opt.map(|x| body)` / `res.and_then(|x| body)` inline.
3966 fn map_closure(
3967 &mut self,
3968 what: &str,
3969 recv: &Val,
3970 kind: &str,
3971 targs: &[Nim],
3972 c: &syn::ExprClosure,
3973 ) -> Result<Val, String> {
3974 if c.capture.is_some() {
3975 return Err("a `move` closure captures by value; Nim's closures \
3976 capture by reference, and the two are not the same"
3977 .into());
3978 }
3979 if c.inputs.len() != 1 {
3980 return Err(format!("`.{what}()` takes a one-argument closure"));
3981 }
3982 let pname = match &c.inputs[0] {
3983 Pat::Ident(i) => i.ident.to_string(),
3984 Pat::Wild(_) => "unused0".into(),
3985 _ => return Err("only plain identifier closure parameters are supported".into()),
3986 };
3987
3988 let is_opt = kind == "Option";
3989 let tmp = self.fresh("Map");
3990 let recv_ty = Nim::Named(kind.to_string(), targs.to_vec());
3991 self.line(&format!("let {}: {} = {}", tmp, recv_ty.render(), recv.code));
3992
3993 let body = match &*c.body {
3994 Expr::Block(b) => single_expr(&b.block)
3995 .ok_or("a closure body with statements is not implemented yet")?,
3996 other => other,
3997 };
3998 self.push_scope();
3999 // The parameter names the payload itself, so a view stays a view.
4000 self.bind_alias(
4001 &pname,
4002 Alias::Value {
4003 code: format!("{}.val", tmp),
4004 ty: Some(targs[0].clone()),
4005 },
4006 );
4007 let v = self.expr(body)?;
4008 self.pop_scope();
4009
4010 let inner = v
4011 .ty
4012 .clone()
4013 .ok_or_else(|| format!("cannot infer the result type of `.{what}()`"))?;
4014 // `and_then`'s closure already returns the wrapped type; `map`'s does
4015 // not and has to be re-wrapped.
4016 let (test, some_branch, none_branch, out_ty) = if is_opt {
4017 let out = if what == "map" {
4018 Nim::Named("Option".into(), vec![inner.clone()])
4019 } else {
4020 inner.clone()
4021 };
4022 let body_code = if what == "map" {
4023 format!("rsSome[{}]({})", inner.render(), v.code)
4024 } else {
4025 v.code.clone()
4026 };
4027 (
4028 format!("{}.has", tmp),
4029 body_code,
4030 format!("rsNone[{}]()", elem_arg(&out).render()),
4031 out,
4032 )
4033 } else {
4034 let e = targs[1].clone();
4035 let out = if what == "map" {
4036 Nim::Named("Result".into(), vec![inner.clone(), e.clone()])
4037 } else {
4038 inner.clone()
4039 };
4040 let ok_ty = elem_arg(&out);
4041 let body_code = if what == "map" {
4042 format!("rsOk[{}, {}]({})", inner.render(), e.render(), v.code)
4043 } else {
4044 v.code.clone()
4045 };
4046 (
4047 format!("{}.ok", tmp),
4048 body_code,
4049 format!("rsErr[{}, {}]({}.err)", ok_ty.render(), e.render(), tmp),
4050 out,
4051 )
4052 };
4053 Ok(Val::new(
4054 format!("(if {}: {} else: {})", test, some_branch, none_branch),
4055 Some(out_ty),
4056 ))
4057 }
4058
4059 /// `|x| x + 1` -> a Nim anonymous proc.
4060 ///
4061 /// Nim's closures capture by reference, as Rust's non-`move` closures do.
4062 /// A `move` closure captures by value, which is a different thing, so it
4063 /// is rejected rather than lowered to the same construct.
4064 fn closure(&mut self, c: &syn::ExprClosure, expect: Option<&Nim>) -> Result<Val, String> {
4065 if c.capture.is_some() {
4066 return Err("a `move` closure captures by value; Nim's closures \
4067 capture by reference, and the two are not the same"
4068 .into());
4069 }
4070 let want: Option<&Vec<Nim>> = match expect {
4071 Some(Nim::Proc(a, _)) => Some(a),
4072 _ => None,
4073 };
4074
4075 self.push_scope();
4076 let mut parts = Vec::new();
4077 let mut ptys = Vec::new();
4078 for (i, p) in c.inputs.iter().enumerate() {
4079 let (name, ann) = match p {
4080 Pat::Ident(id) => (id.ident.to_string(), None),
4081 Pat::Type(t) => match &*t.pat {
4082 Pat::Ident(id) => (id.ident.to_string(), Some(self.map_ty(&t.ty)?)),
4083 _ => return Err("only plain identifier closure parameters are supported".into()),
4084 },
4085 Pat::Wild(_) => (format!("unused{i}"), None),
4086 _ => return Err("only plain identifier closure parameters are supported".into()),
4087 };
4088 let t = ann
4089 .or_else(|| want.and_then(|w| w.get(i).cloned()))
4090 .ok_or_else(|| {
4091 format!(
4092 "cannot infer the type of closure parameter `{name}`; \
4093 annotate it"
4094 )
4095 })?;
4096 parts.push(format!("{}: {}", ident(&name), t.render()));
4097 self.bind(&name, t.clone());
4098 ptys.push(t);
4099 }
4100
4101 let ret_ann = match &c.output {
4102 ReturnType::Default => None,
4103 ReturnType::Type(_, t) => Some(self.map_ty(t)?.owned()),
4104 };
4105 let body = match &*c.body {
4106 Expr::Block(b) => single_expr(&b.block)
4107 .ok_or("a closure body with statements is not implemented yet")?,
4108 other => other,
4109 };
4110 let v = self.expr_at(body, ret_ann.as_ref())?;
4111 self.pop_scope();
4112
4113 let ret = ret_ann
4114 .or_else(|| v.ty.clone())
4115 .ok_or("cannot infer a closure's return type; annotate it")?;
4116 Ok(Val::new(
4117 format!("(proc ({}): {} = {})", parts.join(", "), ret.render(), v.code),
4118 Some(Nim::Proc(ptys, Box::new(ret))),
4119 ))
4120 }
4121
4122 /// Lower a block's statements at the current indentation, without opening
4123 /// a Nim `block:` -- used for `unsafe { .. }`, which introduces no scope
4124 /// of its own in the generated code.
4125 fn nested_block_flat(&mut self, b: &syn::Block) -> Result<(), String> {
4126 self.push_scope();
4127 let tail = self.block_body(b)?;
4128 self.emit_tail(tail);
4129 self.pop_scope();
4130 Ok(())
4131 }
4132
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4133 fn try_op(&mut self, t: &syn::ExprTry) -> Result<Val, String> {
4134 if self.in_loop_cond {
4135 return Err("`?` in a loop condition is not implemented yet: the \
4136 early-return it expands to would be evaluated once, \
4137 before the loop, rather than on each iteration"
4138 .into());
4139 }
4140 let v = self.expr(&t.expr)?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago4141 if self.fmt_param.is_some() {
4142 // Writing into a string cannot fail, so `?` on a formatter write
4143 // is a no-op. `?` on anything else can fail, and `format!` panics
4144 // when a formatting impl returns an error -- so that is what the
4145 // error branch does here, with std's own message.
4146 if v.ty.as_ref() == Some(&Nim::Unit) {
4147 return Ok(v);
4148 }
4149 if let Some(Nim::Named(n, a)) = v.ty.clone() {
4150 if n == "Result" && a.len() == 2 {
4151 let tmp = self.fresh("Fmt");
4152 self.line(&format!(
4153 "let {}: {} = {}",
4154 tmp,
4155 Nim::Named(n, a.clone()).render(),
4156 v.code
4157 ));
4158 self.line(&format!("if not {}.ok:", tmp));
4159 self.line(
4160 " rsPanic(\"a formatting trait implementation returned an error\")",
4161 );
4162 return Ok(Val::new(format!("{}.val", tmp), Some(a[0].clone())));
4163 }
4164 }
4165 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4166 if let (Some(guard), Some(w)) = (v.guard.clone(), v.window.clone()) {
4167 // An `Option`/`Result` of a view: the check is emitted here and the
4168 // view itself survives as an alias, since it has no value form.
4169 let ret = self.ret.clone().ok_or("`?` outside a function with a return type")?;
4170 let err = v.guard_err.clone().ok_or(
4171 "`?` on a `get`/`get_mut` needs an `ok_or` to say what the error is",
4172 )?;
4173 let Nim::Named(n, ra) = &ret else {
4174 return Err(format!("`?` in a function returning `{}`", ret.render()));
4175 };
4176 if n != "Result" || ra.len() != 2 {
4177 return Err(format!("`?` in a function returning `{}`", ret.render()));
4178 }
4179 self.line(&format!("if not {}:", guard));
4180 self.line(&format!(
4181 " return rsErr[{}, {}]({})",
4182 ra[0].render(),
4183 ra[1].render(),
4184 err
4185 ));
4186 let mut out = Val::new(String::new(), None);
4187 out.window = Some(w);
4188 return Ok(out);
4189 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4190 let vt = v.ty.clone().ok_or(
4191 "`?` needs a known `Result`/`Option` type; annotate the expression it applies to",
4192 )?;
4193 let ret = self
4194 .ret
4195 .clone()
4196 .ok_or("`?` outside a function with a return type")?;
4197 let tmp = self.fresh("Try");
4198 self.line(&format!("let {}: {} = {}", tmp, vt.render(), v.code));
4199
4200 match (&vt, &ret) {
4201 (Nim::Named(a, ai), Nim::Named(b, bi))
4202 if a == "Result" && b == "Result" && ai.len() == 2 && bi.len() == 2 =>
4203 {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4204 // Rust inserts a `From::from` on the error here. Where the
4205 // types differ we call the crate's own `impl From`; we never
4206 // assume the conversion is the identity.
4207 let err = if ai[1] == bi[1] {
4208 format!("{}.err", tmp)
4209 } else {
4210 let key = (type_name(&ai[1]), type_name(&bi[1]));
4211 let f = self.from_impls.get(&key).cloned().ok_or_else(|| {
4212 format!(
4213 "`?` needs `From<{}> for {}` to convert the error, and \
4214 no such `impl` is in scope; assuming the conversion is \
4215 the identity would be a guess",
4216 key.0, key.1
4217 )
4218 })?;
4219 format!("{}({}.err)", f, tmp)
4220 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4221 self.line(&format!("if not {}.ok:", tmp));
4222 self.line(&format!(
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4223 " return rsErr[{}, {}]({})",
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4224 bi[0].render(),
4225 bi[1].render(),
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4226 err
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4227 ));
4228 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
4229 }
4230 (Nim::Named(a, ai), Nim::Named(b, bi))
4231 if a == "Option" && b == "Option" && ai.len() == 1 && bi.len() == 1 =>
4232 {
4233 self.line(&format!("if not {}.has:", tmp));
4234 self.line(&format!(" return rsNone[{}]()", bi[0].render()));
4235 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
4236 }
4237 _ => Err(format!(
4238 "`?` on `{}` in a function returning `{}` is not a supported \
4239 combination",
4240 vt.render(),
4241 ret.render()
4242 )),
4243 }
4244 }
4245
4246 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 10h ago4247 let Expr::Path(p) = &*c.func else {
4248 return Err("only calls to named functions are supported".into());
4249 };
4250 let name = path_name(&p.path);
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4251 let target = self.resolve_fn(&p.path);
4252 let ptys: Vec<Nim> = target
4253 .as_ref()
4254 .and_then(|k| self.fns.get(k))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4255 .map(|s| s.params.clone())
4256 .unwrap_or_default();
4257 let mut args = Vec::new();
4258 for (i, a) in c.args.iter().enumerate() {
4259 let want = ptys.get(i).cloned();
4260 args.push(self.expr_at(a, want.as_ref())?);
4261 }
4262 let codes: Vec<String> = args.iter().map(|a| a.code.clone()).collect();
4263
4264 // Constructors from the prelude.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4265 // `Ok`/`Err` must name the *whole* Result type, not just the half
4266 // being constructed: Nim cannot infer `E` from an `Ok(v)` alone.
4267 match name.as_str() {
4268 "Some" => {
4269 let inner = match expect {
4270 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].render(),
4271 _ => {
4272 return Err("`Some(..)` needs a known `Option<T>` type here; \
4273 annotate the binding or the return type"
4274 .into())
4275 }
4276 };
4277 return Ok(Val::new(
4278 format!("rsSome[{}]({})", inner, codes.join(", ")),
4279 expect.cloned(),
4280 ));
4281 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago4282 "Ok" if self.fmt_param.is_some()
4283 && matches!(c.args.first(), Some(Expr::Tuple(t)) if t.elems.is_empty()) =>
4284 {
4285 // `Ok(())` ends a `fmt` body: nothing more is written.
4286 return Ok(Val::new(String::new(), Some(Nim::Unit)));
4287 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4288 "Ok" | "Err" => {
4289 let (t, e) = match expect {
4290 Some(Nim::Named(n, a)) if n == "Result" && a.len() == 2 => {
4291 (a[0].render(), a[1].render())
4292 }
4293 _ => {
4294 return Err(format!(
4295 "`{name}(..)` needs a known `Result<T, E>` type here; \
4296 annotate the binding or the return type"
4297 ))
4298 }
4299 };
4300 let ctor = if name == "Ok" { "rsOk" } else { "rsErr" };
4301 let arg = if codes.is_empty() { String::new() } else { codes.join(", ") };
4302 return Ok(Val::new(
4303 format!("{}[{}, {}]({})", ctor, t, e, arg),
4304 expect.cloned(),
4305 ));
4306 }
4307 _ => {}
4308 }
4309
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago4310 // A tuple struct applied to arguments: `HexDisplay(bytes)`. Nim's
4311 // object constructor names its fields even when Rust's does not.
4312 if let Some(fields) = self.structs.get(&name).cloned() {
4313 if fields.len() == c.args.len() {
4314 let mut parts = Vec::new();
4315 for (i, a) in c.args.iter().enumerate() {
4316 let v = self.expr_at(a, Some(&fields[i].1))?;
4317 parts.push(format!("{}: {}", ident(&fields[i].0), v.code));
4318 }
4319 return Ok(Val::new(
4320 format!("{}({})", ident(&name), parts.join(", ")),
4321 Some(Nim::Named(name.clone(), vec![])),
4322 ));
4323 }
4324 }
4325
Lower the `log` facade, and add explicit enum discriminants 12c0a01 nandithebull 6h ago4326 // `log::set_max_level` / `log::max_level`.
4327 if name == "set_max_level" && codes.len() == 1 {
4328 return Ok(Val::new(
4329 format!("rsLogMaxLevel = int({})", codes[0]),
4330 Some(Nim::Unit),
4331 ));
4332 }
4333 if name == "max_level" && codes.is_empty() {
4334 return Ok(Val::new(
4335 "RsLogFilter(rsLogMaxLevel)",
4336 Some(Nim::Prim("RsLogFilter".into())),
4337 ));
4338 }
4339
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago4340 // `Spacing::from(d)`: a `From` impl called through its target type.
4341 // Rust picks the impl by the argument's type, and so do we -- Nim
4342 // cannot overload on return type, so each impl has its own proc name.
4343 if name == "from" && codes.len() == 1 {
4344 if let Some(q) = p.path.segments.iter().rev().nth(1).map(|s| s.ident.to_string()) {
4345 let q = if q == "Self" {
4346 self.self_ty.as_ref().map(type_name).unwrap_or(q)
4347 } else {
4348 q
4349 };
4350 if let Some(src) = args[0].ty.as_ref().map(type_name) {
4351 if let Some(f) = self.from_impls.get(&(src, q.clone())).cloned() {
4352 return Ok(Val::new(
4353 format!("{}({})", f, codes[0]),
4354 Some(Nim::Named(q, vec![])),
4355 ));
4356 }
4357 }
4358 }
4359 }
4360
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago4361 // `u32::from(b)`: `From` between primitives is lossless by definition
4362 // -- it is the widening direction only -- so a plain Nim conversion is
4363 // exact. (The truncating direction is `as`, which is `cast`.)
4364 if name == "from" && codes.len() == 1 {
4365 if let Some(q) = p.path.segments.iter().rev().nth(1) {
4366 if let Some(Nim::Prim(t)) = ty::prim(&q.ident.to_string()) {
4367 return Ok(Val::new(
4368 format!("{}({})", t, codes[0]),
4369 Some(Nim::Prim(t)),
4370 ));
4371 }
4372 }
4373 }
4374
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4375 // `core::str::from_utf8_unchecked(b)` reinterprets a byte view as a
4376 // string view; no copy, no validation, same memory.
4377 if name == "from_utf8_unchecked" && codes.len() == 1 {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago4378 // `String::from_utf8_unchecked(v)` takes ownership and yields an
4379 // owned `String`; `str::from_utf8_unchecked(b)` borrows and yields
4380 // a view. Same name, different operations -- the qualifier says
4381 // which, and an unqualified call is ambiguous.
4382 let q = p
4383 .path
4384 .segments
4385 .iter()
4386 .rev()
4387 .nth(1)
4388 .map(|s| s.ident.to_string());
4389 return match q.as_deref() {
4390 Some("String") => Ok(Val::new(
4391 format!("rsStringOf({})", codes[0]),
4392 Some(Nim::Prim("string".into())),
4393 )),
4394 Some("str") => Ok(Val::new(
4395 format!("rsStrView({})", codes[0]),
4396 Some(Nim::OpenArray(Box::new(Nim::Prim("char".into())))),
4397 )),
4398 _ => Err(
4399 "`from_utf8_unchecked` must be written as `str::..` (a \
4400 borrowed view) or `String::..` (an owned string); the two \
4401 are different operations"
4402 .into(),
4403 ),
4404 };
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4405 }
4406
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4407 // A tuple enum variant applied to arguments: `Shape::Circle(1.0)`.
4408 if let Some((def, v)) = self.resolve_variant(&p.path) {
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago4409 let (ty, _) = self.variant_type(&def, expect)?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4410 return Ok(Val::new(
4411 format!("{}({})", def.ctor_ident(&v), codes.join(", ")),
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago4412 Some(ty),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4413 ));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4414 }
4415
4416 // A bare path that names a primitive type is Rust's tuple-struct-like
4417 // conversion, e.g. `String::from(..)`; handled by the method path.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4418 // Calling a proc-typed local, which is how an `impl Fn(..)` parameter
4419 // is invoked.
4420 if let Some(Nim::Proc(_, ret)) = self.lookup(&name) {
4421 return Ok(Val::new(
4422 format!("{}({})", ident(&name), codes.join(", ")),
4423 Some((*ret).clone()),
4424 ));
4425 }
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago4426 // `Adler32::new()` / `Adler32::default()`: a method called through
4427 // its type rather than through a receiver.
4428 if let Some(q) = p.path.segments.iter().rev().nth(1).map(|s| s.ident.to_string()) {
4429 // `Self::new()` inside an `impl` names the type being implemented.
4430 let q = if q == "Self" {
4431 self.self_ty.as_ref().map(type_name).unwrap_or(q)
4432 } else {
4433 q
4434 };
4435 if let Some(sig) = self.methods.get(&(q.clone(), name.clone())) {
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 7h ago4436 // Re-lower the arguments with the declared parameter types, so
4437 // a literal takes the width the signature asks for.
4438 let declared = sig.params.clone();
4439 let mut args = args.clone();
4440 let mut codes = codes.clone();
4441 for (i, a) in c.args.iter().enumerate() {
4442 if let Some(want) = declared.get(i) {
4443 let want = want.clone().unvar();
4444 args[i] = self.expr_at(a, Some(&want))?;
4445 codes[i] = args[i].code.clone();
4446 }
4447 }
4448 let sig = &self.methods[&(q.clone(), name.clone())];
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago4449 let arg_tys: Vec<Option<Nim>> = args.iter().map(|a| a.ty.clone()).collect();
4450 let ret = Self::instantiate(sig, &arg_tys);
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago4451 let nim = self
4452 .statics
4453 .get(&(q.clone(), name.clone()))
4454 .cloned()
4455 .unwrap_or_else(|| ident(&name));
4456 return Ok(Val::new(format!("{}({})", nim, codes.join(", ")), Some(ret)));
4457 }
4458 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago4459 let arg_tys: Vec<Option<Nim>> = args.iter().map(|a| a.ty.clone()).collect();
4460 let ret = target
4461 .as_ref()
4462 .and_then(|k| self.fns.get(k))
4463 .map(|sig| Self::instantiate(sig, &arg_tys));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4464 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 10h ago4465 return Err(format!(
4466 "call to unknown function `{name}`; only functions defined in \
4467 this file and the supported standard-library subset can be lowered"
4468 ));
4469 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4470 let nim = match &target {
4471 Some((m, n)) => self.fn_name(m, n),
4472 None => ident(&name),
4473 };
4474 Ok(Val::new(format!("{}({})", nim, codes.join(", ")), ret))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4475 }
4476
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4477 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 10h ago4478 let name = m.method.to_string();
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago4479 // `chunk_iter.remainder()` — the tail `chunks_exact` will not yield.
4480 if name == "remainder" && m.args.is_empty() {
4481 if let Expr::Path(p) = &*m.receiver {
4482 if let Some(Alias::Iterator(it)) = self.lookup_alias(&path_name(&p.path)) {
4483 if let Iter::Chunks { code, base, len, k, elem, .. } = &*it {
4484 let kept = format!("(({} div int({})) * int({}))", len, k, k);
4485 let mut v = Val::new(
4486 String::new(),
4487 elem.clone().map(|e| Nim::OpenArray(Box::new(e))),
4488 );
4489 v.window = Some(Alias::Window {
4490 code: code.clone(),
4491 off: format!("({} + {})", base, kept),
4492 len: format!("({} - {})", len, kept),
4493 elem: elem.clone(),
4494 });
4495 return Ok(v);
4496 }
4497 return Err(
4498 "`.remainder()` is only defined for a `chunks_exact` iterator".into(),
4499 );
4500 }
4501 }
4502 return Err("`.remainder()` needs an iterator bound by `let`".into());
4503 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4504 if let Some(Alias::Window { len, .. }) = self.window_of(&m.receiver) {
4505 match name.as_str() {
4506 "len" => {
4507 return Ok(Val::new(format!("uint({})", len), Some(Nim::Prim("uint".into()))))
4508 }
4509 "is_empty" => {
4510 return Ok(Val::new(format!("({} == 0)", len), Some(Nim::Prim("bool".into()))))
4511 }
4512 other => {
4513 return Err(format!(
4514 "`.{other}()` on a slice window from `chunks_exact`/\
4515 `windows` is not implemented; only indexing and \
4516 `len()` are"
4517 ))
4518 }
4519 }
4520 }
4521 let recv = self.expr(&m.receiver)?;
4522 let rt0 = recv.ty.clone();
4523
4524// `s.get(a..b)` / `s.get_mut(a..b)`: an `Option<&[T]>`. Nim has no
4525 // way to put a view in an object, so instead of materialising an
4526 // Option the view and its validity condition travel together until
4527 // an `ok_or`/`?`/`unwrap` resolves them.
4528 if matches!(name.as_str(), "get" | "get_mut")
4529 && matches!(m.args.first(), Some(Expr::Range(_)))
4530 {
4531 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 9h ago4532 let (code, base, blen, belem) = self.slice_parts(&m.receiver)?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4533 let lo = match &r.start {
4534 Some(e) => format!("int({})", self.expr(e)?.code),
4535 None => "0".into(),
4536 };
4537 let len = match (&r.end, r.limits) {
4538 (Some(e), syn::RangeLimits::HalfOpen(_)) => {
4539 format!("(int({}) - {})", self.expr(e)?.code, lo)
4540 }
4541 (Some(e), syn::RangeLimits::Closed(_)) => {
4542 format!("(int({}) - {} + 1)", self.expr(e)?.code, lo)
4543 }
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4544 (None, _) => format!("({} - {})", blen, lo),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4545 };
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4546 // Hoisted, so the bounds are computed once -- as Rust computes
4547 // them once -- and cannot be re-evaluated later in a scope where
4548 // the names they mention have been shadowed by a loop pattern.
4549 let off_t = self.fresh("Off");
4550 let len_t = self.fresh("Len");
4551 self.line(&format!("let {}: int = {} + {}", off_t, base, lo));
4552 self.line(&format!("let {}: int = {}", len_t, len));
4553 let elem = belem
4554 .or_else(|| elem_of(&rt0))
4555 .ok_or("cannot infer the element type of this slice")?;
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4556 let mut v = Val::new(
4557 String::new(),
4558 Some(Nim::Named(
4559 "Option".into(),
4560 vec![Nim::OpenArray(Box::new(elem.clone()))],
4561 )),
4562 );
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4563 v.guard = Some(format!("({} + {} <= {})", off_t, len_t, blen));
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4564 v.window = Some(Alias::Window {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4565 code,
4566 off: off_t,
4567 len: len_t,
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4568 elem: Some(elem),
4569 });
4570 return Ok(v);
4571 }
4572
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4573 // `.map`/`.and_then` over an `Option`/`Result` take a closure whose
4574 // parameter type comes from the receiver, so they are handled before
4575 // the arguments are lowered. The closure is expanded inline, with its
4576 // parameter aliased to the payload: that keeps the whole thing an
4577 // expression and avoids handing a view to a generic proc.
4578 if matches!(name.as_str(), "map" | "and_then") && m.args.len() == 1 {
4579 if let (Some(Nim::Named(kind, targs)), Expr::Closure(c)) =
4580 (recv.ty.clone(), &m.args[0])
4581 {
4582 if (kind == "Option" && targs.len() == 1) || (kind == "Result" && targs.len() == 2)
4583 {
4584 return self.map_closure(&name, &recv, &kind, &targs, c);
4585 }
4586 }
4587 }
4588
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4589 // `x.wrapping_add(1)` and `x.min(3)` take an argument of the receiver's
4590 // own type; `v.push(e)` takes the element type.
4591 let arg_want = match (name.as_str(), &recv.ty) {
4592 ("push", Some(Nim::Seq(t))) | ("push", Some(Nim::OpenArray(t))) => Some((**t).clone()),
4593 (_, t) => t.clone(),
4594 };
4595 let mut args = Vec::new();
4596 for a in &m.args {
4597 args.push(self.expr_at(a, arg_want.as_ref())?);
4598 }
4599 let a0 = args.first().map(|a| a.code.clone());
4600 let rt = recv.ty.clone();
4601
Lower `bitflags!` directly, checked against the real crate af6e50f nandithebull 7h ago4602 // A method the input defines wins over our model of the standard
4603 // library: `is_empty` on a `bitflags!` type is that type's, not the
4604 // sequence one. Rust resolves inherent methods the same way.
4605 if let Some(t) = &rt {
4606 let key = (type_name(t), name.clone());
4607 if self.methods.contains_key(&key) {
4608 let declared = self.methods[&key].params.clone();
4609 let skip = usize::from(declared.len() == m.args.len() + 1);
4610 for (i, a) in m.args.iter().enumerate() {
4611 if let Some(want) = declared.get(i + skip) {
4612 let want = want.clone().unvar();
4613 args[i] = self.expr_at(a, Some(&want))?;
4614 }
4615 }
4616 let mut arg_tys: Vec<Option<Nim>> = vec![rt.clone()];
4617 arg_tys.extend(args.iter().map(|a| a.ty.clone()));
4618 let ret = Self::instantiate(&self.methods[&key], &arg_tys);
4619 let nim = self
4620 .statics
4621 .get(&key)
4622 .cloned()
4623 .unwrap_or_else(|| ident(&name));
4624 let mut all = vec![recv.code.clone()];
4625 all.extend(args.iter().map(|a| a.code.clone()));
4626 return Ok(Val::new(format!("{}({})", nim, all.join(", ")), Some(ret)));
4627 }
4628 }
4629
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4630 let (code, ty) = match name.as_str() {
4631 // Rust's `len()` is `usize`; Nim's is `int`. The conversion is
4632 // explicit so that a `usize` binding type-checks on the Nim side.
4633 "len" => (format!("uint({}.len)", recv.code), Some(Nim::Prim("uint".into()))),
4634 "is_empty" => (format!("({}.len == 0)", recv.code), Some(Nim::Prim("bool".into()))),
4635 "push" => (format!("{}.add({})", recv.code, a0.unwrap_or_default()), Some(Nim::Unit)),
4636 "clone" | "to_vec" | "to_owned" | "as_slice" | "as_ref" | "as_mut" | "iter"
4637 | "into_iter" => (recv.code.clone(), rt.clone()),
4638 "unwrap" | "expect" => {
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago4639 // Expanded inline rather than called as a generic proc: when
4640 // the payload is a view, Nim can only borrow from a path
4641 // expression, which a proc body containing the panic is not.
4642 let (kind, inner) = match &rt {
4643 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => {
4644 ("Option", a[0].clone())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4645 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago4646 Some(Nim::Named(n, a)) if n == "Result" && a.len() == 2 => {
4647 ("Result", a[0].clone())
4648 }
4649 _ => {
4650 return Err(format!(
4651 "`.{name}()` needs a known `Option`/`Result` receiver type"
4652 ))
4653 }
4654 };
4655 if self.in_loop_cond {
4656 return Err(format!(
4657 "`.{name}()` in a loop condition is not implemented yet: the \
4658 check it expands to would run once, before the loop"
4659 ));
4660 }
4661 let tmp = self.fresh("Unwrap");
4662 let rty = rt.clone().unwrap();
4663 self.line(&format!("let {}: {} = {}", tmp, rty.render(), recv.code));
4664 let (test, msg) = if kind == "Option" {
4665 (format!("{}.has", tmp), "called `Option::unwrap()` on a `None` value")
4666 } else {
4667 (format!("{}.ok", tmp), "called `Result::unwrap()` on an `Err` value")
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4668 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago4669 let msg = if name == "expect" {
4670 args.first().map(|a| a.code.clone()).unwrap_or_else(|| fmt::nim_str(msg))
4671 } else {
4672 fmt::nim_str(msg)
4673 };
4674 self.line(&format!("if not {}:", test));
4675 self.line(&format!(" rsPanic({})", msg));
4676 // If the payload is a view, hand back an alias rather than a
4677 // value: Nim will not let a `let` borrow out of a local, and a
4678 // view is a reference anyway, so there is nothing to bind.
4679 // `{tmp}.val` is a plain field access, so substituting it at
4680 // each use re-evaluates nothing.
4681 if matches!(inner, Nim::OpenArray(_)) {
4682 let mut v = Val::new(format!("{}.val", tmp), Some(inner.clone()));
4683 v.window = Some(Alias::Value {
4684 code: format!("{}.val", tmp),
4685 ty: Some(inner),
4686 });
4687 return Ok(v);
4688 }
4689 (format!("{}.val", tmp), Some(inner))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4690 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4691 "ok_or" if recv.guard.is_some() => {
4692 let e = args.first().ok_or("`ok_or` takes one argument")?;
4693 let ety = e.ty.clone();
4694 let mut v = recv.clone();
4695 v.guard_err = Some(e.code.clone());
4696 v.ty = match (&recv.ty, ety) {
4697 (Some(Nim::Named(_, a)), Some(et)) if a.len() == 1 => {
4698 Some(Nim::Named("Result".into(), vec![a[0].clone(), et]))
4699 }
4700 _ => None,
4701 };
4702 return Ok(v);
4703 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago4704 "ok_or" => {
4705 let inner = match &rt {
4706 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].clone(),
4707 _ => return Err("`ok_or` needs a known `Option<T>` receiver".into()),
4708 };
4709 let e = args.first().ok_or("`ok_or` takes one argument")?;
4710 let ety = e
4711 .ty
4712 .clone()
4713 .ok_or("`ok_or` needs a known error type for its argument")?;
4714 (
4715 format!(
4716 "rsOkOr[{}, {}]({}, {})",
4717 inner.render(),
4718 ety.render(),
4719 recv.code,
4720 e.code
4721 ),
4722 Some(Nim::Named("Result".into(), vec![inner, ety])),
4723 )
4724 }
4725 "unwrap_or" => {
4726 let inner = match &rt {
4727 Some(Nim::Named(n, a)) if (n == "Option" && a.len() == 1) || (n == "Result" && a.len() == 2) => {
4728 Some(a[0].clone())
4729 }
4730 _ => None,
4731 };
4732 (
4733 format!("unwrapOr({}, {})", recv.code, a0.unwrap_or_default()),
4734 inner,
4735 )
4736 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4737 "is_some" => (format!("{}.has", recv.code), Some(Nim::Prim("bool".into()))),
4738 "is_none" => (format!("(not {}.has)", recv.code), Some(Nim::Prim("bool".into()))),
4739 "is_ok" => (format!("{}.ok", recv.code), Some(Nim::Prim("bool".into()))),
4740 "is_err" => (format!("(not {}.ok)", recv.code), Some(Nim::Prim("bool".into()))),
4741
4742 // Settled empirically: Nim's fixed-width *unsigned* arithmetic
4743 // wraps silently, matching Rust's `wrapping_*`. For *signed* types
4744 // Nim raises OverflowDefect, so the operation is routed through
4745 // the unsigned view of the same width, which is what Rust's
4746 // wrapping_* is defined to compute.
4747 "wrapping_add" | "wrapping_sub" | "wrapping_mul" => {
4748 let op = match name.as_str() {
4749 "wrapping_add" => "+",
4750 "wrapping_sub" => "-",
4751 _ => "*",
4752 };
4753 let t = rt.clone().ok_or_else(|| {
4754 format!("`{name}` needs a known receiver type to pick the wrapping width")
4755 })?;
4756 if !t.is_integer() {
4757 return Err(format!("`{name}` on a non-integer type"));
4758 }
4759 let arg = a0.ok_or_else(|| format!("`{name}` takes one argument"))?;
4760 if t.is_unsigned() {
4761 (format!("({} {} {})", recv.code, op, arg), Some(t))
4762 } else {
4763 let u = unsigned_peer(&t)?;
4764 (
4765 format!(
4766 "cast[{}](cast[{}]({}) {} cast[{}]({}))",
4767 t.render(), u, recv.code, op, u, arg
4768 ),
4769 Some(t),
4770 )
4771 }
4772 }
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4773 // Inside a formatting impl, a write through the `Formatter` *is*
4774 // 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 9h ago4775 "write_str" | "write_char" if self.is_fmt_param(&m.receiver) => {
4776 let a = args.first().ok_or("`write_str` takes one argument")?;
4777 // A `&str` argument is a character view, not a Nim string.
4778 let text = match &a.ty {
4779 Some(Nim::Prim(p)) if p == "string" => a.code.clone(),
4780 _ => format!("rsDisplay({})", a.code),
4781 };
4782 (format!("result.add({})", text), Some(Nim::Unit))
4783 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago4784 "saturating_add" | "saturating_sub" | "saturating_mul" | "checked_add"
4785 | "checked_sub" | "checked_mul" => {
4786 let t = rt
4787 .clone()
4788 .filter(|t| t.is_integer())
4789 .ok_or_else(|| format!("`{name}` needs a known integer receiver"))?;
4790 let arg = args
4791 .first()
4792 .ok_or_else(|| format!("`{name}` takes one argument"))?;
4793 let f = match name.as_str() {
4794 "saturating_add" => "rsSatAdd",
4795 "saturating_sub" => "rsSatSub",
4796 "saturating_mul" => "rsSatMul",
4797 "checked_add" => "rsChkAdd",
4798 "checked_sub" => "rsChkSub",
4799 _ => "rsChkMul",
4800 };
4801 let out = if name.starts_with("checked") {
4802 Nim::Named("Option".into(), vec![t])
4803 } else {
4804 t
4805 };
4806 (format!("{}({}, {})", f, recv.code, arg.code), Some(out))
4807 }
Lower `extern "C"` blocks to Nim importc; do not transpile libc 7db7991 nandithebull 6h ago4808 // `as_ptr` hands a C function the address of the first element,
4809 // which is what Rust's does. An empty slice has no first element
4810 // in either language, and reading through the pointer would be
4811 // undefined in both.
4812 "as_ptr" | "as_mut_ptr" => {
4813 let elem = elem_of(&rt)
4814 .ok_or("`as_ptr` needs a known element type")?;
4815 (
4816 format!(
4817 "(if {r}.len == 0: nil else: cast[ptr {e}](addr {r}[0]))",
4818 r = recv.code,
4819 e = elem.render()
4820 ),
4821 Some(Nim::Ptr(Box::new(elem))),
4822 )
4823 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4824 "abs" => (format!("abs({})", recv.code), rt.clone()),
4825 "min" => (format!("min({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
4826 "max" => (format!("max({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
4827 "to_string" => (format!("rsDisplay({})", recv.code), Some(Nim::Prim("string".into()))),
4828 "as_bytes" | "into_bytes" => (
4829 format!("rsBytes({})", recv.code),
4830 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
4831 ),
4832
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4833 "into" => {
4834 // `.into()` resolves through the `impl From` declarations, and
4835 // needs the target type to pick one.
4836 let from = rt
4837 .clone()
4838 .ok_or("`.into()` needs a known receiver type")?;
4839 let to = expect
4840 .ok_or("`.into()` needs a known target type; annotate the binding")?;
4841 let key = (type_name(&from), type_name(to));
4842 let f = self.from_impls.get(&key).cloned().ok_or_else(|| {
4843 format!(
4844 "no `impl From<{}> for {}` in this file, so `.into()` has \
4845 no conversion to call",
4846 key.0, key.1
4847 )
4848 })?;
4849 (format!("{}({})", f, recv.code), Some(to.clone()))
4850 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4851 _ => {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4852 // A method defined in this file via `impl`, found by the
4853 // receiver's type rather than by name alone.
4854 let key = rt.as_ref().map(|t| (type_name(t), name.clone()));
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 7h ago4855 // Re-lower the arguments with the declared parameter types:
4856 // a method's own signature says what width its literals are,
4857 // which the receiver's type does not.
4858 let declared: Option<Vec<Nim>> = key
4859 .as_ref()
4860 .and_then(|k| self.methods.get(k))
4861 .map(|s| s.params.clone());
4862 if let Some(d) = &declared {
4863 // params[0] is the receiver for a method with `self`.
4864 let skip = usize::from(d.len() == m.args.len() + 1);
4865 for (i, a) in m.args.iter().enumerate() {
4866 if let Some(want) = d.get(i + skip) {
4867 let want = want.clone().unvar();
4868 args[i] = self.expr_at(a, Some(&want))?;
4869 }
4870 }
4871 }
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago4872 let mut arg_tys: Vec<Option<Nim>> = vec![recv.ty.clone()];
4873 arg_tys.extend(args.iter().map(|a| a.ty.clone()));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago4874 let sig = key
4875 .as_ref()
4876 .and_then(|k| self.methods.get(k))
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 7h ago4877 .map(|s| Self::instantiate(s, &arg_tys));
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4878 if let Some(ret) = sig {
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago4879 // Use the name the proc was actually emitted under: an
4880 // inherent method is qualified by its module, a trait
4881 // method by its trait.
4882 let nim = key
4883 .and_then(|k| self.statics.get(&k).cloned())
4884 .unwrap_or_else(|| ident(&name));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4885 let mut all = vec![recv.code.clone()];
4886 all.extend(args.iter().map(|a| a.code.clone()));
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago4887 (format!("{}({})", nim, all.join(", ")), Some(ret))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4888 } else {
4889 return Err(format!(
4890 "unsupported method `.{name}()`; it is neither defined in \
4891 this file nor part of the standard-library subset that \
4892 has a verified Nim equivalent"
4893 ));
4894 }
4895 }
4896 };
4897 Ok(Val::new(code, ty))
4898 }
4899
4900 // -------------------------------------------------------------- macros
4901
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago4902 /// The element type of a `vec![..]`, from its first element.
4903 fn vec_elem(&mut self, mac: &syn::Macro) -> Result<Option<Nim>, String> {
4904 let body = mac.tokens.to_string();
4905 if body.trim().is_empty() {
4906 return Ok(None);
4907 }
4908 let first: Option<Expr> = if body.contains(';') {
4909 // The whole body must be consumed or the parse fails, so the
4910 // length is parsed too even though only the element is wanted.
4911 mac.parse_body_with(|input: syn::parse::ParseStream| {
4912 let v: Expr = input.parse()?;
4913 input.parse::<syn::Token![;]>()?;
4914 let _len: Expr = input.parse()?;
4915 Ok(v)
4916 })
4917 .ok()
4918 } else {
4919 mac.parse_body_with(
4920 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
4921 )
4922 .ok()
4923 .and_then(|p| p.into_iter().next())
4924 };
4925 match first {
4926 Some(e) => Ok(self.expr(&e)?.ty),
4927 None => Ok(None),
4928 }
4929 }
4930
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4931 fn macro_call(&mut self, mac: &syn::Macro) -> Result<String, String> {
4932 let name = path_name(&mac.path);
4933 match name.as_str() {
4934 "println" | "print" | "eprintln" | "eprint" => {
4935 let s = self.format_args(mac)?;
4936 let nl = name.ends_with("ln");
4937 Ok(match (name.starts_with('e'), nl) {
4938 (false, true) => format!("echo {s}"),
4939 (false, false) => format!("stdout.write({s})"),
4940 (true, true) => format!("stderr.writeLine({s})"),
4941 (true, false) => format!("stderr.write({s})"),
4942 })
4943 }
4944 "format" => self.format_args(mac),
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4945 "write" | "writeln" => {
4946 // `write!(f, "..", ..)` inside a formatting impl: the first
4947 // argument is the sink, the rest is an ordinary format call.
4948 let args: Vec<Expr> = mac
4949 .parse_body_with(syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated)
4950 .map_err(|e| format!("write!: {e}"))?
4951 .into_iter()
4952 .collect();
4953 let sink = args.first().ok_or("`write!` needs a sink")?;
4954 if !self.is_fmt_param(sink) {
4955 return Err("`write!` to anything but the `Formatter` of the \
4956 enclosing formatting impl is not implemented"
4957 .into());
4958 }
4959 let s = self.format_pieces(&args[1..])?;
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago4960 let s = if name == "writeln" {
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4961 format!("({} & \"\\n\")", s)
4962 } else {
4963 s
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago4964 };
4965 Ok(format!("result.add({})", s))
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago4966 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago4967 "panic" => {
4968 let s = self.format_args(mac)?;
4969 Ok(format!("rsPanic({s})"))
4970 }
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago4971 // `debug_assert*` fires in debug builds, which is the profile
4972 // this project models, so it lowers the same as `assert*`.
4973 "assert" | "debug_assert" => {
4974 let args: Vec<Expr> = mac
4975 .parse_body_with(
4976 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
4977 )
4978 .map_err(|e| format!("{name}!: {e}"))?
4979 .into_iter()
4980 .collect();
4981 let cond = args.first().ok_or("`assert!` needs a condition")?;
4982 let v = self.expr(cond)?;
4983 let msg = if args.len() > 1 {
4984 self.format_pieces(&args[1..])?
4985 } else {
4986 fmt::nim_str("assertion failed")
4987 };
4988 Ok(format!("(if not ({}): rsPanic({}))", v.code, msg))
4989 }
4990 "assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne" => {
4991 let args: Vec<Expr> = mac
4992 .parse_body_with(
4993 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
4994 )
4995 .map_err(|e| format!("{name}!: {e}"))?
4996 .into_iter()
4997 .collect();
4998 if args.len() < 2 {
4999 return Err(format!("`{name}!` takes two operands"));
5000 }
5001 let a = self.expr(&args[0])?;
5002 let b = self.expr_at(&args[1], a.ty.as_ref())?;
5003 let ne = name.ends_with("_ne");
5004 let op = if ne { "!=" } else { "==" };
5005 // Rust's message shows both sides; reproducing it keeps a
5006 // failing assertion as informative as the original.
5007 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 10h ago5008 Ok(format!(
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago5009 "(if not (({}) {} ({})): rsPanic({} & \"\\n left: \" & rsDebug({}) & \"\\n right: \" & rsDebug({})))",
5010 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 10h ago5011 ))
5012 }
Lower the `log` facade, and add explicit enum discriminants 12c0a01 nandithebull 6h ago5013 // The `log` facade. See `src/prelude.nim` for why these are
5014 // lowered directly rather than expanded. The enabled check wraps
5015 // the whole thing because Rust does not evaluate a log record's
5016 // arguments when the level is disabled.
5017 "error" | "warn" | "info" | "debug" | "trace" | "log" => {
5018 let args: Vec<Expr> = mac
5019 .parse_body_with(
5020 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
5021 )
5022 .map_err(|e| format!("`{name}!`: {e}"))?
5023 .into_iter()
5024 .collect();
5025 let (level, rest) = if name == "log" {
5026 let first = args.first().ok_or("`log!` needs a level")?;
5027 (self.log_level_of(first)?, &args[1..])
5028 } else {
5029 (
5030 match name.as_str() {
5031 "error" => "rsLvlError",
5032 "warn" => "rsLvlWarn",
5033 "info" => "rsLvlInfo",
5034 "debug" => "rsLvlDebug",
5035 _ => "rsLvlTrace",
5036 }
5037 .to_string(),
5038 &args[..],
5039 )
5040 };
5041 let msg = self.format_pieces(rest)?;
5042 let target = fmt::nim_str(&self.cur_mod.clone());
5043 Ok(format!(
5044 "(if rsLogEnabled({lvl}): rsLog({lvl}, {target}, {msg}))",
5045 lvl = level
5046 ))
5047 }
5048 "log_enabled" => {
5049 let e: Expr = mac
5050 .parse_body()
5051 .map_err(|e| format!("`log_enabled!`: {e}"))?;
5052 let l = self.log_level_of(&e)?;
5053 Ok(format!("rsLogEnabled({l})"))
5054 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5055 "vec" => {
5056 let body = mac.tokens.to_string();
5057 if body.trim().is_empty() {
5058 return Ok("@[]".into());
5059 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago5060 // `vec![elem; n]` is the repeat form, not a list. The macro
5061 // body has no brackets, so it is parsed directly.
5062 if body.contains(';') {
5063 let (v, n) = mac
5064 .parse_body_with(|input: syn::parse::ParseStream| {
5065 let v: Expr = input.parse()?;
5066 input.parse::<syn::Token![;]>()?;
5067 let n: Expr = input.parse()?;
5068 Ok((v, n))
5069 })
5070 .map_err(|e| format!("vec![elem; n]: {e}"))?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago5071 let want = self.vec_expect.clone();
5072 let v = self.expr_at(&v, want.as_ref())?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago5073 let n = self.expr(&n)?;
5074 return Ok(format!("newSeqWith(int({}), {})", n.code, v.code));
5075 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5076 let elems: syn::punctuated::Punctuated<Expr, syn::Token![,]> = mac
5077 .parse_body_with(syn::punctuated::Punctuated::parse_terminated)
5078 .map_err(|e| format!("vec!: {e}"))?;
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago5079 let want = self.vec_expect.clone();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5080 let mut parts = Vec::new();
5081 for e in &elems {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago5082 parts.push(self.expr_at(e, want.as_ref())?.code);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5083 }
5084 Ok(format!("@[{}]", parts.join(", ")))
5085 }
Expand `macro_rules!` rather than translating it to a Nim template 04eb29f nandithebull 6h ago5086 other => {
5087 if let Some(why) = self.mrules_bad.get(other) {
5088 return Err(format!("`{other}!` cannot be expanded: {why}"));
5089 }
5090 if let Some(def) = self.mrules.get(other).cloned() {
Expand multi-rule and recursive macro_rules d459281 nandithebull 5h ago5091 // A multi-rule macro commonly recurses, shedding one
5092 // argument per step. The depth limit turns a macro that
5093 // does not terminate into an error rather than a hang.
5094 if self.macro_depth > 64 {
5095 return Err(format!(
5096 "`{other}!` expanded more than 64 levels deep; it \
5097 does not appear to terminate"
5098 ));
5099 }
Expand `macro_rules!` rather than translating it to a Nim template 04eb29f nandithebull 6h ago5100 let expanded = def
5101 .expand(mac.tokens.clone())
5102 .map_err(|e| format!("expanding `{other}!`: {e}"))?;
5103 // The expansion is ordinary Rust, lowered in a context
5104 // where its types are known.
5105 let e: Expr = syn::parse2(expanded.clone()).map_err(|_| {
5106 format!(
5107 "`{other}!` expands to something that is not an \
5108 expression: `{}`",
5109 expanded
5110 )
5111 })?;
Expand multi-rule and recursive macro_rules d459281 nandithebull 5h ago5112 self.macro_depth += 1;
5113 let r = self.expr(&e);
5114 self.macro_depth -= 1;
5115 return Ok(r?.code);
Expand `macro_rules!` rather than translating it to a Nim template 04eb29f nandithebull 6h ago5116 }
5117 Err(format!(
5118 "unsupported macro `{other}!`; a macro whose expansion is not \
5119 known cannot be lowered faithfully"
5120 ))
5121 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5122 }
5123 }
5124
5125 /// `println!("{} {}", a, b)` -> a Nim string-concatenation expression.
5126 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 9h ago5127 let args: Vec<Expr> = mac
5128 .parse_body_with(syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated)
5129 .map_err(|e| format!("format arguments: {e}"))?
5130 .into_iter()
5131 .collect();
5132 self.format_pieces(&args)
5133 }
5134
5135 /// `["{} {}", a, b]` -> a Nim string-concatenation expression.
5136 fn format_pieces(&mut self, args: &[Expr]) -> Result<String, String> {
5137 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 10h ago5138 if args.is_empty() {
5139 return Ok("\"\"".into());
5140 }
5141 return Err("the first argument must be a literal format string".into());
5142 };
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago5143 let rest: Vec<&Expr> = args[1..].iter().collect();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5144
5145 let pieces = fmt::parse(&s.value())?;
5146 let mut parts: Vec<String> = Vec::new();
5147 let mut next = 0usize;
5148 let mut used = vec![false; rest.len()];
5149 for p in &pieces {
5150 match p {
5151 fmt::Piece::Lit(l) => parts.push(fmt::nim_str(l)),
5152 fmt::Piece::Arg { r#ref, spec } => {
5153 let v = match r#ref {
5154 fmt::Ref::Next => {
5155 let e = rest.get(next).ok_or("too few arguments for format string")?;
5156 used[next] = true;
5157 next += 1;
5158 self.expr(e)?
5159 }
5160 fmt::Ref::Index(i) => {
5161 let e = rest.get(*i).ok_or("format index out of range")?;
5162 used[*i] = true;
5163 self.expr(e)?
5164 }
5165 fmt::Ref::Named(n) => {
5166 let t = self.lookup(n).ok_or_else(|| {
5167 format!("`{{{n}}}` captures `{n}`, which is not in scope")
5168 })?;
5169 Val::new(ident(n), Some(t))
5170 }
5171 };
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 9h ago5172 let integer = v.ty.as_ref().is_some_and(|t| t.is_integer());
5173 if spec.radix.is_some() && !integer && v.ty.is_none() {
5174 return Err(
5175 "a radix format (`{:x}`, `{:b}`, ...) needs a known \
5176 argument type: on an integer it formats the bit \
5177 pattern, on anything else it calls that type's own \
5178 impl"
5179 .into(),
5180 );
5181 }
5182 parts.push(fmt::render_arg(&v.code, spec, integer));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5183 }
5184 }
5185 }
5186 // Rust rejects an argument that no `{}` consumes; so do we, rather
5187 // than dropping it from the output.
5188 if let Some(i) = used.iter().position(|u| !u) {
5189 return Err(format!(
5190 "argument {} is never used by the format string",
5191 i + 1
5192 ));
5193 }
5194 Ok(if parts.is_empty() { "\"\"".into() } else { parts.join(" & ") })
5195 }
5196}
5197
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago5198/// Whether a pattern introduces a binding.
5199fn binds(p: &Pat) -> bool {
5200 match p {
5201 Pat::Ident(_) => true,
5202 Pat::Guard(g) => binds(&g.pat),
5203 Pat::Paren(x) => binds(&x.pat),
5204 Pat::Reference(r) => binds(&r.pat),
5205 Pat::Or(o) => o.cases.iter().any(binds),
5206 Pat::TupleStruct(t) => t.elems.iter().any(|_| true),
5207 Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_) => true,
5208 _ => false,
5209 }
5210}
5211
5212/// Whether a pattern looks inside the value, which a Nim `case` cannot do.
5213fn destructures(p: &Pat) -> bool {
5214 matches!(
5215 p,
5216 Pat::TupleStruct(_) | Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_)
5217 ) || matches!(p, Pat::Guard(g) if destructures(&g.pat))
5218 || matches!(p, Pat::Paren(x) if destructures(&x.pat))
5219 || matches!(p, Pat::Reference(r) if destructures(&r.pat))
5220}
5221
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5222/// Whether an expression has a direct Nim expression form.
5223///
5224/// Nim's `if` is an expression only when every arm is a single expression, and
5225/// its `case` is never one here. Anything else has to be lowered as statements
5226/// that assign into a target.
5227fn expressible(e: &Expr) -> bool {
5228 match e {
5229 Expr::If(i) => {
5230 let Some(then) = single_expr(&i.then_branch) else { return false };
5231 if !expressible(then) {
5232 return false;
5233 }
5234 match &i.else_branch {
5235 None => false,
5236 Some((_, els)) => match &**els {
5237 Expr::Block(b) => single_expr(&b.block).is_some_and(expressible),
5238 other => expressible(other),
5239 },
5240 }
5241 }
Lower `extern "C"` blocks to Nim importc; do not transpile libc 7db7991 nandithebull 6h ago5242 // `unsafe { .. }` is transparent, so it is an expression exactly when
5243 // its block is one.
5244 Expr::Unsafe(u) => single_expr(&u.block).is_some_and(expressible),
Expand `$(..)` repetition in macro_rules 3d4a7d2 nandithebull 6h ago5245 Expr::Block(b) => {
5246 b.label.is_none() && matches!(b.block.stmts.last(), Some(Stmt::Expr(_, None)))
5247 }
5248 Expr::Match(_) | Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => false,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5249 _ => true,
5250 }
5251}
5252
5253/// The single expression a block consists of, if that is all it is. An `if`
5254/// can only be lowered as a Nim `if`-expression when both arms are this shape.
5255fn single_expr(b: &syn::Block) -> Option<&Expr> {
5256 match (b.stmts.len(), b.stmts.first()) {
5257 (1, Some(Stmt::Expr(e, None))) => Some(e),
5258 _ => None,
5259 }
5260}
5261
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago5262/// Substitute `params[i] -> args[i]` through a type. Enough of the type
5263/// grammar is covered to expand the aliases we accept; anything else is left
5264/// alone and will be reported by `ty::map` if it is unsupported.
5265fn substitute(t: &syn::Type, params: &[String], args: &[syn::Type]) -> syn::Type {
5266 use syn::Type;
5267 match t {
5268 Type::Path(p) => {
5269 if p.qself.is_none() && p.path.segments.len() == 1 {
5270 let seg = &p.path.segments[0];
5271 if seg.arguments.is_empty() {
5272 let name = seg.ident.to_string();
5273 if let Some(i) = params.iter().position(|x| *x == name) {
5274 return args[i].clone();
5275 }
5276 }
5277 }
5278 let mut p = p.clone();
5279 for seg in &mut p.path.segments {
5280 if let syn::PathArguments::AngleBracketed(a) = &mut seg.arguments {
5281 for g in &mut a.args {
5282 if let syn::GenericArgument::Type(t) = g {
5283 *t = substitute(t, params, args);
5284 }
5285 }
5286 }
5287 }
5288 Type::Path(p)
5289 }
5290 Type::Reference(r) => {
5291 let mut r = r.clone();
5292 r.elem = Box::new(substitute(&r.elem, params, args));
5293 Type::Reference(r)
5294 }
5295 Type::Slice(sl) => {
5296 let mut sl = sl.clone();
5297 sl.elem = Box::new(substitute(&sl.elem, params, args));
5298 Type::Slice(sl)
5299 }
5300 Type::Array(a) => {
5301 let mut a = a.clone();
5302 a.elem = Box::new(substitute(&a.elem, params, args));
5303 Type::Array(a)
5304 }
5305 Type::Tuple(tp) => {
5306 let mut tp = tp.clone();
5307 tp.elems = tp.elems.iter().map(|e| substitute(e, params, args)).collect();
5308 Type::Tuple(tp)
5309 }
5310 Type::Paren(p) => substitute(&p.elem, params, args),
5311 Type::Group(g) => substitute(&g.elem, params, args),
5312 other => other.clone(),
5313 }
5314}
5315
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5316// --------------------------------------------------------------- utilities
5317
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago5318/// Whether a return type is a borrow of one of the arguments, which Nim
5319/// models with a view rather than with an owned copy.
5320fn returns_borrow(t: &syn::Type) -> bool {
5321 match t {
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago5322 syn::Type::Reference(r) => match &*r.elem {
5323 syn::Type::Slice(_) => true,
5324 // `&str` is a borrow of someone else's bytes too, and returning it
5325 // means returning a view, not an owned string.
5326 syn::Type::Path(p) => p.path.is_ident("str"),
5327 _ => false,
5328 },
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago5329 syn::Type::Paren(p) => returns_borrow(&p.elem),
5330 syn::Type::Group(g) => returns_borrow(&g.elem),
5331 _ => false,
5332 }
5333}
5334
Add closures and unsafe; base16ct's lower.rs and upper.rs go through 0a375d8 nandithebull 9h ago5335/// The module a `use` prefix names. `crate`, `self` and `super` all resolve
5336/// to the crate root, which is where a flattened module's items live unless
5337/// they came from one of the extra input files.
5338fn module_of(prefix: &[String]) -> String {
5339 match prefix.last() {
5340 Some(m) if m != "crate" && m != "self" && m != "super" => m.clone(),
5341 _ => String::new(),
5342 }
5343}
5344
5345/// The first type argument of an `Option[T]` / `Result[T, E]`.
5346fn elem_arg(t: &Nim) -> Nim {
5347 match t {
5348 Nim::Named(_, a) if !a.is_empty() => a[0].clone(),
5349 other => other.clone(),
5350 }
5351}
5352
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago5353/// The element type of a sequence-like Nim type.
5354fn elem_of(t: &Option<Nim>) -> Option<Nim> {
5355 match t {
5356 Some(Nim::Seq(e)) | Some(Nim::OpenArray(e)) | Some(Nim::Array(_, e)) => Some((**e).clone()),
5357 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
5358 _ => None,
5359 }
5360}
5361
5362/// The short name a Nim type is known by, for keying method tables.
5363fn type_name(t: &Nim) -> String {
5364 match t {
5365 Nim::Named(n, _) => n.clone(),
5366 Nim::Prim(p) => p.clone(),
5367 other => other.render(),
5368 }
5369}
5370
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago5371/// `(trait, operator)` for every operator trait we dispatch.
5372const OPERATOR_TRAITS: &[(&str, &str)] = &[
5373 ("Add", "+"), ("Sub", "-"), ("Mul", "*"), ("Div", "/"), ("Rem", "%"),
5374 ("BitAnd", "&"), ("BitOr", "|"), ("BitXor", "^"), ("Shl", "<<"), ("Shr", ">>"),
5375 ("AddAssign", "+="), ("SubAssign", "-="), ("MulAssign", "*="), ("DivAssign", "/="),
5376 ("RemAssign", "%="), ("BitAndAssign", "&="), ("BitOrAssign", "|="),
5377 ("BitXorAssign", "^="), ("ShlAssign", "<<="), ("ShrAssign", ">>="),
5378 ("Neg", "neg"), ("Not", "not"),
5379];
5380
5381/// `(operator, trait method name)`.
5382const OP_METHOD: &[(&str, &str)] = &[
5383 ("+", "add"), ("-", "sub"), ("*", "mul"), ("/", "div"), ("%", "rem"),
5384 ("&", "bitand"), ("|", "bitor"), ("^", "bitxor"), ("<<", "shl"), (">>", "shr"),
5385 ("+=", "add_assign"), ("-=", "sub_assign"), ("*=", "mul_assign"),
5386 ("/=", "div_assign"), ("%=", "rem_assign"), ("&=", "bitand_assign"),
5387 ("|=", "bitor_assign"), ("^=", "bitxor_assign"), ("<<=", "shl_assign"),
5388 (">>=", "shr_assign"), ("neg", "neg"), ("not", "not"),
5389];
5390
5391fn op_method(op: &str) -> &'static str {
5392 OP_METHOD.iter().find(|(o, _)| *o == op).map(|(_, m)| *m).unwrap_or("")
5393}
5394
5395/// The operator symbol a compound assignment applies.
5396fn compound_symbol(op: &BinOp) -> &'static str {
5397 match op {
5398 BinOp::AddAssign(_) => "+=",
5399 BinOp::SubAssign(_) => "-=",
5400 BinOp::MulAssign(_) => "*=",
5401 BinOp::DivAssign(_) => "/=",
5402 BinOp::RemAssign(_) => "%=",
5403 BinOp::BitAndAssign(_) => "&=",
5404 BinOp::BitOrAssign(_) => "|=",
5405 BinOp::BitXorAssign(_) => "^=",
5406 BinOp::ShlAssign(_) => "<<=",
5407 BinOp::ShrAssign(_) => ">>=",
5408 _ => "",
5409 }
5410}
5411
5412fn binary_symbol(op: &BinOp) -> &'static str {
5413 match op {
5414 BinOp::Add(_) => "+",
5415 BinOp::Sub(_) => "-",
5416 BinOp::Mul(_) => "*",
5417 BinOp::Div(_) => "/",
5418 BinOp::Rem(_) => "%",
5419 BinOp::BitAnd(_) => "&",
5420 BinOp::BitOr(_) => "|",
5421 BinOp::BitXor(_) => "^",
5422 BinOp::Shl(_) => "<<",
5423 BinOp::Shr(_) => ">>",
5424 _ => "",
5425 }
5426}
5427
5428/// The operator a trait overloads, if it is one of the operator traits.
5429fn operator_trait(t: &str) -> Option<&'static str> {
5430 Some(match t {
5431 "Add" => "+",
5432 "Sub" => "-",
5433 "Mul" => "*",
5434 "Div" => "/",
5435 "Rem" => "%",
5436 "BitAnd" => "&",
5437 "BitOr" => "|",
5438 "BitXor" => "^",
5439 "Shl" => "<<",
5440 "Shr" => ">>",
5441 "AddAssign" => "+=",
5442 "SubAssign" => "-=",
5443 "MulAssign" => "*=",
5444 "DivAssign" => "/=",
5445 "RemAssign" => "%=",
5446 "BitAndAssign" => "&=",
5447 "BitOrAssign" => "|=",
5448 "BitXorAssign" => "^=",
5449 "ShlAssign" => "<<=",
5450 "ShrAssign" => ">>=",
5451 "Neg" => "neg",
5452 "Not" => "not",
5453 _ => return None,
5454 })
5455}
5456
5457/// The Nim proc name for a trait method, qualified by trait and type so that
5458/// two traits declaring the same method name cannot collide.
5459fn trait_method_name(ty: &str, tr: &str, m: &str) -> String {
5460 format!("rs{}_{}_{}", tr, ty, m)
5461}
5462
Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 9h ago5463fn is_fmt_trait(t: &str) -> bool {
5464 matches!(t, "Display" | "Debug" | "LowerHex" | "UpperHex" | "Binary" | "Octal")
5465}
5466
5467/// The prelude proc a formatting trait's output is produced by.
5468fn fmt_proc(t: &str) -> &'static str {
5469 match t {
5470 "Display" => "rsDisplay",
5471 "Debug" => "rsDebug",
5472 "LowerHex" => "rsLowerHex",
5473 "UpperHex" => "rsUpperHex",
5474 "Binary" => "rsBinary",
5475 _ => "rsOctal",
5476 }
5477}
5478
Transpile a second crate, adler2, to test whether any of this generalises 5fdd5be nandithebull 8h ago5479/// Whether an expression is an iterator-producing chain rather than a value.
5480fn is_iterator_expr(e: &Expr) -> bool {
5481 match e {
5482 Expr::MethodCall(m) => matches!(
5483 m.method.to_string().as_str(),
5484 "iter" | "iter_mut" | "into_iter" | "enumerate" | "zip" | "chunks_exact"
5485 | "chunks_exact_mut" | "windows"
5486 ),
5487 Expr::Paren(p) => is_iterator_expr(&p.expr),
5488 _ => false,
5489 }
5490}
5491
Prove byte-identity for base16ct by enumerating whole input domains 99b8376 nandithebull 8h ago5492/// Whether an expression denotes a place -- a variable, a field, or an index
5493/// or slice of one -- and so may be re-evaluated with no side effect.
5494fn is_pure_place(e: &Expr) -> bool {
5495 match e {
5496 Expr::Path(_) => true,
5497 Expr::Field(f) => is_pure_place(&f.base),
5498 Expr::Index(i) => {
5499 is_pure_place(&i.expr)
5500 && match &*i.index {
5501 Expr::Range(r) => {
5502 r.start.as_deref().map_or(true, is_pure_place)
5503 && r.end.as_deref().map_or(true, is_pure_place)
5504 }
5505 other => is_pure_place(other),
5506 }
5507 }
5508 Expr::Lit(_) => true,
5509 Expr::Reference(r) => is_pure_place(&r.expr),
5510 Expr::Paren(p) => is_pure_place(&p.expr),
5511 Expr::Group(g) => is_pure_place(&g.expr),
5512 // Arithmetic on places is still side-effect free, so a bound like
5513 // `..want - 1` does not stop the binding being an alias.
5514 Expr::Binary(b) if !is_compound(&b.op) => {
5515 is_pure_place(&b.left) && is_pure_place(&b.right)
5516 }
5517 Expr::Unary(u) => is_pure_place(&u.expr),
5518 Expr::Cast(c) => is_pure_place(&c.expr),
5519 _ => false,
5520 }
5521}
5522
5523/// Whether an expression is a `&mut` borrow, directly or through parens.
5524fn is_mut_borrow(e: &Expr) -> bool {
5525 match e {
5526 Expr::Reference(r) => r.mutability.is_some(),
5527 Expr::Paren(p) => is_mut_borrow(&p.expr),
5528 Expr::Group(g) => is_mut_borrow(&g.expr),
5529 _ => false,
5530 }
5531}
5532
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5533fn takes_self(sig: &syn::Signature) -> bool {
5534 matches!(sig.inputs.first(), Some(FnArg::Receiver(_)))
5535}
5536
5537fn path_name(p: &syn::Path) -> String {
5538 p.segments
5539 .last()
5540 .map(|s| s.ident.to_string())
5541 .unwrap_or_default()
5542}
5543
5544fn is_compound(op: &BinOp) -> bool {
5545 matches!(
5546 op,
5547 BinOp::AddAssign(_)
5548 | BinOp::SubAssign(_)
5549 | BinOp::MulAssign(_)
5550 | BinOp::DivAssign(_)
5551 | BinOp::RemAssign(_)
5552 | BinOp::BitAndAssign(_)
5553 | BinOp::BitOrAssign(_)
5554 | BinOp::BitXorAssign(_)
5555 | BinOp::ShlAssign(_)
5556 | BinOp::ShrAssign(_)
5557 )
5558}
5559
5560/// The Nim literal suffix for an integer type (`5'i32`).
5561fn nim_suffix(t: &Nim) -> Result<&'static str, String> {
5562 let Nim::Prim(p) = t else {
5563 return Err("not a primitive integer".into());
5564 };
5565 Ok(match p.as_str() {
5566 "int8" => "i8",
5567 "int16" => "i16",
5568 "int32" => "i32",
5569 "int64" => "i64",
5570 "int" => "i",
5571 "uint8" => "u8",
5572 "uint16" => "u16",
5573 "uint32" => "u32",
5574 "uint64" => "u64",
5575 "uint" => "u",
5576 other => return Err(format!("no Nim literal suffix for `{other}`")),
5577 })
5578}
5579
5580/// The unsigned integer type of the same width, used to spell `wrapping_*`.
5581fn unsigned_peer(t: &Nim) -> Result<&'static str, String> {
5582 let Nim::Prim(p) = t else {
5583 return Err("not a primitive integer".into());
5584 };
5585 Ok(match p.as_str() {
5586 "int8" => "uint8",
5587 "int16" => "uint16",
5588 "int32" => "uint32",
5589 "int64" => "uint64",
5590 "int" => "uint",
5591 other => return Err(format!("`{other}` has no unsigned peer")),
5592 })
5593}
5594
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 10h ago5595fn quote_meta(m: &syn::Meta) -> String {
5596 match m {
5597 syn::Meta::Path(p) => path_name(p),
5598 syn::Meta::List(l) => format!("{}(..)", path_name(&l.path)),
5599 syn::Meta::NameValue(nv) => format!("{} = ..", path_name(&nv.path)),
5600 }
5601}
5602
5603fn item_attrs(i: &Item) -> &[syn::Attribute] {
5604 match i {
5605 Item::Fn(f) => &f.attrs,
5606 Item::Struct(s) => &s.attrs,
5607 Item::Enum(e) => &e.attrs,
5608 Item::Impl(x) => &x.attrs,
5609 Item::Const(c) => &c.attrs,
5610 Item::Type(t) => &t.attrs,
5611 Item::Mod(m) => &m.attrs,
5612 Item::Use(u) => &u.attrs,
5613 Item::ExternCrate(e) => &e.attrs,
5614 Item::Static(s) => &s.attrs,
5615 _ => &[],
5616 }
5617}
5618
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 10h ago5619fn item_kind(i: &Item) -> &'static str {
5620 match i {
5621 Item::Trait(_) => "`trait`",
5622 Item::Static(_) => "`static`",
5623 Item::Macro(_) => "macro definition",
5624 Item::Union(_) => "`union`",
5625 _ => "item",
5626 }
5627}
5628
5629fn expr_kind(e: &Expr) -> &'static str {
5630 match e {
5631 Expr::Async(_) => "`async` block",
5632 Expr::Await(_) => "`.await`",
5633 Expr::Try(_) => "`?`",
5634 Expr::Range(_) => "range",
5635 Expr::Match(_) => "`match` (only statement position is implemented)",
5636 Expr::Let(_) => "`let` expression",
5637 Expr::Unsafe(_) => "`unsafe` block",
5638 Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => "loop (has no value in Nim)",
5639 _ => "expression",
5640 }
5641}