grammar.rs 15.3 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 10 11 12
use crate::rule::rule_factory::RuleFactory;
use crate::rule::{
    AbstractRule, BeginWhileRule, CaptureRule, EmptyRule, IGrammarRegistry, IRuleFactoryHelper,
    IRuleRegistry,
};
P
Phodal Huang 已提交
13
use core::cmp;
P
Phodal Huang 已提交
14
use scie_scanner::scanner::scanner::{IOnigCaptureIndex, IOnigMatch};
P
Phodal Huang 已提交
15
use std::cmp::max;
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
#[derive(Debug, Clone)]
P
Phodal Huang 已提交
51
pub struct Grammar {
52
    root_id: i32,
P
Phodal Huang 已提交
53
    grammar: IRawGrammar,
54
    pub last_rule_id: i32,
55
    pub rule_id2desc: Map<i32, Box<dyn AbstractRule>>,
P
Phodal Huang 已提交
56
    pub _token_type_matchers: Vec<TokenTypeMatcher>,
P
Phodal Huang 已提交
57 58
}

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

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

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

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

    _grammar
}

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

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

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

        let mut current_state = StackElement::null();

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

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

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

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

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

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

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

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

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

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

P
Phodal Huang 已提交
237 238
                match rule.get_rule_instance() {
                    RuleEnum::BeginEndRule(begin_rule) => {
239
                        // 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 已提交
240 241 242 243
                    }
                    RuleEnum::BeginWhileRule(while_rule) => {}
                    _ => {}
                }
P
Phodal Huang 已提交
244 245
            }

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

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

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

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

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

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

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

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

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

impl IRuleFactoryHelper for Grammar {}

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

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

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

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

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

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

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

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

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

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

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

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