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
222    // For analyzer
223    #[strum(message = "常量 $0 建议使用大写")]
224    PreferUppercaseConstant,
225
226    HintEnd = 4999,
227    // Reference 5000~5999
228    ReferenceStart = 5000,
229
230    #[strum(message = "...在此处声明")]
231    VariableDeclaredHere,
232    #[strum(message = "...在此处声明")]
233    FunctionDeclaredHere,
234    #[strum(message = "...在此处作为参数声明")]
235    ParameterDeclaredHere,
236    #[strum(message = "...在此处被该函数声明为自动参数 `it`")]
237    ParameterItDeclaredHere,
238    #[strum(message = "...在此处作为剩余参数声明")]
239    ParameterRestDeclaredHere,
240    #[strum(message = "...在此处作为参数模式的子模式声明")]
241    ParameterSubPatternDeclaredHere,
242
243    ReferenceEnd = 5999,
244
245    // Tags 10000~10999
246    TagStart = 10000,
247
248    // mark local declarations
249
250    // non-parameter declarations
251    LocalConst,
252    LocalImmutable,
253    LocalMutable,
254    LocalFunction,
255    LocalModule,
256
257    // parameter declarations
258    ParameterIt,
259    ParameterImmutable,
260    ParameterMutable,
261    ParameterImmutableRest,
262    ParameterMutableRest,
263    // parameter patterns holds parameters, but make no declarations
264    ParameterPattern,
265    ParameterRestPattern,
266    // parameter sub-patterns are declarations inside patterns, they are not parameters
267    ParameterSubPatternImmutable,
268    ParameterSubPatternMutable,
269
270    // mark global accesses
271    GlobalVariable,
272    GlobalDynamicAccess,
273
274    // mark record initialization
275    RecordFieldIdName,
276    RecordFieldOrdinalName,
277    RecordFieldStringName,
278    UnnamedRecordField0,
279    UnnamedRecordField1,
280    UnnamedRecordField2,
281    UnnamedRecordField3,
282    UnnamedRecordField4,
283    UnnamedRecordField5,
284    UnnamedRecordField6,
285    UnnamedRecordField7,
286    UnnamedRecordField8,
287    UnnamedRecordField9,
288    UnnamedRecordFieldN,
289    OmitNamedRecordField,
290
291    // mark function calls
292    FunctionCall,
293    ExtensionCall,
294
295    // mark code ranges
296    Scope,
297    String,
298    Interpolation,
299
300    // mark control flows
301    ForExpression,
302    WhileExpression,
303    LoopExpression,
304    FnDeclaration,
305    FnExpression,
306    IfExpression,
307    MatchExpression,
308
309    TagEnd = 10999,
310
311    // TagRef 11000~11999
312    TagRefStart = 11000,
313
314    // mark local accesses
315    // read
316    ReadLocal,
317    // compound read-write
318    ReadWriteLocal,
319    // write
320    WriteLocal,
321    // redeclare local declarations, will also report as error
322    RedeclareLocal,
323    // export by `pub` keyword, mark on the module identifier
324    ExportedLocal,
325
326    // mark function calls
327    Callable,
328    ArgumentExtension,
329    ArgumentStart,
330    ArgumentEnd,
331    ArgumentComma,
332    ArgumentSpread,
333
334    // mark control flows
335    KeywordFor,
336    KeywordIn,
337    KeywordWhile,
338    KeywordLoop,
339    KeywordBreak,
340    KeywordContinue,
341
342    KeywordIf,
343    KeywordElse,
344
345    KeywordMatch,
346    KeywordCase,
347
348    KeywordFn,
349    KeywordReturn,
350
351    /// Work with [DiagnosticCode::OmitNamedRecordField]
352    OmitNamedRecordFieldName,
353
354    TagRefEnd = 11999,
355
356    SourceMap = 12000,
357
358    Unknown = 65535,
359}
360
361impl From<DiagnosticCode> for u16 {
362    fn from(val: DiagnosticCode) -> Self {
363        val.code()
364    }
365}
366
367impl TryFrom<u16> for DiagnosticCode {
368    type Error = ();
369
370    fn try_from(value: u16) -> Result<Self, Self::Error> {
371        DiagnosticCode::from_code(value).ok_or(())
372    }
373}
374
375impl DiagnosticCode {
376    pub fn code(&self) -> u16 {
377        *self as u16
378    }
379
380    pub fn from_code(code: u16) -> Option<Self> {
381        let r = DiagnosticCode::from_repr(code)?;
382        if r == DiagnosticCode::Unknown {
383            None
384        } else {
385            Some(r)
386        }
387    }
388
389    pub fn message(&self) -> &'static str {
390        self.get_message().unwrap_or("Unknown error")
391    }
392
393    pub fn level_str(&self) -> &'static str {
394        if self.is_error() {
395            "Error"
396        } else if self.is_warning() {
397            "Warning"
398        } else if self.is_info() {
399            "Info"
400        } else if self.is_hint() {
401            "Hint"
402        } else if self.is_reference() {
403            "Reference"
404        } else {
405            "Unknown"
406        }
407    }
408
409    pub fn is_error(&self) -> bool {
410        *self > DiagnosticCode::ErrorStart && *self < DiagnosticCode::ErrorEnd
411    }
412
413    pub fn is_warning(&self) -> bool {
414        *self >= DiagnosticCode::WarningStart && *self < DiagnosticCode::WarningEnd
415    }
416
417    pub fn is_info(&self) -> bool {
418        *self >= DiagnosticCode::InfoStart && *self < DiagnosticCode::InfoEnd
419    }
420
421    pub fn is_hint(&self) -> bool {
422        *self >= DiagnosticCode::HintStart && *self < DiagnosticCode::HintEnd
423    }
424
425    pub fn is_reference(&self) -> bool {
426        *self >= DiagnosticCode::ReferenceStart && *self < DiagnosticCode::ReferenceEnd
427    }
428
429    pub fn is_tag(&self) -> bool {
430        *self >= DiagnosticCode::TagStart && *self < DiagnosticCode::TagRefEnd
431    }
432
433    pub fn is_sourcemap(&self) -> bool {
434        *self == DiagnosticCode::SourceMap
435    }
436}