@@ -0,0 +1,9 | |||
|
1 | ||
|
2 | namespace Implab.Automaton { | |
|
3 | public static class DFAConst { | |
|
4 | public const int UNREACHABLE_STATE = -1; | |
|
5 | ||
|
6 | public const int UNCLASSIFIED_INPUT = 0; | |
|
7 | } | |
|
8 | } | |
|
9 |
@@ -0,0 +1,37 | |||
|
1 | using Implab; | |
|
2 | using System; | |
|
3 | using System.Collections.Generic; | |
|
4 | using System.Diagnostics; | |
|
5 | using System.Linq; | |
|
6 | ||
|
7 | namespace Implab.Automaton.RegularExpressions { | |
|
8 | /// <summary> | |
|
9 | /// </summary> | |
|
10 | public class RegularExpressionVisitor<TTag> : RegularExpressionVisitor { | |
|
11 | readonly Dictionary<int, TTag> m_tags = new Dictionary<int, TTag>(); | |
|
12 | ||
|
13 | readonly ITaggedDFABuilder<TTag> m_builder; | |
|
14 | ||
|
15 | public RegularExpressionVisitor(ITaggedDFABuilder<TTag> builder) : base(builder) { | |
|
16 | m_builder = builder; | |
|
17 | } | |
|
18 | ||
|
19 | public override void Visit(EndToken token) { | |
|
20 | base.Visit(token); | |
|
21 | var tagged = token as EndToken<TTag>; | |
|
22 | if (tagged != null) | |
|
23 | m_tags.Add(Index, tagged.Tag); | |
|
24 | } | |
|
25 | ||
|
26 | protected override void MarkFinalState(HashSet<int> state) { | |
|
27 | base.MarkFinalState(state); | |
|
28 | m_builder.SetStateTag(Translate(state), GetStateTags(state)); | |
|
29 | } | |
|
30 | ||
|
31 | TTag[] GetStateTags(IEnumerable<int> state) { | |
|
32 | Debug.Assert(state != null); | |
|
33 | return state.Where(m_tags.ContainsKey).Select(pos => m_tags[pos]).ToArray(); | |
|
34 | } | |
|
35 | ||
|
36 | } | |
|
37 | } |
@@ -0,0 +1,44 | |||
|
1 | using System; | |
|
2 | using System.Threading; | |
|
3 | ||
|
4 | namespace Implab.Components { | |
|
5 | public class LazyAndWeak<T> where T : class { | |
|
6 | ||
|
7 | readonly Func<T> m_factory; | |
|
8 | readonly object m_lock; | |
|
9 | WeakReference m_reference; | |
|
10 | ||
|
11 | ||
|
12 | public LazyAndWeak(Func<T> factory, bool useLock) { | |
|
13 | Safe.ArgumentNotNull(factory, "factory"); | |
|
14 | m_factory = factory; | |
|
15 | m_lock = useLock ? new object() : null; | |
|
16 | } | |
|
17 | ||
|
18 | public LazyAndWeak(Func<T> factory) : this(factory, false) { | |
|
19 | } | |
|
20 | ||
|
21 | public T Value { | |
|
22 | get { | |
|
23 | while (true) { | |
|
24 | var weak = m_reference; | |
|
25 | T value; | |
|
26 | if (weak != null) { | |
|
27 | value = weak.Target as T; | |
|
28 | if (value != null) | |
|
29 | return value; | |
|
30 | } | |
|
31 | ||
|
32 | if (m_lock == null) { | |
|
33 | value = m_factory(); | |
|
34 | ||
|
35 | if (Interlocked.CompareExchange(ref m_reference, new WeakReference(value), weak) == weak) | |
|
36 | return value; | |
|
37 | } else { | |
|
38 | } | |
|
39 | } | |
|
40 | } | |
|
41 | } | |
|
42 | } | |
|
43 | } | |
|
44 |
@@ -1,313 +1,313 | |||
|
1 | 1 | using Implab; |
|
2 | 2 | using System; |
|
3 | 3 | using System.Collections.Generic; |
|
4 | 4 | using System.Linq; |
|
5 | 5 | |
|
6 | 6 | namespace Implab.Automaton { |
|
7 | 7 | public class DFATable : IDFATableBuilder { |
|
8 | 8 | int m_stateCount; |
|
9 | 9 | int m_symbolCount; |
|
10 | 10 | int m_initialState; |
|
11 | 11 | |
|
12 | 12 | readonly HashSet<int> m_finalStates = new HashSet<int>(); |
|
13 | 13 | readonly HashSet<AutomatonTransition> m_transitions = new HashSet<AutomatonTransition>(); |
|
14 | 14 | |
|
15 | 15 | |
|
16 | 16 | #region IDFADefinition implementation |
|
17 | 17 | |
|
18 | 18 | public bool IsFinalState(int s) { |
|
19 | 19 | Safe.ArgumentInRange(s, 0, m_stateCount, "s"); |
|
20 | 20 | |
|
21 | 21 | return m_finalStates.Contains(s); |
|
22 | 22 | } |
|
23 | 23 | |
|
24 | 24 | public IEnumerable<int> FinalStates { |
|
25 | 25 | get { |
|
26 | 26 | return m_finalStates; |
|
27 | 27 | } |
|
28 | 28 | } |
|
29 | 29 | |
|
30 | 30 | public int StateCount { |
|
31 | 31 | get { return m_stateCount; } |
|
32 | 32 | } |
|
33 | 33 | |
|
34 | 34 | public int AlphabetSize { |
|
35 | 35 | get { return m_symbolCount; } |
|
36 | 36 | } |
|
37 | 37 | |
|
38 | 38 | public int InitialState { |
|
39 | 39 | get { return m_initialState; } |
|
40 | 40 | } |
|
41 | 41 | |
|
42 | 42 | #endregion |
|
43 | 43 | |
|
44 | 44 | public void SetInitialState(int s) { |
|
45 | 45 | Safe.ArgumentAssert(s >= 0, "s"); |
|
46 | 46 | m_initialState = s; |
|
47 | 47 | } |
|
48 | 48 | |
|
49 | 49 | public void MarkFinalState(int state) { |
|
50 | 50 | m_finalStates.Add(state); |
|
51 | 51 | } |
|
52 | 52 | |
|
53 | 53 | public void Add(AutomatonTransition item) { |
|
54 | 54 | Safe.ArgumentAssert(item.s1 >= 0, "item"); |
|
55 | 55 | Safe.ArgumentAssert(item.s2 >= 0, "item"); |
|
56 | 56 | Safe.ArgumentAssert(item.edge >= 0, "item"); |
|
57 | 57 | |
|
58 | 58 | m_stateCount = Math.Max(m_stateCount, Math.Max(item.s1, item.s2) + 1); |
|
59 | 59 | m_symbolCount = Math.Max(m_symbolCount, item.edge); |
|
60 | 60 | |
|
61 | 61 | m_transitions.Add(item); |
|
62 | 62 | } |
|
63 | 63 | |
|
64 | 64 | public void Clear() { |
|
65 | 65 | m_stateCount = 0; |
|
66 | 66 | m_symbolCount = 0; |
|
67 | 67 | m_finalStates.Clear(); |
|
68 | 68 | m_transitions.Clear(); |
|
69 | 69 | } |
|
70 | 70 | |
|
71 | 71 | public bool Contains(AutomatonTransition item) { |
|
72 | 72 | return m_transitions.Contains(item); |
|
73 | 73 | } |
|
74 | 74 | |
|
75 | 75 | public void CopyTo(AutomatonTransition[] array, int arrayIndex) { |
|
76 | 76 | m_transitions.CopyTo(array, arrayIndex); |
|
77 | 77 | } |
|
78 | 78 | |
|
79 | 79 | public bool Remove(AutomatonTransition item) { |
|
80 | 80 | m_transitions.Remove(item); |
|
81 | 81 | } |
|
82 | 82 | |
|
83 | 83 | public int Count { |
|
84 | 84 | get { |
|
85 | 85 | return m_transitions.Count; |
|
86 | 86 | } |
|
87 | 87 | } |
|
88 | 88 | |
|
89 | 89 | public bool IsReadOnly { |
|
90 | 90 | get { |
|
91 | 91 | return false; |
|
92 | 92 | } |
|
93 | 93 | } |
|
94 | 94 | |
|
95 | 95 | public IEnumerator<AutomatonTransition> GetEnumerator() { |
|
96 | 96 | return m_transitions.GetEnumerator(); |
|
97 | 97 | } |
|
98 | 98 | |
|
99 | 99 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { |
|
100 | 100 | return GetEnumerator(); |
|
101 | 101 | } |
|
102 | 102 | |
|
103 | 103 | public int[,] CreateTransitionTable() { |
|
104 | 104 | var table = new int[StateCount,AlphabetSize]; |
|
105 | 105 | |
|
106 | 106 | for (int i = 0; i < StateCount; i++) |
|
107 | 107 | for (int j = 0; i < AlphabetSize; j++) |
|
108 |
table[i, j] = |
|
|
108 | table[i, j] = AutomatonConst.UNREACHABLE_STATE; | |
|
109 | 109 | |
|
110 | 110 | foreach (var t in this) |
|
111 | 111 | table[t.s1,t.edge] = t.s2; |
|
112 | 112 | |
|
113 | 113 | return table; |
|
114 | 114 | } |
|
115 | 115 | |
|
116 | 116 | public bool[] CreateFinalStateTable() { |
|
117 | 117 | var table = new bool[StateCount]; |
|
118 | 118 | |
|
119 | 119 | foreach (var s in FinalStates) |
|
120 | 120 | table[s] = true; |
|
121 | 121 | |
|
122 | 122 | return table; |
|
123 | 123 | } |
|
124 | 124 | |
|
125 | 125 | /// <summary>Формирует множества конечных состояний перед началом работы алгоритма минимизации.</summary> |
|
126 | 126 | /// <remarks> |
|
127 | 127 | /// В процессе построения минимального автомата требуется разделить множество состояний, |
|
128 | 128 | /// на два подмножества - конечные состояния и все остальные, после чего эти подмножества |
|
129 | 129 | /// будут резделены на более мелкие. Иногда требуется гарантировать различия конечных сосотяний, |
|
130 | 130 | /// для этого необходимо переопределить даннцю фукнцию, для получения множеств конечных состояний. |
|
131 | 131 | /// </remarks> |
|
132 | 132 | /// <returns>The final states.</returns> |
|
133 | 133 | protected virtual IEnumerable<HashSet<int>> GroupFinalStates() { |
|
134 | 134 | return new HashSet<int>[] { m_finalStates }; |
|
135 | 135 | } |
|
136 | 136 | |
|
137 | 137 | protected void Optimize( |
|
138 | 138 | IDFATableBuilder optimalDFA, |
|
139 | 139 | IDictionary<int,int> alphabetMap, |
|
140 | 140 | IDictionary<int,int> stateMap |
|
141 | 141 | ) { |
|
142 | 142 | Safe.ArgumentNotNull(optimalDFA, "dfa"); |
|
143 | 143 | Safe.ArgumentNotNull(alphabetMap, "alphabetMap"); |
|
144 | 144 | Safe.ArgumentNotNull(stateMap, "stateMap"); |
|
145 | 145 | |
|
146 | 146 | |
|
147 | 147 | var setComparer = new CustomEqualityComparer<HashSet<int>>( |
|
148 | 148 | (x, y) => x.SetEquals(y), |
|
149 | 149 | s => s.Sum(x => x.GetHashCode()) |
|
150 | 150 | ); |
|
151 | 151 | |
|
152 | 152 | var optimalStates = new HashSet<HashSet<int>>(setComparer); |
|
153 | 153 | var queue = new HashSet<HashSet<int>>(setComparer); |
|
154 | 154 | |
|
155 | 155 | // получаем конечные состояния, сгруппированные по маркерам |
|
156 | 156 | optimalStates.UnionWith( |
|
157 | 157 | GroupFinalStates() |
|
158 | 158 | ); |
|
159 | 159 | |
|
160 | 160 | var state = new HashSet<int>( |
|
161 | 161 | Enumerable |
|
162 | 162 | .Range(0, m_stateCount - 1) |
|
163 | 163 | .Where(i => !m_finalStates.Contains(i)) |
|
164 | 164 | ); |
|
165 | 165 | |
|
166 | 166 | optimalStates.Add(state); |
|
167 | 167 | queue.Add(state); |
|
168 | 168 | |
|
169 | 169 | var rmap = m_transitions |
|
170 | 170 | .GroupBy(t => t.s2) |
|
171 | 171 | .ToLookup( |
|
172 | 172 | g => g.Key, // s2 |
|
173 | 173 | g => g.ToLookup(t => t.edge, t => t.s1) |
|
174 | 174 | ); |
|
175 | 175 | |
|
176 | 176 | while (queue.Count > 0) { |
|
177 | 177 | var stateA = queue.First(); |
|
178 | 178 | queue.Remove(stateA); |
|
179 | 179 | |
|
180 | 180 | for (int c = 0; c < m_symbolCount; c++) { |
|
181 | 181 | var stateX = new HashSet<int>(); |
|
182 | 182 | foreach(var a in stateA) |
|
183 | 183 | stateX.UnionWith(rmap[a][c]); // all states from wich 'c' leads to 'a' |
|
184 | 184 | |
|
185 | 185 | foreach (var stateY in optimalStates.ToArray()) { |
|
186 | 186 | if (stateX.Overlaps(stateY) && !stateY.IsSubsetOf(stateX)) { |
|
187 | 187 | var stateR1 = new HashSet<int>(stateY); |
|
188 | 188 | var stateR2 = new HashSet<int>(stateY); |
|
189 | 189 | |
|
190 | 190 | stateR1.IntersectWith(stateX); |
|
191 | 191 | stateR2.ExceptWith(stateX); |
|
192 | 192 | |
|
193 | 193 | optimalStates.Remove(stateY); |
|
194 | 194 | optimalStates.Add(stateR1); |
|
195 | 195 | optimalStates.Add(stateR2); |
|
196 | 196 | |
|
197 | 197 | if (queue.Contains(stateY)) { |
|
198 | 198 | queue.Remove(stateY); |
|
199 | 199 | queue.Add(stateR1); |
|
200 | 200 | queue.Add(stateR2); |
|
201 | 201 | } else { |
|
202 | 202 | queue.Add(stateR1.Count <= stateR2.Count ? stateR1 : stateR2); |
|
203 | 203 | } |
|
204 | 204 | } |
|
205 | 205 | } |
|
206 | 206 | } |
|
207 | 207 | } |
|
208 | 208 | |
|
209 | 209 | // карта получения оптимального состояния по соотвествующему ему простому состоянию |
|
210 | 210 | var nextState = 0; |
|
211 | 211 | foreach (var item in optimalStates) { |
|
212 | 212 | var id = nextState++; |
|
213 | 213 | foreach (var s in item) |
|
214 | 214 | stateMap[s] = id; |
|
215 | 215 | } |
|
216 | 216 | |
|
217 | 217 | // получаем минимальный алфавит |
|
218 | 218 | // входные символы не различимы, если Move(s,a1) == Move(s,a2), для любого s |
|
219 | 219 | // для этого используем алгоритм кластеризации, сначала |
|
220 | 220 | // считаем, что все символы не различимы |
|
221 | 221 | |
|
222 | 222 | var minClasses = new HashSet<HashSet<int>>(setComparer); |
|
223 | 223 | var alphaQueue = new Queue<HashSet<int>>(); |
|
224 | 224 | alphaQueue.Enqueue(new HashSet<int>(Enumerable.Range(0,AlphabetSize))); |
|
225 | 225 | |
|
226 | 226 | // для всех состояний, будем проверять каждый класс на различимость, |
|
227 | 227 | // т.е. символы различимы, если они приводят к разным состояниям |
|
228 | 228 | for (int s = 0 ; s < optimalStates.Count; s++) { |
|
229 | 229 | var newQueue = new Queue<HashSet<int>>(); |
|
230 | 230 | |
|
231 | 231 | foreach (var A in alphaQueue) { |
|
232 | 232 | // классы из одного символа делить бесполезно, переводим их сразу в |
|
233 | 233 | // результирующий алфавит |
|
234 | 234 | if (A.Count == 1) { |
|
235 | 235 | minClasses.Add(A); |
|
236 | 236 | continue; |
|
237 | 237 | } |
|
238 | 238 | |
|
239 | 239 | // различаем классы символов, которые переводят в различные оптимальные состояния |
|
240 | 240 | // optimalState -> alphaClass |
|
241 | 241 | var classes = new Dictionary<int, HashSet<int>>(); |
|
242 | 242 | |
|
243 | 243 | foreach (var term in A) { |
|
244 | 244 | // ищем все переходы класса по символу term |
|
245 | 245 | var res = m_transitions.Where(t => stateMap[t.s1] == s && t.edge == term).Select(t => stateMap[t.s2]).ToArray(); |
|
246 | 246 | |
|
247 | 247 | var s2 = res.Length > 0 ? res[0] : -1; |
|
248 | 248 | |
|
249 | 249 | HashSet<int> a2; |
|
250 | 250 | if (!classes.TryGetValue(s2, out a2)) { |
|
251 | 251 | a2 = new HashSet<int>(); |
|
252 | 252 | newQueue.Enqueue(a2); |
|
253 | 253 | classes[s2] = a2; |
|
254 | 254 | } |
|
255 | 255 | a2.Add(term); |
|
256 | 256 | } |
|
257 | 257 | } |
|
258 | 258 | |
|
259 | 259 | if (newQueue.Count == 0) |
|
260 | 260 | break; |
|
261 | 261 | alphaQueue = newQueue; |
|
262 | 262 | } |
|
263 | 263 | |
|
264 | 264 | // после окончания работы алгоритма в очереди останутся минимальные различимые классы |
|
265 | 265 | // входных символов |
|
266 | 266 | foreach (var A in alphaQueue) |
|
267 | 267 | minClasses.Add(A); |
|
268 | 268 | |
|
269 | 269 | // построение отображения алфавитов входных символов. |
|
270 | 270 | // поскольку символ DFAConst.UNCLASSIFIED_INPUT может иметь |
|
271 | 271 | // специальное значение, тогда сохраним минимальный класс, |
|
272 | 272 | // содержащий этот символ на томже месте. |
|
273 | 273 | |
|
274 | 274 | var nextCls = 0; |
|
275 | 275 | foreach (var item in minClasses) { |
|
276 |
if (nextCls == |
|
|
276 | if (nextCls == AutomatonConst.UNCLASSIFIED_INPUT) | |
|
277 | 277 | nextCls++; |
|
278 | 278 | |
|
279 | 279 | // сохраняем DFAConst.UNCLASSIFIED_INPUT |
|
280 |
var cls = item.Contains( |
|
|
280 | var cls = item.Contains(AutomatonConst.UNCLASSIFIED_INPUT) ? AutomatonConst.UNCLASSIFIED_INPUT : nextCls; | |
|
281 | 281 | |
|
282 | 282 | foreach (var a in item) |
|
283 | 283 | alphabetMap[a] = cls; |
|
284 | 284 | |
|
285 | 285 | nextCls++; |
|
286 | 286 | } |
|
287 | 287 | |
|
288 | 288 | // построение автомата |
|
289 | 289 | optimalDFA.SetInitialState(stateMap[m_initialState]); |
|
290 | 290 | |
|
291 | 291 | foreach (var sf in m_finalStates.Select(s => stateMap[s]).Distinct()) |
|
292 | 292 | optimalDFA.MarkFinalState(sf); |
|
293 | 293 | |
|
294 | 294 | foreach (var t in m_transitions.Select(t => new AutomatonTransition(stateMap[t.s1],stateMap[t.s2],alphabetMap[t.edge])).Distinct()) |
|
295 | 295 | optimalDFA.Add(t); |
|
296 | 296 | } |
|
297 | 297 | |
|
298 | 298 | protected void PrintDFA<TInput, TState>(IAlphabet<TInput> inputAlphabet, IAlphabet<TState> stateAlphabet) { |
|
299 | 299 | Safe.ArgumentNotNull(inputAlphabet, "inputAlphabet"); |
|
300 | 300 | Safe.ArgumentNotNull(stateAlphabet, "stateAlphabet"); |
|
301 | 301 | |
|
302 | 302 | foreach(var t in m_transitions) |
|
303 | 303 | Console.WriteLine( |
|
304 | 304 | "[{0}] -{{{1}}}-> [{2}]{3}", |
|
305 | 305 | String.Join(",", stateAlphabet.GetSymbols(t.s1)), |
|
306 | 306 | String.Join("", inputAlphabet.GetSymbols(t.edge)), |
|
307 | 307 | String.Join(",", stateAlphabet.GetSymbols(t.s2)), |
|
308 | 308 | m_finalStates.Contains(t.s2) ? "$" : "" |
|
309 | 309 | ); |
|
310 | 310 | } |
|
311 | 311 | |
|
312 | 312 | } |
|
313 | 313 | } |
@@ -1,84 +1,84 | |||
|
1 | 1 | using System; |
|
2 | 2 | using System.Collections.Generic; |
|
3 | 3 | using System.Linq; |
|
4 | 4 | |
|
5 | 5 | namespace Implab.Automaton { |
|
6 | 6 | public class MapAlphabet<T> : IAlphabetBuilder<T> { |
|
7 | 7 | readonly Dictionary<T,int> m_map; |
|
8 | 8 | int m_nextCls; |
|
9 | 9 | readonly bool m_supportUnclassified; |
|
10 | 10 | |
|
11 | 11 | public MapAlphabet(bool supportUnclassified, IEqualityComparer<T> comparer) { |
|
12 | 12 | m_map = comparer != null ? new Dictionary<T, int>(comparer) : new Dictionary<T,int>(); |
|
13 | 13 | m_supportUnclassified = supportUnclassified; |
|
14 | 14 | m_nextCls = supportUnclassified ? 1 : 0; |
|
15 | 15 | } |
|
16 | 16 | |
|
17 | 17 | #region IAlphabetBuilder implementation |
|
18 | 18 | |
|
19 | 19 | public int DefineSymbol(T symbol) { |
|
20 | 20 | int cls; |
|
21 | 21 | return m_map.TryGetValue(symbol, out cls) ? cls : DefineSymbol(symbol, m_nextCls); |
|
22 | 22 | } |
|
23 | 23 | |
|
24 | 24 | public int DefineSymbol(T symbol, int cls) { |
|
25 | 25 | Safe.ArgumentAssert(cls >= 0, "cls"); |
|
26 | 26 | |
|
27 | 27 | m_nextCls = Math.Max(cls + 1, m_nextCls); |
|
28 | 28 | m_map.Add(symbol, cls); |
|
29 | 29 | return cls; |
|
30 | 30 | } |
|
31 | 31 | |
|
32 | 32 | public int DefineClass(IEnumerable<T> symbols) { |
|
33 | 33 | return DefineClass(symbols, m_nextCls); |
|
34 | 34 | } |
|
35 | 35 | |
|
36 | 36 | public int DefineClass(IEnumerable<T> symbols, int cls) { |
|
37 | 37 | Safe.ArgumentAssert(cls >= 0, "cls"); |
|
38 | 38 | Safe.ArgumentNotNull(symbols, "symbols"); |
|
39 | 39 | |
|
40 | 40 | m_nextCls = Math.Max(cls + 1, m_nextCls); |
|
41 | 41 | |
|
42 | 42 | foreach (var symbol in symbols) |
|
43 | 43 | m_map[symbol] = cls; |
|
44 | 44 | return cls; |
|
45 | 45 | } |
|
46 | 46 | |
|
47 | 47 | #endregion |
|
48 | 48 | |
|
49 | 49 | #region IAlphabet implementation |
|
50 | 50 | |
|
51 | 51 | public int Translate(T symbol) { |
|
52 | 52 | int cls; |
|
53 | 53 | if (m_map.TryGetValue(symbol, out cls)) |
|
54 | 54 | return cls; |
|
55 | 55 | if (!m_supportUnclassified) |
|
56 | 56 | throw new ArgumentOutOfRangeException("symbol", "The specified symbol isn't in the alphabet"); |
|
57 |
return |
|
|
57 | return AutomatonConst.UNCLASSIFIED_INPUT; | |
|
58 | 58 | } |
|
59 | 59 | |
|
60 | 60 | public int Count { |
|
61 | 61 | get { |
|
62 | 62 | return m_nextCls; |
|
63 | 63 | } |
|
64 | 64 | } |
|
65 | 65 | |
|
66 | 66 | public bool Contains(T symbol) { |
|
67 | 67 | return m_supportUnclassified || m_map.ContainsKey(symbol); |
|
68 | 68 | } |
|
69 | 69 | |
|
70 | 70 | |
|
71 | 71 | public IEnumerable<T> GetSymbols(int cls) { |
|
72 | 72 | Safe.ArgumentAssert(cls > 0, "cls"); |
|
73 | 73 | return m_map.Where(p => p.Value == cls).Select(p => p.Key); |
|
74 | 74 | } |
|
75 | 75 | #endregion |
|
76 | 76 | |
|
77 | 77 | public IEnumerable<KeyValuePair<T,int>> Mappings { |
|
78 | 78 | get { |
|
79 | 79 | return m_map; |
|
80 | 80 | } |
|
81 | 81 | } |
|
82 | 82 | } |
|
83 | 83 | } |
|
84 | 84 |
@@ -1,33 +1,23 | |||
|
1 | using Implab; | |
|
2 | ||
|
3 | namespace Implab.Automaton.RegularExpressions { | |
|
1 | namespace Implab.Automaton.RegularExpressions { | |
|
4 | 2 | /// <summary> |
|
5 | 3 | /// Конечный символ расширенного регулярного выражения, при построении ДКА |
|
6 | 4 | /// используется для определения конечных состояний. |
|
7 | 5 | /// </summary> |
|
8 | public class EndToken<TTag>: Token { | |
|
6 | public class EndToken<TTag>: EndToken { | |
|
9 | 7 | |
|
10 | TTag m_tag; | |
|
8 | readonly TTag m_tag; | |
|
11 | 9 | |
|
12 | 10 | public EndToken(TTag tag) { |
|
13 | 11 | m_tag = tag; |
|
14 | 12 | } |
|
15 | 13 | |
|
16 | 14 | public EndToken() |
|
17 | 15 | : this(default(TTag)) { |
|
18 | 16 | } |
|
19 | 17 | |
|
20 | 18 | public TTag Tag { |
|
21 | 19 | get { return m_tag; } |
|
22 | 20 | } |
|
23 | ||
|
24 | public override void Accept(IVisitor visitor) { | |
|
25 | Safe.ArgumentOfType(visitor, typeof(IVisitor<TTag>), "visitor"); | |
|
26 | Safe.ArgumentNotNull(visitor, "visitor"); | |
|
27 | ((IVisitor<TTag>)visitor).Visit(this); | |
|
28 | } | |
|
29 | public override string ToString() { | |
|
30 | return "#"; | |
|
31 | } | |
|
21 | ||
|
32 | 22 | } |
|
33 | 23 | } |
@@ -1,83 +1,83 | |||
|
1 | 1 | using System.Collections.Generic; |
|
2 | 2 | using System.Linq; |
|
3 | 3 | |
|
4 | 4 | namespace Implab.Automaton.RegularExpressions { |
|
5 |
public class |
|
|
5 | public class TaggedDFA<TInput, TTag> : DFATable, ITaggedDFABuilder<TTag> { | |
|
6 | 6 | |
|
7 | 7 | readonly Dictionary<int,TTag[]> m_tags = new Dictionary<int, TTag[]>(); |
|
8 | 8 | readonly IAlphabet<TInput> m_alphabet; |
|
9 | 9 | |
|
10 |
public |
|
|
10 | public TaggedDFA(IAlphabet<TInput> alphabet) { | |
|
11 | 11 | Safe.ArgumentNotNull(alphabet, "aplhabet"); |
|
12 | 12 | |
|
13 | 13 | m_alphabet = alphabet; |
|
14 | 14 | } |
|
15 | 15 | |
|
16 | 16 | |
|
17 | 17 | public IAlphabet<TInput> InputAlphabet { |
|
18 | 18 | get { |
|
19 | 19 | return m_alphabet; |
|
20 | 20 | } |
|
21 | 21 | } |
|
22 | 22 | |
|
23 | 23 | public void MarkFinalState(int s, TTag[] tags) { |
|
24 | 24 | MarkFinalState(s); |
|
25 | 25 | SetStateTag(s, tags); |
|
26 | 26 | } |
|
27 | 27 | |
|
28 | 28 | public void SetStateTag(int s, TTag[] tags) { |
|
29 | 29 | Safe.ArgumentNotNull(tags, "tags"); |
|
30 | 30 | m_tags[s] = tags; |
|
31 | 31 | } |
|
32 | 32 | |
|
33 | 33 | public TTag[] GetStateTag(int s) { |
|
34 | 34 | TTag[] tags; |
|
35 | 35 | return m_tags.TryGetValue(s, out tags) ? tags : new TTag[0]; |
|
36 | 36 | } |
|
37 | 37 | |
|
38 | 38 | public TTag[][] CreateTagTable() { |
|
39 | 39 | var table = new TTag[StateCount][]; |
|
40 | 40 | |
|
41 | 41 | foreach (var pair in m_tags) |
|
42 | 42 | table[pair.Key] = pair.Value; |
|
43 | 43 | |
|
44 | 44 | return table; |
|
45 | 45 | } |
|
46 | 46 | |
|
47 | 47 | /// <summary> |
|
48 | 48 | /// Optimize the specified alphabet. |
|
49 | 49 | /// </summary> |
|
50 | 50 | /// <param name="alphabet">Пустой алфавит, который будет зполнен в процессе оптимизации.</param> |
|
51 |
public |
|
|
51 | public TaggedDFA<TInput,TTag> Optimize(IAlphabetBuilder<TInput> alphabet) { | |
|
52 | 52 | Safe.ArgumentNotNull(alphabet, "alphabet"); |
|
53 | 53 | |
|
54 |
var dfa = new |
|
|
54 | var dfa = new TaggedDFA<TInput, TTag>(alphabet); | |
|
55 | 55 | |
|
56 | 56 | var states = new DummyAlphabet(StateCount); |
|
57 | 57 | var alphaMap = new Dictionary<int,int>(); |
|
58 | 58 | var stateMap = new Dictionary<int,int>(); |
|
59 | 59 | |
|
60 | 60 | Optimize(dfa, alphaMap, stateMap); |
|
61 | 61 | |
|
62 | 62 | // mark tags in the new DFA |
|
63 | 63 | foreach (var g in m_tags.Where(x => x.Key < StateCount).GroupBy(x => stateMap[x.Key], x => x.Value )) |
|
64 | 64 | dfa.SetStateTag(g.Key, g.SelectMany(x => x).ToArray()); |
|
65 | 65 | |
|
66 | 66 | // make the alphabet for the new DFA |
|
67 | 67 | foreach (var pair in alphaMap) |
|
68 | 68 | alphabet.DefineClass(m_alphabet.GetSymbols(pair.Key), pair.Value); |
|
69 | 69 | |
|
70 | 70 | return dfa; |
|
71 | 71 | } |
|
72 | 72 | |
|
73 | 73 | protected override IEnumerable<HashSet<int>> GroupFinalStates() { |
|
74 | 74 | var arrayComparer = new CustomEqualityComparer<TTag[]>( |
|
75 | 75 | (x,y) => x.Length == y.Length && x.All(it => y.Contains(it)), |
|
76 | 76 | x => x.Sum(it => x.GetHashCode()) |
|
77 | 77 | ); |
|
78 | 78 | return FinalStates.GroupBy(x => m_tags[x], arrayComparer).Select(g => new HashSet<int>(g)); |
|
79 | 79 | } |
|
80 | 80 | |
|
81 | 81 | } |
|
82 | 82 | } |
|
83 | 83 |
@@ -1,206 +1,212 | |||
|
1 | 1 | using Implab; |
|
2 | 2 | using System; |
|
3 | 3 | using System.Collections.Generic; |
|
4 | 4 | using System.Diagnostics; |
|
5 | 5 | using System.Linq; |
|
6 | 6 | |
|
7 | 7 | namespace Implab.Automaton.RegularExpressions { |
|
8 | 8 | /// <summary> |
|
9 | 9 | /// Используется для построения ДКА по регулярному выражению, сначала обходит |
|
10 | 10 | /// регулярное выражение и вычисляет followpos, затем используется метод |
|
11 | 11 | /// <see cref="BuildDFA(IDFADefinition)"/> для построения автомата. |
|
12 | 12 | /// </summary> |
|
13 |
public class RegularExpressionVisitor |
|
|
13 | public class RegularExpressionVisitor : IVisitor { | |
|
14 | 14 | int m_idx; |
|
15 | 15 | Token m_root; |
|
16 | 16 | HashSet<int> m_firstpos; |
|
17 | 17 | HashSet<int> m_lastpos; |
|
18 | 18 | |
|
19 | 19 | readonly Dictionary<int, HashSet<int>> m_followpos = new Dictionary<int, HashSet<int>>(); |
|
20 | 20 | readonly Dictionary<int, int> m_indexes = new Dictionary<int, int>(); |
|
21 | 21 | readonly HashSet<int> m_ends = new HashSet<int>(); |
|
22 | readonly Dictionary<int, TTag> m_tags = new Dictionary<int, TTag>(); | |
|
23 | 22 | |
|
24 | public Dictionary<int, HashSet<int>> FollowposMap { | |
|
25 | get { return m_followpos; } | |
|
23 | readonly IDFATableBuilder m_builder; | |
|
24 | readonly IAlphabetBuilder<HashSet<int>> m_states = new MapAlphabet<HashSet<int>>( | |
|
25 | false, | |
|
26 | new CustomEqualityComparer<HashSet<int>>( | |
|
27 | (x, y) => x.SetEquals(y), | |
|
28 | x => x.Sum(n => n.GetHashCode()) | |
|
29 | ) | |
|
30 | ); | |
|
31 | ||
|
32 | public RegularExpressionVisitor(IDFATableBuilder builder) { | |
|
33 | Safe.ArgumentNotNull(builder, "builder"); | |
|
34 | ||
|
35 | m_builder = builder; | |
|
26 | 36 | } |
|
27 | 37 | |
|
28 |
|
|
|
38 | HashSet<int> Followpos(int pos) { | |
|
29 | 39 | HashSet<int> set; |
|
30 | 40 | return m_followpos.TryGetValue(pos, out set) ? set : m_followpos[pos] = new HashSet<int>(); |
|
31 | 41 | } |
|
32 | 42 | |
|
33 | 43 | bool Nullable(object n) { |
|
34 | 44 | if (n is EmptyToken || n is StarToken) |
|
35 | 45 | return true; |
|
36 | 46 | var altToken = n as AltToken; |
|
37 | 47 | if (altToken != null) |
|
38 | 48 | return Nullable(altToken.Left) || Nullable(altToken.Right); |
|
39 | 49 | var catToken = n as CatToken; |
|
40 | 50 | if (catToken != null) |
|
41 | 51 | return Nullable(catToken.Left) && Nullable(catToken.Right); |
|
42 | 52 | return false; |
|
43 | 53 | } |
|
44 | 54 | |
|
55 | protected int Index { | |
|
56 | get { return m_idx; } | |
|
57 | } | |
|
45 | 58 | |
|
46 | 59 | public void Visit(AltToken token) { |
|
47 | 60 | if (m_root == null) |
|
48 | 61 | m_root = token; |
|
49 | 62 | var firtspos = new HashSet<int>(); |
|
50 | 63 | var lastpos = new HashSet<int>(); |
|
51 | 64 | |
|
52 | 65 | token.Left.Accept(this); |
|
53 | 66 | firtspos.UnionWith(m_firstpos); |
|
54 | 67 | lastpos.UnionWith(m_lastpos); |
|
55 | 68 | |
|
56 | 69 | token.Right.Accept(this); |
|
57 | 70 | firtspos.UnionWith(m_firstpos); |
|
58 | 71 | lastpos.UnionWith(m_lastpos); |
|
59 | 72 | |
|
60 | 73 | m_firstpos = firtspos; |
|
61 | 74 | m_lastpos = lastpos; |
|
62 | 75 | } |
|
63 | 76 | |
|
64 | 77 | public void Visit(StarToken token) { |
|
65 | 78 | if (m_root == null) |
|
66 | 79 | m_root = token; |
|
67 | 80 | token.Token.Accept(this); |
|
68 | 81 | |
|
69 | 82 | foreach (var i in m_lastpos) |
|
70 | 83 | Followpos(i).UnionWith(m_firstpos); |
|
71 | 84 | } |
|
72 | 85 | |
|
73 | 86 | public void Visit(CatToken token) { |
|
74 | 87 | if (m_root == null) |
|
75 | 88 | m_root = token; |
|
76 | 89 | |
|
77 | 90 | var firtspos = new HashSet<int>(); |
|
78 | 91 | var lastpos = new HashSet<int>(); |
|
79 | 92 | token.Left.Accept(this); |
|
80 | 93 | firtspos.UnionWith(m_firstpos); |
|
81 | 94 | var leftLastpos = m_lastpos; |
|
82 | 95 | |
|
83 | 96 | token.Right.Accept(this); |
|
84 | 97 | lastpos.UnionWith(m_lastpos); |
|
85 | 98 | var rightFirstpos = m_firstpos; |
|
86 | 99 | |
|
87 | 100 | if (Nullable(token.Left)) |
|
88 | 101 | firtspos.UnionWith(rightFirstpos); |
|
89 | 102 | |
|
90 | 103 | if (Nullable(token.Right)) |
|
91 | 104 | lastpos.UnionWith(leftLastpos); |
|
92 | 105 | |
|
93 | 106 | m_firstpos = firtspos; |
|
94 | 107 | m_lastpos = lastpos; |
|
95 | 108 | |
|
96 | 109 | foreach (var i in leftLastpos) |
|
97 | 110 | Followpos(i).UnionWith(rightFirstpos); |
|
98 | 111 | |
|
99 | 112 | } |
|
100 | 113 | |
|
101 | 114 | public void Visit(EmptyToken token) { |
|
102 | 115 | if (m_root == null) |
|
103 | 116 | m_root = token; |
|
104 | 117 | } |
|
105 | 118 | |
|
106 | 119 | public void Visit(SymbolToken token) { |
|
107 | 120 | if (m_root == null) |
|
108 | 121 | m_root = token; |
|
109 | 122 | m_idx++; |
|
110 | 123 | m_indexes[m_idx] = token.Value; |
|
111 | 124 | m_firstpos = new HashSet<int>(new[] { m_idx }); |
|
112 | 125 | m_lastpos = new HashSet<int>(new[] { m_idx }); |
|
113 | 126 | } |
|
114 | 127 | |
|
115 |
public void Visit(EndToken |
|
|
128 | public virtual void Visit(EndToken token) { | |
|
116 | 129 | if (m_root == null) |
|
117 | 130 | m_root = token; |
|
118 | 131 | m_idx++; |
|
119 |
m_indexes[m_idx] = |
|
|
120 | m_firstpos = new HashSet<int>(new[] { m_idx }); | |
|
121 | m_lastpos = new HashSet<int>(new[] { m_idx }); | |
|
122 | Followpos(m_idx); | |
|
123 | m_ends.Add(m_idx); | |
|
124 | m_tags.Add(m_idx, token.Tag); | |
|
125 | } | |
|
126 | ||
|
127 | public void Visit(EndToken token) { | |
|
128 | if (m_root == null) | |
|
129 | m_root = token; | |
|
130 | m_idx++; | |
|
131 | m_indexes[m_idx] = DFAConst.UNCLASSIFIED_INPUT; | |
|
132 | m_indexes[m_idx] = AutomatonConst.UNCLASSIFIED_INPUT; | |
|
132 | 133 | m_firstpos = new HashSet<int>(new[] { m_idx }); |
|
133 | 134 | m_lastpos = new HashSet<int>(new[] { m_idx }); |
|
134 | 135 | Followpos(m_idx); |
|
135 | 136 | m_ends.Add(m_idx); |
|
136 | 137 | } |
|
137 | 138 | |
|
138 |
public void BuildDFA( |
|
|
139 | Safe.ArgumentNotNull(dfa,"dfa"); | |
|
139 | public void BuildDFA() { | |
|
140 | AddState(m_firstpos); | |
|
141 | SetInitialState(m_firstpos); | |
|
140 | 142 | |
|
141 | var states = new MapAlphabet<HashSet<int>>( | |
|
142 | false, | |
|
143 | new CustomEqualityComparer<HashSet<int>>( | |
|
144 | (x, y) => x.SetEquals(y), | |
|
145 | x => x.Sum(n => n.GetHashCode()) | |
|
146 | )); | |
|
147 | ||
|
148 | var initialState = states.DefineSymbol(m_firstpos); | |
|
149 | dfa.SetInitialState(initialState); | |
|
150 | ||
|
151 | var tags = GetStateTags(m_firstpos); | |
|
152 | if (tags != null && tags.Length > 0) | |
|
153 | dfa.MarkFinalState(initialState, tags); | |
|
143 | if(IsFinal(m_firstpos)) | |
|
144 | MarkFinalState(m_firstpos); | |
|
154 | 145 | |
|
155 | 146 | var inputMax = m_indexes.Values.Max(); |
|
156 | 147 | var queue = new Queue<HashSet<int>>(); |
|
157 | 148 | |
|
158 | 149 | queue.Enqueue(m_firstpos); |
|
159 | 150 | |
|
160 | 151 | while (queue.Count > 0) { |
|
161 |
var s |
|
|
162 | var s1 = states.Translate(state); | |
|
163 | Debug.Assert(s1 != DFAConst.UNCLASSIFIED_INPUT); | |
|
152 | var s1 = queue.Dequeue(); | |
|
164 | 153 | |
|
165 | 154 | for (int a = 0; a <= inputMax; a++) { |
|
166 |
var |
|
|
167 |
foreach (var p in s |
|
|
155 | var s2 = new HashSet<int>(); | |
|
156 | foreach (var p in s1) { | |
|
168 | 157 | if (m_indexes[p] == a) { |
|
169 |
|
|
|
158 | s2.UnionWith(Followpos(p)); | |
|
170 | 159 | } |
|
171 | 160 | } |
|
172 |
if ( |
|
|
173 |
i |
|
|
174 |
|
|
|
175 |
s2 |
|
|
176 |
|
|
|
177 |
|
|
|
161 | if (s2.Count > 0) { | |
|
162 | if (!HasState(s2)) { | |
|
163 | AddState(s2); | |
|
164 | if (IsFinal(s2)) | |
|
165 | MarkFinalState(s2); | |
|
166 | ||
|
167 | queue.Enqueue(s2); | |
|
168 | } | |
|
178 | 169 | |
|
179 |
|
|
|
180 | ||
|
181 | dfa.MarkFinalState(s2); | |
|
182 | tags = GetStateTags(next); | |
|
183 | if (tags != null && tags.Length > 0) | |
|
184 | dfa.SetStateTag(s2, tags); | |
|
185 | } | |
|
186 | ||
|
187 | queue.Enqueue(next); | |
|
188 | } | |
|
189 | dfa.Add(new AutomatonTransition(s1, s2, a)); | |
|
170 | DefineTransition(s1, s2, a); | |
|
190 | 171 | } |
|
172 | ||
|
191 | 173 | } |
|
192 | 174 | } |
|
193 | 175 | } |
|
194 | 176 | |
|
177 | protected bool HasState(HashSet<int> state) { | |
|
178 | return m_states.Contains(state); | |
|
179 | } | |
|
180 | ||
|
181 | protected void AddState(HashSet<int> state) { | |
|
182 | Debug.Assert(!HasState(state)); | |
|
183 | ||
|
184 | m_states.DefineSymbol(state); | |
|
185 | } | |
|
186 | ||
|
187 | protected int Translate(HashSet<int> state) { | |
|
188 | Debug.Assert(HasState(state)); | |
|
189 | ||
|
190 | return m_states.Translate(state); | |
|
191 | } | |
|
192 | ||
|
193 | protected virtual void SetInitialState(HashSet<int> state) { | |
|
194 | m_builder.SetInitialState(Translate(state)); | |
|
195 | } | |
|
196 | ||
|
197 | protected virtual void MarkFinalState(HashSet<int> state) { | |
|
198 | m_builder.MarkFinalState(Translate(state)); | |
|
199 | } | |
|
200 | ||
|
201 | protected virtual void DefineTransition(HashSet<int> s1, HashSet<int> s2, int ch) { | |
|
202 | ||
|
203 | m_builder.Add(new AutomatonTransition(Translate(s1), Translate(s2), ch)); | |
|
204 | } | |
|
205 | ||
|
195 | 206 | bool IsFinal(IEnumerable<int> state) { |
|
196 | 207 | Debug.Assert(state != null); |
|
197 | 208 | return state.Any(m_ends.Contains); |
|
198 | 209 | } |
|
199 | 210 | |
|
200 | TTag[] GetStateTags(IEnumerable<int> state) { | |
|
201 | Debug.Assert(state != null); | |
|
202 | return state.Where(m_tags.ContainsKey).Select(pos => m_tags[pos]).ToArray(); | |
|
203 | } | |
|
204 | ||
|
205 | 211 | } |
|
206 | 212 | } |
@@ -1,63 +1,63 | |||
|
1 | 1 | using Implab; |
|
2 | 2 | using System; |
|
3 | 3 | using System.Linq; |
|
4 | 4 | |
|
5 | 5 | namespace Implab.Automaton.RegularExpressions { |
|
6 | 6 | public abstract class Token { |
|
7 | 7 | public abstract void Accept(IVisitor visitor); |
|
8 | 8 | |
|
9 |
public Token E |
|
|
9 | public Token End() { | |
|
10 | 10 | return Cat(new EndToken()); |
|
11 | 11 | } |
|
12 | 12 | |
|
13 | 13 | public Token Tag<TTag>(TTag tag) { |
|
14 | 14 | return Cat(new EndToken<TTag>(tag)); |
|
15 | 15 | } |
|
16 | 16 | |
|
17 | 17 | public Token Cat(Token right) { |
|
18 | 18 | return new CatToken(this, right); |
|
19 | 19 | } |
|
20 | 20 | |
|
21 | 21 | public Token Or(Token right) { |
|
22 | 22 | return new AltToken(this, right); |
|
23 | 23 | } |
|
24 | 24 | |
|
25 | 25 | public Token Optional() { |
|
26 | 26 | return Or(new EmptyToken()); |
|
27 | 27 | } |
|
28 | 28 | |
|
29 | 29 | public Token EClosure() { |
|
30 | 30 | return new StarToken(this); |
|
31 | 31 | } |
|
32 | 32 | |
|
33 | 33 | public Token Closure() { |
|
34 | 34 | return Cat(new StarToken(this)); |
|
35 | 35 | } |
|
36 | 36 | |
|
37 | 37 | public Token Repeat(int count) { |
|
38 | 38 | Token token = null; |
|
39 | 39 | |
|
40 | 40 | for (int i = 0; i < count; i++) |
|
41 | 41 | token = token != null ? token.Cat(this) : this; |
|
42 | 42 | return token ?? new EmptyToken(); |
|
43 | 43 | } |
|
44 | 44 | |
|
45 | 45 | public Token Repeat(int min, int max) { |
|
46 | 46 | if (min > max || min < 1) |
|
47 | 47 | throw new ArgumentOutOfRangeException(); |
|
48 | 48 | var token = Repeat(min); |
|
49 | 49 | |
|
50 | 50 | for (int i = min; i < max; i++) |
|
51 | 51 | token = token.Cat( Optional() ); |
|
52 | 52 | return token; |
|
53 | 53 | } |
|
54 | 54 | |
|
55 | 55 | public static Token New(params int[] set) { |
|
56 | 56 | Safe.ArgumentNotNull(set, "set"); |
|
57 | 57 | Token token = null; |
|
58 | 58 | foreach(var c in set.Distinct()) |
|
59 | 59 | token = token == null ? new SymbolToken(c) : token.Or(new SymbolToken(c)); |
|
60 | 60 | return token; |
|
61 | 61 | } |
|
62 | 62 | } |
|
63 | 63 | } |
@@ -1,100 +1,99 | |||
|
1 | 1 | using Implab; |
|
2 | 2 | using System; |
|
3 | 3 | using System.Collections.Generic; |
|
4 | 4 | using System.Linq; |
|
5 | 5 | using Implab.Automaton; |
|
6 | 6 | using Implab.Automaton.RegularExpressions; |
|
7 | 7 | |
|
8 | 8 | namespace Implab.Formats { |
|
9 | 9 | /// <summary> |
|
10 | 10 | /// Базовый абстрактный класс. Грамматика, позволяет формулировать выражения над алфавитом типа <c>char</c>. |
|
11 | 11 | /// </summary> |
|
12 |
public abstract class Grammar<TSymbol |
|
|
12 | public abstract class Grammar<TSymbol> { | |
|
13 | 13 | |
|
14 | 14 | protected abstract IAlphabetBuilder<TSymbol> AlphabetBuilder { |
|
15 | 15 | get; |
|
16 | 16 | } |
|
17 | 17 | |
|
18 |
protected SymbolToken |
|
|
19 |
return new SymbolToken |
|
|
18 | protected SymbolToken UnclassifiedToken() { | |
|
19 | return new SymbolToken(AutomatonConst.UNCLASSIFIED_INPUT); | |
|
20 | 20 | } |
|
21 | 21 | |
|
22 | 22 | protected void DefineAlphabet(IEnumerable<TSymbol> alphabet) { |
|
23 | 23 | Safe.ArgumentNotNull(alphabet, "alphabet"); |
|
24 | 24 | |
|
25 | 25 | foreach (var ch in alphabet) |
|
26 | 26 | AlphabetBuilder.DefineSymbol(ch); |
|
27 | 27 | } |
|
28 | 28 | |
|
29 |
protected Token |
|
|
30 |
return Token |
|
|
29 | protected Token SymbolToken(TSymbol symbol) { | |
|
30 | return Token.New(TranslateOrAdd(symbol)); | |
|
31 | 31 | } |
|
32 | 32 | |
|
33 |
protected Token |
|
|
33 | protected Token SymbolToken(IEnumerable<TSymbol> symbols) { | |
|
34 | 34 | Safe.ArgumentNotNull(symbols, "symbols"); |
|
35 | 35 | |
|
36 |
return Token |
|
|
36 | return Token.New(TranslateOrAdd(symbols).ToArray()); | |
|
37 | 37 | } |
|
38 | 38 | |
|
39 |
protected Token |
|
|
39 | protected Token SymbolSetToken(params TSymbol[] set) { | |
|
40 | 40 | return SymbolToken(set); |
|
41 | 41 | } |
|
42 | 42 | |
|
43 | 43 | int TranslateOrAdd(TSymbol ch) { |
|
44 | 44 | var t = AlphabetBuilder.Translate(ch); |
|
45 |
if (t == |
|
|
45 | if (t == AutomatonConst.UNCLASSIFIED_INPUT) | |
|
46 | 46 | t = AlphabetBuilder.DefineSymbol(ch); |
|
47 | 47 | return t; |
|
48 | 48 | } |
|
49 | 49 | |
|
50 | 50 | IEnumerable<int> TranslateOrAdd(IEnumerable<TSymbol> symbols) { |
|
51 | 51 | return symbols.Distinct().Select(TranslateOrAdd); |
|
52 | 52 | } |
|
53 | 53 | |
|
54 | 54 | int TranslateOrDie(TSymbol ch) { |
|
55 | 55 | var t = AlphabetBuilder.Translate(ch); |
|
56 |
if (t == |
|
|
56 | if (t == AutomatonConst.UNCLASSIFIED_INPUT) | |
|
57 | 57 | throw new ApplicationException(String.Format("Symbol '{0}' is UNCLASSIFIED", ch)); |
|
58 | 58 | return t; |
|
59 | 59 | } |
|
60 | 60 | |
|
61 | 61 | IEnumerable<int> TranslateOrDie(IEnumerable<TSymbol> symbols) { |
|
62 | 62 | return symbols.Distinct().Select(TranslateOrDie); |
|
63 | 63 | } |
|
64 | 64 | |
|
65 |
protected Token |
|
|
65 | protected Token SymbolTokenExcept(IEnumerable<TSymbol> symbols) { | |
|
66 | 66 | Safe.ArgumentNotNull(symbols, "symbols"); |
|
67 | 67 | |
|
68 |
return Token |
|
|
68 | return Token.New( Enumerable.Range(0, AlphabetBuilder.Count).Except(TranslateOrDie(symbols)).ToArray() ); | |
|
69 | 69 | } |
|
70 | 70 | |
|
71 | 71 | protected abstract IndexedAlphabetBase<TSymbol> CreateAlphabet(); |
|
72 | 72 | |
|
73 |
protected ScannerContext<TTag> BuildScannerContext |
|
|
73 | protected ScannerContext<TTag> BuildScannerContext<TTag>(Token regexp) { | |
|
74 | 74 | |
|
75 | 75 | var dfa = new RegularDFA<TSymbol, TTag>(AlphabetBuilder); |
|
76 | 76 | |
|
77 | var visitor = new RegularExpressionVisitor<TTag>(); | |
|
78 |
regexp.Accept( |
|
|
79 | ||
|
80 | visitor.BuildDFA(dfa); | |
|
77 | var visitor = new RegularExpressionVisitor<TTag>(dfa); | |
|
78 | regexp.Accept(visitor); | |
|
79 | visitor.BuildDFA(); | |
|
81 | 80 | |
|
82 | 81 | if (dfa.IsFinalState(dfa.InitialState)) |
|
83 | 82 | throw new ApplicationException("The specified language contains empty token"); |
|
84 | 83 | |
|
85 | 84 | var ab = CreateAlphabet(); |
|
86 | 85 | var optimal = dfa.Optimize(ab); |
|
87 | 86 | |
|
88 | 87 | return new ScannerContext<TTag>( |
|
89 | 88 | optimal.CreateTransitionTable(), |
|
90 | 89 | optimal.CreateFinalStateTable(), |
|
91 | 90 | optimal.CreateTagTable(), |
|
92 | 91 | optimal.InitialState, |
|
93 | 92 | ab.GetTranslationMap() |
|
94 | 93 | ); |
|
95 | 94 | } |
|
96 | 95 | |
|
97 | 96 | } |
|
98 | 97 | |
|
99 | 98 | |
|
100 | 99 | } |
@@ -1,11 +1,10 | |||
|
1 | 1 | namespace Implab.Formats.JSON { |
|
2 | 2 | /// <summary> |
|
3 | 3 | /// internal |
|
4 | 4 | /// </summary> |
|
5 | 5 | enum JSONElementContext { |
|
6 | 6 | None, |
|
7 | 7 | Object, |
|
8 |
Array |
|
|
9 | Closed | |
|
8 | Array | |
|
10 | 9 | } |
|
11 | 10 | } |
@@ -1,109 +1,111 | |||
|
1 | 1 | using System.Linq; |
|
2 | 2 | using Implab.Automaton.RegularExpressions; |
|
3 | 3 | using System; |
|
4 | 4 | using Implab.Automaton; |
|
5 | 5 | |
|
6 | 6 | namespace Implab.Formats.JSON { |
|
7 |
class JSONGrammar : Grammar<char |
|
|
7 | class JSONGrammar : Grammar<char> { | |
|
8 | 8 | public enum TokenType { |
|
9 | 9 | None, |
|
10 | 10 | BeginObject, |
|
11 | 11 | EndObject, |
|
12 | 12 | BeginArray, |
|
13 | 13 | EndArray, |
|
14 | 14 | String, |
|
15 | 15 | Number, |
|
16 | 16 | Literal, |
|
17 | 17 | NameSeparator, |
|
18 | 18 | ValueSeparator, |
|
19 | 19 | |
|
20 | 20 | StringBound, |
|
21 | 21 | EscapedChar, |
|
22 | 22 | UnescapedChar, |
|
23 | 23 | EscapedUnicode |
|
24 | 24 | } |
|
25 | 25 | |
|
26 | 26 | static Lazy<JSONGrammar> _instance = new Lazy<JSONGrammar>(); |
|
27 | 27 | |
|
28 | 28 | public static JSONGrammar Instance { |
|
29 | 29 | get { return _instance.Value; } |
|
30 | 30 | } |
|
31 | 31 | |
|
32 |
readonly ScannerContext<TokenType> m_json |
|
|
33 |
readonly ScannerContext<TokenType> m_string |
|
|
32 | readonly ScannerContext<TokenType> m_jsonExpression; | |
|
33 | readonly ScannerContext<TokenType> m_stringExpression; | |
|
34 | 34 | |
|
35 | 35 | public JSONGrammar() { |
|
36 | 36 | DefineAlphabet(Enumerable.Range(0, 0x20).Select(x => (char)x)); |
|
37 | 37 | var hexDigit = SymbolRangeToken('a','f').Or(SymbolRangeToken('A','F')).Or(SymbolRangeToken('0','9')); |
|
38 | 38 | var digit9 = SymbolRangeToken('1', '9'); |
|
39 | 39 | var zero = SymbolToken('0'); |
|
40 | 40 | var digit = zero.Or(digit9); |
|
41 | 41 | var dot = SymbolToken('.'); |
|
42 | 42 | var minus = SymbolToken('-'); |
|
43 | 43 | var sign = SymbolSetToken('-', '+'); |
|
44 | 44 | var expSign = SymbolSetToken('e', 'E'); |
|
45 | 45 | var letters = SymbolRangeToken('a', 'z'); |
|
46 | 46 | var integer = zero.Or(digit9.Cat(digit.EClosure())); |
|
47 | 47 | var frac = dot.Cat(digit.Closure()); |
|
48 | 48 | var exp = expSign.Cat(sign.Optional()).Cat(digit.Closure()); |
|
49 | 49 | var quote = SymbolToken('"'); |
|
50 | 50 | var backSlash = SymbolToken('\\'); |
|
51 | 51 | var specialEscapeChars = SymbolSetToken('\\', '"', '/', 'b', 'f', 't', 'n', 'r'); |
|
52 | 52 | var unicodeEspace = SymbolToken('u').Cat(hexDigit.Repeat(4)); |
|
53 | 53 | var whitespace = SymbolSetToken('\n', '\r', '\t', ' ').EClosure(); |
|
54 | 54 | var beginObject = whitespace.Cat(SymbolToken('{')).Cat(whitespace); |
|
55 | 55 | var endObject = whitespace.Cat(SymbolToken('}')).Cat(whitespace); |
|
56 | 56 | var beginArray = whitespace.Cat(SymbolToken('[')).Cat(whitespace); |
|
57 | 57 | var endArray = whitespace.Cat(SymbolToken(']')).Cat(whitespace); |
|
58 | 58 | var nameSep = whitespace.Cat(SymbolToken(':')).Cat(whitespace); |
|
59 | 59 | var valueSep = whitespace.Cat(SymbolToken(',')).Cat(whitespace); |
|
60 | 60 | |
|
61 | 61 | var number = minus.Optional().Cat(integer).Cat(frac.Optional()).Cat(exp.Optional()); |
|
62 | 62 | var literal = letters.Closure(); |
|
63 | 63 | var unescaped = SymbolTokenExcept(Enumerable.Range(0, 0x20).Union(new int[] { '\\', '"' }).Select(x => (char)x)); |
|
64 | 64 | |
|
65 | 65 | var jsonExpression = |
|
66 | 66 | number.Tag(TokenType.Number) |
|
67 | 67 | .Or(literal.Tag(TokenType.Literal)) |
|
68 | 68 | .Or(quote.Tag(TokenType.StringBound)) |
|
69 | 69 | .Or(beginObject.Tag(TokenType.BeginObject)) |
|
70 | 70 | .Or(endObject.Tag(TokenType.EndObject)) |
|
71 | 71 | .Or(beginArray.Tag(TokenType.BeginArray)) |
|
72 | 72 | .Or(endArray.Tag(TokenType.EndArray)) |
|
73 | 73 | .Or(nameSep.Tag(TokenType.NameSeparator)) |
|
74 | 74 | .Or(valueSep.Tag(TokenType.ValueSeparator)); |
|
75 | 75 | |
|
76 | 76 | |
|
77 | 77 | var jsonStringExpression = |
|
78 | 78 | quote.Tag(TokenType.StringBound) |
|
79 | 79 | .Or(backSlash.Cat(specialEscapeChars).Tag(TokenType.EscapedChar)) |
|
80 | 80 | .Or(backSlash.Cat(unicodeEspace).Tag(TokenType.EscapedUnicode)) |
|
81 | 81 | .Or(unescaped.Closure().Tag(TokenType.UnescapedChar)); |
|
82 | 82 | |
|
83 | 83 | |
|
84 |
m_json |
|
|
85 |
m_string |
|
|
84 | m_jsonExpression = BuildScannerContext<TokenType>(jsonExpression); | |
|
85 | m_stringExpression = BuildScannerContext<TokenType>(jsonStringExpression); | |
|
86 | ||
|
87 | ||
|
86 | 88 | } |
|
87 | 89 | |
|
88 |
public ScannerContext<TokenType> Json |
|
|
90 | public ScannerContext<TokenType> JsonExpression { | |
|
89 | 91 | get { |
|
90 |
return m_json |
|
|
92 | return m_jsonExpression; | |
|
91 | 93 | } |
|
92 | 94 | } |
|
93 | 95 | |
|
94 |
public ScannerContext<TokenType> JsonString |
|
|
96 | public ScannerContext<TokenType> JsonStringExpression { | |
|
95 | 97 | get { |
|
96 |
return m_string |
|
|
98 | return m_stringExpression; | |
|
97 | 99 | } |
|
98 | 100 | } |
|
99 | 101 | |
|
100 |
Token |
|
|
102 | Token SymbolRangeToken(char start, char stop) { | |
|
101 | 103 | return SymbolToken(Enumerable.Range(start,stop - start).Cast<char>()); |
|
102 | 104 | } |
|
103 | 105 | |
|
104 | 106 | protected override IAlphabetBuilder<char> CreateAlphabet() { |
|
105 | 107 | return new CharAlphabet(); |
|
106 | 108 | } |
|
107 | 109 | |
|
108 | 110 | } |
|
109 | 111 | } |
@@ -1,280 +1,295 | |||
|
1 | 1 | using System; |
|
2 | 2 | using System.Diagnostics; |
|
3 | 3 | using System.IO; |
|
4 | 4 | using Implab.Automaton; |
|
5 | 5 | using Implab.Automaton.RegularExpressions; |
|
6 | 6 | using System.Linq; |
|
7 | 7 | using Implab.Components; |
|
8 | 8 | |
|
9 | 9 | namespace Implab.Formats.JSON { |
|
10 | 10 | /// <summary> |
|
11 | 11 | /// internal |
|
12 | 12 | /// </summary> |
|
13 | 13 | public struct JSONParserContext { |
|
14 | 14 | public string memberName; |
|
15 | 15 | public JSONElementContext elementContext; |
|
16 | 16 | } |
|
17 | 17 | |
|
18 | 18 | /// <summary> |
|
19 | 19 | /// Pull парсер JSON данных. |
|
20 | 20 | /// </summary> |
|
21 | 21 | /// <remarks> |
|
22 | 22 | /// Следует отметить отдельную интерпретацию свойства <see cref="Level"/>, |
|
23 | 23 | /// оно означает текущий уровень вложенности объектов, однако закрывающий |
|
24 | 24 | /// элемент объекта и массива имеет уровень меньше, чем сам объект. |
|
25 | 25 | /// <code> |
|
26 | 26 | /// { // Level = 1 |
|
27 | 27 | /// "name" : "Peter", // Level = 1 |
|
28 | 28 | /// "address" : { // Level = 2 |
|
29 | 29 | /// city : "Stern" // Level = 2 |
|
30 | 30 | /// } // Level = 1 |
|
31 | 31 | /// } // Level = 0 |
|
32 | 32 | /// </code> |
|
33 | 33 | /// </remarks> |
|
34 | 34 | public class JSONParser : Disposable { |
|
35 | 35 | |
|
36 | 36 | enum MemberContext { |
|
37 | 37 | MemberName, |
|
38 | 38 | MemberValue |
|
39 | 39 | } |
|
40 | 40 | |
|
41 | #region Parser rules | |
|
41 | 42 | struct ParserContext { |
|
42 | DFAStateDescriptior<object> | |
|
43 | } | |
|
43 | readonly int[,] m_dfa; | |
|
44 | int m_state; | |
|
45 | ||
|
46 | readonly JSONElementContext m_elementContext; | |
|
44 | 47 | |
|
45 | static readonly EnumAlphabet<JsonTokenType> _alphabet = EnumAlphabet<JsonTokenType>.FullAlphabet; | |
|
46 | static readonly DFAStateDescriptior<object>[] _jsonDFA; | |
|
47 | static readonly int _jsonDFAInitialState; | |
|
48 | static readonly DFAStateDescriptior<object>[] _objectDFA; | |
|
49 | static readonly int _objectDFAInitialState; | |
|
50 | static readonly DFAStateDescriptior<object>[] _arrayDFA; | |
|
51 | static readonly int _arrayDFAInitialState; | |
|
48 | public ParserContext(int[,] dfa, int state, JSONElementContext context) { | |
|
49 | m_dfa = dfa; | |
|
50 | m_state = state; | |
|
51 | m_elementContext = context; | |
|
52 | } | |
|
53 | ||
|
54 | public bool Move(JsonTokenType token) { | |
|
55 | var next = m_dfa[m_state, token]; | |
|
56 | if (next == AutomatonConst.UNREACHABLE_STATE) | |
|
57 | return false; | |
|
58 | m_state = next; | |
|
59 | } | |
|
60 | ||
|
61 | public JSONElementContext ElementContext { | |
|
62 | get { return m_elementContext; } | |
|
63 | } | |
|
64 | } | |
|
52 | 65 | |
|
53 | 66 | static JSONParser() { |
|
54 | 67 | |
|
55 | 68 | |
|
56 | 69 | var valueExpression = Token(JsonTokenType.BeginArray, JsonTokenType.BeginObject, JsonTokenType.Literal, JsonTokenType.Number, JsonTokenType.String); |
|
57 | 70 | var memberExpression = Token(JsonTokenType.String).Cat(Token(JsonTokenType.NameSeparator)).Cat(valueExpression); |
|
58 | 71 | |
|
59 | 72 | var objectExpression = memberExpression |
|
60 | 73 | .Cat( |
|
61 | 74 | Token(JsonTokenType.ValueSeparator) |
|
62 | 75 | .Cat(memberExpression) |
|
63 | 76 | .EClosure() |
|
64 | 77 | ) |
|
65 | 78 | .Optional() |
|
66 | 79 | .Cat(Token(JsonTokenType.EndObject)) |
|
67 |
. |
|
|
80 | .End(); | |
|
81 | ||
|
68 | 82 | var arrayExpression = valueExpression |
|
69 | 83 | .Cat( |
|
70 | 84 | Token(JsonTokenType.ValueSeparator) |
|
71 | 85 | .Cat(valueExpression) |
|
72 | 86 | .EClosure() |
|
73 | 87 | ) |
|
74 | 88 | .Optional() |
|
75 | 89 | .Cat(Token(JsonTokenType.EndArray)) |
|
76 |
. |
|
|
90 | .End(); | |
|
77 | 91 | |
|
78 |
var jsonExpression = valueExpression. |
|
|
92 | var jsonExpression = valueExpression.End(); | |
|
79 | 93 | |
|
80 |
_jsonDFA = Create |
|
|
81 |
_objectDFA = Create |
|
|
82 |
_arrayDFA = Create |
|
|
94 | _jsonDFA = CreateParserContext(jsonExpression, JSONElementContext.None); | |
|
95 | _objectDFA = CreateParserContext(objectExpression, JSONElementContext.Object); | |
|
96 | _arrayDFA = CreateParserContext(arrayExpression, JSONElementContext.Array); | |
|
83 | 97 | } |
|
84 | 98 | |
|
85 |
static Token |
|
|
86 |
return Token |
|
|
99 | static Token Token(params JsonTokenType[] input) { | |
|
100 | return Token.New( input.Select(t => (int)t).ToArray() ); | |
|
87 | 101 | } |
|
88 | 102 | |
|
89 | static RegularDFA<JsonTokenType,object> CreateDFA(Token<object> expr) { | |
|
90 | var builder = new RegularExpressionVisitor<object>(); | |
|
91 |
var dfa = new |
|
|
92 | ||
|
103 | static ParserContext CreateParserContext(Token expr, JSONElementContext context) { | |
|
104 | ||
|
105 | var dfa = new DFATable(); | |
|
106 | var builder = new RegularExpressionVisitor(dfa); | |
|
93 | 107 | expr.Accept(builder); |
|
108 | builder.BuildDFA(); | |
|
94 | 109 | |
|
95 | builder.BuildDFA(dfa); | |
|
96 | return dfa; | |
|
110 | return new ParserContext(dfa.CreateTransitionTable(), dfa.InitialState, context); | |
|
97 | 111 | } |
|
98 | 112 | |
|
113 | #endregion | |
|
114 | ||
|
99 | 115 | JSONScanner m_scanner; |
|
100 | 116 | MemberContext m_memberContext; |
|
101 | 117 | |
|
102 | 118 | JSONElementType m_elementType; |
|
103 | 119 | object m_elementValue; |
|
104 | 120 | |
|
105 | 121 | /// <summary> |
|
106 | 122 | /// Создает новый парсер на основе строки, содержащей JSON |
|
107 | 123 | /// </summary> |
|
108 | 124 | /// <param name="text"></param> |
|
109 | 125 | public JSONParser(string text) |
|
110 | 126 | : base(_jsonDFA, INITIAL_STATE, new JSONParserContext { elementContext = JSONElementContext.None, memberName = String.Empty }) { |
|
111 | 127 | Safe.ArgumentNotEmpty(text, "text"); |
|
112 | 128 | m_scanner = new JSONScanner(); |
|
113 | 129 | m_scanner.Feed(text.ToCharArray()); |
|
114 | 130 | } |
|
115 | 131 | |
|
116 | 132 | /// <summary> |
|
117 | 133 | /// Создает новый экземпляр парсера, на основе текстового потока. |
|
118 | 134 | /// </summary> |
|
119 | 135 | /// <param name="reader">Текстовый поток.</param> |
|
120 | /// <param name="dispose">Признак того, что парсер должен конролировать время жизни входного потока.</param> | |
|
121 | public JSONParser(TextReader reader, bool dispose) | |
|
136 | public JSONParser(TextReader reader) | |
|
122 | 137 | : base(_jsonDFA, INITIAL_STATE, new JSONParserContext { elementContext = JSONElementContext.None, memberName = String.Empty }) { |
|
123 | 138 | Safe.ArgumentNotNull(reader, "reader"); |
|
124 | 139 | m_scanner = new JSONScanner(); |
|
125 | 140 | m_scanner.Feed(reader, dispose); |
|
126 | 141 | } |
|
127 | 142 | |
|
128 | 143 | /// <summary> |
|
129 | 144 | /// Тип текущего элемента на котором стоит парсер. |
|
130 | 145 | /// </summary> |
|
131 | 146 | public JSONElementType ElementType { |
|
132 | 147 | get { return m_elementType; } |
|
133 | 148 | } |
|
134 | 149 | |
|
135 | 150 | /// <summary> |
|
136 | 151 | /// Имя элемента - имя свойства родительского контейнера. Для элементов массивов и корневого всегда |
|
137 | 152 | /// пустая строка. |
|
138 | 153 | /// </summary> |
|
139 | 154 | public string ElementName { |
|
140 | 155 | get { return m_context.info.memberName; } |
|
141 | 156 | } |
|
142 | 157 | |
|
143 | 158 | /// <summary> |
|
144 | 159 | /// Значение элемента. Только для элементов типа <see cref="JSONElementType.Value"/>, для остальных <c>null</c> |
|
145 | 160 | /// </summary> |
|
146 | 161 | public object ElementValue { |
|
147 | 162 | get { return m_elementValue; } |
|
148 | 163 | } |
|
149 | 164 | |
|
150 | 165 | /// <summary> |
|
151 | 166 | /// Читает слеюудущий объект из потока |
|
152 | 167 | /// </summary> |
|
153 | 168 | /// <returns><c>true</c> - операция чтения прошла успешно, <c>false</c> - конец данных</returns> |
|
154 | 169 | public bool Read() { |
|
155 | 170 | if (m_context.current == UNREACHEBLE_STATE) |
|
156 | 171 | throw new InvalidOperationException("The parser is in invalid state"); |
|
157 | 172 | object tokenValue; |
|
158 | 173 | JsonTokenType tokenType; |
|
159 | 174 | m_context.info.memberName = String.Empty; |
|
160 | 175 | while (m_scanner.ReadToken(out tokenValue, out tokenType)) { |
|
161 | 176 | Move((int)tokenType); |
|
162 | 177 | if (m_context.current == UNREACHEBLE_STATE) |
|
163 | 178 | UnexpectedToken(tokenValue, tokenType); |
|
164 | 179 | switch (tokenType) { |
|
165 | 180 | case JsonTokenType.BeginObject: |
|
166 | 181 | Switch( |
|
167 | 182 | _objectDFA, |
|
168 | 183 | INITIAL_STATE, |
|
169 | 184 | new JSONParserContext { |
|
170 | 185 | memberName = m_context.info.memberName, |
|
171 | 186 | elementContext = JSONElementContext.Object |
|
172 | 187 | } |
|
173 | 188 | ); |
|
174 | 189 | m_elementValue = null; |
|
175 | 190 | m_memberContext = MemberContext.MemberName; |
|
176 | 191 | m_elementType = JSONElementType.BeginObject; |
|
177 | 192 | return true; |
|
178 | 193 | case JsonTokenType.EndObject: |
|
179 | 194 | Restore(); |
|
180 | 195 | m_elementValue = null; |
|
181 | 196 | m_elementType = JSONElementType.EndObject; |
|
182 | 197 | return true; |
|
183 | 198 | case JsonTokenType.BeginArray: |
|
184 | 199 | Switch( |
|
185 | 200 | _arrayDFA, |
|
186 | 201 | INITIAL_STATE, |
|
187 | 202 | new JSONParserContext { |
|
188 | 203 | memberName = m_context.info.memberName, |
|
189 | 204 | elementContext = JSONElementContext.Array |
|
190 | 205 | } |
|
191 | 206 | ); |
|
192 | 207 | m_elementValue = null; |
|
193 | 208 | m_memberContext = MemberContext.MemberValue; |
|
194 | 209 | m_elementType = JSONElementType.BeginArray; |
|
195 | 210 | return true; |
|
196 | 211 | case JsonTokenType.EndArray: |
|
197 | 212 | Restore(); |
|
198 | 213 | m_elementValue = null; |
|
199 | 214 | m_elementType = JSONElementType.EndArray; |
|
200 | 215 | return true; |
|
201 | 216 | case JsonTokenType.String: |
|
202 | 217 | if (m_memberContext == MemberContext.MemberName) { |
|
203 | 218 | m_context.info.memberName = (string)tokenValue; |
|
204 | 219 | break; |
|
205 | 220 | } |
|
206 | 221 | m_elementType = JSONElementType.Value; |
|
207 | 222 | m_elementValue = tokenValue; |
|
208 | 223 | return true; |
|
209 | 224 | case JsonTokenType.Number: |
|
210 | 225 | m_elementType = JSONElementType.Value; |
|
211 | 226 | m_elementValue = tokenValue; |
|
212 | 227 | return true; |
|
213 | 228 | case JsonTokenType.Literal: |
|
214 | 229 | m_elementType = JSONElementType.Value; |
|
215 | 230 | m_elementValue = ParseLiteral((string)tokenValue); |
|
216 | 231 | return true; |
|
217 | 232 | case JsonTokenType.NameSeparator: |
|
218 | 233 | m_memberContext = MemberContext.MemberValue; |
|
219 | 234 | break; |
|
220 | 235 | case JsonTokenType.ValueSeparator: |
|
221 | 236 | m_memberContext = m_context.info.elementContext == JSONElementContext.Object ? MemberContext.MemberName : MemberContext.MemberValue; |
|
222 | 237 | break; |
|
223 | 238 | default: |
|
224 | 239 | UnexpectedToken(tokenValue, tokenType); |
|
225 | 240 | break; |
|
226 | 241 | } |
|
227 | 242 | } |
|
228 | 243 | if (m_context.info.elementContext != JSONElementContext.None) |
|
229 | 244 | throw new ParserException("Unexpedted end of data"); |
|
230 | 245 | return false; |
|
231 | 246 | } |
|
232 | 247 | |
|
233 | 248 | object ParseLiteral(string literal) { |
|
234 | 249 | switch (literal) { |
|
235 | 250 | case "null": |
|
236 | 251 | return null; |
|
237 | 252 | case "false": |
|
238 | 253 | return false; |
|
239 | 254 | case "true": |
|
240 | 255 | return true; |
|
241 | 256 | default: |
|
242 | 257 | UnexpectedToken(literal, JsonTokenType.Literal); |
|
243 | 258 | return null; // avoid compliler error |
|
244 | 259 | } |
|
245 | 260 | } |
|
246 | 261 | |
|
247 | 262 | void UnexpectedToken(object value, JsonTokenType tokenType) { |
|
248 | 263 | throw new ParserException(String.Format("Unexpected token {0}: '{1}'", tokenType, value)); |
|
249 | 264 | } |
|
250 | 265 | |
|
251 | 266 | |
|
252 | 267 | /// <summary> |
|
253 | 268 | /// Признак конца потока |
|
254 | 269 | /// </summary> |
|
255 | 270 | public bool EOF { |
|
256 | 271 | get { |
|
257 | 272 | return m_scanner.EOF; |
|
258 | 273 | } |
|
259 | 274 | } |
|
260 | 275 | |
|
261 | 276 | protected override void Dispose(bool disposing) { |
|
262 | 277 | if (disposing) { |
|
263 | 278 | m_scanner.Dispose(); |
|
264 | 279 | } |
|
265 | 280 | } |
|
266 | 281 | |
|
267 | 282 | /// <summary> |
|
268 | 283 | /// Переходит в конец текущего объекта. |
|
269 | 284 | /// </summary> |
|
270 | 285 | public void SeekElementEnd() { |
|
271 | 286 | var level = Level - 1; |
|
272 | 287 | |
|
273 | 288 | Debug.Assert(level >= 0); |
|
274 | 289 | |
|
275 | 290 | while (Level != level) |
|
276 | 291 | Read(); |
|
277 | 292 | } |
|
278 | 293 | } |
|
279 | 294 | |
|
280 | 295 | } |
@@ -1,150 +1,150 | |||
|
1 | 1 | using System; |
|
2 | 2 | using Implab.Components; |
|
3 | 3 | using System.Diagnostics; |
|
4 | 4 | using Implab.Automaton; |
|
5 | 5 | using System.Text; |
|
6 | 6 | |
|
7 | 7 | namespace Implab.Formats { |
|
8 | 8 | public abstract class TextScanner : Disposable { |
|
9 | 9 | readonly int m_bufferMax; |
|
10 | 10 | readonly int m_chunkSize; |
|
11 | 11 | |
|
12 | 12 | char[] m_buffer; |
|
13 | 13 | int m_bufferOffset; |
|
14 | 14 | int m_bufferSize; |
|
15 | 15 | int m_tokenOffset; |
|
16 | 16 | int m_tokenLength; |
|
17 | 17 | |
|
18 | 18 | /// <summary> |
|
19 | 19 | /// Initializes a new instance of the <see cref="Implab.Formats.TextScanner"/> class. |
|
20 | 20 | /// </summary> |
|
21 | 21 | /// <param name="bufferMax">Buffer max.</param> |
|
22 | 22 | /// <param name="chunkSize">Chunk size.</param> |
|
23 | 23 | protected TextScanner(int bufferMax, int chunkSize) { |
|
24 | 24 | Debug.Assert(m_chunkSize <= m_bufferMax); |
|
25 | 25 | |
|
26 | 26 | m_bufferMax = bufferMax; |
|
27 | 27 | m_chunkSize = chunkSize; |
|
28 | 28 | } |
|
29 | 29 | |
|
30 | 30 | /// <summary> |
|
31 | 31 | /// Initializes a new instance of the <see cref="Implab.Formats.TextScanner"/> class. |
|
32 | 32 | /// </summary> |
|
33 | 33 | /// <param name="buffer">Buffer.</param> |
|
34 | 34 | protected TextScanner(char[] buffer) { |
|
35 | 35 | if (buffer != null) { |
|
36 | 36 | m_buffer = buffer; |
|
37 | 37 | m_bufferSize = buffer.Length; |
|
38 | 38 | } |
|
39 | 39 | } |
|
40 | 40 | |
|
41 | 41 | /// <summary> |
|
42 | 42 | /// (hungry) Reads the next token. |
|
43 | 43 | /// </summary> |
|
44 | 44 | /// <returns><c>true</c>, if token internal was read, <c>false</c> if there is no more tokens in the stream.</returns> |
|
45 | 45 | /// <param name="dfa">The transition map for the automaton</param> |
|
46 | 46 | /// <param name="final">Final states of the automaton.</param> |
|
47 | 47 | /// <param name="tags">Tags.</param> |
|
48 | 48 | /// <param name="state">The initial state for the automaton.</param> |
|
49 | 49 | /// <param name="alphabet"></param> |
|
50 | 50 | /// <param name = "tag"></param> |
|
51 | 51 | internal bool ReadToken<TTag>(int[,] dfa, bool[] final, TTag[][] tags, int state, int[] alphabet, out TTag[] tag) { |
|
52 | 52 | Safe.ArgumentNotNull(); |
|
53 | 53 | m_tokenLength = 0; |
|
54 | 54 | |
|
55 | 55 | var maxSymbol = alphabet.Length - 1; |
|
56 | 56 | |
|
57 | 57 | do { |
|
58 | 58 | // after the next chunk is read the offset in the buffer may change |
|
59 | 59 | int pos = m_bufferOffset + m_tokenLength; |
|
60 | 60 | |
|
61 | 61 | while (pos < m_bufferSize) { |
|
62 | 62 | var ch = m_buffer[pos]; |
|
63 | 63 | |
|
64 |
state = dfa[state, ch > maxSymbol ? |
|
|
65 |
if (state == |
|
|
64 | state = dfa[state, ch > maxSymbol ? AutomatonConst.UNCLASSIFIED_INPUT : alphabet[ch]]; | |
|
65 | if (state == AutomatonConst.UNREACHABLE_STATE) | |
|
66 | 66 | break; |
|
67 | 67 | |
|
68 | 68 | pos++; |
|
69 | 69 | } |
|
70 | 70 | |
|
71 | 71 | m_tokenLength = pos - m_bufferOffset; |
|
72 |
} while (state != |
|
|
72 | } while (state != AutomatonConst.UNREACHABLE_STATE && Feed()); | |
|
73 | 73 | |
|
74 | 74 | m_tokenOffset = m_bufferOffset; |
|
75 | 75 | m_bufferOffset += m_tokenLength; |
|
76 | 76 | |
|
77 | 77 | if (final[state]) { |
|
78 | 78 | tag = tags[state]; |
|
79 | 79 | return true; |
|
80 | 80 | } |
|
81 | 81 | |
|
82 | 82 | if (m_bufferOffset == m_bufferSize) { |
|
83 | 83 | if (m_tokenLength == 0) //EOF |
|
84 | 84 | return false; |
|
85 | 85 | |
|
86 | 86 | throw new ParserException(); |
|
87 | 87 | } |
|
88 | 88 | |
|
89 | 89 | throw new ParserException(String.Format("Unexpected symbol '{0}'", m_buffer[m_bufferOffset])); |
|
90 | 90 | |
|
91 | 91 | } |
|
92 | 92 | |
|
93 | 93 | protected void Feed(char[] buffer, int offset, int length) { |
|
94 | 94 | m_buffer = buffer; |
|
95 | 95 | m_bufferOffset = offset; |
|
96 | 96 | m_bufferSize = offset + length; |
|
97 | 97 | } |
|
98 | 98 | |
|
99 | 99 | protected bool Feed() { |
|
100 | 100 | if (m_chunkSize <= 0) |
|
101 | 101 | return false; |
|
102 | 102 | |
|
103 | 103 | if (m_buffer != null) { |
|
104 | 104 | var free = m_buffer.Length - m_bufferSize; |
|
105 | 105 | |
|
106 | 106 | if (free < m_chunkSize) { |
|
107 | 107 | free += m_chunkSize; |
|
108 | 108 | var used = m_bufferSize - m_bufferOffset; |
|
109 | 109 | var size = used + free; |
|
110 | 110 | |
|
111 | 111 | if (size > m_bufferMax) |
|
112 | 112 | throw new ParserException(String.Format("The buffer limit ({0} Kb) is reached", m_bufferMax/1024)); |
|
113 | 113 | |
|
114 | 114 | var temp = new char[size]; |
|
115 | 115 | |
|
116 | 116 | var read = Read(temp, used, m_chunkSize); |
|
117 | 117 | if (read == 0) |
|
118 | 118 | return false; |
|
119 | 119 | |
|
120 | 120 | Array.Copy(m_buffer, m_bufferOffset, temp, 0, used); |
|
121 | 121 | |
|
122 | 122 | m_bufferOffset = 0; |
|
123 | 123 | m_bufferSize = used + read; |
|
124 | 124 | m_buffer = temp; |
|
125 | 125 | } |
|
126 | 126 | } else { |
|
127 | 127 | Debug.Assert(m_bufferOffset == 0); |
|
128 | 128 | m_buffer = new char[m_chunkSize]; |
|
129 | 129 | m_bufferSize = Read(m_buffer, 0, m_chunkSize); |
|
130 | 130 | return (m_bufferSize != 0); |
|
131 | 131 | } |
|
132 | 132 | } |
|
133 | 133 | |
|
134 | 134 | protected abstract int Read(char[] buffer, int offset, int size); |
|
135 | 135 | |
|
136 | 136 | public string GetTokenValue() { |
|
137 | 137 | return new String(m_buffer, m_tokenOffset, m_tokenLength); |
|
138 | 138 | } |
|
139 | 139 | |
|
140 | 140 | public void CopyTokenTo(char[] buffer, int offset) { |
|
141 | 141 | m_buffer.CopyTo(buffer, offset); |
|
142 | 142 | } |
|
143 | 143 | |
|
144 | 144 | public void CopyTokenTo(StringBuilder sb) { |
|
145 | 145 | sb.Append(m_buffer, m_tokenOffset, m_tokenLength); |
|
146 | 146 | } |
|
147 | 147 | |
|
148 | 148 | } |
|
149 | 149 | } |
|
150 | 150 |
@@ -1,275 +1,276 | |||
|
1 | 1 | <?xml version="1.0" encoding="utf-8"?> |
|
2 | 2 | <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> |
|
3 | 3 | <PropertyGroup> |
|
4 | 4 | <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> |
|
5 | 5 | <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> |
|
6 | 6 | <ProjectGuid>{F550F1F8-8746-4AD0-9614-855F4C4B7F05}</ProjectGuid> |
|
7 | 7 | <OutputType>Library</OutputType> |
|
8 | 8 | <RootNamespace>Implab</RootNamespace> |
|
9 | 9 | <AssemblyName>Implab</AssemblyName> |
|
10 | 10 | <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> |
|
11 | 11 | <ReleaseVersion>0.2</ReleaseVersion> |
|
12 | 12 | <ProductVersion>8.0.30703</ProductVersion> |
|
13 | 13 | <SchemaVersion>2.0</SchemaVersion> |
|
14 | 14 | </PropertyGroup> |
|
15 | 15 | <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> |
|
16 | 16 | <DebugSymbols>true</DebugSymbols> |
|
17 | 17 | <DebugType>full</DebugType> |
|
18 | 18 | <Optimize>false</Optimize> |
|
19 | 19 | <OutputPath>bin\Debug</OutputPath> |
|
20 | 20 | <DefineConstants>TRACE;DEBUG;</DefineConstants> |
|
21 | 21 | <ErrorReport>prompt</ErrorReport> |
|
22 | 22 | <WarningLevel>4</WarningLevel> |
|
23 | 23 | <ConsolePause>false</ConsolePause> |
|
24 | 24 | <RunCodeAnalysis>true</RunCodeAnalysis> |
|
25 | 25 | </PropertyGroup> |
|
26 | 26 | <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> |
|
27 | 27 | <DebugType>full</DebugType> |
|
28 | 28 | <Optimize>true</Optimize> |
|
29 | 29 | <OutputPath>bin\Release</OutputPath> |
|
30 | 30 | <ErrorReport>prompt</ErrorReport> |
|
31 | 31 | <WarningLevel>4</WarningLevel> |
|
32 | 32 | <ConsolePause>false</ConsolePause> |
|
33 | 33 | </PropertyGroup> |
|
34 | 34 | <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug 4.5|AnyCPU' "> |
|
35 | 35 | <DebugSymbols>true</DebugSymbols> |
|
36 | 36 | <DebugType>full</DebugType> |
|
37 | 37 | <Optimize>false</Optimize> |
|
38 | 38 | <OutputPath>bin\Debug</OutputPath> |
|
39 | 39 | <DefineConstants>TRACE;DEBUG;NET_4_5</DefineConstants> |
|
40 | 40 | <ErrorReport>prompt</ErrorReport> |
|
41 | 41 | <WarningLevel>4</WarningLevel> |
|
42 | 42 | <RunCodeAnalysis>true</RunCodeAnalysis> |
|
43 | 43 | <ConsolePause>false</ConsolePause> |
|
44 | 44 | </PropertyGroup> |
|
45 | 45 | <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release 4.5|AnyCPU' "> |
|
46 | 46 | <Optimize>true</Optimize> |
|
47 | 47 | <OutputPath>bin\Release</OutputPath> |
|
48 | 48 | <ErrorReport>prompt</ErrorReport> |
|
49 | 49 | <WarningLevel>4</WarningLevel> |
|
50 | 50 | <ConsolePause>false</ConsolePause> |
|
51 | 51 | <DefineConstants>NET_4_5</DefineConstants> |
|
52 | 52 | </PropertyGroup> |
|
53 | 53 | <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'DebugMono|AnyCPU' "> |
|
54 | 54 | <DebugSymbols>true</DebugSymbols> |
|
55 | 55 | <DebugType>full</DebugType> |
|
56 | 56 | <Optimize>false</Optimize> |
|
57 | 57 | <OutputPath>bin\Debug</OutputPath> |
|
58 | 58 | <DefineConstants>TRACE;DEBUG;NET_4_5;MONO</DefineConstants> |
|
59 | 59 | <ErrorReport>prompt</ErrorReport> |
|
60 | 60 | <WarningLevel>4</WarningLevel> |
|
61 | 61 | <RunCodeAnalysis>true</RunCodeAnalysis> |
|
62 | 62 | <ConsolePause>false</ConsolePause> |
|
63 | 63 | </PropertyGroup> |
|
64 | 64 | <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'ReleaseMono|AnyCPU' "> |
|
65 | 65 | <Optimize>true</Optimize> |
|
66 | 66 | <OutputPath>bin\Release</OutputPath> |
|
67 | 67 | <DefineConstants>NET_4_5;MONO;</DefineConstants> |
|
68 | 68 | <ErrorReport>prompt</ErrorReport> |
|
69 | 69 | <WarningLevel>4</WarningLevel> |
|
70 | 70 | <ConsolePause>false</ConsolePause> |
|
71 | 71 | </PropertyGroup> |
|
72 | 72 | <ItemGroup> |
|
73 | 73 | <Reference Include="System" /> |
|
74 | 74 | <Reference Include="System.Xml" /> |
|
75 | 75 | <Reference Include="mscorlib" /> |
|
76 | 76 | </ItemGroup> |
|
77 | 77 | <ItemGroup> |
|
78 | 78 | <Compile Include="CustomEqualityComparer.cs" /> |
|
79 | 79 | <Compile Include="Diagnostics\ConsoleTraceListener.cs" /> |
|
80 | 80 | <Compile Include="Diagnostics\EventText.cs" /> |
|
81 | 81 | <Compile Include="Diagnostics\LogChannel.cs" /> |
|
82 | 82 | <Compile Include="Diagnostics\LogicalOperation.cs" /> |
|
83 | 83 | <Compile Include="Diagnostics\TextFileListener.cs" /> |
|
84 | 84 | <Compile Include="Diagnostics\TraceLog.cs" /> |
|
85 | 85 | <Compile Include="Diagnostics\TraceEvent.cs" /> |
|
86 | 86 | <Compile Include="Diagnostics\TraceEventType.cs" /> |
|
87 | 87 | <Compile Include="ICancellable.cs" /> |
|
88 | 88 | <Compile Include="IProgressHandler.cs" /> |
|
89 | 89 | <Compile Include="IProgressNotifier.cs" /> |
|
90 | 90 | <Compile Include="IPromiseT.cs" /> |
|
91 | 91 | <Compile Include="IPromise.cs" /> |
|
92 | 92 | <Compile Include="IServiceLocator.cs" /> |
|
93 | 93 | <Compile Include="ITaskController.cs" /> |
|
94 | 94 | <Compile Include="Parallels\DispatchPool.cs" /> |
|
95 | 95 | <Compile Include="Parallels\ArrayTraits.cs" /> |
|
96 | 96 | <Compile Include="Parallels\MTQueue.cs" /> |
|
97 | 97 | <Compile Include="Parallels\WorkerPool.cs" /> |
|
98 | 98 | <Compile Include="ProgressInitEventArgs.cs" /> |
|
99 | 99 | <Compile Include="Properties\AssemblyInfo.cs" /> |
|
100 | 100 | <Compile Include="Parallels\AsyncPool.cs" /> |
|
101 | 101 | <Compile Include="Safe.cs" /> |
|
102 | 102 | <Compile Include="ValueEventArgs.cs" /> |
|
103 | 103 | <Compile Include="PromiseExtensions.cs" /> |
|
104 | 104 | <Compile Include="SyncContextPromise.cs" /> |
|
105 | 105 | <Compile Include="Diagnostics\OperationContext.cs" /> |
|
106 | 106 | <Compile Include="Diagnostics\TraceContext.cs" /> |
|
107 | 107 | <Compile Include="Diagnostics\LogEventArgs.cs" /> |
|
108 | 108 | <Compile Include="Diagnostics\LogEventArgsT.cs" /> |
|
109 | 109 | <Compile Include="Diagnostics\Extensions.cs" /> |
|
110 | 110 | <Compile Include="PromiseEventType.cs" /> |
|
111 | 111 | <Compile Include="Parallels\AsyncQueue.cs" /> |
|
112 | 112 | <Compile Include="PromiseT.cs" /> |
|
113 | 113 | <Compile Include="IDeferred.cs" /> |
|
114 | 114 | <Compile Include="IDeferredT.cs" /> |
|
115 | 115 | <Compile Include="Promise.cs" /> |
|
116 | 116 | <Compile Include="PromiseTransientException.cs" /> |
|
117 | 117 | <Compile Include="Parallels\Signal.cs" /> |
|
118 | 118 | <Compile Include="Parallels\SharedLock.cs" /> |
|
119 | 119 | <Compile Include="Diagnostics\ILogWriter.cs" /> |
|
120 | 120 | <Compile Include="Diagnostics\ListenerBase.cs" /> |
|
121 | 121 | <Compile Include="Parallels\BlockingQueue.cs" /> |
|
122 | 122 | <Compile Include="AbstractEvent.cs" /> |
|
123 | 123 | <Compile Include="AbstractPromise.cs" /> |
|
124 | 124 | <Compile Include="AbstractPromiseT.cs" /> |
|
125 | 125 | <Compile Include="FuncTask.cs" /> |
|
126 | 126 | <Compile Include="FuncTaskBase.cs" /> |
|
127 | 127 | <Compile Include="FuncTaskT.cs" /> |
|
128 | 128 | <Compile Include="ActionChainTaskBase.cs" /> |
|
129 | 129 | <Compile Include="ActionChainTask.cs" /> |
|
130 | 130 | <Compile Include="ActionChainTaskT.cs" /> |
|
131 | 131 | <Compile Include="FuncChainTaskBase.cs" /> |
|
132 | 132 | <Compile Include="FuncChainTask.cs" /> |
|
133 | 133 | <Compile Include="FuncChainTaskT.cs" /> |
|
134 | 134 | <Compile Include="ActionTaskBase.cs" /> |
|
135 | 135 | <Compile Include="ActionTask.cs" /> |
|
136 | 136 | <Compile Include="ActionTaskT.cs" /> |
|
137 | 137 | <Compile Include="ICancellationToken.cs" /> |
|
138 | 138 | <Compile Include="SuccessPromise.cs" /> |
|
139 | 139 | <Compile Include="SuccessPromiseT.cs" /> |
|
140 | 140 | <Compile Include="PromiseAwaiterT.cs" /> |
|
141 | 141 | <Compile Include="PromiseAwaiter.cs" /> |
|
142 | 142 | <Compile Include="Components\ComponentContainer.cs" /> |
|
143 | 143 | <Compile Include="Components\Disposable.cs" /> |
|
144 | 144 | <Compile Include="Components\DisposablePool.cs" /> |
|
145 | 145 | <Compile Include="Components\ObjectPool.cs" /> |
|
146 | 146 | <Compile Include="Components\ServiceLocator.cs" /> |
|
147 | 147 | <Compile Include="Components\IInitializable.cs" /> |
|
148 | 148 | <Compile Include="TaskController.cs" /> |
|
149 | 149 | <Compile Include="Components\App.cs" /> |
|
150 | 150 | <Compile Include="Components\IRunnable.cs" /> |
|
151 | 151 | <Compile Include="Components\ExecutionState.cs" /> |
|
152 | 152 | <Compile Include="Components\RunnableComponent.cs" /> |
|
153 | 153 | <Compile Include="Components\IFactory.cs" /> |
|
154 | 154 | <Compile Include="Automaton\EnumAlphabet.cs" /> |
|
155 | 155 | <Compile Include="Automaton\IAlphabet.cs" /> |
|
156 | 156 | <Compile Include="Automaton\ParserException.cs" /> |
|
157 | 157 | <Compile Include="Automaton\IndexedAlphabetBase.cs" /> |
|
158 | 158 | <Compile Include="Automaton\IAlphabetBuilder.cs" /> |
|
159 | 159 | <Compile Include="Automaton\RegularExpressions\AltToken.cs" /> |
|
160 | 160 | <Compile Include="Automaton\RegularExpressions\BinaryToken.cs" /> |
|
161 | 161 | <Compile Include="Automaton\RegularExpressions\CatToken.cs" /> |
|
162 | <Compile Include="Automaton\DFAConst.cs" /> | |
|
163 | 162 | <Compile Include="Automaton\RegularExpressions\StarToken.cs" /> |
|
164 | 163 | <Compile Include="Automaton\RegularExpressions\SymbolToken.cs" /> |
|
165 | 164 | <Compile Include="Automaton\RegularExpressions\EmptyToken.cs" /> |
|
166 | 165 | <Compile Include="Automaton\RegularExpressions\Token.cs" /> |
|
167 | 166 | <Compile Include="Automaton\RegularExpressions\IVisitor.cs" /> |
|
168 | 167 | <Compile Include="Automaton\AutomatonTransition.cs" /> |
|
169 | 168 | <Compile Include="Formats\JSON\JSONElementContext.cs" /> |
|
170 | 169 | <Compile Include="Formats\JSON\JSONElementType.cs" /> |
|
171 | 170 | <Compile Include="Formats\JSON\JSONGrammar.cs" /> |
|
172 | 171 | <Compile Include="Formats\JSON\JSONParser.cs" /> |
|
173 | 172 | <Compile Include="Formats\JSON\JSONScanner.cs" /> |
|
174 | 173 | <Compile Include="Formats\JSON\JsonTokenType.cs" /> |
|
175 | 174 | <Compile Include="Formats\JSON\JSONWriter.cs" /> |
|
176 | 175 | <Compile Include="Formats\JSON\JSONXmlReader.cs" /> |
|
177 | 176 | <Compile Include="Formats\JSON\JSONXmlReaderOptions.cs" /> |
|
178 | 177 | <Compile Include="Formats\JSON\StringTranslator.cs" /> |
|
179 | 178 | <Compile Include="Automaton\MapAlphabet.cs" /> |
|
180 | 179 | <Compile Include="Automaton\DummyAlphabet.cs" /> |
|
181 | 180 | <Compile Include="Formats\CharAlphabet.cs" /> |
|
182 | 181 | <Compile Include="Formats\ByteAlphabet.cs" /> |
|
183 | 182 | <Compile Include="Automaton\IDFATable.cs" /> |
|
184 | 183 | <Compile Include="Automaton\IDFATableBuilder.cs" /> |
|
185 | 184 | <Compile Include="Automaton\DFATable.cs" /> |
|
186 | <Compile Include="Automaton\RegularExpressions\RegularDFA.cs" /> | |
|
187 | 185 | <Compile Include="Automaton\RegularExpressions\RegularExpressionVisitor.cs" /> |
|
188 | 186 | <Compile Include="Automaton\RegularExpressions\ITaggedDFABuilder.cs" /> |
|
189 | 187 | <Compile Include="Formats\TextScanner.cs" /> |
|
190 | 188 | <Compile Include="Formats\StringScanner.cs" /> |
|
191 | 189 | <Compile Include="Formats\ReaderScanner.cs" /> |
|
192 | 190 | <Compile Include="Formats\ScannerContext.cs" /> |
|
193 | 191 | <Compile Include="Formats\Grammar.cs" /> |
|
194 | 192 | <Compile Include="Automaton\RegularExpressions\EndTokenT.cs" /> |
|
195 | 193 | <Compile Include="Automaton\RegularExpressions\EndToken.cs" /> |
|
196 |
<Compile Include="Automaton\RegularExpressions\ |
|
|
194 | <Compile Include="Automaton\RegularExpressions\RegularExpressionVisitorT.cs" /> | |
|
195 | <Compile Include="Automaton\AutomatonConst.cs" /> | |
|
196 | <Compile Include="Automaton\RegularExpressions\RegularDFA.cs" /> | |
|
197 | <Compile Include="Components\LazyAndWeak.cs" /> | |
|
197 | 198 | </ItemGroup> |
|
198 | 199 | <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> |
|
199 | 200 | <ItemGroup /> |
|
200 | 201 | <ProjectExtensions> |
|
201 | 202 | <MonoDevelop> |
|
202 | 203 | <Properties> |
|
203 | 204 | <Policies> |
|
204 | 205 | <CSharpFormattingPolicy IndentSwitchBody="True" NamespaceBraceStyle="EndOfLine" ClassBraceStyle="EndOfLine" InterfaceBraceStyle="EndOfLine" StructBraceStyle="EndOfLine" EnumBraceStyle="EndOfLine" MethodBraceStyle="EndOfLine" ConstructorBraceStyle="EndOfLine" DestructorBraceStyle="EndOfLine" BeforeMethodDeclarationParentheses="False" BeforeMethodCallParentheses="False" BeforeConstructorDeclarationParentheses="False" NewLineBeforeConstructorInitializerColon="NewLine" NewLineAfterConstructorInitializerColon="SameLine" BeforeIndexerDeclarationBracket="False" BeforeDelegateDeclarationParentheses="False" NewParentheses="False" SpacesBeforeBrackets="False" inheritsSet="Mono" inheritsScope="text/x-csharp" scope="text/x-csharp" /> |
|
205 | 206 | <TextStylePolicy FileWidth="120" EolMarker="Unix" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="text/x-csharp" /> |
|
206 | 207 | <DotNetNamingPolicy DirectoryNamespaceAssociation="PrefixedHierarchical" ResourceNamePolicy="MSBuild" /> |
|
207 | 208 | <TextStylePolicy FileWidth="120" TabsToSpaces="False" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="application/xml" /> |
|
208 | 209 | <XmlFormattingPolicy inheritsSet="Mono" inheritsScope="application/xml" scope="application/xml" /> |
|
209 | 210 | <TextStylePolicy FileWidth="120" TabsToSpaces="False" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="text/plain" /> |
|
210 | 211 | <NameConventionPolicy> |
|
211 | 212 | <Rules> |
|
212 | 213 | <NamingRule Name="Namespaces" AffectedEntity="Namespace" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" /> |
|
213 | 214 | <NamingRule Name="Types" AffectedEntity="Class, Struct, Enum, Delegate" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" /> |
|
214 | 215 | <NamingRule Name="Interfaces" AffectedEntity="Interface" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True"> |
|
215 | 216 | <RequiredPrefixes> |
|
216 | 217 | <String>I</String> |
|
217 | 218 | </RequiredPrefixes> |
|
218 | 219 | </NamingRule> |
|
219 | 220 | <NamingRule Name="Attributes" AffectedEntity="CustomAttributes" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True"> |
|
220 | 221 | <RequiredSuffixes> |
|
221 | 222 | <String>Attribute</String> |
|
222 | 223 | </RequiredSuffixes> |
|
223 | 224 | </NamingRule> |
|
224 | 225 | <NamingRule Name="Event Arguments" AffectedEntity="CustomEventArgs" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True"> |
|
225 | 226 | <RequiredSuffixes> |
|
226 | 227 | <String>EventArgs</String> |
|
227 | 228 | </RequiredSuffixes> |
|
228 | 229 | </NamingRule> |
|
229 | 230 | <NamingRule Name="Exceptions" AffectedEntity="CustomExceptions" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True"> |
|
230 | 231 | <RequiredSuffixes> |
|
231 | 232 | <String>Exception</String> |
|
232 | 233 | </RequiredSuffixes> |
|
233 | 234 | </NamingRule> |
|
234 | 235 | <NamingRule Name="Methods" AffectedEntity="Methods" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" /> |
|
235 | 236 | <NamingRule Name="Static Readonly Fields" AffectedEntity="ReadonlyField" VisibilityMask="Internal, Protected, Public" NamingStyle="CamelCase" IncludeInstanceMembers="False" IncludeStaticEntities="True" /> |
|
236 | 237 | <NamingRule Name="Fields (Non Private)" AffectedEntity="Field" VisibilityMask="Internal, Public" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" /> |
|
237 | 238 | <NamingRule Name="ReadOnly Fields (Non Private)" AffectedEntity="ReadonlyField" VisibilityMask="Internal, Public" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="False" /> |
|
238 | 239 | <NamingRule Name="Fields (Private)" AffectedEntity="Field, ReadonlyField" VisibilityMask="Private, Protected" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="False"> |
|
239 | 240 | <RequiredPrefixes> |
|
240 | 241 | <String>m_</String> |
|
241 | 242 | </RequiredPrefixes> |
|
242 | 243 | </NamingRule> |
|
243 | 244 | <NamingRule Name="Static Fields (Private)" AffectedEntity="Field" VisibilityMask="Private" NamingStyle="CamelCase" IncludeInstanceMembers="False" IncludeStaticEntities="True"> |
|
244 | 245 | <RequiredPrefixes> |
|
245 | 246 | <String>_</String> |
|
246 | 247 | </RequiredPrefixes> |
|
247 | 248 | </NamingRule> |
|
248 | 249 | <NamingRule Name="ReadOnly Fields (Private)" AffectedEntity="ReadonlyField" VisibilityMask="Private, Protected" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="False"> |
|
249 | 250 | <RequiredPrefixes> |
|
250 | 251 | <String>m_</String> |
|
251 | 252 | </RequiredPrefixes> |
|
252 | 253 | </NamingRule> |
|
253 | 254 | <NamingRule Name="Constant Fields" AffectedEntity="ConstantField" VisibilityMask="VisibilityMask" NamingStyle="AllUpper" IncludeInstanceMembers="True" IncludeStaticEntities="True" /> |
|
254 | 255 | <NamingRule Name="Properties" AffectedEntity="Property" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" /> |
|
255 | 256 | <NamingRule Name="Events" AffectedEntity="Event" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" /> |
|
256 | 257 | <NamingRule Name="Enum Members" AffectedEntity="EnumMember" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" /> |
|
257 | 258 | <NamingRule Name="Parameters" AffectedEntity="Parameter, LocalVariable" VisibilityMask="VisibilityMask" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" /> |
|
258 | 259 | <NamingRule Name="Type Parameters" AffectedEntity="TypeParameter" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True"> |
|
259 | 260 | <RequiredPrefixes> |
|
260 | 261 | <String>T</String> |
|
261 | 262 | </RequiredPrefixes> |
|
262 | 263 | </NamingRule> |
|
263 | 264 | </Rules> |
|
264 | 265 | </NameConventionPolicy> |
|
265 | 266 | </Policies> |
|
266 | 267 | </Properties> |
|
267 | 268 | </MonoDevelop> |
|
268 | 269 | </ProjectExtensions> |
|
269 | 270 | <ItemGroup> |
|
270 | 271 | <Folder Include="Components\" /> |
|
271 | 272 | <Folder Include="Automaton\RegularExpressions\" /> |
|
272 | 273 | <Folder Include="Formats\" /> |
|
273 | 274 | <Folder Include="Formats\JSON\" /> |
|
274 | 275 | </ItemGroup> |
|
275 | 276 | </Project> No newline at end of file |
|
1 | NO CONTENT: file was removed |
|
1 | NO CONTENT: file was removed |
General Comments 0
You need to be logged in to leave comments.
Login now