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
//! Base helper routines for a code generator.

use crate::collections::Set;
use crate::grammar::free_variables::FreeVariables;
use crate::grammar::repr::*;
use crate::lr1::core::*;
use crate::rust::RustWrite;
use crate::util::Sep;
use std::io::{self, Write};

/// Base struct for various kinds of code generator. The flavor of
/// code generator is customized by supplying distinct types for `C`
/// (e.g., `self::ascent::RecursiveAscent`).
pub struct CodeGenerator<'codegen, 'grammar: 'codegen, W: Write + 'codegen, C> {
    /// the complete grammar
    pub grammar: &'grammar Grammar,

    /// some suitable prefix to separate our identifiers from the user's
    pub prefix: &'grammar str,

    /// types from the grammar
    pub types: &'grammar Types,

    /// the start symbol S the user specified
    pub user_start_symbol: NonterminalString,

    /// the synthetic start symbol S' that we specified
    pub start_symbol: NonterminalString,

    /// the vector of states
    pub states: &'codegen [Lr1State<'grammar>],

    /// where we write output
    pub out: &'codegen mut RustWrite<W>,

    /// where to find the action routines (typically `super`)
    pub action_module: String,

    /// custom fields for the specific kind of codegenerator
    /// (recursive ascent, table-driven, etc)
    pub custom: C,

    pub repeatable: bool,
}

impl<'codegen, 'grammar, W: Write, C> CodeGenerator<'codegen, 'grammar, W, C> {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        grammar: &'grammar Grammar,
        user_start_symbol: NonterminalString,
        start_symbol: NonterminalString,
        states: &'codegen [Lr1State<'grammar>],
        out: &'codegen mut RustWrite<W>,
        repeatable: bool,
        action_module: &str,
        custom: C,
    ) -> Self {
        CodeGenerator {
            grammar,
            prefix: &grammar.prefix,
            types: &grammar.types,
            states,
            user_start_symbol,
            start_symbol,
            out,
            custom,
            repeatable,
            action_module: action_module.to_string(),
        }
    }

    /// We often create meta types that pull together a bunch of
    /// user-given types -- basically describing (e.g.) the full set
    /// of return values from any nonterminal (and, in some cases,
    /// terminals). These types need to carry generic parameters from
    /// the grammar, since the nonterminals may include generic
    /// parameters -- but we don't want them to carry *all* the
    /// generic parameters, since that can be unnecessarily
    /// restrictive.
    ///
    /// In particular, consider something like this:
    ///
    /// ```notrust
    /// grammar<'a>(buffer: &'a mut Vec<u32>);
    /// ```
    ///
    /// Here, we likely do not want the `'a` in the type of `buffer` to appear
    /// in the nonterminal result. That's because, if it did, then the
    /// action functions will have a signature like:
    ///
    /// ```ignore
    /// fn foo<'a, T>(x: &'a mut Vec<T>) -> Result<'a> { ... }
    /// ```
    ///
    /// In that case, we would only be able to call one action fn and
    /// will in fact get borrowck errors, because Rust would think we
    /// were potentially returning this `&'a mut Vec<T>`.
    ///
    /// Therefore, we take the full list of type parameters and we
    /// filter them down to those that appear in the types that we
    /// need to include (those that appear in the `tys` parameter).
    ///
    /// In some cases, we need to include a few more than just that
    /// obviously appear textually: for example, if we have `T::Foo`,
    /// and we see a where-clause `T: Bar<'a>`, then we need to
    /// include both `T` and `'a`, since that bound may be important
    /// for resolving `T::Foo` (in other words, `T::Foo` may expand to
    /// `<T as Bar<'a>>::Foo`).
    pub fn filter_type_parameters_and_where_clauses(
        grammar: &Grammar,
        tys: impl IntoIterator<Item = TypeRepr>,
    ) -> (Vec<TypeParameter>, Vec<WhereClause>) {
        let referenced_ty_params: Set<_> = tys
            .into_iter()
            .flat_map(|t| t.free_variables(&grammar.type_parameters))
            .collect();

        let filtered_type_params: Vec<_> = grammar
            .type_parameters
            .iter()
            .filter(|t| referenced_ty_params.contains(t))
            .cloned()
            .collect();

        // If `T` is referenced in the types we need to keep, then
        // include any bounds like `T: Foo`. This may be needed for
        // the well-formedness conditions on `T` (e.g., maybe we have
        // `T: Hash` and a `HashSet<T>` or something) but it may also
        // be needed because of `T::Foo`-like types.
        //
        // Do not however include a bound like `T: 'a` unless both `T`
        // **and** `'a` are referenced -- same with bounds like `T:
        // Foo<U>`. If those were needed, then `'a` or `U` would also
        // have to appear in the types.
        debug!("filtered_type_params = {:?}", filtered_type_params);
        let filtered_where_clauses: Vec<_> = grammar
            .where_clauses
            .iter()
            .filter(|wc| {
                debug!(
                    "wc = {:?} free_variables = {:?}",
                    wc,
                    wc.free_variables(&grammar.type_parameters)
                );
                wc.free_variables(&grammar.type_parameters)
                    .iter()
                    .all(|p| referenced_ty_params.contains(p))
            })
            .cloned()
            .collect();
        debug!("filtered_where_clauses = {:?}", filtered_where_clauses);

        (filtered_type_params, filtered_where_clauses)
    }

    pub fn write_parse_mod<F>(&mut self, body: F) -> io::Result<()>
    where
        F: FnOnce(&mut Self) -> io::Result<()>,
    {
        rust!(self.out, "");
        rust!(self.out, "#[rustfmt::skip]");
        rust!(
            self.out,
            "#[allow(non_snake_case, non_camel_case_types, unused_mut, unused_variables, \
             unused_imports, unused_parens, clippy::all)]"
        );
        rust!(self.out, "mod {}parse{} {{", self.prefix, self.start_symbol);
        rust!(self.out, "");

        self.write_uses()?;

        body(self)?;

        rust!(self.out, "}}");
        Ok(())
    }

    pub fn write_uses(&mut self) -> io::Result<()> {
        self.out
            .write_uses(&format!("{}::", self.action_module), self.grammar)?;

        if self.grammar.intern_token.is_some() {
            rust!(
                self.out,
                "use self::{}lalrpop_util::lexer::Token;",
                self.prefix
            );
        } else {
            rust!(
                self.out,
                "use {}::{}ToTriple;",
                self.action_module,
                self.prefix
            );
        }

        Ok(())
    }

    pub fn start_parser_fn(&mut self) -> io::Result<()> {
        let parse_error_type = self.types.parse_error_type();

        let (type_parameters, parameters, mut where_clauses);

        let intern_token = self.grammar.intern_token.is_some();
        if intern_token {
            // if we are generating the tokenizer, we just need the
            // input, and that has already been added as one of the
            // user parameters
            type_parameters = vec![];
            parameters = vec![];
            where_clauses = vec![];
        } else {
            // otherwise, we need an iterator of type `TOKENS`
            let mut user_type_parameters = String::new();
            for type_parameter in &self.grammar.type_parameters {
                user_type_parameters.push_str(&format!("{}, ", type_parameter));
            }
            type_parameters = vec![
                format!(
                    "{}TOKEN: {}ToTriple<{}>",
                    self.prefix, self.prefix, user_type_parameters,
                ),
                format!(
                    "{}TOKENS: IntoIterator<Item={}TOKEN>",
                    self.prefix, self.prefix
                ),
            ];
            parameters = vec![format!("{}tokens0: {}TOKENS", self.prefix, self.prefix)];
            where_clauses = vec![];

            if self.repeatable {
                where_clauses.push(format!("{}TOKENS: Clone", self.prefix));
            }
        }

        rust!(
            self.out,
            "{}struct {}Parser {{",
            self.grammar.nonterminals[&self.start_symbol].visibility,
            self.user_start_symbol
        );
        if intern_token {
            rust!(
                self.out,
                "builder: {}lalrpop_util::lexer::MatcherBuilder,",
                self.prefix,
            );
        }
        rust!(self.out, "_priv: (),");
        rust!(self.out, "}}");
        rust!(self.out, "");

        rust!(self.out, "impl {}Parser {{", self.user_start_symbol);
        rust!(
            self.out,
            "{}fn new() -> {}Parser {{",
            self.grammar.nonterminals[&self.start_symbol].visibility,
            self.user_start_symbol
        );
        if intern_token {
            rust!(
                self.out,
                "let {0}builder = {1}::{0}intern_token::new_builder();",
                self.prefix,
                self.action_module
            );
        }
        rust!(self.out, "{}Parser {{", self.user_start_symbol);
        if intern_token {
            rust!(self.out, "builder: {}builder,", self.prefix);
        }
        rust!(self.out, "_priv: (),");
        rust!(self.out, "}}"); // Parser
        rust!(self.out, "}}"); // new()
        rust!(self.out, "");

        rust!(self.out, "#[allow(dead_code)]");
        self.out
            .fn_header(
                &self.grammar.nonterminals[&self.start_symbol].visibility,
                "parse".to_owned(),
            )
            .with_parameters(Some("&self".to_owned()))
            .with_grammar(self.grammar)
            .with_type_parameters(type_parameters)
            .with_parameters(parameters)
            .with_return_type(format!(
                "Result<{}, {}>",
                self.types.nonterminal_type(&self.start_symbol),
                parse_error_type
            ))
            .with_where_clauses(where_clauses)
            .emit()?;
        rust!(self.out, "{{");

        Ok(())
    }

    pub fn define_tokens(&mut self) -> io::Result<()> {
        if self.grammar.intern_token.is_some() {
            // if we are generating the tokenizer, create a matcher as our input iterator
            rust!(
                self.out,
                "let mut {}tokens = self.builder.matcher(input);",
                self.prefix
            );
        } else {
            // otherwise, convert one from the `IntoIterator`
            // supplied, using the `ToTriple` trait which inserts
            // errors/locations etc if none are given
            let clone_call = if self.repeatable { ".clone()" } else { "" };
            rust!(
                self.out,
                "let {}tokens = {}tokens0{}.into_iter();",
                self.prefix,
                self.prefix,
                clone_call
            );

            rust!(
                self.out,
                "let mut {}tokens = {}tokens.map(|t| {}ToTriple::to_triple(t));",
                self.prefix,
                self.prefix,
                self.prefix
            );
        }

        Ok(())
    }

    pub fn end_parser_fn(&mut self) -> io::Result<()> {
        rust!(self.out, "}}"); // fn
        rust!(self.out, "}}"); // impl
        Ok(())
    }

    /// Returns phantom data type that captures the user-declared type
    /// parameters in a phantom-data. This helps with ensuring that
    /// all type parameters are constrained, even if they are not
    /// used.
    pub fn phantom_data_type(&self) -> String {
        let phantom_bits: Vec<_> = self
            .grammar
            .type_parameters
            .iter()
            .map(|tp| match *tp {
                TypeParameter::Lifetime(ref l) => format!("&{} ()", l),

                TypeParameter::Id(ref id) => id.to_string(),
            })
            .collect();
        format!("core::marker::PhantomData<({})>", Sep(", ", &phantom_bits),)
    }

    /// Returns expression that captures the user-declared type
    /// parameters in a phantom-data. This helps with ensuring that
    /// all type parameters are constrained, even if they are not
    /// used.
    pub fn phantom_data_expr(&self) -> String {
        let phantom_bits: Vec<_> = self
            .grammar
            .type_parameters
            .iter()
            .map(|tp| match *tp {
                TypeParameter::Lifetime(_) => "&()".to_string(),
                TypeParameter::Id(ref id) => id.to_string(),
            })
            .collect();
        format!(
            "core::marker::PhantomData::<({})>",
            Sep(", ", &phantom_bits),
        )
    }
}