Skip to main content

Typed

Struct Typed 

Source
pub struct Typed { /* private fields */ }
Expand description

The result of checking one HIR unit.

Every live expression, pattern, and bound binder has a type (dense side tables, indexed by HIR id); a type is TypeId::ERROR where something was reported. Dead nodes (unreachable error forms left by lenient validation) have none.

§Examples

use hir_lang::{Builder, Name, OpKind, Prim};
use intern_lang::Interner;
use typeck_lang::{check, Profile, TypeId};

let mut names = Interner::new();
let mut b = Builder::new();
let (one, two) = (b.int(1), b.int(2));
let sum = b.op(OpKind::Add, &[one, two]);
let body = b.block(&[], Some(sum));
let main = b.func(Name::new(names.intern("main")), &[], body);
let root = b.module(None, &[main]);
let hir = b.finish(root)?;

// `main` has no declared return type: its body must be unit.
let typed = check(&hir, &Profile::static_explicit()).unwrap();
assert_eq!(typed.expr(sum), Some(TypeId::prim(Prim::I64)));
assert_eq!(typed.diagnostics().len(), 1);
assert_eq!(
    typed.message(&typed.diagnostics()[0], &names),
    "mismatched types: expected `()`, found `i64`",
);

Implementations§

Source§

impl Typed

Source

pub fn expr(&self, id: ExprId) -> Option<TypeId>

The type of a live expression.

§Examples
use hir_lang::{Builder, Lit, Name, Prim};
use intern_lang::Interner;
use typeck_lang::{check, Profile, TypeId};

let mut names = Interner::new();
let mut b = Builder::new();
let c = b.lit(Lit::Char('x'));
let s = b.expr_stmt(c);
let body = b.block(&[s], None);
let main = b.func(Name::new(names.intern("main")), &[], body);
let root = b.module(None, &[main]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::static_explicit()).unwrap();
assert_eq!(typed.expr(c), Some(TypeId::prim(Prim::Char)));
Source

pub fn pat(&self, id: PatId) -> Option<TypeId>

The type a live pattern matches.

§Examples
use hir_lang::{Builder, Name};
use intern_lang::Interner;
use typeck_lang::{check, Profile, TypeId};

let mut names = Interner::new();
let mut b = Builder::new();
let x = b.new_binder(Name::new(names.intern("x")), hir_lang::BinderKind::Local);
let pat = b.bind(x);
let init = b.lit(hir_lang::Lit::Bool(true));
let stmt = b.let_stmt(pat, Some(init));
let body = b.block(&[stmt], None);
let main = b.func(Name::new(names.intern("main")), &[], body);
let root = b.module(None, &[main]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::static_explicit()).unwrap();
assert_eq!(typed.pat(pat), Some(TypeId::prim(hir_lang::Prim::Bool)));
assert_eq!(typed.binder(x), Some(TypeId::prim(hir_lang::Prim::Bool)));
Source

pub fn binder(&self, id: BinderId) -> Option<TypeId>

The type of a bound binder (a variable, parameter, or capture).

§Examples
use hir_lang::{Builder, Lit, Name, Prim};
use intern_lang::Interner;
use typeck_lang::{check, Profile, TypeId};

let mut names = Interner::new();
let mut b = Builder::new();
let x = b.new_binder(Name::new(names.intern("x")), hir_lang::BinderKind::Local);
let pat = b.bind(x);
let init = b.lit(Lit::Bool(false));
let s = b.let_stmt(pat, Some(init));
let body = b.block(&[s], None);
let main = b.func(Name::new(names.intern("main")), &[], body);
let root = b.module(None, &[main]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::static_explicit()).unwrap();
assert_eq!(typed.binder(x), Some(TypeId::prim(Prim::Bool)));
Source

pub fn types(&self) -> &Types

The type store the side tables point into.

§Examples
use hir_lang::Builder;
use typeck_lang::{check, Profile, Type, TypeId};

let mut b = Builder::new();
let root = b.module(None, &[]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::dynamic()).unwrap();
assert_eq!(typed.types().get(TypeId::ANY), Type::Any);
Source

pub fn diagnostics(&self) -> &[Diagnostic]

The diagnostics, in source order (span start, then discovery).

§Examples
use hir_lang::{Builder, Lit, Name, Prim};
use intern_lang::Interner;
use typeck_lang::{check, Profile, TypeId};

let mut names = Interner::new();
let mut b = Builder::new();
// let x: bool = 1;
let one = b.int(1);
let ann = b.ty(hir_lang::Ty::Prim(Prim::Bool));
let x = b.new_binder(Name::new(names.intern("x")), hir_lang::BinderKind::Local);
let pat = b.bind(x);
let s = b.stmt(hir_lang::Stmt::Let { pat, ty: Some(ann), init: Some(one), else_: None });
let body = b.block(&[s], None);
let main = b.func(Name::new(names.intern("main")), &[], body);
let root = b.module(None, &[main]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::static_explicit()).unwrap();
let d = typed.diagnostics()[0];
assert_eq!(d.node, hir_lang::NodeRef::Expr(one));
assert_eq!(d.kind.code(), "T0001");
Source

pub fn is_ok(&self) -> bool

true if no error was reported (warnings, such as unreachable match arms, do not count).

§Examples
use hir_lang::Builder;
use typeck_lang::{check, Profile};

let mut b = Builder::new();
let root = b.module(None, &[]);
let hir = b.finish(root)?;
assert!(check(&hir, &Profile::static_explicit()).unwrap().is_ok());
Source

pub fn path_def(&self, path: PathId) -> Option<Def>

The definition the checker resolved a path’s unresolved tail to (Shape::Circle to a variant, Point::new to an impl function). None for paths resolution resolved completely.

§Examples
use hir_lang::{Builder, Def, Expr, Ident, Item, ItemKind, List, Name, Ns, Path, Res, Segment, Shape, Span, SumDef, Variant};
use intern_lang::Interner;
use typeck_lang::{check, Profile};

let mut names = Interner::new();
let mut b = Builder::new();
// enum Shape { Empty }   fn main() { Shape::Empty; }
let empty = b.variant(Variant {
    name: Ident::new(names.intern("Empty"), Span::empty(0)),
    shape: Shape::Unit,
    fields: List::EMPTY,
    discriminant: None,
});
let variants = b.list(&[empty]);
let shape = b.item(Item::new(
    Some(Name::new(names.intern("Shape"))),
    ItemKind::Sum(SumDef { variants, ..SumDef::default() }),
));
// `Shape` resolved by name; `Empty` left to the checker.
let origin = b.origin();
let segments = b.list(&[
    Segment::new(Name::new(names.intern("Shape")), origin),
    Segment::new(Name::new(names.intern("Empty")), origin),
]);
let def = b.def(Def::Item(shape));
let path = b.path(Path { res: Res::Def(def), unresolved: 1, ..Path::new(segments, Ns::Value) });
let e = b.expr(Expr::Path(path));
let s = b.expr_stmt(e);
let body = b.block(&[s], None);
let main = b.func(Name::new(names.intern("main")), &[], body);
let root = b.module(None, &[shape, main]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::static_explicit()).unwrap();
assert_eq!(typed.path_def(path), Some(Def::Variant(empty)));
Source

pub fn method(&self, call: ExprId) -> Option<ItemId>

The function item a method call dispatches to statically.

§Examples
use hir_lang::{Arg, BinderKind, Builder, Def, Expr, FieldDef, FnDef, Ident, ImplDef, Item, ItemKind, List, Name, Ns, Param, ParamKind, Prim, RecordDef, Res, Span, Ty};
use intern_lang::Interner;
use typeck_lang::{check, Profile, TypeId};

let mut names = Interner::new();
let mut b = Builder::new();
// struct P { x: i64 }  impl P { fn get(self) -> i64 { self.x } }
let i64_ty = b.ty(Ty::Prim(Prim::I64));
let x = names.intern("x");
let field = b.field(FieldDef { ty: Some(i64_ty), ..FieldDef::named(Ident::new(x, Span::empty(0))) });
let fields = b.list(&[field]);
let p = b.item(Item::new(Some(Name::new(names.intern("P"))), ItemKind::Record(RecordDef { fields, ..RecordDef::default() })));
let me = b.new_binder(Name::new(names.intern("self")), BinderKind::Param);
let me_pat = b.bind(me);
let recv = b.param(Param { kind: ParamKind::Receiver, ..Param::new(me_pat) });
let base = b.use_binder(me);
let read = b.expr(Expr::Field { base, member: hir_lang::Member::Named(x), span: Span::empty(0) });
let get_body = b.block(&[], Some(read));
let ret = b.ty(Ty::Prim(Prim::I64));
let params = b.list(&[recv]);
let get = b.item(Item::new(Some(Name::new(names.intern("get"))), ItemKind::Fn(FnDef { params, ret: Some(ret), body: Some(get_body), ..FnDef::default() })));
let p_def = b.def(Def::Item(p));
let p_path = b.resolved_path(Name::new(names.intern("P")), Ns::Type, Res::Def(p_def));
let self_ty = b.ty(Ty::Path(p_path));
let items = b.list(&[get]);
let imp = b.item(Item::new(None, ItemKind::Impl(ImplDef { items, ..ImplDef::new(self_ty) })));
// fn main(v: P) { v.get(); }
let p_path2 = b.resolved_path(Name::new(names.intern("P")), Ns::Type, Res::Def(p_def));
let v_ty = b.ty(Ty::Path(p_path2));
let v = b.new_binder(Name::new(names.intern("v")), BinderKind::Param);
let v_pat = b.bind(v);
let v_param = b.param(Param { ty: Some(v_ty), ..Param::new(v_pat) });
let receiver = b.use_binder(v);
let args = b.list::<Arg>(&[]);
let call = b.expr(Expr::MethodCall { receiver, method: Ident::new(names.intern("get"), Span::empty(0)), generic_args: List::EMPTY, args });
let s = b.expr_stmt(call);
let body = b.block(&[s], None);
let main = b.func(Name::new(names.intern("main")), &[v_param], body);
let root = b.module(None, &[p, imp, main]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::static_explicit()).unwrap();
assert!(typed.is_ok());
assert_eq!(typed.method(call), Some(get));
assert_eq!(typed.expr(call), Some(TypeId::prim(Prim::I64)));
Source

pub fn coercion(&self, expr: ExprId) -> Option<(Coercion, TypeId)>

The implicit conversion applied to an expression’s value, and the type it was converted to.

§Examples
use hir_lang::{Builder, Lit, Name, Prim};
use intern_lang::Interner;
use typeck_lang::{check, Coercion, Profile, TypeId};

let mut names = Interner::new();
let mut b = Builder::new();
// let x: f64 = 2i32;   accepted with numeric widening
let two = b.lit(Lit::Int(hir_lang::IntLit::new(2).with_suffix(Prim::I32)));
let ann = b.ty(hir_lang::Ty::Prim(Prim::F64));
let x = b.new_binder(Name::new(names.intern("x")), hir_lang::BinderKind::Local);
let pat = b.bind(x);
let s = b.stmt(hir_lang::Stmt::Let { pat, ty: Some(ann), init: Some(two), else_: None });
let body = b.block(&[s], None);
let main = b.func(Name::new(names.intern("main")), &[], body);
let root = b.module(None, &[main]);
let hir = b.finish(root)?;
let profile = Profile::static_explicit().with_numeric_widening(true);
let typed = check(&hir, &profile).unwrap();
assert!(typed.is_ok());
assert_eq!(typed.coercion(two), Some((Coercion::Widen, TypeId::prim(Prim::F64))));
Source

pub fn op_class(&self, op: ExprId) -> Option<OpClass>

How an Op expression’s operation was resolved.

§Examples
use hir_lang::{Builder, Name, OpKind, Prim};
use intern_lang::Interner;
use typeck_lang::{check, OpClass, Profile};

let mut names = Interner::new();
let mut b = Builder::new();
let (x, y) = (b.int(1), b.int(2));
let lt = b.op(OpKind::Lt, &[x, y]);
let s = b.expr_stmt(lt);
let body = b.block(&[s], None);
let main = b.func(Name::new(names.intern("main")), &[], body);
let root = b.module(None, &[main]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::static_explicit()).unwrap();
assert_eq!(typed.op_class(lt), Some(OpClass::Int(Prim::I64)));
Source

pub fn witnesses<L: Lookup>(&self, match_expr: ExprId, names: &L) -> Vec<String>

The values a non-exhaustive match misses, as patterns (Some(false), Shape::Rect { w: _, h: _ }, 3..=9), at most eight; empty when the match is exhaustive or the profile does not require it.

§Examples
use hir_lang::{Arm, Builder, Expr, Lit, Name, Pat};
use intern_lang::Interner;
use typeck_lang::{check, Profile};

let mut names = Interner::new();
let mut b = Builder::new();
// fn main() { match true { true => {} } }
let scrutinee = b.lit(Lit::Bool(true));
let pat = b.pat(Pat::Lit(Lit::Bool(true)));
let body = b.block(&[], None);
let arms = b.list(&[Arm { pat, guard: None, body }]);
let m = b.expr(Expr::Match { scrutinee, arms });
let s = b.expr_stmt(m);
let main_body = b.block(&[s], None);
let main = b.func(Name::new(names.intern("main")), &[], main_body);
let root = b.module(None, &[main]);
let hir = b.finish(root)?;

let typed = check(&hir, &Profile::static_explicit()).unwrap();
assert_eq!(typed.witnesses(m, &names), ["false"]);
assert_eq!(
    typed.message(&typed.diagnostics()[0], &names),
    "non-exhaustive match: `false` not covered",
);
Source

pub fn instantiation(&self, expr: ExprId) -> Option<Instantiation<'_>>

The generic item an expression uses and its arguments: a path to a generic function, a method call (also on non-generic methods, for the dispatch), a constructor or literal of a generic type.

§Examples
use hir_lang::{Builder, Name};
use intern_lang::Interner;
use typeck_lang::{check, Profile};

let mut b = Builder::new();
let root = b.module(None, &[]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::static_inferred()).unwrap();
let e = hir_lang::ExprId::from_index(0).unwrap();
assert!(typed.instantiation(e).is_none());
Source

pub fn mono_plan(&self) -> &MonoPlan

The monomorphization plan: every instance of a generic function the program reaches, with how it is compiled (see MonoPolicy).

§Examples
use hir_lang::Builder;
use typeck_lang::{check, Profile};

let mut b = Builder::new();
let root = b.module(None, &[]);
let hir = b.finish(root)?;
assert!(check(&hir, &Profile::static_inferred()).unwrap().mono_plan().is_empty());
Source

pub fn opaque_type(&self, origin: TyId) -> Option<TypeId>

The hidden type of a function’s impl Trait result, named by the impl type node of its return type (in the function’s own placeholders). Callers see only the bounds; lowering needs the type.

§Examples
use hir_lang::{Builder, TyId};
use typeck_lang::{check, Profile};

let mut b = Builder::new();
let root = b.module(None, &[]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::static_inferred()).unwrap();
assert!(typed.opaque_type(TyId::from_index(0).unwrap()).is_none());
Source

pub fn profile(&self) -> &Profile

The profile the program was checked under.

§Examples
use hir_lang::Builder;
use typeck_lang::{check, Profile};

let mut b = Builder::new();
let root = b.module(None, &[]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::dynamic()).unwrap();
assert_eq!(*typed.profile(), Profile::dynamic());
Source

pub fn stats(&self) -> Stats

Work counters.

§Examples
use hir_lang::{Builder, Name};
use intern_lang::Interner;
use typeck_lang::{check, Profile};

let mut b = Builder::new();
let one = b.int(1);
let s = b.expr_stmt(one);
let body = b.block(&[s], None);
let main = b.func(Name::new(Interner::new().intern("main")), &[], body);
let root = b.module(None, &[main]);
let hir = b.finish(root)?;
let stats = check(&hir, &Profile::static_explicit()).unwrap().stats();
assert!(stats.steps > 0 && stats.type_nodes >= 20);
Source

pub fn display<'a, L: Lookup>( &'a self, ty: TypeId, names: &'a L, ) -> TypeDisplay<'a, L>

Renders a type; see Types::display.

§Examples
use hir_lang::Builder;
use intern_lang::Interner;
use typeck_lang::{check, Profile, TypeId};

let mut b = Builder::new();
let root = b.module(None, &[]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::dynamic()).unwrap();
assert_eq!(typed.display(TypeId::ANY, &Interner::new()).to_string(), "any");
Source

pub fn message<L: Lookup>(&self, diagnostic: &Diagnostic, names: &L) -> String

Renders a diagnostic’s message (without code or location).

§Examples
use hir_lang::{Builder, Lit, Name, Prim};
use intern_lang::Interner;
use typeck_lang::{check, Profile, TypeId};

let mut names = Interner::new();
let mut b = Builder::new();
// let x: bool = 1;
let one = b.int(1);
let ann = b.ty(hir_lang::Ty::Prim(Prim::Bool));
let x = b.new_binder(Name::new(names.intern("x")), hir_lang::BinderKind::Local);
let pat = b.bind(x);
let s = b.stmt(hir_lang::Stmt::Let { pat, ty: Some(ann), init: Some(one), else_: None });
let body = b.block(&[s], None);
let main = b.func(Name::new(names.intern("main")), &[], body);
let root = b.module(None, &[main]);
let hir = b.finish(root)?;
let typed = check(&hir, &Profile::static_explicit()).unwrap();
let d = typed.diagnostics()[0];
assert_eq!(typed.message(&d, &names), "mismatched types: expected `bool`, found `i64`");

Trait Implementations§

Source§

impl Clone for Typed

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Typed

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Typed

Source§

impl PartialEq for Typed

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Typed

Auto Trait Implementations§

§

impl Freeze for Typed

§

impl RefUnwindSafe for Typed

§

impl Send for Typed

§

impl Sync for Typed

§

impl Unpin for Typed

§

impl UnsafeUnpin for Typed

§

impl UnwindSafe for Typed

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.