Skip to main content

yomi_core/
diag.rs

1//! Diagnostics (errors and warnings). Only codes and arguments; no message text.
2
3/// Severity.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
5pub enum Severity {
6    /// The script cannot run.
7    Error,
8    /// It can run, but there may be a mistake.
9    Warning,
10}
11
12/// A diagnostic code. `as_str` is the stable English name.
13#[non_exhaustive]
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum DiagCode {
16    /// An unexpected token. Argument `found`.
17    UnexpectedToken,
18    /// A string literal is not closed.
19    UnterminatedString,
20    /// An escape that cannot be used. Argument `found`.
21    InvalidEscape,
22    /// Cannot be read as a number. Argument `text`.
23    InvalidNumber,
24    /// There is a full-width space in code.
25    FullWidthSpace,
26    /// An undeclared name. Argument `name`, and `suggestions` if there are close names (up to 3, closest first).
27    UnknownName,
28    /// An unregistered command. Argument `name`, and `suggestions` if there are close names.
29    UnknownCommand,
30    /// A label that does not exist. Argument `name`, and `suggestions` if there are close names.
31    UnknownLabel,
32    /// An unknown type name. Argument `name`.
33    UnknownType,
34    /// Types do not match. Arguments `expected`, `found`.
35    TypeMismatch,
36    /// A condition is not `bool`. Argument `found`.
37    ConditionNotBool,
38    /// The number of arguments does not match. Arguments `name`, `expected`, `found`.
39    ArgCount,
40    /// There is no parameter with that name. Arguments `name` (what was called), `arg` (the parameter name).
41    UnknownArgument,
42    /// The same argument was passed twice. Arguments `name`, `arg`.
43    DuplicateArgument,
44    /// A parameter without a default value was not passed. Arguments `name`, `arg`.
45    MissingArgument,
46    /// Named arguments are not in declaration order. Arguments `name`, `arg`.
47    ArgumentOutOfOrder,
48    /// A positional argument was written after a named argument. Argument `name`.
49    PositionalAfterNamed,
50    /// A parameter without a default value was declared after one with a default value. Arguments `name`, `arg`.
51    RequiredAfterDefault,
52    /// Names collide. Argument `name`.
53    DuplicateName,
54    /// A stable ID collides within the same label. Argument `id`.
55    DuplicateStableId,
56    /// The form of a stable ID is invalid. Argument `id`.
57    InvalidStableId,
58    /// A sugar is not bound. Argument `kind`.
59    UnboundSugar,
60    /// A block is not closed.
61    UnterminatedBlock,
62    /// A `}` without a matching opening.
63    UnexpectedClose,
64    /// An `else` without an `if`.
65    ElseWithoutIf,
66    /// There is a statement or text outside a label.
67    StatementOutsideLabel,
68    /// An initial value that is not a constant.
69    NotConstant,
70    /// Syntax that is not implemented yet (but is in the spec). Argument `what` (a call of a name that cannot be called,
71    /// `call`; a postfix call, `postfix expression`; the name of a return type that cannot be stored in a variable; and so on).
72    NotYetSupported,
73    /// Expressions are nested or chained too deeply. Argument `limit`.
74    TooDeep,
75    /// A line ends where more was expected.
76    UnexpectedEol,
77    /// Blocks are nested too deeply. Argument `limit`.
78    BlockTooDeep,
79    /// One label or `fn` uses too many registers (local variables and temporaries) (the register backend). Argument `limit`.
80    TooManyRegisters,
81    /// An operation that cannot be used on this type. Arguments `op` (the operator, such as `+`, `<`, `-`, `+=`), `type`
82    /// (the type of the operand).
83    InvalidOperation,
84    /// A declaration that cannot be written inside a label (such as `save var`). Argument `what` (the first word).
85    DeclarationNotAllowed,
86    /// `break` / `continue` outside a loop. Argument `what` (`break` or `continue`).
87    OutsideLoop,
88    /// A variable was declared with the same name as a built-in function (warning). Argument `name`.
89    ShadowedBuiltin,
90    /// An `import` is written after other declarations.
91    ImportNotFirst,
92    /// A module that does not exist. Argument `name`, and `suggestions` if there are close names (up to 3, closest first).
93    UnknownModule,
94    /// A module that is not `import`ed was used. Argument `name`.
95    ModuleNotImported,
96    /// Module names collide. Argument `name`.
97    DuplicateModule,
98    /// A module name is not a valid identifier. Argument `name`.
99    InvalidModuleName,
100    /// An alias was given with `as` to the `import` of a package. Argument `name` (the package name).
101    PackageAlias,
102    /// A name used by an `import` collides with a name already `import`ed (an alias can be given with `as`). Argument `name`.
103    DuplicateImport,
104    /// `import`ed but not used (warning). Argument `name` (the path written in the `import`).
105    UnusedImport,
106    /// A local variable declared with `let` is never read (warning). Argument `name`.
107    UnusedVariable,
108    /// A `jump` to a label that has parameters or a return type (it can only be called with `call`). Argument `name`.
109    JumpToCallableLabel,
110    /// A `jump` inside a label that has a return type (it could no longer return a value to the caller). Argument `name`
111    /// (the name of that label).
112    JumpInReturningLabel,
113    /// A `call` in the middle of an expression (it can only be written on the right-hand side of `let` or `=`, or as a
114    /// statement).
115    CallInExpression,
116    /// Tried to receive the value of a label that has no return type. Argument `name`.
117    CallWithoutValue,
118    /// A label with a return type may reach its end without `return`. Argument `name`.
119    MissingReturn,
120    /// A `return` without a value in a label with a return type. Argument `expected` (the type name).
121    MissingReturnValue,
122    /// A `return` with a value in a label without a return type.
123    UnexpectedReturnValue,
124    /// A label that is never `call`ed and does not end with `jump` / `return` / `end` (warning). Argument `name`.
125    LabelFallsThrough,
126    /// The `「` of a quote line or an option is not closed by `」` (quote lines with an identity, and option texts).
127    UnterminatedQuote,
128    /// A bracket of an expression is not closed by the end of the file or the limit of continuation lines. Argument `open`.
129    UnclosedBracket,
130    /// In a quote line with an identity, characters other than spaces and a stable ID follow `」`.
131    TextAfterQuote,
132    /// An option with `once` has no stable ID.
133    OnceWithoutId,
134    /// A `choice` with no options.
135    EmptyChoice,
136    /// A versioned name (`v2::…`) written outside the `migrations` module. Argument `name`.
137    SchemaNameOutsideMigrations,
138    /// A frozen schema file with a wrong file name or header. Argument `path`.
139    InvalidSchemaFile,
140    /// The content of a frozen schema does not match its recorded hash. Argument `version`.
141    SchemaHashMismatch,
142    /// Two `migrate` blocks of the same version. Argument `version`.
143    DuplicateMigrate,
144    /// A `migrate` version below 2. Argument `version`.
145    InvalidMigrateVersion,
146    /// A wrong `min_save_version` (out of range, repeated, not first). Argument `version`.
147    InvalidMinSaveVersion,
148    /// A name not in the schema of that version. Arguments `name`, `version`, and `suggestions` if there are close names.
149    UnknownSchemaName,
150    /// A `rename` between a `save var` and a `persistent var`. Argument `name`.
151    MigrateKindMismatch,
152    /// A written type differs from the schema's type. Arguments `name`, `expected`, `found`.
153    MigrateTypeMismatch,
154    /// The same variable handled twice in one `migrate`. Argument `name`.
155    DuplicateMigrateTarget,
156    /// Something not allowed in a conversion expression. Argument `what`.
157    MigrateImpureExpr,
158    /// A needed frozen schema is missing. Argument `version`.
159    MissingFrozenSchema,
160    /// A needed `migrate` block is missing. Argument `version`.
161    MissingMigrate,
162    /// A variable whose type changed is not handled by `migrate` (warning). Arguments `name`, `version`.
163    UnhandledTypeChange,
164    /// The schema changed after the latest freeze but there is no newer `migrate` (warning). Argument `version`.
165    SchemaChangedSinceFreeze,
166    /// An identity with the same name exists in multiple `import`ed modules. Arguments `name`, `candidates` (a list of
167    /// `module.name`).
168    AmbiguousIdentity,
169    /// A plain line where an undeclared name is followed by `「`, and there is an identity with a close spelling (warning).
170    /// Arguments `name`, `suggestions`.
171    IdentityTypo,
172    /// The string literal passed to `seen` is not the position of an existing stop point (warning). Argument `position`.
173    UnknownPosition,
174    /// The string literal passed to `visited` is not an existing label (warning). Argument `label`.
175    UnknownLabelLiteral,
176    /// A use that does not fit the kind of command (an effect or stop command called inside an expression, a query command
177    /// called as an `@` statement, an `@` call in the middle of an expression, or an `@` call of a command returning `()` or of
178    /// a query command on the right-hand side of `let` or `=`).
179    /// Arguments `name` (the command name), `kind` (`effect`, `query`, `stop`).
180    InvalidCommandUse,
181    /// Assignment to a `read_only` variable. Argument `name` (`package.variable`).
182    AssignToReadOnly,
183    /// A `match` does not cover all values. Argument `missing` (a list of missing patterns, such as `None`, `Dir.South`,
184    /// `_`).
185    NonExhaustiveMatch,
186    /// An arm of a `match` is hidden by an earlier arm and is never chosen (warning).
187    UnreachablePattern,
188    /// A field the type does not have. Arguments `name` (the field name), `type` (the type name), and `suggestions` if there
189    /// are close names.
190    UnknownField,
191    /// A variant the type does not have. Arguments `name` (the variant name), `type` (the type name), and `suggestions` if
192    /// there are close names.
193    UnknownVariant,
194    /// A struct literal is missing a field. Arguments `name` (the field name), `type` (the type name).
195    MissingField,
196    /// The same field is written twice (in a struct declaration or literal). Argument `name`.
197    DuplicateField,
198    /// A type that contains itself (directly or through other types). Argument `name` (the type name).
199    RecursiveType,
200    /// An expression whose type cannot be decided (`[]` or `None` without a type annotation). Add a type annotation
201    /// (`let xs: list<int> = []`).
202    CannotInferType,
203    /// A method the type does not have. Arguments `name` (the method name), `type` (the name of the receiver's type).
204    UnknownMethod,
205    /// A method that updates a variable (`push`, `remove`, `clear`) was called inside an expression. Write it as a statement.
206    /// Argument `name`.
207    StatementMethodInExpression,
208    /// A `list` method that needs ordered or summable elements (`sort`, `sort_by`, `min_by`, `max_by`, `sum`) was used with a
209    /// type that is not `int`, `float`, `str` or `bool` (`sum`: `int` or `float`). Arguments `method` and `type` (the type of
210    /// the elements, or of the keys for `sort_by`, `min_by` and `max_by`).
211    UnsupportedElementType,
212    /// A type that cannot be a `map` key (`float`, `list`, `map`, `Option`, and `struct`s and `enum`s containing them).
213    /// Argument `type` (the name of the type written as the key).
214    InvalidMapKey,
215    /// A statement that cannot be written inside a `fn` (quote lines, plain lines, `choice`, `jump`, `call`, `end`, and
216    /// effect and stop commands). Argument `what` (`plain`, `quote`, `choice`, `jump`, `call`, `end`; for commands, the name
217    /// with `@`, such as `@audio.play`).
218    NotAllowedInFn,
219    /// Tried to write to a `save var`, a `persistent var` or a host-declared variable inside a `fn` (reading is fine).
220    /// Argument `name` (the name of the written variable; variables of other modules are `module.name`).
221    AssignInFn,
222    /// An undeclared `fn` (a call `name(...)`, `module.name(...)` or `@name(...)`). Argument `name`, and `suggestions` if
223    /// there are close names (up to 3, closest first).
224    UnknownFunction,
225    /// A text line (plain line, quote line or option text) without a stable ID while `CompileOptions::require_text_ids` is
226    /// enabled. Argument `kind` (`plain`, `quote`, `choice`).
227    MissingTextId,
228    /// A command was called by an old name (alias) (warning). Arguments `name` (the old name written), `new` (the current
229    /// name).
230    DeprecatedCommandName,
231    /// Tried to put a value containing a function type in a place that goes into saves. Arguments `type` (the type name),
232    /// `what` (`var`: `save var` or `persistent var`; `field`: a field or argument of a `struct` or `enum`; `stop`: a local
233    /// variable that lives across a stop point; `call`: a local variable that lives across a `call`; `repl`: a REPL `let`).
234    FnNotSaveable,
235    /// Something that cannot be written in REPL input (section 7.7 of `spec/host/07-repl.md`). Argument `what` (`stable_id`,
236    /// `once`, `save`, `persistent`, `label`, `jump`, `end`, `return` (outside a `fn`)).
237    ReplNotAllowed,
238}
239
240impl DiagCode {
241    /// All codes (used to check that translation keys are complete).
242    pub const ALL: &'static [DiagCode] = &[
243        DiagCode::UnexpectedToken,
244        DiagCode::UnterminatedString,
245        DiagCode::InvalidEscape,
246        DiagCode::InvalidNumber,
247        DiagCode::FullWidthSpace,
248        DiagCode::UnknownName,
249        DiagCode::UnknownCommand,
250        DiagCode::UnknownLabel,
251        DiagCode::UnknownType,
252        DiagCode::TypeMismatch,
253        DiagCode::ConditionNotBool,
254        DiagCode::ArgCount,
255        DiagCode::UnknownArgument,
256        DiagCode::DuplicateArgument,
257        DiagCode::MissingArgument,
258        DiagCode::ArgumentOutOfOrder,
259        DiagCode::PositionalAfterNamed,
260        DiagCode::RequiredAfterDefault,
261        DiagCode::DuplicateName,
262        DiagCode::DuplicateStableId,
263        DiagCode::InvalidStableId,
264        DiagCode::UnboundSugar,
265        DiagCode::UnterminatedBlock,
266        DiagCode::UnexpectedClose,
267        DiagCode::ElseWithoutIf,
268        DiagCode::StatementOutsideLabel,
269        DiagCode::NotConstant,
270        DiagCode::NotYetSupported,
271        DiagCode::TooDeep,
272        DiagCode::UnexpectedEol,
273        DiagCode::BlockTooDeep,
274        DiagCode::TooManyRegisters,
275        DiagCode::InvalidOperation,
276        DiagCode::DeclarationNotAllowed,
277        DiagCode::OutsideLoop,
278        DiagCode::ShadowedBuiltin,
279        DiagCode::ImportNotFirst,
280        DiagCode::UnknownModule,
281        DiagCode::ModuleNotImported,
282        DiagCode::DuplicateModule,
283        DiagCode::InvalidModuleName,
284        DiagCode::PackageAlias,
285        DiagCode::DuplicateImport,
286        DiagCode::UnusedImport,
287        DiagCode::UnusedVariable,
288        DiagCode::JumpToCallableLabel,
289        DiagCode::JumpInReturningLabel,
290        DiagCode::CallInExpression,
291        DiagCode::CallWithoutValue,
292        DiagCode::MissingReturn,
293        DiagCode::MissingReturnValue,
294        DiagCode::UnexpectedReturnValue,
295        DiagCode::LabelFallsThrough,
296        DiagCode::UnterminatedQuote,
297        DiagCode::UnclosedBracket,
298        DiagCode::TextAfterQuote,
299        DiagCode::OnceWithoutId,
300        DiagCode::EmptyChoice,
301        DiagCode::SchemaNameOutsideMigrations,
302        DiagCode::InvalidSchemaFile,
303        DiagCode::SchemaHashMismatch,
304        DiagCode::DuplicateMigrate,
305        DiagCode::InvalidMigrateVersion,
306        DiagCode::InvalidMinSaveVersion,
307        DiagCode::UnknownSchemaName,
308        DiagCode::MigrateKindMismatch,
309        DiagCode::MigrateTypeMismatch,
310        DiagCode::DuplicateMigrateTarget,
311        DiagCode::MigrateImpureExpr,
312        DiagCode::MissingFrozenSchema,
313        DiagCode::MissingMigrate,
314        DiagCode::UnhandledTypeChange,
315        DiagCode::SchemaChangedSinceFreeze,
316        DiagCode::AmbiguousIdentity,
317        DiagCode::IdentityTypo,
318        DiagCode::UnknownPosition,
319        DiagCode::UnknownLabelLiteral,
320        DiagCode::InvalidCommandUse,
321        DiagCode::AssignToReadOnly,
322        DiagCode::NonExhaustiveMatch,
323        DiagCode::UnreachablePattern,
324        DiagCode::UnknownField,
325        DiagCode::UnknownVariant,
326        DiagCode::MissingField,
327        DiagCode::DuplicateField,
328        DiagCode::RecursiveType,
329        DiagCode::CannotInferType,
330        DiagCode::UnknownMethod,
331        DiagCode::StatementMethodInExpression,
332        DiagCode::UnsupportedElementType,
333        DiagCode::InvalidMapKey,
334        DiagCode::NotAllowedInFn,
335        DiagCode::AssignInFn,
336        DiagCode::UnknownFunction,
337        DiagCode::MissingTextId,
338        DiagCode::DeprecatedCommandName,
339        DiagCode::ReplNotAllowed,
340        DiagCode::FnNotSaveable,
341    ];
342
343    /// The severity of this code (codes other than warnings are errors).
344    pub fn severity(self) -> Severity {
345        match self {
346            DiagCode::IdentityTypo
347            | DiagCode::UnknownPosition
348            | DiagCode::UnknownLabelLiteral
349            | DiagCode::UnreachablePattern
350            | DiagCode::ShadowedBuiltin
351            | DiagCode::LabelFallsThrough
352            | DiagCode::UnusedImport
353            | DiagCode::UnusedVariable
354            | DiagCode::UnhandledTypeChange
355            | DiagCode::SchemaChangedSinceFreeze
356            | DiagCode::DeprecatedCommandName => Severity::Warning,
357            _ => Severity::Error,
358        }
359    }
360
361    /// The argument names that diagnostics with this code have (the public specification of diagnostics; `suggestions` is
362    /// present only when there are close names).
363    pub fn arg_names(self) -> &'static [&'static str] {
364        match self {
365            DiagCode::UnexpectedToken | DiagCode::InvalidEscape => &["found"],
366            DiagCode::InvalidNumber => &["text"],
367            DiagCode::UnknownName
368            | DiagCode::UnknownFunction
369            | DiagCode::UnknownCommand
370            | DiagCode::UnknownLabel
371            | DiagCode::UnknownModule => &["name", "suggestions"],
372            DiagCode::UnknownField | DiagCode::UnknownVariant | DiagCode::UnknownMethod => {
373                &["name", "type", "suggestions"]
374            }
375            DiagCode::IdentityTypo => &["name", "suggestions"],
376            DiagCode::UnknownType
377            | DiagCode::DuplicateName
378            | DiagCode::DuplicateField
379            | DiagCode::RecursiveType
380            | DiagCode::StatementMethodInExpression
381            | DiagCode::ModuleNotImported
382            | DiagCode::DuplicateModule
383            | DiagCode::InvalidModuleName
384            | DiagCode::PackageAlias
385            | DiagCode::DuplicateImport
386            | DiagCode::UnusedImport
387            | DiagCode::UnusedVariable
388            | DiagCode::JumpToCallableLabel
389            | DiagCode::JumpInReturningLabel
390            | DiagCode::CallWithoutValue
391            | DiagCode::MissingReturn
392            | DiagCode::AssignToReadOnly
393            | DiagCode::AssignInFn
394            | DiagCode::ShadowedBuiltin
395            | DiagCode::LabelFallsThrough => &["name"],
396            DiagCode::SchemaNameOutsideMigrations
397            | DiagCode::MigrateKindMismatch
398            | DiagCode::DuplicateMigrateTarget => &["name"],
399            DiagCode::InvalidSchemaFile => &["path"],
400            DiagCode::SchemaHashMismatch
401            | DiagCode::DuplicateMigrate
402            | DiagCode::InvalidMigrateVersion
403            | DiagCode::InvalidMinSaveVersion
404            | DiagCode::MissingFrozenSchema
405            | DiagCode::MissingMigrate
406            | DiagCode::SchemaChangedSinceFreeze => &["version"],
407            DiagCode::UnknownSchemaName => &["name", "version", "suggestions"],
408            DiagCode::MigrateTypeMismatch => &["name", "expected", "found"],
409            DiagCode::MigrateImpureExpr => &["what"],
410            DiagCode::UnclosedBracket => &["open"],
411            DiagCode::UnhandledTypeChange => &["name", "version"],
412            DiagCode::MissingField => &["name", "type"],
413            DiagCode::UnsupportedElementType => &["method", "type"],
414            DiagCode::NonExhaustiveMatch => &["missing"],
415            DiagCode::TypeMismatch => &["expected", "found"],
416            DiagCode::ConditionNotBool => &["found"],
417            DiagCode::ArgCount => &["name", "expected", "found"],
418            DiagCode::UnknownArgument
419            | DiagCode::DuplicateArgument
420            | DiagCode::MissingArgument
421            | DiagCode::ArgumentOutOfOrder
422            | DiagCode::RequiredAfterDefault => &["name", "arg"],
423            DiagCode::PositionalAfterNamed => &["name"],
424            DiagCode::InvalidOperation => &["op", "type"],
425            DiagCode::DuplicateStableId | DiagCode::InvalidStableId => &["id"],
426            DiagCode::UnboundSugar | DiagCode::MissingTextId => &["kind"],
427            DiagCode::InvalidCommandUse => &["name", "kind"],
428            DiagCode::DeclarationNotAllowed
429            | DiagCode::OutsideLoop
430            | DiagCode::NotAllowedInFn
431            | DiagCode::ReplNotAllowed
432            | DiagCode::NotYetSupported => &["what"],
433            DiagCode::InvalidMapKey => &["type"],
434            DiagCode::FnNotSaveable => &["type", "what"],
435            DiagCode::TooDeep | DiagCode::BlockTooDeep | DiagCode::TooManyRegisters => &["limit"],
436            DiagCode::MissingReturnValue => &["expected"],
437            DiagCode::AmbiguousIdentity => &["name", "candidates"],
438            DiagCode::UnknownPosition => &["position"],
439            DiagCode::UnknownLabelLiteral => &["label"],
440            DiagCode::DeprecatedCommandName => &["name", "new"],
441            DiagCode::UnterminatedString
442            | DiagCode::FullWidthSpace
443            | DiagCode::UnterminatedBlock
444            | DiagCode::UnexpectedClose
445            | DiagCode::ElseWithoutIf
446            | DiagCode::StatementOutsideLabel
447            | DiagCode::NotConstant
448            | DiagCode::UnexpectedEol
449            | DiagCode::ImportNotFirst
450            | DiagCode::CallInExpression
451            | DiagCode::UnexpectedReturnValue
452            | DiagCode::UnterminatedQuote
453            | DiagCode::TextAfterQuote
454            | DiagCode::OnceWithoutId
455            | DiagCode::EmptyChoice
456            | DiagCode::UnreachablePattern
457            | DiagCode::CannotInferType => &[],
458        }
459    }
460
461    /// The stable English name.
462    pub fn as_str(self) -> &'static str {
463        match self {
464            DiagCode::UnexpectedToken => "unexpected_token",
465            DiagCode::UnterminatedString => "unterminated_string",
466            DiagCode::InvalidEscape => "invalid_escape",
467            DiagCode::InvalidNumber => "invalid_number",
468            DiagCode::FullWidthSpace => "full_width_space",
469            DiagCode::UnknownName => "unknown_name",
470            DiagCode::UnknownCommand => "unknown_command",
471            DiagCode::UnknownLabel => "unknown_label",
472            DiagCode::UnknownType => "unknown_type",
473            DiagCode::TypeMismatch => "type_mismatch",
474            DiagCode::ConditionNotBool => "condition_not_bool",
475            DiagCode::ArgCount => "arg_count",
476            DiagCode::UnknownArgument => "unknown_argument",
477            DiagCode::DuplicateArgument => "duplicate_argument",
478            DiagCode::MissingArgument => "missing_argument",
479            DiagCode::ArgumentOutOfOrder => "argument_out_of_order",
480            DiagCode::PositionalAfterNamed => "positional_after_named",
481            DiagCode::RequiredAfterDefault => "required_after_default",
482            DiagCode::DuplicateName => "duplicate_name",
483            DiagCode::DuplicateStableId => "duplicate_stable_id",
484            DiagCode::InvalidStableId => "invalid_stable_id",
485            DiagCode::UnboundSugar => "unbound_sugar",
486            DiagCode::UnterminatedBlock => "unterminated_block",
487            DiagCode::UnexpectedClose => "unexpected_close",
488            DiagCode::ElseWithoutIf => "else_without_if",
489            DiagCode::StatementOutsideLabel => "statement_outside_label",
490            DiagCode::NotConstant => "not_constant",
491            DiagCode::NotYetSupported => "not_yet_supported",
492            DiagCode::TooDeep => "too_deep",
493            DiagCode::UnexpectedEol => "unexpected_eol",
494            DiagCode::BlockTooDeep => "block_too_deep",
495            DiagCode::TooManyRegisters => "too_many_registers",
496            DiagCode::InvalidOperation => "invalid_operation",
497            DiagCode::DeclarationNotAllowed => "declaration_not_allowed",
498            DiagCode::OutsideLoop => "outside_loop",
499            DiagCode::ShadowedBuiltin => "shadowed_builtin",
500            DiagCode::ImportNotFirst => "import_not_first",
501            DiagCode::UnknownModule => "unknown_module",
502            DiagCode::ModuleNotImported => "module_not_imported",
503            DiagCode::DuplicateModule => "duplicate_module",
504            DiagCode::InvalidModuleName => "invalid_module_name",
505            DiagCode::PackageAlias => "package_alias",
506            DiagCode::DuplicateImport => "duplicate_import",
507            DiagCode::UnusedImport => "unused_import",
508            DiagCode::UnusedVariable => "unused_variable",
509            DiagCode::JumpToCallableLabel => "jump_to_callable_label",
510            DiagCode::JumpInReturningLabel => "jump_in_returning_label",
511            DiagCode::CallInExpression => "call_in_expression",
512            DiagCode::CallWithoutValue => "call_without_value",
513            DiagCode::MissingReturn => "missing_return",
514            DiagCode::MissingReturnValue => "missing_return_value",
515            DiagCode::UnexpectedReturnValue => "unexpected_return_value",
516            DiagCode::LabelFallsThrough => "label_falls_through",
517            DiagCode::UnterminatedQuote => "unterminated_quote",
518            DiagCode::UnclosedBracket => "unclosed_bracket",
519            DiagCode::TextAfterQuote => "text_after_quote",
520            DiagCode::OnceWithoutId => "once_without_id",
521            DiagCode::SchemaNameOutsideMigrations => "schema_name_outside_migrations",
522            DiagCode::InvalidSchemaFile => "invalid_schema_file",
523            DiagCode::SchemaHashMismatch => "schema_hash_mismatch",
524            DiagCode::DuplicateMigrate => "duplicate_migrate",
525            DiagCode::InvalidMigrateVersion => "invalid_migrate_version",
526            DiagCode::InvalidMinSaveVersion => "invalid_min_save_version",
527            DiagCode::UnknownSchemaName => "unknown_schema_name",
528            DiagCode::MigrateKindMismatch => "migrate_kind_mismatch",
529            DiagCode::MigrateTypeMismatch => "migrate_type_mismatch",
530            DiagCode::DuplicateMigrateTarget => "duplicate_migrate_target",
531            DiagCode::MigrateImpureExpr => "migrate_impure_expr",
532            DiagCode::MissingFrozenSchema => "missing_frozen_schema",
533            DiagCode::MissingMigrate => "missing_migrate",
534            DiagCode::UnhandledTypeChange => "unhandled_type_change",
535            DiagCode::SchemaChangedSinceFreeze => "schema_changed_since_freeze",
536            DiagCode::EmptyChoice => "empty_choice",
537            DiagCode::AmbiguousIdentity => "ambiguous_identity",
538            DiagCode::IdentityTypo => "identity_typo",
539            DiagCode::UnknownPosition => "unknown_position",
540            DiagCode::UnknownLabelLiteral => "unknown_label_literal",
541            DiagCode::InvalidCommandUse => "invalid_command_use",
542            DiagCode::AssignToReadOnly => "assign_to_read_only",
543            DiagCode::NonExhaustiveMatch => "non_exhaustive_match",
544            DiagCode::UnreachablePattern => "unreachable_pattern",
545            DiagCode::UnknownField => "unknown_field",
546            DiagCode::UnknownVariant => "unknown_variant",
547            DiagCode::MissingField => "missing_field",
548            DiagCode::DuplicateField => "duplicate_field",
549            DiagCode::RecursiveType => "recursive_type",
550            DiagCode::CannotInferType => "cannot_infer_type",
551            DiagCode::UnknownMethod => "unknown_method",
552            DiagCode::StatementMethodInExpression => "statement_method_in_expression",
553            DiagCode::UnsupportedElementType => "unsupported_element_type",
554            DiagCode::InvalidMapKey => "invalid_map_key",
555            DiagCode::NotAllowedInFn => "not_allowed_in_fn",
556            DiagCode::AssignInFn => "assign_in_fn",
557            DiagCode::UnknownFunction => "unknown_function",
558            DiagCode::MissingTextId => "missing_text_id",
559            DiagCode::DeprecatedCommandName => "deprecated_command_name",
560            DiagCode::ReplNotAllowed => "repl_not_allowed",
561            DiagCode::FnNotSaveable => "fn_not_saveable",
562        }
563    }
564}
565
566/// The value of a diagnostic argument.
567#[derive(Debug, Clone, PartialEq, Eq)]
568pub enum DiagArg {
569    /// A string.
570    Str(String),
571    /// An integer.
572    Int(i64),
573    /// A list of strings (such as candidate close names, closest first).
574    List(Vec<String>),
575}
576
577impl From<&str> for DiagArg {
578    fn from(s: &str) -> Self {
579        DiagArg::Str(s.to_string())
580    }
581}
582
583impl From<String> for DiagArg {
584    fn from(s: String) -> Self {
585        DiagArg::Str(s)
586    }
587}
588
589impl From<i64> for DiagArg {
590    fn from(n: i64) -> Self {
591        DiagArg::Int(n)
592    }
593}
594
595impl From<usize> for DiagArg {
596    /// Values that do not fit in `i64` become `i64::MAX`.
597    fn from(n: usize) -> Self {
598        DiagArg::Int(i64::try_from(n).unwrap_or(i64::MAX))
599    }
600}
601
602/// Writes only the value in a human-readable form (strings as is, integers in decimal, lists separated by `,`). Not a
603/// message.
604impl std::fmt::Display for DiagArg {
605    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
606        match self {
607            DiagArg::Str(s) => write!(f, "{s}"),
608            DiagArg::Int(n) => write!(f, "{n}"),
609            DiagArg::List(l) => write!(f, "{}", l.join(",")),
610        }
611    }
612}
613
614/// One diagnostic.
615#[non_exhaustive]
616#[derive(Debug, Clone, PartialEq, Eq)]
617pub struct Diagnostic {
618    /// Module name.
619    pub module: String,
620    /// Line (1-based).
621    pub line: u32,
622    /// Column (1-based, in characters).
623    pub col: u32,
624    /// Severity.
625    pub severity: Severity,
626    /// Code.
627    pub code: DiagCode,
628    /// Named arguments determined by each code.
629    pub args: Vec<(&'static str, DiagArg)>,
630}
631
632impl Diagnostic {
633    /// Looks up an argument that is a list of strings.
634    pub fn arg_list(&self, name: &str) -> Option<&[String]> {
635        self.args.iter().find_map(|(n, v)| match v {
636            DiagArg::List(l) if *n == name => Some(l.as_slice()),
637            _ => None,
638        })
639    }
640
641    /// Looks up a string argument.
642    pub fn arg_str(&self, name: &str) -> Option<&str> {
643        self.args.iter().find_map(|(n, v)| match v {
644            DiagArg::Str(s) if *n == name => Some(s.as_str()),
645            _ => None,
646        })
647    }
648}