Skip to main content

bynk_check/
wire_default.rs

1use std::sync::Arc;
2
3/// #2607: why a field default has no wire (or in-memory) form. A default that
4/// reaches a name no type declares is kept apart, because in a generic record
5/// that name is a type parameter, and the checker says so rather than relaying
6/// the message.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum DefaultReason {
9    /// The default reaches a type named by nothing in scope (in a generic
10    /// record, its type parameter).
11    UnresolvedType(String),
12    /// Any other reason, as a message.
13    Invalid(String),
14}
15
16impl std::fmt::Display for DefaultReason {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        match self {
19            DefaultReason::UnresolvedType(name) => write!(f, "cannot resolve type `{name}`"),
20            DefaultReason::Invalid(message) => f.write_str(message),
21        }
22    }
23}
24
25impl From<String> for DefaultReason {
26    fn from(message: String) -> Self {
27        DefaultReason::Invalid(message)
28    }
29}
30
31impl From<&str> for DefaultReason {
32    fn from(message: &str) -> Self {
33        DefaultReason::Invalid(message.to_string())
34    }
35}
36
37use bynk_syntax::ast::{
38    BaseType, Expr, ExprKind, RecordBody, SumBody, TypeBody, TypeDecl, TypeRef, UnaryOp,
39};
40
41/// Events slice 3a (#972): whether an event field's default is closed-form, so that the JSON
42/// it deserialises from when its key is absent from the incoming JSON can be built. Type-directed
43/// — given the field's expected `TypeRef` and the visible `types` table, every syntactic
44/// ambiguity (a bare `Ident` that is really a sum variant, a `FieldAccess` that is a qualified
45/// nullary variant) resolves the same way the checker resolves it, just narrower (a bare name
46/// must match a variant of *this* expected sum specifically) — so this needs no per-expression
47/// `Ty` map (`expr_types`), which a subscriber regenerating a publisher's own event codec
48/// (`emit_consumed_context_helpers`) has no way to obtain anyway.
49///
50/// It is the checker's validation and nothing else (1A.40b, #3996): `Err(reason)` for anything
51/// not closed-form, which `bynk.types.bad_field_default` reports at check time, and `Ok(())`
52/// otherwise. The **wire form** of a default the emitter splices into a codec is a pure function
53/// of [`field_default_value`]'s tree (`wire_default_node` in `bynk-emit`), so this crate writes
54/// no TypeScript text for it. The two walks share `sum_default_parts`, `record_default_field`,
55/// `inst_record_fields` and `base_value`; a test pins that they agree on every case.
56pub fn lower_field_default_wire(
57    init: &Expr,
58    expected: &TypeRef,
59    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
60) -> Result<(), DefaultReason> {
61    lower_field_default_wire_in(init, expected, types, &[])
62}
63
64/// The deepest chain of generic instantiations a default may expand through.
65/// A default that names its own type (`type Tree[T] = { kid: Tree[T] = Tree {} }`)
66/// would otherwise render forever (#2690).
67const MAX_DEFAULT_DEPTH: usize = 16;
68
69/// Where a default is being rendered: the type parameters of the declaration it
70/// belongs to (#2690), which stand for no value whatever `types` holds under the
71/// same name, and how deep the instantiations nest.
72#[derive(Clone, Copy)]
73struct Cx<'a> {
74    params: &'a [String],
75    depth: usize,
76    /// Whether a field that applies a user generic may carry a default. A record
77    /// field may (#2690); an event field and an old-state field may not.
78    generics: bool,
79}
80
81impl<'a> Cx<'a> {
82    fn deeper(self) -> Result<Self, DefaultReason> {
83        if self.depth >= MAX_DEFAULT_DEPTH {
84            return Err(DefaultReason::from(
85                "the default nests generic instantiations too deeply".to_string(),
86            ));
87        }
88        Ok(Cx {
89            depth: self.depth + 1,
90            ..self
91        })
92    }
93}
94
95/// [`lower_field_default_wire`] for a field of a declaration whose type
96/// parameters are `params` (#2690): a default that needs a value of one of them
97/// is [`DefaultReason::UnresolvedType`], even when a type of that name is
98/// declared.
99pub fn lower_field_default_wire_in(
100    init: &Expr,
101    expected: &TypeRef,
102    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
103    params: &[String],
104) -> Result<(), DefaultReason> {
105    wire_in(
106        init,
107        expected,
108        types,
109        Cx {
110            params,
111            depth: 0,
112            generics: true,
113        },
114    )
115}
116
117/// [`lower_field_default_wire`] for an event field or an old-state field, whose
118/// default may not apply a user generic anywhere in it (#2690 widened record
119/// fields only; the event codec and the migration read the default with no
120/// diagnostic path of their own).
121pub fn lower_event_field_default_wire(
122    init: &Expr,
123    expected: &TypeRef,
124    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
125) -> Result<(), DefaultReason> {
126    wire_in(
127        init,
128        expected,
129        types,
130        Cx {
131            params: &[],
132            depth: 0,
133            generics: false,
134        },
135    )
136}
137
138fn wire_in(
139    init: &Expr,
140    expected: &TypeRef,
141    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
142    cx: Cx<'_>,
143) -> Result<(), DefaultReason> {
144    if let ExprKind::Paren(inner) = &init.kind {
145        return wire_in(inner, expected, types, cx);
146    }
147    match expected {
148        TypeRef::Base(b, _) => check_base(*b, init),
149        TypeRef::Named(id) => {
150            if cx.params.contains(&id.name) {
151                return Err(DefaultReason::UnresolvedType(id.name.clone()));
152            }
153            let Some(decl) = types.get(&id.name) else {
154                return Err(DefaultReason::UnresolvedType(id.name.clone()));
155            };
156            match &decl.body {
157                TypeBody::Refined { base, .. } => check_base(*base, init),
158                // ADR 0182: `.unsafe`'s value is an identity cast (`return
159                // value as T;`, `emit.rs`'s opaque emission) — the literal
160                // itself, verbatim, is the wire form. (Its refinement is
161                // additionally checked *statically* for an event field
162                // default specifically — `check_event_field_default` — since
163                // this literal re-enters the same codec a real wire value
164                // would, unlike an ordinary `.unsafe` bypass.)
165                TypeBody::Opaque { base, .. } => match qualified_call(init) {
166                    Some((type_name, "unsafe", [lit])) if type_name == id.name => {
167                        check_base(*base, lit)
168                    }
169                    Some((_, "unsafe", _)) => Err(DefaultReason::from(
170                        "`.unsafe` takes exactly one argument".to_string(),
171                    )),
172                    _ => Err(DefaultReason::from(format!(
173                        "an opaque type's default must be `{}.unsafe(<literal>)`",
174                        id.name
175                    ))),
176                },
177                TypeBody::Sum(s) => lower_sum_default(&id.name, &body_variants(s), init, types, cx),
178                TypeBody::Record(r) => lower_record_default(&body_fields(r), init, types, cx),
179            }
180        }
181        // #2690: a field typed by a generic record or sum. The declaration's
182        // fields are read at the instantiation, so a default is a closed-form
183        // value of `Paginated[String]`; an argument that is the enclosing
184        // declaration's own parameter stays unresolved, so only a value with no
185        // content of that type qualifies.
186        TypeRef::App { name, args, .. } => {
187            if !cx.generics {
188                return Err(DefaultReason::from(
189                    "only a record field's default may apply a generic record or sum".to_string(),
190                ));
191            }
192            let cx = cx.deeper()?;
193            match types.get(&name.name).map(|d| &d.body) {
194                Some(TypeBody::Record(_)) => {
195                    let fields = inst_record_fields(&name.name, args, types)?;
196                    lower_record_default(&fields, init, types, cx)
197                }
198                Some(TypeBody::Sum(_)) => {
199                    let variants = crate::wire::sum_inst_variants(&name.name, args, types)
200                        .ok_or_else(|| {
201                            DefaultReason::from("a generic sum's arity does not match".to_string())
202                        })?;
203                    lower_sum_default(&name.name, &variants, init, types, cx)
204                }
205                _ => Err(DefaultReason::UnresolvedType(name.name.clone())),
206            }
207        }
208        TypeRef::Option(inner, _) => match &init.kind {
209            ExprKind::None => Ok(()),
210            ExprKind::Some(e) => wire_in(e, inner, types, cx),
211            _ => Err(DefaultReason::from(
212                "an `Option` field default must be `Some(...)` or `None`".to_string(),
213            )),
214        },
215        TypeRef::Result(ok, err, _) => match &init.kind {
216            ExprKind::Ok(e) => wire_in(e, ok, types, cx),
217            ExprKind::Err(e) => wire_in(e, err, types, cx),
218            _ => Err(DefaultReason::from(
219                "a `Result` field default must be `Ok(...)` or `Err(...)`".to_string(),
220            )),
221        },
222        TypeRef::List(elem, _) => match &init.kind {
223            ExprKind::ListLit(items, ..) => {
224                items.iter().try_for_each(|e| wire_in(e, elem, types, cx))
225            }
226            _ => Err(DefaultReason::from(
227                "a `List` field default must be a list literal".to_string(),
228            )),
229        },
230        // #2607 (Decision B): `Map.empty()` / `Set.empty()` are the only
231        // closed-form map and set values. Both travel as a JSON array (a map
232        // as its entries, a set as its elements), and both are empty.
233        TypeRef::Map(..) => empty_collection(init, "Map"),
234        TypeRef::Set(..) => empty_collection(init, "Set"),
235        TypeRef::Effect(..)
236        | TypeRef::HttpResult(..)
237        | TypeRef::QueueResult(_)
238        | TypeRef::Asset(_)
239        | TypeRef::RequestHeaders(_)
240        | TypeRef::RequestQuery(_)
241        | TypeRef::RequestCookies(_)
242        | TypeRef::TokenClaims(_)
243        | TypeRef::BoundaryRejection(_)
244        | TypeRef::Query(..)
245        | TypeRef::Stream(..)
246        | TypeRef::Connection(..)
247        | TypeRef::History(..)
248        | TypeRef::ValidationError(_)
249        | TypeRef::DecodeError(_)
250        | TypeRef::Unit(_)
251        | TypeRef::Fn(..) => Err(DefaultReason::from(
252            "this field type is not wire-representable".to_string(),
253        )),
254    }
255}
256
257/// The wire form of a base-type literal — the raw literal a real wire value
258/// of this base type would also be, so it re-enters
259/// `emit_field_deserialise`'s (`bynk-emit`) ordinary `typeof`/
260/// `Number.isInteger` checks unchanged. `Bytes` has no literal syntax, so it
261/// is not admitted.
262/// A qualified `TypeName.method(args)` call, in whichever `ExprKind` shape it
263/// actually parses as. Confirmed empirically (`OrderId.unsafe("x")` parses to
264/// `ExprKind::MethodCall { receiver: Ident("OrderId"), method: "unsafe", .. }`
265/// — the parser never distinguishes a type-qualified call from an ordinary
266/// instance method call; that's a resolver-time decision).
267fn qualified_call(e: &Expr) -> Option<(&str, &str, &[Expr])> {
268    match &e.kind {
269        ExprKind::MethodCall {
270            receiver,
271            method,
272            args,
273            ..
274        } => {
275            let ExprKind::Ident(recv) = &receiver.kind else {
276                return None;
277            };
278            Some((recv.name.as_str(), method.name.as_str(), args.as_slice()))
279        }
280        _ => None,
281    }
282}
283
284/// Whether `e` is a closed-form literal of `base`: [`base_value`], read for its verdict.
285fn check_base(base: BaseType, e: &Expr) -> Result<(), DefaultReason> {
286    base_value(base, e).map(drop)
287}
288
289/// A base-type literal as plain data. [`field_default_value`] reads it for the value, and
290/// [`check_base`] for the verdict.
291fn base_value(base: BaseType, e: &Expr) -> Result<DefaultValue, DefaultReason> {
292    // Strip one level of negation so `-5`/`-5.0` reach the literal arms below,
293    // mirroring `const_literal`'s admission — `i64::checked_neg` guards
294    // `i64::MIN`, which has no positive counterpart to negate away from.
295    let (negate, inner) = match &e.kind {
296        ExprKind::UnaryOp(UnaryOp::Neg, inner) => (true, &inner.kind),
297        other => (false, other),
298    };
299    match (base, inner) {
300        (BaseType::Int | BaseType::Instant, ExprKind::IntLit { value, .. }) => {
301            let v = if negate {
302                value
303                    .checked_neg()
304                    .ok_or_else(|| "integer literal has no negation".to_string())?
305            } else {
306                *value
307            };
308            Ok(DefaultValue::Num(v.to_string()))
309        }
310        (BaseType::Float, ExprKind::IntLit { value, .. }) => {
311            let v = if negate { -*value } else { *value };
312            Ok(DefaultValue::Num(v.to_string()))
313        }
314        (BaseType::Float, ExprKind::FloatLit { lexeme, .. }) => Ok(DefaultValue::Num(if negate {
315            format!("-{lexeme}")
316        } else {
317            lexeme.clone()
318        })),
319        // #3801: a `Decimal` is its coefficient and scale; the wire text is rendered from
320        // them by [`lower_base_literal`] (#2622), the in-memory value by the emitter.
321        (BaseType::Decimal, ExprKind::DecimalLit { coef, scale, .. }) => {
322            let signed = if negate && bynk_syntax::decimal::sign(coef) != 0 {
323                format!("-{coef}")
324            } else {
325                coef.clone()
326            };
327            Ok(DefaultValue::Decimal {
328                coefficient: signed,
329                scale: *scale,
330            })
331        }
332        (BaseType::String, ExprKind::StrLit(s)) if !negate => Ok(DefaultValue::Str(s.clone())),
333        (BaseType::Bool, ExprKind::BoolLit(b)) if !negate => Ok(DefaultValue::Bool(*b)),
334        (BaseType::Duration, ExprKind::DurationLit { millis, .. }) if !negate => {
335            Ok(DefaultValue::Num(millis.to_string()))
336        }
337        (BaseType::Bytes, _) => Err(DefaultReason::from(
338            "a `Bytes` field has no literal default form".to_string(),
339        )),
340        _ => Err(DefaultReason::from(format!(
341            "expected a `{}` literal",
342            base.name()
343        ))),
344    }
345}
346
347/// The wire form of a sum-variant default: `{ kind: "Variant" }` (nullary) or
348/// `{ kind: "Variant", f1: ..., f2: ... }` (payload, positionally recursed
349/// against each field's *declared* type) — never a qualified reference into
350/// the sum's generated value namespace (`Sum.Variant`), which is what the
351/// ordinary handler-body lowering (`lower_expr_into`) would produce and which
352/// a foreign module regenerating this codec cannot import.
353fn lower_sum_default(
354    sum_name: &str,
355    variants: &InstVariants,
356    init: &Expr,
357    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
358    cx: Cx<'_>,
359) -> Result<(), DefaultReason> {
360    let (variant, args) = sum_default_parts(sum_name, variants, init)?;
361    for ((_, ty), arg) in variant.1.iter().zip(args.iter()) {
362        wire_in(arg, ty, types, cx)?;
363    }
364    Ok(())
365}
366
367/// A sum's variants with their payload field types, as written (a non-generic
368/// sum) or substituted (an instantiation, `wire::sum_inst_variants`).
369type InstVariants = Vec<InstVariant>;
370
371/// One variant: its name and payload `(field, type)` list.
372type InstVariant = (String, Vec<(String, TypeRef)>);
373
374fn body_variants(body: &SumBody) -> InstVariants {
375    body.variants
376        .iter()
377        .map(|v| {
378            (
379                v.name.name.clone(),
380                v.payload
381                    .iter()
382                    .map(|f| (f.name.name.clone(), f.type_ref.clone()))
383                    .collect(),
384            )
385        })
386        .collect()
387}
388
389/// A record's fields as `(name, type, declared default)`: as written (a
390/// non-generic record) or substituted (an instantiation).
391type InstFields<'a> = Vec<(String, TypeRef, Option<&'a Expr>)>;
392
393fn body_fields(body: &RecordBody) -> InstFields<'_> {
394    body.fields
395        .iter()
396        .map(|f| (f.name.name.clone(), f.type_ref.clone(), f.init.as_ref()))
397        .collect()
398}
399
400/// #2690: the fields of the generic record `name[args]`, types substituted, each
401/// with the default the declaration gives it.
402fn inst_record_fields<'a>(
403    name: &str,
404    args: &[TypeRef],
405    types: &'a std::collections::HashMap<String, Arc<TypeDecl>>,
406) -> Result<InstFields<'a>, DefaultReason> {
407    let inst = crate::wire::record_inst_fields(name, args, types).ok_or_else(|| {
408        DefaultReason::from("a generic record's arity does not match".to_string())
409    })?;
410    let Some(TypeBody::Record(r)) = types.get(name).map(|d| &d.body) else {
411        return Err(DefaultReason::UnresolvedType(name.to_string()));
412    };
413    Ok(inst
414        .into_iter()
415        .zip(r.fields.iter())
416        .map(|((n, t), f)| (n, t, f.init.as_ref()))
417        .collect())
418}
419
420/// The variant a sum default names, and its payload arguments — shared by the
421/// wire and in-memory renderings so both read a default identically.
422fn sum_default_parts<'a>(
423    sum_name: &str,
424    variants: &'a InstVariants,
425    init: &'a Expr,
426) -> Result<(&'a InstVariant, &'a [Expr]), DefaultReason> {
427    let (variant_name, args): (&str, &[Expr]) = match &init.kind {
428        ExprKind::Ident(id) => (id.name.as_str(), &[]),
429        ExprKind::FieldAccess { receiver, field } => {
430            let ExprKind::Ident(recv) = &receiver.kind else {
431                return Err(DefaultReason::from(format!(
432                    "expected a variant of `{sum_name}`"
433                )));
434            };
435            if recv.name != sum_name {
436                return Err(DefaultReason::from(format!(
437                    "expected a variant of `{sum_name}`, not `{}`",
438                    recv.name
439                )));
440            }
441            (field.name.as_str(), &[])
442        }
443        ExprKind::Call { name, args, .. } => (name.name.as_str(), args.as_slice()),
444        _ => match qualified_call(init) {
445            Some((recv, method, args)) if recv == sum_name => (method, args),
446            Some((recv, ..)) => {
447                return Err(DefaultReason::from(format!(
448                    "expected a variant of `{sum_name}`, not `{recv}`"
449                )));
450            }
451            None => {
452                return Err(DefaultReason::from(format!(
453                    "expected a variant of `{sum_name}`"
454                )));
455            }
456        },
457    };
458    let Some(variant) = variants.iter().find(|v| v.0 == variant_name) else {
459        return Err(DefaultReason::from(format!(
460            "`{variant_name}` is not a variant of `{sum_name}`"
461        )));
462    };
463    if args.len() != variant.1.len() {
464        return Err(DefaultReason::from(format!(
465            "`{variant_name}` takes {} payload field(s), got {}",
466            variant.1.len(),
467            args.len()
468        )));
469    }
470    Ok((variant, args))
471}
472
473/// The wire form of a record-literal default: a plain object literal, each
474/// field recursed against its *declared* type. Records are structurally
475/// wire-shaped (never tagged, never a named constructor), so this never
476/// needs qualification either.
477fn lower_record_default(
478    fields_of: &InstFields<'_>,
479    init: &Expr,
480    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
481    cx: Cx<'_>,
482) -> Result<(), DefaultReason> {
483    let ExprKind::RecordConstruction { fields, .. } = &init.kind else {
484        return Err(DefaultReason::from("expected a record literal".to_string()));
485    };
486    for (name, ty, declared) in fields_of {
487        let value = record_default_field(fields, name, *declared)?;
488        wire_in(value, ty, types, cx)?;
489    }
490    Ok(())
491}
492
493/// #2607: the value a record literal written as a default gives field `name` —
494/// its own written value, or, when it leaves it out, the field's declared default.
495fn record_default_field<'a>(
496    fields: &'a [bynk_syntax::ast::FieldInit],
497    name: &str,
498    declared: Option<&'a Expr>,
499) -> Result<&'a Expr, DefaultReason> {
500    match fields.iter().find(|fi| fi.name.name == name) {
501        Some(given) => given.value.as_ref().ok_or_else(|| {
502            DefaultReason::from(format!(
503                "record default's field `{name}` cannot use shorthand (no bindings are in scope)"
504            ))
505        }),
506        None => declared.ok_or_else(|| {
507            DefaultReason::from(format!("record default is missing field `{name}`"))
508        }),
509    }
510}
511
512/// #2607 (Decision B): accepts exactly `<collection>.empty()`.
513fn empty_collection(init: &Expr, collection: &str) -> Result<(), DefaultReason> {
514    match qualified_call(init) {
515        Some((recv, "empty", [])) if recv == collection => Ok(()),
516        _ => Err(DefaultReason::from(format!(
517            "a `{collection}` field default must be `{collection}.empty()`"
518        ))),
519    }
520}
521
522/// #2607 (Decision C): the **in-memory** value a record literal takes for a field it leaves
523/// out, as plain data — the twin of [`lower_field_default_wire`], over the same closed set of
524/// static values, but in the shape a Bynk value has at runtime (a sum and `Option`/`Result`
525/// carry a variant tag, a `Map`/`Set` is a real collection) rather than its wire JSON.
526///
527/// It is a tree, not text, so the front half knows nothing of TypeScript (1A.31, #3732): the
528/// emitter turns it into nodes (`default_value_node` in `bynk-emit`), writing each tag
529/// `as const` so that an unannotated `const x = { … }` in a test body does not widen `tag` to
530/// `string` (#3404).
531///
532/// It is self-contained on purpose: a literal may build a record declared in another unit
533/// (`FetchOptions` from `bynk`), whose default names values (`Redirect.Follow`) the literal's
534/// own module never imports. Each value is structural, so it needs no import at all, the
535/// reason the wire form is structural too.
536#[derive(Debug, Clone, PartialEq, Eq)]
537pub enum DefaultValue {
538    /// A number's lexeme, sign included (`5`, `-5`, `1e3`, `3600000`).
539    Num(String),
540    /// A string's value, unescaped.
541    Str(String),
542    Bool(bool),
543    /// A `Decimal`: its coefficient's digits, sign included, and its scale (#3801). In memory
544    /// it is `{ coefficient, scale }`; only the wire form is the canonical text.
545    Decimal {
546        coefficient: String,
547        scale: u32,
548    },
549    /// A value of the refined type `name` (#3759): its base value, which the checker has
550    /// already found satisfies the refinement. The emitter brands the field that holds it.
551    Refined {
552        name: String,
553        value: Box<DefaultValue>,
554    },
555    /// A record: every declared field, in declaration order.
556    Record(Vec<(String, DefaultValue)>),
557    /// A sum variant and its payload fields.
558    Sum {
559        variant: String,
560        fields: Vec<(String, DefaultValue)>,
561    },
562    Some(Box<DefaultValue>),
563    None,
564    Ok(Box<DefaultValue>),
565    Err(Box<DefaultValue>),
566    List(Vec<DefaultValue>),
567    EmptyMap,
568    EmptySet,
569}
570
571impl DefaultValue {
572    /// Whether the value holds a refined value anywhere (#3759): its field then needs a cast to
573    /// the field's declared type, which brands it.
574    pub fn holds_refined(&self) -> bool {
575        match self {
576            DefaultValue::Refined { .. } => true,
577            DefaultValue::Record(fields) | DefaultValue::Sum { fields, .. } => {
578                fields.iter().any(|(_, v)| v.holds_refined())
579            }
580            DefaultValue::Some(v) | DefaultValue::Ok(v) | DefaultValue::Err(v) => v.holds_refined(),
581            DefaultValue::List(items) => items.iter().any(DefaultValue::holds_refined),
582            DefaultValue::Num(_)
583            | DefaultValue::Str(_)
584            | DefaultValue::Bool(_)
585            | DefaultValue::Decimal { .. }
586            | DefaultValue::None
587            | DefaultValue::EmptyMap
588            | DefaultValue::EmptySet => false,
589        }
590    }
591}
592
593/// The [`DefaultValue`] of a field's default `init`, given the field's `expected` type and the
594/// visible `types` table. `Err` for anything not closed-form; the checker has already required
595/// every default to have one.
596pub fn field_default_value(
597    init: &Expr,
598    expected: &TypeRef,
599    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
600) -> Result<DefaultValue, DefaultReason> {
601    value_in(
602        init,
603        expected,
604        types,
605        Cx {
606            params: &[],
607            depth: 0,
608            generics: true,
609        },
610    )
611}
612
613fn value_in(
614    init: &Expr,
615    expected: &TypeRef,
616    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
617    cx: Cx<'_>,
618) -> Result<DefaultValue, DefaultReason> {
619    if let ExprKind::Paren(inner) = &init.kind {
620        return value_in(inner, expected, types, cx);
621    }
622    match expected {
623        TypeRef::Base(b, _) => base_value(*b, init),
624        TypeRef::Named(id) => {
625            if cx.params.contains(&id.name) {
626                return Err(DefaultReason::UnresolvedType(id.name.clone()));
627            }
628            let Some(decl) = types.get(&id.name) else {
629                return Err(DefaultReason::UnresolvedType(id.name.clone()));
630            };
631            match &decl.body {
632                TypeBody::Refined { base, .. } => Ok(DefaultValue::Refined {
633                    name: id.name.clone(),
634                    value: Box::new(base_value(*base, init)?),
635                }),
636                TypeBody::Opaque { base, .. } => match qualified_call(init) {
637                    Some((type_name, "unsafe", [lit])) if type_name == id.name => {
638                        base_value(*base, lit)
639                    }
640                    _ => Err(DefaultReason::from(format!(
641                        "an opaque type's default must be `{}.unsafe(<literal>)`",
642                        id.name
643                    ))),
644                },
645                TypeBody::Sum(s) => value_sum(&id.name, &body_variants(s), init, types, cx),
646                TypeBody::Record(r) => value_record(&body_fields(r), init, types, cx),
647            }
648        }
649        // #2690: see `wire_in`.
650        TypeRef::App { name, args, .. } => {
651            if !cx.generics {
652                return Err(DefaultReason::from(
653                    "only a record field's default may apply a generic record or sum".to_string(),
654                ));
655            }
656            let cx = cx.deeper()?;
657            match types.get(&name.name).map(|d| &d.body) {
658                Some(TypeBody::Record(_)) => {
659                    let fields = inst_record_fields(&name.name, args, types)?;
660                    value_record(&fields, init, types, cx)
661                }
662                Some(TypeBody::Sum(_)) => {
663                    let variants = crate::wire::sum_inst_variants(&name.name, args, types)
664                        .ok_or_else(|| {
665                            DefaultReason::from("a generic sum's arity does not match".to_string())
666                        })?;
667                    value_sum(&name.name, &variants, init, types, cx)
668                }
669                _ => Err(DefaultReason::UnresolvedType(name.name.clone())),
670            }
671        }
672        TypeRef::Option(inner, _) => match &init.kind {
673            ExprKind::None => Ok(DefaultValue::None),
674            ExprKind::Some(e) => Ok(DefaultValue::Some(Box::new(value_in(e, inner, types, cx)?))),
675            _ => Err(DefaultReason::from(
676                "an `Option` field default must be `Some(...)` or `None`".to_string(),
677            )),
678        },
679        TypeRef::Result(ok, err, _) => match &init.kind {
680            ExprKind::Ok(e) => Ok(DefaultValue::Ok(Box::new(value_in(e, ok, types, cx)?))),
681            ExprKind::Err(e) => Ok(DefaultValue::Err(Box::new(value_in(e, err, types, cx)?))),
682            _ => Err(DefaultReason::from(
683                "a `Result` field default must be `Ok(...)` or `Err(...)`".to_string(),
684            )),
685        },
686        TypeRef::List(elem, _) => match &init.kind {
687            ExprKind::ListLit(items, ..) => items
688                .iter()
689                .map(|e| value_in(e, elem, types, cx))
690                .collect::<Result<Vec<_>, _>>()
691                .map(DefaultValue::List),
692            _ => Err(DefaultReason::from(
693                "a `List` field default must be a list literal".to_string(),
694            )),
695        },
696        TypeRef::Map(..) => empty_collection(init, "Map").map(|()| DefaultValue::EmptyMap),
697        TypeRef::Set(..) => empty_collection(init, "Set").map(|()| DefaultValue::EmptySet),
698        // Every other type is rejected by `lower_field_default_wire` at check
699        // time, so a program that reaches emission never asks: a field that
700        // applies a user generic (`App`), and the types with no wire form
701        // (`Effect`, `HttpResult`, `QueueResult`, `Query`, `Stream`,
702        // `Connection`, `History`, `Fn`, `Asset`, `RequestHeaders`,
703        // `TokenClaims`, `BoundaryRejection`, `ValidationError`, `DecodeError`
704        // and `Unit`).
705        _ => Err(DefaultReason::from(
706            "this field type cannot carry a default".to_string(),
707        )),
708    }
709}
710
711/// The in-memory twin of [`lower_sum_default`]: the wire form is
712/// `{ kind: "V", … }`; in memory the discriminant is the variant, and the payload
713/// fields recurse in their own in-memory form.
714fn value_sum(
715    sum_name: &str,
716    variants: &InstVariants,
717    init: &Expr,
718    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
719    cx: Cx<'_>,
720) -> Result<DefaultValue, DefaultReason> {
721    let (variant, args) = sum_default_parts(sum_name, variants, init)?;
722    let mut fields = Vec::new();
723    for ((field, ty), arg) in variant.1.iter().zip(args.iter()) {
724        fields.push((field.clone(), value_in(arg, ty, types, cx)?));
725    }
726    Ok(DefaultValue::Sum {
727        variant: variant.0.clone(),
728        fields,
729    })
730}
731
732/// The in-memory twin of [`lower_record_default`].
733fn value_record(
734    fields_of: &InstFields<'_>,
735    init: &Expr,
736    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
737    cx: Cx<'_>,
738) -> Result<DefaultValue, DefaultReason> {
739    let ExprKind::RecordConstruction { fields, .. } = &init.kind else {
740        return Err(DefaultReason::from("expected a record literal".to_string()));
741    };
742    let mut parts = Vec::new();
743    for (name, ty, declared) in fields_of {
744        let value = record_default_field(fields, name, *declared)?;
745        parts.push((name.to_string(), value_in(value, ty, types, cx)?));
746    }
747    Ok(DefaultValue::Record(parts))
748}
749
750#[cfg(test)]
751mod tests {
752    use super::*;
753    use bynk_syntax::ast::CommonsItem;
754    use std::collections::HashMap;
755
756    /// The shared declarations the cases lean on.
757    const PRELUDE: &str = "commons x\n\n\
758        type Age = Int where InRange(0, 150)\n\
759        type Tok = opaque String\n\
760        type Plan = enum { Free, Pro }\n\
761        type Shape = | Dot | Circle(r: Float) | Rect(w: Int, h: Int)\n\
762        type Inner = { n: Int = 7, s: String = \"i\" }\n\
763        type Box[A] = { value: A }\n\
764        type Opt[T] = | Has(value: T) | Nil\n\
765        type Loop[T] = { kid: Loop[T] = Loop { } }\n";
766
767    fn num(s: &str) -> DefaultValue {
768        DefaultValue::Num(s.to_string())
769    }
770    fn text(s: &str) -> DefaultValue {
771        DefaultValue::Str(s.to_string())
772    }
773    fn some(v: DefaultValue) -> DefaultValue {
774        DefaultValue::Some(Box::new(v))
775    }
776    fn dec(coefficient: &str, scale: u32) -> DefaultValue {
777        DefaultValue::Decimal {
778            coefficient: coefficient.to_string(),
779            scale,
780        }
781    }
782    fn refined(name: &str, v: DefaultValue) -> DefaultValue {
783        DefaultValue::Refined {
784            name: name.to_string(),
785            value: Box::new(v),
786        }
787    }
788    fn sum(variant: &str, fields: Vec<(&str, DefaultValue)>) -> DefaultValue {
789        DefaultValue::Sum {
790            variant: variant.to_string(),
791            fields: fields
792                .into_iter()
793                .map(|(k, v)| (k.to_string(), v))
794                .collect(),
795        }
796    }
797    fn record(fields: Vec<(&str, DefaultValue)>) -> DefaultValue {
798        DefaultValue::Record(
799            fields
800                .into_iter()
801                .map(|(k, v)| (k.to_string(), v))
802                .collect(),
803        )
804    }
805
806    /// `(field type, default, the tree, the text the deleted `lower_field_default_value` produced)`.
807    /// The text column was captured from the `String` renderer before it was deleted
808    /// (1A.31, #3732), so the old output and the new tree sit side by side; `bynk-emit` prints
809    /// each tree and compares it with the same text. The `Decimal` rows (#3801) are the corrected
810    /// text: the old renderer wrote the wire string there.
811    pub fn cases() -> Vec<(&'static str, &'static str, DefaultValue, &'static str)> {
812        vec![
813            ("Int", "5", num("5"), "5"),
814            ("Int", "-5", num("-5"), "-5"),
815            ("Instant", "0", num("0"), "0"),
816            ("Float", "1.5", num("1.5"), "1.5"),
817            ("Float", "5", num("5"), "5"),
818            ("Float", "1e3", num("1e3"), "1e3"),
819            ("Float", "-2.5", num("-2.5"), "-2.5"),
820            ("Float", "-5", num("-5"), "-5"),
821            ("Duration", "5.minutes", num("300000"), "300000"),
822            ("Bool", "true", DefaultValue::Bool(true), "true"),
823            ("String", "\"x\"", text("x"), "\"x\""),
824            ("String", "\"a\\\"b\\n\"", text("a\"b\n"), "\"a\\\"b\\n\""),
825            ("String", "\"\"", text(""), "\"\""),
826            // #3801: in memory, a `Decimal` is its coefficient and scale, not its wire text.
827            (
828                "Decimal",
829                "0.00d",
830                dec("000", 2),
831                "{ coefficient: 0n, scale: 2 }",
832            ),
833            (
834                "Decimal",
835                "-1.50d",
836                dec("-150", 2),
837                "{ coefficient: -150n, scale: 2 }",
838            ),
839            // #3759: a refined default is marked; the emitter brands the field that holds it.
840            ("Age", "3", refined("Age", num("3")), "3"),
841            ("Tok", "Tok.unsafe(\"k\")", text("k"), "\"k\""),
842            (
843                "Inner",
844                "Inner { }",
845                record(vec![("n", num("7")), ("s", text("i"))]),
846                "{ n: 7, s: \"i\" }",
847            ),
848            (
849                "Inner",
850                "Inner { n: 9 }",
851                record(vec![("n", num("9")), ("s", text("i"))]),
852                "{ n: 9, s: \"i\" }",
853            ),
854            (
855                "Plan",
856                "Free",
857                sum("Free", vec![]),
858                "{ tag: \"Free\" as const }",
859            ),
860            (
861                "Shape",
862                "Dot",
863                sum("Dot", vec![]),
864                "{ tag: \"Dot\" as const }",
865            ),
866            (
867                "Shape",
868                "Rect(1, -2)",
869                sum("Rect", vec![("w", num("1")), ("h", num("-2"))]),
870                "{ tag: \"Rect\" as const, w: 1, h: -2 }",
871            ),
872            (
873                "Option[Int]",
874                "Some(1)",
875                some(num("1")),
876                "{ tag: \"Some\" as const, value: 1 }",
877            ),
878            (
879                "Option[Int]",
880                "None",
881                DefaultValue::None,
882                "{ tag: \"None\" as const }",
883            ),
884            (
885                "Option[Option[Int]]",
886                "Some(None)",
887                some(DefaultValue::None),
888                "{ tag: \"Some\" as const, value: { tag: \"None\" as const } }",
889            ),
890            (
891                "Result[Int, String]",
892                "Ok(1)",
893                DefaultValue::Ok(Box::new(num("1"))),
894                "{ tag: \"Ok\" as const, value: 1 }",
895            ),
896            (
897                "Result[Int, String]",
898                "Err(\"e\")",
899                DefaultValue::Err(Box::new(text("e"))),
900                "{ tag: \"Err\" as const, error: \"e\" }",
901            ),
902            ("List[Int]", "[]", DefaultValue::List(vec![]), "[]"),
903            (
904                "List[Int]",
905                "[1, 2]",
906                DefaultValue::List(vec![num("1"), num("2")]),
907                "[1, 2]",
908            ),
909            (
910                "List[Option[Int]]",
911                "[None, Some(2)]",
912                DefaultValue::List(vec![DefaultValue::None, some(num("2"))]),
913                "[{ tag: \"None\" as const }, { tag: \"Some\" as const, value: 2 }]",
914            ),
915            (
916                "Map[String, Int]",
917                "Map.empty()",
918                DefaultValue::EmptyMap,
919                "new globalThis.Map()",
920            ),
921            (
922                "Set[Int]",
923                "Set.empty()",
924                DefaultValue::EmptySet,
925                "new globalThis.Set()",
926            ),
927            (
928                "Box[Int]",
929                "Box { value: 3 }",
930                record(vec![("value", num("3"))]),
931                "{ value: 3 }",
932            ),
933            (
934                "Opt[Int]",
935                "Has(4)",
936                sum("Has", vec![("value", num("4"))]),
937                "{ tag: \"Has\" as const, value: 4 }",
938            ),
939            (
940                "Opt[Int]",
941                "Nil",
942                sum("Nil", vec![]),
943                "{ tag: \"Nil\" as const }",
944            ),
945            (
946                "Box[Opt[String]]",
947                "Box { value: Has(\"s\") }",
948                record(vec![("value", sum("Has", vec![("value", text("s"))]))]),
949                "{ value: { tag: \"Has\" as const, value: \"s\" } }",
950            ),
951        ]
952    }
953
954    /// The `types` table and the `f` field of a record `Holder { f: <ty> = <init> }`.
955    pub fn holder(ty: &str, init: &str) -> (HashMap<String, Arc<TypeDecl>>, Expr, TypeRef) {
956        let src = format!("{PRELUDE}\ntype Holder = {{ f: {ty} = {init} }}\n");
957        let tokens = bynk_syntax::lexer::tokenize(&src).expect("lex");
958        let commons = bynk_syntax::parser::parse(&tokens, &src).expect("parse");
959        let types: HashMap<String, Arc<TypeDecl>> = commons
960            .items
961            .iter()
962            .filter_map(|i| match i {
963                CommonsItem::Type(t) => Some((t.name.name.clone(), Arc::new(t.clone()))),
964                _ => None,
965            })
966            .collect();
967        let TypeBody::Record(r) = &types["Holder"].body else {
968            panic!("Holder is a record");
969        };
970        let field = &r.fields[0];
971        (
972            types.clone(),
973            field.init.clone().expect("a default"),
974            field.type_ref.clone(),
975        )
976    }
977
978    /// #3759: only a value with a refined part needs its field branded.
979    #[test]
980    fn holds_refined_finds_a_refined_value_at_any_depth() {
981        let r = refined("Age", num("3"));
982        for v in [
983            r.clone(),
984            some(r.clone()),
985            DefaultValue::Err(Box::new(r.clone())),
986            DefaultValue::List(vec![num("1"), r.clone()]),
987            record(vec![("a", num("1")), ("b", r.clone())]),
988            sum("V", vec![("x", r)]),
989        ] {
990            assert!(v.holds_refined(), "{v:?}");
991        }
992        for v in [
993            num("3"),
994            dec("150", 2),
995            DefaultValue::None,
996            DefaultValue::List(vec![num("1")]),
997            record(vec![("a", text("x"))]),
998            DefaultValue::EmptyMap,
999        ] {
1000            assert!(!v.holds_refined(), "{v:?}");
1001        }
1002    }
1003
1004    #[test]
1005    fn field_default_value_builds_the_tree_for_every_shape() {
1006        for (ty, init, tree, _) in cases() {
1007            let (types, e, t) = holder(ty, init);
1008            assert_eq!(
1009                field_default_value(&e, &t, &types),
1010                Ok(tree),
1011                "{ty} = {init}"
1012            );
1013        }
1014    }
1015
1016    /// The validator and the tree the emitter renders agree on every default (1A.40b): the
1017    /// validator is `Ok` exactly when [`field_default_value`] is, so a default the checker admits
1018    /// is never silently dropped by the emitter's `.ok()`, and one it rejects never reaches a
1019    /// codec. The wording of a rejection may differ (`.unsafe`'s arity has its own message in the
1020    /// validator); the verdict may not.
1021    #[test]
1022    fn the_validator_and_the_tree_agree_on_every_default() {
1023        for (ty, init, _, _) in cases() {
1024            let (types, e, t) = holder(ty, init);
1025            assert_eq!(
1026                lower_field_default_wire(&e, &t, &types),
1027                Ok(()),
1028                "{ty} = {init}"
1029            );
1030            assert!(field_default_value(&e, &t, &types).is_ok(), "{ty} = {init}");
1031        }
1032        // The messages may differ (`.unsafe`'s arity has its own in the validator), and each walk
1033        // keeps its own wording; what must agree is the verdict.
1034        for (ty, init, _) in REJECTIONS {
1035            let (types, e, t) = holder(ty, init);
1036            assert!(
1037                field_default_value(&e, &t, &types).is_err(),
1038                "{ty} = {init}"
1039            );
1040            assert!(
1041                lower_field_default_wire(&e, &t, &types).is_err(),
1042                "{ty} = {init}"
1043            );
1044        }
1045    }
1046
1047    /// The two walks agree on the other two entry points too (1A.40c, a #4069 nit): the event and
1048    /// old-state path, whose defaults may not apply a user generic, and the generic-parameters
1049    /// path, where a parameter stands for no value. Same verdict on every accepted and rejected
1050    /// default, and the generic cases are where the three entry points differ.
1051    #[test]
1052    fn the_walks_agree_on_the_event_and_generic_params_paths() {
1053        let params = ["T".to_string()];
1054        let mut seen_generic_refusal = false;
1055        let defaults = cases()
1056            .into_iter()
1057            .map(|(ty, init, _, _)| (ty, init))
1058            .chain(REJECTIONS.iter().map(|(ty, init, _)| (*ty, *init)));
1059        for (ty, init) in defaults {
1060            let (types, e, t) = holder(ty, init);
1061            let event_cx = Cx {
1062                params: &[],
1063                depth: 0,
1064                generics: false,
1065            };
1066            let event = lower_event_field_default_wire(&e, &t, &types);
1067            let event_tree = value_in(&e, &t, &types, event_cx);
1068            assert_eq!(event.is_ok(), event_tree.is_ok(), "event: {ty} = {init}");
1069            let params_cx = Cx {
1070                params: &params,
1071                depth: 0,
1072                generics: true,
1073            };
1074            let generic = lower_field_default_wire_in(&e, &t, &types, &params);
1075            let generic_tree = value_in(&e, &t, &types, params_cx);
1076            assert_eq!(
1077                generic.is_ok(),
1078                generic_tree.is_ok(),
1079                "params: {ty} = {init}"
1080            );
1081            // The record path accepts what the event path refuses (a default applying a user
1082            // generic), so the three entry points are not one walk with the flag ignored.
1083            seen_generic_refusal |=
1084                lower_field_default_wire(&e, &t, &types).is_ok() && event.is_err();
1085        }
1086        assert!(
1087            seen_generic_refusal,
1088            "no case tells the event path from the record path"
1089        );
1090    }
1091
1092    /// `(field type, default, the rejection)` the old renderer gave, kept verbatim.
1093    pub const REJECTIONS: &[(&str, &str, &str)] = &[
1094        (
1095            "Loop[Int]",
1096            "Loop { }",
1097            "the default nests generic instantiations too deeply",
1098        ),
1099        ("Bytes", "x", "a `Bytes` field has no literal default form"),
1100        ("Int", "\"s\"", "expected a `Int` literal"),
1101        (
1102            "Tok",
1103            "Tok.unsafe(\"k\", 1)",
1104            "an opaque type's default must be `Tok.unsafe(<literal>)`",
1105        ),
1106        (
1107            "Tok",
1108            "5",
1109            "an opaque type's default must be `Tok.unsafe(<literal>)`",
1110        ),
1111        (
1112            "Option[Int]",
1113            "5",
1114            "an `Option` field default must be `Some(...)` or `None`",
1115        ),
1116        (
1117            "Result[Int, Int]",
1118            "5",
1119            "a `Result` field default must be `Ok(...)` or `Err(...)`",
1120        ),
1121        (
1122            "List[Int]",
1123            "5",
1124            "a `List` field default must be a list literal",
1125        ),
1126        (
1127            "Map[String, Int]",
1128            "5",
1129            "a `Map` field default must be `Map.empty()`",
1130        ),
1131        (
1132            "Set[Int]",
1133            "Set.empty(1)",
1134            "a `Set` field default must be `Set.empty()`",
1135        ),
1136        ("Effect[Int]", "5", "this field type cannot carry a default"),
1137        ("Inner", "5", "expected a record literal"),
1138        ("Shape", "Nope", "`Nope` is not a variant of `Shape`"),
1139        ("Box[Int]", "5", "expected a record literal"),
1140    ];
1141
1142    #[test]
1143    fn field_default_value_rejects_with_the_old_messages() {
1144        for (ty, init, msg) in REJECTIONS {
1145            let (types, e, t) = holder(ty, init);
1146            assert_eq!(
1147                field_default_value(&e, &t, &types),
1148                Err(DefaultReason::Invalid((*msg).to_string())),
1149                "{ty} = {init}"
1150            );
1151        }
1152        let (types, e, t) = holder("Missing", "Missing { }");
1153        assert_eq!(
1154            field_default_value(&e, &t, &types),
1155            Err(DefaultReason::UnresolvedType("Missing".to_string()))
1156        );
1157    }
1158}