tokenClassificationRegistry.ts 15.1 KB
Newer Older
M
Martin Aeschlimann 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 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 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
/*---------------------------------------------------------------------------------------------
 *  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';

//  ------ API types

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

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

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

export type ProbeScope = string[];

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

export interface TokenStyleDefaults {
	scopesToProbe: ProbeScope[];
	light: TokenStyleValue | null;
	dark: TokenStyleValue | null;
	hc: TokenStyleValue | null;
}

export interface TokenStylingDefaultRule {
	classification: TokenClassification;
	matchScore: number;
	defaults: TokenStyleDefaults;
}

export interface TokenStylingRule {
	classification: TokenClassification;
	matchScore: number;
	value: TokenStyle;
}

/**
 * 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 {

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

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

M
Martin Aeschlimann 已提交
109 110
	getTokenStylingRule(classification: TokenClassification | string | undefined, value: TokenStyle): TokenStylingRule | undefined;

M
Martin Aeschlimann 已提交
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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
	/**
	 * Register a TokenStyle default to the registry.
	 * @param selector The rule selector
	 * @param defaults The default values
	 */
	registerTokenStyleDefault(selector: TokenClassification, defaults: TokenStyleDefaults): void;

	/**
	 * 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[];

	/**
	 * Resolves a token classification against the given rules and default rules from the registry.
	 */
	resolveTokenStyle(classification: TokenClassification, themingRules: TokenStylingRule[], useDefault: boolean, theme: ITheme): TokenStyle | undefined;
}



class TokenClassificationRegistry implements ITokenClassificationRegistry {

	private currentTypeNumber = 0;
	private currentModifierBit = 1;

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

	private tokenStylingDefaultRules: TokenStylingDefaultRule[] = [];

	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 {
		const num = this.currentTypeNumber++;
		let tokenStyleContribution: TokenTypeOrModifierContribution = { num, id, description, deprecationMessage };
		this.tokenTypeById[id] = tokenStyleContribution;
	}

	public registerTokenModifier(id: string, description: string, deprecationMessage?: string): void {
		const num = this.currentModifierBit;
		this.currentModifierBit = this.currentModifierBit * 2;
		let tokenStyleContribution: TokenTypeOrModifierContribution = { num, id, description, deprecationMessage };
		this.tokenModifierById[id] = tokenStyleContribution;
	}

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

	public getTokenClassificationFromString(str: TokenClassificationString): TokenClassification | undefined {
		const parts = str.split('.');
		const type = parts.shift();
		if (type) {
			return this.getTokenClassification(type, parts);
		}
		return undefined;
	}

M
Martin Aeschlimann 已提交
200 201 202 203 204 205 206 207 208 209
	public getTokenStylingRule(classification: TokenClassification | string | undefined, value: TokenStyle): TokenStylingRule | undefined {
		if (typeof classification === 'string') {
			classification = this.getTokenClassificationFromString(classification);
		}
		if (classification) {
			return { classification, matchScore: getTokenStylingScore(classification), value };
		}
		return undefined;
	}

M
Martin Aeschlimann 已提交
210
	public registerTokenStyleDefault(classification: TokenClassification, defaults: TokenStyleDefaults): void {
M
Martin Aeschlimann 已提交
211
		this.tokenStylingDefaultRules.push({ classification, matchScore: getTokenStylingScore(classification), defaults });
M
Martin Aeschlimann 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
	}

	public deregisterTokenType(id: string): void {
		delete this.tokenTypeById[id];
	}

	public deregisterTokenModifier(id: string): void {
		delete this.tokenModifierById[id];
	}

	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]);
	}

	public resolveTokenStyle(classification: TokenClassification, themingRules: TokenStylingRule[], useDefault: boolean, theme: ITheme): TokenStyle | undefined {
		let result: any = {
232 233 234 235
			foreground: undefined,
			bold: undefined,
			underline: undefined,
			italic: undefined
M
Martin Aeschlimann 已提交
236 237 238 239 240 241 242 243 244
		};
		let score = {
			foreground: -1,
			bold: -1,
			underline: -1,
			italic: -1
		};

		function _processStyle(matchScore: number, style: TokenStyle) {
M
Martin Aeschlimann 已提交
245 246 247 248 249
			if (style.foreground && score.foreground <= matchScore) {
				score.foreground = matchScore;
				result.foreground = style.foreground;
			}
			for (let p of ['bold', 'underline', 'italic']) {
M
Martin Aeschlimann 已提交
250 251
				const property = p as keyof TokenStyle;
				const info = style[property];
M
Martin Aeschlimann 已提交
252
				if (info !== undefined) {
253
					if (score[property] <= matchScore) {
M
Martin Aeschlimann 已提交
254 255 256
						score[property] = matchScore;
						result[property] = info;
					}
M
Martin Aeschlimann 已提交
257 258 259 260
				}
			}
		}
		if (useDefault) {
261
			for (const rule of this.tokenStylingDefaultRules) {
M
Martin Aeschlimann 已提交
262 263 264 265 266 267 268 269 270 271
				const matchScore = match(rule, classification);
				if (matchScore >= 0) {
					let style = theme.resolveScopes(rule.defaults.scopesToProbe);
					if (!style) {
						style = this.resolveTokenStyleValue(rule.defaults[theme.type], theme);
					}
					if (style) {
						_processStyle(matchScore, style);
					}
				}
272 273 274 275 276 277 278
			}
		}
		for (const rule of themingRules) {
			const matchScore = match(rule, classification);
			if (matchScore >= 0) {
				_processStyle(matchScore, rule.value);
			}
M
Martin Aeschlimann 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
		}
		return TokenStyle.fromData(result);
	}

	/**
	 * @param tokenStyleValue Resolve a tokenStyleValue in the context of a theme
	 */
	private resolveTokenStyleValue(tokenStyleValue: TokenStyleValue | null, theme: ITheme): TokenStyle | undefined {
		if (tokenStyleValue === null) {
			return undefined;
		} else if (typeof tokenStyleValue === 'string') {
			const classification = this.getTokenClassificationFromString(tokenStyleValue);
			if (classification) {
				return theme.getTokenStyle(classification);
			}
		} else if (typeof tokenStyleValue === 'object') {
			return tokenStyleValue;
		}
		return undefined;
	}


	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');
	}

}

function match(themeSelector: TokenStylingRule | TokenStylingDefaultRule, classification: TokenClassification): number {
	const selectorType = themeSelector.classification.type;
M
Martin Aeschlimann 已提交
318
	if (selectorType !== TOKEN_TYPE_WILDCARD_NUM && selectorType !== classification.type) {
M
Martin Aeschlimann 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331
		return -1;
	}
	const selectorModifier = themeSelector.classification.modifiers;
	if ((classification.modifiers & selectorModifier) !== selectorModifier) {
		return -1;
	}
	return themeSelector.matchScore;
}


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

M
Martin Aeschlimann 已提交
332
export function registerTokenType(id: string, description: string, scopesToProbe: ProbeScope[] = [], extendsTC: string | null = null, deprecationMessage?: string): string {
M
Martin Aeschlimann 已提交
333 334
	tokenClassificationRegistry.registerTokenType(id, description, deprecationMessage);

M
Martin Aeschlimann 已提交
335
	if (scopesToProbe || extendsTC) {
M
Martin Aeschlimann 已提交
336
		const classification = tokenClassificationRegistry.getTokenClassification(id, []);
M
Martin Aeschlimann 已提交
337
		tokenClassificationRegistry.registerTokenStyleDefault(classification!, { scopesToProbe, light: extendsTC, dark: extendsTC, hc: extendsTC });
M
Martin Aeschlimann 已提交
338 339 340 341
	}
	return id;
}

M
Martin Aeschlimann 已提交
342 343 344 345 346
export function registerTokenModifier(id: string, description: string, deprecationMessage?: string): string {
	tokenClassificationRegistry.registerTokenModifier(id, description, deprecationMessage);
	return id;
}

M
Martin Aeschlimann 已提交
347 348 349 350
export function getTokenClassificationRegistry(): ITokenClassificationRegistry {
	return tokenClassificationRegistry;
}

M
Martin Aeschlimann 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
export const comments = registerTokenType('comments', nls.localize('comments', "Token style for comments."), [['comment']]);
export const strings = registerTokenType('strings', nls.localize('strings', "Token style for strings."), [['string']]);
export const keywords = registerTokenType('keywords', nls.localize('keywords', "Token style for keywords."), [['keyword.control']]);
export const numbers = registerTokenType('numbers', nls.localize('numbers', "Token style for numbers."), [['constant.numeric']]);
export const regexp = registerTokenType('regexp', nls.localize('regexp', "Token style for regular expressions."), [['constant.regexp']]);
export const operators = registerTokenType('operators', nls.localize('operator', "Token style for operators."), [['keyword.operator']]);

export const namespaces = registerTokenType('namespaces', nls.localize('namespace', "Token style for namespaces."), [['entity.name.namespace']]);

export const types = registerTokenType('types', nls.localize('types', "Token style for types."), [['entity.name.type'], ['entity.name.class'], ['support.type'], ['support.class']]);
export const structs = registerTokenType('structs', nls.localize('struct', "Token style for struct."), [['storage.type.struct']], types);
export const classes = registerTokenType('classes', nls.localize('class', "Token style for classes."), [['ntity.name.class']], types);
export const interfaces = registerTokenType('interfaces', nls.localize('interface', "Token style for interfaces."), undefined, types);
export const enums = registerTokenType('enums', nls.localize('enum', "Token style for enums."), undefined, types);
export const parameterTypes = registerTokenType('parameterTypes', nls.localize('parameterType', "Token style for parameterTypes."), undefined, types);

export const functions = registerTokenType('functions', nls.localize('functions', "Token style for functions."), [['entity.name.function'], ['support.function']]);
export const macros = registerTokenType('macros', nls.localize('macro', "Token style for macros."), undefined, functions);

export const variables = registerTokenType('variables', nls.localize('variables', "Token style for variables."), [['variable'], ['entity.name.variable']]);
export const constants = registerTokenType('constants', nls.localize('constants', "Token style for constants."), undefined, variables);
export const parameters = registerTokenType('parameters', nls.localize('parameters', "Token style for parameters."), undefined, variables);
export const property = registerTokenType('properties', nls.localize('properties', "Token style for properties."), undefined, variables);

export const labels = registerTokenType('labels', nls.localize('labels', "Token style for labels."), undefined);

export const m_declaration = registerTokenModifier('declaration', nls.localize('declaration', "Token modifier for declarations."), undefined);
export const m_documentation = registerTokenModifier('documentation', nls.localize('documentation', "Token modifier for documentation."), undefined);
export const m_member = registerTokenModifier('member', nls.localize('member', "Token modifier for member."), undefined);
export const m_static = registerTokenModifier('static', nls.localize('static', "Token modifier for statics."), undefined);
export const m_abstract = registerTokenModifier('abstract', nls.localize('abstract', "Token modifier for abstracts."), undefined);
export const m_deprecated = registerTokenModifier('deprecated', nls.localize('deprecated', "Token modifier for deprecated."), undefined);
export const m_modification = registerTokenModifier('modification', nls.localize('modification', "Token modifier for modification."), undefined);
export const m_async = registerTokenModifier('async', nls.localize('async', "Token modifier for async."), undefined);
M
Martin Aeschlimann 已提交
385 386 387 388 389 390

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 已提交
391 392 393 394

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