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 problem hir-lang's lenient validator found and repaired.
152 Hir(HirError),
153}
154
155impl fmt::Display for ProblemKind {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 match self {
158 Self::SyntaxError => f.write_str("syntax error"),
159 Self::Unmapped => {
160 f.write_str("the language's semantics do not describe this construct")
161 }
162 Self::Unsupported => f.write_str("this construct is not supported yet"),
163 Self::NotAllowedHere { expected } => write!(f, "expected {expected} here"),
164 Self::MissingField { field } => write!(f, "missing {field}"),
165 Self::AmbiguousChild => {
166 f.write_str("one part fills two roles here; a part is probably missing")
167 }
168 Self::UnknownOperator => f.write_str("unknown operator"),
169 Self::UnknownLabel => f.write_str("no enclosing loop or block has this label"),
170 Self::InvalidLiteral => f.write_str("invalid literal"),
171 Self::InvalidEscape => f.write_str("invalid escape sequence"),
172 Self::BadSpan => f.write_str("token span lies outside the source"),
173 Self::MissingHole { template } => {
174 write!(f, "missing a part template {} needs", template.index())
175 }
176 Self::ExpansionTooDeep { template } => write!(
177 f,
178 "template {} is nested too deeply to expand",
179 template.index()
180 ),
181 Self::Hir(e) => write!(f, "{e}"),
182 }
183 }
184}
185
186/// One problem, at the source span it is about.
187///
188/// # Examples
189///
190/// ```
191/// use lower_lang::{Problem, ProblemKind, Span};
192///
193/// let p = Problem { kind: ProblemKind::UnknownOperator, span: Span::new(4, 5) };
194/// assert_eq!(p.to_string(), "4..5: unknown operator");
195/// ```
196#[derive(Clone, Copy, Debug, PartialEq, Eq)]
197pub struct Problem {
198 /// What is wrong.
199 pub kind: ProblemKind,
200 /// Where, in the syntax tree's source.
201 pub span: Span,
202}
203
204impl fmt::Display for Problem {
205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206 write!(
207 f,
208 "{}..{}: {}",
209 self.span.start().to_u32(),
210 self.span.end().to_u32(),
211 self.kind
212 )
213 }
214}
215
216/// Why lowering stopped without a result. Problems in the code never stop it;
217/// only exhausted resources do.
218///
219/// # Examples
220///
221/// ```
222/// use lower_lang::LowerError;
223///
224/// let e = LowerError::NodeBudget { limit: 10 };
225/// assert_eq!(e.to_string(), "lowering would build more than 10 HIR nodes");
226/// ```
227#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228#[non_exhaustive]
229pub enum LowerError {
230 /// Lowering would build more HIR nodes than
231 /// [`Budget::max_nodes`](crate::Budget). Raise the budget if the input is
232 /// trusted and genuinely that large; otherwise reject it.
233 NodeBudget {
234 /// The budget that was exceeded.
235 limit: u64,
236 },
237 /// The interner ran out of symbols. Use a fresh interner per session.
238 SymbolSpaceExhausted,
239 /// hir-lang refused the result without a repair (capacity exceeded). Split
240 /// the input.
241 Hir(HirError),
242}
243
244impl fmt::Display for LowerError {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246 match self {
247 Self::NodeBudget { limit } => {
248 write!(f, "lowering would build more than {limit} HIR nodes")
249 }
250 Self::SymbolSpaceExhausted => f.write_str("the interner ran out of symbols"),
251 Self::Hir(e) => write!(f, "hir-lang refused the result: {e}"),
252 }
253 }
254}
255
256impl core::error::Error for LowerError {}