mo 0.1.0

Create dozens/hundreds/thousands/millions of random examples based on a pest grammar (PEG). It can be used for generate string/structured data for training models in AI, or like a grammar fuzzer for find bugs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
use crate::compile_grammar;
use crate::config::GeneratorConfig;
use crate::parse_input;

use pest_meta::ast::{Expr, Rule as AstRule};
use rand::prelude::*;
use regex::Regex;
use std::collections::HashMap;

#[derive(Clone, Debug)]
pub struct Grammar {
    pub rules: HashMap<String, AstRule>,
}

/// Estructura interna usada para almacenar los datos que se van a procesar por el algoritmo
/// gramática original, y gramática preprocesada para evitar conflictos con pest
#[derive(Clone, Debug)]
pub struct InputData {
    /// Gramática original ingresada por el usuario
    grammar: Grammar,
    /// Gramática limpia (sin blacklist), para otras operaciones con pest
    clean_grammar: Grammar,
}

impl InputData {
    pub fn new(grammar: String) -> Self {
        let (grammar, clean_grammar) = init_grammar(grammar);
        InputData {
            grammar: grammar.unwrap(),
            clean_grammar: clean_grammar.unwrap(),
        }
    }
}

/// Estructura de contexto, para guardar datos del estado actual de cada elemento a procesar
///  Some((weights, choices_count, previous_rule, actual_rule, actual_expr))
///  Vec<(Vec<f32>, HashMap<String, u32>, Option<AstRule>, AstRule, Expr)> = Vec::new();
#[derive(Clone, Debug, Default)]
struct Context {
    total_count: usize,
    /// Contador de profundidad actual como si fuera Breadth-first search
    depth_count: usize,
    /// Contador de hermanos como si fuera Breadth-first search
    breadth_count: usize,
    /// Pesos acumulados
    /// no esta siendo usado actualmente
    weights: Vec<f32>,
    /// Parametro diseñado para mantener un conteo de las reglas que han aparecido hasta el momento
    /// no esta siendo usado actualmente
    choices_count: HashMap<String, u32>,
}

fn init_grammar(
    grammar_string: String,
) -> (
    Result<Grammar, Vec<HashMap<String, String>>>,
    Result<Grammar, Vec<HashMap<String, String>>>,
) {
    // Compilar gramática normal
    let grammar = compile_grammar(grammar_string.clone());

    // Compilar gramática limpia (Sin blacklist)
    let re = Regex::new(r#""\|BLACKLIST\|[I\|R]\|.+\|""#).unwrap();
    let clean_grammar_string = re.replace_all(&grammar_string, "\"\"");
    let clean_grammar = compile_grammar(clean_grammar_string.to_string());

    (grammar, clean_grammar)
}

pub fn generate_example(
    input_data: InputData,
    start_rule: String,
    config: &GeneratorConfig,
) -> Result<String, String> {
    let mut rng = thread_rng();

    // let config = GeneratorConfig {
    //     expand_limit: expand_limit,
    //     soft_limit: 10000,
    //     hard_limit: 25000,
    //     ..Default::default()
    // };

    let result = traverse(input_data, &start_rule, &mut rng, config);
    result
}

pub fn traverse(
    input_data: InputData,
    start_rule: &String,
    rng: &mut ThreadRng,
    config: &GeneratorConfig,
) -> Result<String, String> {
    // Factor de convergencia
    // let c_factor: f32 = 0.01;
    // let c_factor: f32 = 0.5;

    // Regla Inicial
    let rule;
    // Extrae la regla inicial
    let find_lhs = input_data.grammar.rules.get(start_rule);
    match find_lhs {
        Some(r) => rule = r.clone(),
        None => return Ok(start_rule.to_string()),
    }

    // Lista negra dinámica, usada para evitar la expansión de ciertos elementos de forma dinámica
    // Por ejemplo para evitar <a><p><a>TEXT</a></p></a>
    let mut dynamic_blacklist: Vec<String> = Vec::new();

    // Stack usado para almacenar todos los términos sintácticos
    // weights, definitions_count, actual_definition, actual_term
    // Contexto, definicion anterior, definición actual, termino actual a procesar
    let mut processing_stack: Vec<(Context, Option<AstRule>, AstRule, Expr)> = Vec::new();

    // Add first term
    let context: Context = Default::default();
    processing_stack.push((context, None, rule.clone(), rule.expr));

    // Variable que contiene la cadena generada
    let result = processing_terms(
        &input_data,
        rng,
        config,
        0,
        processing_stack,
        &mut dynamic_blacklist,
    );

    result
}

// depth level es una variable auxiliar para apoyar y detener la profundidad de la recursión
fn processing_terms(
    input_data: &InputData,
    rng: &mut ThreadRng,
    config: &GeneratorConfig,
    depth_level: usize,
    processing_stack: Vec<(Context, Option<AstRule>, AstRule, Expr)>,
    dynamic_blacklist: &mut Vec<String>,
) -> Result<String, String> {
    // Call to processing_stack
    let result = processing_stack_fn(
        input_data,
        rng,
        config,
        depth_level,
        processing_stack,
        dynamic_blacklist,
    );

    Ok(result.unwrap().0)
}

/// Retorna (result, count_nodes_processed, count_expand_idents)
/// el resultado en String, los nodos procesados por la función, y los identificadores expandidos (reglas)
fn processing_stack_fn(
    input_data: &InputData,
    mut rng: &mut ThreadRng,
    config: &GeneratorConfig,
    depth_level: usize,
    mut processing_stack: Vec<(Context, Option<AstRule>, AstRule, Expr)>,
    dynamic_blacklist: &mut Vec<String>,
) -> Result<(String, usize, u32), String> {
    // Variable que contiene la cadena generada
    let mut result = String::new();

    // println!("Profundidad: {}", depth_level);

    // 32KB
    let stack_red_zone: usize = 32 * 1024;
    // println!("Stack restante: {}", stacker::remaining_stack().unwrap());
    // println!("Hard Limit: {}", hard_limit);
    if depth_level > config.limit_depth_level
        || config.hard_limit < 1
        || stacker::remaining_stack().unwrap() < stack_red_zone
    {
        // Si el stack esta lleno, forzar un string vacio
        // En realidad debería retorna un error de generación
        // return Err(Error::RecursionLimit(format!(
        //     "Limit for recursion reached processing <{:?}>!",
        //     processing_stack
        // )));

        // return Ok((result, 0, 0));
        return Ok((config.text_expand_limit.to_owned(), 0, 0));
    }

    // Contador de la cantidad de expresiones que han sido procesadas
    let mut count_nodes_processed = 0;

    // Contador de la cantidad de identificadores expandidos
    let mut count_expand_idents = 0;

    // Secuencia superior de repetición
    // 0 - No repeticiones
    // 1 - 0/1 50/50
    // 2 - 0/1/2 33/33/33
    // etc
    // let mut upper_bound_repeated_sequence = 45;
    let mut upper_bound_repeated_sequence = config.upper_bound_zero_or_more_repetition;
    let mut upper_bound_repeated_one_sequence = config.upper_bound_one_or_more_repetition;

    // Limite agresivo para detener la expansión interna de elementos y forzar la convergencia
    let mut bool_hard_limit = false;

    // Variable de control usada para decidir si se debe seguir procesando una expr choice recursivamente
    let mut continue_processing_choice = false;
    // Variable usada para decidir si el procesamiento de opciones aleatorias es detenido por no existir más opciones disponibles
    // Valores posibles
    // -1 -> No se están procesando valores
    // 0 -> Aún se continúan procesando valores
    // 1 -> Ya se ha procesado uno de los dos últimos valores
    // 2 -> Ya se está procesando el último valor
    let mut last_processing_choice = -1;
    let mut selected_choice = Expr::Str("RESERVED".to_string());
    let mut choice_count = 0;

    while let Some((context, previous_rule, actual_rule, actual_expr)) = processing_stack.pop() {
        // println!("TERM: {:?}", actual_expr);
        // result.push_str(" ' ");

        match actual_expr.clone() {
            // Matches an exact string, e.g. `"a"`
            Expr::Str(string) => {
                if continue_processing_choice {
                    auxiliar_function(
                        rng,
                        &mut choice_count,
                        &mut selected_choice,
                        &mut continue_processing_choice,
                        &mut last_processing_choice,
                        context,
                        actual_expr,
                        actual_rule,
                        previous_rule,
                        &mut processing_stack,
                    )
                } else {
                    if string.starts_with("|BLACKLIST|I|") {
                        // Adicionar un ident a la blacklist
                        let blacklisted_idents = string
                            .trim_start_matches("|BLACKLIST|I|")
                            .trim_end_matches("|")
                            .split(",");
                        for ident in blacklisted_idents {
                            if let Some(mut rules) =
                                rule_is_only_ident_choices(&input_data.clean_grammar, &ident)
                            {
                                // Si la regla se compone unicamente de choices donde cada choice es un ident, adicionar todas las choices
                                // println!("{:?}", rules);
                                dynamic_blacklist.append(&mut rules);
                            } else {
                                // sino solo adicionar la regla
                                dynamic_blacklist.push(ident.to_string());
                            }
                        }
                    } else if string.starts_with("|BLACKLIST|R|") {
                        // Remover un ident de la blacklist
                        let blacklisted_idents = string
                            .trim_start_matches("|BLACKLIST|R|")
                            .trim_end_matches("|")
                            .split(",");

                        for ident in blacklisted_idents {
                            if let Some(rules) =
                                rule_is_only_ident_choices(&input_data.clean_grammar, &ident)
                            {
                                // Si la regla se compone unicamente de choices donde cada choice es un ident, remover todas las choices
                                // dynamic_blacklist.retain(|r| !rules.contains(r));

                                // Solo se remueve la ultima ocurrencia encontrada para evitar problemas de remover un item de la blacklist en
                                // profundidad por ejemplo |BLACKLIST|I|ThingWithA|  |BLACKLIST|I|A| / |BLACKLIST|R|A| |BLACKLIST|R|ThingWithA|
                                for rule in rules {
                                    // println!("{:?}", rule);
                                    // println!("Antes: {:?}", dynamic_blacklist);
                                    let index = dynamic_blacklist
                                        .iter()
                                        .rev()
                                        .position(|x| *x == rule)
                                        .unwrap();
                                    // println!("Index: {:?}", index);
                                    // println!("Nuevo Index: {:?}", dynamic_blacklist.len() - 1 - index);

                                    // Puesto que la position obtenida es la invertida, debido a que el iterador recorre al reves
                                    // es necesario hacer el siguiente calculo para poder obtener la posición correcta
                                    // index + len_lista % len_lista => posición
                                    dynamic_blacklist.remove(dynamic_blacklist.len() - 1 - index);
                                    // println!("Despues: {:?}", dynamic_blacklist);
                                }
                            } else {
                                // sino solo remover la regla
                                let index = dynamic_blacklist
                                    .iter()
                                    .rev()
                                    .position(|x| *x == ident)
                                    .unwrap();
                                dynamic_blacklist.remove(dynamic_blacklist.len() - 1 - index);
                            }
                        }
                    } else {
                        result.push_str(&string);
                    }
                }
            }
            // Matches an exact string, case insensitively (ASCII only), e.g. `^"a"`
            Expr::Insens(string) => {
                if continue_processing_choice {
                    auxiliar_function(
                        rng,
                        &mut choice_count,
                        &mut selected_choice,
                        &mut continue_processing_choice,
                        &mut last_processing_choice,
                        context,
                        actual_expr,
                        actual_rule,
                        previous_rule,
                        &mut processing_stack,
                    )
                } else {
                    // FIXME: esto tal vez debería generar algo como hOla

                    // Random bool for transform to lowercase or uppercase
                    let tmp = rng.gen_bool(0.5);
                    if tmp {
                        result.push_str(&string.to_lowercase());
                    } else {
                        result.push_str(&string.to_uppercase());
                    }
                }
            }
            // Matches one character in the range, e.g. `'a'..'z'`
            Expr::Range(initial_char, end_char) => {
                if continue_processing_choice {
                    auxiliar_function(
                        rng,
                        &mut choice_count,
                        &mut selected_choice,
                        &mut continue_processing_choice,
                        &mut last_processing_choice,
                        context,
                        actual_expr,
                        actual_rule,
                        previous_rule,
                        &mut processing_stack,
                    )
                } else {
                    // let mut rng = rand::thread_rng();
                    // Convert range to u32 and choose a random u32
                    let random_u32 = rng.gen_range(
                        initial_char.chars().next().unwrap() as u32,
                        end_char.chars().next().unwrap() as u32 + 1,
                    );

                    if let Some(random_char) = std::char::from_u32(random_u32) {
                        result.push(random_char);
                    } else {
                        // FIXME disparar un error de rango, es decir que no es unicode
                    }
                }
            }
            // Matches the rule with the given name, e.g. `a`
            Expr::Ident(name) => {
                if continue_processing_choice {
                    auxiliar_function(
                        rng,
                        &mut choice_count,
                        &mut selected_choice,
                        &mut continue_processing_choice,
                        &mut last_processing_choice,
                        context,
                        actual_expr,
                        actual_rule,
                        previous_rule,
                        &mut processing_stack,
                    )
                } else {
                    if config.expand_limit.is_none()
                        || config.expand_limit.unwrap() > count_expand_idents
                    {
                        if !dynamic_blacklist.contains(&name) {
                            match input_data.grammar.rules.get(&name) {
                                Some(new_rule) => {
                                    let mut new_context = context.clone();
                                    new_context.depth_count += 1;
                                    new_context.breadth_count = 0;
                                    processing_stack.push((
                                        new_context,
                                        Some(actual_rule.clone()),
                                        new_rule.clone(),
                                        new_rule.clone().expr,
                                    ));
                                    count_expand_idents += 1;
                                }
                                None => {
                                    unimplemented!("The rule hasn't been found: {}", &name);
                                }
                            }
                        } else {
                            // Si `name` está en la blacklist, se coloca la regla actual nuevamente, para que otra opción sea elegida
                            // FIXME: Advertencia: si una regla contiene como única opción un identificador presente en la blacklist
                            // podría ingresar en un bucle infinito, por ejemplo:  IdentExample = OtherIdent; si OtherIdent esta en blacklist se producirá un bucle infinito
                            // println!("Blacklist actual: {:?}", dynamic_blacklist);
                            // println!("Blacklist - {:?} - Se reingresara la regla: {:?}", &name, actual_rule.clone());

                            // Verifica si hay un posible loop comparando la blacklist con los elementos de la regla a abrir
                            if verify_infinite_loop_blacklist(
                                &input_data.clean_grammar,
                                &actual_rule.clone().name,
                                dynamic_blacklist,
                            ) {
                                let mut new_context = context.clone();
                                new_context.depth_count += 1;
                                processing_stack.push((
                                    new_context,
                                    previous_rule.clone(),
                                    actual_rule.clone(),
                                    actual_rule.clone().expr,
                                ));
                            } else {
                                match previous_rule {
                                    Some(previous) => {
                                        if verify_infinite_loop_blacklist(
                                            &input_data.clean_grammar,
                                            &previous.name.clone(),
                                            dynamic_blacklist,
                                        ) {
                                            let mut new_context = context.clone();
                                            new_context.depth_count += 1;
                                            processing_stack.push((
                                                new_context,
                                                None,
                                                previous.clone(),
                                                actual_rule.clone().expr,
                                            ));
                                        }
                                    }
                                    None => {
                                        // println!("Loop detected in grammar");
                                        // return Err("Existe un ciclo en la gramática, se ha detenido la ejecución".to_string());
                                        return Err("Loop detected in grammar, the execution has been stopped".to_string());
                                    }
                                }
                            }
                        }
                    // }
                    } else {
                        // FIXME No se expande el identificador pero se adiciona un texto temporalmente, para que no salgan tantos tags vacios
                        result.push_str(&config.text_expand_limit);
                    }
                }
            }
            //     /// Matches a custom part of the stack, e.g. `PEEK[..]`
            //     Expr::PeekSlice(i32, Option<i32>),
            //     /// Positive lookahead; matches expression without making progress, e.g. `&e`
            //     Expr::PosPred(Box<Expr>),
            //     /// Negative lookahead; matches if expression doesn't match, without making progress, e.g. `!e`
            //     Expr::NegPred(Box<Expr>),
            // Matches a sequence of two expressions, e.g. `e1 ~ e2`
            Expr::Seq(lhs, rhs) => {
                if continue_processing_choice {
                    auxiliar_function(
                        rng,
                        &mut choice_count,
                        &mut selected_choice,
                        &mut continue_processing_choice,
                        &mut last_processing_choice,
                        context,
                        actual_expr,
                        actual_rule,
                        previous_rule,
                        &mut processing_stack,
                    )
                } else {
                    match *lhs.clone() {
                        // Si es una negación seguida de algo más el procesamiento implica un parseo
                        Expr::NegPred(neg_expr) => {
                            let mut new_processing_stack: Vec<(
                                Context,
                                Option<AstRule>,
                                AstRule,
                                Expr,
                            )> = Vec::new();

                            // Add first term
                            let mut new_context = context.clone();
                            new_context.breadth_count += 1;
                            new_processing_stack.push((
                                new_context,
                                previous_rule.clone(),
                                actual_rule.clone(),
                                *rhs.clone(),
                            ));

                            let mut invalid_neg_generation = false;
                            let mut count_remaining_attempts = config.max_attempts_negation;
                            loop {
                                // Se usa un valor más pequeño de soft limit y hard limit para reducir posibilidad de OVERFLOW STACK
                                let mut new_config = config.clone();
                                if let Some(exp_lim) = config.expand_limit {
                                    new_config.expand_limit =
                                        Some(exp_lim.saturating_sub(count_expand_idents));
                                }
                                new_config.soft_limit = 20;
                                new_config.hard_limit =
                                    config.hard_limit.saturating_sub(count_nodes_processed);

                                match processing_stack_fn(
                                    &input_data,
                                    rng,
                                    &new_config,
                                    depth_level + 1,
                                    new_processing_stack.clone(),
                                    dynamic_blacklist,
                                ) {
                                    Ok((
                                        result_neg,
                                        neg_count_nodes_processed,
                                        neg_count_expand_idents,
                                    )) => {
                                        // println!("Resultado negación: {}", &result_neg);
                                        // Se hace un recorrido en toda la expresión de negación (B) unicamente revisando los Ident
                                        let _item = neg_expr.clone().map_bottom_up(|inner_expr| {
                                            match inner_expr.clone() {
                                                Expr::Ident(name) => {
                                                    let parsing = parse_input(
                                                        input_data.clean_grammar.clone(),
                                                        name.clone(),
                                                        result_neg.clone(),
                                                    );
                                                    match parsing {
                                                        // Si el parseo fue exitoso quiere decir que la secuencia generada es invalidad
                                                        Ok(_) => {
                                                            invalid_neg_generation = true;
                                                        }
                                                        Err(_a) => {
                                                            //     println!(
                                                            //     "Error de parseo en negación: {:?}, regla {}",
                                                            //     _a,
                                                            //     name
                                                            // ),
                                                            // Si el parseo no es exitoso se cumple la premisa A - B
                                                            invalid_neg_generation = false
                                                        }
                                                    }
                                                }
                                                _ => {}
                                            };
                                            inner_expr
                                        });

                                        // Si la secuencia generada es valida, es decir no hace parte de la negación se debe adicionar al string
                                        if !invalid_neg_generation {
                                            // Sumar los nodos que han sido procesados en la negación al conteo general
                                            count_nodes_processed += neg_count_nodes_processed;
                                            count_expand_idents += neg_count_expand_idents;
                                            result.push_str(&result_neg);
                                        }
                                    }
                                    error => {
                                        return error;
                                    }
                                }

                                if !invalid_neg_generation {
                                    break;
                                }

                                if count_remaining_attempts <= 0 {
                                    println!(
                                        "Exceso de intentos para A - B en: !{:?} ~ {:?}",
                                        neg_expr, *rhs
                                    );
                                    break;
                                }

                                count_remaining_attempts -= 1;
                                // println!("{}", count_remaining_attempts);
                            }
                        }
                        // Si no es Una negación, la secuencia se procesa normalmente
                        _ => {
                            let mut new_context = context.clone();
                            new_context.breadth_count += 1;
                            // El orden importa, puesto que es un stack
                            processing_stack.push((
                                new_context.clone(),
                                previous_rule.clone(),
                                actual_rule.clone(),
                                *rhs,
                            ));

                            new_context.breadth_count += 1;
                            processing_stack.push((new_context, previous_rule, actual_rule, *lhs));
                        }
                    }
                }
            }
            // Matches either of two expressions, e.g. `e1 | e2`
            Expr::Choice(lhs, rhs) => {
                // TODO debería hacer match también en rhs
                // println!("Izquierda: {:?}", lhs.clone());
                // println!("Derecha: {:?}", rhs.clone());
                match *lhs.clone() {
                    Expr::Choice(_lhs_inner, _rhs_inner) => {
                        continue_processing_choice = true;
                        // selected_choice = *rhs.clone();
                        processing_stack.push((
                            context.clone(),
                            previous_rule.clone(),
                            actual_rule.clone(),
                            *lhs,
                        ));
                        processing_stack.push((context.clone(), previous_rule, actual_rule, *rhs));
                    }
                    _ => {
                        if continue_processing_choice {
                            // Hora de procesar las últimas dos opciones
                            last_processing_choice = 0;
                            processing_stack.push((
                                context.clone(),
                                previous_rule.clone(),
                                actual_rule.clone(),
                                *rhs,
                            ));
                            processing_stack.push((
                                context.clone(),
                                previous_rule,
                                actual_rule,
                                *lhs,
                            ));
                        } else {
                            // Reinicio de las variables de apoyo para selección
                            selected_choice = Expr::Str("RESERVED".to_string());
                            continue_processing_choice = false;
                            choice_count = 0;

                            let selected = *random_definition(&vec![lhs, rhs], &mut rng).unwrap();
                            // println!("SELECCTED: {:?}", &selected);
                            // processing_stack((Vec::new(), HashMap::new(), rule, rule.expr))
                            let mut new_context = context.clone();
                            new_context.breadth_count += 1;
                            processing_stack.push((
                                new_context,
                                previous_rule,
                                actual_rule,
                                selected,
                            ));
                        }
                    }
                }

                // processing_stack.push((Vec::new(), HashMap::new(), actual_rule, selected));
            }
            // Optionally matches an expression, e.g. `e?`
            Expr::Opt(expr) => {
                if continue_processing_choice {
                    auxiliar_function(
                        rng,
                        &mut choice_count,
                        &mut selected_choice,
                        &mut continue_processing_choice,
                        &mut last_processing_choice,
                        context,
                        actual_expr,
                        actual_rule,
                        previous_rule,
                        &mut processing_stack,
                    )
                } else if !bool_hard_limit {
                    let option = rng.gen_bool(0.5);
                    if option {
                        let mut new_context = context.clone();
                        new_context.breadth_count += 1;
                        processing_stack.push((new_context, previous_rule, actual_rule, *expr));
                    }
                }
            }
            // Matches an expression zero or more times, e.g. `e*`
            Expr::Rep(expr) => {
                // HARD LIMIT
                if processing_stack.len() > config.soft_limit {
                    upper_bound_repeated_sequence = 1;
                    upper_bound_repeated_one_sequence = 2;
                } else if !bool_hard_limit {
                    let num_reps = rng.gen_range(0, upper_bound_repeated_sequence);
                    (1..num_reps + 1).for_each(|rep| {
                        let mut new_context = context.clone();
                        new_context.breadth_count += rep as usize;
                        processing_stack.push((
                            new_context,
                            previous_rule.clone(),
                            actual_rule.clone(),
                            *expr.clone(),
                        ))
                    });
                }
            }
            // Matches an expression one or more times, e.g. `e+`
            Expr::RepOnce(expr) => {
                // HARD LIMIT
                if processing_stack.len() > config.soft_limit {
                    upper_bound_repeated_sequence = 1;
                    upper_bound_repeated_one_sequence = 2;
                } else if !bool_hard_limit {
                    let num_reps = rng.gen_range(1, upper_bound_repeated_one_sequence);
                    (1..num_reps + 1).for_each(|rep| {
                        let mut new_context = context.clone();
                        new_context.breadth_count += rep as usize;
                        processing_stack.push((
                            new_context,
                            previous_rule.clone(),
                            actual_rule.clone(),
                            *expr.clone(),
                        ))
                    });
                }
            }
            // Matches an expression an exact number of times, e.g. `e{n}`
            Expr::RepExact(expr, num_reps) => {
                if continue_processing_choice {
                    auxiliar_function(
                        rng,
                        &mut choice_count,
                        &mut selected_choice,
                        &mut continue_processing_choice,
                        &mut last_processing_choice,
                        context,
                        actual_expr,
                        actual_rule,
                        previous_rule,
                        &mut processing_stack,
                    )
                } else if !bool_hard_limit {
                    (1..num_reps + 1).for_each(|rep| {
                        let mut new_context = context.clone();
                        new_context.breadth_count += rep as usize;
                        processing_stack.push((
                            new_context,
                            previous_rule.clone(),
                            actual_rule.clone(),
                            *expr.clone(),
                        ))
                    });
                }
            }
            // Matches an expression at least a number of times, e.g. `e{n,}`
            Expr::RepMin(expr, min_reps) => {
                if continue_processing_choice {
                    auxiliar_function(
                        rng,
                        &mut choice_count,
                        &mut selected_choice,
                        &mut continue_processing_choice,
                        &mut last_processing_choice,
                        context,
                        actual_expr,
                        actual_rule,
                        previous_rule,
                        &mut processing_stack,
                    )
                } else if !bool_hard_limit {
                    // Se suma 1 debido a que el rango es inclusive
                    let num_reps = rng.gen_range(
                        min_reps,
                        min_reps + config.upper_bound_at_least_repetition + 1,
                    );
                    (1..num_reps + 1).for_each(|rep| {
                        let mut new_context = context.clone();
                        new_context.breadth_count += rep as usize;
                        processing_stack.push((
                            new_context,
                            previous_rule.clone(),
                            actual_rule.clone(),
                            *expr.clone(),
                        ))
                    });
                }
            }
            // Matches an expression at most a number of times, e.g. `e{,n}`
            Expr::RepMax(expr, max_reps) => {
                if continue_processing_choice {
                    auxiliar_function(
                        rng,
                        &mut choice_count,
                        &mut selected_choice,
                        &mut continue_processing_choice,
                        &mut last_processing_choice,
                        context,
                        actual_expr,
                        actual_rule,
                        previous_rule,
                        &mut processing_stack,
                    )
                } else if !bool_hard_limit {
                    // Se suma 1 debido a que el rango es inclusive
                    let num_reps = rng.gen_range(0, max_reps + 1);
                    (1..num_reps + 1).for_each(|rep| {
                        let mut new_context = context.clone();
                        new_context.breadth_count += rep as usize;
                        processing_stack.push((
                            new_context,
                            previous_rule.clone(),
                            actual_rule.clone(),
                            *expr.clone(),
                        ))
                    });
                }
            }
            // Matches an expression a number of times within a range, e.g. `e{m, n}`
            Expr::RepMinMax(expr, min_reps, max_reps) => {
                if continue_processing_choice {
                    auxiliar_function(
                        rng,
                        &mut choice_count,
                        &mut selected_choice,
                        &mut continue_processing_choice,
                        &mut last_processing_choice,
                        context,
                        actual_expr,
                        actual_rule,
                        previous_rule,
                        &mut processing_stack,
                    )
                } else if !bool_hard_limit {
                    // Se suma 1 debido a que el rango es inclusive
                    let num_reps = rng.gen_range(min_reps, max_reps + 1);
                    (1..num_reps + 1).for_each(|rep| {
                        let mut new_context = context.clone();
                        new_context.breadth_count += rep as usize;
                        processing_stack.push((
                            new_context,
                            previous_rule.clone(),
                            actual_rule.clone(),
                            *expr.clone(),
                        ))
                    });
                }
            } //     /// Continues to match expressions until one of the strings in the `Vec` is found
            //     Expr::Skip(Vec<String>),
            //     /// Matches an expression and pushes it to the stack, e.g. `push(e)`
            // Expr::Push(Box<Expr>),
            _ => {}
        }
        // println!("{:?}", result);
        // println!("Len: {}", processing_stack.len());
        // println!("Nodes processed: {}", count_nodes_processed);
        count_nodes_processed += 1;

        if count_nodes_processed > config.hard_limit {
            // Activar HARD LIMIT
            bool_hard_limit = true;
            // println!("HARD LIMIT REACHED: {}", hard_limit);
        }
    }

    // println!("Nodes processed: {}", count_nodes_processed);
    Ok((result, count_nodes_processed, count_expand_idents))
}

/// Random entre Simbolos |
pub fn random_definition(
    definitions: &Vec<Box<Expr>>,
    rng: &mut ThreadRng,
) -> Result<Box<Expr>, String> {
    // println!("Selección aleatoria: {:?}", &definitions);
    match definitions.choose(rng) {
        Some(selected) => {
            // println!("Gano: {:?}", &selected);
            Ok(selected.to_owned())
        }
        None => Err("crate::error::GenerationError::RandomChoose".to_string()),
    }
}

fn auxiliar_function(
    rng: &mut ThreadRng,
    choice_count: &mut i32,
    selected_choice: &mut Expr,
    continue_processing_choice: &mut bool,
    last_processing_choice: &mut i8,
    context: Context,
    actual_expr: Expr,
    actual_rule: AstRule,
    previous_rule: Option<AstRule>,
    processing_stack: &mut Vec<(Context, Option<AstRule>, AstRule, Expr)>,
) {
    if *choice_count == 0 {
        *selected_choice = actual_expr;
        *choice_count += 1;
    } else {
        // println!(
        //     "Actual: {:?} vs Selected: {:?}",
        //     actual_expr, selected_choice
        // );
        // println!("Range selection: [{}, {})", 0, *choice_count + 1);
        let num = rng.gen_range(0, *choice_count + 1);
        if num == *choice_count {
            *selected_choice = actual_expr;
        }
        // println!("Choice count: {} - Num: {}", choice_count, num);
        // println!("WIN: {:?}", selected_choice);
        // println!("Last processing choice: {:?}", last_processing_choice);

        if *last_processing_choice == 1 {
            processing_stack.push((
                context.clone(),
                previous_rule.clone(),
                actual_rule.clone(),
                selected_choice.clone(),
            ));

            // Reinicio de variables
            *last_processing_choice = -1;
            *continue_processing_choice = false;
            *selected_choice = Expr::Str("RESERVED".to_string());
            // -1 Para evitar que RESERVED entre en comparación
            // choice_count al final de esta sección terminaria valiendo cero
            *choice_count = -1;
        }

        // Si se estan procesando las últimas dos opciones posibles
        if *last_processing_choice == 0 {
            *last_processing_choice += 1;
        }
        *choice_count += 1;
    }
}

/// Dada una regla, verifica si unicamente se componen de choice que sean idents y retorna los idents
/// si no retorna None
/// TODO: elaborar test para esta función
fn rule_is_only_ident_choices(grammar: &Grammar, blacklisted_ident: &str) -> Option<Vec<String>> {
    if let Some(rule) = grammar.rules.get(blacklisted_ident) {
        let mut idents = Vec::<String>::new();
        let mut aux_expr = Some(rule.expr.clone());
        while let Some(expr) = aux_expr.clone() {
            match expr {
                // Matches either of two expressions, e.g. `e1 | e2`
                Expr::Choice(lhs, rhs) => {
                    // Matching del rhs para valdiar que sea un ident
                    match *rhs {
                        Expr::Ident(rhs_name) => {
                            idents.push(rhs_name);
                        }
                        _ => {
                            // Si es otra cosa diferente de un ident, cancelar
                            return None;
                        }
                    }

                    match *lhs {
                        Expr::Ident(rhs_name) => {
                            idents.push(rhs_name);
                            // aux_expr = None;
                            break;
                        }
                        Expr::Choice(_, _) => aux_expr = Some(*lhs),
                        _ => {
                            // Si es otra cosa diferente de un ident, cancelar
                            return None;
                        }
                    }
                }
                Expr::Ident(name) => {
                    idents.push(name);
                    // aux_expr = None;
                    break;
                }
                _ => {
                    return None;
                }
            }
        }
        return Some(idents);
    } else {
        return None;
    }
}

/**
 * Retorna true si encuentra un ciclo infinito
 */
fn verify_infinite_loop_blacklist(grammar: &Grammar, ident: &str, blacklist: &Vec<String>) -> bool {
    match rule_is_only_ident_choices(grammar, ident) {
        Some(idents) => {
            for ident_item in idents {
                if !blacklist.contains(&ident_item) {
                    return true;
                }
            }
            false
        }
        None => false,
    }
}

#[test]
fn test_only_ident_in_rules() {
    let g = compile_grammar(
        r#"
        Uno = {"a"}
        Dos = {"b"}
        Tres = {"c"}
        Cuatro = {"d"}
        Example = { Uno | Dos | Tres | Cuatro }
    "#
        .to_string(),
    )
    .unwrap();

    let mut results = rule_is_only_ident_choices(&g, &"Example").unwrap();
    assert_eq!(vec!["Uno", "Dos", "Tres", "Cuatro"].sort(), results.sort());
}

#[test]
fn test_only_ident_in_rules_1() {
    let g = compile_grammar(
        r#"
        Uno = {"a"}
        Dos = {"b"}
        Tres = {"c"}
        Example = { Uno | Dos | Tres | "Cuatro" }
    "#
        .to_string(),
    )
    .unwrap();

    let results = rule_is_only_ident_choices(&g, &"Example");
    assert_eq!(None, results);
}

#[test]
fn test_only_ident_in_rules_2() {
    let g = compile_grammar(
        r#"
        Uno = {"a"}
        Dos = {"b"}
        Tres = {"c"}
        Example = { Uno | Dos | Tres ~ Uno }
    "#
        .to_string(),
    )
    .unwrap();

    let results = rule_is_only_ident_choices(&g, &"Example");
    assert_eq!(None, results);
}