grammar.rs 15.6 KB
Newer Older
1
use std::collections::BTreeMap as Map;
P
Phodal Huang 已提交
2

P
Phodal Huang 已提交
3
use crate::grammar::line_tokens::{LineTokens, TokenTypeMatcher};
P
Phodal Huang 已提交
4 5
use crate::grammar::local_stack_element::LocalStackElement;
use crate::grammar::{MatchRuleResult, ScopeListElement, StackElement};
P
Phodal Huang 已提交
6
use crate::inter::{IRawGrammar, IRawRepository, IRawRepositoryMap, IRawRule};
P
Phodal Huang 已提交
7
use crate::rule::abstract_rule::RuleEnum;
P
Phodal Huang 已提交
8 9
use crate::rule::rule_factory::RuleFactory;
use crate::rule::{
P
Phodal Huang 已提交
10
    AbstractRule, EmptyRule, IGrammarRegistry, IRuleFactoryHelper,
P
Phodal Huang 已提交
11 12
    IRuleRegistry,
};
P
Phodal Huang 已提交
13
use core::cmp;
P
Phodal Huang 已提交
14
use scie_scanner::scanner::scanner::{IOnigCaptureIndex};
P
Phodal Huang 已提交
15

P
Phodal Huang 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28
pub struct IToken {
    pub start_index: i32,
    pub end_index: i32,
    pub scopes: Vec<String>,
}

pub struct ITokenizeLineResult {
    pub tokens: Vec<IToken>,
    pub rule_stack: Box<StackElement>,
}

pub struct ITokenizeLineResult2 {
    pub tokens: Vec<i32>,
P
Phodal Huang 已提交
29
    pub rule_stack: Box<StackElement>,
P
Phodal Huang 已提交
30 31 32 33 34
}

pub trait IGrammar {
    fn tokenize_line(line_text: String, prev_state: Option<StackElement>) -> ITokenizeLineResult;
    /**
P
Phodal Huang 已提交
35 36 37 38 39 40 41 42 43
     * Tokenize `lineText` using previous line state `prevState`.
     * The result contains the tokens in binary format, resolved with the following information:
     *  - language
     *  - token type (regex, string, comment, other)
     *  - font style
     *  - foreground color
     *  - background color
     * e.g. for getting the languageId: `(metadata & MetadataConsts.LANGUAGEID_MASK) >>> MetadataConsts.LANGUAGEID_OFFSET`
     */
P
Phodal Huang 已提交
44
    fn tokenize_line2(line_text: String, prev_state: Option<StackElement>) -> ITokenizeLineResult2;
P
Phodal Huang 已提交
45 46
}

P
Phodal Huang 已提交
47
pub trait Matcher {}
P
Phodal Huang 已提交
48

P
Phodal Huang 已提交
49
#[derive(Debug, Clone)]
P
Phodal Huang 已提交
50
pub struct Grammar {
51
    root_id: i32,
P
Phodal Huang 已提交
52
    grammar: IRawGrammar,
53
    pub last_rule_id: i32,
54
    pub rule_id2desc: Map<i32, Box<dyn AbstractRule>>,
P
Phodal Huang 已提交
55
    pub _token_type_matchers: Vec<TokenTypeMatcher>,
P
Phodal Huang 已提交
56 57
}

P
Phodal Huang 已提交
58
pub fn init_grammar(grammar: IRawGrammar, _base: Option<IRawRule>) -> IRawGrammar {
P
Phodal Huang 已提交
59 60 61
    let mut _grammar = grammar.clone();

    let mut new_based: IRawRule = IRawRule::new();
P
Phodal Huang 已提交
62 63 64
    if let Some(repo) = grammar.clone().repository {
        new_based.location = repo.clone().location;
    }
P
Phodal Huang 已提交
65 66
    new_based.patterns = Some(grammar.clone().patterns.clone());
    new_based.name = grammar.clone().name;
P
Phodal Huang 已提交
67 68 69 70

    let mut repository_map = IRawRepositoryMap::new();
    repository_map.base_s = Some(new_based.clone());
    repository_map.self_s = Some(new_based.clone());
P
Phodal Huang 已提交
71 72 73
    if let Some(repo) = grammar.clone().repository {
        repository_map.name_map = repo.clone().map.name_map.clone();
    }
P
Phodal Huang 已提交
74 75 76

    _grammar.repository = Some(IRawRepository {
        map: Box::new(repository_map.clone()),
77
        location: None,
P
Phodal Huang 已提交
78 79 80 81 82
    });

    _grammar
}

P
Phodal Huang 已提交
83
impl Grammar {
P
Phodal Huang 已提交
84
    pub fn new(grammar: IRawGrammar) -> Grammar {
P
Phodal Huang 已提交
85
        let _grammar = init_grammar(grammar.clone(), None);
P
Phodal Huang 已提交
86
        Grammar {
87
            last_rule_id: 0,
P
Phodal Huang 已提交
88
            grammar: _grammar,
P
Phodal Huang 已提交
89
            root_id: -1,
90
            rule_id2desc: Map::new(),
P
Phodal Huang 已提交
91
            _token_type_matchers: vec![],
P
Phodal Huang 已提交
92 93 94
        }
    }

P
Phodal Huang 已提交
95
    fn tokenize(
96
        &mut self,
P
Phodal Huang 已提交
97
        line_text: String,
98
        prev_state: Option<StackElement>,
P
Phodal Huang 已提交
99 100
        emit_binary_tokens: bool,
    ) {
101 102
        if self.root_id.clone() == -1 {
            let mut repository = self.grammar.repository.clone().unwrap();
P
Phodal Huang 已提交
103
            let based = repository.clone().map.self_s.unwrap();
P
Phodal Huang 已提交
104 105 106 107 108 109
            self.root_id = RuleFactory::get_compiled_rule_id(
                based.clone(),
                self,
                &mut repository.clone(),
                String::from(""),
            );
110
        }
P
Phodal Huang 已提交
111

P
Phodal Huang 已提交
112
        let mut is_first_line: bool = false;
113 114 115

        let mut current_state = StackElement::null();

P
Phodal Huang 已提交
116
        match prev_state.clone() {
P
Phodal Huang 已提交
117
            None => is_first_line = true,
118 119 120 121
            Some(state) => {
                if state == StackElement::null() {
                    is_first_line = true
                }
122 123

                current_state = state;
P
Phodal Huang 已提交
124
            }
125
        }
P
Phodal Huang 已提交
126

P
Phodal Huang 已提交
127
        if is_first_line {
P
Phodal Huang 已提交
128
            // let scope_list = ScopeListElement::default();
P
Phodal Huang 已提交
129
            let _root_scope_name = self.get_rule(self.root_id.clone()).get_name(None, None);
P
Phodal Huang 已提交
130 131 132 133 134
            let mut root_scope_name = String::from("unknown");
            if let Some(name) = _root_scope_name {
                root_scope_name = name
            }

P
Phodal Huang 已提交
135
            let scope_list = ScopeListElement::new(None, root_scope_name);
136
            let state = StackElement::new(
P
Phodal Huang 已提交
137 138 139 140 141 142 143 144
                None,
                self.root_id.clone(),
                -1,
                -1,
                false,
                None,
                scope_list.clone(),
                scope_list.clone(),
145 146 147
            );

            current_state = state;
P
Phodal Huang 已提交
148 149
        } else {
            is_first_line = false;
P
Phodal Huang 已提交
150 151
        }

P
Phodal Huang 已提交
152
        let format_line_text = format!("{:?}\n", line_text);
P
Phodal Huang 已提交
153 154 155 156 157
        let line_tokens = LineTokens::new(
            emit_binary_tokens,
            line_text,
            self._token_type_matchers.clone(),
        );
P
Phodal Huang 已提交
158 159 160 161
        self.tokenize_string(
            format_line_text.parse().unwrap(),
            is_first_line,
            0,
162
            &mut current_state,
P
Phodal Huang 已提交
163 164
            line_tokens,
            true,
165
        );
P
Phodal Huang 已提交
166 167
    }

P
Phodal Huang 已提交
168 169 170
    pub fn tokenize_string(
        &mut self,
        line_text: String,
171 172
        origin_is_first: bool,
        origin_line_pos: i32,
173 174
        stack: &mut StackElement,
        mut line_tokens: LineTokens,
P
Phodal Huang 已提交
175
        check_while_conditions: bool,
176
    ) -> Option<StackElement> {
P
Phodal Huang 已提交
177
        let _line_length = line_text.len();
178
        let mut _stop = false;
179
        let anchor_position = -1;
P
Phodal Huang 已提交
180 181

        if check_while_conditions {
P
Phodal Huang 已提交
182 183 184
            // todo: add realy logic
            self.check_while_conditions(
                line_text.clone(),
185 186
                origin_is_first.clone(),
                origin_line_pos.clone(),
187
                stack.clone(),
P
Phodal Huang 已提交
188 189
                line_tokens.clone(),
            );
P
Phodal Huang 已提交
190 191
        }

192 193
        let line_pos = origin_line_pos.clone();
        let is_first_line = origin_is_first.clone();
194
        while !_stop {
P
Phodal Huang 已提交
195 196 197 198 199 200 201
            let r = self.match_rule(
                line_text.clone(),
                is_first_line,
                line_pos,
                stack,
                anchor_position,
            );
202 203
            if let None = r {
                _stop = true;
P
Phodal Huang 已提交
204
                return None;
205 206
            }

P
Phodal Huang 已提交
207 208 209 210 211
            let capture_result = r.unwrap();
            let capture_indices = capture_result.capture_indices;
            let matched_rule_id = capture_result.matched_rule_id;
            if matched_rule_id == -1 {
                println!("todo: matched the `end` for this rule => pop it");
212 213
                _stop = true;
                return None;
P
Phodal Huang 已提交
214 215
            } else {
                let rule = self.get_rule(matched_rule_id);
216
                line_tokens.produce(stack, capture_indices[0].start as i32);
P
Phodal Huang 已提交
217
                // let before_push = stack.clone();
P
Phodal Huang 已提交
218 219 220 221 222 223
                let scope_name =
                    rule.get_name(Some(line_text.clone()), Some(capture_indices.clone()));
                let name_scopes_list = stack
                    .content_name_scopes_list
                    .clone()
                    .push(self, scope_name);
P
Phodal Huang 已提交
224 225 226 227
                let mut begin_rule_capture_eol = false;
                if capture_indices[0].end == _line_length {
                    begin_rule_capture_eol = true;
                }
228
                let mut new_stack = stack.clone().push(
P
Phodal Huang 已提交
229 230 231 232 233 234
                    matched_rule_id,
                    line_pos,
                    anchor_position,
                    begin_rule_capture_eol,
                    None,
                    name_scopes_list.clone(),
P
Phodal Huang 已提交
235
                    name_scopes_list.clone(),
P
Phodal Huang 已提交
236 237
                );

P
Phodal Huang 已提交
238 239
                match rule.get_rule_instance() {
                    RuleEnum::BeginEndRule(begin_rule) => {
240
                        Grammar::handle_captures(self, line_text.clone(), is_first_line, &mut new_stack, line_tokens.clone(), begin_rule.begin_captures, capture_indices.clone());
241 242 243 244 245 246 247 248 249 250 251

                        _stop = true;
                        return None;
                    }
                    RuleEnum::BeginWhileRule(while_rule) => {
                        _stop = true;
                        return None;
                    }
                    _ => {
                        _stop = true;
                        return None;
P
Phodal Huang 已提交
252 253
                    }
                }
P
Phodal Huang 已提交
254
            }
255 256 257 258 259
            //
            // if capture_indices[0].end > line_pos as usize {
            //     line_pos = capture_indices[0].end as i32;
            //     is_first_line = false;
            // }
260
        }
261
        Some(stack.clone())
P
Phodal Huang 已提交
262 263
    }

P
Phodal Huang 已提交
264 265 266 267 268 269 270 271 272
    pub fn handle_captures(
        grammar: &mut Grammar,
        line_text: String,
        is_first_line: bool,
        stack: &mut StackElement,
        mut line_tokens: LineTokens,
        captures: Vec<Box<dyn AbstractRule>>,
        capture_indices: Vec<IOnigCaptureIndex>,
    ) {
P
Phodal Huang 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
        let captures_len = captures.clone().len();
        if captures_len == 0 {
            return;
        }

        let len = cmp::min(captures_len, capture_indices.len());
        let mut local_stack: Vec<LocalStackElement> = vec![];
        let max_end = capture_indices[0].end;
        for i in 0..len {
            let capture_rule = captures[i].clone();
            // if let None = capture_rule {
            //     continue
            // }

            let capture_index = capture_indices[i].clone();
            if capture_index.length == 0 {
                continue;
            }

            if capture_index.start > max_end {
                continue;
            }

P
Phodal Huang 已提交
296 297 298
            while local_stack.len() > 0
                && local_stack[local_stack.len() - 1].end_pos <= capture_index.start as i32
            {
P
Phodal Huang 已提交
299 300 301
                let mut local_stack_element = local_stack[local_stack.len() - 1].clone();
                line_tokens.produce_from_scopes(
                    &mut local_stack_element.scopes,
P
Phodal Huang 已提交
302
                    local_stack_element.end_pos,
P
Phodal Huang 已提交
303 304 305
                );
                local_stack.pop();
            }
306 307 308 309 310 311 312 313 314 315

            if local_stack.len() > 0 {
                let mut local_stack_element = local_stack[local_stack.len() - 1].clone();
                line_tokens.produce_from_scopes(
                    &mut local_stack_element.scopes,
                    local_stack_element.end_pos,
                );
            } else {
                line_tokens.produce(stack, capture_index.start as i32);
            }
316 317

            capture_rule
P
Phodal Huang 已提交
318 319
        }
    }
P
Phodal Huang 已提交
320

P
Phodal Huang 已提交
321 322 323 324 325
    pub fn check_while_conditions(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
326
        _stack: StackElement,
P
Phodal Huang 已提交
327 328 329
        line_tokens: LineTokens,
    ) {
        let mut anchor_position = -1;
P
Phodal Huang 已提交
330 331 332
        if _stack.begin_rule_captured_eol {
            anchor_position = 0
        }
P
Phodal Huang 已提交
333 334
        // let while_rules = vec![];
    }
P
Phodal Huang 已提交
335

P
Phodal Huang 已提交
336 337 338 339 340
    pub fn match_rule_or_injections(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
341
        stack: &mut StackElement,
P
Phodal Huang 已提交
342
        anchor_position: i32,
P
Phodal Huang 已提交
343
    ) {
P
Phodal Huang 已提交
344 345 346 347
        let match_result =
            self.match_rule(line_text, is_first_line, line_pos, stack, anchor_position);
        if let Some(result) = match_result {
        } else {
348 349 350
            // None
        };
        // todo: get injections logic
P
Phodal Huang 已提交
351 352 353 354 355 356 357
    }

    pub fn match_rule(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
358
        stack: &mut StackElement,
P
Phodal Huang 已提交
359
        anchor_position: i32,
360
    ) -> Option<MatchRuleResult> {
361
        let mut rule = stack.get_rule(self);
P
Phodal Huang 已提交
362
        let mut rule_scanner = rule.compile(
P
Phodal Huang 已提交
363
            self,
P
Phodal Huang 已提交
364
            stack.end_rule.clone(),
P
Phodal Huang 已提交
365 366 367
            is_first_line,
            line_pos == anchor_position,
        );
P
Phodal Huang 已提交
368 369 370
        let r = rule_scanner
            .scanner
            .find_next_match_sync(line_text, line_pos);
P
Phodal Huang 已提交
371
        if let Some(result) = r {
372 373
            let match_rule_result = MatchRuleResult {
                capture_indices: result.capture_indices,
374
                matched_rule_id: rule_scanner.rules[result.index],
375 376 377 378
            };

            println!("{:?}", match_rule_result.clone());
            Some(match_rule_result)
P
Phodal Huang 已提交
379 380 381
        } else {
            None
        }
P
Phodal Huang 已提交
382
    }
P
Phodal Huang 已提交
383

384
    pub fn tokenize_line(&mut self, line_text: String, prev_state: Option<StackElement>) {
P
Phodal Huang 已提交
385 386 387
        self.tokenize(line_text, prev_state, false)
    }

P
Phodal Huang 已提交
388 389
    pub fn tokenize_line2(&self, line_text: String, prev_state: Option<StackElement>) {}
}
P
Phodal Huang 已提交
390 391 392 393

impl IRuleFactoryHelper for Grammar {}

impl IGrammarRegistry for Grammar {
P
Phodal Huang 已提交
394 395 396 397 398
    fn get_external_grammar(
        &self,
        scope_name: String,
        repository: IRawRepository,
    ) -> Option<IRawGrammar> {
P
Phodal Huang 已提交
399 400 401 402 403
        None
    }
}

impl IRuleRegistry for Grammar {
P
Phodal Huang 已提交
404 405
    fn register_id(&mut self) -> i32 {
        self.last_rule_id = self.last_rule_id + 1;
P
Phodal Huang 已提交
406
        self.last_rule_id.clone()
P
Phodal Huang 已提交
407 408
    }

P
Phodal Huang 已提交
409 410 411
    fn get_rule(&mut self, pattern_id: i32) -> Box<dyn AbstractRule> {
        if let Some(rule) = self.rule_id2desc.get_mut(&pattern_id) {
            return rule.to_owned();
P
Phodal Huang 已提交
412
        }
P
Phodal Huang 已提交
413
        Box::from(EmptyRule {})
P
Phodal Huang 已提交
414
    }
P
Phodal Huang 已提交
415

P
Phodal Huang 已提交
416
    fn register_rule(&mut self, result: Box<dyn AbstractRule>) -> Box<dyn AbstractRule> {
P
Phodal Huang 已提交
417
        self.rule_id2desc
P
Phodal Huang 已提交
418
            .insert(result.id().clone(), result.clone());
419
        result
P
Phodal Huang 已提交
420
    }
P
Phodal Huang 已提交
421 422 423 424
}

#[cfg(test)]
mod tests {
P
Phodal Huang 已提交
425
    use std::fs::File;
426
    use std::io::{Read, Write};
P
Phodal Huang 已提交
427
    use std::path::Path;
P
Phodal Huang 已提交
428

P
Phodal Huang 已提交
429
    use crate::grammar::Grammar;
P
Phodal Huang 已提交
430
    use crate::inter::IRawGrammar;
431
    use crate::rule::IRuleRegistry;
P
Phodal Huang 已提交
432

P
Phodal Huang 已提交
433
    #[test]
P
Phodal Huang 已提交
434
    fn should_build_json_code() {
435 436 437 438 439 440 441 442
        let code = "
#include <stdio.h>
int main() {
printf(\"Hello, World!\");
return 0;
}
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/c.json", code);
443
        // assert_eq!(grammar.rule_id2desc.len(), 162);
444
        // debug_output(&grammar, String::from("program.json"));
445 446
    }

P
Phodal Huang 已提交
447 448 449
    #[test]
    fn should_build_text_grammar() {
        let code = "
P
Phodal Huang 已提交
450
GitHub 漫游指南
P
Phodal Huang 已提交
451 452
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/text.json", code);
453
        assert_eq!(grammar.rule_id2desc.len(), 8);
454 455 456
    }

    fn debug_output(grammar: &Grammar, path: String) {
P
Phodal Huang 已提交
457
        let j = serde_json::to_string(&grammar.rule_id2desc).unwrap();
458
        let mut file = File::create(path).unwrap();
P
Phodal Huang 已提交
459
        match file.write_all(j.as_bytes()) {
P
Phodal Huang 已提交
460 461
            Ok(_) => {}
            Err(_) => {}
P
Phodal Huang 已提交
462
        };
P
Phodal Huang 已提交
463 464
    }

465 466 467 468
    #[test]
    fn should_build_json_grammar() {
        let code = "{}";
        let grammar = to_grammar("test-cases/first-mate/fixtures/json.json", code);
469 470 471 472 473 474 475 476 477
        assert_eq!(grammar.rule_id2desc.len(), 22);
        debug_output(&grammar, String::from("program.json"));
    }

    #[test]
    fn should_build_html_grammar() {
        let code = "{}";
        let grammar = to_grammar("test-cases/first-mate/fixtures/html.json", code);
        assert_eq!(grammar.rule_id2desc.len(), 67);
478 479 480
        debug_output(&grammar, String::from("program.json"));
    }

P
Phodal Huang 已提交
481 482
    #[test]
    fn should_build_makefile_grammar() {
483 484 485 486 487 488 489 490 491 492
        let code = "CC=gcc
CFLAGS=-I.
DEPS = hellomake.h
OBJ = hellomake.o hellofunc.o

%.o: %.c $(DEPS)
	$(CC) -c -o $@ $< $(CFLAGS)

hellomake: $(OBJ)
	$(CC) -o $@ $^ $(CFLAGS)
P
Phodal Huang 已提交
493
";
494
        let mut grammar = to_grammar("test-cases/first-mate/fixtures/makefile.json", code);
P
Phodal Huang 已提交
495
        assert_eq!(grammar.rule_id2desc.len(), 64);
496
        assert_eq!(grammar.get_rule(1).patterns_length(), 4);
P
Phodal Huang 已提交
497 498 499
        debug_output(&grammar, String::from("program.json"));
    }

500 501
    fn to_grammar(grammar_path: &str, code: &str) -> Grammar {
        let path = Path::new(grammar_path);
P
Phodal Huang 已提交
502 503 504 505 506 507
        let mut file = File::open(path).unwrap();
        let mut data = String::new();
        file.read_to_string(&mut data).unwrap();

        let g: IRawGrammar = serde_json::from_str(&data).unwrap();

P
Phodal Huang 已提交
508
        let mut grammar = Grammar::new(g);
509
        let c_code = String::from(code);
P
Phodal Huang 已提交
510 511 512
        for line in c_code.lines() {
            grammar.tokenize_line(String::from(line), None)
        }
513
        grammar
P
Phodal Huang 已提交
514 515
    }
}