modeServiceImpl.ts 18.7 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

7
import * as nls from 'vs/nls';
A
Alex Dima 已提交
8 9
import {onUnexpectedError} from 'vs/base/common/errors';
import Event, {Emitter} from 'vs/base/common/event';
10
import {IDisposable, empty as EmptyDisposable} from 'vs/base/common/lifecycle'; // TODO@Alex
A
Alex Dima 已提交
11
import * as paths from 'vs/base/common/paths';
E
Erich Gamma 已提交
12
import {TPromise} from 'vs/base/common/winjs.base';
13 14
import mime = require('vs/base/common/mime');
import {IFilesConfiguration} from 'vs/platform/files/common/files';
J
Johannes Rieken 已提交
15
import {createAsyncDescriptor1} from 'vs/platform/instantiation/common/descriptors';
A
Alex Dima 已提交
16
import {IExtensionService} from 'vs/platform/extensions/common/extensions';
17
import {IExtensionPointUser, IExtensionMessageCollector, ExtensionsRegistry} from 'vs/platform/extensions/common/extensionsRegistry';
18
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
A
Alex Dima 已提交
19
import * as modes from 'vs/editor/common/modes';
E
Erich Gamma 已提交
20
import {FrankensteinMode} from 'vs/editor/common/modes/abstractMode';
21
import {ModesRegistry} from 'vs/editor/common/modes/modesRegistry';
A
Alex Dima 已提交
22
import {LanguagesRegistry} from 'vs/editor/common/services/languagesRegistry';
23
import {ILanguageExtensionPoint, IValidLanguageExtensionPoint, IModeLookupResult, IModeService} from 'vs/editor/common/services/modeService';
24
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
A
Alex Dima 已提交
25 26
import {AbstractState} from 'vs/editor/common/modes/abstractState';
import {Token} from 'vs/editor/common/modes/supports';
E
Erich Gamma 已提交
27

28
let languagesExtPoint = ExtensionsRegistry.registerExtensionPoint<ILanguageExtensionPoint[]>('languages', {
29 30 31 32
	description: nls.localize('vscode.extension.contributes.languages', 'Contributes language declarations.'),
	type: 'array',
	items: {
		type: 'object',
33
		defaultSnippets: [{ body: { id: '{{languageId}}', aliases: ['{{label}}'], extensions: ['{{extension}}'], configuration: './language-configuration.json'} }],
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
		properties: {
			id: {
				description: nls.localize('vscode.extension.contributes.languages.id', 'ID of the language.'),
				type: 'string'
			},
			aliases: {
				description: nls.localize('vscode.extension.contributes.languages.aliases', 'Name aliases for the language.'),
				type: 'array',
				items: {
					type: 'string'
				}
			},
			extensions: {
				description: nls.localize('vscode.extension.contributes.languages.extensions', 'File extensions associated to the language.'),
				default: ['.foo'],
				type: 'array',
				items: {
					type: 'string'
				}
			},
			filenames: {
				description: nls.localize('vscode.extension.contributes.languages.filenames', 'File names associated to the language.'),
				type: 'array',
				items: {
					type: 'string'
				}
			},
			filenamePatterns: {
				description: nls.localize('vscode.extension.contributes.languages.filenamePatterns', 'File name glob patterns associated to the language.'),
				type: 'array',
64
				items: {
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
					type: 'string'
				}
			},
			mimetypes: {
				description: nls.localize('vscode.extension.contributes.languages.mimetypes', 'Mime types associated to the language.'),
				type: 'array',
				items: {
					type: 'string'
				}
			},
			firstLine: {
				description: nls.localize('vscode.extension.contributes.languages.firstLine', 'A regular expression matching the first line of a file of the language.'),
				type: 'string'
			},
			configuration: {
				description: nls.localize('vscode.extension.contributes.languages.configuration', 'A relative path to a file containing configuration options for the language.'),
81 82
				type: 'string',
				default: './language-configuration.json'
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
			}
		}
	}
});

function isUndefinedOrStringArray(value: string[]): boolean {
	if (typeof value === 'undefined') {
		return true;
	}
	if (!Array.isArray(value)) {
		return false;
	}
	return value.every(item => typeof item === 'string');
}

98
function isValidLanguageExtensionPoint(value:ILanguageExtensionPoint, collector:IExtensionMessageCollector): boolean {
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
	if (!value) {
		collector.error(nls.localize('invalid.empty', "Empty value for `contributes.{0}`", languagesExtPoint.name));
		return false;
	}
	if (typeof value.id !== 'string') {
		collector.error(nls.localize('require.id', "property `{0}` is mandatory and must be of type `string`", 'id'));
		return false;
	}
	if (!isUndefinedOrStringArray(value.extensions)) {
		collector.error(nls.localize('opt.extensions', "property `{0}` can be omitted and must be of type `string[]`", 'extensions'));
		return false;
	}
	if (!isUndefinedOrStringArray(value.filenames)) {
		collector.error(nls.localize('opt.filenames', "property `{0}` can be omitted and must be of type `string[]`", 'filenames'));
		return false;
	}
	if (typeof value.firstLine !== 'undefined' && typeof value.firstLine !== 'string') {
		collector.error(nls.localize('opt.firstLine', "property `{0}` can be omitted and must be of type `string`", 'firstLine'));
		return false;
	}
	if (typeof value.configuration !== 'undefined' && typeof value.configuration !== 'string') {
		collector.error(nls.localize('opt.configuration', "property `{0}` can be omitted and must be of type `string`", 'configuration'));
		return false;
	}
	if (!isUndefinedOrStringArray(value.aliases)) {
		collector.error(nls.localize('opt.aliases', "property `{0}` can be omitted and must be of type `string[]`", 'aliases'));
		return false;
	}
	if (!isUndefinedOrStringArray(value.mimetypes)) {
		collector.error(nls.localize('opt.mimetypes', "property `{0}` can be omitted and must be of type `string[]`", 'mimetypes'));
		return false;
	}
	return true;
}

E
Erich Gamma 已提交
134
export class ModeServiceImpl implements IModeService {
135
	public _serviceBrand: any;
E
Erich Gamma 已提交
136

137
	private _instantiationService: IInstantiationService;
138 139
	protected _extensionService: IExtensionService;

A
Alex Dima 已提交
140 141
	private _activationPromises: { [modeId: string]: TPromise<modes.IMode>; };
	private _instantiatedModes: { [modeId: string]: modes.IMode; };
E
Erich Gamma 已提交
142

143 144 145 146
	private _registry: LanguagesRegistry;

	private _onDidAddModes: Emitter<string[]> = new Emitter<string[]>();
	public onDidAddModes: Event<string[]> = this._onDidAddModes.event;
147

A
Alex Dima 已提交
148 149 150
	private _onDidCreateMode: Emitter<modes.IMode> = new Emitter<modes.IMode>();
	public onDidCreateMode: Event<modes.IMode> = this._onDidCreateMode.event;

151 152
	constructor(instantiationService:IInstantiationService, extensionService:IExtensionService) {
		this._instantiationService = instantiationService;
A
Alex Dima 已提交
153
		this._extensionService = extensionService;
154

E
Erich Gamma 已提交
155 156
		this._activationPromises = {};
		this._instantiatedModes = {};
157

158 159
		this._registry = new LanguagesRegistry();
		this._registry.onDidAddModes((modes) => this._onDidAddModes.fire(modes));
E
Erich Gamma 已提交
160 161
	}

162
	public isRegisteredMode(mimetypeOrModeId: string): boolean {
163
		return this._registry.isRegisteredMode(mimetypeOrModeId);
164 165
	}

166 167 168 169 170
	public isCompatMode(modeId:string): boolean {
		let compatModeData = this._registry.getCompatMode(modeId);
		return (compatModeData ? true : false);
	}

171
	public getRegisteredModes(): string[] {
172
		return this._registry.getRegisteredModes();
173 174
	}

175
	public getRegisteredLanguageNames(): string[] {
176
		return this._registry.getRegisteredLanguageNames();
177 178 179
	}

	public getExtensions(alias: string): string[] {
180
		return this._registry.getExtensions(alias);
181 182 183
	}

	public getMimeForMode(modeId: string): string {
184
		return this._registry.getMimeForMode(modeId);
185 186 187
	}

	public getLanguageName(modeId: string): string {
188
		return this._registry.getLanguageName(modeId);
189 190 191
	}

	public getModeIdForLanguageName(alias:string): string {
192
		return this._registry.getModeIdForLanguageNameLowercase(alias);
193 194 195
	}

	public getModeId(commaSeparatedMimetypesOrCommaSeparatedIds: string): string {
196
		var modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds);
197 198 199 200 201 202 203 204

		if (modeIds.length > 0) {
			return modeIds[0];
		}

		return null;
	}

205
	public getConfigurationFiles(modeId: string): string[] {
206
		return this._registry.getConfigurationFiles(modeId);
207 208
	}

E
Erich Gamma 已提交
209 210 211 212
	// --- instantiation

	public lookup(commaSeparatedMimetypesOrCommaSeparatedIds: string): IModeLookupResult[]{
		var r: IModeLookupResult[] = [];
213
		var modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds);
E
Erich Gamma 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226

		for (var i = 0; i < modeIds.length; i++) {
			var modeId = modeIds[i];

			r.push({
				modeId: modeId,
				isInstantiated: this._instantiatedModes.hasOwnProperty(modeId)
			});
		}

		return r;
	}

A
Alex Dima 已提交
227
	public getMode(commaSeparatedMimetypesOrCommaSeparatedIds: string): modes.IMode {
228
		var modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds);
E
Erich Gamma 已提交
229 230 231 232 233 234 235 236 237 238 239

		var isPlainText = false;
		for (var i = 0; i < modeIds.length; i++) {
			if (this._instantiatedModes.hasOwnProperty(modeIds[i])) {
				return this._instantiatedModes[modeIds[i]];
			}
			isPlainText = isPlainText || (modeIds[i] === 'plaintext');
		}

		if (isPlainText) {
			// Try to do it synchronously
A
Alex Dima 已提交
240
			var r: modes.IMode = null;
E
Erich Gamma 已提交
241 242
			this.getOrCreateMode(commaSeparatedMimetypesOrCommaSeparatedIds).then((mode) => {
				r = mode;
A
Alex Dima 已提交
243
			}).done(null, onUnexpectedError);
E
Erich Gamma 已提交
244 245 246 247 248
			return r;
		}
	}

	public getModeIdByLanguageName(languageName: string): string {
249
		var modeIds = this._registry.getModeIdsFromLanguageName(languageName);
E
Erich Gamma 已提交
250 251 252 253 254 255 256 257 258

		if (modeIds.length > 0) {
			return modeIds[0];
		}

		return null;
	}

	public getModeIdByFilenameOrFirstLine(filename: string, firstLine?:string): string {
259
		var modeIds = this._registry.getModeIdsFromFilenameOrFirstLine(filename, firstLine);
E
Erich Gamma 已提交
260 261 262 263 264 265 266 267

		if (modeIds.length > 0) {
			return modeIds[0];
		}

		return null;
	}

268 269 270 271
	public onReady(): TPromise<boolean> {
		return this._extensionService.onReady();
	}

A
Alex Dima 已提交
272
	public getOrCreateMode(commaSeparatedMimetypesOrCommaSeparatedIds: string): TPromise<modes.IMode> {
273
		return this.onReady().then(() => {
E
Erich Gamma 已提交
274 275 276 277 278 279
			var modeId = this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds);
			// Fall back to plain text if no mode was found
			return this._getOrCreateMode(modeId || 'plaintext');
		});
	}

A
Alex Dima 已提交
280
	public getOrCreateModeByLanguageName(languageName: string): TPromise<modes.IMode> {
281
		return this.onReady().then(() => {
E
Erich Gamma 已提交
282 283 284 285 286 287
			var modeId = this.getModeIdByLanguageName(languageName);
			// Fall back to plain text if no mode was found
			return this._getOrCreateMode(modeId || 'plaintext');
		});
	}

A
Alex Dima 已提交
288
	public getOrCreateModeByFilenameOrFirstLine(filename: string, firstLine?:string): TPromise<modes.IMode> {
289
		return this.onReady().then(() => {
E
Erich Gamma 已提交
290 291 292 293 294 295
			var modeId = this.getModeIdByFilenameOrFirstLine(filename, firstLine);
			// Fall back to plain text if no mode was found
			return this._getOrCreateMode(modeId || 'plaintext');
		});
	}

A
Alex Dima 已提交
296
	private _getOrCreateMode(modeId: string): TPromise<modes.IMode> {
E
Erich Gamma 已提交
297 298 299 300 301 302 303
		if (this._instantiatedModes.hasOwnProperty(modeId)) {
			return TPromise.as(this._instantiatedModes[modeId]);
		}

		if (this._activationPromises.hasOwnProperty(modeId)) {
			return this._activationPromises[modeId];
		}
304 305 306
		var c, e;
		var promise = new TPromise((cc,ee,pp) => { c = cc; e = ee; });
		this._activationPromises[modeId] = promise;
J
Joao Moreno 已提交
307

308
		this._createMode(modeId).then((mode) => {
E
Erich Gamma 已提交
309 310
			this._instantiatedModes[modeId] = mode;
			delete this._activationPromises[modeId];
A
Alex Dima 已提交
311 312 313

			this._onDidCreateMode.fire(mode);

A
Alex Dima 已提交
314
			this._extensionService.activateByEvent(`onLanguage:${modeId}`).done(null, onUnexpectedError);
A
Alex Dima 已提交
315

E
Erich Gamma 已提交
316
			return this._instantiatedModes[modeId];
317 318 319
		}).then(c, e);

		return promise;
E
Erich Gamma 已提交
320 321
	}

322
	private _createMode(modeId:string): TPromise<modes.IMode> {
A
Alex Dima 已提交
323
		let modeDescriptor = this._createModeDescriptor(modeId);
E
Erich Gamma 已提交
324

325
		let compatModeData = this._registry.getCompatMode(modeId);
326
		if (compatModeData) {
A
Alex Dima 已提交
327
			// This is a compatibility mode
328 329 330 331 332 333 334 335 336 337

			let resolvedDeps: TPromise<modes.IMode[]> = null;
			if (Array.isArray(compatModeData.deps)) {
				resolvedDeps = TPromise.join(compatModeData.deps.map(dep => this.getOrCreateMode(dep)));
			} else {
				resolvedDeps = TPromise.as<modes.IMode[]>(null);
			}

			return resolvedDeps.then(_ => {
				let compatModeAsyncDescriptor = createAsyncDescriptor1<modes.IModeDescriptor, modes.IMode>(compatModeData.moduleId, compatModeData.ctorName);
A
Alex Dima 已提交
338
				return this._instantiationService.createInstance(compatModeAsyncDescriptor, modeDescriptor);
A
Alex Dima 已提交
339
			});
E
Erich Gamma 已提交
340 341
		}

342
		return TPromise.as<modes.IMode>(this._instantiationService.createInstance(FrankensteinMode, modeDescriptor));
E
Erich Gamma 已提交
343 344
	}

A
Alex Dima 已提交
345
	private _createModeDescriptor(modeId:string): modes.IModeDescriptor {
E
Erich Gamma 已提交
346
		return {
J
Johannes Rieken 已提交
347
			id: modeId
E
Erich Gamma 已提交
348 349 350
		};
	}

351 352 353
	private _registerTokenizationSupport<T>(mode:modes.IMode, callback: (mode: modes.IMode) => T): IDisposable {
		if (mode.setTokenizationSupport) {
			return mode.setTokenizationSupport(callback);
354
		} else {
355
			console.warn('Cannot register tokenizationSupport on mode ' + mode.getId() + ' because it does not support it.');
356 357 358 359
			return EmptyDisposable;
		}
	}

360
	private registerModeSupport<T>(modeId: string, callback: (mode: modes.IMode) => T): IDisposable {
361
		if (this._instantiatedModes.hasOwnProperty(modeId)) {
362
			return this._registerTokenizationSupport(this._instantiatedModes[modeId], callback);
363 364 365 366 367 368 369 370
		}

		let cc: (disposable:IDisposable)=>void;
		let promise = new TPromise<IDisposable>((c, e) => { cc = c; });

		let disposable = this.onDidCreateMode((mode) => {
			if (mode.getId() !== modeId) {
				return;
E
Erich Gamma 已提交
371
			}
372

373
			cc(this._registerTokenizationSupport(mode, callback));
374
			disposable.dispose();
E
Erich Gamma 已提交
375
		});
376

E
Erich Gamma 已提交
377 378 379 380
		return {
			dispose: () => {
				promise.done(disposable => disposable.dispose(), null);
			}
A
tslint  
Alex Dima 已提交
381
		};
E
Erich Gamma 已提交
382 383
	}

A
Alex Dima 已提交
384
	public registerTokenizationSupport(modeId: string, callback: (mode: modes.IMode) => modes.ITokenizationSupport): IDisposable {
385
		return this.registerModeSupport(modeId, callback);
E
Erich Gamma 已提交
386
	}
A
Alex Dima 已提交
387

388
	public registerTokenizationSupport2(modeId: string, support: modes.TokensProvider): IDisposable {
389
		return this.registerModeSupport(modeId, (mode) => {
A
Alex Dima 已提交
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
			return new TokenizationSupport2Adapter(mode, support);
		});
	}
}

export class TokenizationState2Adapter implements modes.IState {

	private _mode: modes.IMode;
	private _actual: modes.IState2;
	private _stateData: modes.IState;

	constructor(mode: modes.IMode, actual: modes.IState2, stateData: modes.IState) {
		this._mode = mode;
		this._actual = actual;
		this._stateData = stateData;
	}

	public get actual(): modes.IState2 { return this._actual; }

	public clone(): TokenizationState2Adapter {
		return new TokenizationState2Adapter(this._mode, this._actual.clone(), AbstractState.safeClone(this._stateData));
	}

	public equals(other:modes.IState): boolean {
		if (other instanceof TokenizationState2Adapter) {
			if (!this._actual.equals(other._actual)) {
				return false;
			}
			return AbstractState.safeEquals(this._stateData, other._stateData);
		}
		return false;
	}

	public getMode(): modes.IMode {
		return this._mode;
	}

	public tokenize(stream:any): any {
		throw new Error('Unexpected tokenize call!');
	}

	public getStateData(): modes.IState {
		return this._stateData;
	}

	public setStateData(stateData:modes.IState): void {
		this._stateData = stateData;
	}
}

export class TokenizationSupport2Adapter implements modes.ITokenizationSupport {

	private _mode: modes.IMode;
443
	private _actual: modes.TokensProvider;
A
Alex Dima 已提交
444

445
	constructor(mode: modes.IMode, actual: modes.TokensProvider) {
A
Alex Dima 已提交
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
		this._mode = mode;
		this._actual = actual;
	}

	public getInitialState(): modes.IState {
		return new TokenizationState2Adapter(this._mode, this._actual.getInitialState(), null);
	}

	public tokenize(line:string, state:modes.IState, offsetDelta: number = 0, stopAtOffset?: number): modes.ILineTokens {
		if (state instanceof TokenizationState2Adapter) {
			let actualResult = this._actual.tokenize(line, state.actual);
			let tokens: modes.IToken[] = [];
			actualResult.tokens.forEach((t) => {
				if (typeof t.scopes === 'string') {
					tokens.push(new Token(t.startIndex + offsetDelta, <string>t.scopes));
				} else if (Array.isArray(t.scopes) && t.scopes.length === 1) {
					tokens.push(new Token(t.startIndex + offsetDelta, t.scopes[0]));
				} else {
					throw new Error('Only token scopes as strings or of precisely 1 length are supported at this time!');
				}
			});
			return {
				tokens: tokens,
				actualStopOffset: offsetDelta + line.length,
				endState: new TokenizationState2Adapter(state.getMode(), actualResult.endState, state.getStateData()),
				modeTransitions: [{ startIndex: offsetDelta, mode: state.getMode() }],
			};
		}
		throw new Error('Unexpected state to tokenize with!');
	}

E
Erich Gamma 已提交
477 478 479
}

export class MainThreadModeServiceImpl extends ModeServiceImpl {
480 481
	private _configurationService: IConfigurationService;
	private _onReadyPromise: TPromise<boolean>;
E
Erich Gamma 已提交
482

483
	constructor(
484
		@IInstantiationService instantiationService:IInstantiationService,
485 486
		@IExtensionService extensionService:IExtensionService,
		@IConfigurationService configurationService:IConfigurationService
487
	) {
488
		super(instantiationService, extensionService);
489
		this._configurationService = configurationService;
490 491

		languagesExtPoint.setHandler((extensions:IExtensionPointUser<ILanguageExtensionPoint[]>[]) => {
492
			let allValidLanguages: IValidLanguageExtensionPoint[] = [];
493 494 495 496 497 498 499 500 501 502

			for (let i = 0, len = extensions.length; i < len; i++) {
				let extension = extensions[i];

				if (!Array.isArray(extension.value)) {
					extension.collector.error(nls.localize('invalid', "Invalid `contributes.{0}`. Expected an array.", languagesExtPoint.name));
					continue;
				}

				for (let j = 0, lenJ = extension.value.length; j < lenJ; j++) {
503 504 505
					let ext = extension.value[j];
					if (isValidLanguageExtensionPoint(ext, extension.collector)) {
						let configuration = (ext.configuration ? paths.join(extension.description.extensionFolderPath, ext.configuration) : ext.configuration);
506
						allValidLanguages.push({
507 508 509 510 511 512 513 514
							id: ext.id,
							extensions: ext.extensions,
							filenames: ext.filenames,
							filenamePatterns: ext.filenamePatterns,
							firstLine: ext.firstLine,
							aliases: ext.aliases,
							mimetypes: ext.mimetypes,
							configuration: configuration
515 516 517 518 519 520 521 522
						});
					}
				}
			}

			ModesRegistry.registerLanguages(allValidLanguages);

		});
523

524
		this._configurationService.onDidUpdateConfiguration(e => this.onConfigurationChange(e.config));
525 526 527 528
	}

	public onReady(): TPromise<boolean> {
		if (!this._onReadyPromise) {
529 530 531
			const configuration = this._configurationService.getConfiguration<IFilesConfiguration>();
			this._onReadyPromise = this._extensionService.onReady().then(() => {
				this.onConfigurationChange(configuration);
532

533
				return true;
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
			});
		}

		return this._onReadyPromise;
	}

	private onConfigurationChange(configuration: IFilesConfiguration): void {

		// Clear user configured mime associations
		mime.clearTextMimes(true /* user configured */);

		// Register based on settings
		if (configuration.files && configuration.files.associations) {
			Object.keys(configuration.files.associations).forEach(pattern => {
				mime.registerTextMime({ mime: this.getMimeForMode(configuration.files.associations[pattern]), filepattern: pattern, userConfigured: true });
			});
		}
E
Erich Gamma 已提交
551
	}
552
}