Skip to main content

yomi_core/
codes.rs

1//! The list of codes (used by `yomi codes` and to check against the list in `spec/language/06-diagnostics.md`).
2//!
3//! Lists the stable English names and argument names of compile diagnostics ([`DiagCode`]), as well as runtime errors,
4//! load errors, text table errors and check results, and declaration file errors.
5
6use crate::diag::{DiagCode, Severity};
7
8/// A group of codes (corresponds to the prefix of the FTL keys used to look up messages).
9#[non_exhaustive]
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum CodeGroup {
12    /// Compile diagnostics (`diag-`).
13    Diag,
14    /// Runtime errors (`vm-`).
15    Vm,
16    /// Load errors (`load-`).
17    Load,
18    /// Text table errors (`text-error-`).
19    TextError,
20    /// Results of checking a text table against the scripts (`text-issue-`).
21    TextIssue,
22    /// Declaration file errors (`decl-error-`).
23    DeclError,
24}
25
26impl CodeGroup {
27    /// All groups.
28    pub const ALL: &'static [CodeGroup] = &[
29        CodeGroup::Diag,
30        CodeGroup::Vm,
31        CodeGroup::Load,
32        CodeGroup::TextError,
33        CodeGroup::TextIssue,
34        CodeGroup::DeclError,
35    ];
36
37    /// The name of the group (`group` in `yomi codes --json`).
38    pub fn name(self) -> &'static str {
39        match self {
40            CodeGroup::Diag => "diag",
41            CodeGroup::Vm => "vm",
42            CodeGroup::Load => "load",
43            CodeGroup::TextError => "text-error",
44            CodeGroup::TextIssue => "text-issue",
45            CodeGroup::DeclError => "decl-error",
46        }
47    }
48
49    /// The prefix of the message (FTL) keys (such as `diag-`; the code follows it).
50    pub fn ftl_prefix(self) -> &'static str {
51        match self {
52            CodeGroup::Diag => "diag-",
53            CodeGroup::Vm => "vm-",
54            CodeGroup::Load => "load-",
55            CodeGroup::TextError => "text-error-",
56            CodeGroup::TextIssue => "text-issue-",
57            CodeGroup::DeclError => "decl-error-",
58        }
59    }
60}
61
62/// The public specification of one code.
63#[non_exhaustive]
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct CodeInfo {
66    /// Group.
67    pub group: CodeGroup,
68    /// The stable English name.
69    pub code: &'static str,
70    /// Argument names (`suggestions` of a diagnostic is present only when there are close names).
71    pub args: &'static [&'static str],
72    /// Severity.
73    pub severity: Severity,
74}
75
76/// The code and arguments of a runtime error ([`crate::VmErrorKind`]).
77pub(crate) const VM_CODES: &[(&str, &[&str])] = &[
78    ("step_limit_exceeded", &[]),
79    ("interrupted", &[]),
80    ("call_depth_exceeded", &[]),
81    ("value_too_large", &[]),
82    ("memory_limit_exceeded", &[]),
83    ("index_out_of_range", &["index", "len"]),
84    ("key_not_found", &["key"]),
85    ("integer_overflow", &[]),
86    ("division_by_zero", &[]),
87    ("non_finite_float", &[]),
88    ("float_out_of_range", &[]),
89    ("not_stopped", &[]),
90    ("already_stopped", &[]),
91    ("ended", &[]),
92    ("no_choice_available", &[]),
93    ("choice_out_of_range", &["index", "count"]),
94    ("poisoned", &[]),
95    ("persistent_data", &["reason"]),
96    ("invalid_random_range", &["min", "max"]),
97    ("snapshot_mismatch", &[]),
98    ("bad_input", &["expected", "found"]),
99    ("start_label_not_found", &["name"]),
100    ("command_missing", &["name"]),
101    ("command_failed", &["code"]),
102    ("unknown_variable", &["name"]),
103    ("slice_serialize", &["name"]),
104    ("decl_only_registry", &[]),
105];
106
107/// One error code of a command (decided by the package; [`crate::CommandError::with_code`]).
108#[non_exhaustive]
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub struct ErrorCodeInfo {
111    /// The stable English name, in the form `package.error_name`.
112    pub code: &'static str,
113    /// Argument names.
114    pub args: &'static [&'static str],
115}
116
117impl ErrorCodeInfo {
118    /// Makes one from a code and argument names (used when writing a package's list of codes).
119    pub const fn new(code: &'static str, args: &'static [&'static str]) -> Self {
120        Self { code, args }
121    }
122}
123
124/// Codes that the core returns as `CommandFailed` (errors in the core's mechanisms; bugs in the host's implementation).
125const CORE_COMMAND_ERRORS: &[ErrorCodeInfo] = &[
126    ErrorCodeInfo::new("core.state_type_mismatch", &["package"]),
127    ErrorCodeInfo::new("core.persistent_type_mismatch", &["package"]),
128    ErrorCodeInfo::new("core.dep_not_declared", &["package", "dep"]),
129    ErrorCodeInfo::new("core.dep_not_registered", &["dep"]),
130    ErrorCodeInfo::new("core.dep_is_self", &["package"]),
131    ErrorCodeInfo::new("core.bad_args", &["name"]),
132    ErrorCodeInfo::new("core.package_slice_missing", &[]),
133    ErrorCodeInfo::new("core.decl_only_function", &[]),
134];
135
136/// The list of codes the core returns as command failures (`VmErrorKind::CommandFailed`; codes start with `core.`).
137pub fn core_command_error_codes() -> &'static [ErrorCodeInfo] {
138    CORE_COMMAND_ERRORS
139}
140
141/// The code and arguments of a load error ([`crate::LoadErrorKind`]).
142pub(crate) const LOAD_CODES: &[(&str, &[&str])] = &[
143    ("bad_magic", &[]),
144    ("unsupported_version", &["version"]),
145    ("checksum_mismatch", &[]),
146    ("corrupt", &[]),
147    ("label_not_found", &["name"]),
148    ("module_mismatch", &["name"]),
149    ("command_missing", &["name"]),
150    ("stop_args_failed", &[]),
151    ("package_slice", &["name"]),
152    ("decl_only_registry", &[]),
153    ("save_from_newer_version", &["saved", "current"]),
154    ("save_version_unsupported", &["saved", "min"]),
155    ("schema_mismatch", &["vars"]),
156    ("migrate_failed", &["vars"]),
157];
158
159/// The code and arguments of a text table error ([`crate::TextErrorKind`]).
160pub(crate) const TEXT_ERROR_CODES: &[(&str, &[&str])] = &[
161    ("invalid_escape", &["found", "key"]),
162    ("invalid_placeholder", &["found", "key"]),
163    ("missing_tab", &[]),
164    ("empty_key", &[]),
165    ("duplicate_key", &["key"]),
166    ("unknown_directive", &["name"]),
167];
168
169/// The code, arguments and severity of a check result ([`crate::TextIssueKind`]).
170pub(crate) const TEXT_ISSUE_CODES: &[(&str, &[&str], Severity)] = &[
171    ("missing", &["key"], Severity::Warning),
172    ("unused", &["key"], Severity::Warning),
173    ("bad_number", &["key", "number", "count"], Severity::Error),
174];
175
176/// The code and arguments of a declaration file error ([`crate::DeclErrorKind`]).
177pub(crate) const DECL_ERROR_CODES: &[(&str, &[&str])] = &[
178    ("syntax", &["line", "col"]),
179    ("too_large", &[]),
180    ("too_deep", &[]),
181    ("not_decls", &[]),
182    ("unsupported_version", &["version"]),
183    ("missing_field", &[]),
184    ("wrong_type", &[]),
185    ("invalid_type", &["found"]),
186    ("invalid_value", &[]),
187    ("registry", &["reason"]),
188];
189
190/// The list of all codes (in group order; within a group, in definition order).
191pub fn all_codes() -> Vec<CodeInfo> {
192    let mut out = Vec::new();
193    for c in DiagCode::ALL {
194        out.push(CodeInfo {
195            group: CodeGroup::Diag,
196            code: c.as_str(),
197            args: c.arg_names(),
198            severity: c.severity(),
199        });
200    }
201    let plain = |group,
202                 table: &'static [(&'static str, &'static [&'static str])],
203                 out: &mut Vec<CodeInfo>| {
204        for (code, args) in table {
205            out.push(CodeInfo {
206                group,
207                code,
208                args,
209                severity: Severity::Error,
210            });
211        }
212    };
213    plain(CodeGroup::Vm, VM_CODES, &mut out);
214    plain(CodeGroup::Load, LOAD_CODES, &mut out);
215    plain(CodeGroup::TextError, TEXT_ERROR_CODES, &mut out);
216    for (code, args, severity) in TEXT_ISSUE_CODES {
217        out.push(CodeInfo {
218            group: CodeGroup::TextIssue,
219            code,
220            args,
221            severity: *severity,
222        });
223    }
224    plain(CodeGroup::DeclError, DECL_ERROR_CODES, &mut out);
225    out
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use crate::decls::DeclErrorKind;
232    use crate::registry::RegistryError;
233    use crate::texts::{TextErrorKind, TextIssueKind};
234    use crate::value::Ty;
235    use crate::vm::{LoadErrorKind, VmErrorKind};
236
237    fn s() -> String {
238        String::new()
239    }
240
241    /// Indices of samples (one per kind). Adding a kind makes this fail to compile unless it is covered here.
242    fn vm_index(k: &VmErrorKind) -> usize {
243        match k {
244            VmErrorKind::StepLimitExceeded => 0,
245            VmErrorKind::Interrupted => 1,
246            VmErrorKind::CallDepthExceeded => 2,
247            VmErrorKind::ValueTooLarge => 3,
248            VmErrorKind::MemoryLimitExceeded => 4,
249            VmErrorKind::IndexOutOfRange { .. } => 5,
250            VmErrorKind::KeyNotFound { .. } => 6,
251            VmErrorKind::IntegerOverflow => 7,
252            VmErrorKind::DivisionByZero => 8,
253            VmErrorKind::NonFiniteFloat => 9,
254            VmErrorKind::FloatOutOfRange => 10,
255            VmErrorKind::NotStopped => 11,
256            VmErrorKind::AlreadyStopped => 12,
257            VmErrorKind::Ended => 13,
258            VmErrorKind::NoChoiceAvailable => 14,
259            VmErrorKind::ChoiceOutOfRange { .. } => 15,
260            VmErrorKind::Poisoned => 16,
261            VmErrorKind::PersistentData(_) => 17,
262            VmErrorKind::InvalidRandomRange { .. } => 18,
263            VmErrorKind::SnapshotMismatch => 19,
264            VmErrorKind::BadInput { .. } => 20,
265            VmErrorKind::StartLabelNotFound(_) => 21,
266            VmErrorKind::CommandMissing(_) => 22,
267            VmErrorKind::CommandFailed { .. } => 23,
268            VmErrorKind::UnknownVariable(_) => 24,
269            VmErrorKind::SliceSerialize(_) => 25,
270            VmErrorKind::DeclOnlyRegistry => 26,
271        }
272    }
273
274    #[test]
275    fn runtime_error_list_matches_all_codes_in_order() {
276        let samples = [
277            VmErrorKind::StepLimitExceeded,
278            VmErrorKind::Interrupted,
279            VmErrorKind::CallDepthExceeded,
280            VmErrorKind::ValueTooLarge,
281            VmErrorKind::MemoryLimitExceeded,
282            VmErrorKind::IndexOutOfRange { index: 0, len: 0 },
283            VmErrorKind::KeyNotFound { key: s() },
284            VmErrorKind::IntegerOverflow,
285            VmErrorKind::DivisionByZero,
286            VmErrorKind::NonFiniteFloat,
287            VmErrorKind::FloatOutOfRange,
288            VmErrorKind::NotStopped,
289            VmErrorKind::AlreadyStopped,
290            VmErrorKind::Ended,
291            VmErrorKind::NoChoiceAvailable,
292            VmErrorKind::ChoiceOutOfRange { index: 0, count: 0 },
293            VmErrorKind::Poisoned,
294            VmErrorKind::PersistentData(LoadErrorKind::Corrupt),
295            VmErrorKind::InvalidRandomRange { min: 0, max: 0 },
296            VmErrorKind::SnapshotMismatch,
297            VmErrorKind::BadInput {
298                expected: Ty::Int,
299                found: Ty::Int,
300            },
301            VmErrorKind::StartLabelNotFound(s()),
302            VmErrorKind::CommandMissing(s()),
303            VmErrorKind::CommandFailed {
304                code: s(),
305                args: Vec::new(),
306            },
307            VmErrorKind::UnknownVariable(s()),
308            VmErrorKind::SliceSerialize(s()),
309            VmErrorKind::DeclOnlyRegistry,
310        ];
311        assert_eq!(samples.len(), VM_CODES.len());
312        for (i, k) in samples.iter().enumerate() {
313            assert_eq!(vm_index(k), i);
314            assert_eq!(k.code(), VM_CODES[i].0);
315        }
316    }
317
318    fn load_index(k: &LoadErrorKind) -> usize {
319        match k {
320            LoadErrorKind::BadMagic => 0,
321            LoadErrorKind::UnsupportedVersion(_) => 1,
322            LoadErrorKind::ChecksumMismatch => 2,
323            LoadErrorKind::Corrupt => 3,
324            LoadErrorKind::LabelNotFound(_) => 4,
325            LoadErrorKind::ModuleMismatch(_) => 5,
326            LoadErrorKind::CommandMissing(_) => 6,
327            LoadErrorKind::StopArgsFailed => 7,
328            LoadErrorKind::PackageSlice(_) => 8,
329            LoadErrorKind::DeclOnlyRegistry => 9,
330            LoadErrorKind::SaveFromNewerVersion { .. } => 10,
331            LoadErrorKind::SaveVersionUnsupported { .. } => 11,
332            LoadErrorKind::SchemaMismatch(_) => 12,
333            LoadErrorKind::MigrateFailed(_) => 13,
334        }
335    }
336
337    #[test]
338    fn load_error_list_matches_all_codes_in_order() {
339        let samples = [
340            LoadErrorKind::BadMagic,
341            LoadErrorKind::UnsupportedVersion(0),
342            LoadErrorKind::ChecksumMismatch,
343            LoadErrorKind::Corrupt,
344            LoadErrorKind::LabelNotFound(s()),
345            LoadErrorKind::ModuleMismatch(s()),
346            LoadErrorKind::CommandMissing(s()),
347            LoadErrorKind::StopArgsFailed,
348            LoadErrorKind::PackageSlice(s()),
349            LoadErrorKind::DeclOnlyRegistry,
350            LoadErrorKind::SaveFromNewerVersion {
351                saved: 0,
352                current: 0,
353            },
354            LoadErrorKind::SaveVersionUnsupported { saved: 0, min: 0 },
355            LoadErrorKind::SchemaMismatch(Vec::new()),
356            LoadErrorKind::MigrateFailed(Vec::new()),
357        ];
358        assert_eq!(samples.len(), LOAD_CODES.len());
359        for (i, k) in samples.iter().enumerate() {
360            assert_eq!(load_index(k), i);
361            assert_eq!(k.code(), LOAD_CODES[i].0);
362        }
363    }
364
365    fn text_error_index(k: &TextErrorKind) -> usize {
366        match k {
367            TextErrorKind::InvalidEscape { .. } => 0,
368            TextErrorKind::InvalidPlaceholder { .. } => 1,
369            TextErrorKind::MissingTab => 2,
370            TextErrorKind::EmptyKey => 3,
371            TextErrorKind::DuplicateKey => 4,
372            TextErrorKind::UnknownDirective { .. } => 5,
373        }
374    }
375
376    #[test]
377    fn text_table_error_list_matches_all_codes_in_order() {
378        let samples = [
379            TextErrorKind::InvalidEscape { found: s() },
380            TextErrorKind::InvalidPlaceholder { found: s() },
381            TextErrorKind::MissingTab,
382            TextErrorKind::EmptyKey,
383            TextErrorKind::DuplicateKey,
384            TextErrorKind::UnknownDirective { name: s() },
385        ];
386        assert_eq!(samples.len(), TEXT_ERROR_CODES.len());
387        for (i, k) in samples.iter().enumerate() {
388            assert_eq!(text_error_index(k), i);
389            assert_eq!(k.code(), TEXT_ERROR_CODES[i].0);
390        }
391    }
392
393    fn text_issue_index(k: &TextIssueKind) -> usize {
394        match k {
395            TextIssueKind::Missing => 0,
396            TextIssueKind::Unused => 1,
397            TextIssueKind::BadNumber { .. } => 2,
398        }
399    }
400
401    #[test]
402    fn match_result_list_has_same_codes_and_severities_for_all_kinds() {
403        let samples = [
404            TextIssueKind::Missing,
405            TextIssueKind::Unused,
406            TextIssueKind::BadNumber {
407                number: 1,
408                count: 0,
409            },
410        ];
411        assert_eq!(samples.len(), TEXT_ISSUE_CODES.len());
412        for (i, k) in samples.iter().enumerate() {
413            assert_eq!(text_issue_index(k), i);
414            assert_eq!(k.code(), TEXT_ISSUE_CODES[i].0);
415            assert_eq!(k.severity(), TEXT_ISSUE_CODES[i].2);
416        }
417    }
418
419    fn decl_index(k: &DeclErrorKind) -> usize {
420        match k {
421            DeclErrorKind::Syntax { .. } => 0,
422            DeclErrorKind::TooLarge => 1,
423            DeclErrorKind::TooDeep => 2,
424            DeclErrorKind::NotDecls => 3,
425            DeclErrorKind::UnsupportedVersion(_) => 4,
426            DeclErrorKind::MissingField => 5,
427            DeclErrorKind::WrongType => 6,
428            DeclErrorKind::InvalidType(_) => 7,
429            DeclErrorKind::InvalidValue => 8,
430            DeclErrorKind::Registry(_) => 9,
431        }
432    }
433
434    #[test]
435    fn declaration_file_error_list_matches_all_codes_in_order() {
436        let samples = [
437            DeclErrorKind::Syntax { line: 1, col: 1 },
438            DeclErrorKind::TooLarge,
439            DeclErrorKind::TooDeep,
440            DeclErrorKind::NotDecls,
441            DeclErrorKind::UnsupportedVersion(0),
442            DeclErrorKind::MissingField,
443            DeclErrorKind::WrongType,
444            DeclErrorKind::InvalidType(s()),
445            DeclErrorKind::InvalidValue,
446            DeclErrorKind::Registry(RegistryError::NoCommand),
447        ];
448        assert_eq!(samples.len(), DECL_ERROR_CODES.len());
449        for (i, k) in samples.iter().enumerate() {
450            assert_eq!(decl_index(k), i);
451            assert_eq!(k.code(), DECL_ERROR_CODES[i].0);
452        }
453    }
454
455    #[test]
456    fn diagnostic_codes_are_unique_and_names_are_lowercase_and_underscores() {
457        let all = all_codes();
458        for g in CodeGroup::ALL {
459            let mut seen = std::collections::HashSet::new();
460            for c in all.iter().filter(|c| c.group == *g) {
461                assert!(seen.insert(c.code), "{}: {} が重複", g.name(), c.code);
462                assert!(
463                    c.code
464                        .chars()
465                        .all(|ch| ch.is_ascii_lowercase() || ch == '_'),
466                    "{}",
467                    c.code
468                );
469            }
470        }
471        assert_eq!(
472            all.iter().filter(|c| c.group == CodeGroup::Diag).count(),
473            DiagCode::ALL.len()
474        );
475    }
476}