languageFeatures.ts 15.7 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
import {IModelService} from 'vs/editor/common/services/modelService';
16 17
import {TypeScriptWorkerProtocol, LanguageServiceDefaults} from 'vs/languages/typescript/common/typescript';
import * as ts from 'vs/languages/typescript/common/lib/typescriptServices';
18
import {CancellationToken} from 'vs/base/common/cancellation';
19

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

23
	const disposables: lifecycle.IDisposable[] = [];
24
	disposables.push(modes.SuggestRegistry.register(selector, new SuggestAdapter(modelService, worker)));
A
Alex Dima 已提交
25
	disposables.push(modes.SignatureHelpProviderRegistry.register(selector, new SignatureHelpAdapter(modelService, worker)));
A
Alex Dima 已提交
26
	disposables.push(modes.HoverProviderRegistry.register(selector, new QuickInfoAdapter(modelService, worker)));
27 28
	disposables.push(modes.OccurrencesRegistry.register(selector, new OccurrencesAdapter(modelService, worker)));
	disposables.push(modes.DeclarationRegistry.register(selector, new DeclarationAdapter(modelService, worker)));
29
	disposables.push(modes.ReferenceSearchRegistry.register(selector, new ReferenceAdapter(modelService, worker)));
30 31 32
	disposables.push(modes.OutlineRegistry.register(selector, new OutlineAdapter(modelService, worker)));
	disposables.push(modes.FormatRegistry.register(selector, new FormatAdapter(modelService, worker)));
	disposables.push(modes.FormatOnTypeRegistry.register(selector, new FormatAdapter(modelService, worker)));
33
	disposables.push(new DiagnostcsAdapter(defaults, selector, markerService, modelService, worker));
J
Johannes Rieken 已提交
34

J
Johannes Rieken 已提交
35
	return lifecycle.combinedDisposable(disposables);
36 37 38 39
}

abstract class Adapter {

40
	constructor(protected _modelService: IModelService, protected _worker: (first:URI, ...more:URI[]) => TPromise<TypeScriptWorkerProtocol>) {
41 42 43 44 45 46 47

	}

	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++) {
48
			result += model.getLineContent(i).length + model.getEOL().length;
49 50 51 52 53 54 55
		}
		return result;
	}

	protected _offsetToPosition(resource: URI, offset: number): editor.IPosition {
		const model = this._modelService.getModel(resource);
		let lineNumber = 1;
56 57 58 59 60 61 62
		while (true) {
			let len = model.getLineContent(lineNumber).length + model.getEOL().length;
			if (offset < len) {
				break;
			}
			offset -= len;
			lineNumber++;
63
		}
64
		return { lineNumber, column: 1 + offset };
65 66 67 68 69 70 71 72 73 74 75
	}

	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 已提交
76 77 78 79 80 81 82
// --- diagnostics --- ---

class DiagnostcsAdapter extends Adapter {

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

83 84
	constructor(private _defaults: LanguageServiceDefaults, private _selector: string,
		private _markerService: IMarkerService, modelService: IModelService,
85 86
		worker: (first: URI, ...more: URI[]) => TPromise<TypeScriptWorkerProtocol>
	) {
J
Johannes Rieken 已提交
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
		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 已提交
126
		this._disposables = lifecycle.dispose(this._disposables);
J
Johannes Rieken 已提交
127 128 129
	}

	private _doValidate(resource: URI): void {
130 131 132 133 134 135 136 137 138 139 140 141 142
		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 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
			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')
		};
	}
}

164 165 166 167 168 169 170 171 172 173
// --- 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 已提交
174
		return this._worker(resource).then(worker => {
175 176
			return worker.getCompletionsAtPosition(resource.toString(), offset);
		}).then(info => {
J
Johannes Rieken 已提交
177 178 179
			if (!info) {
				return;
			}
180 181 182 183
			let suggestions = info.entries.map(entry => {
				return <modes.ISuggestion>{
					label: entry.name,
					codeSnippet: entry.name,
J
Johannes Rieken 已提交
184
					type: SuggestAdapter.asType(entry.kind)
185 186 187 188 189 190 191 192 193 194 195 196
				};
			});

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

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

J
Johannes Rieken 已提交
197
		return this._worker(resource).then(worker => {
198 199 200
			return worker.getCompletionEntryDetails(resource.toString(),
				this._positionToOffset(resource, position),
				suggestion.label);
J
Johannes Rieken 已提交
201

202
		}).then(details => {
J
Johannes Rieken 已提交
203 204 205
			if (!details) {
				return suggestion;
			}
206 207 208
			return <modes.ISuggestion>{
				label: details.name,
				codeSnippet: details.name,
J
Johannes Rieken 已提交
209
				type: SuggestAdapter.asType(details.kind),
J
Johannes Rieken 已提交
210 211
				typeLabel: ts.displayPartsToString(details.displayParts),
				documentationLabel: ts.displayPartsToString(details.documentation)
212 213 214 215
			};
		});
	}

J
Johannes Rieken 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
	static asType(kind: string): modes.SuggestionType{
		switch (kind) {
			case 'getter':
			case 'setting':
			case 'constructor':
			case 'method':
			case 'property':
				return 'property';
			case 'function':
			case 'local function':
				return 'function';
			case 'class':
				return 'class';
			case 'interface':
				return 'interface';
		}

		return 'variable';
	}

236 237 238 239 240 241 242 243 244
	getTriggerCharacters(): string[] {
		return ['.'];
	}

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

A
Alex Dima 已提交
245
class SignatureHelpAdapter extends Adapter implements modes.SignatureHelpProvider {
246

A
Alex Dima 已提交
247
	public signatureHelpTriggerCharacters = ['(', ','];
248

249 250
	provideSignatureHelp(model: editor.IModel, position: editor.IEditorPosition, token: CancellationToken): TPromise<modes.SignatureHelp> {
		let resource = model.getAssociatedResource();
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

			if (!info) {
				return;
			}

257 258 259
			let ret:modes.SignatureHelp = {
				activeSignature: info.selectedItemIndex,
				activeParameter: info.argumentIndex,
J
Johannes Rieken 已提交
260 261 262 263 264
				signatures: []
			};

			info.items.forEach(item => {

265
				let signature:modes.SignatureInformation = {
J
Johannes Rieken 已提交
266 267 268 269 270 271 272 273
					label: '',
					documentation: null,
					parameters: []
				};

				signature.label += ts.displayPartsToString(item.prefixDisplayParts);
				item.parameters.forEach((p, i, a) => {
					let label = ts.displayPartsToString(p.displayParts);
274
					let parameter:modes.ParameterInformation = {
J
Johannes Rieken 已提交
275
						label: label,
276
						documentation: ts.displayPartsToString(p.documentation)
J
Johannes Rieken 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
					};
					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;

		});
	}
}

294 295
// --- hover ------

A
Alex Dima 已提交
296
class QuickInfoAdapter extends Adapter implements modes.HoverProvider {
297

298 299 300
	provideHover(model:editor.IModel, position:editor.IEditorPosition, cancellationToken:CancellationToken): TPromise<modes.Hover> {
		let resource = model.getAssociatedResource();

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
			return <modes.Hover>{
308
				range: this._textSpanToRange(resource, info.textSpan),
309
				htmlContent: [{ text: ts.displayPartsToString(info.displayParts) }]
310 311 312 313 314 315 316 317 318
			};
		});
	}
}

// --- 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
		};
	}
}