-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathjsonParser.ts
1395 lines (1247 loc) · 49.9 KB
/
jsonParser.ts
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as Json from 'jsonc-parser';
import { JSONSchema, JSONSchemaRef } from '../jsonSchema';
import { isNumber, equals, isBoolean, isString, isDefined, isObject } from '../utils/objects';
import { extendedRegExp, stringLength } from '../utils/strings';
import { TextDocument, ASTNode, ObjectASTNode, ArrayASTNode, BooleanASTNode, NumberASTNode, StringASTNode, NullASTNode, PropertyASTNode, JSONPath, ErrorCode, Diagnostic, DiagnosticSeverity, Range, SchemaDraft } from '../jsonLanguageTypes';
import * as l10n from '@vscode/l10n';
export interface IRange {
offset: number;
length: number;
}
const formats = {
'color-hex': { errorMessage: l10n.t('Invalid color format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA.'), pattern: /^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$/ },
'date-time': { errorMessage: l10n.t('String is not a RFC3339 date-time.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i },
'date': { errorMessage: l10n.t('String is not a RFC3339 date.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/i },
'time': { errorMessage: l10n.t('String is not a RFC3339 time.'), pattern: /^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i },
'email': { errorMessage: l10n.t('String is not an e-mail address.'), pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}))$/ },
'hostname': { errorMessage: l10n.t('String is not a hostname.'), pattern: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i },
'ipv4': { errorMessage: l10n.t('String is not an IPv4 address.'), pattern: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/ },
'ipv6': { errorMessage: l10n.t('String is not an IPv6 address.'), pattern: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i },
};
export interface IProblem {
location: IRange;
severity?: DiagnosticSeverity;
code?: ErrorCode;
message: string;
}
export abstract class ASTNodeImpl {
public readonly abstract type: 'object' | 'property' | 'array' | 'number' | 'boolean' | 'null' | 'string';
public offset: number;
public length: number;
public readonly parent: ASTNode | undefined;
constructor(parent: ASTNode | undefined, offset: number, length: number = 0) {
this.offset = offset;
this.length = length;
this.parent = parent;
}
public get children(): ASTNode[] {
return [];
}
public toString(): string {
return 'type: ' + this.type + ' (' + this.offset + '/' + this.length + ')' + (this.parent ? ' parent: {' + this.parent.toString() + '}' : '');
}
}
export class NullASTNodeImpl extends ASTNodeImpl implements NullASTNode {
public type: 'null' = 'null';
public value: null = null;
constructor(parent: ASTNode | undefined, offset: number) {
super(parent, offset);
}
}
export class BooleanASTNodeImpl extends ASTNodeImpl implements BooleanASTNode {
public type: 'boolean' = 'boolean';
public value: boolean;
constructor(parent: ASTNode | undefined, boolValue: boolean, offset: number) {
super(parent, offset);
this.value = boolValue;
}
}
export class ArrayASTNodeImpl extends ASTNodeImpl implements ArrayASTNode {
public type: 'array' = 'array';
public items: ASTNode[];
constructor(parent: ASTNode | undefined, offset: number) {
super(parent, offset);
this.items = [];
}
public get children(): ASTNode[] {
return this.items;
}
}
export class NumberASTNodeImpl extends ASTNodeImpl implements NumberASTNode {
public type: 'number' = 'number';
public isInteger: boolean;
public value: number;
constructor(parent: ASTNode | undefined, offset: number) {
super(parent, offset);
this.isInteger = true;
this.value = Number.NaN;
}
}
export class StringASTNodeImpl extends ASTNodeImpl implements StringASTNode {
public type: 'string' = 'string';
public value: string;
constructor(parent: ASTNode | undefined, offset: number, length?: number) {
super(parent, offset, length);
this.value = '';
}
}
export class PropertyASTNodeImpl extends ASTNodeImpl implements PropertyASTNode {
public type: 'property' = 'property';
public keyNode: StringASTNode;
public valueNode?: ASTNode;
public colonOffset: number;
constructor(parent: ObjectASTNode | undefined, offset: number, keyNode: StringASTNode) {
super(parent, offset);
this.colonOffset = -1;
this.keyNode = keyNode;
}
public get children(): ASTNode[] {
return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode];
}
}
export class ObjectASTNodeImpl extends ASTNodeImpl implements ObjectASTNode {
public type: 'object' = 'object';
public properties: PropertyASTNode[];
constructor(parent: ASTNode | undefined, offset: number) {
super(parent, offset);
this.properties = [];
}
public get children(): ASTNode[] {
return this.properties;
}
}
export function asSchema(schema: JSONSchemaRef): JSONSchema;
export function asSchema(schema: JSONSchemaRef | undefined): JSONSchema | undefined;
export function asSchema(schema: JSONSchemaRef | undefined): JSONSchema | undefined {
if (isBoolean(schema)) {
return schema ? {} : { "not": {} };
}
return schema;
}
export interface JSONDocumentConfig {
collectComments?: boolean;
schemaDraft?: SchemaDraft;
}
export interface IApplicableSchema {
node: ASTNode;
inverted?: boolean;
schema: JSONSchema;
}
export enum EnumMatch {
Key, Enum
}
const schemaDraftFromId : { [id:string]: SchemaDraft } = {
'http://json-schema.org/draft-03/schema#': SchemaDraft.v3,
'http://json-schema.org/draft-04/schema#': SchemaDraft.v4,
'http://json-schema.org/draft-06/schema#': SchemaDraft.v6,
'http://json-schema.org/draft-07/schema#': SchemaDraft.v7,
'https://json-schema.org/draft/2019-09/schema': SchemaDraft.v2019_09,
'https://json-schema.org/draft/2020-12/schema': SchemaDraft.v2020_12
};
export interface ISchemaCollector {
schemas: IApplicableSchema[];
add(schema: IApplicableSchema): void;
merge(other: ISchemaCollector): void;
include(node: ASTNode): boolean;
newSub(): ISchemaCollector;
}
export interface IEvaluationContext {
readonly schemaDraft: SchemaDraft;
}
class EvaluationContext implements IEvaluationContext {
constructor(public readonly schemaDraft: SchemaDraft) {
}
}
class SchemaCollector implements ISchemaCollector {
schemas: IApplicableSchema[] = [];
constructor(private focusOffset = -1, private exclude?: ASTNode) {
}
add(schema: IApplicableSchema) {
this.schemas.push(schema);
}
merge(other: ISchemaCollector) {
Array.prototype.push.apply(this.schemas, other.schemas);
}
include(node: ASTNode) {
return (this.focusOffset === -1 || contains(node, this.focusOffset)) && (node !== this.exclude);
}
newSub(): ISchemaCollector {
return new SchemaCollector(-1, this.exclude);
}
}
class NoOpSchemaCollector implements ISchemaCollector {
private constructor() { }
get schemas() { return []; }
add(_schema: IApplicableSchema) { }
merge(_other: ISchemaCollector) { }
include(_node: ASTNode) { return true; }
newSub(): ISchemaCollector { return this; }
static instance = new NoOpSchemaCollector();
}
export class ValidationResult {
public problems: IProblem[];
public propertiesMatches: number;
public processedProperties: Set<string>;
public propertiesValueMatches: number;
public primaryValueMatches: number;
public enumValueMatch: boolean;
public enumValues: any[] | undefined;
constructor() {
this.problems = [];
this.propertiesMatches = 0;
this.processedProperties = new Set();
this.propertiesValueMatches = 0;
this.primaryValueMatches = 0;
this.enumValueMatch = false;
this.enumValues = undefined;
}
public hasProblems(): boolean {
return !!this.problems.length;
}
public merge(validationResult: ValidationResult): void {
this.problems = this.problems.concat(validationResult.problems);
this.propertiesMatches += validationResult.propertiesMatches;
this.propertiesValueMatches += validationResult.propertiesValueMatches;
this.mergeProcessedProperties(validationResult);
}
public mergeEnumValues(validationResult: ValidationResult): void {
if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) {
this.enumValues = this.enumValues.concat(validationResult.enumValues);
for (const error of this.problems) {
if (error.code === ErrorCode.EnumValueMismatch) {
error.message = l10n.t('Value is not accepted. Valid values: {0}.', this.enumValues.map(v => JSON.stringify(v)).join(', '));
}
}
}
}
public mergePropertyMatch(propertyValidationResult: ValidationResult): void {
this.problems = this.problems.concat(propertyValidationResult.problems);
this.propertiesMatches++;
if (propertyValidationResult.enumValueMatch || !propertyValidationResult.hasProblems() && propertyValidationResult.propertiesMatches) {
this.propertiesValueMatches++;
}
if (propertyValidationResult.enumValueMatch && propertyValidationResult.enumValues && propertyValidationResult.enumValues.length === 1) {
this.primaryValueMatches++;
}
}
public mergeProcessedProperties(validationResult: ValidationResult): void {
validationResult.processedProperties.forEach(p => this.processedProperties.add(p));
}
public compare(other: ValidationResult): number {
const hasProblems = this.hasProblems();
if (hasProblems !== other.hasProblems()) {
return hasProblems ? -1 : 1;
}
if (this.enumValueMatch !== other.enumValueMatch) {
return other.enumValueMatch ? -1 : 1;
}
if (this.primaryValueMatches !== other.primaryValueMatches) {
return this.primaryValueMatches - other.primaryValueMatches;
}
if (this.propertiesValueMatches !== other.propertiesValueMatches) {
return this.propertiesValueMatches - other.propertiesValueMatches;
}
return this.propertiesMatches - other.propertiesMatches;
}
}
export function newJSONDocument(root: ASTNode, diagnostics: Diagnostic[] = []) {
return new JSONDocument(root, diagnostics, []);
}
export function getNodeValue(node: ASTNode): any {
return Json.getNodeValue(node);
}
export function getNodePath(node: ASTNode): JSONPath {
return Json.getNodePath(node);
}
export function contains(node: ASTNode, offset: number, includeRightBound = false): boolean {
return offset >= node.offset && offset < (node.offset + node.length) || includeRightBound && offset === (node.offset + node.length);
}
export class JSONDocument {
constructor(public readonly root: ASTNode | undefined, public readonly syntaxErrors: Diagnostic[] = [], public readonly comments: Range[] = []) {
}
public getNodeFromOffset(offset: number, includeRightBound = false): ASTNode | undefined {
if (this.root) {
return <ASTNode>Json.findNodeAtOffset(this.root, offset, includeRightBound);
}
return undefined;
}
public visit(visitor: (node: ASTNode) => boolean): void {
if (this.root) {
const doVisit = (node: ASTNode): boolean => {
let ctn = visitor(node);
const children = node.children;
if (Array.isArray(children)) {
for (let i = 0; i < children.length && ctn; i++) {
ctn = doVisit(children[i]);
}
}
return ctn;
};
doVisit(this.root);
}
}
public validate(textDocument: TextDocument, schema: JSONSchema | undefined, severity: DiagnosticSeverity = DiagnosticSeverity.Warning, schemaDraft?: SchemaDraft): Diagnostic[] | undefined {
if (this.root && schema) {
const validationResult = new ValidationResult();
validate(this.root, schema, validationResult, NoOpSchemaCollector.instance, new EvaluationContext(schemaDraft ?? getSchemaDraft(schema)));
return validationResult.problems.map(p => {
const range = Range.create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length));
return Diagnostic.create(range, p.message, p.severity ?? severity, p.code);
});
}
return undefined;
}
public getMatchingSchemas(schema: JSONSchema, focusOffset: number = -1, exclude?: ASTNode): IApplicableSchema[] {
if (this.root && schema) {
const matchingSchemas = new SchemaCollector(focusOffset, exclude);
const schemaDraft = getSchemaDraft(schema);
const context = new EvaluationContext(schemaDraft);
validate(this.root, schema, new ValidationResult(), matchingSchemas, context);
return matchingSchemas.schemas;
}
return [];
}
}
function getSchemaDraft(schema: JSONSchema, fallBack = SchemaDraft.v2020_12 ) {
let schemaId = schema.$schema;
if (schemaId) {
return schemaDraftFromId[schemaId] ?? fallBack;
}
return fallBack;
}
function validate(n: ASTNode | undefined, schema: JSONSchema, validationResult: ValidationResult, matchingSchemas: ISchemaCollector, context: IEvaluationContext): void {
if (!n || !matchingSchemas.include(n)) {
return;
}
if (n.type === 'property') {
return validate(n.valueNode, schema, validationResult, matchingSchemas, context);
}
const node = n;
_validateNode();
switch (node.type) {
case 'object':
_validateObjectNode(node);
break;
case 'array':
_validateArrayNode(node);
break;
case 'string':
_validateStringNode(node);
break;
case 'number':
_validateNumberNode(node);
break;
}
matchingSchemas.add({ node: node, schema: schema });
function _validateNode() {
function matchesType(type: string) {
return node.type === type || (type === 'integer' && node.type === 'number' && node.isInteger);
}
if (Array.isArray(schema.type)) {
if (!schema.type.some(matchesType)) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: schema.errorMessage || l10n.t('Incorrect type. Expected one of {0}.', (<string[]>schema.type).join(', '))
});
}
}
else if (schema.type) {
if (!matchesType(schema.type)) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: schema.errorMessage || l10n.t('Incorrect type. Expected "{0}".', schema.type)
});
}
}
if (Array.isArray(schema.allOf)) {
for (const subSchemaRef of schema.allOf) {
const subValidationResult = new ValidationResult();
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, asSchema(subSchemaRef), subValidationResult, subMatchingSchemas, context);
validationResult.merge(subValidationResult);
matchingSchemas.merge(subMatchingSchemas);
}
}
const notSchema = asSchema(schema.not);
if (notSchema) {
const subValidationResult = new ValidationResult();
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, notSchema, subValidationResult, subMatchingSchemas, context);
if (!subValidationResult.hasProblems()) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: schema.errorMessage || l10n.t("Matches a schema that is not allowed.")
});
}
for (const ms of subMatchingSchemas.schemas) {
ms.inverted = !ms.inverted;
matchingSchemas.add(ms);
}
}
const testAlternatives = (alternatives: JSONSchemaRef[], maxOneMatch: boolean) => {
const matches = [];
// remember the best match that is used for error messages
let bestMatch: { schema: JSONSchema; validationResult: ValidationResult; matchingSchemas: ISchemaCollector; } | undefined = undefined;
for (const subSchemaRef of alternatives) {
const subSchema = asSchema(subSchemaRef);
const subValidationResult = new ValidationResult();
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, subSchema, subValidationResult, subMatchingSchemas, context);
if (!subValidationResult.hasProblems()) {
matches.push(subSchema);
}
if (!bestMatch) {
bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
} else {
if (!maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems()) {
// no errors, both are equally good matches
bestMatch.matchingSchemas.merge(subMatchingSchemas);
bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches;
bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
bestMatch.validationResult.mergeProcessedProperties(subValidationResult);
} else {
const compareResult = subValidationResult.compare(bestMatch.validationResult);
if (compareResult > 0) {
// our node is the best matching so far
bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
} else if (compareResult === 0) {
// there's already a best matching but we are as good
bestMatch.matchingSchemas.merge(subMatchingSchemas);
bestMatch.validationResult.mergeEnumValues(subValidationResult);
}
}
}
}
if (matches.length > 1 && maxOneMatch) {
validationResult.problems.push({
location: { offset: node.offset, length: 1 },
message: l10n.t("Matches multiple schemas when only one must validate.")
});
}
if (bestMatch) {
validationResult.merge(bestMatch.validationResult);
matchingSchemas.merge(bestMatch.matchingSchemas);
}
return matches.length;
};
if (Array.isArray(schema.anyOf)) {
testAlternatives(schema.anyOf, false);
}
if (Array.isArray(schema.oneOf)) {
testAlternatives(schema.oneOf, true);
}
const testBranch = (schema: JSONSchemaRef) => {
const subValidationResult = new ValidationResult();
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, asSchema(schema), subValidationResult, subMatchingSchemas, context);
validationResult.merge(subValidationResult);
matchingSchemas.merge(subMatchingSchemas);
};
const testCondition = (ifSchema: JSONSchemaRef, thenSchema?: JSONSchemaRef, elseSchema?: JSONSchemaRef) => {
const subSchema = asSchema(ifSchema);
const subValidationResult = new ValidationResult();
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, subSchema, subValidationResult, subMatchingSchemas, context);
matchingSchemas.merge(subMatchingSchemas);
validationResult.mergeProcessedProperties(subValidationResult);
if (!subValidationResult.hasProblems()) {
if (thenSchema) {
testBranch(thenSchema);
}
} else if (elseSchema) {
testBranch(elseSchema);
}
};
const ifSchema = asSchema(schema.if);
if (ifSchema) {
testCondition(ifSchema, asSchema(schema.then), asSchema(schema.else));
}
if (Array.isArray(schema.enum)) {
const val = getNodeValue(node);
let enumValueMatch = false;
for (const e of schema.enum) {
if (equals(val, e)) {
enumValueMatch = true;
break;
}
}
validationResult.enumValues = schema.enum;
validationResult.enumValueMatch = enumValueMatch;
if (!enumValueMatch) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
code: ErrorCode.EnumValueMismatch,
message: schema.errorMessage || l10n.t('Value is not accepted. Valid values: {0}.', schema.enum.map(v => JSON.stringify(v)).join(', '))
});
}
}
if (isDefined(schema.const)) {
const val = getNodeValue(node);
if (!equals(val, schema.const)) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
code: ErrorCode.EnumValueMismatch,
message: schema.errorMessage || l10n.t('Value must be {0}.', JSON.stringify(schema.const))
});
validationResult.enumValueMatch = false;
} else {
validationResult.enumValueMatch = true;
}
validationResult.enumValues = [schema.const];
}
let deprecationMessage = schema.deprecationMessage;
if ((deprecationMessage || schema.deprecated) && node.parent) {
deprecationMessage = deprecationMessage || l10n.t('Value is deprecated');
validationResult.problems.push({
location: { offset: node.parent.offset, length: node.parent.length },
severity: DiagnosticSeverity.Warning,
message: deprecationMessage,
code: ErrorCode.Deprecated
});
}
}
function _validateNumberNode(node: NumberASTNode): void {
const val = node.value;
function normalizeFloats(float: number): { value: number, multiplier: number } | null {
const parts = /^(-?\d+)(?:\.(\d+))?(?:e([-+]\d+))?$/.exec(float.toString());
return parts && {
value: Number(parts[1] + (parts[2] || '')),
multiplier: (parts[2]?.length || 0) - (parseInt(parts[3]) || 0)
};
};
if (isNumber(schema.multipleOf)) {
let remainder: number = -1;
if (Number.isInteger(schema.multipleOf)) {
remainder = val % schema.multipleOf;
} else {
let normMultipleOf = normalizeFloats(schema.multipleOf);
let normValue = normalizeFloats(val);
if (normMultipleOf && normValue) {
const multiplier = 10 ** Math.abs(normValue.multiplier - normMultipleOf.multiplier);
if (normValue.multiplier < normMultipleOf.multiplier) {
normValue.value *= multiplier;
} else {
normMultipleOf.value *= multiplier;
}
remainder = normValue.value % normMultipleOf.value;
}
}
if (remainder !== 0) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Value is not divisible by {0}.', schema.multipleOf)
});
}
}
function getExclusiveLimit(limit: number | undefined, exclusive: boolean | number | undefined): number | undefined {
if (isNumber(exclusive)) {
return exclusive;
}
if (isBoolean(exclusive) && exclusive) {
return limit;
}
return undefined;
}
function getLimit(limit: number | undefined, exclusive: boolean | number | undefined): number | undefined {
if (!isBoolean(exclusive) || !exclusive) {
return limit;
}
return undefined;
}
const exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
if (isNumber(exclusiveMinimum) && val <= exclusiveMinimum) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Value is below the exclusive minimum of {0}.', exclusiveMinimum)
});
}
const exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
if (isNumber(exclusiveMaximum) && val >= exclusiveMaximum) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Value is above the exclusive maximum of {0}.', exclusiveMaximum)
});
}
const minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
if (isNumber(minimum) && val < minimum) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Value is below the minimum of {0}.', minimum)
});
}
const maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
if (isNumber(maximum) && val > maximum) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Value is above the maximum of {0}.', maximum)
});
}
}
function _validateStringNode(node: StringASTNode): void {
if (isNumber(schema.minLength) && stringLength(node.value) < schema.minLength) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('String is shorter than the minimum length of {0}.', schema.minLength)
});
}
if (isNumber(schema.maxLength) && stringLength(node.value) > schema.maxLength) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('String is longer than the maximum length of {0}.', schema.maxLength)
});
}
if (isString(schema.pattern)) {
const regex = extendedRegExp(schema.pattern);
if (!(regex?.test(node.value))) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: schema.patternErrorMessage || schema.errorMessage || l10n.t('String does not match the pattern of "{0}".', schema.pattern)
});
}
}
if (schema.format) {
switch (schema.format) {
case 'uri':
case 'uri-reference': {
let errorMessage;
if (!node.value) {
errorMessage = l10n.t('URI expected.');
} else {
const match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value);
if (!match) {
errorMessage = l10n.t('URI is expected.');
} else if (!match[2] && schema.format === 'uri') {
errorMessage = l10n.t('URI with a scheme is expected.');
}
}
if (errorMessage) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: schema.patternErrorMessage || schema.errorMessage || l10n.t('String is not a URI: {0}', errorMessage)
});
}
}
break;
case 'color-hex':
case 'date-time':
case 'date':
case 'time':
case 'email':
case 'hostname':
case 'ipv4':
case 'ipv6':
const format = formats[schema.format];
if (!node.value || !format.pattern.exec(node.value)) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: schema.patternErrorMessage || schema.errorMessage || format.errorMessage
});
}
default:
}
}
}
function _validateArrayNode(node: ArrayASTNode): void {
let prefixItemsSchemas: JSONSchemaRef[] | undefined;
let additionalItemSchema: JSONSchemaRef | undefined;
if (context.schemaDraft >= SchemaDraft.v2020_12) {
prefixItemsSchemas = schema.prefixItems;
additionalItemSchema = !Array.isArray(schema.items) ? schema.items : undefined;
} else {
prefixItemsSchemas = Array.isArray(schema.items) ? schema.items : undefined;
additionalItemSchema = !Array.isArray(schema.items) ? schema.items : schema.additionalItems;
}
let index = 0;
if (prefixItemsSchemas !== undefined) {
const max = Math.min(prefixItemsSchemas.length, node.items.length);
for (; index < max; index++) {
const subSchemaRef = prefixItemsSchemas[index];
const subSchema = asSchema(subSchemaRef);
const itemValidationResult = new ValidationResult();
const item = node.items[index];
if (item) {
validate(item, subSchema, itemValidationResult, matchingSchemas, context);
validationResult.mergePropertyMatch(itemValidationResult);
}
validationResult.processedProperties.add(String(index));
}
}
if (additionalItemSchema !== undefined && index < node.items.length) {
if (typeof additionalItemSchema === 'boolean') {
if (additionalItemSchema === false) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Array has too many items according to schema. Expected {0} or fewer.', index)
});
}
for (; index < node.items.length; index++) {
validationResult.processedProperties.add(String(index));
validationResult.propertiesValueMatches++;
}
} else {
for (; index < node.items.length; index++) {
const itemValidationResult = new ValidationResult();
validate(node.items[index], additionalItemSchema, itemValidationResult, matchingSchemas, context);
validationResult.mergePropertyMatch(itemValidationResult);
validationResult.processedProperties.add(String(index));
}
}
}
const containsSchema = asSchema(schema.contains);
if (containsSchema) {
let containsCount = 0;
for (let index = 0; index < node.items.length; index++) {
const item = node.items[index];
const itemValidationResult = new ValidationResult();
validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance, context);
if (!itemValidationResult.hasProblems()) {
containsCount++;
if (context.schemaDraft >= SchemaDraft.v2020_12) {
validationResult.processedProperties.add(String(index));
}
}
}
if (containsCount === 0 && !isNumber(schema.minContains)) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: schema.errorMessage || l10n.t('Array does not contain required item.')
});
}
if (isNumber(schema.minContains) && containsCount < schema.minContains) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Array has too few items that match the contains contraint. Expected {0} or more.', schema.minContains)
});
}
if (isNumber(schema.maxContains) && containsCount > schema.maxContains) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Array has too many items that match the contains contraint. Expected {0} or less.', schema.maxContains)
});
}
}
const unevaluatedItems = schema.unevaluatedItems;
if (unevaluatedItems !== undefined) {
for (let i = 0; i < node.items.length; i++) {
if (!validationResult.processedProperties.has(String(i))) {
if (unevaluatedItems === false) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Item does not match any validation rule from the array.')
});
} else {
const itemValidationResult = new ValidationResult();
validate(node.items[i], <any>schema.unevaluatedItems, itemValidationResult, matchingSchemas, context);
validationResult.mergePropertyMatch(itemValidationResult);
}
}
validationResult.processedProperties.add(String(i));
validationResult.propertiesValueMatches++;
}
}
if (isNumber(schema.minItems) && node.items.length < schema.minItems) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Array has too few items. Expected {0} or more.', schema.minItems)
});
}
if (isNumber(schema.maxItems) && node.items.length > schema.maxItems) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Array has too many items. Expected {0} or fewer.', schema.maxItems)
});
}
if (schema.uniqueItems === true) {
const values = getNodeValue(node);
const duplicates = values.some((value: any, index: number) => {
return index !== values.lastIndexOf(value);
});
if (duplicates) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: l10n.t('Array has duplicate items.')
});
}
}
}
function _validateObjectNode(node: ObjectASTNode): void {
const seenKeys: { [key: string]: ASTNode | undefined } = Object.create(null);
const unprocessedProperties: Set<string> = new Set();
for (const propertyNode of node.properties) {
const key = propertyNode.keyNode.value;
seenKeys[key] = propertyNode.valueNode;
unprocessedProperties.add(key);
}
if (Array.isArray(schema.required)) {
for (const propertyName of schema.required) {
if (!seenKeys[propertyName]) {
const keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode;
const location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 };
validationResult.problems.push({
location: location,
message: l10n.t('Missing property "{0}".', propertyName)
});
}
}
}
const propertyProcessed = (prop: string) => {
unprocessedProperties.delete(prop);
validationResult.processedProperties.add(prop);
};
if (schema.properties) {
for (const propertyName of Object.keys(schema.properties)) {
propertyProcessed(propertyName);
const propertySchema = schema.properties[propertyName];
const child = seenKeys[propertyName];
if (child) {
if (isBoolean(propertySchema)) {
if (!propertySchema) {
const propertyNode = <PropertyASTNode>child.parent;
validationResult.problems.push({
location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
message: schema.errorMessage || l10n.t('Property {0} is not allowed.', propertyName)
});
} else {
validationResult.propertiesMatches++;
validationResult.propertiesValueMatches++;
}
} else {
const propertyValidationResult = new ValidationResult();
validate(child, propertySchema, propertyValidationResult, matchingSchemas, context);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
}
}
if (schema.patternProperties) {
for (const propertyPattern of Object.keys(schema.patternProperties)) {
const regex = extendedRegExp(propertyPattern);
if (regex) {
const processed = [];
for (const propertyName of unprocessedProperties) {
if (regex.test(propertyName)) {
processed.push(propertyName);
const child = seenKeys[propertyName];
if (child) {
const propertySchema = schema.patternProperties[propertyPattern];
if (isBoolean(propertySchema)) {
if (!propertySchema) {
const propertyNode = <PropertyASTNode>child.parent;
validationResult.problems.push({
location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
message: schema.errorMessage || l10n.t('Property {0} is not allowed.', propertyName)
});
} else {
validationResult.propertiesMatches++;
validationResult.propertiesValueMatches++;
}
} else {
const propertyValidationResult = new ValidationResult();
validate(child, propertySchema, propertyValidationResult, matchingSchemas, context);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
}
}
processed.forEach(propertyProcessed);
}
}
}
const additionalProperties = schema.additionalProperties;
if (additionalProperties !== undefined) {
for (const propertyName of unprocessedProperties) {
propertyProcessed(propertyName);
const child = seenKeys[propertyName];
if (child) {
if (additionalProperties === false) {
const propertyNode = <PropertyASTNode>child.parent;
validationResult.problems.push({
location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
message: schema.errorMessage || l10n.t('Property {0} is not allowed.', propertyName)
});
} else if (additionalProperties !== true) {
const propertyValidationResult = new ValidationResult();
validate(child, additionalProperties, propertyValidationResult, matchingSchemas, context);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
}
}
const unevaluatedProperties = schema.unevaluatedProperties;
if (unevaluatedProperties !== undefined) {
const processed = [];
for (const propertyName of unprocessedProperties) {
if (!validationResult.processedProperties.has(propertyName)) {
processed.push(propertyName);
const child = seenKeys[propertyName];
if (child) {
if (unevaluatedProperties === false) {
const propertyNode = <PropertyASTNode>child.parent;
validationResult.problems.push({
location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
message: schema.errorMessage || l10n.t('Property {0} is not allowed.', propertyName)
});
} else if (unevaluatedProperties !== true) {
const propertyValidationResult = new ValidationResult();
validate(child, unevaluatedProperties, propertyValidationResult, matchingSchemas, context);
validationResult.mergePropertyMatch(propertyValidationResult);