TokenSymbolFactory運算符工廠類的分析過程和TokenKeyWordFactory基本相似。但是運算符一般只包含一個字符或者兩個字符,就不需要 一直向後分析了,只需要判斷運算符字典中是否存在對應的項即可。另外有些操作符的第一個字符是重復的,比如“>”和 “>=”,這時候就需要判斷“>”之後是否還存在“=”。如果向後再截取一個字符,在字典中也存在 對應項,則按雙字符運算符處理,否則就是單字符運算符。TokenSymbolFactory的代碼如下:
/// <summary>
/// 運算符工廠
/// </summary>
/// <remarks>Author:Alex Leo</remarks>
class TokenSymbolFactory : TokenFactory
{
private static SortedDictionary<string, string> m_DictionarySymbol = new SortedDictionary<string, string>();
/// <summary>
/// 獲取運算符字典
/// </summary>
/// <returns>運算符字典</returns>
/// <remarks>Author:Alex Leo; Date:2008-5-19;</remarks>
internal static SortedDictionary<string, string> GetSymbolDictionary()
{
if (m_DictionarySymbol.Count == 0)
{
m_DictionarySymbol = TokenFactory.GetOperateTokenDictionary (OperateTokenTypeEnum.TokenSymbol);
}
return m_DictionarySymbol;
}
/// <summary>
/// 詞法分析
/// </summary>
/// <param name="TokenList">記號對象列表</param>
/// <param name="Code">源表達式</param>
/// <param name="Index">分析序號</param>
/// <remarks>Author:Alex Leo</remarks>
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);
}
/// <summary>
/// 產生記號對象
/// </summary>
/// <param name="TokenWord">分析得到的單詞</param>
/// <param name="Index">當前序號</param>
/// <returns>記號對象</returns>
/// <remarks>Author:Alex Leo</remarks>
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;
}//ProduceToken
}//class TokenSymbolFactory