languageFeatures.ts 16.1 KB
Newer Older
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  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 {TPromise} from 'vs/base/common/winjs.base';
import URI from 'vs/base/common/uri';
J
Johannes Rieken 已提交
9
import Severity from 'vs/base/common/severity';
10
import * as lifecycle from 'vs/base/common/lifecycle';
11 12
import * as editor from 'vs/editor/common/editorCommon';
import * as modes from 'vs/editor/common/modes';
J
Johannes Rieken 已提交
13 14
import matches from 'vs/editor/common/modes/languageSelector';
import {IMarkerService, IMarkerData} from 'vs/platform/markers/common/markers';
15 16
import {IModelService} from 'vs/editor/common/services/modelService';
import {SuggestRegistry} from 'vs/editor/contrib/suggest/common/suggest';
J
Johannes Rieken 已提交
17
import {ParameterHintsRegistry} from 'vs/editor/contrib/parameterHints/common/parameterHints';
18 19
import {OccurrencesRegistry} from 'vs/editor/contrib/wordHighlighter/common/wordHighlighter';
import {ExtraInfoRegistry} from 'vs/editor/contrib/hover/common/hover';
J
Johannes Rieken 已提交
20 21
import {ReferenceRegistry} from 'vs/editor/contrib/referenceSearch/common/referenceSearch';
import {DeclarationRegistry} from 'vs/editor/contrib/goToDeclaration/common/goToDeclaration';
22 23
import {OutlineRegistry} from 'vs/editor/contrib/quickOpen/common/quickOpen';
import {FormatRegistry, FormatOnTypeRegistry} from 'vs/editor/contrib/format/common/format';
24 25
import {TypeScriptWorkerProtocol, LanguageServiceDefaults} from 'vs/languages/typescript/common/typescript';
import * as ts from 'vs/languages/typescript/common/lib/typescriptServices';
26

J
Johannes Rieken 已提交
27
export function register(modelService: IModelService, markerService: IMarkerService,
28
	selector: string, defaults:LanguageServiceDefaults, worker: (first: URI, ...more: URI[]) => TPromise<TypeScriptWorkerProtocol>): lifecycle.IDisposable {
J
Johannes Rieken 已提交
29

30 31
	const disposables: lifecycle.IDisposable[] = [];
	disposables.push(SuggestRegistry.register(selector, new SuggestAdapter(modelService, worker)));
J
Johannes Rieken 已提交
32
	disposables.push(ParameterHintsRegistry.register(selector, new ParameterHintsAdapter(modelService, worker)));
33 34
	disposables.push(ExtraInfoRegistry.register(selector, new QuickInfoAdapter(modelService, worker)));
	disposables.push(OccurrencesRegistry.register(selector, new OccurrencesAdapter(modelService, worker)));
J
Johannes Rieken 已提交
35 36
	disposables.push(DeclarationRegistry.register(selector, new DeclarationAdapter(modelService, worker)));
	disposables.push(ReferenceRegistry.register(selector, new ReferenceAdapter(modelService, worker)));
37 38 39
	disposables.push(OutlineRegistry.register(selector, new OutlineAdapter(modelService, worker)));
	disposables.push(FormatRegistry.register(selector, new FormatAdapter(modelService, worker)));
	disposables.push(FormatOnTypeRegistry.register(selector, new FormatAdapter(modelService, worker)));
40
	disposables.push(new DiagnostcsAdapter(defaults, selector, markerService, modelService, worker));
J
Johannes Rieken 已提交
41

J
Johannes Rieken 已提交
42
	return lifecycle.combinedDisposable(disposables);
43 44 45 46
}

abstract class Adapter {

47
	constructor(protected _modelService: IModelService, protected _worker: (first:URI, ...more:URI[]) => TPromise<TypeScriptWorkerProtocol>) {
48 49 50 51 52 53 54

	}

	protected _positionToOffset(resource: URI, position: editor.IPosition): number {
		const model = this._modelService.getModel(resource);
		let result = position.column - 1;
		for (let i = 1; i < position.lineNumber; i++) {
55
			result += model.getLineContent(i).length + model.getEOL().length;
56 57 58 59 60 61 62
		}
		return result;
	}

	protected _offsetToPosition(resource: URI, offset: number): editor.IPosition {
		const model = this._modelService.getModel(resource);
		let lineNumber = 1;
63 64 65 66 67 68 69
		while (true) {
			let len = model.getLineContent(lineNumber).length + model.getEOL().length;
			if (offset < len) {
				break;
			}
			offset -= len;
			lineNumber++;
70
		}
71
		return { lineNumber, column: 1 + offset };
72 73 74 75 76 77 78 79 80 81 82
	}

	protected _textSpanToRange(resource: URI, span: ts.TextSpan): editor.IRange {
		let p1 = this._offsetToPosition(resource, span.start);
		let p2 = this._offsetToPosition(resource, span.start + span.length);
		let {lineNumber: startLineNumber, column: startColumn} = p1;
		let {lineNumber: endLineNumber, column: endColumn} = p2;
		return { startLineNumber, startColumn, endLineNumber, endColumn };
	}
}

J
Johannes Rieken 已提交
83 84 85 86 87 88 89
// --- diagnostics --- ---

class DiagnostcsAdapter extends Adapter {

	private _disposables: lifecycle.IDisposable[] = [];
	private _listener: { [uri: string]: lifecycle.IDisposable } = Object.create(null);

90 91
	constructor(private _defaults: LanguageServiceDefaults, private _selector: string,
		private _markerService: IMarkerService, modelService: IModelService,
92 93
		worker: (first: URI, ...more: URI[]) => TPromise<TypeScriptWorkerProtocol>
	) {
J
Johannes Rieken 已提交
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
		super(modelService, worker);

		const onModelAdd = (model: editor.IModel): void => {
			if (!matches(_selector, model.getAssociatedResource(), model.getModeId())) {
				return;
			}

			let handle: number;
			this._listener[model.getAssociatedResource().toString()] = model.addListener2(editor.EventType.ModelContentChanged2, () => {
				clearTimeout(handle);
				handle = setTimeout(() => this._doValidate(model.getAssociatedResource()), 500);
			});

			this._doValidate(model.getAssociatedResource());
		};

		const onModelRemoved = (model: editor.IModel): void => {
			delete this._listener[model.getAssociatedResource().toString()];
		};

		this._disposables.push(modelService.onModelAdded(onModelAdd));
		this._disposables.push(modelService.onModelRemoved(onModelRemoved));
		this._disposables.push(modelService.onModelModeChanged(event => {
			onModelRemoved(event.model);
			onModelAdd(event.model);
		}));

		this._disposables.push({
			dispose: () => {
				for (let key in this._listener) {
					this._listener[key].dispose();
				}
			}
		});

		modelService.getModels().forEach(onModelAdd);
	}

	public dispose(): void {
J
Johannes Rieken 已提交
133
		this._disposables = lifecycle.dispose(this._disposables);
J
Johannes Rieken 已提交
134 135 136
	}

	private _doValidate(resource: URI): void {
137 138 139 140 141 142 143 144 145 146 147 148 149
		this._worker(resource).then(worker => {
			let promises: TPromise<ts.Diagnostic[]>[] = [];
			if (!this._defaults.diagnosticsOptions.noSyntaxValidation) {
				promises.push(worker.getSyntacticDiagnostics(resource.toString()));
			}
			if (!this._defaults.diagnosticsOptions.noSemanticValidation) {
				promises.push(worker.getSemanticDiagnostics(resource.toString()));
			}
			return TPromise.join(promises);
		}).then(diagnostics => {
			const markers = diagnostics
				.reduce((p, c) => c.concat(p), [])
				.map(d => this._convertDiagnostics(resource, d));
J
Johannes Rieken 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
			this._markerService.changeOne(this._selector, resource, markers);
		}).done(undefined, err => {
			console.error(err);
		});
	}

	private _convertDiagnostics(resource: URI, diag: ts.Diagnostic): IMarkerData {
		const {lineNumber: startLineNumber, column: startColumn} = this._offsetToPosition(resource, diag.start);
		const {lineNumber: endLineNumber, column: endColumn} = this._offsetToPosition(resource, diag.start + diag.length);

		return {
			severity: Severity.Error,
			startLineNumber,
			startColumn,
			endLineNumber,
			endColumn,
			message: ts.flattenDiagnosticMessageText(diag.messageText, '\n')
		};
	}
}

171 172 173 174 175 176 177 178 179 180
// --- suggest ------

class SuggestAdapter extends Adapter implements modes.ISuggestSupport {

	suggest(resource: URI, position: editor.IPosition, triggerCharacter?: string) {

		const model = this._modelService.getModel(resource);
		const wordInfo = model.getWordUntilPosition(position);
		const offset = this._positionToOffset(resource, position);

J
Johannes Rieken 已提交
181
		return this._worker(resource).then(worker => {
182 183
			return worker.getCompletionsAtPosition(resource.toString(), offset);
		}).then(info => {
J
Johannes Rieken 已提交
184 185 186
			if (!info) {
				return;
			}
187 188 189 190
			let suggestions = info.entries.map(entry => {
				return <modes.ISuggestion>{
					label: entry.name,
					codeSnippet: entry.name,
J
Johannes Rieken 已提交
191
					type: entry.kind
192 193 194 195 196 197 198 199 200 201 202 203
				};
			});

			return [{
				currentWord: wordInfo && wordInfo.word,
				suggestions
			}];
		});
	}

	getSuggestionDetails(resource: URI, position: editor.IPosition, suggestion: modes.ISuggestion) {

J
Johannes Rieken 已提交
204
		return this._worker(resource).then(worker => {
205 206 207
			return worker.getCompletionEntryDetails(resource.toString(),
				this._positionToOffset(resource, position),
				suggestion.label);
J
Johannes Rieken 已提交
208

209
		}).then(details => {
J
Johannes Rieken 已提交
210 211 212
			if (!details) {
				return suggestion;
			}
213 214 215
			return <modes.ISuggestion>{
				label: details.name,
				codeSnippet: details.name,
J
Johannes Rieken 已提交
216 217 218
				type: details.kind,
				typeLabel: ts.displayPartsToString(details.displayParts),
				documentationLabel: ts.displayPartsToString(details.documentation)
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
			};
		});
	}

	getFilter(): modes.ISuggestionFilter {
		return;
	}

	getTriggerCharacters(): string[] {
		return ['.'];
	}

	shouldShowEmptySuggestionList(): boolean {
		return true;
	}

	shouldAutotriggerSuggest(context: modes.ILineContext, offset: number, triggeredByCharacter: string): boolean {
		return true;
	}
}

J
Johannes Rieken 已提交
240
class ParameterHintsAdapter extends Adapter implements modes.IParameterHintsSupport {
241

J
Johannes Rieken 已提交
242 243 244
	getParameterHintsTriggerCharacters(): string[] {
		return ['(', ','];
	}
245

J
Johannes Rieken 已提交
246 247 248
	shouldTriggerParameterHints(context: modes.ILineContext, offset: number): boolean {
		return true;
	}
249

J
Johannes Rieken 已提交
250
	getParameterHints(resource: URI, position: editor.IPosition, triggerCharacter?: string): TPromise<modes.IParameterHints> {
J
Johannes Rieken 已提交
251
		return this._worker(resource).then(worker => worker.getSignatureHelpItems(resource.toString(), this._positionToOffset(resource, position))).then(info => {
J
Johannes Rieken 已提交
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

			if (!info) {
				return;
			}

			let ret = <modes.IParameterHints>{
				currentSignature: info.selectedItemIndex,
				currentParameter: info.argumentIndex,
				signatures: []
			};

			info.items.forEach(item => {

				let signature = <modes.ISignature>{
					label: '',
					documentation: null,
					parameters: []
				};

				signature.label += ts.displayPartsToString(item.prefixDisplayParts);
				item.parameters.forEach((p, i, a) => {
					let label = ts.displayPartsToString(p.displayParts);
					let parameter = <modes.IParameter>{
						label: label,
						documentation: ts.displayPartsToString(p.documentation),
						signatureLabelOffset: signature.label.length,
						signatureLabelEnd: signature.label.length + label.length
					};
					signature.label += label;
					signature.parameters.push(parameter);
					if (i < a.length - 1) {
						signature.label += ts.displayPartsToString(item.separatorDisplayParts);
					}
				});
				signature.label += ts.displayPartsToString(item.suffixDisplayParts);
				ret.signatures.push(signature);
			});

			return ret;

		});
	}
}

296 297 298 299 300
// --- hover ------

class QuickInfoAdapter extends Adapter implements modes.IExtraInfoSupport {

	computeInfo(resource: URI, position: editor.IPosition): TPromise<modes.IComputeExtraInfoResult> {
J
Johannes Rieken 已提交
301
		return this._worker(resource).then(worker => {
302 303
			return worker.getQuickInfoAtPosition(resource.toString(), this._positionToOffset(resource, position));
		}).then(info => {
304 305 306
			if (!info) {
				return;
			}
307 308 309 310 311 312 313 314 315 316 317 318
			return <modes.IComputeExtraInfoResult>{
				range: this._textSpanToRange(resource, info.textSpan),
				value: ts.displayPartsToString(info.displayParts)
			};
		});
	}
}

// --- occurrences ------

class OccurrencesAdapter extends Adapter implements modes.IOccurrencesSupport {

J
Johannes Rieken 已提交
319
	findOccurrences(resource: URI, position: editor.IPosition, strict?: boolean): TPromise<modes.IOccurence[]> {
J
Johannes Rieken 已提交
320
		return this._worker(resource).then(worker => {
321 322
			return worker.getOccurrencesAtPosition(resource.toString(), this._positionToOffset(resource, position));
		}).then(entries => {
323 324 325
			if (!entries) {
				return;
			}
326 327 328 329 330 331 332 333 334 335
			return entries.map(entry => {
				return <modes.IOccurence>{
					range: this._textSpanToRange(resource, entry.textSpan),
					kind: entry.isWriteAccess ? 'write' : 'text'
				};
			});
		});
	}
}

J
Johannes Rieken 已提交
336 337 338 339
// --- definition ------

class DeclarationAdapter extends Adapter implements modes.IDeclarationSupport {

J
Johannes Rieken 已提交
340
	canFindDeclaration(context: modes.ILineContext, offset: number): boolean {
J
Johannes Rieken 已提交
341 342 343 344
		return true;
	}

	findDeclaration(resource: URI, position: editor.IPosition): TPromise<modes.IReference[]> {
J
Johannes Rieken 已提交
345
		return this._worker(resource).then(worker => {
J
Johannes Rieken 已提交
346 347
			return worker.getDefinitionAtPosition(resource.toString(), this._positionToOffset(resource, position));
		}).then(entries => {
348 349 350
			if (!entries) {
				return;
			}
J
Johannes Rieken 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
			const result: modes.IReference[] = [];
			for (let entry of entries) {
				const uri = URI.parse(entry.fileName);
				if (this._modelService.getModel(uri)) {
					result.push({
						resource: uri,
						range: this._textSpanToRange(uri, entry.textSpan)
					});
				}
			}
			return result;
		});
	}
}

// --- references ------

class ReferenceAdapter extends Adapter implements modes.IReferenceSupport {

	canFindReferences(context: modes.ILineContext, offset: number): boolean {
		return true;
	}

J
Johannes Rieken 已提交
374
	findReferences(resource: URI, position: editor.IPosition, includeDeclaration: boolean): TPromise<modes.IReference[]> {
J
Johannes Rieken 已提交
375
		return this._worker(resource).then(worker => {
J
Johannes Rieken 已提交
376 377
			return worker.getReferencesAtPosition(resource.toString(), this._positionToOffset(resource, position));
		}).then(entries => {
378 379 380
			if (!entries) {
				return;
			}
J
Johannes Rieken 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394
			const result: modes.IReference[] = [];
			for (let entry of entries) {
				const uri = URI.parse(entry.fileName);
				if (this._modelService.getModel(uri)) {
					result.push({
						resource: uri,
						range: this._textSpanToRange(uri, entry.textSpan)
					});
				}
			}
			return result;
		});
	}
}
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

// --- outline ------

class OutlineAdapter extends Adapter implements modes.IOutlineSupport {

	getOutline(resource: URI): TPromise<modes.IOutlineEntry[]> {
		return this._worker(resource).then(worker => worker.getNavigationBarItems(resource.toString())).then(items => {
			if (!items) {
				return;
			}

			const convert = (item: ts.NavigationBarItem): modes.IOutlineEntry => {
				return {
					label: item.text,
					type: item.kind,
					range: this._textSpanToRange(resource, item.spans[0]),
					children: item.childItems && item.childItems.map(convert)
				};
			};

			return items.map(convert);
		});
	}
}

// --- formatting ----

class FormatAdapter extends Adapter implements modes.IFormattingSupport {

	formatRange(resource: URI, range: editor.IRange, options: modes.IFormattingOptions): TPromise<editor.ISingleEditOperation[]>{
		return this._worker(resource).then(worker => {
			return worker.getFormattingEditsForRange(resource.toString(),
				this._positionToOffset(resource, { lineNumber: range.startLineNumber, column: range.startColumn }),
				this._positionToOffset(resource, { lineNumber: range.endLineNumber, column: range.endColumn }),
				FormatAdapter._convertOptions(options));
		}).then(edits => {
			if (edits) {
				return edits.map(edit => this._convertTextChanges(resource, edit));
			}
		});
	}

	get autoFormatTriggerCharacters() {
		return [';', '}', '\n'];
	}

	formatAfterKeystroke(resource: URI, position: editor.IPosition, ch: string, options: modes.IFormattingOptions): TPromise<editor.ISingleEditOperation[]> {
		return this._worker(resource).then(worker => {
			return worker.getFormattingEditsAfterKeystroke(resource.toString(),
				this._positionToOffset(resource, position),
				ch, FormatAdapter._convertOptions(options));
		}).then(edits => {
			if (edits) {
				return edits.map(edit => this._convertTextChanges(resource, edit));
			}
		});
	}

	private _convertTextChanges(resource: URI, change: ts.TextChange): editor.ISingleEditOperation {
		return <editor.ISingleEditOperation>{
			text: change.newText,
			range: this._textSpanToRange(resource, change.span)
		};
	}

	private static _convertOptions(options: modes.IFormattingOptions): ts.FormatCodeOptions {
		return {
			ConvertTabsToSpaces: options.insertSpaces,
			TabSize: options.tabSize,
			IndentSize: options.tabSize,
J
Johannes Rieken 已提交
465
			IndentStyle: ts.IndentStyle.Smart,
466 467 468 469 470
			NewLineCharacter: '\n',
			InsertSpaceAfterCommaDelimiter: true,
			InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
			InsertSpaceAfterKeywordsInControlFlowStatements: false,
			InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: true,
J
Johannes Rieken 已提交
471 472
			InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: true,
			InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: true,
473 474 475 476 477 478 479
			InsertSpaceAfterSemicolonInForStatements: false,
			InsertSpaceBeforeAndAfterBinaryOperators: true,
			PlaceOpenBraceOnNewLineForControlBlocks: false,
			PlaceOpenBraceOnNewLineForFunctions: false
		};
	}
}