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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
use std::collections::HashSet;

use super::grammar_type_generator::GrammarTypeInfo;
use super::symbol_table::{SymbolId, SymbolTable, TypeEntrails};
use super::template_data::{
    NonTerminalTypeEnum, NonTerminalTypeStruct, UserTraitCallerFunctionDataBuilder,
    UserTraitDataBuilder, UserTraitFunctionDataBuilder, UserTraitFunctionStackPopDataBuilder,
};
use crate::generators::naming_helper::NamingHelper as NmHlp;
use crate::generators::GrammarConfig;
use crate::grammar::{ProductionAttribute, SymbolAttribute};
use crate::parser::{ParolGrammarItem, Production};
use crate::{ParolGrammar, Pr, StrVec};
use log::trace;
use miette::{bail, miette, IntoDiagnostic, Result};

/// Generator for user trait code
#[derive(Builder, Debug, Default)]
pub struct UserTraitGenerator<'a> {
    /// User type that implements the language processing
    user_type_name: String,
    /// User type's module name
    module_name: &'a str,
    /// Enable feature auto-generation for expanded grammar's semantic actions
    auto_generate: bool,
    /// Parsed original user grammar
    parol_grammar: &'a ParolGrammar,
    /// Compiled grammar configuration
    grammar_config: &'a GrammarConfig,
}

impl<'a> UserTraitGenerator<'a> {
    fn generate_inner_action_args(
        &self,
        action_id: SymbolId,
        symbol_table: &SymbolTable,
    ) -> Result<String> {
        // We reference the parse_tree argument only if a token is in the argument list
        let lifetime = if self.auto_generate { "<'t>" } else { "" };
        let mut parse_tree_argument_used = false;
        let mut arguments = Vec::new();

        for member_id in symbol_table.members(action_id)? {
            let arg_inst = symbol_table.symbol_as_instance(*member_id)?;
            let arg_type = symbol_table.symbol_as_type(arg_inst.type_id)?;
            if matches!(arg_type.entrails, TypeEntrails::Token) {
                parse_tree_argument_used = true;
            }
            arguments.push(format!(
                "{}: &ParseTreeStackEntry{}",
                NmHlp::add_unused_indicator(arg_inst.used, symbol_table.name(arg_inst.name_id)),
                lifetime
            ));
        }

        arguments.push(format!(
            "{}parse_tree: &Tree<ParseTreeType{}>",
            NmHlp::item_unused_indicator(self.auto_generate && parse_tree_argument_used),
            lifetime
        ));
        Ok(arguments.join(", "))
    }

    fn generate_context(&self, code: &mut StrVec) {
        if self.auto_generate {
            code.push("let context = function_name!();".to_string());
            code.push("trace!(\"{}\", self.trace_item_stack(context));".to_string());
        }
    }

    fn generate_token_assignments(
        &self,
        code: &mut StrVec,
        action_id: SymbolId,
        symbol_table: &SymbolTable,
    ) -> Result<()> {
        if !self.auto_generate {
            return Ok(());
        }

        for member_id in symbol_table.members(action_id)? {
            let arg_inst = symbol_table.symbol_as_instance(*member_id)?;
            let arg_type = symbol_table.symbol_as_type(arg_inst.type_id)?;
            if matches!(arg_type.entrails, TypeEntrails::Token) {
                let arg_name = symbol_table.name(arg_inst.name_id);
                code.push(format!(
                    "let {} = *{}.token(parse_tree)?;",
                    arg_name, arg_name
                ))
            }
        }
        Ok(())
    }

    fn generate_stack_pops(
        &self,
        code: &mut StrVec,
        action_id: SymbolId,
        symbol_table: &SymbolTable,
    ) -> Result<()> {
        if !self.auto_generate {
            return Ok(());
        }

        let function = symbol_table.symbol_as_function(action_id)?;

        for (i, member_id) in symbol_table.members(action_id)?.iter().rev().enumerate() {
            let arg_inst = symbol_table.symbol_as_instance(*member_id)?;
            let arg_type = symbol_table.symbol_as_type(arg_inst.type_id)?;
            if !matches!(arg_type.entrails, TypeEntrails::Token) {
                let arg_name = symbol_table.name(arg_inst.name_id);
                let stack_pop_data = UserTraitFunctionStackPopDataBuilder::default()
                    .arg_name(arg_name.to_string())
                    .arg_type(arg_type.inner_name(symbol_table)?)
                    .vec_anchor(arg_inst.sem == SymbolAttribute::RepetitionAnchor)
                    .vec_push_semantic(
                        function.sem == ProductionAttribute::AddToCollection && i == 0,
                    )
                    .build()
                    .into_diagnostic()?;
                code.push(format!("{}", stack_pop_data));
            }
        }
        Ok(())
    }

    fn generate_push_semantic(
        &self,
        code: &mut StrVec,
        action_id: SymbolId,
        symbol_table: &SymbolTable,
    ) -> Result<()> {
        let function = symbol_table.symbol_as_function(action_id)?;
        let fn_type = symbol_table.symbol_as_type(action_id)?;
        let fn_name = symbol_table.name(fn_type.name_id).to_string();

        if self.auto_generate && function.sem == ProductionAttribute::AddToCollection {
            let last_arg = symbol_table
                .members(action_id)?
                .iter()
                .last()
                .ok_or_else(|| miette!("There should be at least one argument!"))?;
            let arg_inst = symbol_table.symbol_as_instance(*last_arg)?;
            let arg_name = symbol_table.name(arg_inst.name_id);
            code.push("// Add an element to the vector".to_string());
            code.push(format!(" {}.push({}_built);", arg_name, fn_name,));
        }
        Ok(())
    }

    fn generate_result_builder(
        &self,
        code: &mut StrVec,
        action_id: SymbolId,
        type_info: &GrammarTypeInfo,
    ) -> Result<()> {
        if !self.auto_generate {
            return Ok(());
        }

        let symbol_table = &type_info.symbol_table;
        let function = symbol_table.symbol_as_function(action_id)?;
        let fn_type = symbol_table.symbol_as_type(action_id)?;
        let fn_name = symbol_table.name(fn_type.name_id).to_string();
        let fn_out_type = symbol_table.symbol_as_type(
            *type_info
                .production_types
                .get(&function.prod_num)
                .ok_or_else(|| miette!("Production output type not accessible!"))?,
        )?;
        let nt_type = symbol_table.symbol_as_type(
            *type_info
                .non_terminal_types
                .get(&function.non_terminal)
                .ok_or_else(|| miette!("Non-terminal type not accessible!"))?,
        )?;

        if function.sem == ProductionAttribute::CollectionStart {
            code.push(format!("let {}_built = Vec::new();", fn_name));
        } else if function.sem == ProductionAttribute::AddToCollection {
            code.push(format!(
                "let {}_built = {}Builder::default()",
                fn_name,
                nt_type.name(symbol_table)
            ));
            for member_id in symbol_table.members(action_id)?.iter().rev().skip(1) {
                let arg_inst = symbol_table.symbol_as_instance(*member_id)?;
                let arg_type = symbol_table.symbol_as_type(arg_inst.type_id)?;
                let arg_name = symbol_table.name(arg_inst.name_id);
                let setter_name = &arg_name;
                let arg_name = if matches!(arg_type.entrails, TypeEntrails::Box(_))
                    && arg_inst.sem == SymbolAttribute::None
                {
                    format!("Box::new({})", &arg_name)
                } else {
                    arg_name.to_string()
                };
                code.push(format!("    .{}({})", setter_name, arg_name));
            }
            code.push("    .build()".to_string());
            code.push("    .into_diagnostic()?;".to_string());
        } else {
            let builder_prefix = if function.alts == 1 {
                nt_type.name(symbol_table)
            } else {
                fn_out_type.name(symbol_table)
            };
            code.push(format!(
                "let {}_built = {}Builder::default()",
                fn_name, builder_prefix
            ));
            for member_id in symbol_table.members(action_id)? {
                let arg_inst = symbol_table.symbol_as_instance(*member_id)?;
                let arg_type = symbol_table.symbol_as_type(arg_inst.type_id)?;
                let arg_name = symbol_table.name(arg_inst.name_id);
                let setter_name = &arg_name;
                let arg_name = if matches!(arg_type.entrails, TypeEntrails::Box(_)) {
                    format!("Box::new({})", arg_name)
                } else {
                    arg_name.to_string()
                };
                code.push(format!("    .{}({})", setter_name, arg_name));
            }
            code.push("    .build()".to_string());
            code.push("    .into_diagnostic()?;".to_string());
            if function.alts > 1 {
                // Type adjustment to the non-terminal enum
                // let list_0 = List::List0(list_0);
                let enum_variant_name = symbol_table
                    .members(nt_type.my_id)?
                    .iter()
                    .find(|variant| {
                        if let Ok(enum_variant) = symbol_table.symbol_as_type(**variant) {
                            if let TypeEntrails::EnumVariant(inner_type) = enum_variant.entrails {
                                inner_type == fn_out_type.my_id
                            } else {
                                false
                            }
                        } else {
                            false
                        }
                    })
                    .map(|enum_variant_id| {
                        symbol_table
                            .symbol_as_type(
                                symbol_table.symbol_as_type(*enum_variant_id).unwrap().my_id,
                            )
                            .unwrap()
                            .name(symbol_table)
                    })
                    .ok_or_else(|| miette!("Enum variant not found"))?;
                code.push(format!(
                    "let {}_built = {}::{}({}_built);",
                    fn_name,
                    nt_type.name(symbol_table),
                    enum_variant_name,
                    fn_name
                ));
            }
        }
        Ok(())
    }

    fn generate_user_action_call(
        &self,
        code: &mut StrVec,
        action_id: SymbolId,
        type_info: &GrammarTypeInfo,
        parol_grammar: &'a ParolGrammar,
    ) -> Result<()> {
        let symbol_table = &type_info.symbol_table;
        let function = symbol_table.symbol_as_function(action_id)?;
        let fn_type = symbol_table.symbol_as_type(action_id)?;
        let fn_name = symbol_table.name(fn_type.name_id).to_string();

        if self.auto_generate
            && parol_grammar
                .item_stack
                .iter()
                .filter_map(|item| match item {
                    ParolGrammarItem::Prod(Production { lhs, .. }) => Some(lhs),
                    _ => None,
                })
                .any(|lhs| &function.non_terminal == lhs)
        {
            code.push("// Calling user action here".to_string());
            code.push(format!(
                "self.user_grammar.{}(&{}_built)?;",
                NmHlp::to_lower_snake_case(&function.non_terminal),
                fn_name
            ));
        }
        Ok(())
    }

    fn generate_stack_push(
        &self,
        code: &mut StrVec,
        action_id: SymbolId,
        symbol_table: &SymbolTable,
    ) -> Result<()> {
        if self.auto_generate {
            let function = symbol_table.symbol_as_function(action_id)?;
            let fn_type = symbol_table.symbol_as_type(action_id)?;
            let fn_name = symbol_table.name(fn_type.name_id).to_string();

            if function.sem == ProductionAttribute::AddToCollection {
                // The output type of the action is the type generated for the action's non-terminal
                // filled with type of the action's last argument (the vector)
                let last_arg = symbol_table
                    .members(action_id)?
                    .iter()
                    .last()
                    .ok_or_else(|| miette!("There should be at least one argument!"))?;
                let arg_inst = symbol_table.symbol_as_instance(*last_arg)?;
                let arg_name = symbol_table.name(arg_inst.name_id);

                code.push(format!(
                    "self.push(ASTType::{}({}), context);",
                    NmHlp::to_upper_camel_case(&function.non_terminal),
                    arg_name
                ));
            } else {
                // The output type of the action is the type generated for the action's non-terminal
                // filled with type kind of the action
                code.push(format!(
                    "self.push(ASTType::{}({}_built), context);",
                    NmHlp::to_upper_camel_case(&function.non_terminal),
                    fn_name
                ));
            }
        }
        Ok(())
    }

    fn generate_user_action_args(non_terminal: &str) -> String {
        format!("_arg: &{}<'t>", NmHlp::to_upper_camel_case(non_terminal))
    }

    fn generate_caller_argument_list(pr: &Pr) -> String {
        let mut arguments = pr
            .get_r()
            .iter()
            .filter(|s| !s.is_switch())
            .enumerate()
            .map(|(i, _)| format!("&children[{}]", i))
            .collect::<Vec<String>>();
        arguments.push("parse_tree".to_string());
        arguments.join(", ")
    }

    fn format_type(
        type_id: SymbolId,
        symbol_table: &SymbolTable,
        comment: StrVec,
    ) -> Result<Option<String>> {
        let type_symbol = symbol_table.symbol_as_type(type_id)?;
        let type_name = symbol_table.name(type_symbol.name_id).to_string();
        let lifetime = symbol_table.lifetime(type_symbol.my_id);
        let default_members = Vec::default();
        let members = symbol_table
            .members(type_symbol.my_id)
            .unwrap_or(&default_members);

        match type_symbol.entrails {
            TypeEntrails::Struct => {
                let struct_data = NonTerminalTypeStruct {
                    comment,
                    type_name,
                    lifetime,
                    members: members.iter().fold(StrVec::new(4), |mut acc, m| {
                        acc.push(symbol_table.symbol(*m).to_rust(symbol_table));
                        acc
                    }),
                };
                Ok(Some(format!("{}", struct_data)))
            }
            TypeEntrails::Enum => {
                let struct_data = NonTerminalTypeEnum {
                    comment,
                    type_name,
                    lifetime,
                    members: members.iter().fold(StrVec::new(4), |mut acc, m| {
                        acc.push(symbol_table.symbol(*m).to_rust(symbol_table));
                        acc
                    }),
                };
                Ok(Some(format!("{}", struct_data)))
            }
            _ => bail!("Unexpected type!"),
        }
    }

    // ---------------------------------------------------
    // Part of the Public API
    // *Changes will affect crate's version according to semver*
    // ---------------------------------------------------
    ///
    /// Generates the file with the user actions trait.
    ///
    pub fn generate_user_trait_source(&self) -> Result<String> {
        let mut type_info: GrammarTypeInfo = GrammarTypeInfo::try_new(&self.user_type_name)?;
        type_info.build(self.grammar_config)?;
        type_info.set_auto_generate(self.auto_generate)?;

        let production_output_types = if self.auto_generate {
            type_info
                .production_types
                .iter()
                .map(|(prod_num, type_id)| {
                    (
                        type_id,
                        type_info
                            .symbol_table
                            .symbol_as_function(*type_info.adapter_actions.get(prod_num).unwrap()),
                    )
                })
                .filter_map(|(t, f)| {
                    if let Ok(f) = f {
                        if f.alts > 1 && f.sem == ProductionAttribute::None {
                            Some((t, f))
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                })
                .fold(Ok(StrVec::new(0)), |acc: Result<StrVec>, (t, f)| {
                    if let Ok(mut acc) = acc {
                        let mut comment = StrVec::new(0);
                        comment.push(String::default());
                        comment.push(format!("Type derived for production {}", f.prod_num));
                        comment.push(String::default());
                        comment.push(f.prod_string.clone());
                        comment.push(String::default());
                        Self::format_type(*t, &type_info.symbol_table, comment)?
                            .into_iter()
                            .for_each(|s| acc.push(s));
                        Ok(acc)
                    } else {
                        acc
                    }
                })?
        } else {
            StrVec::new(0)
        };

        let non_terminal_types = if self.auto_generate {
            type_info.non_terminal_types.iter().fold(
                Ok(StrVec::new(0)),
                |acc: Result<StrVec>, (s, t)| {
                    if let Ok(mut acc) = acc {
                        let mut comment = StrVec::new(0);
                        comment.push(String::default());
                        comment.push(format!("Type derived for non-terminal {}", s));
                        comment.push(String::default());
                        Self::format_type(*t, &type_info.symbol_table, comment)?
                            .into_iter()
                            .for_each(|s| acc.push(s));
                        Ok(acc)
                    } else {
                        acc
                    }
                },
            )?
        } else {
            StrVec::new(0)
        };

        let ast_type_decl = if self.auto_generate {
            let mut comment = StrVec::new(0);
            comment.push(String::default());
            comment.push("Deduced ASTType of expanded grammar".to_string());
            comment.push(String::default());
            Self::format_type(type_info.ast_enum_type, &type_info.symbol_table, comment)?.unwrap()
        } else {
            String::default()
        };

        let trait_functions = type_info.adapter_actions.iter().fold(
            Ok(StrVec::new(0).first_line_no_indent()),
            |acc: Result<StrVec>, a| {
                if let Ok(mut acc) = acc {
                    let action_id = *a.1;
                    let fn_type = type_info.symbol_table.symbol_as_type(action_id)?;
                    let fn_name = type_info.symbol_table.name(fn_type.name_id).to_string();
                    let function = type_info.symbol_table.symbol_as_function(action_id)?;
                    let prod_num = function.prod_num;
                    let prod_string = function.prod_string.clone();
                    let fn_arguments =
                        self.generate_inner_action_args(action_id, &type_info.symbol_table)?;
                    let mut code = StrVec::new(8);
                    self.generate_context(&mut code);
                    self.generate_token_assignments(&mut code, action_id, &type_info.symbol_table)?;
                    self.generate_stack_pops(&mut code, action_id, &type_info.symbol_table)?;
                    self.generate_result_builder(&mut code, action_id, &type_info)?;
                    self.generate_push_semantic(&mut code, action_id, &type_info.symbol_table)?;
                    self.generate_user_action_call(
                        &mut code,
                        action_id,
                        &type_info,
                        self.parol_grammar,
                    )?;
                    self.generate_stack_push(&mut code, action_id, &type_info.symbol_table)?;
                    let user_trait_function_data = UserTraitFunctionDataBuilder::default()
                        .fn_name(&fn_name)
                        .prod_num(prod_num)
                        .fn_arguments(fn_arguments)
                        .prod_string(prod_string)
                        .named(self.auto_generate)
                        .code(code)
                        .inner(true)
                        .build()
                        .into_diagnostic()?;
                    acc.push(format!("{}", user_trait_function_data));
                    Ok(acc)
                } else {
                    acc
                }
            },
        )?;

        let user_trait_functions = if self.auto_generate {
            trace!(
                "parol_grammar.item_stack:\n{:?}",
                self.parol_grammar.item_stack
            );

            let mut processed_non_terminals: HashSet<String> = HashSet::new();
            self.parol_grammar
                .item_stack
                .iter()
                .fold(
                    Ok((StrVec::new(0).first_line_no_indent(), 0)),
                    |acc: Result<(StrVec, usize)>, p| {
                        if let Ok((mut acc, mut i)) = acc {
                            if let ParolGrammarItem::Prod(Production { lhs, rhs: _ }) = p {
                                if !processed_non_terminals.contains(lhs) {
                                    let fn_name = NmHlp::to_lower_snake_case(lhs);
                                    let prod_string = p.to_par();
                                    let fn_arguments = Self::generate_user_action_args(lhs);
                                    let code = StrVec::default();
                                    let user_trait_function_data =
                                        UserTraitFunctionDataBuilder::default()
                                            .fn_name(&fn_name)
                                            .prod_num(i)
                                            .fn_arguments(fn_arguments)
                                            .prod_string(prod_string)
                                            .code(code)
                                            .named(false)
                                            .inner(false)
                                            .build()
                                            .into_diagnostic()?;

                                    acc.push(format!("{}", user_trait_function_data));
                                    processed_non_terminals.insert(lhs.to_string());
                                }
                                i += 1;
                            }
                            Ok((acc, i))
                        } else {
                            acc
                        }
                    },
                )?
                .0
        } else {
            StrVec::default()
        };

        trace!("user_trait_functions:\n{}", user_trait_functions);

        let trait_caller = self.grammar_config.cfg.pr.iter().enumerate().fold(
            Ok(StrVec::new(12)),
            |acc: Result<StrVec>, (i, p)| {
                if let Ok(mut acc) = acc {
                    let fn_type_id = type_info.adapter_actions.get(&i).unwrap();
                    let fn_type = type_info.symbol_table.symbol_as_type(*fn_type_id)?;
                    let fn_name = type_info.symbol_table.name(fn_type.name_id).to_string();
                    let fn_arguments = Self::generate_caller_argument_list(p);
                    let user_trait_function_data = UserTraitCallerFunctionDataBuilder::default()
                        .fn_name(fn_name)
                        .prod_num(i)
                        .fn_arguments(fn_arguments)
                        .build()
                        .into_diagnostic()?;
                    acc.push(format!("{}", user_trait_function_data));
                    Ok(acc)
                } else {
                    acc
                }
            },
        )?;

        let user_trait_data = UserTraitDataBuilder::default()
            .user_type_name(&self.user_type_name)
            .auto_generate(self.auto_generate)
            .production_output_types(production_output_types)
            .non_terminal_types(non_terminal_types)
            .ast_type_decl(ast_type_decl)
            .trait_functions(trait_functions)
            .trait_caller(trait_caller)
            .module_name(self.module_name)
            .user_trait_functions(user_trait_functions)
            .build()
            .into_diagnostic()?;

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

    // ---------------------------------------------------
    // Part of the Public API
    // *Changes will affect crate's version according to semver*
    // ---------------------------------------------------
    /// Creates a new item
    pub fn try_new(
        user_type_name: &'a str,
        module_name: &'a str,
        auto_generate: bool,
        parol_grammar: &'a ParolGrammar,
        grammar_config: &'a GrammarConfig,
    ) -> Result<Self> {
        let user_type_name = NmHlp::to_upper_camel_case(user_type_name);
        UserTraitGeneratorBuilder::default()
            .user_type_name(user_type_name)
            .module_name(module_name)
            .auto_generate(auto_generate)
            .grammar_config(grammar_config)
            .parol_grammar(parol_grammar)
            .build()
            .into_diagnostic()
    }
}