tokengeex 1.1.0

TokenGeeX is an efficient tokenizer for code based on UnigramLM and TokenMonster.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use regex::Regex;

pub const ANY_CHAR: &str = r#"."#;
pub const LOWERCASE_WORD: &str = r#" ?[a-z]+"#;
pub const UPPERCASE_WORD: &str = r#" ?[A-Z]+"#;
pub const CAPITALIZED_WORD: &str = r#" ?[A-Z][a-z]+"#;
pub const WORD: &str = r#" ?[A-Za-z]+"#;
pub const ENGLISH_WORD: &str = r#" ?[A-Za-z]+'[a-zA-Z]{1,2}"#;
pub const FRENCH_WORD: &str = r#" ?[A-Za-zÀ-ÿ]+"#;
pub const CHINESE_WORD: &str = r#"[\u3400-\u4DBF\u4E00-\u9FFF]+"#;
pub const ENGLISH_CONTRACTION: &str = r#"'(?:re|ve|s|d|ll|t|m)"#;
pub const SPACE_DIGIT: &str = r#" [0-9]"#;
pub const SHORT_NUMBER: &str = r#"[0-9]{1,3}"#;
pub const SPACE_SHORT_NUMBER: &str = r#" [0-9]{1,3}"#;
pub const SHORT_DECIMAL_NUMBER: &str = r#"[0-9]{1,3}\.[0-9]"#;
pub const SPACE_SHORT_DECIMAL_NUMBER: &str = r#" [0-9]{1,3}\.[0-9]"#;
pub const WORD_WRAPPED_IN_BRACKETS: &str = r#"\[[A-Za-z]+\]"#;
pub const SHORT_NUMBER_WRAPPED_IN_BRACKETS: &str = r#"\[[0-9]{1,3}\]"#;
pub const WORD_WRAPPED_IN_QUOTES: &str = r#"['"][A-Za-z]+['"]"#;
pub const WORD_WRAPPED_IN_ANGLE_BRACKETS: &str = r#"<[A-Za-z]+>"#;
pub const PUNCT_WORD: &str = r#"[[:punct:]][A-Za-z]+"#;
pub const SPACE_PUNCT_WORD: &str = r#" [[:punct:]][A-Za-z]+"#;
pub const WORD_PUNCT: &str = r#"[A-Za-z][[:punct:]]"#;
pub const DOT_SHORT_NUMBER: &str = r#"\.[0-9]{1,3}"#;
pub const BRACKET_SHORT_NUMBER: &str = r#"\[[0-9]{1,3}"#;
pub const INDENT: &str = r#"(?:[ ]+)|[\t]+"#;
pub const NEWLINE_INDENT: &str = r#"(?:\n[ ]+)|(?:\n[\t]+)"#;
pub const WHITESPACE: &str = r#"\s+"#;
pub const REPEATED_PUNCT: &str = r#"[[:punct:]]+"#;
pub const FEW_REPEATED_PUNCT: &str = r#"[[:punct:]]{1,4}"#;
pub const REPEATED_PUNCT_SPACE: &str = r#"(?: |[[:punct:]])+"#;
pub const FEW_REPEATED_PUNCT_SPACE: &str = r#"(?: |[[:punct:]]){1,4}"#;
pub const PUNCT_NEWLINE: &str = r#"[[:punct:]]+\n"#;
pub const REPEATED_PUNCT_NEWLINE_INDENT: &str = r#"[[:punct:]]+\n[ \t]+"#;

macro_rules! constexpr_regex {
    ($regex:expr) => {{
        fn generated_function() -> Regex {
            Regex::new($regex).unwrap()
        }
        generated_function as fn() -> Regex
    }};
}

macro_rules! repeated_char_regex {
    ($chars:expr, $min:expr, $max:expr) => {{
        fn generated_function() -> Regex {
            let mut components = Vec::new();

            for c in $chars.chars() {
                let mut regex = String::new();
                regex.push_str(&regex::escape(&c.to_string()));
                regex.push_str("{");
                regex.push_str($min.to_string().as_str());
                regex.push_str(",");
                regex.push_str($max.to_string().as_str());
                regex.push_str("}");
                components.push(regex);
            }

            Regex::new(components.join("|").as_str()).unwrap()
        }
        generated_function as fn() -> Regex
    }};
}

pub const PACKAGE_KEYWORDS: &[&str] = &["package", "import", "export", "module", "use"];

pub const CONTROL_FLOW_STATEMENTS: &[&str] = &[
    "if", "else", "for", "while", "do", "break", "continue", "return", "switch", "case", "default",
    "goto", "try", "catch", "finally", "throw", "assert", "yield", "defer", "await",
];

pub const LITERALS: &[&str] = &[
    "true",
    "false",
    "True",
    "False",
    "null",
    "nil",
    "None",
    "undefined",
];

pub const QUALIFIERS: &[&str] = &[
    "const",
    "static",
    "final",
    "volatile",
    "extern",
    "register",
    "pub",
    "private",
    "protected",
    "public",
    "abstract",
    "virtual",
    "override",
    "inline",
    "constexpr",
    "explicit",
    "implicit",
    "async",
    "signed",
    "unsigned",
];

pub const PRIMITIVE_TYPES: &[&str] = &[
    "void",
    "bool",
    "char",
    "int",
    "short",
    "long",
    "float",
    "double",
    "u8",
    "u16",
    "u32",
    "u64",
    "u128",
    "i8",
    "i16",
    "i32",
    "i64",
    "i128",
    "f32",
    "f64",
    "usize",
    "isize",
    "str",
    "string",
    "byte",
    "rune",
    "uint",
    "int8",
    "int16",
    "int32",
    "int64",
    "int128",
    "uint8",
    "uint16",
    "uint32",
    "uint64",
    "uint128",
    "float32",
    "float64",
    "uintptr",
    "complex64",
    "complex128",
];

type RegexFnPtr = fn() -> Regex;

pub enum PatternKind {}

pub const PATTERNS: &[(&str, RegexFnPtr, &[&str], &[&str])] = &[
    // Char
    (
        "any-char",
        constexpr_regex!(ANY_CHAR),
        &["", "A"],
        &["123"],
    ),
    // Words
    (
        "lowercase-word",
        constexpr_regex!(LOWERCASE_WORD),
        &["hello", " world"],
        &["Hello", "HELLO"],
    ),
    (
        "uppercase-word",
        constexpr_regex!(UPPERCASE_WORD),
        &["HELLO", " WORLD"],
        &["Hello", " WoRLD"],
    ),
    (
        "capitalized-word",
        constexpr_regex!(CAPITALIZED_WORD),
        &[" Hello", "Hello"],
        &["HeLlO"],
    ),
    (
        "word",
        constexpr_regex!(WORD),
        &["hello", " Hello", " HeLlO"],
        &["123"],
    ),
    (
        "english-word",
        constexpr_regex!(ENGLISH_WORD),
        &["don't", " You'll", " He's"],
        &["ABC'DEF"],
    ),
    (
        "french-word",
        constexpr_regex!(FRENCH_WORD),
        &["Été", " compliqué"],
        &["مرحبا"],
    ),
    (
        "chinese-word",
        constexpr_regex!(CHINESE_WORD),
        &["你好", "大家好"],
        &["مرحبا"],
    ),
    // Grammar
    (
        "english-contraction",
        constexpr_regex!(ENGLISH_CONTRACTION),
        &["'re", "'ve", "'s", "'d", "'ll", "'t", "'m"],
        &[],
    ),
    // Numbers
    (
        "space-digit",
        constexpr_regex!(SPACE_DIGIT),
        &[" 1", " 2", " 3"],
        &[" 10"],
    ),
    (
        "short-number",
        constexpr_regex!(SHORT_NUMBER),
        &["1", "123", "789"],
        &["1000"],
    ),
    (
        "space-short-number",
        constexpr_regex!(SPACE_SHORT_NUMBER),
        &[" 1", " 123", " 789"],
        &[],
    ),
    (
        "short-decimal-number",
        constexpr_regex!(SHORT_DECIMAL_NUMBER),
        &["1.1", "123.4", "789.9"],
        &["123.456", "1000.0"],
    ),
    (
        "space-short-decimal-number",
        constexpr_regex!(SPACE_SHORT_DECIMAL_NUMBER),
        &[" 1.1", " 123.4", " 789.9"],
        &[" 123.456", " 1000.0"],
    ),
    // Wrapped
    (
        "word-wrapped-in-brackets",
        constexpr_regex!(WORD_WRAPPED_IN_BRACKETS),
        &["[abc]", "[VALUE]"],
        &[],
    ),
    (
        "short-number-wrapped-in-brackets",
        constexpr_regex!(SHORT_NUMBER_WRAPPED_IN_BRACKETS),
        &["[1]", "[123]", "[789]"],
        &[],
    ),
    (
        "word-wrapped-in-quotes",
        constexpr_regex!(WORD_WRAPPED_IN_QUOTES),
        &["'abc'", "\"VALUE\""],
        &[],
    ),
    (
        "word-wrapped-in-angle-brackets",
        constexpr_regex!(WORD_WRAPPED_IN_ANGLE_BRACKETS),
        &["<abc>", "<VALUE>"],
        &[],
    ),
    // Punctuation Word
    (
        "punct-word",
        constexpr_regex!(PUNCT_WORD),
        &["&abc", ":Abc", "+ABC"],
        &[],
    ),
    // Space Punct Word
    (
        "space-punct-word",
        constexpr_regex!(SPACE_PUNCT_WORD),
        &[" &abc", " :Abc", " +ABC"],
        &[],
    ),
    // Word Punctuation
    (
        "word-punct",
        constexpr_regex!(WORD_PUNCT),
        &["a&", "B:", "C+"],
        &[],
    ),
    // Punctuation Number
    (
        "dot-short-number",
        constexpr_regex!(DOT_SHORT_NUMBER),
        &[".1", ".123", ".789"],
        &[".1000"],
    ),
    (
        "bracket-short-number",
        constexpr_regex!(BRACKET_SHORT_NUMBER),
        &["[1", "[123", "[789"],
        &["[1000"],
    ),
    // Whitespace
    (
        "indent",
        constexpr_regex!(INDENT),
        &[" ", "  ", "    ", "\t", "\t\t", "\t\t\t"],
        &["\t "],
    ),
    (
        "newline-indent",
        constexpr_regex!(NEWLINE_INDENT),
        &["\n ", "\n  ", "\n    ", "\n\t\t", "\n\t\t", "\n\t\t\t"],
        &["\n\t "],
    ),
    (
        "whitespace",
        constexpr_regex!(WHITESPACE),
        &[" ", "  ", "    ", "\n", "\n\n", "\t\t", " \n\t"],
        &[],
    ),
    // Punctuation
    (
        "repeated-same-punct",
        repeated_char_regex!("!?#$%^&*()`[]{}<>|/\\+-=", 2, 4),
        &["##", "%%%", "&&&", "(((", "[[["],
        &["#/", "%%%%%", "&%("],
    ),
    (
        "repeated-punct",
        constexpr_regex!(REPEATED_PUNCT),
        &["####", "()[]{}"],
        &["\n#\n#\n#"],
    ),
    (
        "few-repeated-punct",
        constexpr_regex!(FEW_REPEATED_PUNCT),
        &["#", "##", "###", "()", "[]", "{}"],
        &["#####", "()[]{}"],
    ),
    (
        "repeated-punct-space",
        constexpr_regex!(REPEATED_PUNCT_SPACE),
        &[" # ", " ( ", " ) ", " { ", " } ", " != ", ", "],
        &[],
    ),
    (
        "few-repeated-punct-space",
        constexpr_regex!(FEW_REPEATED_PUNCT_SPACE),
        &[" # ", " ( ", " ) ", " { ", " } ", " != ", ", "],
        &[],
    ),
    (
        "punct-newline",
        constexpr_regex!(PUNCT_NEWLINE),
        &[";\n", "]\n", "}\n"],
        &[";\n\n", "]\n\n", "}\n\n"],
    ),
    (
        "repeated-punct-newline-indent",
        constexpr_regex!(REPEATED_PUNCT_NEWLINE_INDENT),
        &[");\n\t\t", "]\n    "],
        &[],
    ),
];

pub fn build_allow_regex<I>(regexes: I) -> Regex
where
    I: IntoIterator<Item = Regex>,
{
    Regex::new(
        &regexes
            .into_iter()
            .map(|r| format!("^(?:{})$", r.as_str()))
            .collect::<Vec<String>>()
            .join("|"),
    )
    .unwrap()
}

pub fn build_mine_regex<I>(regexes: I) -> Regex
where
    I: IntoIterator<Item = Regex>,
{
    Regex::new(
        &regexes
            .into_iter()
            .map(|r| format!("(?:{})", r.as_str()))
            .collect::<Vec<String>>()
            .join("|"),
    )
    .unwrap()
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use regex::Regex;

    use super::*;

    #[test]
    fn test_regexes() {
        for (name, regex, examples, counter_examples) in PATTERNS {
            let re = Regex::new(&format!("^(?:{})$", &regex())).unwrap();
            for &sample in examples.iter() {
                assert!(
                    re.is_match(sample),
                    "Rule {:?} expected to match {:?} ({})",
                    name,
                    sample,
                    &re,
                );
            }
            for &sample in counter_examples.iter() {
                assert!(
                    !re.is_match(sample),
                    "Rule {:?} expected not to match {:?} ({})",
                    name,
                    sample,
                    &re,
                );
            }
        }

        // Ensure there are no duplicate regex names
        let mut names = HashSet::new();
        let mut regexes = HashSet::new();
        for (name, regex, _, _) in PATTERNS {
            assert!(names.insert(name), "Duplicate regex name found: {:?}", name);
            assert!(regexes.insert(regex), "Duplicate regex found: {:?}", regex);
        }
    }
}