Skip to main content

bynk_check/checker/
refinements.rs

1//! Refinement, literal, and zero-value logic.
2//!
3//! Split out of `checker.rs` (v0.29.10) verbatim; the parent module
4//! re-exports these via `use refinements::*`.
5
6use super::*;
7
8pub(crate) fn check_type_decl(
9    t: &TypeDecl,
10    types: &HashMap<String, Arc<TypeDecl>>,
11    tys: &Types,
12    errors: &mut Vec<CompileError>,
13) {
14    match &t.body {
15        TypeBody::Refined {
16            base,
17            base_span,
18            refinement,
19        } => {
20            check_refinement(*base, *base_span, refinement.as_ref(), errors);
21        }
22        TypeBody::Opaque {
23            base,
24            base_span,
25            refinement,
26        } => {
27            // Opaque types share refinement-validity rules with refined types.
28            check_refinement(*base, *base_span, refinement.as_ref(), errors);
29        }
30        TypeBody::Record(r) => {
31            for f in &r.fields {
32                if let Some(ref_r) = &f.refinement {
33                    // Inline refinements on fields must apply to the field's base type.
34                    if let Some(b) = field_base_type(&f.type_ref, types) {
35                        check_refinement(b, f.type_ref.span(), Some(ref_r), errors);
36                        // #2686: an example is the field's own value only where
37                        // the field is a base type; a named type's example is
38                        // the type's, checked at its declaration.
39                        if matches!(f.type_ref, TypeRef::Named(_)) {
40                            for ann in &ref_r.annotations {
41                                errors.push(
42                                    CompileError::new(
43                                        "bynk.types.example_on_named_field",
44                                        ann.span,
45                                        format!(
46                                            "`@{}` on field `{}` of a named type has no effect",
47                                            ann.name.name, f.name.name
48                                        ),
49                                    )
50                                    .with_note("put the `@example` on the named type's declaration instead"),
51                                );
52                            }
53                        }
54                    } else {
55                        errors.push(CompileError::new(
56                            "bynk.types.field_refinement_not_base",
57                            ref_r.span,
58                            format!(
59                                "inline refinement on field `{}` requires a base or refined type",
60                                f.name.name
61                            ),
62                        ));
63                    }
64                }
65            }
66        }
67        TypeBody::Sum(s) => {
68            check_embeds(&t.name.name, s, types, errors, tys);
69        }
70    }
71}
72
73/// v0.154 (ADR 0178): validate a sum's declared error embeddings. Each
74/// `embeds E as V` requires the named variant `V` to exist in this sum and to
75/// have **exactly one payload field whose type is `E`** — that is the shape a
76/// value of `E` auto-wraps into. A source type may be embedded by at most one
77/// variant, so `?`'s conversion is unambiguous.
78pub(crate) fn check_embeds(
79    sum_name: &str,
80    s: &SumBody,
81    types: &HashMap<String, Arc<TypeDecl>>,
82    errors: &mut Vec<CompileError>,
83    tys: &Types,
84) {
85    let mut seen_sources: Vec<TyId> = Vec::new();
86    for clause in &s.embeds {
87        let Some(source_ty) = resolve_type_ref(&clause.source_type, types, tys) else {
88            // An unresolvable type ref is already reported by reference
89            // resolution; skip to avoid a duplicate error.
90            continue;
91        };
92        // The named variant must exist in this sum.
93        let Some(variant) = s
94            .variants
95            .iter()
96            .find(|v| v.name.name == clause.variant.name)
97        else {
98            errors.push(CompileError::new(
99                "bynk.types.embeds_unknown_variant",
100                clause.variant.span,
101                format!(
102                    "`embeds … as {}` names no variant of `{}`",
103                    clause.variant.name, sum_name
104                ),
105            ));
106            continue;
107        };
108        // The variant must be a single-payload wrapper of the embedded type.
109        if variant.payload.len() != 1 {
110            errors.push(
111                CompileError::new(
112                    "bynk.types.embeds_variant_shape",
113                    clause.span,
114                    format!(
115                        "`embeds … as {}` requires `{}` to have exactly one payload field, but it has {}",
116                        clause.variant.name,
117                        clause.variant.name,
118                        variant.payload.len()
119                    ),
120                )
121                .with_note("a value of the embedded type is wrapped into that single field"),
122            );
123            continue;
124        }
125        let field_ty = resolve_type_ref(&variant.payload[0].type_ref, types, tys);
126        if let Some(field_ty) = &field_ty
127            && !compatible(source_ty, *field_ty, tys)
128        {
129            errors.push(CompileError::new(
130                "bynk.types.embeds_variant_shape",
131                clause.span,
132                format!(
133                    "`embeds {} as {}` — but `{}`'s payload field has type `{}`, not `{}`",
134                    source_ty.display(tys),
135                    clause.variant.name,
136                    clause.variant.name,
137                    field_ty.display(tys),
138                    source_ty.display(tys)
139                ),
140            ));
141            continue;
142        }
143        // The same source type may be embedded once at most (unambiguous `?`).
144        if seen_sources.iter().any(|t| compatible(*t, source_ty, tys)) {
145            errors.push(CompileError::new(
146                "bynk.types.embeds_ambiguous",
147                clause.span,
148                format!(
149                    "`{}` is embedded more than once by `{}` — the conversion would be ambiguous",
150                    source_ty.display(tys),
151                    sum_name
152                ),
153            ));
154            continue;
155        }
156        seen_sources.push(source_ty);
157    }
158}
159
160/// The base type of a field's type-ref (chasing through named refined types).
161fn field_base_type(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> Option<BaseType> {
162    match r {
163        TypeRef::Base(b, _) => Some(*b),
164        TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
165            Some(TypeBody::Refined { base, .. }) => Some(*base),
166            _ => None,
167        },
168        _ => None,
169    }
170}
171
172/// The implicit base type of a TypeDecl whose constructor would be `T.of`:
173/// Refined and Opaque types alike share the `of(base) -> Result[T, _]` shape.
174/// Returns None for record / sum types.
175pub(crate) fn type_decl_base(decl: &TypeDecl) -> Option<BaseType> {
176    match &decl.body {
177        TypeBody::Refined { base, .. } => Some(*base),
178        TypeBody::Opaque { base, .. } => Some(*base),
179        _ => None,
180    }
181}
182
183/// The refinement attached to a refined or opaque type declaration, if any.
184pub(crate) fn type_decl_refinement(decl: &TypeDecl) -> Option<&Refinement> {
185    match &decl.body {
186        TypeBody::Refined { refinement, .. } | TypeBody::Opaque { refinement, .. } => {
187            refinement.as_ref()
188        }
189        _ => None,
190    }
191}
192
193/// Extract a compile-time literal from an expression, if it is one v0.9.4's
194/// static refinement check accepts: an int/string/bool/unit literal, or a unary
195/// minus applied directly to an int literal. Anything else (arithmetic, idents,
196/// calls) is not statically evaluated and keeps the runtime `Result` path.
197pub(crate) fn const_literal(e: &Expr) -> Option<ConstLit> {
198    match &e.kind {
199        ExprKind::IntLit { value: n, .. } => Some(ConstLit::Int(*n)),
200        ExprKind::FloatLit { value, .. } => Some(ConstLit::Float(*value)),
201        ExprKind::DecimalLit { coef, scale, .. } => Some(ConstLit::Decimal(coef.clone(), *scale)),
202        ExprKind::StrLit(s) => Some(ConstLit::Str(s.clone())),
203        ExprKind::BoolLit(b) => Some(ConstLit::Bool(*b)),
204        ExprKind::UnitLit => Some(ConstLit::Unit),
205        ExprKind::UnaryOp(UnaryOp::Neg, inner) => match &inner.kind {
206            ExprKind::IntLit { value: n, .. } => Some(ConstLit::Int(n.checked_neg()?)),
207            ExprKind::FloatLit { value, .. } => Some(ConstLit::Float(-*value)),
208            ExprKind::DecimalLit { coef, scale, .. } => {
209                Some(ConstLit::Decimal(format!("-{coef}"), *scale))
210            }
211            _ => None,
212        },
213        _ => None,
214    }
215}
216
217/// Evaluate a single predicate against a constant literal. A predicate whose
218/// expected base type doesn't match the literal (e.g. a length predicate on an
219/// int) returns `true` here — the base/predicate mismatch is a declaration-time
220/// error reported by `check_refinement`, not a construction concern. String
221/// length is measured in code points (#3949), the unit the emitted run-time
222/// check (`__bynkCodePointLength`), `chars()` and OpenAPI's `maxLength` use too.
223pub(crate) fn eval_predicate(pred: &PredKind, lit: &ConstLit) -> bool {
224    match (pred, lit) {
225        (PredKind::NonNegative, ConstLit::Int(n)) => *n >= 0,
226        (PredKind::Positive, ConstLit::Int(n)) => *n > 0,
227        (PredKind::InRange(lo, hi), ConstLit::Int(n)) => lo.value <= *n && *n <= hi.value,
228        (PredKind::NonNegative, ConstLit::Float(v)) => *v >= 0.0,
229        (PredKind::Positive, ConstLit::Float(v)) => *v > 0.0,
230        (PredKind::InRangeF(lo, hi), ConstLit::Float(v)) => lo.value <= *v && *v <= hi.value,
231        (PredKind::NonNegative, ConstLit::Decimal(c, _)) => bynk_syntax::decimal::sign(c) >= 0,
232        (PredKind::Positive, ConstLit::Decimal(c, _)) => bynk_syntax::decimal::sign(c) > 0,
233        (PredKind::InRangeD(lo, hi), ConstLit::Decimal(c, s)) => {
234            use std::cmp::Ordering::Greater;
235            bynk_syntax::decimal::cmp(&lo.coef, lo.scale, c, *s) != Greater
236                && bynk_syntax::decimal::cmp(c, *s, &hi.coef, hi.scale) != Greater
237        }
238        (PredKind::MinLength(k), ConstLit::Str(s)) => s.chars().count() as i64 >= *k,
239        (PredKind::MaxLength(k), ConstLit::Str(s)) => (s.chars().count() as i64) <= *k,
240        (PredKind::Length(k), ConstLit::Str(s)) => s.chars().count() as i64 == *k,
241        (PredKind::NonEmpty, ConstLit::Str(s)) => !s.is_empty(),
242        (PredKind::IsoDate, ConstLit::Str(s)) => bynk_syntax::ast::is_iso_date(s),
243        (PredKind::Cron, ConstLit::Str(s)) => bynk_syntax::cron::is_cron_expression(s).is_ok(),
244        (PredKind::Matches(pat), ConstLit::Str(s)) => {
245            // Evaluated with the same engine semantics the emitted
246            // `new RegExp(...)` runs under (ECMAScript, no flags).
247            regress::Regex::new(&format!("^(?:{pat})$"))
248                .map(|re| re.find(s).is_some())
249                .unwrap_or(false)
250        }
251        _ => true,
252    }
253}
254
255/// The first predicate the literal fails, or `None` if it satisfies them all.
256pub(crate) fn first_failed_predicate<'a>(
257    refinement: &'a Refinement,
258    lit: &ConstLit,
259) -> Option<&'a PredKind> {
260    // #1651: the runtime checks' order, so a literal rejected here names the
261    // predicate the boundary would.
262    bynk_syntax::ast::in_check_order(&refinement.predicates, |p| &p.kind)
263        .into_iter()
264        .find(|p| !eval_predicate(&p.kind, lit))
265        .map(|p| &p.kind)
266}
267
268/// `LocaleTag`'s refinement, read once from the firstparty `bynk.locale.types`
269/// source — the single source of truth the emitter also lowers to a
270/// `new RegExp(...)`. `None` only if that type ever loses its refinement or the
271/// firstparty source stops parsing (both guarded elsewhere), in which case the
272/// tag check below accepts everything rather than spuriously rejecting.
273fn locale_tag_refinement() -> Option<&'static Refinement> {
274    use std::sync::OnceLock;
275    static REFINEMENT: OnceLock<Option<Refinement>> = OnceLock::new();
276    REFINEMENT
277        .get_or_init(|| {
278            let src = crate::firstparty::BYNK_LOCALE_TYPES_SRC;
279            let tokens = bynk_syntax::lexer::tokenize(src).ok()?;
280            let unit = bynk_syntax::parser::parse_unit(&tokens, src).ok()?;
281            let bynk_syntax::ast::SourceUnit::Commons(commons) = unit else {
282                return None;
283            };
284            commons.items.iter().find_map(|item| match item {
285                CommonsItem::Type(t) if t.name.name == "LocaleTag" => {
286                    type_decl_refinement(t).cloned()
287                }
288                _ => None,
289            })
290        })
291        .as_ref()
292}
293
294/// The pattern `LocaleTag`'s refinement matches against, for a diagnostic that
295/// names it. `None` if the type carries no `Matches` predicate.
296pub fn locale_tag_pattern() -> Option<&'static str> {
297    locale_tag_refinement()?.predicates.iter().find_map(|p| {
298        if let PredKind::Matches(pat) = &p.kind {
299            Some(pat.as_str())
300        } else {
301            None
302        }
303    })
304}
305
306/// Whether `tag` satisfies `LocaleTag`'s refinement — the check behind
307/// `bynk.messages.invalid_locale_tag`. Evaluated with the same regex-engine
308/// semantics (`regress`, anchored, no flags) the emitted `new RegExp(...)`
309/// runs under, so a tag accepted here is one the runtime cast is honest about.
310pub fn locale_tag_accepts(tag: &str) -> bool {
311    match locale_tag_refinement() {
312        Some(refinement) => {
313            first_failed_predicate(refinement, &ConstLit::Str(tag.to_string())).is_none()
314        }
315        None => true,
316    }
317}
318
319pub(crate) fn literal_matches_base(lit: &ConstLit, base: BaseType) -> bool {
320    matches!(
321        (lit, base),
322        (ConstLit::Int(_), BaseType::Int)
323            | (ConstLit::Str(_), BaseType::String)
324            | (ConstLit::Bool(_), BaseType::Bool)
325            | (ConstLit::Float(_), BaseType::Float)
326            | (ConstLit::Decimal(..), BaseType::Decimal)
327    )
328}
329
330/// v0.9.4: expected-type-directed literal admission. When a position expects a
331/// **refined** type `T` and `expr` is a compile-time literal of `T`'s base, the
332/// literal takes the type `T` directly (the emitter lowers it to an inline brand
333/// cast, `(lit as T)` — ADR 0182); a literal that violates the refinement is a
334/// compile error. Returns `None` when no refined type is expected (so the caller
335/// keeps the literal's base type) — `.of` remains the only constructor for
336/// runtime values.
337/// Opaque types are intentionally excluded: their representation is hidden, so
338/// they are still built via `T.of(...)`.
339///
340/// Looks through one `Effect[_]` layer first (Locale capability track, slice 1,
341/// #844): a `stub Cap.op() returns <lit>` RHS is checked as a bare tail value
342/// against the op's full `Effect[T]` return type (§tail-position auto-lift
343/// handles the reverse direction, wrapping a matched bare value back up to
344/// `Effect[T]`), so a refined `T` reached only through that wrapper must still
345/// be visible here or the literal falls back to its unrefined base type and the
346/// auto-lift's own `compatible` check then rejects it.
347pub(crate) fn admit_refined_literal(
348    expr: &Expr,
349    expected: Option<TyId>,
350    ctx: &mut Ctx,
351) -> Option<TyId> {
352    let input = ctx.input;
353    admit_refined_literal_in(expr, expected, &input.types, ctx)
354}
355
356/// [`admit_refined_literal`] against an explicit declaration table: the one
357/// that declares `expected`'s names. #2025: a cross-context argument's
358/// parameter type is named in the consumed context's table, so a literal
359/// passed straight to it is checked against the callee's declaration, not
360/// whatever the caller binds under that name (or nothing, when the caller
361/// has no `uses` of the declaring commons).
362pub(crate) fn admit_refined_literal_in(
363    expr: &Expr,
364    expected: Option<TyId>,
365    types: &HashMap<String, Arc<TypeDecl>>,
366    ctx: &mut Ctx,
367) -> Option<TyId> {
368    let tys = ctx.tys;
369    let expected = match expected.map(|e| tys.get(e)).as_deref() {
370        Some(Ty::Effect(inner)) => Some(*inner),
371        _ => expected,
372    };
373    let expected_node = expected.map(|e| tys.get(e));
374    let Some(Ty::Named {
375        name,
376        kind: NamedKind::Refined(base),
377        ..
378    }) = expected_node.as_deref()
379    else {
380        return None;
381    };
382    let lit = const_literal(expr)?;
383    if !literal_matches_base(&lit, *base) {
384        return None;
385    }
386    let decl = types.get(name)?.clone();
387    if let Some(refinement) = type_decl_refinement(&decl)
388        && let Some(failed) = first_failed_predicate(refinement, &lit)
389    {
390        ctx.errors.push(CompileError::new(
391            "bynk.refine.literal_violates",
392            expr.span,
393            format!(
394                "literal {} does not satisfy `{}` required by type `{}`",
395                lit.display(),
396                failed.name(),
397                name
398            ),
399        ));
400    }
401    Some(named_ty(&decl, tys))
402}
403
404pub(crate) fn check_refinement(
405    base: BaseType,
406    base_span: Span,
407    refinement: Option<&Refinement>,
408    errors: &mut Vec<CompileError>,
409) {
410    let Some(refinement) = refinement else {
411        return;
412    };
413
414    check_refinement_annotations(base, refinement, errors);
415
416    for pred in &refinement.predicates {
417        if !pred_applies_to(&pred.kind, base) {
418            // v0.21: `InRange` bounds must match the numeric base type —
419            // `Float where InRange(0, 1)` is the no-coercion rule applied
420            // to refinement bounds, not a predicate/base mismatch.
421            let numeric_bound_mismatch = matches!(
422                (&pred.kind, base),
423                (PredKind::InRange(_, _), BaseType::Float | BaseType::Decimal)
424                    | (PredKind::InRangeF(_, _), BaseType::Int | BaseType::Decimal)
425                    | (PredKind::InRangeD(_, _), BaseType::Int | BaseType::Float)
426            );
427            if numeric_bound_mismatch {
428                let bounds = match &pred.kind {
429                    PredKind::InRange(..) => "`Int`",
430                    PredKind::InRangeF(..) => "`Float`",
431                    _ => "`Decimal`",
432                };
433                let want = match base {
434                    BaseType::Float => "`InRange(0.0, 1.0)`",
435                    BaseType::Decimal => "`InRange(0.00d, 1.00d)`",
436                    _ => "`InRange(0, 1)`",
437                };
438                errors.push(
439                    CompileError::new(
440                        "bynk.types.no_numeric_coercion",
441                        pred.span,
442                        format!(
443                            "`InRange` bounds are {bounds} literals, but the base type is `{}`",
444                            base.name()
445                        ),
446                    )
447                    .with_label(
448                        base_span,
449                        format!("base type `{}` declared here", base.name()),
450                    )
451                    .with_note(format!(
452                        "refinement bounds must match the base type — e.g. {want}"
453                    )),
454                );
455                continue;
456            }
457            errors.push(
458                CompileError::new(
459                    "bynk.types.predicate_base_mismatch",
460                    pred.span,
461                    format!(
462                        "predicate `{}` cannot be applied to base type `{}`",
463                        pred.kind.name(),
464                        base.name()
465                    ),
466                )
467                .with_label(
468                    base_span,
469                    format!("base type `{}` declared here", base.name()),
470                )
471                .with_note(predicate_base_help(pred.kind.name())),
472            );
473        }
474        match &pred.kind {
475            PredKind::Matches(pat) => {
476                // Validate with ECMAScript semantics (the `regress` engine):
477                // the emitted check runs the pattern under JS `RegExp`, so a
478                // pattern the Rust `regex` crate accepts but JS rejects
479                // (`(?P<name>…)`, inline flags) would otherwise compile
480                // cleanly and then throw at runtime — a 500 on the request
481                // path instead of a compile error.
482                if let Err(e) = regress::Regex::new(pat) {
483                    errors.push(
484                        CompileError::new(
485                            "bynk.types.invalid_regex",
486                            pred.span,
487                            format!("invalid regular expression in `Matches(\"{pat}\")`"),
488                        )
489                        .with_note(format!("regex parse error (JS `RegExp` semantics): {e}")),
490                    );
491                } else if has_nested_unbounded_quantifier(pat) && !proved_linear(pat, "") {
492                    // The emitted boundary check runs this pattern under JS
493                    // `RegExp`, a backtracking engine. A repeated group that
494                    // itself contains an unbounded quantifier (`(a+)+`) makes
495                    // matching take exponential time on a crafted near-miss
496                    // input — a refined `String` on an HTTP boundary would let
497                    // an unauthenticated client stall the Worker (ReDoS, #724).
498                    // Reject the pattern at compile time rather than ship the
499                    // hazard. This cheap first pass keeps its own, clearer
500                    // message; the ambiguity analysis below covers the rest.
501                    errors.push(
502                        CompileError::new(
503                            "bynk.types.catastrophic_regex",
504                            pred.span,
505                            format!(
506                                "the pattern in `Matches(\"{pat}\")` nests unbounded quantifiers, \
507                                 which can cause catastrophic backtracking (ReDoS)"
508                            ),
509                        )
510                        .with_note(
511                            "a repeated group that itself contains `*`, `+`, or `{n,}` makes \
512                             matching take exponential time on crafted input; restructure the \
513                             pattern so no unbounded quantifier is nested inside another",
514                        ),
515                    );
516                } else if let Some(e) = ambiguity_diagnostic(
517                    pat,
518                    "",
519                    pred.span,
520                    &format!("`Matches(\"{pat}\")`"),
521                    // The tightest length bound the refinement states. Length
522                    // predicates run before `Matches` (`in_check_order`), so it
523                    // caps the input the pattern ever sees.
524                    Some(
525                        refinement
526                            .predicates
527                            .iter()
528                            .filter_map(|p| match p.kind {
529                                PredKind::MaxLength(n) | PredKind::Length(n) => Some(n),
530                                // `IsoDate` admits only `YYYY-MM-DD`.
531                                PredKind::IsoDate => Some(10),
532                                _ => None,
533                            })
534                            .min(),
535                    ),
536                ) {
537                    errors.push(e);
538                }
539            }
540            PredKind::InRange(lo, hi) => {
541                if lo.value > hi.value {
542                    errors.push(
543                        CompileError::new(
544                            "bynk.types.inverted_range",
545                            pred.span,
546                            format!(
547                                "`InRange({}, {})` has its bounds inverted (`min` must be ≤ `max`)",
548                                lo.value, hi.value
549                            ),
550                        )
551                        // v0.40 (ADR 0073): a machine-applicable swap — replace
552                        // each bound's text with the other's, in place.
553                        .with_suggestion(
554                            "swap the bounds",
555                            vec![
556                                (lo.span, hi.value.to_string()),
557                                (hi.span, lo.value.to_string()),
558                            ],
559                            Applicability::MachineApplicable,
560                        ),
561                    );
562                }
563            }
564            PredKind::InRangeF(lo, hi) => {
565                if lo.value > hi.value {
566                    errors.push(
567                        CompileError::new(
568                            "bynk.types.inverted_range",
569                            pred.span,
570                            format!(
571                                "`InRange({}, {})` has its bounds inverted (`min` must be ≤ `max`)",
572                                lo.lexeme, hi.lexeme
573                            ),
574                        )
575                        .with_suggestion(
576                            "swap the bounds",
577                            vec![(lo.span, hi.lexeme.clone()), (hi.span, lo.lexeme.clone())],
578                            Applicability::MachineApplicable,
579                        ),
580                    );
581                }
582            }
583            PredKind::InRangeD(lo, hi) => {
584                if bynk_syntax::decimal::cmp(&lo.coef, lo.scale, &hi.coef, hi.scale)
585                    == std::cmp::Ordering::Greater
586                {
587                    errors.push(
588                        CompileError::new(
589                            "bynk.types.inverted_range",
590                            pred.span,
591                            format!(
592                                "`InRange({}, {})` has its bounds inverted (`min` must be ≤ `max`)",
593                                lo.lexeme, hi.lexeme
594                            ),
595                        )
596                        .with_suggestion(
597                            "swap the bounds",
598                            vec![(lo.span, hi.lexeme.clone()), (hi.span, lo.lexeme.clone())],
599                            Applicability::MachineApplicable,
600                        ),
601                    );
602                }
603            }
604            PredKind::MinLength(n) | PredKind::MaxLength(n) | PredKind::Length(n) => {
605                if *n < 0 {
606                    errors.push(CompileError::new(
607                        "bynk.types.negative_length",
608                        pred.span,
609                        format!("length argument must be non-negative, got {n}"),
610                    ));
611                }
612            }
613            PredKind::NonNegative
614            | PredKind::Positive
615            | PredKind::NonEmpty
616            | PredKind::IsoDate
617            | PredKind::Cron => {}
618        }
619    }
620
621    let all_compatible = refinement
622        .predicates
623        .iter()
624        .all(|p| pred_applies_to(&p.kind, base));
625    if !all_compatible {
626        return;
627    }
628    match base {
629        BaseType::Int => check_int_refinement_consistency(refinement, errors),
630        BaseType::String => check_string_refinement_consistency(refinement, errors),
631        BaseType::Bool => {}
632        BaseType::Float => check_float_refinement_consistency(refinement, errors),
633        // v0.86/v0.90/v0.110: no refinement predicate applies to `Duration`,
634        // `Instant`, or `Bytes` (none is in any `pred_applies_to` row), so a
635        // refined one is rejected upstream and there is nothing to
636        // consistency-check here.
637        BaseType::Duration | BaseType::Instant | BaseType::Bytes => {}
638        // #2622: a decimal range has no further consistency check here; an
639        // inverted `InRange` is reported above.
640        BaseType::Decimal => {}
641    }
642}
643
644fn pred_applies_to(pred: &PredKind, base: BaseType) -> bool {
645    matches!(
646        (pred, base),
647        (PredKind::Matches(_), BaseType::String)
648            | (PredKind::InRange(_, _), BaseType::Int)
649            | (PredKind::InRangeF(_, _), BaseType::Float)
650            | (PredKind::InRangeD(_, _), BaseType::Decimal)
651            | (PredKind::MinLength(_), BaseType::String)
652            | (PredKind::MaxLength(_), BaseType::String)
653            | (PredKind::Length(_), BaseType::String)
654            | (
655                PredKind::NonNegative,
656                BaseType::Int | BaseType::Float | BaseType::Decimal
657            )
658            | (
659                PredKind::Positive,
660                BaseType::Int | BaseType::Float | BaseType::Decimal
661            )
662            | (PredKind::NonEmpty, BaseType::String)
663            | (PredKind::IsoDate, BaseType::String)
664            | (PredKind::Cron, BaseType::String)
665    )
666}
667
668fn predicate_base_help(name: &str) -> &'static str {
669    match name {
670        "Matches" | "MinLength" | "MaxLength" | "Length" | "NonEmpty" | "IsoDate" | "Cron" => {
671            "this predicate applies to `String` only"
672        }
673        "NonNegative" | "Positive" => "this predicate applies to `Int`, `Float` and `Decimal` only",
674        "InRange" => {
675            "this predicate applies to `Int`, `Float` and `Decimal` only, with bounds matching the base"
676        }
677        _ => "see the documentation for valid predicate-base combinations",
678    }
679}
680
681pub(crate) fn check_int_refinement_consistency(
682    refinement: &Refinement,
683    errors: &mut Vec<CompileError>,
684) {
685    let mut lo: i64 = i64::MIN;
686    let mut hi: i64 = i64::MAX;
687    for p in &refinement.predicates {
688        match &p.kind {
689            PredKind::Positive => lo = lo.max(1),
690            PredKind::NonNegative => lo = lo.max(0),
691            PredKind::InRange(a, b) => {
692                lo = lo.max(a.value);
693                hi = hi.min(b.value);
694            }
695            _ => {}
696        }
697    }
698    if lo > hi {
699        errors.push(
700            CompileError::new(
701                "bynk.types.empty_refinement",
702                refinement.span,
703                "this refinement has no valid values — the predicates contradict each other",
704            )
705            .with_note(format!(
706                "the effective range is `{lo}..={hi}`, which is empty"
707            )),
708        );
709    }
710}
711
712pub(crate) fn check_float_refinement_consistency(
713    refinement: &Refinement,
714    errors: &mut Vec<CompileError>,
715) {
716    let mut lo = f64::NEG_INFINITY;
717    let mut hi = f64::INFINITY;
718    // `Positive` excludes the lower endpoint (0.0 itself is not positive).
719    let mut lo_exclusive = false;
720    for p in &refinement.predicates {
721        match &p.kind {
722            PredKind::Positive if 0.0 >= lo => {
723                lo = 0.0;
724                lo_exclusive = true;
725            }
726            PredKind::NonNegative if 0.0 > lo => {
727                lo = 0.0;
728                lo_exclusive = false;
729            }
730            PredKind::InRangeF(a, b) => {
731                if a.value > lo {
732                    lo = a.value;
733                    lo_exclusive = false;
734                }
735                hi = hi.min(b.value);
736            }
737            _ => {}
738        }
739    }
740    if lo > hi || (lo == hi && lo_exclusive) {
741        errors.push(
742            CompileError::new(
743                "bynk.types.empty_refinement",
744                refinement.span,
745                "this refinement has no valid values — the predicates contradict each other",
746            )
747            .with_note(format!(
748                "the effective range is `{lo}..={hi}`{}, which is empty",
749                if lo_exclusive {
750                    " (lower bound exclusive)"
751                } else {
752                    ""
753                }
754            )),
755        );
756    }
757}
758
759pub(crate) fn check_string_refinement_consistency(
760    refinement: &Refinement,
761    errors: &mut Vec<CompileError>,
762) {
763    let mut min_len: i64 = 0;
764    let mut max_len: i64 = i64::MAX;
765    let mut exact_len: Option<i64> = None;
766    for p in &refinement.predicates {
767        match &p.kind {
768            PredKind::MinLength(n) => min_len = min_len.max(*n),
769            PredKind::MaxLength(n) => max_len = max_len.min(*n),
770            PredKind::NonEmpty => min_len = min_len.max(1),
771            // #2867: `YYYY-MM-DD` is exactly ten characters.
772            PredKind::IsoDate => {
773                min_len = min_len.max(10);
774                max_len = max_len.min(10);
775            }
776            // #3873: `* * * * *` is the shortest valid schedule, nine characters.
777            PredKind::Cron => min_len = min_len.max(9),
778            PredKind::Length(n) => {
779                if let Some(prev) = exact_len {
780                    if prev != *n {
781                        errors.push(CompileError::new(
782                            "bynk.types.empty_refinement",
783                            refinement.span,
784                            format!(
785                                "conflicting exact lengths: `Length({prev})` and `Length({n})` cannot both hold"
786                            ),
787                        ));
788                    }
789                } else {
790                    exact_len = Some(*n);
791                }
792                min_len = min_len.max(*n);
793                max_len = max_len.min(*n);
794            }
795            _ => {}
796        }
797    }
798    if min_len > max_len {
799        errors.push(
800            CompileError::new(
801                "bynk.types.empty_refinement",
802                refinement.span,
803                "this refinement has no valid values — minimum length exceeds maximum length",
804            )
805            .with_note(format!(
806                "the effective length range is `{min_len}..={max_len}`, which is empty"
807            )),
808        );
809    }
810}
811
812// -- function body type checking --
813
814/// v0.9.1: `assert e` as an expression. Test-privileged. Requires `e : Bool`.
815/// Always yields type `()`.
816/// True if a refinement cannot be satisfied by a generated default value — i.e.
817/// it contains a `Matches` predicate, where bare `Val[T]` must be given an
818/// explicit pin instead.
819pub(crate) fn refinement_needs_pin(refinement: &Refinement) -> bool {
820    refinement.predicates.iter().any(|p| {
821        matches!(
822            p.kind,
823            PredKind::Matches(_) | PredKind::IsoDate | PredKind::Cron
824        )
825    })
826}
827
828/// #2686: the `@example(<arg>)` annotation's argument on a refinement, if
829/// one is written (well-formed or not: `check_refinement_annotations`
830/// reports a malformed one, and `Val` must not pile a `needs_pin` on top).
831pub fn refinement_example(refinement: &Refinement) -> Option<&Expr> {
832    refinement
833        .annotations
834        .iter()
835        .find(|a| a.name.name == "example")
836        .and_then(|a| a.args.first())
837        .map(|a| &a.value)
838}
839
840/// #2686: whether bare `Val` still has no value for this refinement: it needs
841/// a pin (`Matches`, `IsoDate`) and carries no `@example`.
842pub(crate) fn refinement_needs_pin_without_example(refinement: &Refinement) -> bool {
843    refinement_needs_pin(refinement) && refinement_example(refinement).is_none()
844}
845
846/// #2686: validate the `@…` annotations after a type's or field's refinement.
847/// The only name is `example`; its one argument is a literal of the base type
848/// that satisfies every predicate (the check `Val[T](lit)` applies to a pin),
849/// and it is allowed only where `Val` has no value of its own.
850fn check_refinement_annotations(
851    base: BaseType,
852    refinement: &Refinement,
853    errors: &mut Vec<CompileError>,
854) {
855    let mut seen = false;
856    for ann in &refinement.annotations {
857        if ann.name.name != "example" {
858            errors.push(
859                CompileError::new(
860                    "bynk.types.unknown_annotation",
861                    ann.name.span,
862                    format!("unknown annotation `@{}` after a refinement", ann.name.name),
863                )
864                .with_note("the only annotation here is `@example(<literal>)`"),
865            );
866            continue;
867        }
868        if seen {
869            errors.push(CompileError::new(
870                "bynk.types.duplicate_example",
871                ann.span,
872                "a refinement takes at most one `@example`",
873            ));
874            continue;
875        }
876        seen = true;
877        let arg = match ann.args.as_slice() {
878            [a] if a.label.is_none() => &a.value,
879            _ => {
880                errors.push(CompileError::new(
881                    "bynk.types.example_not_literal",
882                    ann.span,
883                    "`@example` takes exactly one literal value",
884                ));
885                continue;
886            }
887        };
888        let lit = match const_literal(arg) {
889            Some(l) if literal_matches_base(&l, base) => l,
890            _ => {
891                errors.push(CompileError::new(
892                    "bynk.types.example_not_literal",
893                    arg.span,
894                    format!(
895                        "`@example` requires a literal `{}` value, or a `{}` constant bound to one",
896                        base.name(),
897                        base.name()
898                    ),
899                ));
900                continue;
901            }
902        };
903        if !refinement_needs_pin(refinement) {
904            errors.push(
905                CompileError::new(
906                    "bynk.types.example_unneeded",
907                    ann.span,
908                    "`@example` is only for a `Matches` or `IsoDate` refinement, which `Val` cannot generate",
909                )
910                .with_note("`Val` already fabricates a value for every other refinement"),
911            );
912            continue;
913        }
914        if let Some(failed) = first_failed_predicate(refinement, &lit) {
915            errors.push(CompileError::new(
916                "bynk.types.example_violates",
917                arg.span,
918                format!(
919                    "the example {} does not satisfy `{}`",
920                    lit.display(),
921                    failed.name()
922                ),
923            ));
924        }
925    }
926}
927
928/// A target-neutral zero value: what a state field holds before it is first
929/// written. The checker decides *whether* a type has one; each backend decides
930/// how to spell it.
931#[derive(Debug, Clone, PartialEq, Eq)]
932pub enum ZeroValue {
933    /// `0`: the zero of `Int`, `Float`, `Duration` (milliseconds) and
934    /// `Instant` (epoch milliseconds, the Unix epoch).
935    Number,
936    /// `false`.
937    False,
938    /// The empty string.
939    EmptyString,
940    /// The empty octet sequence (the zero of `Bytes`, ADR 0142).
941    EmptyBytes,
942    /// An `Option`'s zero, `None`, whatever its inner type.
943    None,
944    /// A record's zero: each field's zero, in declaration order.
945    Record(Vec<(String, ZeroValue)>),
946}
947
948/// The zero value of `type_ref` (with an optional inline field refinement), or
949/// `None` if the type is not zeroable.
950pub fn zero_value(
951    type_ref: &TypeRef,
952    inline: Option<&Refinement>,
953    types: &HashMap<String, Arc<TypeDecl>>,
954) -> Option<ZeroValue> {
955    zero_value_inner(type_ref, inline, types, &mut Vec::new())
956}
957
958/// Whether `type_ref` has a zero value.
959pub fn is_zeroable(
960    type_ref: &TypeRef,
961    inline: Option<&Refinement>,
962    types: &HashMap<String, Arc<TypeDecl>>,
963) -> bool {
964    zero_value(type_ref, inline, types).is_some()
965}
966
967fn zero_value_inner(
968    type_ref: &TypeRef,
969    inline: Option<&Refinement>,
970    types: &HashMap<String, Arc<TypeDecl>>,
971    visiting: &mut Vec<String>,
972) -> Option<ZeroValue> {
973    match type_ref {
974        TypeRef::Base(b, _) => {
975            if refinement_admits_zero(*b, inline) {
976                zero_of_base(*b)
977            } else {
978                None
979            }
980        }
981        // Option's zero is None, regardless of the inner type.
982        TypeRef::Option(_, _) => Some(ZeroValue::None),
983        TypeRef::Named(id) => {
984            let decl = types.get(&id.name)?;
985            match &decl.body {
986                TypeBody::Refined {
987                    base, refinement, ..
988                } => {
989                    if refinement_admits_zero(*base, refinement.as_ref()) {
990                        zero_of_base(*base)
991                    } else {
992                        None
993                    }
994                }
995                TypeBody::Record(rec) => {
996                    // A record cycle (`A = { b: B }`, `B = { a: A }`) has no
997                    // finite zero value; without this guard the recursion is
998                    // unbounded and overflows the stack. The resolver rejects
999                    // such cycles, but this walk must terminate regardless of
1000                    // what reaches it.
1001                    if visiting.iter().any(|n| n == &id.name) {
1002                        return None;
1003                    }
1004                    visiting.push(id.name.clone());
1005                    let z = agent_state_zero_record(&rec.fields, types, visiting);
1006                    visiting.pop();
1007                    z
1008                }
1009                // Non-Option sum types and opaque types have no defined zero.
1010                TypeBody::Sum(_) | TypeBody::Opaque { .. } => None,
1011            }
1012        }
1013        // Result / Effect / HttpResult / ValidationError / Unit are not
1014        // admissible state-field types and have no zero.
1015        _ => None,
1016    }
1017}
1018
1019/// The zero record for a set of fields, or `None` if any field is not
1020/// zeroable.
1021fn agent_state_zero_record(
1022    fields: &[RecordField],
1023    types: &HashMap<String, Arc<TypeDecl>>,
1024    visiting: &mut Vec<String>,
1025) -> Option<ZeroValue> {
1026    let mut parts = Vec::new();
1027    for f in fields {
1028        let z = zero_value_inner(&f.type_ref, f.refinement.as_ref(), types, visiting)?;
1029        parts.push((f.name.name.clone(), z));
1030    }
1031    Some(ZeroValue::Record(parts))
1032}
1033
1034fn zero_of_base(b: BaseType) -> Option<ZeroValue> {
1035    Some(match b {
1036        BaseType::Int | BaseType::Float | BaseType::Duration | BaseType::Instant => {
1037            ZeroValue::Number
1038        }
1039        BaseType::Bool => ZeroValue::False,
1040        BaseType::String => ZeroValue::EmptyString,
1041        BaseType::Bytes => ZeroValue::EmptyBytes,
1042        // #2622: a `Decimal`'s zero is a runtime value (`0d`), not an inline
1043        // literal, so a bare `Decimal` state field has no zero default.
1044        BaseType::Decimal => return None,
1045    })
1046}
1047
1048/// Whether the zero value of `base` satisfies every predicate in `refinement`.
1049/// Conservative: any predicate we cannot prove admits the zero returns false,
1050/// surfacing the `non_zeroable_state_field` diagnostic rather than risking an
1051/// invalid fresh state.
1052fn refinement_admits_zero(base: BaseType, refinement: Option<&Refinement>) -> bool {
1053    let Some(r) = refinement else {
1054        return true;
1055    };
1056    r.predicates.iter().all(|p| pred_admits_zero(base, &p.kind))
1057}
1058
1059fn pred_admits_zero(base: BaseType, k: &PredKind) -> bool {
1060    match base {
1061        BaseType::Int => match k {
1062            PredKind::NonNegative => true,
1063            PredKind::Positive => false,
1064            PredKind::InRange(lo, hi) => lo.value <= 0 && 0 <= hi.value,
1065            // Length/Matches predicates don't apply to Int; reject conservatively.
1066            _ => false,
1067        },
1068        BaseType::String => match k {
1069            PredKind::Matches(p) => regex_matches_empty(p),
1070            PredKind::MinLength(n) => *n <= 0,
1071            PredKind::MaxLength(n) => *n >= 0,
1072            PredKind::Length(n) => *n == 0,
1073            PredKind::NonEmpty => false,
1074            // Numeric predicates don't apply to String; reject conservatively.
1075            _ => false,
1076        },
1077        // The only Bool zero is `false`; no Bool refinement predicates exist.
1078        BaseType::Bool => true,
1079        // No refinement predicate applies to `Duration`, `Instant`, or
1080        // `Bytes`, so the question is vacuous — admit it (mirrors `Bool`).
1081        BaseType::Duration | BaseType::Instant | BaseType::Bytes => true,
1082        BaseType::Decimal => match k {
1083            PredKind::NonNegative => true,
1084            PredKind::Positive => false,
1085            PredKind::InRangeD(lo, hi) => {
1086                bynk_syntax::decimal::sign(&lo.coef) <= 0
1087                    && bynk_syntax::decimal::sign(&hi.coef) >= 0
1088            }
1089            _ => false,
1090        },
1091        BaseType::Float => match k {
1092            PredKind::NonNegative => true,
1093            PredKind::Positive => false,
1094            PredKind::InRangeF(lo, hi) => lo.value <= 0.0 && 0.0 <= hi.value,
1095            // Other predicates don't apply to Float; reject conservatively.
1096            _ => false,
1097        },
1098    }
1099}
1100
1101/// Does the refinement pattern match the empty string? Anchored exactly as the
1102/// emitted refined-type constructor anchors it (`^(?:pattern)$`), and
1103/// evaluated with the same engine semantics (ECMAScript, no flags).
1104fn regex_matches_empty(pattern: &str) -> bool {
1105    match regress::Regex::new(&format!("^(?:{pattern})$")) {
1106        Ok(re) => re.find("").is_some(),
1107        Err(_) => false,
1108    }
1109}
1110
1111/// #2895: the nested-quantifier first pass is a structural over-approximation:
1112/// it flags any repeated group holding an unbounded quantifier, including
1113/// unambiguous ones such as the slug `[a-z]+(-[a-z]+)*`, where each repetition
1114/// must open with a literal `-` that neither `[a-z]+` can match. A flagged
1115/// pattern is refused unless the automaton analysis (`regex_ambiguity`) proves
1116/// it linear: it decides on the pattern's character sets (what can end one
1117/// repetition against what must start the next), covers the nested shapes
1118/// (`(a+)+`, `([a-z]+)*`, `(\w+\s?)*`, an optional separator `(-?[a-z]+)*`)
1119/// as exponential, and treats anything it cannot analyse as unsafe.
1120fn proved_linear(pat: &str, flags: &str) -> bool {
1121    use super::regex_ambiguity::{Verdict, analyse_with_flags};
1122    analyse_with_flags(pat, flags) == Verdict::Linear
1123}
1124
1125/// #1651: the diagnostic for a `Matches` pattern the automaton ambiguity
1126/// analysis (`regex_ambiguity`) does not prove linear, or `None` when it does.
1127///
1128/// Exponential ambiguity, and a pattern the analysis cannot bound, are errors.
1129/// Polynomial ambiguity is an error unless the refinement also bounds the
1130/// input's length (`MaxLength` or `Length`) tightly enough for the
1131/// polynomial's degree (`bound^degree` within [`POLYNOMIAL_STEP_CAP`]): the
1132/// emitter checks length predicates before `Matches`
1133/// (`bynk_syntax::ast::in_check_order`), so such a bound caps the cost, and it
1134/// is a warning.
1135/// `label` names the pattern in the message (`` `Matches("…")` ``, or a K6c
1136/// regex argument). `bound` is the input-length bound a refinement states:
1137/// `Some(None)` when it could state one but does not, `None` when no bound is
1138/// possible (a K6c regex method runs on any string), which changes the advice.
1139fn ambiguity_diagnostic(
1140    pat: &str,
1141    flags: &str,
1142    span: Span,
1143    label: &str,
1144    bound: Option<Option<i64>>,
1145) -> Option<CompileError> {
1146    use super::regex_ambiguity::{Verdict, analyse_with_flags};
1147    // K6c (#2600): the flags change what `.` and a cased letter match, so the
1148    // analysis must read the pattern under them (`Matches` has none).
1149    Some(match analyse_with_flags(pat, flags) {
1150        Verdict::Linear => return None,
1151        Verdict::Exponential(a, b) => CompileError::new(
1152            "bynk.types.catastrophic_regex",
1153            span,
1154            format!(
1155                "the pattern in {label} can match the same text in \
1156                 exponentially many ways, which can cause catastrophic backtracking (ReDoS)"
1157            ),
1158        )
1159        .with_note(format!(
1160            "inside a repetition, `{a}` and `{b}` can match the same character on \
1161             different paths, so each repetition doubles the ways a near-miss input \
1162             is tried; make the alternatives (or repeat counts) inside the loop \
1163             unambiguous, e.g. `(a|aa)+` as `a+`"
1164        )),
1165        Verdict::Unanalysable(why) => CompileError::new(
1166            "bynk.types.catastrophic_regex",
1167            span,
1168            format!(
1169                "the pattern in {label} cannot be shown free of catastrophic \
1170                 backtracking (ReDoS): {why}"
1171            ),
1172        )
1173        .with_note(
1174            "the boundary check runs this pattern on request input under a backtracking \
1175             engine, so a pattern that cannot be analysed is rejected; simplify it",
1176        ),
1177        Verdict::Polynomial(degree, a, b) => {
1178            let largest = largest_safe_bound(degree);
1179            let (code, advice) = match bound.flatten() {
1180                Some(n) if n <= largest => (
1181                    "bynk.types.polynomial_regex_capped",
1182                    format!(
1183                        "the refinement bounds the input at {n} characters, which keeps \
1184                         the cost small, so this is a warning; rewrite the pattern so the \
1185                         repetitions cannot overlap to silence it"
1186                    ),
1187                ),
1188                Some(n) => (
1189                    "bynk.types.polynomial_regex",
1190                    format!(
1191                        "the refinement bounds the input at {n} characters, but at degree \
1192                         {degree} that still allows about {n}^{degree} steps; lower the \
1193                         bound to at most {largest}, or rewrite the pattern so the \
1194                         repetitions cannot overlap"
1195                    ),
1196                ),
1197                None if bound.is_some() => (
1198                    "bynk.types.polynomial_regex",
1199                    format!(
1200                        "add a `MaxLength(n)` predicate with `n` at most {largest} to bound \
1201                         the input, or rewrite the pattern so the repetitions cannot overlap"
1202                    ),
1203                ),
1204                None => (
1205                    "bynk.types.polynomial_regex",
1206                    "a regex method runs on input of any length, so rewrite the pattern so \
1207                     the repetitions cannot overlap"
1208                        .to_string(),
1209                ),
1210            };
1211            CompileError::new(
1212                code,
1213                span,
1214                format!(
1215                    "the pattern in {label} can split the same text between \
1216                     repetitions in many ways, so matching time grows with the input's \
1217                     length to the power {degree} (ReDoS)"
1218                ),
1219            )
1220            .with_note(format!(
1221                "`{a}` and `{b}` repeat in sequence and can match the same characters, as \
1222                 in `\\d*\\d*`; {advice}"
1223            ))
1224        }
1225    })
1226}
1227
1228/// K6c (#2594's sibling, #2600): check a regex method's pattern argument the
1229/// way a `Matches` pattern is checked: valid under ECMAScript semantics
1230/// (`regress`), no nested unbounded quantifier, and no ambiguity the automaton
1231/// analysis finds — with no length bound to excuse a polynomial one. A pattern
1232/// may open with one inline-flag group, `(?i)`, `(?m)`, `(?s)` or a
1233/// combination, which JS lacks; it is stripped here and returned as the
1234/// `RegExp` flags. On success, the pattern without that group and its flags.
1235pub(crate) fn check_regex_literal(
1236    literal: &str,
1237    span: Span,
1238) -> Result<(String, String), CompileError> {
1239    let label = format!("`\"{literal}\"`");
1240    let (pat, flags) = match leading_flag_group(literal) {
1241        Some((pat, flags)) => {
1242            let mut seen = String::new();
1243            for c in flags.chars() {
1244                if !"ims".contains(c) || seen.contains(c) {
1245                    return Err(CompileError::new(
1246                        "bynk.types.invalid_regex",
1247                        span,
1248                        format!("invalid inline flags `(?{flags})` in {label}"),
1249                    )
1250                    .with_note("the inline flags are `i`, `m` and `s`, each at most once"));
1251                }
1252                seen.push(c);
1253            }
1254            (pat.to_string(), seen)
1255        }
1256        None => (literal.to_string(), String::new()),
1257    };
1258    if let Err(e) = regress::Regex::with_flags(&pat, flags.as_str()) {
1259        return Err(CompileError::new(
1260            "bynk.types.invalid_regex",
1261            span,
1262            format!("invalid regular expression {label}"),
1263        )
1264        .with_note(format!("regex parse error (JS `RegExp` semantics): {e}")));
1265    }
1266    if has_nested_unbounded_quantifier(&pat) && !proved_linear(&pat, &flags) {
1267        return Err(CompileError::new(
1268            "bynk.types.catastrophic_regex",
1269            span,
1270            format!(
1271                "the pattern {label} nests unbounded quantifiers, which can cause \
1272                 catastrophic backtracking (ReDoS)"
1273            ),
1274        )
1275        .with_note(
1276            "a repeated group that itself contains `*`, `+`, or `{n,}` makes matching take \
1277             exponential time on crafted input; restructure the pattern so no unbounded \
1278             quantifier is nested inside another",
1279        ));
1280    }
1281    if let Some(e) = ambiguity_diagnostic(&pat, &flags, span, &label, None) {
1282        return Err(e);
1283    }
1284    Ok((pat, flags))
1285}
1286
1287/// A leading `(?flags)` group of letters, split off: the rest of the pattern
1288/// and the letters. `None` when the literal opens with no such group (a
1289/// lookaround `(?=`, `(?!`, `(?<` or a non-capturing `(?:` is not one).
1290fn leading_flag_group(literal: &str) -> Option<(&str, &str)> {
1291    let rest = literal.strip_prefix("(?")?;
1292    let end = rest.find(')')?;
1293    let flags = &rest[..end];
1294    (!flags.is_empty() && flags.chars().all(|c| c.is_ascii_alphabetic()))
1295        .then(|| (&rest[end + 1..], flags))
1296}
1297
1298/// K6c (#2600): a checked regex literal as the emitter writes it, the pattern
1299/// and its `RegExp` flags. The checker has already refused a malformed flag
1300/// group, so this only splits.
1301pub fn split_regex_flags(literal: &str) -> (String, String) {
1302    match leading_flag_group(literal) {
1303        Some((pat, flags)) => (pat.to_string(), flags.to_string()),
1304        None => (literal.to_string(), String::new()),
1305    }
1306}
1307
1308/// #1651: how many steps a polynomially ambiguous pattern may take on its
1309/// longest admitted input and still only warn. At `10⁷` V8 matches in tens of
1310/// milliseconds: `\d*\d*\d*` takes about 23 ms at 256 characters.
1311const POLYNOMIAL_STEP_CAP: u128 = 10_000_000;
1312
1313/// The largest length bound `n` with `n^degree` within [`POLYNOMIAL_STEP_CAP`]:
1314/// 3162 at degree 2, 215 at degree 3, 56 at degree 4.
1315fn largest_safe_bound(degree: u32) -> i64 {
1316    let mut n: i64 = 1;
1317    while (n as u128 + 1)
1318        .checked_pow(degree)
1319        .is_some_and(|s| s <= POLYNOMIAL_STEP_CAP)
1320    {
1321        n += 1;
1322    }
1323    n
1324}
1325
1326/// #724 — detect one catastrophic-backtracking (ReDoS) signature: an unbounded
1327/// quantifier applied to a group that itself contains an unbounded quantifier
1328/// ("star height ≥ 2", e.g. `(a+)+`, `(a*)*b`, `((ab)+)+`). Under the JS
1329/// backtracking `RegExp` the emitted boundary check runs, this class takes
1330/// exponential time on a crafted near-miss input; the conservative structural
1331/// rule rejects it at compile time.
1332///
1333/// "Unbounded" means `*`, `+`, or `{n,}` (open upper bound). A bounded
1334/// quantifier is not flagged here, though one inside a loop can explode too
1335/// (`(a{2,3})+`); that is the ambiguity analysis's case. The scan is purely structural — the pattern is
1336/// already known valid (`regress` accepted it) — so it need not model match
1337/// semantics, only quantifier nesting through groups. Inner unbounded
1338/// quantifiers propagate up through *bounded* quantifiers too, so `((a+)?)+`
1339/// is still caught. The check is conservative in the safe direction: it can
1340/// reject a star-height-2 pattern whose sub-expressions provably never overlap,
1341/// but every *nested-quantifier* blowup is flagged.
1342///
1343/// This is a cheap first pass, not the whole exponential class. Ambiguous
1344/// alternation under a single quantifier (`(a|a)+`, `(\d|\d\d)+`), a bounded
1345/// quantifier inside a loop (`(a{2,3})+`) and the polynomial class
1346/// (`\d*\d*`) are star height 1 and pass here. `regex_ambiguity` (#1651)
1347/// decides them on the pattern's automaton, and runs only on patterns this
1348/// pass accepts, so this pass's clearer message wins where both apply.
1349fn has_nested_unbounded_quantifier(pat: &str) -> bool {
1350    // Precondition: `pat` is a valid regex (`regress` accepted it), so its
1351    // parentheses are balanced. The `stack.last_mut().unwrap()` arms below rely
1352    // on that — a `)` never pops the root frame — which the sole caller ensures
1353    // by running this only after the validity check. The `)` arm keeps a
1354    // defensive `unwrap_or` regardless.
1355    let chars: Vec<char> = pat.chars().collect();
1356    // One boolean per open group (index 0 = top level): does this group contain
1357    // an unbounded quantifier anywhere within it?
1358    let mut stack: Vec<bool> = vec![false];
1359    // The atom a following quantifier would apply to: `None` if none is pending,
1360    // else `Some(inner_unbounded)` where `inner_unbounded` is true when that atom
1361    // is a group carrying an unbounded quantifier inside it.
1362    let mut pending: Option<bool> = None;
1363    let mut i = 0;
1364
1365    // Fold a pending atom that turned out to be unquantified into the current
1366    // frame: if it was a group with inner unbounded content, that content still
1367    // lives in the enclosing group.
1368    fn fold(pending: &mut Option<bool>, stack: &mut [bool]) {
1369        if pending.take() == Some(true) {
1370            *stack.last_mut().unwrap() = true;
1371        }
1372    }
1373
1374    while i < chars.len() {
1375        match chars[i] {
1376            // An escape is a single atom; skip the escaped char.
1377            '\\' => {
1378                fold(&mut pending, &mut stack);
1379                i += 2;
1380                pending = Some(false);
1381            }
1382            // A character class is one atom; `*`/`+`/`{` inside it are literal.
1383            '[' => {
1384                fold(&mut pending, &mut stack);
1385                i += 1;
1386                if i < chars.len() && chars[i] == '^' {
1387                    i += 1;
1388                }
1389                // A leading `]` is a literal member, not the class terminator.
1390                if i < chars.len() && chars[i] == ']' {
1391                    i += 1;
1392                }
1393                while i < chars.len() && chars[i] != ']' {
1394                    if chars[i] == '\\' {
1395                        i += 1;
1396                    }
1397                    i += 1;
1398                }
1399                i += 1; // consume the closing `]`
1400                pending = Some(false);
1401            }
1402            '(' => {
1403                fold(&mut pending, &mut stack);
1404                stack.push(false);
1405                i += 1;
1406                // Skip a group-type prefix so its punctuation is not mistaken for
1407                // an atom: `(?:`, `(?=`, `(?!`, `(?<=`, `(?<!`, `(?<name>`.
1408                if i < chars.len() && chars[i] == '?' {
1409                    i += 1;
1410                    if i < chars.len() && matches!(chars[i], ':' | '=' | '!') {
1411                        i += 1;
1412                    } else if i < chars.len() && chars[i] == '<' {
1413                        i += 1;
1414                        if i < chars.len() && matches!(chars[i], '=' | '!') {
1415                            i += 1;
1416                        } else {
1417                            while i < chars.len() && chars[i] != '>' {
1418                                i += 1;
1419                            }
1420                            if i < chars.len() {
1421                                i += 1; // consume `>`
1422                            }
1423                        }
1424                    }
1425                }
1426            }
1427            ')' => {
1428                fold(&mut pending, &mut stack);
1429                let closed = stack.pop().unwrap_or(false);
1430                i += 1;
1431                // The whole group is now an atom in its parent frame.
1432                pending = Some(closed);
1433            }
1434            // Alternation ends the current atom; an unbounded one folds in.
1435            '|' => {
1436                fold(&mut pending, &mut stack);
1437                i += 1;
1438            }
1439            // Unbounded quantifier.
1440            '*' | '+' => {
1441                let atom_unbounded = pending.take().unwrap_or(false);
1442                if atom_unbounded {
1443                    return true; // unbounded nested inside unbounded
1444                }
1445                *stack.last_mut().unwrap() = true;
1446                i += 1;
1447                if i < chars.len() && chars[i] == '?' {
1448                    i += 1; // lazy marker
1449                }
1450            }
1451            // Optional: bounded, but inner unbounded content still propagates.
1452            '?' => {
1453                if let Some(atom_unbounded) = pending.take() {
1454                    if atom_unbounded {
1455                        *stack.last_mut().unwrap() = true;
1456                    }
1457                    i += 1;
1458                    if i < chars.len() && chars[i] == '?' {
1459                        i += 1; // lazy marker
1460                    }
1461                } else {
1462                    // Stray `?` (unreachable for a valid pattern) — treat as atom.
1463                    i += 1;
1464                    pending = Some(false);
1465                }
1466            }
1467            '{' => {
1468                if let Some((unbounded_q, next)) = parse_brace_quantifier(&chars, i) {
1469                    let atom_unbounded = pending.take().unwrap_or(false);
1470                    if unbounded_q && atom_unbounded {
1471                        return true;
1472                    }
1473                    if unbounded_q || atom_unbounded {
1474                        *stack.last_mut().unwrap() = true;
1475                    }
1476                    i = next;
1477                    if i < chars.len() && chars[i] == '?' {
1478                        i += 1; // lazy marker
1479                    }
1480                } else {
1481                    // A `{` that is not a quantifier is a literal atom.
1482                    fold(&mut pending, &mut stack);
1483                    i += 1;
1484                    pending = Some(false);
1485                }
1486            }
1487            // Any other char (`.`, literal, `^`, `$`) is an ordinary atom.
1488            _ => {
1489                fold(&mut pending, &mut stack);
1490                i += 1;
1491                pending = Some(false);
1492            }
1493        }
1494    }
1495    false
1496}
1497
1498/// Parse a `{m}`, `{m,}`, or `{m,n}` quantifier starting at `chars[start] == '{'`.
1499/// Returns `(is_unbounded, index_after_close)` when it is a well-formed
1500/// quantifier — `is_unbounded` is true only for `{m,}` (open upper bound) — or
1501/// `None` when the braces are not a quantifier (then they are literal text, as
1502/// JS `RegExp` treats them).
1503fn parse_brace_quantifier(chars: &[char], start: usize) -> Option<(bool, usize)> {
1504    let mut i = start + 1;
1505    let lo_start = i;
1506    while i < chars.len() && chars[i].is_ascii_digit() {
1507        i += 1;
1508    }
1509    if i == lo_start {
1510        return None; // `{m` requires at least one digit
1511    }
1512    let mut unbounded = false;
1513    if i < chars.len() && chars[i] == ',' {
1514        i += 1;
1515        let hi_start = i;
1516        while i < chars.len() && chars[i].is_ascii_digit() {
1517            i += 1;
1518        }
1519        if i == hi_start {
1520            unbounded = true; // `{m,}` — no upper bound
1521        }
1522    }
1523    if i < chars.len() && chars[i] == '}' {
1524        Some((unbounded, i + 1))
1525    } else {
1526        None
1527    }
1528}
1529
1530#[cfg(test)]
1531mod redos_tests {
1532    use super::has_nested_unbounded_quantifier as redos;
1533
1534    #[test]
1535    fn flags_nested_unbounded_quantifiers() {
1536        // The classic exponential shapes: an unbounded quantifier over a group
1537        // that itself repeats unboundedly.
1538        assert!(redos("(a+)+"));
1539        assert!(redos("(a+)+$"));
1540        assert!(redos("(a*)*"));
1541        assert!(redos("(a+)*"));
1542        assert!(redos("(a*)+"));
1543        assert!(redos("((ab)+)+"));
1544        assert!(redos("(a{1,})+")); // `{1,}` is unbounded
1545        assert!(redos("(a+){2,}")); // outer open bound over inner `+`
1546        assert!(redos("x(y(z+)+w)+")); // nested a level deep
1547        assert!(redos("(\\d+)+"));
1548        assert!(redos("(?:a+)+")); // non-capturing group
1549        assert!(redos("([a-z]+)*")); // class inside the repeated group
1550        assert!(redos("((a+)?)+")); // inner unbounded propagates through `?`
1551        assert!(redos("(a+|b)+")); // alternation does not launder the nesting
1552    }
1553
1554    #[test]
1555    fn nested_quantifiers_are_refused_unless_proved_linear() {
1556        // #2895: the first pass flags every pattern below; `proved_linear`
1557        // separates the unambiguous separator shapes from the dangerous ones.
1558        for pat in [
1559            "[a-z]+(-[a-z]+)*",
1560            "[a-z0-9]+(\\.[a-z0-9]+)*",
1561            "[a-z]+(?:_[a-z]+)*",
1562            "[A-Z]+(-[A-Z]+)+",
1563        ] {
1564            assert!(redos(pat), "first pass should flag `{pat}`");
1565            assert!(super::proved_linear(pat, ""), "`{pat}` is unambiguous");
1566        }
1567        // Bounded inner repeat: not flagged by the first pass, but linear.
1568        assert!(!redos("\\d+(,\\d{3})*") && super::proved_linear("\\d+(,\\d{3})*", ""));
1569        for pat in [
1570            "(a+)+",
1571            "(a|a)*",
1572            "([a-z]+)*",
1573            "[a-z]+(-?[a-z]+)*",
1574            "[a-z]+([-a-z]+)*",
1575            "(\\w+\\s?)*",
1576            "[a-z]+(-?[a-z])*",
1577            "[a-z]*(-[a-z]+)*[a-z]*",
1578            "[a-z]+(-[a-z]+|[a-z])*",
1579        ] {
1580            assert!(!super::proved_linear(pat, ""), "`{pat}` must stay refused");
1581        }
1582    }
1583
1584    #[test]
1585    fn allows_safe_patterns() {
1586        // A single quantifier level is fine, however placed.
1587        assert!(!redos("a+"));
1588        assert!(!redos("(a+)")); // repeated once, not nested
1589        assert!(!redos("(a+)(b+)")); // siblings, not nested
1590        assert!(!redos("(ab)+")); // repeated group with no inner quantifier
1591        assert!(!redos("(a+)?")); // bounded outer quantifier
1592        assert!(!redos("(a+){2,3}")); // finite outer bound
1593        // Not flagged *here*, though exponential: a bounded quantifier inside a
1594        // loop is the ambiguity analysis's case (#1651), pinned below.
1595        assert!(!redos("(a{2,3})+"));
1596        assert!(!redos("[a-z]+")); // `+` binds the class, not a group
1597        assert!(!redos("a{2,}b{2,}")); // two unbounded, neither nested
1598    }
1599
1600    #[test]
1601    fn the_ambiguity_analysis_covers_what_the_first_pass_does_not() {
1602        // #1651: star-height-1 shapes the first pass passes, and the ambiguity
1603        // analysis decides. `(foo|foobar)+` is unambiguous ({foo, foobar} is
1604        // uniquely decodable), so it is linear and accepted.
1605        use super::super::regex_ambiguity::{Verdict, analyse};
1606        for pat in [
1607            "(a|a)+",
1608            "(\\d|\\d\\d)+",
1609            "(a|aa)*",
1610            "(a{1,2})+",
1611            "(a{2,3})+",
1612        ] {
1613            assert!(!redos(pat), "the first pass is not meant to flag `{pat}`");
1614            assert!(
1615                matches!(analyse(pat), Verdict::Exponential(..)),
1616                "`{pat}` is exponential"
1617            );
1618        }
1619        assert!(matches!(analyse("\\d*\\d*"), Verdict::Polynomial(..)));
1620        assert_eq!(analyse("(foo|foobar)+"), Verdict::Linear);
1621    }
1622
1623    #[test]
1624    fn allows_every_pattern_used_in_the_repo() {
1625        // Guard against a false positive on the `Matches` patterns the fixtures,
1626        // docs, and examples ship — none nests unbounded quantifiers.
1627        for pat in [
1628            "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
1629            "[a-z][a-z0-9-]*",
1630            "[A-Z]{3}-[0-9]{4}",
1631            "[A-Z]{3}",
1632            "[a-z]+",
1633            "[A-Z]+",
1634            "[a-z]+(?<=ing)",
1635            "[a-z0-9_]+",
1636            "[a-z0-9]{1,16}",
1637            "[a-z0-9]{1,8}",
1638            "[A-Z0-9]{3,16}",
1639            "[a-z0-9]{3,8}",
1640            "[a-zA-Z0-9]{6,8}",
1641            "ab|cd",
1642            "AUTH-[0-9]{8}",
1643            "AUTH-[0-9]+",
1644            "CUST-[0-9]+",
1645            "https?://.+",
1646            "ORD-[0-9]{6}",
1647            "ORD-[0-9]+",
1648            "SHP-[0-9]{8}",
1649            "T-[0-9]+",
1650            "[A-Z0-9]{8}",
1651            "[A-Z]{2}[0-9]{2}",
1652            "^[a-z]+$",
1653            "\\d{4}",
1654            "\\d+",
1655        ] {
1656            assert!(!redos(pat), "false positive on safe pattern `{pat}`");
1657            assert_eq!(
1658                super::super::regex_ambiguity::analyse(pat),
1659                super::super::regex_ambiguity::Verdict::Linear,
1660                "the ambiguity analysis rejects safe pattern `{pat}`"
1661            );
1662        }
1663        // `LocaleTag`'s pattern is read from the firstparty source rather than
1664        // duplicated here (its own single-source-of-truth rule, ADR 0279), so
1665        // fetch it live instead of hand-copying the string.
1666        let locale_pat = super::locale_tag_pattern().expect("LocaleTag has a Matches predicate");
1667        assert!(
1668            !redos(locale_pat),
1669            "false positive on safe pattern `{locale_pat}`"
1670        );
1671        assert_eq!(
1672            super::super::regex_ambiguity::analyse(locale_pat),
1673            super::super::regex_ambiguity::Verdict::Linear,
1674            "the ambiguity analysis rejects `LocaleTag`"
1675        );
1676    }
1677}
1678
1679#[cfg(test)]
1680mod locale_tag_tests {
1681    use super::locale_tag_accepts;
1682
1683    #[test]
1684    fn admits_the_pre_existing_shapes() {
1685        for tag in ["en", "pt-BR", "zh-Hans-CN", "es-419"] {
1686            assert!(locale_tag_accepts(tag), "expected `{tag}` to be admitted");
1687        }
1688    }
1689
1690    #[test]
1691    fn admits_variants_extensions_private_use_and_extlang() {
1692        for tag in [
1693            "de-CH-1996",          // variant (digit-led)
1694            "ca-valencia",         // variant (alpha)
1695            "sl-rozaj",            // variant, shortest admitted length
1696            "en-scotland-fonipa",  // two variants
1697            "en-US-u-ca-buddhist", // extension
1698            "de-CH-x-phonebk",     // attached private-use
1699            "x-custom",            // standalone private-use
1700            "zh-yue",              // extlang
1701        ] {
1702            assert!(locale_tag_accepts(tag), "expected `{tag}` to be admitted");
1703        }
1704    }
1705
1706    #[test]
1707    fn rejects_grandfathered_and_malformed_tags() {
1708        for tag in [
1709            "i-klingon",      // grandfathered irregular
1710            "en-GB-oed",      // grandfathered irregular
1711            "Klingon",        // not a tag at all
1712            "pt-br",          // region must be uppercase
1713            "en-SCOTLAND",    // variant must be lowercase
1714            "en-x-abcdefghi", // private-use subtag over 8 chars
1715            "x",              // private-use with no subtag
1716            "",
1717        ] {
1718            assert!(!locale_tag_accepts(tag), "expected `{tag}` to be rejected");
1719        }
1720    }
1721}