-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathcomputation.go
More file actions
535 lines (480 loc) · 15.6 KB
/
Copy pathcomputation.go
File metadata and controls
535 lines (480 loc) · 15.6 KB
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
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
385
386
387
388
389
390
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
444
445
446
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
package parser
// ComputedToken is a token recognized by a computation.
type ComputedToken struct {
// Offset is the token's start position,
// defined relative to the computation's start position.
Offset uint64
Length uint64
Role TokenRole
}
// computation is a result produced by a parser.
// computations are composable, so part of one computation
// can be re-used when re-parsing an edited text.
type computation struct {
readLength uint64
consumedLength uint64
treeHeight uint64
startState State
endState State
tokens []ComputedToken // Only in leaves.
leftChild *computation
rightChild *computation
}
// newComputation constructs a computation.
// readLength is the number of runes read by the parser,
// and consumedLength is the number of runes consumed by the parser.
// The tokens slice contains any tokens recognized by the parser;
// these must have non-zero length, be ordered sequentially by start position,
// and be non-overlapping.
func newComputation(
readLength uint64,
consumedLength uint64,
startState State,
endState State,
tokens []ComputedToken,
) *computation {
if consumedLength == 0 {
panic("computation must consume at least one rune")
}
if consumedLength > readLength {
panic("Consumed length must be less than or equal to read length")
}
var lastEndPos uint64
for _, tok := range tokens {
if tok.Length == 0 {
panic("Token must have non-zero length")
}
if tok.Offset < lastEndPos {
panic("Token must be sequential and non-overlapping")
}
tokEndPos := tok.Offset + tok.Length
if tokEndPos > consumedLength {
panic("Token length must be less than consumed length")
}
lastEndPos = tokEndPos
}
return &computation{
readLength: readLength,
consumedLength: consumedLength,
treeHeight: 1,
startState: startState,
endState: endState,
tokens: tokens,
}
}
// ReadLength returns the number of runes read to produce this computation.
func (c *computation) ReadLength() uint64 {
if c == nil {
return 0
} else {
return c.readLength
}
}
// ConsumedLength returns the number of runes consumed to produce this computation.
func (c *computation) ConsumedLength() uint64 {
if c == nil {
return 0
} else {
return c.consumedLength
}
}
// TreeHeight returns the height of the computation tree.
func (c *computation) TreeHeight() uint64 {
if c == nil {
return 0
} else {
return c.treeHeight
}
}
// StartState returns the parse state at the start of the computation.
func (c *computation) StartState() State {
if c == nil {
return EmptyState{}
}
return c.startState
}
// EndState returns the parse state at the end of the computation.
func (c *computation) EndState() State {
if c == nil {
return EmptyState{}
}
return c.endState
}
// Append appends one computation after another computation.
// The positions of the computations and tokens in the second computation
// are "shifted" to start immediately after the end (consumed length) of
// the first computation.
func (c *computation) Append(other *computation) *computation {
if c == nil {
return other
} else if other == nil {
return c
}
// This is the AVL join algorithm from
// Blelloch, G. E., Ferizovic, D., & Sun, Y. (2016). Just join for parallel ordered sets.
// In Proceedings of the 28th ACM Symposium on Parallelism in Algorithms and Architectures.
h1, h2 := c.TreeHeight(), other.TreeHeight()
if h1 == h2 {
return computationFromChildren(c, other)
} else if h1 < h2 {
return other.prependSubtree(c)
} else {
return c.appendSubtree(other)
}
}
// prependSubtree inserts a computation *before* a given computation,
// rebalancing the tree if necessary (AVL balance invariant).
// This assumes that both computations are non-nil.
func (c *computation) prependSubtree(other *computation) *computation {
if c.leftChild.TreeHeight() <= other.TreeHeight()+1 {
// Insert the new tree as a sibling of a left child with approximately the same height.
newLeft := computationFromChildren(other, c.leftChild)
if newLeft.TreeHeight() <= c.rightChild.TreeHeight()+1 {
// The new tree already satisfies the AVL balance invariant.
return computationFromChildren(newLeft, c.rightChild)
} else {
// The new tree violates the AVL balance invariant.
// Double-rotate to restore balance.
return computationFromChildren(newLeft.rotateLeft(), c.rightChild).rotateRight()
}
}
// Recursively search for a sibling with approximately the same height as the inserted subtree.
newLeft := c.leftChild.prependSubtree(other)
newRoot := computationFromChildren(newLeft, c.rightChild)
if newLeft.TreeHeight() <= c.rightChild.TreeHeight()+1 {
// The new tree already satisfies the AVL balance invariant.
return newRoot
} else {
// The new tree violates the AVL balance invariant.
// Rotate to restore balance.
return newRoot.rotateRight()
}
}
// appendSubtree inserts a computation *after* a given computation,
// rebalancing the tree if necessary (AVL balance invariant).
// This assumes that both computations are non-nil.
func (c *computation) appendSubtree(other *computation) *computation {
if c.rightChild.TreeHeight() <= other.TreeHeight()+1 {
// Insert the new tree as a sibling of a right child with approximately the same height.
newRight := computationFromChildren(c.rightChild, other)
if newRight.TreeHeight() <= c.leftChild.TreeHeight()+1 {
// The new tree already satisfies the AVL balance invariant.
return computationFromChildren(c.leftChild, newRight)
} else {
// The new tree violates the AVL balance invariant.
// Double-rotate to restore balance.
return computationFromChildren(c.leftChild, newRight.rotateRight()).rotateLeft()
}
}
// Recursively search for a sibling with approximately the same height as the inserted subtree.
newRight := c.rightChild.appendSubtree(other)
newRoot := computationFromChildren(c.leftChild, newRight)
if newRight.TreeHeight() <= c.leftChild.TreeHeight()+1 {
// The new tree already satisfies the AVL balance invariant.
return newRoot
} else {
// The new tree violates the AVL balance invariant.
// Rotate to restore balance.
return newRoot.rotateLeft()
}
}
func (c *computation) rotateLeft() *computation {
if c == nil || c.rightChild == nil {
// Can't rotate left for an empty tree or tree without a right child.
return c
}
// [x] [y']
// / \ / \
// [q] [y] ==> [x'] [s]
// / \ / \
// [r] [s] [q] [r]
x := c
y := x.rightChild
q := x.leftChild
r := y.leftChild
s := y.rightChild
if r == nil && s == nil {
// If y is a leaf, then we can't rotate it into an inner node
// without losing information about the original computation,
// so copy y into the leaf node position.
// This does not change the height of the resulting tree.
s = y
}
return computationFromChildren(computationFromChildren(q, r), s)
}
func (c *computation) rotateRight() *computation {
if c == nil || c.leftChild == nil {
// Can't rotate right for an empty tree or tree without a left child.
return c
}
// [x] [y']
// / \ / \
// [y] [s] ==> [q] [x']
// / \ / \
// [q] [r] [r] [s]
x := c
y := x.leftChild
q := y.leftChild
r := y.rightChild
s := x.rightChild
if q == nil && r == nil {
// If y is a leaf, then we can't rotate it into an inner node
// without losing information about the original computation,
// so copy y into the leaf node position.
// This does not change the height of the resulting tree.
q = y
}
return computationFromChildren(q, computationFromChildren(r, s))
}
func computationFromChildren(leftChild, rightChild *computation) *computation {
var startState, endState State
if leftChild == nil && rightChild == nil {
return nil
} else if leftChild == nil {
startState, endState = rightChild.StartState(), rightChild.EndState()
} else if rightChild == nil {
startState, endState = leftChild.StartState(), leftChild.EndState()
} else {
startState, endState = leftChild.StartState(), rightChild.EndState()
}
maxChildTreeHeight := leftChild.TreeHeight()
if rightChild.TreeHeight() > maxChildTreeHeight {
maxChildTreeHeight = rightChild.TreeHeight()
}
// Right child starts reading after last character consumed by left child.
maxReadLength := leftChild.ConsumedLength() + rightChild.ReadLength()
if leftChild.ReadLength() > maxReadLength {
maxReadLength = leftChild.ReadLength()
}
return &computation{
readLength: maxReadLength,
consumedLength: leftChild.ConsumedLength() + rightChild.ConsumedLength(),
treeHeight: maxChildTreeHeight + 1,
startState: startState,
endState: endState,
leftChild: leftChild,
rightChild: rightChild,
}
}
// LargestMatchingSubComputation returns the largest sub-computation that has both
// (1) a read range contained within the requested range and (2) a start state
// that matches the requested state.
// This is used to find a re-usable computation that is still valid after an edit.
// A computation is considered *invalid* if it read some text that was edited,
// so if the computation did *not* read any edited text, it's definitely still valid.
func (c *computation) LargestMatchingSubComputation(
rangeStartPos, rangeEndPos uint64,
state State,
) *computation {
return c.largestSubComputationInRange(0, c.readLength, rangeStartPos, rangeEndPos, state)
}
func (c *computation) largestSubComputationInRange(
readStartPos, readEndPos uint64,
rangeStartPos, rangeEndPos uint64,
state State,
) *computation {
// First, search until we find a sub-computation with the requested start position.
if readStartPos != rangeStartPos {
if c.leftChild == nil && c.rightChild == nil {
return nil
} else if c.leftChild == nil {
// Right child has no sibling, so there's only one direction to search.
return c.rightChild.largestSubComputationInRange(
readStartPos,
readEndPos,
rangeStartPos,
rangeEndPos,
state,
)
} else if c.rightChild == nil {
// Left child has no sibling, so there's only one direction to search.
return c.leftChild.largestSubComputationInRange(
readStartPos,
readEndPos,
rangeStartPos,
rangeEndPos,
state,
)
} else if rangeStartPos < readStartPos+c.leftChild.consumedLength {
return c.leftChild.largestSubComputationInRange(
readStartPos,
readStartPos+c.leftChild.readLength,
rangeStartPos,
rangeEndPos,
state,
)
} else {
// Right child starts reading after last character consumed by left child.
newReadStartPos := readStartPos + c.leftChild.consumedLength
newReadEndPos := newReadStartPos + c.rightChild.readLength
return c.rightChild.largestSubComputationInRange(
newReadStartPos,
newReadEndPos,
rangeStartPos,
rangeEndPos,
state,
)
}
}
// Keep searching smaller and smaller sub-computations with the requested start position
// until we find one that didn't read past the end position.
if readEndPos > rangeEndPos {
if c.leftChild == nil && c.rightChild == nil {
return nil
} else if c.leftChild == nil {
// Right child has no sibling, so there's only one direction to search.
return c.rightChild.largestSubComputationInRange(
readStartPos,
readEndPos,
rangeStartPos,
rangeEndPos,
state,
)
} else if c.rightChild == nil {
// Left child has no sibling, so there's only one direction to search.
return c.leftChild.largestSubComputationInRange(
readStartPos,
readEndPos,
rangeStartPos,
rangeEndPos,
state,
)
} else {
return c.leftChild.largestSubComputationInRange(
readStartPos,
readStartPos+c.leftChild.readLength,
rangeStartPos,
rangeEndPos,
state,
)
}
}
// If the start state doesn't match, we can't re-use this computation.
if !c.StartState().Equals(state) {
return nil
}
return c
}
// TokenAtPosition returns the token containing a position.
// If no such token exists, it returns the Token zero value.
func (c *computation) TokenAtPosition(pos uint64) Token {
var offset uint64
for c != nil && pos >= offset && pos < offset+c.consumedLength {
// If this is a leaf computation, it will have tokens.
// Check if any of them contain the target position.
for _, computedToken := range c.tokens {
token := Token{
StartPos: offset + computedToken.Offset,
EndPos: offset + computedToken.Offset + computedToken.Length,
Role: computedToken.Role,
}
if pos >= token.StartPos && pos < token.EndPos {
// Found a token at the target position.
return token
}
}
if c.leftChild != nil && pos < offset+c.leftChild.consumedLength {
// Left child contains the position, so recurse left.
c = c.leftChild
} else {
// Otherwise, recurse right.
if c.leftChild != nil {
offset += c.leftChild.consumedLength
}
c = c.rightChild
}
}
// No token found at the target position.
return Token{}
}
// TokensIntersectingRange returns tokens that overlap the interval [startPos, endPos)
func (c *computation) TokensIntersectingRange(startPos, endPos uint64) []Token {
if c == nil {
return nil
}
var result []Token
type stackItem struct {
offset uint64
c *computation
}
item := stackItem{offset: 0, c: c}
stack := []stackItem{item}
for len(stack) > 0 {
item, stack = stack[len(stack)-1], stack[0:len(stack)-1]
offset, c := item.offset, item.c
if endPos <= offset || offset+c.consumedLength <= startPos {
// The range doesn't intersect this computation or any of its children.
continue
}
// Find all tokens from this computation that intersect the range
// (only leaf nodes have tokens).
for _, computedToken := range c.tokens {
tok := Token{
StartPos: offset + computedToken.Offset,
EndPos: offset + computedToken.Offset + computedToken.Length,
Role: computedToken.Role,
}
if !(endPos <= tok.StartPos || startPos >= tok.EndPos) {
result = append(result, tok)
}
}
// Add tokens from the right child, if it exists.
// Push this onto the stack first so tokens are added
// AFTER tokens from the left child.
if c.rightChild != nil {
newOffset := offset
if c.leftChild != nil {
newOffset += c.leftChild.consumedLength
}
stack = append(stack, stackItem{
offset: newOffset,
c: c.rightChild,
})
}
// Add tokens from the left child, if it exists.
if c.leftChild != nil {
stack = append(stack, stackItem{
offset: offset,
c: c.leftChild,
})
}
}
return result
}
// concatLeafComputations combines leaf computations into a single computation.
// A leaf computation is a computation constructed by newComputation
// without any other computations appended.
// This produces the same result as sequentially appending the computations,
// but does so more efficiently.
func concatLeafComputations(computations []*computation) *computation {
if len(computations) == 0 {
return nil
}
for _, c := range computations {
if c.TreeHeight() > 1 {
panic("Expected computation to be a leaf")
}
}
// Construct the tree layer-by-layer. This is cheaper than
// calling Append repeatedly, because every node we allocate
// will be used in the final tree. Additionally, we avoid
// the cost of rebalancing the tree since it's balanced by construction.
nextComputations := make([]*computation, 0, len(computations)/2+1)
for len(computations) > 1 {
var i int
for i < len(computations) {
if i+1 < len(computations) {
c1, c2 := computations[i], computations[i+1]
nextComputations = append(nextComputations, c1.Append(c2))
i += 2
} else {
c := computations[i]
nextComputations = append(nextComputations, c)
i++
}
}
computations = nextComputations
nextComputations = nextComputations[:0]
}
return computations[0]
}