tokenClassificationRegistry.ts 17.0 KB
Newer Older
M
Martin Aeschlimann 已提交
1 2 3 4 5 6 7 8 9
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as platform from 'vs/platform/registry/common/platform';
import { Color } from 'vs/base/common/color';
import { ITheme } from 'vs/platform/theme/common/themeService';
import * as nls from 'vs/nls';
10 11 12 13
import { Extensions as JSONExtensions, IJSONContributionRegistry } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
import { RunOnceScheduler } from 'vs/base/common/async';
import { Event, Emitter } from 'vs/base/common/event';
import { IJSONSchema, IJSONSchemaMap } from 'vs/base/common/jsonSchema';
M
Martin Aeschlimann 已提交
14 15 16 17 18 19 20

export const TOKEN_TYPE_WILDCARD = '*';
export const TOKEN_TYPE_WILDCARD_NUM = -1;

// qualified string [type|*](.modifier)*
export type TokenClassificationString = string;

21
export const typeAndModifierIdPattern = '^\\w+[-_\\w+]*$';
M
Martin Aeschlimann 已提交
22
export const fontStylePattern = '^(\\s*(-?italic|-?bold|-?underline))*\\s*$';
23

M
Martin Aeschlimann 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
export interface TokenClassification {
	type: number;
	modifiers: number;
}

export interface TokenTypeOrModifierContribution {
	readonly num: number;
	readonly id: string;
	readonly description: string;
	readonly deprecationMessage: string | undefined;
}


export interface TokenStyleData {
	foreground?: Color;
	bold?: boolean;
	underline?: boolean;
	italic?: boolean;
}

export class TokenStyle implements Readonly<TokenStyleData> {
	constructor(
		public readonly foreground?: Color,
		public readonly bold?: boolean,
		public readonly underline?: boolean,
		public readonly italic?: boolean,
	) {
	}
}

export namespace TokenStyle {
	export function fromData(data: { foreground?: Color, bold?: boolean, underline?: boolean, italic?: boolean }) {
		return new TokenStyle(data.foreground, data.bold, data.underline, data.italic);
	}
M
Martin Aeschlimann 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
	export function fromSettings(foreground: string | undefined, fontStyle: string | undefined): TokenStyle {
		let foregroundColor = undefined;
		if (foreground !== undefined) {
			foregroundColor = Color.fromHex(foreground);
		}
		let bold, underline, italic;
		if (fontStyle !== undefined) {
			fontStyle = fontStyle.trim();
			if (fontStyle.length === 0) {
				bold = italic = underline = false;
			} else {
				const expression = /-?italic|-?bold|-?underline/g;
				let match;
				while ((match = expression.exec(fontStyle))) {
					switch (match[0]) {
						case 'bold': bold = true; break;
						case 'italic': italic = true; break;
						case 'underline': underline = true; break;
					}
				}
			}
		}
		return new TokenStyle(foregroundColor, bold, underline, italic);

	}
M
Martin Aeschlimann 已提交
83 84 85 86 87 88 89 90 91
}

export type ProbeScope = string[];

export interface TokenStyleFunction {
	(theme: ITheme): TokenStyle | undefined;
}

export interface TokenStyleDefaults {
M
Martin Aeschlimann 已提交
92 93 94 95
	scopesToProbe?: ProbeScope[];
	light?: TokenStyleValue;
	dark?: TokenStyleValue;
	hc?: TokenStyleValue;
M
Martin Aeschlimann 已提交
96 97 98
}

export interface TokenStylingDefaultRule {
99 100
	match(classification: TokenClassification): number;
	selector: TokenClassification;
M
Martin Aeschlimann 已提交
101 102 103 104
	defaults: TokenStyleDefaults;
}

export interface TokenStylingRule {
105
	match(classification: TokenClassification): number;
M
Martin Aeschlimann 已提交
106
	value: TokenStyle;
107
	selector: TokenClassification;
M
Martin Aeschlimann 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121
}

/**
 * A TokenStyle Value is either a token style literal, or a TokenClassificationString
 */
export type TokenStyleValue = TokenStyle | TokenClassificationString;

// TokenStyle registry
export const Extensions = {
	TokenClassificationContribution: 'base.contributions.tokenClassification'
};

export interface ITokenClassificationRegistry {

122 123
	readonly onDidChangeSchema: Event<void>;

M
Martin Aeschlimann 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
	/**
	 * Register a token type to the registry.
	 * @param id The TokenType id as used in theme description files
	 * @description the description
	 */
	registerTokenType(id: string, description: string): void;

	/**
	 * Register a token modifier to the registry.
	 * @param id The TokenModifier id as used in theme description files
	 * @description the description
	 */
	registerTokenModifier(id: string, description: string): void;

	getTokenClassification(type: string, modifiers: string[]): TokenClassification | undefined;

140
	getTokenStylingRule(classification: TokenClassification, value: TokenStyle): TokenStylingRule;
M
Martin Aeschlimann 已提交
141

M
Martin Aeschlimann 已提交
142 143 144 145 146 147 148
	/**
	 * Register a TokenStyle default to the registry.
	 * @param selector The rule selector
	 * @param defaults The default values
	 */
	registerTokenStyleDefault(selector: TokenClassification, defaults: TokenStyleDefaults): void;

149 150 151 152 153 154
	/**
	 * Deregister a TokenStyle default to the registry.
	 * @param selector The rule selector
	 */
	deregisterTokenStyleDefault(selector: TokenClassification): void;

M
Martin Aeschlimann 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
	/**
	 * Deregister a TokenType from the registry.
	 */
	deregisterTokenType(id: string): void;

	/**
	 * Deregister a TokenModifier from the registry.
	 */
	deregisterTokenModifier(id: string): void;

	/**
	 * Get all TokenType contributions
	 */
	getTokenTypes(): TokenTypeOrModifierContribution[];

	/**
	 * Get all TokenModifier contributions
	 */
	getTokenModifiers(): TokenTypeOrModifierContribution[];

	/**
176
	 * The styling rules to used when a schema does not define any styling rules.
M
Martin Aeschlimann 已提交
177
	 */
178
	getTokenStylingDefaultRules(): TokenStylingDefaultRule[];
M
Martin Aeschlimann 已提交
179

180 181 182 183 184
	/**
	 * JSON schema for an object to assign styling to token classifications
	 */
	getTokenStylingSchema(): IJSONSchema;
}
M
Martin Aeschlimann 已提交
185 186 187

class TokenClassificationRegistry implements ITokenClassificationRegistry {

188 189 190
	private readonly _onDidChangeSchema = new Emitter<void>();
	readonly onDidChangeSchema: Event<void> = this._onDidChangeSchema.event;

M
Martin Aeschlimann 已提交
191 192 193 194 195 196 197 198
	private currentTypeNumber = 0;
	private currentModifierBit = 1;

	private tokenTypeById: { [key: string]: TokenTypeOrModifierContribution };
	private tokenModifierById: { [key: string]: TokenTypeOrModifierContribution };

	private tokenStylingDefaultRules: TokenStylingDefaultRule[] = [];

199 200 201
	private tokenStylingSchema: IJSONSchema & { properties: IJSONSchemaMap } = {
		type: 'object',
		properties: {},
202
		additionalProperties: getStylingSchemeEntry(),
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
		definitions: {
			style: {
				type: 'object',
				description: nls.localize('schema.token.settings', 'Colors and styles for the token.'),
				properties: {
					foreground: {
						type: 'string',
						description: nls.localize('schema.token.foreground', 'Foreground color for the token.'),
						format: 'color-hex',
						default: '#ff0000'
					},
					background: {
						type: 'string',
						deprecationMessage: nls.localize('schema.token.background.warning', 'Token background colors are currently not supported.')
					},
					fontStyle: {
						type: 'string',
220
						description: nls.localize('schema.token.fontStyle', 'Font style of the rule: \'italic\', \'bold\' or \'underline\' or a combination. The empty string unsets inherited settings.'),
M
Martin Aeschlimann 已提交
221
						pattern: fontStylePattern,
222 223
						patternErrorMessage: nls.localize('schema.fontStyle.error', 'Font style must be \'italic\', \'bold\' or \'underline\' or a combination. The empty string unsets all styles.'),
						defaultSnippets: [{ label: nls.localize('schema.token.fontStyle.none', 'None (clear inherited style)'), bodyText: '""' }, { body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }]
224 225 226 227 228 229 230 231
					}
				},
				additionalProperties: false,
				defaultSnippets: [{ body: { foreground: '${1:#FF0000}', fontStyle: '${2:bold}' } }]
			}
		}
	};

M
Martin Aeschlimann 已提交
232 233 234 235 236 237 238 239
	constructor() {
		this.tokenTypeById = {};
		this.tokenModifierById = {};

		this.tokenTypeById[TOKEN_TYPE_WILDCARD] = { num: TOKEN_TYPE_WILDCARD_NUM, id: TOKEN_TYPE_WILDCARD, description: '', deprecationMessage: undefined };
	}

	public registerTokenType(id: string, description: string, deprecationMessage?: string): void {
240 241 242 243
		if (!id.match(typeAndModifierIdPattern)) {
			throw new Error('Invalid token type id.');
		}

M
Martin Aeschlimann 已提交
244 245 246
		const num = this.currentTypeNumber++;
		let tokenStyleContribution: TokenTypeOrModifierContribution = { num, id, description, deprecationMessage };
		this.tokenTypeById[id] = tokenStyleContribution;
247 248

		this.tokenStylingSchema.properties[id] = getStylingSchemeEntry(description, deprecationMessage);
M
Martin Aeschlimann 已提交
249 250 251
	}

	public registerTokenModifier(id: string, description: string, deprecationMessage?: string): void {
252 253 254 255
		if (!id.match(typeAndModifierIdPattern)) {
			throw new Error('Invalid token modifier id.');
		}

M
Martin Aeschlimann 已提交
256 257 258 259
		const num = this.currentModifierBit;
		this.currentModifierBit = this.currentModifierBit * 2;
		let tokenStyleContribution: TokenTypeOrModifierContribution = { num, id, description, deprecationMessage };
		this.tokenModifierById[id] = tokenStyleContribution;
260 261

		this.tokenStylingSchema.properties[`*.${id}`] = getStylingSchemeEntry(description, deprecationMessage);
M
Martin Aeschlimann 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
	}

	public getTokenClassification(type: string, modifiers: string[]): TokenClassification | undefined {
		const tokenTypeDesc = this.tokenTypeById[type];
		if (!tokenTypeDesc) {
			return undefined;
		}
		let allModifierBits = 0;
		for (const modifier of modifiers) {
			const tokenModifierDesc = this.tokenModifierById[modifier];
			if (tokenModifierDesc) {
				allModifierBits |= tokenModifierDesc.num;
			}
		}
		return { type: tokenTypeDesc.num, modifiers: allModifierBits };
	}

279 280 281 282 283 284 285 286 287 288 289 290 291 292

	private newMatcher(selector: TokenClassification) {
		const score = getTokenStylingScore(selector);
		return (classification: TokenClassification) => {
			const selectorType = selector.type;
			if (selectorType !== TOKEN_TYPE_WILDCARD_NUM && selectorType !== classification.type) {
				return -1;
			}
			const selectorModifier = selector.modifiers;
			if ((classification.modifiers & selectorModifier) !== selectorModifier) {
				return -1;
			}
			return score;
		};
M
Martin Aeschlimann 已提交
293 294
	}

295 296 297
	public getTokenStylingRule(selector: TokenClassification, value: TokenStyle): TokenStylingRule {
		return {
			match: this.newMatcher(selector),
298 299
			value,
			selector
300 301 302 303 304
		};
	}

	public registerTokenStyleDefault(selector: TokenClassification, defaults: TokenStyleDefaults): void {
		this.tokenStylingDefaultRules.push({ selector, match: this.newMatcher(selector), defaults });
M
Martin Aeschlimann 已提交
305 306
	}

307
	public deregisterTokenStyleDefault(classification: TokenClassification): void {
308
		this.tokenStylingDefaultRules = this.tokenStylingDefaultRules.filter(r => !(r.selector.type === classification.type && r.selector.modifiers === classification.modifiers));
309 310
	}

M
Martin Aeschlimann 已提交
311 312
	public deregisterTokenType(id: string): void {
		delete this.tokenTypeById[id];
313
		delete this.tokenStylingSchema.properties[id];
M
Martin Aeschlimann 已提交
314 315 316 317
	}

	public deregisterTokenModifier(id: string): void {
		delete this.tokenModifierById[id];
318
		delete this.tokenStylingSchema.properties[`*.${id}`];
M
Martin Aeschlimann 已提交
319 320 321 322 323 324 325 326 327 328
	}

	public getTokenTypes(): TokenTypeOrModifierContribution[] {
		return Object.keys(this.tokenTypeById).map(id => this.tokenTypeById[id]);
	}

	public getTokenModifiers(): TokenTypeOrModifierContribution[] {
		return Object.keys(this.tokenModifierById).map(id => this.tokenModifierById[id]);
	}

329 330 331 332
	public getTokenStylingSchema(): IJSONSchema {
		return this.tokenStylingSchema;
	}

333 334 335
	public getTokenStylingDefaultRules(): TokenStylingDefaultRule[] {
		return this.tokenStylingDefaultRules;
	}
M
Martin Aeschlimann 已提交
336

337

M
Martin Aeschlimann 已提交
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
	public toString() {
		let sorter = (a: string, b: string) => {
			let cat1 = a.indexOf('.') === -1 ? 0 : 1;
			let cat2 = b.indexOf('.') === -1 ? 0 : 1;
			if (cat1 !== cat2) {
				return cat1 - cat2;
			}
			return a.localeCompare(b);
		};

		return Object.keys(this.tokenTypeById).sort(sorter).map(k => `- \`${k}\`: ${this.tokenTypeById[k].description}`).join('\n');
	}

}


const tokenClassificationRegistry = new TokenClassificationRegistry();
platform.Registry.add(Extensions.TokenClassificationContribution, tokenClassificationRegistry);

M
Martin Aeschlimann 已提交
357 358 359 360 361
registerDefaultClassifications();

function registerDefaultClassifications(): void {
	function registerTokenType(id: string, description: string, scopesToProbe: ProbeScope[] = [], extendsTC?: string, deprecationMessage?: string): string {
		tokenClassificationRegistry.registerTokenType(id, description, deprecationMessage);
M
Martin Aeschlimann 已提交
362

M
Martin Aeschlimann 已提交
363 364 365 366 367
		if (scopesToProbe || extendsTC) {
			const classification = tokenClassificationRegistry.getTokenClassification(id, []);
			tokenClassificationRegistry.registerTokenStyleDefault(classification!, { scopesToProbe, light: extendsTC, dark: extendsTC, hc: extendsTC });
		}
		return id;
M
Martin Aeschlimann 已提交
368 369
	}

M
Martin Aeschlimann 已提交
370 371 372 373 374 375 376 377 378 379 380
	// default token types

	registerTokenType('comment', nls.localize('comment', "Style for comments."), [['comment']]);
	registerTokenType('string', nls.localize('string', "Style for strings."), [['string']]);
	registerTokenType('keyword', nls.localize('keyword', "Style for keywords."), [['keyword.control']]);
	registerTokenType('number', nls.localize('number', "Style for numbers."), [['constant.numeric']]);
	registerTokenType('regexp', nls.localize('regexp', "Style for expressions."), [['constant.regexp']]);
	registerTokenType('operator', nls.localize('operator', "Style for operators."), [['keyword.operator']]);

	registerTokenType('namespace', nls.localize('namespace', "Style for namespaces."), [['entity.name.namespace']]);

381
	registerTokenType('type', nls.localize('type', "Style for types."), [['entity.name.type'], ['support.type'], ['support.class']]);
M
Martin Aeschlimann 已提交
382
	registerTokenType('struct', nls.localize('struct', "Style for structs."), [['storage.type.struct']], 'type');
383 384 385
	registerTokenType('class', nls.localize('class', "Style for classes."), [['entity.name.type.class']], 'type');
	registerTokenType('interface', nls.localize('interface', "Style for interfaces."), [['entity.name.type.interface']], 'type');
	registerTokenType('enum', nls.localize('enum', "Style for enums."), [['entity.name.type.enum']], 'type');
386
	registerTokenType('typeParameter', nls.localize('typeParameter', "Style for type parameters."), [['entity.name.type', 'meta.type.parameters']], 'type');
M
Martin Aeschlimann 已提交
387 388

	registerTokenType('function', nls.localize('function', "Style for functions"), [['entity.name.function'], ['support.function']]);
389 390
	registerTokenType('member', nls.localize('member', "Style for member"), [['entity.name.function.member'], ['support.function']]);
	registerTokenType('macro', nls.localize('macro', "Style for macros."), [['entity.name.other.preprocessor.macro']], 'function');
M
Martin Aeschlimann 已提交
391 392

	registerTokenType('variable', nls.localize('variable', "Style for variables."), [['variable'], ['entity.name.variable']]);
393 394 395
	registerTokenType('constant', nls.localize('constant', "Style for constants."), [['variable.other.constant']], 'variable');
	registerTokenType('parameter', nls.localize('parameter', "Style for parameters."), [['variable.parameter']], 'variable');
	registerTokenType('property', nls.localize('property', "Style for properties."), [['variable.other.property']], 'variable');
M
Martin Aeschlimann 已提交
396 397 398 399 400 401 402 403 404 405 406 407

	registerTokenType('label', nls.localize('labels', "Style for labels. "), undefined);

	// default token modifiers

	tokenClassificationRegistry.registerTokenModifier('declaration', nls.localize('declaration', "Style for all symbol declarations."), undefined);
	tokenClassificationRegistry.registerTokenModifier('documentation', nls.localize('documentation', "Style to use for references in documentation."), undefined);
	tokenClassificationRegistry.registerTokenModifier('static', nls.localize('static', "Style to use for symbols that are static."), undefined);
	tokenClassificationRegistry.registerTokenModifier('abstract', nls.localize('abstract', "Style to use for symbols that are abstract."), undefined);
	tokenClassificationRegistry.registerTokenModifier('deprecated', nls.localize('deprecated', "Style to use for symbols that are deprecated."), undefined);
	tokenClassificationRegistry.registerTokenModifier('modification', nls.localize('modification', "Style to use for write accesses."), undefined);
	tokenClassificationRegistry.registerTokenModifier('async', nls.localize('async', "Style to use for symbols that are async."), undefined);
408
	tokenClassificationRegistry.registerTokenModifier('readonly', nls.localize('readonly', "Style to use for symbols that are readonly."), undefined);
409 410


M
Martin Aeschlimann 已提交
411 412
}

M
Martin Aeschlimann 已提交
413 414 415 416 417 418 419 420 421
export function getTokenClassificationRegistry(): ITokenClassificationRegistry {
	return tokenClassificationRegistry;
}

function bitCount(u: number) {
	// https://blogs.msdn.microsoft.com/jeuge/2005/06/08/bit-fiddling-3/
	const uCount = u - ((u >> 1) & 0o33333333333) - ((u >> 2) & 0o11111111111);
	return ((uCount + (uCount >> 3)) & 0o30707070707) % 63;
}
M
Martin Aeschlimann 已提交
422 423 424 425

function getTokenStylingScore(classification: TokenClassification) {
	return bitCount(classification.modifiers) + ((classification.type !== TOKEN_TYPE_WILDCARD_NUM) ? 1 : 0);
}
426

427
function getStylingSchemeEntry(description?: string, deprecationMessage?: string): IJSONSchema {
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
	return {
		description,
		deprecationMessage,
		defaultSnippets: [{ body: '${1:#ff0000}' }],
		anyOf: [
			{
				type: 'string',
				format: 'color-hex'
			},
			{
				$ref: '#definitions/style'
			}
		]
	};
}

export const tokenStylingSchemaId = 'vscode://schemas/token-styling';

let schemaRegistry = platform.Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
schemaRegistry.registerSchema(tokenStylingSchemaId, tokenClassificationRegistry.getTokenStylingSchema());

const delayer = new RunOnceScheduler(() => schemaRegistry.notifySchemaChanged(tokenStylingSchemaId), 200);
tokenClassificationRegistry.onDidChangeSchema(() => {
	if (!delayer.isScheduled()) {
		delayer.schedule();
	}
});