TokenSymbolFactory 運算子工廠類別分析過程與 TokenKeyWordFactory 基本相似。但運算子通常只有一或兩個字元,不需持續向後分析,只需判斷運算子字典是否存在對應項。另有些運算子首字元重複(如 > 和 >=),需判斷 > 後是否還有 =。若向後再截取一字元在字典也存在,按雙字元運算子處理,否則為單字元。代碼如下:
class TokenSymbolFactory : TokenFactory
{
private static SortedDictionary<string, string> m_DictionarySymbol = new SortedDictionary<string, string>();
internal static SortedDictionary<string, string> GetSymbolDictionary()
{
if (m_DictionarySymbol.Count == 0) m_DictionarySymbol = TokenFactory.GetOperateTokenDictionary(OperateTokenTypeEnum.TokenSymbol);
return m_DictionarySymbol;
}
public new static void LexicalAnalysis(List<TokenRecord> TokenList, string Code, ref int Index)
{
string strTempWord;
if ((Index < Code.Length - 1) && GetSymbolDictionary().ContainsKey(Code.Substring(Index, 2)))
{ strTempWord = Code.Substring(Index, 2); Index += 1; }
else strTempWord = Code.Substring(Index, 1);
TokenRecord Token = ProduceToken(strTempWord, Index);
TokenList.Add(Token);
}
protected new static TokenRecord ProduceToken(string TokenWord, int Index)
{
TokenRecord Token;
if (GetSymbolDictionary().ContainsKey(TokenWord.ToLower()))
{
string strFullClassName = "ConExpress.Calculator." + GetSymbolDictionary()[TokenWord.ToLower()];
Type TokenType = Type.GetType(strFullClassName);
Token = (TokenRecord)Activator.CreateInstance(TokenType, new object[] { Index, TokenWord.Length });
}
else throw new SyntaxException(Index, TokenWord.Length, "未知運算式:" + TokenWord);
return Token;
}
}