Repository navigation
Expand file tree
/
Copy pathhighlight.py
More file actions
729 lines (624 loc) · 21.9 KB
/
Copy pathhighlight.py
File metadata and controls
729 lines (624 loc) · 21.9 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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
import contextlib
import functools
import json
import os.path
from typing import Any
from typing import Dict
from typing import FrozenSet
from typing import List
from typing import Match
from typing import NamedTuple
from typing import Optional
from typing import Tuple
from babi._types import Protocol
from babi.fdict import FDict
from babi.reg import _Reg
from babi.reg import _RegSet
from babi.reg import ERR_REG
from babi.reg import make_reg
from babi.reg import make_regset
Scope = Tuple[str, ...]
Regions = Tuple['Region', ...]
Captures = Tuple[Tuple[int, '_Rule'], ...]
def _split_name(s: Optional[str]) -> Tuple[str, ...]:
if s is None:
return ()
else:
return tuple(s.split())
class _Rule(Protocol):
"""hax for recursive types python/mypy#731"""
@property
def name(self) -> Tuple[str, ...]: ...
@property
def match(self) -> Optional[str]: ...
@property
def begin(self) -> Optional[str]: ...
@property
def end(self) -> Optional[str]: ...
@property
def while_(self) -> Optional[str]: ...
@property
def content_name(self) -> Tuple[str, ...]: ...
@property
def captures(self) -> Captures: ...
@property
def begin_captures(self) -> Captures: ...
@property
def end_captures(self) -> Captures: ...
@property
def while_captures(self) -> Captures: ...
@property
def include(self) -> Optional[str]: ...
@property
def patterns(self) -> 'Tuple[_Rule, ...]': ...
class Rule(NamedTuple):
name: Tuple[str, ...]
match: Optional[str]
begin: Optional[str]
end: Optional[str]
while_: Optional[str]
content_name: Tuple[str, ...]
captures: Captures
begin_captures: Captures
end_captures: Captures
while_captures: Captures
include: Optional[str]
patterns: Tuple[_Rule, ...]
@classmethod
def from_dct(cls, dct: Dict[str, Any]) -> _Rule:
name = _split_name(dct.get('name'))
match = dct.get('match')
begin = dct.get('begin')
end = dct.get('end')
while_ = dct.get('while')
content_name = _split_name(dct.get('contentName'))
if 'captures' in dct:
captures = tuple(
(int(k), Rule.from_dct(v))
for k, v in dct['captures'].items()
)
else:
captures = ()
if 'beginCaptures' in dct:
begin_captures = tuple(
(int(k), Rule.from_dct(v))
for k, v in dct['beginCaptures'].items()
)
else:
begin_captures = ()
if 'endCaptures' in dct:
end_captures = tuple(
(int(k), Rule.from_dct(v))
for k, v in dct['endCaptures'].items()
)
else:
end_captures = ()
if 'whileCaptures' in dct:
while_captures = tuple(
(int(k), Rule.from_dct(v))
for k, v in dct['whileCaptures'].items()
)
else:
while_captures = ()
# Using the captures key for a begin/end/while rule is short-hand for
# giving both beginCaptures and endCaptures with same values
if begin and end and captures:
begin_captures = end_captures = captures
captures = ()
elif begin and while_ and captures:
begin_captures = while_captures = captures
captures = ()
include = dct.get('include')
if 'patterns' in dct:
patterns = tuple(Rule.from_dct(d) for d in dct['patterns'])
else:
patterns = ()
return cls(
name=name,
match=match,
begin=begin,
end=end,
while_=while_,
content_name=content_name,
captures=captures,
begin_captures=begin_captures,
end_captures=end_captures,
while_captures=while_captures,
include=include,
patterns=patterns,
)
class Grammar(NamedTuple):
scope_name: str
first_line_match: Optional[_Reg]
file_types: FrozenSet[str]
patterns: Tuple[_Rule, ...]
repository: FDict[str, _Rule]
@classmethod
def from_data(cls, data: Dict[str, Any]) -> 'Grammar':
scope_name = data['scopeName']
if 'firstLineMatch' in data:
first_line_match: Optional[_Reg] = make_reg(data['firstLineMatch'])
else:
first_line_match = None
if 'fileTypes' in data:
file_types = frozenset(data['fileTypes'])
else:
file_types = frozenset()
patterns = tuple(Rule.from_dct(dct) for dct in data['patterns'])
if 'repository' in data:
repository = FDict({
k: Rule.from_dct(dct) for k, dct in data['repository'].items()
})
else:
repository = FDict({})
return cls(
scope_name=scope_name,
first_line_match=first_line_match,
file_types=file_types,
patterns=patterns,
repository=repository,
)
@classmethod
def parse(cls, filename: str) -> 'Grammar':
with open(filename) as f:
return cls.from_data(json.load(f))
@classmethod
def blank(cls) -> 'Grammar':
return cls(
scope_name='source.unknown',
first_line_match=None,
file_types=frozenset(),
patterns=(),
repository=FDict({}),
)
def matches_file(self, filename: str, first_line: str) -> bool:
_, ext = os.path.splitext(filename)
if ext.lstrip('.') in self.file_types:
return True
elif self.first_line_match is not None:
return bool(
self.first_line_match.match(
first_line, 0, first_line=True, boundary=True,
),
)
else:
return False
class Region(NamedTuple):
start: int
end: int
scope: Scope
class State(NamedTuple):
entries: Tuple['Entry', ...]
while_stack: Tuple[Tuple['WhileRule', int], ...]
@classmethod
def root(cls, entry: 'Entry') -> 'State':
return cls((entry,), ())
@property
def cur(self) -> 'Entry':
return self.entries[-1]
def push(self, entry: 'Entry') -> 'State':
return self._replace(entries=(*self.entries, entry))
def pop(self) -> 'State':
return self._replace(entries=self.entries[:-1])
def push_while(self, rule: 'WhileRule', entry: 'Entry') -> 'State':
entries = (*self.entries, entry)
while_stack = (*self.while_stack, (rule, len(entries)))
return self._replace(entries=entries, while_stack=while_stack)
def pop_while(self) -> 'State':
entries, while_stack = self.entries[:-1], self.while_stack[:-1]
return self._replace(entries=entries, while_stack=while_stack)
class CompiledRule(Protocol):
@property
def name(self) -> Tuple[str, ...]: ...
def start(
self,
compiler: 'Compiler',
match: Match[str],
state: State,
) -> Tuple[State, bool, Regions]:
...
def search(
self,
compiler: 'Compiler',
state: State,
line: str,
pos: int,
first_line: bool,
boundary: bool,
) -> Optional[Tuple[State, int, bool, Regions]]:
...
class CompiledRegsetRule(CompiledRule, Protocol):
@property
def regset(self) -> _RegSet: ...
@property
def u_rules(self) -> Tuple[_Rule, ...]: ...
class Entry(NamedTuple):
scope: Tuple[str, ...]
rule: CompiledRule
reg: _Reg = ERR_REG
boundary: bool = False
def _inner_capture_parse(
compiler: 'Compiler',
start: int,
s: str,
scope: Scope,
rule: CompiledRule,
) -> Regions:
state = State.root(Entry(scope + rule.name, rule))
_, regions = highlight_line(compiler, state, s, first_line=False)
return tuple(
r._replace(start=r.start + start, end=r.end + start) for r in regions
)
def _captures(
compiler: 'Compiler',
scope: Scope,
match: Match[str],
captures: Captures,
) -> Regions:
ret: List[Region] = []
pos, pos_end = match.span()
for i, u_rule in captures:
try:
group_s = match[i]
except IndexError: # some grammars are malformed here?
continue
if not group_s:
continue
rule = compiler.compile_rule(u_rule)
start, end = match.span(i)
if start < pos:
# TODO: could maybe bisect but this is probably fast enough
j = len(ret) - 1
while j > 0 and start < ret[j - 1].end:
j -= 1
oldtok = ret[j]
newtok = []
if start > oldtok.start:
newtok.append(oldtok._replace(end=start))
newtok.extend(
_inner_capture_parse(
compiler, start, match[i], oldtok.scope, rule,
),
)
if end < oldtok.end:
newtok.append(oldtok._replace(start=end))
ret[j:j + 1] = newtok
else:
if start > pos:
ret.append(Region(pos, start, scope))
ret.extend(
_inner_capture_parse(compiler, start, match[i], scope, rule),
)
pos = end
if pos < pos_end:
ret.append(Region(pos, pos_end, scope))
return tuple(ret)
def _do_regset(
idx: int,
match: Optional[Match[str]],
rule: CompiledRegsetRule,
compiler: 'Compiler',
state: State,
pos: int,
) -> Optional[Tuple[State, int, bool, Regions]]:
if match is None:
return None
ret = []
if match.start() > pos:
ret.append(Region(pos, match.start(), state.cur.scope))
target_rule = compiler.compile_rule(rule.u_rules[idx])
state, boundary, regions = target_rule.start(compiler, match, state)
ret.extend(regions)
return state, match.end(), boundary, tuple(ret)
class PatternRule(NamedTuple):
name: Tuple[str, ...]
regset: _RegSet
u_rules: Tuple[_Rule, ...]
def start(
self,
compiler: 'Compiler',
match: Match[str],
state: State,
) -> Tuple[State, bool, Regions]:
raise AssertionError(f'unreachable {self}')
def search(
self,
compiler: 'Compiler',
state: State,
line: str,
pos: int,
first_line: bool,
boundary: bool,
) -> Optional[Tuple[State, int, bool, Regions]]:
idx, match = self.regset.search(line, pos, first_line, boundary)
return _do_regset(idx, match, self, compiler, state, pos)
class MatchRule(NamedTuple):
name: Tuple[str, ...]
captures: Captures
def start(
self,
compiler: 'Compiler',
match: Match[str],
state: State,
) -> Tuple[State, bool, Regions]:
scope = state.cur.scope + self.name
return state, False, _captures(compiler, scope, match, self.captures)
def search(
self,
compiler: 'Compiler',
state: State,
line: str,
pos: int,
first_line: bool,
boundary: bool,
) -> Optional[Tuple[State, int, bool, Regions]]:
raise AssertionError(f'unreachable {self}')
class EndRule(NamedTuple):
name: Tuple[str, ...]
content_name: Tuple[str, ...]
begin_captures: Captures
end_captures: Captures
end: str
regset: _RegSet
u_rules: Tuple[_Rule, ...]
def start(
self,
compiler: 'Compiler',
match: Match[str],
state: State,
) -> Tuple[State, bool, Regions]:
scope = state.cur.scope + self.name
next_scope = scope + self.content_name
boundary = match.end() == len(match.string)
reg = make_reg(match.expand(self.end))
state = state.push(Entry(next_scope, self, reg, boundary))
regions = _captures(compiler, scope, match, self.begin_captures)
return state, True, regions
def _end_ret(
self,
compiler: 'Compiler',
state: State,
pos: int,
m: Match[str],
) -> Tuple[State, int, bool, Regions]:
ret = []
if m.start() > pos:
ret.append(Region(pos, m.start(), state.cur.scope))
ret.extend(_captures(compiler, state.cur.scope, m, self.end_captures))
return state.pop(), m.end(), False, tuple(ret)
def search(
self,
compiler: 'Compiler',
state: State,
line: str,
pos: int,
first_line: bool,
boundary: bool,
) -> Optional[Tuple[State, int, bool, Regions]]:
end_match = state.cur.reg.search(line, pos, first_line, boundary)
if end_match is not None and end_match.start() == pos:
return self._end_ret(compiler, state, pos, end_match)
elif end_match is None:
idx, match = self.regset.search(line, pos, first_line, boundary)
return _do_regset(idx, match, self, compiler, state, pos)
else:
idx, match = self.regset.search(line, pos, first_line, boundary)
if match is None or end_match.start() <= match.start():
return self._end_ret(compiler, state, pos, end_match)
else:
return _do_regset(idx, match, self, compiler, state, pos)
class WhileRule(NamedTuple):
name: Tuple[str, ...]
content_name: Tuple[str, ...]
begin_captures: Captures
while_captures: Captures
while_: str
regset: _RegSet
u_rules: Tuple[_Rule, ...]
def start(
self,
compiler: 'Compiler',
match: Match[str],
state: State,
) -> Tuple[State, bool, Regions]:
scope = state.cur.scope + self.name
next_scope = scope + self.content_name
boundary = match.end() == len(match.string)
reg = make_reg(match.expand(self.while_))
state = state.push_while(self, Entry(next_scope, self, reg, boundary))
regions = _captures(compiler, scope, match, self.begin_captures)
return state, True, regions
def continues(
self,
compiler: 'Compiler',
state: State,
line: str,
pos: int,
first_line: bool,
boundary: bool,
) -> Optional[Tuple[int, bool, Regions]]:
match = state.cur.reg.match(line, pos, first_line, boundary)
if match is None:
return None
ret = _captures(compiler, state.cur.scope, match, self.while_captures)
return match.end(), True, ret
def search(
self,
compiler: 'Compiler',
state: State,
line: str,
pos: int,
first_line: bool,
boundary: bool,
) -> Optional[Tuple[State, int, bool, Regions]]:
idx, match = self.regset.search(line, pos, first_line, boundary)
return _do_regset(idx, match, self, compiler, state, pos)
class Compiler:
def __init__(self, grammar: Grammar, grammars: Dict[str, Grammar]) -> None:
self._root_scope = grammar.scope_name
self._grammars = grammars
self._rule_to_grammar: Dict[_Rule, Grammar] = {}
self._c_rules: Dict[_Rule, CompiledRule] = {}
root = self._compile_root(grammar)
self.root_state = State.root(Entry(root.name, root))
def _visit_rule(self, grammar: Grammar, rule: _Rule) -> _Rule:
self._rule_to_grammar[rule] = grammar
return rule
@functools.lru_cache(maxsize=None)
def _include(
self,
grammar: Grammar,
s: str,
) -> Tuple[List[str], Tuple[_Rule, ...]]:
if s == '$self':
return self._patterns(grammar, grammar.patterns)
elif s == '$base':
return self._include(self._grammars[self._root_scope], '$self')
elif s.startswith('#'):
return self._patterns(grammar, (grammar.repository[s[1:]],))
elif '#' not in s:
return self._include(self._grammars[s], '$self')
else:
scope, _, s = s.partition('#')
return self._include(self._grammars[scope], f'#{s}')
@functools.lru_cache(maxsize=None)
def _patterns(
self,
grammar: Grammar,
rules: Tuple[_Rule, ...],
) -> Tuple[List[str], Tuple[_Rule, ...]]:
ret_regs = []
ret_rules: List[_Rule] = []
for rule in rules:
if rule.include is not None:
tmp_regs, tmp_rules = self._include(grammar, rule.include)
ret_regs.extend(tmp_regs)
ret_rules.extend(tmp_rules)
elif rule.match is None and rule.begin is None and rule.patterns:
tmp_regs, tmp_rules = self._patterns(grammar, rule.patterns)
ret_regs.extend(tmp_regs)
ret_rules.extend(tmp_rules)
elif rule.match is not None:
ret_regs.append(rule.match)
ret_rules.append(self._visit_rule(grammar, rule))
elif rule.begin is not None:
ret_regs.append(rule.begin)
ret_rules.append(self._visit_rule(grammar, rule))
else:
raise AssertionError(f'unreachable {rule}')
return ret_regs, tuple(ret_rules)
def _captures_ref(
self,
grammar: Grammar,
captures: Captures,
) -> Captures:
return tuple((n, self._visit_rule(grammar, r)) for n, r in captures)
def _compile_root(self, grammar: Grammar) -> PatternRule:
regs, rules = self._patterns(grammar, grammar.patterns)
return PatternRule((grammar.scope_name,), make_regset(*regs), rules)
def _compile_rule(self, grammar: Grammar, rule: _Rule) -> CompiledRule:
assert rule.include is None, rule
if rule.match is not None:
captures_ref = self._captures_ref(grammar, rule.captures)
return MatchRule(rule.name, captures_ref)
elif rule.begin is not None and rule.end is not None:
regs, rules = self._patterns(grammar, rule.patterns)
return EndRule(
rule.name,
rule.content_name,
self._captures_ref(grammar, rule.begin_captures),
self._captures_ref(grammar, rule.end_captures),
rule.end,
make_regset(*regs),
rules,
)
elif rule.begin is not None and rule.while_ is not None:
regs, rules = self._patterns(grammar, rule.patterns)
return WhileRule(
rule.name,
rule.content_name,
self._captures_ref(grammar, rule.begin_captures),
self._captures_ref(grammar, rule.while_captures),
rule.while_,
make_regset(*regs),
rules,
)
else:
regs, rules = self._patterns(grammar, rule.patterns)
return PatternRule(rule.name, make_regset(*regs), rules)
def compile_rule(self, rule: _Rule) -> CompiledRule:
with contextlib.suppress(KeyError):
return self._c_rules[rule]
grammar = self._rule_to_grammar[rule]
ret = self._c_rules[rule] = self._compile_rule(grammar, rule)
return ret
class Grammars:
def __init__(self, grammars: List[Grammar]) -> None:
self.grammars = {grammar.scope_name: grammar for grammar in grammars}
self._compilers: Dict[Grammar, Compiler] = {}
@classmethod
def from_syntax_dir(cls, syntax_dir: str) -> 'Grammars':
grammars = [Grammar.blank()]
if os.path.exists(syntax_dir):
grammars.extend(
Grammar.parse(os.path.join(syntax_dir, filename))
for filename in os.listdir(syntax_dir)
)
return cls(grammars)
def _compiler_for_grammar(self, grammar: Grammar) -> Compiler:
with contextlib.suppress(KeyError):
return self._compilers[grammar]
ret = self._compilers[grammar] = Compiler(grammar, self.grammars)
return ret
def compiler_for_scope(self, scope: str) -> Compiler:
return self._compiler_for_grammar(self.grammars[scope])
def blank_compiler(self) -> Compiler:
return self.compiler_for_scope('source.unknown')
def compiler_for_file(self, filename: str) -> Compiler:
if os.path.exists(filename):
with open(filename) as f:
first_line = next(f, '')
else:
first_line = ''
for grammar in self.grammars.values():
if grammar.matches_file(filename, first_line):
break
else:
grammar = self.grammars['source.unknown']
return self._compiler_for_grammar(grammar)
@functools.lru_cache(maxsize=None)
def highlight_line(
compiler: 'Compiler',
state: State,
line: str,
first_line: bool,
) -> Tuple[State, Regions]:
ret: List[Region] = []
pos = 0
boundary = state.cur.boundary
# TODO: this is still a little wasteful
while_stack = []
for while_rule, idx in state.while_stack:
while_stack.append((while_rule, idx))
while_state = State(state.entries[:idx], tuple(while_stack))
while_res = while_rule.continues(
compiler, while_state, line, pos, first_line, boundary,
)
if while_res is None:
state = while_state.pop_while()
break
else:
pos, boundary, regions = while_res
ret.extend(regions)
search_res = state.cur.rule.search(
compiler, state, line, pos, first_line, boundary,
)
while search_res is not None:
state, pos, boundary, regions = search_res
ret.extend(regions)
search_res = state.cur.rule.search(
compiler, state, line, pos, first_line, boundary,
)
if pos < len(line):
ret.append(Region(pos, len(line), state.cur.scope))
return state, tuple(ret)