/
parser.rs
1846 lines (1686 loc) · 63.8 KB
/
parser.rs
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Suppression of a false positive clippy lint. Upstream issue:
//
// mutable_key_type false positive for raw pointers
// https://github.com/rust-lang/rust-clippy/issues/6745
//
// We use `*const MatchPattern` as key in our `SearchCache` hash map.
// Clippy thinks this is a problem since `MatchPattern` has interior mutability
// via `MatchPattern::regex::regex` which is an `AtomicLazyCell`.
// But raw pointers are hashed via the pointer itself, not what is pointed to.
// See https://github.com/rust-lang/rust/blob/1.54.0/library/core/src/hash/mod.rs#L717-L725
#![allow(clippy::mutable_key_type)]
use super::syntax_definition::*;
use super::scope::*;
use super::regex::Region;
use std::usize;
use std::collections::HashMap;
use std::i32;
use std::hash::BuildHasherDefault;
use fnv::FnvHasher;
use crate::parsing::syntax_set::{SyntaxSet, SyntaxReference};
use crate::parsing::syntax_definition::ContextId;
/// Errors that can occur while parsing.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ParsingError {
#[error("Somehow main context was popped from the stack")]
MissingMainContext,
/// A context is missing. Usually caused by a syntax referencing a another
/// syntax that is not known to syntect. See e.g. <https://github.com/trishume/syntect/issues/421>
#[error("Missing context with ID '{0:?}'")]
MissingContext(ContextId),
#[error("Bad index to match_at: {0}")]
BadMatchIndex(usize),
#[error("Tried to use a ContextReference that has not bee resolved yet: {0:?}")]
UnresolvedContextReference(ContextReference),
}
/// Keeps the current parser state (the internal syntax interpreter stack) between lines of parsing.
///
/// If you are parsing an entire file you create one of these at the start and use it
/// all the way to the end.
///
/// # Caching
///
/// One reason this is exposed is that since it implements `Clone` you can actually cache
/// these (probably along with a [`HighlightState`]) and only re-start parsing from the point of a change.
/// See the docs for [`HighlightState`] for more in-depth discussion of caching.
///
/// This state doesn't keep track of the current scope stack and parsing only returns changes to this stack
/// so if you want to construct scope stacks you'll need to keep track of that as well.
/// Note that [`HighlightState`] contains exactly this as a public field that you can use.
///
/// **Note:** Caching is for advanced users who have tons of time to maximize performance or want to do so eventually.
/// It is not recommended that you try caching the first time you implement highlighting.
///
/// [`HighlightState`]: ../highlighting/struct.HighlightState.html
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ParseState {
stack: Vec<StateLevel>,
first_line: bool,
// See issue #101. Contains indices of frames pushed by `with_prototype`s.
// Doesn't look at `with_prototype`s below top of stack.
proto_starts: Vec<usize>,
}
#[derive(Debug, Clone, Eq, PartialEq)]
struct StateLevel {
context: ContextId,
prototypes: Vec<ContextId>,
captures: Option<(Region, String)>,
}
#[derive(Debug)]
struct RegexMatch<'a> {
regions: Region,
context: &'a Context,
pat_index: usize,
from_with_prototype: bool,
would_loop: bool,
}
/// Maps the pattern to the start index, which is -1 if not found.
type SearchCache = HashMap<*const MatchPattern, Option<Region>, BuildHasherDefault<FnvHasher>>;
// To understand the implementation of this, here's an introduction to how
// Sublime Text syntax definitions work.
//
// Let's say we have the following made-up syntax definition:
//
// contexts:
// main:
// - match: A
// scope: scope.a.first
// push: context-a
// - match: b
// scope: scope.b
// - match: \w+
// scope: scope.other
// context-a:
// - match: a+
// scope: scope.a.rest
// - match: (?=.)
// pop: true
//
// There are two contexts, `main` and `context-a`. Each context contains a list
// of match rules with instructions for how to proceed.
//
// Let's say we have the input string " Aaaabxxx". We start at position 0 in
// the string. We keep a stack of contexts, which at the beginning is just main.
//
// So we start by looking at the top of the context stack (main), and look at
// the rules in order. The rule that wins is the first one that matches
// "earliest" in the input string. In our example:
//
// 1. The first one matches "A". Note that matches are not anchored, so this
// matches at position 1.
// 2. The second one matches "b", so position 5. The first rule is winning.
// 3. The third one matches "\w+", so also position 1. But because the first
// rule comes first, it wins.
//
// So now we execute the winning rule. Whenever we matched some text, we assign
// the scope (if there is one) to the matched text and advance our position to
// after the matched text. The scope is "scope.a.first" and our new position is
// after the "A", so 2. The "push" means that we should change our stack by
// pushing `context-a` on top of it.
//
// In the next step, we repeat the above, but now with the rules in `context-a`.
// The result is that we match "a+" and assign "scope.a.rest" to "aaa", and our
// new position is now after the "aaa". Note that there was no instruction for
// changing the stack, so we stay in that context.
//
// In the next step, the first rule doesn't match anymore, so we go to the next
// rule where "(?=.)" matches. The instruction is to "pop", which means we
// pop the top of our context stack, which means we're now back in main.
//
// This time in main, we match "b", and in the next step we match the rest with
// "\w+", and we're done.
//
//
// ## Preventing loops
//
// These are the basics of how matching works. Now, you saw that you can write
// patterns that result in an empty match and don't change the position. These
// are called non-consuming matches. The problem with them is that they could
// result in infinite loops. Let's look at a syntax where that is the case:
//
// contexts:
// main:
// - match: (?=.)
// push: test
// test:
// - match: \w+
// scope: word
// - match: (?=.)
// pop: true
//
// This is a bit silly, but it's a minimal example for explaining how matching
// works in that case.
//
// Let's say we have the input string " hello". In `main`, our rule matches and
// we go into `test` and stay at position 0. Now, the best match is the rule
// with "pop". But if we used that rule, we'd pop back to `main` and would still
// be at the same position we started at! So this would be an infinite loop,
// which we don't want.
//
// So what Sublime Text does in case a looping rule "won":
//
// * If there's another rule that matches at the same position and does not
// result in a loop, use that instead.
// * Otherwise, go to the next position and go through all the rules in the
// current context again. Note that it means that the "pop" could again be the
// winning rule, but that's ok as it wouldn't result in a loop anymore.
//
// So in our input string, we'd skip one character and try to match the rules
// again. This time, the "\w+" wins because it comes first.
impl ParseState {
/// Creates a state from a syntax definition, keeping its own reference-counted point to the
/// main context of the syntax
pub fn new(syntax: &SyntaxReference) -> ParseState {
let start_state = StateLevel {
context: syntax.context_ids()["__start"],
prototypes: Vec::new(),
captures: None,
};
ParseState {
stack: vec![start_state],
first_line: true,
proto_starts: Vec::new(),
}
}
/// Parses a single line of the file. Because of the way regex engines work you unfortunately
/// have to pass in a single line contiguous in memory. This can be bad for really long lines.
/// Sublime Text avoids this by just not highlighting lines that are too long (thousands of characters).
///
/// For efficiency reasons this returns only the changes to the current scope at each point in the line.
/// You can use [`ScopeStack::apply`] on each operation in succession to get the stack for a given point.
/// Look at the code in `highlighter.rs` for an example of doing this for highlighting purposes.
///
/// The returned vector is in order both by index to apply at (the `usize`) and also by order to apply them at a
/// given index (e.g popping old scopes before pushing new scopes).
///
/// The [`SyntaxSet`] has to be the one that contained the syntax that was used to construct
/// this [`ParseState`], or an extended version of it. Otherwise the parsing would return the
/// wrong result or even panic. The reason for this is that contexts within the [`SyntaxSet`]
/// are referenced via indexes.
///
/// [`ScopeStack::apply`]: struct.ScopeStack.html#method.apply
/// [`SyntaxSet`]: struct.SyntaxSet.html
/// [`ParseState`]: struct.ParseState.html
pub fn parse_line(
&mut self,
line: &str,
syntax_set: &SyntaxSet,
) -> Result<Vec<(usize, ScopeStackOp)>, ParsingError> {
if self.stack.is_empty() {
return Err(ParsingError::MissingMainContext)
}
let mut match_start = 0;
let mut res = Vec::new();
if self.first_line {
let cur_level = &self.stack[self.stack.len() - 1];
let context = syntax_set.get_context(&cur_level.context)?;
if !context.meta_content_scope.is_empty() {
res.push((0, ScopeStackOp::Push(context.meta_content_scope[0])));
}
self.first_line = false;
}
let mut regions = Region::new();
let fnv = BuildHasherDefault::<FnvHasher>::default();
let mut search_cache: SearchCache = HashMap::with_capacity_and_hasher(128, fnv);
// Used for detecting loops with push/pop, see long comment above.
let mut non_consuming_push_at = (0, 0);
while self.parse_next_token(
line,
syntax_set,
&mut match_start,
&mut search_cache,
&mut regions,
&mut non_consuming_push_at,
&mut res
)? {}
Ok(res)
}
#[allow(clippy::too_many_arguments)]
fn parse_next_token(
&mut self,
line: &str,
syntax_set: &SyntaxSet,
start: &mut usize,
search_cache: &mut SearchCache,
regions: &mut Region,
non_consuming_push_at: &mut (usize, usize),
ops: &mut Vec<(usize, ScopeStackOp)>,
) -> Result<bool, ParsingError> {
let check_pop_loop = {
let (pos, stack_depth) = *non_consuming_push_at;
pos == *start && stack_depth == self.stack.len()
};
// Trim proto_starts that are no longer valid
while self.proto_starts.last().map(|start| *start >= self.stack.len()).unwrap_or(false) {
self.proto_starts.pop();
}
let best_match = self.find_best_match(line, *start, syntax_set, search_cache, regions, check_pop_loop)?;
if let Some(reg_match) = best_match {
if reg_match.would_loop {
// A push that doesn't consume anything (a regex that resulted
// in an empty match at the current position) can not be
// followed by a non-consuming pop. Otherwise we're back where
// we started and would try the same sequence of matches again,
// resulting in an infinite loop. In this case, Sublime Text
// advances one character and tries again, thus preventing the
// loop.
// println!("pop_would_loop for match {:?}, start {}", reg_match, *start);
// nth(1) gets the next character if there is one. Need to do
// this instead of just += 1 because we have byte indices and
// unicode characters can be more than 1 byte.
if let Some((i, _)) = line[*start..].char_indices().nth(1) {
*start += i;
return Ok(true);
} else {
// End of line, no character to advance and no point trying
// any more patterns.
return Ok(false);
}
}
let match_end = reg_match.regions.pos(0).unwrap().1;
let consuming = match_end > *start;
if !consuming {
// The match doesn't consume any characters. If this is a
// "push", remember the position and stack size so that we can
// check the next "pop" for loops. Otherwise leave the state,
// e.g. non-consuming "set" could also result in a loop.
let context = reg_match.context;
let match_pattern = context.match_at(reg_match.pat_index)?;
if let MatchOperation::Push(_) = match_pattern.operation {
*non_consuming_push_at = (match_end, self.stack.len() + 1);
}
}
*start = match_end;
// ignore `with_prototype`s below this if a context is pushed
if reg_match.from_with_prototype {
// use current height, since we're before the actual push
self.proto_starts.push(self.stack.len());
}
let level_context = {
let id = &self.stack[self.stack.len() - 1].context;
syntax_set.get_context(id)?
};
self.exec_pattern(line, ®_match, level_context, syntax_set, ops)?;
Ok(true)
} else {
Ok(false)
}
}
fn find_best_match<'a>(
&self,
line: &str,
start: usize,
syntax_set: &'a SyntaxSet,
search_cache: &mut SearchCache,
regions: &mut Region,
check_pop_loop: bool,
) -> Result<Option<RegexMatch<'a>>, ParsingError> {
let cur_level = &self.stack[self.stack.len() - 1];
let context = syntax_set.get_context(&cur_level.context)?;
let prototype = if let Some(ref p) = context.prototype {
Some(p)
} else {
None
};
// Build an iterator for the contexts we want to visit in order
let context_chain = {
let proto_start = self.proto_starts.last().cloned().unwrap_or(0);
// Sublime applies with_prototypes from bottom to top
let with_prototypes = self.stack[proto_start..].iter().flat_map(|lvl| lvl.prototypes.iter().map(move |ctx| (true, ctx, lvl.captures.as_ref())));
let cur_prototype = prototype.into_iter().map(|ctx| (false, ctx, None));
let cur_context = Some((false, &cur_level.context, cur_level.captures.as_ref())).into_iter();
with_prototypes.chain(cur_prototype).chain(cur_context)
};
// println!("{:#?}", cur_level);
// println!("token at {} on {}", start, line.trim_right());
let mut min_start = usize::MAX;
let mut best_match: Option<RegexMatch<'_>> = None;
let mut pop_would_loop = false;
for (from_with_proto, ctx, captures) in context_chain {
for (pat_context, pat_index) in context_iter(syntax_set, syntax_set.get_context(ctx)?) {
let match_pat = pat_context.match_at(pat_index)?;
if let Some(match_region) = self.search(
line, start, match_pat, captures, search_cache, regions
) {
let (match_start, match_end) = match_region.pos(0).unwrap();
// println!("matched pattern {:?} at start {} end {}", match_pat.regex_str, match_start, match_end);
if match_start < min_start || (match_start == min_start && pop_would_loop) {
// New match is earlier in text than old match,
// or old match was a looping pop at the same
// position.
// println!("setting as current match");
min_start = match_start;
let consuming = match_end > start;
pop_would_loop = check_pop_loop
&& !consuming
&& matches!(match_pat.operation, MatchOperation::Pop);
best_match = Some(RegexMatch {
regions: match_region,
context: pat_context,
pat_index,
from_with_prototype: from_with_proto,
would_loop: pop_would_loop,
});
if match_start == start && !pop_would_loop {
// We're not gonna find a better match after this,
// so as an optimization we can stop matching now.
return Ok(best_match);
}
}
}
}
}
Ok(best_match)
}
fn search(&self,
line: &str,
start: usize,
match_pat: &MatchPattern,
captures: Option<&(Region, String)>,
search_cache: &mut SearchCache,
regions: &mut Region,
) -> Option<Region> {
// println!("{} - {:?} - {:?}", match_pat.regex_str, match_pat.has_captures, cur_level.captures.is_some());
let match_ptr = match_pat as *const MatchPattern;
if let Some(maybe_region) = search_cache.get(&match_ptr) {
if let Some(ref region) = *maybe_region {
let match_start = region.pos(0).unwrap().0;
if match_start >= start {
// Cached match is valid, return it. Otherwise do another
// search below.
return Some(region.clone());
}
} else {
// Didn't find a match earlier, so no point trying to match it again
return None;
}
}
let (matched, can_cache) = match (match_pat.has_captures, captures) {
(true, Some(captures)) => {
let &(ref region, ref s) = captures;
let regex = match_pat.regex_with_refs(region, s);
let matched = regex.search(line, start, line.len(), Some(regions));
(matched, false)
}
_ => {
let regex = match_pat.regex();
let matched = regex.search(line, start, line.len(), Some(regions));
(matched, true)
}
};
if matched {
let (match_start, match_end) = regions.pos(0).unwrap();
// this is necessary to avoid infinite looping on dumb patterns
let does_something = match match_pat.operation {
MatchOperation::None => match_start != match_end,
_ => true,
};
if can_cache && does_something {
search_cache.insert(match_pat, Some(regions.clone()));
}
if does_something {
// print!("catch {} at {} on {}", match_pat.regex_str, match_start, line);
return Some(regions.clone());
}
} else if can_cache {
search_cache.insert(match_pat, None);
}
None
}
/// Returns true if the stack was changed
fn exec_pattern<'a>(
&mut self,
line: &str,
reg_match: &RegexMatch<'a>,
level_context: &'a Context,
syntax_set: &'a SyntaxSet,
ops: &mut Vec<(usize, ScopeStackOp)>,
) -> Result<bool, ParsingError> {
let (match_start, match_end) = reg_match.regions.pos(0).unwrap();
let context = reg_match.context;
let pat = context.match_at(reg_match.pat_index)?;
// println!("running pattern {:?} on '{}' at {}, operation {:?}", pat.regex_str, line, match_start, pat.operation);
self.push_meta_ops(true, match_start, level_context, &pat.operation, syntax_set, ops)?;
for s in &pat.scope {
// println!("pushing {:?} at {}", s, match_start);
ops.push((match_start, ScopeStackOp::Push(*s)));
}
if let Some(ref capture_map) = pat.captures {
// captures could appear in an arbitrary order, have to produce ops in right order
// ex: ((bob)|(hi))* could match hibob in wrong order, and outer has to push first
// we don't have to handle a capture matching multiple times, Sublime doesn't
let mut map: Vec<((usize, i32), ScopeStackOp)> = Vec::new();
for &(cap_index, ref scopes) in capture_map.iter() {
if let Some((cap_start, cap_end)) = reg_match.regions.pos(cap_index) {
// marking up empty captures causes pops to be sorted wrong
if cap_start == cap_end {
continue;
}
// println!("capture {:?} at {:?}-{:?}", scopes[0], cap_start, cap_end);
for scope in scopes.iter() {
map.push(((cap_start, -((cap_end - cap_start) as i32)),
ScopeStackOp::Push(*scope)));
}
map.push(((cap_end, i32::MIN), ScopeStackOp::Pop(scopes.len())));
}
}
map.sort_by(|a, b| a.0.cmp(&b.0));
for ((index, _), op) in map.into_iter() {
ops.push((index, op));
}
}
if !pat.scope.is_empty() {
// println!("popping at {}", match_end);
ops.push((match_end, ScopeStackOp::Pop(pat.scope.len())));
}
self.push_meta_ops(false, match_end, &*level_context, &pat.operation, syntax_set, ops)?;
self.perform_op(line, ®_match.regions, pat, syntax_set)
}
fn push_meta_ops<'a>(
&self,
initial: bool,
index: usize,
cur_context: &Context,
match_op: &MatchOperation,
syntax_set: &'a SyntaxSet,
ops: &mut Vec<(usize, ScopeStackOp)>,
) -> Result<(), ParsingError>{
// println!("metas ops for {:?}, initial: {}",
// match_op,
// initial);
// println!("{:?}", cur_context.meta_scope);
match *match_op {
MatchOperation::Pop => {
let v = if initial {
&cur_context.meta_content_scope
} else {
&cur_context.meta_scope
};
if !v.is_empty() {
ops.push((index, ScopeStackOp::Pop(v.len())));
}
// cleared scopes are restored after the scopes from match pattern that invoked the pop are applied
if !initial && cur_context.clear_scopes != None {
ops.push((index, ScopeStackOp::Restore))
}
},
// for some reason the ST3 behaviour of set is convoluted and is inconsistent with the docs and other ops
// - the meta_content_scope of the current context is applied to the matched thing, unlike pop
// - the clear_scopes are applied after the matched token, unlike push
// - the interaction with meta scopes means that the token has the meta scopes of both the current scope and the new scope.
MatchOperation::Push(ref context_refs) |
MatchOperation::Set(ref context_refs) => {
let is_set = matches!(*match_op, MatchOperation::Set(_));
// a match pattern that "set"s keeps the meta_content_scope and meta_scope from the previous context
if initial {
if is_set && cur_context.clear_scopes != None {
// cleared scopes from the old context are restored immediately
ops.push((index, ScopeStackOp::Restore));
}
// add each context's meta scope
for r in context_refs.iter() {
let ctx = r.resolve(syntax_set)?;
if !is_set {
if let Some(clear_amount) = ctx.clear_scopes {
ops.push((index, ScopeStackOp::Clear(clear_amount)));
}
}
for scope in ctx.meta_scope.iter() {
ops.push((index, ScopeStackOp::Push(*scope)));
}
}
} else {
let repush = (is_set && (!cur_context.meta_scope.is_empty() || !cur_context.meta_content_scope.is_empty())) || context_refs.iter().any(|r| {
let ctx = r.resolve(syntax_set).unwrap();
!ctx.meta_content_scope.is_empty() || (ctx.clear_scopes.is_some() && is_set)
});
if repush {
// remove previously pushed meta scopes, so that meta content scopes will be applied in the correct order
let mut num_to_pop : usize = context_refs.iter().map(|r| {
let ctx = r.resolve(syntax_set).unwrap();
ctx.meta_scope.len()
}).sum();
// also pop off the original context's meta scopes
if is_set {
num_to_pop += cur_context.meta_content_scope.len() + cur_context.meta_scope.len();
}
// do all the popping as one operation
if num_to_pop > 0 {
ops.push((index, ScopeStackOp::Pop(num_to_pop)));
}
// now we push meta scope and meta context scope for each context pushed
for r in context_refs {
let ctx = r.resolve(syntax_set)?;
// for some reason, contrary to my reading of the docs, set does this after the token
if is_set {
if let Some(clear_amount) = ctx.clear_scopes {
ops.push((index, ScopeStackOp::Clear(clear_amount)));
}
}
for scope in ctx.meta_scope.iter() {
ops.push((index, ScopeStackOp::Push(*scope)));
}
for scope in ctx.meta_content_scope.iter() {
ops.push((index, ScopeStackOp::Push(*scope)));
}
}
}
}
},
MatchOperation::None => (),
}
Ok(())
}
/// Returns true if the stack was changed
fn perform_op(
&mut self,
line: &str,
regions: &Region,
pat: &MatchPattern,
syntax_set: &SyntaxSet
) -> Result<bool, ParsingError> {
let (ctx_refs, old_proto_ids) = match pat.operation {
MatchOperation::Push(ref ctx_refs) => (ctx_refs, None),
MatchOperation::Set(ref ctx_refs) => {
// a `with_prototype` stays active when the context is `set`
// until the context layer in the stack (where the `with_prototype`
// was initially applied) is popped off.
(ctx_refs, self.stack.pop().map(|s| s.prototypes))
}
MatchOperation::Pop => {
self.stack.pop();
return Ok(true);
}
MatchOperation::None => return Ok(false),
};
for (i, r) in ctx_refs.iter().enumerate() {
let mut proto_ids = if i == 0 {
// it is only necessary to preserve the old prototypes
// at the first stack frame pushed
old_proto_ids.clone().unwrap_or_else(Vec::new)
} else {
Vec::new()
};
if i == ctx_refs.len() - 1 {
// if a with_prototype was specified, and multiple contexts were pushed,
// then the with_prototype applies only to the last context pushed, i.e.
// top most on the stack after all the contexts are pushed - this is also
// referred to as the "target" of the push by sublimehq - see
// https://forum.sublimetext.com/t/dev-build-3111/19240/17 for more info
if let Some(ref p) = pat.with_prototype {
proto_ids.push(p.id()?);
}
}
let context_id = r.id()?;
let context = syntax_set.get_context(&context_id)?;
let captures = {
let mut uses_backrefs = context.uses_backrefs;
if !proto_ids.is_empty() {
uses_backrefs = uses_backrefs || proto_ids.iter().any(|id| syntax_set.get_context(id).unwrap().uses_backrefs);
}
if uses_backrefs {
Some((regions.clone(), line.to_owned()))
} else {
None
}
};
self.stack.push(StateLevel {
context: context_id,
prototypes: proto_ids,
captures,
});
}
Ok(true)
}
}
#[cfg(feature = "yaml-load")]
#[cfg(test)]
mod tests {
use super::*;
use crate::parsing::{SyntaxSet, SyntaxSetBuilder, Scope, ScopeStack};
use crate::parsing::ScopeStackOp::{Push, Pop, Clear, Restore};
use crate::util::debug_print_ops;
const TEST_SYNTAX: &str = include_str!("../../testdata/parser_tests.sublime-syntax");
#[test]
fn can_parse_simple() {
let ss = SyntaxSet::load_from_folder("testdata/Packages").unwrap();
let mut state = {
let syntax = ss.find_syntax_by_name("Ruby on Rails").unwrap();
ParseState::new(syntax)
};
let ops1 = ops(&mut state, "module Bob::Wow::Troll::Five; 5; end", &ss);
let test_ops1 = vec![
(0, Push(Scope::new("source.ruby.rails").unwrap())),
(0, Push(Scope::new("meta.module.ruby").unwrap())),
(0, Push(Scope::new("keyword.control.module.ruby").unwrap())),
(6, Pop(2)),
(6, Push(Scope::new("meta.module.ruby").unwrap())),
(7, Pop(1)),
(7, Push(Scope::new("meta.module.ruby").unwrap())),
(7, Push(Scope::new("entity.name.module.ruby").unwrap())),
(7, Push(Scope::new("support.other.namespace.ruby").unwrap())),
(10, Pop(1)),
(10, Push(Scope::new("punctuation.accessor.ruby").unwrap())),
];
assert_eq!(&ops1[0..test_ops1.len()], &test_ops1[..]);
let ops2 = ops(&mut state, "def lol(wow = 5)", &ss);
let test_ops2 = vec![
(0, Push(Scope::new("meta.function.ruby").unwrap())),
(0, Push(Scope::new("keyword.control.def.ruby").unwrap())),
(3, Pop(2)),
(3, Push(Scope::new("meta.function.ruby").unwrap())),
(4, Push(Scope::new("entity.name.function.ruby").unwrap())),
(7, Pop(1))
];
assert_eq!(&ops2[0..test_ops2.len()], &test_ops2[..]);
}
#[test]
fn can_parse_yaml() {
let ps = SyntaxSet::load_from_folder("testdata/Packages").unwrap();
let mut state = {
let syntax = ps.find_syntax_by_name("YAML").unwrap();
ParseState::new(syntax)
};
assert_eq!(ops(&mut state, "key: value\n", &ps), vec![
(0, Push(Scope::new("source.yaml").unwrap())),
(0, Push(Scope::new("string.unquoted.plain.out.yaml").unwrap())),
(0, Push(Scope::new("entity.name.tag.yaml").unwrap())),
(3, Pop(2)),
(3, Push(Scope::new("punctuation.separator.key-value.mapping.yaml").unwrap())),
(4, Pop(1)),
(5, Push(Scope::new("string.unquoted.plain.out.yaml").unwrap())),
(10, Pop(1)),
]);
}
#[test]
fn can_parse_includes() {
let ss = SyntaxSet::load_from_folder("testdata/Packages").unwrap();
let mut state = {
let syntax = ss.find_syntax_by_name("HTML (Rails)").unwrap();
ParseState::new(syntax)
};
let ops = ops(&mut state, "<script>var lol = '<% def wow(", &ss);
let mut test_stack = ScopeStack::new();
test_stack.push(Scope::new("text.html.ruby").unwrap());
test_stack.push(Scope::new("text.html.basic").unwrap());
test_stack.push(Scope::new("source.js.embedded.html").unwrap());
test_stack.push(Scope::new("source.js").unwrap());
test_stack.push(Scope::new("string.quoted.single.js").unwrap());
test_stack.push(Scope::new("source.ruby.rails.embedded.html").unwrap());
test_stack.push(Scope::new("meta.function.parameters.ruby").unwrap());
let mut stack = ScopeStack::new();
for &(_, ref op) in ops.iter() {
stack.apply(op).expect("#[cfg(test)]");
}
assert_eq!(stack, test_stack);
}
#[test]
fn can_parse_backrefs() {
let ss = SyntaxSet::load_from_folder("testdata/Packages").unwrap();
let mut state = {
let syntax = ss.find_syntax_by_name("Ruby on Rails").unwrap();
ParseState::new(syntax)
};
// For parsing HEREDOC, the "SQL" is captured at the beginning and then used in another
// regex with a backref, to match the end of the HEREDOC. Note that there can be code
// after the marker (`.strip`) here.
assert_eq!(ops(&mut state, "lol = <<-SQL.strip", &ss), vec![
(0, Push(Scope::new("source.ruby.rails").unwrap())),
(4, Push(Scope::new("keyword.operator.assignment.ruby").unwrap())),
(5, Pop(1)),
(6, Push(Scope::new("string.unquoted.embedded.sql.ruby").unwrap())),
(6, Push(Scope::new("punctuation.definition.string.begin.ruby").unwrap())),
(12, Pop(1)),
(12, Pop(1)),
(12, Push(Scope::new("string.unquoted.embedded.sql.ruby").unwrap())),
(12, Push(Scope::new("text.sql.embedded.ruby").unwrap())),
(12, Clear(ClearAmount::TopN(2))),
(12, Push(Scope::new("punctuation.accessor.ruby").unwrap())),
(13, Pop(1)),
(18, Restore),
]);
assert_eq!(ops(&mut state, "wow", &ss), vec![]);
assert_eq!(ops(&mut state, "SQL", &ss), vec![
(0, Pop(1)),
(0, Push(Scope::new("punctuation.definition.string.end.ruby").unwrap())),
(3, Pop(1)),
(3, Pop(1)),
]);
}
#[test]
fn can_parse_preprocessor_rules() {
let ss = SyntaxSet::load_from_folder("testdata/Packages").unwrap();
let mut state = {
let syntax = ss.find_syntax_by_name("C").unwrap();
ParseState::new(syntax)
};
assert_eq!(ops(&mut state, "#ifdef FOO", &ss), vec![
(0, Push(Scope::new("source.c").unwrap())),
(0, Push(Scope::new("meta.preprocessor.c").unwrap())),
(0, Push(Scope::new("keyword.control.import.c").unwrap())),
(6, Pop(1)),
(10, Pop(1)),
]);
assert_eq!(ops(&mut state, "{", &ss), vec![
(0, Push(Scope::new("meta.block.c").unwrap())),
(0, Push(Scope::new("punctuation.section.block.begin.c").unwrap())),
(1, Pop(1)),
]);
assert_eq!(ops(&mut state, "#else", &ss), vec![
(0, Push(Scope::new("meta.preprocessor.c").unwrap())),
(0, Push(Scope::new("keyword.control.import.c").unwrap())),
(5, Pop(1)),
(5, Pop(1)),
]);
assert_eq!(ops(&mut state, "{", &ss), vec![
(0, Push(Scope::new("meta.block.c").unwrap())),
(0, Push(Scope::new("punctuation.section.block.begin.c").unwrap())),
(1, Pop(1)),
]);
assert_eq!(ops(&mut state, "#endif", &ss), vec![
(0, Pop(1)),
(0, Push(Scope::new("meta.block.c").unwrap())),
(0, Push(Scope::new("meta.preprocessor.c").unwrap())),
(0, Push(Scope::new("keyword.control.import.c").unwrap())),
(6, Pop(2)),
(6, Pop(2)),
(6, Push(Scope::new("meta.block.c").unwrap())),
]);
assert_eq!(ops(&mut state, " foo;", &ss), vec![
(7, Push(Scope::new("punctuation.terminator.c").unwrap())),
(8, Pop(1)),
]);
assert_eq!(ops(&mut state, "}", &ss), vec![
(0, Push(Scope::new("punctuation.section.block.end.c").unwrap())),
(1, Pop(1)),
(1, Pop(1)),
]);
}
#[test]
fn can_parse_issue25() {
let ss = SyntaxSet::load_from_folder("testdata/Packages").unwrap();
let mut state = {
let syntax = ss.find_syntax_by_name("C").unwrap();
ParseState::new(syntax)
};
// test fix for issue #25
assert_eq!(ops(&mut state, "struct{estruct", &ss).len(), 10);
}
#[test]
fn can_compare_parse_states() {
let ss = SyntaxSet::load_from_folder("testdata/Packages").unwrap();
let syntax = ss.find_syntax_by_name("Java").unwrap();
let mut state1 = ParseState::new(syntax);
let mut state2 = ParseState::new(syntax);
assert_eq!(ops(&mut state1, "class Foo {", &ss).len(), 11);
assert_eq!(ops(&mut state2, "class Fooo {", &ss).len(), 11);
assert_eq!(state1, state2);
ops(&mut state1, "}", &ss);
assert_ne!(state1, state2);
}
#[test]
fn can_parse_non_nested_clear_scopes() {
let line = "'hello #simple_cleared_scopes_test world test \\n '";
let expect = [
"<source.test>, <example.meta-scope.after-clear-scopes.example>, <example.pushes-clear-scopes.example>",
"<source.test>, <example.meta-scope.after-clear-scopes.example>, <example.pops-clear-scopes.example>",
"<source.test>, <string.quoted.single.example>, <constant.character.escape.example>",
];
expect_scope_stacks(line, &expect, TEST_SYNTAX);
}
#[test]
fn can_parse_non_nested_too_many_clear_scopes() {
let line = "'hello #too_many_cleared_scopes_test world test \\n '";
let expect = [
"<example.meta-scope.after-clear-scopes.example>, <example.pushes-clear-scopes.example>",
"<example.meta-scope.after-clear-scopes.example>, <example.pops-clear-scopes.example>",
"<source.test>, <string.quoted.single.example>, <constant.character.escape.example>",
];
expect_scope_stacks(line, &expect, TEST_SYNTAX);
}
#[test]
fn can_parse_nested_clear_scopes() {
let line = "'hello #nested_clear_scopes_test world foo bar test \\n '";
let expect = [
"<source.test>, <example.meta-scope.after-clear-scopes.example>, <example.pushes-clear-scopes.example>",
"<source.test>, <example.meta-scope.cleared-previous-meta-scope.example>, <foo>",
"<source.test>, <example.meta-scope.after-clear-scopes.example>, <example.pops-clear-scopes.example>",
"<source.test>, <string.quoted.single.example>, <constant.character.escape.example>",
];
expect_scope_stacks(line, &expect, TEST_SYNTAX);
}
#[test]
fn can_parse_infinite_loop() {
let line = "#infinite_loop_test 123";
let expect = [
"<source.test>, <constant.numeric.test>",
];
expect_scope_stacks(line, &expect, TEST_SYNTAX);
}
#[test]
fn can_parse_infinite_seeming_loop() {
// See https://github.com/SublimeTextIssues/Core/issues/1190 for an
// explanation.
let line = "#infinite_seeming_loop_test hello";
let expect = [
"<source.test>, <keyword.test>",
"<source.test>, <test>, <string.unquoted.test>",
"<source.test>, <test>, <keyword.control.test>",
];
expect_scope_stacks(line, &expect, TEST_SYNTAX);
}
#[test]
fn can_parse_prototype_that_pops_main() {
let syntax = r#"
name: test
scope: source.test
contexts:
prototype:
# This causes us to pop out of the main context. Sublime Text handles that
# by pushing main back automatically.
- match: (?=!)
pop: true
main:
- match: foo
scope: test.good
"#;
let line = "foo!";
let expect = ["<source.test>, <test.good>"];
expect_scope_stacks(line, &expect, syntax);
}
#[test]
fn can_parse_syntax_with_newline_in_character_class() {
let syntax = r#"
name: test
scope: source.test
contexts:
main:
- match: foo[\n]
scope: foo.end
- match: foo
scope: foo.any
"#;
let line = "foo";
let expect = ["<source.test>, <foo.end>"];
expect_scope_stacks(line, &expect, syntax);
let line = "foofoofoo";
let expect = [
"<source.test>, <foo.any>",
"<source.test>, <foo.any>",
"<source.test>, <foo.end>",