grammar.rs 13.5 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};
4
use crate::grammar::{ScopeListElement, StackElement, MatchRuleResult};
P
Phodal Huang 已提交
5
use crate::inter::{IRawGrammar, IRawRepository, IRawRepositoryMap, IRawRule};
6
use crate::rule::rule_factory::RuleFactory;
P
Phodal Huang 已提交
7 8
use crate::rule::{AbstractRule, EmptyRule, IGrammarRegistry, IRuleFactoryHelper, IRuleRegistry, BeginWhileRule, CaptureRule};
use scie_scanner::scanner::scanner::{IOnigMatch, IOnigCaptureIndex};
P
Phodal Huang 已提交
9
use crate::rule::abstract_rule::RuleEnum;
P
Phodal Huang 已提交
10

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

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

P
Phodal Huang 已提交
42
pub trait Matcher {}
P
Phodal Huang 已提交
43

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

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

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

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

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

    _grammar
}

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

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

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

        let mut current_state = StackElement::null();

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

                current_state = state;
P
Phodal Huang 已提交
119
            }
120
        }
P
Phodal Huang 已提交
121

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

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

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

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

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

180

P
Phodal Huang 已提交
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 195

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

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

P
Phodal Huang 已提交
227 228 229 230 231 232 233
                match rule.get_rule_instance() {
                    RuleEnum::BeginEndRule(begin_rule) => {
                        Grammar::handle_captures(self, line_text.clone(), is_first_line, new_stack, line_tokens.clone(), begin_rule.begin_captures, capture_indices.clone());
                    }
                    RuleEnum::BeginWhileRule(while_rule) => {}
                    _ => {}
                }
P
Phodal Huang 已提交
234 235
            }

236 237 238 239 240
            if capture_indices[0].end > line_pos as usize {
                line_pos = capture_indices[0].end as i32;
                is_first_line = false;
            }
        }
241
        Some(stack.clone())
P
Phodal Huang 已提交
242 243
    }

P
Phodal Huang 已提交
244
    pub fn handle_captures(grammar: &mut Grammar, line_text: String, is_first_line: bool, stack: StackElement, line_tokens: LineTokens, captures: Vec<Box<dyn AbstractRule>>, captureIndices: Vec<IOnigCaptureIndex>) {}
P
Phodal Huang 已提交
245

P
Phodal Huang 已提交
246 247 248 249 250
    pub fn check_while_conditions(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
251
        _stack: StackElement,
P
Phodal Huang 已提交
252 253 254
        line_tokens: LineTokens,
    ) {
        let mut anchor_position = -1;
P
Phodal Huang 已提交
255 256 257
        if _stack.begin_rule_captured_eol {
            anchor_position = 0
        }
P
Phodal Huang 已提交
258 259
        // let while_rules = vec![];
    }
P
Phodal Huang 已提交
260

P
Phodal Huang 已提交
261 262 263 264 265
    pub fn match_rule_or_injections(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
266
        stack: &mut StackElement,
P
Phodal Huang 已提交
267
        anchor_position: i32,
P
Phodal Huang 已提交
268
    ) {
269
        let match_result = self.match_rule(
P
Phodal Huang 已提交
270 271 272
            line_text,
            is_first_line,
            line_pos,
P
Phodal Huang 已提交
273
            stack,
P
Phodal Huang 已提交
274 275
            anchor_position,
        );
276 277 278 279
        if let Some(result) = match_result {} else {
            // None
        };
        // todo: get injections logic
P
Phodal Huang 已提交
280 281 282 283 284 285 286
    }

    pub fn match_rule(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
287
        stack: &mut StackElement,
P
Phodal Huang 已提交
288
        anchor_position: i32,
289
    ) -> Option<MatchRuleResult> {
290
        let mut rule = stack.get_rule(self);
P
Phodal Huang 已提交
291
        let mut rule_scanner = rule.compile(
P
Phodal Huang 已提交
292
            self,
P
Phodal Huang 已提交
293
            stack.end_rule.clone(),
P
Phodal Huang 已提交
294 295 296
            is_first_line,
            line_pos == anchor_position,
        );
P
Phodal Huang 已提交
297 298
        let r = rule_scanner.scanner.find_next_match_sync(line_text, line_pos);
        if let Some(result) = r {
299 300
            let match_rule_result = MatchRuleResult {
                capture_indices: result.capture_indices,
301
                matched_rule_id: rule_scanner.rules[result.index],
302 303 304 305
            };

            println!("{:?}", match_rule_result.clone());
            Some(match_rule_result)
P
Phodal Huang 已提交
306 307 308
        } else {
            None
        }
P
Phodal Huang 已提交
309
    }
P
Phodal Huang 已提交
310

311
    pub fn tokenize_line(&mut self, line_text: String, prev_state: Option<StackElement>) {
P
Phodal Huang 已提交
312 313 314
        self.tokenize(line_text, prev_state, false)
    }

P
Phodal Huang 已提交
315 316
    pub fn tokenize_line2(&self, line_text: String, prev_state: Option<StackElement>) {}
}
P
Phodal Huang 已提交
317 318 319 320

impl IRuleFactoryHelper for Grammar {}

impl IGrammarRegistry for Grammar {
P
Phodal Huang 已提交
321 322 323 324 325
    fn get_external_grammar(
        &self,
        scope_name: String,
        repository: IRawRepository,
    ) -> Option<IRawGrammar> {
P
Phodal Huang 已提交
326 327 328 329 330
        None
    }
}

impl IRuleRegistry for Grammar {
P
Phodal Huang 已提交
331 332
    fn register_id(&mut self) -> i32 {
        self.last_rule_id = self.last_rule_id + 1;
P
Phodal Huang 已提交
333
        self.last_rule_id.clone()
P
Phodal Huang 已提交
334 335
    }

P
Phodal Huang 已提交
336 337 338
    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 已提交
339
        }
P
Phodal Huang 已提交
340
        Box::from(EmptyRule {})
P
Phodal Huang 已提交
341
    }
P
Phodal Huang 已提交
342

P
Phodal Huang 已提交
343
    fn register_rule(&mut self, result: Box<dyn AbstractRule>) -> Box<dyn AbstractRule> {
P
Phodal Huang 已提交
344
        self.rule_id2desc
P
Phodal Huang 已提交
345
            .insert(result.id().clone(), result.clone());
346
        result
P
Phodal Huang 已提交
347
    }
P
Phodal Huang 已提交
348 349 350 351
}

#[cfg(test)]
mod tests {
P
Phodal Huang 已提交
352
    use std::fs::File;
353
    use std::io::{Read, Write};
P
Phodal Huang 已提交
354
    use std::path::Path;
P
Phodal Huang 已提交
355

P
Phodal Huang 已提交
356
    use crate::grammar::Grammar;
P
Phodal Huang 已提交
357
    use crate::inter::IRawGrammar;
358
    use crate::rule::IRuleRegistry;
P
Phodal Huang 已提交
359

P
Phodal Huang 已提交
360
    #[test]
P
Phodal Huang 已提交
361
    fn should_build_json_code() {
362 363 364 365 366 367 368 369
        let code = "
#include <stdio.h>
int main() {
printf(\"Hello, World!\");
return 0;
}
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/c.json", code);
370
        // assert_eq!(grammar.rule_id2desc.len(), 162);
371
        // debug_output(&grammar, String::from("program.json"));
372 373
    }

P
Phodal Huang 已提交
374 375 376
    #[test]
    fn should_build_text_grammar() {
        let code = "
P
Phodal Huang 已提交
377
GitHub 漫游指南
P
Phodal Huang 已提交
378 379
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/text.json", code);
380
        assert_eq!(grammar.rule_id2desc.len(), 8);
381 382 383
    }

    fn debug_output(grammar: &Grammar, path: String) {
P
Phodal Huang 已提交
384
        let j = serde_json::to_string(&grammar.rule_id2desc).unwrap();
385
        let mut file = File::create(path).unwrap();
P
Phodal Huang 已提交
386
        match file.write_all(j.as_bytes()) {
P
Phodal Huang 已提交
387 388
            Ok(_) => {}
            Err(_) => {}
P
Phodal Huang 已提交
389
        };
P
Phodal Huang 已提交
390 391
    }

392 393 394 395
    #[test]
    fn should_build_json_grammar() {
        let code = "{}";
        let grammar = to_grammar("test-cases/first-mate/fixtures/json.json", code);
396 397 398 399 400 401 402 403 404
        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);
405 406 407
        debug_output(&grammar, String::from("program.json"));
    }

P
Phodal Huang 已提交
408 409
    #[test]
    fn should_build_makefile_grammar() {
410 411 412 413 414 415 416 417 418 419
        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 已提交
420
";
421
        let mut grammar = to_grammar("test-cases/first-mate/fixtures/makefile.json", code);
P
Phodal Huang 已提交
422
        assert_eq!(grammar.rule_id2desc.len(), 64);
423
        assert_eq!(grammar.get_rule(1).patterns_length(), 4);
P
Phodal Huang 已提交
424 425 426
        debug_output(&grammar, String::from("program.json"));
    }

427 428
    fn to_grammar(grammar_path: &str, code: &str) -> Grammar {
        let path = Path::new(grammar_path);
P
Phodal Huang 已提交
429 430 431 432 433 434
        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 已提交
435
        let mut grammar = Grammar::new(g);
436
        let c_code = String::from(code);
P
Phodal Huang 已提交
437 438 439
        for line in c_code.lines() {
            grammar.tokenize_line(String::from(line), None)
        }
440
        grammar
P
Phodal Huang 已提交
441 442
    }
}