1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
use crate::analysis::lookahead_dfa::ProductionIndex;
use crate::errors::*;
use crate::generate_name;
use crate::parser::{
    Alternation, Alternations, Factor, ParolGrammar, ParolGrammarItem, Production,
};
use crate::utils::combine;
use crate::{Cfg, GrammarConfig, Pr, Symbol};
use std::convert::TryFrom;

pub fn try_to_convert(parol_grammar: ParolGrammar) -> Result<GrammarConfig> {
    let st = parol_grammar.start_symbol;
    let pr = transform_productions(parol_grammar.ast_stack)?;
    let cfg = Cfg { st, pr };
    let title = parol_grammar.title;
    let comment = parol_grammar.comment;
    let line_comments = parol_grammar.line_comments;
    let block_comments = parol_grammar.block_comments;
    let lookahead_size = 1; // Updated later

    Ok(GrammarConfig::new(
        cfg,
        title,
        comment,
        line_comments,
        block_comments,
        lookahead_size,
    ))
}

pub fn try_from_factor(factor: Factor) -> Result<Symbol> {
    match factor {
        Factor::NonTerminal(n) => Ok(Symbol::n(&n)),
        Factor::Terminal(t) => Ok(Symbol::t(&t)),
        _ => Err(format!("Unexpected type of factor: {}", factor).into()),
    }
}

fn transform_productions(ast_stack: Vec<ParolGrammarItem>) -> Result<Vec<Pr>> {
    if !ast_stack
        .iter()
        .all(|i| matches!(i, ParolGrammarItem::Prod(_)))
    {
        return Err("Expecting only productions on user stack".into());
    }

    let productions = ast_stack
        .into_iter()
        .map(|i| match i {
            ParolGrammarItem::Prod(p) => p,
            _ => panic!("Can't happen"),
        })
        .collect::<Vec<Production>>();

    transform(productions)
}

struct TransformationOperand {
    modified: bool,
    productions: Vec<Production>,
}

fn finalize(productions: Vec<Production>) -> Result<Vec<Pr>> {
    productions
        .into_iter()
        .map(|r| {
            let Alternations(mut e) = r.rhs;
            if e.len() > 1 {
                return Err(
                    "Expected exactly one alternative per production after transformation!".into(),
                );
            }
            let single_alternative = e.pop().unwrap();
            Ok(Pr(
                Symbol::N(r.lhs),
                if single_alternative.0.is_empty() {
                    vec![]
                } else {
                    let prod: Result<Vec<Symbol>> =
                        single_alternative
                            .0
                            .into_iter()
                            .try_fold(Vec::new(), |mut acc, f| {
                                let s = Symbol::try_from(f)?;
                                acc.push(s);
                                Ok(acc)
                            });
                    prod?
                },
            ))
        })
        .collect()
}

fn variable_names(productions: &[Production]) -> Vec<String> {
    let mut productions_vars = productions.iter().fold(vec![], |mut res, r| {
        let variable = &r.lhs;
        res.push(variable.clone());
        let mut alternation_vars = r.rhs.0.iter().fold(vec![], |mut res, a| {
            let mut factors_vars = a.0.iter().fold(vec![], |mut res, f| {
                if let Factor::NonTerminal(n) = f {
                    res.push(n.clone());
                }
                res
            });
            res.append(&mut factors_vars);
            res
        });
        res.append(&mut alternation_vars);
        res
    });
    productions_vars.sort();
    productions_vars.dedup();
    productions_vars
}

/// Substitutes the production on 'index' in the vector of productions with the result of the transformation
fn apply_production_transformation(
    productions: &mut Vec<Production>,
    index: usize,
    trans: impl Fn(Production) -> Vec<Production>,
) {
    let production_to_substitute = productions.remove(index);
    let mut substitutes = trans(production_to_substitute);
    productions.reserve(substitutes.len());
    for i in index..(index + substitutes.len()) {
        productions.insert(i, substitutes.remove(0));
    }
}

fn find_production_with_factor(
    productions: &[Production],
    pred: impl Fn(&Factor) -> bool,
) -> Option<(ProductionIndex, usize)> {
    let production_index = productions.iter().position(|r| {
        let Alternations(e) = &r.rhs;
        e.iter().any(|r| r.0.iter().any(|r| pred(r)))
    });
    if let Some(production_index) = production_index {
        let Alternations(e) = &productions[production_index].rhs;
        Some((
            production_index,
            e.iter().position(|r| r.0.iter().any(|r| pred(r))).unwrap(),
        ))
    } else {
        None
    }
}

/// Transform productions with multiple alternatives
fn separate_alternatives(opd: TransformationOperand) -> TransformationOperand {
    fn production_has_multiple_alts(r: &Production) -> bool {
        let Alternations(e) = &r.rhs;
        e.len() > 1
    }

    /// -------------------------------------------------------------------------
    /// Replace the given production with multiple alternatives by a list of new productions.
    /// -------------------------------------------------------------------------
    fn separate_production_with_multiple_alts(r: Production) -> Vec<Production> {
        let Production { lhs, rhs } = r;
        let Alternations(e) = rhs;

        e.into_iter()
            .map(|a| Production {
                lhs: lhs.clone(),
                rhs: Alternations(vec![a]),
            })
            .collect::<Vec<Production>>()
    }

    fn separate_single_production(productions: &mut Vec<Production>) -> bool {
        let candidate_index = productions
            .iter()
            .position(|r| production_has_multiple_alts(r));
        if let Some(index) = candidate_index {
            apply_production_transformation(
                productions,
                index,
                separate_production_with_multiple_alts,
            );
            true
        } else {
            false
        }
    }

    let mut modified = opd.modified;
    let mut productions = opd.productions;

    while separate_single_production(&mut productions) {
        modified |= true;
    }

    TransformationOperand {
        modified,
        productions,
    }
}

// Eliminate repetitions
fn eliminate_repetitions(opd: TransformationOperand) -> TransformationOperand {
    fn find_production_with_repetition(
        productions: &[Production],
    ) -> Option<(ProductionIndex, usize)> {
        find_production_with_factor(productions, |f| matches!(f, Factor::Repeat(_)))
    }
    /// -------------------------------------------------------------------------
    /// Replace the first Factor that is a R with a non-left-recursive substitution.
    /// -------------------------------------------------------------------------
    /// R  -> x { a } y
    /// =>
    /// R  -> x R' y     (1)
    /// R  -> x y        (1a)
    /// R' -> (a) R'     (2)
    /// R' -> (a)        (2a)
    fn eliminate_single_rep(
        exclusions: &[String],
        alt_index: usize,
        production: Production,
    ) -> Vec<Production> {
        let mut r = production;
        let production_name = r.lhs.clone();
        if let Some(index) = r.rhs.0[alt_index]
            .0
            .iter()
            .position(|f| matches!(f, Factor::Repeat(_)))
        {
            let r_tick_name = generate_name(exclusions, production_name + "Rest");
            if let Factor::Repeat(repeat) = r.rhs.0[alt_index].0[index].clone() {
                r.rhs.0[alt_index].0[index] = Factor::NonTerminal(r_tick_name.clone());
                let production1 = r;
                let mut production1a = production1.clone();
                production1a.rhs.0[0].0.remove(index);

                let production2 = Production {
                    lhs: r_tick_name.clone(),
                    rhs: Alternations(vec![Alternation(if repeat.0.len() == 1 {
                        let mut fs = repeat.0[0].0.clone();
                        fs.push(Factor::NonTerminal(r_tick_name));
                        fs
                    } else {
                        vec![Factor::Group(repeat), Factor::NonTerminal(r_tick_name)]
                    })]),
                };
                let mut production2a = production2.clone();
                production2a.rhs.0[0].0.pop();

                vec![production1, production1a, production2, production2a]
            } else {
                panic!("Expected Factor::Repeat!");
            }
        } else {
            vec![r]
        }
    }
    fn eliminate_repetition(productions: &mut Vec<Production>) -> bool {
        if let Some((production_index, alt_index)) = find_production_with_repetition(productions) {
            let exclusions = variable_names(productions);
            apply_production_transformation(productions, production_index, |r| {
                eliminate_single_rep(&exclusions, alt_index, r)
            });
            true
        } else {
            false
        }
    }

    let mut modified = opd.modified;
    let mut productions = opd.productions;

    while eliminate_repetition(&mut productions) {
        modified |= true;
    }
    TransformationOperand {
        modified,
        productions,
    }
}

fn eliminate_options(opd: TransformationOperand) -> TransformationOperand {
    fn find_production_with_optional(
        productions: &[Production],
    ) -> Option<(ProductionIndex, usize)> {
        find_production_with_factor(productions, |f| matches!(f, Factor::Optional(_)))
    }
    /// -------------------------------------------------------------------------
    /// Replace the first Factor that is an O with new productions.
    /// -------------------------------------------------------------------------
    /// R  -> x [ a ] y.
    /// =>
    /// R  -> x R' y.    (1)
    /// R  -> x y.       (1a)
    /// R' -> (a).       (2)
    fn eliminate_single_opt(
        exclusions: &[String],
        alt_index: usize,
        production: Production,
    ) -> Vec<Production> {
        let mut r = production;
        let production_name = r.lhs.clone();
        if let Some(index) = r.rhs.0[alt_index]
            .0
            .iter()
            .position(|f| matches!(f, Factor::Optional(_)))
        {
            let r_tick_name = generate_name(exclusions, production_name + "Opt");
            if let Factor::Optional(optional) = r.rhs.0[alt_index].0[index].clone() {
                r.rhs.0[alt_index].0[index] = Factor::NonTerminal(r_tick_name.clone());
                let production1 = r;
                let mut production1a = production1.clone();
                production1a.rhs.0[0].0.remove(index);

                let production2 = Production {
                    lhs: r_tick_name,
                    rhs: Alternations(vec![Alternation(if optional.0.len() == 1 {
                        optional.0[0].0.clone()
                    } else {
                        vec![Factor::Group(optional)]
                    })]),
                };

                vec![production1, production1a, production2]
            } else {
                panic!("Expected Factor::Optional!");
            }
        } else {
            vec![r]
        }
    }
    fn eliminate_option(productions: &mut Vec<Production>) -> bool {
        if let Some((production_index, alt_index)) = find_production_with_optional(productions) {
            let exclusions = variable_names(productions);
            apply_production_transformation(productions, production_index, |r| {
                eliminate_single_opt(&exclusions, alt_index, r)
            });
            true
        } else {
            false
        }
    }

    let mut modified = opd.modified;
    let mut productions = opd.productions;

    while eliminate_option(&mut productions) {
        modified |= true;
    }
    TransformationOperand {
        modified,
        productions,
    }
}

fn eliminate_groups(opd: TransformationOperand) -> TransformationOperand {
    fn find_production_with_group(productions: &[Production]) -> Option<(ProductionIndex, usize)> {
        find_production_with_factor(productions, |f| matches!(f, Factor::Group(_)))
    }
    /// -------------------------------------------------------------------------
    /// Replace the first Factor that is a G with new productions.
    /// -------------------------------------------------------------------------
    /// Case 1: Iff g is only of size 1
    /// R  -> x ( g ) y.
    /// =>
    /// R  -> x g y.     (1)
    /// Case 2: Otherwise
    /// R  -> x ( g ) y.
    /// =>
    /// R  -> x G y.     (1)
    /// G  -> g.         (2)
    fn eliminate_single_grp(
        exclusions: &[String],
        alt_index: usize,
        production: Production,
    ) -> Vec<Production> {
        let mut r = production;
        let production_name = r.lhs.clone();
        if let Some(index) = r.rhs.0[alt_index]
            .0
            .iter()
            .position(|f| matches!(f, Factor::Group(_)))
        {
            if let Factor::Group(alts) = r.rhs.0[alt_index].0[index].clone() {
                if alts.0.len() == 1 && alts.0[0].0.len() == 1 {
                    // Case 1
                    r.rhs.0[alt_index].0[index] = alts.0[0].0[0].clone();
                    vec![r]
                } else {
                    // Case 2
                    let g_name = generate_name(exclusions, production_name + "Group");
                    if let Factor::Group(group) = r.rhs.0[alt_index].0[index].clone() {
                        r.rhs.0[alt_index].0[index] = Factor::NonTerminal(g_name.clone());
                        let production1 = r;
                        let production2 = Production {
                            lhs: g_name,
                            rhs: group,
                        };

                        vec![production1, production2]
                    } else {
                        panic!("Expected Factor::Group!");
                    }
                }
            } else {
                panic!("Expected Group here");
            }
        } else {
            vec![r]
        }
    }
    fn eliminate_group(productions: &mut Vec<Production>) -> bool {
        if let Some((production_index, alt_index)) = find_production_with_group(productions) {
            let exclusions = variable_names(productions);
            apply_production_transformation(productions, production_index, |r| {
                eliminate_single_grp(&exclusions, alt_index, r)
            });
            true
        } else {
            false
        }
    }

    let mut modified = opd.modified;
    let mut productions = opd.productions;

    while eliminate_group(&mut productions) {
        modified |= true;
    }
    TransformationOperand {
        modified,
        productions,
    }
}

fn eliminate_duplicates(opd: TransformationOperand) -> TransformationOperand {
    fn find_productions_with_same_rhs(
        productions: &[Production],
    ) -> Option<(ProductionIndex, ProductionIndex)> {
        for i in 0..productions.len() {
            for j in 0..productions.len() {
                if i != j && productions[i].rhs == productions[j].rhs {
                    let (i, j) = if i < j { (i, j) } else { (j, i) };
                    let first = &productions[i].lhs;
                    let duplicate = &productions[j].lhs;
                    if productions.iter().filter(|pr| &pr.lhs == first).count() == 1
                        && productions.iter().filter(|pr| &pr.lhs == duplicate).count() == 1
                    {
                        return Some((i, j));
                    }
                }
            }
        }
        None
    }
    /// -------------------------------------------------------------------------
    /// Replace the all occurrences of the LHS of the second production within
    /// all productions RHS.
    /// Then Remove the second production.
    /// -------------------------------------------------------------------------
    fn eliminate_single_duplicate(
        productions: &mut Vec<Production>,
        production_index_1: ProductionIndex,
        production_index_2: ProductionIndex,
    ) {
        let to_find = productions[production_index_2].lhs.clone();
        let replace_with = productions[production_index_1].lhs.clone();

        #[allow(clippy::needless_range_loop)]
        for pi in 0..productions.len() {
            if pi != production_index_2 {
                let pr = &mut productions[pi];
                debug_assert!(pr.rhs.0.len() == 1, "Only one single Alternation expected!");
                for s in &mut pr.rhs.0[0].0 {
                    if let Factor::NonTerminal(n) = s {
                        if n == &to_find {
                            *s = Factor::NonTerminal(replace_with.clone());
                        }
                    }
                }
            }
        }

        productions.remove(production_index_2);
    }
    fn eliminate_duplicate(productions: &mut Vec<Production>) -> bool {
        if let Some((production_index_1, production_index_2)) =
            find_productions_with_same_rhs(productions)
        {
            eliminate_single_duplicate(productions, production_index_1, production_index_2);
            true
        } else {
            false
        }
    }

    let mut modified = opd.modified;
    let mut productions = opd.productions;

    while eliminate_duplicate(&mut productions) {
        modified |= true;
    }
    TransformationOperand {
        modified,
        productions,
    }
}

/// -------------------------------------------------------------------------
/// Guidelines:
/// After applying all transformation inner (sub-) expressions should be factored out.
/// The grammar's structure should be 'linear' then (i.e no loops like in {}).
/// The input order should be preserved as much as possible.
/// -------------------------------------------------------------------------
fn transform(productions: Vec<Production>) -> Result<Vec<Pr>> {
    let mut operand = TransformationOperand {
        modified: true,
        productions,
    };
    let trans_fn = combine(
        combine(
            combine(separate_alternatives, eliminate_repetitions),
            eliminate_options,
        ),
        eliminate_groups,
    );

    while operand.modified {
        operand.modified = false;
        operand = trans_fn(operand);
    }

    operand.modified = true;
    while operand.modified {
        operand.modified = false;
        operand = eliminate_duplicates(operand);
    }

    finalize(operand.productions)
}