nandi/rustnimpublic Fork 0
b0ccd80a849033974bea0c5eccff995ecb632c3e
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 · 2535 lines · 101.6 KBRust Blame HistoryRaw
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1//! Rust AST -> Nim source.
2//!
3//! The governing rule is in DESIGN.md and it shapes every function here:
4//! anything whose Rust semantics cannot be reproduced exactly in Nim returns
5//! `Err` with a reason. Nothing is emitted on a guess. Where a construct maps
6//! one-to-one (signed `shr`, unsigned wrapping, truncating `div`/`mod`) the
7//! mapping is direct and there is a comment saying why that is safe.
8
9use crate::fmt;
10use crate::ty::{self, Nim};
11use std::collections::HashMap;
12use syn::{
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago13 BinOp, Expr, FnArg, GenericArgument, Item, Lit, Local, Pat, ReturnType, Stmt, UnOp,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago14};
15
16// --------------------------------------------------------------- vocabulary
17
18/// Nim keywords. Rust code may legally use any of these as an identifier.
19const NIM_KEYWORDS: &[&str] = &[
20 "addr", "and", "as", "asm", "bind", "block", "break", "case", "cast",
21 "concept", "const", "continue", "converter", "defer", "discard", "distinct",
22 "div", "do", "elif", "else", "end", "enum", "except", "export", "finally",
23 "for", "from", "func", "if", "import", "in", "include", "interface", "is",
24 "isnot", "iterator", "let", "macro", "method", "mixin", "mod", "nil", "not",
25 "notin", "object", "of", "or", "out", "proc", "ptr", "raise", "ref",
26 "return", "shl", "shr", "static", "template", "try", "tuple", "type",
27 "using", "var", "when", "while", "xor", "result", "echo",
28];
29
30fn ident(name: &str) -> String {
31 if NIM_KEYWORDS.contains(&name) {
32 format!("{name}_r")
33 } else {
34 name.to_string()
35 }
36}
37
38/// A lowered expression: its Nim text, and its type where we know it.
39///
40/// The type is not decoration. Nim needs it to pick `div` over `/`, to size a
41/// `cast`, and to annotate every binding so that Nim's own type checker
42/// catches a mistake in this file rather than letting it through as output
43/// that runs and is wrong.
44#[derive(Clone, Debug)]
45struct Val {
46 code: String,
47 ty: Option<Nim>,
48}
49
50impl Val {
51 fn new(code: impl Into<String>, ty: Option<Nim>) -> Self {
52 Val { code: code.into(), ty }
53 }
54 fn untyped(code: impl Into<String>) -> Self {
55 Val { code: code.into(), ty: None }
56 }
57}
58
59struct Sig {
60 params: Vec<Nim>,
61 ret: Nim,
62}
63
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago64/// One variant of a Rust enum.
65#[derive(Clone)]
66struct Variant {
67 name: String,
68 /// `(nim field name, type)`. Empty for a unit variant. Tuple variants get
69 /// `f0`, `f1`, ...; every field is prefixed with the variant name because
70 /// Nim requires the branches of a variant object to have distinct fields.
71 fields: Vec<(String, Nim)>,
72}
73
74#[derive(Clone)]
75struct EnumDef {
76 name: String,
77 /// True when every variant is a unit variant, which Nim represents as a
78 /// plain `enum` rather than an object variant.
79 simple: bool,
80 variants: Vec<Variant>,
81}
82
83impl EnumDef {
84 fn kind_ident(&self, v: &str) -> String {
85 format!("k{}{}", self.name, v)
86 }
87 fn ctor_ident(&self, v: &str) -> String {
88 format!("{}{}", self.name, v)
89 }
90 fn get(&self, v: &str) -> Option<&Variant> {
91 self.variants.iter().find(|x| x.name == v)
92 }
93}
94
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago95pub struct Lowerer {
96 out: String,
97 indent: usize,
98 scopes: Vec<HashMap<String, Nim>>,
99 fns: HashMap<String, Sig>,
100 /// struct name -> (field, type)
101 structs: HashMap<String, Vec<(String, Nim)>>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago102 enums: HashMap<String, EnumDef>,
103 /// variant name -> enums declaring it. A variant named by more than one
104 /// enum must be written qualified, or it is rejected as ambiguous.
105 variant_owner: HashMap<String, Vec<String>>,
106 /// `type X<T> = ...`, expanded before any type is mapped.
107 aliases: HashMap<String, (Vec<String>, syn::Type)>,
108 /// Cargo features that are on, as `--cfg feature=<name>`. `#[cfg]` is
109 /// evaluated against these exactly as rustc would, so an item that is
110 /// dropped here is genuinely not part of the program being compiled.
111 pub features: Vec<String>,
112 dropped_by_cfg: usize,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago113 /// Return type of the proc being lowered, so `return e` and a trailing
114 /// expression can type their literals the way Rust's inference would.
115 ret: Option<Nim>,
116 /// `(name, type)` that the arms of the `if`/`match` being lowered as a
117 /// statement must assign their value to.
118 target: Option<(String, Option<Nim>)>,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago119 /// Set while lowering a `while` condition, which Nim re-evaluates each
120 /// iteration and so cannot have statements hoisted out of it.
121 in_loop_cond: bool,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago122 tmp: usize,
123}
124
125impl Lowerer {
126 pub fn new() -> Self {
127 Lowerer {
128 out: String::new(),
129 indent: 0,
130 scopes: vec![HashMap::new()],
131 fns: HashMap::new(),
132 structs: HashMap::new(),
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago133 enums: HashMap::new(),
134 variant_owner: HashMap::new(),
135 aliases: HashMap::new(),
136 features: Vec::new(),
137 dropped_by_cfg: 0,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago138 ret: None,
139 target: None,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago140 in_loop_cond: false,
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago141 tmp: 0,
142 }
143 }
144
145 // ------------------------------------------------------------ emission
146
147 fn line(&mut self, s: &str) {
148 for _ in 0..self.indent {
149 self.out.push_str(" ");
150 }
151 self.out.push_str(s);
152 self.out.push('\n');
153 }
154
155 fn blank(&mut self) {
156 self.out.push('\n');
157 }
158
159 fn fresh(&mut self, hint: &str) -> String {
160 self.tmp += 1;
161 format!("rsTmp{}{}", hint, self.tmp)
162 }
163
164 // --------------------------------------------------------------- scope
165
166 fn push_scope(&mut self) {
167 self.scopes.push(HashMap::new());
168 }
169 fn pop_scope(&mut self) {
170 self.scopes.pop();
171 }
172 fn bind(&mut self, name: &str, t: Nim) {
173 self.scopes.last_mut().unwrap().insert(name.to_string(), t);
174 }
175 fn lookup(&self, name: &str) -> Option<Nim> {
176 self.scopes.iter().rev().find_map(|s| s.get(name).cloned())
177 }
178
179 // ---------------------------------------------------------------- file
180
181 pub fn lower_file(&mut self, file: &syn::File) -> Result<String, String> {
182 self.out.push_str(include_str!("prelude.nim"));
183 self.blank();
184
185 // Pass 1: signatures and struct shapes, so that a call can be typed
186 // regardless of declaration order (Rust has no forward declarations).
187 for item in &file.items {
188 self.collect(item)?;
189 }
190 // Pass 2: bodies.
191 for item in &file.items {
192 self.item(item)?;
193 }
194
195 if self.fns.contains_key("main") {
196 self.blank();
197 self.line("when isMainModule:");
198 self.indent += 1;
199 self.line("try:");
200 self.line(" main()");
201 // Rust's panic exits 101 with a message on stderr. Nim's Defects
202 // exit 1. Mapping them here is what keeps the differential runner's
203 // exit-status comparison meaningful for panicking programs.
204 self.line("except RustPanic as e:");
205 self.line(" stderr.writeLine(\"thread 'main' panicked: \" & e.msg)");
206 self.line(" quit(101)");
207 self.line("except Defect as e:");
208 self.line(" stderr.writeLine(\"thread 'main' panicked: \" & e.msg)");
209 self.line(" quit(101)");
210 self.indent -= 1;
211 }
212 Ok(std::mem::take(&mut self.out))
213 }
214
215 fn collect(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago216 // A `#[cfg(..)]` item exists only under some feature set. Dropping it
217 // silently would change what the program does; picking a feature set
218 // on the user's behalf would be a guess. So it is reported, except on
219 // items that carry no runtime meaning here anyway.
220 if !self.cfg_keeps(item_attrs(item))? {
221 self.dropped_by_cfg += 1;
222 return Ok(());
223 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago224 match item {
225 Item::Fn(f) => {
226 let (params, ret) = self.signature(&f.sig)?;
227 self.fns.insert(f.sig.ident.to_string(), Sig { params, ret });
228 }
229 Item::Struct(s) => {
230 let mut fields = Vec::new();
231 for (i, f) in s.fields.iter().enumerate() {
232 let name = match &f.ident {
233 Some(id) => id.to_string(),
234 None => format!("f{i}"), // tuple struct
235 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago236 fields.push((name, self.map_ty(&f.ty)?.owned()));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago237 }
238 self.structs.insert(s.ident.to_string(), fields);
239 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago240 Item::Type(t) => {
241 let params: Vec<String> = t
242 .generics
243 .params
244 .iter()
245 .filter_map(|g| match g {
246 syn::GenericParam::Type(t) => Some(t.ident.to_string()),
247 _ => None,
248 })
249 .collect();
250 self.aliases
251 .insert(t.ident.to_string(), (params, (*t.ty).clone()));
252 }
253 Item::Enum(e) => {
254 let name = e.ident.to_string();
255 if e.generics.params.iter().any(|p| !matches!(p, syn::GenericParam::Lifetime(_))) {
256 return Err(format!("`enum {name}` is generic: not implemented yet"));
257 }
258 let mut variants = Vec::new();
259 for v in &e.variants {
260 let vname = v.ident.to_string();
261 if v.discriminant.is_some() {
262 return Err(format!(
263 "`{name}::{vname}` has an explicit discriminant; Rust's \
264 `as` on such an enum has a value this lowering does not \
265 yet preserve"
266 ));
267 }
268 let mut fields = Vec::new();
269 for (i, f) in v.fields.iter().enumerate() {
270 // Nim requires the branches of a variant object to have
271 // distinct field names, so each is prefixed.
272 let fname = match &f.ident {
273 Some(id) => format!("{vname}_{id}"),
274 None => format!("{vname}_f{i}"),
275 };
276 fields.push((fname, self.map_ty(&f.ty)?.owned()));
277 }
278 variants.push(Variant { name: vname, fields });
279 }
280 let simple = variants.iter().all(|v| v.fields.is_empty());
281 for v in &variants {
282 self.variant_owner
283 .entry(v.name.clone())
284 .or_default()
285 .push(name.clone());
286 }
287 self.enums.insert(
288 name.clone(),
289 EnumDef { name, simple, variants },
290 );
291 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago292 Item::Impl(im) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago293 let self_ty = self.map_ty(&im.self_ty)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago294 for it in &im.items {
295 if let syn::ImplItem::Fn(m) = it {
296 let (mut params, ret) = self.signature(&m.sig)?;
297 if takes_self(&m.sig) {
298 params.insert(0, self_ty.clone());
299 }
300 self.fns.insert(m.sig.ident.to_string(), Sig { params, ret });
301 }
302 }
303 }
304 _ => {}
305 }
306 Ok(())
307 }
308
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago309 /// Whether `#[cfg(..)]` keeps this item, given the enabled features.
310 ///
311 /// This is evaluation, not approximation: rustc does the same thing, and
312 /// an item whose predicate is false is not part of the compiled program.
313 /// A predicate that cannot be evaluated is reported rather than assumed.
314 fn cfg_keeps(&self, attrs: &[syn::Attribute]) -> Result<bool, String> {
315 for a in attrs {
316 if a.path().is_ident("cfg") {
317 let pred: syn::Meta = a
318 .parse_args()
319 .map_err(|e| format!("cannot parse `#[cfg(..)]`: {e}"))?;
320 if !self.cfg_eval(&pred)? {
321 return Ok(false);
322 }
323 }
324 }
325 Ok(true)
326 }
327
328 fn cfg_eval(&self, m: &syn::Meta) -> Result<bool, String> {
329 match m {
330 syn::Meta::NameValue(nv) if nv.path.is_ident("feature") => {
331 let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
332 return Err("`feature = ..` expects a string".into());
333 };
334 Ok(self.features.iter().any(|f| *f == s.value()))
335 }
336 syn::Meta::List(l) if l.path.is_ident("not") => {
337 let inner: syn::Meta = l.parse_args().map_err(|e| e.to_string())?;
338 Ok(!self.cfg_eval(&inner)?)
339 }
340 syn::Meta::List(l) if l.path.is_ident("all") || l.path.is_ident("any") => {
341 let items: syn::punctuated::Punctuated<syn::Meta, syn::Token![,]> = l
342 .parse_args_with(syn::punctuated::Punctuated::parse_terminated)
343 .map_err(|e| e.to_string())?;
344 let all = l.path.is_ident("all");
345 let mut acc = all;
346 for i in &items {
347 let v = self.cfg_eval(i)?;
348 acc = if all { acc && v } else { acc || v };
349 }
350 Ok(acc)
351 }
352 other => Err(format!(
353 "`#[cfg({})]` is not a predicate rustnim can evaluate; only \
354 `feature = \"..\"`, `not`, `all` and `any` are implemented",
355 quote_meta(other)
356 )),
357 }
358 }
359
360 /// Map a Rust type, expanding any `type` alias first. Every type in the
361 /// lowering goes through here rather than calling `ty::map` directly, so
362 /// an alias cannot be missed in one position and honoured in another.
363 fn map_ty(&self, t: &syn::Type) -> Result<Nim, String> {
364 ty::map(&self.expand(t, 0)?)
365 }
366
367 fn expand(&self, t: &syn::Type, depth: usize) -> Result<syn::Type, String> {
368 if depth > 16 {
369 return Err("type alias expansion did not terminate; is it cyclic?".into());
370 }
371 let syn::Type::Path(p) = t else { return Ok(t.clone()) };
372 // Only an unqualified name can be one of this file's aliases.
373 // `fmt::Result` and `core::result::Result` are different types that
374 // merely end in the same segment.
375 if p.path.segments.len() != 1 {
376 return Ok(t.clone());
377 }
378 let Some(seg) = p.path.segments.last() else { return Ok(t.clone()) };
379 let Some((params, target)) = self.aliases.get(&seg.ident.to_string()) else {
380 return Ok(t.clone());
381 };
382 let args: Vec<syn::Type> = match &seg.arguments {
383 syn::PathArguments::AngleBracketed(a) => a
384 .args
385 .iter()
386 .filter_map(|g| match g {
387 GenericArgument::Type(t) => Some(t.clone()),
388 _ => None,
389 })
390 .collect(),
391 _ => vec![],
392 };
393 if args.len() != params.len() {
394 // Flattening several files into one module can bring a crate's own
395 // alias (`type Result<T> = Result<T, Error>`) into scope at a site
396 // that meant the builtin (`Result<T, E>`). Rust kept them apart by
397 // module; here they are told apart by arity, and a use that fits
398 // neither is left for `ty::map` to report.
399 return Ok(t.clone());
400 }
401 self.expand(&substitute(target, params, &args), depth + 1)
402 }
403
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago404 fn signature(&self, sig: &syn::Signature) -> Result<(Vec<Nim>, Nim), String> {
405 if sig.asyncness.is_some() {
406 return Err(format!("`async fn {}`: Nim has no equivalent", sig.ident));
407 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago408 // Lifetime parameters carry no runtime meaning and Nim is GC'd, so
409 // `fn encode<'a>(..)` is not generic for our purposes. Type and const
410 // parameters genuinely are, and are rejected.
411 if let Some(p) = sig.generics.params.iter().find(|p| !matches!(p, syn::GenericParam::Lifetime(_))) {
412 let what = match p {
413 syn::GenericParam::Const(_) => "const",
414 _ => "type",
415 };
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago416 return Err(format!(
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago417 "`fn {}` has a {what} parameter: generics are not implemented yet",
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago418 sig.ident
419 ));
420 }
421 let mut params = Vec::new();
422 for a in &sig.inputs {
423 if let FnArg::Typed(t) = a {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago424 params.push(self.map_ty(&t.ty)?);
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago425 }
426 }
427 let ret = match &sig.output {
428 ReturnType::Default => Nim::Unit,
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago429 ReturnType::Type(_, t) => self.map_ty(t)?.owned(),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago430 };
431 Ok((params, ret))
432 }
433
434 // --------------------------------------------------------------- items
435
436 fn item(&mut self, item: &Item) -> Result<(), String> {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago437 if !self.cfg_keeps(item_attrs(item))? {
438 return Ok(());
439 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago440 match item {
441 Item::Fn(f) => self.func(&f.sig, &f.block, None),
442 Item::Struct(s) => {
443 let name = s.ident.to_string();
444 let fields = self.structs[&name].clone();
445 self.line(&format!("type {}* = object", ident(&name)));
446 self.indent += 1;
447 if fields.is_empty() {
448 self.line("discard");
449 }
450 for (fname, fty) in &fields {
451 self.line(&format!("{}*: {}", ident(fname), fty.render()));
452 }
453 self.indent -= 1;
454 self.blank();
455 Ok(())
456 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago457 Item::Type(_) => Ok(()), // expanded at every use site
458 Item::Enum(e) => {
459 let def = self.enums[&e.ident.to_string()].clone();
460 self.emit_enum(&def);
461 Ok(())
462 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago463 Item::Const(c) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago464 let t = self.map_ty(&c.ty)?.owned();
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago465 let v = self.expr(&c.expr)?;
466 self.bind(&c.ident.to_string(), t.clone());
467 let line = format!("const {}*: {} = {}", ident(&c.ident.to_string()), t.render(), v.code);
468 self.line(&line);
469 self.blank();
470 Ok(())
471 }
472 Item::Impl(im) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago473 let self_ty = self.map_ty(&im.self_ty)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago474 if im.trait_.is_some() {
475 return Err(format!(
476 "`impl Trait for {}`: trait impls are not implemented yet",
477 self_ty.render()
478 ));
479 }
480 for it in &im.items {
481 match it {
482 syn::ImplItem::Fn(m) => {
483 let recv = if takes_self(&m.sig) { Some(self_ty.clone()) } else { None };
484 self.func(&m.sig, &m.block, recv)?;
485 }
486 _ => return Err("only `fn` items are supported inside `impl`".into()),
487 }
488 }
489 Ok(())
490 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago491 // `use` and `extern crate` are resolution directives with no Nim
492 // analogue once everything is one module.
493 Item::Use(_) | Item::ExternCrate(_) => Ok(()),
494 Item::Mod(m) if m.content.is_some() => {
495 // An inline `mod` is flattened; Nim has no nested modules in a
496 // single file.
497 let items = m.content.as_ref().map(|(_, i)| i.clone()).unwrap_or_default();
498 for i in &items {
499 self.collect(i)?;
500 }
501 for i in &items {
502 self.item(i)?;
503 }
504 Ok(())
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago505 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago506 Item::Mod(m) => Err(format!(
507 "`mod {};` refers to another file; pass that file to rustnim as \
508 an additional input instead",
509 m.ident
510 )),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago511 other => Err(format!("unsupported item: {}", item_kind(other))),
512 }
513 }
514
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago515 /// `None` carries no type of its own, so Nim needs the `Option[T]` named.
516 fn none_of(&self, expect: Option<&Nim>) -> String {
517 match expect {
518 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => {
519 format!("rsNone[{}]()", a[0].render())
520 }
521 _ => "rsNone()".to_string(),
522 }
523 }
524
525 fn emit_enum(&mut self, def: &EnumDef) {
526 let name = ident(&def.name);
527 if def.simple {
528 // Every variant is a unit variant, so a plain Nim enum is an exact
529 // fit: it compares, orders and `case`-checks like Rust's.
530 self.line(&format!("type {name}* = enum"));
531 self.indent += 1;
532 for v in &def.variants {
533 self.line(&format!("{}", ident(&v.name)));
534 }
535 self.indent -= 1;
536 self.blank();
537 self.line(&format!("proc rsDebug*(x: {name}): string ="));
538 self.indent += 1;
539 self.line("case x");
540 for v in &def.variants {
541 self.line(&format!("of {}.{}: \"{}\"", name, ident(&v.name), v.name));
542 }
543 self.indent -= 1;
544 self.blank();
545 return;
546 }
547
548 // A data-carrying enum is a Nim object variant: one discriminant enum
549 // plus a branch per variant. This is the same shape the prelude uses
550 // for `Option` and `Result`.
551 self.line("type");
552 self.indent += 1;
553 self.line(&format!("{}Kind* = enum", name));
554 self.indent += 1;
555 for v in &def.variants {
556 self.line(&def.kind_ident(&v.name));
557 }
558 self.indent -= 1;
559 self.blank();
560 self.line(&format!("{}* = object", name));
561 self.indent += 1;
562 self.line(&format!("case kind*: {}Kind", name));
563 for v in &def.variants {
564 if v.fields.is_empty() {
565 self.line(&format!("of {}: discard", def.kind_ident(&v.name)));
566 } else {
567 self.line(&format!("of {}:", def.kind_ident(&v.name)));
568 self.indent += 1;
569 for (f, t) in &v.fields {
570 self.line(&format!("{}*: {}", ident(f), t.render()));
571 }
572 self.indent -= 1;
573 }
574 }
575 self.indent -= 2;
576 self.blank();
577
578 for v in &def.variants {
579 let args: Vec<String> = v
580 .fields
581 .iter()
582 .enumerate()
583 .map(|(i, (_, t))| format!("a{}: {}", i, t.render()))
584 .collect();
585 let inits: Vec<String> = v
586 .fields
587 .iter()
588 .enumerate()
589 .map(|(i, (f, _))| format!("{}: a{}", ident(f), i))
590 .collect();
591 let mut all = vec![format!("kind: {}", def.kind_ident(&v.name))];
592 all.extend(inits);
593 self.line(&format!(
594 "proc {}*({}): {} = {}({})",
595 def.ctor_ident(&v.name),
596 args.join(", "),
597 name,
598 name,
599 all.join(", ")
600 ));
601 }
602 self.blank();
603
604 self.line(&format!("proc rsDebug*(x: {name}): string ="));
605 self.indent += 1;
606 self.line("case x.kind");
607 for v in &def.variants {
608 if v.fields.is_empty() {
609 self.line(&format!("of {}: \"{}\"", def.kind_ident(&v.name), v.name));
610 } else {
611 let parts: Vec<String> = v
612 .fields
613 .iter()
614 .map(|(f, _)| format!("rsDebug(x.{})", ident(f)))
615 .collect();
616 self.line(&format!(
617 "of {}: \"{}(\" & {} & \")\"",
618 def.kind_ident(&v.name),
619 v.name,
620 parts.join(" & \", \" & ")
621 ));
622 }
623 }
624 self.indent -= 1;
625 self.blank();
626 }
627
628 /// Resolve a Rust path like `Error::InvalidLength` or a bare `InvalidLength`
629 /// to the enum that declares it.
630 fn resolve_variant(&self, path: &syn::Path) -> Option<(EnumDef, String)> {
631 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
632 let last = segs.last()?.clone();
633 if segs.len() >= 2 {
634 if let Some(def) = self.enums.get(&segs[segs.len() - 2]) {
635 if def.get(&last).is_some() {
636 return Some((def.clone(), last));
637 }
638 }
639 }
640 // Unqualified: only unambiguous if exactly one enum declares it.
641 match self.variant_owner.get(&last) {
642 Some(owners) if owners.len() == 1 => {
643 let def = self.enums.get(&owners[0])?;
644 Some((def.clone(), last))
645 }
646 _ => None,
647 }
648 }
649
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago650 fn func(
651 &mut self,
652 sig: &syn::Signature,
653 body: &syn::Block,
654 recv: Option<Nim>,
655 ) -> Result<(), String> {
656 let name = sig.ident.to_string();
657 let (ptys, ret) = self.signature(sig)?;
658
659 self.push_scope();
660 let mut rendered: Vec<String> = Vec::new();
661
662 if let Some(self_ty) = recv {
663 // `&mut self` and `mut self` both mean the body may mutate the
664 // receiver; only the former is observable by the caller, and a Nim
665 // `var` parameter is the faithful spelling of that.
666 let mutable = matches!(
667 sig.inputs.first(),
668 Some(FnArg::Receiver(r))
669 if matches!(&r.kind, syn::ReceiverKind::Reference(_, _, m) if m.is_some())
670 );
671 let t = if mutable { Nim::Var(Box::new(self_ty.clone())) } else { self_ty.clone() };
672 rendered.push(format!("self: {}", t.render()));
673 self.bind("self", self_ty);
674 }
675
676 let typed: Vec<&syn::PatType> = sig
677 .inputs
678 .iter()
679 .filter_map(|a| match a {
680 FnArg::Typed(t) => Some(t),
681 _ => None,
682 })
683 .collect();
684 for (p, t) in typed.iter().zip(ptys.iter()) {
685 let pname = match &*p.pat {
686 Pat::Ident(i) => i.ident.to_string(),
687 _ => return Err("only plain identifier parameters are supported".into()),
688 };
689 rendered.push(format!("{}: {}", ident(&pname), t.render()));
690 // Inside the body a `var T` parameter is used exactly like a `T`.
691 self.bind(&pname, t.clone().owned());
692 }
693
694 let head = if ret == Nim::Unit {
695 format!("proc {}*({}) =", ident(&name), rendered.join(", "))
696 } else {
697 format!("proc {}*({}): {} =", ident(&name), rendered.join(", "), ret.render())
698 };
699 self.line(&head);
700 self.indent += 1;
701 let outer_ret = self.ret.replace(ret.clone());
702
703 // A Rust fn's trailing expression is its return value. Naming Nim's
704 // implicit `result` as the target makes that true whether the tail is
705 // a plain expression or an `if`/`match` with statement arms.
706 let outer_target = if ret == Nim::Unit {
707 self.target.take()
708 } else {
709 self.target.replace(("result".to_string(), Some(ret.clone())))
710 };
711 let before = self.out.len();
712 let tail = self.block_body_at(body, Some(&ret))?;
713 self.target = outer_target;
714 match tail {
715 Some(v) if ret != Nim::Unit => {
716 let code = v.code.clone();
717 self.line(&format!("result = {code}"));
718 }
719 Some(v) => {
720 // A trailing expression in a `()`-returning fn is evaluated for
721 // its effect; Nim requires an explicit discard.
722 let needs_discard = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
723 if needs_discard && !v.code.is_empty() {
724 let code = v.code.clone();
725 self.line(&format!("discard {code}"));
726 }
727 }
728 None => {}
729 }
730 if self.out.len() == before {
731 self.line("discard");
732 }
733
734 self.indent -= 1;
735 self.ret = outer_ret;
736 self.pop_scope();
737 self.blank();
738 Ok(())
739 }
740
741 // ---------------------------------------------------------- statements
742
743 /// Lower a block's statements. Returns the block's trailing expression,
744 /// if it has one, *without* emitting it — the caller decides whether that
745 /// value is a return value, a binding, or discarded.
746 fn block_body(&mut self, b: &syn::Block) -> Result<Option<Val>, String> {
747 self.block_body_at(b, None)
748 }
749
750 fn block_body_at(
751 &mut self,
752 b: &syn::Block,
753 expect: Option<&Nim>,
754 ) -> Result<Option<Val>, String> {
755 // An assignment target belongs to *this* block's trailing expression
756 // only. A non-final `if` is a statement and must not assign anything.
757 let target = self.target.take();
758 let n = b.stmts.len();
759 let mut tail = None;
760 for (i, st) in b.stmts.iter().enumerate() {
761 let last = i + 1 == n;
762 match st {
763 Stmt::Expr(e, None) if last && expressible(e) => {
764 tail = Some(self.expr_at(e, expect)?)
765 }
766 Stmt::Expr(e, None) if last => {
767 // A trailing `if`/`match` with statement arms, or a loop.
768 // Lower it as statements; if this block's value is wanted,
769 // each arm assigns it.
770 match &target {
771 Some((t, ty)) => {
772 let (t, ty) = (t.clone(), ty.clone());
773 self.assign_from(e, &t, ty.as_ref())?;
774 }
775 None => self.stmt(st)?,
776 }
777 }
778 _ => self.stmt(st)?,
779 }
780 }
781 self.target = target;
782 Ok(tail)
783 }
784
785 /// Lower a block in statement position (loop bodies, `if` arms).
786 fn nested_block(&mut self, b: &syn::Block) -> Result<(), String> {
787 self.push_scope();
788 self.indent += 1;
789 let before = self.out.len();
790 let want = self.target.clone().and_then(|(_, t)| t);
791 let tail = self.block_body_at(b, want.as_ref())?;
792 self.emit_tail(tail);
793 if self.out.len() == before {
794 self.line("discard");
795 }
796 self.indent -= 1;
797 self.pop_scope();
798 Ok(())
799 }
800
801 fn stmt(&mut self, s: &Stmt) -> Result<(), String> {
802 match s {
803 Stmt::Local(l) => self.local(l),
804 Stmt::Expr(e, _) => {
805 let v = self.expr_stmt(e)?;
806 if let Some(v) = v {
807 // A bare expression with a value must be discarded in Nim.
808 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
809 let code = v.code.clone();
810 if needs {
811 self.line(&format!("discard {code}"));
812 } else if !code.is_empty() {
813 self.line(&code);
814 }
815 }
816 Ok(())
817 }
818 Stmt::Item(i) => self.item(i),
819 Stmt::Macro(m) => {
820 let line = self.macro_call(&m.mac)?;
821 self.line(&line);
822 Ok(())
823 }
824 }
825 }
826
827 fn local(&mut self, l: &Local) -> Result<(), String> {
828 let (name, mutable, ann): (String, bool, Option<Nim>) = match &l.pat {
829 Pat::Ident(i) => (i.ident.to_string(), i.mutability.is_some(), None),
830 Pat::Type(t) => match &*t.pat {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago831 Pat::Ident(i) => (i.ident.to_string(), i.mutability.is_some(), Some(self.map_ty(&t.ty)?)),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago832 _ => return Err("only `let <ident>` bindings are supported".into()),
833 },
834 Pat::Wild(_) => ("_".into(), false, None),
835 _ => return Err("destructuring `let` is not implemented yet".into()),
836 };
837
838 let Some(init) = &l.init else {
839 // `let x: T;` — Nim's `var x: T` zero-initialises, which Rust does
840 // not. Rust's own rules make reading it before assignment illegal,
841 // so the two agree on every program rustc accepts.
842 let t = ann.ok_or("`let` without an initialiser needs a type annotation")?;
843 let t = t.owned();
844 self.line(&format!("var {}: {}", ident(&name), t.render()));
845 self.bind(&name, t);
846 return Ok(());
847 };
848 if init.diverge.is_some() {
849 return Err("`let ... else` is not implemented yet".into());
850 }
851
852 if !expressible(&init.expr) && name != "_" {
853 // The initialiser is an `if`/`match` whose arms are statements.
854 // Declare first, then let each arm assign into the binding.
855 let t = ann
856 .clone()
857 .ok_or_else(|| {
858 format!(
859 "`let {name} = match/if ...` needs a type annotation: \
860 its arms are statements, so the binding must be \
861 declared before they run"
862 )
863 })?
864 .owned();
865 self.line(&format!("var {}: {}", ident(&name), t.render()));
866 self.bind(&name, t.clone());
867 let target = ident(&name);
868 return self.assign_from(&init.expr, &target, Some(&t));
869 }
870
871 let v = self.expr_at(&init.expr, ann.as_ref())?;
872 let t = match (ann, &v.ty) {
873 (Some(a), _) => a.owned(),
874 (None, Some(t)) => t.clone().owned(),
875 (None, None) => {
876 return Err(format!(
877 "cannot infer the type of `let {name}`; annotate it — \
878 guessing here would change integer width, and with it the \
879 meaning of any arithmetic on `{name}`"
880 ))
881 }
882 };
883
884 if name == "_" {
885 let code = v.code.clone();
886 self.line(&format!("discard {code}"));
887 return Ok(());
888 }
889 // Rust's immutable `let` is Nim's `let`; `let mut` is `var`. Shadowing
890 // works in both, so a re-`let` of the same name needs no rename.
891 let kw = if mutable { "var" } else { "let" };
892 let line = format!("{} {}: {} = {}", kw, ident(&name), t.render(), v.code);
893 self.line(&line);
894 self.bind(&name, t);
895 Ok(())
896 }
897
898 /// Expressions that are statements in Rust and statements in Nim too
899 /// (control flow). Returns `None` when it emitted lines itself.
900 fn expr_stmt(&mut self, e: &Expr) -> Result<Option<Val>, String> {
901 match e {
902 Expr::If(_) => {
903 self.if_stmt(e)?;
904 Ok(None)
905 }
906 Expr::While(w) => {
907 if w.label.is_some() {
908 return Err("loop labels are not implemented yet".into());
909 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago910 self.in_loop_cond = true;
911 let c = self.expr(&w.cond);
912 self.in_loop_cond = false;
913 let c = c?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago914 self.line(&format!("while {}:", c.code));
915 let saved = self.target.take();
916 self.nested_block(&w.body)?;
917 self.target = saved;
918 Ok(None)
919 }
920 Expr::Loop(l) => {
921 if l.label.is_some() {
922 return Err("loop labels are not implemented yet".into());
923 }
924 self.line("while true:");
925 let saved = self.target.take();
926 self.nested_block(&l.body)?;
927 self.target = saved;
928 Ok(None)
929 }
930 Expr::ForLoop(f) => {
931 self.for_loop(f)?;
932 Ok(None)
933 }
934 Expr::Block(b) => {
935 if b.label.is_some() {
936 return Err("block labels are not implemented yet".into());
937 }
938 self.line("block:");
939 self.nested_block(&b.block)?;
940 Ok(None)
941 }
942 Expr::Match(_) => {
943 self.match_stmt(e)?;
944 Ok(None)
945 }
946 Expr::Return(r) => {
947 match &r.expr {
948 Some(e) => {
949 let want = self.ret.clone();
950 let v = self.expr_at(e, want.as_ref())?;
951 self.line(&format!("return {}", v.code));
952 }
953 None => self.line("return"),
954 }
955 Ok(None)
956 }
957 Expr::Break(b) => {
958 if b.expr.is_some() || b.label.is_some() {
959 return Err("`break` with a value or a label is not implemented yet".into());
960 }
961 self.line("break");
962 Ok(None)
963 }
964 Expr::Continue(c) => {
965 if c.label.is_some() {
966 return Err("labelled `continue` is not implemented yet".into());
967 }
968 self.line("continue");
969 Ok(None)
970 }
971 Expr::Assign(a) => {
972 let lhs = self.expr(&a.left)?;
973 if !expressible(&a.right) {
974 let target = lhs.code.clone();
975 return self.assign_from(&a.right, &target, lhs.ty.as_ref()).map(|_| None);
976 }
977 let rhs = self.expr_at(&a.right, lhs.ty.as_ref())?;
978 self.line(&format!("{} = {}", lhs.code, rhs.code));
979 Ok(None)
980 }
981 Expr::Binary(b) if is_compound(&b.op) => {
982 let lhs = self.expr(&b.left)?;
983 // `i += 1` must widen the literal to `i`'s type, not to the
984 // i32 an unconstrained Rust literal would default to.
985 let rhs = self.expr_at(&b.right, lhs.ty.as_ref())?;
986 let op = self.bin_op(&b.op, &lhs, &rhs)?;
987 // Nim has no `shl=` etc., and `+=` on a `let` is illegal in
988 // both languages, so the expanded form is always correct.
989 self.line(&format!("{} = {} {} {}", lhs.code, lhs.code, op, rhs.code));
990 Ok(None)
991 }
992 Expr::Macro(m) => {
993 let line = self.macro_call(&m.mac)?;
994 self.line(&line);
995 Ok(None)
996 }
997 _ => Ok(Some(self.expr(e)?)),
998 }
999 }
1000
1001 /// Lower `e` in statement position, assigning each arm's value to
1002 /// `target`. This is how Rust's expression-oriented `if`/`match` survive
1003 /// the trip when their arms are too big for a Nim `if`-expression.
1004 fn assign_from(
1005 &mut self,
1006 e: &Expr,
1007 target: &str,
1008 expect: Option<&Nim>,
1009 ) -> Result<(), String> {
1010 let saved = self.target.replace((target.to_string(), expect.cloned()));
1011 let r = match e {
1012 Expr::If(_) => self.if_stmt(e),
1013 Expr::Match(_) => self.match_stmt(e),
1014 other => {
1015 let v = self.expr_at(other, expect)?;
1016 self.line(&format!("{} = {}", target, v.code));
1017 Ok(())
1018 }
1019 };
1020 self.target = saved;
1021 r
1022 }
1023
1024 /// Emit a block's value into the active assignment target, if there is
1025 /// one, or discard it if there is not.
1026 fn emit_tail(&mut self, v: Option<Val>) {
1027 let Some(v) = v else { return };
1028 match self.target.clone() {
1029 Some((t, _)) => {
1030 let code = v.code.clone();
1031 self.line(&format!("{t} = {code}"));
1032 }
1033 None => {
1034 let needs = v.ty.as_ref().is_none_or(|t| *t != Nim::Unit);
1035 let code = v.code.clone();
1036 if needs {
1037 self.line(&format!("discard {code}"));
1038 } else if !code.is_empty() {
1039 self.line(&code);
1040 }
1041 }
1042 }
1043 }
1044
1045 fn if_stmt(&mut self, e: &Expr) -> Result<(), String> {
1046 let Expr::If(i) = e else { unreachable!() };
1047 if let Expr::Let(_) = &*i.cond {
1048 return Err("`if let` is not implemented yet".into());
1049 }
1050 let c = self.expr(&i.cond)?;
1051 self.line(&format!("if {}:", c.code));
1052 self.nested_block(&i.then_branch)?;
1053 match &i.else_branch {
1054 None => {}
1055 Some((_, els)) => match &**els {
1056 Expr::If(_) => {
1057 // Nim needs `elif`; splice the nested `if` in as one.
1058 let mark = self.out.len();
1059 self.if_stmt(els)?;
1060 let tail = self.out.split_off(mark);
1061 let indent = " ".repeat(self.indent);
1062 self.out.push_str(&tail.replacen(&format!("{indent}if "), &format!("{indent}elif "), 1));
1063 }
1064 Expr::Block(b) => {
1065 self.line("else:");
1066 self.nested_block(&b.block)?;
1067 }
1068 _ => return Err("unsupported `else` form".into()),
1069 },
1070 }
1071 Ok(())
1072 }
1073
1074 fn for_loop(&mut self, f: &syn::ExprForLoop) -> Result<(), String> {
1075 if f.label.is_some() {
1076 return Err("loop labels are not implemented yet".into());
1077 }
1078 let name = match &*f.pat {
1079 Pat::Ident(i) => i.ident.to_string(),
1080 Pat::Wild(_) => "_".into(),
1081 _ => return Err("destructuring `for` patterns are not implemented yet".into()),
1082 };
1083
1084 // Strip the iterator adaptors that are no-ops once we are iterating a
1085 // Nim container directly. Anything else (`.map`, `.filter`, `.rev`)
1086 // is a real iterator and is rejected rather than silently dropped.
1087 let mut src = &*f.expr;
1088 loop {
1089 match src {
1090 Expr::MethodCall(m)
1091 if matches!(m.method.to_string().as_str(), "iter" | "into_iter" | "iter_mut")
1092 && m.args.is_empty() =>
1093 {
1094 src = &m.receiver
1095 }
1096 Expr::Reference(r) => src = &r.expr,
1097 _ => break,
1098 }
1099 }
1100
1101 let (header, elem) = match src {
1102 Expr::Range(r) => {
1103 let lo = match &r.start {
1104 Some(e) => self.expr(e)?,
1105 None => return Err("a `for` over `..n` needs a start bound".into()),
1106 };
1107 let hi = match &r.end {
1108 Some(e) => self.expr(e)?,
1109 None => return Err("a `for` over an unbounded range would not terminate".into()),
1110 };
1111 let op = match r.limits {
1112 syn::RangeLimits::HalfOpen(_) => "..<",
1113 syn::RangeLimits::Closed(_) => "..",
1114 };
1115 let t = lo.ty.clone().or(hi.ty.clone());
1116 (format!("{} {} {}", lo.code, op, hi.code), t)
1117 }
1118 other => {
1119 let v = self.expr(other)?;
1120 let elem = match v.ty.clone() {
1121 Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) | Some(Nim::Array(_, t)) => Some(*t),
1122 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
1123 _ => None,
1124 };
1125 (v.code, elem)
1126 }
1127 };
1128
1129 self.line(&format!("for {} in {}:", ident(&name), header));
1130 self.push_scope();
1131 if let Some(t) = elem {
1132 self.bind(&name, t);
1133 }
1134 self.indent += 1;
1135 let before = self.out.len();
1136 let saved = self.target.take();
1137 if let Some(v) = self.block_body(&f.body)? {
1138 let code = v.code.clone();
1139 self.line(&format!("discard {code}"));
1140 }
1141 self.target = saved;
1142 if self.out.len() == before {
1143 self.line("discard");
1144 }
1145 self.indent -= 1;
1146 self.pop_scope();
1147 Ok(())
1148 }
1149
1150 fn match_stmt(&mut self, e: &Expr) -> Result<(), String> {
1151 let Expr::Match(m) = e else { unreachable!() };
1152 let scrut = self.expr(&m.expr)?;
1153 let t = scrut
1154 .ty
1155 .clone()
1156 .ok_or("cannot infer the type of a `match` scrutinee")?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1157 let name = self.fresh("Match");
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1158 self.line(&format!("let {}: {} = {}", name, t.render(), scrut.code));
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1159
1160 // A `match` whose arms neither bind nor guard is a Nim `case`, which
1161 // is exhaustiveness-checked the way Rust's is. Anything richer becomes
1162 // an if/elif chain, because Nim's `case` cannot destructure.
1163 let plain = m.arms.iter().all(|a| {
1164 !matches!(a.pat, Pat::Guard(_)) && !binds(&a.pat) && !destructures(&a.pat)
1165 });
1166 if plain {
1167 self.match_case(m, &name, &t)
1168 } else {
1169 self.match_chain(m, &name, &t)
1170 }
1171 }
1172
1173 fn match_case(
1174 &mut self,
1175 m: &syn::ExprMatch,
1176 name: &str,
1177 t: &Nim,
1178 ) -> Result<(), String> {
1179 // A variant object is discriminated by its `kind` field.
1180 let on_kind = matches!(t, Nim::Named(n, _) if self.enums.get(n).is_some_and(|d| !d.simple));
1181 self.line(&format!("case {}{}", name, if on_kind { ".kind" } else { "" }));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1182
1183 let mut saw_wild = false;
1184 for arm in &m.arms {
1185 match &arm.pat {
1186 Pat::Wild(_) => {
1187 saw_wild = true;
1188 self.line("else:");
1189 }
1190 p => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1191 let labels = self.pat_labels(p, Some(t))?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1192 self.line(&format!("of {}:", labels.join(", ")));
1193 }
1194 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1195 self.arm_body(&arm.body)?;
1196 }
1197 if !saw_wild && !self.case_is_total(t, m) {
1198 // Rust checked exhaustiveness already, but Nim cannot always see
1199 // it -- an integer `case` needs every value covered -- so make the
1200 // unreachable arm explicit rather than leave a compile error.
1201 self.line("else:");
1202 self.line(" rsPanic(\"unreachable match arm\")");
1203 }
1204 Ok(())
1205 }
1206
1207 /// Whether a Nim `case` over this type is already total, in which case
1208 /// adding an `else` would be a compile error rather than a safety net.
1209 fn case_is_total(&self, t: &Nim, m: &syn::ExprMatch) -> bool {
1210 let Nim::Named(n, _) = t else { return false };
1211 let Some(def) = self.enums.get(n) else { return false };
1212 def.variants.len() == m.arms.len()
1213 }
1214
1215 /// The if/elif form, for arms that bind or destructure.
1216 fn match_chain(
1217 &mut self,
1218 m: &syn::ExprMatch,
1219 name: &str,
1220 t: &Nim,
1221 ) -> Result<(), String> {
1222 let mut first = true;
1223 let mut closed = false;
1224 for arm in &m.arms {
1225 let (pat, guard) = match &arm.pat {
1226 Pat::Guard(g) => (&*g.pat, Some(&*g.guard)),
1227 p => (p, None),
1228 };
1229 if guard.is_some() && binds(pat) {
1230 return Err("a `match` guard on a binding pattern is not \
1231 implemented yet"
1232 .into());
1233 }
1234 let test = self.pat_test(pat, name, t)?;
1235 let test = match (test, guard) {
1236 (Some(t), Some(g)) => {
1237 let g = self.expr(g)?;
1238 Some(format!("({}) and ({})", t, g.code))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1239 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1240 (None, Some(g)) => Some(self.expr(g)?.code),
1241 (t, None) => t,
1242 };
1243 match test {
1244 Some(test) => {
1245 self.line(&format!(
1246 "{} {}:",
1247 if first { "if" } else { "elif" },
1248 test
1249 ));
1250 first = false;
1251 }
1252 None => {
1253 // An irrefutable pattern: everything left falls here.
1254 if first {
1255 self.line("block:");
1256 } else {
1257 self.line("else:");
1258 }
1259 closed = true;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1260 }
1261 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1262 self.indent += 1;
1263 self.push_scope();
1264 let before = self.out.len();
1265 self.pat_bind(pat, name, t)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1266 self.indent -= 1;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1267 self.arm_body_at(&arm.body, before)?;
1268 self.pop_scope();
1269 if closed {
1270 break;
1271 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1272 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1273 if !closed {
1274 // Rust proved this unreachable; Nim cannot see that, and leaving
1275 // the chain open would silently fall through instead.
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1276 self.line("else:");
1277 self.line(" rsPanic(\"unreachable match arm\")");
1278 }
1279 Ok(())
1280 }
1281
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1282 /// The condition that selects this arm, or `None` if it always matches.
1283 fn pat_test(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<Option<String>, String> {
1284 Ok(match p {
1285 Pat::Wild(_) => None,
1286 Pat::Ident(i) if i.subpat.is_none() => None,
1287 Pat::Or(o) => {
1288 let mut parts = Vec::new();
1289 for c in &o.cases {
1290 match self.pat_test(c, name, t)? {
1291 Some(x) => parts.push(x),
1292 None => return Ok(None),
1293 }
1294 }
1295 Some(format!("({})", parts.join(" or ")))
1296 }
1297 Pat::Lit(_) | Pat::Range(_) => {
1298 let labels = self.pat_labels(p, Some(t))?;
1299 Some(match p {
1300 Pat::Range(_) => format!("({} in {})", name, labels[0]),
1301 _ => format!("({} == {})", name, labels[0]),
1302 })
1303 }
1304 Pat::Path(pp) => Some(self.variant_test(&pp.path, name, t)?),
1305 Pat::TupleStruct(ts) => Some(self.variant_test(&ts.path, name, t)?),
1306 Pat::Struct(st) => Some(self.variant_test(&st.path, name, t)?),
1307 Pat::Paren(pp) => return self.pat_test(&pp.pat, name, t),
1308 Pat::Reference(r) => return self.pat_test(&r.pat, name, t),
1309 _ => return Err("unsupported `match` pattern".into()),
1310 })
1311 }
1312
1313 /// The discriminant test for `Ok`/`Err`/`Some`/`None` or an enum variant.
1314 fn variant_test(&self, path: &syn::Path, name: &str, t: &Nim) -> Result<String, String> {
1315 let last = path_name(path);
1316 match last.as_str() {
1317 "Ok" => return Ok(format!("{name}.ok")),
1318 "Err" => return Ok(format!("(not {name}.ok)")),
1319 "Some" => return Ok(format!("{name}.has")),
1320 "None" => return Ok(format!("(not {name}.has)")),
1321 _ => {}
1322 }
1323 let Some((def, v)) = self.resolve_variant(path) else {
1324 return Err(format!(
1325 "`{last}` in a pattern is not a known enum variant; if it names \
1326 an enum declared in another module, that is not implemented yet"
1327 ));
1328 };
1329 if let Nim::Named(n, _) = t {
1330 if *n != def.name {
1331 return Err(format!(
1332 "pattern `{}::{}` does not match the scrutinee type `{}`",
1333 def.name, v, n
1334 ));
1335 }
1336 }
1337 Ok(if def.simple {
1338 format!("({} == {}.{})", name, ident(&def.name), ident(&v))
1339 } else {
1340 format!("({}.kind == {})", name, def.kind_ident(&v))
1341 })
1342 }
1343
1344 /// Emit the `let`s that a pattern's bindings introduce.
1345 fn pat_bind(&mut self, p: &Pat, name: &str, t: &Nim) -> Result<(), String> {
1346 match p {
1347 Pat::Wild(_) | Pat::Lit(_) | Pat::Range(_) | Pat::Path(_) | Pat::Or(_) => Ok(()),
1348 Pat::Paren(pp) => self.pat_bind(&pp.pat, name, t),
1349 Pat::Reference(r) => self.pat_bind(&r.pat, name, t),
1350 Pat::Ident(i) if i.subpat.is_none() => {
1351 let b = i.ident.to_string();
1352 self.line(&format!("let {}: {} = {}", ident(&b), t.render(), name));
1353 self.bind(&b, t.clone());
1354 Ok(())
1355 }
1356 Pat::TupleStruct(ts) => {
1357 let fields = self.variant_fields(&ts.path, t)?;
1358 for (i, sub) in ts.elems.iter().enumerate() {
1359 let Some((fname, fty)) = fields.get(i) else {
1360 return Err(format!(
1361 "pattern binds {} field(s) but the variant has {}",
1362 ts.elems.len(),
1363 fields.len()
1364 ));
1365 };
1366 let access = format!("{}.{}", name, ident(fname));
1367 self.pat_bind(sub, &access, fty)?;
1368 }
1369 Ok(())
1370 }
1371 Pat::Struct(st) => {
1372 let fields = self.variant_fields(&st.path, t)?;
1373 for f in &st.fields {
1374 let syn::Member::Named(m) = &f.member else {
1375 return Err("unsupported struct pattern field".into());
1376 };
1377 let m = m.to_string();
1378 let Some((fname, fty)) = fields.iter().find(|(f, _)| f.ends_with(&m)) else {
1379 return Err(format!("unknown field `{m}` in pattern"));
1380 };
1381 let access = format!("{}.{}", name, ident(fname));
1382 self.pat_bind(&f.pat, &access, fty)?;
1383 }
1384 Ok(())
1385 }
1386 _ => Err("unsupported `match` pattern".into()),
1387 }
1388 }
1389
1390 /// The payload fields a variant pattern destructures.
1391 fn variant_fields(
1392 &self,
1393 path: &syn::Path,
1394 t: &Nim,
1395 ) -> Result<Vec<(String, Nim)>, String> {
1396 let last = path_name(path);
1397 // `Ok`/`Err`/`Some` read the prelude's own field names.
1398 if let Nim::Named(n, a) = t {
1399 match (n.as_str(), last.as_str()) {
1400 ("Result", "Ok") if a.len() == 2 => return Ok(vec![("val".into(), a[0].clone())]),
1401 ("Result", "Err") if a.len() == 2 => return Ok(vec![("err".into(), a[1].clone())]),
1402 ("Option", "Some") if a.len() == 1 => return Ok(vec![("val".into(), a[0].clone())]),
1403 _ => {}
1404 }
1405 }
1406 let Some((def, v)) = self.resolve_variant(path) else {
1407 return Err(format!("`{last}` is not a known enum variant"));
1408 };
1409 Ok(def.get(&v).map(|v| v.fields.clone()).unwrap_or_default())
1410 }
1411
1412 fn arm_body(&mut self, body: &Expr) -> Result<(), String> {
1413 self.indent += 1;
1414 let before = self.out.len();
1415 self.indent -= 1;
1416 self.arm_body_at(body, before)
1417 }
1418
1419 fn arm_body_at(&mut self, body: &Expr, before: usize) -> Result<(), String> {
1420 match body {
1421 Expr::Block(b) => self.nested_block(&b.block)?,
1422 other => {
1423 self.indent += 1;
1424 // An arm's value is the `match`'s value, so it is typed by
1425 // whatever the `match` is being assigned to -- without which
1426 // an `Ok(..)` arm has no way to know its `Result<T, E>`.
1427 let want = self.target.clone().and_then(|(_, t)| t);
1428 let v = match (want, expressible(other)) {
1429 (Some(t), true) => Some(self.expr_at(other, Some(&t))?),
1430 _ => self.expr_stmt(other)?,
1431 };
1432 self.emit_tail(v);
1433 self.indent -= 1;
1434 }
1435 }
1436 if self.out.len() == before {
1437 self.indent += 1;
1438 self.line("discard");
1439 self.indent -= 1;
1440 }
1441 Ok(())
1442 }
1443
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1444 fn pat_labels(&mut self, p: &Pat, expect: Option<&Nim>) -> Result<Vec<String>, String> {
1445 match p {
1446 Pat::Lit(l) => Ok(vec![self.lit_at(&l.lit, expect)?.code]),
1447 Pat::Or(o) => {
1448 let mut out = Vec::new();
1449 for p in &o.cases {
1450 out.extend(self.pat_labels(p, expect)?);
1451 }
1452 Ok(out)
1453 }
1454 Pat::Range(r) => {
1455 let lo = r.start.as_ref().ok_or("open-ended range pattern")?;
1456 let hi = r.end.as_ref().ok_or("open-ended range pattern")?;
1457 let (lo, hi) = (self.expr_at(lo, expect)?, self.expr_at(hi, expect)?);
1458 let op = match r.limits {
1459 syn::RangeLimits::HalfOpen(_) => "..<",
1460 syn::RangeLimits::Closed(_) => "..",
1461 };
1462 Ok(vec![format!("{} {} {}", lo.code, op, hi.code)])
1463 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1464 Pat::Path(pp) => {
1465 if let Some((def, v)) = self.resolve_variant(&pp.path) {
1466 return Ok(vec![if def.simple {
1467 format!("{}.{}", ident(&def.name), ident(&v))
1468 } else {
1469 def.kind_ident(&v)
1470 }]);
1471 }
1472 Ok(vec![ident(&path_name(&pp.path))])
1473 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1474 _ => Err("unsupported `match` pattern; only literals, ranges, `|` \
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1475 alternatives, enum variants and `_` are implemented"
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1476 .into()),
1477 }
1478 }
1479
1480 // --------------------------------------------------------- expressions
1481
1482 fn expr(&mut self, e: &Expr) -> Result<Val, String> {
1483 self.expr_at(e, None)
1484 }
1485
1486 /// Lower `e`, with the type the surrounding code expects of it.
1487 ///
1488 /// Rust infers an unsuffixed integer literal's type from its context and
1489 /// falls back to `i32`; Nim falls back to 64-bit `int`. Carrying the
1490 /// expected type down to the literal is what makes `let x: u8 = 255` and
1491 /// `x.wrapping_add(100)` mean the same thing on both sides. Without it the
1492 /// widths silently diverge, which is exactly the class of bug this
1493 /// project refuses to ship.
1494 fn expr_at(&mut self, e: &Expr, expect: Option<&Nim>) -> Result<Val, String> {
1495 match e {
1496 Expr::Lit(l) => self.lit_at(&l.lit, expect),
1497 Expr::Path(p) => {
1498 let name = path_name(&p.path);
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1499 if name == "None" {
1500 return Ok(Val::new(self.none_of(expect), expect.cloned()));
1501 }
1502 // A unit enum variant used as a value: `Error::InvalidLength`.
1503 if let Some((def, v)) = self.resolve_variant(&p.path) {
1504 let ty = Some(Nim::Named(def.name.clone(), vec![]));
1505 return Ok(if def.simple {
1506 Val::new(format!("{}.{}", ident(&def.name), ident(&v)), ty)
1507 } else {
1508 Val::new(format!("{}()", def.ctor_ident(&v)), ty)
1509 });
1510 }
1511 if let Some(t) = self.lookup(&name) {
1512 return Ok(Val::new(ident(&name), Some(t)));
1513 }
1514 // A top-level function used as a value, e.g. passed to a
1515 // parameter of `impl Fn(..)` type.
1516 if let Some(sig) = self.fns.get(&name) {
1517 let t = Nim::Proc(sig.params.clone(), Box::new(sig.ret.clone()));
1518 return Ok(Val::new(ident(&name), Some(t)));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1519 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1520 Ok(Val::new(ident(&name), None))
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1521 }
1522 Expr::Paren(p) => {
1523 let v = self.expr_at(&p.expr, expect)?;
1524 Ok(Val::new(format!("({})", v.code), v.ty))
1525 }
1526 Expr::Group(g) => self.expr_at(&g.expr, expect),
1527 // `&x` is a value in Nim; `&mut x` in an argument position binds to
1528 // a `var` parameter, which is also just `x` at the call site.
1529 Expr::Reference(r) => self.expr_at(&r.expr, expect),
1530 Expr::Unary(u) => self.unary(u, expect),
1531 Expr::Binary(b) => self.binary(b, expect),
1532 Expr::Cast(c) => self.cast(c),
1533 Expr::Index(i) => {
1534 let base = self.expr(&i.expr)?;
1535 let idx = self.expr(&i.index)?;
1536 // Rust indexes with usize; Nim wants an `int`, and a `uint`
1537 // index is a type error there rather than a silent conversion.
1538 let idx_code = match &idx.ty {
1539 Some(t) if t.is_unsigned() => format!("int({})", idx.code),
1540 _ => idx.code.clone(),
1541 };
1542 let elem = match base.ty.clone() {
1543 Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) | Some(Nim::Array(_, t)) => Some(*t),
1544 Some(Nim::Prim(p)) if p == "string" => Some(Nim::Prim("char".into())),
1545 _ => None,
1546 };
1547 Ok(Val::new(format!("{}[{}]", base.code, idx_code), elem))
1548 }
1549 Expr::Field(f) => {
1550 let base = self.expr(&f.base)?;
1551 let name = match &f.member {
1552 syn::Member::Named(n) => n.to_string(),
1553 syn::Member::Unnamed(i) => format!("f{}", i.index),
1554 };
1555 let t = match &base.ty {
1556 Some(Nim::Named(s, _)) => self
1557 .structs
1558 .get(s)
1559 .and_then(|fs| fs.iter().find(|(f, _)| *f == name))
1560 .map(|(_, t)| t.clone()),
1561 _ => None,
1562 };
1563 Ok(Val::new(format!("{}.{}", base.code, ident(&name)), t))
1564 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1565 Expr::Try(t) => self.try_op(t),
1566 Expr::Call(c) => self.call(c, expect),
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1567 Expr::MethodCall(m) => self.method(m),
1568 Expr::Macro(m) => {
1569 let code = self.macro_call(&m.mac)?;
1570 Ok(Val::new(code, None))
1571 }
1572 Expr::Struct(s) => {
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1573 if s.rest.is_some() {
1574 return Err("struct update syntax `..rest` is not implemented yet".into());
1575 }
1576 // `Shape::Rect { w: 3, h: 5 }` is a struct-shaped *enum variant*,
1577 // which is constructed positionally in Nim.
1578 if let Some((def, v)) = self.resolve_variant(&s.path) {
1579 let fields = def.get(&v).map(|v| v.fields.clone()).unwrap_or_default();
1580 let mut args = vec![String::new(); fields.len()];
1581 for f in &s.fields {
1582 let syn::Member::Named(m) = &f.member else {
1583 return Err("unsupported enum variant field".into());
1584 };
1585 let want = format!("{}_{}", v, m);
1586 let i = fields
1587 .iter()
1588 .position(|(n, _)| *n == want)
1589 .ok_or_else(|| format!("`{}::{}` has no field `{m}`", def.name, v))?;
1590 args[i] = self.expr_at(&f.expr, Some(&fields[i].1))?.code;
1591 }
1592 if let Some(i) = args.iter().position(|a| a.is_empty()) {
1593 return Err(format!(
1594 "`{}::{}` is missing field `{}`",
1595 def.name, v, fields[i].0
1596 ));
1597 }
1598 return Ok(Val::new(
1599 format!("{}({})", def.ctor_ident(&v), args.join(", ")),
1600 Some(Nim::Named(def.name.clone(), vec![])),
1601 ));
1602 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1603 let name = path_name(&s.path);
1604 let mut parts = Vec::new();
1605 for f in &s.fields {
1606 let fname = match &f.member {
1607 syn::Member::Named(n) => n.to_string(),
1608 syn::Member::Unnamed(i) => format!("f{}", i.index),
1609 };
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1610 let want = self
1611 .structs
1612 .get(&name)
1613 .and_then(|fs| fs.iter().find(|(n, _)| *n == fname))
1614 .map(|(_, t)| t.clone());
1615 let v = self.expr_at(&f.expr, want.as_ref())?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1616 parts.push(format!("{}: {}", ident(&fname), v.code));
1617 }
1618 Ok(Val::new(
1619 format!("{}({})", ident(&name), parts.join(", ")),
1620 Some(Nim::Named(name, vec![])),
1621 ))
1622 }
1623 Expr::Array(a) => {
1624 let mut parts = Vec::new();
1625 let mut elem = match expect {
1626 Some(Nim::Array(_, t)) | Some(Nim::Seq(t)) | Some(Nim::OpenArray(t)) => {
1627 Some((**t).clone())
1628 }
1629 _ => None,
1630 };
1631 for e in &a.elems {
1632 let want = elem.clone();
1633 let v = self.expr_at(e, want.as_ref())?;
1634 elem = elem.or(v.ty.clone());
1635 parts.push(v.code);
1636 }
1637 let t = elem.map(|t| Nim::Array(a.elems.len(), Box::new(t)));
1638 Ok(Val::new(format!("[{}]", parts.join(", ")), t))
1639 }
1640 Expr::Repeat(r) => {
1641 let v = self.expr(&r.expr)?;
1642 let n = self.expr(&r.len)?;
1643 let t = v.ty.clone().map(|t| Nim::Seq(Box::new(t)));
1644 Ok(Val::new(format!("newSeqWith(int({}), {})", n.code, v.code), t))
1645 }
1646 Expr::Tuple(t) if t.elems.is_empty() => Ok(Val::new("", Some(Nim::Unit))),
1647 Expr::Tuple(t) => {
1648 let mut parts = Vec::new();
1649 let mut tys = Vec::new();
1650 for e in &t.elems {
1651 let v = self.expr(e)?;
1652 tys.push(v.ty.clone());
1653 parts.push(v.code);
1654 }
1655 let ty = tys
1656 .iter()
1657 .cloned()
1658 .collect::<Option<Vec<_>>>()
1659 .map(Nim::Tuple);
1660 Ok(Val::new(format!("({})", parts.join(", ")), ty))
1661 }
1662 // `if` and `match` are expressions in both languages, but only
1663 // when every arm is itself a single expression.
1664 Expr::If(i) => self.if_expr(i, expect),
1665 Expr::Block(b) if b.block.stmts.len() == 1 => {
1666 if let Some(Stmt::Expr(e, None)) = b.block.stmts.first() {
1667 self.expr_at(e, expect)
1668 } else {
1669 Err("block expression with statements in value position is not implemented yet".into())
1670 }
1671 }
1672 other => Err(format!(
1673 "unsupported expression in value position: {}",
1674 expr_kind(other)
1675 )),
1676 }
1677 }
1678
1679 fn if_expr(&mut self, i: &syn::ExprIf, expect: Option<&Nim>) -> Result<Val, String> {
1680 let (Some(then), Some((_, els))) = (single_expr(&i.then_branch), &i.else_branch) else {
1681 return Err(
1682 "an `if` used as a value must have an `else` and single-expression arms".into(),
1683 );
1684 };
1685 let c = self.expr(&i.cond)?;
1686 let t = self.expr_at(then, expect)?;
1687 let want = expect.cloned().or_else(|| t.ty.clone());
1688 let e = match &**els {
1689 Expr::Block(b) => match single_expr(&b.block) {
1690 Some(x) => self.expr_at(x, want.as_ref())?,
1691 None => return Err("an `if` used as a value must have single-expression arms".into()),
1692 },
1693 other => self.expr_at(other, want.as_ref())?,
1694 };
1695 let ty = t.ty.clone().or(e.ty.clone());
1696 Ok(Val::new(
1697 format!("(if {}: {} else: {})", c.code, t.code, e.code),
1698 ty,
1699 ))
1700 }
1701
1702 fn lit_at(&mut self, l: &Lit, expect: Option<&Nim>) -> Result<Val, String> {
1703 match l {
1704 Lit::Int(i) => {
1705 let suffix = i.suffix();
1706 if let Some(why) = ty::rejected(suffix) {
1707 return Err(format!("integer literal `{}`: {}", i, why));
1708 }
1709 let digits = i.base10_digits().to_string();
1710 // Rust's default for an unconstrained integer literal is i32.
1711 // Nim's is `int` (64-bit). Making the width explicit is what
1712 // keeps overflow behaviour the same on both sides.
1713 let t = if suffix.is_empty() {
1714 match expect {
1715 Some(t) if t.is_integer() => t.clone(),
1716 // Rust's fallback for an otherwise-unconstrained
1717 // integer literal.
1718 _ => Nim::Prim("int32".into()),
1719 }
1720 } else {
1721 ty::prim(suffix).ok_or_else(|| format!("unknown literal suffix `{suffix}`"))?
1722 };
1723 Ok(Val::new(format!("{}'{}", digits, nim_suffix(&t)?), Some(t)))
1724 }
1725 Lit::Float(f) => {
1726 let t = match f.suffix() {
1727 "" => match expect {
1728 Some(Nim::Prim(p)) if p == "float32" => Nim::Prim("float32".into()),
1729 _ => Nim::Prim("float64".into()),
1730 },
1731 "f64" => Nim::Prim("float64".into()),
1732 "f32" => Nim::Prim("float32".into()),
1733 s => return Err(format!("unknown float suffix `{s}`")),
1734 };
1735 let d = f.base10_digits();
1736 let d = if d.contains('.') || d.contains('e') { d.to_string() } else { format!("{d}.0") };
1737 Ok(Val::new(d, Some(t)))
1738 }
1739 Lit::Bool(b) => Ok(Val::new(b.value.to_string(), Some(Nim::Prim("bool".into())))),
1740 Lit::Str(s) => Ok(Val::new(
1741 fmt::nim_str(&s.value()),
1742 Some(Nim::Prim("string".into())),
1743 )),
1744 Lit::Char(c) => Ok(Val::new(
1745 format!("Rune({})", c.value() as u32),
1746 Some(Nim::Prim("Rune".into())),
1747 )),
1748 Lit::Byte(b) => Ok(Val::new(
1749 format!("{}'u8", b.value()),
1750 Some(Nim::Prim("uint8".into())),
1751 )),
1752 Lit::ByteStr(b) => {
1753 let bytes: Vec<String> = b.value().iter().map(|x| format!("{x}'u8")).collect();
1754 Ok(Val::new(
1755 format!("@[{}]", bytes.join(", ")),
1756 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
1757 ))
1758 }
1759 other => Err(format!("unsupported literal: {other:?}")),
1760 }
1761 }
1762
1763 fn unary(&mut self, u: &syn::ExprUnary, expect: Option<&Nim>) -> Result<Val, String> {
1764 // `-128i8` is a literal in Rust, but `-(128'i8)` in Nim would overflow
1765 // the positive half of the range before the negation runs. Folding the
1766 // sign into the literal keeps `i8::MIN` and friends expressible.
1767 if let (UnOp::Neg(_), Expr::Lit(l)) = (&u.op, &*u.expr) {
1768 if matches!(l.lit, Lit::Int(_) | Lit::Float(_)) {
1769 let v = self.lit_at(&l.lit, expect)?;
1770 return Ok(Val::new(format!("-{}", v.code), v.ty));
1771 }
1772 }
1773 let v = self.expr_at(&u.expr, expect)?;
1774 match u.op {
1775 UnOp::Neg(_) => Ok(Val::new(format!("(-{})", v.code), v.ty)),
1776 // Rust's `!` is logical on bool and bitwise-complement on integers.
1777 // Nim spells those `not` and `not` as well, so one mapping covers
1778 // both — but only because Nim overloads `not` the same way.
1779 UnOp::Not(_) => Ok(Val::new(format!("(not {})", v.code), v.ty)),
1780 UnOp::Deref(_) => Ok(v),
1781 _ => Err("unsupported unary operator".into()),
1782 }
1783 }
1784
1785 fn binary(&mut self, b: &syn::ExprBinary, expect: Option<&Nim>) -> Result<Val, String> {
1786 // A comparison's operands are unrelated to the `bool` it produces, so
1787 // the outer expectation is not passed through to them.
1788 let down = match b.op {
1789 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
1790 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => None,
1791 _ => expect,
1792 };
1793 let mut l = self.expr_at(&b.left, down)?;
1794 // Rust unifies the two operand types; propagating whichever side is
1795 // known to the other reproduces that, and disagreement then surfaces
1796 // as a Nim type error rather than as a silent width change.
1797 let mut r = self.expr_at(&b.right, l.ty.as_ref().or(down))?;
1798 if l.ty.is_none() && r.ty.is_some() {
1799 l = self.expr_at(&b.left, r.ty.as_ref())?;
1800 }
1801 let r = std::mem::replace(&mut r, Val::untyped(""));
1802 let op = self.bin_op(&b.op, &l, &r)?;
1803 let ty = match b.op {
1804 BinOp::Eq(_) | BinOp::Ne(_) | BinOp::Lt(_) | BinOp::Le(_) | BinOp::Gt(_)
1805 | BinOp::Ge(_) | BinOp::And(_) | BinOp::Or(_) => Some(Nim::Prim("bool".into())),
1806 // Rust's shift takes its result type from the *left* operand, and
1807 // the right may be a different width entirely.
1808 BinOp::Shl(_) | BinOp::Shr(_) => l.ty.clone(),
1809 _ => l.ty.clone().or(r.ty.clone()),
1810 };
1811 Ok(Val::new(format!("({} {} {})", l.code, op, r.code), ty))
1812 }
1813
1814 fn bin_op(&mut self, op: &BinOp, l: &Val, r: &Val) -> Result<&'static str, String> {
1815 Ok(match op {
1816 BinOp::Add(_) | BinOp::AddAssign(_) => "+",
1817 BinOp::Sub(_) | BinOp::SubAssign(_) => "-",
1818 BinOp::Mul(_) | BinOp::MulAssign(_) => "*",
1819 BinOp::Div(_) | BinOp::DivAssign(_) => {
1820 // Nim spells integer division `div`. Both languages truncate
1821 // toward zero, so once the right operator is chosen the
1822 // semantics match, including for negative operands.
1823 let t = l.ty.clone().or(r.ty.clone()).ok_or(
1824 "cannot tell integer from float division here; annotate the operands",
1825 )?;
1826 if t.is_integer() { "div" } else { "/" }
1827 }
1828 BinOp::Rem(_) | BinOp::RemAssign(_) => {
1829 let t = l.ty.clone().or(r.ty.clone()).ok_or(
1830 "cannot tell integer from float remainder here; annotate the operands",
1831 )?;
1832 if t.is_integer() { "mod" } else { return Err("float `%` is not implemented yet".into()) }
1833 }
1834 BinOp::And(_) => "and",
1835 BinOp::Or(_) => "or",
1836 // Nim's `and`/`or`/`xor` are bitwise on integers and logical on
1837 // bools, exactly as Rust's `&`/`|`/`^` are.
1838 BinOp::BitAnd(_) | BinOp::BitAndAssign(_) => "and",
1839 BinOp::BitOr(_) | BinOp::BitOrAssign(_) => "or",
1840 BinOp::BitXor(_) | BinOp::BitXorAssign(_) => "xor",
1841 // Settled empirically: Nim's `shr` on a signed integer is
1842 // arithmetic, matching Rust. See DESIGN.md.
1843 BinOp::Shl(_) | BinOp::ShlAssign(_) => "shl",
1844 BinOp::Shr(_) | BinOp::ShrAssign(_) => "shr",
1845 BinOp::Eq(_) => "==",
1846 BinOp::Ne(_) => "!=",
1847 BinOp::Lt(_) => "<",
1848 BinOp::Le(_) => "<=",
1849 BinOp::Gt(_) => ">",
1850 BinOp::Ge(_) => ">=",
1851 other => return Err(format!("unsupported binary operator {other:?}")),
1852 })
1853 }
1854
1855 fn cast(&mut self, c: &syn::ExprCast) -> Result<Val, String> {
1856 let v = self.expr(&c.expr)?;
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1857 let to = self.map_ty(&c.ty)?;
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1858 let from = v.ty.clone().ok_or_else(|| {
1859 format!(
1860 "cannot lower `as {}`: the source type is unknown, and `as` \
1861 truncates, so the source width decides the result",
1862 to.render()
1863 )
1864 })?;
1865
1866 let code = match (&from, &to) {
1867 (f, t) if f.is_integer() && t.is_integer() => {
1868 // Rust's `as` between integers is a pure bit-width truncation
1869 // or sign-extension — never a range check. Nim's `T(x)` *does*
1870 // range-check and would raise where Rust wraps, so `cast` is
1871 // the only faithful spelling. Probed against both compilers.
1872 format!("cast[{}]({})", t.render(), v.code)
1873 }
1874 (f, Nim::Prim(p)) if f.is_integer() && (p == "float64" || p == "float32") => {
1875 format!("{}({})", p, v.code)
1876 }
1877 (Nim::Prim(b), t) if b == "bool" && t.is_integer() => {
1878 format!("{}(ord({}))", t.render(), v.code)
1879 }
1880 (Nim::Prim(r), t) if r == "Rune" && t.is_integer() => {
1881 format!("cast[{}](int32({}))", t.render(), v.code)
1882 }
1883 (f, Nim::Prim(r)) if f.is_integer() && r == "Rune" => {
1884 format!("Rune(int32({}))", v.code)
1885 }
1886 (Nim::Prim(a), Nim::Prim(b)) if a == b => v.code.clone(),
1887 (f, t) if matches!(f, Nim::Prim(p) if p.starts_with("float")) && t.is_integer() => {
1888 // Rust saturates float->int casts; Nim rounds and range-errors.
1889 // Not the same operation, so it is refused rather than mapped.
1890 return Err(format!(
1891 "`as {}` from a float: Rust saturates, Nim rounds and range-checks; \
1892 no faithful mapping is implemented",
1893 t.render()
1894 ));
1895 }
1896 (f, t) => {
1897 return Err(format!(
1898 "unsupported cast from `{}` to `{}`",
1899 f.render(),
1900 t.render()
1901 ))
1902 }
1903 };
1904 Ok(Val::new(code, Some(to)))
1905 }
1906
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1907 /// Rust's `?`: return early on the error branch, otherwise yield the value.
1908 ///
1909 /// The early return is statements, not an expression, so they are emitted
1910 /// ahead of the line being built. Every caller lowers its sub-expressions
1911 /// before emitting its own line, which is what makes that ordering hold.
1912 fn try_op(&mut self, t: &syn::ExprTry) -> Result<Val, String> {
1913 if self.in_loop_cond {
1914 return Err("`?` in a loop condition is not implemented yet: the \
1915 early-return it expands to would be evaluated once, \
1916 before the loop, rather than on each iteration"
1917 .into());
1918 }
1919 let v = self.expr(&t.expr)?;
1920 let vt = v.ty.clone().ok_or(
1921 "`?` needs a known `Result`/`Option` type; annotate the expression it applies to",
1922 )?;
1923 let ret = self
1924 .ret
1925 .clone()
1926 .ok_or("`?` outside a function with a return type")?;
1927 let tmp = self.fresh("Try");
1928 self.line(&format!("let {}: {} = {}", tmp, vt.render(), v.code));
1929
1930 match (&vt, &ret) {
1931 (Nim::Named(a, ai), Nim::Named(b, bi))
1932 if a == "Result" && b == "Result" && ai.len() == 2 && bi.len() == 2 =>
1933 {
1934 // Rust inserts a `From::from` on the error here. We only accept
1935 // the case where the error types already agree, rather than
1936 // silently dropping a conversion that might not be the identity.
1937 if ai[1] != bi[1] {
1938 return Err(format!(
1939 "`?` would need `From<{}> for {}`: an error-type conversion \
1940 is not implemented, and assuming it is the identity would \
1941 be a guess",
1942 ai[1].render(),
1943 bi[1].render()
1944 ));
1945 }
1946 self.line(&format!("if not {}.ok:", tmp));
1947 self.line(&format!(
1948 " return rsErr[{}, {}]({}.err)",
1949 bi[0].render(),
1950 bi[1].render(),
1951 tmp
1952 ));
1953 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
1954 }
1955 (Nim::Named(a, ai), Nim::Named(b, bi))
1956 if a == "Option" && b == "Option" && ai.len() == 1 && bi.len() == 1 =>
1957 {
1958 self.line(&format!("if not {}.has:", tmp));
1959 self.line(&format!(" return rsNone[{}]()", bi[0].render()));
1960 Ok(Val::new(format!("{}.val", tmp), Some(ai[0].clone())))
1961 }
1962 _ => Err(format!(
1963 "`?` on `{}` in a function returning `{}` is not a supported \
1964 combination",
1965 vt.render(),
1966 ret.render()
1967 )),
1968 }
1969 }
1970
1971 fn call(&mut self, c: &syn::ExprCall, expect: Option<&Nim>) -> Result<Val, String> {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago1972 let Expr::Path(p) = &*c.func else {
1973 return Err("only calls to named functions are supported".into());
1974 };
1975 let name = path_name(&p.path);
1976 let ptys: Vec<Nim> = self
1977 .fns
1978 .get(&name)
1979 .map(|s| s.params.clone())
1980 .unwrap_or_default();
1981 let mut args = Vec::new();
1982 for (i, a) in c.args.iter().enumerate() {
1983 let want = ptys.get(i).cloned();
1984 args.push(self.expr_at(a, want.as_ref())?);
1985 }
1986 let codes: Vec<String> = args.iter().map(|a| a.code.clone()).collect();
1987
1988 // Constructors from the prelude.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago1989 // `Ok`/`Err` must name the *whole* Result type, not just the half
1990 // being constructed: Nim cannot infer `E` from an `Ok(v)` alone.
1991 match name.as_str() {
1992 "Some" => {
1993 let inner = match expect {
1994 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].render(),
1995 _ => {
1996 return Err("`Some(..)` needs a known `Option<T>` type here; \
1997 annotate the binding or the return type"
1998 .into())
1999 }
2000 };
2001 return Ok(Val::new(
2002 format!("rsSome[{}]({})", inner, codes.join(", ")),
2003 expect.cloned(),
2004 ));
2005 }
2006 "Ok" | "Err" => {
2007 let (t, e) = match expect {
2008 Some(Nim::Named(n, a)) if n == "Result" && a.len() == 2 => {
2009 (a[0].render(), a[1].render())
2010 }
2011 _ => {
2012 return Err(format!(
2013 "`{name}(..)` needs a known `Result<T, E>` type here; \
2014 annotate the binding or the return type"
2015 ))
2016 }
2017 };
2018 let ctor = if name == "Ok" { "rsOk" } else { "rsErr" };
2019 let arg = if codes.is_empty() { String::new() } else { codes.join(", ") };
2020 return Ok(Val::new(
2021 format!("{}[{}, {}]({})", ctor, t, e, arg),
2022 expect.cloned(),
2023 ));
2024 }
2025 _ => {}
2026 }
2027
2028 // A tuple enum variant applied to arguments: `Shape::Circle(1.0)`.
2029 if let Some((def, v)) = self.resolve_variant(&p.path) {
2030 return Ok(Val::new(
2031 format!("{}({})", def.ctor_ident(&v), codes.join(", ")),
2032 Some(Nim::Named(def.name.clone(), vec![])),
2033 ));
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2034 }
2035
2036 // A bare path that names a primitive type is Rust's tuple-struct-like
2037 // conversion, e.g. `String::from(..)`; handled by the method path.
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2038 // Calling a proc-typed local, which is how an `impl Fn(..)` parameter
2039 // is invoked.
2040 if let Some(Nim::Proc(_, ret)) = self.lookup(&name) {
2041 return Ok(Val::new(
2042 format!("{}({})", ident(&name), codes.join(", ")),
2043 Some((*ret).clone()),
2044 ));
2045 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2046 let ret = self.fns.get(&name).map(|s| s.ret.clone());
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2047 if ret.is_none() && !self.structs.contains_key(&name) && !self.enums.contains_key(&name) {
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2048 return Err(format!(
2049 "call to unknown function `{name}`; only functions defined in \
2050 this file and the supported standard-library subset can be lowered"
2051 ));
2052 }
2053 Ok(Val::new(
2054 format!("{}({})", ident(&name), codes.join(", ")),
2055 ret,
2056 ))
2057 }
2058
2059 fn method(&mut self, m: &syn::ExprMethodCall) -> Result<Val, String> {
2060 let recv = self.expr(&m.receiver)?;
2061 let name = m.method.to_string();
2062 // `x.wrapping_add(1)` and `x.min(3)` take an argument of the receiver's
2063 // own type; `v.push(e)` takes the element type.
2064 let arg_want = match (name.as_str(), &recv.ty) {
2065 ("push", Some(Nim::Seq(t))) | ("push", Some(Nim::OpenArray(t))) => Some((**t).clone()),
2066 (_, t) => t.clone(),
2067 };
2068 let mut args = Vec::new();
2069 for a in &m.args {
2070 args.push(self.expr_at(a, arg_want.as_ref())?);
2071 }
2072 let a0 = args.first().map(|a| a.code.clone());
2073 let rt = recv.ty.clone();
2074
2075 let (code, ty) = match name.as_str() {
2076 // Rust's `len()` is `usize`; Nim's is `int`. The conversion is
2077 // explicit so that a `usize` binding type-checks on the Nim side.
2078 "len" => (format!("uint({}.len)", recv.code), Some(Nim::Prim("uint".into()))),
2079 "is_empty" => (format!("({}.len == 0)", recv.code), Some(Nim::Prim("bool".into()))),
2080 "push" => (format!("{}.add({})", recv.code, a0.unwrap_or_default()), Some(Nim::Unit)),
2081 "clone" | "to_vec" | "to_owned" | "as_slice" | "as_ref" | "as_mut" | "iter"
2082 | "into_iter" => (recv.code.clone(), rt.clone()),
2083 "unwrap" | "expect" => {
2084 let inner = match &rt {
2085 Some(Nim::Named(n, a)) if (n == "Option" && a.len() == 1) || (n == "Result" && a.len() == 2) => {
2086 Some(a[0].clone())
2087 }
2088 _ => None,
2089 };
2090 (format!("unwrap({})", recv.code), inner)
2091 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2092 "ok_or" => {
2093 let inner = match &rt {
2094 Some(Nim::Named(n, a)) if n == "Option" && a.len() == 1 => a[0].clone(),
2095 _ => return Err("`ok_or` needs a known `Option<T>` receiver".into()),
2096 };
2097 let e = args.first().ok_or("`ok_or` takes one argument")?;
2098 let ety = e
2099 .ty
2100 .clone()
2101 .ok_or("`ok_or` needs a known error type for its argument")?;
2102 (
2103 format!(
2104 "rsOkOr[{}, {}]({}, {})",
2105 inner.render(),
2106 ety.render(),
2107 recv.code,
2108 e.code
2109 ),
2110 Some(Nim::Named("Result".into(), vec![inner, ety])),
2111 )
2112 }
2113 "unwrap_or" => {
2114 let inner = match &rt {
2115 Some(Nim::Named(n, a)) if (n == "Option" && a.len() == 1) || (n == "Result" && a.len() == 2) => {
2116 Some(a[0].clone())
2117 }
2118 _ => None,
2119 };
2120 (
2121 format!("unwrapOr({}, {})", recv.code, a0.unwrap_or_default()),
2122 inner,
2123 )
2124 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2125 "is_some" => (format!("{}.has", recv.code), Some(Nim::Prim("bool".into()))),
2126 "is_none" => (format!("(not {}.has)", recv.code), Some(Nim::Prim("bool".into()))),
2127 "is_ok" => (format!("{}.ok", recv.code), Some(Nim::Prim("bool".into()))),
2128 "is_err" => (format!("(not {}.ok)", recv.code), Some(Nim::Prim("bool".into()))),
2129
2130 // Settled empirically: Nim's fixed-width *unsigned* arithmetic
2131 // wraps silently, matching Rust's `wrapping_*`. For *signed* types
2132 // Nim raises OverflowDefect, so the operation is routed through
2133 // the unsigned view of the same width, which is what Rust's
2134 // wrapping_* is defined to compute.
2135 "wrapping_add" | "wrapping_sub" | "wrapping_mul" => {
2136 let op = match name.as_str() {
2137 "wrapping_add" => "+",
2138 "wrapping_sub" => "-",
2139 _ => "*",
2140 };
2141 let t = rt.clone().ok_or_else(|| {
2142 format!("`{name}` needs a known receiver type to pick the wrapping width")
2143 })?;
2144 if !t.is_integer() {
2145 return Err(format!("`{name}` on a non-integer type"));
2146 }
2147 let arg = a0.ok_or_else(|| format!("`{name}` takes one argument"))?;
2148 if t.is_unsigned() {
2149 (format!("({} {} {})", recv.code, op, arg), Some(t))
2150 } else {
2151 let u = unsigned_peer(&t)?;
2152 (
2153 format!(
2154 "cast[{}](cast[{}]({}) {} cast[{}]({}))",
2155 t.render(), u, recv.code, op, u, arg
2156 ),
2157 Some(t),
2158 )
2159 }
2160 }
2161 "abs" => (format!("abs({})", recv.code), rt.clone()),
2162 "min" => (format!("min({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
2163 "max" => (format!("max({}, {})", recv.code, a0.unwrap_or_default()), rt.clone()),
2164 "to_string" => (format!("rsDisplay({})", recv.code), Some(Nim::Prim("string".into()))),
2165 "as_bytes" | "into_bytes" => (
2166 format!("rsBytes({})", recv.code),
2167 Some(Nim::Seq(Box::new(Nim::Prim("uint8".into())))),
2168 ),
2169
2170 _ => {
2171 // A method defined in this file via `impl`. Nim's UFCS makes
2172 // the call site spelling identical.
2173 if let Some(sig) = self.fns.get(&name) {
2174 let ret = sig.ret.clone();
2175 let mut all = vec![recv.code.clone()];
2176 all.extend(args.iter().map(|a| a.code.clone()));
2177 (format!("{}({})", ident(&name), all.join(", ")), Some(ret))
2178 } else {
2179 return Err(format!(
2180 "unsupported method `.{name}()`; it is neither defined in \
2181 this file nor part of the standard-library subset that \
2182 has a verified Nim equivalent"
2183 ));
2184 }
2185 }
2186 };
2187 Ok(Val::new(code, ty))
2188 }
2189
2190 // -------------------------------------------------------------- macros
2191
2192 fn macro_call(&mut self, mac: &syn::Macro) -> Result<String, String> {
2193 let name = path_name(&mac.path);
2194 match name.as_str() {
2195 "println" | "print" | "eprintln" | "eprint" => {
2196 let s = self.format_args(mac)?;
2197 let nl = name.ends_with("ln");
2198 Ok(match (name.starts_with('e'), nl) {
2199 (false, true) => format!("echo {s}"),
2200 (false, false) => format!("stdout.write({s})"),
2201 (true, true) => format!("stderr.writeLine({s})"),
2202 (true, false) => format!("stderr.write({s})"),
2203 })
2204 }
2205 "format" => self.format_args(mac),
2206 "panic" => {
2207 let s = self.format_args(mac)?;
2208 Ok(format!("rsPanic({s})"))
2209 }
2210 "assert" => {
2211 let e: Expr = mac.parse_body().map_err(|e| format!("assert!: {e}"))?;
2212 let v = self.expr(&e)?;
2213 Ok(format!(
2214 "(if not ({}): rsPanic(\"assertion failed\"))",
2215 v.code
2216 ))
2217 }
2218 "vec" => {
2219 let body = mac.tokens.to_string();
2220 if body.trim().is_empty() {
2221 return Ok("@[]".into());
2222 }
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2223 // `vec![elem; n]` is the repeat form, not a list. The macro
2224 // body has no brackets, so it is parsed directly.
2225 if body.contains(';') {
2226 let (v, n) = mac
2227 .parse_body_with(|input: syn::parse::ParseStream| {
2228 let v: Expr = input.parse()?;
2229 input.parse::<syn::Token![;]>()?;
2230 let n: Expr = input.parse()?;
2231 Ok((v, n))
2232 })
2233 .map_err(|e| format!("vec![elem; n]: {e}"))?;
2234 let v = self.expr(&v)?;
2235 let n = self.expr(&n)?;
2236 return Ok(format!("newSeqWith(int({}), {})", n.code, v.code));
2237 }
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2238 let elems: syn::punctuated::Punctuated<Expr, syn::Token![,]> = mac
2239 .parse_body_with(syn::punctuated::Punctuated::parse_terminated)
2240 .map_err(|e| format!("vec!: {e}"))?;
2241 let mut parts = Vec::new();
2242 for e in &elems {
2243 parts.push(self.expr(e)?.code);
2244 }
2245 Ok(format!("@[{}]", parts.join(", ")))
2246 }
2247 other => Err(format!(
2248 "unsupported macro `{other}!`; a macro whose expansion is not \
2249 known cannot be lowered faithfully"
2250 )),
2251 }
2252 }
2253
2254 /// `println!("{} {}", a, b)` -> a Nim string-concatenation expression.
2255 fn format_args(&mut self, mac: &syn::Macro) -> Result<String, String> {
2256 let args: syn::punctuated::Punctuated<Expr, syn::Token![,]> = mac
2257 .parse_body_with(syn::punctuated::Punctuated::parse_terminated)
2258 .map_err(|e| format!("format arguments: {e}"))?;
2259 let mut it = args.iter();
2260 let Some(Expr::Lit(syn::ExprLit { lit: Lit::Str(s), .. })) = it.next() else {
2261 if args.is_empty() {
2262 return Ok("\"\"".into());
2263 }
2264 return Err("the first argument must be a literal format string".into());
2265 };
2266 let rest: Vec<&Expr> = it.collect();
2267
2268 let pieces = fmt::parse(&s.value())?;
2269 let mut parts: Vec<String> = Vec::new();
2270 let mut next = 0usize;
2271 let mut used = vec![false; rest.len()];
2272 for p in &pieces {
2273 match p {
2274 fmt::Piece::Lit(l) => parts.push(fmt::nim_str(l)),
2275 fmt::Piece::Arg { r#ref, spec } => {
2276 let v = match r#ref {
2277 fmt::Ref::Next => {
2278 let e = rest.get(next).ok_or("too few arguments for format string")?;
2279 used[next] = true;
2280 next += 1;
2281 self.expr(e)?
2282 }
2283 fmt::Ref::Index(i) => {
2284 let e = rest.get(*i).ok_or("format index out of range")?;
2285 used[*i] = true;
2286 self.expr(e)?
2287 }
2288 fmt::Ref::Named(n) => {
2289 let t = self.lookup(n).ok_or_else(|| {
2290 format!("`{{{n}}}` captures `{n}`, which is not in scope")
2291 })?;
2292 Val::new(ident(n), Some(t))
2293 }
2294 };
2295 parts.push(fmt::render_arg(&v.code, spec));
2296 }
2297 }
2298 }
2299 // Rust rejects an argument that no `{}` consumes; so do we, rather
2300 // than dropping it from the output.
2301 if let Some(i) = used.iter().position(|u| !u) {
2302 return Err(format!(
2303 "argument {} is never used by the format string",
2304 i + 1
2305 ));
2306 }
2307 Ok(if parts.is_empty() { "\"\"".into() } else { parts.join(" & ") })
2308 }
2309}
2310
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2311/// Whether a pattern introduces a binding.
2312fn binds(p: &Pat) -> bool {
2313 match p {
2314 Pat::Ident(_) => true,
2315 Pat::Guard(g) => binds(&g.pat),
2316 Pat::Paren(x) => binds(&x.pat),
2317 Pat::Reference(r) => binds(&r.pat),
2318 Pat::Or(o) => o.cases.iter().any(binds),
2319 Pat::TupleStruct(t) => t.elems.iter().any(|_| true),
2320 Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_) => true,
2321 _ => false,
2322 }
2323}
2324
2325/// Whether a pattern looks inside the value, which a Nim `case` cannot do.
2326fn destructures(p: &Pat) -> bool {
2327 matches!(
2328 p,
2329 Pat::TupleStruct(_) | Pat::Struct(_) | Pat::Tuple(_) | Pat::Slice(_)
2330 ) || matches!(p, Pat::Guard(g) if destructures(&g.pat))
2331 || matches!(p, Pat::Paren(x) if destructures(&x.pat))
2332 || matches!(p, Pat::Reference(r) if destructures(&r.pat))
2333}
2334
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2335/// Whether an expression has a direct Nim expression form.
2336///
2337/// Nim's `if` is an expression only when every arm is a single expression, and
2338/// its `case` is never one here. Anything else has to be lowered as statements
2339/// that assign into a target.
2340fn expressible(e: &Expr) -> bool {
2341 match e {
2342 Expr::If(i) => {
2343 let Some(then) = single_expr(&i.then_branch) else { return false };
2344 if !expressible(then) {
2345 return false;
2346 }
2347 match &i.else_branch {
2348 None => false,
2349 Some((_, els)) => match &**els {
2350 Expr::Block(b) => single_expr(&b.block).is_some_and(expressible),
2351 other => expressible(other),
2352 },
2353 }
2354 }
2355 Expr::Match(_) | Expr::Block(_) | Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => false,
2356 _ => true,
2357 }
2358}
2359
2360/// The single expression a block consists of, if that is all it is. An `if`
2361/// can only be lowered as a Nim `if`-expression when both arms are this shape.
2362fn single_expr(b: &syn::Block) -> Option<&Expr> {
2363 match (b.stmts.len(), b.stmts.first()) {
2364 (1, Some(Stmt::Expr(e, None))) => Some(e),
2365 _ => None,
2366 }
2367}
2368
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2369/// Substitute `params[i] -> args[i]` through a type. Enough of the type
2370/// grammar is covered to expand the aliases we accept; anything else is left
2371/// alone and will be reported by `ty::map` if it is unsupported.
2372fn substitute(t: &syn::Type, params: &[String], args: &[syn::Type]) -> syn::Type {
2373 use syn::Type;
2374 match t {
2375 Type::Path(p) => {
2376 if p.qself.is_none() && p.path.segments.len() == 1 {
2377 let seg = &p.path.segments[0];
2378 if seg.arguments.is_empty() {
2379 let name = seg.ident.to_string();
2380 if let Some(i) = params.iter().position(|x| *x == name) {
2381 return args[i].clone();
2382 }
2383 }
2384 }
2385 let mut p = p.clone();
2386 for seg in &mut p.path.segments {
2387 if let syn::PathArguments::AngleBracketed(a) = &mut seg.arguments {
2388 for g in &mut a.args {
2389 if let syn::GenericArgument::Type(t) = g {
2390 *t = substitute(t, params, args);
2391 }
2392 }
2393 }
2394 }
2395 Type::Path(p)
2396 }
2397 Type::Reference(r) => {
2398 let mut r = r.clone();
2399 r.elem = Box::new(substitute(&r.elem, params, args));
2400 Type::Reference(r)
2401 }
2402 Type::Slice(sl) => {
2403 let mut sl = sl.clone();
2404 sl.elem = Box::new(substitute(&sl.elem, params, args));
2405 Type::Slice(sl)
2406 }
2407 Type::Array(a) => {
2408 let mut a = a.clone();
2409 a.elem = Box::new(substitute(&a.elem, params, args));
2410 Type::Array(a)
2411 }
2412 Type::Tuple(tp) => {
2413 let mut tp = tp.clone();
2414 tp.elems = tp.elems.iter().map(|e| substitute(e, params, args)).collect();
2415 Type::Tuple(tp)
2416 }
2417 Type::Paren(p) => substitute(&p.elem, params, args),
2418 Type::Group(g) => substitute(&g.elem, params, args),
2419 other => other.clone(),
2420 }
2421}
2422
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2423// --------------------------------------------------------------- utilities
2424
2425fn takes_self(sig: &syn::Signature) -> bool {
2426 matches!(sig.inputs.first(), Some(FnArg::Receiver(_)))
2427}
2428
2429fn path_name(p: &syn::Path) -> String {
2430 p.segments
2431 .last()
2432 .map(|s| s.ident.to_string())
2433 .unwrap_or_default()
2434}
2435
2436fn is_compound(op: &BinOp) -> bool {
2437 matches!(
2438 op,
2439 BinOp::AddAssign(_)
2440 | BinOp::SubAssign(_)
2441 | BinOp::MulAssign(_)
2442 | BinOp::DivAssign(_)
2443 | BinOp::RemAssign(_)
2444 | BinOp::BitAndAssign(_)
2445 | BinOp::BitOrAssign(_)
2446 | BinOp::BitXorAssign(_)
2447 | BinOp::ShlAssign(_)
2448 | BinOp::ShrAssign(_)
2449 )
2450}
2451
2452/// The Nim literal suffix for an integer type (`5'i32`).
2453fn nim_suffix(t: &Nim) -> Result<&'static str, String> {
2454 let Nim::Prim(p) = t else {
2455 return Err("not a primitive integer".into());
2456 };
2457 Ok(match p.as_str() {
2458 "int8" => "i8",
2459 "int16" => "i16",
2460 "int32" => "i32",
2461 "int64" => "i64",
2462 "int" => "i",
2463 "uint8" => "u8",
2464 "uint16" => "u16",
2465 "uint32" => "u32",
2466 "uint64" => "u64",
2467 "uint" => "u",
2468 other => return Err(format!("no Nim literal suffix for `{other}`")),
2469 })
2470}
2471
2472/// The unsigned integer type of the same width, used to spell `wrapping_*`.
2473fn unsigned_peer(t: &Nim) -> Result<&'static str, String> {
2474 let Nim::Prim(p) = t else {
2475 return Err("not a primitive integer".into());
2476 };
2477 Ok(match p.as_str() {
2478 "int8" => "uint8",
2479 "int16" => "uint16",
2480 "int32" => "uint32",
2481 "int64" => "uint64",
2482 "int" => "uint",
2483 other => return Err(format!("`{other}` has no unsigned peer")),
2484 })
2485}
2486
Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 nandithebull 19h ago2487fn quote_meta(m: &syn::Meta) -> String {
2488 match m {
2489 syn::Meta::Path(p) => path_name(p),
2490 syn::Meta::List(l) => format!("{}(..)", path_name(&l.path)),
2491 syn::Meta::NameValue(nv) => format!("{} = ..", path_name(&nv.path)),
2492 }
2493}
2494
2495fn item_attrs(i: &Item) -> &[syn::Attribute] {
2496 match i {
2497 Item::Fn(f) => &f.attrs,
2498 Item::Struct(s) => &s.attrs,
2499 Item::Enum(e) => &e.attrs,
2500 Item::Impl(x) => &x.attrs,
2501 Item::Const(c) => &c.attrs,
2502 Item::Type(t) => &t.attrs,
2503 Item::Mod(m) => &m.attrs,
2504 Item::Use(u) => &u.attrs,
2505 Item::ExternCrate(e) => &e.attrs,
2506 Item::Static(s) => &s.attrs,
2507 _ => &[],
2508 }
2509}
2510
Add the differential test runner, and a lowering to measure with it 8ac32af nandithebull 19h ago2511fn item_kind(i: &Item) -> &'static str {
2512 match i {
2513 Item::Trait(_) => "`trait`",
2514 Item::Static(_) => "`static`",
2515 Item::Macro(_) => "macro definition",
2516 Item::Union(_) => "`union`",
2517 Item::ForeignMod(_) => "`extern` block",
2518 _ => "item",
2519 }
2520}
2521
2522fn expr_kind(e: &Expr) -> &'static str {
2523 match e {
2524 Expr::Closure(_) => "closure",
2525 Expr::Async(_) => "`async` block",
2526 Expr::Await(_) => "`.await`",
2527 Expr::Try(_) => "`?`",
2528 Expr::Range(_) => "range",
2529 Expr::Match(_) => "`match` (only statement position is implemented)",
2530 Expr::Let(_) => "`let` expression",
2531 Expr::Unsafe(_) => "`unsafe` block",
2532 Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_) => "loop (has no value in Nim)",
2533 _ => "expression",
2534 }
2535}