Skip to main content

mirascript_core/diagnostic/
diagnostic_code.rs

1use strum::{Display, EnumMessage, FromRepr, IntoStaticStr};
2
3/// Diagnostic codes for MiraScript compiler and tools.
4#[cfg_attr(feature = "wasm-constants", wasm_bindgen::prelude::wasm_bindgen)]
5#[derive(
6    Debug, Clone, Copy, PartialEq, PartialOrd, EnumMessage, FromRepr, Display, IntoStaticStr,
7)]
8#[repr(u16)]
9pub enum DiagnosticCode {
10    // Preserved 0~999
11
12    // Error 1000~1999
13    ErrorStart = 1000,
14
15    #[strum(message = "发生未知内部错误")]
16    InternalError,
17    #[strum(message = "发生未知词法错误")]
18    LexerError,
19    #[strum(message = "发生未知解析错误")]
20    ParserError,
21    #[strum(message = "发生未知生成错误")]
22    EmitterError,
23    #[strum(message = "发生未知优化错误")]
24    OptimizerError,
25    #[strum(message = "该功能尚未实现")]
26    Unimplemented,
27
28    #[strum(message = "遇到未知的记号")]
29    UnknownToken,
30    #[strum(message = "发现意外的记号")]
31    UnexpectedToken,
32    #[strum(message = "`$0` 是保留关键字,不能用作标识符")]
33    InvalidReservedKeyword,
34    #[strum(message = "`$0` 是关键字,不能用作标识符")]
35    InvalidKeyword,
36    #[strum(message = "数字字面量不能以下划线开头或结尾")]
37    InvalidNumberLiteralUnderscore,
38    #[strum(message = "无效的数字字面量")]
39    InvalidNumberLiteral,
40    #[strum(message = "数字字面量过大")]
41    OverflowNumberLiteral,
42    #[strum(message = "整数字面量过大")]
43    OverflowIntegerLiteral,
44    #[strum(message = "无效的序数字面量;请移除前导零和下划线,或改用 `[$0]`")]
45    InvalidOrdinalLiteral,
46    #[strum(message = "字符串字面量未终止")]
47    UnterminatedString,
48    #[strum(message = "字符串中的转义序列无效")]
49    InvalidEscapeSequence,
50    #[strum(message = "十六进制转义序列的值不是有效的 ASCII 字符")]
51    InvalidHexEscapeSequence,
52    #[strum(message = "Unicode 转义序列的值不是有效的 Unicode 码点")]
53    InvalidUnicodeEscapeSequence,
54    #[strum(message = "在 `..` 之后需要表达式")]
55    BadArraySpread,
56    #[strum(message = "插值表达式未终止")]
57    UnterminatedInterpolation,
58    #[strum(message = "无效的插值表达式")]
59    BadInterpolation,
60    #[strum(message = "插值表达式为空")]
61    EmptyInterpolation,
62    #[strum(message = "意外的 `_`;它是用于丢弃值的保留关键字")]
63    UnexpectedUnderscore,
64    #[strum(message = "意外的 `global`;它是用于全局变量的保留关键字")]
65    UnexpectedGlobal,
66    #[strum(message = "列表中缺少 `,`")]
67    MissingComma,
68    #[strum(message = "缺少 `]` 以关闭中括号")]
69    MissingCloseBracket,
70    #[strum(message = "缺少 `{` 以打开花括号")]
71    MissingOpenBrace,
72    #[strum(message = "缺少 `}` 以关闭花括号")]
73    MissingCloseBrace,
74    #[strum(message = "缺少 `)` 以关闭括号")]
75    MissingCloseParen,
76    #[strum(message = "语句末尾缺少 `;`")]
77    MissingSemicolon,
78    #[strum(message = "条件表达式中缺少 `:`")]
79    MissingColon,
80    #[strum(message = "在 bind 或 const 语句中需要 `=` 运算符")]
81    MissingBindOperator,
82    #[strum(message = "常量名必须以 `@` 开头")]
83    InvalidConstantName,
84    #[strum(message = "声明中缺少函数名")]
85    MissingFunctionName,
86    #[strum(message = "声明中缺少模块名")]
87    MissingModuleName,
88    #[strum(message = "扩展调用必须以参数列表结尾;请在此处添加 `(`")]
89    MissingOpenParenAfterExtension,
90    #[strum(message = "`type` 是类函数关键字;请在此处添加 `(`")]
91    MissingOpenParenAfterType,
92    #[strum(message = "`type` 调用必须恰好有一个参数")]
93    InvalidTypeCall,
94    #[strum(message = "意外的记录字面量;此处需要分组表达式")]
95    RecordLiteralInExtensionCaller,
96    #[strum(message = "语句中缺少 `case`")]
97    MissingCase,
98    #[strum(message = "遇到未知的表达式")]
99    UnknownExpression,
100    #[strum(message = "发现未匹配的 `}`")]
101    UnmatchedCloseBrace,
102    #[strum(message = "发现未匹配的 `]`")]
103    UnmatchedCloseBracket,
104    #[strum(message = "发现未匹配的 `)`")]
105    UnmatchedCloseParen,
106    #[strum(message = "遇到未知的模式")]
107    UnknownPattern,
108    #[strum(message = "此处只允许常量或字面量")]
109    InvalidConstantLiteral,
110    #[strum(message = "遇到未知的语句")]
111    UnknownStatement,
112    #[strum(message = "此处需要表达式")]
113    ExpressionExpected,
114    #[strum(message = "此处需要模式")]
115    PatternExpected,
116    #[strum(message = "字面量模式中不允许 `!` 运算符")]
117    ExclamationInLiteralPattern,
118    #[strum(message = "重绑定时不允许使用 `mut`")]
119    MutInRebindPattern,
120    #[strum(message = "名称以 `@` 开头的变量不允许被重绑定")]
121    ConstantInBindPattern,
122    #[strum(message = "弃元模式中不能使用 `mut`")]
123    MutInDiscardPattern,
124    #[strum(message = "展开模式中应省略丢弃弃元")]
125    DiscardInSpreadPattern,
126    #[strum(message = "记录模式中的展开模式应为最后一个字段")]
127    MispositionedSpreadInRecordPattern,
128    #[strum(message = "记录模式中不允许插值名称")]
129    InterpolatedNameRecordPattern,
130    #[strum(message = "省略记录字段名时需要绑定模式")]
131    BadOmitKeyRecordPattern,
132    #[strum(message = "数组模式中的范围模式应加括号")]
133    AmbiguousRangePattern,
134    #[strum(message = "数组模式中展开模式只能使用一次")]
135    DuplicateSpreadPattern,
136    #[strum(message = "函数声明中剩余参数应为最后一个参数")]
137    MispositionedRestParameter,
138    #[strum(message = "不能对未声明的变量赋值")]
139    UndefinedVariableAssignment,
140    #[strum(message = "不能对不可变变量赋值...")]
141    ImmutableVariableAssignment,
142    #[strum(message = "变量无法在此之前访问...")]
143    UninitializedVariable,
144    #[strum(message = "该变量已...")]
145    DuplicateVariableDeclaration,
146    #[strum(message = "在循环之外出现意外的 `break`")]
147    UnexpectedBreak,
148    #[strum(message = "在循环之外出现意外的 `continue`")]
149    UnexpectedContinue,
150    #[strum(
151        message = "`global` 关键字只能用作 `global.<name>`、`global[<name>]` 或 `in` 运算符右侧"
152    )]
153    MisuseOfGlobalKeyword,
154    #[strum(message = "无法从表达式推断键名")]
155    BadOmitKeyRecordExpression,
156    #[strum(message = "只能对变量或字段访问赋值")]
157    UnassignableExpression,
158    #[strum(message = "在模块声明之外出现意外的 `pub`")]
159    UnexpectedPub,
160
161    ErrorEnd = 1999,
162    // Warning 2000~2999
163    WarningStart = 2000,
164
165    // The null value in MiraScript is represented by `nil`,
166    // Emit a warning when a global variable is read as `null` `undefined` or similar.
167    #[strum(message = "`$0` 不是空值;显式使用全局变量 `global.$0` 或空值 `nil`")]
168    MisleadingNilVariable,
169    #[strum(message = "不可失败匹配中的该模式是多余的;请考虑移除它或改为在 `is` 表达式中使用")]
170    UnnecessaryIrrefutablePattern,
171    #[strum(message = "该 `match` 表达式没有分支;它永远不会匹配任何值")]
172    MatchExpressionHasNoCases,
173
174    // Static type checking warnings
175    #[strum(message = "范围中不能使用非数字字面量")]
176    NonNumberInRange,
177    #[strum(message = "比较表达式中不能使用非数字或字符串字面量")]
178    NonNumberOrStringInComparison,
179    #[strum(message = "算术表达式中不能使用非数字字面量")]
180    NonNumberInArithmetic,
181    #[strum(message = "逻辑表达式中不能使用非布尔字面量")]
182    NonBooleanInLogical,
183    #[strum(message = "`in` 运算符右侧必须为复合类型")]
184    NonCompoundIn,
185    #[strum(message = "字面量不能作为函数调用")]
186    LiteralNotCallable,
187    #[strum(message = "字面量不能作为记录或数组访问")]
188    LiteralNotIndexable,
189
190    // For analyzer
191    #[strum(message = "全局变量 `$0` 未声明")]
192    GlobalVariableNotDeclared,
193
194    WarningEnd = 2999,
195    // Info 3000~3999
196    InfoStart = 3000,
197
198    InfoEnd = 3999,
199    // Hint 4000~4999
200    HintStart = 4000,
201
202    #[strum(message = "局部变量未使用;请考虑删除它或使用 `_` 忽略")]
203    UnusedLocalVariable,
204    #[strum(message = "局部函数未使用;请考虑删除它")]
205    UnusedLocalFunction,
206
207    // Code style
208    #[strum(message = "逻辑运算中更推荐使用 `&&` 而非 `and`")]
209    PreferLogicalOperatorAnd,
210    #[strum(message = "逻辑运算中更推荐使用 `||` 而非 `or`")]
211    PreferLogicalOperatorOr,
212    #[strum(message = "逻辑运算中更推荐使用 `!` 而非 `not`")]
213    PreferLogicalOperatorNot,
214    #[strum(message = "记录字面量声明中更推荐使用 `()` 而非 `{}`")]
215    PreferParenthesesForRecordLiteral,
216    #[strum(message = "更推荐使用 if 表达式而非条件表达式")]
217    PreferIfExpression,
218
219    #[strum(message = "考虑移除多余的括号")]
220    UnnecessaryParentheses,
221    // For analyzer
222    #[strum(message = "常量 $0 建议使用大写")]
223    PreferUppercaseConstant,
224    #[strum(message = "此处的代码不可达")]
225    UnreachableCode,
226
227    HintEnd = 4999,
228    // Reference 5000~5999
229    ReferenceStart = 5000,
230
231    #[strum(message = "...在此处声明")]
232    VariableDeclaredHere,
233    #[strum(message = "...在此处声明")]
234    FunctionDeclaredHere,
235    #[strum(message = "...在此处作为参数声明")]
236    ParameterDeclaredHere,
237    #[strum(message = "...在此处被该函数声明为自动参数 `it`")]
238    ParameterItDeclaredHere,
239    #[strum(message = "...在此处作为剩余参数声明")]
240    ParameterRestDeclaredHere,
241    #[strum(message = "...在此处作为参数模式的子模式声明")]
242    ParameterSubPatternDeclaredHere,
243
244    ReferenceEnd = 5999,
245
246    // Tags 10000~10999
247    TagStart = 10000,
248
249    // mark local declarations
250
251    // non-parameter declarations
252    LocalConst,
253    LocalImmutable,
254    LocalMutable,
255    LocalFunction,
256    LocalModule,
257
258    // parameter declarations
259    ParameterIt,
260    ParameterImmutable,
261    ParameterMutable,
262    ParameterImmutableRest,
263    ParameterMutableRest,
264    // parameter patterns holds parameters, but make no declarations
265    ParameterPattern,
266    ParameterRestPattern,
267    // parameter sub-patterns are declarations inside patterns, they are not parameters
268    ParameterSubPatternImmutable,
269    ParameterSubPatternMutable,
270
271    // mark global accesses
272    GlobalVariable,
273    GlobalDynamicAccess,
274
275    // mark record initialization
276    RecordFieldIdName,
277    RecordFieldOrdinalName,
278    RecordFieldStringName,
279    UnnamedRecordField0,
280    UnnamedRecordField1,
281    UnnamedRecordField2,
282    UnnamedRecordField3,
283    UnnamedRecordField4,
284    UnnamedRecordField5,
285    UnnamedRecordField6,
286    UnnamedRecordField7,
287    UnnamedRecordField8,
288    UnnamedRecordField9,
289    UnnamedRecordFieldN,
290    OmitNamedRecordField,
291
292    // mark function calls
293    FunctionCall,
294    ExtensionCall,
295
296    // mark code ranges
297    Scope,
298    String,
299    Interpolation,
300
301    // mark control flows
302    ForExpression,
303    WhileExpression,
304    LoopExpression,
305    FnDeclaration,
306    FnExpression,
307    IfExpression,
308    MatchExpression,
309
310    TagEnd = 10999,
311
312    // TagRef 11000~11999
313    TagRefStart = 11000,
314
315    // mark local accesses
316    // read
317    ReadLocal,
318    // compound read-write
319    ReadWriteLocal,
320    // write
321    WriteLocal,
322    // redeclare local declarations, will also report as error
323    RedeclareLocal,
324    // export by `pub` keyword, mark on the module identifier
325    ExportedLocal,
326
327    // mark function calls
328    Callable,
329    ArgumentExtension,
330    ArgumentStart,
331    ArgumentEnd,
332    ArgumentComma,
333    ArgumentSpread,
334
335    // mark control flows
336    KeywordFor,
337    KeywordIn,
338    KeywordWhile,
339    KeywordLoop,
340    KeywordBreak,
341    KeywordContinue,
342
343    KeywordIf,
344    KeywordElse,
345
346    KeywordMatch,
347    KeywordCase,
348
349    KeywordFn,
350    KeywordReturn,
351
352    /// Work with [DiagnosticCode::OmitNamedRecordField]
353    OmitNamedRecordFieldName,
354
355    TagRefEnd = 11999,
356
357    SourceMap = 12000,
358
359    Unknown = 65535,
360}
361
362impl From<DiagnosticCode> for u16 {
363    fn from(val: DiagnosticCode) -> Self {
364        val.code()
365    }
366}
367
368impl TryFrom<u16> for DiagnosticCode {
369    type Error = ();
370
371    fn try_from(value: u16) -> Result<Self, Self::Error> {
372        DiagnosticCode::from_code(value).ok_or(())
373    }
374}
375
376impl DiagnosticCode {
377    pub fn code(&self) -> u16 {
378        *self as u16
379    }
380
381    pub fn from_code(code: u16) -> Option<Self> {
382        let r = DiagnosticCode::from_repr(code)?;
383        if r == DiagnosticCode::Unknown {
384            None
385        } else {
386            Some(r)
387        }
388    }
389
390    pub fn message(&self) -> &'static str {
391        self.get_message().unwrap_or("Unknown error")
392    }
393
394    pub fn level_str(&self) -> &'static str {
395        if self.is_error() {
396            "Error"
397        } else if self.is_warning() {
398            "Warning"
399        } else if self.is_info() {
400            "Info"
401        } else if self.is_hint() {
402            "Hint"
403        } else if self.is_reference() {
404            "Reference"
405        } else {
406            "Unknown"
407        }
408    }
409
410    pub fn is_error(&self) -> bool {
411        *self > DiagnosticCode::ErrorStart && *self < DiagnosticCode::ErrorEnd
412    }
413
414    pub fn is_warning(&self) -> bool {
415        *self >= DiagnosticCode::WarningStart && *self < DiagnosticCode::WarningEnd
416    }
417
418    pub fn is_info(&self) -> bool {
419        *self >= DiagnosticCode::InfoStart && *self < DiagnosticCode::InfoEnd
420    }
421
422    pub fn is_hint(&self) -> bool {
423        *self >= DiagnosticCode::HintStart && *self < DiagnosticCode::HintEnd
424    }
425
426    pub fn is_reference(&self) -> bool {
427        *self >= DiagnosticCode::ReferenceStart && *self < DiagnosticCode::ReferenceEnd
428    }
429
430    pub fn is_tag(&self) -> bool {
431        *self >= DiagnosticCode::TagStart && *self < DiagnosticCode::TagRefEnd
432    }
433
434    pub fn is_sourcemap(&self) -> bool {
435        *self == DiagnosticCode::SourceMap
436    }
437}