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
use crate::generate_name;
use crate::generators::{generate_terminal_name, GrammarConfig};
use anyhow::Result;
use parol_runtime::TerminalIndex;

use crate::StrVec;
use std::fmt::Debug;

#[derive(Debug, Default)]
struct ScannerBuildInfo {
    scanner_index: usize,
    scanner_name: String,
    terminal_index_count: usize,
    special_tokens: StrVec,
    terminal_indices: StrVec,
}

impl ScannerBuildInfo {
    fn from_scanner_build_info(
        scanner_index: usize,
        scanner_name: String,
        terminal_names: &[String],
        width: usize,
        special_tokens: &[String],
        terminal_indices: &[TerminalIndex],
    ) -> Self {
        let special_tokens =
            special_tokens
                .iter()
                .enumerate()
                .fold(StrVec::new(0), |mut acc, (i, e)| {
                    let e = match e.as_str() {
                        "UNMATCHABLE_TOKEN" | "NEW_LINE_TOKEN" | "WHITESPACE_TOKEN"
                        | "ERROR_TOKEN" => e.to_owned(),
                        _ => {
                            let hashes = determine_hashes_for_raw_string(e);
                            format!(r#"r{}"{}"{}"#, hashes, e, hashes)
                        }
                    };
                    acc.push(format!("/* {:w$} */ {},", i, e, w = width));
                    acc
                });
        let terminal_indices = terminal_indices.iter().fold(StrVec::new(8), |mut acc, e| {
            acc.push(format!(r#"{}, /* {} */"#, e, terminal_names[*e as usize]));
            acc
        });
        Self {
            scanner_index,
            scanner_name,
            terminal_index_count: terminal_indices.len(),
            special_tokens,
            terminal_indices,
        }
    }
}

fn determine_hashes_for_raw_string(e: &str) -> String {
    let mut pattern = r#"""#.to_string();
    let mut count = 0;
    while e.contains(&pattern) {
        pattern.push('#');
        count += 1;
    }
    "#".repeat(count)
}

#[derive(Debug, Default)]
struct LexerData {
    augmented_terminals: StrVec,
    used_token_constants: String,
    terminal_names: StrVec,
    terminal_count: usize,
    scanner_build_configs: StrVec,
}

// ---------------------------------------------------
// Part of the Public API
// *Changes will affect crate's version according to semver*
// ---------------------------------------------------
///
/// Generates the lexer part of the parser output file.
///
pub fn generate_lexer_source(grammar_config: &GrammarConfig) -> Result<String> {
    let original_augmented_terminals = grammar_config.generate_augmented_terminals();

    let terminal_count = original_augmented_terminals.len();
    let width = (terminal_count as f32).log10() as usize + 1;

    let augmented_terminals =
        original_augmented_terminals
            .iter()
            .enumerate()
            .fold(StrVec::new(4), |mut acc, (i, e)| {
                let e = match e.as_str() {
                    "UNMATCHABLE_TOKEN" | "NEW_LINE_TOKEN" | "WHITESPACE_TOKEN" | "ERROR_TOKEN" => {
                        e.to_owned()
                    }
                    _ => {
                        let hashes = determine_hashes_for_raw_string(e);
                        format!(r#"r{}"{}"{}"#, hashes, e, hashes)
                    }
                };
                acc.push(format!("/* {:w$} */ {},", i, e, w = width));
                acc
            });

    let token_constants: Vec<(&str, bool)> = vec![
        ("ERROR_TOKEN,", true),
        (
            "NEW_LINE_TOKEN,",
            grammar_config
                .scanner_configurations
                .iter()
                .any(|sc| sc.auto_newline),
        ),
        ("UNMATCHABLE_TOKEN,", true),
        (
            "WHITESPACE_TOKEN,",
            grammar_config
                .scanner_configurations
                .iter()
                .any(|sc| sc.auto_ws),
        ),
    ];

    let used_token_constants = token_constants
        .iter()
        .fold(String::new(), |mut acc, (c, u)| {
            if *u {
                acc.push_str(c);
            }
            acc
        });

    let terminal_names =
        original_augmented_terminals
            .iter()
            .enumerate()
            .fold(Vec::new(), |mut acc, (i, e)| {
                let n = generate_name(
                    &acc,
                    generate_terminal_name(e, Some(i as TerminalIndex), &grammar_config.cfg),
                );
                acc.push(n);
                acc
            });

    let scanner_build_configs = grammar_config
        .scanner_configurations
        .iter()
        .enumerate()
        .map(|(i, sc)| (i, sc.generate_build_information(&grammar_config.cfg)))
        .map(|(i, (sp, ti, n))| {
            ScannerBuildInfo::from_scanner_build_info(i, n, &terminal_names, width, &sp, &ti)
        })
        .fold(StrVec::new(0), |mut acc, e| {
            acc.push(format!("{}", e));
            acc
        });

    let terminal_names =
        terminal_names
            .iter()
            .enumerate()
            .fold(StrVec::new(4), |mut acc, (i, e)| {
                acc.push(format!(r#"/* {:w$} */ "{}","#, i, e, w = width));
                acc
            });

    let lexer_data = LexerData {
        augmented_terminals,
        used_token_constants,
        terminal_names,
        terminal_count,
        scanner_build_configs,
    };

    Ok(format!("{}", lexer_data))
}

/// Generates all terminal names of a given grammar
pub fn generate_terminal_names(grammar_config: &GrammarConfig) -> Vec<String> {
    grammar_config
        .generate_augmented_terminals()
        .iter()
        .enumerate()
        .fold(Vec::new(), |mut acc, (i, e)| {
            let n = generate_name(
                &acc,
                generate_terminal_name(e, Some(i as TerminalIndex), &grammar_config.cfg),
            );
            acc.push(n);
            acc
        })
}

impl std::fmt::Display for LexerData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let LexerData {
            augmented_terminals,
            used_token_constants,
            terminal_names,
            terminal_count,
            scanner_build_configs,
        } = self;

        let blank_line = "\n\n";
        let scanner_build_configs = scanner_build_configs.join("\n\n");
        f.write_fmt(ume::ume! {
        use parol_runtime::lexer::tokenizer::{
            #used_token_constants
        };
        #blank_line
        pub const TERMINALS: &[&str; #terminal_count] = &[
        #augmented_terminals];
        #blank_line
        pub const TERMINAL_NAMES: &[&str; #terminal_count] = &[
        #terminal_names];
        #blank_line
        #scanner_build_configs
        })
    }
}

impl std::fmt::Display for ScannerBuildInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ScannerBuildInfo {
            scanner_index,
            scanner_name,
            terminal_index_count,
            special_tokens,
            terminal_indices,
        } = self;

        writeln!(f, r#"/* SCANNER_{scanner_index}: "{scanner_name}" */"#)?;
        let scanner_name = format!("SCANNER_{}", scanner_index);
        f.write_fmt(ume::ume! {
            const #scanner_name: (&[&str; 5], &[TerminalIndex; #terminal_index_count]) = (
                &[#special_tokens], &[#terminal_indices],
            );
        })
    }
}