hir_lang/error.rs
1//! Validation and resolution errors.
2
3use core::fmt;
4
5use intern_lang::Symbol;
6
7use crate::{
8 id::{BinderId, ExprId, IdKind, NodeRef, PatId, PathId},
9 name::{BinderKind, Ns, Res},
10 origin::ExpnId,
11};
12
13/// Where an error was found: a node, a binder, an expansion record, the root,
14/// or a node's attribute list.
15///
16/// # Examples
17///
18/// ```
19/// use hir_lang::{ExprId, NodeRef, Site};
20///
21/// let site = Site::Node(NodeRef::Expr(ExprId::from_index(0).unwrap()));
22/// assert_eq!(site.to_string(), "expression 0");
23/// ```
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25pub enum Site {
26 /// A tree node.
27 Node(NodeRef),
28 /// A binder record.
29 Binder(BinderId),
30 /// An expansion record.
31 Expansion(ExpnId),
32 /// The root passed to `finish`.
33 Root,
34 /// The attribute list of a node.
35 Attrs(NodeRef),
36}
37
38impl fmt::Display for Site {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 match self {
41 Self::Node(node) => write!(f, "{} {}", node.kind(), node.index()),
42 Self::Binder(b) => write!(f, "binder {}", b.index()),
43 Self::Expansion(e) => write!(f, "expansion {}", e.as_u32()),
44 Self::Root => f.write_str("the root"),
45 Self::Attrs(node) => write!(f, "the attributes of {} {}", node.kind(), node.index()),
46 }
47 }
48}
49
50/// A structural problem inside one node; carried by [`HirError::Malformed`].
51///
52/// # Examples
53///
54/// ```
55/// use hir_lang::Malformed;
56///
57/// assert_eq!(Malformed::EmptyPath.to_string(), "a path has no segments");
58/// ```
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
60#[non_exhaustive]
61pub enum Malformed {
62 /// A path has no segments.
63 EmptyPath,
64 /// An or-pattern has no alternatives.
65 EmptyOrPattern,
66 /// A tuple or constructor pattern's `..` position is past its elements.
67 RestOutOfRange,
68 /// A range pattern has neither bound.
69 RangeWithoutBounds,
70 /// A range pattern's bounds are not both integers, both chars, or both floats.
71 RangeBoundKinds,
72 /// An integer literal does not fit its suffix type.
73 LiteralOutOfRange,
74 /// A literal's suffix is not of the literal's class (e.g. `1f32` on an
75 /// integer, or a suffix on a char).
76 LiteralSuffix,
77 /// An `f32` literal is not exactly representable in `f32`.
78 InexactF32,
79 /// A string literal's payload is not valid UTF-8.
80 InvalidUtf8,
81 /// A big-integer literal is not an optional `-` followed by decimal digits.
82 InvalidBigInt,
83 /// A conversion op's target type has the wrong class.
84 ConversionTarget,
85 /// An assignment target is not a place expression.
86 AssignTarget,
87 /// A compound assignment's operator is not a binary op.
88 CompoundAssignOp,
89 /// A let-else has no initializer.
90 LetElseWithoutInit,
91 /// A record's or variant's fields do not fit its shape.
92 ShapeFields,
93 /// An item kind that requires a name has none.
94 MissingName,
95 /// An item kind that takes no name (an impl, a glob import) has one.
96 UnexpectedName,
97 /// A function has no body outside an interface, a class, or a foreign
98 /// declaration.
99 MissingBody,
100 /// A constant has no value outside an interface.
101 MissingConstValue,
102 /// An item kind is not allowed in its container.
103 ItemPlacement,
104 /// A receiver parameter is not first, is in a closure, or is in a function
105 /// that is not a member of an interface, impl, or class.
106 ReceiverPlacement,
107 /// Parameter kinds are out of order or repeated.
108 ParamOrder,
109 /// A receiver or rest parameter has a default.
110 ParamDefault,
111 /// An explicit capture uses `CaptureMode::Infer`.
112 InferCapture,
113 /// An attribute argument has neither key nor value.
114 EmptyAttrArg,
115 /// The attribute table is not sorted by target with one entry per target.
116 AttrOrder,
117 /// The `promote` overflow policy is used where HIR fixes a static result
118 /// type: on `int_cast`, on a cast to a type other than `Any`, or in an
119 /// integer constant context (array length, const generic argument,
120 /// discriminant). `promote` needs a dynamically typed result.
121 PromoteOnStaticResult,
122 /// A path's root, qualified self, unresolved count, and resolution do not
123 /// fit together (`super` with depth 0; a qualified self with a non-relative
124 /// root or no item segment; more unresolved segments than segments; an
125 /// empty resolved prefix without a type root or qualified self; a resolved
126 /// prefix that names something without associated items).
127 PathShape,
128 /// A range-pattern bound is not a literal or constant path pattern.
129 RangeBound,
130 /// An integer literal is `-0`; write `0`.
131 NegativeZero,
132 /// An inline-assembly template is not UTF-8, has an unbalanced brace, or
133 /// names an operand that does not exist.
134 AsmTemplate,
135 /// An inline-assembly output operand is not a place, or a `sym` operand is
136 /// not a path.
137 AsmOperand,
138 /// An intrinsic has the wrong number of operands.
139 IntrinsicArity,
140 /// An atomic intrinsic uses a memory ordering it cannot have.
141 MemOrder,
142 /// A `place` argument is not a place expression, or is a spread.
143 PlaceArg,
144 /// An append place (`$a[]`) is used other than as the target of an
145 /// assignment or reference assignment, or as a place argument.
146 AppendContext,
147 /// An or-pattern alternative binds a binder with a different binding mode
148 /// than the first alternative.
149 OrPatternModes,
150 /// A union or intersection has fewer than two members (spec §5.1).
151 TypeArity,
152 /// A union contains a union or a `Nullable`, or an intersection an
153 /// intersection, directly (spec §5.1).
154 TypeNesting,
155 /// Union or intersection members are not in canonical order, or one
156 /// repeats (spec §5.1).
157 TypeOrder,
158 /// A `yield` has a key but no value.
159 YieldKey,
160}
161
162impl fmt::Display for Malformed {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 f.write_str(match self {
165 Self::EmptyPath => "a path has no segments",
166 Self::EmptyOrPattern => "an or-pattern has no alternatives",
167 Self::RestOutOfRange => "the `..` position is past the last element",
168 Self::RangeWithoutBounds => "a range pattern has no bounds",
169 Self::RangeBoundKinds => {
170 "range bounds must both be integers, both chars, or both floats"
171 }
172 Self::LiteralOutOfRange => "an integer literal does not fit its suffix type",
173 Self::LiteralSuffix => "a literal's suffix does not match its kind",
174 Self::InexactF32 => "an f32 literal is not exactly representable in f32",
175 Self::InvalidUtf8 => "a string literal is not valid UTF-8",
176 Self::InvalidBigInt => "a big-integer literal is not decimal digits",
177 Self::ConversionTarget => "a conversion's target type has the wrong class",
178 Self::AssignTarget => "an assignment target is not a place expression",
179 Self::CompoundAssignOp => "a compound assignment's operator is not binary",
180 Self::LetElseWithoutInit => "a let-else has no initializer",
181 Self::ShapeFields => "the fields do not fit the declared shape",
182 Self::MissingName => "this kind of item needs a name",
183 Self::UnexpectedName => "this kind of item takes no name",
184 Self::MissingBody => {
185 "a function needs a body outside interfaces, classes, and foreign declarations"
186 }
187 Self::MissingConstValue => "a constant needs a value outside interfaces",
188 Self::ItemPlacement => "this kind of item is not allowed in its container",
189 Self::ReceiverPlacement => {
190 "a receiver must be the first parameter of an interface, impl, or class member"
191 }
192 Self::ParamOrder => "parameter kinds are out of order or repeated",
193 Self::ParamDefault => "receiver and rest parameters cannot have defaults",
194 Self::InferCapture => "an explicit capture cannot use the `Infer` mode",
195 Self::EmptyAttrArg => "an attribute argument has neither key nor value",
196 Self::AttrOrder => "the attribute table is not sorted by target",
197 Self::PromoteOnStaticResult => {
198 "the `promote` overflow policy needs a dynamically typed result"
199 }
200 Self::PathShape => {
201 "the path's root, qualified self, and resolution do not fit together"
202 }
203 Self::RangeBound => "a range bound must be a literal or a constant path",
204 Self::NegativeZero => "an integer literal is `-0`",
205 Self::AsmTemplate => "the assembly template is malformed or names a missing operand",
206 Self::AsmOperand => "an assembly output must be a place and a `sym` operand a path",
207 Self::IntrinsicArity => "the intrinsic has the wrong number of operands",
208 Self::MemOrder => "the atomic intrinsic cannot use this memory ordering",
209 Self::PlaceArg => "a place argument must be a non-spread place expression",
210 Self::AppendContext => "an append place can only be written to",
211 Self::OrPatternModes => "or-pattern alternatives bind a binder with different modes",
212 Self::TypeArity => "a union or intersection has fewer than two members",
213 Self::TypeNesting => {
214 "a union or intersection directly contains one of its own kind (or a union a nullable type)"
215 }
216 Self::TypeOrder => "union or intersection members are not in canonical order, or repeat",
217 Self::YieldKey => "a `yield` with a key needs a value",
218 })
219 }
220}
221
222/// A jump that has no valid target; carried by [`HirError::Jump`].
223///
224/// # Examples
225///
226/// ```
227/// use hir_lang::JumpProblem;
228///
229/// assert_eq!(JumpProblem::ContinueToBlock.to_string(), "`continue` targets a block, not a loop");
230/// ```
231#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
232#[non_exhaustive]
233pub enum JumpProblem {
234 /// `break` without a label outside any loop of the current function.
235 BreakOutsideLoop,
236 /// `continue` without a label outside any loop of the current function.
237 ContinueOutsideLoop,
238 /// The label is not an enclosing loop or block of the current function.
239 LabelNotInScope,
240 /// `continue` names a labeled block.
241 ContinueToBlock,
242 /// A jump would leave a `defer` body (jumps may leave `finally`).
243 OutOfDefer,
244 /// `continue` targets the loop whose `step` it is in.
245 ContinueInStep,
246}
247
248impl fmt::Display for JumpProblem {
249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 f.write_str(match self {
251 Self::BreakOutsideLoop => "`break` outside a loop",
252 Self::ContinueOutsideLoop => "`continue` outside a loop",
253 Self::LabelNotInScope => "the label is not an enclosing loop or block",
254 Self::ContinueToBlock => "`continue` targets a block, not a loop",
255 Self::OutOfDefer => "a jump would leave a `defer` body",
256 Self::ContinueInStep => "`continue` inside a loop's own step",
257 })
258 }
259}
260
261/// An effect form outside a frame that allows it; carried by
262/// [`HirError::Effect`].
263///
264/// # Examples
265///
266/// ```
267/// use hir_lang::EffectProblem;
268///
269/// assert_eq!(EffectProblem::AwaitOutsideAsync.to_string(), "`await` outside an async function");
270/// ```
271#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
272#[non_exhaustive]
273pub enum EffectProblem {
274 /// `return` outside a function or closure body.
275 ReturnOutsideFunction,
276 /// `await` in a frame without `ASYNC`.
277 AwaitOutsideAsync,
278 /// `yield` in a frame without `YIELD`.
279 YieldOutsideGenerator,
280 /// `throw` in a frame without `THROWS` and outside a `try` body.
281 ThrowNotAllowed,
282}
283
284impl fmt::Display for EffectProblem {
285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 f.write_str(match self {
287 Self::ReturnOutsideFunction => "`return` outside a function",
288 Self::AwaitOutsideAsync => "`await` outside an async function",
289 Self::YieldOutsideGenerator => "`yield` outside a generator",
290 Self::ThrowNotAllowed => "`throw` in a function that does not throw, outside `try`",
291 })
292 }
293}
294
295/// What a container overflowed; carried by [`HirError::CapacityExceeded`].
296///
297/// # Examples
298///
299/// ```
300/// use hir_lang::{Capacity, IdKind};
301///
302/// assert_eq!(Capacity::Arena(IdKind::Expr).to_string(), "the expression arena");
303/// ```
304#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
305#[non_exhaustive]
306pub enum Capacity {
307 /// A node, binder, or expansion arena.
308 Arena(IdKind),
309 /// A list pool.
310 Pool,
311 /// The text pool.
312 Text,
313 /// The total node count across all arenas (positions are 32-bit).
314 Total,
315}
316
317impl fmt::Display for Capacity {
318 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319 match self {
320 Self::Arena(kind) => write!(f, "the {kind} arena"),
321 Self::Pool => f.write_str("a list pool"),
322 Self::Text => f.write_str("the text pool"),
323 Self::Total => f.write_str("the total node count"),
324 }
325 }
326}
327
328/// Why a HIR was rejected by the validator, or a resolution by
329/// [`Hir::resolve`](crate::Hir::resolve).
330///
331/// Every variant names the offending node, binder, path, or expansion, so a
332/// lowering bug can be traced to the construct that produced it (each node has
333/// an origin). The validator reports the first problem in a deterministic order
334/// (spec §13).
335///
336/// # Examples
337///
338/// ```
339/// use hir_lang::{Builder, HirError, ItemId};
340///
341/// // A root id this builder never issued.
342/// let err = Builder::new().finish(ItemId::from_index(5).unwrap()).unwrap_err();
343/// assert!(matches!(err, HirError::Dangling { .. }));
344/// ```
345#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
346#[non_exhaustive]
347pub enum HirError {
348 /// An arena or pool grew past `u32::MAX - 1` entries while building. Split
349 /// the input into several HIRs.
350 CapacityExceeded {
351 /// What overflowed.
352 what: Capacity,
353 },
354 /// An id does not name an existing node, binder, or expansion. A lowering
355 /// bug, or ids mixed between builders.
356 Dangling {
357 /// Where the id is stored.
358 site: Site,
359 /// The kind of id.
360 kind: IdKind,
361 /// Its index.
362 index: usize,
363 },
364 /// A list lies outside its pool.
365 ListOutOfBounds {
366 /// Where the list is stored.
367 site: Site,
368 },
369 /// A text reference lies outside the text pool.
370 TextOutOfBounds {
371 /// Where the reference is stored.
372 site: Site,
373 },
374 /// An expansion refers to itself or a later expansion, so a backtrace could
375 /// loop.
376 ExpansionOrder {
377 /// The offending expansion.
378 expn: ExpnId,
379 },
380 /// The root item is not a module.
381 RootNotModule,
382 /// A node is the child of more than one parent (or of itself).
383 SharedNode {
384 /// The node.
385 node: NodeRef,
386 },
387 /// A node is not reachable from the root.
388 Unreachable {
389 /// The node.
390 node: NodeRef,
391 },
392 /// A node's own structure is invalid.
393 Malformed {
394 /// The node.
395 site: Site,
396 /// What is wrong.
397 problem: Malformed,
398 },
399 /// Two members of one list share a name (fields, variants, named arguments,
400 /// field initializers, field patterns). Reported at the first repetition in
401 /// source order.
402 DuplicateName {
403 /// The node owning the list.
404 node: NodeRef,
405 /// The repeated name.
406 name: Symbol,
407 /// The position of the repetition in its list.
408 index: u32,
409 },
410 /// An op instance does not carry exactly the policy fields its op consults
411 /// (or a cast does not carry exactly `overflow` and `float_to_int`).
412 Policy {
413 /// The `Op`, `Cast`, or compound `Assign` expression.
414 expr: ExprId,
415 },
416 /// An op has the wrong number of operands.
417 Arity {
418 /// The `Op` expression.
419 expr: ExprId,
420 /// The op's arity.
421 expected: usize,
422 /// The number of operands given.
423 found: usize,
424 },
425 /// A binder is bound by two binding constructs.
426 BinderBoundTwice {
427 /// The binder.
428 binder: BinderId,
429 /// The second binding site found.
430 node: NodeRef,
431 },
432 /// A binder appears twice in one pattern alternative.
433 DuplicateBinding {
434 /// The binder.
435 binder: BinderId,
436 /// The pattern (the binding construct's root or the alternative).
437 pat: PatId,
438 },
439 /// The alternatives of an or-pattern bind different binders.
440 OrPatternBinders {
441 /// The or-pattern.
442 pat: PatId,
443 },
444 /// A binder's kind does not fit its binding site.
445 BinderKind {
446 /// The binder.
447 binder: BinderId,
448 /// The kind the site requires.
449 expected: BinderKind,
450 },
451 /// A path's namespace does not match its parent node.
452 PathNamespace {
453 /// The path.
454 path: PathId,
455 /// The namespace its parent requires.
456 expected: Ns,
457 },
458 /// A resolution names something the path's namespace cannot refer to (or an
459 /// id that does not exist).
460 Resolution {
461 /// The path.
462 path: PathId,
463 /// The rejected resolution.
464 res: Res,
465 },
466 /// A resolution names a definition of this unit through a `DefId` minted
467 /// by a different `Hir` or builder (ids are not portable between `Hir`s).
468 ForeignDef {
469 /// The path.
470 path: PathId,
471 },
472 /// A path resolves to a binder that is not in scope where the path is.
473 OutOfScope {
474 /// The path.
475 path: PathId,
476 /// The binder.
477 binder: BinderId,
478 },
479 /// A path resolves to a binder outside a frame it may not cross: a local of
480 /// an enclosing function from a nested item, a local from a constant
481 /// context, a local from a closure that forbids implicit captures, or a
482 /// parameter from a default evaluated once at definition.
483 NotCapturable {
484 /// The path.
485 path: PathId,
486 /// The binder.
487 binder: BinderId,
488 },
489 /// A `break` or `continue` has no valid target.
490 Jump {
491 /// The jump.
492 expr: ExprId,
493 /// Why.
494 problem: JumpProblem,
495 },
496 /// An effect form is outside a frame that allows it.
497 Effect {
498 /// The expression.
499 expr: ExprId,
500 /// Why.
501 problem: EffectProblem,
502 },
503}
504
505impl fmt::Display for HirError {
506 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507 match self {
508 Self::CapacityExceeded { what } => write!(f, "{what} exceeded its capacity"),
509 Self::Dangling { site, kind, index } => {
510 write!(f, "{site} refers to {kind} {index}, which does not exist")
511 }
512 Self::ListOutOfBounds { site } => write!(f, "a list in {site} lies outside its pool"),
513 Self::TextOutOfBounds { site } => {
514 write!(f, "a text reference in {site} lies outside the text pool")
515 }
516 Self::ExpansionOrder { expn } => write!(
517 f,
518 "expansion {} refers to itself or a later expansion",
519 expn.as_u32()
520 ),
521 Self::RootNotModule => f.write_str("the root item is not a module"),
522 Self::SharedNode { node } => {
523 write!(
524 f,
525 "{} {} has more than one parent",
526 node.kind(),
527 node.index()
528 )
529 }
530 Self::Unreachable { node } => write!(
531 f,
532 "{} {} is not reachable from the root",
533 node.kind(),
534 node.index()
535 ),
536 Self::Malformed { site, problem } => write!(f, "{site}: {problem}"),
537 Self::DuplicateName { node, name, index } => write!(
538 f,
539 "{} {}: member {index} repeats the name of an earlier member (symbol {})",
540 node.kind(),
541 node.index(),
542 name.as_u32()
543 ),
544 Self::Policy { expr } => write!(
545 f,
546 "expression {} does not carry exactly the policy fields its operation uses",
547 expr.index()
548 ),
549 Self::Arity {
550 expr,
551 expected,
552 found,
553 } => write!(
554 f,
555 "expression {}: the operation takes {expected} operands, {found} given",
556 expr.index()
557 ),
558 Self::BinderBoundTwice { binder, node } => write!(
559 f,
560 "binder {} is bound a second time at {} {}",
561 binder.index(),
562 node.kind(),
563 node.index()
564 ),
565 Self::DuplicateBinding { binder, pat } => write!(
566 f,
567 "binder {} is bound twice in pattern {}",
568 binder.index(),
569 pat.index()
570 ),
571 Self::OrPatternBinders { pat } => write!(
572 f,
573 "the alternatives of or-pattern {} bind different binders",
574 pat.index()
575 ),
576 Self::BinderKind { binder, expected } => write!(
577 f,
578 "binder {} is bound where a {} binder is required",
579 binder.index(),
580 expected.name()
581 ),
582 Self::PathNamespace { path, expected } => write!(
583 f,
584 "path {} must be in the {} namespace",
585 path.index(),
586 expected.name()
587 ),
588 Self::Resolution { path, res } => write!(
589 f,
590 "path {} cannot resolve to {res:?} in its namespace",
591 path.index()
592 ),
593 Self::ForeignDef { path } => write!(
594 f,
595 "path {} names this unit through a definition id minted for another HIR",
596 path.index()
597 ),
598 Self::OutOfScope { path, binder } => write!(
599 f,
600 "path {} refers to binder {}, which is not in scope there",
601 path.index(),
602 binder.index()
603 ),
604 Self::NotCapturable { path, binder } => write!(
605 f,
606 "path {} refers to binder {} across a function, constant, or non-capturing closure boundary",
607 path.index(),
608 binder.index()
609 ),
610 Self::Jump { expr, problem } => write!(f, "expression {}: {problem}", expr.index()),
611 Self::Effect { expr, problem } => write!(f, "expression {}: {problem}", expr.index()),
612 }
613 }
614}
615
616impl HirError {
617 /// Returns the node the problem is about, when it is one (a path's node
618 /// for resolution problems), so a host can find its origin.
619 ///
620 /// # Examples
621 ///
622 /// ```
623 /// use hir_lang::{ExprId, HirError, NodeRef};
624 ///
625 /// let e = ExprId::from_index(3).unwrap();
626 /// assert_eq!(HirError::Policy { expr: e }.node(), Some(NodeRef::Expr(e)));
627 /// assert_eq!(HirError::RootNotModule.node(), None);
628 /// ```
629 #[must_use]
630 pub const fn node(&self) -> Option<NodeRef> {
631 match *self {
632 Self::Dangling { site, .. }
633 | Self::ListOutOfBounds { site }
634 | Self::TextOutOfBounds { site }
635 | Self::Malformed { site, .. } => match site {
636 Site::Node(n) | Site::Attrs(n) => Some(n),
637 _ => None,
638 },
639 Self::SharedNode { node }
640 | Self::Unreachable { node }
641 | Self::DuplicateName { node, .. }
642 | Self::BinderBoundTwice { node, .. } => Some(node),
643 Self::Policy { expr }
644 | Self::Arity { expr, .. }
645 | Self::Jump { expr, .. }
646 | Self::Effect { expr, .. } => Some(NodeRef::Expr(expr)),
647 Self::DuplicateBinding { pat, .. } | Self::OrPatternBinders { pat } => {
648 Some(NodeRef::Pat(pat))
649 }
650 Self::PathNamespace { path, .. }
651 | Self::Resolution { path, .. }
652 | Self::ForeignDef { path }
653 | Self::OutOfScope { path, .. }
654 | Self::NotCapturable { path, .. } => Some(NodeRef::Path(path)),
655 Self::CapacityExceeded { .. }
656 | Self::ExpansionOrder { .. }
657 | Self::RootNotModule
658 | Self::BinderKind { .. } => None,
659 }
660 }
661}
662
663impl core::error::Error for HirError {}