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 this error with the supplied grammar context.
103 #[must_use = "the updated syntax error must be used"]
104 #[inline(always)]
105 pub const fn with_context(mut self, context: JsonDecodeContext) -> Self {
106 self.context = Some(context);
107 self
108 }
109
110 /// Returns the zero-based byte offset.
111 ///
112 /// # Returns
113 ///
114 /// The zero-based byte offset at which the error was observed.
115 #[must_use]
116 #[inline(always)]
117 pub const fn offset(&self) -> usize {
118 self.offset
119 }
120
121 /// Returns the one-based source line.
122 ///
123 /// # Returns
124 ///
125 /// The one-based source line containing the error.
126 #[must_use]
127 #[inline(always)]
128 pub const fn line(&self) -> usize {
129 self.line
130 }
131
132 /// Returns the one-based UTF-8 character column.
133 ///
134 /// # Returns
135 ///
136 /// The one-based UTF-8 character column containing the error.
137 #[must_use]
138 #[inline(always)]
139 pub const fn column(&self) -> usize {
140 self.column
141 }
142
143 /// Returns the stable syntax classification.
144 ///
145 /// # Returns
146 ///
147 /// The stable lexical failure classification.
148 #[inline(always)]
149 pub const fn reason(&self) -> JsonSyntaxErrorReason {
150 self.reason
151 }
152}
153
154impl fmt::Display for JsonSyntaxError {
155 /// Formats the reason and complete source location for human-readable
156 /// diagnostics.
157 ///
158 /// # Errors
159 ///
160 /// Returns the formatter's error if writing the diagnostic to its output
161 /// fails.
162 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
163 write!(
164 formatter,
165 "{} at line {} column {} (byte offset {})",
166 self.reason, self.line, self.column, self.offset,
167 )
168 }
169}
170
171impl Error for JsonSyntaxError {}