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
use std::borrow::Borrow;
use std::cell::{Ref, RefCell, RefMut};
use std::collections::{HashMap, HashSet};
use std::collections::hash_map::RandomState;
use std::hash::Hash;
use std::iter::{FromIterator, Map};
use std::slice::Iter;

use crate::grammar::context_free_grammar::ContextFreeGrammar;
use crate::grammar::context_free_grammar_production::ContextFreeGrammarProduction;

pub type SymbolsMap<T> = HashMap<T, HashSet<T>>;

pub struct FirstFollowSymbols<T> {
    first_symbols: SymbolsMap<T>,
    follow_symbols: SymbolsMap<T>,
}

impl<T> FirstFollowSymbols<T> {
    fn converge<M, F>(model: &M, callback: F) -> ()
        where
            F: Fn(&M) -> bool,
    {
        while callback(model) {}
    }
}

impl<T: Eq + Hash> FirstFollowSymbols<T> {
    pub fn new(first_symbols: SymbolsMap<T>, follow_symbols: SymbolsMap<T>) -> Self {
        FirstFollowSymbols {
            first_symbols,
            follow_symbols,
        }
    }

    pub fn get_first_symbols<'a>(&'a self, symbol: &'a T) -> Option<&'a HashSet<T>> {
        FirstFollowSymbols::get_symbols_from_hash_map(&self.first_symbols, symbol)
    }

    pub fn get_follow_symbols<'a>(&'a self, symbol: &'a T) -> Option<&'a HashSet<T>> {
        FirstFollowSymbols::get_symbols_from_hash_map(&self.follow_symbols, symbol)
    }

    fn get_symbols_from_hash_map<'a>(
        hash_map: &'a SymbolsMap<T>,
        key: &T,
    ) -> Option<&'a HashSet<T>> {
        hash_map.get(key)
    }

    fn ref_map_to_symbols_map(symbols_ref_map: HashMap<T, RefCell<HashSet<T>>>) -> SymbolsMap<T> {
        HashMap::from_iter(
            symbols_ref_map.into_iter().map(
                |(symbol, symbols_ref)|
                    (symbol, symbols_ref.take())
            )
        )
    }
}

impl<T: Clone + Eq + Hash> FirstFollowSymbols<T> {

    pub fn from(grammar: &ContextFreeGrammar<T>) -> Self {
        let first_symbols = Self::inner_get_first_symbols(grammar);
        let follow_symbols = Self::inner_get_follow_symbols(grammar, &first_symbols);

        Self::new(first_symbols, follow_symbols)
    }

    fn inner_get_first_symbols(grammar: &ContextFreeGrammar<T>) -> SymbolsMap<T> {
        let non_terminal_symbols = grammar.get_non_terminal_symbols();
        let terminal_symbols = grammar.get_terminal_symbols();

        let first_symbols_map: HashMap<T, RefCell<HashSet<T>>> = Self::inner_get_first_symbols_initial_map(
            &non_terminal_symbols,
            &terminal_symbols,
        );

        Self::converge(&first_symbols_map, |model: &HashMap<T, RefCell<HashSet<T>>>| -> bool {
            let mut updated_at_iter: bool = false;

            let productions = non_terminal_symbols
                .iter()
                .map(|symbol| (symbol, grammar.get_productions(symbol).unwrap()));

            for (symbol, tuple_productions) in productions {
                let mut tuple_symbol_first_symbols: RefMut<HashSet<T>> =
                    first_symbols_map.get(symbol).unwrap().borrow_mut();

                for production in tuple_productions {
                    updated_at_iter |= Self::inner_get_first_symbols_process_production(
                        grammar,
                        model,
                        &mut tuple_symbol_first_symbols,
                        &production,
                    );
                }
            }

            updated_at_iter
        });

        Self::ref_map_to_symbols_map(first_symbols_map)
    }

    fn inner_get_first_symbols_initial_map(non_terminal_symbols: &Vec<T>, terminal_symbols: &Vec<T>)
        -> HashMap<T, RefCell<HashSet<T>>> {
        let non_terminal_symbols_iterator
            = Self::inner_get_first_symbols_non_terminal_map(&non_terminal_symbols);
        let terminal_symbols_iterator
            = Self::inner_get_first_symbols_terminal_map(&terminal_symbols);

        HashMap::from_iter(
            non_terminal_symbols_iterator.chain(terminal_symbols_iterator),
        )
    }

    fn inner_get_first_symbols_non_terminal_map(symbols: &Vec<T>)
        -> Map<Iter<'_, T>, fn(&T) -> (T, RefCell<HashSet<T, RandomState>>)> {
        symbols
            .iter()
            .map(|symbol| (symbol.clone(), RefCell::new(HashSet::new())))
    }

    fn inner_get_first_symbols_process_production(
        grammar: &ContextFreeGrammar<T>,
        first_symbols_map: &HashMap<T, RefCell<HashSet<T>>>,
        tuple_symbol_first_symbols: &mut RefMut<HashSet<T>>,
        production: &ContextFreeGrammarProduction<T>,
    ) -> bool {
        let mut first_symbols_updated: bool = false;
        let mut output_iterator_option: Option<Iter<T>> = Some(production.output.iter());

        while output_iterator_option.is_some() {
            let production_symbol_option = output_iterator_option.as_mut().unwrap().next();

            match production_symbol_option {
                Some(production_symbol) => {
                    first_symbols_updated |= Self::inner_get_first_symbols_process_production_symbol(
                        grammar,
                        first_symbols_map,
                        tuple_symbol_first_symbols,
                        &mut output_iterator_option,
                        &production.input,
                        production_symbol,
                    );
                },
                None => {
                    first_symbols_updated |= tuple_symbol_first_symbols.insert(
                        grammar.get_epsilon_symbol().clone()
                    );
                    break;
                }
            }
        }

        first_symbols_updated
    }

    fn inner_get_first_symbols_process_production_symbol(
        grammar: &ContextFreeGrammar<T>,
        first_symbols_map: &HashMap<T, RefCell<HashSet<T>>>,
        tuple_symbol_first_symbols: &mut RefMut<HashSet<T>>,
        output_iterator_option: &mut Option<Iter<T>>,
        production_input: &T,
        production_symbol: &T,
    ) -> bool {
        let mut first_symbols_updated = false;

        if production_symbol.eq(production_input) {
            if !tuple_symbol_first_symbols.contains(grammar.get_epsilon_symbol()) {
                *output_iterator_option = None;
            }
        } else {
            if grammar.is_non_terminal(production_symbol) {
                first_symbols_updated |= Self::inner_get_first_symbols_process_production_non_terminal_symbol(
                    grammar,
                    first_symbols_map,
                    tuple_symbol_first_symbols,
                    output_iterator_option,
                    production_symbol,
                );
            } else {
                first_symbols_updated |= tuple_symbol_first_symbols.insert(production_symbol.clone());

                *output_iterator_option = None
            }
        }

        first_symbols_updated
    }

    fn inner_get_first_symbols_process_production_non_terminal_symbol(
        grammar: &ContextFreeGrammar<T>,
        first_symbols_map: &HashMap<T, RefCell<HashSet<T>>>,
        tuple_symbol_first_symbols: &mut RefMut<HashSet<T>>,
        output_iterator_option: &mut Option<Iter<T>>,
        production_symbol: &T,
    ) -> bool {
        let mut first_symbols_updated = false;

        let symbol_first_symbols: Ref<HashSet<T>> =
            first_symbols_map.get(production_symbol).unwrap().borrow();

        if symbol_first_symbols.contains(grammar.get_epsilon_symbol()) {
            first_symbols_updated |= Self::insert_many(
                tuple_symbol_first_symbols,
                &mut symbol_first_symbols
                    .iter()
                    .filter(|symbol| grammar.get_epsilon_symbol().ne(*symbol)),
            );
        } else {
            first_symbols_updated |= Self::insert_many(
                tuple_symbol_first_symbols,
                &mut symbol_first_symbols.iter(),
            );

            *output_iterator_option = None
        }

        first_symbols_updated
    }

    fn inner_get_first_symbols_terminal_map(symbols: &Vec<T>)
        -> Map<Iter<'_, T>, fn(&T) -> (T, RefCell<HashSet<T, RandomState>>)> {
        symbols
            .iter()
            .map(
                |symbol| {
                    let mut hash_set = HashSet::new();
                    hash_set.insert(symbol.clone());

                    (symbol.clone(), RefCell::new(hash_set))
                },
            )
    }

    fn inner_get_follow_symbols(
        grammar: &ContextFreeGrammar<T>,
        first_symbols_map: &SymbolsMap<T>,
    ) -> SymbolsMap<T> {
        let non_terminal_symbols = grammar.get_non_terminal_symbols();

        let follow_symbols_map: HashMap<T, RefCell<HashSet<T>>> = HashMap::from_iter(
            non_terminal_symbols.iter()
                .map(|symbol| (symbol.clone(), RefCell::new(HashSet::new()))),
        );

        Self::converge(&follow_symbols_map, |model| {
            let mut updated_at_iter: bool = false;

            let productions = non_terminal_symbols
                .iter()
                .map(|symbol| (symbol, grammar.get_productions(symbol).unwrap()));

            for (_, tuple_productions) in productions {
                for production in tuple_productions {
                    updated_at_iter |= Self::get_follow_symbols_process_production(
                        grammar,
                        first_symbols_map,
                        model,
                        production,
                    );
                }
            }

            updated_at_iter
        });

        Self::ref_map_to_symbols_map(follow_symbols_map)
    }

    fn get_follow_symbols_process_production_last_epsilon_chain(
        grammar: &ContextFreeGrammar<T>,
        first_symbols_map: &SymbolsMap<T>,
        follow_symbols_map: &HashMap<T, RefCell<HashSet<T>>>,
        production: &ContextFreeGrammarProduction<T>,
    ) -> bool {
        let mut follow_symbols_updated: bool = false;

        let mut production_output_index: usize = production.output.len() - 1;

        loop {
            let output_symbol: &T = production.output.get(production_output_index).unwrap();

            if output_symbol.ne(&production.input) && grammar.is_non_terminal(output_symbol) {
                let input_follow_symbols = follow_symbols_map.get(&production.input).unwrap().borrow();
                let mut symbol_follow_symbols_ref = follow_symbols_map.get(output_symbol).unwrap().borrow_mut();

                input_follow_symbols.iter().for_each(|symbol| {
                    follow_symbols_updated |= symbol_follow_symbols_ref.insert(symbol.clone());
                });
            }

            let output_symbol_first_symbols: &HashSet<T> = first_symbols_map
                .get(output_symbol).unwrap().borrow();

            let output_symbol_first_symbols_contains_epsilon: bool =
                output_symbol_first_symbols.contains(grammar.get_epsilon_symbol());

            if production_output_index == 0 || !output_symbol_first_symbols_contains_epsilon {
                break;
            } else {
                production_output_index -= 1;
            }
        }

        follow_symbols_updated
    }

    fn get_follow_symbols_process_production(
        grammar: &ContextFreeGrammar<T>,
        first_symbols_map: &SymbolsMap<T>,
        follow_symbols_map: &HashMap<T, RefCell<HashSet<T>>>,
        production: &ContextFreeGrammarProduction<T>,
    ) -> bool {
        let mut follow_symbols_updated: bool = Self::get_follow_symbols_process_production_last_epsilon_chain(
            grammar,
            first_symbols_map,
            follow_symbols_map,
            &production,
        );

        let last_production_output_index: usize = production.output.len() - 1;

        if last_production_output_index > 0 {
            let mut production_output_index: usize = last_production_output_index - 1;
            let mut first_indexes: Vec<usize> = vec![];

            loop {
                follow_symbols_updated |= Self::get_follow_symbols_process_production_symbol(
                    grammar,
                    first_symbols_map,
                    follow_symbols_map,
                    production,
                    production_output_index,
                    &mut first_indexes,
                );

                if production_output_index == 0 {
                    break
                } else {
                    production_output_index -= 1;
                }
            }
        }

        follow_symbols_updated
    }

    fn get_follow_symbols_process_production_symbol(
        grammar: &ContextFreeGrammar<T>,
        first_symbols_map: &SymbolsMap<T>,
        follow_symbols_map: &HashMap<T, RefCell<HashSet<T>>>,
        production: &ContextFreeGrammarProduction<T>,
        production_output_index: usize,
        first_indexes: &mut Vec<usize>,
    ) -> bool {
        let follow_symbols_updated: bool;

        let current_symbol: &T = production.output.get(production_output_index).unwrap();

        if grammar.is_non_terminal(current_symbol) {
            follow_symbols_updated = Self::get_follow_symbols_process_production_non_terminal_symbol(
                grammar,
                first_symbols_map,
                follow_symbols_map,
                production,
                production_output_index,
                first_indexes,
                current_symbol,
            );
        } else {
            follow_symbols_updated = false;

            first_indexes.clear();
        }

        follow_symbols_updated
    }

    fn get_follow_symbols_process_production_non_terminal_symbol(
        grammar: &ContextFreeGrammar<T>,
        first_symbols_map: &SymbolsMap<T>,
        follow_symbols_map: &HashMap<T, RefCell<HashSet<T>>>,
        production: &ContextFreeGrammarProduction<T>,
        production_output_index: usize,
        first_indexes: &mut Vec<usize>,
        current_symbol: &T,
    ) -> bool {
        let mut follow_symbols_updated: bool = false;

        let next_symbol_index: usize = production_output_index + 1;
        let next_symbol = production.output.get(next_symbol_index).unwrap();

        if current_symbol.ne(next_symbol) {
            let next_symbol_first_symbols = first_symbols_map.get(next_symbol).unwrap();

            if !next_symbol_first_symbols.contains(grammar.get_epsilon_symbol()) {
                first_indexes.clear();
            }

            first_indexes.push(next_symbol_index);

            let mut current_symbol_follow_symbols = follow_symbols_map
                .get(current_symbol)
                .unwrap()
                .borrow_mut();

            follow_symbols_updated |= Self::update_follow_symbols_lambda_chain(
                grammar,
                first_symbols_map,
                production,
                first_indexes,
                &mut current_symbol_follow_symbols,
            );
        }

        follow_symbols_updated
    }

    fn insert_many(hash_set_ref: &mut RefMut<HashSet<T>>, iterator: &mut dyn Iterator<Item=&T>) -> bool {
        let mut item_inserted: bool = false;

        iterator.for_each(|symbol_first_symbol| {
            item_inserted |= hash_set_ref.insert(symbol_first_symbol.clone());
        });

        item_inserted
    }

    fn update_follow_symbols_lambda_chain(
        grammar: &ContextFreeGrammar<T>,
        first_symbols_map: &SymbolsMap<T>,
        production: &ContextFreeGrammarProduction<T>,
        first_indexes: &Vec<usize>,
        current_symbol_follow_symbols: &mut HashSet<T>,
    ) -> bool {
        let mut follow_symbols_updated: bool = false;

        first_indexes.iter().for_each(|index| {
            let symbol: &T = production.output.get(*index).unwrap();

            first_symbols_map.get(symbol)
                .unwrap()
                .iter()
                .filter(|symbol| (grammar.get_epsilon_symbol()).ne(*symbol))
                .for_each(|symbol| {
                    follow_symbols_updated |= current_symbol_follow_symbols.insert(symbol.clone());
                });
        });

        follow_symbols_updated
    }
}