Skip to main content

mirascript_vm/error/
compile.rs

1pub use mirascript_core::DiagnosticCode;
2use mirascript_core::OpCode;
3use thiserror::Error;
4
5use super::MiraError;
6
7/// Represents a diagnostic message produced by the compiler.
8#[derive(Debug, Error)]
9#[error("{start_line}:{start_col}-{end_line}:{end_col} {code:?}")]
10pub struct Diagnostics {
11    /// The diagnostic code associated with this message.
12    pub code: DiagnosticCode,
13    /// The starting line of the diagnostic message (1-based).
14    pub start_line: u32,
15    /// The starting column of the diagnostic message (1-based).
16    pub start_col: u32,
17    /// The ending line of the diagnostic message (1-based).
18    pub end_line: u32,
19    /// The ending column of the diagnostic message (1-based).
20    pub end_col: u32,
21}
22
23/// Represents the reason for an invalid bytecode error.
24#[derive(Debug, Error)]
25pub enum InvalidBytecodeReason {
26    /// The chunk header is truncated.
27    #[error("chunk header is truncated")]
28    BadChunkHeader,
29    /// The chunk length header does not match the actual chunk length.
30    #[error("chunk length header is {0}, expected {1}")]
31    ChunkLengthMismatch(usize, usize),
32    /// The code section exceeds the chunk length.
33    #[error("code section exceeds chunk")]
34    CodeSectionExceedsChunk,
35    /// The constant section exceeds the chunk length.
36    #[error("constant section length exceeds chunk")]
37    ConstantSectionExceedsChunk,
38    /// The constant section is truncated.
39    #[error("truncated constant")]
40    TruncatedConstant,
41    /// The constant section contains an invalid UTF-8 string.
42    #[error("invalid UTF-8 string constant")]
43    InvalidStringConstant,
44    /// The constant section contains an unknown constant tag.
45    #[error("unknown constant tag {0}")]
46    UnknownConstantTag(u8),
47    /// The root instruction must be a `Func` instruction.
48    #[error("root instruction must be Func")]
49    BadRootStart,
50    /// The last instruction must be a `FuncEnd` instruction.
51    #[error("trailing code after root FuncEnd")]
52    BadRootEnd,
53    /// The root function destination must be register 0.
54    #[error("root function destination must be register 0")]
55    BadRootDestination,
56    /// Unknown opcode encountered in the bytecode.
57    #[error("unknown opcode 0x{0:02x}")]
58    InvalidOpCode(u8),
59    /// The bytecode is truncated while reading an opcode.
60    #[error("unexpected end of code while reading opcode")]
61    TruncatedOpCode,
62    /// The bytecode is truncated while reading an instruction parameter.
63    #[error("truncated op parameter at code offset {0}")]
64    TruncatedParameter(usize),
65    /// The bytecode references a register index that is out of range.
66    #[error("register index {0} is out of range 0..={1}")]
67    RegisterIndexOutOfRange(usize, usize),
68    /// The bytecode references a constant index that is out of range.
69    #[error("constant index {0} is out of range 0..{1}")]
70    ConstantIndexOutOfRange(usize, usize),
71    /// The bytecode references a constant of an invalid type for the instruction.
72    #[error("invalid constant type for instruction")]
73    InvalidConstantType,
74    /// The function instruction has a different number of arguments than the number of registers provided.
75    #[error("function has {0} arguments but only {1} registers")]
76    FunctionArgCountMismatch(usize, usize),
77    /// Unterminated bytecode block encountered while reading an instruction.
78    #[error("unterminated bytecode block")]
79    UnterminatedBlock,
80    /// The bytecode contains an unsupported wide encoding opcode.
81    #[error("cannot use wide encoding opcode here")]
82    UnsupportedWide,
83    /// The bytecode contains an unsupported instruction for the current context.
84    #[error("unexpected opcode {0}")]
85    UnexpectedOpCode(OpCode),
86    /// The module contains a duplicate export key.
87    #[error("duplicate export key {0:?}")]
88    DuplicateExportKey(String),
89    /// The bytecode references an invalid upvalue level.
90    #[error("invalid upvalue level {0}")]
91    InvalidUpvalueLevel(usize),
92    /// The call instruction references an argument index that is out of range for the number of arguments provided.
93    #[error("spread argument index {0} is out of range 0..{1}")]
94    SpreadArgumentIndexOutOfRange(usize, usize),
95}
96
97fn decode_diagnostics(diagnostics: &[u32]) -> Vec<Diagnostics> {
98    diagnostics
99        .chunks(5)
100        .map(|chunk| {
101            let start_line = chunk[0] as usize;
102            let start_col = chunk[1] as usize;
103            let end_line = chunk[2] as usize;
104            let end_col = chunk[3] as usize;
105            let code =
106                DiagnosticCode::from_code(chunk[4] as u16).unwrap_or(DiagnosticCode::Unknown);
107            Diagnostics {
108                code,
109                start_line: start_line as u32,
110                start_col: start_col as u32,
111                end_line: end_line as u32,
112                end_col: end_col as u32,
113            }
114        })
115        .collect()
116}
117
118impl MiraError {
119    pub(crate) fn invalid_bytecode(offset: usize, reason: InvalidBytecodeReason) -> Box<Self> {
120        Self::InvalidBytecode { offset, reason }.into()
121    }
122
123    pub(crate) fn compile(diagnostics: &[u32]) -> Box<Self> {
124        Self::Compile {
125            diagnostics: decode_diagnostics(diagnostics),
126        }
127        .into()
128    }
129}