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
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
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { Range } from 'vs/editor/common/core/range';
import { ITextModel } from 'vs/editor/common/model';
import { BracketInfo, BracketPairWithMinIndentationInfo } from 'vs/editor/common/textModelBracketPairs';
import { BackgroundTokenizationState, TextModel } from 'vs/editor/common/model/textModel';
import { IModelContentChangedEvent, IModelTokensChangedEvent } from 'vs/editor/common/textModelEvents';
import { ResolvedLanguageConfiguration } from 'vs/editor/common/languages/languageConfigurationRegistry';
import { AstNode, AstNodeKind } from './ast';
import { TextEditInfo } from './beforeEditPositionMapper';
import { LanguageAgnosticBracketTokens } from './brackets';
import { Length, lengthAdd, lengthGreaterThanEqual, lengthLessThanEqual, lengthOfString, lengthsToRange, lengthZero, positionToLength, toLength } from './length';
import { parseDocument } from './parser';
import { DenseKeyProvider } from './smallImmutableSet';
import { FastTokenizer, TextBufferTokenizer } from './tokenizer';
export class BracketPairsTree extends Disposable {
private readonly didChangeEmitter = new Emitter<void>();
/*
There are two trees:
* The initial tree that has no token information and is used for performant initial bracket colorization.
* The tree that used token information to detect bracket pairs.
To prevent flickering, we only switch from the initial tree to tree with token information
when tokenization completes.
Since the text can be edited while background tokenization is in progress, we need to update both trees.
*/
private initialAstWithoutTokens: AstNode | undefined;
private astWithTokens: AstNode | undefined;
private readonly denseKeyProvider = new DenseKeyProvider<string>();
private readonly brackets = new LanguageAgnosticBracketTokens(this.denseKeyProvider, this.getLanguageConfiguration);
public didLanguageChange(languageId: string): boolean {
return this.brackets.didLanguageChange(languageId);
}
public readonly onDidChange = this.didChangeEmitter.event;
public constructor(
private readonly textModel: TextModel,
private readonly getLanguageConfiguration: (languageId: string) => ResolvedLanguageConfiguration
) {
super();
if (textModel.backgroundTokenizationState === BackgroundTokenizationState.Uninitialized) {
// There are no token information yet
const brackets = this.brackets.getSingleLanguageBracketTokens(this.textModel.getLanguageId());
const tokenizer = new FastTokenizer(this.textModel.getValue(), brackets);
this.initialAstWithoutTokens = parseDocument(tokenizer, [], undefined, true);
this.astWithTokens = this.initialAstWithoutTokens;
} else if (textModel.backgroundTokenizationState === BackgroundTokenizationState.Completed) {
// Skip the initial ast, as there is no flickering.
// Directly create the tree with token information.
this.initialAstWithoutTokens = undefined;
this.astWithTokens = this.parseDocumentFromTextBuffer([], undefined, false);
} else if (textModel.backgroundTokenizationState === BackgroundTokenizationState.InProgress) {
this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer([], undefined, true);
this.astWithTokens = this.initialAstWithoutTokens;
}
}
//#region TextModel events
public handleDidChangeBackgroundTokenizationState(): void {
if (this.textModel.backgroundTokenizationState === BackgroundTokenizationState.Completed) {
const wasUndefined = this.initialAstWithoutTokens === undefined;
// Clear the initial tree as we can use the tree with token information now.
this.initialAstWithoutTokens = undefined;
if (!wasUndefined) {
this.didChangeEmitter.fire();
}
}
}
public handleDidChangeTokens({ ranges }: IModelTokensChangedEvent): void {
const edits = ranges.map(r =>
new TextEditInfo(
toLength(r.fromLineNumber - 1, 0),
toLength(r.toLineNumber, 0),
toLength(r.toLineNumber - r.fromLineNumber + 1, 0)
)
);
this.astWithTokens = this.parseDocumentFromTextBuffer(edits, this.astWithTokens, false);
if (!this.initialAstWithoutTokens) {
this.didChangeEmitter.fire();
}
}
public handleContentChanged(change: IModelContentChangedEvent) {
const edits = change.changes.map(c => {
const range = Range.lift(c.range);
return new TextEditInfo(
positionToLength(range.getStartPosition()),
positionToLength(range.getEndPosition()),
lengthOfString(c.text)
);
}).reverse();
this.astWithTokens = this.parseDocumentFromTextBuffer(edits, this.astWithTokens, false);
if (this.initialAstWithoutTokens) {
this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer(edits, this.initialAstWithoutTokens, false);
}
}
//#endregion
/**
* @pure (only if isPure = true)
*/
private parseDocumentFromTextBuffer(edits: TextEditInfo[], previousAst: AstNode | undefined, immutable: boolean): AstNode {
// Is much faster if `isPure = false`.
const isPure = false;
const previousAstClone = isPure ? previousAst?.deepClone() : previousAst;
const tokenizer = new TextBufferTokenizer(this.textModel, this.brackets);
const result = parseDocument(tokenizer, edits, previousAstClone, immutable);
return result;
}
public getBracketsInRange(range: Range): BracketInfo[] {
const startOffset = toLength(range.startLineNumber - 1, range.startColumn - 1);
const endOffset = toLength(range.endLineNumber - 1, range.endColumn - 1);
const result = new Array<BracketInfo>();
const node = this.initialAstWithoutTokens || this.astWithTokens!;
collectBrackets(node, lengthZero, node.length, startOffset, endOffset, result, 0, new Map());
return result;
}
public getBracketPairsInRange(range: Range, includeMinIndentation: boolean): BracketPairWithMinIndentationInfo[] {
const result = new Array<BracketPairWithMinIndentationInfo>();
const startLength = positionToLength(range.getStartPosition());
const endLength = positionToLength(range.getEndPosition());
const node = this.initialAstWithoutTokens || this.astWithTokens!;
const context = new CollectBracketPairsContext(result, includeMinIndentation, this.textModel);
collectBracketPairs(node, lengthZero, node.length, startLength, endLength, context, 0, new Map());
return result;
}
}
function collectBrackets(
node: AstNode,
nodeOffsetStart: Length,
nodeOffsetEnd: Length,
startOffset: Length,
endOffset: Length,
result: BracketInfo[],
level: number,
levelPerBracketType: Map<string, number>
): void {
if (node.kind === AstNodeKind.List) {
for (const child of node.children) {
nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
if (
lengthLessThanEqual(nodeOffsetStart, endOffset) &&
lengthGreaterThanEqual(nodeOffsetEnd, startOffset)
) {
collectBrackets(
child,
nodeOffsetStart,
nodeOffsetEnd,
startOffset,
endOffset,
result,
level,
levelPerBracketType
);
}
nodeOffsetStart = nodeOffsetEnd;
}
} else if (node.kind === AstNodeKind.Pair) {
let levelPerBracket = 0;
if (levelPerBracketType) {
let existing = levelPerBracketType.get(node.openingBracket.text);
if (existing === undefined) {
existing = 0;
}
levelPerBracket = existing;
existing++;
levelPerBracketType.set(node.openingBracket.text, existing);
}
// Don't use node.children here to improve performance
{
const child = node.openingBracket;
nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
if (
lengthLessThanEqual(nodeOffsetStart, endOffset) &&
lengthGreaterThanEqual(nodeOffsetEnd, startOffset)
) {
const range = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
result.push(
new BracketInfo(range, level, levelPerBracket, !node.closingBracket)
);
}
nodeOffsetStart = nodeOffsetEnd;
}
if (node.child) {
const child = node.child;
nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
if (
lengthLessThanEqual(nodeOffsetStart, endOffset) &&
lengthGreaterThanEqual(nodeOffsetEnd, startOffset)
) {
collectBrackets(
child,
nodeOffsetStart,
nodeOffsetEnd,
startOffset,
endOffset,
result,
level + 1,
levelPerBracketType
);
}
nodeOffsetStart = nodeOffsetEnd;
}
if (node.closingBracket) {
const child = node.closingBracket;
nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
if (
lengthLessThanEqual(nodeOffsetStart, endOffset) &&
lengthGreaterThanEqual(nodeOffsetEnd, startOffset)
) {
const range = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
result.push(new BracketInfo(range, level, levelPerBracket, false));
}
nodeOffsetStart = nodeOffsetEnd;
}
if (levelPerBracketType) {
levelPerBracketType.set(node.openingBracket.text, levelPerBracket);
}
} else if (node.kind === AstNodeKind.UnexpectedClosingBracket) {
const range = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
result.push(new BracketInfo(range, level - 1, 0, true));
} else if (node.kind === AstNodeKind.Bracket) {
const range = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
result.push(new BracketInfo(range, level - 1, 0, false));
}
}
class CollectBracketPairsContext {
constructor(
public readonly result: BracketPairWithMinIndentationInfo[],
public readonly includeMinIndentation: boolean,
public readonly textModel: ITextModel,
) {
}
}
function collectBracketPairs(
node: AstNode,
nodeOffsetStart: Length,
nodeOffsetEnd: Length,
startOffset: Length,
endOffset: Length,
context: CollectBracketPairsContext,
level: number,
levelPerBracketType: Map<string, number>
) {
if (node.kind === AstNodeKind.Pair) {
let levelPerBracket = 0;
if (levelPerBracketType) {
let existing = levelPerBracketType.get(node.openingBracket.text);
if (existing === undefined) {
existing = 0;
}
levelPerBracket = existing;
existing++;
levelPerBracketType.set(node.openingBracket.text, existing);
}
const openingBracketEnd = lengthAdd(nodeOffsetStart, node.openingBracket.length);
let minIndentation = -1;
if (context.includeMinIndentation) {
minIndentation = node.computeMinIndentation(
nodeOffsetStart,
context.textModel
);
}
context.result.push(
new BracketPairWithMinIndentationInfo(
lengthsToRange(nodeOffsetStart, nodeOffsetEnd),
lengthsToRange(nodeOffsetStart, openingBracketEnd),
node.closingBracket
? lengthsToRange(
lengthAdd(openingBracketEnd, node.child?.length || lengthZero),
nodeOffsetEnd
)
: undefined,
level,
levelPerBracket,
minIndentation
)
);
nodeOffsetStart = openingBracketEnd;
if (node.child) {
const child = node.child;
nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
if (
lengthLessThanEqual(nodeOffsetStart, endOffset) &&
lengthGreaterThanEqual(nodeOffsetEnd, startOffset)
) {
collectBracketPairs(
child,
nodeOffsetStart,
nodeOffsetEnd,
startOffset,
endOffset,
context,
level + 1,
levelPerBracketType
);
}
}
if (levelPerBracketType) {
levelPerBracketType.set(node.openingBracket.text, levelPerBracket);
}
} else {
let curOffset = nodeOffsetStart;
for (const child of node.children) {
const childOffset = curOffset;
curOffset = lengthAdd(curOffset, child.length);
if (
lengthLessThanEqual(childOffset, endOffset) &&
lengthLessThanEqual(startOffset, curOffset)
) {
collectBracketPairs(
child,
childOffset,
curOffset,
startOffset,
endOffset,
context,
level,
levelPerBracketType
);
}
}
}
}
|