Skip to main content

lexigram_lib/parsergen/
mod.rs

1// Copyright (c) 2025 Redglyph (@gmail.com). All Rights Reserved.
2
3use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
4use iter_index::IndexerIterator;
5use vectree::VecTree;
6use lexigram_core::alt::Alternative;
7use lexigram_core::log::LogMsg;
8use lexigram_core::TokenId;
9use crate::grammar::{grtree_to_str, GrTreeExt, LLParsingTable, NTConversion, ProdRuleSet};
10use crate::{columns_to_str, indent_source, AltId, CharLen, NameFixer, NameTransformer, SourceSpacer, StructLibs, SymbolTable, VarId, LL1};
11use crate::fixed_sym_table::{FixedSymTable, SymInfoTable};
12use crate::alt::ruleflag;
13use crate::build::{BuildError, BuildErrorSource, BuildFrom, HasBuildErrorSource, TryBuildFrom};
14use crate::CollectJoin;
15use crate::grammar::origin::{FromPRS, Origin};
16use crate::lexergen::LexigramCrate;
17use crate::log::{BufLog, LogReader, LogStatus, Logger};
18use crate::parser::{OpCode, Parser, Symbol};
19use crate::segments::Segments;
20use crate::segmap::Seg;
21
22pub(crate) mod tests;
23
24// ---------------------------------------------------------------------------------------------
25
26pub(crate) fn symbol_to_code(s: &Symbol) -> String {
27    match s {
28        Symbol::Empty => "Symbol::Empty".to_string(),
29        Symbol::T(t) => format!("Symbol::T({t})"),
30        Symbol::NT(nt) => format!("Symbol::NT({nt})"),
31        Symbol::End => "Symbol::End".to_string(),
32    }
33}
34
35// ---------------------------------------------------------------------------------------------
36
37#[derive(Clone, Debug, PartialEq)]
38struct ItemInfo {
39    name: String,
40    sym: Symbol,            // NT(var) or T(token)
41    owner: VarId,           // NT owning this item; for ex. owner = `A` for `sym = b` in `A -> a b+ c`
42    index: Option<usize>    // when several identical symbols in the same alternative: `A -> id := id ( id )`
43}
44
45#[allow(unused)]
46impl ItemInfo {
47    fn to_str(&self, symbol_table: Option<&SymbolTable>) -> String {
48        format!("{} ({}{}, ◄{})",
49                self.name,
50                self.sym.to_str(symbol_table),
51                if let Some(n) = self.index { format!(", [{n}]") } else { "".to_string() },
52                Symbol::NT(self.owner).to_str(symbol_table))
53    }
54}
55
56// ---------------------------------------------------------------------------------------------
57
58/// Tables and parameters used to create a [`Parser`]. This type is used as a return object from the parser generator,
59/// when the Parser must be created dynamically; for example, in tests or in situations where the grammar isn't
60/// known in advance. In those situations, the ParserTables object must live as long as the parser it generates.
61///
62/// The Parser itself uses references to tables whenever possible because, in most situations, the tables are
63/// static in generated source files. A few fields must still be created dynamically from (possibly) static
64/// tables because they don't exist in static form.
65pub struct ParserTables {
66    num_nt: usize,
67    num_t: usize,
68    // parsing_table: LLParsingTable,
69    alt_var: Vec<VarId>,
70    alts: Vec<Alternative>,
71    opcodes: Vec<Vec<OpCode>>,
72    init_opcodes: Vec<OpCode>,
73    table: Vec<AltId>,
74    symbol_table: FixedSymTable,
75    start: VarId,
76    include_alts: bool,
77}
78
79impl ParserTables {
80    pub fn new(
81        parsing_table: LLParsingTable,
82        symbol_table: FixedSymTable,
83        opcodes: Vec<Vec<OpCode>>,
84        init_opcodes: Vec<OpCode>,
85        start: VarId,
86        include_alts: bool
87    ) -> Self {
88        assert!(parsing_table.num_nt > start as usize);
89        let num_nt = parsing_table.num_nt;
90        let num_t = parsing_table.num_t;
91        let table = parsing_table.table;
92        let (factor_var, alts): (Vec<_>, Vec<_>) = parsing_table.alts.into_iter().unzip();
93        ParserTables { num_nt, num_t, alt_var: factor_var, alts, opcodes, init_opcodes, table, symbol_table, start, include_alts }
94    }
95
96    pub fn make_parser(&self) -> Parser<'_> {
97        Parser::new(
98            self.num_nt,
99            self.num_t,
100            self.alt_var.as_slice(),
101            if self.include_alts { self.alts.clone() } else { vec![] },
102            self.opcodes.clone(),
103            self.init_opcodes.clone(),
104            self.table.as_slice(),
105            self.symbol_table.clone(),
106            self.start,
107        )
108    }
109}
110
111impl BuildFrom<ParserGen> for ParserTables {
112    /// Creates a [`ParserTables`], from which a parser can be created dynamically with
113    /// [`parser_table.make_parser()`](ParserTables::make_parser).
114    fn build_from(parser_gen: ParserGen) -> Self {
115        ParserTables::new(
116            parser_gen.parsing_table,
117            parser_gen.symbol_table.to_fixed_sym_table(),
118            parser_gen.opcodes,
119            parser_gen.init_opcodes,
120            parser_gen.start,
121            parser_gen.include_alts
122        )
123    }
124}
125
126// not generated automatically since ParserTables isn't LogReader
127impl TryBuildFrom<ParserGen> for ParserTables {
128    type Error = BuildError;
129
130    fn try_build_from(source: ParserGen) -> Result<Self, Self::Error> {
131        if source.get_log().has_no_errors() {
132            Ok(ParserTables::build_from(source))
133        } else {
134            Err(BuildError::new(source.give_log(), BuildErrorSource::ParserGen))
135        }
136    }
137}
138
139// ---------------------------------------------------------------------------------------------
140
141/// Determines which nonterminals have a value, so a dedicated type and field in contexts:
142/// * [`None`](NTValue::None): No nonterminal has a value
143/// * [`Parents`](NTValue::Parents): Only the top nonterminal parents have a value
144/// * [`Default`](NTValue::Default): The top nonterminal parents and the children of `(<L> )+*` have a value
145/// * [`SetIds(Vec<VarId>)`](NTValue::SetIds): The nonterminals that have a value is set explicitly by ID
146/// * [`SetNames(Vec<String>)`](NTValue::SetNames): The nonterminals that have a value is set explicitly by name.
147///   The names "`<default>`" and "`<parents>`" can be used to set all the nonterminals of the corresponding class.
148///   Individual nonterminals can be preceded by a "-" to indicate they don't hold a value.
149#[derive(Clone, PartialEq, Debug)]
150pub enum NTValue {
151    /// No nonterminal has a value
152    None,
153    /// Only the top nonterminal parents have a value
154    Parents,
155    /// The top nonterminal parents and the children of `(<L> )+*` have a value
156    Default,
157    /// The set of nonterminals that have a value is set explicitly by ID
158    SetIds(Vec<VarId>),
159    /// The set of nonterminals that have a value is set explicitly by name. Individual names preceded by a "-" don't have a value.
160    SetNames(Vec<String>),
161}
162
163impl NTValue {
164    /// Only the top nonterminal parents have a value (can be used in [NTValue::SetNames])
165    pub const DEFAULT: &str = "<default>";
166    /// The top nonterminal parents and the children of `(<L> )+*` have a value (can be used in [NTValue::SetNames])
167    pub const PARENTS: &str = "<parents>";
168
169    pub fn is_none(&self) -> bool {
170        matches!(self, NTValue::None)
171    }
172
173    pub fn is_parents(&self) -> bool {
174        matches!(self, NTValue::Parents)
175    }
176
177    pub fn is_default(&self) -> bool {
178        matches!(self, NTValue::Default)
179    }
180
181    pub fn is_ids(&self) -> bool {
182        matches!(self, NTValue::SetIds(_))
183    }
184
185    pub fn is_names(&self) -> bool {
186        matches!(self, NTValue::SetNames(_))
187    }
188}
189
190// ---------------------------------------------------------------------------------------------
191
192pub static DEFAULT_LISTENER_NAME: &str = "Parser";
193
194pub type SpanNbr = u16;
195
196fn count_span_nbr(opcode: &[OpCode]) -> SpanNbr {
197    let count = opcode.iter().filter(|op| op.has_span()).count();
198    count.try_into().unwrap_or_else(|_| panic!("# span = {count} > {}", SpanNbr::MAX))
199}
200
201struct SourceInputContext<'a> {
202    parent_has_value        : bool,
203    parent_nt               : usize,
204    pinfo                   : &'a LLParsingTable,
205    syns                    : &'a Vec<VarId>,
206    ambig_op_alts           : &'a BTreeMap<AltId, Vec<AltId>>,
207}
208
209struct SourceState<'a> {
210    init_nt_done            : &'a mut HashSet<VarId>,
211    span_init               : &'a mut HashSet<VarId>,
212    nt_contexts             : &'a mut Vec<Option<Vec<AltId>>>,
213    exit_alt_done           : &'a mut HashSet<VarId>,
214    exit_fixer              : &'a mut NameFixer,
215}
216
217struct WrapperSources {
218    src                     : Vec<String>,
219    src_listener_decl       : Vec<String>,
220    src_skel                : Vec<String>,
221    src_types               : Vec<String>,
222    src_init                : Vec<Vec<String>>,
223    src_exit                : Vec<Vec<String>>,
224    src_wrapper_impl        : Vec<String>,
225}
226
227#[derive(Debug)]
228pub struct ParserGen {
229    parsing_table: LLParsingTable,
230    symbol_table: SymbolTable,
231    terminal_hooks: Vec<TokenId>,
232    name: String,
233    nt_value: Vec<bool>,
234    /// `nt_parent[v]` is the vector of all variables having `v` has top parent (including `v` itself)
235    nt_parent: Vec<Vec<VarId>>,
236    var_alts: Vec<Vec<AltId>>,
237    origin: Origin<VarId, FromPRS>,
238    item_ops: Vec<Vec<Symbol>>,
239    opcodes: Vec<Vec<OpCode>>,
240    init_opcodes: Vec<OpCode>,
241    nt_name: Vec<(String, String, String)>,
242    alt_info: Vec<Option<(VarId, String)>>,
243    item_info: Vec<Vec<ItemInfo>>,
244    child_repeat_endpoints: HashMap<VarId, Vec<AltId>>,
245    /// generates the parser source code
246    gen_parser: bool,
247    /// generates the wrapper source code
248    gen_wrapper: bool,
249    /// source code indentation of the wrapper, in number of space characters
250    indent: usize,
251    /// source code indentation of the template for the user types
252    types_indent: usize,
253    /// source code indentation of the template for the listener implementation
254    listener_indent: usize,
255    /// generates code to give the location of nonterminals and tokens as extra parameters of listener methods
256    gen_span_params: bool,
257    gen_token_enums: bool,
258    span_nbrs: Vec<SpanNbr>,
259    /// Number of span values taken from a PARENT_REPEAT in init() to extract the first item of a SEP_LIST
260    span_nbrs_sep_list: HashMap<AltId, SpanNbr>,
261    start: VarId,
262    nt_conversion: HashMap<VarId, NTConversion>,
263    headers: Vec<String>,
264    used_libs: StructLibs,
265    nt_type: HashMap<VarId, String>,
266    log: BufLog,
267    include_alts: bool,
268    lib_crate: LexigramCrate,
269}
270
271impl ParserGen {
272    /// Creates a [ParserGen] from a set of production rules and gives it a specific name, which is used
273    /// to name the user listener trait in the generated code.
274    ///
275    /// If `rules` already has a name, it is best to use the
276    /// [`BuildFrom<ProdRuleSet<T>>`](BuildFrom<ProdRuleSet<T>>::build_from) trait.
277    pub fn build_from_rules<T>(mut rules: ProdRuleSet<T>, name: String) -> Self
278    where
279        ProdRuleSet<LL1>: BuildFrom<ProdRuleSet<T>>,
280    {
281        rules.log.add_note("building parser gen from rules...");
282        let mut ll1_rules = ProdRuleSet::<LL1>::build_from(rules);
283        assert_eq!(ll1_rules.get_log().num_errors(), 0);
284        let parsing_table = ll1_rules.make_parsing_table(true);
285        let num_nt = ll1_rules.get_num_nt();
286        let start = ll1_rules.get_start().unwrap();
287        let mut var_alts = vec![vec![]; num_nt];
288        for (alt_id, (var_id, _)) in parsing_table.alts.iter().index() {
289            var_alts[*var_id as usize].push(alt_id);
290        }
291        let mut nt_parent: Vec<Vec<VarId>> = vec![vec![]; num_nt];
292        for var_id in 0..num_nt {
293            let top_var_id = parsing_table.get_top_parent(var_id as VarId) as usize;
294            nt_parent[top_var_id].push(var_id as VarId);
295        }
296        let ProdRuleSet { symbol_table, nt_conversion, origin, .. } = ll1_rules;
297        let mut builder = ParserGen {
298            parsing_table,
299            symbol_table: symbol_table.expect(stringify!("symbol table is required to create a {}", std::any::type_name::<Self>())),
300            gen_span_params: false,
301            gen_token_enums: false,
302            name,
303            nt_value: vec![false; num_nt],
304            nt_parent,
305            var_alts,
306            origin,
307            terminal_hooks: Vec::new(),
308            item_ops: Vec::new(),
309            opcodes: Vec::new(),
310            init_opcodes: Vec::new(),
311            nt_name: Vec::new(),
312            alt_info: Vec::new(),
313            item_info: Vec::new(),
314            child_repeat_endpoints: HashMap::new(),
315            gen_parser: true,
316            gen_wrapper: true,
317            indent: 0,
318            types_indent: 0,
319            listener_indent: 0,
320            span_nbrs: Vec::new(),
321            span_nbrs_sep_list: HashMap::new(),
322            start,
323            nt_conversion,
324            headers: Vec::new(),
325            used_libs: StructLibs::new(),
326            nt_type: HashMap::new(),
327            log: ll1_rules.log,
328            include_alts: false,
329            lib_crate: LexigramCrate::Core,
330        };
331        builder.make_opcodes();
332        builder.make_span_nbrs();
333        builder
334    }
335
336    pub fn set_name(&mut self, name: String) {
337        self.name = name;
338    }
339
340    pub fn get_name(&self) -> &str {
341        &self.name
342    }
343
344    #[inline]
345    pub fn get_symbol_table(&self) -> Option<&SymbolTable> {
346        Some(&self.symbol_table)
347    }
348
349    #[inline]
350    pub fn get_parsing_table(&self) -> &LLParsingTable {
351        &self.parsing_table
352    }
353
354    #[inline]
355    pub fn set_terminal_hooks(&mut self, terminal_hooks: Vec<TokenId>) {
356        if !terminal_hooks.is_empty() {
357            self.gen_token_enums = true;
358        }
359        self.terminal_hooks = terminal_hooks;
360        self.add_opcode_hooks();
361    }
362
363    #[inline]
364    pub fn add_header<T: Into<String>>(&mut self, header: T) {
365        self.headers.push(header.into());
366    }
367
368    #[inline]
369    pub fn extend_headers<I: IntoIterator<Item=T>, T: Into<String>>(&mut self, headers: I) {
370        self.headers.extend(headers.into_iter().map(|s| s.into()));
371    }
372
373    #[inline]
374    pub fn add_lib<T: Into<String>>(&mut self, lib:T) {
375        self.used_libs.add(lib);
376    }
377
378    #[inline]
379    pub fn extend_libs<I: IntoIterator<Item=T>, T: Into<String>>(&mut self, libs: I) {
380        self.used_libs.extend(libs);
381    }
382
383    #[inline]
384    /// Declares the type of a non-terminal. The index of the NT, `org_var`, is the original index
385    /// in the ruletree set, which is the index originally assigned when parsing the grammar file.
386    pub fn add_nt_type<T: Into<String>>(&mut self, org_var: VarId, var_type: T) {
387        let var = self.conv_nt(org_var).unwrap_or_else(|| panic!("var {org_var} doesn't exist"));
388        self.nt_type.insert(var, var_type.into());
389    }
390
391    #[inline]
392    pub fn get_nt_type(&self, v: VarId) -> &str {
393        self.nt_type.get(&v).unwrap().as_str()
394    }
395
396    /// Sets which nonterminals have a value, from [nt_value](NTValue).
397    pub fn set_nt_value(&mut self, nt_value: &NTValue) {
398        let num_nt = self.get_symbol_table().unwrap().get_num_nt() as VarId;
399        let mut stack = vec![nt_value];
400        let mut neg_stack = vec![];
401        while let Some(nt_value) = stack.pop() {
402            match nt_value {
403                NTValue::None => {}
404                NTValue::Parents => {
405                    for v in 0..num_nt {
406                        if self.get_nt_parent(v).is_none() {
407                            self.nt_value[v as usize] = true;
408                        }
409                    }
410                }
411                NTValue::Default => {
412                    for v in 0..num_nt {
413                        if self.get_nt_parent(v).is_none() || self.nt_has_all_flags(v, ruleflag::CHILD_REPEAT | ruleflag::L_FORM) {
414                            self.nt_value[v as usize] = true;
415                        }
416                    }
417                }
418                NTValue::SetIds(ids) => {
419                    for v in ids {
420                        if *v < num_nt {
421                            self.nt_value[*v as usize] = true;
422                        } else {
423                            self.log.add_error(format!("setting value of NT #{v}, which doesn't exist"));
424                        }
425                    }
426                }
427                NTValue::SetNames(names) => {
428                    let name_to_id = self.symbol_table.get_nonterminals().index::<VarId>()
429                        .map(|(v, name)| (name.as_str(), v))
430                        .collect::<HashMap<&str, VarId>>();
431                    for name in names {
432                        match name.as_str() {
433                            NTValue::DEFAULT => stack.push(&NTValue::Default),
434                            NTValue::PARENTS => stack.push(&NTValue::Parents),
435                            mut nt_name => {
436                                let add = if !nt_name.starts_with('-') {
437                                    true
438                                } else {
439                                    nt_name = &nt_name[1..];
440                                    false
441                                };
442                                if let Some(v) = name_to_id.get(nt_name) {
443                                    if add {
444                                        self.nt_value[*v as usize] = true;
445                                    } else {
446                                        neg_stack.push(*v);
447                                    }
448                                } else {
449                                    self.log.add_error(format!("setting value of NT '{name}', which doesn't exist"));
450                                }
451                            }
452                        }
453                    }
454                }
455            }
456        }
457        for v in neg_stack {
458            self.nt_value[v as usize] = false;
459        }
460    }
461
462    #[inline]
463    pub fn set_nt_has_value(&mut self, v: VarId, has_value: bool) {
464        self.nt_value[v as usize] = has_value;
465    }
466
467    /// Generates the parser source code if `gen_parser` is `true`. This option is `true` by default.
468    pub fn set_gen_parser(&mut self, gen_parser: bool) {
469        self.gen_parser = gen_parser;
470    }
471
472    /// Generates the wrapper source code if `gen_parser` is `true`. This option is `true` by default.
473    pub fn set_gen_wrapper(&mut self, gen_wrapper: bool) {
474        self.gen_wrapper = gen_wrapper;
475    }
476
477    /// Sets the source code indentation. This option is 0 by default.
478    pub fn set_indent(&mut self, indent: usize) {
479        self.indent = indent;
480    }
481
482    /// Sets the source code indentation of the template for the user types.
483    /// This option is 0 by default.
484    pub fn set_types_indent(&mut self, indent: usize) {
485        self.types_indent = indent;
486    }
487
488    /// Sets the source code indentation of the template for the listener implementation.
489    /// This option is 0 by default.
490    pub fn set_listener_indent(&mut self, indent: usize) {
491        self.listener_indent = indent;
492    }
493
494    /// Sets the source code indentation for the wrapper, the template for the user types and the
495    /// template for the listener implementation.
496    pub fn set_indents(&mut self, wrapper: usize, types: usize, listner: usize) {
497        self.indent = wrapper;
498        self.types_indent = types;
499        self.listener_indent = listner;
500    }
501
502    /// Generates code to give the location of nonterminals and tokens as extra parameters of listener methods.
503    pub fn set_gen_span_params(&mut self, gen_span_params: bool) {
504        self.gen_span_params = gen_span_params;
505    }
506
507    /// Generates enums for the terminal and nonterminal values. They may be helpful in the optional
508    /// listener trait methods like `hook()` and `intercept_token()` when they are used.
509    ///
510    /// # Example
511    ///
512    /// ```ignore
513    /// #[derive(Clone, Copy, PartialEq, Debug)]
514    /// #[repr(u16)]
515    /// pub enum Term {
516    ///     #[doc = "','"]        Comma = 0,
517    ///     #[doc = "';'"]        SemiColon = 1,
518    /// }
519    ///
520    /// #[derive(Clone, Copy, PartialEq, Debug)]
521    /// #[repr(u16)]
522    /// pub enum NTerm {
523    ///     #[doc = "`program`"]                   Program = 0,
524    ///     #[doc = "`stmt_i`, parent: `program`"] StmtI = 1,
525    /// }
526    /// ```
527    pub fn set_gen_token_enums(&mut self, gen_token_enums: bool) {
528        self.gen_token_enums = gen_token_enums;
529    }
530
531    #[inline]
532    pub fn get_nt_parent(&self, v: VarId) -> Option<VarId> {
533        self.parsing_table.parent[v as usize]
534    }
535
536    /// Include the definitions of the alternatives in the parser, for debugging purposes:
537    /// allows to print out the alternatives in VERBOSE mode.
538    pub fn set_include_alts(&mut self, include_alts: bool) {
539        self.include_alts = include_alts;
540    }
541
542    #[inline]
543    pub fn use_full_lib(&mut self, use_full_lib: bool) {
544        self.lib_crate = if use_full_lib { LexigramCrate::Full } else { LexigramCrate::Core };
545    }
546
547    #[inline]
548    pub fn set_crate(&mut self, lcrate: LexigramCrate) {
549        self.lib_crate = lcrate;
550    }
551
552    #[cfg(test)] // we keep it here because we'll need it later for doc comments and logs
553    fn get_original_alt_str(&self, a_id: AltId, symbol_table: Option<&SymbolTable>) -> Option<String> {
554        let (_var, f) = &self.parsing_table.alts[a_id as usize];
555        f.get_origin().and_then(|(o_v, o_id)| {
556            Some(format!(
557                "{} -> {}",
558                Symbol::NT(o_v).to_str(symbol_table),
559                grtree_to_str(self.origin.get_tree(o_v).unwrap(), Some(o_id), None, Some(o_v), symbol_table, false)
560            ))
561        })
562    }
563
564    /// Converts the original index of an NT to its current index.
565    ///
566    /// The original index is the NT's index of a general (non-normalized) ruletree set, as parsed from
567    /// a grammar file. The current index may differ if NTs were removed during the analysis of the
568    /// production rules or if <L> low-latency labels were declared.
569    fn conv_nt(&self, org_var: VarId) -> Option<VarId> {
570        match self.nt_conversion.get(&org_var) {
571            None => if (org_var as usize) < self.parsing_table.num_nt { Some(org_var) } else { None },
572            Some(NTConversion::MovedTo(new)) => Some(*new),
573            Some(NTConversion::Removed) => None
574        }
575    }
576
577    #[allow(unused)]
578    fn nt_has_all_flags(&self, var: VarId, flags: u32) -> bool {
579        self.parsing_table.flags[var as usize] & flags == flags
580    }
581
582    #[allow(unused)]
583    fn nt_has_any_flags(&self, var: VarId, flags: u32) -> bool {
584        self.parsing_table.flags[var as usize] & flags != 0
585    }
586
587    #[allow(unused)]
588    fn sym_has_flags(&self, s: &Symbol, flags: u32) -> bool {
589        if let Symbol::NT(nt) = s { self.nt_has_all_flags(*nt, flags) } else { false }
590    }
591
592    #[allow(unused)]
593    fn sym_has_value(&self, symbol: &Symbol) -> bool {
594        match symbol {
595            Symbol::T(t) => self.symbol_table.is_token_data(*t),
596            Symbol::NT(nt) => self.nt_value[*nt as usize],
597            _ => false
598        }
599    }
600
601    fn full_alt_components(&self, a_id: AltId, emphasis: Option<VarId>) -> (String, String) {
602        const VERBOSE: bool = false;
603        if VERBOSE { println!("full_alt_components(a_id = {a_id}):"); }
604        let &(mut v_a, ref alt) = &self.parsing_table.alts[a_id as usize];
605        while self.parsing_table.flags[v_a as usize] & ruleflag::CHILD_L_FACT != 0 {
606            v_a = *self.parsing_table.parent[v_a as usize].as_ref().unwrap();
607        }
608        let symtab = self.get_symbol_table();
609        if let Some(v_emph) = emphasis {
610            let parent_nt = self.parsing_table.get_top_parent(v_emph);
611            if let Some((t_emph, id_emph)) = self.origin.get(v_emph) {
612                return ((Symbol::NT(parent_nt).to_str(symtab)), grtree_to_str(t_emph, None, Some(id_emph), Some(parent_nt), symtab, true));
613            } else {
614                return (Symbol::NT(parent_nt).to_str(symtab), format!("<VAR {v_emph} NOT FOUND>"));
615            }
616        }
617        if let Some((vo, id)) = alt.get_origin() {
618            let t = self.origin.get_tree(vo).unwrap();
619            let flags = self.parsing_table.flags[v_a as usize];
620            if v_a != vo && flags & ruleflag::CHILD_REPEAT != 0 {
621                // iteration in parent rule
622                (
623                    String::new(),
624                    format!("`{}` {} in `{} -> {}`",
625                            grtree_to_str(t, Some(id), None, Some(vo), symtab, true),
626                            if flags & ruleflag::L_FORM != 0 { "iteration" } else { "item" },
627                            Symbol::NT(vo).to_str(symtab),
628                            grtree_to_str(t, None, Some(id), Some(vo), symtab, true))
629                )
630            } else {
631                let root = Some(id);
632                (Symbol::NT(vo).to_str(symtab), grtree_to_str(t, root, None, Some(vo), symtab, true))
633            }
634        } else {
635            (Symbol::NT(v_a).to_str(symtab), format!("<alt {a_id} NOT FOUND>"))
636        }
637    }
638
639    /// Representation of the original rule behind a context or a user variable
640    fn full_alt_str(&self, a_id: AltId, emphasis: Option<VarId>, quote: bool) -> String {
641        let (left, right) = self.full_alt_components(a_id, emphasis);
642        if left.is_empty() {
643            right
644        } else {
645            format!("{q}{left} -> {right}{q}", q = if quote { "`" } else { "" })
646        }
647    }
648
649    fn make_opcodes(&mut self) {
650        const VERBOSE: bool = false;
651        self.log.add_note("- making opcodes...");
652        self.opcodes.clear();
653        self.init_opcodes = vec![OpCode::End, OpCode::NT(self.start)];
654        for (alt_id, (var_id, alt)) in self.parsing_table.alts.iter().index() {
655            if VERBOSE {
656                println!("{alt_id}: {}", alt.to_rule_str(*var_id, self.get_symbol_table(), 0));
657            }
658            let flags = self.parsing_table.flags[*var_id as usize];
659            let stack_sym = Symbol::NT(*var_id);
660            let mut new = self.parsing_table.alts[alt_id as usize].1.iter().filter(|s| !s.is_empty()).rev().cloned().to_vec();
661            if VERBOSE { println!("  - {}", new.iter().map(|s| s.to_str(self.get_symbol_table())).join(" ")); }
662            let mut opcode = Vec::<OpCode>::new();
663            let mut parent = self.parsing_table.parent[*var_id as usize];
664            if flags & ruleflag::CHILD_L_FACT != 0 {
665                while self.nt_has_all_flags(parent.unwrap(), ruleflag::CHILD_L_FACT) {
666                    parent = self.parsing_table.parent[parent.unwrap() as usize];
667                }
668                let parent = parent.unwrap();
669                // replaces Enter by Loop when going back to left-factorization parent, typically when coupled with + or *
670                // (per construction, there can't be any alternative going back to the grandparent or further up in a left factorization, so
671                //  we don't check that)
672                let parent_r_form_right_rec = self.parsing_table.flags[parent as usize] & ruleflag::R_RECURSION != 0 && flags & ruleflag::L_FORM == 0;
673                if VERBOSE {
674                    println!("  - child lfact, parent: {}, !parent_r_form_right_rec = !{parent_r_form_right_rec}, match = {}",
675                             Symbol::NT(parent).to_str(self.get_symbol_table()),
676                             new.first() == Some(&Symbol::NT(parent)));
677                }
678                if new.first() == Some(&Symbol::NT(parent)) && !parent_r_form_right_rec {
679                    opcode.push(OpCode::Loop(parent));
680                    new.remove(0);
681                }
682            }
683            let parent_lrec_no_lfact = flags & (ruleflag::PARENT_L_RECURSION | ruleflag::PARENT_L_FACTOR) == ruleflag::PARENT_L_RECURSION;
684            if flags & ruleflag::PARENT_L_FACTOR == 0 ||
685                parent_lrec_no_lfact ||
686                new.iter().all(|s| if let Symbol::NT(ch) = s { !self.nt_has_all_flags(*ch, ruleflag::CHILD_L_FACT) } else { true })
687            {
688                // if it's not a parent of left factorization, or
689                // if none of the NT in the alternative is a child of left factorization, or
690                // if it's the top parent of left recursion + left factorization,
691                // => adds an Exit
692                // (said otherwise: we don't want an exit in a parent or in the middle of a chain of left factorizations;
693                //  the exit should be only at the end of left factorizations, or in alternatives that aren't left-factorized -
694                //  except the special case of left recursion + left factorization, which needs the final exit)
695                opcode.push(OpCode::Exit(alt_id)); // will be popped when this NT is completed
696            }
697            opcode.extend(new.into_iter().map(OpCode::from));
698            let r_form_right_rec = flags & ruleflag::R_RECURSION != 0 && flags & ruleflag::L_FORM == 0;
699            if VERBOSE { println!("  - r_form_right_rec = {r_form_right_rec} = {} || {}",
700                                  flags & ruleflag::R_RECURSION != 0 && flags & ruleflag::L_FORM == 0,
701                                  flags & ruleflag::CHILD_L_FACT != 0 && self.parsing_table.flags[parent.unwrap() as usize] & ruleflag::R_RECURSION != 0 && flags & ruleflag::L_FORM == 0); }
702            if opcode.get(1).map(|op| op.matches(stack_sym)).unwrap_or(false) && !r_form_right_rec {
703                // swaps Exit(self) when it's in 2nd position (only happens in [Loop(_), Exit(self), ...],
704                // except right recursions that aren't left-form, because we let them unfold naturally (uses more stack)
705                opcode.swap(0, 1);
706                if VERBOSE { println!("  - swap 0, 1: {}", opcode.iter().map(|s| s.to_str(self.get_symbol_table())).join(" ")); }
707            } else if parent_lrec_no_lfact {
708                if let Some(OpCode::NT(x)) = opcode.get(1) {
709                    if self.nt_has_all_flags(*x, ruleflag::CHILD_L_RECURSION) {
710                        // swaps Exit(self) and call to left recursive item so that the wrapper can issue an exit_NT
711                        // with the correct context
712                        opcode.swap(0, 1);
713                        if VERBOSE { println!("  - swap 0, 1: {}", opcode.iter().map(|s| s.to_str(self.get_symbol_table())).join(" ")); }
714                    }
715                }
716            } else if flags & ruleflag::CHILD_INDEPENDENT_AMBIGUITY != 0 && opcode.len() > 1 {
717                // E_1: ◄4 ►E_2 ►E_1 abs  =>  ●E_2 ◄4 ●E_1 abs (where var_prime E_2 has child_amb flag)
718                if let Some(OpCode::NT(var_prime)) = opcode.get(1) {
719                    let vp = *var_prime; // to work around borrow checker
720                    if self.nt_has_all_flags(vp, ruleflag::CHILD_AMBIGUITY) {
721                        opcode.swap(0, 1);
722                        opcode[0] = OpCode::Loop(vp);
723                        if VERBOSE { println!("  - child indep ambig: {}", opcode.iter().map(|s| s.to_str(self.get_symbol_table())).join(" ")); }
724                    }
725                }
726            }
727            if flags & ruleflag::CHILD_L_FACT != 0 && opcode.len() >= 2 {
728                if self.nt_has_all_flags(parent.unwrap(), ruleflag::R_RECURSION | ruleflag::L_FORM)
729                    && opcode[1] == OpCode::NT(parent.unwrap())
730                {
731                    opcode.swap(0, 1);
732                    opcode[0] = OpCode::Loop(parent.unwrap());
733                }
734                let fact_top = self.parsing_table.get_top_parent(*var_id);
735                if VERBOSE {
736                    println!("  - check for initial exit swap: opcode = [{}], daddy = {}",
737                             opcode.iter().map(|s| s.to_str(self.get_symbol_table())).join(" "),
738                             Symbol::NT(fact_top).to_str(self.get_symbol_table()));
739                }
740                if self.parsing_table.flags[fact_top as usize] & ruleflag::PARENT_L_RECURSION != 0 &&
741                    matches!(opcode[0], OpCode::Exit(_)) &&
742                    matches!(opcode[1], OpCode::NT(v) if self.parsing_table.flags[v as usize] & ruleflag::CHILD_L_RECURSION != 0)
743                {
744                    if VERBOSE {
745                        println!("    swapping for initial exit_{}: {} <-> {}",
746                            Symbol::NT(fact_top).to_str(self.get_symbol_table()).to_lowercase(),
747                            opcode[0].to_str(self.get_symbol_table()),
748                            opcode[1].to_str(self.get_symbol_table())
749                        );
750                    }
751                    opcode.swap(0, 1);
752                }
753            }
754            opcode.iter_mut().for_each(|o| {
755                if let OpCode::NT(v) = o {
756                    // replaces Enter by Loop when back to self,
757                    // except right recursions that aren't left-form, because we let them unfold naturally (uses more stack)
758                    if v == var_id && !r_form_right_rec {
759                        *o = OpCode::Loop(*v)
760                    }
761                }
762            });
763            if VERBOSE { println!("  -> {}", opcode.iter().map(|s| s.to_str(self.get_symbol_table())).join(" ")); }
764            self.opcodes.push(opcode);
765        }
766    }
767
768    /// Adds hook opcodes that must be popped before the corresponding terminal is processed,
769    /// and possibly modified. For example, an `Id` terminal must be changed into `Type`
770    /// when that id has been previously declared as type in the parsed text.
771    ///
772    /// ```text
773    ///          | Num Id  Type  ,   ;  typedef let  =  print  -   +   $
774    /// ---------+--------------------------------------------------------
775    /// program  |  .   .   0    .   .     0     0   .    0    .   .   p
776    /// decl_i   |  .   .   1    .   .     1     2   .    2    .   .   .
777    /// inst_i   |  .   .   .    .   .     .     3   .    3    .   .   p
778    /// decl     |  .   .   4    .   .     5     p   .    p    .   .   .
779    /// […]
780    ///
781    ///  0: program -> decl_i inst_i      | ◄0 ►inst_i ►decl_i
782    ///  1: decl_i -> decl decl_i         | ●decl_i ◄1 ►decl
783    ///  2: decl_i -> ε                   | ◄2
784    ///  3: inst_i -> inst inst_i_1       | ►inst_i_1 ►inst
785    ///  4: decl -> Type Id decl_1 ";"    | ◄4 ";" ►decl_1 Id! Type!
786    ///  5: decl -> "typedef" Type Id ";" | ◄5 ";" Id! Type! "typedef"
787    /// […]
788    /// ```
789    /// - create set of NT that need hooked terminal to make a decision in the table:
790    ///
791    ///     `deps = { ►program, ►decl_i, ►decl }`
792    ///
793    /// - hook required at init if start NT in deps:
794    ///
795    ///     `init stack = [end ►program hook]`
796    ///
797    /// - hook required after each deps item that isn't in last opcode position:
798    ///     ```text
799    ///     1: decl_i -> decl decl_i         | ●decl_i hook ◄1 ►decl hook
800    ///                                                ^^^^
801    ///     ```
802    /// - hook required after each hooked terminal that isn't in last opcode position:
803    ///     ```text
804    ///     5: decl -> "typedef" Type Id ";" | ◄5 ";" Id! Type! hook "typedef"
805    ///                                                         ^^^^
806    ///     ```
807    fn add_opcode_hooks(&mut self) {
808        const VERBOSE: bool = false;
809        self.log.add_note("- adding hooks into opcodes...");
810        let hooks: HashSet<TokenId> = self.terminal_hooks.iter().cloned().collect();
811        let num_nt = self.parsing_table.num_nt;
812        let num_t = self.parsing_table.num_t;
813        let err = self.parsing_table.alts.len() as AltId;
814        if VERBOSE {
815            self.parsing_table.print(self.get_symbol_table(), 0);
816            println!("num_nt = {num_nt}\nnum_t = {num_t}\ntable: {}", self.parsing_table.table.len());
817        }
818        if VERBOSE { println!("hooks: {}", self.terminal_hooks.iter().map(|t| self.symbol_table.get_t_name(*t)).join(", ")); }
819        let deps: HashSet<VarId> = (0..num_nt as VarId)
820            .filter(|&nt| hooks.iter().any(|&t| self.parsing_table.table[nt as usize * num_t + t as usize] < err))
821            .collect();
822        if VERBOSE { println!("deps = {deps:?} = {}", deps.iter().map(|nt| self.symbol_table.get_nt_name(*nt)).join(", ")); }
823
824        // hook required when parser starts?
825        if deps.contains(&self.start) {
826            self.init_opcodes = vec![OpCode::End, OpCode::NT(self.start), OpCode::Hook];
827        }
828        let mut changed = false;
829        for opcodes in self.opcodes.iter_mut() {
830            let mut new = vec![];
831            let n = opcodes.len();
832            for op in &opcodes[..n - 1] {
833                new.push(*op);
834                match op {
835                    OpCode::T(t) if hooks.contains(t) => {
836                        new.push(OpCode::Hook);
837                    }
838                    OpCode::NT(nt) | OpCode::Loop(nt) if deps.contains(nt) => {
839                        new.push(OpCode::Hook);
840                    }
841                    _ => {}
842                }
843            }
844            if new.len() + 1 > n {
845                new.push(opcodes[n - 1]);
846                *opcodes = new;
847                changed = true;
848            }
849        }
850        if VERBOSE && changed {
851            println!("new opcodes:");
852            let mut cols = vec![];
853            let tbl = self.get_symbol_table();
854            for (i, (opcodes, (nt, alt))) in self.opcodes.iter().zip(&self.parsing_table.alts).enumerate() {
855                cols.push(vec![
856                    i.to_string(),
857                    format!("{} -> ", Symbol::NT(*nt).to_str(tbl)),
858                    alt.to_str(tbl),
859                    opcodes.iter().map(|op| op.to_str(tbl)).join(" "),
860                ]);
861            }
862            println!("{}", indent_source(vec![columns_to_str(cols, None)], 4))
863        }
864    }
865
866    fn make_span_nbrs(&mut self) {
867        self.log.add_note("- making spans...");
868        let mut span_nbrs = vec![0 as SpanNbr; self.parsing_table.alts.len()];
869        for (alt_id, (var_id, _)) in self.parsing_table.alts.iter().enumerate() {
870            let opcode = &self.opcodes[alt_id];
871            let mut span_nbr = span_nbrs[alt_id] + count_span_nbr(opcode);
872            if self.nt_has_any_flags(*var_id, ruleflag::CHILD_REPEAT | ruleflag::CHILD_L_RECURSION) ||
873                self.nt_has_all_flags(*var_id, ruleflag::R_RECURSION | ruleflag::L_FORM) {
874                // there is a loop span
875                span_nbr += 1;
876            }
877            if matches!(opcode.first(), Some(OpCode::NT(nt)) if nt != var_id && self.parsing_table.flags[*nt as usize] & ruleflag::CHILD_L_RECURSION != 0) {
878                // independent lrec term: the first NT doesn't count
879                span_nbr -= 1;
880            }
881            // println!("### {} -> span = {span_nbr}: {}",
882            //          opcode.iter().map(|o| o.to_string()).join(" "), opcode.iter().filter(|o| o.has_span()).map(|o| o.to_string()).join(" "));
883            // println!("[{alt_id}]: {} + {} -> {span_nbr}", span_nbrs[alt_id], count_span_nbr(&opcode));
884            if self.nt_has_all_flags(*var_id, ruleflag::PARENT_L_FACTOR) {
885                if let Some(OpCode::NT(nt)) = opcode.first() {
886                    span_nbr -= 1;
887                    for a_id in self.var_alts[*nt as usize].iter() {
888                        span_nbrs[*a_id as usize] += span_nbr;
889                        // println!("- [{a_id}] += {span_nbr} -> {}", span_nbrs[*a_id as usize]);
890                    }
891                    // println!(" -> [{alt_id}] = 0");
892                    span_nbr = 0;
893                }
894            }
895            span_nbrs[alt_id] = span_nbr;
896        }
897        self.span_nbrs = span_nbrs;
898    }
899
900    fn get_group_alts(&self, g: &[VarId]) -> Vec<(VarId, AltId)> {
901        g.iter().flat_map(|c|
902            self.var_alts[*c as usize].iter().map(|a| (*c, *a))
903        ).collect::<Vec<_>>()
904    }
905
906    /// Gathers all the alternatives of a nonterminal, and if some of them are parent_l_fact, searches the
907    /// terminal child_l_fact instead. The result is the set of contexts that are used to
908    /// call self.listener.exit_<NT>(ctx) for a right-rec, a left-rec parent, a left-rec child, ...
909    fn gather_alts(&self, nt: VarId) -> Vec<AltId> {
910        const VERBOSE: bool = false;
911        let mut alt = vec![];
912        let mut explore = VecDeque::<VarId>::new();
913        explore.push_back(nt);
914        while !explore.is_empty() {
915            let var = explore.pop_front().unwrap();
916            if VERBOSE { println!("{var}: alt = {} | explore = {} | alts: {}",
917                                  alt.iter().join(", "), explore.iter().join(", "),
918                                  &self.var_alts[var as usize].iter().join(", ")); }
919            for a in &self.var_alts[var as usize] {
920                let (_, alter) = &self.parsing_table.alts[*a as usize];
921                if let Some(Symbol::NT(last)) = alter.symbols().last() {
922                    if self.nt_has_all_flags(*last, ruleflag::CHILD_L_FACT) {
923                        // only one alternative calls NT(last), so we won't push it twice in explore:
924                        explore.push_back(*last);
925                        continue;
926                    }
927                }
928                alt.push(*a);
929            }
930            if VERBOSE { println!("  => alt = {} | explore = {}", alt.iter().join(", "), explore.iter().join(", ")); }
931        }
932        alt
933    }
934
935    fn calc_nt_value(&mut self) {
936        const VERBOSE: bool = false;
937        self.log.add_note("- calculating nonterminals' value...");
938        // we proceed by var parent, then all alternatives in each parent/children group
939        for g in self.nt_parent.iter().filter(|va| !va.is_empty()) {
940            // takes all the alternatives in the group (and their NT ID):
941            let group = self.get_group_alts(g);
942            let mut re_evaluate = true;
943            let g_top = g[0];
944            let is_ambig = self.nt_has_all_flags(g_top, ruleflag::PARENT_AMBIGUITY);
945            while re_evaluate {
946                re_evaluate = false;
947                let mut nt_used = HashSet::<VarId>::new();
948                if VERBOSE {
949                    let ids = group.iter().map(|(v, _)| *v).collect::<BTreeSet<VarId>>();
950                    println!("parent: {}, NT with value: {}",
951                             Symbol::NT(g[0]).to_str(self.get_symbol_table()),
952                             ids.into_iter().filter_map(|v|
953                                 if self.nt_value[v as usize] { Some(Symbol::NT(v as VarId).to_str(self.get_symbol_table())) } else { None }
954                             ).join(", "));
955                }
956                for (var_id, alt_id) in &group {
957                    // Default values are taken from opcodes.
958                    let mut has_value = false;
959                    for s in &self.opcodes[*alt_id as usize] {
960                        match s {
961                            OpCode::T(t) =>
962                                has_value |= self.symbol_table.is_token_data(*t),
963                            OpCode::NT(nt) => {
964                                let is_ambig_top = is_ambig && self.get_nt_parent(*nt) == Some(g_top)
965                                    && !self.nt_has_any_flags(*nt, ruleflag::CHILD_L_RECURSION | ruleflag::CHILD_REPEAT);
966                                let var = if is_ambig_top { g_top } else { *nt };
967                                nt_used.insert(var);
968                                has_value |= self.nt_value[var as usize]
969                            },
970                            _ => {}
971                        }
972                    }
973                    // Looks if a child_repeat has a value
974                    if has_value && self.parsing_table.parent[*var_id as usize].is_some() {
975                        // If it's a child of left factorization, we need to find the original nonterminal with the flags:
976                        let mut child_nt = *var_id as usize;
977                        while self.parsing_table.flags[child_nt] & ruleflag::CHILD_REPEAT == 0 {
978                            if let Some(parent) = self.parsing_table.parent[child_nt] {
979                                child_nt = parent as usize;
980                            } else {
981                                break;
982                            }
983                        }
984                        // +* non-lform children have the same value as their parent, but +* lform
985                        // children's value is independent of their parent's
986                        if self.parsing_table.flags[child_nt] & (ruleflag::CHILD_REPEAT | ruleflag::L_FORM) == ruleflag::CHILD_REPEAT {
987                            if VERBOSE && !self.nt_value[child_nt] {
988                                print!(" | {} is now valued {}",
989                                       Symbol::NT(child_nt as VarId).to_str(self.get_symbol_table()),
990                                       if nt_used.contains(&(child_nt as VarId)) { "and was used before" } else { "but wasn't used before" }
991                                );
992                            }
993                            re_evaluate |= !self.nt_value[child_nt] && nt_used.contains(&(child_nt as VarId));
994                            self.nt_value[child_nt] = true;
995                        }
996                    }
997                }
998            }
999        }
1000    }
1001
1002    pub(crate) fn make_item_ops(&mut self) {
1003        const VERBOSE: bool = false;
1004        self.calc_nt_value();
1005        self.log.add_note("- making item ops...");
1006        let info = &self.parsing_table;
1007        let mut items = vec![Vec::<Symbol>::new(); self.parsing_table.alts.len()];
1008        if VERBOSE {
1009            println!("Groups:");
1010            for g in self.nt_parent.iter().filter(|va| !va.is_empty()) {
1011                let group = self.get_group_alts(g);
1012                let ids = group.iter().map(|(v, _)| *v).collect::<BTreeSet<VarId>>();
1013                println!("{}: {}, alts {}",
1014                         Symbol::NT(g[0]).to_str(self.get_symbol_table()),
1015                    ids.iter().map(|v| Symbol::NT(*v).to_str(self.get_symbol_table())).join(", "),
1016                    group.iter().map(|(_, a)| a.to_string()).join(", ")
1017                );
1018            }
1019        }
1020        let mut alts_to_revisit = HashSet::<AltId>::new();
1021        // we proceed by var parent, then all alternatives in each parent/children group
1022        for g in self.nt_parent.iter().filter(|va| !va.is_empty()) {
1023            // takes all the alternatives in the group (and their NT ID):
1024            let group = self.get_group_alts(g);
1025            let g_top = g[0];
1026            let is_ambig = self.nt_has_all_flags(g_top, ruleflag::PARENT_AMBIGUITY);
1027            if VERBOSE {
1028                let ids = group.iter().map(|(v, _)| *v).collect::<BTreeSet<VarId>>();
1029                println!("parent: {}, NT with value: {}",
1030                         Symbol::NT(g[0]).to_str(self.get_symbol_table()),
1031                         ids.into_iter().filter_map(|v|
1032                             if self.nt_value[v as usize] { Some(Symbol::NT(v as VarId).to_str(self.get_symbol_table())) } else { None }
1033                         ).join(", "));
1034            }
1035            let g_top_has_value = self.nt_value[g_top as usize];
1036            for (var_id, alt_id) in &group {
1037                let ambig_loop_value = g_top_has_value && is_ambig && self.nt_has_all_flags(*var_id, ruleflag::CHILD_L_RECURSION);
1038                items[*alt_id as usize] = if ambig_loop_value { vec![Symbol::NT(g_top)] } else { vec![] };
1039            }
1040            for (var_id, alt_id) in &group {
1041                let opcode = &self.opcodes[*alt_id as usize];
1042                let (_, alt) = &info.alts[*alt_id as usize];
1043                if VERBOSE {
1044                    print!("- {alt_id}: {} -> {}   [{}]",
1045                           Symbol::NT(*var_id).to_str(self.get_symbol_table()),
1046                           alt.to_str(self.get_symbol_table()),
1047                           opcode.iter().map(|op| op.to_str(self.get_symbol_table())).join(" "));
1048                }
1049                let flags = info.flags[*var_id as usize];
1050
1051                // Default values are taken from opcodes. Loop(nt) is only taken if the parent is l-rec;
1052                // we look at the parent's flags instead of the alternative's because left factorization could
1053                // displace the Loop(nt) to another non-l-rec child alternative.
1054                let mut has_sep_list_child_without_value = false;
1055                let mut values = self.opcodes[*alt_id as usize].iter().rev()
1056                    .filter_map(|s| {
1057                        let sym_maybe = match s {
1058                            OpCode::T(t) => Some(Symbol::T(*t)),
1059                            OpCode::NT(nt) => {
1060                                let is_ambig_top = is_ambig && self.get_nt_parent(*nt) == Some(g_top)
1061                                    && !self.nt_has_any_flags(*nt, ruleflag::CHILD_L_RECURSION | ruleflag::CHILD_REPEAT);
1062                                let var = if is_ambig_top { g_top } else { *nt };
1063                                Some(Symbol::NT(var))
1064                            },
1065                            _ => {
1066                                if VERBOSE { print!(" | {} dropped", s.to_str(self.get_symbol_table())); }
1067                                None
1068                            }
1069                        };
1070                        sym_maybe.and_then(|s| {
1071                            const REP_MASK: u32 = ruleflag::CHILD_REPEAT | ruleflag::REPEAT_PLUS | ruleflag::L_FORM;
1072                            const CHILD_STAR: u32 = ruleflag::CHILD_REPEAT | ruleflag::L_FORM;
1073                            let has_value = self.sym_has_value(&s);
1074                            if has_value
1075                                // for now, leaves child* nonterminals used in another nonterminal (the parent),
1076                                // because they're necessary in check_sep_list() to locate the first sep_list item:
1077                                || matches!(s, Symbol::NT(v) if v != *var_id && self.parsing_table.flags[v as usize] & REP_MASK == CHILD_STAR)
1078                            {
1079                                if !has_value {
1080                                    has_sep_list_child_without_value = true;
1081                                }
1082                                Some(s)
1083                            } else {
1084                                None
1085                            }
1086                        })
1087                    }).to_vec();
1088                //
1089                if has_sep_list_child_without_value {
1090                    // there's a child* nonterminal in `values` that has no value and should be removed later
1091                    alts_to_revisit.insert(*alt_id);
1092                }
1093                // Loop NTs which carry values are kept on the stack, too
1094                let parent_is_rrec_lfact = !is_ambig && self.nt_has_all_flags(g[0], ruleflag::R_RECURSION | ruleflag::PARENT_L_FACTOR);
1095                if parent_is_rrec_lfact {
1096                    if flags & ruleflag::CHILD_L_FACT != 0 && self.nt_has_all_flags(g[0], ruleflag::L_FORM) {
1097                        assert!(!self.nt_has_all_flags(*var_id, ruleflag::CHILD_L_FACT | ruleflag::L_FORM), "this was useful after all");
1098                        if VERBOSE { print!(" child_rrec_lform_lfact"); }
1099                        items[*alt_id as usize].insert(0, Symbol::NT(g[0]));
1100                    }
1101                } else {
1102                    let sym_maybe = if flags & ruleflag::CHILD_REPEAT != 0 && (self.nt_value[*var_id as usize] || flags & ruleflag::L_FORM != 0) {
1103                        Some(Symbol::NT(*var_id))
1104                    } else if !is_ambig && flags & ruleflag::CHILD_L_RECURSION != 0 {
1105                        let parent = info.parent[*var_id as usize].unwrap();
1106                        Some(Symbol::NT(parent))
1107                    } else if !is_ambig && flags & (ruleflag::R_RECURSION | ruleflag::L_FORM) == ruleflag::R_RECURSION | ruleflag::L_FORM {
1108                        Some(Symbol::NT(*var_id))
1109                    } else {
1110                        None
1111                    };
1112                    if let Some(s) = sym_maybe {
1113                        if self.sym_has_value(&s) {
1114                            if VERBOSE { print!(" | loop => {}", s.to_str(self.get_symbol_table())); }
1115                            values.insert(0, s);
1116                        }
1117                    }
1118                }
1119                if VERBOSE {
1120                    println!(" ==> [{}] + [{}]",
1121                             items[*alt_id as usize].iter().map(|s| s.to_str(self.get_symbol_table())).join(" "),
1122                             values.iter().map(|s| s.to_str(self.get_symbol_table())).join(" "));
1123                }
1124                if let Some(OpCode::NT(nt)) = opcode.first() {
1125                    // Take the values except the last NT
1126                    let backup = if matches!(values.last(), Some(Symbol::NT(x)) if x == nt) {
1127                        Some(values.pop().unwrap())
1128                    } else {
1129                        None
1130                    };
1131                    if nt != var_id && self.nt_has_all_flags(*nt, ruleflag::CHILD_L_RECURSION) {
1132                        if VERBOSE { println!("  CHILD_L_RECURSION"); }
1133                        // exit_<var_id>(context = values) before entering child loop
1134                        items[*alt_id as usize].extend(values);
1135                        continue;
1136                    }
1137                    if flags & ruleflag::PARENT_L_FACTOR != 0 {
1138                        if VERBOSE {
1139                            println!("  PARENT_L_FACTOR: moving {} to child {}",
1140                                     values.iter().map(|s| s.to_str(self.get_symbol_table())).join(" "),
1141                                     Symbol::NT(*nt).to_str(self.get_symbol_table()));
1142                        }
1143                        // factorization reports all the values to the children
1144                        let pre = &mut items[*alt_id as usize];
1145                        if !pre.is_empty() {
1146                            // pre-pends values that already exist for alt_id (and empties alt_id)
1147                            values.splice(0..0, std::mem::take(pre));
1148                        }
1149                        for a_id in self.var_alts[*nt as usize].iter() {
1150                            items[*a_id as usize].extend(values.clone());
1151                            // Can an lfact parent contain a child*? No, because child* are transformed in the
1152                            // RTS, while lfact is a late-PRS transformation. If an lfact parent included a
1153                            // child*, like in `parent -> x* A | x* B`, the x* of each lfact alt would be
1154                            // different: something like `parent -> parent_1 A | parent_2 B`.
1155                            // There wouldn't be an lfact => we don't need to add a_id to alts_to_revisit
1156                        }
1157                        continue;
1158                    }
1159                    if let Some(sym) = backup {
1160                        values.push(sym);
1161                    }
1162                }
1163                items[*alt_id as usize].extend(values);
1164            } // WARNING: loop has `continue` jumps
1165        }
1166
1167        // adds sep_list flags to * with token-separated lists, and removes the corresponding
1168        // items that will be taken in an init method or added in first position in the array
1169        self.check_sep_list(&mut items);
1170
1171        // removes the child* nonterminals with no value that had been left earlier for check_sep_list()
1172        for alt_id in alts_to_revisit {
1173            items[alt_id as usize].retain(|s| self.sym_has_value(s));
1174        }
1175        self.item_ops = items;
1176
1177        self.log.add_note(
1178            format!(
1179                "NT with value: {}",
1180                self.nt_value.iter().index()
1181                    .filter(|&(_, val)| *val)
1182                    .map(|(var, _)| Symbol::NT(var).to_str(self.get_symbol_table()))
1183                    .join(", ")));
1184    }
1185
1186    /// Detects and transforms token-separated item lists of the form α (β α)*
1187    /// - α having valuable T/NT
1188    /// - β having no value (typ. fixed terminals)
1189    fn check_sep_list(&mut self, items: &mut [Vec<Symbol>]) {
1190        // a -> Id "(" Id ":" type ("," Id ":" type)* ")"
1191        //
1192        // alt | rule alternative                 | items
1193        // ----+----------------------------------+---------------
1194        //  0  |  a -> Id "(" Id ":" type a_1 ")" | Id Id type a_1
1195        //  1  |  type -> Id                      | Id
1196        //  2  |  a_1 -> "," Id ":" type a_1      | a_1 Id type
1197        //  3  |  a_1 -> ε                        | a_1
1198        //
1199        // - c_alt = 2 is child_*, pattern in `items` = [Id type] (a_1 is skipped),
1200        //   - pattern_len = 2
1201        //   - find NT in group that's not a_1 and that has a_1 in one of its alt
1202        //     => p_var = a, p_alt_id = 0
1203        //   - find position of a_1 in p_alt; check if there's something on the left (reject if not)
1204        //     and takes the position of the left symbol:
1205
1206        //          0   1  2   3    4          0  1   2  3   4    5
1207        //       2: "," Id ":" type a_1     0: Id "(" Id ":" type a_1 ")"
1208        //                     ^^^^ c_pos (init) = 3         ^^^^ p_pos0 = p_pos (init) = 4
1209        //
1210        //   - counts how many symbols match on the left, and
1211        //     for each symbol that has a value, pops one from pattern,
1212        //     until pattern is empty of c_pos/p_pos is 0
1213        //
1214        //          0   1  2   3    4          0  1   2  3   4    5
1215        //       2: "," Id ":" type a_1     0: Id "(" Id ":" type a_1 ")"
1216        //          !=  <----------               !=  <---------- span_nbr = 3 (Id ":" type)
1217        //
1218        //   - if pattern is empty, we have a potential match, but we must still verify if
1219        //     all the parents alternatives that use a_1 also include the pattern. For example,
1220        //     `a -> Id? ("," Id)*` would be transformed as `a -> Id ("," Id)* | ("," Id)*`, so
1221        //     we can't apply sep_list because the child* shouldn't always expect a first Id
1222        //     on the stack.
1223        //     - find all the positions of a_1 in self.gather(a)
1224        //     - check that, for each of the a_1 found, the pattern precedes it: Id [Id type] a_1 => OK
1225        //     - for each p_alt and postion (here, p_alt = 0 and pos = 3),
1226        //       - remove [pos - pattern_len..pos] from items[p_alt] -> [3 - 2..3] = [1..3] => [Id a_1] is left
1227        const VERBOSE: bool = false;
1228        if VERBOSE {
1229            let log = std::mem::take(&mut self.log);
1230            self.item_ops = items.iter().cloned().to_vec();
1231            self.log_nt_info();
1232            self.log_alt_info();
1233            println!("{}", self.log);
1234            self.item_ops.clear();
1235            self.log = log;
1236        }
1237        self.log.add_note("- determining sep_list nonterminals...");
1238        if VERBOSE { println!("check_sep_list:"); }
1239        // takes one group at a time
1240        for (top_nt, g) in self.nt_parent.iter().enumerate().filter(|va| !va.1.is_empty()) {
1241            // takes the potential child_*
1242            let candidate_children = g.iter()
1243                .filter_map(|&var| {
1244                    let alts = &self.var_alts[var as usize];
1245                    let flags = self.parsing_table.flags[var as usize];
1246                    // takes only len() == 2 to reject complex cases like a -> A B C (B C | D)*
1247                    if alts.len() == 2 && flags & (ruleflag::CHILD_REPEAT | ruleflag::REPEAT_PLUS) == ruleflag::CHILD_REPEAT {
1248                        Some((var, alts[0] as usize, flags))
1249                    } else {
1250                        None
1251                    }
1252                })
1253                .to_vec();  // to avoid borrow checker issue with &mut self later
1254            for &(c_var, c_alt_id, _c_flags) in &candidate_children {
1255                let has_value = self.nt_value[c_var as usize];
1256                let skip_loop_nt = if has_value { 1 } else { 0 }; // the loop NT that's put in front when it has a value
1257                let mut pattern = items[c_alt_id].iter().skip(skip_loop_nt).cloned().to_vec();
1258                if VERBOSE {
1259                    println!(
1260                        "? {} {c_alt_id}: pattern = {}",
1261                        Symbol::NT(c_var).to_str(self.get_symbol_table()),
1262                        pattern.iter().map(|s| s.to_str(self.get_symbol_table())).join(" ")); }
1263                if !pattern.is_empty() {
1264                    let pattern_len = pattern.len();
1265                    let pattern_copy = pattern.clone();
1266                    let c_sym = Symbol::NT(c_var);
1267                    // finds the parent's alt that includes this child_+*
1268                    let (p_var, _p_alt_id, p_alt, mut p_pos) = self.nt_parent[top_nt].iter()
1269                        .flat_map(|&p_var| &self.var_alts[p_var as usize])
1270                        .filter_map(|&p_alt_id| {
1271                            let (p_var, p_alt) = &self.parsing_table.alts[p_alt_id as usize];
1272                            if *p_var != c_var {
1273                                p_alt.v.iter().position(|s| s == &c_sym).map(|p_pos| (*p_var, p_alt_id as usize, p_alt, p_pos))
1274                            } else {
1275                                None
1276                            }
1277                        })
1278                        .next()
1279                        .unwrap_or_else(|| panic!("NT {c_var} alt {c_alt_id} should have a parent's alt that includes it"));
1280                    if p_pos > 0 {
1281                        // verifies if enough symbols match
1282                        p_pos -= 1; // easier to skip the child nonterminal, since it may or may not have a value
1283                        let c_alt = &self.parsing_table.alts[c_alt_id].1.v;
1284                        let mut c_pos = c_alt.len() - 2; // safe: there's at least another symbol before `c_sym` (per design)
1285                        let p_pos0 = p_pos;
1286                        let mut span_nbr = 0;
1287                        while !pattern.is_empty() {
1288                            if p_alt[p_pos] == c_alt[c_pos] {
1289                                span_nbr += 1;
1290                                if self.sym_has_value(&c_alt[c_pos]) {
1291                                    pattern.pop();
1292                                }
1293                                if c_pos == 0 || p_pos == 0 {
1294                                    break;
1295                                }
1296                                c_pos -= 1;
1297                                p_pos -= 1;
1298                            } else {
1299                                break;
1300                            }
1301                        }
1302                        if pattern.is_empty() {
1303                            let exit_alts = self.gather_alts(p_var);
1304                            // check that all the items that include c_var have the whole pattern to avoid cases like
1305                            // a -> V? ("," V) => a -> V ("," V) | ("," V) => a -> V a_1 | a_1
1306                            // where one branch doesn't have the initial V
1307                            // let mut whole_pattern = items[c_alt_id].iter().skip(skip_loop_nt).cloned().to_vec();
1308                            // whole_pattern.push(c_sym);
1309                            let mut found_pos = vec![];
1310                            let all_match = exit_alts.into_iter().all(|a| {
1311                                let a_items = &items[a as usize];
1312                                if let Some(p) = a_items.iter().position(|s| *s == c_sym) {
1313                                    // c_var is in items, but does it have the pattern too?
1314                                    if p >= pattern_len && a_items[p - pattern_len..p] == pattern_copy {
1315                                        found_pos.push((a as usize, p));
1316                                        true
1317                                    } else {
1318                                        // c_var is there, but the pattern isn't, we can't do the modification for this child*
1319                                        false
1320                                    }
1321                                } else {
1322                                    true
1323                                }
1324                            });
1325                            if all_match {
1326                                if VERBOSE {
1327                                    println!("- match:");
1328                                    println!("  c[{c_alt_id}]: {}    items: {}",
1329                                             c_alt.iter().map(|s| s.to_str_quote(self.get_symbol_table())).join(" "),
1330                                             items[c_alt_id].iter().map(|s| s.to_str_quote(self.get_symbol_table())).join(" "));
1331                                }
1332                                for (p_alt_id, pos) in found_pos {
1333                                    if VERBOSE {
1334                                        println!("  p[{p_alt_id}]: {}    items: {}",
1335                                                 p_alt.iter().map(|s| s.to_str_quote(self.get_symbol_table())).join(" "),
1336                                                 items[p_alt_id].iter().map(|s| s.to_str_quote(self.get_symbol_table())).join(" "));
1337                                        println!(
1338                                            "    c_alt_id = {c_alt_id}, p_alt_id = {p_alt_id}, p_pos0 = {p_pos0}, span_nbr = {span_nbr}, pos = {pos} => remove  [{}..{}]",
1339                                            pos - pattern_len, pos);
1340                                    }
1341                                    self.span_nbrs[p_alt_id] -= span_nbr as SpanNbr;
1342                                    self.span_nbrs_sep_list.insert(c_alt_id as AltId, span_nbr as SpanNbr);
1343                                    items[p_alt_id].drain(pos - pattern_len..pos);
1344                                    if VERBOSE {
1345                                        println!("    => p items: {}", items[p_alt_id].iter().map(|s| s.to_str_quote(self.get_symbol_table())).join(" "));
1346                                    }
1347                                    self.parsing_table.flags[c_var as usize] |= ruleflag::SEP_LIST;
1348                                }
1349                            }
1350                        }
1351                    }
1352                }
1353            }
1354        }
1355    }
1356
1357    fn sort_alt_ids(&self, top_nt: VarId, alts: &[AltId]) -> Vec<AltId> {
1358        const VERBOSE: bool = false;
1359        if VERBOSE {
1360            println!("  sorting {} alts {alts:?}", Symbol::NT(top_nt).to_str(self.get_symbol_table()));
1361            for &a_id in alts {
1362                let &(_nt, ref alt) = &self.parsing_table.alts[a_id as usize];
1363                if let Some((v, id)) = alt.origin {
1364                    let tree = &self.origin.trees[v as usize];
1365                    println!("    [{a_id}] id = {},{id} -> {}  <->  {}",
1366                             Symbol::NT(v).to_str(self.get_symbol_table()),
1367                             crate::grammar::grtree_to_str_ansi(tree, None, Some(id), Some(v), self.get_symbol_table(), false),
1368                             tree.to_str_index(None, self.get_symbol_table())
1369                    );
1370                    assert_eq!(v, top_nt, "v = {}, top_nt = {}", Symbol::NT(v).to_str(self.get_symbol_table()), Symbol::NT(top_nt).to_str(self.get_symbol_table()));
1371                }
1372            }
1373        }
1374        let mut sorted = vec![];
1375        let mut ids = alts.iter().filter_map(|&alt_id| self.parsing_table.alts[alt_id as usize].1.origin.map(|(_var, id)| (id, alt_id)))
1376            .collect::<HashMap<_, _>>();
1377        let tree = &self.origin.trees[top_nt as usize];
1378        for node in tree.iter_post_depth() {
1379            if let Some((_, alt_id)) = ids.remove_entry(&node.index) {
1380                sorted.push(alt_id);
1381            }
1382        }
1383        if VERBOSE { println!("    -> {sorted:?}"); }
1384        sorted
1385    }
1386
1387    /// Calculates nt_name, nt_info, item_info
1388    ///
1389    /// * `nt_name[var]: (String, String, String)` contains (upper, lower, lower)-case unique identifiers for each parent NT (the first two
1390    ///   are changed if they're Rust identifiers)
1391    /// * `alt_info[alt]: Vec<Option<(VarId, String)>>` contains the enum variant names for each context (must be regrouped by VarId)
1392    /// * `item_info[alt]: Vec<ItemInfo>` contains the data available on the stacks when exiting the alternative
1393    /// * `child_repeat_endpoints[var]: HashMap<VarId, Vec<AltId>>` list of alts (several when the repeat child has several outcomes,
1394    ///   as in `a -> (A | B)+`), where each alt corresponds to the item_ops with the values on the stack.
1395    ///
1396    /// For example:
1397    ///
1398    /// ```text
1399    /// // a -> (b C | A D | A E E)* D | A; b -> B;
1400    /// //
1401    /// //  0: a -> a_1 D     | ◄0 D! ►a_1    | a_1 D
1402    /// //  1: a -> A         | ◄1 A!         | A
1403    /// //  2: b -> B         | ◄2 B!         | B
1404    /// //  3: a_1 -> A a_2   | ►a_2 A!       |
1405    /// //  4: a_1 -> b C a_1 | ●a_1 ◄4 C! ►b | a_1 b C
1406    /// //  5: a_1 -> ε       | ◄5            | a_1
1407    /// //  6: a_2 -> D a_1   | ●a_1 ◄6 D!    | a_1 A D
1408    /// //  7: a_2 -> E E a_1 | ●a_1 ◄7 E! E! | a_1 A E E
1409    ///
1410    /// pub enum CtxA {
1411    ///     A1 { star: SynA1, d: String },  // `a -> (b C | A D | A E E)* D`
1412    ///     A2 { a: String },               // `a -> A`
1413    /// }
1414    /// pub enum CtxB {
1415    ///     B { b: String },                // `b -> B`
1416    /// }
1417    /// pub struct SynA1(pub Vec<SynA1Item>);
1418    /// pub enum SynA1Item {
1419    ///     Ch1 { b: SynB, c: String },         // `b C` item in `a -> ( ►► b C ◄◄  | A D | A E E)* D | A`
1420    ///     Ch2 { a: String, d: String },       // `A D` item in `a -> (b C |  ►► A D ◄◄  | A E E)* D | A`
1421    ///     Ch3 { a: String, e: [String; 2] },  // `A E E` item in `a -> (b C | A D |  ►► A E E ◄◄ )* D | A`
1422    /// }
1423    /// // User-defined: SynA, SynB
1424    ///
1425    /// nt_name: [("A", "a", "a"), ("B", "b", "b"), ("A1", "a1", "a1"), ("A2", "a2", "a2")]
1426    /// alt_info: [Some((0, "A1")), Some((0, "A2")), Some((1, "B")), None, None, None, None, None]
1427    /// item_info:
1428    /// 0:  [ItemInfo { name: "star", sym: NT(2), owner: 0, index: None },
1429    ///      ItemInfo { name: "d", sym: T(2), owner: 0, index: None }],
1430    /// 1:  [ItemInfo { name: "a", sym: T(1), owner: 0, index: None }],
1431    /// 2:  [ItemInfo { name: "b", sym: T(4), owner: 1, index: None }],
1432    /// 3:  [],
1433    /// 4:  [ItemInfo { name: "b", sym: NT(1), owner: 2, index: None },
1434    ///      ItemInfo { name: "c", sym: T(0), owner: 2, index: None }],
1435    /// 5:  [],
1436    /// 6:  [ItemInfo { name: "a", sym: T(1), owner: 2, index: None },
1437    ///      ItemInfo { name: "d", sym: T(2), owner: 2, index: None }],
1438    /// 7:  [ItemInfo { name: "a", sym: T(1), owner: 2, index: None },
1439    ///      ItemInfo { name: "e", sym: T(3), owner: 2, index: Some(0) },
1440    ///      ItemInfo { name: "e", sym: T(3), owner: 2, index: Some(1) }]
1441    /// child_repeat_endpoints: {2: [4, 6, 7]}
1442    /// ```
1443    fn get_type_info(&mut self) {
1444        const VERBOSE: bool = false;
1445
1446        self.log.add_note("- determining item_info...");
1447        let pinfo = &self.parsing_table;
1448        let mut nt_upper_fixer = NameFixer::new();
1449        let mut nt_lower_fixer = NameFixer::new();
1450        let mut nt_plower_fixer = NameFixer::new_empty(); // prefixed lowercase: don't worry about reserved words
1451        let nt_name: Vec<(String, String, String)> = (0..pinfo.num_nt).map(|v| {
1452            let name = self.symbol_table.get_nt_name(v as VarId);
1453            let nu = nt_upper_fixer.get_unique_name(name.to_camelcase());
1454            let nl = nt_lower_fixer.get_unique_name(nu.to_underscore_lowercase());
1455            let npl = nt_plower_fixer.get_unique_name(nu.to_underscore_lowercase());
1456            (nu, nl, npl)
1457        }).to_vec();
1458
1459        let mut alt_info: Vec<Option<(VarId, String)>> = vec![None; pinfo.alts.len()];
1460        let mut nt_repeat = HashMap::<VarId, Vec<ItemInfo>>::new();
1461        let mut item_info: Vec<Vec<ItemInfo>> = vec![vec![]; pinfo.alts.len()];
1462        let mut child_repeat_endpoints = HashMap::<VarId, Vec<AltId>>::new();
1463        for group in self.nt_parent.iter().filter(|vf| !vf.is_empty()) {
1464            let is_ambig = self.nt_has_any_flags(group[0], ruleflag::PARENT_AMBIGUITY);
1465            let mut is_ambig_1st_child = is_ambig;
1466            let mut alt_info_to_sort = HashMap::<VarId, Vec<AltId>>::new();
1467            for var in group {
1468                let nt = *var as usize;
1469                let nt_flags = pinfo.flags[nt];
1470                if is_ambig && (nt_flags & ruleflag::PARENT_L_RECURSION != 0 || (nt_flags & ruleflag::CHILD_L_RECURSION != 0 && !is_ambig_1st_child)) {
1471                    continue;
1472                }
1473                if nt_flags & (ruleflag::CHILD_REPEAT | ruleflag::L_FORM) == ruleflag::CHILD_REPEAT {
1474                    // collects the alt endpoints that correspond to each choice (one or several choices if | is used inside the repeat),
1475                    // each alt endpoint corresponding to the data in item_info
1476                    let is_plus = nt_flags & ruleflag::REPEAT_PLUS != 0;
1477                    let mut endpoints = self.gather_alts(*var);
1478                    if VERBOSE { println!("** {} endpoints: {endpoints:?} ", Symbol::NT(*var).to_str(self.get_symbol_table())); }
1479                    if is_plus {
1480                        // with +, alt endpoints come in couples: the first loops, the other exits, both having the same data
1481                        // (in each (id1, id2) couple, id2 == id1 + 1)
1482                        endpoints = endpoints.chunks(2).map(|slice| slice[0]).to_vec();
1483                    } else {
1484                        // with *, the endpoint corresponding to the exit has no data
1485                        endpoints.retain(|e| !pinfo.alts[*e as usize].1.is_sym_empty());
1486                    }
1487                    assert!(!endpoints.is_empty());
1488                    let endpoints = self.sort_alt_ids(group[0], &endpoints);
1489                    child_repeat_endpoints.insert(*var, endpoints);
1490                }
1491                for &alt_id in &self.var_alts[nt] {
1492                    let i = alt_id as usize;
1493                    if is_ambig_1st_child && pinfo.alts[i].1.is_sym_empty() {
1494                        continue;
1495                    }
1496                    let item_ops = &self.item_ops[alt_id as usize];
1497                    // Adds a suffix to the names of different symbols that would otherwise collide in the same context option:
1498                    // - identical symbols are put in a vector (e.g. `id: [String; 2]`)
1499                    // - different symbols, which means T vs NT, must have different names (e.g. `NT(A)` becomes "a",
1500                    //   `T(a)` becomes "a", too => one is renamed to "a1" to avoid the collision: `{ a: SynA, a1: String }`)
1501                    let mut indices = HashMap::<Symbol, (String, Option<usize>)>::new();
1502                    let mut fixer = NameFixer::new();
1503                    let mut owner = pinfo.alts[i].0;
1504                    while let Some(parent) = pinfo.parent[owner as usize] {
1505                        if pinfo.flags[owner as usize] & ruleflag::CHILD_REPEAT != 0 {
1506                            // a child + * is owner
1507                            // - if <L>, it has its own public context and a user-defined return type
1508                            // - if not <L>, it has no context and a generator-defined return type (like Vec<String>)
1509                            // (we keep the loop for +, which has a left factorization, too)
1510                            break;
1511                        }
1512                        owner = parent;
1513                    }
1514                    let is_nt_child_repeat = pinfo.flags[owner as usize] & ruleflag::CHILD_REPEAT != 0;
1515                    for s in item_ops {
1516                        if let Some((_, c)) = indices.get_mut(s) {
1517                            *c = Some(0);
1518                        } else {
1519                            let name = if let Symbol::NT(vs) = s {
1520                                let flag = pinfo.flags[*vs as usize];
1521                                if flag & ruleflag::CHILD_REPEAT != 0 {
1522                                    let inside_alt_id = self.var_alts[*vs as usize][0];
1523                                    let inside_alt = &pinfo.alts[inside_alt_id as usize].1;
1524                                    if false {
1525                                        // we don't use this any more
1526                                        let mut plus_name = inside_alt.symbols()[0].to_str(self.get_symbol_table()).to_underscore_lowercase();
1527                                        plus_name.push_str(if flag & ruleflag::REPEAT_PLUS != 0 { "_plus" } else { "_star" });
1528                                        plus_name
1529                                    } else if is_nt_child_repeat && indices.is_empty() {
1530                                        // iterator variable in a + * loop (visible with <L>, for ex)
1531                                        if flag & ruleflag::REPEAT_PLUS != 0 { "plus_acc".to_string() } else { "star_acc".to_string() }
1532                                    } else {
1533                                        // reference to a + * result
1534                                        if flag & ruleflag::REPEAT_PLUS != 0 { "plus".to_string() } else { "star".to_string() }
1535                                    }
1536                                } else {
1537                                    nt_name[*vs as usize].clone().1
1538                                }
1539                            } else {
1540                                s.to_str(self.get_symbol_table()).to_lowercase()
1541                            };
1542                            indices.insert(*s, (fixer.get_unique_name(name), None));
1543                        }
1544                    }
1545
1546                    // A parent of left factorization has no context, but we must check the alternatives that are the actual parents.
1547                    // The flag test is optional, but it serves to gate the more complex parental test.
1548                    let has_lfact_child = nt_flags & ruleflag::PARENT_L_FACTOR != 0 &&
1549                        pinfo.alts[i].1.symbols().iter().any(|s| matches!(s, &Symbol::NT(c) if pinfo.flags[c as usize] & ruleflag::CHILD_L_FACT != 0));
1550
1551                    // (α)* doesn't call the listener for each α, unless it's l-form. We say it's a hidden child_repeat, and it doesn't need a context.
1552                    // The only children a child_repeat can have is due to left factorization in (α)+, so we check `owner` rather than `nt`.
1553                    let is_hidden_repeat_child = pinfo.flags[owner as usize] & (ruleflag::CHILD_REPEAT | ruleflag::L_FORM) == ruleflag::CHILD_REPEAT;
1554
1555                    // <alt> -> ε
1556                    let is_alt_sym_empty = self.is_alt_sym_empty(alt_id);
1557
1558                    // (α <L>)+ have two similar alternatives with the same data on the stack, one that loops and the last iteration. We only
1559                    // keep one context because we use a flag to tell the listener when it's the last iteration (more convenient).
1560                    let is_duplicate = i > 0 && self.nt_has_all_flags(owner, ruleflag::CHILD_REPEAT | ruleflag::REPEAT_PLUS | ruleflag::L_FORM) &&
1561                        is_alt_sym_empty;
1562
1563                    let is_last_empty_iteration = (nt_flags & ruleflag::CHILD_L_RECURSION != 0
1564                        || self.nt_has_all_flags(*var, ruleflag::CHILD_REPEAT | ruleflag::L_FORM)) && is_alt_sym_empty;
1565
1566                    let has_context = !has_lfact_child && !is_hidden_repeat_child && !is_duplicate && !is_last_empty_iteration;
1567                    if VERBOSE {
1568                        println!("NT {nt}, alt {alt_id}: has_lfact_child = {has_lfact_child}, is_hidden_repeat_child = {is_hidden_repeat_child}, \
1569                            is_duplicate = {is_duplicate}, is_last_empty_iteration = {is_last_empty_iteration} => has_context = {has_context}");
1570                    }
1571                    if has_context {
1572                        alt_info_to_sort.entry(owner)
1573                            .and_modify(|v| v.push(alt_id))
1574                            .or_insert_with(|| vec![alt_id]);
1575                    }
1576                    let has_owner_value = self.nt_value[owner as usize];
1577                    item_info[i] = if item_ops.is_empty() && nt_flags & ruleflag::CHILD_L_RECURSION != 0 {
1578                        // we put here the return context for the final exit of left recursive rule
1579                        if has_owner_value {
1580                            vec![ItemInfo {
1581                                name: nt_name[owner as usize].1.clone(),
1582                                sym: Symbol::NT(owner),
1583                                owner,
1584                                index: None,
1585                            }]
1586                        } else {
1587                            vec![]
1588                        }
1589                    } else {
1590                        let is_rrec_lform = self.nt_has_all_flags(owner, ruleflag::R_RECURSION | ruleflag::L_FORM);
1591                        let skip = if (is_nt_child_repeat || is_rrec_lform) && has_owner_value { 1 } else { 0 };
1592                        let mut infos = item_ops.iter()
1593                            .skip(skip)
1594                            .map(|s| {
1595                                let index = if let Some((_, Some(index))) = indices.get_mut(s) {
1596                                    let idx = *index;
1597                                    *index += 1;
1598                                    Some(idx)
1599                                } else {
1600                                    None
1601                                };
1602                                ItemInfo {
1603                                    name: indices[s].0.clone(),
1604                                    sym: *s,
1605                                    owner,
1606                                    index,
1607                                }
1608                            }).to_vec();
1609                        if self.nt_has_all_flags(owner, ruleflag::CHILD_REPEAT | ruleflag::REPEAT_PLUS | ruleflag::L_FORM) {
1610                            // we add the flag telling the listener whether it's the last iteration or not
1611                            let last_name = fixer.get_unique_name("last_iteration".to_string());
1612                            infos.push(ItemInfo {
1613                                name: last_name,
1614                                sym: Symbol::Empty, // this marks the special flag variable
1615                                owner,
1616                                index: None,
1617                            });
1618                        };
1619                        if is_nt_child_repeat && !infos.is_empty() && !nt_repeat.contains_key(&owner) {
1620                            nt_repeat.insert(owner, infos.clone());
1621                        }
1622                        infos
1623                    }
1624                } // alt_id in var
1625                if is_ambig && nt_flags & ruleflag::CHILD_L_RECURSION != 0 {
1626                    is_ambig_1st_child = false;
1627                }
1628            } // var in group
1629            if VERBOSE { println!("alt_info_to_sort = {alt_info_to_sort:?}"); }
1630            for (owner, alts) in alt_info_to_sort {
1631                for (num, alt) in self.sort_alt_ids(group[0], &alts).into_iter().index_start(1) {
1632                    alt_info[alt as usize] = Some((owner, format!("V{num}")));
1633                }
1634            }
1635        } // group
1636
1637        if VERBOSE {
1638            println!("NT names: {}", nt_name.iter()
1639                .map(|(u, l, pl)| format!("{u}/{l}/{pl}"))
1640                .join(", "));
1641            println!("alt info:");
1642            for (alt_id, alt_names) in alt_info.iter().enumerate() {
1643                if let Some((v, name)) = alt_names {
1644                    println!("- alt {alt_id}, NT {v} {}, Ctx name: {name}", Symbol::NT(*v).to_str(self.get_symbol_table()));
1645                }
1646            }
1647            println!();
1648            println!("nt_name: {nt_name:?}");
1649            println!("alt_info: {alt_info:?}");
1650            println!("item_info:");
1651            for (i, item) in item_info.iter().enumerate().filter(|(_, item)| !item.is_empty()) {
1652                println!("- {i}: {{ {} }}", item.iter()
1653                    .map(|ii| format!("{}{} ({})", ii.name, ii.index.map(|i| format!("[{i}]")).unwrap_or(String::new()), ii.sym.to_str(self.get_symbol_table())))
1654                    .join(", "));
1655            }
1656            println!("item_info: {item_info:?}");
1657            println!("child_repeat_endpoints: {child_repeat_endpoints:?}");
1658        }
1659        self.nt_name = nt_name;
1660        self.alt_info = alt_info;
1661        self.item_info = item_info;
1662        self.child_repeat_endpoints = child_repeat_endpoints;
1663    }
1664
1665    /// Generates the source code of the wrapper and the accompanying templates. Returns
1666    /// * the indented source of the wrapper
1667    /// * the indented source of the template for the user types
1668    /// * the indented source of the template for the listener implementation
1669    pub fn gen_source_code(&mut self) -> (String, String, String) {
1670        self.log.add_note("generating source code...");
1671        if !self.log.has_no_errors() {
1672            return (String::new(), String::new(), String::new());
1673        }
1674        // Building the source code as we do below is not the most efficient, but it's done that way to
1675        // - be able to build only a part of the parser, and
1676        // - get the sources for the validation tests or print them / write them into a file.
1677        // The whole code isn't that big, so it's not a major issue.
1678        let mut parts = vec![];
1679        if !self.headers.is_empty() {
1680            parts.push(self.headers.clone());
1681        }
1682        let mut tmp_parts = if self.gen_parser {
1683            vec![self.source_build_parser()]
1684        } else {
1685            vec![]
1686        };
1687        let (src_types, src_listener) = if self.gen_wrapper {
1688            self.make_item_ops();
1689            let (src_wrapper, src_types, src_listener) = self.source_wrapper();
1690            tmp_parts.push(src_wrapper);
1691            (
1692                indent_source(vec![src_types], self.types_indent),
1693                indent_source(vec![src_listener], self.listener_indent)
1694            )
1695        } else {
1696            (String::new(), String::new())
1697        };
1698        self.log_nt_info();
1699        self.log_alt_info();
1700        parts.push(self.source_use());
1701        parts.extend(tmp_parts);
1702        // Create source code:
1703        (indent_source(parts, self.indent), src_types, src_listener)
1704    }
1705
1706    pub fn try_gen_source_code(mut self) -> Result<(BufLog, String, String, String), BuildError> {
1707        let (src, src_types, src_listener) = self.gen_source_code();
1708        if self.log.has_no_errors() {
1709            Ok((self.give_log(), src, src_types, src_listener))
1710        } else {
1711            Err(BuildError::new(self.give_log(), BuildErrorSource::ParserGen))
1712        }
1713    }
1714
1715    fn source_use(&self) -> Vec<String> {
1716        self.used_libs.gen_source_code()
1717    }
1718
1719    fn source_build_parser(&mut self) -> Vec<String> {
1720        static BASE_PARSER_LIBS: [&str; 5] = [
1721            "::VarId",
1722            "::AltId",
1723            "::parser::OpCode",
1724            "::parser::Parser",
1725            "::fixed_sym_table::FixedSymTable",
1726        ];
1727        static ALT_PARSER_LIBS: [&str; 2] = [
1728            "::alt::Alternative",
1729            "::parser::Symbol",
1730        ];
1731
1732        self.log.add_note("generating build_parser source...");
1733        let num_nt = self.symbol_table.get_num_nt();
1734        let num_t = self.symbol_table.get_num_t();
1735        self.used_libs.extend(BASE_PARSER_LIBS.into_iter().map(|s| format!("{}{s}", self.lib_crate)));
1736        self.log.add_note(format!("- creating symbol tables: {num_t} terminals, {num_nt} nonterminals"));
1737        let mut src = vec![
1738            format!("const PARSER_NUM_T: usize = {num_t};"),
1739            format!("const PARSER_NUM_NT: usize = {num_nt};"),
1740            format!("static SYMBOLS_T: [(&str, Option<&str>); PARSER_NUM_T] = [{}];",
1741                     self.symbol_table.get_terminals().map(|(s, os)|
1742                         format!("(\"{s}\", {})", os.as_ref().map(|s| format!("Some({s:?})")).unwrap_or("None".to_string()))).join(", ")),
1743            format!("static SYMBOLS_NT: [&str; PARSER_NUM_NT] = [{}];",
1744                     self.symbol_table.get_nonterminals().map(|s| format!("{s:?}")).join(", ")),
1745            format!("static ALT_VAR: [VarId; {}] = [{}];",
1746                    self.parsing_table.alts.len(),
1747                    self.parsing_table.alts.iter().map(|(v, _)| format!("{v}")).join(", ")),
1748        ];
1749        if self.include_alts {
1750            self.used_libs.extend(ALT_PARSER_LIBS.into_iter().map(|s| format!("{}{s}", self.lib_crate)));
1751            src.push(format!("static ALTERNATIVES: [&[Symbol]; {}] = [{}];",
1752                             self.parsing_table.alts.len(),
1753                             self.parsing_table.alts.iter().map(|(_, f)| format!("&[{}]", f.iter().map(symbol_to_code).join(", "))).join(", ")));
1754        }
1755        self.log.add_note(format!("- creating parsing tables: {} items, {} opcodes", self.parsing_table.table.len(), self.opcodes.len()));
1756        src.extend(vec![
1757            format!(
1758                "static PARSING_TABLE: [AltId; {}] = [{}];",
1759                self.parsing_table.table.len(),
1760                self.parsing_table.table.iter().map(|v| format!("{v}")).join(", ")),
1761            format!(
1762                "static OPCODES: [&[OpCode]; {}] = [{}];",
1763                self.opcodes.len(),
1764                self.opcodes.iter().map(|strip| format!("&[{}]", strip.iter().map(|op| format!("OpCode::{op:?}")).join(", "))).join(", ")),
1765            format!(
1766                "static INIT_OPCODES: [OpCode; {}] = [{}];",
1767                self.init_opcodes.len(),
1768                self.init_opcodes.iter().map(|op| format!("OpCode::{op:?}")).join(", ")),
1769            format!("static START_SYMBOL: VarId = {};\n", self.start),
1770        ]);
1771        if self.gen_token_enums {
1772            src.add_space();
1773            src.push("#[derive(Clone, Copy, PartialEq, Debug)]".to_string());
1774            src.push("#[repr(u16)]".to_string());
1775            src.push("pub enum Term {".to_string());
1776            let cols = self.symbol_table.get_terminals().enumerate()
1777                .map(|(t, (s, s_opt))| vec![
1778                    // format!("    #[doc=\"{:?}\"]", if let Some(so) = s_opt { format!("{so:?}") } else { String::new() }),
1779                    // if let Some(so) = s_opt { format!("    #[doc = \"'{so}'\"]") } else { String::new() },
1780                    format!("    #[doc = \"{}\"]", if let Some(so) = s_opt { format!("'{so}'") } else { "(variable)".to_string() }),
1781                    format!("{s} = {t},", )])
1782                .to_vec();
1783            src.extend(columns_to_str(cols, Some(vec![16, 0])));
1784            src.push("}\n".to_string());
1785            src.push("#[derive(Clone, Copy, PartialEq, Debug)]".to_string());
1786            src.push("#[repr(u16)]".to_string());
1787            src.push("pub enum NTerm {".to_string());
1788            let cols = self.symbol_table.get_nonterminals().index()
1789                .map(|(t, s)| vec![
1790                    format!(
1791                        "    #[doc = \"`{s}`{}\"]",
1792                        if let Some(p) = self.get_nt_parent(t) {
1793                            format!(", parent: `{}`", Symbol::NT(p).to_str(self.get_symbol_table()))
1794                        } else {
1795                            String::new()
1796                        }),
1797                    format!("{} = {t},", s.to_camelcase())])
1798                .to_vec();
1799            src.extend(columns_to_str(cols, Some(vec![16, 0])));
1800            src.push("}\n".to_string());
1801            src.push("pub fn get_term_name(t: TokenId) -> (&'static str, Option<&'static str>) {".to_string());
1802            src.push("    SYMBOLS_T[t as usize]".to_string());
1803            src.push("}\n".to_string());
1804        }
1805        src.extend(vec![
1806            "pub fn build_parser() -> Parser<'static> {{".to_string(),
1807            "    let symbol_table = FixedSymTable::new(".to_string(),
1808            "        SYMBOLS_T.into_iter().map(|(s, os)| (s.to_string(), os.map(|s| s.to_string()))).collect(),".to_string(),
1809            "        SYMBOLS_NT.into_iter().map(|s| s.to_string()).collect()".to_string(),
1810            "    );".to_string(),
1811            "    Parser::new(".to_string(),
1812            "        PARSER_NUM_NT, PARSER_NUM_T + 1,".to_string(),
1813            "        &ALT_VAR,".to_string(),
1814            if self.include_alts {
1815                "        ALTERNATIVES.into_iter().map(|s| Alternative::new(s.to_vec())).collect(),".to_string()
1816            } else {
1817                "        Vec::new(),".to_string()
1818            },
1819            "        OPCODES.into_iter().map(|strip| strip.to_vec()).collect(),".to_string(),
1820            "        INIT_OPCODES.to_vec(),".to_string(),
1821            "        &PARSING_TABLE,".to_string(),
1822            "        symbol_table,".to_string(),
1823            "        START_SYMBOL".to_string(),
1824            "    )".to_string(),
1825            "}}".to_string(),
1826        ]);
1827        src
1828    }
1829
1830    fn get_info_type(&self, infos: &[ItemInfo], info: &ItemInfo) -> String {
1831        let type_name_base = match info.sym {
1832            Symbol::T(_) => "String".to_string(),
1833            Symbol::NT(vs) => self.get_nt_type(vs).to_string(),
1834            Symbol::Empty => "bool".to_string(),
1835            _ => panic!("unexpected symbol {}", info.sym)
1836        };
1837        if info.index.is_some() {
1838            let nbr = infos.iter()
1839                .map(|nfo| if nfo.sym == info.sym { nfo.index.unwrap() } else { 0 })
1840                .max().unwrap() + 1;
1841            format!("[{type_name_base}; {nbr}]")
1842        } else {
1843            type_name_base
1844        }
1845    }
1846
1847    /// Structure elements used in a context or in a +* child type
1848    fn source_infos(&self, infos: &[ItemInfo], add_pub: bool, add_type: bool) -> String {
1849        let pub_str = if add_pub { "pub " } else { "" };
1850        infos.iter()
1851            .filter_map(|info| {
1852                if info.index.is_none() || info.index == Some(0) {
1853                    let type_name = if add_type {
1854                        format!(": {}", self.get_info_type(infos, info))
1855                    } else {
1856                        String::new()
1857                    };
1858                    Some(format!("{pub_str}{}{type_name}", info.name))
1859                } else {
1860                    None
1861                }
1862        }).join(", ")
1863    }
1864
1865    fn is_alt_sym_empty(&self, a_id: AltId) -> bool {
1866        self.parsing_table.alts[a_id as usize].1.is_sym_empty()
1867    }
1868
1869    /// Generates the match cases for the "Call::Exit" in the `switch` method.
1870    fn make_match_choices(&self, alts: &[AltId], name: &str, flags: u32, no_method: bool, force_id: Option<AltId>) -> (bool, Vec<String>) {
1871        assert!(!alts.is_empty(), "alts cannot be empty");
1872        // If + <L> child, the two alts are identical. We keep the two alts anyway because it's more coherent
1873        // for the rest of the flow. At the end, when we generate the wrapper method, we'll discard the 2nd alternative and use
1874        // the `alt_id` parameter to determine whether it's the last iteration or not.
1875        // We do discard the 2nd, empty alternative immediately for a non-<L> * child because there's no associated context.
1876        let discarded = if !no_method && flags & (ruleflag::CHILD_REPEAT | ruleflag::REPEAT_PLUS | ruleflag::L_FORM) == ruleflag::CHILD_REPEAT { 1 } else { 0 };
1877
1878        // + children always have 2*n left-factorized children, each couple with identical item_ops (one for the loop, one for the last iteration).
1879        // So in non-<L> +, we need more than 2 alts to need the alt_id parameter. In other cases, we need more than one
1880        // alt (after removing the possible discarded one) to require the alt_id parameter.
1881        let is_plus_no_lform = flags & (ruleflag::CHILD_REPEAT | ruleflag::REPEAT_PLUS | ruleflag::L_FORM) == (ruleflag::CHILD_REPEAT | ruleflag::REPEAT_PLUS);
1882        let is_alt_id_threshold = if is_plus_no_lform { 2 } else { 1 };
1883        let is_alt_id = force_id.is_none() && alts.len() - discarded > is_alt_id_threshold;
1884
1885        let mut choices = Vec::<String>::new();
1886        let force_id_str = force_id.map(|f| f.to_string()).unwrap_or_default();
1887        if alts.len() - discarded == 1 {
1888            if no_method {
1889                choices.push(format!("                    {} => {{}}", alts[0]));
1890            } else {
1891                choices.push(format!("                    {} => self.{name}({force_id_str}),", alts[0]));
1892            }
1893        } else {
1894            let last = alts.len() - 1 - discarded;
1895            choices.extend((0..last).map(|i| format!("                    {} |", alts[i])));
1896            if no_method {
1897                choices.push(format!("                    {} => {{}}", alts[last]));
1898            } else {
1899                choices.push(format!("                    {} => self.{name}({}{force_id_str}),",
1900                                     alts[last],
1901                                     if is_alt_id { "alt_id" } else { "" }));
1902            }
1903        }
1904        if discarded == 1 {
1905            choices.push(format!("                    {} => {{}}", alts.last().unwrap()));
1906        }
1907        (is_alt_id, choices)
1908    }
1909
1910    /// Generates a string with either `"{common}"` or `"({span_code}, {common})"`, where `span_code` is
1911    /// created by the closure. We use a closure because it's executed only if necessary, which
1912    /// avoids accessing data that might not be available when the span code is not generated.
1913    fn gen_match_item<F: FnOnce() -> String>(&self, common: String, span_only: F) -> String {
1914        if self.gen_span_params {
1915            let span_code = span_only();
1916            format!("({span_code}, {common})")
1917        } else {
1918            common
1919        }
1920    }
1921
1922    fn get_var_param(item: &ItemInfo, indices: &HashMap<Symbol, Vec<String>>, non_indices: &mut Vec<String>) -> Option<String> {
1923        if let Some(index) = item.index {
1924            if index == 0 {
1925                Some(format!("{}: [{}]", item.name, indices[&item.sym].iter().rev().join(", ")))
1926            } else {
1927                None
1928            }
1929        } else {
1930            let name = non_indices.pop().unwrap();
1931            if name == item.name {
1932                Some(name)
1933            } else {
1934                Some(format!("{}: {name}", item.name))
1935            }
1936        }
1937    }
1938
1939    fn get_var_params(item_info: &[ItemInfo], skip: usize, indices: &HashMap<Symbol, Vec<String>>, non_indices: &mut Vec<String>) -> String {
1940        item_info.iter().skip(skip).filter_map(|item| {
1941            Self::get_var_param(item, indices, non_indices)
1942        }).join(", ")
1943    }
1944
1945    fn source_lets(infos: &[ItemInfo], nt_name: &[(String, String, String)], indent: &str, last_alt_id_maybe: Option<AltId>) -> (Vec<String>, String) {
1946        let mut src_let = vec![];
1947        let mut var_fixer = NameFixer::new();
1948        let mut indices = HashMap::<Symbol, Vec<String>>::new();
1949        let mut non_indices = Vec::<String>::new();
1950        for item in infos.iter().rev() {
1951            let varname = if let Some(index) = item.index {
1952                let name = var_fixer.get_unique_name(format!("{}_{}", item.name, index + 1));
1953                indices.entry(item.sym).and_modify(|v| v.push(name.clone())).or_insert(vec![name.clone()]);
1954                name
1955            } else {
1956                let name = item.name.clone();
1957                non_indices.push(name.clone());
1958                name
1959            };
1960            if item.sym.is_empty() {
1961                src_let.push(format!("{indent}let {varname} = alt_id == {};", last_alt_id_maybe.unwrap()));
1962            } else if let Symbol::NT(v) = item.sym {
1963                src_let.push(format!("{indent}let {varname} = self.stack.pop().unwrap().get_{}();", nt_name[v as usize].2));
1964            } else {
1965                src_let.push(format!("{indent}let {varname} = self.stack_t.pop().unwrap();"));
1966            }
1967        }
1968        let src_struct = Self::get_var_params(infos, 0, &indices, &mut non_indices);
1969        (src_let, src_struct)
1970    }
1971
1972    fn source_update_span(n: &str) -> Vec<String> {
1973        vec![
1974            format!("        let spans = self.stack_span.drain(self.stack_span.len() - {n} ..).collect::<Vec<_>>();"),
1975            "        self.stack_span.push(spans.iter().fold(PosSpan::empty(), |acc, sp| acc + sp));".to_string(),
1976        ]
1977    }
1978
1979    /// Source code of the first part of exit_* method for children of *+,
1980    /// which takes the values of the NT and T items from the stack at each iteration.
1981    /// The same code is generated for init_* methods in the case of token-separated items,
1982    /// when the accumulator is initialized with the first items.
1983    fn source_child_repeat_lets(
1984        &self,
1985        endpoints: &[AltId],
1986        item_info: &[Vec<ItemInfo>],
1987        is_plus: bool,
1988        nt_name: &[(String, String, String)],
1989        fn_name: &str,
1990        nu: &str,
1991        is_init: bool,
1992    ) -> (Vec<String>, String)
1993    {
1994        // ex:
1995        //     let type1 = self.stack.pop().unwrap().get_type();
1996        //     let id = self.stack_t.pop().unwrap();
1997        //     let val = SynA1Item { id, type1 };
1998        //     let spans = self.stack_span.drain(self.stack_span.len() - 5 ..).collect::<Vec<_>>();
1999        //     self.stack_span.push(spans.iter().fold(PosSpan::empty(), |acc, sp| acc + sp));
2000        //
2001        let mut src_val = vec![];
2002        let val_name = if endpoints.len() > 1 {
2003            // several possibilities; for ex. a -> (A | B)+  => Vec of enum type
2004            src_val.push(format!("        let {} = match alt_id {{", self.gen_match_item("val".to_string(), || "n".to_string())));
2005            for (i, &a_id) in endpoints.iter().index_start(1) {
2006                let infos = &item_info[a_id as usize];
2007                src_val.push(format!("            {a_id}{} => {{", if is_plus { format!(" | {}", a_id + 1) } else { String::new() }));
2008                let (src_let, src_struct) = Self::source_lets(infos, nt_name, "                ", None);
2009                src_val.extend(src_let);
2010                let return_value = self.gen_match_item(
2011                    format!("Syn{nu}Item::V{i} {{ {} }}", src_struct),
2012                    || self.span_nbrs[a_id as usize].to_string());
2013                src_val.push(format!("                {return_value}"));
2014                src_val.push("            }".to_string());
2015            }
2016            src_val.push(format!("            _ => panic!(\"unexpected alt id {{alt_id}} in fn {fn_name}\"),"));
2017            src_val.push("        };".to_string());
2018            if self.gen_span_params {
2019                src_val.extend(Self::source_update_span("n"));
2020            }
2021            "val".to_string()
2022        } else {
2023            // single possibility; for ex. a -> (A B)+  => struct
2024            let a_id = endpoints[0];
2025            if self.gen_span_params {
2026                let span_nbr = if is_init {
2027                    *self.span_nbrs_sep_list.get(&a_id).unwrap()
2028                } else {
2029                    self.span_nbrs[a_id as usize]
2030                };
2031                src_val.extend(Self::source_update_span(&span_nbr.to_string()));
2032            }
2033            let infos = &item_info[a_id as usize];
2034            let (src_let, src_struct) = Self::source_lets(infos, nt_name, "        ", None);
2035            src_val.extend(src_let);
2036            if infos.len() == 1 {
2037                // single repeat item; for ex. A -> B+  => type directly as Vec<type>
2038                infos[0].name.clone()
2039            } else {
2040                // several repeat items; for ex. A -> (B b)+  => intermediate struct type for Vec
2041                src_val.push(format!("        let val = Syn{nu}Item {{ {} }};", src_struct));
2042                "val".to_string()
2043            }
2044        };
2045        (src_val, val_name)
2046    }
2047
2048    /// Generates the wrapper source code and returns
2049    /// * the wrapper source code
2050    /// * the template for the user-defined types (Syn*)
2051    /// * the template for the listener implementation
2052    fn source_wrapper(&mut self) -> (Vec<String>, Vec<String>, Vec<String>) {
2053        const VERBOSE: bool = false;
2054        const MATCH_COMMENTS_SHOW_DESCRIPTIVE_ALTS: bool = false;
2055
2056        static PARSER_LIBS: [&str; 8] = [
2057            "::VarId", "::parser::Call", "::parser::ListenerWrapper",
2058            "::AltId", "::log::Logger", "::TokenId", "::lexer::PosSpan",
2059            "::parser::Terminate"
2060        ];
2061
2062        self.log.add_note("generating wrapper source...");
2063        self.used_libs.extend(PARSER_LIBS.into_iter().map(|s| format!("{}{s}", self.lib_crate)));
2064        if self.gen_span_params {
2065            self.used_libs.add(format!("{}::lexer::PosSpan", self.lib_crate));
2066        }
2067
2068        self.get_type_info();
2069        let pinfo = &self.parsing_table;
2070
2071        // defines missing type names
2072        for (v, name) in self.nt_name.iter().enumerate().filter(|(v, _)| self.nt_value[*v]) {
2073            let v = v as VarId;
2074            self.nt_type.entry(v).or_insert_with(|| format!("Syn{}", name.0));
2075        }
2076
2077        let mut src = vec![];
2078
2079        // writes contexts
2080        let mut nt_contexts = self.source_wrapper_ctx::<VERBOSE>(&mut src);
2081
2082        // writes intermediate Syn types
2083        let (src_types, syns) = self.source_wrapper_types::<VERBOSE>(&mut src);
2084
2085        // prepares the data for the following sections
2086        let mut exit_fixer = NameFixer::new();
2087        let mut span_init = HashSet::<VarId>::new();
2088        let src_skel = vec![
2089            format!("// {:-<80}", ""),
2090            format!("// Template for the user implementation of {}Listener", self.name),
2091            String::new(),
2092            "struct Listener {".to_string(),
2093            "    log: BufLog,".to_string(),
2094            "}".to_string(),
2095            String::new(),
2096            "#[allow(unused)]".to_string(),
2097            format!("impl {}Listener for Listener {{", self.name),
2098            "    fn get_log_mut(&mut self) -> &mut impl Logger {".to_string(),
2099            "        &mut self.log".to_string(),
2100            "    }".to_string(),
2101            String::new(),
2102        ];
2103        let mut sources = WrapperSources {
2104            src,
2105            src_listener_decl: vec![],
2106            src_skel,
2107            src_types,
2108            src_init: vec![],
2109            src_exit: vec![],
2110            src_wrapper_impl: vec![],
2111        };
2112
2113        // we proceed by var parent, then all alts in each parent/children group
2114        for group in self.nt_parent.iter().filter(|vf| !vf.is_empty()) {
2115            let parent_nt = group[0] as usize;
2116            let parent_flags = self.parsing_table.flags[parent_nt];
2117            let parent_has_value = self.nt_value[parent_nt];
2118            let mut exit_alt_done = HashSet::<VarId>::new();
2119            let mut init_nt_done = HashSet::<VarId>::new();
2120            if VERBOSE { println!("- GROUP {}, parent has {}value, parent flags: {}",
2121                                  group.iter().map(|v| Symbol::NT(*v).to_str(self.get_symbol_table())).join(", "),
2122                                  if parent_has_value { "" } else { "no " },
2123                                  ruleflag::to_string(parent_flags).join(" | ")); }
2124            let is_ambig = parent_flags & ruleflag::PARENT_AMBIGUITY != 0;
2125            let ambig_children = if is_ambig {
2126                group.iter().filter(|&v| self.nt_has_any_flags(*v, ruleflag::CHILD_L_RECURSION)).cloned().to_vec()
2127            } else {
2128                Vec::new()
2129            };
2130            let mut ambig_op_alts = BTreeMap::<AltId, Vec<AltId>>::new();
2131            for (id, f) in ambig_children.iter()        // id = operator priority/ID in ambig rule
2132                .flat_map(|v| self.gather_alts(*v))
2133                .filter_map(|f| self.parsing_table.alts[f as usize].1.get_ambig_alt_id().map(|id| (id, f)))
2134            {
2135                ambig_op_alts.entry(id).or_default().push(f);
2136            }
2137            if VERBOSE && is_ambig {
2138                println!("- ambig children vars: {}", ambig_children.iter().map(|v| Symbol::NT(*v).to_str(self.get_symbol_table())).join(", "));
2139                println!("  ambig op alts: {ambig_op_alts:?}");
2140            }
2141
2142            // contexts used in source_wrapper_init and source_wrapper_exit methods:
2143            let in_ctx = SourceInputContext {
2144                parent_has_value,
2145                parent_nt,
2146                pinfo,
2147                syns: &syns,
2148                ambig_op_alts: &ambig_op_alts,
2149            };
2150            let mut state = SourceState {
2151                init_nt_done: &mut init_nt_done,
2152                span_init: &mut span_init,
2153                nt_contexts: &mut nt_contexts,
2154                exit_alt_done: &mut exit_alt_done,
2155                exit_fixer: &mut exit_fixer,
2156            };
2157
2158            for var in group {
2159                let nt = *var as usize;
2160                let flags = self.parsing_table.flags[nt];
2161                // the parents of left recursion are not useful in ambiguous rules (they just push / pop the same value):
2162                let is_ambig_1st_child =  is_ambig && flags & ruleflag::CHILD_L_RECURSION != 0 && ambig_children.first() == Some(var);
2163                // we only process the first variable of the left recursion; below we gather the alts of
2164                // the other variables of the same type (in ambiguous rules, they repeat the same operators)
2165                let is_ambig_redundant = is_ambig && flags & ruleflag::L_RECURSION != 0 && !is_ambig_1st_child;
2166                let has_value = self.nt_value[nt];
2167
2168                // Call::Enter
2169                self.source_wrapper_init::<VERBOSE>(
2170                    &in_ctx,
2171                    *var,
2172                    flags,
2173                    has_value,
2174                    is_ambig_1st_child,
2175                    &mut state,
2176                    &mut sources
2177                );
2178
2179                // Call::Exit
2180                self.source_wrapper_exit::<VERBOSE>(
2181                    &in_ctx,
2182                    *var,
2183                    flags,
2184                    has_value,
2185                    is_ambig_1st_child,
2186                    is_ambig_redundant,
2187                    &mut state,
2188                    &mut sources
2189                );
2190            }
2191
2192            // completes the unused nt entries in the match's Call::Exit => { ... }
2193            for a in group.iter().flat_map(|v| &self.var_alts[*v as usize]).filter(|a| !exit_alt_done.contains(a)) {
2194                let is_called = self.opcodes[*a as usize].contains(&OpCode::Exit(*a));
2195                let (v, alt) = &self.parsing_table.alts[*a as usize];
2196                let alt_str = if MATCH_COMMENTS_SHOW_DESCRIPTIVE_ALTS {
2197                    self.full_alt_str(*a, None, false)
2198                } else {
2199                    alt.to_rule_str(*v, self.get_symbol_table(), self.parsing_table.flags[*v as usize])
2200                };
2201                let comment = format!("// {alt_str} ({})", if is_called { "not used" } else { "never called" });
2202                if is_called {
2203                    sources.src_exit.push(vec![format!("                    {a} => {{}}"), comment]);
2204                } else {
2205                    sources.src_exit.push(vec![format!("                 /* {a} */"), comment]);
2206                }
2207            }
2208            // adds unused init calls, using Segments to regroup them
2209            let mut seg_init = Segments::from_iter(
2210                group.iter()
2211                    .filter_map(|&v| if !init_nt_done.contains(&v) { Some(Seg(v as u32, v as u32)) } else { None })
2212            );
2213            seg_init.normalize();
2214            for seg in seg_init {
2215                let Seg(a, b) = seg;
2216                if a == b {
2217                    sources.src_init.push(vec![format!("                    {a} => {{}}"), format!("// {}", Symbol::NT(a as VarId).to_str(self.get_symbol_table()))]);
2218                } else {
2219                    sources.src_init.push(vec![
2220                        format!("                    {a}{}{b} => {{}}", if b == a + 1 { " | " } else { " ..= " }),
2221                        format!("// {}", (a..=b).map(|v| Symbol::NT(v as VarId).to_str(self.get_symbol_table())).join(", "))
2222                    ]);
2223                }
2224            }
2225        }
2226
2227        self.source_wrapper_finalize(span_init, sources)
2228    }
2229
2230    /// Adds the wrapper source code related to the Ctx types
2231    fn source_wrapper_ctx<const VERBOSE: bool>(&self, src: &mut Vec<String>) -> Vec<Option<Vec<AltId>>> {
2232        let mut nt_contexts: Vec<Option<Vec<AltId>>> = vec![None; self.parsing_table.num_nt];
2233        for group in self.nt_parent.iter().filter(|vf| !vf.is_empty()) {
2234            let mut group_names = HashMap::<VarId, Vec<AltId>>::new();
2235            // fetches the NT that have alt data
2236            for nt in group {
2237                for &alt_id in &self.var_alts[*nt as usize] {
2238                    if let Some((owner, _name)) = &self.alt_info[alt_id as usize] {
2239                        group_names.entry(*owner)
2240                            .and_modify(|v| v.push(alt_id))
2241                            .or_insert_with(|| vec![alt_id]);
2242                    }
2243                }
2244            }
2245            if VERBOSE {
2246                println!("group {}", group.iter().map(|nt| Symbol::NT(*nt).to_str(self.get_symbol_table())).join(" "));
2247            }
2248            for &nt in group {
2249                if let Some(alts) = group_names.get(&nt) {
2250                    let flags = self.parsing_table.flags[nt as usize];
2251                    if VERBOSE {
2252                        print!("- {}: flags {}", Symbol::NT(nt).to_str(self.get_symbol_table()), ruleflag::to_string(flags).join(" "));
2253                        if let Some(gn) = group_names.get(&nt) {
2254                            println!(", alts = {}", gn.iter().map(|a| a.to_string()).join(", "));
2255                            let sorted = self.sort_alt_ids(group[0], gn);
2256                            println!("     sorted alts: {sorted:?}");
2257                        } else {
2258                            println!();
2259                        }
2260                    }
2261                    if flags & (ruleflag::SEP_LIST | ruleflag::L_FORM) == ruleflag::SEP_LIST | ruleflag::L_FORM {
2262                        src.push("#[derive(Debug)]".to_string());
2263                        src.push(format!("pub enum InitCtx{} {{", self.nt_name[nt as usize].0));
2264                        let a_id = self.var_alts[nt as usize][0];
2265                        let comment = format!(
2266                            "value of `{}` before {}",
2267                            self.item_ops[a_id as usize][1..].iter().map(|s| s.to_str(self.get_symbol_table())).join(" "),
2268                            self.full_alt_components(a_id, None).1
2269                        );
2270                        let ctx_content = self.source_infos(&self.item_info[a_id as usize], false, true);
2271                        src.push(format!("    /// {comment}"));
2272                        let a_name = &self.alt_info[a_id as usize].as_ref().unwrap().1;
2273                        let ctx_item = if ctx_content.is_empty() {
2274                            if VERBOSE { println!("      {a_name},"); }
2275                            format!("    {a_name},", )
2276                        } else {
2277                            if VERBOSE { println!("      {a_name} {{ {ctx_content} }},"); }
2278                            format!("    {a_name} {{ {ctx_content} }},", )
2279                        };
2280                        src.push(ctx_item);
2281                        src.push("}".to_string());
2282                    }
2283                    src.push("#[derive(Debug)]".to_string());
2284                    src.push(format!("pub enum Ctx{} {{", self.nt_name[nt as usize].0));
2285                    if VERBOSE { println!("  context Ctx{}:", self.nt_name[nt as usize].0); }
2286                    let alts = self.sort_alt_ids(group[0], alts);
2287                    nt_contexts[nt as usize] = Some(alts.clone());
2288                    for a_id in alts {
2289                        let comment = self.full_alt_str(a_id, None, true);
2290                        src.push(format!("    /// {comment}"));
2291                        if VERBOSE { println!("      /// {comment}"); }
2292                        let ctx_content = self.source_infos(&self.item_info[a_id as usize], false, true);
2293                        let a_name = &self.alt_info[a_id as usize].as_ref().unwrap().1;
2294                        let ctx_item = if ctx_content.is_empty() {
2295                            if VERBOSE { println!("      {a_name},"); }
2296                            format!("    {a_name},", )
2297                        } else {
2298                            if VERBOSE { println!("      {a_name} {{ {ctx_content} }},"); }
2299                            format!("    {a_name} {{ {ctx_content} }},", )
2300                        };
2301                        src.push(ctx_item);
2302                    }
2303                    src.push("}".to_string());
2304                }
2305            }
2306        }
2307        nt_contexts
2308    }
2309
2310    /// Adds the wrapper source code related to the user types
2311    fn source_wrapper_types<const VERBOSE: bool>(&self, src: &mut Vec<String>) -> (Vec<String>, Vec<VarId>) {
2312        static TYPE_DERIVE: &str = "#[derive(Debug, PartialEq)]";
2313
2314        let mut src_types = vec![
2315            format!("// {:-<80}", ""),
2316            "// Template for the user-defined types:".to_string(),
2317        ];
2318        src.add_space();
2319        let mut syns = Vec::<VarId>::new(); // list of valuable NTs
2320        for (v, names) in self.nt_name.iter().enumerate().filter(|(v, _)| self.nt_value[*v]) {
2321            let v = v as VarId;
2322            let (nu, _nl, _npl) = names;
2323            let nt_type = self.get_nt_type(v);
2324            if self.nt_has_all_flags(v, ruleflag::CHILD_REPEAT) {
2325                let is_lform = self.nt_has_all_flags(v, ruleflag::L_FORM);
2326                let first_alt = self.var_alts[v as usize][0];
2327                let (t, var_oid) = self.origin.get(v).unwrap();
2328                if is_lform {
2329                    let astr = format!("/// User-defined type for {}", self.full_alt_str(first_alt, None, true));
2330                    src_types.push(String::new());
2331                    src_types.push(astr.clone());
2332                    src_types.push(TYPE_DERIVE.to_string());
2333                    src_types.push(format!("pub struct {}();", self.get_nt_type(v)));
2334                } else {
2335                    let top_parent = self.parsing_table.get_top_parent(v);
2336                    src.push(format!("/// Computed `{}` array in `{} -> {}`",
2337                                     grtree_to_str(t, Some(var_oid), None, Some(top_parent), self.get_symbol_table(), true),
2338                                     Symbol::NT(top_parent).to_str(self.get_symbol_table()),
2339                                     grtree_to_str(t, None, Some(var_oid), Some(top_parent), self.get_symbol_table(), true),
2340                    ));
2341                    let endpoints = self.child_repeat_endpoints.get(&v).unwrap();
2342                    if endpoints.len() > 1 {
2343                        // several possibilities; for ex. a -> (A | B)+  => Vec of enum type
2344                        src.push("#[derive(Debug, PartialEq)]".to_string());
2345                        src.push(format!("pub struct {nt_type}(pub Vec<Syn{nu}Item>);"));
2346                        src.push("#[derive(Debug, PartialEq)]".to_string());
2347                        src.push(format!("pub enum Syn{nu}Item {{"));
2348                        for (i, &a_id) in endpoints.iter().index_start(1) {
2349                            src.push(format!("    /// {}", self.full_alt_str(a_id, None, true)));
2350                            src.push(format!("    V{i} {{ {} }},", self.source_infos(&self.item_info[a_id as usize], false, true)));
2351                        }
2352                        src.push("}".to_string());
2353                    } else {
2354                        // single possibility; for ex. a -> (A B)+  => struct
2355                        let a_id = endpoints[0];
2356                        let infos = &self.item_info[a_id as usize];
2357                        if infos.len() == 1 {
2358                            // single repeat item; for ex. A -> B+  => type directly as Vec<type>
2359                            let type_name = self.get_info_type(infos, &infos[0]);
2360                            src.push("#[derive(Debug, PartialEq)]".to_string());
2361                            src.push(format!("pub struct {nt_type}(pub Vec<{type_name}>);", ));
2362                        } else {
2363                            // several repeat items; for ex. A -> (B b)+  => intermediate struct type for Vec
2364                            src.push("#[derive(Debug, PartialEq)]".to_string());
2365                            src.push(format!("pub struct {nt_type}(pub Vec<Syn{nu}Item>);"));
2366                            src.push(format!("/// {}", self.full_alt_str(first_alt, None, false)));
2367                            src.push("#[derive(Debug, PartialEq)]".to_string());
2368                            src.push(format!("pub struct Syn{nu}Item {{ {} }}", self.source_infos(infos, true, true)));
2369                        }
2370                    }
2371                }
2372            } else {
2373                src_types.push(String::new());
2374                src_types.push(format!("/// User-defined type for `{}`", Symbol::NT(v).to_str(self.get_symbol_table())));
2375                src_types.push(TYPE_DERIVE.to_string());
2376                src_types.push(format!("pub struct {}();", self.get_nt_type(v)));
2377            }
2378            syns.push(v);
2379        }
2380        if !self.nt_value[self.start as usize] {
2381            let nu = &self.nt_name[self.start as usize].0;
2382            src.push(format!("/// Top non-terminal {nu} (has no value)"));
2383            src.push("#[derive(Debug, PartialEq)]".to_string());
2384            src.push(format!("pub struct Syn{nu}();"))
2385        }
2386
2387        // Writes EnumSynValue type and implementation
2388        if VERBOSE { println!("syns = {syns:?}"); }
2389        src.add_space();
2390        // EnumSynValue type
2391        src.push("#[derive(Debug)]".to_string());
2392        src.push(format!("enum EnumSynValue {{ {} }}",
2393                         syns.iter().map(|v| format!("{}({})", self.nt_name[*v as usize].0, self.get_nt_type(*v))).join(", ")));
2394        if !syns.is_empty() {
2395            // EnumSynValue getters
2396            src.add_space();
2397            src.push("impl EnumSynValue {".to_string());
2398            for v in &syns {
2399                let (nu, _, npl) = &self.nt_name[*v as usize];
2400                let nt_type = self.get_nt_type(*v);
2401                src.push(format!("    fn get_{npl}(self) -> {nt_type} {{"));
2402                if syns.len() == 1 {
2403                    src.push(format!("        let EnumSynValue::{nu}(val) = self;"));
2404                    src.push("        val".to_string());
2405                } else {
2406                    src.push(format!("        if let EnumSynValue::{nu}(val) = self {{ val }} else {{ panic!() }}"));
2407                }
2408                src.push("    }".to_string());
2409            }
2410            src.push("}".to_string());
2411        }
2412        (src_types, syns)
2413    }
2414
2415    /// Adds the wrapper source code related to Call::Enter
2416    fn source_wrapper_init<const VERBOSE: bool>(
2417        &self,
2418        ctx                 : &SourceInputContext,
2419        var                 : VarId,
2420        flags               : u32,
2421        has_value           : bool,
2422        is_ambig_1st_child  : bool,
2423        state               : &mut SourceState,
2424        sources             : &mut WrapperSources
2425    ) {
2426        let &SourceInputContext { ambig_op_alts, .. } = ctx;
2427        let SourceState { init_nt_done, span_init, .. } = state;
2428        let WrapperSources { src_listener_decl, src_skel, src_init, src_wrapper_impl, .. } = sources;
2429        let nt = var as usize;
2430        let sym_nt = Symbol::NT(var);
2431        let nt_comment = format!("// {}", sym_nt.to_str(self.get_symbol_table()));
2432        let is_sep_list = flags & ruleflag::SEP_LIST != 0;
2433        let is_lform = flags & ruleflag::L_FORM != 0;
2434        let is_rrec_lform = is_lform && flags & ruleflag::R_RECURSION != 0;
2435        let is_plus = flags & ruleflag::REPEAT_PLUS != 0;
2436        let (nu, nl, npl) = &self.nt_name[nt];
2437        if VERBOSE { println!("  - VAR {}, has {}value, flags: {}",
2438                              sym_nt.to_str(self.get_symbol_table()),
2439                              if has_value { "" } else { "no " },
2440                              ruleflag::to_string(flags).join(" | ")); }
2441
2442        let mut has_skel_init = false;
2443        let init_fn_name = format!("init_{npl}");
2444        if self.parsing_table.parent[nt].is_none() {
2445            init_nt_done.insert(var);
2446            if is_rrec_lform {
2447                span_init.insert(var);
2448            }
2449            if is_rrec_lform && has_value {
2450                src_wrapper_impl.push(String::new());
2451                src_listener_decl.push(format!("    fn {init_fn_name}(&mut self) -> {};", self.get_nt_type(nt as VarId)));
2452                src_skel.push(format!("    fn {init_fn_name}(&mut self) -> {} {{", self.get_nt_type(nt as VarId)));
2453                has_skel_init = true;
2454                src_init.push(vec![format!("                    {nt} => self.init_{nl}(),"), nt_comment]);
2455                src_wrapper_impl.push(format!("    fn {init_fn_name}(&mut self) {{"));
2456                src_wrapper_impl.push(format!("        let val = self.listener.init_{nl}();"));
2457                src_wrapper_impl.push(format!("        self.stack.push(EnumSynValue::{nu}(val));"));
2458                src_wrapper_impl.push("    }".to_string());
2459            } else {
2460                src_listener_decl.push(format!("    fn {init_fn_name}(&mut self) {{}}"));
2461                src_init.push(vec![format!("                    {nt} => self.listener.{init_fn_name}(),"), nt_comment]);
2462            }
2463        } else if flags & ruleflag::CHILD_REPEAT != 0 {
2464            if !is_sep_list {
2465                span_init.insert(var);
2466            }
2467            if has_value || is_sep_list {
2468                init_nt_done.insert(var);
2469                src_wrapper_impl.push(String::new());
2470                src_init.push(vec![format!("                    {nt} => self.{init_fn_name}(),"), nt_comment]);
2471                src_wrapper_impl.push(format!("    fn {init_fn_name}(&mut self) {{"));
2472                if is_lform {
2473                    if is_sep_list {
2474                        let all_exit_alts = if is_ambig_1st_child {
2475                            ambig_op_alts.values().rev().map(|v| v[0]).to_vec()
2476                        } else {
2477                            self.gather_alts(nt as VarId)
2478                        };
2479                        let exit_alts = all_exit_alts.into_iter()
2480                            .filter(|f|
2481                                (flags & ruleflag::CHILD_L_RECURSION == 0
2482                                    && flags & (ruleflag::CHILD_REPEAT_LFORM | ruleflag::REPEAT_PLUS) != ruleflag::CHILD_REPEAT_LFORM)
2483                                || !self.is_alt_sym_empty(*f)
2484                            );
2485                        let (mut last_alt_ids, exit_info_alts): (Vec<AltId>, Vec<AltId>) = exit_alts.into_iter()
2486                            .partition(|i| self.alt_info[*i as usize].is_none());
2487                        let last_alt_id_maybe = if last_alt_ids.is_empty() { None } else { Some(last_alt_ids.remove(0)) };
2488                        let a = exit_info_alts[0];
2489                        let indent = "        ";
2490                        let (src_let, ctx_params) = Self::source_lets(&self.item_info[a as usize], &self.nt_name, indent, last_alt_id_maybe);
2491                        src_wrapper_impl.extend(src_let);
2492                        let ctx = if ctx_params.is_empty() {
2493                            format!("InitCtx{nu}::{}", self.alt_info[a as usize].as_ref().unwrap().1)
2494                        } else {
2495                            format!("InitCtx{nu}::{} {{ {ctx_params} }}", self.alt_info[a as usize].as_ref().unwrap().1)
2496                        };
2497                        src_wrapper_impl.push(format!("        let ctx = {ctx};"));
2498                        if self.gen_span_params {
2499                            src_wrapper_impl.extend(Self::source_update_span(&self.span_nbrs_sep_list[&a].to_string()));
2500                        }
2501                        src_wrapper_impl.push(format!(
2502                            "        {}self.listener.{init_fn_name}(ctx{});",
2503                            if has_value { "let val = " } else { "" },
2504                            if self.gen_span_params { ", spans" } else { "" }));
2505                        let ret = if has_value {
2506                            format!("-> {};", self.get_nt_type(nt as VarId))
2507                        } else {
2508                            src_listener_decl.push("    #[allow(unused_variables)]".to_string());
2509                            "{}".to_string()
2510                        };
2511                        src_listener_decl.push(format!(
2512                            "    fn {init_fn_name}(&mut self, ctx: InitCtx{nu}{}) {ret}",
2513                            if self.gen_span_params { ", spans: Vec<PosSpan>" } else { "" }));
2514
2515                        // skeleton (listener template)
2516                        let ret = if has_value { format!(" -> {}", self.get_nt_type(nt as VarId)) } else { String::new() };
2517                        src_skel.push(format!(
2518                            "    fn {init_fn_name}(&mut self, ctx: InitCtx{nu}{}){ret} {{",
2519                            if self.gen_span_params { ", spans: Vec<PosSpan>" } else { "" }));
2520                        let a_id = self.var_alts[nt][0];
2521                        let a_info = &self.item_info[a_id as usize];
2522                        if !a_info.is_empty() {
2523                            let comment = format!(
2524                                "value of `{}` before {}",
2525                                self.item_ops[a_id as usize][1..].iter().map(|s| s.to_str(self.get_symbol_table())).join(" "),
2526                                self.full_alt_components(a_id, None).1
2527                            );
2528                            let ctx_content = a_info.iter().map(|i| i.name.clone()).join(", ");
2529                            let a_name = &self.alt_info[a_id as usize].as_ref().unwrap().1;
2530                            src_skel.push(format!("        // {comment}"));
2531                            src_skel.push(format!("        let InitCtx{nu}::{a_name} {{ {ctx_content} }} = ctx;"));
2532                        }
2533                        has_skel_init = true;
2534                    } else {
2535                        src_wrapper_impl.push(format!("        let val = self.listener.{init_fn_name}();"));
2536                        src_listener_decl.push(format!("    fn {init_fn_name}(&mut self) -> {};", self.get_nt_type(nt as VarId)));
2537                        src_skel.push(format!("    fn {init_fn_name}(&mut self) -> {} {{", self.get_nt_type(nt as VarId)));
2538                        has_skel_init = true;
2539                    }
2540                    if has_value {
2541                        src_wrapper_impl.push(format!("        self.stack.push(EnumSynValue::{nu}(val));"));
2542                    }
2543                } else if is_sep_list {
2544                    // fetch values from stack to init the list with the first value that was outside the repetition:
2545                    // first α in α (β α)*
2546                    let endpoints = self.child_repeat_endpoints.get(&var).unwrap();
2547                    let (src_val, val_name) = self.source_child_repeat_lets(endpoints, &self.item_info, is_plus, &self.nt_name, &init_fn_name, nu, true);
2548                    src_wrapper_impl.extend(src_val);
2549                    src_wrapper_impl.push(format!("        self.stack.push(EnumSynValue::{nu}(Syn{nu}(vec![{val_name}])));"));
2550                } else {
2551                    src_wrapper_impl.push(format!("        let val = Syn{nu}(Vec::new());"));
2552                    src_wrapper_impl.push(format!("        self.stack.push(EnumSynValue::{nu}(val));"));
2553                }
2554                src_wrapper_impl.push("    }".to_string());
2555            } else if is_lform {
2556                init_nt_done.insert(var);
2557                src_init.push(vec![format!("                    {nt} => self.listener.{init_fn_name}(),"), nt_comment]);
2558                src_listener_decl.push(format!("    fn {init_fn_name}(&mut self) {{}}"));
2559            } else {
2560                // src_init.push(vec![format!("                    {nt} => {{}}"), nt_comment]);
2561            }
2562        } else {
2563            // src_init.push(vec![format!("                    {nt} => {{}}"), nt_comment]);
2564        }
2565        if has_skel_init {
2566            if has_value {
2567                src_skel.push(format!("        {}()", self.get_nt_type(nt as VarId)));
2568            }
2569            src_skel.push("    }".to_string());
2570            src_skel.push(String::new());
2571        }
2572    }
2573
2574    /// Adds the wrapper source code related to Call::Exit
2575    fn source_wrapper_exit<const VERBOSE: bool>(
2576        &self,
2577        ctx                 : &SourceInputContext,
2578        var                 : VarId,
2579        flags               : u32,
2580        has_value           : bool,
2581        is_ambig_1st_child  : bool,
2582        is_ambig_redundant  : bool,
2583        state               : &mut SourceState,
2584        sources             : &mut WrapperSources
2585    ) {
2586        const MATCH_COMMENTS_SHOW_DESCRIPTIVE_ALTS: bool = false;
2587
2588        let &SourceInputContext {
2589            parent_has_value, parent_nt, pinfo, syns, ambig_op_alts
2590        } = ctx;
2591        let SourceState { nt_contexts, exit_alt_done, exit_fixer, .. } = state;
2592        let WrapperSources { src_listener_decl, src_skel, src_exit, src_wrapper_impl, .. } = sources;
2593        let nt = var as usize;
2594        let is_plus = flags & ruleflag::REPEAT_PLUS != 0;
2595        let is_parent = nt == parent_nt;
2596        let is_child_repeat_lform = self.nt_has_all_flags(var, ruleflag::CHILD_REPEAT_LFORM);
2597        let (nu, _nl, npl) = &self.nt_name[nt];
2598
2599        // handles most rules except children of left factorization (already taken by self.gather_alts)
2600        if !is_ambig_redundant && flags & ruleflag::CHILD_L_FACT == 0 {
2601            let mut has_skel_exit = false;
2602            let mut has_skel_exit_return = false;
2603            let (pnu, _pnl, pnpl) = &self.nt_name[parent_nt];
2604            if VERBOSE { println!("    {nu} (parent {pnu})"); }
2605            let no_method = !has_value && flags & ruleflag::CHILD_REPEAT_LFORM == ruleflag::CHILD_REPEAT;
2606            let is_rrec_lform = self.nt_has_all_flags(var, ruleflag::R_RECURSION | ruleflag::L_FORM);
2607            let (fnpl, fnu, fnt, f_valued) = if is_ambig_1st_child {
2608                (pnpl, pnu, parent_nt, parent_has_value)    // parent_nt doesn't come through this code, so we must do it now
2609            } else {
2610                (npl, nu, nt, has_value)
2611            };
2612            if is_parent || (is_child_repeat_lform && !no_method) || is_ambig_1st_child {
2613                let extra_param = if self.gen_span_params { ", spans: Vec<PosSpan>" } else { "" };
2614                if f_valued {
2615                    let nt_type = self.get_nt_type(fnt as VarId);
2616                    if is_rrec_lform || (is_child_repeat_lform) {
2617                        src_listener_decl.push(format!("    fn exit_{fnpl}(&mut self, acc: &mut {nt_type}, ctx: Ctx{fnu}{extra_param});"));
2618                        src_skel.push(format!("    fn exit_{fnpl}(&mut self, acc: &mut {nt_type}, ctx: Ctx{fnu}{extra_param}) {{"));
2619                    } else {
2620                        src_listener_decl.push(format!("    fn exit_{fnpl}(&mut self, ctx: Ctx{fnu}{extra_param}) -> {nt_type};"));
2621                        src_skel.push(format!("    fn exit_{fnpl}(&mut self, ctx: Ctx{fnu}{extra_param}) -> {nt_type} {{"));
2622                        has_skel_exit_return = true;
2623                    }
2624                } else {
2625                    src_listener_decl.push("    #[allow(unused_variables)]".to_string());
2626                    src_listener_decl.push(format!("    fn exit_{fnpl}(&mut self, ctx: Ctx{fnu}{extra_param}) {{}}"));
2627                    src_skel.push(format!("    fn exit_{fnpl}(&mut self, ctx: Ctx{fnu}{extra_param}) {{"));
2628                }
2629                has_skel_exit = true;
2630            }
2631            let all_exit_alts = if is_ambig_1st_child {
2632                ambig_op_alts.values().rev().map(|v| v[0]).to_vec()
2633            } else {
2634                self.gather_alts(nt as VarId)
2635            };
2636            let (last_it_alts, exit_alts) = all_exit_alts.into_iter()
2637                .partition::<Vec<_>, _>(|f|
2638                    (flags & ruleflag::CHILD_L_RECURSION != 0
2639                        || flags & (ruleflag::CHILD_REPEAT_LFORM | ruleflag::REPEAT_PLUS) == ruleflag::CHILD_REPEAT_LFORM)
2640                    && self.is_alt_sym_empty(*f));
2641            if VERBOSE {
2642                println!("    no_method: {no_method}, exit alts: {}", exit_alts.iter().join(", "));
2643                if !last_it_alts.is_empty() {
2644                    println!("    last_it_alts: {}", last_it_alts.iter().join(", "));
2645                }
2646            }
2647
2648            // skeleton (listener template)
2649            if has_skel_exit {
2650                if let Some(alts) = &nt_contexts[fnt] {
2651                    let mut skel_ctx = vec![];
2652                    for &a_id in alts {
2653                        if let Some((_, variant)) = self.alt_info[a_id as usize].as_ref() {
2654                            let comment = self.full_alt_str(a_id, None, false);
2655                            let fields = self.source_infos(&self.item_info[a_id as usize], false, false);
2656                            let ctx_content = if fields.is_empty() {
2657                                String::new()
2658                            } else {
2659                                format!(" {{ {fields} }}")
2660                            };
2661                            skel_ctx.push((comment, variant, ctx_content));
2662                        }
2663                    }
2664                    match skel_ctx.len() {
2665                        0 => {}
2666                        1 => {
2667                            let (comment, variant, ctx_content) = skel_ctx.pop().unwrap();
2668                            src_skel.push(format!("        // {comment}"));
2669                            src_skel.push(format!("        let Ctx{fnu}::{variant}{ctx_content} = ctx;"));
2670                        }
2671                        _ => {
2672                            src_skel.push("        match ctx {".to_string());
2673                            for (comment, variant, ctx_content) in skel_ctx {
2674                                src_skel.push(format!("            // {comment}"));
2675                                src_skel.push(format!("            Ctx{fnu}::{variant}{ctx_content} => {{}}"));
2676                            }
2677                            src_skel.push("        }".to_string());
2678                        }
2679                    }
2680                    if has_skel_exit_return {
2681                        src_skel.push(format!("        {}()", self.get_nt_type(fnt as VarId)));
2682                    }
2683                    src_skel.push("    }".to_string());
2684                    src_skel.push(String::new());
2685                } else {
2686                    panic!("no alts for NT {fnpl} [{fnt}]");
2687                }
2688            }
2689
2690            for f in &exit_alts {
2691                exit_alt_done.insert(*f);
2692            }
2693            let inter_or_exit_name = if flags & ruleflag::PARENT_L_RECURSION != 0 { format!("inter_{npl}") } else { format!("exit_{npl}") };
2694            let fn_name = exit_fixer.get_unique_name(inter_or_exit_name.clone());
2695            let (is_alt_id, choices) = self.make_match_choices(&exit_alts, &fn_name, flags, no_method, None);
2696            if VERBOSE { println!("    choices: {}", choices.iter().map(|s| s.trim()).join(" ")); }
2697            let comments = exit_alts.iter().map(|f| {
2698                let (v, pf) = &self.parsing_table.alts[*f as usize];
2699                if MATCH_COMMENTS_SHOW_DESCRIPTIVE_ALTS {
2700                    format!("// {}", self.full_alt_str(*f, None, false))
2701                } else {
2702                    format!("// {}", pf.to_rule_str(*v, self.get_symbol_table(), self.parsing_table.flags[*v as usize]))
2703                }
2704            }).to_vec();
2705            src_exit.extend(choices.into_iter().zip(comments).map(|(a, b)| vec![a, b]));
2706            if is_ambig_1st_child {
2707                for (a_id, dup_alts) in ambig_op_alts.values().rev().filter_map(|v| if v.len() > 1 { v.split_first() } else { None }) {
2708                    // note: is_alt_id must be true because we wouldn't get duplicate alternatives otherwise in an ambiguous rule
2709                    //       (it's duplicated to manage the priority between several alternatives, which are all in the first NT)
2710                    let (_, choices) = self.make_match_choices(dup_alts, &fn_name, 0, no_method, Some(*a_id));
2711                    let comments = dup_alts.iter()
2712                        .map(|a| {
2713                            let (v, alt) = &pinfo.alts[*a as usize];
2714                            format!("// {} (duplicate of {a_id})", alt.to_rule_str(*v, self.get_symbol_table(), 0))
2715                        }).to_vec();
2716                    src_exit.extend(choices.into_iter().zip(comments).map(|(a, b)| vec![a, b]));
2717                    for a in dup_alts {
2718                        exit_alt_done.insert(*a);
2719                    }
2720                }
2721            }
2722            if !no_method {
2723                src_wrapper_impl.push(String::new());
2724                src_wrapper_impl.push(format!("    fn {fn_name}(&mut self{}) {{", if is_alt_id { ", alt_id: AltId" } else { "" }));
2725            }
2726            if flags & ruleflag::CHILD_REPEAT_LFORM == ruleflag::CHILD_REPEAT {
2727                if has_value {
2728                    let endpoints = self.child_repeat_endpoints.get(&var).unwrap();
2729                    let (src_val, val_name) = self.source_child_repeat_lets(endpoints, &self.item_info, is_plus, &self.nt_name, &fn_name, nu, false);
2730                    src_wrapper_impl.extend(src_val);
2731                    let vec_name = if is_plus { "plus_acc" } else { "star_acc" };
2732                    src_wrapper_impl.push(format!("        let Some(EnumSynValue::{nu}(Syn{nu}({vec_name}))) = self.stack.last_mut() else {{"));
2733                    src_wrapper_impl.push(format!("            panic!(\"expected Syn{nu} item on wrapper stack\");"));
2734                    src_wrapper_impl.push("        };".to_string());
2735                    src_wrapper_impl.push(format!("        {vec_name}.push({val_name});"));
2736                }
2737            } else {
2738                assert!(!no_method, "no_method is not expected here (only used in +* with no lform)");
2739                let (mut last_alt_ids, exit_info_alts): (Vec<AltId>, Vec<AltId>) = exit_alts.into_iter()
2740                    .partition(|i| self.alt_info[*i as usize].is_none());
2741                let fnu = if is_child_repeat_lform { nu } else { pnu }; // +* <L> use the loop variable, the other alternatives use the parent
2742                let fnpl = if is_child_repeat_lform { npl } else { pnpl }; // +* <L> use the loop variable, the other alternatives use the parent
2743                let a_has_value = if is_child_repeat_lform { has_value } else { parent_has_value };
2744                let is_single = exit_info_alts.len() == 1;
2745                let indent = if is_single { "        " } else { "                " };
2746                if !is_single {
2747                    if self.gen_span_params {
2748                        src_wrapper_impl.push("        let (n, ctx) = match alt_id {".to_string());
2749                    } else {
2750                        src_wrapper_impl.push("        let ctx = match alt_id {".to_string());
2751                    }
2752                }
2753                if VERBOSE { println!("    exit_alts -> {exit_info_alts:?}, last_alt_id -> {last_alt_ids:?}"); }
2754                let spans_param = if self.gen_span_params { ", spans" } else { "" };
2755                for a in exit_info_alts {
2756                    if VERBOSE {
2757                        println!("    - ALTERNATIVE {a}: {} -> {}",
2758                                 Symbol::NT(var).to_str(self.get_symbol_table()),
2759                                 self.parsing_table.alts[a as usize].1.to_str(self.get_symbol_table()));
2760                    }
2761                    let last_alt_id_maybe = if last_alt_ids.is_empty() { None } else { Some(last_alt_ids.remove(0)) };
2762                    if !is_single {
2763                        let last_alt_choice = if let Some(last_alt_id) = last_alt_id_maybe { format!(" | {last_alt_id}") } else { String::new() };
2764                        src_wrapper_impl.push(format!("            {a}{last_alt_choice} => {{", ));
2765                    }
2766                    let (src_let, ctx_params) = Self::source_lets(&self.item_info[a as usize], &self.nt_name, indent, last_alt_id_maybe);
2767                    src_wrapper_impl.extend(src_let);
2768                    let ctx = if ctx_params.is_empty() {
2769                        format!("Ctx{fnu}::{}", self.alt_info[a as usize].as_ref().unwrap().1)
2770                    } else {
2771                        format!("Ctx{fnu}::{} {{ {ctx_params} }}", self.alt_info[a as usize].as_ref().unwrap().1)
2772                    };
2773                    if is_single {
2774                        src_wrapper_impl.push(format!("        let ctx = {ctx};"));
2775                        if self.gen_span_params {
2776                            src_wrapper_impl.extend(Self::source_update_span(&self.span_nbrs[a as usize].to_string()));
2777
2778                        }
2779                    } else {
2780                        let ctx_value = self.gen_match_item(ctx, || self.span_nbrs[a as usize].to_string());
2781                        src_wrapper_impl.push(format!("{indent}{ctx_value}"));
2782                        src_wrapper_impl.push("            }".to_string());
2783                    }
2784                }
2785                if !is_single {
2786                    src_wrapper_impl.push(format!("            _ => panic!(\"unexpected alt id {{alt_id}} in fn {fn_name}\")"));
2787                    src_wrapper_impl.push("        };".to_string());
2788                    if self.gen_span_params {
2789                        src_wrapper_impl.extend(Self::source_update_span("n"));
2790                    }
2791                }
2792                if (is_rrec_lform | is_child_repeat_lform) && f_valued {
2793                    src_wrapper_impl.push(
2794                        format!("        let Some(EnumSynValue::{fnu}(acc)) = self.stack.last_mut() else {{ panic!() }};"));
2795                    src_wrapper_impl.push(
2796                        format!("        self.listener.exit_{fnpl}(acc, ctx{spans_param});"));
2797                } else {
2798                    src_wrapper_impl.push(format!(
2799                        "        {}self.listener.exit_{fnpl}(ctx{spans_param});",
2800                        if a_has_value { "let val = " } else { "" }));
2801                    if a_has_value {
2802                        src_wrapper_impl.push(format!("        self.stack.push(EnumSynValue::{fnu}(val));"));
2803                    }
2804                }
2805            }
2806            if !no_method {
2807                src_wrapper_impl.push("    }".to_string());
2808            }
2809            for a in last_it_alts {
2810                assert_eq!(flags, pinfo.flags[nt]);
2811                // optional exitloop_<NT> used by lrec and child_* <L> to post-process the accumulator
2812                // (rrec <L> and child_+ <L> don't need it because the context indicates the end alternative)
2813                let owner_maybe = if flags & ruleflag::CHILD_REPEAT_LFORM == ruleflag::CHILD_REPEAT_LFORM {
2814                    Some(var)
2815                } else if flags & ruleflag::CHILD_L_RECURSION != 0 {
2816                    pinfo.parent[nt]
2817                } else {
2818                    None
2819                };
2820                if let Some(owner) = owner_maybe {
2821                    if self.nt_value[owner as usize] {
2822                        let (variant, _, fnname) = &self.nt_name[owner as usize];
2823                        let typ = self.get_nt_type(owner);
2824                        let varname = if is_child_repeat_lform { "acc" } else { fnname };
2825                        if VERBOSE { println!("    exitloop{fnname}({varname}) owner = {}", Symbol::NT(owner).to_str(self.get_symbol_table())); }
2826                        src_listener_decl.push("    #[allow(unused_variables)]".to_string());
2827                        src_listener_decl.push(format!("    fn exitloop_{fnname}(&mut self, {varname}: &mut {typ}) {{}}"));
2828                        let (v, pf) = &self.parsing_table.alts[a as usize];
2829                        let alt_str = if MATCH_COMMENTS_SHOW_DESCRIPTIVE_ALTS {
2830                            self.full_alt_str(a, None, false)
2831                        } else {
2832                            pf.to_rule_str(*v, self.get_symbol_table(), self.parsing_table.flags[*v as usize])
2833                        };
2834                        src_exit.push(vec![format!("                    {a} => self.exitloop_{fnpl}(),"), format!("// {alt_str}")]);
2835                        exit_alt_done.insert(a);
2836                        src_wrapper_impl.push(String::new());
2837                        src_wrapper_impl.push(format!("    fn exitloop_{fnpl}(&mut self) {{"));
2838                        src_wrapper_impl.push(format!("        let EnumSynValue::{variant}({varname}) = self.stack.last_mut().unwrap(){};",
2839                                                      if syns.len() > 1 { " else { panic!() }" } else { "" }));
2840                        src_wrapper_impl.push(format!("        self.listener.exitloop_{fnname}({varname});"));
2841                        src_wrapper_impl.push("    }".to_string());
2842                    }
2843                }
2844            }
2845        }
2846    }
2847
2848    fn source_wrapper_finalize(&mut self, span_init: HashSet<VarId>, sources: WrapperSources) -> (Vec<String>, Vec<String>, Vec<String>) {
2849        let WrapperSources { mut src, src_listener_decl, mut src_skel, mut src_types, src_init, src_exit, src_wrapper_impl } = sources;
2850
2851        // Writes the listener trait declaration
2852        src.add_space();
2853        src.push(format!("pub trait {}Listener {{", self.name));
2854        src.push("    /// Checks if the listener requests an abort. This happens if an error is too difficult to recover from".to_string());
2855        src.push("    /// and may corrupt the stack content. In that case, the parser immediately stops and returns `ParserError::AbortRequest`.".to_string());
2856        src.push("    fn check_abort_request(&self) -> Terminate { Terminate::None }".to_string());
2857        src.push("    fn get_log_mut(&mut self) -> &mut impl Logger;".to_string());
2858        let extra_span = if self.gen_span_params { ", span: PosSpan" } else { "" };
2859        let extra_ref_span = if self.gen_span_params { ", span: &PosSpan" } else { "" };
2860        if !self.terminal_hooks.is_empty() {
2861            src.push("    #[allow(unused_variables)]".to_string());
2862            src.push(format!("    fn hook(&mut self, token: TokenId, text: &str{extra_ref_span}) -> TokenId {{ token }}"));
2863        }
2864        src.push("    #[allow(unused_variables)]".to_string());
2865        src.push(format!("    fn intercept_token(&mut self, token: TokenId, text: &str{extra_ref_span}) -> TokenId {{ token }}"));
2866        if self.nt_value[self.start as usize] || self.gen_span_params {
2867            src.push("    #[allow(unused_variables)]".to_string());
2868        }
2869        if self.nt_value[self.start as usize] {
2870            src.push(format!("    fn exit(&mut self, {}: {}{extra_span}) {{}}", self.nt_name[self.start as usize].2, self.get_nt_type(self.start)));
2871        } else {
2872            src.push(format!("    fn exit(&mut self{extra_span}) {{}}"));
2873        }
2874        src.push("    #[allow(unused_variables)]".to_string());
2875        src.push("    fn abort(&mut self, terminate: Terminate) {}".to_string());
2876        /*
2877                              fn init_a(&mut self) {}
2878                              fn exit_a(&mut self, ctx: CtxA, spans: Vec<PosSpan>) -> SynA;
2879                              fn init_a_iter(&mut self) -> SynAIter;
2880                              #[allow(unused_variables)]
2881                              fn exit_a_iter(&mut self, ctx: CtxAIter) -> SynAIter {};
2882        */
2883        src.extend(src_listener_decl);
2884        src.push("}".to_string());
2885
2886        // Writes the switch() function
2887        src.add_space();
2888        src.push("pub struct Wrapper<T> {".to_string());
2889        src.push("    verbose: bool,".to_string());
2890        src.push("    listener: T,".to_string());
2891        src.push("    stack: Vec<EnumSynValue>,".to_string());
2892        src.push("    max_stack: usize,".to_string());
2893        src.push("    stack_t: Vec<String>,".to_string());
2894        if self.gen_span_params {
2895            src.push("    stack_span: Vec<PosSpan>,".to_string());
2896        }
2897        src.push("}".to_string());
2898        src.push(String::new());
2899        src.push(format!("impl<T: {}Listener> ListenerWrapper for Wrapper<T> {{", self.name));
2900        src.push("    fn switch(&mut self, call: Call, nt: VarId, alt_id: AltId, t_data: Option<Vec<String>>) {".to_string());
2901        src.push("        if self.verbose {".to_string());
2902        src.push("            println!(\"switch: call={call:?}, nt={nt}, alt={alt_id}, t_data={t_data:?}\");".to_string());
2903        src.push("        }".to_string());
2904        src.push("        if let Some(mut t_data) = t_data {".to_string());
2905        src.push("            self.stack_t.append(&mut t_data);".to_string());
2906        src.push("        }".to_string());
2907        src.push("        match call {".to_string());
2908        src.push("            Call::Enter => {".to_string());
2909        if self.gen_span_params {
2910            // adds span accumulator inits, using Segments to regroup them
2911            let mut seg_span = Segments::from_iter(span_init.into_iter().map(|v| Seg(v as u32, v as u32)));
2912            seg_span.normalize();
2913            let pattern = seg_span.into_iter().map(|Seg(a, b)| {
2914                if a == b {
2915                    a.to_string()
2916                } else if b == a + 1 {
2917                    format!("{a} | {b}")
2918                } else {
2919                    format!("{a} ..= {b}")
2920                }
2921            }).join(" | ");
2922            if !pattern.is_empty() {
2923                src.push(format!("                if matches!(nt, {pattern}) {{"));
2924                src.push("                    self.stack_span.push(PosSpan::empty());".to_string());
2925                src.push("                }".to_string());
2926            }
2927        }
2928        src.push("                match nt {".to_string());
2929        /*
2930                                              0 => self.listener.init_a(),                // A
2931                                              1 => self.init_a_iter(),                    // AIter1
2932                                              2 => {}                                     // A_1
2933        */
2934        src.extend(columns_to_str(src_init, Some(vec![64, 0])));
2935        src.push("                    _ => panic!(\"unexpected enter nonterminal id: {nt}\")".to_string());
2936        src.push("                }".to_string());
2937        src.push("            }".to_string());
2938        src.push("            Call::Loop => {}".to_string());
2939        src.push("            Call::Exit => {".to_string());
2940        src.push("                match alt_id {".to_string());
2941        /*
2942                                              3 |                                         // A -> a a (b <L>)* c
2943                                              4 => self.exit_a(alt_id),                   // A -> a c (b <L>)* c
2944                                              1 => self.exit_a_iter(),                    // (b <L>)* iteration in A -> a a  ► (b <L>)* ◄  c | ...
2945                                              2 => {}                                     // end of (b <L>)* iterations in A -> a a  ► (b <L>)* ◄  c | ...
2946                                           /* 0 */                                        // A -> a a (b <L>)* c | a c (b <L>)* c (never called)
2947        */
2948        src.extend(columns_to_str(src_exit, Some(vec![64, 0])));
2949        src.push("                    _ => panic!(\"unexpected exit alternative id: {alt_id}\")".to_string());
2950        src.push("                }".to_string());
2951        src.push("            }".to_string());
2952        src.push("            Call::End(terminate) => {".to_string());
2953        src.push("                match terminate {".to_string());
2954        src.push("                    Terminate::None => {".to_string());
2955        let mut args = vec![];
2956        let (_nu, _nl, npl) = &self.nt_name[self.start as usize];
2957        if self.nt_value[self.start as usize] {
2958            src.push(format!("                        let val = self.stack.pop().unwrap().get_{npl}();"));
2959            args.push("val");
2960        }
2961        if self.gen_span_params {
2962            src.push("                        let span = self.stack_span.pop().unwrap();".to_string());
2963            args.push("span");
2964        }
2965        src.push(format!("                        self.listener.exit({});", args.join(", ")));
2966        src.push("                    }".to_string());
2967        src.push("                    Terminate::Abort | Terminate::Conclude => self.listener.abort(terminate),".to_string());
2968        src.push("                }".to_string());
2969        src.push("            }".to_string());
2970        src.push("        }".to_string());
2971        src.push("        self.max_stack = std::cmp::max(self.max_stack, self.stack.len());".to_string());
2972        src.push("        if self.verbose {".to_string());
2973        src.push("            println!(\"> stack_t:   {}\", self.stack_t.join(\", \"));".to_string());
2974        src.push("            println!(\"> stack:     {}\", self.stack.iter().map(|it| format!(\"{it:?}\")).collect::<Vec<_>>().join(\", \"));".to_string());
2975        src.push("        }".to_string());
2976        src.push("    }".to_string());
2977        src.push(String::new());
2978        src.push("    fn check_abort_request(&self) -> Terminate {".to_string());
2979        src.push("        self.listener.check_abort_request()".to_string());
2980        src.push("    }".to_string());
2981        src.push(String::new());
2982        src.push("    fn abort(&mut self) {".to_string());
2983        src.push("        self.stack.clear();".to_string());
2984        if self.gen_span_params {
2985            src.push("        self.stack_span.clear();".to_string());
2986        }
2987        src.push("        self.stack_t.clear();".to_string());
2988        src.push("    }".to_string());
2989        src.push(String::new());
2990        src.push("    fn get_log_mut(&mut self) -> &mut impl Logger {".to_string());
2991        src.push("        self.listener.get_log_mut()".to_string());
2992        src.push("    }".to_string());
2993        if self.gen_span_params {
2994            src.push(String::new());
2995            src.push("    fn push_span(&mut self, span: PosSpan) {".to_string());
2996            src.push("        self.stack_span.push(span);".to_string());
2997            src.push("    }".to_string());
2998        }
2999        src.push(String::new());
3000        src.push("    fn is_stack_empty(&self) -> bool {".to_string());
3001        src.push("        self.stack.is_empty()".to_string());
3002        src.push("    }".to_string());
3003        src.push(String::new());
3004        src.push("    fn is_stack_t_empty(&self) -> bool {".to_string());
3005        src.push("        self.stack_t.is_empty()".to_string());
3006        src.push("    }".to_string());
3007        if self.gen_span_params {
3008            src.add_space();
3009            src.push("    fn is_stack_span_empty(&self) -> bool {".to_string());
3010            src.push("        self.stack_span.is_empty()".to_string());
3011            src.push("    }".to_string());
3012        }
3013        let unused_span = if self.gen_span_params { "" } else { "_" };
3014        let extra_span_arg = if self.gen_span_params { ", span" } else { "" };
3015        if !self.terminal_hooks.is_empty() {
3016            src.add_space();
3017            src.push(format!("    fn hook(&mut self, token: TokenId, text: &str, {unused_span}span: &PosSpan) -> TokenId {{"));
3018            src.push(format!("        self.listener.hook(token, text{extra_span_arg})"));
3019            src.push("    }".to_string());
3020        }
3021        src.add_space();
3022        src.push(format!("    fn intercept_token(&mut self, token: TokenId, text: &str, {unused_span}span: &PosSpan) -> TokenId {{"));
3023        src.push(format!("        self.listener.intercept_token(token, text{extra_span_arg})"));
3024        src.push("    }".to_string());
3025        src.push("}".to_string());
3026
3027        src.add_space();
3028        src.push(format!("impl<T: {}Listener> Wrapper<T> {{", self.name));
3029        src.push("    pub fn new(listener: T, verbose: bool) -> Self {".to_string());
3030        src.push(format!(
3031            "        Wrapper {{ verbose, listener, stack: Vec::new(), max_stack: 0, stack_t: Vec::new(){} }}",
3032            if self.gen_span_params { ", stack_span: Vec::new()" } else { "" }
3033        ));
3034        src.push("    }".to_string());
3035        src.push(String::new());
3036        src.push("    pub fn get_listener(&self) -> &T {".to_string());
3037        src.push("        &self.listener".to_string());
3038        src.push("    }".to_string());
3039        src.push(String::new());
3040        src.push("    pub fn get_listener_mut(&mut self) -> &mut T {".to_string());
3041        src.push("        &mut self.listener".to_string());
3042        src.push("    }".to_string());
3043        src.push(String::new());
3044        src.push("    pub fn give_listener(self) -> T {".to_string());
3045        src.push("        self.listener".to_string());
3046        src.push("    }".to_string());
3047        src.push(String::new());
3048        src.push("    pub fn set_verbose(&mut self, verbose: bool) {".to_string());
3049        src.push("        self.verbose = verbose;".to_string());
3050        src.push("    }".to_string());
3051/*
3052                              impl<T: TestListener> ListenerWrapper<T> {
3053                                  fn exit(&mut self) {
3054                                      let a = self.stack.pop().unwrap().get_a();
3055                                      self.listener.exit(Ctx::A { a });
3056                                  }
3057                                  fn init_a_iter(&mut self) {
3058                                      let val = self.listener.init_a_iter();
3059                                      self.stack.push(EnumSynValue::AIter(val));
3060                                  }
3061                                  fn exit_a_iter(&mut self) {
3062                                      let b = self.stack_t.pop().unwrap();
3063                                      let star_acc = self.stack.pop().unwrap().get_a_iter();
3064                                      let val = self.listener.exit_a_iter(CtxAIter::Aiter1 { star_acc, b });
3065                                      self.stack.push(EnumSynValue::AIter(val));
3066                                  }
3067                                  // ...
3068                              }
3069*/
3070        src.extend(src_wrapper_impl);
3071        src.push("}".to_string());
3072
3073        // templates
3074        src_types.extend(vec![
3075            String::new(),
3076            format!("// {:-<80}", ""),
3077        ]);
3078        if let Some(line) = src_skel.last() {
3079            if line.is_empty() {
3080                src_skel.pop();
3081            }
3082        }
3083        src_skel.extend(vec![
3084            "}".to_string(),
3085            String::new(),
3086            format!("// {:-<80}", ""),
3087        ]);
3088        self.log.add_info(format!("Template for the user types:\n\n{}\n", src_types.join("\n")));
3089        self.log.add_info(format!("Template for the listener implementation:\n\n{}\n", src_skel.join("\n")));
3090
3091        (src, src_types, src_skel)
3092    }
3093}
3094
3095impl LogReader for ParserGen {
3096    type Item = BufLog;
3097
3098    fn get_log(&self) -> &Self::Item {
3099        &self.log
3100    }
3101
3102    fn give_log(self) -> Self::Item {
3103        self.log
3104    }
3105}
3106
3107impl HasBuildErrorSource for ParserGen {
3108    const SOURCE: BuildErrorSource = BuildErrorSource::ParserGen;
3109}
3110
3111impl<T> BuildFrom<ProdRuleSet<T>> for ParserGen where ProdRuleSet<LL1>: BuildFrom<ProdRuleSet<T>> {
3112    /// Creates a [`ParserGen`] from a set of production rules.
3113    ///
3114    /// If the rule set has a name, it's transmitted to the parser generator to name the user
3115    /// listener trait in the generated code. If the rule set has no name, a default "Parser" name
3116    /// is used instead (unless the name is set with [`ParserGen::set_name()`].
3117    fn build_from(mut rules: ProdRuleSet<T>) -> Self {
3118        let name = rules.name.take().unwrap_or(DEFAULT_LISTENER_NAME.to_string());
3119        ParserGen::build_from_rules(rules, name)
3120    }
3121}
3122
3123// ---------------------------------------------------------------------------------------------
3124// Supporting functions
3125
3126impl ParserGen {
3127
3128    pub fn get_nt_tree(&self) -> VecTree<VarId> {
3129        let mut tree = VecTree::new();
3130        let root = tree.add_root(0);
3131        let mut idx = HashMap::new();
3132        for group in self.nt_parent.iter().filter(|vf| !vf.is_empty()) {
3133            idx.clear();
3134            // some parents are later in the group, so we can't do this:
3135            // for &c in group {
3136            //     let idx_parent = self.parsing_table
3137            //         .parent[c as usize]
3138            //         .map(|v| idx.get(&v).unwrap())
3139            //         .unwrap_or(&root);
3140            //     let idx_c = tree.add(Some(*idx_parent), c);
3141            //     idx.insert(c, idx_c);
3142            // }
3143            let tree_ids = tree.add_iter(None, group.iter().cloned()).to_vec();
3144            idx.extend(group.iter().zip(tree_ids));
3145            for &child in group.iter() {
3146                tree.attach_child(
3147                    self.parsing_table.parent[child as usize]
3148                        .map(|p| idx[&p])
3149                        .unwrap_or(root),
3150                    idx[&child]);
3151            }
3152        }
3153        tree
3154    }
3155
3156    pub fn get_indented_nt(&self) -> Vec<(VarId, String)>{
3157        let tree = self.get_nt_tree();
3158        let mut indented = vec![];
3159        let mut indent = vec![];
3160        for node in tree.iter_pre_depth_simple().skip(1) {
3161            let depth = node.depth as usize;
3162            if indent.len() < depth {
3163                indent.push((1..depth).map(|i| if i & 1 == 0 { "  " } else { ". " }).join(""));
3164            }
3165            indented.push((*node, format!("{}{}", &indent[depth - 1], Symbol::NT(*node).to_str(self.get_symbol_table()))));
3166        }
3167        indented
3168    }
3169
3170    pub fn nt_info_str(&self) -> Vec<String> {
3171        let indented = self.get_indented_nt();
3172        let mut cols = vec![
3173            vec!["  NT".to_string(), "  name".to_string(), " val".to_string(), /*"  parent".to_string(),*/ "  flags".to_string(), String::new()]];
3174        for (v, line) in indented {
3175            let nt = v as usize;
3176            // let parent = self.parsing_table.parent[nt].map(|p| Symbol::NT(p).to_str(self.get_symbol_table())).unwrap_or_else(||String::new());
3177            cols.push(vec![
3178                format!("| {v:3}"),
3179                format!("| {line}"),
3180                if self.nt_value[nt] { "| y".to_string() } else { "|".to_string() },
3181                // format!("| {parent}"),
3182                format!("| {}", ruleflag::to_string(self.parsing_table.flags[nt]).join(", ")),
3183                "|".to_string(),
3184            ]);
3185        }
3186        let mut txt = columns_to_str(cols, Some(vec![3, 5, 0, /*0,*/ 0, 0]));
3187        if let Some(max) = txt.get(1).map(|s| s.charlen()) {
3188            let sep = format!("+{:-<1$}+", "", max - 2);
3189            txt.insert(1, sep.clone());
3190            txt.push(sep);
3191        }
3192        txt
3193    }
3194
3195    pub fn log_nt_info(&mut self) {
3196        let mut txt = self.nt_info_str();
3197        txt.push(String::new());
3198        self.log.add_info("nonterminal information:");
3199        self.log.extend_messages(txt.into_iter().map(LogMsg::Info));
3200    }
3201
3202    pub fn alt_info_str(&self) -> Vec<String> {
3203        let indented = self.get_indented_nt();
3204        let mut cols = vec![
3205            vec!["  NT".to_string(), "  alt".to_string(), "  opcodes".to_string(), " spans".to_string(), "  item_ops".to_string(), String::new()]];
3206        for (v, line) in indented {
3207            let nt = v as usize;
3208            for &alt_id in &self.var_alts[nt] {
3209                let a_id = alt_id as usize;
3210                let alt = &self.parsing_table.alts[a_id].1;
3211                let opcodes = self.opcodes[a_id].iter().map(|o| o.to_str_quote(self.get_symbol_table())).join(" ");
3212                let item_ops = self.item_ops.get(a_id)
3213                    .map(|ops| ops.iter().map(|s| s.to_str(self.get_symbol_table())).join(" "))
3214                    .unwrap_or_else(|| "-".to_string());
3215                cols.push(vec![
3216                    format!("| {v:3}"),
3217                    format!("| {alt_id:4}: {line} -> {}", alt.to_str(self.get_symbol_table())),
3218                    format!("| {opcodes}"),
3219                    format!("| {}{}",
3220                        &self.span_nbrs[a_id],
3221                        if let Some(ispan) = self.span_nbrs_sep_list.get(&alt_id) { format!(", {ispan}") } else { String::new() }),
3222                    format!("| {item_ops}"),
3223                    "|".to_string(),
3224                ]);
3225            }
3226        }
3227        let mut txt = columns_to_str(cols, Some(vec![3, 5, 0, 0, 0, 0]));
3228        if let Some(max) = txt.get(1).map(|s| s.charlen()) {
3229            let sep = format!("+{:-<1$}+", "", max - 2);
3230            txt.insert(1, sep.clone());
3231            txt.push(sep);
3232        }
3233        txt
3234    }
3235
3236    pub fn log_alt_info(&mut self) {
3237        let mut txt = self.alt_info_str();
3238        txt.push("legend: ►nt = enter nonterminal nt, ◄0 = exit alt, ●nt = loop nonterminal, Xyz! = variable terminal, \"…\" = fixed terminal, ▲ = hook".to_string());
3239        txt.push(String::new());
3240        self.log.add_note("rule alternatives:");
3241        self.log.extend_messages(txt.into_iter().map(LogMsg::Info));
3242    }
3243
3244    pub fn print_items(&self, indent: usize, show_symbols: bool, show_span: bool) {
3245        let tbl = self.get_symbol_table();
3246        let fields = (0..self.parsing_table.alts.len())
3247            .map(|a| {
3248                let a_id = a as AltId;
3249                let (v, alt) = &self.parsing_table.alts[a];
3250                let ops = &self.opcodes[a];
3251                let it = &self.item_ops[a_id as usize];
3252                let mut cols = vec![];
3253                if show_symbols {
3254                    let symbols = format!("symbols![{}]", it.iter().map(|s| s.to_macro_item()).join(", "));
3255                    let value = if show_span {
3256                        assert!(self.gen_span_params, "ParserGen is not configured for spans");
3257                        format!("({}, {symbols})", self.span_nbrs[a_id as usize])
3258                    } else {
3259                        symbols
3260                    };
3261                    cols.push(format!("{a_id} => {value},"));
3262                }
3263                cols.extend([
3264                    format!("// {a_id:2}: {} -> {}", Symbol::NT(*v).to_str(tbl), alt.iter().map(|s| s.to_str_quote(tbl)).join(" ")),
3265                    format!("| {}", ops.iter().map(|s| s.to_str_quote(tbl)).join(" ")),
3266                    format!(
3267                        "| {}{}",
3268                        &self.span_nbrs[a_id as usize],
3269                        if let Some(ispan) = self.span_nbrs_sep_list.get(&a_id) { format!(", {ispan}") } else { String::new() }),
3270                    format!("| {}", it.iter().map(|s| s.to_str(tbl)).join(" ")),
3271                ]);
3272                cols
3273            }).to_vec();
3274        let widths = if show_symbols { vec![40, 0, 0, 0, 0] } else { vec![16, 0, 0, 0, 0] };
3275        for l in columns_to_str(fields, Some(widths)) {
3276            println!("{:indent$}{l}", "", indent = indent)
3277        }
3278    }
3279
3280    pub fn print_flags(&self, indent: usize) {
3281        let tbl: Option<&SymbolTable> = self.get_symbol_table();
3282        let prefix = format!("{:width$}//", "", width = indent);
3283        let nt_flags = self.get_parsing_table().flags.iter().index().filter_map(|(nt, &f)|
3284            if f != 0 { Some(format!("{prefix}  - {}: {} ({})", Symbol::NT(nt).to_str(tbl), ruleflag::to_string(f).join(" | "), f)) } else { None }
3285        ).join("\n");
3286        let parents = self.get_parsing_table().parent.iter().index().filter_map(|(c, &par)|
3287            par.map(|p| format!("{prefix}  - {} -> {}", Symbol::NT(c).to_str(tbl), Symbol::NT(p).to_str(tbl)))
3288        ).join("\n");
3289        if !nt_flags.is_empty() {
3290            println!("{prefix} NT flags:\n{nt_flags}");
3291        }
3292        if !parents.is_empty() {
3293            println!("{prefix} parents:\n{parents}");
3294        }
3295    }
3296}