- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathJSONPath.swift
More file actions
Latest commit
459 lines (429 loc) · 13.6 KB
/
Copy pathJSONPath.swift
File metadata and controls
459 lines (429 loc) · 13.6 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
//
// JSONPath.swift
// DynamicJSON
//
// Created by Matthias Zenger on 13/02/2024.
// Copyright © 2024 Matthias Zenger. All rights reserved.
//
// 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.
//
import Foundation
///
/// Enumeration `JSONPath` represents JSONPath queries based on RFC 9535
/// (JSONPath: Query Expressions for JSON). JSONPath defines a syntax
/// for selecting and extracting JSON (RFC 8259) values from within a given
/// JSON value.
///
publicindirectenumJSONPath:Codable,
Hashable,
CustomStringConvertible{
case `self`
case current
case select(JSONPath,Segment)
/// Syntactic sugar for appending a single selector to the JSONPath query `path`.
publicstaticfunc children(_ path:JSONPath, _ selector:Selector)->JSONPath{
return.select(path,.children([selector]))
}
/// Syntactic sugar for appending a single descendant to the JSONPath query `path`.
publicstaticfunc descendants(_ path:JSONPath, _ selector:Selector)->JSONPath{
return.select(path,.descendants([selector]))
}
/// Creates a `JSONPath` representation of the JSONPath query represented
/// using the syntax as specified by RFC 9535. An error is thrown if `query`
/// is not compliant with JSONPath syntax. If parameter `strict` is set to
/// false, the syntax and semantics of JSONPath are slighly relaxed. For
/// instance, non-singular queries are supported in query filters.
publicinit(query:String, strict:Bool=true)throws{
varparser=JSONPathParser(string: query, strict: strict)
self=try parser.parse()
}
/// Initialize a `JSONPath` reference using a decoder.
publicinit(from decoder:Decoder)throws{
letcontainer=try decoder.singleValueContainer()
tryself.init(query:try container.decode(String.self))
}
/// Encode a `JSONPath` reference using the given encoder.
publicfunc encode(to encoder:Encoder)throws{
varcontainer= encoder.singleValueContainer()
try container.encode(self.description)
}
/// Returns true if this JSONPath value represents a singular query.
publicvarisSingular:Bool{
switchself{
case.self:
returntrue
case.current:
returntrue
case.select(let path,let segment):
return path.isSingular && segment.isSingular
}
}
/// Returns true if this query is a relative JSONPath query, i.e. it does not start
/// with "$'.
publicvarisRelative:Bool{
switchself{
case.self:
returnfalse
case.current:
returntrue
case.select(let path, _):
return path.isRelative
}
}
/// Returns the sequence of segments of this JSONPath query.
publicvarsegments:[Segment]{
varres:[Segment]=[]
self.insert(into:&res)
return res
}
privatefunc insert(into segments:inout[Segment]){
switchself{
case.self,.current:
break
case.select(let path,let segment):
path.insert(into:&segments)
segments.append(segment)
}
}
/// Returns a `JSONLocation` value matching this JSONPath query. Non-singular queries
/// cannot be represented as a `JSONLocation` value and thus `nil` gets returned.
publicvarlocation:JSONLocation?{
switchself{
case.self:
return.root
case.select(let path,.children(let selectors)):
iflet parentLocation = path.location, selectors.count ==1{
switchselectors[0]{
case.member(let member):
return.member(parentLocation, member)
case.index(let index):
return.index(parentLocation, index)
default:
returnnil
}
}
fallthrough
default:
returnnil
}
}
/// Returns the JSONPath query as a string.
publicvardescription:String{
switchself{
case.self:
return"$"
case.current:
return"@"
case.select(let path,let segment):
return"\(path)\(segment)"
}
}
/// Representation of JSONPath query segments. There are two different segment types:
/// children and descendants.
publicenumSegment:Hashable,CustomStringConvertible{
case children([Selector])
case descendants([Selector])
/// Returns true if this segment is a descendant segment.
publicvarisDescendant:Bool{
switchself{
case.children(_):
returnfalse
case.descendants(_):
returntrue
}
}
/// Returns true if this segment is singular, i.e. it refers to at most one value.
publicvarisSingular:Bool{
switchself{
case.children(let selectors):
return selectors.count ==1 && selectors[0].isSingular
case.descendants(_):
returnfalse
}
}
/// Returns the selectors encapsulated by this segment.
publicvarselectors:[Selector]{
switchself{
case.children(let selectors):
return selectors
case.descendants(let selectors):
return selectors
}
}
/// Returns true if this segment can be represented using a shorthand form avoiding
/// the usage of brackets.
privatefunc canUseShorthand(for member:String)->Bool{
varfirst=true
forchin member {
letscalars= ch.unicodeScalars
guard ch.isLetter
|| !first && ch.isHexDigit
|| ch =="_"
|| !first && ch =="-"
|| scalars.allSatisfy({ c in c.value >=0x80 && c.value <=0xD7FF})
|| scalars.allSatisfy({ c in c.value >=0xE000 && c.value <=0x10FFFF})else{
returnfalse
}
first =false
}
returntrue
}
/// Returns a string representation of this segment.
publicvardescription:String{
varres=""
varselectors:[Selector]
switchself{
case.children(let sel):
selectors = sel
case.descendants(let sel):
selectors = sel
res.append(".")
}
if selectors.count ==0{
return"\(res)[]"
}elseif selectors.count ==1{
switchselectors[0]{
case.wildcard:
return"\(res).*"
case.member(let member):
ifself.canUseShorthand(for: member){
return"\(res).\(member)"
}elseif res.isEmpty {
return"['\(JSONLocation.escapeMember(member))']"
}else{
return"..['\(JSONLocation.escapeMember(member))']"
}
default:
if res.isEmpty {
return"[\(selectors[0])]"
}else{
return"..[\(selectors[0])]"
}
}
}else{
if res.isEmpty {
return"[\(selectors.map{ x in x.description }.joined(separator:", "))]"
}else{
return"..[\(selectors.map{ x in x.description }.joined(separator:", "))]"
}
}
}
}
/// Representation of JSONPath query path selectors. Selectors are either child or
/// descendant selectors. Supported are:
/// - wildcard selectors,
/// - member selectors,
/// - index selectors,
/// - slice selectors, and
/// - filter selectors.
publicenumSelector:Hashable,CustomStringConvertible{
case wildcard
case member(String)
case index(Int)
case slice(Int?,Int?,Int?)
case filter(Expression)
/// Returns true if this selector is singular, i.e. it refers to at most one value.
publicvarisSingular:Bool{
switchself{
case.wildcard:
returnfalse
case.member(_):
returntrue
case.index(_):
returntrue
case.slice(_, _, _):
returnfalse
case.filter(_):
returnfalse
}
}
/// Returns a string representation of this selector when used within a segment
/// delimited by brackets.
publicvardescription:String{
switchself{
case.wildcard:
return"*"
case.member(let member):
return"'\(JSONLocation.escapeMember(member))'"
case.index(let n):
returnString(n)
case.slice(nil,nil,nil):
return":"
case.slice(.some(let start),nil,nil):
return"\(start):"
case.slice(nil,.some(let end),nil):
return":\(end)"
case.slice(nil,nil,.some(let step)):
return"::\(step)"
case.slice(.some(let start),.some(let end),nil):
return"\(start):\(end)"
case.slice(.some(let start),nil,.some(let step)):
return"\(start)::\(step)"
case.slice(nil,.some(let end),.some(let step)):
return":\(end):\(step)"
case.slice(.some(let start),.some(let end),.some(let step)):
return"\(start):\(end):\(step)"
case.filter(let condition):
return"? \(condition)"
}
}
}
/// Representation of JSONPath query filter expressions.
publicindirectenumExpression:Hashable,CustomStringConvertible{
case `null`
case `true`
case `false`
case integer(Int64)
case float(Double)
case string(String)
case variable(String)
case query(JSONPath)
case singularQuery(JSONPath)
case call(String,[Expression])
case prefix(UnaryOperator,Expression)
case operation(Expression,BinaryOperator,Expression)
/// Return a string representation of this expression if nested within another expression.
publicfunc description(within context:Expression)->String{
switch(self, context){
case(.null, _),(.true, _),(.false, _),
(.integer(_), _),(.float(_), _),(.string(_), _),
(.variable(_), _),(.query(_), _),(.call(_, _), _):
returnself.description
case(.operation(_, _, _),.prefix(_, _)):
return"(\(self))"
case(.operation(_,let op, _),.operation(_,let cop, _)):
if cop.precedence > op.precedence {
return"(\(self))"
}
fallthrough
default:
returnself.description
}
}
/// Returns a string representation of this expression assuming it is not
/// embedded in another expression.
publicvardescription:String{
switchself{
case.null:
return"null"
case.true:
return"true"
case.false:
return"false"
case.integer(let x):
returnString(x)
case.float(let x):
returnString(x)
case.string(let str):
return"'\(str)'"
case.variable(let ident):
return ident
case.query(let path):
return path.description
case.singularQuery(let path):
return path.description
case.call(let ident,let args):
return"\(ident)(\(args.map{ x in x.description }.joined(separator:", ")))"
case.prefix(let op,let oper):
return"\(op)\(oper.description(within:self))"
case.operation(let lhs,let op,let rhs):
return"\(lhs.description(within:self))\(op)\(rhs.description(within:self))"
}
}
}
/// Representation of a unary operator. Supported are currently "-" and "!".
publicenumUnaryOperator:Hashable,CustomStringConvertible{
case not
case negate
publicvardescription:String{
switchself{
case.not:
return"!"
case.negate:
return"-"
}
}
}
/// Representation of a binary operator. Supported are currently "==", "!=", "<",
/// ">", "<=", ">=", "||", "&&", "+", "-", "*", and "/".
publicenumBinaryOperator:Hashable,CustomStringConvertible{
case equals
case notEquals
case lessThan
case lessThanEquals
case greaterThan
case greaterThanEquals
case or
case and
case plus
case minus
case mult
case divide
varprecedence:Int{
switchself{
case.or:
return0
case.and:
return1
case.equals:
return2
case.notEquals:
return2
case.lessThan:
return2
case.lessThanEquals:
return2
case.greaterThan:
return2
case.greaterThanEquals:
return2
case.plus:
return3
case.minus:
return3
case.mult:
return4
case.divide:
return4
}
}
publicvardescription:String{
switchself{
case.equals:
return"=="
case.notEquals:
return"!="
case.lessThan:
return"<"
case.lessThanEquals:
return"<="
case.greaterThan:
return">"
case.greaterThanEquals:
return">="
case.or:
return"||"
case.and:
return"&&"
case.plus:
return"+"
case.minus:
return"-"
case.mult:
return"*"
case.divide:
return"/"
}
}
}
}