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    /// A numeric `break N` / `continue N`
167    /// ([`BreakLevels::Numeric`](crate::BreakLevels::Numeric)) whose level
168    /// is not a positive integer literal (`level` is `0`), or is larger than
169    /// the number of loops around it in its function (`loops`). The jump is
170    /// lowered as an error expression. PHP: "'break' operator accepts only
171    /// positive integers", "Cannot 'break' 2 levels".
172    ///
173    /// ```
174    /// use lower_lang::ProblemKind;
175    ///
176    /// let p = ProblemKind::BreakLevel { level: 3, loops: 2 };
177    /// assert_eq!(p.to_string(), "cannot break or continue 3 levels: only 2 loops enclose it");
178    /// ```
179    BreakLevel {
180        /// The level written (`0`: not a positive integer literal; levels
181        /// beyond `u64` saturate).
182        level: u64,
183        /// The loops around the jump in its function.
184        loops: u32,
185    },
186    /// The implicit receiver
187    /// ([`LangPolicy::implicit_receiver`](crate::LangPolicy::implicit_receiver),
188    /// PHP's `$this`) read inside a `static` closure, or a closure nested in
189    /// one, where PHP has no `$this` ("Using $this when not in object
190    /// context"). Lowered as written; the problem keeps the closure from
191    /// silently capturing the method's receiver.
192    NoReceiver,
193}
194
195/// Why a binding could not be hoisted to its function.
196///
197/// # Examples
198///
199/// ```
200/// use lower_lang::{HoistBlocker, ProblemKind};
201///
202/// let p = ProblemKind::CannotHoist { reason: HoistBlocker::ByReference };
203/// assert_eq!(
204///     p.to_string(),
205///     "this binding cannot be function-scoped: a by-reference binding would become a copy"
206/// );
207/// ```
208#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
209#[non_exhaustive]
210pub enum HoistBlocker {
211    /// A by-reference binding (`&$v`, `ref x`): hoisting assigns a copy, so
212    /// the function-scoped variable would not alias.
213    ByReference,
214    /// A template uses the pattern hole more than once, so one binding would
215    /// be assigned from several places.
216    ReusedHole,
217    /// The template never binds the pattern hole in a `match` arm or a
218    /// `let` (its expansion was cut short), so nothing assigns the binding.
219    NoBindingSite,
220}
221
222impl fmt::Display for HoistBlocker {
223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224        f.write_str(match self {
225            Self::ByReference => "a by-reference binding would become a copy",
226            Self::ReusedHole => "the template binds this pattern in more than one place",
227            Self::NoBindingSite => "the template never binds this pattern",
228        })
229    }
230}
231
232impl fmt::Display for ProblemKind {
233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234        match self {
235            Self::SyntaxError => f.write_str("syntax error"),
236            Self::Unmapped => {
237                f.write_str("the language's semantics do not describe this construct")
238            }
239            Self::Unsupported => f.write_str("this construct is not supported yet"),
240            Self::NotAllowedHere { expected } => write!(f, "expected {expected} here"),
241            Self::MissingField { field } => write!(f, "missing {field}"),
242            Self::AmbiguousChild => {
243                f.write_str("one part fills two roles here; a part is probably missing")
244            }
245            Self::UnknownOperator => f.write_str("unknown operator"),
246            Self::UnknownLabel => f.write_str("no enclosing loop or block has this label"),
247            Self::InvalidLiteral => f.write_str("invalid literal"),
248            Self::InvalidEscape => f.write_str("invalid escape sequence"),
249            Self::BadSpan => f.write_str("token span lies outside the source"),
250            Self::MissingHole { template } => {
251                write!(f, "missing a part template {} needs", template.index())
252            }
253            Self::ExpansionTooDeep { template } => write!(
254                f,
255                "template {} is nested too deeply to expand",
256                template.index()
257            ),
258            Self::CannotHoist { reason } => {
259                write!(f, "this binding cannot be function-scoped: {reason}")
260            }
261            Self::AttributeArgument => f.write_str(
262                "an attribute argument must be a literal or a name; this one is left out",
263            ),
264            Self::MisplacedAttribute => {
265                f.write_str("nothing here can carry an attribute; it is dropped")
266            }
267            Self::Hir(e) => write!(f, "{e}"),
268            Self::BreakLevel { level: 0, .. } => {
269                f.write_str("a break or continue level must be a positive integer literal")
270            }
271            Self::BreakLevel { level, loops: 0 } => write!(
272                f,
273                "cannot break or continue {level} levels: no loop encloses it in this function"
274            ),
275            Self::BreakLevel { level, loops: 1 } => write!(
276                f,
277                "cannot break or continue {level} levels: only 1 loop encloses it"
278            ),
279            Self::BreakLevel { level, loops } => write!(
280                f,
281                "cannot break or continue {level} levels: only {loops} loops enclose it"
282            ),
283            Self::NoReceiver => f.write_str(
284                "the receiver is not available here: a static closure (and any closure inside one) has none",
285            ),
286        }
287    }
288}
289
290/// One problem, at the source span it is about.
291///
292/// # Examples
293///
294/// ```
295/// use lower_lang::{Problem, ProblemKind, Span};
296///
297/// let p = Problem { kind: ProblemKind::UnknownOperator, span: Span::new(4, 5) };
298/// assert_eq!(p.to_string(), "4..5: unknown operator");
299/// ```
300#[derive(Clone, Copy, Debug, PartialEq, Eq)]
301pub struct Problem {
302    /// What is wrong.
303    pub kind: ProblemKind,
304    /// Where, in the syntax tree's source.
305    pub span: Span,
306}
307
308impl fmt::Display for Problem {
309    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310        write!(
311            f,
312            "{}..{}: {}",
313            self.span.start().to_u32(),
314            self.span.end().to_u32(),
315            self.kind
316        )
317    }
318}
319
320/// Why lowering stopped without a result. Problems in the code never stop it;
321/// only exhausted resources do.
322///
323/// # Examples
324///
325/// ```
326/// use lower_lang::LowerError;
327///
328/// let e = LowerError::NodeBudget { limit: 10 };
329/// assert_eq!(e.to_string(), "lowering would build more than 10 HIR nodes");
330/// ```
331#[derive(Clone, Copy, Debug, PartialEq, Eq)]
332#[non_exhaustive]
333pub enum LowerError {
334    /// Lowering would build more HIR nodes than
335    /// [`Budget::max_nodes`](crate::Budget). Raise the budget if the input is
336    /// trusted and genuinely that large; otherwise reject it.
337    NodeBudget {
338        /// The budget that was exceeded.
339        limit: u64,
340    },
341    /// The interner ran out of symbols. Use a fresh interner per session.
342    SymbolSpaceExhausted,
343    /// hir-lang refused the result without a repair (capacity exceeded). Split
344    /// the input.
345    Hir(HirError),
346}
347
348impl fmt::Display for LowerError {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        match self {
351            Self::NodeBudget { limit } => {
352                write!(f, "lowering would build more than {limit} HIR nodes")
353            }
354            Self::SymbolSpaceExhausted => f.write_str("the interner ran out of symbols"),
355            Self::Hir(e) => write!(f, "hir-lang refused the result: {e}"),
356        }
357    }
358}
359
360impl core::error::Error for LowerError {}