Skip to main content

lower_lang/
problem.rs

1//! What lowering reports: problems in the code (values, never panics) and the
2//! few failures that stop it.
3
4use core::fmt;
5
6use hir_lang::{HirError, Span};
7
8use crate::template::TemplateId;
9
10/// The context a construct was lowered in, for problem messages.
11///
12/// # Examples
13///
14/// ```
15/// use lower_lang::Context;
16///
17/// assert_eq!(Context::Pattern.to_string(), "a pattern");
18/// ```
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub enum Context {
22    /// An expression.
23    Expression,
24    /// A statement in a block or module body.
25    Statement,
26    /// A declaration (module or block item).
27    Item,
28    /// A member of a class, interface, or impl.
29    Member,
30    /// A pattern.
31    Pattern,
32    /// A type.
33    Type,
34    /// A path.
35    Path,
36    /// A name.
37    Name,
38    /// A parameter.
39    Parameter,
40    /// A call argument.
41    Argument,
42    /// A match arm or catch clause.
43    Arm,
44    /// A closure capture.
45    Capture,
46    /// A record, variant, or class field.
47    Field,
48    /// A sum variant.
49    Variant,
50    /// A generic parameter, argument, or where-predicate.
51    Generic,
52    /// A map entry or field initializer.
53    Entry,
54    /// A path segment.
55    Segment,
56    /// A label.
57    Label,
58}
59
60impl fmt::Display for Context {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.write_str(match self {
63            Self::Expression => "an expression",
64            Self::Statement => "a statement",
65            Self::Item => "a declaration",
66            Self::Member => "a member",
67            Self::Pattern => "a pattern",
68            Self::Type => "a type",
69            Self::Path => "a path",
70            Self::Name => "a name",
71            Self::Parameter => "a parameter",
72            Self::Argument => "an argument",
73            Self::Arm => "a match arm",
74            Self::Capture => "a capture",
75            Self::Field => "a field",
76            Self::Variant => "a variant",
77            Self::Generic => "a generic parameter or argument",
78            Self::Entry => "an entry",
79            Self::Segment => "a path segment",
80            Self::Label => "a label",
81        })
82    }
83}
84
85/// What is wrong with one construct.
86///
87/// Every kind except [`Hir`](ProblemKind::Hir) comes from lowering itself; a
88/// `Hir` problem comes from hir-lang's lenient validator (a `break` outside a
89/// loop, a duplicate named argument, an out-of-range literal, ...). Either
90/// way the construct became an HIR error form and the rest of the unit was
91/// lowered.
92///
93/// # Examples
94///
95/// ```
96/// use lower_lang::ProblemKind;
97///
98/// assert_eq!(ProblemKind::UnknownLabel.to_string(), "no enclosing loop or block has this label");
99/// ```
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101#[non_exhaustive]
102pub enum ProblemKind {
103    /// A syntax error node from the parser (already reported by it; listed so
104    /// a host can tell lowering skipped the region).
105    SyntaxError,
106    /// A node or token kind the mapping does not describe.
107    Unmapped,
108    /// A construct the mapping marks [`Unsupported`](crate::Arch::Unsupported).
109    Unsupported,
110    /// A construct in a context it cannot appear in (a `let` used as an
111    /// expression, a call used as a type).
112    NotAllowedHere {
113        /// What was expected there.
114        expected: Context,
115    },
116    /// A required part is missing (half-typed code: `if` with no condition,
117    /// `fn` with no name).
118    MissingField {
119        /// The archetype field.
120        field: &'static str,
121    },
122    /// One child was selected for two fields of a construct (positional
123    /// picks alias in half-typed code, such as `while { ... }` with its
124    /// condition missing). The first field keeps it; the later one is left
125    /// absent.
126    AmbiguousChild,
127    /// An operator token with no entry in the operator table for its
128    /// position.
129    UnknownOperator,
130    /// A `break` or `continue` whose label no enclosing loop or block has.
131    UnknownLabel,
132    /// A number or character literal that does not decode (bad digits, too
133    /// large for its radix, an empty or multi-character char literal).
134    InvalidLiteral,
135    /// An escape sequence the literal's escape style does not define.
136    InvalidEscape,
137    /// A token's span does not lie inside the source text (a host bug).
138    BadSpan,
139    /// A required hole of a template is absent (the node lacks the part the
140    /// template needs, such as a `while` without its condition).
141    MissingHole {
142        /// The template.
143        template: TemplateId,
144    },
145    /// A template application nested deeper than
146    /// [`Budget::max_expansion_depth`](crate::Budget).
147    ExpansionTooDeep {
148        /// The template that could not be applied.
149        template: TemplateId,
150    },
151    /// A binding that must be function-scoped
152    /// ([`LangPolicy::function_scoped_bindings`](crate::LangPolicy), or a
153    /// hoisted `let`) but cannot be hoisted; it stays scoped to its construct.
154    CannotHoist {
155        /// Why.
156        reason: HoistBlocker,
157    },
158    /// An attribute argument that is neither a literal nor a name (HIR
159    /// attributes are data); it is left out of the attribute.
160    AttributeArgument,
161    /// An attribute on a construct that has no HIR node to carry it (a
162    /// wrapper, a capture, a match arm); it is dropped.
163    MisplacedAttribute,
164    /// A problem hir-lang's lenient validator found and repaired.
165    Hir(HirError),
166}
167
168/// Why a binding could not be hoisted to its function.
169///
170/// # Examples
171///
172/// ```
173/// use lower_lang::{HoistBlocker, ProblemKind};
174///
175/// let p = ProblemKind::CannotHoist { reason: HoistBlocker::ByReference };
176/// assert_eq!(
177///     p.to_string(),
178///     "this binding cannot be function-scoped: a by-reference binding would become a copy"
179/// );
180/// ```
181#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
182#[non_exhaustive]
183pub enum HoistBlocker {
184    /// A by-reference binding (`&$v`, `ref x`): hoisting assigns a copy, so
185    /// the function-scoped variable would not alias.
186    ByReference,
187    /// A template uses the pattern hole more than once, so one binding would
188    /// be assigned from several places.
189    ReusedHole,
190    /// The template never binds the pattern hole in a `match` arm or a
191    /// `let` (its expansion was cut short), so nothing assigns the binding.
192    NoBindingSite,
193}
194
195impl fmt::Display for HoistBlocker {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        f.write_str(match self {
198            Self::ByReference => "a by-reference binding would become a copy",
199            Self::ReusedHole => "the template binds this pattern in more than one place",
200            Self::NoBindingSite => "the template never binds this pattern",
201        })
202    }
203}
204
205impl fmt::Display for ProblemKind {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        match self {
208            Self::SyntaxError => f.write_str("syntax error"),
209            Self::Unmapped => {
210                f.write_str("the language's semantics do not describe this construct")
211            }
212            Self::Unsupported => f.write_str("this construct is not supported yet"),
213            Self::NotAllowedHere { expected } => write!(f, "expected {expected} here"),
214            Self::MissingField { field } => write!(f, "missing {field}"),
215            Self::AmbiguousChild => {
216                f.write_str("one part fills two roles here; a part is probably missing")
217            }
218            Self::UnknownOperator => f.write_str("unknown operator"),
219            Self::UnknownLabel => f.write_str("no enclosing loop or block has this label"),
220            Self::InvalidLiteral => f.write_str("invalid literal"),
221            Self::InvalidEscape => f.write_str("invalid escape sequence"),
222            Self::BadSpan => f.write_str("token span lies outside the source"),
223            Self::MissingHole { template } => {
224                write!(f, "missing a part template {} needs", template.index())
225            }
226            Self::ExpansionTooDeep { template } => write!(
227                f,
228                "template {} is nested too deeply to expand",
229                template.index()
230            ),
231            Self::CannotHoist { reason } => {
232                write!(f, "this binding cannot be function-scoped: {reason}")
233            }
234            Self::AttributeArgument => f.write_str(
235                "an attribute argument must be a literal or a name; this one is left out",
236            ),
237            Self::MisplacedAttribute => {
238                f.write_str("nothing here can carry an attribute; it is dropped")
239            }
240            Self::Hir(e) => write!(f, "{e}"),
241        }
242    }
243}
244
245/// One problem, at the source span it is about.
246///
247/// # Examples
248///
249/// ```
250/// use lower_lang::{Problem, ProblemKind, Span};
251///
252/// let p = Problem { kind: ProblemKind::UnknownOperator, span: Span::new(4, 5) };
253/// assert_eq!(p.to_string(), "4..5: unknown operator");
254/// ```
255#[derive(Clone, Copy, Debug, PartialEq, Eq)]
256pub struct Problem {
257    /// What is wrong.
258    pub kind: ProblemKind,
259    /// Where, in the syntax tree's source.
260    pub span: Span,
261}
262
263impl fmt::Display for Problem {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        write!(
266            f,
267            "{}..{}: {}",
268            self.span.start().to_u32(),
269            self.span.end().to_u32(),
270            self.kind
271        )
272    }
273}
274
275/// Why lowering stopped without a result. Problems in the code never stop it;
276/// only exhausted resources do.
277///
278/// # Examples
279///
280/// ```
281/// use lower_lang::LowerError;
282///
283/// let e = LowerError::NodeBudget { limit: 10 };
284/// assert_eq!(e.to_string(), "lowering would build more than 10 HIR nodes");
285/// ```
286#[derive(Clone, Copy, Debug, PartialEq, Eq)]
287#[non_exhaustive]
288pub enum LowerError {
289    /// Lowering would build more HIR nodes than
290    /// [`Budget::max_nodes`](crate::Budget). Raise the budget if the input is
291    /// trusted and genuinely that large; otherwise reject it.
292    NodeBudget {
293        /// The budget that was exceeded.
294        limit: u64,
295    },
296    /// The interner ran out of symbols. Use a fresh interner per session.
297    SymbolSpaceExhausted,
298    /// hir-lang refused the result without a repair (capacity exceeded). Split
299    /// the input.
300    Hir(HirError),
301}
302
303impl fmt::Display for LowerError {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        match self {
306            Self::NodeBudget { limit } => {
307                write!(f, "lowering would build more than {limit} HIR nodes")
308            }
309            Self::SymbolSpaceExhausted => f.write_str("the interner ran out of symbols"),
310            Self::Hir(e) => write!(f, "hir-lang refused the result: {e}"),
311        }
312    }
313}
314
315impl core::error::Error for LowerError {}