grammar.rs 11.8 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
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,
92
        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;
107 108 109

        let mut current_state = StackElement::null();

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

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

P
Phodal Huang 已提交
121 122
        if is_first_line {
            let scope_list = ScopeListElement::default();
123 124 125
            // self.get_rule(self.root_id.clone());
            // let scope_list = ScopeListElement::new(
            //     None, );
126
            let mut state = StackElement::new(
P
Phodal Huang 已提交
127 128 129 130 131 132 133 134
                None,
                self.root_id.clone(),
                -1,
                -1,
                false,
                None,
                scope_list.clone(),
                scope_list.clone(),
135 136 137
            );

            current_state = state;
P
Phodal Huang 已提交
138 139
        }

P
Phodal Huang 已提交
140
        let format_line_text = format!("{:?}\n", line_text);
P
Phodal Huang 已提交
141 142 143 144 145
        let line_tokens = LineTokens::new(
            emit_binary_tokens,
            line_text,
            self._token_type_matchers.clone(),
        );
P
Phodal Huang 已提交
146 147 148 149
        self.tokenize_string(
            format_line_text.parse().unwrap(),
            is_first_line,
            0,
150
            &mut current_state,
P
Phodal Huang 已提交
151 152
            line_tokens,
            true,
153
        );
P
Phodal Huang 已提交
154 155
    }

P
Phodal Huang 已提交
156 157 158
    pub fn tokenize_string(
        &mut self,
        line_text: String,
159 160 161
        origin_is_first: bool,
        origin_line_pos: i32,
        prev_state: &mut StackElement,
P
Phodal Huang 已提交
162
        line_tokens: LineTokens,
P
Phodal Huang 已提交
163
        check_while_conditions: bool,
164
    ) -> Option<StackElement> {
P
Phodal Huang 已提交
165
        let _line_length = line_text.len();
166
        let mut _stop = false;
P
Phodal Huang 已提交
167
        let mut anchor_position = -1;
P
Phodal Huang 已提交
168

169

P
Phodal Huang 已提交
170
        if check_while_conditions {
P
Phodal Huang 已提交
171 172 173
            // todo: add realy logic
            self.check_while_conditions(
                line_text.clone(),
174 175
                origin_is_first.clone(),
                origin_line_pos.clone(),
P
Phodal Huang 已提交
176 177 178
                prev_state.clone(),
                line_tokens.clone(),
            );
P
Phodal Huang 已提交
179 180
        }

181 182 183 184

        let mut line_pos = origin_line_pos.clone();
        let mut is_first_line = origin_is_first.clone();
        while !_stop {
P
Phodal Huang 已提交
185
            let r = self.match_rule(line_text.clone(), is_first_line, line_pos, prev_state, anchor_position);
186 187 188 189 190
            if let None = r {
                _stop = true;
                return None
            }

P
Phodal Huang 已提交
191 192 193 194 195 196 197 198 199 200
            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);
                line_tokens.produce(prev_state, capture_indices[0].start as i32)
            }

201 202 203 204 205 206
            if capture_indices[0].end > line_pos as usize {
                line_pos = capture_indices[0].end as i32;
                is_first_line = false;
            }
        }
        Some(prev_state.clone())
P
Phodal Huang 已提交
207 208
    }

P
Phodal Huang 已提交
209 210 211 212 213
    pub fn check_while_conditions(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
214
        _stack: StackElement,
P
Phodal Huang 已提交
215 216 217
        line_tokens: LineTokens,
    ) {
        let mut anchor_position = -1;
P
Phodal Huang 已提交
218 219 220
        if _stack.begin_rule_captured_eol {
            anchor_position = 0
        }
P
Phodal Huang 已提交
221 222
        // let while_rules = vec![];
    }
P
Phodal Huang 已提交
223

P
Phodal Huang 已提交
224 225 226 227 228
    pub fn match_rule_or_injections(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
229
        stack: &mut StackElement,
P
Phodal Huang 已提交
230
        anchor_position: i32,
P
Phodal Huang 已提交
231
    ) {
232
        let match_result = self.match_rule(
P
Phodal Huang 已提交
233 234 235
            line_text,
            is_first_line,
            line_pos,
P
Phodal Huang 已提交
236
            stack,
P
Phodal Huang 已提交
237 238
            anchor_position,
        );
239 240 241 242
        if let Some(result) = match_result {} else {
            // None
        };
        // todo: get injections logic
P
Phodal Huang 已提交
243 244 245 246 247 248 249
    }

    pub fn match_rule(
        &mut self,
        line_text: String,
        is_first_line: bool,
        line_pos: i32,
P
Phodal Huang 已提交
250
        stack: &mut StackElement,
P
Phodal Huang 已提交
251
        anchor_position: i32,
252
    ) -> Option<MatchRuleResult> {
253
        let mut rule = stack.get_rule(self);
P
Phodal Huang 已提交
254
        let mut rule_scanner = rule.compile(
P
Phodal Huang 已提交
255
            self,
P
Phodal Huang 已提交
256
            stack.end_rule.clone(),
P
Phodal Huang 已提交
257 258 259
            is_first_line,
            line_pos == anchor_position,
        );
P
Phodal Huang 已提交
260 261 262
        // rule_scanner.scanner
        let r = rule_scanner.scanner.find_next_match_sync(line_text, line_pos);
        if let Some(result) = r {
263 264
            let match_rule_result = MatchRuleResult {
                capture_indices: result.capture_indices,
265
                matched_rule_id: rule_scanner.rules[result.index],
266 267 268 269
            };

            println!("{:?}", match_rule_result.clone());
            Some(match_rule_result)
P
Phodal Huang 已提交
270 271 272
        } else {
            None
        }
P
Phodal Huang 已提交
273
    }
P
Phodal Huang 已提交
274

275
    pub fn tokenize_line(&mut self, line_text: String, prev_state: Option<StackElement>) {
P
Phodal Huang 已提交
276 277 278
        self.tokenize(line_text, prev_state, false)
    }

P
Phodal Huang 已提交
279 280
    pub fn tokenize_line2(&self, line_text: String, prev_state: Option<StackElement>) {}
}
P
Phodal Huang 已提交
281 282 283 284

impl IRuleFactoryHelper for Grammar {}

impl IGrammarRegistry for Grammar {
P
Phodal Huang 已提交
285 286 287 288 289
    fn get_external_grammar(
        &self,
        scope_name: String,
        repository: IRawRepository,
    ) -> Option<IRawGrammar> {
P
Phodal Huang 已提交
290 291 292 293 294
        None
    }
}

impl IRuleRegistry for Grammar {
P
Phodal Huang 已提交
295 296
    fn register_id(&mut self) -> i32 {
        self.last_rule_id = self.last_rule_id + 1;
P
Phodal Huang 已提交
297
        self.last_rule_id.clone()
P
Phodal Huang 已提交
298 299
    }

P
Phodal Huang 已提交
300 301 302
    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 已提交
303
        }
P
Phodal Huang 已提交
304
        Box::from(EmptyRule {})
P
Phodal Huang 已提交
305
    }
P
Phodal Huang 已提交
306

P
Phodal Huang 已提交
307
    fn register_rule(&mut self, result: Box<dyn AbstractRule>) -> Box<dyn AbstractRule> {
P
Phodal Huang 已提交
308
        self.rule_id2desc
P
Phodal Huang 已提交
309
            .insert(result.id().clone(), result.clone());
310
        result
P
Phodal Huang 已提交
311
    }
P
Phodal Huang 已提交
312 313 314 315
}

#[cfg(test)]
mod tests {
P
Phodal Huang 已提交
316
    use std::fs::File;
317
    use std::io::{Read, Write};
P
Phodal Huang 已提交
318
    use std::path::Path;
P
Phodal Huang 已提交
319

P
Phodal Huang 已提交
320
    use crate::grammar::Grammar;
P
Phodal Huang 已提交
321
    use crate::inter::IRawGrammar;
322
    use crate::rule::IRuleRegistry;
P
Phodal Huang 已提交
323

P
Phodal Huang 已提交
324
    #[test]
P
Phodal Huang 已提交
325
    fn should_build_json_code() {
326 327 328 329 330 331 332 333
        let code = "
#include <stdio.h>
int main() {
printf(\"Hello, World!\");
return 0;
}
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/c.json", code);
334
        // assert_eq!(grammar.rule_id2desc.len(), 162);
335
        // debug_output(&grammar, String::from("program.json"));
336 337
    }

P
Phodal Huang 已提交
338 339 340
    #[test]
    fn should_build_text_grammar() {
        let code = "
P
Phodal Huang 已提交
341
GitHub 漫游指南
P
Phodal Huang 已提交
342 343
";
        let grammar = to_grammar("test-cases/first-mate/fixtures/text.json", code);
344
        assert_eq!(grammar.rule_id2desc.len(), 8);
345 346 347
    }

    fn debug_output(grammar: &Grammar, path: String) {
P
Phodal Huang 已提交
348
        let j = serde_json::to_string(&grammar.rule_id2desc).unwrap();
349
        let mut file = File::create(path).unwrap();
P
Phodal Huang 已提交
350
        match file.write_all(j.as_bytes()) {
P
Phodal Huang 已提交
351 352
            Ok(_) => {}
            Err(_) => {}
P
Phodal Huang 已提交
353
        };
P
Phodal Huang 已提交
354 355
    }

356 357 358 359
    #[test]
    fn should_build_json_grammar() {
        let code = "{}";
        let grammar = to_grammar("test-cases/first-mate/fixtures/json.json", code);
360 361 362 363 364 365 366 367 368
        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);
369 370 371
        debug_output(&grammar, String::from("program.json"));
    }

P
Phodal Huang 已提交
372 373
    #[test]
    fn should_build_makefile_grammar() {
374 375 376 377 378 379 380 381 382 383
        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 已提交
384
";
385
        let mut grammar = to_grammar("test-cases/first-mate/fixtures/makefile.json", code);
P
Phodal Huang 已提交
386
        assert_eq!(grammar.rule_id2desc.len(), 64);
387
        assert_eq!(grammar.get_rule(1).patterns_length(), 4);
P
Phodal Huang 已提交
388 389 390
        debug_output(&grammar, String::from("program.json"));
    }

391 392
    fn to_grammar(grammar_path: &str, code: &str) -> Grammar {
        let path = Path::new(grammar_path);
P
Phodal Huang 已提交
393 394 395 396 397 398
        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 已提交
399
        let mut grammar = Grammar::new(g);
400
        let c_code = String::from(code);
P
Phodal Huang 已提交
401 402 403
        for line in c_code.lines() {
            grammar.tokenize_line(String::from(line), None)
        }
404
        grammar
P
Phodal Huang 已提交
405 406
    }
}