Skip to main content

opy_rs/
diag.rs

1//! Frontend diagnostics: structured, source-located failures.
2//!
3//! Every frontend failure is a [`OpyError`] with a stable `code`, a
4//! human message, and an optional source span. The `code` is the machine
5//! contract; wording is not.
6//!
7//! [`Position`] is serializable so tooling surfaces ([`crate::tooling`]) can
8//! emit resolved source locations as JSON without introducing a parallel
9//! position type.
10
11/// A structured frontend error.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct OpyError {
14    /// A stable machine-readable code, e.g. `parse-error`.
15    pub code: String,
16    /// Human-readable message (not part of the machine contract).
17    pub message: String,
18    /// The offending source region, when known.
19    pub span: Option<Span>,
20}
21
22/// A source span in the frontend's file registry.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct Span {
25    pub file: u32,
26    pub start: Position,
27    pub end: Position,
28}
29
30/// A 1-based line/column position.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
32pub struct Position {
33    pub line: u32,
34    pub col: u32,
35}
36
37impl Position {
38    pub const fn new(line: u32, col: u32) -> Position {
39        Position { line, col }
40    }
41}
42
43impl Span {
44    pub fn new(file: u32, start: Position, end: Position) -> Span {
45        Span { file, start, end }
46    }
47}
48
49/// A crate-wide result alias.
50pub type OpyResult<T> = Result<T, OpyError>;
51
52impl OpyError {
53    /// An error without a source span.
54    pub fn new(code: impl Into<String>, message: impl Into<String>) -> OpyError {
55        OpyError {
56            code: code.into(),
57            message: message.into(),
58            span: None,
59        }
60    }
61
62    /// An error at a source position.
63    pub fn at(code: impl Into<String>, message: impl Into<String>, span: Span) -> OpyError {
64        OpyError {
65            code: code.into(),
66            message: message.into(),
67            span: Some(span),
68        }
69    }
70}
71
72impl std::fmt::Display for OpyError {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        write!(f, "{}: {}", self.code, self.message)
75    }
76}
77
78impl std::error::Error for OpyError {}