egglog/
typechecking.rs

1use std::hash::Hasher;
2
3use crate::Context;
4use crate::proofs::proof_container_rebuild::register_container_rebuild_from_spec;
5use crate::{
6    core::{CoreActionContext, GenericActionsExt, ResolvedCall},
7    *,
8};
9use ast::{
10    MappedExprExt, ResolvedAction, ResolvedExpr, ResolvedFact, ResolvedRule, ResolvedVar, Rule,
11    RuleEvalMode,
12};
13use core_relations::ExternalFunction;
14use egglog_ast::generic_ast::GenericAction;
15use egglog_bridge::ActionRegistry;
16use enum_map::EnumMap;
17use std::sync::{Arc, RwLock};
18
19// `ExternalFunction` wrapper for `PurePrim`. Holds the primitive
20// directly so the dispatch chain `external_funcs[id].invoke(...)` →
21// `T::apply(...)` is just one vtable hop plus a direct call — no
22// closure indirection that defeats inlining.
23#[derive(Clone)]
24struct PurePrimWrapper<T> {
25    prim: T,
26    /// The call-site [`Context`] this wrapper stamps onto the
27    /// `PureState` before dispatching. `register_per_context` commits
28    /// one wrapper per valid `Context` for the trait, so the
29    /// typechecker's pick at each call site is encoded directly here.
30    ctx: Context,
31}
32
33impl<T: PurePrim + Clone> ExternalFunction for PurePrimWrapper<T> {
34    fn invoke(&self, exec_state: &mut ExecutionState, args: &[Value]) -> Option<Value> {
35        self.prim.apply(PureState::wrap(exec_state, self.ctx), args)
36    }
37}
38
39// `ExternalFunction` wrapper for primitives that need the
40// `ActionRegistry` (`ReadPrim`, `WritePrim`, `FullPrim`). One generic
41// over the `Wrap` strategy that knows how to construct the right
42// state type and dispatch to the primitive's `apply`.
43#[derive(Clone)]
44struct RegistryPrimWrapper<T, S> {
45    prim: T,
46    registry: Arc<RwLock<ActionRegistry>>,
47    /// Stamped onto the state wrapper.
48    ctx: Context,
49    _wrap: std::marker::PhantomData<fn() -> S>,
50}
51
52trait RegistryWrap<T>: Clone + Send + Sync {
53    fn invoke(
54        prim: &T,
55        exec_state: &mut ExecutionState,
56        ctx: Context,
57        args: &[Value],
58        registry: &ActionRegistry,
59    ) -> Option<Value>;
60}
61
62#[derive(Clone)]
63struct WrapRead;
64impl<T: ReadPrim> RegistryWrap<T> for WrapRead {
65    #[inline]
66    fn invoke(
67        prim: &T,
68        exec_state: &mut ExecutionState,
69        ctx: Context,
70        args: &[Value],
71        registry: &ActionRegistry,
72    ) -> Option<Value> {
73        prim.apply(ReadState::wrap(exec_state, registry, ctx), args)
74    }
75}
76#[derive(Clone)]
77struct WrapWrite;
78impl<T: WritePrim> RegistryWrap<T> for WrapWrite {
79    #[inline]
80    fn invoke(
81        prim: &T,
82        exec_state: &mut ExecutionState,
83        ctx: Context,
84        args: &[Value],
85        registry: &ActionRegistry,
86    ) -> Option<Value> {
87        prim.apply(WriteState::wrap(exec_state, registry, ctx), args)
88    }
89}
90#[derive(Clone)]
91struct WrapFull;
92impl<T: FullPrim> RegistryWrap<T> for WrapFull {
93    #[inline]
94    fn invoke(
95        prim: &T,
96        exec_state: &mut ExecutionState,
97        ctx: Context,
98        args: &[Value],
99        registry: &ActionRegistry,
100    ) -> Option<Value> {
101        prim.apply(FullState::wrap(exec_state, registry, ctx), args)
102    }
103}
104
105impl<T: Clone + Send + Sync + 'static, S: RegistryWrap<T> + 'static> ExternalFunction
106    for RegistryPrimWrapper<T, S>
107{
108    fn invoke(&self, exec_state: &mut ExecutionState, args: &[Value]) -> Option<Value> {
109        let registry = self.registry.read().unwrap();
110        S::invoke(&self.prim, exec_state, self.ctx, args, &registry)
111    }
112}
113
114#[derive(Clone, Debug)]
115pub struct FuncType {
116    pub name: String,
117    pub subtype: FunctionSubtype,
118    pub input: Vec<ArcSort>,
119    pub output: ArcSort,
120}
121
122impl PartialEq for FuncType {
123    fn eq(&self, other: &Self) -> bool {
124        if self.name == other.name
125            && self.subtype == other.subtype
126            && self.output.name() == other.output.name()
127        {
128            if self.input.len() != other.input.len() {
129                return false;
130            }
131            for (a, b) in self.input.iter().zip(other.input.iter()) {
132                if a.name() != b.name() {
133                    return false;
134                }
135            }
136            true
137        } else {
138            false
139        }
140    }
141}
142
143impl Eq for FuncType {}
144
145impl Hash for FuncType {
146    fn hash<H: Hasher>(&self, state: &mut H) {
147        self.name.hash(state);
148        self.subtype.hash(state);
149        self.output.name().hash(state);
150        for inp in &self.input {
151            inp.name().hash(state);
152        }
153    }
154}
155/// Validators take a termdag and arguments (as TermIds) and return
156/// a newly computed TermId if the primitive application is valid,
157/// or None if it is invalid.
158pub type PrimitiveValidator = Arc<dyn Fn(&mut TermDag, &[TermId]) -> Option<TermId> + Send + Sync>;
159
160#[derive(Clone)]
161pub struct PrimitiveWithId {
162    pub(crate) primitive: Arc<dyn Primitive>,
163    pub(crate) validator: Option<PrimitiveValidator>,
164    /// Runtime entrypoints for the contexts this primitive is valid in.
165    /// The primitive definition is stored once, while each context keeps
166    /// its own backend id so higher-order dispatch can still recover the
167    /// application context at runtime.
168    pub(crate) context_ids: EnumMap<Context, Option<ExternalFunctionId>>,
169}
170
171impl PrimitiveWithId {
172    /// Takes the full signature of a primitive (both input and output types).
173    /// Returns whether the primitive is compatible with this signature.
174    pub fn accept(&self, tys: &[Arc<dyn Sort>], typeinfo: &TypeInfo) -> bool {
175        let mut constraints = vec![];
176        let lits: Vec<_> = (0..tys.len())
177            .map(|i| AtomTerm::Literal(Span::Panic, Literal::Int(i as i64)))
178            .collect();
179        for (lit, ty) in lits.iter().zip(tys.iter()) {
180            constraints.push(constraint::assign(lit.clone(), ty.clone()))
181        }
182        constraints.extend(
183            self.primitive
184                .get_type_constraints(&Span::Panic)
185                .get(&lits, typeinfo),
186        );
187        let problem = Problem {
188            constraints,
189            range: HashSet::default(),
190        };
191        problem.solve(|sort| sort.name()).is_ok()
192    }
193
194    /// Returns whether this primitive has a runtime entrypoint for `context`.
195    pub fn is_valid_in_context(&self, context: Context) -> bool {
196        self.context_ids[context].is_some()
197    }
198}
199
200impl Debug for PrimitiveWithId {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        write!(f, "Prim({})", self.primitive.name())
203    }
204}
205
206/// Stores resolved typechecking information.
207#[derive(Clone, Default)]
208pub struct TypeInfo {
209    mksorts: HashMap<String, MkSort>,
210    // TODO(yz): I want to get rid of this as now we have user-defined primitives and constraint based type checking
211    reserved_primitives: HashSet<&'static str>,
212    pub(crate) sorts: HashMap<String, Arc<dyn Sort>>,
213    primitives: HashMap<String, Vec<PrimitiveWithId>>,
214    func_types: HashMap<String, Arc<FuncType>>,
215    pub(crate) global_sorts: HashMap<String, ArcSort>,
216    /// Sorts that do not allow union (e.g., from `:no-union` sorts or relations).
217    pub(crate) non_unionable_sorts: HashSet<String>,
218    /// Function declarations hidden from user-facing table listings.
219    pub(crate) hidden_functions: HashSet<String>,
220}
221
222// These methods need to be on the `EGraph` in order to
223// register sorts and primitives with the backend.
224impl EGraph {
225    /// Add a user-defined sort to the e-graph.
226    ///
227    /// Also look at [`prelude::add_base_sort`] for a convenience method for adding user-defined sorts
228    pub fn add_sort<S: Sort + 'static>(&mut self, sort: S, span: Span) -> Result<(), TypeError> {
229        self.add_arcsort(Arc::new(sort), span)
230    }
231
232    /// Declare a sort. This corresponds to the `sort` keyword in egglog.
233    /// It can either declares a new [`EqSort`] if `presort_and_args` is not provided,
234    /// or an instantiation of a presort (e.g., containers like `Vec`).
235    pub fn declare_sort(
236        &mut self,
237        name: impl Into<String>,
238        presort_and_args: &Option<(String, Vec<Expr>)>,
239        span: Span,
240    ) -> Result<(), TypeError> {
241        let name = name.into();
242        if self.type_info.func_types.contains_key(&name) {
243            return Err(TypeError::FunctionAlreadyBound(name, span));
244        }
245
246        let sort = match presort_and_args {
247            None => Arc::new(EqSort { name }),
248            Some((presort, args)) => {
249                if let Some(mksort) = self.type_info.mksorts.get(presort) {
250                    mksort(&mut self.type_info, name, args, span.clone())?
251                } else {
252                    return Err(TypeError::PresortNotFound(presort.clone(), span));
253                }
254            }
255        };
256
257        self.add_arcsort(sort, span)
258    }
259
260    /// Add a user-defined sort to the e-graph.
261    pub fn add_arcsort(&mut self, sort: ArcSort, span: Span) -> Result<(), TypeError> {
262        sort.register_type(&mut self.backend);
263
264        let name = sort.name();
265        match self.type_info.sorts.entry(name.to_owned()) {
266            HEntry::Occupied(_) => Err(TypeError::SortAlreadyBound(name.to_owned(), span)),
267            HEntry::Vacant(e) => {
268                e.insert(sort.clone());
269                sort.register_primitives(self);
270                Ok(())
271            }
272        }
273    }
274
275    /// Register a [`PurePrim`]. Pass `None` for the validator if not
276    /// using the proof checker.
277    ///
278    /// Pick the trait whose state wrapper matches the body's needs:
279    /// [`PurePrim`] for pure ops, [`WritePrim`] for writes,
280    /// [`ReadPrim`] for table reads, [`FullPrim`] for both. The Rust
281    /// type checker enforces the body only uses methods the chosen
282    /// state allows.
283    pub fn add_pure_primitive<T>(&mut self, x: T, validator: Option<PrimitiveValidator>)
284    where
285        T: PurePrim + Clone,
286    {
287        self.register_per_context(x, validator, PureState::valid_contexts(), |x, ctx| {
288            Box::new(PurePrimWrapper { prim: x, ctx })
289        });
290    }
291
292    /// Register a [`WritePrim`]. Pass `None` for the validator if not
293    /// using the proof checker.
294    pub fn add_write_primitive<T>(&mut self, x: T, validator: Option<PrimitiveValidator>)
295    where
296        T: WritePrim + Clone,
297    {
298        self.register_registry_primitive::<T, WrapWrite>(
299            x,
300            validator,
301            WriteState::valid_contexts(),
302        );
303    }
304
305    /// Register a [`ReadPrim`]. Pass `None` for the validator if not
306    /// using the proof checker.
307    pub fn add_read_primitive<T>(&mut self, x: T, validator: Option<PrimitiveValidator>)
308    where
309        T: ReadPrim + Clone,
310    {
311        self.register_registry_primitive::<T, WrapRead>(x, validator, ReadState::valid_contexts());
312    }
313
314    /// Register a [`FullPrim`]. Pass `None` for the validator if not
315    /// using the proof checker.
316    pub fn add_full_primitive<T>(&mut self, x: T, validator: Option<PrimitiveValidator>)
317    where
318        T: FullPrim + Clone,
319    {
320        self.register_registry_primitive::<T, WrapFull>(x, validator, FullState::valid_contexts());
321    }
322
323    fn register_registry_primitive<T, S>(
324        &mut self,
325        x: T,
326        validator: Option<PrimitiveValidator>,
327        valid_ctxs: &[Context],
328    ) where
329        T: Primitive + Clone,
330        S: RegistryWrap<T> + 'static,
331    {
332        let registry = self.backend.action_registry().clone();
333        self.register_per_context(x, validator, valid_ctxs, move |x, ctx| {
334            Box::new(RegistryPrimWrapper::<T, S> {
335                prim: x,
336                registry: registry.clone(),
337                ctx,
338                _wrap: std::marker::PhantomData,
339            })
340        });
341    }
342
343    /// Shared registration engine. Stores one primitive definition, plus
344    /// one runtime id per valid [`Context`]. Each wrapper carries its
345    /// specific context stamped onto the state wrapper at invoke time.
346    ///
347    /// The typechecker filters by the context-id mask at each call site;
348    /// an `unstable-fn` value built around the primitive bakes *all*
349    /// signature-matching context ids, and `FunctionContainer::apply`
350    /// picks the one whose context matches the application ctx — so
351    /// values flow freely across contexts.
352    fn register_per_context<T, F>(
353        &mut self,
354        x: T,
355        validator: Option<PrimitiveValidator>,
356        valid_ctxs: &[Context],
357        mut build_wrapper: F,
358    ) where
359        T: Primitive + Clone,
360        F: FnMut(T, Context) -> Box<dyn ExternalFunction>,
361    {
362        let primitive: Arc<dyn Primitive> = Arc::new(x.clone());
363        let name = primitive.name().to_owned();
364        let context_ids = EnumMap::from_fn(|ctx| {
365            valid_ctxs.contains(&ctx).then(|| {
366                self.backend
367                    .register_external_func(build_wrapper(x.clone(), ctx))
368            })
369        });
370        self.type_info
371            .primitives
372            .entry(name)
373            .or_default()
374            .push(PrimitiveWithId {
375                primitive,
376                validator,
377                context_ids,
378            });
379    }
380}
381
382impl EGraph {
383    pub(crate) fn typecheck_program(
384        &mut self,
385        program: &Vec<NCommand>,
386    ) -> Result<Vec<ResolvedNCommand>, TypeError> {
387        let mut result = vec![];
388        for command in program {
389            result.push(self.typecheck_command(command)?);
390        }
391        Ok(result)
392    }
393
394    fn typecheck_command(&mut self, command: &NCommand) -> Result<ResolvedNCommand, TypeError> {
395        let symbol_gen = &mut self.parser.symbol_gen;
396
397        let command: ResolvedNCommand = match command {
398            NCommand::Function(fdecl) => {
399                let resolved = self.type_info.typecheck_function(symbol_gen, fdecl)?;
400                // If this is a let binding, add it to global_sorts
401                // This preserves bahavior for lets after desugaring
402                if resolved.internal_let {
403                    let output_sort = self.type_info.sorts.get(&fdecl.schema.output).unwrap();
404                    self.type_info
405                        .global_sorts
406                        .insert(fdecl.name.clone(), output_sort.clone());
407                }
408                ResolvedNCommand::Function(resolved)
409            }
410            NCommand::NormRule { rule } => ResolvedNCommand::NormRule {
411                rule: self
412                    .type_info
413                    .typecheck_rule(symbol_gen, rule, self.seminaive)?,
414            },
415            NCommand::Sort {
416                span,
417                name,
418                presort_and_args,
419                uf,
420                proof_func,
421                container_rebuild,
422                proof_constructors,
423                unionable,
424            } => {
425                // Note this is bad since typechecking should be pure and idempotent
426                // Otherwise typechecking the same program twice will fail
427                self.declare_sort(name.clone(), presort_and_args, span.clone())?;
428                // Mark as non-unionable if the sort declaration says so
429                if !unionable {
430                    self.type_info.non_unionable_sorts.insert(name.clone());
431                }
432                // Record this sort's UF / proof tables in proof_state (as
433                // run_command also does) so the container rebuild registration
434                // below can recover them — including this container's own proof
435                // table, which has not run yet.
436                if let Some((uf_ctor, uf_index)) = uf {
437                    self.proof_state
438                        .uf_parent
439                        .insert(name.clone(), uf_ctor.clone());
440                    if let Some(uf_index) = uf_index {
441                        self.proof_state
442                            .uf_function
443                            .insert(name.clone(), uf_index.clone());
444                    }
445                }
446                if let Some(pf) = proof_func {
447                    self.proof_state
448                        .proof_func_parent
449                        .insert(name.clone(), pf.clone());
450                }
451                // The Proof sort records the global proof constructors; restore
452                // them into proof_state so container rebuild can recover them
453                // (the `Proof` datatype name is this sort's own name).
454                if let Some(pc) = proof_constructors {
455                    let names = &mut self.proof_state.proof_names;
456                    names.proof_datatype = name.clone();
457                    names.congr_constructor = pc.congr.clone();
458                    names.eq_trans_constructor = pc.trans.clone();
459                    names.eq_sym_constructor = pc.sym.clone();
460                    names.container_normalize_constructor = pc.normalize.clone();
461                }
462                // A container sort under the term/proof encoding carries a spec
463                // for its rebuild primitives; register them here so they are
464                // available both during encoding and when the desugared program
465                // is re-parsed.
466                if let Some(spec) = container_rebuild {
467                    register_container_rebuild_from_spec(self, name, spec);
468                }
469                ResolvedNCommand::Sort {
470                    span: span.clone(),
471                    name: name.clone(),
472                    presort_and_args: presort_and_args.clone(),
473                    uf: uf.clone(),
474                    proof_func: proof_func.clone(),
475                    container_rebuild: container_rebuild.clone(),
476                    proof_constructors: proof_constructors.clone(),
477                    unionable: *unionable,
478                }
479            }
480            NCommand::CoreAction(action @ Action::Let(span, var, _)) => {
481                let action = self.type_info.typecheck_standalone_action(
482                    symbol_gen,
483                    action,
484                    &Default::default(),
485                    Context::Full,
486                )?;
487                self.ensure_global_name_prefix(span, var)?;
488                let ResolvedAction::Let(_, resolved_var, _) = &action else {
489                    unreachable!("typechecking an Action::Let should return ResolvedAction::Let")
490                };
491                self.type_info
492                    .global_sorts
493                    .insert(resolved_var.name.clone(), resolved_var.sort.clone());
494                ResolvedNCommand::CoreAction(action)
495            }
496            NCommand::CoreAction(action) => {
497                ResolvedNCommand::CoreAction(self.type_info.typecheck_standalone_action(
498                    symbol_gen,
499                    action,
500                    &Default::default(),
501                    Context::Full,
502                )?)
503            }
504            NCommand::Extract(span, expr, variants) => {
505                let res_expr = self.type_info.typecheck_standalone_expr(
506                    symbol_gen,
507                    expr,
508                    &Default::default(),
509                    Context::Full,
510                )?;
511
512                let res_variants = self.type_info.typecheck_standalone_expr(
513                    symbol_gen,
514                    variants,
515                    &Default::default(),
516                    Context::Full,
517                )?;
518                if res_variants.output_type().name() != I64Sort.name() {
519                    return Err(TypeError::Mismatch {
520                        expr: variants.clone(),
521                        expected: I64Sort.to_arcsort(),
522                        actual: res_variants.output_type(),
523                    });
524                }
525
526                ResolvedNCommand::Extract(span.clone(), res_expr, res_variants)
527            }
528            NCommand::Check(span, facts) => ResolvedNCommand::Check(
529                span.clone(),
530                self.type_info.typecheck_facts(symbol_gen, facts)?,
531            ),
532            NCommand::Fail(span, cmd) => {
533                ResolvedNCommand::Fail(span.clone(), Box::new(self.typecheck_command(cmd)?))
534            }
535            NCommand::RunSchedule(schedule) => ResolvedNCommand::RunSchedule(
536                self.type_info.typecheck_schedule(symbol_gen, schedule)?,
537            ),
538            NCommand::Pop(span, n) => ResolvedNCommand::Pop(span.clone(), *n),
539            NCommand::Push(n) => ResolvedNCommand::Push(*n),
540            NCommand::AddRuleset(span, ruleset) => {
541                ResolvedNCommand::AddRuleset(span.clone(), ruleset.clone())
542            }
543            NCommand::UnstableCombinedRuleset(span, name, sub_rulesets) => {
544                ResolvedNCommand::UnstableCombinedRuleset(
545                    span.clone(),
546                    name.clone(),
547                    sub_rulesets.clone(),
548                )
549            }
550            NCommand::PrintOverallStatistics(span, file) => {
551                ResolvedNCommand::PrintOverallStatistics(span.clone(), file.clone())
552            }
553            NCommand::PrintFunction(span, table, size, file, mode) => {
554                ResolvedNCommand::PrintFunction(
555                    span.clone(),
556                    table.clone(),
557                    *size,
558                    file.clone(),
559                    *mode,
560                )
561            }
562            NCommand::PrintSize(span, n) => {
563                // Should probably also resolve the function symbol here
564                ResolvedNCommand::PrintSize(span.clone(), n.clone())
565            }
566            NCommand::ProveExists(span, constructor) => {
567                let func_type = self
568                    .type_info
569                    .get_func_type(constructor)
570                    .ok_or_else(|| TypeError::UnboundFunction(constructor.clone(), span.clone()))?;
571                if func_type.subtype != FunctionSubtype::Constructor {
572                    return Err(TypeError::ProveExistsRequiresConstructor(
573                        constructor.clone(),
574                        span.clone(),
575                    ));
576                }
577                ResolvedNCommand::ProveExists(span.clone(), ResolvedCall::Func(func_type.clone()))
578            }
579            NCommand::Output { span, file, exprs } => {
580                let exprs = exprs
581                    .iter()
582                    .map(|expr| {
583                        self.type_info.typecheck_standalone_expr(
584                            symbol_gen,
585                            expr,
586                            &Default::default(),
587                            Context::Full,
588                        )
589                    })
590                    .collect::<Result<Vec<_>, _>>()?;
591                ResolvedNCommand::Output {
592                    span: span.clone(),
593                    file: file.clone(),
594                    exprs,
595                }
596            }
597            NCommand::Input { span, name, file } => ResolvedNCommand::Input {
598                span: span.clone(),
599                name: name.clone(),
600                file: file.clone(),
601            },
602            NCommand::UserDefined(span, name, exprs) => {
603                ResolvedNCommand::UserDefined(span.clone(), name.clone(), exprs.clone())
604            }
605        };
606        if let ResolvedNCommand::NormRule { rule } = &command {
607            self.warn_for_prefixed_non_globals_in_rule(rule)?;
608        }
609        Ok(command)
610    }
611
612    fn warn_for_prefixed_non_globals_in_var(
613        &mut self,
614        span: &Span,
615        var: &ResolvedVar,
616    ) -> Result<(), TypeError> {
617        if var.is_global_ref {
618            return Ok(());
619        }
620        if var.name.starts_with(crate::GLOBAL_NAME_PREFIX) {
621            self.warn_prefixed_non_globals(span, &var.name)?;
622        }
623        Ok(())
624    }
625
626    fn warn_for_prefixed_non_globals_in_rule(
627        &mut self,
628        rule: &ResolvedRule,
629    ) -> Result<(), TypeError> {
630        let mut res: Result<(), TypeError> = Ok(());
631
632        for fact in &rule.body {
633            fact.visit_vars(&mut |span, var| {
634                if res.is_ok() {
635                    res = self.warn_for_prefixed_non_globals_in_var(span, var);
636                }
637            });
638        }
639
640        rule.head.visit_vars(&mut |span, var| {
641            if res.is_ok() {
642                res = self.warn_for_prefixed_non_globals_in_var(span, var);
643            }
644        });
645        res
646    }
647}
648
649impl TypeInfo {
650    /// Adds a sort constructor to the typechecker's known set of types.
651    pub fn add_presort<S: Presort>(&mut self, span: Span) -> Result<(), TypeError> {
652        let name = S::presort_name();
653        match self.mksorts.entry(name.to_owned()) {
654            HEntry::Occupied(_) => Err(TypeError::SortAlreadyBound(name.to_owned(), span)),
655            HEntry::Vacant(e) => {
656                e.insert(S::make_sort);
657                self.reserved_primitives.extend(S::reserved_primitives());
658                Ok(())
659            }
660        }
661    }
662
663    /// Returns all sorts that satisfy the type and predicate.
664    pub fn get_sorts_by<S: Sort>(&self, pred: impl Fn(&Arc<S>) -> bool) -> Vec<Arc<S>> {
665        let mut results = Vec::new();
666        for sort in self.sorts.values() {
667            let sort = sort.clone().as_arc_any();
668            if let Ok(sort) = Arc::downcast(sort)
669                && pred(&sort)
670            {
671                results.push(sort);
672            }
673        }
674        results
675    }
676
677    /// Returns all sorts based on the type.
678    pub fn get_sorts<S: Sort>(&self) -> Vec<Arc<S>> {
679        self.get_sorts_by(|_| true)
680    }
681
682    /// Returns a sort that satisfies the type and predicate.
683    pub fn get_sort_by<S: Sort>(&self, pred: impl Fn(&Arc<S>) -> bool) -> Arc<S> {
684        let results = self.get_sorts_by(pred);
685        assert_eq!(
686            results.len(),
687            1,
688            "Expected exactly one sort for type {}",
689            std::any::type_name::<S>()
690        );
691        results.into_iter().next().unwrap()
692    }
693
694    /// Returns a sort based on the type.
695    pub fn get_sort<S: Sort>(&self) -> Arc<S> {
696        self.get_sort_by(|_| true)
697    }
698
699    /// Returns all sorts that satisfy the predicate.
700    pub fn get_arcsorts_by(&self, f: impl Fn(&ArcSort) -> bool) -> Vec<ArcSort> {
701        self.sorts.values().filter(|&x| f(x)).cloned().collect()
702    }
703
704    /// Returns a sort based on the predicate.
705    pub fn get_arcsort_by(&self, f: impl Fn(&ArcSort) -> bool) -> ArcSort {
706        let results = self.get_arcsorts_by(f);
707        assert_eq!(
708            results.len(),
709            1,
710            "Expected exactly one sort matching the given predicate"
711        );
712        results.into_iter().next().unwrap()
713    }
714
715    /// Returns the unique sort whose runtime values have Rust type `T`.
716    pub fn get_arcsort_for_value_type<T: 'static>(&self) -> ArcSort {
717        let results = self.get_arcsorts_by(|s| s.value_type() == Some(std::any::TypeId::of::<T>()));
718        assert_eq!(
719            results.len(),
720            1,
721            "Expected exactly one sort for type `{}`",
722            std::any::type_name::<T>()
723        );
724        results.into_iter().next().unwrap()
725    }
726
727    /// Check if a sort allows union operations.
728    /// A sort is unionable if it's an eq_sort and not marked as non-unionable
729    /// (e.g., from `(sort Foo :no-union)` or relation desugaring).
730    pub fn is_sort_unionable(&self, sort: &ArcSort) -> bool {
731        sort.is_eq_sort() && !self.non_unionable_sorts.contains(sort.name())
732    }
733
734    fn function_to_functype(&self, func: &FunctionDecl) -> Result<FuncType, TypeError> {
735        let input = func
736            .schema
737            .input
738            .iter()
739            .map(|name| {
740                if let Some(sort) = self.sorts.get(name) {
741                    Ok(sort.clone())
742                } else {
743                    Err(TypeError::UndefinedSort(name.clone(), func.span.clone()))
744                }
745            })
746            .collect::<Result<Vec<_>, _>>()?;
747        let output = if let Some(sort) = self.sorts.get(&func.schema.output) {
748            Ok(sort.clone())
749        } else {
750            Err(TypeError::UndefinedSort(
751                func.schema.output.clone(),
752                func.span.clone(),
753            ))
754        }?;
755
756        Ok(FuncType {
757            name: func.name.clone(),
758            subtype: func.subtype,
759            input,
760            output: output.clone(),
761        })
762    }
763
764    fn typecheck_function(
765        &mut self,
766        symbol_gen: &mut SymbolGen,
767        fdecl: &FunctionDecl,
768    ) -> Result<ResolvedFunctionDecl, TypeError> {
769        if self.sorts.contains_key(&fdecl.name) {
770            return Err(TypeError::SortAlreadyBound(
771                fdecl.name.clone(),
772                fdecl.span.clone(),
773            ));
774        }
775        if self.is_primitive(&fdecl.name) {
776            return Err(TypeError::PrimitiveAlreadyBound(
777                fdecl.name.clone(),
778                fdecl.span.clone(),
779            ));
780        }
781        // View tables (with term_constructor) must have at least one input (the e-class)
782        if fdecl.term_constructor.is_some() && fdecl.schema.input.is_empty() {
783            return Err(TypeError::TermConstructorNoInputs(
784                fdecl.name.clone(),
785                fdecl.span.clone(),
786            ));
787        }
788        let ftype = self.function_to_functype(fdecl)?;
789        if self
790            .func_types
791            .insert(fdecl.name.clone(), Arc::new(ftype))
792            .is_some()
793        {
794            return Err(TypeError::FunctionAlreadyBound(
795                fdecl.name.clone(),
796                fdecl.span.clone(),
797            ));
798        }
799        let mut bound_vars = IndexMap::default();
800        let output_type = self.sorts.get(&fdecl.schema.output).unwrap();
801        if fdecl.subtype == FunctionSubtype::Constructor && !output_type.is_eq_sort() {
802            return Err(TypeError::ConstructorOutputNotSort(
803                fdecl.name.clone(),
804                fdecl.span.clone(),
805            ));
806        }
807        bound_vars.insert("old", (fdecl.span.clone(), output_type.clone()));
808        bound_vars.insert("new", (fdecl.span.clone(), output_type.clone()));
809
810        Ok(ResolvedFunctionDecl {
811            name: fdecl.name.clone(),
812            subtype: fdecl.subtype,
813            schema: fdecl.schema.clone(),
814            merge: match &fdecl.merge {
815                // Merge expressions run as part of action-side table updates:
816                // writes are allowed, but live DB reads would be untracked by
817                // seminaive rule execution.
818                Some(merge) => Some(self.typecheck_standalone_expr(
819                    symbol_gen,
820                    merge,
821                    &bound_vars,
822                    Context::Write,
823                )?),
824                None => None,
825            },
826            cost: fdecl.cost,
827            unextractable: fdecl.unextractable,
828            internal_hidden: fdecl.internal_hidden,
829            internal_let: fdecl.internal_let,
830            span: fdecl.span.clone(),
831            term_constructor: fdecl.term_constructor.clone(),
832        })
833    }
834
835    fn typecheck_schedule(
836        &self,
837        symbol_gen: &mut SymbolGen,
838        schedule: &Schedule,
839    ) -> Result<ResolvedSchedule, TypeError> {
840        let schedule = match schedule {
841            Schedule::Repeat(span, times, schedule) => ResolvedSchedule::Repeat(
842                span.clone(),
843                *times,
844                Box::new(self.typecheck_schedule(symbol_gen, schedule)?),
845            ),
846            Schedule::Sequence(span, schedules) => {
847                let schedules = schedules
848                    .iter()
849                    .map(|schedule| self.typecheck_schedule(symbol_gen, schedule))
850                    .collect::<Result<Vec<_>, _>>()?;
851                ResolvedSchedule::Sequence(span.clone(), schedules)
852            }
853            Schedule::Saturate(span, schedule) => ResolvedSchedule::Saturate(
854                span.clone(),
855                Box::new(self.typecheck_schedule(symbol_gen, schedule)?),
856            ),
857            Schedule::Run(span, RunConfig { ruleset, until }) => {
858                let until = until
859                    .as_ref()
860                    .map(|facts| self.typecheck_facts(symbol_gen, facts))
861                    .transpose()?;
862                ResolvedSchedule::Run(
863                    span.clone(),
864                    ResolvedRunConfig {
865                        ruleset: ruleset.clone(),
866                        until,
867                    },
868                )
869            }
870        };
871
872        Result::Ok(schedule)
873    }
874
875    fn typecheck_rule(
876        &self,
877        symbol_gen: &mut SymbolGen,
878        rule: &Rule,
879        global_seminaive: bool,
880    ) -> Result<ResolvedRule, TypeError> {
881        let Rule {
882            span,
883            head,
884            body,
885            name,
886            ruleset,
887            eval_mode,
888            no_decomp,
889            include_subsumed,
890        } = rule;
891        // Compile with the permissive Read/Full primitive contexts (so the RHS
892        // can read the database) when the whole EGraph is non-seminaive, or the
893        // rule's own mode requires it (`:naive` / `:unsafe-seminaive`).
894        let read_contexts = !global_seminaive
895            || matches!(
896                eval_mode,
897                RuleEvalMode::Naive | RuleEvalMode::UnsafeSeminaive
898            );
899        let (query_ctx, action_ctx) = if read_contexts {
900            (Context::Read, Context::Full)
901        } else {
902            (Context::Pure, Context::Write)
903        };
904
905        let (query, mapped_query) = Facts::to_query(body, self, symbol_gen);
906        let mut problem = Problem::default();
907        problem.add_query(&query, self, query_ctx)?;
908
909        let mut binding = query.get_vars();
910        // We lower to core actions with `union_to_set_optimization`
911        // later in the pipeline. For typechecking we do not need it.
912        let mut ctx = CoreActionContext::new(self, &mut binding, symbol_gen, false);
913        let (actions, mapped_action) = head.to_core_actions(&mut ctx)?;
914        problem.add_actions(&actions, self, symbol_gen, action_ctx)?;
915
916        let assignment = problem
917            .solve(|sort: &ArcSort| sort.name())
918            .map_err(|e| e.to_type_error())?;
919
920        let body: Vec<ResolvedFact> = assignment.annotate_facts(&mapped_query, self, query_ctx)?;
921        let actions: ResolvedActions =
922            assignment.annotate_actions(&mapped_action, self, action_ctx)?;
923
924        // Function lookups in actions need the `Full` action context; the
925        // `Write` context (`!read_contexts`) can't express them.
926        if !read_contexts {
927            self.check_no_function_lookups_in_actions(&actions)?;
928        }
929
930        Ok(ResolvedRule {
931            span: span.clone(),
932            body,
933            head: actions,
934            name: name.clone(),
935            ruleset: ruleset.clone(),
936            eval_mode: *eval_mode,
937            no_decomp: *no_decomp,
938            include_subsumed: *include_subsumed,
939        })
940    }
941
942    fn check_lookup_expr(&self, expr: &ResolvedExpr) -> Result<(), TypeError> {
943        if let Some(span) = self.expr_has_function_lookup(expr) {
944            return Err(TypeError::LookupInRuleDisallowed(
945                "function".to_string(),
946                span,
947            ));
948        }
949        Ok(())
950    }
951
952    fn check_no_function_lookups_in_actions(
953        &self,
954        actions: &ResolvedActions,
955    ) -> Result<(), TypeError> {
956        for action in actions.iter() {
957            match action {
958                GenericAction::Let(_, _, rhs) => self.check_lookup_expr(rhs)?,
959                GenericAction::Set(_, _, args, rhs) => {
960                    for arg in args.iter() {
961                        self.check_lookup_expr(arg)?;
962                    }
963                    self.check_lookup_expr(rhs)?;
964                }
965                GenericAction::Union(_, lhs, rhs) => {
966                    self.check_lookup_expr(lhs)?;
967                    self.check_lookup_expr(rhs)?;
968                }
969                GenericAction::Change(_, _, _, args) => {
970                    for arg in args.iter() {
971                        self.check_lookup_expr(arg)?;
972                    }
973                }
974                GenericAction::Panic(..) => {}
975                GenericAction::Expr(_, expr) => self.check_lookup_expr(expr)?,
976            }
977        }
978        Ok(())
979    }
980
981    pub fn typecheck_facts(
982        &self,
983        symbol_gen: &mut SymbolGen,
984        facts: &[Fact],
985    ) -> Result<Vec<ResolvedFact>, TypeError> {
986        let (query, mapped_facts) = Facts::to_query(facts, self, symbol_gen);
987        let mut problem = Problem::default();
988        // Top-level query-shaped commands (e.g. `check`) are read-only:
989        // primitives may inspect the database but not write to it.
990        problem.add_query(&query, self, Context::Read)?;
991        let assignment = problem
992            .solve(|sort: &ArcSort| sort.name())
993            .map_err(|e| e.to_type_error())?;
994        let annotated_facts = assignment.annotate_facts(&mapped_facts, self, Context::Read)?;
995        Ok(annotated_facts)
996    }
997
998    // Standalone expressions/actions use action lowering. Top-level commands
999    // pass `Full`; function `:merge` reuses this path with `Write` because
1000    // merge expressions run during table updates.
1001    fn typecheck_standalone_actions(
1002        &self,
1003        symbol_gen: &mut SymbolGen,
1004        actions: &Actions,
1005        binding: &IndexMap<&str, (Span, ArcSort)>,
1006        context: Context,
1007    ) -> Result<ResolvedActions, TypeError> {
1008        let mut binding_set: IndexSet<String> =
1009            binding.keys().copied().map(str::to_string).collect();
1010        // We lower to core actions with `union_to_set_optimization`
1011        // later in the pipeline. For typechecking we do not need it.
1012        let mut ctx = CoreActionContext::new(self, &mut binding_set, symbol_gen, false);
1013        let (actions, mapped_action) = actions.to_core_actions(&mut ctx)?;
1014        let mut problem = Problem::default();
1015
1016        problem.add_actions(&actions, self, symbol_gen, context)?;
1017
1018        // add bindings from the context
1019        for (var, (span, sort)) in binding {
1020            problem.assign_local_var_type(var, span.clone(), sort.clone())?;
1021        }
1022
1023        let assignment = problem
1024            .solve(|sort: &ArcSort| sort.name())
1025            .map_err(|e| e.to_type_error())?;
1026
1027        let annotated_actions = assignment.annotate_actions(&mapped_action, self, context)?;
1028        Ok(annotated_actions)
1029    }
1030
1031    fn typecheck_standalone_expr(
1032        &self,
1033        symbol_gen: &mut SymbolGen,
1034        expr: &Expr,
1035        binding: &IndexMap<&str, (Span, ArcSort)>,
1036        context: Context,
1037    ) -> Result<ResolvedExpr, TypeError> {
1038        let action = Action::Expr(expr.span(), expr.clone());
1039        let typechecked_action =
1040            self.typecheck_standalone_action(symbol_gen, &action, binding, context)?;
1041        match typechecked_action {
1042            ResolvedAction::Expr(_, expr) => Ok(expr),
1043            _ => unreachable!(),
1044        }
1045    }
1046
1047    pub(crate) fn typecheck_expr_with_output(
1048        &self,
1049        symbol_gen: &mut SymbolGen,
1050        expr: &Expr,
1051        binding: &IndexMap<&str, (Span, ArcSort)>,
1052        output_sort: ArcSort,
1053        context: Context,
1054    ) -> Result<ResolvedExpr, TypeError> {
1055        let action = Action::Expr(expr.span(), expr.clone());
1056        let mut binding_set: IndexSet<String> =
1057            binding.keys().copied().map(str::to_string).collect();
1058        let mut ctx = CoreActionContext::new(self, &mut binding_set, symbol_gen, false);
1059        let (actions, mapped_action) = Actions::singleton(action).to_core_actions(&mut ctx)?;
1060        let mut problem = Problem::default();
1061
1062        problem.add_actions(&actions, self, symbol_gen, context)?;
1063
1064        for (var, (span, sort)) in binding {
1065            problem.assign_local_var_type(var, span.clone(), sort.clone())?;
1066        }
1067
1068        let [GenericAction::Expr(_, mapped_expr)] = mapped_action.0.as_slice() else {
1069            unreachable!("typechecking an expression should produce one expression action")
1070        };
1071        let output_atom = mapped_expr.get_corresponding_var_or_lit(self);
1072        problem.add_binding(output_atom, output_sort.clone());
1073
1074        let assignment = problem
1075            .solve(|sort: &ArcSort| sort.name())
1076            .map_err(|e| e.to_type_error())?;
1077
1078        let annotated_actions = assignment.annotate_actions(&mapped_action, self, context)?;
1079        match annotated_actions.0.into_iter().next().unwrap() {
1080            ResolvedAction::Expr(_, resolved_expr) => {
1081                let actual = resolved_expr.output_type();
1082                if actual.name() != output_sort.name() {
1083                    return Err(TypeError::Mismatch {
1084                        expr: expr.clone(),
1085                        expected: output_sort,
1086                        actual,
1087                    });
1088                }
1089                Ok(resolved_expr)
1090            }
1091            _ => unreachable!(),
1092        }
1093    }
1094
1095    fn typecheck_standalone_action(
1096        &self,
1097        symbol_gen: &mut SymbolGen,
1098        action: &Action,
1099        binding: &IndexMap<&str, (Span, ArcSort)>,
1100        context: Context,
1101    ) -> Result<ResolvedAction, TypeError> {
1102        self.typecheck_standalone_actions(
1103            symbol_gen,
1104            &Actions::singleton(action.clone()),
1105            binding,
1106            context,
1107        )
1108        .map(|v| {
1109            assert_eq!(v.len(), 1);
1110            v.0.into_iter().next().unwrap()
1111        })
1112    }
1113
1114    pub fn get_sort_by_name(&self, sym: &str) -> Option<&ArcSort> {
1115        self.sorts.get(sym)
1116    }
1117
1118    pub fn get_prims(&self, sym: &str) -> Option<&[PrimitiveWithId]> {
1119        self.primitives.get(sym).map(Vec::as_slice)
1120    }
1121
1122    pub fn is_primitive(&self, sym: &str) -> bool {
1123        self.primitives.contains_key(sym) || self.reserved_primitives.contains(sym)
1124    }
1125
1126    pub fn primitive_has_validator(&self, id: ExternalFunctionId) -> bool {
1127        self.primitives
1128            .values()
1129            .flat_map(|v| v.iter())
1130            .any(|p| p.context_ids.iter().any(|(_, pid)| *pid == Some(id)) && p.validator.is_some())
1131    }
1132
1133    /// The shared signature declared for `sym`, or `None` if no function with
1134    /// that name is declared. Clone it to keep it past the borrow.
1135    pub fn get_func_type(&self, sym: &str) -> Option<&Arc<FuncType>> {
1136        self.func_types.get(sym)
1137    }
1138
1139    /// Record a signature for a function that did not come through
1140    /// typechecking — desugaring generates some (global bindings, proof
1141    /// tables) directly.
1142    pub(crate) fn declare_func_type(&mut self, func_type: Arc<FuncType>) {
1143        self.func_types.insert(func_type.name.clone(), func_type);
1144    }
1145
1146    pub fn is_constructor(&self, sym: &str) -> bool {
1147        self.get_func_type(sym)
1148            .is_some_and(|f| f.subtype == FunctionSubtype::Constructor)
1149    }
1150
1151    pub fn get_global_sort(&self, sym: &str) -> Option<&ArcSort> {
1152        self.global_sorts.get(sym)
1153    }
1154
1155    pub fn is_global(&self, sym: &str) -> bool {
1156        self.global_sorts.contains_key(sym)
1157    }
1158
1159    /// Check if an expression contains non-global function lookups (FunctionSubtype::Custom calls).
1160    /// Global function calls are allowed since they get desugared to constructors.
1161    /// Returns Some(span) if a lookup is found, None otherwise.
1162    pub fn expr_has_function_lookup(&self, expr: &ResolvedExpr) -> Option<Span> {
1163        use ast::GenericExpr;
1164
1165        expr.find(&mut |e| {
1166            if let GenericExpr::Call(span, ResolvedCall::Func(func_type), _) = e
1167                && func_type.subtype == FunctionSubtype::Custom
1168                && !self.is_global(&func_type.name)
1169            {
1170                return Some(span.clone());
1171            }
1172            None
1173        })
1174    }
1175}
1176
1177#[derive(Debug, Clone, Error)]
1178pub enum TypeError {
1179    #[error("{}\nArity mismatch, expected {expected} args: {expr}", .expr.span())]
1180    Arity { expr: Expr, expected: usize },
1181    #[error(
1182        "{}\n Expect expression {expr} to have type {}, but get type {}",
1183        .expr.span(), .expected.name(), .actual.name(),
1184    )]
1185    Mismatch {
1186        expr: Expr,
1187        expected: ArcSort,
1188        actual: ArcSort,
1189    },
1190    #[error("{1}\nUnbound symbol {0}")]
1191    Unbound(String, Span),
1192    #[error(
1193        "{1}\nVariable {0} is ungrounded. A variable is grounded when it appears as an argument to a constructor or function in the query, not just under primitives or equalities."
1194    )]
1195    Ungrounded(String, Span),
1196    #[error("{1}\nUndefined sort {0}")]
1197    UndefinedSort(String, Span),
1198    #[error("{1}\nUnbound function {0}")]
1199    UnboundFunction(String, Span),
1200    #[error("{1}\nprove-exists requires constructor function, but {0} is not a constructor")]
1201    ProveExistsRequiresConstructor(String, Span),
1202    #[error("{1}\nFunction already bound {0}")]
1203    FunctionAlreadyBound(String, Span),
1204    #[error("{1}\nSort {0} already declared.")]
1205    SortAlreadyBound(String, Span),
1206    #[error("{1}\nPrimitive {0} already declared.")]
1207    PrimitiveAlreadyBound(String, Span),
1208    #[error("Function type mismatch: expected {} => {}, actual {} => {}", .1.iter().map(|s| s.name().to_string()).collect::<Vec<_>>().join(", "), .0.name(), .3.iter().map(|s| s.name().to_string()).collect::<Vec<_>>().join(", "), .2.name())]
1209    FunctionTypeMismatch(ArcSort, Vec<ArcSort>, ArcSort, Vec<ArcSort>),
1210    #[error("{1}\nPresort {0} not found.")]
1211    PresortNotFound(String, Span),
1212    #[error("{1}\nInvalid arguments to sort constructor `{0}`")]
1213    BadPresortArguments(String, Span),
1214    #[error("{}\nFailed to infer a type for: {}", .0.span(), .0)]
1215    InferenceFailure(Expr),
1216    #[error("{1}\nVariable {0} was already defined")]
1217    AlreadyDefined(String, Span),
1218    #[error("{1}\nThe output type of constructor function {0} must be sort")]
1219    ConstructorOutputNotSort(String, Span),
1220    #[error("{1}\nValue lookup of non-constructor function {0} in rule is disallowed.")]
1221    LookupInRuleDisallowed(String, Span),
1222    #[error("{1}\nCannot set constructor {0}. Use `union` instead or declare {0} as a function.")]
1223    SetConstructorDisallowed(String, Span),
1224    #[error("All alternative definitions considered failed\n{}", .0.iter().map(|e| format!("  {e}\n")).collect::<Vec<_>>().join(""))]
1225    AllAlternativeFailed(Vec<TypeError>),
1226    #[error("{}\nCannot union values of sort {}", .1, .0.name())]
1227    NonEqsortUnion(ArcSort, Span),
1228    #[error("{}\nCannot union values of sort {} because it is marked as non-unionable (e.g. from a relation)", .1, .0.name())]
1229    NonUnionableSort(ArcSort, Span),
1230    #[error(
1231        "{1}\nView table {0} with :internal-term-constructor must have at least one input (the e-class)."
1232    )]
1233    TermConstructorNoInputs(String, Span),
1234    #[error(
1235        "{span}\nNon-global variable `{name}` must not start with `{}`.",
1236        crate::GLOBAL_NAME_PREFIX
1237    )]
1238    NonGlobalPrefixed { name: String, span: Span },
1239    #[error(
1240        "{span}\nGlobal `{name}` must start with `{}`.",
1241        crate::GLOBAL_NAME_PREFIX
1242    )]
1243    GlobalMissingPrefix { name: String, span: Span },
1244    #[error(
1245        "{span}\nAmbiguous primitive resolution for `{name}` in {ctx:?} context: multiple registered primitives match the same signature."
1246    )]
1247    AmbiguousPrimitive {
1248        name: String,
1249        ctx: crate::Context,
1250        span: Span,
1251    },
1252    #[error("{span}\nNo resolution for `{name}` in {ctx:?} context.")]
1253    UnresolvedPrimitive {
1254        name: String,
1255        ctx: crate::Context,
1256        span: Span,
1257    },
1258}
1259
1260#[cfg(test)]
1261mod test {
1262    use crate::{EGraph, Error, typechecking::TypeError};
1263
1264    #[test]
1265    fn test_arity_mismatch() {
1266        let mut egraph = EGraph::default();
1267
1268        let prog = "
1269            (relation f (i64 i64))
1270            (rule ((f a b c)) ())
1271       ";
1272        let res = egraph.parse_and_run_program(None, prog);
1273        match res {
1274            Err(Error::TypeError(TypeError::Arity {
1275                expected: 2,
1276                expr: e,
1277            })) => {
1278                assert_eq!(e.span().string(), "(f a b c)");
1279            }
1280            _ => panic!("Expected arity mismatch, got: {res:?}"),
1281        }
1282    }
1283}