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
// =============================================================================
// Copyright (c) 2026 Haixing Hu.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Non-recursive lexical admission for one JSON input document.
use qubit_budget::ResourceQuantity;
use qubit_budget::json::JsonValueTransaction;
use super::JsonLexicalAdmissionPolicy;
use super::internal::JsonLexicalContainerFrame;
use super::internal::json_lexical_cursor::JsonLexicalCursor;
use super::json_lexical_consumer::JsonLexicalConsumer;
use super::json_lexical_delimiter_check_timing::JsonLexicalDelimiterCheckTiming;
use super::json_lexical_error::JsonLexicalError;
use super::json_lexical_error_reason::JsonLexicalErrorReason;
use super::json_lexical_event::JsonLexicalEvent;
use super::json_lexical_scan_error::JsonLexicalScanError;
use super::json_lexical_scan_point::JsonLexicalScanPoint;
use super::json_number_model::JsonNumberModel;
use crate::decode::JsonDecodeContext;
/// Lexically validates and charges one JSON document without recursion.
///
/// # Type Parameters
///
/// * `R` - Resource identity type used by the value transaction.
/// * `Q` - Quantity representation used for resource accounting.
#[must_use]
pub(crate) struct JsonLexicalScanner<'transaction, 'budget, R, Q>
where
Q: ResourceQuantity,
{
/// JSON value resources charged while scanning the document.
transaction: &'transaction mut JsonValueTransaction<'budget, R, Q>,
/// Root-inclusive depth assigned to the scanned value.
root_depth: usize,
/// Whether scanning must stage JSON value measurements.
has_value_limits: bool,
/// Numeric range contract selected by the owning decoder.
number_model: JsonNumberModel,
/// Determines whether token admission uses delimiter-first or token-first
/// checks.
admission_policy: JsonLexicalAdmissionPolicy,
/// Selects when a consumer scan checks number delimiters.
delimiter_check_timing: JsonLexicalDelimiterCheckTiming,
/// Optional maximum root-inclusive depth; `None` adds no depth cap.
depth_limit: Option<Q>,
/// Optional maximum encoded bytes inside each string token, excluding
/// quotes.
max_encoded_string_bytes: Option<usize>,
}
impl<'transaction, 'budget, R, Q> JsonLexicalScanner<'transaction, 'budget, R, Q>
where
R: Clone,
Q: ResourceQuantity,
{
/// Creates a lexical scanner bound to one value transaction.
///
/// # Parameters
///
/// * `transaction` - Value transaction charged for admitted measurements.
/// * `has_value_limits` - Whether scanning stages value measurements.
///
/// # Returns
///
/// A scanner rooted at depth one using the `Integer64` number model.
#[inline(always)]
pub(crate) const fn new(
transaction: &'transaction mut JsonValueTransaction<'budget, R, Q>,
has_value_limits: bool,
) -> Self {
Self {
transaction,
root_depth: 1,
has_value_limits,
number_model: JsonNumberModel::Integer64,
admission_policy: JsonLexicalAdmissionPolicy::Immediate,
delimiter_check_timing: JsonLexicalDelimiterCheckTiming::Immediate,
depth_limit: None,
max_encoded_string_bytes: None,
}
}
/// Creates a lexical scanner rooted at an enclosing serializer depth.
///
/// # Parameters
///
/// * `transaction` - Value transaction charged for admitted measurements.
/// * `root_depth` - Root-inclusive depth assigned to the scanned value.
/// * `has_value_limits` - Whether scanning stages value measurements.
///
/// # Returns
///
/// A scanner using the specified root depth and the `Integer64` model.
#[inline(always)]
pub(crate) const fn at_depth(
transaction: &'transaction mut JsonValueTransaction<'budget, R, Q>,
root_depth: usize,
has_value_limits: bool,
) -> Self {
Self {
transaction,
root_depth,
has_value_limits,
number_model: JsonNumberModel::Integer64,
admission_policy: JsonLexicalAdmissionPolicy::Immediate,
delimiter_check_timing: JsonLexicalDelimiterCheckTiming::Immediate,
depth_limit: None,
max_encoded_string_bytes: None,
}
}
/// Selects the number range contract for this scan.
///
/// # Parameters
///
/// * `number_model` - Integer or feature-selected binary64 range contract.
///
/// # Returns
///
/// This scanner with the selected number model.
#[inline(always)]
pub(crate) const fn with_number_model(mut self, number_model: JsonNumberModel) -> Self {
self.number_model = number_model;
self
}
/// Selects when lexical tokens are admitted; defaults to
/// [`JsonLexicalAdmissionPolicy::Immediate`].
///
/// The ordering depends on token kind: `Immediate` checks delimiters before
/// admission for literals and numbers, while `TokenFirst` validates
/// complete tokens before following syntax is checked. This policy does
/// not enable or disable value-resource accounting.
///
/// # Parameters
///
/// * `policy` - Token admission ordering used by the scan.
///
/// # Returns
///
/// This scanner configured with `policy`.
pub(crate) const fn with_admission_policy(mut self, policy: JsonLexicalAdmissionPolicy) -> Self {
self.admission_policy = policy;
self
}
/// Selects when consumer scans check the byte following a number token.
///
/// Immediate checking reports an illegal suffix before consumer
/// materialization and number-byte admission. Deferred checking preserves
/// callback-first behavior for consumers whose contract depends on it.
///
/// # Parameters
///
/// * `timing` - Whether number delimiters are checked before or after
/// consumer admission.
///
/// # Returns
///
/// This scanner configured with the requested delimiter-check timing.
pub(crate) const fn with_delimiter_check_timing(mut self, timing: JsonLexicalDelimiterCheckTiming) -> Self {
self.delimiter_check_timing = timing;
self
}
/// Sets an optional root-inclusive maximum depth; `None` disables this
/// additional cap.
///
/// A limit of zero rejects the root value. This check is independent of
/// `has_value_limits`, which controls staging of ordinary value
/// measurements.
///
/// # Parameters
///
/// * `depth_limit` - Optional root-inclusive maximum depth; `None` disables
/// the cap.
///
/// # Returns
///
/// This scanner configured with the requested depth cap.
pub(crate) const fn with_depth_limit(mut self, depth_limit: Option<Q>) -> Self {
self.depth_limit = depth_limit;
self
}
/// Sets an optional maximum number of encoded bytes inside each string
/// token.
///
/// The surrounding quotes are excluded; `None` disables this token-local
/// check, while zero permits only empty encoded string contents. This
/// check is independent of `has_value_limits` and does not measure
/// decoded string bytes.
///
/// # Parameters
///
/// * `maximum` - Optional maximum encoded content bytes per string token.
///
/// # Returns
///
/// This scanner configured with the requested token-local limit.
pub(crate) const fn with_max_encoded_string_bytes(mut self, maximum: Option<usize>) -> Self {
self.max_encoded_string_bytes = maximum;
self
}
/// Validates and charges one complete JSON document.
///
/// # Parameters
///
/// * `input` - Byte sequence containing exactly one JSON document.
///
/// # Returns
///
/// `Ok(())` when the entire input is valid and all measurements are staged.
///
/// # Errors
///
/// Returns [`JsonLexicalError::Budget`] for the first resource violation,
/// or [`JsonLexicalError::Syntax`] when `input` is not one complete JSON
/// value. All value measurements remain staged in the caller's transaction.
#[inline]
pub(crate) fn scan(&mut self, input: &[u8]) -> Result<(), JsonLexicalError<R, Q>> {
self.scan_with_events(input, |_| {})
}
/// Validates a document and synchronously emits each admitted token.
///
/// Events may precede a later document error; consumers must only
/// materialize input after a complete admission pass has succeeded.
///
/// # Type Parameters
///
/// * `F` - Callback type used to receive lexical events.
///
/// # Parameters
///
/// * `input` - Byte sequence containing exactly one JSON document.
/// * `emit` - Synchronous callback invoked for each admitted token.
///
/// # Returns
///
/// `Ok(())` after complete validation and event emission.
///
/// # Errors
///
/// Returns a budget error for the first resource violation or a syntax
/// error when the input is not one complete JSON value.
pub(crate) fn scan_with_events<'input, F>(
&mut self,
input: &'input [u8],
mut emit: F,
) -> Result<(), JsonLexicalError<R, Q>>
where
F: FnMut(JsonLexicalEvent<'input>),
{
let mut cursor = JsonLexicalCursor::new(input, &mut *self.transaction, self.has_value_limits);
cursor.set_number_model(self.number_model);
cursor.set_admission_policy(self.admission_policy);
cursor.set_depth_limit(self.depth_limit);
cursor.set_max_encoded_string_bytes(self.max_encoded_string_bytes);
let mut adapter = |point| match point {
JsonLexicalScanPoint::Event(event) => {
emit(event);
true
}
_ => true,
};
let mut stack: Vec<JsonLexicalContainerFrame> = Vec::new();
cursor.skip_whitespace();
cursor.set_context(JsonDecodeContext::Value);
cursor.value(self.root_depth, &mut stack, &mut adapter)?;
while let Some(frame) = stack.pop() {
cursor.resume(frame, &mut stack, &mut adapter)?;
}
cursor.skip_whitespace();
cursor.set_context(JsonDecodeContext::TrailingInput);
if cursor.is_at_end() {
Ok(())
} else {
Err(cursor.syntax(JsonLexicalErrorReason::TrailingCharacters))
}
}
/// Scans through the shared grammar and stops at the first reported
/// failure.
///
/// A consumer error is returned as [`JsonLexicalScanError::Consumer`];
/// scanner syntax or budget failures are returned as `Lexical`, except
/// an encoded-string byte-limit violation, which is returned as
/// `EncodedStringLimit`. A failed consumer callback stops further
/// callbacks and scanning immediately. Number delimiter timing is selected
/// with [`Self::with_delimiter_check_timing`]; deferred timing lets a
/// consumer callback stop before the following delimiter is checked.
///
/// # Type Parameters
///
/// * `C` - Consumer implementing synchronous checks for this input
/// lifetime.
///
/// # Parameters
///
/// * `input` - Byte sequence containing exactly one JSON document.
/// * `consumer` - Callback implementation receiving checks and token
/// events.
///
/// # Returns
///
/// `Ok(())` after complete validation and callback processing.
///
/// # Errors
///
/// Returns the consumer's error when a callback stops scanning, an
/// encoded-string limit error for that token-local violation, or a
/// lexical error for syntax or budget failures.
pub(crate) fn scan_with_consumer<'input, C>(
&mut self,
input: &'input [u8],
consumer: &mut C,
) -> Result<(), JsonLexicalScanError<C::Error, R, Q>>
where
C: JsonLexicalConsumer<'input>,
{
let mut cursor = JsonLexicalCursor::new(input, &mut *self.transaction, self.has_value_limits);
cursor.set_number_model(self.number_model);
cursor.set_admission_policy(self.admission_policy);
cursor.set_depth_limit(self.depth_limit);
cursor.set_max_encoded_string_bytes(self.max_encoded_string_bytes);
cursor.set_delimiter_check_timing(self.delimiter_check_timing);
let mut consumer_error = None;
let mut dispatch = |point| {
let result = match point {
JsonLexicalScanPoint::BeforeValue { depth, offset } => consumer.before_value(depth, offset),
JsonLexicalScanPoint::BeforeKey { offset } => consumer.before_key(offset),
JsonLexicalScanPoint::BeforeNumber { token, offset } => consumer.before_number(token, offset),
JsonLexicalScanPoint::Event(event) => consumer.event(event),
};
match result {
Ok(()) => true,
Err(error) => {
consumer_error = Some(error);
false
}
}
};
let mut stack = Vec::new();
let scan = (|| {
cursor.skip_whitespace();
cursor.set_context(JsonDecodeContext::Value);
cursor.value(self.root_depth, &mut stack, &mut dispatch)?;
while let Some(frame) = stack.pop() {
cursor.resume(frame, &mut stack, &mut dispatch)?;
}
cursor.skip_whitespace();
cursor.set_context(JsonDecodeContext::TrailingInput);
if cursor.is_at_end() {
Ok(())
} else {
Err(cursor.syntax(JsonLexicalErrorReason::TrailingCharacters))
}
})();
match scan {
Ok(()) => Ok(()),
Err(JsonLexicalError::Syntax(failure)) => match failure.reason {
JsonLexicalErrorReason::EncodedStringLimit { maximum, observed } => {
Err(JsonLexicalScanError::EncodedStringLimit {
maximum,
observed,
offset: failure.offset,
})
}
JsonLexicalErrorReason::ConsumerStopped if consumer_error.is_some() => Err(
JsonLexicalScanError::Consumer(consumer_error.expect("consumer failure was captured")),
),
_ if consumer_error.is_some() => Err(JsonLexicalScanError::Consumer(consumer_error.unwrap())),
_ => Err(JsonLexicalScanError::Lexical(JsonLexicalError::Syntax(failure))),
},
Err(_error) if consumer_error.is_some() => Err(JsonLexicalScanError::Consumer(consumer_error.unwrap())),
Err(error) => Err(JsonLexicalScanError::Lexical(error)),
}
}
}