1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

//**************************************************************************************************
// Main types
//**************************************************************************************************

#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash, PartialOrd, Ord)]
pub enum Severity {
    Warning = 0,
    NonblockingError = 1,
    BlockingError = 2,
    Bug = 3,
}

#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct DiagnosticInfo {
    severity: Severity,
    category: Category,
    code: u8,
    message: &'static str,
}

pub trait DiagnosticCode: Copy {
    const CATEGORY: Category;

    fn severity(self) -> Severity;

    fn code_and_message(self) -> (u8, &'static str);

    fn into_info(self) -> DiagnosticInfo {
        let severity = self.severity();
        let category = Self::CATEGORY;
        let (code, message) = self.code_and_message();
        DiagnosticInfo {
            severity,
            category,
            code,
            message,
        }
    }
}

//**************************************************************************************************
// Categories and Codes
//**************************************************************************************************

macro_rules! codes {
    ($($cat:ident: [
        $($code:ident: { msg: $code_msg:literal, severity:$sev:ident $(,)? }),* $(,)?
    ]),* $(,)?) => {
        #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
        #[repr(u8)]
        pub enum Category {
            $($cat,)*
        }

        $(
            #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
            #[repr(u8)]
            pub enum $cat {
                DontStartAtZeroPlaceholder,
                $($code,)*
            }

            impl DiagnosticCode for $cat {
                const CATEGORY: Category = {
                    // hacky check that $cat_num <= 99
                    let cat_is_leq_99 = (Category::$cat as u8) <= 99;
                    ["Diagnostic Category must be a u8 <= 99"][!cat_is_leq_99 as usize];
                    Category::$cat
                };

                fn severity(self) -> Severity {
                    match self {
                        Self::DontStartAtZeroPlaceholder =>
                            panic!("ICE do not use placeholder error code"),
                        $(Self::$code => Severity::$sev,)*
                    }
                }

                fn code_and_message(self) -> (u8, &'static str) {
                    let code = self as u8;
                    debug_assert!(code > 0);
                    match self {
                        Self::DontStartAtZeroPlaceholder =>
                            panic!("ICE do not use placeholder error code"),
                        $(Self::$code => (code, $code_msg),)*
                    }
                }
            }
        )*

    };
}

codes!(
    // bucket for random one off errors. unlikely to be used
    Uncategorized: [],
    // syntax errors
    Syntax: [
        InvalidCharacter: { msg: "invalid character", severity: BlockingError },
        UnexpectedToken: { msg: "unexpected token", severity: BlockingError },
        InvalidModifier: { msg: "invalid modifier", severity: BlockingError },
        InvalidDocComment: { msg: "invalid documentation comment", severity: Warning },
        InvalidAddress: { msg: "invalid address", severity: BlockingError },
        InvalidNumber: { msg: "invalid number literal", severity: BlockingError },
        InvalidByteString: { msg: "invalid byte string", severity: BlockingError },
        InvalidHexString: { msg: "invalid hex string", severity: BlockingError },
        InvalidLValue: { msg: "invalid assignment", severity: BlockingError },
        SpecContextRestricted:
            { msg: "syntax item restricted to spec contexts", severity: BlockingError },
    ],
    // errors for any rules around declaration items
    Declarations: [
        DuplicateItem:
            { msg: "duplicate declaration, item, or annotation", severity: NonblockingError },
        UnnecessaryItem: { msg: "unnecessary or extraneous item", severity: NonblockingError },
        InvalidAddress: { msg: "invalid 'address' declaration", severity: NonblockingError },
        InvalidModule: { msg: "invalid 'module' declaration", severity: NonblockingError },
        InvalidScript: { msg: "invalid 'script' declaration", severity: NonblockingError },
        InvalidConstant: { msg: "invalid 'const' declaration", severity: NonblockingError },
        InvalidFunction: { msg: "invalid 'fun' declaration", severity: NonblockingError },
        InvalidStruct: { msg: "invalid 'struct' declaration", severity: NonblockingError },
        InvalidSpec: { msg: "invalid 'spec' declaration", severity: NonblockingError },
        InvalidName: { msg: "invalid name", severity: BlockingError },
        InvalidFriendDeclaration:
            { msg: "invalid 'friend' declaration", severity: NonblockingError },
        InvalidAcquiresItem: { msg: "invalid 'acquires' item", severity: NonblockingError },
        InvalidPhantomUse: { msg: "invalid phantom type parameter usage", severity: NonblockingError },
        InvalidNonPhantomUse: { msg: "invalid non-phantom type parameter usage", severity: Warning },
    ],
    // errors name resolution, mostly expansion/translate and naming/translate
    NameResolution: [
        AddressWithoutValue: { msg: "address with no value", severity: NonblockingError },
        UnboundModule: { msg: "unbound module", severity: BlockingError },
        UnboundModuleMember: { msg: "unbound module member", severity: BlockingError },
        UnboundType: { msg: "unbound type", severity: BlockingError },
        UnboundUnscopedName: { msg: "unbound unscoped name", severity: BlockingError },
        NamePositionMismatch: { msg: "unexpected name in this position", severity: BlockingError },
        TooManyTypeArguments: { msg: "too many type arguments", severity: NonblockingError },
        TooFewTypeArguments: { msg: "too few type arguments", severity: BlockingError },
        UnboundVariable: { msg: "unbound variable", severity: BlockingError },
        UnboundField: { msg: "unbound field", severity: BlockingError },
        ReservedName: { msg: "Invalid use of reserved name", severity: BlockingError },
    ],
    // errors for typing rules. mostly typing/translate
    TypeSafety: [
        Visibility: { msg: "restricted visibility", severity: NonblockingError },
        ScriptContext: { msg: "requires script context", severity: NonblockingError },
        BuiltinOperation: { msg: "built-in operation not supported", severity: BlockingError },
        ExpectedBaseType: { msg: "expected a single non-reference type", severity: BlockingError },
        ExpectedSingleType: { msg: "expected a single type", severity: BlockingError },
        SubtypeError: { msg: "invalid subtype", severity: BlockingError },
        JoinError: { msg: "incompatible types", severity: BlockingError },
        RecursiveType: { msg: "invalid type. recursive type found", severity: BlockingError },
        ExpectedSpecificType: { msg: "expected specific type", severity: BlockingError },
        UninferredType: { msg: "cannot infer type", severity: BlockingError },
        ScriptSignature: { msg: "invalid script signature", severity: NonblockingError },
        TypeForConstant: { msg: "invalid type for constant", severity: BlockingError },
        UnsupportedConstant:
            { msg: "invalid statement or expression in constant", severity: BlockingError },
        InvalidLoopControl: { msg: "invalid loop control", severity: BlockingError },
        InvalidNativeUsage: { msg: "invalid use of native item", severity: BlockingError },
        TooFewArguments: { msg: "too few arguments", severity: NonblockingError },
        TooManyArguments: { msg: "too many arguments", severity: NonblockingError },
        CyclicData: { msg: "cyclic data", severity: NonblockingError },
        CyclicInstantiation:
            { msg: "cyclic type instantiation", severity: NonblockingError },
        MissingAcquires: { msg: "missing acquires annotation", severity: NonblockingError },
        InvalidNum: { msg: "invalid number after type inference", severity: NonblockingError },
    ],
    // errors for ability rules. mostly typing/translate
    AbilitySafety: [
        Constraint: { msg: "ability constraint not satisfied", severity: NonblockingError },
        ImplicitlyCopyable: { msg: "type not implicitly copyable", severity: NonblockingError },
    ],
    // errors for move rules. mostly cfgir/locals
    MoveSafety: [
        UnusedUndroppable: { msg: "unused value without 'drop'", severity: NonblockingError },
        UnassignedVariable: { msg: "use of unassigned variable", severity: NonblockingError },
    ],
    // errors for move rules. mostly cfgir/borrows
    ReferenceSafety: [
        RefTrans: { msg: "referential transparency violated", severity: BlockingError },
        MutOwns: { msg: "mutable ownership violated", severity: NonblockingError },
        Dangling: {
            msg: "invalid operation, could create dangling a reference",
            severity: NonblockingError,
        },
        InvalidReturn:
            { msg: "invalid return of locally borrowed state", severity: NonblockingError },
        InvalidTransfer: { msg: "invalid transfer of references", severity: NonblockingError },
    ],
    BytecodeGeneration: [
        UnfoldableConstant: { msg: "cannot compute constant value", severity: NonblockingError },
    ],
    // errors for any unused code or items
    UnusedItem: [
        Alias: { msg: "unused alias", severity: Warning },
        Variable: { msg: "unused variable", severity: Warning },
        Assignment: { msg: "unused assignment", severity: Warning },
        TrailingSemi: { msg: "unnecessary trailing semicolon", severity: Warning },
        DeadCode: { msg: "dead or unreachable code", severity: Warning },
        StructTypeParam: { msg: "unused struct type parameter", severity: Warning }
    ],
    Attributes: [
        Duplicate: { msg: "invalid duplicate attribute", severity: NonblockingError },
        InvalidName: { msg: "invalid attribute name", severity: NonblockingError },
        InvalidValue: { msg: "invalid attribute value", severity: NonblockingError },
        InvalidUsage: { msg: "invalid usage of known attribute", severity: NonblockingError },
        InvalidTest: { msg: "unable to generate test", severity: NonblockingError },
    ],
    Tests: [
        TestFailed: { msg: "test failure", severity: BlockingError },
    ],
    Bug: [
        BytecodeGeneration: { msg: "BYTECODE GENERATION FAILED", severity: Bug },
        BytecodeVerification: { msg: "BYTECODE VERIFICATION FAILED", severity: Bug },
    ],
);

//**************************************************************************************************
// impls
//**************************************************************************************************

impl DiagnosticInfo {
    pub fn render(self) -> (/* code */ String, /* message */ &'static str) {
        let Self {
            severity,
            category,
            code,
            message,
        } = self;
        let sev_prefix = match severity {
            Severity::BlockingError | Severity::NonblockingError => "E",
            Severity::Warning => "W",
            Severity::Bug => "ICE",
        };
        let cat_prefix: u8 = category as u8;
        debug_assert!(cat_prefix <= 99);
        let string_code = format!("{}{:02}{:03}", sev_prefix, cat_prefix, code);
        (string_code, message)
    }

    pub fn message(&self) -> &'static str {
        self.message
    }

    pub fn severity(&self) -> Severity {
        self.severity
    }
}

impl Severity {
    pub const MIN: Self = Self::Warning;
    pub const MAX: Self = Self::Bug;

    pub fn into_codespan_severity(self) -> codespan_reporting::diagnostic::Severity {
        use codespan_reporting::diagnostic::Severity as CSRSeverity;
        match self {
            Severity::Bug => CSRSeverity::Bug,
            Severity::BlockingError | Severity::NonblockingError => CSRSeverity::Error,
            Severity::Warning => CSRSeverity::Warning,
        }
    }
}

impl Default for Severity {
    fn default() -> Self {
        Self::MIN
    }
}