grammar.rs 19.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
use crate::rule::rule_factory::RuleFactory;
P
Phodal Huang 已提交
9
use crate::rule::{AbstractRule, EmptyRule, IGrammarRegistry, IRuleFactoryHelper, IRuleRegistry};
P
Phodal Huang 已提交
10
use core::cmp;
P
Phodal Huang 已提交
11
use scie_scanner::scanner::scanner::IOnigCaptureIndex;
P
Phodal Huang 已提交
12

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

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

P
Phodal Huang 已提交
44
pub trait Matcher {}
P
Phodal Huang 已提交
45

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

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

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

    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 已提交
68 69 70
    if let Some(repo) = grammar.clone().repository {
        repository_map.name_map = repo.clone().map.name_map.clone();
    }
P
Phodal Huang 已提交
71 72 73

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

    _grammar
}

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

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

P
Phodal Huang 已提交
109
        let mut is_first_line: bool = false;
110 111 112

        let mut current_state = StackElement::null();

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

                current_state = state;
P
Phodal Huang 已提交
121
            }
122
        }
P
Phodal Huang 已提交
123

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

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

            current_state = state;
P
Phodal Huang 已提交
145 146
        } else {
            is_first_line = false;
P
Phodal Huang 已提交
147 148
        }

149
        let format_line_text = line_text.clone() + "\n";
P
Phodal Huang 已提交
150
        let mut line_tokens = LineTokens::new(
P
Phodal Huang 已提交
151 152 153 154
            emit_binary_tokens,
            line_text,
            self._token_type_matchers.clone(),
        );
P
Phodal Huang 已提交
155
        self.tokenize_string(
156
            format_line_text,
P
Phodal Huang 已提交
157 158
            is_first_line,
            0,
P
Phodal Huang 已提交
159
            current_state,
160
            &mut line_tokens,
P
Phodal Huang 已提交
161
            true,
162
        );
P
Phodal Huang 已提交
163 164
    }

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

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

189 190
        let mut line_pos = origin_line_pos.clone();
        let mut is_first_line = origin_is_first.clone();
191
        while !_stop {
P
Phodal Huang 已提交
192 193 194 195
            let r = self.match_rule(
                line_text.clone(),
                is_first_line,
                line_pos,
P
Phodal Huang 已提交
196
                &mut stack,
P
Phodal Huang 已提交
197 198
                anchor_position,
            );
199
            if let None = r {
P
Phodal Huang 已提交
200
                line_tokens.produce(&mut stack, _line_length as i32);
201
                _stop = true;
P
Phodal Huang 已提交
202
                return Some(stack.clone());
203 204
            }

P
Phodal Huang 已提交
205 206 207 208 209
            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");
210
                _stop = true;
P
Phodal Huang 已提交
211
                return Some(stack.clone());
P
Phodal Huang 已提交
212 213
            } else {
                let rule = self.get_rule(matched_rule_id);
P
Phodal Huang 已提交
214
                line_tokens.produce(&mut stack, capture_indices[0].start as i32);
P
Phodal Huang 已提交
215
                // let before_push = stack.clone();
P
Phodal Huang 已提交
216 217 218 219 220
                let scope_name =
                    rule.get_name(Some(line_text.clone()), Some(capture_indices.clone()));
                let name_scopes_list = stack
                    .content_name_scopes_list
                    .push(self, scope_name);
P
Phodal Huang 已提交
221 222 223 224
                let mut begin_rule_capture_eol = false;
                if capture_indices[0].end == _line_length {
                    begin_rule_capture_eol = true;
                }
P
Phodal Huang 已提交
225
                let new_stack = stack.push(
P
Phodal Huang 已提交
226 227 228 229 230 231
                    matched_rule_id,
                    line_pos,
                    anchor_position,
                    begin_rule_capture_eol,
                    None,
                    name_scopes_list.clone(),
P
Phodal Huang 已提交
232
                    name_scopes_list.clone(),
P
Phodal Huang 已提交
233
                );
P
Phodal Huang 已提交
234
                stack = new_stack;
P
Phodal Huang 已提交
235

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

P
Phodal Huang 已提交
249
                        line_tokens.produce(&mut stack, capture_indices[0].end.clone() as i32);
250
                        anchor_position = capture_indices[0].end.clone() as i32;
P
Phodal Huang 已提交
251 252
                        let content_name = push_rule
                            .get_name(Some(line_text.clone()), Some(capture_indices.clone()));
253 254 255 256 257 258
                        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 {
                        //
                        // }
259

260 261 262
                        // if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {
                        // _stop = true;
                        // return None;
263 264 265
                    }
                    RuleEnum::BeginWhileRule(while_rule) => {
                        _stop = true;
P
Phodal Huang 已提交
266
                        return Some(stack.clone());
267 268 269
                    }
                    _ => {
                        _stop = true;
P
Phodal Huang 已提交
270
                        return Some(stack.clone());
P
Phodal Huang 已提交
271 272
                    }
                }
P
Phodal Huang 已提交
273
            }
274 275 276 277 278

            if capture_indices[0].end > line_pos as usize {
                line_pos = capture_indices[0].end as i32;
                is_first_line = false;
            }
279
        }
280
        Some(stack.clone())
P
Phodal Huang 已提交
281 282
    }

P
Phodal Huang 已提交
283 284 285 286 287
    pub fn handle_captures(
        grammar: &mut Grammar,
        line_text: String,
        is_first_line: bool,
        stack: &mut StackElement,
288
        mut line_tokens: &mut LineTokens,
P
Phodal Huang 已提交
289 290
        captures: Vec<Box<dyn AbstractRule>>,
        capture_indices: Vec<IOnigCaptureIndex>,
P
Phodal Huang 已提交
291
    ) -> Option<LineTokens> {
P
Phodal Huang 已提交
292 293
        let captures_len = captures.clone().len();
        if captures_len == 0 {
P
Phodal Huang 已提交
294
            return None;
P
Phodal Huang 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
        }

        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 已提交
315 316 317
            while local_stack.len() > 0
                && local_stack[local_stack.len() - 1].end_pos <= capture_index.start as i32
            {
P
Phodal Huang 已提交
318 319 320
                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 已提交
321
                    local_stack_element.end_pos,
P
Phodal Huang 已提交
322 323 324
                );
                local_stack.pop();
            }
325 326 327 328 329 330 331 332 333 334

            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);
            }
335

336 337 338
            match capture_rule.get_rule_instance() {
                RuleEnum::CaptureRule(capture) => {
                    if capture.retokenize_captured_with_rule_id != 0 {
P
Phodal Huang 已提交
339 340 341 342 343 344 345 346
                        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()),
                        );
347
                        let content_name_scopes_list = name_scopes_list.push(grammar, content_name);
348

P
Phodal Huang 已提交
349 350 351 352 353 354 355 356
                        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,
357 358
                        );

359 360 361 362 363
                        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;
                        }
P
Phodal Huang 已提交
364 365 366 367 368
                        Grammar::tokenize_string(
                            grammar,
                            String::from(sub_text),
                            sub_is_first_line,
                            capture_index.start as i32,
P
Phodal Huang 已提交
369
                            stack_clone,
370
                            line_tokens,
P
Phodal Huang 已提交
371
                            false,
372
                        );
P
Phodal Huang 已提交
373
                        continue;
374 375 376 377
                    }
                }
                _ => {}
            }
P
Phodal Huang 已提交
378

P
Phodal Huang 已提交
379 380
            let capture_scope_name =
                capture_rule.get_name(Some(line_text.clone()), Some(capture_indices.clone()));
P
Phodal Huang 已提交
381 382 383 384 385 386
            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());
P
Phodal Huang 已提交
387 388 389 390
                local_stack.push(LocalStackElement::new(
                    capture_rule_scopes_list,
                    capture_index.end as i32,
                ));
P
Phodal Huang 已提交
391 392 393 394
            }
        }

        while local_stack.len() > 0 {
P
Phodal Huang 已提交
395 396
            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 已提交
397
            local_stack.pop();
P
Phodal Huang 已提交
398
        }
P
Phodal Huang 已提交
399 400

        return Some(line_tokens.to_owned());
P
Phodal Huang 已提交
401
    }
P
Phodal Huang 已提交
402

P
Phodal Huang 已提交
403 404 405 406 407
    pub fn check_while_conditions(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
408
        _stack: StackElement,
P
Phodal Huang 已提交
409 410 411
        line_tokens: LineTokens,
    ) {
        let mut anchor_position = -1;
P
Phodal Huang 已提交
412 413 414
        if _stack.begin_rule_captured_eol {
            anchor_position = 0
        }
P
Phodal Huang 已提交
415 416
        // let while_rules = vec![];
    }
P
Phodal Huang 已提交
417

P
Phodal Huang 已提交
418 419 420 421 422
    pub fn match_rule_or_injections(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
423
        stack: &mut StackElement,
P
Phodal Huang 已提交
424
        anchor_position: i32,
P
Phodal Huang 已提交
425
    ) {
P
Phodal Huang 已提交
426 427
        let match_result =
            self.match_rule(line_text, is_first_line, line_pos, stack, anchor_position);
P
Phodal Huang 已提交
428
        if let Some(result) = match_result {} else {
429 430 431
            // None
        };
        // todo: get injections logic
P
Phodal Huang 已提交
432 433 434 435 436 437 438
    }

    pub fn match_rule(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
439
        stack: &mut StackElement,
P
Phodal Huang 已提交
440
        anchor_position: i32,
441
    ) -> Option<MatchRuleResult> {
442
        let mut rule = stack.get_rule(self);
P
Phodal Huang 已提交
443
        let mut rule_scanner = rule.compile(
P
Phodal Huang 已提交
444
            self,
P
Phodal Huang 已提交
445
            stack.end_rule.clone(),
P
Phodal Huang 已提交
446 447 448
            is_first_line,
            line_pos == anchor_position,
        );
P
Phodal Huang 已提交
449 450 451
        let r = rule_scanner
            .scanner
            .find_next_match_sync(line_text, line_pos);
P
Phodal Huang 已提交
452
        if let Some(result) = r {
453 454
            let match_rule_result = MatchRuleResult {
                capture_indices: result.capture_indices,
455
                matched_rule_id: rule_scanner.rules[result.index],
456 457 458 459
            };

            println!("{:?}", match_rule_result.clone());
            Some(match_rule_result)
P
Phodal Huang 已提交
460 461 462
        } else {
            None
        }
P
Phodal Huang 已提交
463
    }
P
Phodal Huang 已提交
464

465
    pub fn tokenize_line(&mut self, line_text: String, prev_state: Option<StackElement>) {
P
Phodal Huang 已提交
466 467 468
        self.tokenize(line_text, prev_state, false)
    }

P
Phodal Huang 已提交
469 470
    pub fn tokenize_line2(&self, line_text: String, prev_state: Option<StackElement>) {}
}
P
Phodal Huang 已提交
471 472 473 474

impl IRuleFactoryHelper for Grammar {}

impl IGrammarRegistry for Grammar {
P
Phodal Huang 已提交
475 476 477 478 479
    fn get_external_grammar(
        &self,
        scope_name: String,
        repository: IRawRepository,
    ) -> Option<IRawGrammar> {
P
Phodal Huang 已提交
480 481 482 483 484
        None
    }
}

impl IRuleRegistry for Grammar {
P
Phodal Huang 已提交
485 486
    fn register_id(&mut self) -> i32 {
        self.last_rule_id = self.last_rule_id + 1;
P
Phodal Huang 已提交
487
        self.last_rule_id.clone()
P
Phodal Huang 已提交
488 489
    }

P
Phodal Huang 已提交
490 491 492
    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 已提交
493
        }
P
Phodal Huang 已提交
494
        Box::from(EmptyRule {})
P
Phodal Huang 已提交
495
    }
P
Phodal Huang 已提交
496

P
Phodal Huang 已提交
497
    fn register_rule(&mut self, result: Box<dyn AbstractRule>) -> Box<dyn AbstractRule> {
P
Phodal Huang 已提交
498
        self.rule_id2desc
P
Phodal Huang 已提交
499
            .insert(result.id().clone(), result.clone());
500
        result
P
Phodal Huang 已提交
501
    }
P
Phodal Huang 已提交
502 503 504 505
}

#[cfg(test)]
mod tests {
P
Phodal Huang 已提交
506
    use std::fs::File;
507
    use std::io::{Read, Write};
P
Phodal Huang 已提交
508
    use std::path::Path;
P
Phodal Huang 已提交
509

P
Phodal Huang 已提交
510
    use crate::grammar::Grammar;
P
Phodal Huang 已提交
511
    use crate::inter::IRawGrammar;
512
    use crate::rule::IRuleRegistry;
P
Phodal Huang 已提交
513

P
Phodal Huang 已提交
514
    #[test]
P
Phodal Huang 已提交
515
    fn should_build_json_code() {
516 517 518 519 520 521 522 523
        let code = "
#include <stdio.h>
int main() {
printf(\"Hello, World!\");
return 0;
}
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/c.json", code);
524
        // assert_eq!(grammar.rule_id2desc.len(), 162);
525
        // debug_output(&grammar, String::from("program.json"));
526 527
    }

P
Phodal Huang 已提交
528 529 530
    #[test]
    fn should_build_text_grammar() {
        let code = "
P
Phodal Huang 已提交
531
GitHub 漫游指南
P
Phodal Huang 已提交
532 533
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/text.json", code);
534
        assert_eq!(grammar.rule_id2desc.len(), 8);
535 536 537
    }

    fn debug_output(grammar: &Grammar, path: String) {
P
Phodal Huang 已提交
538
        let j = serde_json::to_string(&grammar.rule_id2desc).unwrap();
539
        let mut file = File::create(path).unwrap();
P
Phodal Huang 已提交
540
        match file.write_all(j.as_bytes()) {
P
Phodal Huang 已提交
541 542
            Ok(_) => {}
            Err(_) => {}
P
Phodal Huang 已提交
543
        };
P
Phodal Huang 已提交
544 545
    }

546 547 548 549
    #[test]
    fn should_build_json_grammar() {
        let code = "{}";
        let grammar = to_grammar("test-cases/first-mate/fixtures/json.json", code);
550 551 552 553 554 555 556 557 558
        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);
559 560 561
        debug_output(&grammar, String::from("program.json"));
    }

P
Phodal Huang 已提交
562 563
    #[test]
    fn should_build_makefile_grammar() {
564 565 566 567 568 569 570 571 572 573
        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 已提交
574
";
575
        let mut grammar = to_grammar("test-cases/first-mate/fixtures/makefile.json", code);
P
Phodal Huang 已提交
576
        assert_eq!(grammar.rule_id2desc.len(), 64);
577
        assert_eq!(grammar.get_rule(1).patterns_length(), 4);
P
Phodal Huang 已提交
578 579 580
        debug_output(&grammar, String::from("program.json"));
    }

581 582
    fn to_grammar(grammar_path: &str, code: &str) -> Grammar {
        let path = Path::new(grammar_path);
P
Phodal Huang 已提交
583 584 585 586 587 588
        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 已提交
589
        let mut grammar = Grammar::new(g);
590
        let c_code = String::from(code);
P
Phodal Huang 已提交
591 592 593
        for line in c_code.lines() {
            grammar.tokenize_line(String::from(line), None)
        }
594
        grammar
P
Phodal Huang 已提交
595 596
    }
}