typeck_lang/profile.rs
1//! Type-system profiles: what a language's checker is, as data.
2//!
3//! A [`Profile`] is a [`Discipline`] (how much is checked statically and how
4//! much is inferred) plus toggles that differ between languages of the same
5//! discipline. One checker reads the profile; no language gets its own
6//! checker.
7
8use hir_lang::{Prim, Symbol};
9
10use crate::mono::MonoPolicy;
11
12/// How much a language checks statically, and how much it infers.
13///
14/// | Discipline | Like | Static checking | Inference |
15/// |---|---|---|---|
16/// | `Dynamic` | Python, Lua, Mox | Only statically certain arity and shape errors | none: every value is `any` |
17/// | `Gradual` | TypeScript, Mercury | Where annotated; `any` at the boundaries | local |
18/// | `StaticExplicit` | C, Go, Zero | Everything | `let` initializers, literals, generic arguments |
19/// | `StaticInferred` | Kraken, Iron | Everything | bidirectional: also closure signatures from context |
20/// | `Hm` | ML family | Everything | full, with let-polymorphism |
21///
22/// Both static disciplines check generic items, interfaces (traits), `impl`
23/// blocks, associated types, and `dyn`/`impl Trait` types: any HIR that uses
24/// them needs them. `StaticInferred` additionally infers unannotated closure
25/// parameters and results from the expected function type, or from use.
26///
27/// Implemented in 0.3.0: `Dynamic`, `StaticExplicit`, and `StaticInferred`.
28/// `Gradual` and `Hm` are designed (see the crate's `dev/ROADMAP.md`) and
29/// land in 0.5.0; checking under them returns
30/// [`CheckError::NotImplemented`](crate::CheckError::NotImplemented).
31///
32/// # Examples
33///
34/// ```
35/// use typeck_lang::Discipline;
36///
37/// assert!(Discipline::Dynamic.is_implemented());
38/// assert!(Discipline::StaticInferred.is_implemented());
39/// assert!(!Discipline::Hm.is_implemented());
40/// ```
41#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
42#[non_exhaustive]
43pub enum Discipline {
44 /// No static type errors; every value has type `any`.
45 Dynamic,
46 /// Checked where annotated; unannotated values are `any`.
47 Gradual,
48 /// Declared types on signatures and globals; local inference for `let`.
49 StaticExplicit,
50 /// Bidirectional local inference, generics, traits or interfaces.
51 StaticInferred,
52 /// Hindley-Milner: full inference with let-polymorphism.
53 Hm,
54}
55
56impl Discipline {
57 /// Whether this version of the checker implements the discipline.
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// use typeck_lang::Discipline;
63 ///
64 /// assert!(Discipline::StaticExplicit.is_implemented());
65 /// assert!(!Discipline::Gradual.is_implemented());
66 /// ```
67 #[must_use]
68 pub const fn is_implemented(self) -> bool {
69 matches!(
70 self,
71 Self::Dynamic | Self::StaticExplicit | Self::StaticInferred
72 )
73 }
74
75 /// The discipline's name as profiles spell it (`static-explicit`).
76 ///
77 /// # Examples
78 ///
79 /// ```
80 /// use typeck_lang::Discipline;
81 ///
82 /// assert_eq!(Discipline::StaticExplicit.name(), "static-explicit");
83 /// ```
84 #[must_use]
85 pub const fn name(self) -> &'static str {
86 match self {
87 Self::Dynamic => "dynamic",
88 Self::Gradual => "gradual",
89 Self::StaticExplicit => "static-explicit",
90 Self::StaticInferred => "static-inferred",
91 Self::Hm => "hm",
92 }
93 }
94}
95
96/// Whether record types are identified by declaration or by shape.
97///
98/// # Examples
99///
100/// ```
101/// use typeck_lang::RecordTyping;
102///
103/// assert_ne!(RecordTyping::Nominal, RecordTyping::Structural);
104/// ```
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106pub enum RecordTyping {
107 /// Two record declarations are different types even with equal fields
108 /// (Rust, C, Kraken).
109 Nominal,
110 /// Records with the same field names and types are the same type, and an
111 /// anonymous record literal of that shape has it (TypeScript, Go's
112 /// unnamed structs). Applies to records with named fields; tuple-shaped
113 /// records and classes stay nominal.
114 Structural,
115}
116
117/// How a language attaches behaviour to types.
118///
119/// All three resolve members through the same engine (`impl` blocks and
120/// classes' declared interfaces are both implementations). The difference is
121/// what an interface name means where a type is expected: with
122/// `Interfaces`, the interface type (a `dyn` value, as in Java or Kraken);
123/// with `Traits` and `Typeclasses`, an error (write `dyn Trait` or
124/// `impl Trait`).
125///
126/// # Examples
127///
128/// ```
129/// use typeck_lang::Polymorphism;
130///
131/// assert_ne!(Polymorphism::Traits, Polymorphism::Typeclasses);
132/// ```
133#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
134pub enum Polymorphism {
135 /// Nominal implementations, coherent, separate from the type (Rust).
136 Traits,
137 /// Declared at the class, checked structurally against the interface
138 /// (Java, Go, Kraken).
139 Interfaces,
140 /// Dictionary-passing typeclasses (Haskell).
141 Typeclasses,
142}
143
144/// What `let x = null` (no annotation) gives `x` (ISSUES P17).
145///
146/// # Examples
147///
148/// ```
149/// use typeck_lang::NullLet;
150///
151/// assert_ne!(NullLet::NullType, NullLet::Nullable);
152/// ```
153#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
154pub enum NullLet {
155 /// The type of the literal, `null`: the variable can only ever hold
156 /// `null` (the 0.2 convention).
157 NullType,
158 /// `T?` for a `T` inferred from the variable's later uses (an
159 /// assignment `x = 5` makes it `i64?`). Under a profile without null
160 /// safety, `T` itself.
161 Nullable,
162}
163
164/// How `?`-style error propagation reaches the checker.
165///
166/// HIR lowers `e?` as a template (`match e { Ok(v) => v, Err(x) => return
167/// Err(x) }`, spec section 8.7), which needs no hook: it is ordinary code. A
168/// language whose lowering keeps `?` as a named intrinsic instead gets it
169/// typed here: the operand is a *carrier* (a nullable `T?`, or a sum of two
170/// variants that is either option-like, one unit variant and one with a
171/// single field, or result-like, two single-field variants with the success
172/// variant first); the expression has the success value's type, and the
173/// enclosing function must return a carrier of the same kind whose failure
174/// type the operand's failure converts to.
175///
176/// # Examples
177///
178/// ```
179/// use typeck_lang::TryHook;
180///
181/// assert_eq!(TryHook::default(), TryHook::Template);
182/// ```
183#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
184#[non_exhaustive]
185pub enum TryHook {
186 /// `?` arrives lowered as a `match`; nothing special.
187 #[default]
188 Template,
189 /// `Intrinsic::Named(name)` with one operand is `?`.
190 Intrinsic {
191 /// The intrinsic's name.
192 name: Symbol,
193 /// An interface (by name, among this unit's interfaces) whose
194 /// implementation `impl Conv<E1> for E2` lets a failure of type `E1`
195 /// propagate out of a function failing with `E2` (Rust's `From`).
196 /// `None`: the failure types must be equal.
197 convert: Option<Symbol>,
198 },
199}
200
201/// A type-system profile.
202///
203/// Built from a preset and adjusted with the `with_*` methods; fields are
204/// public to read. `#[non_exhaustive]`: profiles grow toggles as disciplines
205/// land, without breaking callers that start from a preset.
206///
207/// # Examples
208///
209/// ```
210/// use typeck_lang::{Profile, RecordTyping};
211///
212/// let iron_like = Profile::static_explicit()
213/// .with_records(RecordTyping::Nominal)
214/// .with_numeric_widening(false);
215/// assert!(iron_like.null_safety);
216/// assert!(!iron_like.numeric_widening);
217/// ```
218#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
219#[non_exhaustive]
220pub struct Profile {
221 /// How much is checked and inferred.
222 pub discipline: Discipline,
223 /// A subclass value may be used where a base class is expected, and (with
224 /// structural records) a record with extra fields where fewer are
225 /// expected.
226 pub subtyping: bool,
227 /// Nominal or structural records.
228 pub records: RecordTyping,
229 /// Lossless numeric conversions are implicit (`i32` to `i64`, `f32` to
230 /// `f64`, integers to floats that hold them exactly), and integer
231 /// literals may type as floats.
232 pub numeric_widening: bool,
233 /// `null` inhabits only `T?` types (Kotlin, Kraken). When `false`, `null`
234 /// coerces to any non-value type: references, pointers, nominal types,
235 /// functions, strings, slices, maps (Java, Go).
236 pub null_safety: bool,
237 /// `match` must cover every value of the scrutinee's type.
238 pub exhaustive_match: bool,
239 /// Traits, interfaces, or typeclasses: what an interface name means as
240 /// a type.
241 pub polymorphism: Polymorphism,
242 /// The type of an unsuffixed integer literal that nothing constrains.
243 pub default_int: Prim,
244 /// The type of an unsuffixed float literal that nothing constrains.
245 pub default_float: Prim,
246 /// `add` on two strings is concatenation.
247 pub string_add: bool,
248 /// Under `Dynamic`: report the arity and shape errors that are certain
249 /// whatever the run-time values (wrong argument count to a known
250 /// function, an unknown named argument or record field, a constructor
251 /// pattern of the wrong length).
252 pub certain_errors: bool,
253 /// Method receivers are borrowed (`&x`, `&mut x`) and dereferenced
254 /// implicitly to fit the method's receiver parameter, and lookup looks
255 /// through references (Rust, Iron). When `false`, the receiver must
256 /// already have the receiver parameter's type.
257 pub method_autoref: bool,
258 /// Which generic items the monomorphization plan copies per
259 /// instantiation and which it shares through dictionary passing.
260 pub mono: MonoPolicy,
261 /// What `let x = null` gives `x`.
262 pub null_let: NullLet,
263 /// How `?` reaches the checker.
264 pub try_hook: TryHook,
265}
266
267impl Default for Profile {
268 /// [`Profile::static_explicit`].
269 fn default() -> Self {
270 Self::static_explicit()
271 }
272}
273
274impl Profile {
275 /// Python, Lua, Mox: no static type errors, only certain shape errors.
276 ///
277 /// # Examples
278 ///
279 /// ```
280 /// use typeck_lang::{Discipline, Profile};
281 ///
282 /// let p = Profile::dynamic();
283 /// assert_eq!(p.discipline, Discipline::Dynamic);
284 /// assert!(p.certain_errors);
285 /// ```
286 #[must_use]
287 pub const fn dynamic() -> Self {
288 Self {
289 discipline: Discipline::Dynamic,
290 subtyping: true,
291 records: RecordTyping::Structural,
292 numeric_widening: true,
293 null_safety: false,
294 exhaustive_match: false,
295 polymorphism: Polymorphism::Interfaces,
296 default_int: Prim::I64,
297 default_float: Prim::F64,
298 string_add: true,
299 certain_errors: true,
300 method_autoref: true,
301 mono: MonoPolicy::Shared,
302 null_let: NullLet::NullType,
303 try_hook: TryHook::Template,
304 }
305 }
306
307 /// TypeScript-like: checked where annotated (0.5).
308 ///
309 /// # Examples
310 ///
311 /// ```
312 /// use typeck_lang::{Discipline, Profile};
313 ///
314 /// assert_eq!(Profile::gradual().discipline, Discipline::Gradual);
315 /// ```
316 #[must_use]
317 pub const fn gradual() -> Self {
318 Self {
319 discipline: Discipline::Gradual,
320 null_safety: true,
321 ..Self::dynamic()
322 }
323 }
324
325 /// C, Go, Zero: declared types, local inference for `let`.
326 ///
327 /// Nominal records, no subtyping beyond `Never`, `null` only in `T?`,
328 /// no implicit widening, exhaustive `match`, `i64`/`f64` literal
329 /// defaults.
330 ///
331 /// # Examples
332 ///
333 /// ```
334 /// use typeck_lang::{Profile, RecordTyping};
335 ///
336 /// let p = Profile::static_explicit();
337 /// assert_eq!(p.records, RecordTyping::Nominal);
338 /// assert!(p.exhaustive_match);
339 /// ```
340 #[must_use]
341 pub const fn static_explicit() -> Self {
342 Self {
343 discipline: Discipline::StaticExplicit,
344 subtyping: false,
345 records: RecordTyping::Nominal,
346 numeric_widening: false,
347 null_safety: true,
348 exhaustive_match: true,
349 polymorphism: Polymorphism::Interfaces,
350 default_int: Prim::I64,
351 default_float: Prim::F64,
352 string_add: false,
353 certain_errors: true,
354 method_autoref: true,
355 mono: MonoPolicy::Copy,
356 null_let: NullLet::NullType,
357 try_hook: TryHook::Template,
358 }
359 }
360
361 /// Kraken, Iron: bidirectional inference, generics, traits.
362 ///
363 /// As [`static_explicit`](Self::static_explicit), with traits, closure
364 /// signatures inferred from context, and `let x = null` giving a nullable
365 /// type inferred from later uses.
366 ///
367 /// # Examples
368 ///
369 /// ```
370 /// use typeck_lang::{Discipline, NullLet, Polymorphism, Profile};
371 ///
372 /// let p = Profile::static_inferred();
373 /// assert_eq!(p.discipline, Discipline::StaticInferred);
374 /// assert_eq!(p.polymorphism, Polymorphism::Traits);
375 /// assert_eq!(p.null_let, NullLet::Nullable);
376 /// ```
377 #[must_use]
378 pub const fn static_inferred() -> Self {
379 Self {
380 discipline: Discipline::StaticInferred,
381 polymorphism: Polymorphism::Traits,
382 null_let: NullLet::Nullable,
383 ..Self::static_explicit()
384 }
385 }
386
387 /// ML: Hindley-Milner with let-polymorphism (0.5).
388 ///
389 /// # Examples
390 ///
391 /// ```
392 /// use typeck_lang::{Discipline, Polymorphism, Profile};
393 ///
394 /// let p = Profile::hm();
395 /// assert_eq!(p.discipline, Discipline::Hm);
396 /// assert_eq!(p.polymorphism, Polymorphism::Typeclasses);
397 /// ```
398 #[must_use]
399 pub const fn hm() -> Self {
400 Self {
401 discipline: Discipline::Hm,
402 polymorphism: Polymorphism::Typeclasses,
403 ..Self::static_explicit()
404 }
405 }
406
407 /// Sets [`subtyping`](Self::subtyping).
408 ///
409 /// # Examples
410 ///
411 /// ```
412 /// assert!(typeck_lang::Profile::static_explicit().with_subtyping(true).subtyping);
413 /// ```
414 #[must_use]
415 pub const fn with_subtyping(mut self, on: bool) -> Self {
416 self.subtyping = on;
417 self
418 }
419
420 /// Sets [`records`](Self::records).
421 ///
422 /// # Examples
423 ///
424 /// ```
425 /// use typeck_lang::{Profile, RecordTyping};
426 ///
427 /// let p = Profile::static_explicit().with_records(RecordTyping::Structural);
428 /// assert_eq!(p.records, RecordTyping::Structural);
429 /// ```
430 #[must_use]
431 pub const fn with_records(mut self, records: RecordTyping) -> Self {
432 self.records = records;
433 self
434 }
435
436 /// Sets [`numeric_widening`](Self::numeric_widening).
437 ///
438 /// # Examples
439 ///
440 /// ```
441 /// assert!(typeck_lang::Profile::static_explicit().with_numeric_widening(true).numeric_widening);
442 /// ```
443 #[must_use]
444 pub const fn with_numeric_widening(mut self, on: bool) -> Self {
445 self.numeric_widening = on;
446 self
447 }
448
449 /// Sets [`null_safety`](Self::null_safety).
450 ///
451 /// # Examples
452 ///
453 /// ```
454 /// assert!(!typeck_lang::Profile::static_explicit().with_null_safety(false).null_safety);
455 /// ```
456 #[must_use]
457 pub const fn with_null_safety(mut self, on: bool) -> Self {
458 self.null_safety = on;
459 self
460 }
461
462 /// Sets [`exhaustive_match`](Self::exhaustive_match).
463 ///
464 /// # Examples
465 ///
466 /// ```
467 /// assert!(!typeck_lang::Profile::static_explicit().with_exhaustive_match(false).exhaustive_match);
468 /// ```
469 #[must_use]
470 pub const fn with_exhaustive_match(mut self, on: bool) -> Self {
471 self.exhaustive_match = on;
472 self
473 }
474
475 /// Sets [`polymorphism`](Self::polymorphism).
476 ///
477 /// # Examples
478 ///
479 /// ```
480 /// use typeck_lang::{Polymorphism, Profile};
481 ///
482 /// let p = Profile::static_inferred().with_polymorphism(Polymorphism::Interfaces);
483 /// assert_eq!(p.polymorphism, Polymorphism::Interfaces);
484 /// ```
485 #[must_use]
486 pub const fn with_polymorphism(mut self, polymorphism: Polymorphism) -> Self {
487 self.polymorphism = polymorphism;
488 self
489 }
490
491 /// Sets the literal defaults. A non-integer `int` or non-float `float` is
492 /// refused by [`check`](crate::check) with
493 /// [`CheckError::InvalidProfile`](crate::CheckError::InvalidProfile).
494 ///
495 /// # Examples
496 ///
497 /// ```
498 /// use hir_lang::Prim;
499 /// use typeck_lang::Profile;
500 ///
501 /// let p = Profile::static_explicit().with_literal_defaults(Prim::I32, Prim::F32);
502 /// assert_eq!(p.default_int, Prim::I32);
503 /// ```
504 #[must_use]
505 pub const fn with_literal_defaults(mut self, int: Prim, float: Prim) -> Self {
506 self.default_int = int;
507 self.default_float = float;
508 self
509 }
510
511 /// Sets [`string_add`](Self::string_add).
512 ///
513 /// # Examples
514 ///
515 /// ```
516 /// assert!(typeck_lang::Profile::static_explicit().with_string_add(true).string_add);
517 /// ```
518 #[must_use]
519 pub const fn with_string_add(mut self, on: bool) -> Self {
520 self.string_add = on;
521 self
522 }
523
524 /// Sets [`certain_errors`](Self::certain_errors).
525 ///
526 /// # Examples
527 ///
528 /// ```
529 /// assert!(!typeck_lang::Profile::dynamic().with_certain_errors(false).certain_errors);
530 /// ```
531 #[must_use]
532 pub const fn with_certain_errors(mut self, on: bool) -> Self {
533 self.certain_errors = on;
534 self
535 }
536
537 /// Sets [`method_autoref`](Self::method_autoref).
538 ///
539 /// # Examples
540 ///
541 /// ```
542 /// assert!(!typeck_lang::Profile::static_inferred().with_method_autoref(false).method_autoref);
543 /// ```
544 #[must_use]
545 pub const fn with_method_autoref(mut self, on: bool) -> Self {
546 self.method_autoref = on;
547 self
548 }
549
550 /// Sets [`mono`](Self::mono).
551 ///
552 /// # Examples
553 ///
554 /// ```
555 /// use typeck_lang::{MonoPolicy, Profile};
556 ///
557 /// let iron = Profile::static_inferred().with_mono(MonoPolicy::Selective { max_nodes: 64 });
558 /// assert_eq!(iron.mono, MonoPolicy::Selective { max_nodes: 64 });
559 /// ```
560 #[must_use]
561 pub const fn with_mono(mut self, mono: MonoPolicy) -> Self {
562 self.mono = mono;
563 self
564 }
565
566 /// Sets [`null_let`](Self::null_let).
567 ///
568 /// # Examples
569 ///
570 /// ```
571 /// use typeck_lang::{NullLet, Profile};
572 ///
573 /// let p = Profile::static_explicit().with_null_let(NullLet::Nullable);
574 /// assert_eq!(p.null_let, NullLet::Nullable);
575 /// ```
576 #[must_use]
577 pub const fn with_null_let(mut self, null_let: NullLet) -> Self {
578 self.null_let = null_let;
579 self
580 }
581
582 /// Sets [`try_hook`](Self::try_hook).
583 ///
584 /// # Examples
585 ///
586 /// ```
587 /// use intern_lang::Interner;
588 /// use typeck_lang::{Profile, TryHook};
589 ///
590 /// let mut names = Interner::new();
591 /// let hook = TryHook::Intrinsic { name: names.intern("try"), convert: None };
592 /// assert_eq!(Profile::static_inferred().with_try_hook(hook).try_hook, hook);
593 /// ```
594 #[must_use]
595 pub const fn with_try_hook(mut self, hook: TryHook) -> Self {
596 self.try_hook = hook;
597 self
598 }
599
600 /// Whether the static rules apply (every discipline but `Dynamic`).
601 pub(crate) const fn is_static(&self) -> bool {
602 !matches!(self.discipline, Discipline::Dynamic)
603 }
604
605 /// Whether unannotated closure signatures are inferred.
606 pub(crate) const fn infers_closures(&self) -> bool {
607 matches!(self.discipline, Discipline::StaticInferred | Discipline::Hm)
608 }
609}