172
|
1 using System;
|
|
2 using System.Collections.Generic;
|
|
3 using System.Linq;
|
|
4
|
|
5 namespace Implab.Automaton.RegularExpressions {
|
|
6 public class RegularDFA<TInput, TTag> : DFATable, ITaggedDFABuilder<TTag> {
|
|
7
|
|
8 readonly Dictionary<int,TTag[]> m_tags = new Dictionary<int, TTag[]>();
|
|
9 readonly IAlphabet<TInput> m_alphabet;
|
|
10
|
|
11 public RegularDFA(IAlphabet<TInput> alphabet) {
|
|
12 Safe.ArgumentNotNull(alphabet, "aplhabet");
|
|
13
|
|
14 m_alphabet = alphabet;
|
|
15 }
|
|
16
|
|
17
|
|
18 public IAlphabet<TInput> InputAlphabet {
|
|
19 get {
|
|
20 return m_alphabet;
|
|
21 }
|
|
22 }
|
|
23
|
|
24 public void MarkFinalState(int s, TTag[] tags) {
|
|
25 MarkFinalState(s);
|
|
26 SetStateTag(s, tags);
|
|
27 }
|
|
28
|
|
29 public void SetStateTag(int s, TTag[] tags) {
|
|
30 Safe.ArgumentNotNull(tags, "tags");
|
|
31 m_tags[s] = tags;
|
|
32 }
|
|
33
|
|
34 public TTag[] GetStateTag(int s) {
|
|
35 TTag[] tags;
|
|
36 return m_tags.TryGetValue(s, out tags) ? tags : new TTag[0];
|
|
37 }
|
|
38
|
176
|
39 public TTag[][] CreateTagTable() {
|
|
40 var table = new TTag[StateCount][];
|
172
|
41
|
176
|
42 foreach (var pair in m_tags)
|
|
43 table[pair.Key] = pair.Value;
|
172
|
44
|
|
45 return table;
|
|
46 }
|
|
47
|
|
48 /// <summary>
|
|
49 /// Optimize the specified alphabet.
|
|
50 /// </summary>
|
|
51 /// <param name="alphabet">Пустой алфавит, который будет зполнен в процессе оптимизации.</param>
|
|
52 public RegularDFA<TInput,TTag> Optimize(IAlphabetBuilder<TInput> alphabet) {
|
|
53 Safe.ArgumentNotNull(alphabet, "alphabet");
|
|
54
|
|
55 var dfa = new RegularDFA<TInput, TTag>(alphabet);
|
|
56
|
|
57 var states = new DummyAlphabet(StateCount);
|
|
58 var alphaMap = new Dictionary<int,int>();
|
|
59 var stateMap = new Dictionary<int,int>();
|
|
60
|
|
61 Optimize(dfa, alphaMap, stateMap);
|
|
62
|
|
63 // mark tags in the new DFA
|
|
64 foreach (var g in m_tags.Where(x => x.Key < StateCount).GroupBy(x => stateMap[x.Key], x => x.Value ))
|
|
65 dfa.SetStateTag(g.Key, g.SelectMany(x => x).ToArray());
|
|
66
|
|
67 // make the alphabet for the new DFA
|
|
68 foreach (var pair in alphaMap)
|
|
69 alphabet.DefineClass(m_alphabet.GetSymbols(pair.Key), pair.Value);
|
|
70
|
|
71 return dfa;
|
|
72 }
|
|
73
|
|
74 protected override IEnumerable<HashSet<int>> GroupFinalStates() {
|
|
75 var arrayComparer = new CustomEqualityComparer<TTag[]>(
|
|
76 (x,y) => x.Length == y.Length && x.All(it => y.Contains(it)),
|
|
77 x => x.Sum(it => x.GetHashCode())
|
|
78 );
|
|
79 return FinalStates.GroupBy(x => m_tags[x], arrayComparer).Select(g => new HashSet<int>(g));
|
|
80 }
|
|
81
|
|
82 }
|
|
83 }
|
|
84
|