hir_lang/name.rs
1//! Binders, paths, namespaces, and resolutions.
2
3use intern_lang::Symbol;
4
5use crate::{
6 def::DefId,
7 id::{BinderId, List, TyId},
8 lit::Prim,
9 origin::{Name, Origin},
10 ty::GenericArg,
11};
12
13/// What a binder names. Each kind has its own binding sites; see the spec,
14/// §3.1.
15///
16/// # Examples
17///
18/// ```
19/// use hir_lang::BinderKind;
20///
21/// assert!(BinderKind::Param.is_value());
22/// assert!(BinderKind::TypeParam.is_type_level());
23/// assert!(!BinderKind::Label.is_value());
24/// ```
25#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub enum BinderKind {
27 /// A local variable: bound by a `let`, an arm pattern, a `static` or
28 /// `global` declaration.
29 Local,
30 /// A parameter bound by a parameter pattern.
31 Param,
32 /// A closure-local variable: bound by an explicit capture or as a
33 /// closure's self binder.
34 Capture,
35 /// A generic type parameter.
36 TypeParam,
37 /// A generic constant parameter.
38 ConstParam,
39 /// A region (lifetime) parameter.
40 Region,
41 /// A loop or block label.
42 Label,
43 /// A place alias bound by [`Expr::LetPlace`](crate::Expr::LetPlace): it
44 /// names a place whose operands were evaluated once. Never visible across
45 /// a frame.
46 Place,
47}
48
49impl BinderKind {
50 /// Returns `true` for run-time variables: `Local`, `Param`, `Capture`,
51 /// `Place`.
52 ///
53 /// # Examples
54 ///
55 /// ```
56 /// use hir_lang::BinderKind;
57 ///
58 /// assert!(BinderKind::Capture.is_value());
59 /// assert!(!BinderKind::ConstParam.is_value());
60 /// ```
61 #[must_use]
62 pub const fn is_value(self) -> bool {
63 matches!(
64 self,
65 Self::Local | Self::Param | Self::Capture | Self::Place
66 )
67 }
68
69 /// Returns `true` for compile-time binders: `TypeParam`, `ConstParam`,
70 /// `Region`. These may be referenced across closures and constant contexts.
71 ///
72 /// # Examples
73 ///
74 /// ```
75 /// use hir_lang::BinderKind;
76 ///
77 /// assert!(BinderKind::Region.is_type_level());
78 /// assert!(!BinderKind::Local.is_type_level());
79 /// ```
80 #[must_use]
81 pub const fn is_type_level(self) -> bool {
82 matches!(self, Self::TypeParam | Self::ConstParam | Self::Region)
83 }
84
85 /// Returns the namespace a path naming this binder is in, or `None` for
86 /// labels (which are never named by paths).
87 ///
88 /// # Examples
89 ///
90 /// ```
91 /// use hir_lang::{BinderKind, Ns};
92 ///
93 /// assert_eq!(BinderKind::ConstParam.ns(), Some(Ns::Value));
94 /// assert_eq!(BinderKind::Label.ns(), None);
95 /// ```
96 #[must_use]
97 pub const fn ns(self) -> Option<Ns> {
98 match self {
99 Self::Local | Self::Param | Self::Capture | Self::Place | Self::ConstParam => {
100 Some(Ns::Value)
101 }
102 Self::TypeParam => Some(Ns::Type),
103 Self::Region => Some(Ns::Region),
104 Self::Label => None,
105 }
106 }
107
108 /// Returns the kind's spelling, as the printer and errors use it.
109 ///
110 /// # Examples
111 ///
112 /// ```
113 /// use hir_lang::BinderKind;
114 ///
115 /// assert_eq!(BinderKind::TypeParam.name(), "type-param");
116 /// ```
117 #[must_use]
118 pub const fn name(self) -> &'static str {
119 match self {
120 Self::Local => "local",
121 Self::Param => "param",
122 Self::Capture => "capture",
123 Self::TypeParam => "type-param",
124 Self::ConstParam => "const-param",
125 Self::Region => "region",
126 Self::Label => "label",
127 Self::Place => "place",
128 }
129 }
130}
131
132/// A binder: one variable, parameter, capture, generic parameter, or label.
133///
134/// Binder ids are unique across a `Hir`. A reference to a local is a binder id
135/// (in a path's [`Res`]), never a name to be looked up again.
136///
137/// # Examples
138///
139/// ```
140/// use hir_lang::{Binder, BinderKind, Name};
141/// use intern_lang::Interner;
142///
143/// let mut names = Interner::new();
144/// let x = Binder::new(Name::new(names.intern("x")), BinderKind::Local);
145/// assert!(!x.mutable);
146/// assert!(x.with_mutable(true).mutable);
147/// ```
148#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
149pub struct Binder {
150 /// The hygienic name.
151 pub name: Name,
152 /// What it binds.
153 pub kind: BinderKind,
154 /// Declared mutable (`let mut`, `var`).
155 pub mutable: bool,
156}
157
158impl Binder {
159 /// An immutable binder.
160 ///
161 /// # Examples
162 ///
163 /// ```
164 /// use hir_lang::{Binder, BinderKind, Name};
165 /// use intern_lang::Interner;
166 ///
167 /// let mut names = Interner::new();
168 /// let t = Binder::new(Name::new(names.intern("T")), BinderKind::TypeParam);
169 /// assert_eq!(t.kind, BinderKind::TypeParam);
170 /// ```
171 #[must_use]
172 pub const fn new(name: Name, kind: BinderKind) -> Self {
173 Self {
174 name,
175 kind,
176 mutable: false,
177 }
178 }
179
180 /// Returns the binder with its mutability set.
181 ///
182 /// # Examples
183 ///
184 /// ```
185 /// use hir_lang::{Binder, BinderKind, Name};
186 /// use intern_lang::Interner;
187 ///
188 /// let mut names = Interner::new();
189 /// let n = Binder::new(Name::new(names.intern("n")), BinderKind::Local).with_mutable(true);
190 /// assert!(n.mutable);
191 /// ```
192 #[must_use]
193 pub const fn with_mutable(mut self, mutable: bool) -> Self {
194 self.mutable = mutable;
195 self
196 }
197}
198
199/// The namespace a path is looked up in, fixed by the path's context.
200///
201/// # Examples
202///
203/// ```
204/// use hir_lang::Ns;
205///
206/// assert_eq!(Ns::Value.name(), "value");
207/// ```
208#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
209pub enum Ns {
210 /// Expression paths, capture sources, `global` declarations.
211 Value,
212 /// Type paths and the paths of record expressions/patterns.
213 Type,
214 /// Constructor, constant, and identifier paths in patterns.
215 Pattern,
216 /// Explicit regions in reference types, bounds, and generic arguments.
217 Region,
218 /// Import paths.
219 Import,
220}
221
222impl Ns {
223 /// Returns the namespace's spelling.
224 ///
225 /// # Examples
226 ///
227 /// ```
228 /// use hir_lang::Ns;
229 ///
230 /// assert_eq!(Ns::Pattern.name(), "pattern");
231 /// ```
232 #[must_use]
233 pub const fn name(self) -> &'static str {
234 match self {
235 Self::Value => "value",
236 Self::Type => "type",
237 Self::Pattern => "pattern",
238 Self::Region => "region",
239 Self::Import => "import",
240 }
241 }
242}
243
244/// What a path (or its resolved prefix) refers to. Lowering may set it;
245/// resolve-lang sets the rest with [`Hir::resolve`](crate::Hir::resolve).
246///
247/// # Examples
248///
249/// ```
250/// use hir_lang::{Prim, Res};
251///
252/// assert!(Res::Unresolved.is_unresolved());
253/// assert!(!Res::Prim(Prim::Bool).is_unresolved());
254/// ```
255#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
256pub enum Res {
257 /// Not resolved yet.
258 #[default]
259 Unresolved,
260 /// A binder: a local, parameter, capture, or generic parameter.
261 Local(BinderId),
262 /// An item or variant, in this unit or another.
263 Def(DefId),
264 /// A primitive type.
265 Prim(Prim),
266 /// A host or standard-library symbol bound by the language's `[stdlib]`
267 /// table (resolved by host-lang, not by HIR).
268 Extern(Symbol),
269 /// Resolution failed and was reported; consumers suppress cascades.
270 Err,
271}
272
273impl Res {
274 /// Returns `true` for [`Res::Unresolved`].
275 ///
276 /// # Examples
277 ///
278 /// ```
279 /// use hir_lang::Res;
280 ///
281 /// assert!(!Res::Err.is_unresolved());
282 /// ```
283 #[must_use]
284 pub const fn is_unresolved(self) -> bool {
285 matches!(self, Self::Unresolved)
286 }
287}
288
289/// Where a path starts.
290///
291/// # Examples
292///
293/// ```
294/// use hir_lang::PathRoot;
295///
296/// assert_eq!(PathRoot::default(), PathRoot::Relative);
297/// assert!(PathRoot::StaticType.is_type_root());
298/// ```
299#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
300pub enum PathRoot {
301 /// Looked up from the current scope.
302 #[default]
303 Relative,
304 /// `::a` — from the root module of the package.
305 Global,
306 /// `self::a` (Rust) — from the current module.
307 SelfModule,
308 /// `super::a`, `super::super::a` — from an enclosing module, this many
309 /// levels up (at least 1).
310 Super(u8),
311 /// `Self::a` (Rust), `self::a` (PHP) — relative to the enclosing
312 /// impl/interface/class type.
313 SelfType,
314 /// `parent::a` (PHP) — relative to the enclosing class's base class.
315 ParentType,
316 /// `static::a` (PHP) — relative to the run-time class (late static
317 /// binding).
318 StaticType,
319}
320
321impl PathRoot {
322 /// Returns `true` for the roots that start at a type (`Self`, `parent`,
323 /// `static`), whose tails may be resolved by type.
324 ///
325 /// # Examples
326 ///
327 /// ```
328 /// use hir_lang::PathRoot;
329 ///
330 /// assert!(PathRoot::ParentType.is_type_root());
331 /// assert!(!PathRoot::Global.is_type_root());
332 /// ```
333 #[must_use]
334 pub const fn is_type_root(self) -> bool {
335 matches!(self, Self::SelfType | Self::ParentType | Self::StaticType)
336 }
337}
338
339/// A qualified self type: `<T>::a` or `<T as Tr>::a`.
340///
341/// The first `trait_len` segments of the path name the trait (none for
342/// `<T>::a`); the rest are resolved relative to `ty` (by typeck).
343///
344/// # Examples
345///
346/// ```
347/// use hir_lang::{Builder, QSelf, Ty};
348///
349/// let mut b = Builder::new();
350/// let t = b.ty(Ty::SelfTy);
351/// let q = QSelf { ty: t, trait_len: 1 };
352/// assert_eq!(q.trait_len, 1);
353/// ```
354#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
355pub struct QSelf {
356 /// The self type.
357 pub ty: TyId,
358 /// How many leading segments name the trait.
359 pub trait_len: u32,
360}
361
362/// One segment of a path: a hygienic name, its generic arguments, and its own
363/// origin (what an LSP renames).
364///
365/// # Examples
366///
367/// ```
368/// use hir_lang::{Name, Origin, Segment};
369/// use intern_lang::Interner;
370///
371/// let mut names = Interner::new();
372/// let seg = Segment::new(Name::new(names.intern("Vec")), Origin::default());
373/// assert!(seg.args.is_empty());
374/// ```
375#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
376pub struct Segment {
377 /// The name.
378 pub name: Name,
379 /// Generic arguments (`Vec::<T>`, `Iterator<Item = u8>`, `Ref<'a>`).
380 pub args: List<GenericArg>,
381 /// The segment's own origin.
382 pub origin: Origin,
383}
384
385impl Segment {
386 /// A segment without generic arguments.
387 ///
388 /// # Examples
389 ///
390 /// ```
391 /// use hir_lang::{Name, Origin, Segment};
392 /// use intern_lang::Interner;
393 ///
394 /// let mut names = Interner::new();
395 /// let seg = Segment::new(Name::new(names.intern("io")), Origin::default());
396 /// assert_eq!(seg.origin, Origin::default());
397 /// ```
398 #[must_use]
399 pub const fn new(name: Name, origin: Origin) -> Self {
400 Self {
401 name,
402 args: List::EMPTY,
403 origin,
404 }
405 }
406}
407
408/// A name reference: root, optional qualified self, segments, namespace, and
409/// a partial resolution.
410///
411/// `res` names what the first `segments.len() - unresolved` segments refer to
412/// (the resolved prefix); the remaining `unresolved` segments are resolved by
413/// type (associated items, `Vec::new`, `T::Item`). A path with no segments and
414/// `res: Err` is the error path.
415///
416/// # Examples
417///
418/// ```
419/// use hir_lang::{List, Ns, Path, PathRoot, Res};
420///
421/// let p = Path::new(List::EMPTY, Ns::Type);
422/// assert_eq!((p.root, p.res, p.unresolved), (PathRoot::Relative, Res::Unresolved, 0));
423/// ```
424#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
425pub struct Path {
426 /// The segments (at least one, except for the error path).
427 pub segments: List<Segment>,
428 /// The namespace, which must match the path's context.
429 pub ns: Ns,
430 /// Where lookup starts.
431 pub root: PathRoot,
432 /// `<T>::…` or `<T as Tr>::…`.
433 pub qself: Option<QSelf>,
434 /// What the resolved prefix refers to.
435 pub res: Res,
436 /// How many trailing segments are left to type-directed resolution.
437 pub unresolved: u32,
438}
439
440impl Path {
441 /// An unresolved relative path.
442 ///
443 /// # Examples
444 ///
445 /// ```
446 /// use hir_lang::{List, Ns, Path};
447 ///
448 /// assert!(Path::new(List::EMPTY, Ns::Value).qself.is_none());
449 /// ```
450 #[must_use]
451 pub const fn new(segments: List<Segment>, ns: Ns) -> Self {
452 Self {
453 segments,
454 ns,
455 root: PathRoot::Relative,
456 qself: None,
457 res: Res::Unresolved,
458 unresolved: 0,
459 }
460 }
461}