Skip to main content

qubit_json/decode/
json_syntax_error.rs

1// =============================================================================
2//    Copyright (c) 2025 - 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Structured location-aware JSON lexical errors.
9
10use std::error::Error;
11use std::fmt;
12
13use super::JsonDecodeContext;
14use super::JsonSyntaxErrorReason;
15use crate::lexical::JsonLexicalFailure;
16
17/// A JSON syntax error with a zero-based byte offset and one-based source
18/// coordinates. Its column counts UTF-8 characters; CRLF is one line break,
19/// while LF and standalone CR each also start a new line.
20///
21/// # Examples
22///
23/// ```
24/// use qubit_json::decode::{JsonSyntaxError, JsonSyntaxErrorReason};
25///
26/// let error = JsonSyntaxError::new(
27///     0,
28///     1,
29///     1,
30///     JsonSyntaxErrorReason::UnexpectedEnd,
31/// );
32/// assert_eq!(error.line(), 1);
33/// assert_eq!(error.reason(), JsonSyntaxErrorReason::UnexpectedEnd);
34/// ```
35#[must_use]
36#[derive(Clone, Copy, Debug, Eq, PartialEq)]
37pub struct JsonSyntaxError {
38    /// Zero-based byte offset at which the error was observed.
39    offset: usize,
40    /// One-based source line containing the error.
41    line: usize,
42    /// One-based UTF-8 character column containing the error.
43    column: usize,
44    /// Stable classification of the lexical failure.
45    reason: JsonSyntaxErrorReason,
46    /// Grammar location where the lexical failure occurred, when known.
47    context: Option<JsonDecodeContext>,
48}
49
50impl JsonSyntaxError {
51    /// Creates a syntax error from a source position and stable reason.
52    ///
53    /// # Parameters
54    ///
55    /// * `offset` - Zero-based byte offset at which the error was observed.
56    /// * `line` - One-based source line containing the error.
57    /// * `column` - One-based UTF-8 character column containing the error.
58    /// * `reason` - Stable classification of the lexical failure.
59    ///
60    /// # Returns
61    ///
62    /// A syntax error containing the supplied location and classification.
63    #[inline]
64    pub const fn new(offset: usize, line: usize, column: usize, reason: JsonSyntaxErrorReason) -> Self {
65        Self {
66            offset,
67            line,
68            column,
69            reason,
70            context: None,
71        }
72    }
73
74    /// Converts a crate-private lexical failure into the text-domain syntax
75    /// error.
76    ///
77    /// The byte offset, line, and column are preserved, while the lexical
78    /// reason is mapped to its syntax-error classification.
79    ///
80    /// # Parameters
81    ///
82    /// * `failure` - The lexical failure whose location and reason are
83    ///   converted.
84    ///
85    /// # Returns
86    ///
87    /// A syntax error with the lexical failure's source coordinates and mapped
88    /// reason.
89    pub(crate) fn from_lexical(failure: JsonLexicalFailure) -> Self {
90        let mut error = Self::new(failure.offset, failure.line, failure.column, failure.reason.into());
91        error.context = failure.context;
92        error
93    }
94
95    /// Returns the grammar location where the error occurred, when known.
96    #[must_use]
97    #[inline(always)]
98    pub const fn context(&self) -> Option<JsonDecodeContext> {
99        self.context
100    }
101
102    /// Returns the zero-based byte offset.
103    ///
104    /// # Returns
105    ///
106    /// The zero-based byte offset at which the error was observed.
107    #[must_use]
108    #[inline(always)]
109    pub const fn offset(&self) -> usize {
110        self.offset
111    }
112
113    /// Returns the one-based source line.
114    ///
115    /// # Returns
116    ///
117    /// The one-based source line containing the error.
118    #[must_use]
119    #[inline(always)]
120    pub const fn line(&self) -> usize {
121        self.line
122    }
123
124    /// Returns the one-based UTF-8 character column.
125    ///
126    /// # Returns
127    ///
128    /// The one-based UTF-8 character column containing the error.
129    #[must_use]
130    #[inline(always)]
131    pub const fn column(&self) -> usize {
132        self.column
133    }
134
135    /// Returns the stable syntax classification.
136    ///
137    /// # Returns
138    ///
139    /// The stable lexical failure classification.
140    #[inline(always)]
141    pub const fn reason(&self) -> JsonSyntaxErrorReason {
142        self.reason
143    }
144
145    /// Returns this error with the supplied grammar context.
146    ///
147    /// # Parameters
148    ///
149    /// * `context` - Grammar location associated with this syntax error.
150    #[must_use = "the updated syntax error must be used"]
151    #[inline(always)]
152    pub const fn with_context(mut self, context: JsonDecodeContext) -> Self {
153        self.context = Some(context);
154        self
155    }
156}
157
158impl fmt::Display for JsonSyntaxError {
159    /// Formats the reason and complete source location for human-readable
160    /// diagnostics.
161    ///
162    /// # Parameters
163    ///
164    /// * `formatter` - Destination that receives the human-readable diagnostic.
165    ///
166    /// # Errors
167    ///
168    /// Returns the formatter's error if writing the diagnostic to its output
169    /// fails.
170    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
171        write!(
172            formatter,
173            "{} at line {} column {} (byte offset {})",
174            self.reason, self.line, self.column, self.offset,
175        )
176    }
177}
178
179impl Error for JsonSyntaxError {}