55
|
1 using Implab;
|
|
2 using System;
|
|
3 using System.Collections.Generic;
|
59
|
4 using System.Diagnostics;
|
55
|
5 using System.Globalization;
|
|
6 using System.Linq;
|
|
7 using System.Text;
|
|
8 using System.Threading.Tasks;
|
|
9
|
|
10 namespace Implab.Parsing {
|
|
11 /// <summary>
|
|
12 /// Алфавит символами которого являются элементы перечислений.
|
|
13 /// </summary>
|
|
14 /// <typeparam name="T">Тип перечислений</typeparam>
|
|
15 public class EnumAlphabet<T> : AlphabetBase<T> where T : struct, IConvertible {
|
|
16 static readonly T[] _symbols;
|
|
17 static readonly EnumAlphabet<T> _fullAlphabet;
|
|
18
|
65
|
19 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
|
55
|
20 static EnumAlphabet() {
|
|
21 if (!typeof(T).IsEnum)
|
|
22 throw new InvalidOperationException("Invalid generic parameter, enumeration is required");
|
|
23
|
|
24 if (Enum.GetUnderlyingType(typeof(T)) != typeof(Int32))
|
|
25 throw new InvalidOperationException("Only enums based on Int32 are supported");
|
|
26
|
|
27 _symbols = ((T[])Enum.GetValues(typeof(T)))
|
|
28 .OrderBy(x => x.ToInt32(CultureInfo.InvariantCulture))
|
|
29 .ToArray();
|
|
30
|
|
31 if (
|
|
32 _symbols[_symbols.Length - 1].ToInt32(CultureInfo.InvariantCulture) >= _symbols.Length
|
|
33 || _symbols[0].ToInt32(CultureInfo.InvariantCulture) != 0
|
|
34 )
|
|
35 throw new InvalidOperationException("The specified enumeration must be zero-based and continuously numbered");
|
|
36
|
|
37 _fullAlphabet = new EnumAlphabet<T>(_symbols.Select(x => x.ToInt32(CultureInfo.InvariantCulture)).ToArray());
|
|
38 }
|
|
39
|
|
40
|
|
41
|
|
42 public static EnumAlphabet<T> FullAlphabet {
|
|
43 get {
|
|
44 return _fullAlphabet;
|
|
45 }
|
|
46 }
|
|
47
|
|
48
|
|
49 public EnumAlphabet()
|
59
|
50 : base(_symbols.Length) {
|
55
|
51 }
|
|
52
|
|
53 public EnumAlphabet(int[] map)
|
|
54 : base(map) {
|
59
|
55 Debug.Assert(map.Length == _symbols.Length);
|
55
|
56 }
|
|
57
|
|
58
|
|
59 public override int GetSymbolIndex(T symbol) {
|
|
60 return symbol.ToInt32(CultureInfo.InvariantCulture);
|
|
61 }
|
|
62
|
|
63 public override IEnumerable<T> InputSymbols {
|
|
64 get { return _symbols; }
|
|
65 }
|
|
66
|
|
67 }
|
|
68 }
|