]> git.lizzy.rs Git - rust.git/blob - editors/code/src/scopes_mapper.ts
Fix https://github.com/rust-analyzer/rust-analyzer/pull/2061#discussion_r348716036
[rust.git] / editors / code / src / scopes_mapper.ts
1 import * as vscode from 'vscode';
2 import { TextMateRuleSettings } from './scopes';
3
4 let mappings = new Map<string, string[]>();
5
6 const defaultMapping = new Map<string, string[]>([
7     [
8         'comment',
9         [
10             'comment',
11             'comment.block',
12             'comment.line',
13             'comment.block.documentation',
14         ],
15     ],
16     ['string', ['string']],
17     ['keyword', ['keyword']],
18     ['keyword.control', ['keyword.control', 'keyword', 'keyword.other']],
19     [
20         'keyword.unsafe',
21         ['storage.modifier', 'keyword.other', 'keyword.control', 'keyword'],
22     ],
23     ['function', ['entity.name.function']],
24     ['parameter', ['variable.parameter']],
25     ['constant', ['constant', 'variable']],
26     ['type', ['entity.name.type']],
27     ['builtin', ['variable.language', 'support.type', 'support.type']],
28     ['text', ['string', 'string.quoted', 'string.regexp']],
29     ['attribute', ['keyword']],
30     ['literal', ['string', 'string.quoted', 'string.regexp']],
31     ['macro', ['entity.name.function', 'keyword.other', 'entity.name.macro']],
32     ['variable', ['variable']],
33     ['variable.mut', ['variable', 'storage.modifier']],
34     [
35         'field',
36         [
37             'variable.object.property',
38             'meta.field.declaration',
39             'meta.definition.property',
40             'variable.other',
41         ],
42     ],
43     ['module', ['entity.name.section', 'entity.other']],
44 ]);
45
46 export function find(scope: string): string[] {
47     return mappings.get(scope) || [];
48 }
49
50 export function toRule(
51     scope: string,
52     intoRule: (scope: string) => TextMateRuleSettings | undefined,
53 ): TextMateRuleSettings | undefined {
54     return find(scope)
55         .map(intoRule)
56         .filter(rule => rule !== undefined)[0];
57 }
58
59 function isString(value: any): value is string {
60     return typeof value === 'string';
61 }
62
63 function isArrayOfString(value: any): value is string[] {
64     return Array.isArray(value) && value.every(item => isString(item));
65 }
66
67 export function load() {
68     const rawConfig: { [key: string]: any } =
69         vscode.workspace
70             .getConfiguration('rust-analyzer')
71             .get('scopeMappings') || {};
72
73     mappings = Object.entries(rawConfig)
74         .filter(([_, value]) => isString(value) || isArrayOfString(value))
75         .reduce((list, [key, value]: [string, string | string[]]) => {
76             return list.set(key, isString(value) ? [value] : value);
77         }, defaultMapping);
78 }