All files / src/services jsonCompletion.ts

84.57% Statements 433/512
77.5% Branches 341/440
81.54% Functions 53/65
84.23% Lines 406/482

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          1x 1x       1x 1x 1x 1x             1x 1x   1x 1x   1x           329x 658x 329x 550x     1x                         90x   90x         90x   90x 90x 90x 1x   89x 28x 28x   1x       89x     89x 25x   64x 64x     64x     89x   89x 89x   232x 232x 232x 208x 208x 5x 5x 3x     208x 208x   208x     208x 208x 208x 24x 24x                         89x       89x 89x   89x 89x   89x 89x   86x 24x 24x 13x 13x 13x 13x 13x             89x   43x       43x 43x 31x 18x     43x 43x 42x     43x   32x     11x     43x 43x           43x                       89x 89x   72x     17x   89x       89x 89x 2x 2x     2x 2x   89x         32x 32x 32x 81x 61x 61x 44x 98x 98x 96x               96x 18x         96x               11x 11x 11x 19x 19x                   11x 10x   1x 1x 24x 1x   24x   9x   9x 19x 10x       1x 1x                   17x 17x 17x 3x 3x     17x                                 17x 17x 13x 10x             13x 1x       17x 6x   6x 6x       6x 6x 75x 13x   75x   6x         17x                                     1x 72x 72x 72x   72x 9x 9x 9x     72x 3x 3x     69x 28x 28x     28x 28x     69x 37x   37x 74x 57x 46x 9x 4x 4x 4x     5x     46x 28x 28x 28x         37x 4x   37x 2x 2x   37x 1x           1x                                                         42x 42x 42x 42x 42x 42x     42x 2x   42x           85x 43x 43x 6x 6x 6x       6x             6x   43x 1x 2x 2x 2x       2x           2x     43x 3x 5x 5x 5x     5x 4x 4x 1x 1x   4x 4x 4x 1x 1x 1x 1x 1x 1x 1x   1x 1x         5x               5x     43x 1x         1x 42x 2x                 42x 31x 68x 68x 68x 9x 59x 6x   68x                     1x 42x 33x   9x 9x 3x 7x 5x       1x 2x 1x                 2x                       1x 5x                 1x 1x                 4x 16x 16x                 1x 94x     1x 132x     1x 4x     1x 2x 2x     1x 233x     1x 217x 217x 3x 214x     214x     1x 7x 7x 7x 1x     6x   7x     1x 13x   1x     1x   10x 10x 10x 10x     2x         1x 100x 6x 6x   100x 60x   40x 17x 5x   18x       1x 10x       1x   9x 9x       1x 10x       1x   9x 9x       1x   97x 97x     97x     97x 97x 96x 4x 3x 3x 3x     4x   96x 13x 7x   13x   96x 6x 5x   6x   96x           96x 77x 77x 7x   7x       77x   11x 11x   41x 41x   6x 6x   1x 1x     11x 11x         7x       90x 8x   90x     1x 89x 89x 89x 26x   89x     1x 98x 98x 98x 98x         91x   7x       1x 4x 4x 4x 3x 3x 1x 1x 1x 1x     2x 1x     2x     1x 90x 90x 90x 90x 181x   90x     1x 180x 18x         162x     1x 33x 11x 11x   33x     1x               1x  
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
 
import * as Parser from '../parser/jsonParser';
import * as Json from 'jsonc-parser';
import * as SchemaService from './jsonSchemaService';
import { JSONSchema, JSONSchemaRef } from '../jsonSchema';
import { JSONWorkerContribution, CompletionsCollector } from '../jsonContributions';
import { stringifyObject } from '../utils/json';
import { endsWith } from '../utils/strings';
import { isDefined } from '../utils/objects';
import {
	PromiseConstructor, Thenable,
	ASTNode, ObjectASTNode, ArrayASTNode, PropertyASTNode, ClientCapabilities,
	TextDocument,
	CompletionItem, CompletionItemKind, CompletionList, Position, Range, TextEdit, InsertTextFormat, MarkupContent, MarkupKind
} from '../jsonLanguageTypes';
 
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
 
const valueCommitCharacters = [',', '}', ']'];
const propertyCommitCharacters = [':'];
 
export class JSONCompletion {
 
	private supportsMarkdown: boolean | undefined;
	private supportsCommitCharacters: boolean | undefined;
 
	constructor(
		private schemaService: SchemaService.IJSONSchemaService,
		private Econtributions: JSONWorkerContribution[] = [],
		private IpromiseConstructor: PromiseConstructor = Promise,
		private clientCapabilities: ClientCapabilities = {}) {
	}
 
	public doResolve(item: CompletionItem): Thenable<CompletionItem> {
		for (let i = this.contributions.length - 1; i >= 0; i--) {
			const resolveCompletion = this.contributions[i].resolveCompletion;
			if (resolveCompletion) {
				const resolver = resolveCompletion(item);
				if (resolver) {
					return resolver;
				}
			}
		}
		return this.promiseConstructor.resolve(item);
	}
 
	public doComplete(document: TextDocument, position: Position, doc: Parser.JSONDocument): Thenable<CompletionList> {
 
		const result: CompletionList = {
			items: [],
			isIncomplete: false
		};
 
		const text = document.getText();
 
		const offset = document.offsetAt(position);
		let node = doc.getNodeFromOffset(offset, true);
		if (this.isInComment(document, node ? node.offset : 0, offset)) {
			return Promise.resolve(result);
		}
		if (node && (offset === node.offset + node.length) && offset > 0) {
			const ch = text[offset - 1];
			if (node.type === 'object' && ch === '}' || node.type === 'array' && ch === ']') {
				// after ] or }
				node = node.parent;
			}
		}
 
		const currentWord = this.getCurrentWord(document, offset);
		let overwriteRange: Range;
 
		if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
			overwriteRange = Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
		} else {
			let overwriteStart = offset - currentWord.length;
			Iif (overwriteStart > 0 && text[overwriteStart - 1] === '"') {
				overwriteStart--;
			}
			overwriteRange = Range.create(document.positionAt(overwriteStart), position);
		}
 
		const supportsCommitCharacters = false; //this.doesSupportsCommitCharacters(); disabled for now, waiting for new API: https://github.com/microsoft/vscode/issues/42544
 
		const proposed: { [key: string]: CompletionItem } = {};
		const collector: CompletionsCollector = {
			add: (suggestion: CompletionItem) => {
				let label = suggestion.label;
				const existing = proposed[label];
				if (!existing) {
					label = label.replace(/[\n]/g, '↵');
					if (label.length > 60) {
						const shortendedLabel = label.substr(0, 57).trim() + '...';
						if (!proposed[shortendedLabel]) {
							label = shortendedLabel;
						}
					}
					Eif (overwriteRange && suggestion.insertText !== undefined) {
						suggestion.textEdit = TextEdit.replace(overwriteRange, suggestion.insertText);
					}
					Iif (supportsCommitCharacters) {
						suggestion.commitCharacters = suggestion.kind === CompletionItemKind.Property ? propertyCommitCharacters : valueCommitCharacters;
					}
					suggestion.label = label;
					proposed[label] = suggestion;
					result.items.push(suggestion);
				} else Eif (!existing.documentation) {
					existing.documentation = suggestion.documentation;
				}
			},
			setAsIncomplete: () => {
				result.isIncomplete = true;
			},
			error: (message: string) => {
				console.error(message);
			},
			log: (message: string) => {
				console.log(message);
			},
			getNumberOfProposals: () => {
				return result.items.length;
			}
		};
 
		return this.schemaService.getSchemaForResource(document.uri, doc).then((schema) => {
			const collectionPromises: Thenable<any>[] = [];
 
			let addValue = true;
			let currentKey = '';
 
			let currentProperty: PropertyASTNode | undefined = undefined;
			if (node) {
 
				if (node.type === 'string') {
					const parent = node.parent;
					if (parent && parent.type === 'property' && parent.keyNode === node) {
						addValue = !parent.valueNode;
						currentProperty = parent;
						currentKey = text.substr(node.offset + 1, node.length - 2);
						Eif (parent) {
							node = parent.parent;
						}
					}
				}
			}
 
			// proposals for properties
			if (node && node.type === 'object') {
				// don't suggest keys when the cursor is just before the opening curly brace
				Iif (node.offset === offset) {
					return result;
				}
				// don't suggest properties that are already present
				const properties = node.properties;
				properties.forEach(p => {
					if (!currentProperty || currentProperty !== p) {
						proposed[p.keyNode.value] = CompletionItem.create('__');
					}
				});
				let separatorAfter = '';
				if (addValue) {
					separatorAfter = this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end));
				}
 
				if (schema) {
					// property proposals with schema
					this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter, collector);
				} else {
					// property proposals without schema
					this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector);
				}
 
				const location = Parser.getNodePath(node);
				this.contributions.forEach((contribution) => {
					const collectPromise = contribution.collectPropertyCompletions(document.uri, location, currentWord, addValue, separatorAfter === '', collector);
					if (collectPromise) {
						collectionPromises.push(collectPromise);
					}
				});
				Iif ((!schema && currentWord.length > 0 && text.charAt(offset - currentWord.length - 1) !== '"')) {
					collector.add({
						kind: CompletionItemKind.Property,
						label: this.getLabelForValue(currentWord),
						insertText: this.getInsertTextForProperty(currentWord, undefined, false, separatorAfter),
						insertTextFormat: InsertTextFormat.Snippet, documentation: '',
					});
					collector.setAsIncomplete();
				}
			}
 
			// proposals for values
			const types: { [type: string]: boolean } = {};
			if (schema) {
				// value proposals with schema
				this.getValueCompletions(schema, doc, node, offset, document, collector, types);
			} else {
				// value proposals without schema
				this.getSchemaLessValueCompletions(doc, node, offset, document, collector);
			}
			Iif (this.contributions.length > 0) {
				this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises);
			}
 
			return this.promiseConstructor.all(collectionPromises).then(() => {
				if (collector.getNumberOfProposals() === 0) {
					let offsetForSeparator = offset;
					Iif (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
						offsetForSeparator = node.offset + node.length;
					}
					const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
					this.addFillerValueCompletions(types, separatorAfter, collector);
				}
				return result;
			});
		});
	}
 
	private getPropertyCompletions(schema: SchemaService.ResolvedSchema, doc: Parser.JSONDocument, node: ASTNode, addValue: boolean, separatorAfter: string, collector: CompletionsCollector): void {
		const matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
		matchingSchemas.forEach((s) => {
			if (s.node === node && !s.inverted) {
				const schemaProperties = s.schema.properties;
				if (schemaProperties) {
					Object.keys(schemaProperties).forEach((key: string) => {
						const propertySchema = schemaProperties[key];
						if (typeof propertySchema === 'object' && !propertySchema.deprecationMessage && !propertySchema.doNotSuggest) {
							const proposal: CompletionItem = {
								kind: CompletionItemKind.Property,
								label: key,
								insertText: this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter),
								insertTextFormat: InsertTextFormat.Snippet,
								filterText: this.getFilterTextForValue(key),
								documentation: this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '',
							};
							if (proposal.insertText && endsWith(proposal.insertText, `$1${separatorAfter}`)) {
								proposal.command = {
									title: 'Suggest',
									command: 'editor.action.triggerSuggest'
								};
							}
							collector.add(proposal);
						}
					});
				}
			}
		});
	}
 
	private getSchemaLessPropertyCompletions(doc: Parser.JSONDocument, node: ASTNode, currentKey: string, collector: CompletionsCollector): void {
		const collectCompletionsForSimilarObject = (obj: ObjectASTNode) => {
			obj.properties.forEach((p) => {
				const key = p.keyNode.value;
				collector.add({
					kind: CompletionItemKind.Property,
					label: key,
					insertText: this.getInsertTextForValue(key, ''),
					insertTextFormat: InsertTextFormat.Snippet,
					filterText: this.getFilterTextForValue(key),
					documentation: ''
				});
			});
		};
		if (node.parent) {
			if (node.parent.type === 'property') {
				// if the object is a property value, check the tree for other objects that hang under a property of the same name
				const parentKey = node.parent.keyNode.value;
				doc.visit(n => {
					if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey && n.valueNode && n.valueNode.type === 'object') {
						collectCompletionsForSimilarObject(n.valueNode);
					}
					return true;
				});
			} else Eif (node.parent.type === 'array') {
				// if the object is in an array, use all other array elements as similar objects
				node.parent.items.forEach(n => {
					if (n.type === 'object' && n !== node) {
						collectCompletionsForSimilarObject(n);
					}
				});
			}
		} else Eif (node.type === 'object') {
			collector.add({
				kind: CompletionItemKind.Property,
				label: '$schema',
				insertText: this.getInsertTextForProperty('$schema', undefined, true, ''),
				insertTextFormat: InsertTextFormat.Snippet, documentation: '',
				filterText: this.getFilterTextForValue("$schema")
			});
		}
	}
 
	private getSchemaLessValueCompletions(doc: Parser.JSONDocument, node: ASTNode | undefined, offset: number, document: TextDocument, collector: CompletionsCollector): void {
		let offsetForSeparator = offset;
		if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
			offsetForSeparator = node.offset + node.length;
			node = node.parent;
		}
 
		Iif (!node) {
			collector.add({
				kind: this.getSuggestionKind('object'),
				label: 'Empty object',
				insertText: this.getInsertTextForValue({}, ''),
				insertTextFormat: InsertTextFormat.Snippet,
				documentation: ''
			});
			collector.add({
				kind: this.getSuggestionKind('array'),
				label: 'Empty array',
				insertText: this.getInsertTextForValue([], ''),
				insertTextFormat: InsertTextFormat.Snippet,
				documentation: ''
			});
			return;
		}
		const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
		const collectSuggestionsForValues = (value: ASTNode) => {
			if (value.parent && !Parser.contains(value.parent, offset, true)) {
				collector.add({
					kind: this.getSuggestionKind(value.type),
					label: this.getLabelTextForMatchingNode(value, document),
					insertText: this.getInsertTextForMatchingNode(value, document, separatorAfter),
					insertTextFormat: InsertTextFormat.Snippet, documentation: ''
				});
			}
			if (value.type === 'boolean') {
				this.addBooleanValueCompletion(!value.value, separatorAfter, collector);
			}
		};
 
		if (node.type === 'property') {
			Eif (offset > (node.colonOffset || 0)) {
 
				const valueNode = node.valueNode;
				Iif (valueNode && (offset > (valueNode.offset + valueNode.length) || valueNode.type === 'object' || valueNode.type === 'array')) {
					return;
				}
				// suggest values at the same key
				const parentKey = node.keyNode.value;
				doc.visit(n => {
					if (n.type === 'property' && n.keyNode.value === parentKey && n.valueNode) {
						collectSuggestionsForValues(n.valueNode);
					}
					return true;
				});
				Iif (parentKey === '$schema' && node.parent && !node.parent.parent) {
					this.addDollarSchemaCompletions(separatorAfter, collector);
				}
			}
		}
		Iif (node.type === 'array') {
			if (node.parent && node.parent.type === 'property') {
 
				// suggest items of an array at the same key
				const parentKey = node.parent.keyNode.value;
				doc.visit((n) => {
					if (n.type === 'property' && n.keyNode.value === parentKey && n.valueNode && n.valueNode.type === 'array') {
						n.valueNode.items.forEach(collectSuggestionsForValues);
					}
					return true;
				});
			} else {
				// suggest items in the same array
				node.items.forEach(collectSuggestionsForValues);
			}
		}
	}
 
 
	private getValueCompletions(schema: SchemaService.ResolvedSchema, doc: Parser.JSONDocument, node: ASTNode | undefined, offset: number, document: TextDocument, collector: CompletionsCollector, types: { [type: string]: boolean }): void {
		let offsetForSeparator = offset;
		let parentKey: string | undefined = undefined;
		let valueNode: ASTNode | undefined = undefined;
 
		if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
			offsetForSeparator = node.offset + node.length;
			valueNode = node;
			node = node.parent;
		}
 
		if (!node) {
			this.addSchemaValueCompletions(schema.schema, '', collector, types);
			return;
		}
 
		if ((node.type === 'property') && offset > (node.colonOffset || 0)) {
			const valueNode = node.valueNode;
			Iif (valueNode && offset > (valueNode.offset + valueNode.length)) {
				return; // we are past the value node
			}
			parentKey = node.keyNode.value;
			node = node.parent;
		}
 
		if (node && (parentKey !== undefined || node.type === 'array')) {
			const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
 
			const matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode);
			for (const s of matchingSchemas) {
				if (s.node === node && !s.inverted && s.schema) {
					if (node.type === 'array' && s.schema.items) {
						if (Array.isArray(s.schema.items)) {
							const index = this.findItemAtOffset(node, document, offset);
							Eif (index < s.schema.items.length) {
								this.addSchemaValueCompletions(s.schema.items[index], separatorAfter, collector, types);
							}
						} else {
							this.addSchemaValueCompletions(s.schema.items, separatorAfter, collector, types);
						}
					}
					if (s.schema.properties && parentKey !== undefined) {
						const propertySchema = s.schema.properties[parentKey];
						Eif (propertySchema) {
							this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);
						}
					}
				}
			}
			if (parentKey === '$schema' && !node.parent) {
				this.addDollarSchemaCompletions(separatorAfter, collector);
			}
			if (types['boolean']) {
				this.addBooleanValueCompletion(true, separatorAfter, collector);
				this.addBooleanValueCompletion(false, separatorAfter, collector);
			}
			if (types['null']) {
				this.addNullValueCompletion(separatorAfter, collector);
			}
		}
 
	}
 
	private getContributedValueCompletions(doc: Parser.JSONDocument, node: ASTNode | undefined, offset: number, document: TextDocument, collector: CompletionsCollector, collectionPromises: Thenable<any>[]) {
		if (!node) {
			this.contributions.forEach((contribution) => {
				const collectPromise = contribution.collectDefaultCompletions(document.uri, collector);
				if (collectPromise) {
					collectionPromises.push(collectPromise);
				}
			});
		} else {
			if (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null') {
				node = node.parent;
			}
			if (node && (node.type === 'property') && offset > (node.colonOffset || 0)) {
				const parentKey = node.keyNode.value;
 
				const valueNode = node.valueNode;
				if ((!valueNode || offset <= (valueNode.offset + valueNode.length)) && node.parent) {
					const location = Parser.getNodePath(node.parent);
					this.contributions.forEach((contribution) => {
						const collectPromise = contribution.collectValueCompletions(document.uri, location, parentKey, collector);
						if (collectPromise) {
							collectionPromises.push(collectPromise);
						}
					});
				}
			}
		}
	}
 
	private addSchemaValueCompletions(schema: JSONSchemaRef, separatorAfter: string, collector: CompletionsCollector, types: { [type: string]: boolean }): void {
		Eif (typeof schema === 'object') {
			this.addEnumValueCompletions(schema, separatorAfter, collector);
			this.addDefaultValueCompletions(schema, separatorAfter, collector);
			this.collectTypes(schema, types);
			Iif (Array.isArray(schema.allOf)) {
				schema.allOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types));
			}
			if (Array.isArray(schema.anyOf)) {
				schema.anyOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types));
			}
			Iif (Array.isArray(schema.oneOf)) {
				schema.oneOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types));
			}
		}
	}
 
	private addDefaultValueCompletions(schema: JSONSchema, separatorAfter: string, collector: CompletionsCollector, arrayDepth = 0): void {
		let hasProposals = false;
		if (isDefined(schema.default)) {
			let type = schema.type;
			let value = schema.default;
			for (let i = arrayDepth; i > 0; i--) {
				value = [value];
				type = 'array';
			}
			collector.add({
				kind: this.getSuggestionKind(type),
				label: this.getLabelForValue(value),
				insertText: this.getInsertTextForValue(value, separatorAfter),
				insertTextFormat: InsertTextFormat.Snippet,
				detail: localize('json.suggest.default', 'Default value')
			});
			hasProposals = true;
		}
		if (Array.isArray(schema.examples)) {
			schema.examples.forEach(example => {
				let type = schema.type;
				let value = example;
				for (let i = arrayDepth; i > 0; i--) {
					value = [value];
					type = 'array';
				}
				collector.add({
					kind: this.getSuggestionKind(type),
					label: this.getLabelForValue(value),
					insertText: this.getInsertTextForValue(value, separatorAfter),
					insertTextFormat: InsertTextFormat.Snippet
				});
				hasProposals = true;
			});
		}
		if (Array.isArray(schema.defaultSnippets)) {
			schema.defaultSnippets.forEach(s => {
				let type = schema.type;
				let value = s.body;
				let label = s.label;
				let insertText: string;
				let filterText: string;
				if (isDefined(value)) {
					let type = schema.type;
					for (let i = arrayDepth; i > 0; i--) {
						value = [value];
						type = 'array';
					}
					insertText = this.getInsertTextForSnippetValue(value, separatorAfter);
					filterText = this.getFilterTextForSnippetValue(value);
					label = label || this.getLabelForSnippetValue(value);
				} else Eif (typeof s.bodyText === 'string') {
					let prefix = '', suffix = '', indent = '';
					for (let i = arrayDepth; i > 0; i--) {
						prefix = prefix + indent + '[\n';
						suffix = suffix + '\n' + indent + ']';
						indent += '\t';
						type = 'array';
					}
					insertText = prefix + indent + s.bodyText.split('\n').join('\n' + indent) + suffix + separatorAfter;
					label = label || insertText,
						filterText = insertText.replace(/[\n]/g, '');   // remove new lines
				} else {
					return;
				}
				collector.add({
					kind: this.getSuggestionKind(type),
					label,
					documentation: this.fromMarkup(s.markdownDescription) || s.description,
					insertText,
					insertTextFormat: InsertTextFormat.Snippet,
					filterText
				});
				hasProposals = true;
			});
		}
		if (!hasProposals && typeof schema.items === 'object' && !Array.isArray(schema.items) && arrayDepth < 5 /* beware of recursion */) {
			this.addDefaultValueCompletions(schema.items, separatorAfter, collector, arrayDepth + 1);
		}
	}
 
 
	private addEnumValueCompletions(schema: JSONSchema, separatorAfter: string, collector: CompletionsCollector): void {
		if (isDefined(schema.const)) {
			collector.add({
				kind: this.getSuggestionKind(schema.type),
				label: this.getLabelForValue(schema.const),
				insertText: this.getInsertTextForValue(schema.const, separatorAfter),
				insertTextFormat: InsertTextFormat.Snippet,
				documentation: this.fromMarkup(schema.markdownDescription) || schema.description
			});
		}
 
		if (Array.isArray(schema.enum)) {
			for (let i = 0, length = schema.enum.length; i < length; i++) {
				const enm = schema.enum[i];
				let documentation: string | MarkupContent | undefined = this.fromMarkup(schema.markdownDescription) || schema.description;
				if (schema.markdownEnumDescriptions && i < schema.markdownEnumDescriptions.length && this.doesSupportMarkdown()) {
					documentation = this.fromMarkup(schema.markdownEnumDescriptions[i]);
				} else if (schema.enumDescriptions && i < schema.enumDescriptions.length) {
					documentation = schema.enumDescriptions[i];
				}
				collector.add({
					kind: this.getSuggestionKind(schema.type),
					label: this.getLabelForValue(enm),
					insertText: this.getInsertTextForValue(enm, separatorAfter),
					insertTextFormat: InsertTextFormat.Snippet,
					documentation
				});
			}
		}
	}
 
	private collectTypes(schema: JSONSchema, types: { [type: string]: boolean }) {
		if (Array.isArray(schema.enum) || isDefined(schema.const)) {
			return;
		}
		const type = schema.type;
		if (Array.isArray(type)) {
			type.forEach(t => types[t] = true);
		} else if (type) {
			types[type] = true;
		}
	}
 
	private addFillerValueCompletions(types: { [type: string]: boolean }, separatorAfter: string, collector: CompletionsCollector): void {
		if (types['object']) {
			collector.add({
				kind: this.getSuggestionKind('object'),
				label: '{}',
				insertText: this.getInsertTextForGuessedValue({}, separatorAfter),
				insertTextFormat: InsertTextFormat.Snippet,
				detail: localize('defaults.object', 'New object'),
				documentation: ''
			});
		}
		Iif (types['array']) {
			collector.add({
				kind: this.getSuggestionKind('array'),
				label: '[]',
				insertText: this.getInsertTextForGuessedValue([], separatorAfter),
				insertTextFormat: InsertTextFormat.Snippet,
				detail: localize('defaults.array', 'New array'),
				documentation: ''
			});
		}
	}
 
	private addBooleanValueCompletion(value: boolean, separatorAfter: string, collector: CompletionsCollector): void {
		collector.add({
			kind: this.getSuggestionKind('boolean'),
			label: value ? 'true' : 'false',
			insertText: this.getInsertTextForValue(value, separatorAfter),
			insertTextFormat: InsertTextFormat.Snippet,
			documentation: ''
		});
	}
 
	private addNullValueCompletion(separatorAfter: string, collector: CompletionsCollector): void {
		collector.add({
			kind: this.getSuggestionKind('null'),
			label: 'null',
			insertText: 'null' + separatorAfter,
			insertTextFormat: InsertTextFormat.Snippet,
			documentation: ''
		});
	}
 
	private addDollarSchemaCompletions(separatorAfter: string, collector: CompletionsCollector): void {
		const schemaIds = this.schemaService.getRegisteredSchemaIds(schema => schema === 'http' || schema === 'https');
		schemaIds.forEach(schemaId => collector.add({
			kind: CompletionItemKind.Module,
			label: this.getLabelForValue(schemaId),
			filterText: this.getFilterTextForValue(schemaId),
			insertText: this.getInsertTextForValue(schemaId, separatorAfter),
			insertTextFormat: InsertTextFormat.Snippet, documentation: ''
		}));
	}
 
	private getLabelForValue(value: any): string {
		return JSON.stringify(value);
	}
 
	private getFilterTextForValue(value: any): string {
		return JSON.stringify(value);
	}
 
	private getFilterTextForSnippetValue(value: any): string {
		return JSON.stringify(value).replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
	}
 
	private getLabelForSnippetValue(value: any): string {
		const label = JSON.stringify(value);
		return label.replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
	}
 
	private getInsertTextForPlainText(text: string): string {
		return text.replace(/[\\\$\}]/g, '\\$&');   // escape $, \ and } 
	}
 
	private getInsertTextForValue(value: any, separatorAfter: string): string {
		var text = JSON.stringify(value, null, '\t');
		if (text === '{}') {
			return '{$1}' + separatorAfter;
		} else Iif (text === '[]') {
			return '[$1]' + separatorAfter;
		}
		return this.getInsertTextForPlainText(text + separatorAfter);
	}
 
	private getInsertTextForSnippetValue(value: any, separatorAfter: string): string {
		const replacer = (value: any) => {
			Eif (typeof value === 'string') {
				if (value[0] === '^') {
					return value.substr(1);
				}
			}
			return JSON.stringify(value);
		};
		return stringifyObject(value, '', replacer) + separatorAfter;
	}
 
	private getInsertTextForGuessedValue(value: any, separatorAfter: string): string {
		switch (typeof value) {
			case 'object':
				Iif (value === null) {
					return '${1:null}' + separatorAfter;
				}
				return this.getInsertTextForValue(value, separatorAfter);
			case 'string':
				let snippetValue = JSON.stringify(value);
				snippetValue = snippetValue.substr(1, snippetValue.length - 2); // remove quotes
				snippetValue = this.getInsertTextForPlainText(snippetValue); // escape \ and }
				return '"${1:' + snippetValue + '}"' + separatorAfter;
			case 'number':
			case 'boolean':
				return '${1:' + JSON.stringify(value) + '}' + separatorAfter;
		}
		return this.getInsertTextForValue(value, separatorAfter);
	}
 
	private getSuggestionKind(type: any): CompletionItemKind {
		if (Array.isArray(type)) {
			const array = <any[]>type;
			type = array.length > 0 ? array[0] : undefined;
		}
		if (!type) {
			return CompletionItemKind.Value;
		}
		switch (type) {
			case 'string': return CompletionItemKind.Value;
			case 'object': return CompletionItemKind.Module;
			case 'property': return CompletionItemKind.Property;
			default: return CompletionItemKind.Value;
		}
	}
 
	private getLabelTextForMatchingNode(node: ASTNode, document: TextDocument): string {
		switch (node.type) {
			case 'array':
				return '[]';
			case 'object':
				return '{}';
			default:
				const content = document.getText().substr(node.offset, node.length);
				return content;
		}
	}
 
	private getInsertTextForMatchingNode(node: ASTNode, document: TextDocument, separatorAfter: string): string {
		switch (node.type) {
			case 'array':
				return this.getInsertTextForValue([], separatorAfter);
			case 'object':
				return this.getInsertTextForValue({}, separatorAfter);
			default:
				const content = document.getText().substr(node.offset, node.length) + separatorAfter;
				return this.getInsertTextForPlainText(content);
		}
	}
 
	private getInsertTextForProperty(key: string, propertySchema: JSONSchema | undefined, addValue: boolean, separatorAfter: string): string {
 
		const propertyText = this.getInsertTextForValue(key, '');
		Iif (!addValue) {
			return propertyText;
		}
		const resultText = propertyText + ': ';
 
		let value;
		let nValueProposals = 0;
		if (propertySchema) {
			if (Array.isArray(propertySchema.defaultSnippets)) {
				if (propertySchema.defaultSnippets.length === 1) {
					const body = propertySchema.defaultSnippets[0].body;
					Eif (isDefined(body)) {
						value = this.getInsertTextForSnippetValue(body, '');
					}
				}
				nValueProposals += propertySchema.defaultSnippets.length;
			}
			if (propertySchema.enum) {
				if (!value && propertySchema.enum.length === 1) {
					value = this.getInsertTextForGuessedValue(propertySchema.enum[0], '');
				}
				nValueProposals += propertySchema.enum.length;
			}
			if (isDefined(propertySchema.default)) {
				if (!value) {
					value = this.getInsertTextForGuessedValue(propertySchema.default, '');
				}
				nValueProposals++;
			}
			Iif (Array.isArray(propertySchema.examples) && propertySchema.examples.length) {
				if (!value) {
					value = this.getInsertTextForGuessedValue(propertySchema.examples[0], '');
				}
				nValueProposals += propertySchema.examples.length;
			}
			if (nValueProposals === 0) {
				var type = Array.isArray(propertySchema.type) ? propertySchema.type[0] : propertySchema.type;
				if (!type) {
					Iif (propertySchema.properties) {
						type = 'object';
					} else Iif (propertySchema.items) {
						type = 'array';
					}
				}
				switch (type) {
					case 'boolean':
						value = '$1';
						break;
					case 'string':
						value = '"$1"';
						break;
					case 'object':
						value = '{$1}';
						break;
					case 'array':
						value = '[$1]';
						break;
					case 'number':
					case 'integer':
						value = '${1:0}';
						break;
					case 'null':
						value = '${1:null}';
						break;
					default:
						return propertyText;
				}
			}
		}
		if (!value || nValueProposals > 1) {
			value = '$1';
		}
		return resultText + value + separatorAfter;
	}
 
	private getCurrentWord(document: TextDocument, offset: number) {
		var i = offset - 1;
		var text = document.getText();
		while (i >= 0 && ' \t\n\r\v":{[,]}'.indexOf(text.charAt(i)) === -1) {
			i--;
		}
		return text.substring(i + 1, offset);
	}
 
	private evaluateSeparatorAfter(document: TextDocument, offset: number) {
		const scanner = Json.createScanner(document.getText(), true);
		scanner.setPosition(offset);
		const token = scanner.scan();
		switch (token) {
			case Json.SyntaxKind.CommaToken:
			case Json.SyntaxKind.CloseBraceToken:
			case Json.SyntaxKind.CloseBracketToken:
			case Json.SyntaxKind.EOF:
				return '';
			default:
				return ',';
		}
	}
 
	private findItemAtOffset(node: ArrayASTNode, document: TextDocument, offset: number) {
		const scanner = Json.createScanner(document.getText(), true);
		const children = node.items;
		for (let i = children.length - 1; i >= 0; i--) {
			const child = children[i];
			if (offset > child.offset + child.length) {
				scanner.setPosition(child.offset + child.length);
				const token = scanner.scan();
				Eif (token === Json.SyntaxKind.CommaToken && offset >= scanner.getTokenOffset() + scanner.getTokenLength()) {
					return i + 1;
				}
				return i;
			} else if (offset >= child.offset) {
				return i;
			}
		}
		return 0;
	}
 
	private isInComment(document: TextDocument, start: number, offset: number) {
		const scanner = Json.createScanner(document.getText(), false);
		scanner.setPosition(start);
		let token = scanner.scan();
		while (token !== Json.SyntaxKind.EOF && (scanner.getTokenOffset() + scanner.getTokenLength() < offset)) {
			token = scanner.scan();
		}
		return (token === Json.SyntaxKind.LineCommentTrivia || token === Json.SyntaxKind.BlockCommentTrivia) && scanner.getTokenOffset() <= offset;
	}
 
	private fromMarkup(markupString: string | undefined): MarkupContent | string | undefined {
		if (markupString && this.doesSupportMarkdown()) {
			return {
				kind: MarkupKind.Markdown,
				value: markupString
			};
		}
		return undefined;
	}
 
	private doesSupportMarkdown() {
		if (!isDefined(this.supportsMarkdown)) {
			const completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
			this.supportsMarkdown = completion && completion.completionItem && Array.isArray(completion.completionItem.documentationFormat) && completion.completionItem.documentationFormat.indexOf(MarkupKind.Markdown) !== -1;
		}
		return this.supportsMarkdown;
	}
 
	private doesSupportsCommitCharacters() {
		if (!isDefined(this.supportsCommitCharacters)) {
			const completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
			this.supportsCommitCharacters = completion && completion.completionItem && !!completion.completionItem.commitCharactersSupport;
		}
		return this.supportsCommitCharacters;
	}
 
}