|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace DigitalSamurai.SpellSharp.InputProcessing
{
public abstract partial class Processor<TLexicalElements>
{
public class LiteralToElementRecognizer
{
private static Dictionary<string, TLexicalElements> literalToLexicalElementTable;
static LiteralToElementRecognizer ()
{
var table = new Dictionary<string, TLexicalElements>
(
DetermineStringComparer ()
);
foreach (var field in typeof (TLexicalElements).GetFields (BindingFlags.Static | BindingFlags.Public))
{
foreach (LexicalLiteralAttribute literalAttribute in field.GetCustomAttributes (typeof (LexicalLiteralAttribute), false))
{
var literalValue = literalAttribute.Value;
if (!string.IsNullOrEmpty (literalValue) && !table.ContainsKey (literalValue))
{
table.Add
(
literalValue,
(TLexicalElements) field.GetValue (null)
);
}
}
}
literalToLexicalElementTable = table;
}
private static IEqualityComparer<string> DetermineStringComparer ()
{
var comparisonType = StringComparison.Ordinal;
foreach (LexicalElementComparisonAttribute comparisonAttribute in typeof (TLexicalElements).GetCustomAttributes (typeof (LexicalElementComparisonAttribute), false))
{
comparisonType = comparisonAttribute.Value;
break;
}
var comparer = DetermineStringComparer (comparisonType);
if (comparer != null)
{
return comparer;
}
return DetermineStringComparer (StringComparison.Ordinal);
}
private static IEqualityComparer<string> DetermineStringComparer (StringComparison comparisonType)
{
var property = typeof (StringComparer).GetProperty (comparisonType.ToString (), BindingFlags.Static | BindingFlags.Public);
if (property == null)
{
return null;
}
return (IEqualityComparer<string>) property.GetValue (null, null);
}
public static bool TryDetermine (string literal, out TLexicalElements lexicalElement)
{
return literalToLexicalElementTable.TryGetValue (literal, out lexicalElement);
}
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.