jsonCompletion.ts 16.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';


import URI from './utils/uri';
import Parser = require('./jsonParser');
import SchemaService = require('./jsonSchemaService');
import JsonSchema = require('./json-toolbox/jsonSchema');
import nls = require('./utils/nls');
13
import {IJSONWorkerContribution} from './jsonContributions';
14

15
import {CompletionItem, CompletionItemKind, CompletionList, CompletionOptions, ITextDocument, TextDocumentIdentifier, TextDocumentPosition, Range, TextEdit} from 'vscode-languageserver';
16 17 18

export interface ISuggestionsCollector {
	add(suggestion: CompletionItem): void;
19 20
	error(message:string): void;
	setAsIncomplete(): void;
21 22 23 24 25
}

export class JSONCompletion {

	private schemaService: SchemaService.IJSONSchemaService;
26
	private contributions: IJSONWorkerContribution[];
27

28
	constructor(schemaService: SchemaService.IJSONSchemaService, contributions: IJSONWorkerContribution[] = []) {
29
		this.schemaService = schemaService;
30
		this.contributions = contributions;
31 32
	}

33
	public doSuggest(document: ITextDocument, textDocumentPosition: TextDocumentPosition, doc: Parser.JSONDocument): Thenable<CompletionList> {
34

35 36
		let offset = document.offsetAt(textDocumentPosition.position);
		let node = doc.getNodeFromOffsetEndInclusive(offset);
37

38
		let currentWord = this.getCurrentWord(document, offset);
39
		let overwriteRange = null;
40 41 42 43
		let result: CompletionList = {
			items: [],
			isIncomplete: false
		}
44 45

		if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
46
			overwriteRange = Range.create(document.positionAt(node.start), document.positionAt(node.end));
47 48
		} else {
			overwriteRange = Range.create(document.positionAt(offset - currentWord.length), textDocumentPosition.position);
49 50
		}

51 52
		let proposed: { [key: string]: boolean } = {};
		let collector: ISuggestionsCollector = {
53 54 55 56 57 58
			add: (suggestion: CompletionItem) => {
				if (!proposed[suggestion.label]) {
					proposed[suggestion.label] = true;
					if (overwriteRange) {
						suggestion.textEdit = TextEdit.replace(overwriteRange, suggestion.insertText);
					}
59

60
					result.items.push(suggestion);
61
				}
62 63
			},
			setAsIncomplete: () => {
64
				result.isIncomplete = true;
65 66 67 68 69 70 71
			},
			error: (message: string) => {
				console.log(message);
			}
		};

		return this.schemaService.getSchemaForResource(textDocumentPosition.uri, doc).then((schema) => {
72
			let collectionPromises: Thenable<any>[] = [];
73

74 75
			let addValue = true;
			let currentKey = '';
76
			
77
			let currentProperty: Parser.PropertyASTNode = null;
78 79 80
			if (node) {

				if (node.type === 'string') {
81
					let stringNode = <Parser.StringASTNode>node;
82 83 84
					if (stringNode.isKey) {
						addValue = !(node.parent && ((<Parser.PropertyASTNode>node.parent).value));
						currentProperty = node.parent ? <Parser.PropertyASTNode>node.parent : null;
85
						currentKey = document.getText().substring(node.start + 1, node.end - 1);
86 87 88 89 90 91 92 93 94 95 96 97 98 99
						if (node.parent) {
							node = 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
				if (node.start === offset) {
					return result;
				}
				// don't suggest properties that are already present
100
				let properties = (<Parser.ObjectASTNode>node).properties;
101 102 103 104 105
				properties.forEach(p => {
					if (!currentProperty || currentProperty !== p) {
						proposed[p.key.value] = true;
					}
				});
106

107
				let isLast = properties.length === 0 || offset >= properties[properties.length - 1].start;
108 109
				if (schema) {
					// property proposals with schema
110 111
					this.getPropertySuggestions(schema, doc, node, addValue, isLast, collector);
				} else {
112
					// property proposals without schema
113
					this.getSchemaLessPropertySuggestions(doc, node, currentKey, currentWord, isLast, collector);
114
				}
115

116 117
				let location = node.getNodeLocation();
				this.contributions.forEach((contribution) => {
118
					let collectPromise = contribution.collectPropertySuggestions(textDocumentPosition.uri, location, currentWord, addValue, isLast, collector);
119 120 121 122
					if (collectPromise) {
						collectionPromises.push(collectPromise);
					}
				});
123 124 125 126 127 128 129 130 131 132 133 134 135 136

			}

			// proposals for values
			if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
				node = node.parent;
			}

			if (schema) {
				// value proposals with schema
				this.getValueSuggestions(schema, doc, node, offset, collector);
			} else {
				// value proposals without schema
				this.getSchemaLessValueSuggestions(doc, node, offset, document, collector);
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
			if (!node) {
				this.contributions.forEach((contribution) => {
					let collectPromise = contribution.collectDefaultSuggestions(textDocumentPosition.uri, collector);
					if (collectPromise) {
						collectionPromises.push(collectPromise);
					}
				});
			} else {
				if ((node.type === 'property') && offset > (<Parser.PropertyASTNode> node).colonOffset) {
					let parentKey = (<Parser.PropertyASTNode>node).key.value;

					let valueNode = (<Parser.PropertyASTNode> node).value;
					if (!valueNode || offset <= valueNode.end) {
						let location = node.parent.getNodeLocation();
						this.contributions.forEach((contribution) => {
							let collectPromise = contribution.collectValueSuggestions(textDocumentPosition.uri, location, parentKey, collector);
							if (collectPromise) {
								collectionPromises.push(collectPromise);
							}
						});
					}
				}
			}
			return Promise.all(collectionPromises).then(() => result );
163 164 165
		});
	}

166
	private getPropertySuggestions(schema: SchemaService.ResolvedSchema, doc: Parser.JSONDocument, node: Parser.ASTNode, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector): void {
167
		let matchingSchemas: Parser.IApplicableSchema[] = [];
168 169 170 171
		doc.validate(schema.schema, matchingSchemas, node.start);

		matchingSchemas.forEach((s) => {
			if (s.node === node && !s.inverted) {
172
				let schemaProperties = s.schema.properties;
173 174
				if (schemaProperties) {
					Object.keys(schemaProperties).forEach((key: string) => {
175
						let propertySchema = schemaProperties[key];
176 177 178 179 180 181 182
						collector.add({ kind: CompletionItemKind.Property, label: key, insertText: this.getSnippetForProperty(key, propertySchema, addValue, isLast), documentation: propertySchema.description || '' });
					});
				}
			}
		});
	}

183
	private getSchemaLessPropertySuggestions(doc: Parser.JSONDocument, node: Parser.ASTNode, currentKey: string, currentWord: string, isLast: boolean, collector: ISuggestionsCollector): void {
184
		let collectSuggestionsForSimilarObject = (obj: Parser.ObjectASTNode) => {
185
			obj.properties.forEach((p) => {
186
				let key = p.key.value;
187 188 189
				collector.add({ kind: CompletionItemKind.Property, label: key, insertText: this.getSnippetForSimilarProperty(key, p.value), documentation: '' });
			});
		};
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
		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
				let parentKey = (<Parser.PropertyASTNode>node.parent).key.value;
				doc.visit((n) => {
					if (n.type === 'property' && (<Parser.PropertyASTNode>n).key.value === parentKey && (<Parser.PropertyASTNode>n).value && (<Parser.PropertyASTNode>n).value.type === 'object') {
						collectSuggestionsForSimilarObject(<Parser.ObjectASTNode>(<Parser.PropertyASTNode>n).value);
					}
					return true;
				});
			} else if (node.parent.type === 'array') {
				// if the object is in an array, use all other array elements as similar objects
				(<Parser.ArrayASTNode>node.parent).items.forEach((n) => {
					if (n.type === 'object' && n !== node) {
						collectSuggestionsForSimilarObject(<Parser.ObjectASTNode>n);
					}
				});
			}
		}
		if (!currentKey && currentWord.length > 0) {
			collector.add({ kind: CompletionItemKind.Property, label: JSON.stringify(currentWord), insertText: this.getSnippetForProperty(currentWord, null, true, isLast), documentation: '' });
211 212 213 214
		}
	}

	private getSchemaLessValueSuggestions(doc: Parser.JSONDocument, node: Parser.ASTNode, offset: number, document: ITextDocument, collector: ISuggestionsCollector): void {
215
		let collectSuggestionsForValues = (value: Parser.ASTNode) => {
216 217 218 219
			if (!value.contains(offset)) {
				let content = this.getMatchingSnippet(value, document);
				collector.add({ kind: this.getSuggestionKind(value.type), label: content, insertText: content, documentation: '' });
			}
220 221 222 223 224 225 226 227 228 229
			if (value.type === 'boolean') {
				this.addBooleanSuggestion(!value.getValue(), collector);
			}
		};

		if (!node) {
			collector.add({ kind: this.getSuggestionKind('object'), label: 'Empty object', insertText: '{\n\t{{}}\n}', documentation: '' });
			collector.add({ kind: this.getSuggestionKind('array'), label: 'Empty array', insertText: '[\n\t{{}}\n]', documentation: '' });
		} else {
			if (node.type === 'property' && offset > (<Parser.PropertyASTNode>node).colonOffset) {
230
				let valueNode = (<Parser.PropertyASTNode>node).value;
231 232 233 234
				if (valueNode && offset > valueNode.end) {
					return;
				}
				// suggest values at the same key
235
				let parentKey = (<Parser.PropertyASTNode>node).key.value;
236 237 238 239 240 241 242 243 244 245
				doc.visit((n) => {
					if (n.type === 'property' && (<Parser.PropertyASTNode>n).key.value === parentKey && (<Parser.PropertyASTNode>n).value) {
						collectSuggestionsForValues((<Parser.PropertyASTNode>n).value);
					}
					return true;
				});
			}
			if (node.type === 'array') {
				if (node.parent && node.parent.type === 'property') {
					// suggest items of an array at the same key
246
					let parentKey = (<Parser.PropertyASTNode>node.parent).key.value;
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
					doc.visit((n) => {
						if (n.type === 'property' && (<Parser.PropertyASTNode>n).key.value === parentKey && (<Parser.PropertyASTNode>n).value && (<Parser.PropertyASTNode>n).value.type === 'array') {
							((<Parser.ArrayASTNode>(<Parser.PropertyASTNode>n).value).items).forEach((n) => {
								collectSuggestionsForValues(<Parser.ObjectASTNode>n);
							});
						}
						return true;
					});
				} else {
					// suggest items in the same array
					(<Parser.ArrayASTNode>node).items.forEach((n) => {
						collectSuggestionsForValues(<Parser.ObjectASTNode>n);
					});
				}
			}
		}
	}


	private getValueSuggestions(schema: SchemaService.ResolvedSchema, doc: Parser.JSONDocument, node: Parser.ASTNode, offset: number, collector: ISuggestionsCollector): void {

		if (!node) {
			this.addDefaultSuggestion(schema.schema, collector);
		} else {
271
			let parentKey: string = null;
272
			if (node && (node.type === 'property') && offset > (<Parser.PropertyASTNode>node).colonOffset) {
273
				let valueNode = (<Parser.PropertyASTNode>node).value;
274 275 276 277 278 279 280
				if (valueNode && offset > valueNode.end) {
					return; // we are past the value node
				}
				parentKey = (<Parser.PropertyASTNode>node).key.value;
				node = node.parent;
			}
			if (node && (parentKey !== null || node.type === 'array')) {
281
				let matchingSchemas: Parser.IApplicableSchema[] = [];
282 283 284 285 286 287 288 289 290
				doc.validate(schema.schema, matchingSchemas, node.start);

				matchingSchemas.forEach((s) => {
					if (s.node === node && !s.inverted && s.schema) {
						if (s.schema.items) {
							this.addDefaultSuggestion(s.schema.items, collector);
							this.addEnumSuggestion(s.schema.items, collector);
						}
						if (s.schema.properties) {
291
							let propertySchema = s.schema.properties[parentKey];
292 293 294 295 296 297 298 299 300 301 302 303 304
							if (propertySchema) {
								this.addDefaultSuggestion(propertySchema, collector);
								this.addEnumSuggestion(propertySchema, collector);
							}
						}
					}
				});

			}
		}
	}

	private addBooleanSuggestion(value: boolean, collector: ISuggestionsCollector): void {
305
		collector.add({ kind: this.getSuggestionKind('boolean'), label: value ? 'true' : 'false', insertText: this.getTextForValue(value), documentation: '' });
306 307 308 309
	}

	private addEnumSuggestion(schema: JsonSchema.IJSONSchema, collector: ISuggestionsCollector): void {
		if (Array.isArray(schema.enum)) {
310
			schema.enum.forEach((enm) => collector.add({ kind: this.getSuggestionKind(schema.type), label: this.getLabelForValue(enm), insertText: this.getTextForValue(enm), documentation: '' }));
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
		} else if (schema.type === 'boolean') {
			this.addBooleanSuggestion(true, collector);
			this.addBooleanSuggestion(false, collector);
		}
		if (Array.isArray(schema.allOf)) {
			schema.allOf.forEach((s) => this.addEnumSuggestion(s, collector));
		}
		if (Array.isArray(schema.anyOf)) {
			schema.anyOf.forEach((s) => this.addEnumSuggestion(s, collector));
		}
		if (Array.isArray(schema.oneOf)) {
			schema.oneOf.forEach((s) => this.addEnumSuggestion(s, collector));
		}
	}

	private addDefaultSuggestion(schema: JsonSchema.IJSONSchema, collector: ISuggestionsCollector): void {
		if (schema.default) {
			collector.add({
				kind: this.getSuggestionKind(schema.type),
				label: this.getLabelForValue(schema.default),
331
				insertText: this.getTextForValue(schema.default),
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
				detail: nls.localize('json.suggest.default', 'Default value'),
			});
		}
		if (Array.isArray(schema.allOf)) {
			schema.allOf.forEach((s) => this.addDefaultSuggestion(s, collector));
		}
		if (Array.isArray(schema.anyOf)) {
			schema.anyOf.forEach((s) => this.addDefaultSuggestion(s, collector));
		}
		if (Array.isArray(schema.oneOf)) {
			schema.oneOf.forEach((s) => this.addDefaultSuggestion(s, collector));
		}
	}

	private getLabelForValue(value: any): string {
347
		let label = JSON.stringify(value);
348 349 350 351 352 353 354
		label = label.replace('{{', '').replace('}}', '');
		if (label.length > 57) {
			return label.substr(0, 57).trim() + '...';
		}
		return label;
	}

355 356 357 358
	private getTextForValue(value: any): string {
		return JSON.stringify(value, null, '\t');
	}

359
	private getSnippetForValue(value: any): string {
360
		let snippet = JSON.stringify(value, null, '\t');
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
		switch (typeof value) {
			case 'object':
				if (value === null) {
					return '{{null}}';
				}
				return snippet;
			case 'string':
				return '"{{' + snippet.substr(1, snippet.length - 2) + '}}"';
			case 'number':
			case 'boolean':
				return '{{' + snippet + '}}';
		}
		return snippet;
	}

	private getSuggestionKind(type: any): CompletionItemKind {
		if (Array.isArray(type)) {
378
			let array = <any[]>type;
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
			type = array.length > 0 ? array[0] : null;
		}
		if (!type) {
			return CompletionItemKind.Text;
		}
		switch (type) {
			case 'string': return CompletionItemKind.Text;
			case 'object': return CompletionItemKind.Module;
			case 'property': return CompletionItemKind.Property;
			default: return CompletionItemKind.Value
		}
	}


	private getMatchingSnippet(node: Parser.ASTNode, document: ITextDocument): string {
		switch (node.type) {
			case 'array':
				return '[]';
			case 'object':
				return '{}';
			default:
400
				let content = document.getText().substr(node.start, node.end - node.start);
401 402 403 404 405 406
				return content;
		}
	}

	private getSnippetForProperty(key: string, propertySchema: JsonSchema.IJSONSchema, addValue: boolean, isLast: boolean): string {

407
		let result = '"' + key + '"';
408 409 410 411
		if (!addValue) {
			return result;
		}
		result += ': ';
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
		
		if (propertySchema) {
			let defaultVal = propertySchema.default;
			if (typeof defaultVal !== 'undefined') {
				result = result + this.getSnippetForValue(defaultVal);
			} else if (propertySchema.enum && propertySchema.enum.length > 0) {
				result = result + this.getSnippetForValue(propertySchema.enum[0]);
			} else {
				switch (propertySchema.type) {
					case 'boolean':
						result += '{{false}}';
						break;
					case 'string':
						result += '"{{}}"';
						break;
					case 'object':
						result += '{\n\t{{}}\n}';
						break;
					case 'array':
						result += '[\n\t{{}}\n]';
						break;
					case 'number':
						result += '{{0}}';
						break;
					case 'null':
						result += '{{null}}';
						break;
					default:
						return result;
				}
442
			}
443 444
		} else {
			result += '{{0}}';
445 446 447 448 449 450 451 452 453 454
		}
		if (!isLast) {
			result += ',';
		}
		return result;
	}

	private getSnippetForSimilarProperty(key: string, templateValue: Parser.ASTNode): string {
		return '"' + key + '"';
	}
455

456 457 458 459 460 461 462 463 464
	private getCurrentWord(document: ITextDocument, 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);
	}
}