EnumAlphabet.cs
67 lines
| 2.4 KiB
| text/x-csharp
|
CSharpLexer
cin
|
r156 | using System; | ||
cin
|
r55 | using System.Collections.Generic; | ||
cin
|
r59 | using System.Diagnostics; | ||
cin
|
r55 | using System.Globalization; | ||
using System.Linq; | ||||
cin
|
r156 | using System.Diagnostics.CodeAnalysis; | ||
cin
|
r55 | |||
namespace Implab.Parsing { | ||||
/// <summary> | ||||
/// Алфавит символами которого являются элементы перечислений. | ||||
/// </summary> | ||||
/// <typeparam name="T">Тип перечислений</typeparam> | ||||
cin
|
r158 | public class EnumAlphabet<T> : IndexedAlphabetBase<T> where T : struct, IConvertible { | ||
cin
|
r156 | [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] | ||
cin
|
r55 | static readonly T[] _symbols; | ||
static readonly EnumAlphabet<T> _fullAlphabet; | ||||
cin
|
r156 | [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] | ||
cin
|
r55 | static EnumAlphabet() { | ||
if (!typeof(T).IsEnum) | ||||
throw new InvalidOperationException("Invalid generic parameter, enumeration is required"); | ||||
if (Enum.GetUnderlyingType(typeof(T)) != typeof(Int32)) | ||||
throw new InvalidOperationException("Only enums based on Int32 are supported"); | ||||
_symbols = ((T[])Enum.GetValues(typeof(T))) | ||||
.OrderBy(x => x.ToInt32(CultureInfo.InvariantCulture)) | ||||
.ToArray(); | ||||
if ( | ||||
_symbols[_symbols.Length - 1].ToInt32(CultureInfo.InvariantCulture) >= _symbols.Length | ||||
|| _symbols[0].ToInt32(CultureInfo.InvariantCulture) != 0 | ||||
) | ||||
throw new InvalidOperationException("The specified enumeration must be zero-based and continuously numbered"); | ||||
_fullAlphabet = new EnumAlphabet<T>(_symbols.Select(x => x.ToInt32(CultureInfo.InvariantCulture)).ToArray()); | ||||
} | ||||
public static EnumAlphabet<T> FullAlphabet { | ||||
get { | ||||
return _fullAlphabet; | ||||
} | ||||
} | ||||
public EnumAlphabet() | ||||
cin
|
r59 | : base(_symbols.Length) { | ||
cin
|
r55 | } | ||
public EnumAlphabet(int[] map) | ||||
: base(map) { | ||||
cin
|
r59 | Debug.Assert(map.Length == _symbols.Length); | ||
cin
|
r55 | } | ||
public override int GetSymbolIndex(T symbol) { | ||||
return symbol.ToInt32(CultureInfo.InvariantCulture); | ||||
} | ||||
public override IEnumerable<T> InputSymbols { | ||||
get { return _symbols; } | ||||
} | ||||
} | ||||
} | ||||