qubit-json 0.9.0

Resource-aware infrastructure for lenient and strict JSON processing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Defines the shared error returned by all JSON decoding facades.

use std::error::Error;
use std::fmt;
use std::sync::Arc;

use qubit_budget::MeasuredBudgetError;
use qubit_budget::ResourceQuantity;
use qubit_budget::json::JsonResource;
use serde_json::Error as JsonError;

use super::DiagnosticPolicy;
use super::JsonDecodeErrorKind;
use super::JsonDecodeErrorSource;
use super::JsonDecodeStage;
use super::JsonRootKind;
use super::JsonSyntaxError;
use crate::lexical::JsonLexicalFailure;

/// Failure produced by either strict or normalizing JSON decoding.
///
/// Internal variants are private so callers branch through stable semantic
/// accessors rather than depending on scanner, normalizer, or Serde details.
///
/// # Type Parameters
///
/// * `R` - Resource identity attached to budget failures.
/// * `Q` - Quantity representation attached to budget failures.
///
/// # Examples
///
/// ```
/// use qubit_json::decode::{JsonDecodeError, JsonDecodeErrorKind, JsonDecoder};
/// use serde_json::Value;
///
/// let mut decoder = JsonDecoder::unlimited();
/// let error: JsonDecodeError = decoder
///     .decode_str::<Value>("")
///     .expect_err("empty input must be rejected");
/// assert_eq!(error.kind(), JsonDecodeErrorKind::InvalidJson);
/// ```
#[must_use]
#[derive(Clone)]
pub struct JsonDecodeError<R = JsonResource, Q = usize>
where
    Q: Copy + fmt::Debug,
{
    /// Policy controlling input-derived source retention.
    diagnostic_policy: DiagnosticPolicy,
    /// Mutually exclusive structured failure.
    failure: JsonDecodeErrorSource<R, Q>,
}

impl<R, Q> JsonDecodeError<R, Q>
where
    Q: Copy + fmt::Debug,
{
    /// Creates a measured-budget failure at a semantic stage.
    #[must_use = "return or inspect the constructed decoding error"]
    pub(crate) const fn budget(
        source: MeasuredBudgetError<R, Q>,
        stage: JsonDecodeStage,
        raw_input_bytes: usize,
        normalized_input_bytes: Option<usize>,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        Self {
            diagnostic_policy,
            failure: JsonDecodeErrorSource::Budget {
                stage,
                raw_input_bytes,
                normalized_input_bytes,
                source,
            },
        }
    }

    /// Creates an empty-input failure at a semantic stage.
    #[must_use = "return or inspect the constructed decoding error"]
    pub(crate) const fn empty_input(
        stage: JsonDecodeStage,
        raw_input_bytes: usize,
        normalized_input_bytes: Option<usize>,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        Self {
            diagnostic_policy,
            failure: JsonDecodeErrorSource::EmptyInput {
                stage,
                raw_input_bytes,
                normalized_input_bytes,
            },
        }
    }

    /// Creates an invalid-UTF-8 failure and conditionally retains its source.
    #[must_use = "return or inspect the constructed decoding error"]
    pub(crate) fn invalid_utf8(
        source: std::str::Utf8Error,
        raw_input_bytes: usize,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        let valid_up_to = source.valid_up_to();
        let error_len = source.error_len();
        let source = (diagnostic_policy == DiagnosticPolicy::Detailed).then_some(source);
        Self {
            diagnostic_policy,
            failure: JsonDecodeErrorSource::InvalidUtf8 {
                raw_input_bytes,
                valid_up_to,
                error_len,
                source,
            },
        }
    }

    /// Creates a stable invalid-JSON failure from lexical admission.
    #[must_use = "return or inspect the constructed decoding error"]
    pub(crate) fn invalid_json(
        syntax_source: JsonLexicalFailure,
        detailed_source: Option<Arc<dyn Error + Send + Sync>>,
        raw_input_bytes: usize,
        normalized_input_bytes: Option<usize>,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        Self {
            diagnostic_policy,
            failure: JsonDecodeErrorSource::InvalidJson {
                raw_input_bytes,
                normalized_input_bytes,
                syntax: JsonSyntaxError::from_lexical(syntax_source),
                source: detailed_source,
            },
        }
    }

    /// Creates an unexpected-top-level failure.
    #[must_use = "return or inspect the constructed decoding error"]
    pub(crate) const fn unexpected_top_level(
        expected: JsonRootKind,
        actual: JsonRootKind,
        raw_input_bytes: usize,
        normalized_input_bytes: Option<usize>,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        Self {
            diagnostic_policy,
            failure: JsonDecodeErrorSource::UnexpectedTopLevel {
                raw_input_bytes,
                normalized_input_bytes,
                expected,
                actual,
            },
        }
    }

    /// Creates a target-deserialization failure and conditionally retains its
    /// input-derived source.
    #[must_use = "return or inspect the constructed decoding error"]
    pub(crate) fn deserialize(
        source: JsonError,
        raw_input_bytes: usize,
        normalized_input_bytes: Option<usize>,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        let line = source.line();
        let column = source.column();
        let source =
            (diagnostic_policy == DiagnosticPolicy::Detailed).then(|| Arc::new(source) as Arc<dyn Error + Send + Sync>);
        Self {
            diagnostic_policy,
            failure: JsonDecodeErrorSource::Deserialize {
                raw_input_bytes,
                normalized_input_bytes,
                line,
                column,
                source,
            },
        }
    }

    /// Returns the stable failure category.
    ///
    /// # Returns
    ///
    /// The category describing which kind of decode operation failed.
    #[must_use]
    #[inline(always)]
    pub const fn kind(&self) -> JsonDecodeErrorKind {
        match self.failure {
            JsonDecodeErrorSource::Budget { .. } => JsonDecodeErrorKind::Budget,
            JsonDecodeErrorSource::EmptyInput { .. } => JsonDecodeErrorKind::EmptyInput,
            JsonDecodeErrorSource::InvalidUtf8 { .. } => JsonDecodeErrorKind::InvalidUtf8,
            JsonDecodeErrorSource::InvalidJson { .. } => JsonDecodeErrorKind::InvalidJson,
            JsonDecodeErrorSource::UnexpectedTopLevel { .. } => JsonDecodeErrorKind::UnexpectedTopLevel,
            JsonDecodeErrorSource::Deserialize { .. } => JsonDecodeErrorKind::Deserialize,
        }
    }

    /// Returns the semantic stage that produced the failure.
    ///
    /// # Returns
    ///
    /// The pipeline stage at which the failure was recorded.
    #[must_use]
    #[inline(always)]
    pub const fn stage(&self) -> JsonDecodeStage {
        match self.failure {
            JsonDecodeErrorSource::Budget { stage, .. } | JsonDecodeErrorSource::EmptyInput { stage, .. } => stage,
            JsonDecodeErrorSource::InvalidUtf8 { .. } => JsonDecodeStage::DecodeText,
            JsonDecodeErrorSource::InvalidJson { .. } => JsonDecodeStage::Parse,
            JsonDecodeErrorSource::UnexpectedTopLevel { .. } => JsonDecodeStage::TopLevelCheck,
            JsonDecodeErrorSource::Deserialize { .. } => JsonDecodeStage::Deserialize,
        }
    }

    /// Returns the diagnostic policy applied while constructing this error.
    ///
    /// # Returns
    ///
    /// The policy that determines whether input-derived details are retained.
    #[must_use]
    #[inline(always)]
    pub const fn diagnostic_policy(&self) -> DiagnosticPolicy {
        self.diagnostic_policy
    }

    /// Returns the original input length in bytes.
    ///
    /// # Returns
    ///
    /// The number of bytes charged for the input that caused this error.
    #[must_use]
    #[inline(always)]
    pub const fn raw_input_bytes(&self) -> usize {
        match self.failure {
            JsonDecodeErrorSource::Budget { raw_input_bytes, .. }
            | JsonDecodeErrorSource::EmptyInput { raw_input_bytes, .. }
            | JsonDecodeErrorSource::InvalidUtf8 { raw_input_bytes, .. }
            | JsonDecodeErrorSource::InvalidJson { raw_input_bytes, .. }
            | JsonDecodeErrorSource::UnexpectedTopLevel { raw_input_bytes, .. }
            | JsonDecodeErrorSource::Deserialize { raw_input_bytes, .. } => raw_input_bytes,
        }
    }

    /// Returns the normalized text length when normalization completed.
    ///
    /// # Returns
    ///
    /// `Some(length)` when normalization produced text, or `None` when the
    /// failure occurred before a normalized document existed.
    #[must_use]
    #[inline(always)]
    pub const fn normalized_input_bytes(&self) -> Option<usize> {
        match self.failure {
            JsonDecodeErrorSource::Budget {
                normalized_input_bytes, ..
            }
            | JsonDecodeErrorSource::EmptyInput {
                normalized_input_bytes, ..
            }
            | JsonDecodeErrorSource::InvalidJson {
                normalized_input_bytes, ..
            }
            | JsonDecodeErrorSource::UnexpectedTopLevel {
                normalized_input_bytes, ..
            }
            | JsonDecodeErrorSource::Deserialize {
                normalized_input_bytes, ..
            } => normalized_input_bytes,
            JsonDecodeErrorSource::InvalidUtf8 { .. } => None,
        }
    }

    /// Returns the one-based error line when available.
    ///
    /// # Returns
    ///
    /// `Some(line)` for failures with source coordinates, otherwise `None`.
    #[must_use]
    #[inline(always)]
    pub const fn line(&self) -> Option<usize> {
        match &self.failure {
            JsonDecodeErrorSource::InvalidJson { syntax, .. } => Some(syntax.line()),
            JsonDecodeErrorSource::Deserialize { line, .. } if *line > 0 => Some(*line),
            _ => None,
        }
    }

    /// Returns the one-based error column when available.
    ///
    /// # Returns
    ///
    /// `Some(column)` for failures with source coordinates, otherwise `None`.
    #[must_use]
    #[inline(always)]
    pub const fn column(&self) -> Option<usize> {
        match &self.failure {
            JsonDecodeErrorSource::InvalidJson { syntax, .. } => Some(syntax.column()),
            JsonDecodeErrorSource::Deserialize { column, .. } if *column > 0 => Some(*column),
            _ => None,
        }
    }

    /// Returns the structured syntax failure for invalid JSON.
    ///
    /// # Returns
    ///
    /// A borrowed syntax error when parsing failed, otherwise `None`.
    #[must_use]
    #[inline(always)]
    pub const fn syntax_error(&self) -> Option<&JsonSyntaxError> {
        match &self.failure {
            JsonDecodeErrorSource::InvalidJson { syntax, .. } => Some(syntax),
            _ => None,
        }
    }

    /// Returns the complete measured-budget failure when present.
    ///
    /// # Returns
    ///
    /// A borrowed budget error when resource accounting rejected the input,
    /// otherwise `None`.
    #[must_use]
    #[inline(always)]
    pub const fn budget_error(&self) -> Option<&MeasuredBudgetError<R, Q>> {
        match &self.failure {
            JsonDecodeErrorSource::Budget { source, .. } => Some(source),
            _ => None,
        }
    }

    /// Returns the valid UTF-8 prefix length for invalid byte input.
    ///
    /// # Returns
    ///
    /// `Some(bytes)` for an invalid UTF-8 failure, or `None` for other failure
    /// kinds.
    #[must_use]
    #[inline(always)]
    pub const fn utf8_valid_up_to(&self) -> Option<usize> {
        match self.failure {
            JsonDecodeErrorSource::InvalidUtf8 { valid_up_to, .. } => Some(valid_up_to),
            _ => None,
        }
    }

    /// Returns the invalid UTF-8 sequence length when known.
    ///
    /// # Returns
    ///
    /// The length of the invalid sequence when the decoder can determine it,
    /// otherwise `None`.
    #[must_use]
    #[inline(always)]
    pub const fn utf8_error_len(&self) -> Option<usize> {
        match self.failure {
            JsonDecodeErrorSource::InvalidUtf8 { error_len, .. } => error_len,
            _ => None,
        }
    }

    /// Returns the expected top-level kind for a constrained decode failure.
    ///
    /// # Returns
    ///
    /// The required root kind when a constrained operation failed, otherwise
    /// `None`.
    #[must_use]
    #[inline(always)]
    pub const fn expected_top_level(&self) -> Option<JsonRootKind> {
        match self.failure {
            JsonDecodeErrorSource::UnexpectedTopLevel { expected, .. } => Some(expected),
            _ => None,
        }
    }

    /// Returns the observed top-level kind for a constrained decode failure.
    ///
    /// # Returns
    ///
    /// The root kind observed in the valid document, otherwise `None`.
    #[must_use]
    #[inline(always)]
    pub const fn actual_top_level(&self) -> Option<JsonRootKind> {
        match self.failure {
            JsonDecodeErrorSource::UnexpectedTopLevel { actual, .. } => Some(actual),
            _ => None,
        }
    }

    /// Consumes this error and returns its owned semantic source.
    ///
    /// Unlike the kind-specific accessors, this operation preserves the
    /// complete mutually exclusive failure state. Input-derived third-party
    /// sources remain present only when the decoder used
    /// [`DiagnosticPolicy::Detailed`].
    ///
    /// # Returns
    ///
    /// The structured budget, input, syntax, top-level, or deserialization
    /// source retained by this error.
    #[inline(always)]
    pub fn into_source(self) -> JsonDecodeErrorSource<R, Q> {
        self.failure
    }
}

impl<R, Q> fmt::Debug for JsonDecodeError<R, Q>
where
    R: fmt::Debug,
    Q: Copy + fmt::Debug,
{
    /// Formats structured diagnostics retained under the active policy.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("JsonDecodeError")
            .field("diagnostic_policy", &self.diagnostic_policy)
            .field("failure", &self.failure)
            .finish()
    }
}

impl<R, Q> fmt::Display for JsonDecodeError<R, Q>
where
    R: fmt::Debug,
    Q: ResourceQuantity,
{
    /// Formats a privacy-safe or detailed message according to the policy.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.failure {
            JsonDecodeErrorSource::Budget { source, .. } => {
                write!(formatter, "JSON resource budget rejected input: {source}")
            }
            JsonDecodeErrorSource::EmptyInput { .. } => formatter.write_str("JSON input is empty after normalization"),
            JsonDecodeErrorSource::InvalidUtf8 { source, .. } => match source {
                Some(source) => write!(formatter, "Failed to decode JSON input as UTF-8: {source}"),
                None => formatter.write_str("Failed to decode JSON input as UTF-8"),
            },
            JsonDecodeErrorSource::InvalidJson { syntax, source, .. } => match source {
                Some(source) => {
                    write!(formatter, "Failed to parse JSON: {source}")
                }
                None => write!(formatter, "Failed to parse JSON: {syntax}"),
            },
            JsonDecodeErrorSource::UnexpectedTopLevel { expected, actual, .. } => {
                write!(
                    formatter,
                    "Unexpected JSON top-level type: expected {expected}, got {actual}"
                )
            }
            JsonDecodeErrorSource::Deserialize {
                normalized_input_bytes,
                line,
                column,
                source,
                ..
            } => match source {
                Some(source) => write!(formatter, "Failed to deserialize JSON value: {source}"),
                None if normalized_input_bytes.is_some() => write!(
                    formatter,
                    "Failed to deserialize JSON value at normalized line {line} column {column}"
                ),
                None => write!(
                    formatter,
                    "Failed to deserialize JSON value at line {line} column {column}"
                ),
            },
        }
    }
}

impl<R, Q> Error for JsonDecodeError<R, Q>
where
    R: fmt::Debug + 'static,
    Q: ResourceQuantity + 'static,
{
    /// Returns budget sources unconditionally and input-derived sources only
    /// when detailed diagnostics retained them.
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match &self.failure {
            JsonDecodeErrorSource::Budget { source, .. } => Some(source),
            JsonDecodeErrorSource::InvalidUtf8 {
                source: Some(source), ..
            } => Some(source),
            JsonDecodeErrorSource::InvalidJson {
                source: Some(source), ..
            } => Some(source.as_ref()),
            JsonDecodeErrorSource::Deserialize {
                source: Some(source), ..
            } => Some(source.as_ref()),
            _ => None,
        }
    }
}