modeServiceImpl.ts 18.8 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';
27
import {ModeTransition} from 'vs/editor/common/core/modeTransition';
E
Erich Gamma 已提交
28

29
let languagesExtPoint = ExtensionsRegistry.registerExtensionPoint<ILanguageExtensionPoint[]>('languages', {
30 31 32 33
	description: nls.localize('vscode.extension.contributes.languages', 'Contributes language declarations.'),
	type: 'array',
	items: {
		type: 'object',
34
		defaultSnippets: [{ body: { id: '{{languageId}}', aliases: ['{{label}}'], extensions: ['{{extension}}'], configuration: './language-configuration.json'} }],
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 64
		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',
65
				items: {
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
					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.'),
82 83
				type: 'string',
				default: './language-configuration.json'
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
			}
		}
	}
});

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

99
function isValidLanguageExtensionPoint(value:ILanguageExtensionPoint, collector:IExtensionMessageCollector): boolean {
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
	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 已提交
135
export class ModeServiceImpl implements IModeService {
136
	public _serviceBrand: any;
E
Erich Gamma 已提交
137

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

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

144 145 146 147
	private _registry: LanguagesRegistry;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return null;
	}

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

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

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

		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 已提交
228
	public getMode(commaSeparatedMimetypesOrCommaSeparatedIds: string): modes.IMode {
229
		var modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds);
E
Erich Gamma 已提交
230 231 232 233 234 235 236 237 238 239 240

		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 已提交
241
			var r: modes.IMode = null;
E
Erich Gamma 已提交
242 243
			this.getOrCreateMode(commaSeparatedMimetypesOrCommaSeparatedIds).then((mode) => {
				r = mode;
A
Alex Dima 已提交
244
			}).done(null, onUnexpectedError);
E
Erich Gamma 已提交
245 246 247 248 249
			return r;
		}
	}

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

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

		return null;
	}

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

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

		return null;
	}

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

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

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

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

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

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

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

			this._onDidCreateMode.fire(mode);

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

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

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

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

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

			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 已提交
339
				return this._instantiationService.createInstance(compatModeAsyncDescriptor, modeDescriptor);
A
Alex Dima 已提交
340
			});
E
Erich Gamma 已提交
341 342
		}

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

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

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

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

		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 已提交
372
			}
373

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

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

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

389
	public registerTokenizationSupport2(modeId: string, support: modes.TokensProvider): IDisposable {
390
		return this.registerModeSupport(modeId, (mode) => {
A
Alex Dima 已提交
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
			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;
444
	private _actual: modes.TokensProvider;
A
Alex Dima 已提交
445

446
	constructor(mode: modes.IMode, actual: modes.TokensProvider) {
A
Alex Dima 已提交
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
		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()),
472
				modeTransitions: [new ModeTransition(offsetDelta, state.getMode().getId())],
A
Alex Dima 已提交
473 474 475 476 477
			};
		}
		throw new Error('Unexpected state to tokenize with!');
	}

E
Erich Gamma 已提交
478 479 480
}

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

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

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

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

			ModesRegistry.registerLanguages(allValidLanguages);

		});
524

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

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

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

		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 => {
549 550
				const langId = configuration.files.associations[pattern];
				const mimetype = this.getMimeForMode(langId) || `text/x-${langId}`;
551

552
				mime.registerTextMime({ mime: mimetype, filepattern: pattern, userConfigured: true });
553 554
			});
		}
E
Erich Gamma 已提交
555
	}
556
}