grammar.rs 15.2 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 mut 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;
P
Phodal Huang 已提交
179
        let mut 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 194
        let mut line_pos = origin_line_pos.clone();
        let mut is_first_line = origin_is_first.clone();
        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 212 213
            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");
            } else {
                let rule = self.get_rule(matched_rule_id);
214
                line_tokens.produce(stack, capture_indices[0].start as i32);
P
Phodal Huang 已提交
215
                // let before_push = stack.clone();
P
Phodal Huang 已提交
216 217 218 219 220 221
                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 已提交
222 223 224 225
                let mut begin_rule_capture_eol = false;
                if capture_indices[0].end == _line_length {
                    begin_rule_capture_eol = true;
                }
226
                let mut new_stack = stack.clone().push(
P
Phodal Huang 已提交
227 228 229 230 231 232
                    matched_rule_id,
                    line_pos,
                    anchor_position,
                    begin_rule_capture_eol,
                    None,
                    name_scopes_list.clone(),
P
Phodal Huang 已提交
233
                    name_scopes_list.clone(),
P
Phodal Huang 已提交
234 235
                );

P
Phodal Huang 已提交
236 237
                match rule.get_rule_instance() {
                    RuleEnum::BeginEndRule(begin_rule) => {
238
                        // Grammar::handle_captures(self, line_text.clone(), is_first_line, &mut new_stack, line_tokens.clone(), begin_rule.begin_captures, capture_indices.clone());
P
Phodal Huang 已提交
239 240 241 242
                    }
                    RuleEnum::BeginWhileRule(while_rule) => {}
                    _ => {}
                }
P
Phodal Huang 已提交
243 244
            }

245 246 247 248 249
            if capture_indices[0].end > line_pos as usize {
                line_pos = capture_indices[0].end as i32;
                is_first_line = false;
            }
        }
250
        Some(stack.clone())
P
Phodal Huang 已提交
251 252
    }

P
Phodal Huang 已提交
253 254 255 256 257 258 259 260 261
    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 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        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 已提交
285 286 287
            while local_stack.len() > 0
                && local_stack[local_stack.len() - 1].end_pos <= capture_index.start as i32
            {
P
Phodal Huang 已提交
288 289 290
                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 已提交
291
                    local_stack_element.end_pos,
P
Phodal Huang 已提交
292 293 294
                );
                local_stack.pop();
            }
295 296 297 298 299 300 301 302 303 304

            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);
            }
P
Phodal Huang 已提交
305 306
        }
    }
P
Phodal Huang 已提交
307

P
Phodal Huang 已提交
308 309 310 311 312
    pub fn check_while_conditions(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
313
        _stack: StackElement,
P
Phodal Huang 已提交
314 315 316
        line_tokens: LineTokens,
    ) {
        let mut anchor_position = -1;
P
Phodal Huang 已提交
317 318 319
        if _stack.begin_rule_captured_eol {
            anchor_position = 0
        }
P
Phodal Huang 已提交
320 321
        // let while_rules = vec![];
    }
P
Phodal Huang 已提交
322

P
Phodal Huang 已提交
323 324 325 326 327
    pub fn match_rule_or_injections(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
328
        stack: &mut StackElement,
P
Phodal Huang 已提交
329
        anchor_position: i32,
P
Phodal Huang 已提交
330
    ) {
P
Phodal Huang 已提交
331 332 333 334
        let match_result =
            self.match_rule(line_text, is_first_line, line_pos, stack, anchor_position);
        if let Some(result) = match_result {
        } else {
335 336 337
            // None
        };
        // todo: get injections logic
P
Phodal Huang 已提交
338 339 340 341 342 343 344
    }

    pub fn match_rule(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
345
        stack: &mut StackElement,
P
Phodal Huang 已提交
346
        anchor_position: i32,
347
    ) -> Option<MatchRuleResult> {
348
        let mut rule = stack.get_rule(self);
P
Phodal Huang 已提交
349
        let mut rule_scanner = rule.compile(
P
Phodal Huang 已提交
350
            self,
P
Phodal Huang 已提交
351
            stack.end_rule.clone(),
P
Phodal Huang 已提交
352 353 354
            is_first_line,
            line_pos == anchor_position,
        );
P
Phodal Huang 已提交
355 356 357
        let r = rule_scanner
            .scanner
            .find_next_match_sync(line_text, line_pos);
P
Phodal Huang 已提交
358
        if let Some(result) = r {
359 360
            let match_rule_result = MatchRuleResult {
                capture_indices: result.capture_indices,
361
                matched_rule_id: rule_scanner.rules[result.index],
362 363 364 365
            };

            println!("{:?}", match_rule_result.clone());
            Some(match_rule_result)
P
Phodal Huang 已提交
366 367 368
        } else {
            None
        }
P
Phodal Huang 已提交
369
    }
P
Phodal Huang 已提交
370

371
    pub fn tokenize_line(&mut self, line_text: String, prev_state: Option<StackElement>) {
P
Phodal Huang 已提交
372 373 374
        self.tokenize(line_text, prev_state, false)
    }

P
Phodal Huang 已提交
375 376
    pub fn tokenize_line2(&self, line_text: String, prev_state: Option<StackElement>) {}
}
P
Phodal Huang 已提交
377 378 379 380

impl IRuleFactoryHelper for Grammar {}

impl IGrammarRegistry for Grammar {
P
Phodal Huang 已提交
381 382 383 384 385
    fn get_external_grammar(
        &self,
        scope_name: String,
        repository: IRawRepository,
    ) -> Option<IRawGrammar> {
P
Phodal Huang 已提交
386 387 388 389 390
        None
    }
}

impl IRuleRegistry for Grammar {
P
Phodal Huang 已提交
391 392
    fn register_id(&mut self) -> i32 {
        self.last_rule_id = self.last_rule_id + 1;
P
Phodal Huang 已提交
393
        self.last_rule_id.clone()
P
Phodal Huang 已提交
394 395
    }

P
Phodal Huang 已提交
396 397 398
    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 已提交
399
        }
P
Phodal Huang 已提交
400
        Box::from(EmptyRule {})
P
Phodal Huang 已提交
401
    }
P
Phodal Huang 已提交
402

P
Phodal Huang 已提交
403
    fn register_rule(&mut self, result: Box<dyn AbstractRule>) -> Box<dyn AbstractRule> {
P
Phodal Huang 已提交
404
        self.rule_id2desc
P
Phodal Huang 已提交
405
            .insert(result.id().clone(), result.clone());
406
        result
P
Phodal Huang 已提交
407
    }
P
Phodal Huang 已提交
408 409 410 411
}

#[cfg(test)]
mod tests {
P
Phodal Huang 已提交
412
    use std::fs::File;
413
    use std::io::{Read, Write};
P
Phodal Huang 已提交
414
    use std::path::Path;
P
Phodal Huang 已提交
415

P
Phodal Huang 已提交
416
    use crate::grammar::Grammar;
P
Phodal Huang 已提交
417
    use crate::inter::IRawGrammar;
418
    use crate::rule::IRuleRegistry;
P
Phodal Huang 已提交
419

P
Phodal Huang 已提交
420
    #[test]
P
Phodal Huang 已提交
421
    fn should_build_json_code() {
422 423 424 425 426 427 428 429
        let code = "
#include <stdio.h>
int main() {
printf(\"Hello, World!\");
return 0;
}
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/c.json", code);
430
        // assert_eq!(grammar.rule_id2desc.len(), 162);
431
        // debug_output(&grammar, String::from("program.json"));
432 433
    }

P
Phodal Huang 已提交
434 435 436
    #[test]
    fn should_build_text_grammar() {
        let code = "
P
Phodal Huang 已提交
437
GitHub 漫游指南
P
Phodal Huang 已提交
438 439
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/text.json", code);
440
        assert_eq!(grammar.rule_id2desc.len(), 8);
441 442 443
    }

    fn debug_output(grammar: &Grammar, path: String) {
P
Phodal Huang 已提交
444
        let j = serde_json::to_string(&grammar.rule_id2desc).unwrap();
445
        let mut file = File::create(path).unwrap();
P
Phodal Huang 已提交
446
        match file.write_all(j.as_bytes()) {
P
Phodal Huang 已提交
447 448
            Ok(_) => {}
            Err(_) => {}
P
Phodal Huang 已提交
449
        };
P
Phodal Huang 已提交
450 451
    }

452 453 454 455
    #[test]
    fn should_build_json_grammar() {
        let code = "{}";
        let grammar = to_grammar("test-cases/first-mate/fixtures/json.json", code);
456 457 458 459 460 461 462 463 464
        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);
465 466 467
        debug_output(&grammar, String::from("program.json"));
    }

P
Phodal Huang 已提交
468 469
    #[test]
    fn should_build_makefile_grammar() {
470 471 472 473 474 475 476 477 478 479
        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 已提交
480
";
481
        let mut grammar = to_grammar("test-cases/first-mate/fixtures/makefile.json", code);
P
Phodal Huang 已提交
482
        assert_eq!(grammar.rule_id2desc.len(), 64);
483
        assert_eq!(grammar.get_rule(1).patterns_length(), 4);
P
Phodal Huang 已提交
484 485 486
        debug_output(&grammar, String::from("program.json"));
    }

487 488
    fn to_grammar(grammar_path: &str, code: &str) -> Grammar {
        let path = Path::new(grammar_path);
P
Phodal Huang 已提交
489 490 491 492 493 494
        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 已提交
495
        let mut grammar = Grammar::new(g);
496
        let c_code = String::from(code);
P
Phodal Huang 已提交
497 498 499
        for line in c_code.lines() {
            grammar.tokenize_line(String::from(line), None)
        }
500
        grammar
P
Phodal Huang 已提交
501 502
    }
}