Skip to main content

bynk_check/
consts.rs

1//! #2617 (named constants): the checker-side rules for `const Name: Type =
2//! <static expression>` declarations — the name rules, the closed set of
3//! static initialisers (ADR 0004, plus references to other constants), the
4//! cycle rule and the composition of a unit's visible constants through
5//! `uses`.
6//!
7//! A constant is a value in its unit's single value namespace (spec §5.1),
8//! like a function, an asset or an embed: a unit that `uses` a commons sees
9//! its constants, and a sibling file of the same unit imports them as it
10//! imports a function. Its type is its annotation, resolved where it is used.
11//! It emits as a hoisted, cached function (spec §7.3.1a), so neither the
12//! order of a file's constants nor the order in which a unit's file modules
13//! evaluate matters.
14
15use std::collections::{BTreeMap, HashMap, HashSet};
16use std::sync::Arc;
17
18use bynk_syntax::ast::{
19    BaseType, CommonsItem, ConstDecl, Expr, ExprKind, FnName, Ident, TypeBody, TypeDecl, TypeRef,
20    UnaryOp,
21};
22use bynk_syntax::error::CompileError;
23
24use crate::project_model::UnitInfo;
25use crate::symbols::UnitTable;
26
27/// Whether `name` is upper-camel case: the lexer's `constant_name` class,
28/// `/[A-Z][A-Za-z0-9_]*/`.
29pub fn is_constant_name(name: &str) -> bool {
30    let mut chars = name.chars();
31    chars.next().is_some_and(|c| c.is_ascii_uppercase())
32        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
33}
34
35/// `bynk.resolve.const_name_case` for `c`, when its name is not upper-camel.
36pub fn name_case_error(c: &ConstDecl) -> Option<CompileError> {
37    if is_constant_name(&c.name.name) {
38        return None;
39    }
40    let mut err = CompileError::new(
41        "bynk.resolve.const_name_case",
42        c.name.span,
43        format!(
44            "constant `{}` must be named in upper-camel case",
45            c.name.name
46        ),
47    )
48    .with_note(
49        "a constant's name starts with a capital letter and continues with letters, digits or `_` (`MaxRetries`)",
50    );
51    if let Some(suggested) = upper_camel(&c.name.name) {
52        err = err.with_note(format!("rename it `{suggested}`"));
53    }
54    Some(err)
55}
56
57/// A best-effort upper-camel spelling of `name` (`max_retries` → `MaxRetries`),
58/// or `None` when that gives nothing usable.
59fn upper_camel(name: &str) -> Option<String> {
60    let mut out = String::new();
61    let mut upper_next = true;
62    for c in name.chars() {
63        if c == '_' || c == '-' {
64            upper_next = true;
65        } else if upper_next {
66            out.extend(c.to_uppercase());
67            upper_next = false;
68        } else {
69            out.push(c);
70        }
71    }
72    is_constant_name(&out).then_some(out)
73}
74
75/// `bynk.resolve.const_outside_context_or_commons` for `c`.
76pub fn placement_error(c: &ConstDecl) -> CompileError {
77    CompileError::new(
78        "bynk.resolve.const_outside_context_or_commons",
79        c.span,
80        "`const` declarations are only allowed inside a context or a commons",
81    )
82    .with_note("an adapter is the host boundary; declare the constant in a commons or a context")
83}
84
85/// The name rule for constant `c`, given what its unit already declares under
86/// that name: an earlier constant is `bynk.resolve.duplicate_const`; an embed,
87/// an asset, a free function or a type is `bynk.resolve.name_conflict` (a
88/// constant is a value, in the same namespace as a free function). `None`
89/// when the name is free. One rule for the project pipeline
90/// (`symbols::build_unit_table`) and the single-file compile.
91pub fn name_error(
92    c: &ConstDecl,
93    prev_const: Option<&Ident>,
94    prev_embed: Option<&Ident>,
95    prev_asset: Option<&Ident>,
96    prev_fn: Option<&Ident>,
97    prev_type: Option<&Ident>,
98) -> Option<CompileError> {
99    let name = &c.name.name;
100    if let Some(prev) = prev_const {
101        return Some(
102            CompileError::new(
103                "bynk.resolve.duplicate_const",
104                c.name.span,
105                format!("constant `{name}` is already declared"),
106            )
107            .with_label(prev.span, "previously declared here"),
108        );
109    }
110    let (kind, prev) = prev_embed
111        .map(|p| ("an embed", p))
112        .or_else(|| prev_asset.map(|p| ("an asset", p)))
113        .or_else(|| prev_fn.map(|p| ("a function", p)))
114        .or_else(|| prev_type.map(|p| ("a type", p)))?;
115    Some(
116        CompileError::new(
117            "bynk.resolve.name_conflict",
118            c.name.span,
119            format!("constant `{name}` conflicts with {kind} of the same name"),
120        )
121        .with_label(prev.span, "declared here"),
122    )
123}
124
125/// `bynk.resolve.name_conflict` for a constant named like a built-in type
126/// (`List`, `Map`): the parser reads such a name as the type in every later
127/// reference, so the constant could never be used (the same reservation
128/// `bynk.resolve.reserved_builtin_type` makes for a `type` declaration).
129pub fn builtin_name_error(c: &ConstDecl) -> Option<CompileError> {
130    bynk_syntax::keywords::is_builtin_type_name(&c.name.name).then(|| {
131        CompileError::new(
132            "bynk.resolve.name_conflict",
133            c.name.span,
134            format!(
135                "constant `{}` conflicts with the built-in type of the same name",
136                c.name.name
137            ),
138        )
139        .with_note("choose another name for the constant")
140    })
141}
142
143/// `bynk.resolve.name_conflict` for a constant that shares its name with a
144/// variant of a sum type in scope, or with a predeclared `HttpResult` variant:
145/// a bare `Name` would read as either, so the constant may not take the name.
146pub fn variant_conflict_error(
147    c: &ConstDecl,
148    types: &HashMap<String, Arc<TypeDecl>>,
149    unselected: &std::collections::HashSet<String>,
150) -> Option<CompileError> {
151    // #3536: a sum a braced `consumes` leaves out is not in scope to clash with.
152    let mut owners: Vec<&TypeDecl> = types
153        .values()
154        .map(Arc::as_ref)
155        .filter(|t| {
156            !unselected.contains(&t.name.name)
157                && matches!(&t.body, TypeBody::Sum(s)
158                    if s.variants.iter().any(|v| v.name.name == c.name.name))
159        })
160        .collect();
161    owners.sort_by(|a, b| a.name.name.cmp(&b.name.name));
162    // A predeclared `HttpResult` variant (`NotFound`, `Accepted`) is a bare
163    // name in every unit.
164    let owner = match owners.first() {
165        Some(t) => t.name.name.as_str(),
166        None if bynk_syntax::ast::http_variant(&c.name.name).is_some() => "HttpResult",
167        None => return None,
168    };
169    Some(
170        CompileError::new(
171            "bynk.resolve.name_conflict",
172            c.name.span,
173            format!(
174                "constant `{}` conflicts with a variant of `{owner}`",
175                c.name.name
176            ),
177        )
178        .with_note("a bare name would read as either; choose another name for the constant"),
179    )
180}
181
182/// The first part of `init` outside the closed set of static initialisers
183/// (decision A of #2617, after ADR 0004), as `bynk.resolve.bad_const_initialiser`
184/// on that part. `consts` are the constants in scope (a reference to one is
185/// static); `types` let a variant constructor be told from a function call.
186pub fn static_error(
187    c: &ConstDecl,
188    consts: &HashMap<String, ConstDecl>,
189    types: &HashMap<String, Arc<TypeDecl>>,
190) -> Option<CompileError> {
191    let (span, what) = first_non_static(&c.init, consts, types)?;
192    Some(
193        CompileError::new(
194            "bynk.resolve.bad_const_initialiser",
195            span,
196            format!(
197                "the initialiser of constant `{}` must be a static value, but {what} is not",
198                c.name.name
199            ),
200        )
201        .with_note(
202            "a constant's initialiser is a literal (a string without interpolation, or a negative \
203             number), a `Duration` literal, a record, list or sum-variant construction over static \
204             values, `Some`/`None`/`Ok`/`Err`, `T.unsafe(lit)` for an opaque type, \
205             `List.empty()`/`Map.empty()`/`Set.empty()`, or another constant",
206        ),
207    )
208}
209
210fn sum_has_variant(types: &HashMap<String, Arc<TypeDecl>>, ty: &str, variant: &str) -> bool {
211    types.get(ty).is_some_and(|t| {
212        matches!(&t.body, TypeBody::Sum(s) if s.variants.iter().any(|v| v.name.name == variant))
213    })
214}
215
216fn is_any_variant(types: &HashMap<String, Arc<TypeDecl>>, variant: &str) -> bool {
217    types.values().any(|t| {
218        matches!(&t.body, TypeBody::Sum(s) if s.variants.iter().any(|v| v.name.name == variant))
219    })
220}
221
222fn is_literal(e: &Expr) -> bool {
223    match &e.kind {
224        ExprKind::IntLit { .. }
225        | ExprKind::FloatLit { .. }
226        | ExprKind::DecimalLit { .. }
227        | ExprKind::StrLit(_)
228        | ExprKind::BoolLit(_)
229        | ExprKind::UnitLit => true,
230        ExprKind::UnaryOp(UnaryOp::Neg, inner) => {
231            matches!(
232                inner.kind,
233                ExprKind::IntLit { .. } | ExprKind::FloatLit { .. } | ExprKind::DecimalLit { .. }
234            )
235        }
236        ExprKind::Paren(inner) => is_literal(inner),
237        _ => false,
238    }
239}
240
241/// The span and a short description of the first non-static part of `e`.
242fn first_non_static(
243    e: &Expr,
244    consts: &HashMap<String, ConstDecl>,
245    types: &HashMap<String, Arc<TypeDecl>>,
246) -> Option<(bynk_syntax::span::Span, &'static str)> {
247    let all = |items: std::slice::Iter<'_, Expr>| {
248        items
249            .map(|x| first_non_static(x, consts, types))
250            .find(Option::is_some)
251            .flatten()
252    };
253    match &e.kind {
254        ExprKind::IntLit { .. }
255        | ExprKind::FloatLit { .. }
256        | ExprKind::DecimalLit { .. }
257        | ExprKind::DurationLit { .. }
258        | ExprKind::StrLit(_)
259        | ExprKind::BoolLit(_)
260        | ExprKind::UnitLit
261        | ExprKind::None => None,
262        ExprKind::UnaryOp(UnaryOp::Neg, inner)
263            if matches!(
264                inner.kind,
265                ExprKind::IntLit { .. } | ExprKind::FloatLit { .. } | ExprKind::DecimalLit { .. }
266            ) =>
267        {
268            None
269        }
270        ExprKind::Paren(inner)
271        | ExprKind::Some(inner)
272        | ExprKind::Ok(inner)
273        | ExprKind::Err(inner) => first_non_static(inner, consts, types),
274        ExprKind::ListLit(items, ..) => all(items.iter()),
275        ExprKind::RecordConstruction { fields, .. } => {
276            for f in fields {
277                match &f.value {
278                    Some(v) => {
279                        if let Some(bad) = first_non_static(v, consts, types) {
280                            return Some(bad);
281                        }
282                    }
283                    None => return Some((f.span, "a shorthand field (a reference to a binding)")),
284                }
285            }
286            None
287        }
288        // A reference to another constant, or a bare nullary variant.
289        ExprKind::Ident(id) if consts.contains_key(&id.name) || is_any_variant(types, &id.name) => {
290            None
291        }
292        // A bare variant constructor call `Circle(3)`.
293        ExprKind::Call { name, args, .. } if is_any_variant(types, &name.name) => all(args.iter()),
294        // `Shape.Circle`, a qualified nullary variant.
295        ExprKind::FieldAccess { receiver, field } if matches!(&receiver.kind, ExprKind::Ident(t) if sum_has_variant(types, &t.name, &field.name)) => {
296            None
297        }
298        ExprKind::MethodCall {
299            receiver,
300            method,
301            args,
302            ..
303        } => {
304            let ExprKind::Ident(t) = &receiver.kind else {
305                return Some((e.span, "a method call"));
306            };
307            if sum_has_variant(types, &t.name, &method.name) {
308                // `Shape.Circle(3)`, a qualified variant constructor.
309                all(args.iter())
310            } else if method.name == "empty"
311                && args.is_empty()
312                && matches!(t.name.as_str(), "List" | "Map" | "Set")
313            {
314                None
315            } else if method.name == "unsafe"
316                && types
317                    .get(&t.name)
318                    .is_some_and(|d| matches!(d.body, TypeBody::Opaque { .. }))
319            {
320                match args.as_slice() {
321                    [lit] if is_literal(lit) => None,
322                    _ => Some((e.span, "`.unsafe` of anything but a literal")),
323                }
324            } else {
325                Some((e.span, "a function or method call"))
326            }
327        }
328        ExprKind::Ident(_) => Some((e.span, "a reference to something other than a constant")),
329        ExprKind::Call { .. } => Some((e.span, "a function call")),
330        ExprKind::InterpStr(_) => Some((e.span, "an interpolated string")),
331        ExprKind::BinOp(..) | ExprKind::UnaryOp(..) => Some((e.span, "an operator expression")),
332        ExprKind::RecordSpread { .. } => Some((e.span, "a record spread")),
333        ExprKind::FieldAccess { .. } => Some((e.span, "a field access")),
334        ExprKind::Lambda(_) => Some((e.span, "a lambda")),
335        ExprKind::If { .. } | ExprKind::Match { .. } | ExprKind::Block(_) => {
336            Some((e.span, "a control-flow expression"))
337        }
338        _ => Some((e.span, "this expression")),
339    }
340}
341
342/// The constants `e` refers to, by name, in source order (with repeats).
343pub fn referenced_consts<'a>(
344    e: &'a Expr,
345    consts: &HashMap<String, ConstDecl>,
346    out: &mut Vec<&'a Ident>,
347) {
348    if let ExprKind::Ident(id) = &e.kind
349        && consts.contains_key(&id.name)
350    {
351        out.push(id);
352    }
353    for child in bynk_syntax::ast::expr_children(e) {
354        referenced_consts(child, consts, out);
355    }
356}
357
358/// `bynk.resolve.const_cycle` for each cycle through the constants `local`
359/// (this file's, in declaration order) among `consts` (every constant in
360/// scope). Each cycle is reported once, at the member declared first here.
361pub fn cycle_errors(
362    local: &[&ConstDecl],
363    consts: &HashMap<String, ConstDecl>,
364) -> Vec<CompileError> {
365    let order: HashMap<&str, usize> = local
366        .iter()
367        .enumerate()
368        .map(|(i, c)| (c.name.name.as_str(), i))
369        .collect();
370    let mut errors = Vec::new();
371    for (i, c) in local.iter().enumerate() {
372        let Some(path) = find_cycle(&c.name.name, consts) else {
373            continue;
374        };
375        // Reported at the member of the cycle declared first in this file.
376        if path
377            .iter()
378            .any(|n| order.get(n.as_str()).is_some_and(|&j| j < i))
379        {
380            continue;
381        }
382        let shown = path
383            .iter()
384            .chain(std::iter::once(&c.name.name))
385            .map(|n| format!("`{n}`"))
386            .collect::<Vec<_>>()
387            .join(" → ");
388        errors.push(
389            CompileError::new(
390                "bynk.resolve.const_cycle",
391                c.name.span,
392                format!("constant `{}` refers to itself: {shown}", c.name.name),
393            )
394            .with_note(
395                "a constant's value cannot depend on itself; break the cycle with a literal",
396            ),
397        );
398    }
399    errors
400}
401
402/// A path `start → … → (back to start)` through the constants' references,
403/// without the closing `start`, or `None` when `start` is on no cycle.
404fn find_cycle(start: &str, consts: &HashMap<String, ConstDecl>) -> Option<Vec<String>> {
405    fn dfs(
406        node: &str,
407        start: &str,
408        consts: &HashMap<String, ConstDecl>,
409        path: &mut Vec<String>,
410        visited: &mut HashSet<String>,
411    ) -> bool {
412        let Some(decl) = consts.get(node) else {
413            return false;
414        };
415        path.push(node.to_string());
416        let mut refs = Vec::new();
417        referenced_consts(&decl.init, consts, &mut refs);
418        for r in refs {
419            if r.name == start {
420                return true;
421            }
422            if visited.insert(r.name.clone()) && dfs(&r.name, start, consts, path, visited) {
423                return true;
424            }
425        }
426        path.pop();
427        false
428    }
429    let mut path = Vec::new();
430    let mut visited = HashSet::new();
431    dfs(start, start, consts, &mut path, &mut visited).then_some(path)
432}
433
434/// The single-file compile's declaration diagnostics for constants, in
435/// declaration order: each constant's name rules ([`name_error`], against the
436/// file's own embeds, assets, functions, types and earlier constants, and
437/// [`builtin_name_error`]). Placement needs no check here: a single file is
438/// always a commons. The case, static-ness, type and cycle rules are the
439/// checker's, on every path.
440pub fn single_file_const_errors(items: &[CommonsItem]) -> Vec<CompileError> {
441    let mut fns: HashMap<&str, &Ident> = HashMap::new();
442    let mut types: HashMap<&str, &Ident> = HashMap::new();
443    let mut assets: HashMap<&str, &Ident> = HashMap::new();
444    let mut embeds: HashMap<&str, &Ident> = HashMap::new();
445    for item in items {
446        match item {
447            CommonsItem::Fn(f) => {
448                if let FnName::Free(id) = &f.name {
449                    fns.entry(id.name.as_str()).or_insert(id);
450                }
451            }
452            CommonsItem::Type(t) => {
453                types.entry(t.name.name.as_str()).or_insert(&t.name);
454            }
455            CommonsItem::Event(ev) => {
456                types.entry(ev.name.name.as_str()).or_insert(&ev.name);
457            }
458            CommonsItem::Asset(a) => {
459                assets.entry(a.name.name.as_str()).or_insert(&a.name);
460            }
461            CommonsItem::Embed(e) => {
462                embeds.entry(e.name.name.as_str()).or_insert(&e.name);
463            }
464            _ => {}
465        }
466    }
467    let mut consts: HashMap<&str, &Ident> = HashMap::new();
468    let mut errors = Vec::new();
469    for item in items {
470        let CommonsItem::Const(c) = item else {
471            continue;
472        };
473        let key = c.name.name.as_str();
474        match name_error(
475            c,
476            consts.get(key).copied(),
477            embeds.get(key).copied(),
478            assets.get(key).copied(),
479            fns.get(key).copied(),
480            types.get(key).copied(),
481        )
482        .or_else(|| builtin_name_error(c))
483        {
484            Some(err) => errors.push(err),
485            None => {
486                consts.insert(key, &c.name);
487            }
488        }
489    }
490    errors
491}
492
493/// Every constant visible in unit `name`: its own, plus the public ones of
494/// each commons it `uses` (one level, the mixin rule [`crate::embeds::compose_unit_embeds`]
495/// applies to embeds). A local declaration of any kind wins over an imported
496/// constant of the same name; two used commons declaring the same name is
497/// `bynk.uses.name_conflict`, so which is kept here is never observable in a
498/// program that checks.
499pub fn compose_unit_consts(
500    name: &str,
501    unit_info: &BTreeMap<String, UnitInfo>,
502) -> HashMap<String, ConstDecl> {
503    let Some(info) = unit_info.get(name) else {
504        return HashMap::new();
505    };
506    visible_consts(&info.table, &info.uses, |u| {
507        unit_info.get(u).map(|i| &i.table)
508    })
509    .into_iter()
510    .map(|(n, c)| {
511        let mut decl = c.decl.clone();
512        // #3065: an imported `String` alias (`const Tail: String = Base`) names
513        // its target in the *declaring* unit's scope, not this one's, where a
514        // local `Base` may differ or the real one be `private`. Fold it to the
515        // literal it denotes there, so a checker reading the view's initialiser
516        // (the SQL a database call sends) sees the declarer's text.
517        if let Some(owner) = c.owner
518            && matches!(decl.init.kind, ExprKind::Ident(_))
519            && let Some(text) = alias_literal(
520                |u| unit_info.get(u).map(|i| (&i.table, i.uses.as_slice())),
521                owner,
522                &decl,
523            )
524        {
525            decl.init.kind = ExprKind::StrLit(text);
526        }
527        (n, decl)
528    })
529    .collect()
530}
531
532/// Whether `kind` is a plain literal of the base type `base`: the closed set of
533/// values a constant can be bound to directly (a constant's initialiser has no
534/// operators, calls or interpolation, [`static_error`]).
535pub fn is_literal_of(kind: &ExprKind, base: BaseType) -> bool {
536    let numeric = |k: &ExprKind| match base {
537        BaseType::Int => matches!(k, ExprKind::IntLit { .. }),
538        BaseType::Float => matches!(k, ExprKind::FloatLit { .. }),
539        BaseType::Decimal => matches!(k, ExprKind::DecimalLit { .. }),
540        _ => false,
541    };
542    match kind {
543        ExprKind::StrLit(_) => base == BaseType::String,
544        ExprKind::BoolLit(_) => base == BaseType::Bool,
545        ExprKind::DurationLit { .. } => base == BaseType::Duration,
546        // A negative numeric literal is a static initialiser too ([`static_error`]).
547        ExprKind::UnaryOp(UnaryOp::Neg, inner) => numeric(&inner.kind),
548        k => numeric(k),
549    }
550}
551
552/// #3445: the literal a constant denotes, following constant-to-constant
553/// references. The one resolution loop every literal-only position shares: the
554/// text of a SQL call (#3065, ADR 0762) and an annotation argument (ADR 0678 C,
555/// as amended). Every constant on the chain must be declared exactly `base`
556/// (a refined or opaque constant does not count) and the chain must end at a
557/// literal of it. `next` names the constant a reference points to, in whichever
558/// scope the caller resolves names; `limit` bounds the walk, since a longer
559/// chain is a cycle already reported as `bynk.resolve.const_cycle`.
560pub fn chain_literal<'a>(
561    start: &'a ConstDecl,
562    base: BaseType,
563    limit: usize,
564    next: impl FnMut(&str) -> Option<&'a ConstDecl>,
565) -> Option<&'a Expr> {
566    chain_literal_with(
567        start,
568        base,
569        |ty| matches!(ty, TypeRef::Base(b, _) if *b == base),
570        limit,
571        next,
572    )
573}
574
575/// [`chain_literal`] with the declared-type test supplied: each constant on the
576/// chain must satisfy `accepts`, and the chain must end at a literal of `base`.
577/// #3875: a cron schedule position accepts a constant declared exactly
578/// `CronSchedule` as well as `String`.
579pub fn chain_literal_with<'a>(
580    start: &'a ConstDecl,
581    base: BaseType,
582    accepts: impl Fn(&TypeRef) -> bool,
583    limit: usize,
584    mut next: impl FnMut(&str) -> Option<&'a ConstDecl>,
585) -> Option<&'a Expr> {
586    let mut current = start;
587    for _ in 0..=limit {
588        if !accepts(&current.ty) {
589            return None;
590        }
591        match &current.init.kind {
592            k if is_literal_of(k, base) => return Some(&current.init),
593            ExprKind::Ident(n) => current = next(n.name.as_str())?,
594            _ => return None,
595        }
596    }
597    None
598}
599
600/// #3065: the string literal a `String` constant alias denotes, following each
601/// hop in the scope of the unit declaring the constant it was written in.
602pub fn alias_literal<'a>(
603    unit: impl Fn(&str) -> Option<(&'a UnitTable, &'a [String])>,
604    owner: &str,
605    start: &'a ConstDecl,
606) -> Option<String> {
607    let mut at = owner;
608    let lit = chain_literal(start, BaseType::String, 64, |name| {
609        let (table, uses) = unit(at)?;
610        let vis = visible_consts(table, uses, |u| unit(u).map(|(t, _)| t));
611        let found = vis.get(name)?;
612        if let Some(o) = found.owner {
613            at = o;
614        }
615        Some(found.decl)
616    })?;
617    match &lit.kind {
618        ExprKind::StrLit(s) => Some(s.clone()),
619        _ => None,
620    }
621}
622
623/// #3445: a constant an annotation argument names, resolved to the literal it
624/// denotes.
625pub struct ResolvedConst<'a> {
626    /// The constant the argument names (the first hop).
627    pub decl: &'a ConstDecl,
628    /// The literal at the end of its chain.
629    pub literal: &'a Expr,
630    /// The used commons declaring `decl`; `None` for the unit's own constant.
631    pub owner: Option<&'a str>,
632}
633
634/// #3445: resolve the bare name `name`, written in unit `at`, to the literal of
635/// type `base` it denotes. Each hop of the chain is read in the scope of the
636/// unit declaring it, as [`alias_literal`] does.
637pub fn resolve_const_literal<'a>(
638    unit: impl Fn(&str) -> Option<(&'a UnitTable, &'a [String])>,
639    at: &'a str,
640    name: &str,
641    base: BaseType,
642) -> Option<ResolvedConst<'a>> {
643    let (table, uses) = unit(at)?;
644    let vis = visible_consts(table, uses, |u| unit(u).map(|(t, _)| t));
645    let first = vis.get(name)?;
646    let (decl, owner) = (first.decl, first.owner);
647    let mut scope = owner.unwrap_or(at);
648    let literal = chain_literal(decl, base, 64, |n| {
649        let (table, uses) = unit(scope)?;
650        let vis = visible_consts(table, uses, |u| unit(u).map(|(t, _)| t));
651        let found = vis.get(n)?;
652        if let Some(o) = found.owner {
653            scope = o;
654        }
655        Some(found.decl)
656    })?;
657    Some(ResolvedConst {
658        decl,
659        literal,
660        owner,
661    })
662}
663
664/// #3875: whether a constant's declared type is one a cron schedule position
665/// takes: exactly `String`, or exactly the prelude's `CronSchedule`. A constant
666/// of any other refined type (`String where MaxLength(20)`, a user's own
667/// `type Nightly = String where Cron`) is refused, which keeps named types
668/// distinct inside a context (ADR 0714 B).
669pub fn is_schedule_type(ty: &TypeRef) -> bool {
670    match ty {
671        TypeRef::Base(BaseType::String, _) => true,
672        TypeRef::Named(id) => id.name == "CronSchedule",
673        _ => false,
674    }
675}
676
677/// #3875: [`resolve_const_literal`] for a cron schedule: the chain's constants
678/// are each `String` or `CronSchedule` ([`is_schedule_type`]).
679pub fn resolve_schedule_literal<'a>(
680    unit: impl Fn(&str) -> Option<(&'a UnitTable, &'a [String])>,
681    at: &'a str,
682    name: &str,
683) -> Result<ResolvedConst<'a>, Option<&'a ConstDecl>> {
684    let Some((table, uses)) = unit(at) else {
685        return Err(None);
686    };
687    let vis = visible_consts(table, uses, |u| unit(u).map(|(t, _)| t));
688    let Some(first) = vis.get(name) else {
689        return Err(None);
690    };
691    let (decl, owner) = (first.decl, first.owner);
692    let mut scope = owner.unwrap_or(at);
693    let literal = chain_literal_with(decl, BaseType::String, is_schedule_type, 64, |n| {
694        let (table, uses) = unit(scope)?;
695        let vis = visible_consts(table, uses, |u| unit(u).map(|(t, _)| t));
696        let found = vis.get(n)?;
697        if let Some(o) = found.owner {
698            scope = o;
699        }
700        Some(found.decl)
701    });
702    match literal {
703        Some(literal) => Ok(ResolvedConst {
704            decl,
705            literal,
706            owner,
707        }),
708        None => Err(Some(decl)),
709    }
710}
711
712/// A constant visible in a unit ([`visible_consts`]), with where it is declared.
713pub struct VisibleConst<'a> {
714    pub decl: &'a ConstDecl,
715    /// `None` for the unit's own constant, else the used commons declaring it.
716    pub owner: Option<&'a str>,
717}
718
719/// #2967: the constants [`compose_unit_consts`] composes, from a unit's own
720/// table, its `uses` and a lookup of the used units' tables, each with its
721/// owner. The project phases that run before `UnitInfo` is assembled
722/// (`project_model::phase_workers_ws_open_key`) and the Workers emitter read
723/// the same set through this, so the checker and the emitter agree on which
724/// names are constants.
725pub fn visible_consts<'a>(
726    table: &'a UnitTable,
727    uses: &'a [String],
728    used_table: impl Fn(&str) -> Option<&'a UnitTable>,
729) -> HashMap<String, VisibleConst<'a>> {
730    let mut combined: HashMap<String, VisibleConst<'a>> = table
731        .consts
732        .iter()
733        .map(|(n, decl)| (n.clone(), VisibleConst { decl, owner: None }))
734        .collect();
735    for used in uses {
736        let Some(used_table) = used_table(used) else {
737            continue;
738        };
739        // A used commons' `private` constants stay in it.
740        for (const_name, decl) in used_table
741            .consts
742            .iter()
743            .filter(|(_, d)| d.private.is_none())
744        {
745            if crate::symbols::local_value_kind(table, const_name).is_some() {
746                continue;
747            }
748            combined.entry(const_name.clone()).or_insert(VisibleConst {
749                decl,
750                owner: Some(used.as_str()),
751            });
752        }
753    }
754    combined
755}
756
757#[cfg(test)]
758mod tests {
759    use super::*;
760
761    #[test]
762    fn constant_names_are_upper_camel() {
763        assert!(is_constant_name("MaxRetries"));
764        assert!(is_constant_name("A"));
765        assert!(is_constant_name("HTTP_2"));
766        assert!(!is_constant_name("maxRetries"));
767        assert!(!is_constant_name("_Max"));
768        assert!(!is_constant_name(""));
769        assert_eq!(upper_camel("max_retries").as_deref(), Some("MaxRetries"));
770        assert_eq!(upper_camel("timeout").as_deref(), Some("Timeout"));
771    }
772}