grammar.rs 24.9 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
use crate::rule::rule_factory::RuleFactory;
P
Phodal Huang 已提交
9 10 11
use crate::rule::{
    AbstractRule, BeginWhileRule, EmptyRule, IGrammarRegistry, IRuleFactoryHelper, IRuleRegistry,
};
P
Phodal Huang 已提交
12
use core::cmp;
13
use scie_scanner::scanner::scanner::{IOnigCaptureIndex, IOnigMatch};
P
Phodal Huang 已提交
14
use std::borrow::Borrow;
15
use std::alloc::handle_alloc_error;
P
Phodal Huang 已提交
16

P
Phodal Huang 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29
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 已提交
30
    pub rule_stack: Box<StackElement>,
P
Phodal Huang 已提交
31 32 33 34 35
}

pub trait IGrammar {
    fn tokenize_line(line_text: String, prev_state: Option<StackElement>) -> ITokenizeLineResult;
    /**
P
Phodal Huang 已提交
36 37 38 39 40 41 42 43 44
     * 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 已提交
45
    fn tokenize_line2(line_text: String, prev_state: Option<StackElement>) -> ITokenizeLineResult2;
P
Phodal Huang 已提交
46 47
}

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

P
Phodal Huang 已提交
50 51 52
#[derive(Debug, Clone)]
pub struct CheckWhileRuleResult {
    pub rule: Box<BeginWhileRule>,
53 54 55 56 57 58
    pub stack: Box<StackElement>,
}

#[derive(Debug, Clone)]
pub struct CheckWhileConditionResult {
    pub stack: Box<StackElement>,
P
Phodal Huang 已提交
59
    pub line_pos: i32,
60
    pub anchor_position: i32,
P
Phodal Huang 已提交
61
    pub is_first_line: bool,
P
Phodal Huang 已提交
62 63
}

P
Phodal Huang 已提交
64 65 66 67
#[derive(Debug, Clone)]
pub struct TokenizeResult {
    line_length: usize,
    line_tokens: Box<LineTokens>,
P
Phodal Huang 已提交
68
    rule_stack: Box<Option<StackElement>>,
P
Phodal Huang 已提交
69 70
}

P
Phodal Huang 已提交
71
#[derive(Debug, Clone)]
P
Phodal Huang 已提交
72
pub struct Grammar {
73
    root_id: i32,
P
Phodal Huang 已提交
74
    grammar: IRawGrammar,
75
    pub last_rule_id: i32,
76
    pub rule_id2desc: Map<i32, Box<dyn AbstractRule>>,
P
Phodal Huang 已提交
77
    pub _token_type_matchers: Vec<TokenTypeMatcher>,
P
Phodal Huang 已提交
78 79
}

P
Phodal Huang 已提交
80
pub fn init_grammar(grammar: IRawGrammar, _base: Option<IRawRule>) -> IRawGrammar {
P
Phodal Huang 已提交
81 82 83
    let mut _grammar = grammar.clone();

    let mut new_based: IRawRule = IRawRule::new();
P
Phodal Huang 已提交
84 85 86
    if let Some(repo) = grammar.clone().repository {
        new_based.location = repo.clone().location;
    }
P
Phodal Huang 已提交
87 88
    new_based.patterns = Some(grammar.clone().patterns.clone());
    new_based.name = grammar.clone().name;
P
Phodal Huang 已提交
89 90 91 92

    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 已提交
93 94 95
    if let Some(repo) = grammar.clone().repository {
        repository_map.name_map = repo.clone().map.name_map.clone();
    }
P
Phodal Huang 已提交
96 97 98

    _grammar.repository = Some(IRawRepository {
        map: Box::new(repository_map.clone()),
99
        location: None,
P
Phodal Huang 已提交
100 101 102 103 104
    });

    _grammar
}

P
Phodal Huang 已提交
105
impl Grammar {
P
Phodal Huang 已提交
106
    pub fn new(grammar: IRawGrammar) -> Grammar {
P
Phodal Huang 已提交
107
        let _grammar = init_grammar(grammar.clone(), None);
P
Phodal Huang 已提交
108
        Grammar {
109
            last_rule_id: 0,
P
Phodal Huang 已提交
110
            grammar: _grammar,
P
Phodal Huang 已提交
111
            root_id: -1,
112
            rule_id2desc: Map::new(),
P
Phodal Huang 已提交
113
            _token_type_matchers: vec![],
P
Phodal Huang 已提交
114 115 116
        }
    }

P
Phodal Huang 已提交
117
    fn tokenize(
118
        &mut self,
P
Phodal Huang 已提交
119
        line_text: String,
120
        prev_state: Option<StackElement>,
P
Phodal Huang 已提交
121
        emit_binary_tokens: bool,
P
Phodal Huang 已提交
122
    ) -> TokenizeResult {
123 124
        if self.root_id.clone() == -1 {
            let mut repository = self.grammar.repository.clone().unwrap();
P
Phodal Huang 已提交
125
            let based = repository.clone().map.self_s.unwrap();
P
Phodal Huang 已提交
126 127 128 129 130 131
            self.root_id = RuleFactory::get_compiled_rule_id(
                based.clone(),
                self,
                &mut repository.clone(),
                String::from(""),
            );
132
        }
P
Phodal Huang 已提交
133

P
Phodal Huang 已提交
134
        let mut is_first_line: bool = false;
135 136 137

        let mut current_state = StackElement::null();

P
Phodal Huang 已提交
138
        match prev_state.clone() {
P
Phodal Huang 已提交
139
            None => is_first_line = true,
140 141 142 143
            Some(state) => {
                if state == StackElement::null() {
                    is_first_line = true
                }
144 145

                current_state = state;
P
Phodal Huang 已提交
146
            }
147
        }
P
Phodal Huang 已提交
148

P
Phodal Huang 已提交
149
        if is_first_line {
P
Phodal Huang 已提交
150
            // let scope_list = ScopeListElement::default();
P
Phodal Huang 已提交
151
            let _root_scope_name = self.get_rule(self.root_id.clone()).get_name(None, None);
P
Phodal Huang 已提交
152 153 154 155 156
            let mut root_scope_name = String::from("unknown");
            if let Some(name) = _root_scope_name {
                root_scope_name = name
            }

P
Phodal Huang 已提交
157
            let scope_list = ScopeListElement::new(None, root_scope_name);
158
            let state = StackElement::new(
P
Phodal Huang 已提交
159 160 161 162 163 164 165 166
                None,
                self.root_id.clone(),
                -1,
                -1,
                false,
                None,
                scope_list.clone(),
                scope_list.clone(),
167 168 169
            );

            current_state = state;
P
Phodal Huang 已提交
170 171
        } else {
            is_first_line = false;
P
Phodal Huang 已提交
172 173
        }

174
        let format_line_text = line_text.clone() + "\n";
P
Phodal Huang 已提交
175
        let mut line_tokens = LineTokens::new(
P
Phodal Huang 已提交
176 177 178 179
            emit_binary_tokens,
            line_text,
            self._token_type_matchers.clone(),
        );
P
Phodal Huang 已提交
180 181
        let next_state = self.tokenize_string(
            format_line_text.clone(),
P
Phodal Huang 已提交
182 183
            is_first_line,
            0,
P
Phodal Huang 已提交
184
            current_state,
185
            &mut line_tokens,
P
Phodal Huang 已提交
186
            true,
187
        );
P
Phodal Huang 已提交
188 189 190 191

        TokenizeResult {
            line_length: format_line_text.clone().len(),
            line_tokens: Box::new(line_tokens),
P
Phodal Huang 已提交
192
            rule_stack: Box::new(next_state),
P
Phodal Huang 已提交
193
        }
P
Phodal Huang 已提交
194 195
    }

P
Phodal Huang 已提交
196 197 198
    pub fn tokenize_string(
        &mut self,
        line_text: String,
199 200
        origin_is_first: bool,
        origin_line_pos: i32,
P
Phodal Huang 已提交
201
        mut stack: StackElement,
202
        mut line_tokens: &mut LineTokens,
P
Phodal Huang 已提交
203
        check_while_conditions: bool,
204
    ) -> Option<StackElement> {
P
Phodal Huang 已提交
205
        let _line_length = line_text.len();
206
        let mut _stop = false;
207
        let mut anchor_position = -1;
208 209
        let mut line_pos = origin_line_pos.clone();
        let mut is_first_line = origin_is_first.clone();
P
Phodal Huang 已提交
210 211

        if check_while_conditions {
212
            // todo: add really logic
213
            let while_check_result = self.check_while_conditions(
P
Phodal Huang 已提交
214
                line_text.clone(),
215 216
                origin_is_first.clone(),
                origin_line_pos.clone(),
217
                stack.clone(),
P
Phodal Huang 已提交
218 219
                line_tokens.clone(),
            );
220 221 222 223
            stack = *while_check_result.stack;
            line_pos = while_check_result.line_pos;
            is_first_line = while_check_result.is_first_line;
            anchor_position = while_check_result.anchor_position;
P
Phodal Huang 已提交
224 225
        }

226
        while !_stop {
P
Phodal Huang 已提交
227 228 229 230
            let r = self.match_rule(
                line_text.clone(),
                is_first_line,
                line_pos,
P
Phodal Huang 已提交
231
                &mut stack,
P
Phodal Huang 已提交
232 233
                anchor_position,
            );
234
            if let None = r {
P
Phodal Huang 已提交
235
                line_tokens.produce(&mut stack, _line_length as i32);
236
                _stop = true;
P
Phodal Huang 已提交
237
                return Some(stack.clone());
238 239
            }

P
Phodal Huang 已提交
240 241 242 243
            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 {
244 245 246 247 248 249 250
                let _popped_rule = stack.get_rule(self);
                if let RuleEnum::BeginEndRule(popped_rule) = _popped_rule.get_rule_instance() {
                    let name_scopes_list = stack.clone().name_scopes_list;
                    line_tokens.produce(&mut stack, capture_indices[0].clone().start as i32);
                    stack = stack.set_content_name_scopes_list(name_scopes_list);
                    Grammar::handle_captures(
                        self,
251
                        line_text.clone(),
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
                        is_first_line,
                        &mut stack,
                        line_tokens,
                        popped_rule.end_captures,
                        capture_indices.clone(),
                    );

                    line_tokens.produce(&mut stack, capture_indices[0].end as i32);
                    let popped = stack.clone();

                    if let Some(_stack) = stack.pop() {
                        stack = _stack;
                    }
                    anchor_position = popped.anchor_pos;
                }
P
Phodal Huang 已提交
267 268
            } else {
                let rule = self.get_rule(matched_rule_id);
P
Phodal Huang 已提交
269
                line_tokens.produce(&mut stack, capture_indices[0].start as i32);
P
Phodal Huang 已提交
270
                // let before_push = stack.clone();
P
Phodal Huang 已提交
271 272
                let scope_name =
                    rule.get_name(Some(line_text.clone()), Some(capture_indices.clone()));
P
Phodal Huang 已提交
273
                let name_scopes_list = stack.content_name_scopes_list.push(self, scope_name);
P
Phodal Huang 已提交
274 275 276 277
                let mut begin_rule_capture_eol = false;
                if capture_indices[0].end == _line_length {
                    begin_rule_capture_eol = true;
                }
P
Phodal Huang 已提交
278
                stack = stack.push(
P
Phodal Huang 已提交
279 280 281 282 283 284
                    matched_rule_id,
                    line_pos,
                    anchor_position,
                    begin_rule_capture_eol,
                    None,
                    name_scopes_list.clone(),
P
Phodal Huang 已提交
285
                    name_scopes_list.clone(),
P
Phodal Huang 已提交
286 287
                );

P
Phodal Huang 已提交
288 289
                match rule.get_rule_instance() {
                    RuleEnum::BeginEndRule(begin_rule) => {
290
                        let push_rule = begin_rule.clone();
P
Phodal Huang 已提交
291
                        Grammar::handle_captures(
P
Phodal Huang 已提交
292 293 294
                            self,
                            line_text.clone(),
                            is_first_line,
P
Phodal Huang 已提交
295
                            &mut stack,
296
                            line_tokens,
P
Phodal Huang 已提交
297 298 299
                            begin_rule.begin_captures,
                            capture_indices.clone(),
                        );
P
Phodal Huang 已提交
300

P
Phodal Huang 已提交
301
                        line_tokens.produce(&mut stack, capture_indices[0].end.clone() as i32);
302
                        anchor_position = capture_indices[0].end.clone() as i32;
P
Phodal Huang 已提交
303 304
                        let content_name = push_rule
                            .get_name(Some(line_text.clone()), Some(capture_indices.clone()));
305 306 307 308 309 310
                        let content_name_scopes_list = name_scopes_list.push(self, content_name);
                        // todo: not used
                        // let temp_stack = &mut stack.set_content_name_scopes_list(content_name_scopes_list);
                        // if push_rule.endHasBackReferences {
                        //
                        // }
311

312 313 314
                        // if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {
                        // _stop = true;
                        // return None;
315 316 317
                    }
                    RuleEnum::BeginWhileRule(while_rule) => {
                        _stop = true;
P
Phodal Huang 已提交
318
                        return Some(stack.clone());
319 320 321
                    }
                    _ => {
                        _stop = true;
P
Phodal Huang 已提交
322
                        return Some(stack.clone());
P
Phodal Huang 已提交
323 324
                    }
                }
P
Phodal Huang 已提交
325
            }
326 327 328 329 330

            if capture_indices[0].end > line_pos as usize {
                line_pos = capture_indices[0].end as i32;
                is_first_line = false;
            }
331
        }
332
        Some(stack.clone())
P
Phodal Huang 已提交
333 334
    }

P
Phodal Huang 已提交
335 336 337 338
    pub fn handle_captures(
        grammar: &mut Grammar,
        line_text: String,
        is_first_line: bool,
P
Phodal Huang 已提交
339
        mut stack: &mut StackElement,
340
        mut line_tokens: &mut LineTokens,
P
Phodal Huang 已提交
341 342
        captures: Vec<Box<dyn AbstractRule>>,
        capture_indices: Vec<IOnigCaptureIndex>,
P
Phodal Huang 已提交
343
    ) -> Option<LineTokens> {
P
Phodal Huang 已提交
344 345
        let captures_len = captures.clone().len();
        if captures_len == 0 {
P
Phodal Huang 已提交
346
            return None;
P
Phodal Huang 已提交
347 348 349 350 351 352 353
        }

        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();
P
Phodal Huang 已提交
354 355 356 357
            if let RuleEnum::CaptureRule(capture) = capture_rule.get_rule_instance() {
                if capture.clone().rule._type == "" {
                    continue;
                }
P
Phodal Huang 已提交
358

P
Phodal Huang 已提交
359 360 361 362
                let capture_index = capture_indices[i].clone();
                if capture_index.length == 0 {
                    continue;
                }
P
Phodal Huang 已提交
363

P
Phodal Huang 已提交
364 365 366
                if capture_index.start > max_end {
                    continue;
                }
367

P
Phodal Huang 已提交
368 369 370 371 372 373 374 375 376 377
                while local_stack.len() > 0
                    && local_stack[local_stack.len() - 1].end_pos <= capture_index.start as i32
                {
                    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,
                    );
                    local_stack.pop();
                }
378

P
Phodal Huang 已提交
379 380 381 382 383 384 385 386 387
                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,
                        capture_index.start as i32,
                    );
                } else {
                    line_tokens.produce(stack, capture_index.start as i32);
                }
388

P
Phodal Huang 已提交
389
                if capture.retokenize_captured_with_rule_id != 0 {
P
Phodal Huang 已提交
390 391 392 393 394
                    let scope_name =
                        capture.get_name(Some(line_text.clone()), Some(capture_indices.clone()));
                    let name_scopes_list = stack.content_name_scopes_list.push(grammar, scope_name);
                    let content_name = capture
                        .get_content_name(Some(line_text.clone()), Some(capture_indices.clone()));
P
Phodal Huang 已提交
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
                    let content_name_scopes_list = name_scopes_list.push(grammar, content_name);

                    let mut stack_clone = stack.clone().push(
                        capture.retokenize_captured_with_rule_id,
                        capture_index.start.clone() as i32,
                        -1,
                        false,
                        None,
                        name_scopes_list,
                        content_name_scopes_list,
                    );

                    let sub_text = line_text.split_at(capture_index.end).0;
                    let mut sub_is_first_line = false;
                    if is_first_line && capture_index.start == 0 {
                        sub_is_first_line = true;
411
                    }
P
Phodal Huang 已提交
412 413 414 415 416 417 418 419 420 421 422
                    Grammar::tokenize_string(
                        grammar,
                        String::from(sub_text),
                        sub_is_first_line,
                        capture_index.start as i32,
                        stack_clone,
                        line_tokens,
                        false,
                    );
                    // todo: find the next_text_not_switch_issues
                    continue;
423
                }
P
Phodal Huang 已提交
424

P
Phodal Huang 已提交
425 426 427 428 429 430 431 432 433 434 435 436
                let capture_scope_name =
                    capture_rule.get_name(Some(line_text.clone()), Some(capture_indices.clone()));
                if let Some(name) = capture_scope_name.clone() {
                    let mut base = stack.clone().content_name_scopes_list;
                    if local_stack.len() > 0 {
                        base = local_stack[local_stack.len() - 1].clone().scopes;
                    }
                    let capture_rule_scopes_list = base.push(grammar, capture_scope_name.clone());
                    local_stack.push(LocalStackElement::new(
                        capture_rule_scopes_list,
                        capture_index.end as i32,
                    ));
P
Phodal Huang 已提交
437 438 439 440 441
                }
            }
        }

        while local_stack.len() > 0 {
P
Phodal Huang 已提交
442 443
            let mut last_stack = local_stack[local_stack.len() - 1].clone();
            line_tokens.produce_from_scopes(&mut last_stack.scopes, last_stack.end_pos);
P
Phodal Huang 已提交
444
            local_stack.pop();
P
Phodal Huang 已提交
445
        }
P
Phodal Huang 已提交
446 447

        return Some(line_tokens.to_owned());
P
Phodal Huang 已提交
448
    }
P
Phodal Huang 已提交
449 450 451 452 453
    /**
     * Walk the stack from bottom to top, and check each while condition in this order.
     * If any fails, cut off the entire stack above the failed while condition. While conditions
     * may also advance the linePosition.
     */
P
Phodal Huang 已提交
454 455 456 457 458
    pub fn check_while_conditions(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
459
        mut stack: StackElement,
P
Phodal Huang 已提交
460
        line_tokens: LineTokens,
461
    ) -> CheckWhileConditionResult {
P
Phodal Huang 已提交
462
        let mut anchor_position = -1;
P
Phodal Huang 已提交
463
        if stack.begin_rule_captured_eol {
P
Phodal Huang 已提交
464 465
            anchor_position = 0
        }
P
Phodal Huang 已提交
466 467 468 469 470 471 472 473
        let mut while_rules = vec![];
        let mut has_node = true;
        let mut node = stack.clone();
        while has_node {
            let rule = node.clone().get_rule(self);
            if let RuleEnum::BeginWhileRule(begin_rule) = rule.get_rule_instance() {
                while_rules.push(CheckWhileRuleResult {
                    rule: Box::from(begin_rule),
474
                    stack: Box::from(node.clone()),
P
Phodal Huang 已提交
475 476 477 478
                })
            }

            match node.pop() {
P
Phodal Huang 已提交
479
                None => has_node = false,
P
Phodal Huang 已提交
480 481
                Some(n) => {
                    node = n;
482
                }
P
Phodal Huang 已提交
483 484 485
            }
        }

486 487 488 489 490 491 492 493
        for while_rule in while_rules.clone() {
            let allow_g = anchor_position == line_pos;
            let mut rule_scanner = while_rule.clone().rule.compile_while(
                self,
                while_rule.clone().stack.end_rule,
                is_first_line,
                allow_g,
            );
P
Phodal Huang 已提交
494 495 496
            let match_result = rule_scanner
                .scanner
                .find_next_match_sync(line_text.clone(), line_pos);
497 498 499 500 501 502 503 504 505
            match match_result {
                None => {
                    stack = while_rule.stack.pop().unwrap();
                    break;
                }
                Some(_) => {
                    println!("todo: check_while_conditions");
                }
            }
P
Phodal Huang 已提交
506 507
        }

508 509 510 511 512
        // println!("{:?}", while_rules);
        CheckWhileConditionResult {
            stack: Box::new(stack),
            line_pos,
            anchor_position,
P
Phodal Huang 已提交
513
            is_first_line,
514
        }
P
Phodal Huang 已提交
515
    }
P
Phodal Huang 已提交
516

P
Phodal Huang 已提交
517 518 519 520 521
    pub fn match_rule_or_injections(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
522
        stack: &mut StackElement,
P
Phodal Huang 已提交
523
        anchor_position: i32,
P
Phodal Huang 已提交
524
    ) {
P
Phodal Huang 已提交
525 526
        let match_result =
            self.match_rule(line_text, is_first_line, line_pos, stack, anchor_position);
P
Phodal Huang 已提交
527
        if let Some(result) = match_result {} else {
528 529 530
            // None
        };
        // todo: get injections logic
P
Phodal Huang 已提交
531 532 533 534 535 536 537
    }

    pub fn match_rule(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
538
        stack: &mut StackElement,
P
Phodal Huang 已提交
539
        anchor_position: i32,
540
    ) -> Option<MatchRuleResult> {
541
        let mut rule = stack.get_rule(self);
P
Phodal Huang 已提交
542
        let mut rule_scanner = rule.compile(
P
Phodal Huang 已提交
543
            self,
P
Phodal Huang 已提交
544
            stack.end_rule.clone(),
P
Phodal Huang 已提交
545 546 547
            is_first_line,
            line_pos == anchor_position,
        );
P
Phodal Huang 已提交
548 549 550
        let r = rule_scanner
            .scanner
            .find_next_match_sync(line_text, line_pos);
P
Phodal Huang 已提交
551
        if let Some(result) = r {
552 553
            let match_rule_result = MatchRuleResult {
                capture_indices: result.capture_indices,
554
                matched_rule_id: rule_scanner.rules[result.index],
555 556 557 558
            };

            println!("{:?}", match_rule_result.clone());
            Some(match_rule_result)
P
Phodal Huang 已提交
559 560 561
        } else {
            None
        }
P
Phodal Huang 已提交
562
    }
P
Phodal Huang 已提交
563

P
Phodal Huang 已提交
564 565 566 567 568
    pub fn tokenize_line(
        &mut self,
        line_text: String,
        prev_state: Option<StackElement>,
    ) -> TokenizeResult {
P
Phodal Huang 已提交
569 570 571
        self.tokenize(line_text, prev_state, false)
    }

P
Phodal Huang 已提交
572 573
    pub fn tokenize_line2(&self, line_text: String, prev_state: Option<StackElement>) {}
}
P
Phodal Huang 已提交
574 575 576 577

impl IRuleFactoryHelper for Grammar {}

impl IGrammarRegistry for Grammar {
P
Phodal Huang 已提交
578 579 580 581 582
    fn get_external_grammar(
        &self,
        scope_name: String,
        repository: IRawRepository,
    ) -> Option<IRawGrammar> {
P
Phodal Huang 已提交
583 584 585 586 587
        None
    }
}

impl IRuleRegistry for Grammar {
P
Phodal Huang 已提交
588 589
    fn register_id(&mut self) -> i32 {
        self.last_rule_id = self.last_rule_id + 1;
P
Phodal Huang 已提交
590
        self.last_rule_id.clone()
P
Phodal Huang 已提交
591 592
    }

P
Phodal Huang 已提交
593 594 595
    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 已提交
596
        }
P
Phodal Huang 已提交
597
        Box::from(EmptyRule {})
P
Phodal Huang 已提交
598
    }
P
Phodal Huang 已提交
599

P
Phodal Huang 已提交
600
    fn register_rule(&mut self, result: Box<dyn AbstractRule>) -> Box<dyn AbstractRule> {
P
Phodal Huang 已提交
601
        self.rule_id2desc
P
Phodal Huang 已提交
602
            .insert(result.id().clone(), result.clone());
603
        result
P
Phodal Huang 已提交
604
    }
P
Phodal Huang 已提交
605 606 607 608
}

#[cfg(test)]
mod tests {
P
Phodal Huang 已提交
609
    use std::fs::File;
610
    use std::io::{Read, Write};
P
Phodal Huang 已提交
611
    use std::path::Path;
P
Phodal Huang 已提交
612

P
Phodal Huang 已提交
613
    use crate::grammar::Grammar;
P
Phodal Huang 已提交
614
    use crate::inter::IRawGrammar;
P
Phodal Huang 已提交
615
    use crate::rule::abstract_rule::RuleEnum;
P
Phodal Huang 已提交
616
    use crate::rule::IRuleRegistry;
P
Phodal Huang 已提交
617

P
Phodal Huang 已提交
618
    #[test]
P
Phodal Huang 已提交
619
    fn should_build_json_code() {
620 621 622 623 624 625 626 627
        let code = "
#include <stdio.h>
int main() {
printf(\"Hello, World!\");
return 0;
}
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/c.json", code);
628
        // assert_eq!(grammar.rule_id2desc.len(), 162);
629
        // debug_output(&grammar, String::from("program.json"));
630 631
    }

P
Phodal Huang 已提交
632 633 634
    #[test]
    fn should_build_text_grammar() {
        let code = "
P
Phodal Huang 已提交
635
GitHub 漫游指南
P
Phodal Huang 已提交
636 637
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/text.json", code);
638
        assert_eq!(grammar.rule_id2desc.len(), 8);
639 640 641
    }

    fn debug_output(grammar: &Grammar, path: String) {
P
Phodal Huang 已提交
642
        let j = serde_json::to_string(&grammar.rule_id2desc).unwrap();
643
        let mut file = File::create(path).unwrap();
P
Phodal Huang 已提交
644
        match file.write_all(j.as_bytes()) {
P
Phodal Huang 已提交
645 646
            Ok(_) => {}
            Err(_) => {}
P
Phodal Huang 已提交
647
        };
P
Phodal Huang 已提交
648 649
    }

650 651 652 653
    #[test]
    fn should_build_json_grammar() {
        let code = "{}";
        let grammar = to_grammar("test-cases/first-mate/fixtures/json.json", code);
654 655 656 657 658 659 660 661 662
        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);
663 664 665
        debug_output(&grammar, String::from("program.json"));
    }

P
Phodal Huang 已提交
666 667 668 669 670 671 672 673
    #[test]
    fn should_build_correct_end_rule_id_for_makefile() {
        let code = "CC=gcc
CFLAGS=-I.
DEPS = hellomake.h
OBJ = hellomake.o hellofunc.o
";
        let mut grammar = to_grammar("test-cases/first-mate/fixtures/makefile.json", code);
P
Phodal Huang 已提交
674 675 676 677
        let mut end_rule_count = 0;
        for (x, rule) in grammar.rule_id2desc.clone() {
            let rule_instance = rule.get_rule_instance();
            if let RuleEnum::BeginEndRule(rule) = rule_instance {
P
Phodal Huang 已提交
678
                assert_eq!(rule._end.rule_id, -1);
P
Phodal Huang 已提交
679
                end_rule_count = end_rule_count + 1;
P
Phodal Huang 已提交
680 681
            }
        }
P
Phodal Huang 已提交
682
        assert_eq!(grammar.get_rule(1).patterns_length(), 4);
P
Phodal Huang 已提交
683
        assert_eq!(end_rule_count, 24);
P
Phodal Huang 已提交
684 685 686
        debug_output(&grammar, String::from("program.json"));
    }

P
Phodal Huang 已提交
687 688
    #[test]
    fn should_build_makefile_grammar() {
689 690 691 692 693 694 695 696 697 698
        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 已提交
699
";
700
        let mut grammar = to_grammar("test-cases/first-mate/fixtures/makefile.json", code);
P
Phodal Huang 已提交
701
        assert_eq!(grammar.rule_id2desc.len(), 64);
702
        assert_eq!(grammar.get_rule(1).patterns_length(), 4);
P
Phodal Huang 已提交
703 704 705
        debug_output(&grammar, String::from("program.json"));
    }

P
Phodal Huang 已提交
706 707
    #[test]
    fn should_resolve_make_file_error_issues() {
P
Phodal Huang 已提交
708
        let code = "%.o: %.c $(DEPS)\
P
Phodal Huang 已提交
709 710 711 712 713 714 715
";
        let mut grammar = to_grammar("test-cases/first-mate/fixtures/makefile.json", code);
        assert_eq!(grammar.rule_id2desc.len(), 64);
        assert_eq!(grammar.get_rule(1).patterns_length(), 4);
        debug_output(&grammar, String::from("program.json"));
    }

716 717
    fn to_grammar(grammar_path: &str, code: &str) -> Grammar {
        let path = Path::new(grammar_path);
P
Phodal Huang 已提交
718 719 720 721 722 723
        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 已提交
724
        let mut grammar = Grammar::new(g);
725
        let c_code = String::from(code);
P
Phodal Huang 已提交
726
        for line in c_code.lines() {
P
Phodal Huang 已提交
727
            let result = grammar.tokenize_line(String::from(line), None);
P
Phodal Huang 已提交
728 729 730 731 732 733 734
            for token in result.line_tokens._tokens {
                let start = token.start_index.clone() as usize;
                let end = token.end_index.clone() as usize;
                let new_line: String = String::from(line).chars().skip(start).take(end - start).collect();
                let token_str: String = token.scopes.join(", ");
                println!(" - token from {:?} to {:?} ({:?}) with scopes {:?}", token.start_index, token.end_index, new_line, token_str)
            }
P
Phodal Huang 已提交
735
        }
736
        grammar
P
Phodal Huang 已提交
737 738
    }
}