Skip to main content

typeck_lang/
lib.rs

1//! # typeck_lang
2//!
3//! Profile-driven type checking over HIR: one checker, configured by a
4//! type-system [`Profile`] instead of written per language.
5//!
6//! ```
7//! use hir_lang::{Builder, Name, OpKind};
8//! use intern_lang::Interner;
9//! use typeck_lang::{check, Profile};
10//!
11//! let mut names = Interner::new();
12//! let mut b = Builder::new();
13//! // fn main() { 1 + true; }
14//! let one = b.int(1);
15//! let yes = b.lit(hir_lang::Lit::Bool(true));
16//! let sum = b.op(OpKind::Add, &[one, yes]);
17//! let stmt = b.expr_stmt(sum);
18//! let body = b.block(&[stmt], None);
19//! let main = b.func(Name::new(names.intern("main")), &[], body);
20//! let root = b.module(None, &[main]);
21//! let hir = b.finish(root)?;
22//!
23//! // Statically: one diagnostic, at `true`.
24//! let typed = check(&hir, &Profile::static_explicit()).unwrap();
25//! let d = typed.diagnostics()[0];
26//! assert_eq!(d.node, hir_lang::NodeRef::Expr(yes));
27//! assert_eq!(typed.message(&d, &names), "`add` is not defined for `bool`");
28//!
29//! // Dynamically: nothing to report; every value is `any`.
30//! assert!(check(&hir, &Profile::dynamic()).unwrap().is_ok());
31//! # Ok::<(), hir_lang::HirError>(())
32//! ```
33//!
34//! ## What it does
35//!
36//! - **Profiles as data** ([`Profile`], [`Discipline`]): `dynamic`,
37//!   `gradual`, `static-explicit`, `static-inferred`, and `hm`, with toggles
38//!   for subtyping, nominal or structural records, numeric widening, null
39//!   safety, exhaustive matches, traits versus interfaces, implicit receiver
40//!   borrowing, the monomorphization policy, `let x = null`, and `?`. This
41//!   version implements `dynamic`, `static-explicit`, and `static-inferred`;
42//!   `gradual` and `hm` return [`CheckError::NotImplemented`] (see
43//!   `dev/ROADMAP.md`).
44//! - **Generics and interfaces**: generic functions and types with bounds and
45//!   where clauses, constant parameters, defaults; interfaces (traits) with
46//!   methods, default methods, constants, associated types, and supertraits;
47//!   `impl` blocks, generic ones indexed like any other; interface method
48//!   resolution through bounds, `dyn` types, and implementations; `impl
49//!   Trait` parameters and results; coherence (overlapping implementations)
50//!   and conformance (missing, extra, or mistyped members).
51//! - **Bidirectional checking**: expected types flow into arguments of
52//!   generic calls, record literals, and closures (whose signatures
53//!   `static-inferred` infers).
54//! - **Exhaustiveness** through match-lang: missing values as witnesses,
55//!   unreachable arms and redundant alternatives as warnings.
56//! - **Output** ([`Typed`]): dense side tables of types keyed by HIR
57//!   expression, pattern, and binder ids; typed diagnostics with origins;
58//!   the implicit conversions lowering must materialise; how each operation
59//!   resolved (integer, IEEE, string); the definitions of partial paths'
60//!   unresolved tails (`Shape::Circle`, `T::new`); what each use of a generic
61//!   item instantiates; and the monomorphization plan ([`MonoPlan`]).
62//! - **One root cause, one diagnostic**: anything reported has type
63//!   [`TypeId::ERROR`], which every later check accepts silently.
64//! - **Termination**: union-find over hash-consed type terms (no exponential
65//!   blow-up on shared structure), iterative traversals everywhere, and a
66//!   [`Budget`] (steps, type-store size, trait-resolution depth) that turns
67//!   pathological input into [`CheckError::BudgetExceeded`] instead of a
68//!   hang.
69//!
70//! The checker does not resolve names (resolve-lang does) and does not
71//! compile patterns into decision trees (match-lang decides exhaustiveness
72//! for it; lowering compiles them).
73
74#![cfg_attr(not(feature = "std"), no_std)]
75#![cfg_attr(docsrs, feature(doc_cfg))]
76#![forbid(unsafe_code)]
77#![deny(missing_docs)]
78#![deny(unused_must_use)]
79#![deny(unused_results)]
80#![deny(clippy::unwrap_used)]
81#![deny(clippy::expect_used)]
82#![deny(clippy::panic)]
83#![deny(clippy::todo)]
84#![deny(clippy::unimplemented)]
85#![deny(clippy::unreachable)]
86#![deny(clippy::print_stdout)]
87#![deny(clippy::print_stderr)]
88#![deny(clippy::dbg_macro)]
89
90extern crate alloc;
91
92mod check;
93mod diag;
94mod error;
95mod infer;
96mod mono;
97mod profile;
98mod typed;
99mod types;
100
101pub use check::Checker;
102pub use diag::{Diagnostic, DiagnosticKind, Feature, Severity};
103pub use error::{Budget, CheckError, Limit};
104pub use mono::{Dispatch, Instance, Instantiation, MonoPlan, MonoPolicy, Strategy};
105pub use profile::{Discipline, NullLet, Polymorphism, Profile, RecordTyping, TryHook};
106pub use typed::{Coercion, OpClass, Stats, Typed};
107pub use types::{Field, Type, TypeDisplay, TypeId, Types};
108
109use hir_lang::Hir;
110
111/// Checks `hir` under `profile`, with no host declarations and a budget
112/// scaled to the HIR ([`Budget::for_hir`]).
113///
114/// Type errors in the program are [`Diagnostic`]s in the result; see
115/// [`Checker`] to declare host functions and types, or to set a budget.
116///
117/// # Errors
118///
119/// See [`Checker::check`].
120///
121/// # Examples
122///
123/// ```
124/// use hir_lang::{Builder, Lit, Name, Prim};
125/// use intern_lang::Interner;
126/// use typeck_lang::{check, Profile, TypeId};
127///
128/// let mut b = Builder::new();
129/// let t = b.lit(Lit::Bool(true));
130/// let body = b.block(&[], Some(t));
131/// // A function without a declared return type returns unit.
132/// let f = b.func(Name::new(Interner::new().intern("f")), &[], body);
133/// let root = b.module(None, &[f]);
134/// let hir = b.finish(root)?;
135/// let typed = check(&hir, &Profile::static_explicit()).unwrap();
136/// assert_eq!(typed.diagnostics().len(), 1);
137/// assert_eq!(typed.expr(t), Some(TypeId::prim(Prim::Bool)));
138/// # Ok::<(), hir_lang::HirError>(())
139/// ```
140pub fn check(hir: &Hir, profile: &Profile) -> Result<Typed, CheckError> {
141    Checker::new(hir, *profile).check()
142}
143
144/// Compiles and runs the `rust` code blocks in `README.md` and `docs/API.md`
145/// as part of `cargo test`, so the published examples cannot drift from the
146/// API.
147#[cfg(doctest)]
148#[doc = include_str!("../README.md")]
149#[doc = include_str!("../docs/API.md")]
150pub struct MarkdownDocTests;