-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathjson.mbt
More file actions
626 lines (598 loc) · 18 KB
/
Copy pathjson.mbt
File metadata and controls
626 lines (598 loc) · 18 KB
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
// Copyright 2026 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
/// Try to get this element as a Null
#deprecated("Suggestion: `if json is Null { Some(()) } else { None }`")
pub fn Json::as_null(self : Json) -> Unit? {
guard self is Null else { return None }
Some(())
}
///|
/// Try to get this element as a Boolean
#deprecated("Suggestion: `if json is True { Some(true) } else if json is False { Some(false) } else { None }`")
pub fn Json::as_bool(self : Json) -> Bool? {
match self {
True => Some(true)
False => Some(false)
_ => None
}
}
///|
/// Try to get this element as a Number
#deprecated("Suggestion: `if json is Number(n) { Some(n) } else { None }`")
pub fn Json::as_number(self : Json) -> Double? {
guard self is Number(n, ..) else { return None }
Some(n)
}
///|
/// Try to get this element as a String
#deprecated("Suggestion: `if json is String(s) { Some(s) } else { None }`")
pub fn Json::as_string(self : Json) -> String? {
guard self is String(s) else { return None }
Some(s)
}
///|
/// Try to get this element as an Array
#deprecated("Suggestion: `if json is Array(array) { Some(array) } else { None }`")
pub fn Json::as_array(self : Json) -> Array[Json]? {
guard self is Array(arr) else { return None }
Some(arr)
}
///|
/// Try to get this element as a Json Array and get the element at the `index` as a Json Value
#deprecated("Suggestion: `if json is Array(array) { array.get(index) } else { None }`")
pub fn Json::item(self : Json, index : Int) -> Json? {
if self is Array(arr) {
arr.get(index)
} else {
None
}
}
///|
/// Try to get this element as an Object
#deprecated
pub fn Json::as_object(self : Json) -> Map[String, Json]? {
guard self is Object(obj) else { return None }
Some(obj)
}
///|
/// Try to get this element as a Json Object and get the element with the `key` as a Json Value
#deprecated("Suggestion: `if json is Object(obj) { obj.get(key) } else { None }`")
pub fn Json::value(self : Json, key : String) -> Json? {
if self is Object(obj) {
obj.get(key)
} else {
None
}
}
///|
fn indent_str(level : Int, indent : Int) -> String {
if indent == 0 {
""
} else {
let spaces = indent * level
match spaces {
0 => "\n"
1 => "\n "
2 => "\n "
3 => "\n "
4 => "\n "
5 => "\n "
6 => "\n "
7 => "\n "
8 => "\n "
_ => "\n" + " ".repeat(spaces)
}
}
}
///|
/// Internal stack frame used by iterative stringify to avoid recursion
priv enum WriteFrame {
Array(Array[Json], mut i~ : Int) // (arr, index)
Object(Iter[(String, Json)], mut first~ : Bool) // (kvs, first)
}
///|
/// A Replacer provides a way to filter and transform JSON object properties during stringification.
///
/// Replacers contain a function that takes a property key and value, and returns:
/// - `Some(value)` to include the property in the output (possibly transformed)
/// - `None` to exclude the property from the output
///
/// Only applies to object properties, not array elements.
pub struct Replacer {
priv kind : ReplacerKind
}
///|
priv enum ReplacerKind {
Custom((String, Json) -> Json?)
Keep(ArrayView[StringView])
Exclude(ArrayView[StringView])
}
///|
pub impl @debug.Debug for Replacer with fn to_repr(_) {
@debug.Repr::record(Map([("f", @debug.Repr::literal("<function: ...>"))]))
}
///|
/// Create a new Replacer with a custom function.
///
/// The function receives `(key, value)` pairs and should return:
/// - `Some(transformed_value)` to include the property
/// - `None` to exclude the property
///
/// ## Example
///
/// ```mbt check
/// test {
/// // Transform numbers and exclude sensitive fields
/// ignore(
/// @json.Replacer((key, value) => {
/// match key {
/// "password" | "secret" => None // exclude sensitive fields
/// _ =>
/// match value {
/// Number(n, ..) => Some(Json::number(n * 2.0)) // double all numbers
/// _ => Some(value) // keep other values as-is
/// }
/// }
/// }),
/// )
/// }
/// ```
#alias(new, deprecated="Use `Replacer()` instead")
pub fn Replacer::Replacer(f : (String, Json) -> Json?) -> Replacer {
{ kind: Custom(f) }
}
///|
/// Create a Replacer that only keeps the specified property keys.
/// All other properties will be excluded from the output.
///
/// ## Example
///
/// ```mbt check
/// test {
/// let replacer = @json.Replacer::keep(["name", "age", "email"])
/// let json : Json = {
/// "name": "Alice",
/// "age": 30.0,
/// "email": "alice@example.com",
/// "password": "secret",
/// }
/// ignore(json.stringify(replacer~)) // {"name":"Alice","age":30,"email":"alice@example.com"}
/// }
/// ```
pub fn Replacer::keep(array : ArrayView[StringView]) -> Replacer {
{ kind: Keep(array) }
}
///|
/// Create a Replacer that excludes the specified property keys.
/// All other properties will be included in the output.
///
/// ## Example
///
/// ```mbt check
/// test {
/// let replacer = @json.Replacer::exclude(["password", "secret", "private"])
/// let json : Json = {
/// "name": "Alice",
/// "age": 30.0,
/// "password": "secret",
/// "email": "alice@example.com",
/// }
/// ignore(json.stringify(replacer~)) // {"name":"Alice","age":30,"email":"alice@example.com"}
/// }
/// ```
pub fn Replacer::exclude(array : ArrayView[StringView]) -> Replacer {
{ kind: Exclude(array) }
}
///|
fn Replacer::prepare(self : Replacer) -> (String, Json) -> Json? {
match self.kind {
Custom(f) => f
Keep(array) =>
if array.length() <= 8 {
(idx, value) => if array.contains(idx) { Some(value) } else { None }
} else {
let keys : Map[String, Unit] = Map([])
for key in array {
keys[key.to_owned()] = ()
}
(idx, value) => if keys.contains(idx) { Some(value) } else { None }
}
Exclude(array) =>
if array.length() <= 8 {
(idx, value) => if array.contains(idx) { None } else { Some(value) }
} else {
let keys : Map[String, Unit] = Map([])
for key in array {
keys[key.to_owned()] = ()
}
(idx, value) => if keys.contains(idx) { None } else { Some(value) }
}
}
}
///|
/// Convert this Json value to a String
/// - `escape_slash`: Whether to escape '/' as '\/' (default: false)
/// - `indent`: Number of spaces to indent nested structures (default: 0 = non-indented)
/// - `replacer`: An optional Replacer function to transform or filter values during stringification
///
/// ## Replacer
///
/// The replacer parameter allows you to control which object properties are included in the output
/// and optionally transform values during stringification. Only applies to object properties, not array elements.
///
/// ### Creating Replacers
///
/// 1. **Replacer(f)** - Create a custom replacer with a function `(String, Json) -> Json?`:
/// - Return `Some(value)` to include the property (possibly transformed)
/// - Return `None` to exclude the property
///
/// 2. **Replacer::keep(keys)** - Include only the specified property keys
///
/// 3. **Replacer::exclude(keys)** - Exclude the specified property keys
///
/// ### Examples
///
/// ```mbt check
/// test {
/// let json : Json = { "a": 1.0, "b": 2.0, "c": 3.0, "password": "secret" }
///
/// // Keep only specific keys
/// let keep_replacer = @json.Replacer::keep(["a", "c"])
/// ignore(json.stringify(replacer=keep_replacer)) // {"a":1,"c":3}
///
/// // Exclude sensitive keys
/// let exclude_replacer = @json.Replacer::exclude(["password"])
/// ignore(json.stringify(replacer=exclude_replacer)) // {"a":1,"b":2,"c":3}
///
/// // Custom transformation
/// let transform_replacer = @json.Replacer((_key, value) => {
/// match value {
/// Number(n, ..) => Some(Json::number(n * 10.0)) // multiply numbers by 10
/// _ => Some(value) // keep other values unchanged
/// }
/// })
/// ignore(json.stringify(replacer=transform_replacer)) // {"a":10,"b":20,"c":30,"password":"secret"}
///
/// // Filter and transform
/// let filter_replacer = @json.Replacer((key, value) => {
/// match key {
/// "password" => None // exclude password
/// _ =>
/// match value {
/// Number(n, ..) => Some(Json::number(n + 100.0)) // add 100 to numbers
/// _ => Some(value)
/// }
/// }
/// })
/// ignore(json.stringify(replacer=filter_replacer)) // {"a":101,"b":102,"c":103}
/// }
/// ```
///
/// ### Nested Objects
///
/// Replacers work recursively on nested objects:
///
/// ```mbt check
/// test {
/// let nested : Json = {
/// "user": { "name": "Alice", "password": "secret" },
/// "id": 123.0,
/// }
/// let safe_replacer = @json.Replacer::exclude(["password"])
/// ignore(nested.stringify(replacer=safe_replacer)) // {"user":{"name":"Alice"},"id":123}
/// }
/// ```
pub fn Json::stringify(
self : Json,
escape_slash? : Bool = false,
indent? : Int = 0,
replacer? : Replacer,
) -> String {
let buf = StringBuilder(size_hint=0)
let prepared_replacer = replacer.map(replacer => replacer.prepare())
// Explicit stack to replace recursive calls
let stack : Array[WriteFrame] = []
let mut depth = 0
for x = Some(self) {
match x {
Some(value) => {
match value {
Object(members) =>
if members.is_empty() {
buf.write_string("{}")
} else {
depth += 1
buf.write_char('{')
buf.write_string(indent_str(depth, indent))
// After child value printed, we resume from this frame
stack.push(Object(members.iter(), first=true))
}
Array(arr) =>
if arr.is_empty() {
buf.write_string("[]")
} else {
depth += 1
buf.write_char('[')
buf.write_string(indent_str(depth, indent))
stack.push(Array(arr, i=0))
}
String(s) => {
buf.write_char('\"')
buf.write_string(escape(s, escape_slash~))
buf.write_char('\"')
}
Number(n, repr~) =>
match repr {
None => buf.write_object(n)
Some(r) => buf.write_string(r)
}
True => buf.write_string("true")
False => buf.write_string("false")
Null => buf.write_string("null")
}
continue None
}
None =>
// No current node to write; try to resume a pending container
match stack {
[] => break
[.., Array(arr, i~) as frame] =>
if i < arr.length() {
let element = arr[i]
frame.i = i + 1
if i > 0 {
buf.write_char(',')
buf.write_string(indent_str(depth, indent))
}
continue Some(element)
} else {
depth -= 1
ignore(stack.pop())
buf.write_string(indent_str(depth, indent))
buf.write_char(']')
continue None
}
[.., Object(iterator, first~) as frame] =>
match iterator.next() {
Some((k, v)) => {
let mut v2 = v
if prepared_replacer is Some(replacer) {
if replacer(k, v) is Some(v) {
v2 = v
} else {
continue None
}
}
if !first {
buf.write_char(',')
buf.write_string(indent_str(depth, indent))
}
buf.write_char('\"')
buf.write_string(escape(k, escape_slash~))
buf.write_char('\"')
buf.write_char(':')
if indent > 0 {
buf.write_char(' ')
}
frame.first = false
continue Some(v2)
}
None => {
depth -= 1
ignore(stack.pop())
buf.write_string(indent_str(depth, indent))
buf.write_char('}')
continue None
}
}
}
}
}
buf.to_string()
}
///|
#inline
fn need_escape_scalar(
str : String,
escape_slash : Bool,
start : Int,
end : Int,
) -> Bool {
for i in start..<end {
let code = str.unsafe_get(i)
if code == '"' ||
code == '\\' ||
code < ' ' ||
(escape_slash && code == '/') {
return true
}
}
false
}
///|
#cfg(not(any(target="native", target="wasm")))
#warnings("-unused_value")
fn suppress_unused_v128_import_on_scalar_targets() -> Unit {
ignore(@v128.i16x8_splat(0))
}
///|
#cfg(not(any(target="native", target="wasm")))
fn need_escape(str : String, escape_slash : Bool) -> Bool {
need_escape_scalar(str, escape_slash, 0, str.length())
}
///|
// Scan eight UTF-16 code units at a time on linear-memory backends, then scan
// the remaining tail one code unit at a time.
#cfg(any(target="native", target="wasm"))
fn need_escape(str : String, escape_slash : Bool) -> Bool {
let len = str.length()
guard len >= 8 else { return need_escape_scalar(str, escape_slash, 0, len) }
let control_limit = @v128.i16x8_splat(' ')
let quote = @v128.i16x8_splat('"')
let backslash = @v128.i16x8_splat('\\')
let slash = @v128.i16x8_splat('/')
let tail_start = for pos = 0; pos + 8 <= len; {
let block = @v128.v128_load_i16x8(str, pos)
let escaped = @v128.v128_or_(
@v128.i16x8_lt_u(block, control_limit),
@v128.v128_or_(
@v128.i16x8_eq(block, quote),
@v128.i16x8_eq(block, backslash),
),
)
let escaped = if escape_slash {
@v128.v128_or_(escaped, @v128.i16x8_eq(block, slash))
} else {
escaped
}
if @v128.v128_any_true(escaped) {
return true
}
continue pos + 8
} nobreak {
pos
}
need_escape_scalar(str, escape_slash, tail_start, len)
}
///|
fn escape(str : String, escape_slash~ : Bool) -> String {
let len = str.length()
if !need_escape(str, escape_slash) {
return str
}
let buf = StringBuilder(size_hint=len)
for code in str.code_units() {
match code {
'"' => buf.write_string("\\\"")
'\\' => buf.write_string("\\\\")
'/' =>
if escape_slash {
buf.write_string("\\/")
} else {
buf.write_char('/')
}
'\n' => buf.write_string("\\n")
'\r' => buf.write_string("\\r")
'\b' => buf.write_string("\\b")
'\t' => buf.write_string("\\t")
0x0C => buf.write_string("\\f")
_ =>
if code < ' ' {
buf.write_string("\\u00")
buf.write_string(code.to_byte().to_hex())
} else {
buf.write_char(code.unsafe_to_char())
}
}
}
buf.to_string()
}
///|
/// Transform a JSON value by applying a replacer recursively to all object properties.
///
/// Unlike `stringify(replacer~)` which only affects the string output, `transform()`
/// returns a new JSON value with properties filtered and transformed according to the replacer.
///
/// This is useful when you want to create a modified JSON structure that can be further
/// processed, rather than just converting to a string.
///
/// ## Example
///
/// ```mbt check
/// test {
/// let json : Json = {
/// "user": { "name": "Alice", "password": "secret", "age": 30.0 },
/// "id": 123.0,
/// }
///
/// // Remove sensitive data and double numeric values
/// ignore(
/// json.transform(
/// Replacer((key, value) => {
/// match key {
/// "password" => None // exclude password fields
/// _ =>
/// match value {
/// Number(n, ..) => Some(Json::number(n * 2.0)) // double numbers
/// _ => Some(value) // keep other values
/// }
/// }
/// }),
/// ),
/// )
/// // Result: { "user": { "name": "Alice", "age": 60 }, "id": 246 }
/// }
/// ```
///
/// ## Behavior
///
/// - Recursively applies the replacer to all nested objects
/// - Non-object values (arrays, strings, numbers, etc.) are returned unchanged
/// - The original JSON value is not modified; a new value is returned
pub fn Json::transform(self : Self, replacer : Replacer) -> Json {
self.transform_with(replacer.prepare())
}
///|
fn Json::transform_with(
self : Self,
replacer : (String, Json) -> Json?,
) -> Json {
match self {
Object(members) =>
members
.iter()
.filter_map(pair => {
let (k, v) = pair
if replacer(k, v) is Some(v2) {
Some((k, v2.transform_with(replacer)))
} else {
None
}
})
|> Map::from_iter()
|> Object
Array(members) => Array(members.map(m => m.transform_with(replacer)))
value => value
}
}
///|
/// Useful for json interpolation
pub impl ToJson for Json with fn to_json(self) {
self
}
///|
/// Inspect JSON value with snapshot-friendly formatting.
#callsite(autofill(args_loc, loc))
#alias(inspect, deprecated="Use `json_inspect` without package name instead.")
pub fn json_inspect(
obj : &ToJson,
content? : Json,
loc~ : SourceLoc,
args_loc~ : ArgsLoc,
) -> Unit raise InspectError {
let loc = loc.to_json_string()
let args_loc = args_loc.to_json()
let actual = obj.to_json().stringify(escape_slash=false)
let want = match content {
Some(x) | (None with x = "".to_json()) => x.stringify(escape_slash=false)
}
if actual != want {
raise InspectError(
(
$|@EXPECT_FAILED {"loc": \{loc}, "args_loc": \{args_loc}, "expect": \{want.escape()}, "actual": \{actual.escape()}, "mode": "json"}
),
)
}
}