1use 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 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 if let Some(b) = field_base_type(&f.type_ref, types) {
35 check_refinement(b, f.type_ref.span(), Some(ref_r), errors);
36 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
73pub(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 continue;
91 };
92 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 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 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
160fn 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
172pub(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
183pub(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
193pub(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
217pub(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 regress::Regex::new(&format!("^(?:{pat})$"))
248 .map(|re| re.find(s).is_some())
249 .unwrap_or(false)
250 }
251 _ => true,
252 }
253}
254
255pub(crate) fn first_failed_predicate<'a>(
257 refinement: &'a Refinement,
258 lit: &ConstLit,
259) -> Option<&'a PredKind> {
260 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
268fn 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
294pub 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
306pub 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
330pub(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
356pub(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 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 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 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 Some(
525 refinement
526 .predicates
527 .iter()
528 .filter_map(|p| match p.kind {
529 PredKind::MaxLength(n) | PredKind::Length(n) => Some(n),
530 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 .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 BaseType::Duration | BaseType::Instant | BaseType::Bytes => {}
638 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 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 PredKind::IsoDate => {
773 min_len = min_len.max(10);
774 max_len = max_len.min(10);
775 }
776 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
812pub(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
828pub 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
840pub(crate) fn refinement_needs_pin_without_example(refinement: &Refinement) -> bool {
843 refinement_needs_pin(refinement) && refinement_example(refinement).is_none()
844}
845
846fn 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#[derive(Debug, Clone, PartialEq, Eq)]
932pub enum ZeroValue {
933 Number,
936 False,
938 EmptyString,
940 EmptyBytes,
942 None,
944 Record(Vec<(String, ZeroValue)>),
946}
947
948pub 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
958pub 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 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 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 TypeBody::Sum(_) | TypeBody::Opaque { .. } => None,
1011 }
1012 }
1013 _ => None,
1016 }
1017}
1018
1019fn 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 BaseType::Decimal => return None,
1045 })
1046}
1047
1048fn 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 _ => 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 _ => false,
1076 },
1077 BaseType::Bool => true,
1079 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 _ => false,
1097 },
1098 }
1099}
1100
1101fn 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
1111fn 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
1125fn 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 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
1228pub(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
1287fn 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
1298pub 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
1308const POLYNOMIAL_STEP_CAP: u128 = 10_000_000;
1312
1313fn 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
1326fn has_nested_unbounded_quantifier(pat: &str) -> bool {
1350 let chars: Vec<char> = pat.chars().collect();
1356 let mut stack: Vec<bool> = vec![false];
1359 let mut pending: Option<bool> = None;
1363 let mut i = 0;
1364
1365 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 '\\' => {
1378 fold(&mut pending, &mut stack);
1379 i += 2;
1380 pending = Some(false);
1381 }
1382 '[' => {
1384 fold(&mut pending, &mut stack);
1385 i += 1;
1386 if i < chars.len() && chars[i] == '^' {
1387 i += 1;
1388 }
1389 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; pending = Some(false);
1401 }
1402 '(' => {
1403 fold(&mut pending, &mut stack);
1404 stack.push(false);
1405 i += 1;
1406 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; }
1423 }
1424 }
1425 }
1426 }
1427 ')' => {
1428 fold(&mut pending, &mut stack);
1429 let closed = stack.pop().unwrap_or(false);
1430 i += 1;
1431 pending = Some(closed);
1433 }
1434 '|' => {
1436 fold(&mut pending, &mut stack);
1437 i += 1;
1438 }
1439 '*' | '+' => {
1441 let atom_unbounded = pending.take().unwrap_or(false);
1442 if atom_unbounded {
1443 return true; }
1445 *stack.last_mut().unwrap() = true;
1446 i += 1;
1447 if i < chars.len() && chars[i] == '?' {
1448 i += 1; }
1450 }
1451 '?' => {
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; }
1461 } else {
1462 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; }
1480 } else {
1481 fold(&mut pending, &mut stack);
1483 i += 1;
1484 pending = Some(false);
1485 }
1486 }
1487 _ => {
1489 fold(&mut pending, &mut stack);
1490 i += 1;
1491 pending = Some(false);
1492 }
1493 }
1494 }
1495 false
1496}
1497
1498fn 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; }
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; }
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 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,})+")); assert!(redos("(a+){2,}")); assert!(redos("x(y(z+)+w)+")); assert!(redos("(\\d+)+"));
1548 assert!(redos("(?:a+)+")); assert!(redos("([a-z]+)*")); assert!(redos("((a+)?)+")); assert!(redos("(a+|b)+")); }
1553
1554 #[test]
1555 fn nested_quantifiers_are_refused_unless_proved_linear() {
1556 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 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 assert!(!redos("a+"));
1588 assert!(!redos("(a+)")); assert!(!redos("(a+)(b+)")); assert!(!redos("(ab)+")); assert!(!redos("(a+)?")); assert!(!redos("(a+){2,3}")); assert!(!redos("(a{2,3})+"));
1596 assert!(!redos("[a-z]+")); assert!(!redos("a{2,}b{2,}")); }
1599
1600 #[test]
1601 fn the_ambiguity_analysis_covers_what_the_first_pass_does_not() {
1602 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 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 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", "ca-valencia", "sl-rozaj", "en-scotland-fonipa", "en-US-u-ca-buddhist", "de-CH-x-phonebk", "x-custom", "zh-yue", ] {
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", "en-GB-oed", "Klingon", "pt-br", "en-SCOTLAND", "en-x-abcdefghi", "x", "",
1717 ] {
1718 assert!(!locale_tag_accepts(tag), "expected `{tag}` to be rejected");
1719 }
1720 }
1721}