Skip to main content

lean_rs_host/host/elaboration/
diagnostic.rs

1//! Typed diagnostic surface attached to elaboration / kernel-check
2//! failures.
3//!
4//! Lean's `MessageLog` carries a severity tag, a human-readable message,
5//! and an optional source position. The capability shim copies each
6//! diagnostic into a `Diagnostic` structure on the Lean side; the impls
7//! in this module decode them into Rust [`LeanDiagnostic`] /
8//! [`LeanPosition`] values without inspecting Lean's internal
9//! representation.
10//!
11//! The encoding contract (mirrored in `Elaboration.lean`):
12//!
13//! - `Diagnostic = lean_alloc_ctor(0, 3, 1)` — three object slots
14//!   (message, position, fileLabel) and one scalar byte (severity at
15//!   offset 0 of the scalar tail).
16//! - `DiagnosticPos = lean_alloc_ctor(0, 4, 0)` — four object slots
17//!   (line, column, endLine, endColumn) carrying `Nat` and `Option Nat`
18//!   values. `Nat` is scalar-tagged for small values (always true for
19//!   source positions), so each slot decodes through
20//!   [`lean_rs::abi::nat::try_to_u64`].
21
22// SAFETY DOC: every `unsafe { ... }` block in this file carries its own
23// `// SAFETY:` comment; the blanket allow keeps the scope minimal per
24// `docs/architecture/01-safety-model.md`.
25#![allow(unsafe_code)]
26
27use lean_rs_sys::ctor::lean_ctor_get_uint8;
28use lean_rs_sys::object::{lean_is_scalar, lean_obj_tag, lean_unbox};
29
30use lean_rs::Obj;
31use lean_rs::abi::nat;
32use lean_rs::abi::structure::{ctor_tag, take_ctor_objects};
33use lean_rs::abi::traits::{TryFromLean, conversion_error};
34use lean_rs::error::{LeanResult, bound_message};
35
36/// Severity classification attached to each [`LeanDiagnostic`]. Mirrors
37/// Lean's `MessageSeverity` constructors at 4.29.1.
38#[derive(Copy, Clone, Debug, Eq, PartialEq)]
39pub enum LeanSeverity {
40    /// Informational diagnostic; the operation may still have succeeded.
41    Info,
42    /// Warning diagnostic; the operation may still have succeeded.
43    Warning,
44    /// Error diagnostic; the operation did not succeed.
45    Error,
46}
47
48impl LeanSeverity {
49    /// Decode the byte the Lean side wrote for the `severity` scalar field.
50    /// `0 = info`, `1 = warning`, `2 = error` per the Lean-side
51    /// declaration order of `LeanRsHostShims.Elaboration.Severity`.
52    fn from_byte(byte: u8) -> LeanResult<Self> {
53        match byte {
54            0 => Ok(Self::Info),
55            1 => Ok(Self::Warning),
56            2 => Ok(Self::Error),
57            other => Err(conversion_error(format!(
58                "Lean Severity tag {other} is not in {{0=info, 1=warning, 2=error}}"
59            ))),
60        }
61    }
62}
63
64/// Source position attached to a Lean-emitted diagnostic.
65///
66/// `line` and `column` are 1-indexed (Lean convention). `end_line` /
67/// `end_column` are present when Lean attached an end position to the
68/// diagnostic — parser errors usually carry only a start position, while
69/// elaborator and kernel errors carry both.
70#[derive(Copy, Clone, Debug, Eq, PartialEq)]
71pub struct LeanPosition {
72    line: u32,
73    column: u32,
74    end_line: Option<u32>,
75    end_column: Option<u32>,
76}
77
78impl LeanPosition {
79    /// 1-indexed line number.
80    #[must_use]
81    pub fn line(&self) -> u32 {
82        self.line
83    }
84
85    /// 1-indexed column number.
86    #[must_use]
87    pub fn column(&self) -> u32 {
88        self.column
89    }
90
91    /// 1-indexed end line, if Lean attached one.
92    #[must_use]
93    pub fn end_line(&self) -> Option<u32> {
94        self.end_line
95    }
96
97    /// 1-indexed end column, if Lean attached one.
98    #[must_use]
99    pub fn end_column(&self) -> Option<u32> {
100        self.end_column
101    }
102}
103
104impl<'lean> TryFromLean<'lean> for LeanPosition {
105    fn try_from_lean(obj: Obj<'lean>) -> LeanResult<Self> {
106        let [line_o, column_o, end_line_o, end_column_o] = take_ctor_objects::<4>(obj, 0, "DiagnosticPos")?;
107        Ok(Self {
108            line: decode_nat_u32(line_o, "DiagnosticPos.line")?,
109            column: decode_nat_u32(column_o, "DiagnosticPos.column")?,
110            end_line: decode_option_nat_u32(end_line_o, "DiagnosticPos.endLine")?,
111            end_column: decode_option_nat_u32(end_column_o, "DiagnosticPos.endColumn")?,
112        })
113    }
114}
115
116/// One Lean-emitted diagnostic: severity tag, bounded message, optional
117/// source position, and the file label the elaborator received.
118///
119/// The `message` is structurally bounded at
120/// [`lean_rs::LEAN_ERROR_MESSAGE_LIMIT`]: the decoder truncates on a UTF-8
121/// char boundary before storing.
122#[derive(Clone, Debug)]
123pub struct LeanDiagnostic {
124    severity: LeanSeverity,
125    message: String,
126    position: Option<LeanPosition>,
127    file_label: String,
128}
129
130impl LeanDiagnostic {
131    /// The severity tag Lean attached to this diagnostic.
132    #[must_use]
133    pub fn severity(&self) -> LeanSeverity {
134        self.severity
135    }
136
137    /// Lean's diagnostic message, truncated to at most
138    /// [`lean_rs::LEAN_ERROR_MESSAGE_LIMIT`] bytes on a UTF-8 char
139    /// boundary.
140    #[must_use]
141    pub fn message(&self) -> &str {
142        &self.message
143    }
144
145    /// Source position when Lean attached one. Parser-level errors
146    /// often carry no position; elaborator and kernel errors do.
147    #[must_use]
148    pub fn position(&self) -> Option<&LeanPosition> {
149        self.position.as_ref()
150    }
151
152    /// The file label this diagnostic belongs to. Falls back to the
153    /// caller-supplied [`crate::host::elaboration::LeanElabOptions::file_label`]
154    /// when Lean's own `MessageLog` did not carry a file name.
155    #[must_use]
156    pub fn file_label(&self) -> &str {
157        &self.file_label
158    }
159
160    /// Construct a synthetic error-severity diagnostic without a source
161    /// position. Used by the host stack when it must surface a
162    /// diagnostic that did not originate in Lean's `MessageLog` — for
163    /// example, the `LeanMetaResponse::Unsupported` branch built when a
164    /// capability dylib does not export the requested meta service.
165    /// The `message` is bounded at [`lean_rs::LEAN_ERROR_MESSAGE_LIMIT`]
166    /// on a UTF-8 char boundary, mirroring the Lean-decoded path.
167    pub(crate) fn synthetic_error(message: String, file_label: String) -> Self {
168        Self {
169            severity: LeanSeverity::Error,
170            message: bound_message(message),
171            position: None,
172            file_label,
173        }
174    }
175}
176
177impl<'lean> TryFromLean<'lean> for LeanDiagnostic {
178    fn try_from_lean(obj: Obj<'lean>) -> LeanResult<Self> {
179        require_diagnostic_ctor(&obj)?;
180        let ptr = obj.as_raw_borrowed();
181        // SAFETY: ctor shape validated above; `lean_ctor_scalar_cptr`
182        // starts immediately past the object slots, so offset 0 reads
183        // the first scalar tail byte (the severity tag the Lean-side
184        // constructor writes via `lean_ctor_set_uint8(_,
185        // sizeof(void*)*num_objs, _)`).
186        let severity_byte = unsafe { lean_ctor_get_uint8(ptr, 0) };
187        let [msg_o, pos_o, label_o] = take_ctor_objects::<3>(obj, 0, "Diagnostic")?;
188        let severity = LeanSeverity::from_byte(severity_byte)?;
189        let message = bound_message(String::try_from_lean(msg_o)?);
190        let position = Option::<LeanPosition>::try_from_lean(pos_o)?;
191        let file_label = String::try_from_lean(label_o)?;
192        Ok(Self {
193            severity,
194            message,
195            position,
196            file_label,
197        })
198    }
199}
200
201/// Tag-only check; the field-count check happens inside
202/// [`take_ctor_objects`] below.
203fn require_diagnostic_ctor(obj: &Obj<'_>) -> LeanResult<()> {
204    let tag = ctor_tag(obj)?;
205    if tag == 0 {
206        Ok(())
207    } else {
208        Err(conversion_error(format!(
209            "expected Lean Diagnostic ctor (tag 0), found tag {tag}"
210        )))
211    }
212}
213
214/// Decode a Lean `Nat` slot to a `u32`, refusing values that overflow.
215fn decode_nat_u32(obj: Obj<'_>, label: &str) -> LeanResult<u32> {
216    let raw = nat::try_to_u64(obj)?;
217    u32::try_from(raw).map_err(|_| conversion_error(format!("{label} = {raw} exceeds u32 range")))
218}
219
220/// Decode a Lean `Option Nat` slot, refusing wrong tags / out-of-range
221/// `Some` payloads. Inlined rather than reusing [`Option<T>`]'s blanket
222/// impl because the inner `T = Nat` does not match the polymorphic-boxed
223/// `u32::try_from_lean` ABI (Nat is scalar-tagged, `UInt32` in
224/// polymorphic position is ctor-boxed).
225fn decode_option_nat_u32(obj: Obj<'_>, label: &str) -> LeanResult<Option<u32>> {
226    let ptr = obj.as_raw_borrowed();
227    // SAFETY: pure pointer-bit math.
228    if unsafe { lean_is_scalar(ptr) } {
229        // SAFETY: scalar branch verified above.
230        let payload = unsafe { lean_unbox(ptr) };
231        return match payload {
232            0 => Ok(None),
233            other => Err(conversion_error(format!(
234                "{label}: expected Option.none (scalar tag 0), found scalar payload {other}"
235            ))),
236        };
237    }
238    // SAFETY: non-scalar branch; tag read on the owned object header.
239    let tag = unsafe { lean_obj_tag(ptr) };
240    if tag != 1 {
241        return Err(conversion_error(format!(
242            "{label}: expected Option.some ctor (tag 1), found heap tag {tag}"
243        )));
244    }
245    let [inner] = take_ctor_objects::<1>(obj, 1, "Option Nat")?;
246    Ok(Some(decode_nat_u32(inner, label)?))
247}