1use std::collections::{HashMap, HashSet};
14
15use super::decimal::Decimal;
16use super::diagnostics::{Result, TranslationError, type_error, unsupported};
17use super::ir::{
18 Binder, ByZero, Case, Comparison, Ctor, DataDecl, Decl, Effect, Expr, Field, FnDecl, Hints,
19 Item, LitValue, Main, Node, Param, Pattern, Plan, Program, Proof, Prop, Semantics, TheoremDecl,
20};
21use super::proof::{ProofContext, ProofName, TheoremHead, normalise_proof};
22use super::surface::{
23 BinaryOp, External, Flavor, Rounding, SArrayItem, SCase, SCasePattern, SEffect, SExpr, SItem,
24 SMain, SNode, SPattern, SPatternNode, SProgram, SProp, SPropNode, SRow, ShowStyle, UnaryOp,
25};
26use super::types::{BOOL, FLOAT, INT, NAT, STRING, Type, UNIT, array, data, fixed, fixed_bounds};
27use super::{Language, Span};
28
29mod array_bindings;
30mod array_callbacks;
31mod array_from;
32mod array_relative_element_template;
33mod arrays;
34mod callables;
35mod collections;
36mod expectation;
37mod expressions;
38mod externals;
39mod items;
40mod matches;
41mod math;
42mod optional_values;
43mod primitive_methods;
44mod records;
45mod recursion;
46mod string_code_unit_template;
47mod strings;
48mod type_queries;
49pub use self::recursion::*;
50
51pub fn check_program(surface: &SProgram) -> Result<Program> {
56 super::source_diagnostic_attributes::validate_surface(surface)?;
57 super::source_unit_clone_derivations::validate_surface_unit_clone_derivations(surface)?;
58 Checker::new(surface.language, surface.externals.clone()).program(surface)
59}
60
61pub(crate) fn read_checked_match_pattern_bindings(
63 pattern: &Pattern,
64 ty: &Type,
65 declarations: &[Decl],
66) -> Result<Vec<Binder>> {
67 let surface = match pattern {
68 Pattern::Wild => SCasePattern::Wild,
69 Pattern::Bind { name } => SCasePattern::Bind { name: name.clone() },
70 Pattern::NatZero => SCasePattern::NatZero,
71 Pattern::NatSucc { name } => SCasePattern::NatSucc { name: name.clone() },
72 Pattern::Ctor { ctor, binds, .. } => SCasePattern::Ctor {
73 path: vec![ctor.clone()],
74 binds: binds.clone(),
75 },
76 };
77 let mut checker = Checker::new(Language::JavaScript, Vec::new());
78 checker.decls = declarations
79 .iter()
80 .map(|declaration| (declaration.full_name().to_owned(), declaration.clone()))
81 .collect();
82 let mut environment = Env::default();
83 let verified_pattern = checker.pattern(&surface, ty, &mut environment, None)?;
84 if verified_pattern != *pattern {
85 return Err(type_error(
86 "a checked pattern has inconsistent ownership",
87 None,
88 ));
89 }
90 let mut names = HashSet::new();
91 verified_pattern
92 .bound()
93 .into_iter()
94 .map(|name| {
95 if name.is_empty() || !names.insert(name) {
96 return Err(type_error(
97 "a checked pattern binds the same name twice",
98 None,
99 ));
100 }
101 let ty = environment
102 .vars
103 .get(name)
104 .ok_or_else(|| type_error("a checked pattern binding is unresolved", None))?;
105 Ok(Binder {
106 name: name.to_owned(),
107 ty: ty.clone(),
108 })
109 })
110 .collect()
111}
112
113pub fn coerce(
118 value: Expr,
119 ty: &Type,
120 language: Language,
121 span: Option<Span>,
122 flavor: Option<Flavor>,
123) -> Result<Expr> {
124 if value.ty.is_literal() {
125 return Err(type_error("untyped literal", span));
126 }
127 if value.ty.same(ty) {
128 return Ok(value);
129 }
130 if matches!(value.node, Node::Abort { .. }) {
131 return Ok(Expr {
132 ty: ty.clone(),
133 ..value
134 });
135 }
136 let absence = match &value.node {
137 Node::None { absence } => absence.as_str(),
138 _ => "",
139 };
140 let same_element = matches!(ty, Type::Option { element, .. } if value.ty.same(element));
141 let optional = super::optional_value_rules::read_optional_coercion_operation(
142 language.as_str(),
143 ty.kind(),
144 value.ty.kind(),
145 value.kind(),
146 ty.accepts_absence(absence),
147 ty.accepts_absence("undefined"),
148 same_element,
149 );
150 match optional.as_str() {
151 "absence-error" => {
152 let Type::Option {
153 absence: expected, ..
154 } = ty
155 else {
156 unreachable!("the generated absence check requires Option")
157 };
158 return Err(type_error(
159 format!("expected {expected} absence but found {absence}"),
160 span,
161 ));
162 }
163 "none" => {
164 return Ok(Expr {
165 ty: ty.clone(),
166 ..value
167 });
168 }
169 "unit" | "discard-unit" => {
170 let absent = Expr::new(
171 Node::None {
172 absence: "undefined".to_owned(),
173 },
174 ty.clone(),
175 );
176 return Ok(if optional == "unit" {
177 absent
178 } else {
179 Expr::new(
180 Node::Let {
181 name: "ml_discarded_unit".to_owned(),
182 value: Box::new(value),
183 body: Box::new(absent),
184 },
185 ty.clone(),
186 )
187 });
188 }
189 "some" => {
190 return Ok(Expr::new(
191 Node::Some {
192 value: Box::new(value),
193 },
194 ty.clone(),
195 ));
196 }
197 _ => {}
198 }
199 if language == Language::JavaScript && value.ty == Type::Nat && *ty == Type::Int {
200 return cast_to(value, &INT, Flavor::Exact, span);
201 }
202 if language == Language::JavaScript && value.ty == Type::Int && *ty == Type::Nat {
203 return cast_to(value, &NAT, flavor.unwrap_or(Flavor::Checked), span);
204 }
205 Err(type_error(
206 format!("expected {} but found {}", ty.key(), value.ty.key()),
207 span,
208 ))
209}
210
211fn cast_to(arg: Expr, to: &Type, flavor: Flavor, span: Option<Span>) -> Result<Expr> {
212 if arg.ty.same(to) {
213 return Ok(arg);
214 }
215 let from = arg.ty.clone();
216 let cast = |arg: Expr, flavor: Flavor| {
217 Expr::new(
218 Node::Cast {
219 arg: Box::new(arg),
220 from: from.clone(),
221 to: to.clone(),
222 flavor,
223 message: None,
224 order: None,
225 },
226 to.clone(),
227 )
228 };
229 match (&from, to) {
230 (Type::Nat, Type::Int) => Ok(cast(arg, Flavor::Exact)),
231 (Type::Int, Type::Nat) => {
232 if !matches!(flavor, Flavor::Checked | Flavor::Clamp) {
233 return Err(type_error(
234 "int to nat conversion needs checked or clamp semantics",
235 span,
236 ));
237 }
238 Ok(cast(arg, flavor))
239 }
240 (
241 Type::Fixed {
242 bits: from_bits,
243 signed: from_signed,
244 },
245 Type::Fixed { bits, signed },
246 ) => {
247 let (source_min, source_max) = fixed_bounds(*from_bits, *from_signed);
248 let (target_min, target_max) = fixed_bounds(*bits, *signed);
249 if source_min >= target_min && source_max <= target_max {
250 return Ok(cast(arg, Flavor::Exact));
251 }
252 Err(unsupported(
253 "narrowing integer cast",
254 &format!(
255 "{} as {} wraps in Rust and has no portable encoding yet",
256 from.key(),
257 to.key()
258 ),
259 span,
260 ))
261 }
262 _ => Err(type_error(
263 format!("cannot convert {} to {}", from.key(), to.key()),
264 span,
265 )),
266 }
267}
268
269#[derive(Clone, Debug)]
271enum Entry {
272 Decl(String),
273 Ctor {
274 data: String,
275 name: String,
276 },
277 External(String),
279}
280
281#[derive(Default)]
282struct Scope {
283 path: Vec<String>,
284 names: HashMap<String, Entry>,
285 modules: HashMap<String, String>,
287}
288
289#[derive(Clone, Debug)]
291struct Fact {
292 ctor: String,
293 binds: Vec<String>,
294}
295
296#[derive(Clone, Debug, Default)]
297struct Env {
298 vars: HashMap<String, Type>,
299 known: HashMap<String, Fact>,
300 immutable_products: HashMap<String, bool>,
301}
302
303impl Env {
304 fn has(&self, name: &str) -> bool {
305 self.vars.contains_key(name)
306 }
307
308 fn bind_local(&mut self, name: &str, ty: Type) {
310 self.vars.insert(name.to_owned(), ty);
311 self.immutable_products.remove(name);
312 self.known.retain(|variable, fact| {
313 variable != name && !fact.binds.iter().any(|bind| bind == name)
314 });
315 }
316
317 fn local<'a>(&self, expr: &'a SExpr) -> Option<&'a str> {
319 expr.simple_name().filter(|name| self.has(name))
320 }
321}
322
323#[derive(Clone, Debug)]
324struct Column {
325 name: String,
326 ty: Type,
327}
328
329const NAT_PATTERN_UNFOLD: i128 = 16;
331
332#[derive(Clone, Debug)]
334enum NPat {
335 Surface(SPattern),
336 Wild,
337 Bind(String),
338 Nat { succ: bool, args: Vec<Self> },
339 Data { ctor: String, args: Vec<Self> },
340 Lit { value: Box<SExpr>, key: String },
341}
342
343impl NPat {
344 const fn irrefutable(&self) -> bool {
345 matches!(self, Self::Wild | Self::Bind(_))
346 }
347
348 fn ctor(&self) -> Option<&str> {
349 match self {
350 Self::Nat { succ, .. } => Some(if *succ { "succ" } else { "zero" }),
351 Self::Data { ctor, .. } => Some(ctor),
352 _ => None,
353 }
354 }
355
356 fn args(&self) -> &[Self] {
357 match self {
358 Self::Nat { args, .. } | Self::Data { args, .. } => args,
359 _ => &[],
360 }
361 }
362
363 fn nat_value(&self) -> Option<Decimal> {
365 let Self::Lit { value, .. } = self else {
366 return None;
367 };
368 let SNode::Num { value, .. } = &value.node else {
369 return None;
370 };
371 Decimal::parse(value)
372 }
373
374 fn lit_key(&self) -> Option<&str> {
375 match self {
376 Self::Lit { key, .. } => Some(key),
377 _ => None,
378 }
379 }
380}
381
382#[derive(Clone, Debug)]
383struct Row {
384 patterns: Vec<NPat>,
385 body: SExpr,
386 binds: Vec<(String, String)>,
387}
388
389const fn comparison(op: BinaryOp) -> bool {
390 matches!(
391 op,
392 BinaryOp::Eq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge
393 )
394}
395
396#[allow(clippy::too_many_arguments)]
397const fn binary_node(
398 op: BinaryOp,
399 left: Box<Expr>,
400 right: Box<Expr>,
401 domain: Option<Type>,
402 semantics: Option<Semantics>,
403 rounding: Option<Rounding>,
404 by_zero: Option<ByZero>,
405) -> Node {
406 Node::Binary {
407 op,
408 left,
409 right,
410 domain,
411 semantics,
412 rounding,
413 by_zero,
414 }
415}
416
417fn plain_binary(op: BinaryOp, left: Expr, right: Expr, ty: Type) -> Expr {
418 Expr::new(
419 binary_node(op, Box::new(left), Box::new(right), None, None, None, None),
420 ty,
421 )
422}
423
424fn text_lit(ty: Type, value: impl Into<String>) -> Expr {
425 Expr::lit(ty, LitValue::Text(value.into()))
426}
427
428fn negate_number(text: &str) -> String {
430 if text == "NaN" {
431 return text.to_owned();
432 }
433 text.strip_prefix('-')
434 .map_or_else(|| format!("-{text}"), str::to_owned)
435}
436
437fn surface_let(name: &str, value: &str, body: SExpr, span: Option<Span>) -> SExpr {
438 SExpr::new(
439 SNode::Let {
440 name: name.to_owned(),
441 ty: None,
442 value: Box::new(SExpr::name(value)),
443 body: Box::new(body),
444 },
445 span,
446 )
447}
448
449struct Checker {
450 language: Language,
451 reference_semantics: bool,
452 order: Vec<String>,
454 decls: HashMap<String, Decl>,
455 signatures: HashSet<String>,
457 fresh: usize,
458 modules: HashMap<String, Scope>,
459 externals: Vec<External>,
461}
462
463impl Checker {
464 fn new(language: Language, externals: Vec<External>) -> Self {
465 let mut modules = HashMap::new();
466 modules.insert(String::new(), Scope::default());
467 Self {
468 language,
469 reference_semantics: false,
470 order: Vec::new(),
471 decls: HashMap::new(),
472 signatures: HashSet::new(),
473 fresh: 0,
474 modules,
475 externals,
476 }
477 }
478
479 fn program(mut self, surface: &SProgram) -> Result<Program> {
480 self.reference_semantics =
481 super::surface_raw_metadata_rules::select_surface_reference_semantics(
482 surface
483 .reference_semantics
484 .as_ref()
485 .and_then(super::surface::SurfaceRawMetadata::as_boolean)
486 .unwrap_or(false),
487 false,
488 false,
489 );
490 self.declare(&surface.items, &[])?;
491 let items = self.check_items(&surface.items)?;
492 let main = match &surface.main {
493 Some(main) => Some(self.check_main(main)?),
494 None => None,
495 };
496 for name in &self.order {
497 if let Some(Decl::Fn(entry)) = self.decls.get_mut(name) {
498 entry.body = reuse_successors(&entry.body, &HashMap::new());
499 }
500 }
501 let mut declarations: Vec<Decl> = self
502 .order
503 .iter()
504 .filter_map(|name| self.decls.remove(name))
505 .collect();
506 analyse_recursion(&mut declarations);
507 let mut program = Program {
508 reference_semantics: self.reference_semantics,
509 utf16_strings: None,
510 schema_version: 1,
511 source_language: self.language,
512 items,
513 main,
514 declarations,
515 output_threaded: false,
516 aborts_threaded: false,
517 imports: surface.imports.clone(),
518 externals: self.externals,
519 source_pure_unit_calls: surface.source_pure_unit_calls.clone(),
520 source_runtime_shell: surface.source_runtime_shell.clone(),
521 };
522 super::source_unit_clone_derivations::validate_source_unit_clone_derivations(&program)?;
523 super::source_primitive_owners::validate_source_primitive_owners(&program)?;
524 super::source_empty_options::validate_source_empty_options(&program)?;
525 super::source_type_namespaces::validate_source_type_namespaces(&program)?;
526 super::source_pure_unit_calls::validate_source_pure_unit_calls(&program)?;
527 super::owned_local_state::validate_owned_local_state(&program)?;
528 super::source_const_functions::validate_const_functions(&program)?;
529 if let Some(source) = &surface.source_runtime_shell {
530 super::runtime_shell::capture_program(&mut program, source)?;
531 }
532 super::runtime_shell::validate_program(&program)?;
533 Ok(program)
534 }
535
536 fn scope_mut(&mut self, path: &[String]) -> &mut Scope {
537 self.modules
538 .get_mut(&path.join("."))
539 .unwrap_or_else(|| unreachable!("module {} is declared", path.join(".")))
540 }
541}
542
543struct ProofScope<'a> {
545 checker: &'a Checker,
546 path: &'a [String],
547 span: Option<Span>,
548}
549
550impl ProofContext for ProofScope<'_> {
551 fn lookup(&self, name: &str) -> Result<Option<ProofName>> {
552 let segments: Vec<String> = name.split('.').map(str::to_owned).collect();
553 Ok(
554 match self.checker.lookup(&segments, self.path, self.span)? {
555 None => None,
556 Some(Entry::Ctor { .. } | Entry::External(_)) => Some(ProofName::Other),
557 Some(Entry::Decl(full_name)) => Some(match self.checker.decls.get(&full_name) {
558 Some(Decl::Fn(_)) => ProofName::Function(full_name),
559 Some(Decl::Theorem(_)) => ProofName::Theorem(full_name),
560 _ => ProofName::Other,
561 }),
562 },
563 )
564 }
565
566 fn ctors(&self, data: &str) -> Vec<Ctor> {
567 self.checker
568 .data_decl(data)
569 .map(|decl| decl.ctors.clone())
570 .unwrap_or_default()
571 }
572}
573
574fn full(path: &[String], name: &str) -> String {
575 let mut parts = path.to_vec();
576 parts.push(name.to_owned());
577 parts.join(".")
578}
579
580fn flatten<'a>(items: &'a [SItem], path: &[String], out: &mut Vec<(&'a SItem, Vec<String>)>) {
581 for item in items {
582 if let SItem::Module(module) = item {
583 let mut inner = path.to_vec();
584 inner.push(module.name.clone());
585 flatten(&module.items, &inner, out);
586 } else {
587 out.push((item, path.to_vec()));
588 }
589 }
590}
591
592fn build_items(items: &[SItem], path: &[String]) -> Vec<Item> {
593 items
594 .iter()
595 .map(|item| match item {
596 SItem::Module(module) => {
597 let mut inner = path.to_vec();
598 inner.push(module.name.clone());
599 Item::Module {
600 name: module.name.clone(),
601 full_name: inner.join("."),
602 items: build_items(&module.items, &inner),
603 span: module.span,
604 }
605 }
606 other => Item::Decl {
607 full_name: full(path, other.name()),
608 },
609 })
610 .collect()
611}
612
613const fn op_name(op: BinaryOp) -> &'static str {
614 match op {
615 BinaryOp::Add => "add",
616 BinaryOp::Sub => "sub",
617 BinaryOp::Mul => "mul",
618 BinaryOp::Div => "div",
619 BinaryOp::Rem => "rem",
620 BinaryOp::Eq => "eq",
621 BinaryOp::Ne => "ne",
622 BinaryOp::Lt => "lt",
623 BinaryOp::Le => "le",
624 BinaryOp::Gt => "gt",
625 BinaryOp::Ge => "ge",
626 BinaryOp::And => "and",
627 BinaryOp::Or => "or",
628 BinaryOp::Concat => "concat",
629 BinaryOp::Plus => "plus",
630 }
631}
632
633fn arithmetic_semantics(
634 language: Language,
635 op: BinaryOp,
636 ty: &Type,
637 rounding: Option<Rounding>,
638) -> (Semantics, Option<Rounding>, Option<ByZero>) {
639 if ty.is_float() {
642 return (Semantics::Ieee, None, None);
643 }
644 let division = matches!(op, BinaryOp::Div | BinaryOp::Rem);
645 if matches!(ty, Type::Fixed { .. }) {
646 return if division {
649 (
650 Semantics::Checked,
651 Some(rounding.unwrap_or(Rounding::Trunc)),
652 Some(ByZero::Abort),
653 )
654 } else {
655 (Semantics::Checked, None, None)
656 };
657 }
658 if op == BinaryOp::Sub {
659 let semantics = if *ty == Type::Nat {
660 Semantics::Truncated
661 } else {
662 Semantics::Exact
663 };
664 return (semantics, None, None);
665 }
666 if !division {
667 return (Semantics::Exact, None, None);
668 }
669 if language == Language::JavaScript {
670 return (Semantics::Exact, Some(Rounding::Trunc), Some(ByZero::Abort));
671 }
672 if *ty == Type::Nat {
674 return (Semantics::Exact, Some(Rounding::Trunc), Some(ByZero::Total));
675 }
676 let default = if language == Language::Lean {
677 Rounding::Euclid
678 } else {
679 Rounding::Floor
680 };
681 (
682 Semantics::Exact,
683 Some(rounding.unwrap_or(default)),
684 Some(ByZero::Total),
685 )
686}