languageFeatures.ts 15.5 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 11 12 13
import * as editor from 'vs/editor/common/editorCommon';
import * as modes from 'vs/editor/common/modes';
import * as lifecycle from 'vs/base/common/lifecycle';
import * as ts from 'vs/languages/typescript/common/lib/typescriptServices';
J
Johannes Rieken 已提交
14
import matches from 'vs/editor/common/modes/languageSelector';
15
import AbstractWorker from './worker/worker';
J
Johannes Rieken 已提交
16
import {IMarkerService, IMarkerData} from 'vs/platform/markers/common/markers';
17 18
import {IModelService} from 'vs/editor/common/services/modelService';
import {SuggestRegistry} from 'vs/editor/contrib/suggest/common/suggest';
J
Johannes Rieken 已提交
19
import {ParameterHintsRegistry} from 'vs/editor/contrib/parameterHints/common/parameterHints';
20 21
import {OccurrencesRegistry} from 'vs/editor/contrib/wordHighlighter/common/wordHighlighter';
import {ExtraInfoRegistry} from 'vs/editor/contrib/hover/common/hover';
J
Johannes Rieken 已提交
22 23
import {ReferenceRegistry} from 'vs/editor/contrib/referenceSearch/common/referenceSearch';
import {DeclarationRegistry} from 'vs/editor/contrib/goToDeclaration/common/goToDeclaration';
24 25
import {OutlineRegistry} from 'vs/editor/contrib/quickOpen/common/quickOpen';
import {FormatRegistry, FormatOnTypeRegistry} from 'vs/editor/contrib/format/common/format';
26

J
Johannes Rieken 已提交
27
export function registerLanguageFeatures(modelService: IModelService, markerService: IMarkerService, selector: string, worker: (first: URI, ...more: URI[]) => TPromise<AbstractWorker>): lifecycle.IDisposable {
28 29
	const disposables: lifecycle.IDisposable[] = [];
	disposables.push(SuggestRegistry.register(selector, new SuggestAdapter(modelService, worker)));
J
Johannes Rieken 已提交
30
	disposables.push(ParameterHintsRegistry.register(selector, new ParameterHintsAdapter(modelService, worker)));
31 32
	disposables.push(ExtraInfoRegistry.register(selector, new QuickInfoAdapter(modelService, worker)));
	disposables.push(OccurrencesRegistry.register(selector, new OccurrencesAdapter(modelService, worker)));
J
Johannes Rieken 已提交
33 34
	disposables.push(DeclarationRegistry.register(selector, new DeclarationAdapter(modelService, worker)));
	disposables.push(ReferenceRegistry.register(selector, new ReferenceAdapter(modelService, worker)));
35 36 37
	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)));
J
Johannes Rieken 已提交
38 39
	disposables.push(new DiagnostcsAdapter(selector, markerService, modelService, worker));

40 41 42 43 44
	return lifecycle.combinedDispose2(disposables);
}

abstract class Adapter {

J
Johannes Rieken 已提交
45
	constructor(protected _modelService: IModelService, protected _worker: (first:URI, ...more:URI[]) => TPromise<AbstractWorker>) {
46 47 48 49 50 51 52

	}

	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++) {
53
			result += model.getLineContent(i).length + model.getEOL().length;
54 55 56 57 58 59 60
		}
		return result;
	}

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

	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 已提交
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
// --- diagnostics --- ---

class DiagnostcsAdapter extends Adapter {

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

	constructor(private _selector:string, private _markerService: IMarkerService, modelService: IModelService, worker: (first: URI, ...more: URI[]) => TPromise<AbstractWorker>) {
		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 {
		this._disposables = lifecycle.disposeAll(this._disposables);
	}

	private _doValidate(resource: URI): void {
		this._worker(resource).then(worker => TPromise.join([worker.getSyntacticDiagnostics(resource.toString()), worker.getSemanticDiagnostics(resource.toString())])).then(diagnostics => {
			const [syntactic, semantic] = diagnostics;
			const markers = syntactic.concat(semantic).map(d => this._convertDiagnostics(resource, d));
			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')
		};
	}
}

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

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

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

J
Johannes Rieken 已提交
189
		return this._worker(resource).then(worker => {
190 191 192
			return worker.getCompletionEntryDetails(resource.toString(),
				this._positionToOffset(resource, position),
				suggestion.label);
J
Johannes Rieken 已提交
193

194
		}).then(details => {
J
Johannes Rieken 已提交
195 196 197
			if (!details) {
				return suggestion;
			}
198 199 200
			return <modes.ISuggestion>{
				label: details.name,
				codeSnippet: details.name,
J
Johannes Rieken 已提交
201 202 203
				type: details.kind,
				typeLabel: ts.displayPartsToString(details.displayParts),
				documentationLabel: ts.displayPartsToString(details.documentation)
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
			};
		});
	}

	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 已提交
225 226 227 228 229 230 231 232
class ParameterHintsAdapter extends Adapter implements modes.IParameterHintsSupport {
	getParameterHintsTriggerCharacters(): string[] {
		return ['(', ','];
	}
	shouldTriggerParameterHints(context: modes.ILineContext, offset: number): boolean {
		return true;
	}
	getParameterHints(resource: URI, position: editor.IPosition, triggerCharacter?: string): TPromise<modes.IParameterHints> {
J
Johannes Rieken 已提交
233
		return this._worker(resource).then(worker => worker.getSignatureHelpItems(resource.toString(), this._positionToOffset(resource, position))).then(info => {
J
Johannes Rieken 已提交
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

			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;

		});
	}
}

278 279 280 281 282
// --- hover ------

class QuickInfoAdapter extends Adapter implements modes.IExtraInfoSupport {

	computeInfo(resource: URI, position: editor.IPosition): TPromise<modes.IComputeExtraInfoResult> {
J
Johannes Rieken 已提交
283
		return this._worker(resource).then(worker => {
284 285
			return worker.getQuickInfoAtPosition(resource.toString(), this._positionToOffset(resource, position));
		}).then(info => {
286 287 288
			if (!info) {
				return;
			}
289 290 291 292 293 294 295 296 297 298 299 300
			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 已提交
301
	findOccurrences(resource: URI, position: editor.IPosition, strict?: boolean): TPromise<modes.IOccurence[]> {
J
Johannes Rieken 已提交
302
		return this._worker(resource).then(worker => {
303 304
			return worker.getOccurrencesAtPosition(resource.toString(), this._positionToOffset(resource, position));
		}).then(entries => {
305 306 307
			if (!entries) {
				return;
			}
308 309 310 311 312 313 314 315 316 317
			return entries.map(entry => {
				return <modes.IOccurence>{
					range: this._textSpanToRange(resource, entry.textSpan),
					kind: entry.isWriteAccess ? 'write' : 'text'
				};
			});
		});
	}
}

J
Johannes Rieken 已提交
318 319 320 321
// --- definition ------

class DeclarationAdapter extends Adapter implements modes.IDeclarationSupport {

J
Johannes Rieken 已提交
322
	canFindDeclaration(context: modes.ILineContext, offset: number): boolean {
J
Johannes Rieken 已提交
323 324 325 326
		return true;
	}

	findDeclaration(resource: URI, position: editor.IPosition): TPromise<modes.IReference[]> {
J
Johannes Rieken 已提交
327
		return this._worker(resource).then(worker => {
J
Johannes Rieken 已提交
328 329
			return worker.getDefinitionAtPosition(resource.toString(), this._positionToOffset(resource, position));
		}).then(entries => {
330 331 332
			if (!entries) {
				return;
			}
J
Johannes Rieken 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
			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 已提交
356
	findReferences(resource: URI, position: editor.IPosition, includeDeclaration: boolean): TPromise<modes.IReference[]> {
J
Johannes Rieken 已提交
357
		return this._worker(resource).then(worker => {
J
Johannes Rieken 已提交
358 359
			return worker.getReferencesAtPosition(resource.toString(), this._positionToOffset(resource, position));
		}).then(entries => {
360 361 362
			if (!entries) {
				return;
			}
J
Johannes Rieken 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376
			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;
		});
	}
}
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

// --- 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,
			NewLineCharacter: '\n',
			InsertSpaceAfterCommaDelimiter: true,
			InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
			InsertSpaceAfterKeywordsInControlFlowStatements: false,
			InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: true,
			InsertSpaceAfterSemicolonInForStatements: false,
			InsertSpaceBeforeAndAfterBinaryOperators: true,
			PlaceOpenBraceOnNewLineForControlBlocks: false,
			PlaceOpenBraceOnNewLineForFunctions: false
		};
	}
}