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
use super::syntax_definition::*;
use super::scope::*;
use onig::{self, Region};
use std::usize;
use std::collections::{HashMap, HashSet};
use std::i32;
use std::hash::BuildHasherDefault;
use fnv::FnvHasher;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseState {
stack: Vec<StateLevel>,
first_line: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct StateLevel {
context: ContextPtr,
prototype: Option<ContextPtr>,
captures: Option<(Region, String)>,
}
#[derive(Debug)]
struct RegexMatch {
regions: Region,
context: ContextPtr,
pat_index: usize,
match_ptr: *const MatchPattern,
}
type SearchCache = HashMap<*const MatchPattern, Option<Region>, BuildHasherDefault<FnvHasher>>;
type MatchedPatterns = HashSet<*const MatchPattern, BuildHasherDefault<FnvHasher>>;
impl ParseState {
pub fn new(syntax: &SyntaxDefinition) -> ParseState {
let start_state = StateLevel {
context: syntax.contexts["main"].clone(),
prototype: None,
captures: None,
};
ParseState {
stack: vec![start_state],
first_line: true,
}
}
pub fn parse_line(&mut self, line: &str) -> Vec<(usize, ScopeStackOp)> {
assert!(self.stack.len() > 0,
"Somehow main context was popped from the stack");
let mut match_start = 0;
let mut prev_match_start = 0;
let mut res = Vec::new();
if self.first_line {
let cur_level = &self.stack[self.stack.len() - 1];
let context = cur_level.context.borrow();
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::with_capacity(8);
let fnv = BuildHasherDefault::<FnvHasher>::default();
let mut search_cache: SearchCache = HashMap::with_capacity_and_hasher(128, fnv);
let fnv2 = BuildHasherDefault::<FnvHasher>::default();
let mut matched: MatchedPatterns = HashSet::with_capacity_and_hasher(4, fnv2);
while self.parse_next_token(line,
&mut match_start,
&mut search_cache,
&mut matched,
&mut regions,
&mut res) {
if match_start != prev_match_start {
matched.clear();
}
prev_match_start = match_start;
}
res
}
fn parse_next_token(&mut self,
line: &str,
start: &mut usize,
search_cache: &mut SearchCache,
matched: &mut MatchedPatterns,
regions: &mut Region,
ops: &mut Vec<(usize, ScopeStackOp)>)
-> bool {
let cur_match = {
let cur_level = &self.stack[self.stack.len() - 1];
let mut min_start = usize::MAX;
let mut cur_match: Option<RegexMatch> = None;
let prototype: Option<ContextPtr> = {
let ctx_ref = cur_level.context.borrow();
ctx_ref.prototype.clone()
};
let context_chain = self.stack
.iter()
.filter_map(|lvl| lvl.prototype.as_ref().cloned())
.chain(prototype.into_iter())
.chain(Some(cur_level.context.clone()).into_iter());
for ctx in context_chain {
for (pat_context_ptr, pat_index) in context_iter(ctx) {
let mut pat_context = pat_context_ptr.borrow_mut();
let mut match_pat = pat_context.match_at_mut(pat_index);
let match_ptr = match_pat as *const MatchPattern;
if matched.contains(&match_ptr) {
continue;
}
if let Some(maybe_region) =
search_cache.get(&match_ptr) {
let mut valid_entry = true;
if let Some(ref region) = *maybe_region {
let match_start = region.pos(0).unwrap().0;
if match_start < *start {
valid_entry = false;
} else if match_start < min_start {
min_start = match_start;
cur_match = Some(RegexMatch {
regions: region.clone(),
context: pat_context_ptr.clone(),
pat_index: pat_index,
match_ptr: match_ptr,
});
}
}
if valid_entry {
continue;
}
}
match_pat.ensure_compiled_if_possible();
let refs_regex = if match_pat.has_captures && cur_level.captures.is_some() {
let &(ref region, ref s) = cur_level.captures.as_ref().unwrap();
Some(match_pat.compile_with_refs(region, s))
} else {
None
};
let regex = if let Some(ref rgx) = refs_regex {
rgx
} else {
match_pat.regex.as_ref().unwrap()
};
let matched = regex.search_with_options(line,
*start,
line.len(),
onig::SEARCH_OPTION_NONE,
Some(regions));
if let Some(match_start) = matched {
let match_end = regions.pos(0).unwrap().1;
let does_something = match match_pat.operation {
MatchOperation::None => match_start != match_end,
_ => true,
};
if refs_regex.is_none() && does_something {
search_cache.insert(match_pat, Some(regions.clone()));
}
if match_start < min_start && does_something {
min_start = match_start;
cur_match = Some(RegexMatch {
regions: regions.clone(),
context: pat_context_ptr.clone(),
pat_index: pat_index,
match_ptr: match_ptr,
});
}
} else if refs_regex.is_none() {
search_cache.insert(match_pat, None);
}
}
}
cur_match
};
if let Some(reg_match) = cur_match {
let (_, match_end) = reg_match.regions.pos(0).unwrap();
*start = match_end;
let level_context = self.stack[self.stack.len() - 1].context.clone();
matched.insert(reg_match.match_ptr);
self.exec_pattern(line, reg_match, level_context, ops);
true
} else {
false
}
}
fn exec_pattern(&mut self,
line: &str,
reg_match: RegexMatch,
level_context_ptr: ContextPtr,
ops: &mut Vec<(usize, ScopeStackOp)>)
-> bool {
let (match_start, match_end) = reg_match.regions.pos(0).unwrap();
let context = reg_match.context.borrow();
let pat = context.match_at(reg_match.pat_index);
let level_context = level_context_ptr.borrow();
self.push_meta_ops(true, match_start, &*level_context, &pat.operation, ops);
for s in &pat.scope {
ops.push((match_start, ScopeStackOp::Push(*s)));
}
if let Some(ref capture_map) = pat.captures {
let mut map: Vec<((usize, i32), ScopeStackOp)> = Vec::new();
for (cap_index, scopes) in capture_map.iter() {
if let Some((cap_start, cap_end)) = reg_match.regions.pos(*cap_index) {
if cap_start == cap_end {
continue;
}
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() {
ops.push((match_end, ScopeStackOp::Pop(pat.scope.len())));
}
self.push_meta_ops(false, match_end, &*level_context, &pat.operation, ops);
self.perform_op(line, ®_match.regions, pat)
}
fn push_meta_ops(&self,
initial: bool,
index: usize,
cur_context: &Context,
match_op: &MatchOperation,
ops: &mut Vec<(usize, ScopeStackOp)>) {
let involves_pop = match *match_op {
MatchOperation::Pop |
MatchOperation::Set(_) => true,
MatchOperation::Push(_) |
MatchOperation::None => false,
};
if involves_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())));
}
}
match *match_op {
MatchOperation::Push(ref context_refs) |
MatchOperation::Set(ref context_refs) => {
for r in context_refs {
let ctx_ptr = r.resolve();
let ctx = ctx_ptr.borrow();
let v = if initial {
&ctx.meta_scope
} else {
&ctx.meta_content_scope
};
for scope in v.iter() {
ops.push((index, ScopeStackOp::Push(*scope)));
}
}
}
MatchOperation::None |
MatchOperation::Pop => (),
}
}
fn perform_op(&mut self, line: &str, regions: &Region, pat: &MatchPattern) -> bool {
let ctx_refs = match pat.operation {
MatchOperation::Push(ref ctx_refs) => ctx_refs,
MatchOperation::Set(ref ctx_refs) => {
self.stack.pop();
ctx_refs
}
MatchOperation::Pop => {
self.stack.pop();
return true;
}
MatchOperation::None => return false,
};
for (i, r) in ctx_refs.iter().enumerate() {
let proto = if i == 0 {
pat.with_prototype.clone()
} else {
None
};
let ctx_ptr = r.resolve();
let captures = {
let ctx = ctx_ptr.borrow();
if ctx.uses_backrefs {
Some((regions.clone(), line.to_owned()))
} else {
None
}
};
self.stack.push(StateLevel {
context: ctx_ptr,
prototype: proto,
captures: captures,
});
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use parsing::{SyntaxSet, Scope, ScopeStack};
use util::debug_print_ops;
#[test]
fn can_parse() {
use parsing::ScopeStackOp::{Push, Pop};
let ps = SyntaxSet::load_from_folder("testdata/Packages").unwrap();
let mut state = {
let syntax = ps.find_syntax_by_name("Ruby on Rails").unwrap();
ParseState::new(syntax)
};
let mut state2 = {
let syntax = ps.find_syntax_by_name("HTML (Rails)").unwrap();
ParseState::new(syntax)
};
let mut state3 = {
let syntax = ps.find_syntax_by_name("C").unwrap();
ParseState::new(syntax)
};
let line = "module Bob::Wow::Troll::Five; 5; end";
let ops = state.parse_line(line);
debug_print_ops(line, &ops);
let test_ops = 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(1)),
(7, Push(Scope::new("entity.name.type.module.ruby").unwrap())),
(7, Push(Scope::new("entity.other.inherited-class.module.first.ruby").unwrap())),
(10, Push(Scope::new("punctuation.separator.inheritance.ruby").unwrap())),
(12, Pop(1)),
(12, Pop(1)),
];
assert_eq!(&ops[0..test_ops.len()], &test_ops[..]);
let line2 = "def lol(wow = 5)";
let ops2 = state.parse_line(line2);
debug_print_ops(line2, &ops2);
let test_ops2 =
vec![(0, Push(Scope::new("meta.function.method.with-arguments.ruby").unwrap())),
(0, Push(Scope::new("keyword.control.def.ruby").unwrap())),
(3, Pop(1)),
(4, Push(Scope::new("entity.name.function.ruby").unwrap())),
(7, Pop(1)),
(7, Push(Scope::new("punctuation.definition.parameters.ruby").unwrap())),
(8, Pop(1)),
(8, Push(Scope::new("variable.parameter.function.ruby").unwrap())),
(12, Push(Scope::new("keyword.operator.assignment.ruby").unwrap())),
(13, Pop(1)),
(14, Push(Scope::new("constant.numeric.ruby").unwrap())),
(15, Pop(1)),
(15, Pop(1)),
(15, Push(Scope::new("punctuation.definition.parameters.ruby").unwrap())),
(16, Pop(1)),
(16, Pop(1))];
assert_eq!(ops2, test_ops2);
let line3 = "<script>var lol = '<% def wow(";
let ops3 = state2.parse_line(line3);
debug_print_ops(line3, &ops3);
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("string.quoted.single.js").unwrap());
test_stack.push(Scope::new("source.ruby.rails.embedded.html").unwrap());
test_stack.push(Scope::new("meta.function.method.with-arguments.ruby").unwrap());
test_stack.push(Scope::new("variable.parameter.function.ruby").unwrap());
let mut test_stack2 = ScopeStack::new();
for &(_, ref op) in ops3.iter() {
test_stack2.apply(op);
}
assert_eq!(test_stack2, test_stack);
let line4 = "lol = <<-END wow END";
let ops4 = state.parse_line(line4);
debug_print_ops(line4, &ops4);
let test_ops4 = vec![
(4, Push(Scope::new("keyword.operator.assignment.ruby").unwrap())),
(5, Pop(1)),
(6, Push(Scope::new("string.unquoted.heredoc.ruby").unwrap())),
(6, Push(Scope::new("punctuation.definition.string.begin.ruby").unwrap())),
(12, Pop(1)),
(16, Push(Scope::new("punctuation.definition.string.end.ruby").unwrap())),
(20, Pop(1)),
(20, Pop(1)),
];
assert_eq!(ops4, test_ops4);
let line5 = "struct{estruct";
let ops5 = state3.parse_line(line5);
assert_eq!(ops5.len(), 10);
}
}