//! Source map: maps bytecode instruction indices to source spans. //! //! Only emitted for the debug target. The JSON format is simple and can be //! consumed by any debugger or IDE extension. use serde::{Deserialize, Serialize}; use el_lexer::Span; /// A single mapping entry: bytecode index → source span. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MapEntry { /// Index of the bytecode instruction (0-based). pub instruction: usize, pub start: usize, pub end: usize, pub line: u32, pub col: u32, } impl MapEntry { pub fn new(instruction: usize, span: Span) -> Self { Self { instruction, start: span.start, end: span.end, line: span.line, col: span.col, } } } /// The full source map for a compilation unit. #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct SourceMap { pub entries: Vec, } impl SourceMap { pub fn new() -> Self { Self::default() } /// Record that instruction at `index` was generated from `span`. pub fn record(&mut self, index: usize, span: Span) { self.entries.push(MapEntry::new(index, span)); } /// Look up the source span for a given instruction index. pub fn lookup(&self, index: usize) -> Option<&MapEntry> { self.entries.iter().rfind(|e| e.instruction <= index) } /// Serialize to JSON string. pub fn to_json(&self) -> Result { serde_json::to_string_pretty(self).map_err(|e| e.to_string()) } }