Skip to main content

rune/runtime/
debug.rs

1//! Debug information for units.
2
3use core::fmt;
4
5#[cfg(feature = "musli02")]
6use musli_core02::{Decode, Encode};
7#[cfg(feature = "serde")]
8use serde::{Deserialize, Serialize};
9
10use crate as rune;
11use crate::alloc::prelude::*;
12use crate::alloc::{Box, HashMap, Vec};
13use crate::ast::Span;
14use crate::runtime::DebugLabel;
15use crate::{Hash, ItemBuf, SourceId};
16
17/// Debug information about a unit.
18#[derive(Debug, TryClone, Default)]
19#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
20#[cfg_attr(feature = "musli02", derive(Decode, Encode), musli(crate = musli_core02))]
21#[non_exhaustive]
22pub struct DebugInfo {
23    /// Debug information on each instruction.
24    pub instructions: HashMap<usize, DebugInst>,
25    /// Function signatures.
26    pub functions: HashMap<Hash, DebugSignature>,
27    /// Reverse lookup of a function.
28    pub functions_rev: HashMap<usize, Hash>,
29    /// Hash to identifier.
30    pub hash_to_ident: HashMap<Hash, Box<str>>,
31    /// Static slots, indexed by slot.
32    ///
33    /// This is empty if debug information has been disabled, in which case
34    /// diagnostics have to refer to a static by its slot index.
35    pub globals: Vec<DebugGlobal>,
36    /// Functions which a declaration source (`.d.rn`) declared and a script
37    /// calls, so that calling one the host does not provide can name it.
38    pub declared: HashMap<Hash, ItemBuf>,
39}
40
41impl DebugInfo {
42    /// Get debug instruction at the given instruction pointer.
43    pub fn instruction_at(&self, ip: usize) -> Option<&DebugInst> {
44        self.instructions.get(&ip)
45    }
46
47    /// Get the function corresponding to the given instruction pointer.
48    pub fn function_at(&self, ip: usize) -> Option<(Hash, &DebugSignature)> {
49        let hash = *self.functions_rev.get(&ip)?;
50        let signature = self.functions.get(&hash)?;
51        Some((hash, signature))
52    }
53
54    /// Access an identifier for the given hash - if it exists.
55    pub fn ident_for_hash(&self, hash: Hash) -> Option<&str> {
56        Some(self.hash_to_ident.get(&hash)?)
57    }
58
59    /// The item of a function a declaration source declared, if `hash` is
60    /// one.
61    pub fn declared(&self, hash: Hash) -> Option<&ItemBuf> {
62        self.declared.get(&hash)
63    }
64
65    /// Access debug information for the given static slot - if it exists.
66    pub fn global(&self, slot: usize) -> Option<&DebugGlobal> {
67        self.globals.get(slot)
68    }
69}
70
71/// Debug information for a static slot.
72#[derive(Debug, TryClone)]
73#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
74#[cfg_attr(feature = "musli02", derive(Decode, Encode), musli(crate = musli_core02))]
75#[non_exhaustive]
76pub struct DebugGlobal {
77    /// The path of the static item occupying the slot.
78    pub path: ItemBuf,
79}
80
81impl DebugGlobal {
82    /// Construct a new static slot description.
83    #[inline]
84    pub fn new(path: ItemBuf) -> Self {
85        Self { path }
86    }
87}
88
89impl fmt::Display for DebugGlobal {
90    #[inline]
91    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
92        write!(fmt, "{}", self.path)
93    }
94}
95
96/// Debug information for every instruction.
97#[derive(Debug, TryClone)]
98#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
99#[cfg_attr(feature = "musli02", derive(Decode, Encode), musli(crate = musli_core02))]
100#[non_exhaustive]
101pub struct DebugInst {
102    /// The file by id the instruction belongs to.
103    pub source_id: SourceId,
104    /// The span of the instruction.
105    pub span: Span,
106    /// The comment for the line.
107    pub comment: Option<Box<str>>,
108    /// Label associated with the location.
109    pub labels: Vec<DebugLabel>,
110}
111
112impl DebugInst {
113    /// Construct a new debug instruction.
114    pub fn new(
115        source_id: SourceId,
116        span: Span,
117        comment: Option<Box<str>>,
118        labels: Vec<DebugLabel>,
119    ) -> Self {
120        Self {
121            source_id,
122            span,
123            comment,
124            labels,
125        }
126    }
127}
128
129/// Debug information on function arguments.
130#[derive(Debug, TryClone)]
131#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
132#[cfg_attr(feature = "musli02", derive(Decode, Encode), musli(crate = musli_core02))]
133#[non_exhaustive]
134pub enum DebugArgs {
135    /// An empty, with not arguments.
136    EmptyArgs,
137    /// A tuple, with the given number of arguments.
138    TupleArgs(usize),
139    /// A collection of named arguments.
140    Named(Box<[Box<str>]>),
141}
142
143/// A description of a function signature.
144#[derive(Debug, TryClone)]
145#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
146#[cfg_attr(feature = "musli02", derive(Decode, Encode), musli(crate = musli_core02))]
147#[non_exhaustive]
148pub struct DebugSignature {
149    /// The path of the function.
150    pub path: ItemBuf,
151    /// The number of arguments expected in the function.
152    pub args: DebugArgs,
153}
154
155impl DebugSignature {
156    /// Construct a new function signature.
157    #[inline]
158    pub fn new(path: ItemBuf, args: DebugArgs) -> Self {
159        Self { path, args }
160    }
161}
162
163impl fmt::Display for DebugSignature {
164    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
165        match &self.args {
166            DebugArgs::EmptyArgs => {
167                write!(fmt, "{}", self.path)?;
168            }
169            DebugArgs::TupleArgs(args) if *args > 0 => {
170                write!(fmt, "{}(", self.path)?;
171
172                let mut it = 0..*args;
173                let last = it.next_back();
174
175                for arg in it {
176                    write!(fmt, "{arg}, ")?;
177                }
178
179                if let Some(arg) = last {
180                    write!(fmt, "{arg}")?;
181                }
182
183                write!(fmt, ")")?;
184            }
185            DebugArgs::Named(args) => {
186                write!(fmt, "{}(", self.path)?;
187
188                let mut it = args.iter();
189                let last = it.next_back();
190
191                for arg in it {
192                    write!(fmt, "{arg}, ")?;
193                }
194
195                if let Some(arg) = last {
196                    write!(fmt, "{arg}")?;
197                }
198
199                write!(fmt, ")")?;
200            }
201            _ => (),
202        }
203
204        Ok(())
205    }
206}