All files / src/parser jsonParser.ts

96.67% Statements 696/720
93.15% Branches 435/467
95.4% Functions 83/87
96.86% Lines 617/637

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261          1x   1x 1x   1x   1x             1x                             1x               6306x 3320x 3320x 3320x     1x 114x     1x     1x   1x   9x 9x   9x   1x   1x   73x       73x 73x   1x   1x   101x       101x 101x     1x 71x   1x   1x   568x         568x 568x 568x   1x   1x 1379x       1379x 1379x   1x   1x 844x           844x 844x 844x     1x 178x   1x   1x 346x       346x   346x     1x 184x     1x     1x 2714x     2714x                         1x 1x                     1x 135x 135x   1x 195x   1x 39x   1x 227x   1x 50x   1x   1x   2x 1x 1x 721x 119x   1x 1x   1x                   880x 880x 880x 880x 880x 880x     1x 746x     1x           1x 548x     1x 26x 3x 3x 3x 9x           1x 471x 471x 471x 59x   471x 20x       1x 58x 58x 18x   40x     40x 7x   33x 5x   28x     1x   1x       1x 151x     1x 64x     275x 144x     1x   350x     185x 152x 149x   3x     1x 7x 7x 99x 99x 99x 99x 92x     99x   7x       1x 142x 142x 142x 142x 84x 84x           87x 85x 85x 85x   85x   1x       948x 32x   916x 916x   484x 484x   44x 44x   246x 246x   99x 99x       916x   916x         589x     916x 3x 1x             913x 584x 45x             916x 72x 72x     916x 916x 2x 2x 2x 2x 1x           2x           916x 61x     61x 133x 133x 133x 133x 133x 133x 58x   133x 61x   72x   14x 14x 14x   58x 58x   10x 48x   26x 26x           61x 8x           61x 61x 61x 61x 61x   61x   916x 19x   916x 42x     916x 16x 16x   16x   16x 16x 16x 16x     916x 18x 18x 18x   18x 18x   18x 9x 8x   9x 8x       916x 916x 18x     916x 94x 94x 142x 142x 32x 32x     94x 94x 94x 62x       72x         916x 29x 29x 19x           19x   10x   29x     916x 1x                     99x   99x 2x 1x               198x 2x   196x 2x   194x     198x 196x   2x   99x 99x 2x           99x 99x 2x           99x 99x 1x           99x 99x 1x                 246x 1x             246x 2x             246x 5x 5x 1x               246x 23x     6x 6x 2x   4x 4x   4x 2x     6x 4x             6x           15x 15x 7x                       44x 12x 12x 36x 36x 36x 36x 36x 29x 29x 7x       12x 4x 2x 4x 4x 4x   2x 1x               32x 32x 24x 24x 24x 24x         44x 44x 2x 6x 6x 6x     2x 1x               44x 1x             44x 1x             44x 3x 3x 8x   3x 2x                     484x 484x 1140x 1140x 1140x 1140x     484x 199x 199x 45x 45x 45x                 484x 750x 750x 434x 434x       484x 742x 742x 742x 742x 742x 402x 2x 1x 1x           1x 1x     400x 400x 400x             484x 7x 7x 10x 10x 8x 8x 8x 8x 8x 2x 1x 1x           1x 1x     6x 6x 6x               484x 6x 5x 5x 5x 5x 5x     481x 5x 2x 1x 1x 1x   1x                   484x 3x 1x               484x 3x 1x               484x 7x 7x 7x 5x 5x 4x 2x 1x           1x       3x 3x 3x 3x 3x             484x 484x 3x 3x 3x 3x                 1x   330x 330x 330x 330x   330x     4359x 5624x 5624x 5624x     10x 10x   10x     1255x   4359x                         421x   214x 165x 165x 165x       296x 170x 170x 170x 93x 93x 38x   93x   170x   170x 101x   170x 44x 44x 32x     32x 23x   9x     170x       5624x   3x 3x   2x 2x   2x 2x   1x 1x   17x 17x   1x 1x   5598x       2178x   2178x 2077x     2178x       1347x 1246x   101x 101x   101x 101x 101x 196x 107x 1x   107x 107x 107x 7x 6x   7x   89x 4x   189x 189x 5x   184x   189x     101x 19x     82x     330x     844x 844x 844x 7x   4x 4x 4x 4x 4x   3x     841x   841x 841x 4x 4x 3x   4x   837x     841x 825x 825x   16x 16x 3x 3x     838x 838x 36x   802x 802x 802x       1246x 900x   346x 346x 346x 346x   346x 875x 560x 1x   560x 560x 560x 31x 31x   31x   315x 7x   844x 844x 3x   841x   844x     346x 46x   300x       1744x 699x     1045x 1045x   1045x       692x 124x     568x 568x 566x 566x 566x 566x     566x       566x   568x         124x   9x   59x   14x   42x         1347x     330x 330x 330x 320x 320x 1x 319x 1x     330x  
/*---------------------------------------------------------------------------------------------
 *  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 } from '../utils/objects';
import { TextDocument, ASTNode, ObjectASTNode, ArrayASTNode, BooleanASTNode, NumberASTNode, StringASTNode, NullASTNode, PropertyASTNode, JSONPath, ErrorCode, Diagnostic, DiagnosticSeverity, Range } from '../jsonLanguageTypes';
 
import * as nls from 'vscode-nls';
 
const localize = nls.loadMessageBundle();
 
export interface IRange {
	offset: number;
	length: number;
}
 
const formats = {
	'color-hex': { errorMessage: localize('colorHexFormatWarning', '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: localize('dateTimeFormatWarning', '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: localize('dateFormatWarning', '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: localize('timeFormatWarning', '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: localize('emailFormatWarning', '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-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 | 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 {
	Iif (isBoolean(schema)) {
		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): boolean;
	newSub(): ISchemaCollector;
}
 
class SchemaCollector implements ISchemaCollector {
	schemas: IApplicableSchema[] = [];
	constructor(private IfocusOffset = -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 propertiesValueMatches: number;
	public primaryValueMatches: number;
	public enumValueMatch: boolean;
	public enumValues: any[] | undefined;
 
	constructor() {
		this.problems = [];
		this.propertiesMatches = 0;
		this.propertiesValueMatches = 0;
		this.primaryValueMatches = 0;
		this.enumValueMatch = false;
		this.enumValues = undefined;
	}
 
	public hasProblems(): boolean {
		return !!this.problems.length;
	}
 
	public mergeAll(validationResults: ValidationResult[]): void {
		for (const validationResult of validationResults) {
			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 (const error of this.problems) {
				Eif (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 {
		const hasProblems = this.hasProblems();
		if (hasProblems !== other.hasProblems()) {
			return hasProblems ? -1 : 1;
		}
		Iif (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 IsyntaxErrors: 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 {
		Eif (this.root) {
			const doVisit = (node: ASTNode): boolean => {
				let ctn = visitor(node);
				const children = node.children;
				Eif (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): Diagnostic[] | undefined {
		Eif (this.root && schema) {
			const validationResult = new ValidationResult();
			validate(this.root, schema, validationResult, NoOpSchemaCollector.instance);
			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, p.code);
			});
		}
		return undefined;
	}
 
	public getMatchingSchemas(schema: JSONSchema, focusOffset: number = -1, exclude?: ASTNode): IApplicableSchema[] {
		const matchingSchemas = new SchemaCollector(focusOffset, exclude);
		Eif (this.root && schema) {
			validate(this.root, schema, new ValidationResult(), matchingSchemas);
		}
		return matchingSchemas.schemas;
	}
}
 
function validate(n: ASTNode | undefined, schema: JSONSchema, validationResult: ValidationResult, matchingSchemas: ISchemaCollector): void {
 
	if (!n || !matchingSchemas.include(n)) {
		return;
	}
	const node = n;
	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)) {
			for (const subSchemaRef of schema.allOf) {
				validate(node, asSchema(subSchemaRef), validationResult, matchingSchemas);
			}
		}
		const notSchema = asSchema(schema.not);
		if (notSchema) {
			const subValidationResult = new ValidationResult();
			const 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.")
				});
			}
			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);
				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 {
						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 },
					severity: DiagnosticSeverity.Warning,
					message: localize('oneOfWarning', "Matches multiple schemas when only one must validate.")
				});
			}
			Eif (bestMatch) {
				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);
		}
 
		const testBranch = (schema: JSONSchemaRef) => {
			const subValidationResult = new ValidationResult();
			const subMatchingSchemas = matchingSchemas.newSub();
 
			validate(node, asSchema(schema), subValidationResult, subMatchingSchemas);
 
			validationResult.merge(subValidationResult);
			validationResult.propertiesMatches += subValidationResult.propertiesMatches;
			validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
			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);
			matchingSchemas.merge(subMatchingSchemas);
 
			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 },
					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 (isDefined(schema.const)) {
			const val = getNodeValue(node);
			if (!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 {
		const val = node.value;
 
		if (isNumber(schema.multipleOf)) {
			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 (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 },
				severity: DiagnosticSeverity.Warning,
				message: localize('exclusiveMinimumWarning', '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 },
				severity: DiagnosticSeverity.Warning,
				message: localize('exclusiveMaximumWarning', '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 },
				severity: DiagnosticSeverity.Warning,
				message: localize('minimumWarning', '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 },
				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 (isNumber(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 (isNumber(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 (isString(schema.pattern)) {
			const 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 {
						const match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value);
						Iif (!match) {
							errorMessage = localize('uriMissing', 'URI is expected.');
						} else if (!match[2] && schema.format === 'uri') {
							errorMessage = localize('uriSchemeMissing', 'URI with a scheme is expected.');
						}
					}
					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 'color-hex':
				case 'date-time':
				case 'date':
				case 'time':
				case 'email':
					const format = formats[schema.format];
					if (!node.value || !format.pattern.exec(node.value)) {
						validationResult.problems.push({
							location: { offset: node.offset, length: node.length },
							severity: DiagnosticSeverity.Warning,
							message: schema.patternErrorMessage || schema.errorMessage || format.errorMessage
						});
					}
				default:
			}
		}
 
	}
	function _validateArrayNode(node: ArrayASTNode, schema: JSONSchema, validationResult: ValidationResult, matchingSchemas: ISchemaCollector): void {
		if (Array.isArray(schema.items)) {
			const subSchemas = schema.items;
			for (let index = 0; index < subSchemas.length; index++) {
				const subSchemaRef = subSchemas[index];
				const subSchema = asSchema(subSchemaRef);
				const itemValidationResult = new ValidationResult();
				const item = node.items[index];
				if (item) {
					validate(item, subSchema, itemValidationResult, matchingSchemas);
					validationResult.mergePropertyMatch(itemValidationResult);
				} else Iif (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++) {
						const 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 {
			const itemSchema = asSchema(schema.items);
			if (itemSchema) {
				for (const item of node.items) {
					const itemValidationResult = new ValidationResult();
					validate(item, itemSchema, itemValidationResult, matchingSchemas);
					validationResult.mergePropertyMatch(itemValidationResult);
				}
			}
		}
 
		const containsSchema = asSchema(schema.contains);
		if (containsSchema) {
			const doesContain = node.items.some(item => {
				const 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.')
				});
			}
		}
 
		if (isNumber(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 (isNumber(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) {
			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 },
					severity: DiagnosticSeverity.Warning,
					message: localize('uniqueItemsWarning', 'Array has duplicate items.')
				});
			}
		}
 
	}
 
	function _validateObjectNode(node: ObjectASTNode, schema: JSONSchema, validationResult: ValidationResult, matchingSchemas: ISchemaCollector): void {
		const seenKeys: { [key: string]: ASTNode | undefined } = Object.create(null);
		const unprocessedProperties: string[] = [];
		for (const propertyNode of node.properties) {
			const key = propertyNode.keyNode.value;
			seenKeys[key] = propertyNode.valueNode;
			unprocessedProperties.push(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,
						severity: DiagnosticSeverity.Warning,
						message: localize('MissingRequiredPropWarning', 'Missing property "{0}".', propertyName)
					});
				}
			}
		}
 
		const propertyProcessed = (prop: string) => {
			let index = unprocessedProperties.indexOf(prop);
			while (index >= 0) {
				unprocessedProperties.splice(index, 1);
				index = unprocessedProperties.indexOf(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 },
								severity: DiagnosticSeverity.Warning,
								message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
							});
						} else {
							validationResult.propertiesMatches++;
							validationResult.propertiesValueMatches++;
						}
					} else {
						const propertyValidationResult = new ValidationResult();
						validate(child, propertySchema, propertyValidationResult, matchingSchemas);
						validationResult.mergePropertyMatch(propertyValidationResult);
					}
				}
 
			}
		}
 
		if (schema.patternProperties) {
			for (const propertyPattern of Object.keys(schema.patternProperties)) {
				const regex = new RegExp(propertyPattern);
				for (const propertyName of unprocessedProperties.slice(0)) {
					if (regex.test(propertyName)) {
						propertyProcessed(propertyName);
						const child = seenKeys[propertyName];
						Eif (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 },
										severity: DiagnosticSeverity.Warning,
										message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
									});
								} else {
									validationResult.propertiesMatches++;
									validationResult.propertiesValueMatches++;
								}
							} else {
								const propertyValidationResult = new ValidationResult();
								validate(child, propertySchema, propertyValidationResult, matchingSchemas);
								validationResult.mergePropertyMatch(propertyValidationResult);
							}
						}
					}
				}
			}
		}
 
		if (typeof schema.additionalProperties === 'object') {
			for (const propertyName of unprocessedProperties) {
				const child = seenKeys[propertyName];
				Eif (child) {
					const propertyValidationResult = new ValidationResult();
					validate(child, <any>schema.additionalProperties, propertyValidationResult, matchingSchemas);
					validationResult.mergePropertyMatch(propertyValidationResult);
				}
			}
		} else if (schema.additionalProperties === false) {
			if (unprocessedProperties.length > 0) {
				for (const propertyName of unprocessedProperties) {
					const child = seenKeys[propertyName];
					Eif (child) {
						const 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 (isNumber(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 (isNumber(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) {
			for (const key of Object.keys(schema.dependencies)) {
				const prop = seenKeys[key];
				if (prop) {
					const propertyDep = schema.dependencies[key];
					if (Array.isArray(propertyDep)) {
						for (const requiredProp of propertyDep) {
							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 {
						const propertySchema = asSchema(propertyDep);
						Eif (propertySchema) {
							const propertyValidationResult = new ValidationResult();
							validate(node, propertySchema, propertyValidationResult, matchingSchemas);
							validationResult.mergePropertyMatch(propertyValidationResult);
						}
					}
				}
			}
		}
 
		const propertyNames = asSchema(schema.propertyNames);
		if (propertyNames) {
			for (const f of node.properties) {
				const key = f.keyNode;
				Eif (key) {
					validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance);
				}
			}
		}
	}
 
}
 
 
export function parse(textDocument: TextDocument, config?: JSONDocumentConfig): JSONDocument {
 
	const problems: Diagnostic[] = [];
	let lastProblemOffset = -1;
	const text = textDocument.getText();
	const scanner = Json.createScanner(text, false);
 
	const commentRanges: Range[] | undefined = config && config.collectComments ? [] : undefined;
 
	function _scanNext(): Json.SyntaxKind {
		while (true) {
			const token = scanner.scan();
			_checkScanError();
			switch (token) {
				case Json.SyntaxKind.LineCommentTrivia:
				case Json.SyntaxKind.BlockCommentTrivia:
					Eif (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) {
			const 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 | undefined = undefined, skipUntilAfter: Json.SyntaxKind[] = [], skipUntil: Json.SyntaxKind[] = []): T | undefined {
		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) {
				Iif (skipUntilAfter.indexOf(token) !== -1) {
					_scanNext();
					break;
				} else if (skipUntil.indexOf(token) !== -1) {
					break;
				}
				token = _scanNext();
			}
		}
		return node;
	}
 
	function _checkScanError(): boolean {
		switch (scanner.getTokenError()) {
			case Json.ScanError.InvalidUnicode:
				_error(localize('InvalidUnicode', 'Invalid unicode sequence in string.'), ErrorCode.InvalidUnicode);
				return true;
			case Json.ScanError.InvalidEscapeCharacter:
				_error(localize('InvalidEscapeCharacter', 'Invalid escape character in string.'), ErrorCode.InvalidEscapeCharacter);
				return true;
			case Json.ScanError.UnexpectedEndOfNumber:
				_error(localize('UnexpectedEndOfNumber', 'Unexpected end of number.'), ErrorCode.UnexpectedEndOfNumber);
				return true;
			case Json.ScanError.UnexpectedEndOfComment:
				_error(localize('UnexpectedEndOfComment', 'Unexpected end of comment.'), ErrorCode.UnexpectedEndOfComment);
				return true;
			case Json.ScanError.UnexpectedEndOfString:
				_error(localize('UnexpectedEndOfString', 'Unexpected end of string.'), ErrorCode.UnexpectedEndOfString);
				return true;
			case Json.ScanError.InvalidCharacter:
				_error(localize('InvalidCharacter', 'Invalid characters in string. Control characters must be escaped.'), ErrorCode.InvalidCharacter);
				return true;
		}
		return false;
	}
 
	function _finalize<T extends ASTNodeImpl>(node: T, scanNext: boolean): T {
		node.length = scanner.getTokenOffset() + scanner.getTokenLength() - node.offset;
 
		if (scanNext) {
			_scanNext();
		}
 
		return node;
	}
 
	function _parseArray(parent: ASTNode | undefined): ArrayASTNode | undefined {
		if (scanner.getToken() !== Json.SyntaxKind.OpenBracketToken) {
			return undefined;
		}
		const node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset());
		_scanNext(); // consume OpenBracketToken
 
		const count = 0;
		let needsComma = false;
		while (scanner.getToken() !== Json.SyntaxKind.CloseBracketToken && scanner.getToken() !== Json.SyntaxKind.EOF) {
			if (scanner.getToken() === Json.SyntaxKind.CommaToken) {
				if (!needsComma) {
					_error(localize('ValueExpected', 'Value expected'), ErrorCode.ValueExpected);
				}
				const commaOffset = scanner.getTokenOffset();
				_scanNext(); // consume comma
				if (scanner.getToken() === Json.SyntaxKind.CloseBracketToken) {
					if (needsComma) {
						_errorAtRange(localize('TrailingComma', 'Trailing comma'), ErrorCode.TrailingComma, commaOffset, commaOffset + 1);
					}
					continue;
				}
			} else if (needsComma) {
				_error(localize('ExpectedComma', 'Expected comma'), ErrorCode.CommaExpected);
			}
			const item = _parseValue(node);
			if (!item) {
				_error(localize('PropertyExpected', 'Value expected'), ErrorCode.ValueExpected, undefined, [], [Json.SyntaxKind.CloseBracketToken, Json.SyntaxKind.CommaToken]);
			} else {
				node.items.push(item);
			}
			needsComma = true;
		}
 
		if (scanner.getToken() !== Json.SyntaxKind.CloseBracketToken) {
			return _error(localize('ExpectedCloseBracket', 'Expected comma or closing bracket'), ErrorCode.CommaOrCloseBacketExpected, node);
		}
 
		return _finalize(node, true);
	}
 
	const keyPlaceholder = new StringASTNodeImpl(undefined, 0, 0);
 
	function _parseProperty(parent: ObjectASTNode | undefined, keysSeen: { [key: string]: (PropertyASTNode | boolean) }): PropertyASTNode | undefined {
		const node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset(), keyPlaceholder);
		let key = _parseString(node);
		if (!key) {
			if (scanner.getToken() === Json.SyntaxKind.Unknown) {
				// give a more helpful error message
				_error(localize('DoubleQuotesExpected', 'Property keys must be doublequoted'), ErrorCode.Undefined);
				const keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength());
				keyNode.value = scanner.getTokenValue();
				key = keyNode;
				_scanNext(); // consume Unknown
			} else {
				return undefined;
			}
		}
		node.keyNode = key;
 
		const seen = keysSeen[key.value];
		if (seen) {
			_errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), ErrorCode.DuplicateKey, node.keyNode.offset, node.keyNode.offset + node.keyNode.length, DiagnosticSeverity.Warning);
			if (typeof seen === 'object') {
				_errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), ErrorCode.DuplicateKey, seen.keyNode.offset, seen.keyNode.offset + seen.keyNode.length, DiagnosticSeverity.Warning);
			}
			keysSeen[key.value] = true; // if the same key is duplicate again, avoid duplicate error reporting
		} else {
			keysSeen[key.value] = node;
		}
 
		if (scanner.getToken() === Json.SyntaxKind.ColonToken) {
			node.colonOffset = scanner.getTokenOffset();
			_scanNext(); // consume ColonToken
		} else {
			_error(localize('ColonExpected', 'Colon expected'), ErrorCode.ColonExpected);
			if (scanner.getToken() === Json.SyntaxKind.StringLiteral && textDocument.positionAt(key.offset + key.length).line < textDocument.positionAt(scanner.getTokenOffset()).line) {
				node.length = key.length;
				return node;
			}
		}
		const value = _parseValue(node);
		if (!value) {
			return _error(localize('ValueExpected', 'Value expected'), ErrorCode.ValueExpected, node, [], [Json.SyntaxKind.CloseBraceToken, Json.SyntaxKind.CommaToken]);
		}
		node.valueNode = value;
		node.length = value.offset + value.length - node.offset;
		return node;
	}
 
	function _parseObject(parent: ASTNode | undefined): ObjectASTNode | undefined {
		if (scanner.getToken() !== Json.SyntaxKind.OpenBraceToken) {
			return undefined;
		}
		const node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset());
		const keysSeen: any = Object.create(null);
		_scanNext(); // consume OpenBraceToken
		let needsComma = false;
 
		while (scanner.getToken() !== Json.SyntaxKind.CloseBraceToken && scanner.getToken() !== Json.SyntaxKind.EOF) {
			if (scanner.getToken() === Json.SyntaxKind.CommaToken) {
				if (!needsComma) {
					_error(localize('PropertyExpected', 'Property expected'), ErrorCode.PropertyExpected);
				}
				const commaOffset = scanner.getTokenOffset();
				_scanNext(); // consume comma
				if (scanner.getToken() === Json.SyntaxKind.CloseBraceToken) {
					Eif (needsComma) {
						_errorAtRange(localize('TrailingComma', 'Trailing comma'), ErrorCode.TrailingComma, commaOffset, commaOffset + 1);
					}
					continue;
				}
			} else if (needsComma) {
				_error(localize('ExpectedComma', 'Expected comma'), ErrorCode.CommaExpected);
			}
			const property = _parseProperty(node, keysSeen);
			if (!property) {
				_error(localize('PropertyExpected', 'Property expected'), ErrorCode.PropertyExpected, undefined, [], [Json.SyntaxKind.CloseBraceToken, Json.SyntaxKind.CommaToken]);
			} else {
				node.properties.push(property);
			}
			needsComma = true;
		}
 
		if (scanner.getToken() !== Json.SyntaxKind.CloseBraceToken) {
			return _error(localize('ExpectedCloseBrace', 'Expected comma or closing brace'), ErrorCode.CommaOrCloseBraceExpected, node);
		}
		return _finalize(node, true);
	}
 
	function _parseString(parent: ASTNode | undefined): StringASTNode | undefined {
		if (scanner.getToken() !== Json.SyntaxKind.StringLiteral) {
			return undefined;
		}
 
		const node = new StringASTNodeImpl(parent, scanner.getTokenOffset());
		node.value = scanner.getTokenValue();
 
		return _finalize(node, true);
	}
 
	function _parseNumber(parent: ASTNode | undefined): NumberASTNode | undefined {
		if (scanner.getToken() !== Json.SyntaxKind.NumericLiteral) {
			return undefined;
		}
 
		const node = new NumberASTNodeImpl(parent, scanner.getTokenOffset());
		if (scanner.getTokenError() === Json.ScanError.None) {
			const tokenValue = scanner.getTokenValue();
			try {
				const numberValue = JSON.parse(tokenValue);
				Iif (!isNumber(numberValue)) {
					return _error(localize('InvalidNumberFormat', 'Invalid number format.'), ErrorCode.Undefined, node);
				}
				node.value = numberValue;
			} catch (e) {
				return _error(localize('InvalidNumberFormat', 'Invalid number format.'), ErrorCode.Undefined, node);
			}
			node.isInteger = tokenValue.indexOf('.') === -1;
		}
		return _finalize(node, true);
	}
 
	function _parseLiteral(parent: ASTNode | undefined): ASTNode | undefined {
		let node: ASTNodeImpl;
		switch (scanner.getToken()) {
			case Json.SyntaxKind.NullKeyword:
				return _finalize(new NullASTNodeImpl(parent, scanner.getTokenOffset()), true);
			case Json.SyntaxKind.TrueKeyword:
				return _finalize(new BooleanASTNodeImpl(parent, true, scanner.getTokenOffset()), true);
			case Json.SyntaxKind.FalseKeyword:
				return _finalize(new BooleanASTNodeImpl(parent, false, scanner.getTokenOffset()), true);
			default:
				return undefined;
		}
	}
 
	function _parseValue(parent: ASTNode | undefined): ASTNode | undefined {
		return _parseArray(parent) || _parseObject(parent) || _parseString(parent) || _parseNumber(parent) || _parseLiteral(parent);
	}
 
	let _root: ASTNode | undefined = undefined;
	const token = _scanNext();
	if (token !== Json.SyntaxKind.EOF) {
		_root = _parseValue(_root);
		if (!_root) {
			_error(localize('Invalid symbol', 'Expected a JSON object, array or literal.'), ErrorCode.Undefined);
		} else if (scanner.getToken() !== Json.SyntaxKind.EOF) {
			_error(localize('End of file expected', 'End of file expected.'), ErrorCode.Undefined);
		}
	}
	return new JSONDocument(_root, problems, commentRanges);
}