/// <summary> /// 解析 /// </summary> private void Analyze() { if (_link_OP == null) { if (_expression.Trim().Length > 0) { PhraseAnalyzer analyze = new PhraseAnalyzer(_expression); _link_OP = analyze.Analyze(); } else { throw new Exception("Error! 表达式为空"); } } }
/// <summary> /// 词法分析 /// </summary> public Link_OP Analyze() { _link_OP = new Link_OP(); char[] chArray = _expression.Trim().ToCharArray(); int i = 0; int startpos = 0; int endpos = 0; EDFAState prestate = EDFAState.Start; //DFA的前一个状态 while (i < chArray.Length) { if (prestate == EDFAState.CharStr) { //字符串结构 - 字符串结构是处理当前态 - 其它类型是处理上一态 if (chArray[i] == '"' && chArray[i - 1] != '\\') { endpos = i; AddToLink(startpos, endpos, prestate); prestate = EDFAState.Start; startpos = i + 1; } else if (i + 1 == chArray.Length) { throw new Exception("Error! 词法.缺少字符串引号(\")"); } } else if (chArray[i] == '"') { //字符串开始 if (prestate != EDFAState.Start) { endpos = i - 1; AddToLink(startpos, endpos, prestate); startpos = i; } prestate = EDFAState.CharStr; } else if (Char.IsLetter(chArray[i])) { //字母 if (prestate == EDFAState.Start) { prestate = EDFAState.ABCStr; } else if (prestate != EDFAState.ABCStr) { //处理前一个词 endpos = i - 1; //保存结束位置 AddToLink(startpos, endpos, prestate); prestate = EDFAState.ABCStr; startpos = i; //保存开始位置 } } else if (Char.IsDigit(chArray[i])) { //数字 if (prestate == EDFAState.Start) { prestate = EDFAState.IntStr; } else if (prestate != EDFAState.IntStr && prestate != EDFAState.DoubleStr) { endpos = i - 1; AddToLink(startpos, endpos, prestate); prestate = EDFAState.IntStr; startpos = i; } } else if (chArray[i] == '.') { //小数点 if (prestate == EDFAState.IntStr) { prestate = EDFAState.DoubleStr; } else { throw new Exception(string.Format("Error! 词法.错误的小数点位置,索引:{0}", i.ToString())); } } else if (chArray[i] == ',') { //逗号 endpos = i - 1; AddToLink(startpos, endpos, prestate); prestate = EDFAState.Comma; startpos = i; } else if (Char.IsWhiteSpace(chArray[i]) || chArray[i] == '\r' || chArray[i] == '\n' || chArray[i] == '\t') { //空格,回车,制表符 跳过 } else if (chArray[i] == '(' || chArray[i] == ')' || chArray[i] == '+' || chArray[i] == '-' || chArray[i] == '*' || chArray[i] == '/' || chArray[i] == '%' || chArray[i] == '>' || chArray[i] == '<' || chArray[i] == '=') { //操作符只能是单值符号+多值符号在链表添加时处理 if (prestate != EDFAState.Start) { endpos = i - 1; AddToLink(startpos, endpos, prestate); startpos = i; } prestate = EDFAState.OperatorStr; } else { throw new Exception(string.Format("Error! 词法.非法字符“{0}”(索引:{1})", chArray[i].ToString(), i.ToString())); } i++; if (i == chArray.Length) { endpos = i - 1; if (startpos == endpos && chArray[endpos] == '"') { throw new Exception("Error! 词法.缺少字符串引号(\")"); } AddToLink(startpos, endpos, prestate); } }// end while return(_link_OP); }