grammar.rs 10.1 KB
Newer Older
1
use std::collections::BTreeMap as Map;
P
Phodal Huang 已提交
2

P
Phodal Huang 已提交
3 4
use crate::grammar::line_tokens::{LineTokens, TokenTypeMatcher};
use crate::grammar::{ScopeListElement, StackElement};
P
Phodal Huang 已提交
5
use crate::inter::{IRawGrammar, IRawRepository, IRawRepositoryMap, IRawRule};
6
use crate::rule::rule_factory::RuleFactory;
P
Phodal Huang 已提交
7
use crate::rule::{AbstractRule, EmptyRule, IGrammarRegistry, IRuleFactoryHelper, IRuleRegistry};
P
Phodal Huang 已提交
8
use scie_scanner::scanner::scanner::IOnigMatch;
P
Phodal Huang 已提交
9

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

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

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

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

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

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

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

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

    _grammar
}

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

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

P
Phodal Huang 已提交
106
        let mut is_first_line: bool = false;
P
Phodal Huang 已提交
107
        match prev_state.clone() {
P
Phodal Huang 已提交
108
            None => is_first_line = true,
109 110 111 112
            Some(state) => {
                if state == StackElement::null() {
                    is_first_line = true
                }
P
Phodal Huang 已提交
113
            }
114
        }
P
Phodal Huang 已提交
115

P
Phodal Huang 已提交
116 117
        if is_first_line {
            let scope_list = ScopeListElement::default();
P
Phodal Huang 已提交
118 119 120 121 122 123 124 125 126 127
            prev_state = Some(StackElement::new(
                None,
                self.root_id.clone(),
                -1,
                -1,
                false,
                None,
                scope_list.clone(),
                scope_list.clone(),
            ))
P
Phodal Huang 已提交
128 129
        }

P
Phodal Huang 已提交
130
        let format_line_text = format!("{:?}\n", line_text);
P
Phodal Huang 已提交
131 132 133 134 135
        let line_tokens = LineTokens::new(
            emit_binary_tokens,
            line_text,
            self._token_type_matchers.clone(),
        );
P
Phodal Huang 已提交
136 137 138 139
        self.tokenize_string(
            format_line_text.parse().unwrap(),
            is_first_line,
            0,
P
Phodal Huang 已提交
140
            prev_state.unwrap(),
P
Phodal Huang 已提交
141 142 143
            line_tokens,
            true,
        )
P
Phodal Huang 已提交
144 145
    }

P
Phodal Huang 已提交
146 147 148 149 150
    pub fn tokenize_string(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
151
        prev_state: StackElement,
P
Phodal Huang 已提交
152
        line_tokens: LineTokens,
P
Phodal Huang 已提交
153 154
        check_while_conditions: bool,
    ) {
P
Phodal Huang 已提交
155 156
        let _line_length = line_text.len();
        let _stop = false;
P
Phodal Huang 已提交
157
        let mut anchor_position = -1;
P
Phodal Huang 已提交
158 159

        if check_while_conditions {
P
Phodal Huang 已提交
160 161 162 163 164 165 166 167
            // todo: add realy logic
            self.check_while_conditions(
                line_text.clone(),
                is_first_line.clone(),
                line_pos.clone(),
                prev_state.clone(),
                line_tokens.clone(),
            );
P
Phodal Huang 已提交
168 169
        }

P
Phodal Huang 已提交
170 171 172 173 174 175 176
        self.match_rule_or_injections(
            line_text,
            is_first_line,
            line_pos,
            prev_state,
            anchor_position,
        );
P
Phodal Huang 已提交
177 178
    }

P
Phodal Huang 已提交
179 180 181 182 183
    pub fn check_while_conditions(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
184
        _stack: StackElement,
P
Phodal Huang 已提交
185 186 187
        line_tokens: LineTokens,
    ) {
        let mut anchor_position = -1;
P
Phodal Huang 已提交
188 189 190
        if _stack.begin_rule_captured_eol {
            anchor_position = 0
        }
P
Phodal Huang 已提交
191 192
        // let while_rules = vec![];
    }
P
Phodal Huang 已提交
193

P
Phodal Huang 已提交
194 195 196 197 198
    pub fn match_rule_or_injections(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
199
        stack: StackElement,
P
Phodal Huang 已提交
200
        anchor_position: i32,
P
Phodal Huang 已提交
201
    ) {
P
Phodal Huang 已提交
202 203 204 205 206 207 208
        self.match_rule(
            line_text,
            is_first_line,
            line_pos,
            stack.clone(),
            anchor_position,
        );
P
Phodal Huang 已提交
209 210 211 212 213 214 215 216 217
    }

    pub fn match_rule(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
        stack: StackElement,
        anchor_position: i32,
P
Phodal Huang 已提交
218
    ) -> Option<IOnigMatch> {
219
        let mut rule = stack.get_rule(self);
P
Phodal Huang 已提交
220
        let mut rule_scanner = rule.compile(
P
Phodal Huang 已提交
221 222 223 224 225
            self,
            stack.end_rule,
            is_first_line,
            line_pos == anchor_position,
        );
P
Phodal Huang 已提交
226 227 228 229 230 231 232 233
        // rule_scanner.scanner
        let r = rule_scanner.scanner.find_next_match_sync(line_text, line_pos);
        if let Some(result) = r {
            println!("{:?}", result);
            Some(result)
        } else {
            None
        }
P
Phodal Huang 已提交
234
    }
P
Phodal Huang 已提交
235

236
    pub fn tokenize_line(&mut self, line_text: String, prev_state: Option<StackElement>) {
P
Phodal Huang 已提交
237 238 239
        self.tokenize(line_text, prev_state, false)
    }

P
Phodal Huang 已提交
240 241
    pub fn tokenize_line2(&self, line_text: String, prev_state: Option<StackElement>) {}
}
P
Phodal Huang 已提交
242 243 244 245

impl IRuleFactoryHelper for Grammar {}

impl IGrammarRegistry for Grammar {
P
Phodal Huang 已提交
246 247 248 249 250
    fn get_external_grammar(
        &self,
        scope_name: String,
        repository: IRawRepository,
    ) -> Option<IRawGrammar> {
P
Phodal Huang 已提交
251 252 253 254 255
        None
    }
}

impl IRuleRegistry for Grammar {
P
Phodal Huang 已提交
256 257
    fn register_id(&mut self) -> i32 {
        self.last_rule_id = self.last_rule_id + 1;
P
Phodal Huang 已提交
258
        self.last_rule_id.clone()
P
Phodal Huang 已提交
259 260
    }

P
Phodal Huang 已提交
261 262 263
    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 已提交
264
        }
P
Phodal Huang 已提交
265
        Box::from(EmptyRule {})
P
Phodal Huang 已提交
266
    }
P
Phodal Huang 已提交
267

P
Phodal Huang 已提交
268
    fn register_rule(&mut self, result: Box<dyn AbstractRule>) -> Box<dyn AbstractRule> {
P
Phodal Huang 已提交
269
        self.rule_id2desc
P
Phodal Huang 已提交
270
            .insert(result.id().clone(), result.clone());
271
        result
P
Phodal Huang 已提交
272
    }
P
Phodal Huang 已提交
273 274 275 276
}

#[cfg(test)]
mod tests {
P
Phodal Huang 已提交
277
    use std::fs::File;
278
    use std::io::{Read, Write};
P
Phodal Huang 已提交
279
    use std::path::Path;
P
Phodal Huang 已提交
280

P
Phodal Huang 已提交
281
    use crate::grammar::Grammar;
P
Phodal Huang 已提交
282
    use crate::inter::IRawGrammar;
283
    use crate::rule::IRuleRegistry;
P
Phodal Huang 已提交
284

P
Phodal Huang 已提交
285
    #[test]
P
Phodal Huang 已提交
286
    fn should_build_json_code() {
287 288 289 290 291 292 293 294
        let code = "
#include <stdio.h>
int main() {
printf(\"Hello, World!\");
return 0;
}
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/c.json", code);
295
        // assert_eq!(grammar.rule_id2desc.len(), 162);
296
        // debug_output(&grammar, String::from("program.json"));
297 298
    }

P
Phodal Huang 已提交
299 300 301
    #[test]
    fn should_build_text_grammar() {
        let code = "
P
Phodal Huang 已提交
302
GitHub 漫游指南
P
Phodal Huang 已提交
303 304
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/text.json", code);
305
        assert_eq!(grammar.rule_id2desc.len(), 8);
306 307 308
    }

    fn debug_output(grammar: &Grammar, path: String) {
P
Phodal Huang 已提交
309
        let j = serde_json::to_string(&grammar.rule_id2desc).unwrap();
310
        let mut file = File::create(path).unwrap();
P
Phodal Huang 已提交
311
        match file.write_all(j.as_bytes()) {
P
Phodal Huang 已提交
312 313
            Ok(_) => {}
            Err(_) => {}
P
Phodal Huang 已提交
314
        };
P
Phodal Huang 已提交
315 316
    }

317 318 319 320
    #[test]
    fn should_build_json_grammar() {
        let code = "{}";
        let grammar = to_grammar("test-cases/first-mate/fixtures/json.json", code);
321 322 323 324 325 326 327 328 329
        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);
330 331 332
        debug_output(&grammar, String::from("program.json"));
    }

P
Phodal Huang 已提交
333 334
    #[test]
    fn should_build_makefile_grammar() {
P
Phodal Huang 已提交
335 336 337 338
        let code = "objects=main.o test.o
clean:
	rm -f *.o demo
";
339
        let mut grammar = to_grammar("test-cases/first-mate/fixtures/makefile.json", code);
P
Phodal Huang 已提交
340
        assert_eq!(grammar.rule_id2desc.len(), 64);
341
        assert_eq!(grammar.get_rule(1).patterns_length(), 4);
P
Phodal Huang 已提交
342 343 344
        debug_output(&grammar, String::from("program.json"));
    }

345 346
    fn to_grammar(grammar_path: &str, code: &str) -> Grammar {
        let path = Path::new(grammar_path);
P
Phodal Huang 已提交
347 348 349 350 351 352
        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 已提交
353
        let mut grammar = Grammar::new(g);
354
        let c_code = String::from(code);
P
Phodal Huang 已提交
355 356 357
        for line in c_code.lines() {
            grammar.tokenize_line(String::from(line), None)
        }
358
        grammar
P
Phodal Huang 已提交
359 360
    }
}