forked from microsoft/vscode-json-languageservice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonParser.ts
1230 lines (1094 loc) · 42.4 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.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as Json from 'jsonc-parser';
import { JSONSchema, JSONSchemaRef } from '../jsonSchema';
import * as objects from '../utils/objects';
import { ASTNode, ObjectASTNode, ArrayASTNode, BooleanASTNode, NumberASTNode, StringASTNode, NullASTNode, PropertyASTNode, JSONPath, ErrorCode } from '../jsonLanguageTypes';
import * as nls from 'vscode-nls';
import Uri from 'vscode-uri';
import { TextDocument, Diagnostic, DiagnosticSeverity, Range } from 'vscode-languageserver-types';
const localize = nls.loadMessageBundle();
export interface IRange {
offset: number;
length: number;
}
const colorHexPattern = /^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$/;
const emailPattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
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;
constructor(parent: ASTNode, offset: number, length?: number) {
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, offset: number) {
super(parent, offset);
}
}
export class BooleanASTNodeImpl extends ASTNodeImpl implements BooleanASTNode {
public type: 'boolean' = 'boolean';
public value: boolean;
constructor(parent: ASTNode, 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, 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, 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, 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, offset: number) {
super(parent, offset);
this.colonOffset = -1;
}
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, offset: number) {
super(parent, offset);
this.properties = [];
}
public get children(): ASTNode[] {
return this.properties;
}
}
export function asSchema(schema: JSONSchemaRef) {
if (typeof schema === 'boolean') {
return schema ? {} : { "not": {} };
}
return schema;
}
export interface JSONDocumentConfig {
collectComments?: boolean;
}
export interface IApplicableSchema {
node: ASTNode;
inverted?: boolean;
schema: JSONSchema;
}
export enum EnumMatch {
Key, Enum
}
export interface ISchemaCollector {
schemas: IApplicableSchema[];
add(schema: IApplicableSchema): void;
merge(other: ISchemaCollector): void;
include(node: ASTNode): void;
newSub(): ISchemaCollector;
}
class SchemaCollector implements ISchemaCollector {
schemas: IApplicableSchema[] = [];
constructor(private focusOffset = -1, private exclude: ASTNode = null) {
}
add(schema: IApplicableSchema) {
this.schemas.push(schema);
}
merge(other: ISchemaCollector) {
this.schemas.push(...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 propertiesValueMatches: number;
public primaryValueMatches: number;
public enumValueMatch: boolean;
public enumValues: any[];
constructor() {
this.problems = [];
this.propertiesMatches = 0;
this.propertiesValueMatches = 0;
this.primaryValueMatches = 0;
this.enumValueMatch = false;
this.enumValues = null;
}
public hasProblems(): boolean {
return !!this.problems.length;
}
public mergeAll(validationResults: ValidationResult[]): void {
validationResults.forEach((validationResult) => {
this.merge(validationResult);
});
}
public merge(validationResult: ValidationResult): void {
this.problems = this.problems.concat(validationResult.problems);
}
public mergeEnumValues(validationResult: ValidationResult): void {
if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) {
this.enumValues = this.enumValues.concat(validationResult.enumValues);
for (let error of this.problems) {
if (error.code === ErrorCode.EnumValueMismatch) {
error.message = localize('enumWarning', 'Value is not accepted. Valid values: {0}.', this.enumValues.map(v => JSON.stringify(v)).join(', '));
}
}
}
}
public mergePropertyMatch(propertyValidationResult: ValidationResult): void {
this.merge(propertyValidationResult);
this.propertiesMatches++;
if (propertyValidationResult.enumValueMatch || !propertyValidationResult.hasProblems() && propertyValidationResult.propertiesMatches) {
this.propertiesValueMatches++;
}
if (propertyValidationResult.enumValueMatch && propertyValidationResult.enumValues && propertyValidationResult.enumValues.length === 1) {
this.primaryValueMatches++;
}
}
public compare(other: ValidationResult): number {
let 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, 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 void 0;
}
public visit(visitor: (node: ASTNode) => boolean): void {
if (this.root) {
let doVisit = (node: ASTNode): boolean => {
let ctn = visitor(node);
let 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): Diagnostic[] {
if (this.root && schema) {
let validationResult = new ValidationResult();
validate(this.root, schema, validationResult, NoOpSchemaCollector.instance);
return validationResult.problems.map(p => {
let range = Range.create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length));
return Diagnostic.create(range, p.message, p.severity, p.code);
});
}
return null;
}
public getMatchingSchemas(schema: JSONSchema, focusOffset: number = -1, exclude: ASTNode = null): IApplicableSchema[] {
let matchingSchemas = new SchemaCollector(focusOffset, exclude);
if (this.root && schema) {
validate(this.root, schema, new ValidationResult(), matchingSchemas);
}
return matchingSchemas.schemas;
}
}
function validate(node: ASTNode, schema: JSONSchema, validationResult: ValidationResult, matchingSchemas: ISchemaCollector) {
if (!node || !matchingSchemas.include(node)) {
return;
}
switch (node.type) {
case 'object':
_validateObjectNode(node, schema, validationResult, matchingSchemas);
break;
case 'array':
_validateArrayNode(node, schema, validationResult, matchingSchemas);
break;
case 'string':
_validateStringNode(node, schema, validationResult, matchingSchemas);
break;
case 'number':
_validateNumberNode(node, schema, validationResult, matchingSchemas);
break;
case 'property':
return validate(node.valueNode, schema, validationResult, matchingSchemas);
}
_validateNode();
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 },
severity: DiagnosticSeverity.Warning,
message: schema.errorMessage || localize('typeArrayMismatchWarning', '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 },
severity: DiagnosticSeverity.Warning,
message: schema.errorMessage || localize('typeMismatchWarning', 'Incorrect type. Expected "{0}".', schema.type)
});
}
}
if (Array.isArray(schema.allOf)) {
schema.allOf.forEach(subSchemaRef => {
validate(node, asSchema(subSchemaRef), validationResult, matchingSchemas);
});
}
let notSchema = asSchema(schema.not);
if (notSchema) {
let subValidationResult = new ValidationResult();
let subMatchingSchemas = matchingSchemas.newSub();
validate(node, notSchema, subValidationResult, subMatchingSchemas);
if (!subValidationResult.hasProblems()) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('notSchemaWarning', "Matches a schema that is not allowed.")
});
}
subMatchingSchemas.schemas.forEach((ms) => {
ms.inverted = !ms.inverted;
matchingSchemas.add(ms);
});
}
let testAlternatives = (alternatives: JSONSchemaRef[], maxOneMatch: boolean) => {
let matches = [];
// remember the best match that is used for error messages
let bestMatch: { schema: JSONSchema; validationResult: ValidationResult; matchingSchemas: ISchemaCollector; } = null;
alternatives.forEach(subSchemaRef => {
let subSchema = asSchema(subSchemaRef);
let subValidationResult = new ValidationResult();
let subMatchingSchemas = matchingSchemas.newSub();
validate(node, subSchema, subValidationResult, subMatchingSchemas);
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;
} else {
let 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 },
severity: DiagnosticSeverity.Warning,
message: localize('oneOfWarning', "Matches multiple schemas when only one must validate.")
});
}
if (bestMatch !== null) {
validationResult.merge(bestMatch.validationResult);
validationResult.propertiesMatches += bestMatch.validationResult.propertiesMatches;
validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches;
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);
}
if (Array.isArray(schema.enum)) {
let val = getNodeValue(node);
let enumValueMatch = false;
for (let e of schema.enum) {
if (objects.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 },
severity: DiagnosticSeverity.Warning,
code: ErrorCode.EnumValueMismatch,
message: schema.errorMessage || localize('enumWarning', 'Value is not accepted. Valid values: {0}.', schema.enum.map(v => JSON.stringify(v)).join(', '))
});
}
}
if (schema.const) {
let val = getNodeValue(node);
if (!objects.equals(val, schema.const)) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
code: ErrorCode.EnumValueMismatch,
message: schema.errorMessage || localize('constWarning', 'Value must be {0}.', JSON.stringify(schema.const))
});
validationResult.enumValueMatch = false;
} else {
validationResult.enumValueMatch = true;
}
validationResult.enumValues = [schema.const];
}
if (schema.deprecationMessage && node.parent) {
validationResult.problems.push({
location: { offset: node.parent.offset, length: node.parent.length },
severity: DiagnosticSeverity.Warning,
message: schema.deprecationMessage
});
}
}
function _validateNumberNode(node: NumberASTNode, schema: JSONSchema, validationResult: ValidationResult, matchingSchemas: ISchemaCollector): void {
let val = node.value;
if (typeof schema.multipleOf === 'number') {
if (val % schema.multipleOf !== 0) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('multipleOfWarning', 'Value is not divisible by {0}.', schema.multipleOf)
});
}
}
function getExclusiveLimit(limit: number | undefined, exclusive: boolean | number | undefined): number | undefined {
if (typeof exclusive === 'number') {
return exclusive;
}
if (typeof exclusive === 'boolean' && exclusive) {
return limit;
}
return void 0;
}
function getLimit(limit: number | undefined, exclusive: boolean | number | undefined): number | undefined {
if (typeof exclusive !== 'boolean' || !exclusive) {
return limit;
}
return void 0;
}
let exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
if (typeof exclusiveMinimum === 'number' && val <= exclusiveMinimum) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('exclusiveMinimumWarning', 'Value is below the exclusive minimum of {0}.', exclusiveMinimum)
});
}
let exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
if (typeof exclusiveMaximum === 'number' && val >= exclusiveMaximum) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('exclusiveMaximumWarning', 'Value is above the exclusive maximum of {0}.', exclusiveMaximum)
});
}
let minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
if (typeof minimum === 'number' && val < minimum) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('minimumWarning', 'Value is below the minimum of {0}.', minimum)
});
}
let maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
if (typeof maximum === 'number' && val > maximum) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('maximumWarning', 'Value is above the maximum of {0}.', maximum)
});
}
}
function _validateStringNode(node: StringASTNode, schema: JSONSchema, validationResult: ValidationResult, matchingSchemas: ISchemaCollector): void {
if (schema.minLength && node.value.length < schema.minLength) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('minLengthWarning', 'String is shorter than the minimum length of {0}.', schema.minLength)
});
}
if (schema.maxLength && node.value.length > schema.maxLength) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('maxLengthWarning', 'String is longer than the maximum length of {0}.', schema.maxLength)
});
}
if (schema.pattern) {
let regex = new RegExp(schema.pattern);
if (!regex.test(node.value)) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: schema.patternErrorMessage || schema.errorMessage || localize('patternWarning', '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 = localize('uriEmpty', 'URI expected.');
} else {
try {
let uri = Uri.parse(node.value);
if (!uri.scheme && schema.format === 'uri') {
errorMessage = localize('uriSchemeMissing', 'URI with a scheme is expected.');
}
} catch (e) {
errorMessage = e.message;
}
}
if (errorMessage) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: schema.patternErrorMessage || schema.errorMessage || localize('uriFormatWarning', 'String is not a URI: {0}', errorMessage)
});
}
}
break;
case 'email': {
if (!node.value.match(emailPattern)) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: schema.patternErrorMessage || schema.errorMessage || localize('emailFormatWarning', 'String is not an e-mail address.')
});
}
}
break;
case 'color-hex': {
if (!node.value.match(colorHexPattern)) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: schema.patternErrorMessage || schema.errorMessage || localize('colorHexFormatWarning', 'Invalid color format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA.')
});
}
}
break;
default:
}
}
}
function _validateArrayNode(node: ArrayASTNode, schema: JSONSchema, validationResult: ValidationResult, matchingSchemas: ISchemaCollector): void {
if (Array.isArray(schema.items)) {
let subSchemas = schema.items;
subSchemas.forEach((subSchemaRef, index) => {
let subSchema = asSchema(subSchemaRef);
let itemValidationResult = new ValidationResult();
let item = node.items[index];
if (item) {
validate(item, subSchema, itemValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(itemValidationResult);
} else if (node.items.length >= subSchemas.length) {
validationResult.propertiesValueMatches++;
}
});
if (node.items.length > subSchemas.length) {
if (typeof schema.additionalItems === 'object') {
for (let i = subSchemas.length; i < node.items.length; i++) {
let itemValidationResult = new ValidationResult();
validate(node.items[i], <any>schema.additionalItems, itemValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(itemValidationResult);
}
} else if (schema.additionalItems === false) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('additionalItemsWarning', 'Array has too many items according to schema. Expected {0} or fewer.', subSchemas.length)
});
}
}
} else {
let itemSchema = asSchema(schema.items);
if (itemSchema) {
node.items.forEach((item) => {
let itemValidationResult = new ValidationResult();
validate(item, itemSchema, itemValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(itemValidationResult);
});
}
}
let containsSchema = asSchema(schema.contains);
if (containsSchema) {
let doesContain = node.items.some(item => {
let itemValidationResult = new ValidationResult();
validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance);
return !itemValidationResult.hasProblems();
});
if (!doesContain) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: schema.errorMessage || localize('requiredItemMissingWarning', 'Array does not contain required item.', schema.minItems)
});
}
}
if (schema.minItems && node.items.length < schema.minItems) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('minItemsWarning', 'Array has too few items. Expected {0} or more.', schema.minItems)
});
}
if (schema.maxItems && node.items.length > schema.maxItems) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('maxItemsWarning', 'Array has too many items. Expected {0} or fewer.', schema.maxItems)
});
}
if (schema.uniqueItems === true) {
let values = getNodeValue(node);
let duplicates = values.some((value, index) => {
return index !== values.lastIndexOf(value);
});
if (duplicates) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('uniqueItemsWarning', 'Array has duplicate items.')
});
}
}
}
function _validateObjectNode(node: ObjectASTNode, schema: JSONSchema, validationResult: ValidationResult, matchingSchemas: ISchemaCollector): void {
let seenKeys: { [key: string]: ASTNode } = Object.create(null);
let unprocessedProperties: string[] = [];
node.properties.forEach((node) => {
let key = node.keyNode.value;
seenKeys[key] = node.valueNode;
unprocessedProperties.push(key);
});
if (Array.isArray(schema.required)) {
schema.required.forEach((propertyName: string) => {
if (!seenKeys[propertyName]) {
let keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode;
let location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 };
validationResult.problems.push({
location: location,
severity: DiagnosticSeverity.Warning,
message: localize('MissingRequiredPropWarning', 'Missing property "{0}".', propertyName)
});
}
});
}
let propertyProcessed = (prop: string) => {
let index = unprocessedProperties.indexOf(prop);
while (index >= 0) {
unprocessedProperties.splice(index, 1);
index = unprocessedProperties.indexOf(prop);
}
};
if (schema.properties) {
Object.keys(schema.properties).forEach((propertyName: string) => {
propertyProcessed(propertyName);
let propertySchema = schema.properties[propertyName];
let child = seenKeys[propertyName];
if (child) {
if (typeof propertySchema === 'boolean') {
if (!propertySchema) {
let propertyNode = <PropertyASTNode>child.parent;
validationResult.problems.push({
location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
severity: DiagnosticSeverity.Warning,
message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
});
} else {
validationResult.propertiesMatches++;
validationResult.propertiesValueMatches++;
}
} else {
let propertyValidationResult = new ValidationResult();
validate(child, propertySchema, propertyValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
});
}
if (schema.patternProperties) {
Object.keys(schema.patternProperties).forEach((propertyPattern: string) => {
let regex = new RegExp(propertyPattern);
unprocessedProperties.slice(0).forEach((propertyName: string) => {
if (regex.test(propertyName)) {
propertyProcessed(propertyName);
let child = seenKeys[propertyName];
if (child) {
let propertySchema = schema.patternProperties[propertyPattern];
if (typeof propertySchema === 'boolean') {
if (!propertySchema) {
let propertyNode = <PropertyASTNode>child.parent;
validationResult.problems.push({
location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
severity: DiagnosticSeverity.Warning,
message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
});
} else {
validationResult.propertiesMatches++;
validationResult.propertiesValueMatches++;
}
} else {
let propertyValidationResult = new ValidationResult();
validate(child, propertySchema, propertyValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
}
});
});
}
if (typeof schema.additionalProperties === 'object') {
unprocessedProperties.forEach((propertyName: string) => {
let child = seenKeys[propertyName];
if (child) {
let propertyValidationResult = new ValidationResult();
validate(child, <any>schema.additionalProperties, propertyValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(propertyValidationResult);
}
});
} else if (schema.additionalProperties === false) {
if (unprocessedProperties.length > 0) {
unprocessedProperties.forEach((propertyName: string) => {
let child = seenKeys[propertyName];
if (child) {
let propertyNode = <PropertyASTNode>child.parent;
validationResult.problems.push({
location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
severity: DiagnosticSeverity.Warning,
message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
});
}
});
}
}
if (schema.maxProperties) {
if (node.properties.length > schema.maxProperties) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('MaxPropWarning', 'Object has more properties than limit of {0}.', schema.maxProperties)
});
}
}
if (schema.minProperties) {
if (node.properties.length < schema.minProperties) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('MinPropWarning', 'Object has fewer properties than the required number of {0}', schema.minProperties)
});
}
}
if (schema.dependencies) {
Object.keys(schema.dependencies).forEach((key: string) => {
let prop = seenKeys[key];
if (prop) {
let propertyDep = schema.dependencies[key];
if (Array.isArray(propertyDep)) {
propertyDep.forEach((requiredProp: string) => {
if (!seenKeys[requiredProp]) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
severity: DiagnosticSeverity.Warning,
message: localize('RequiredDependentPropWarning', 'Object is missing property {0} required by property {1}.', requiredProp, key)
});
} else {
validationResult.propertiesValueMatches++;
}
});
} else {
let propertySchema = asSchema(propertyDep);
if (propertySchema) {
let propertyValidationResult = new ValidationResult();
validate(node, propertySchema, propertyValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
}
});
}
let propertyNames = asSchema(schema.propertyNames);
if (propertyNames) {
node.properties.forEach(f => {
let key = f.keyNode;
if (key) {
validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance);
}
});
}
}
}
export function parse(textDocument: TextDocument, config?: JSONDocumentConfig): JSONDocument {
let problems: Diagnostic[] = [];
let lastProblemOffset = -1;
let text = textDocument.getText();
let scanner = Json.createScanner(text, false);
let commentRanges: Range[] = config && config.collectComments ? [] : void 0;
function _scanNext(): Json.SyntaxKind {
while (true) {
let token = scanner.scan();
_checkScanError();
switch (token) {
case Json.SyntaxKind.LineCommentTrivia:
case Json.SyntaxKind.BlockCommentTrivia:
if (Array.isArray(commentRanges)) {
commentRanges.push(Range.create(textDocument.positionAt(scanner.getTokenOffset()), textDocument.positionAt(scanner.getTokenOffset() + scanner.getTokenLength())));
}
break;
case Json.SyntaxKind.Trivia:
case Json.SyntaxKind.LineBreakTrivia:
break;
default:
return token;
}
}
}
function _accept(token: Json.SyntaxKind): boolean {
if (scanner.getToken() === token) {
_scanNext();
return true;
}
return false;
}
function _errorAtRange<T extends ASTNode>(message: string, code: ErrorCode, startOffset: number, endOffset: number, severity : DiagnosticSeverity = DiagnosticSeverity.Error): void {
if (problems.length === 0 || startOffset !== lastProblemOffset) {
let range = Range.create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset));
problems.push(Diagnostic.create(range, message, severity, code, textDocument.languageId));
lastProblemOffset = startOffset;
}
}
function _error<T extends ASTNodeImpl>(message: string, code: ErrorCode, node: T = null, skipUntilAfter: Json.SyntaxKind[] = [], skipUntil: Json.SyntaxKind[] = []): T {
let start = scanner.getTokenOffset();
let end = scanner.getTokenOffset() + scanner.getTokenLength();
if (start === end && start > 0) {
start--;
while (start > 0 && /\s/.test(text.charAt(start))) {
start--;
}
end = start + 1;
}
_errorAtRange(message, code, start, end);
if (node) {
_finalize(node, false);
}
if (skipUntilAfter.length + skipUntil.length > 0) {
let token = scanner.getToken();
while (token !== Json.SyntaxKind.EOF) {
if (skipUntilAfter.indexOf(token) !== -1) {
_scanNext();
break;
} else if (skipUntil.indexOf(token) !== -1) {
break;
}
token = _scanNext();
}