protected override void OnElement(Lexem lexem) { if (lexem is LexemValue) _lexems.Add(lexem); else if (lexem is LexemVariable) _lexems.Add(lexem); else if (lexem is LexemFunction) _lexems.Add(lexem); else throw new FormatException(String.Format("Expression Element not recognized: {0}", lexem.ToString())); }
private void Eval() { for (int i = 0; i < Output.Count; i++) { var isTaken = false; Lexem lex = Output[i]; if (lex.LexemType == LexemType.SpecialWord) { if (lex.Content.ToString() == "while") { _whilePoses.Push(lex.Position); } else if (lex.Content.ToString() == "if") { _ifStateLevel++; } else if (lex.Content.ToString() == "else") { _ifStateLevel++; _inElse = true; } } if (lex.LexemType == LexemType.Brace) { if (lex.Content.ToString() == "{") { if (_inElse) { _skipToCloseBrace = _curIfResult; return; } var conditionResult = Stack.Peek().ToBoolean(); if (Output.Any(x => x.LexemType == LexemType.SpecialWord && x.Content.ToString() == "if")) { _curIfResult = conditionResult; } if (conditionResult == false) { _skipToCloseBrace = true; return; } } else { if (_skipToCloseBrace) { _skipToCloseBrace = false; if (_ifStateLevel == 0) { _whilePoses.Pop(); } } else { if (_ifStateLevel == 0 && _whilePoses.Count > 0) { isTaken = true; _stToLex.currentPosition = _whilePoses.Pop(); } } if (!isTaken && _ifStateLevel > 0) { _ifStateLevel--; } if (_inElse) { _inElse = false; _curIfResult = false; } return; } } if (lex.LexemType == LexemType.Variable || lex.LexemType == LexemType.Number || lex.LexemType == LexemType.Boolean || lex.LexemType == LexemType.String) { Stack.Push(lex); } if (lex.LexemType == LexemType.Modificator) { while (Stack.Count > 0) { var variable = Stack.Pop(); Storage.SetVarConst(variable.Content); } } if (lex.LexemType == LexemType.Operator) { if (lex.Content.Equals("++") || lex.Content.Equals("--")) { try { _increaseStack.Push(new Tuple <Lexem, Lexem>(Stack.Peek(), lex)); continue; } catch (Exception) { throw new SyntaxException("Ошибка выполнения операции " + lex.Content, lex); } } else if (lex.Content.Equals("var")) { Lexem lexVar; try { lexVar = Stack.Pop(); } catch (Exception) { throw new SyntaxException("Пропущено название переменной", lex); } if (lexVar.LexemType == LexemType.Variable && (Stack.Count == 0 || Storage.VariableExists(Stack.Peek()))) { Storage.AddVariable(lexVar, 0); Stack.Push(lexVar); } else if (lexVar.LexemType == LexemType.Number || lexVar.LexemType == LexemType.Variable) { Lexem lexVarConcrete; try { lexVarConcrete = Stack.Pop(); // имя массива } catch (Exception) { throw new SyntaxException("Пропущено имя массива", lex); } Storage.AddArrayVariable(lexVarConcrete, lexVar); Stack.Push(lexVar); if (Output[i + 1].LexemType == LexemType.Operator && Output[i + 1].Content.ToString() == "]") { Output.RemoveAt(i + 1); } else { throw new SyntaxException("Пропущена закрывающаяся скобка: ]", lexVarConcrete); } } continue; } Lexem right, left; try { right = Stack.Pop(); left = Stack.Pop(); } catch (Exception) { throw new SyntaxException("Ошибка выполнения операции " + lex.Content, lex); } Stack.Push(new Lexem(ProcessOperator(lex, left, right, ref _curLexType), _curLexType, lex.Position)); } if (lex.LexemType == LexemType.EndOfExpr) { while (_increaseStack.Count > 0) { var tuple = _increaseStack.Pop(); if (tuple.Item2.Content.Equals("++")) { Storage.SetVariableValue(tuple.Item1, tuple.Item1.ToDouble() + 1); } else { Storage.SetVariableValue(tuple.Item1, tuple.Item1.ToDouble() - 1); } } Stack.Clear(); return; } if (lex.LexemType == LexemType.Function) { ProcessFunction(lex); } } }
public void setLexemType(Lexem lexemType) { this.lexemType = lexemType; }
public EmptyLexem(Lexem Parent, int lineNumber) : base(Parent, ref lineNumber, "_", 0, null) { }
/*Запись строки в таблицу*/ public void SetTableString(Lexem lit) { MyLexems.Add(lit); }
static private SingleCondition <VariableType, ValueType> ParseConclusion <VariableType, ValueType>(List <IExpression> conditionExpression, List <VariableType> output, Dictionary <string, Lexem> lexems) where VariableType : class, INamedVariable where ValueType : class, INamedValue { List <IExpression> copyExpression = conditionExpression.GetRange(0, conditionExpression.Count); // // Remove extra brackets // while ( copyExpression.Count >= 2 && (copyExpression[0] == lexems["("] && copyExpression[conditionExpression.Count - 1] == lexems[")"])) { copyExpression = copyExpression.GetRange(1, copyExpression.Count - 2); } if (copyExpression.Count != 3) { throw new Exception("Conclusion part of the rule should be in form: 'variable is term'"); } // // Parse variable // Lexem exprVariable = (Lexem)copyExpression[0]; if (!(exprVariable is VarLexem <VariableType>)) { throw new Exception(string.Format("Wrong identifier '{0}' in conclusion part of the rule.", exprVariable.Text)); } VarLexem <VariableType> varLexem = (VarLexem <VariableType>)exprVariable; if (varLexem.Input == true) { throw new Exception("The variable in conclusion part must be an output variable."); } // // Parse 'is' lexem // Lexem exprIs = (Lexem)copyExpression[1]; if (exprIs != lexems["is"]) { throw new Exception(string.Format("'is' keyword must go after {0} identifier.", varLexem.Text)); } // // Parse term // Lexem exprTerm = (Lexem)copyExpression[2]; if (!(exprTerm is IAltLexem)) { throw new Exception(string.Format("Wrong identifier '{0}' in conclusion part of the rule.", exprTerm.Text)); } IAltLexem altLexem = (IAltLexem)exprTerm; TermLexem <ValueType> termLexem = null; do { if (!(altLexem is TermLexem <ValueType>)) { continue; } termLexem = (TermLexem <ValueType>)altLexem; if (!varLexem.Var.Values.Contains(termLexem.Term)) { termLexem = null; continue; } }while ((altLexem = altLexem.Alternative) != null && termLexem == null); if (termLexem == null) { throw new Exception(string.Format("Wrong identifier '{0}' in conclusion part of the rule.", exprTerm.Text)); } // // Return fuzzy rule's conclusion // return(new SingleCondition <VariableType, ValueType>(varLexem.Var, termLexem.Term, false)); }
public SyntaxException(string message, Lexem lexem) : base(message) { Lexem = lexem; }
static private SingleCondition <VariableType, ValueType> ParseConclusion <VariableType, ValueType>(List <IExpression> conditionExpression, List <VariableType> output, Dictionary <string, Lexem> lexems) where VariableType : class, INamedVariable where ValueType : class, INamedValue { List <IExpression> copyExpression = conditionExpression.GetRange(0, conditionExpression.Count); // // Удаление лишних скобок // while ( copyExpression.Count >= 2 && (copyExpression[0] == lexems["("] && copyExpression[conditionExpression.Count - 1] == lexems[")"])) { copyExpression = copyExpression.GetRange(1, copyExpression.Count - 2); } if (copyExpression.Count != 3) { throw new Exception("Вывод часть правила должны быть в форме: 'переменная есть терм'"); } // // Разбор переменной // Lexem exprVariable = (Lexem)copyExpression[0]; if (!(exprVariable is VarLexem <VariableType>)) { throw new Exception(string.Format("Неверный идентификатор '{0}' в состоянии части правила.", exprVariable.Text)); } VarLexem <VariableType> varLexem = (VarLexem <VariableType>)exprVariable; if (varLexem.Input == true) { throw new Exception("Переменная в заключительной части должна быть выходной переменной."); } // // Разбор 'is' лексемы // Lexem exprIs = (Lexem)copyExpression[1]; if (exprIs != lexems["is"]) { throw new Exception(string.Format("'is' ключевое слово после {0} идентификатора.", varLexem.Text)); } // // Parse term // Lexem exprTerm = (Lexem)copyExpression[2]; if (!(exprTerm is IAltLexem)) { throw new Exception(string.Format("Неверный идентификатор '{0}' в заключительной части правила.", exprTerm.Text)); } IAltLexem altLexem = (IAltLexem)exprTerm; TermLexem <ValueType> termLexem = null; do { if (!(altLexem is TermLexem <ValueType>)) { continue; } termLexem = (TermLexem <ValueType>)altLexem; if (!varLexem.Var.Values.Contains(termLexem.Term)) { termLexem = null; continue; } }while ((altLexem = altLexem.Alternative) != null && termLexem == null); if (termLexem == null) { throw new Exception(string.Format("Неверный идентификатор '{0}' в заключительной части правила.", exprTerm.Text)); } // // Возвращение нечеткого правила заключения // return(new SingleCondition <VariableType, ValueType>(varLexem.Var, termLexem.Term, false)); }
private static Lexem GetLexem() { SkipSpaces(); Lexem result = default(Lexem); switch (symbol) { case EOF: result = new Lexem(LexType.EOF); break; case Add: result = new Lexem(LexType.Add); break; case Minus: result = new Lexem(LexType.Minus); break; case Multiply: endPosition++; if (symbol == Multiply) { result = new Lexem(LexType.Degree); } else { endPosition--; result = new Lexem(LexType.Multiply); } break; case Divide: result = new Lexem(LexType.Divide); break; case OpenBracket: result = new Lexem(LexType.OpenBreaket); break; case CloseBracket: result = new Lexem(LexType.CloseBracket); break; case Semicolon: result = new Lexem(LexType.Semicolon); break; case EqualSign: endPosition++; if (symbol == EqualSign) { result = new Lexem(LexType.Equal); } else { endPosition--; result = new Lexem(LexType.EqualSign); } break; case OpenBlockBracket: result = new Lexem(LexType.OpenBlockBracket); break; case CloseBlockBracket: result = new Lexem(LexType.CloseBlockBracket); break; case OpenSquadBracket: result = new Lexem(LexType.OpenSquadBracket); break; case CloseSquadBracket: result = new Lexem(LexType.CloseSquadBracket); break; case Colon: result = new Lexem(LexType.Colon); break; case Not: endPosition++; if (symbol == EqualSign) { result = new Lexem(LexType.NotEqual); } else { endPosition--; Parser.ErrorList.Add(new Error(LexerException.IncorrectOperator, new Nodes.Node.Coords(x, y))); result = new Lexem(LexType.Error); } break; case Higher: endPosition++; if (symbol == EqualSign) { result = new Lexem(LexType.HighEqual); } else { endPosition--; result = new Lexem(LexType.Higher); } break; case Lower: endPosition++; if (symbol == EqualSign) { result = new Lexem(LexType.LowEqual); } else { endPosition--; result = new Lexem(LexType.Lower); } break; case Quote: int newPos = endPosition + 1; while (newPos < expression.Length && expression[newPos] != Quote && expression[newPos] != LineFeed) { newPos++; } result = new Lexem(endPosition + 1, newPos - 1); endPosition = newPos; break; default: if (digits.Contains(symbol)) { result = GetNumber(); break; } if (letters.Contains(symbol) || symbol == Underline) { result = GetVar(); break; } Parser.ErrorList.Add(new Error(LexerException.IncorrectSymbol, new Nodes.Node.Coords(x, y))); endPosition++; PushCoordinates(); result = GetLexem(); break; } endPosition++; PushCoordinates(); return result; }
private static Lexem GetNumber() { endPosition = GetEndOfNumber(); Lexem result; float number = 0; bool correctNumber = true; try { number = float.Parse(expression.Substring(startPosition, endPosition - startPosition + 1).Replace(Point, Comma)); } catch (Exception) { correctNumber = false; } finally { result = new Lexem(number); if (!correctNumber) Parser.ErrorList.Add(new Error(LexerException.IncorrectNumber, result.EndCoords)); } return result; }
public static List <Lexem> getLex(string text) { List <Lexem> lexems = new List <Lexem>(); //Список распознанных лексем int st_id = 0; string lex1 = ""; //Конкретная лексема в выражении int buff = 0; for (int i = 0; i < text.Length; i++) //Цикл по символам строки { Lexem lex = new Lexem("Unknown", ""); //Пока не начали распознавание очередной лексемы while (i < text.Length && transTable(text[i], st_id) != -1) //Начинаем распознавание очередной лексемы { lex1 += Convert.ToString(text[i]); buff = st_id; st_id = transTable(text[i], buff); i++; } if (st_id == 4) { i--; string numb_buf = ""; string let_buf = ""; string oper_buf = ""; int j; for (j = 0; j < lex1.Length; j++) { if (char.IsDigit(lex1[j])) { numb_buf += Convert.ToString(lex1[j]); } else if (char.IsLetter(lex1[j])) { let_buf += Convert.ToString(lex1[j]); } else if (lex1[j] == '+' || lex1[j] == '-') { oper_buf = Convert.ToString(lex1[j]); } } lex.Value = numb_buf; lex.TokType = "Number"; lexems.Add(lex); lex.Value = let_buf; lex.TokType = "Identifier"; lexems.Add(lex); lex.Value = oper_buf; lex.TokType = "Operator"; lexems.Add(lex); st_id = 0; lex1 = ""; } else { i--; lex.Value = lex1; lex.TokType = getTokenType(transTable(text[i], buff)); st_id = 0; lex1 = ""; lexems.Add(lex); } } return(lexems); }
public override Lexem ReadNextLexem(SourceCodeIterator iterator) { return(Lexem.Empty()); }
public override LexemVariable Execute(Lexem lexem, ILexemEnvironment environment = null) { if (lexem == null) throw new InvalidOperationException("Can't execute null lexem on Value"); if (lexem is LexemVariable) { switch (((LexemVariable)lexem).Name.ToLower()) { case "date": return this.Value.Date; case "year": return this.Value.Year; case "month": return this.Value.Month; case "day": return this.Value.Day; case "hour": return this.Value.Hour; case "minute": return this.Value.Minute; case "second": return this.Value.Second; case "dayofweek": return this.Value.DayOfWeek.ToString(); } } else if (lexem is LexemFunction) { var function = lexem as LexemFunction; Func<int, double> getFuncNumber = i => (function.Arguments[i].Calculate(environment).Value as LexemValueNumber).Value; switch (((LexemFunction)lexem).Name.ToLower()) { case "tostring": return this.Value.ToString(Formats.First()); case "addyears": return this.Value.Date.AddYears((int)getFuncNumber(0)); case "addmonths": return this.Value.Date.AddMonths((int)getFuncNumber(0)); case "adddays": return this.Value.Date.AddDays(getFuncNumber(0)); case "addhours": return this.Value.Date.AddHours(getFuncNumber(0)); case "addminutes": return this.Value.Date.AddMinutes(getFuncNumber(0)); case "addseconds": return this.Value.Date.AddSeconds(getFuncNumber(0)); } } return base.Execute(lexem, environment); }
public void SetNext(Lexem next) { NextLexem = next; }
public override LexemVariable Execute(Lexem lexem, ILexemEnvironment environment = null) { return base.Execute(lexem, environment); }
protected Lexem ReadLexem(string s, int startIdx) { var lexem = new Lexem(); lexem.Type = LexemType.Unknown; lexem.Expr = s; lexem.Start = startIdx; lexem.End = startIdx; while (lexem.End < s.Length) { if (Array.IndexOf(delimiters, s[lexem.End]) >= 0) { if (lexem.Type == LexemType.Unknown) { lexem.End++; lexem.Type = LexemType.Delimiter; return(lexem); } if (lexem.Type != LexemType.StringConstant && (lexem.Type != LexemType.NumberConstant || s[lexem.End] != '.')) { return(lexem); // stop } } else if (Char.IsSeparator(s[lexem.End])) { if (lexem.Type != LexemType.StringConstant && lexem.Type != LexemType.Unknown) { return(lexem); // stop } } else if (Char.IsLetter(s[lexem.End])) { if (lexem.Type == LexemType.Unknown) { lexem.Type = LexemType.Name; } } else if (Char.IsDigit(s[lexem.End])) { if (lexem.Type == LexemType.Unknown) { lexem.Type = LexemType.NumberConstant; } } else if (Array.IndexOf(specialNameChars, s[lexem.End]) >= 0) { if (lexem.Type == LexemType.Unknown) { lexem.Type = LexemType.Name; } else if (lexem.Type != LexemType.StringConstant) { return(lexem); } } else if (s[lexem.End] == charQuote) { if (lexem.Type == LexemType.Unknown) { lexem.Type = LexemType.StringConstant; } else { if (lexem.Type == LexemType.StringConstant) { // check for "" combination if (((lexem.End + 1) >= s.Length || s[lexem.End + 1] != charQuote)) { lexem.End++; return(lexem); } else if ((lexem.End + 1) < s.Length) { lexem.End++; // skip next quote } } else { return(lexem); } } } else if (Char.IsControl(s[lexem.End]) && lexem.Type != LexemType.Unknown && lexem.Type != LexemType.StringConstant) { return(lexem); } // goto next char lexem.End++; } if (lexem.Type == LexemType.Unknown) { lexem.Type = LexemType.Stop; return(lexem); } if (lexem.Type == LexemType.StringConstant) { throw new LambdaParserException(s, startIdx, "Unterminated string constant"); } return(lexem); }
private bool match(Lexem lexem) { return(iter >= tokens.Count ? false : tokens[iter].getLexemType().getType() == lexem.getType() ? iter++ != -1 && true : this.error.add(iter, tokens[iter], lexem) && false); }
private IFormat ParseExpression(string str) { List <IFormat> operands = new List <IFormat>(); LatexLexems ll = LatexLexems.getInstance(); foreach (var def in ll.getDefinitionsLexem()) { if (matches(str, def.getRegex())) { IFormat name = ParseExpression(getTokenValue(str, def.getRegex(), "name")); IFormat value = ParseExpression(getTokenValue(str, def.getRegex(), "expr")); operands.Add(name); operands.Add(value); return(new Latex(def.getType(), operands, null)); } } if ((operands = ParseMultiOperandsExpression(str, '+')) != null) { return(new Latex(Types.Addition, operands, null)); } if ((operands = ParseMultiOperandsExpression(str, '-')) != null) { return(new Latex(Types.Substraction, operands, null)); } if ((operands = ParseMultiOperandsExpression(str, '*')) != null) { return(new Latex(Types.Multiplication, operands, null)); } operands = new List <IFormat>(); string[] strings; Lexem tmp = new Lexem(Types.Variable, ""); int length = 0; foreach (var def in ll.getOperandsLexem()) { Regex rgx = new Regex(def.getRegex()); Match match = rgx.Match(str); if (match.Length > length) { tmp = def; length = match.Length; } } if (tmp.getRegex() == "") { throw new Exception("Bad input, really! Follow the syntax"); } switch (tmp.getType()) { case Types.Variable: return(new Latex(str)); case Types.Number: return(new Latex(Convert.ToDouble(str))); case Types.Interval: case Types.List: { str = str.Substring(1, str.Length - 2); strings = str.Split(';'); foreach (var s in strings) { operands.Add(ParseExpression(s)); } return(new Latex(tmp.getType(), operands, null)); } case Types.FuncExpression: IFormat funcName = ParseExpression(getTokenValue(str, tmp.getRegex(), "fr")); string parametrs = getTokenValue(str, tmp.getRegex(), "sec"); parametrs = parametrs.Substring(1, parametrs.Length - 2); strings = parametrs.Split(','); foreach (var s in strings) { operands.Add(ParseExpression(s)); } return(new Latex(tmp.getType(), operands, funcName)); } IFormat first = ParseExpression(getTokenValue(str, tmp.getRegex(), "fr")); IFormat second = ParseExpression(getTokenValue(str, tmp.getRegex(), "sec")); operands.Add(first); operands.Add(second); return(new Latex(tmp.getType(), operands, null)); }
public override LexemVariable Execute(Lexem lexem, ILexemEnvironment environment = null) { if (lexem == null) throw new InvalidOperationException("Can't execute null lexem on Value"); if (lexem is LexemVariable) return this[((LexemVariable)lexem).Name]; return base.Execute(lexem, environment); }
protected Lexem ReadLexem(string s, int startIdx) { var lexem = new Lexem(); lexem.Type = LexemType.Unknown; lexem.Expr = s; lexem.Start = startIdx; lexem.End = startIdx; while (lexem.End < s.Length) { if (Array.IndexOf(delimiters, s[lexem.End]) >= 0) { if (lexem.Type == LexemType.Unknown) { lexem.End++; lexem.Type = LexemType.Delimiter; return lexem; } if (lexem.Type != LexemType.StringConstant && (lexem.Type != LexemType.NumberConstant || s[lexem.End] != '.')) return lexem; // stop } else if (Char.IsSeparator(s[lexem.End])) { if (lexem.Type != LexemType.StringConstant && lexem.Type != LexemType.Unknown) return lexem; // stop } else if (Char.IsLetter(s[lexem.End])) { if (lexem.Type == LexemType.Unknown) lexem.Type = LexemType.Name; } else if (Char.IsDigit(s[lexem.End])) { if (lexem.Type == LexemType.Unknown) lexem.Type = LexemType.NumberConstant; } else if (Array.IndexOf(specialNameChars, s[lexem.End]) >= 0) { if (lexem.Type == LexemType.Unknown) lexem.Type = LexemType.Name; else if (lexem.Type!=LexemType.StringConstant) return lexem; } else if (s[lexem.End] == charQuote) { if (lexem.Type == LexemType.Unknown) lexem.Type = LexemType.StringConstant; else { if (lexem.Type == LexemType.StringConstant) { // check for "" combination if (((lexem.End + 1) >= s.Length || s[lexem.End + 1] != charQuote)) { lexem.End++; return lexem; } else if ((lexem.End + 1) < s.Length) lexem.End++; // skip next quote } else { return lexem; } } } else if (Char.IsControl(s[lexem.End]) && lexem.Type != LexemType.Unknown && lexem.Type != LexemType.StringConstant) return lexem; // goto next char lexem.End++; } if (lexem.Type == LexemType.Unknown) { lexem.Type = LexemType.Stop; return lexem; } if (lexem.Type == LexemType.StringConstant) throw new LambdaParserException(s, startIdx, "Unterminated string constant"); return lexem; }
private static TypeCode PickCorrectType(Lexem leftValue, Lexem rightValue) { LexemType lType = leftValue.LexemType, rType = rightValue.LexemType; if (lType == LexemType.Number && rType == LexemType.Number) { return(TypeCode.Double); } if (lType == LexemType.String && rType == LexemType.String) { return(TypeCode.String); } if (lType == LexemType.Variable && rType == LexemType.Number || lType == LexemType.String && rType == LexemType.Number) { try { leftValue.ToDouble(); return(TypeCode.Double); } catch (Exception) { return(TypeCode.String); } } if (lType == LexemType.Number && rType == LexemType.Variable || lType == LexemType.Number && rType == LexemType.String) { try { rightValue.ToDouble(); return(TypeCode.Double); } catch (Exception) { return(TypeCode.String); } } if (lType == LexemType.Variable && rType == LexemType.String || lType == LexemType.String && rType == LexemType.Variable) { return(TypeCode.String); } if (lType == LexemType.Variable && rType == LexemType.Boolean || lType == LexemType.Boolean && rType == LexemType.Variable) { return(TypeCode.Boolean); } if (lType == LexemType.Boolean && rType == LexemType.Boolean) { return(TypeCode.Boolean); } if (lType == LexemType.Variable && rType == LexemType.Variable) { try { leftValue.ToDouble(); return(TypeCode.Double); } catch (Exception) { try { leftValue.ToBoolean(); return(TypeCode.Boolean); } catch (Exception) { return(TypeCode.String); } } } throw new SyntaxException("Не удалось определить общий тип", leftValue); }
protected bool Equals(Lexem other) { return Kind == other.Kind; }
public static object Calculate(Lexem oper, Lexem leftValue, Lexem rightValue, ref LexemType lt) { var t = PickCorrectType(leftValue, rightValue); switch (t) { case TypeCode.Double: lt = LexemType.Number; switch (oper.Content.ToString()) { case "*": return(leftValue.ToDouble() * rightValue.ToDouble()); case "/": return(leftValue.ToDouble() / rightValue.ToDouble()); case "+": return(leftValue.ToDouble() + rightValue.ToDouble()); case "-": return(leftValue.ToDouble() - rightValue.ToDouble()); case ">": lt = LexemType.Boolean; return(leftValue.ToDouble() > rightValue.ToDouble()); case "<": lt = LexemType.Boolean; return(leftValue.ToDouble() < rightValue.ToDouble()); case "!=": lt = LexemType.Boolean; return(leftValue.ToDouble() != rightValue.ToDouble()); case "==": lt = LexemType.Boolean; return(leftValue.ToDouble() == rightValue.ToDouble()); case ">=": lt = LexemType.Boolean; return(leftValue.ToDouble() >= rightValue.ToDouble()); case "<=": lt = LexemType.Boolean; return(leftValue.ToDouble() <= rightValue.ToDouble()); case "=": Storage.SetVariableValue(leftValue, rightValue.ToDouble()); if (leftValue.Content is Variable) { return((leftValue.Content as Variable).Value); } return(Storage.GetVariable(leftValue.Content.ToString())); } break; case TypeCode.String: lt = LexemType.String; switch (oper.Content.ToString()) { case "+": return(leftValue.ToString() + rightValue.ToString()); case "!=": lt = LexemType.Boolean; return(leftValue.ToString() != rightValue.ToString()); case "==": lt = LexemType.Boolean; return(leftValue.ToString() == rightValue.ToString()); case "=": Storage.SetVariableValue(leftValue, rightValue.ToString()); if (leftValue.Content is Variable) { return((leftValue.Content as Variable).Value); } return(Storage.GetVariable(leftValue.Content.ToString())); default: throw new SyntaxException("Неверная операция", oper); } case TypeCode.Boolean: lt = LexemType.Boolean; switch (oper.Content.ToString()) { case "||": return(leftValue.ToBoolean() || rightValue.ToBoolean()); case "&&": return(leftValue.ToBoolean() && rightValue.ToBoolean()); case "==": return(leftValue.ToBoolean() == rightValue.ToBoolean()); case "!=": return(leftValue.ToBoolean() != rightValue.ToBoolean()); case "=": Storage.SetVariableValue(leftValue, rightValue.ToBoolean()); if (leftValue.Content is Variable) { return((leftValue.Content as Variable).Value); } return(Storage.GetVariable(leftValue.Content.ToString())); default: throw new SyntaxException("Неверная операция", oper); } } throw new SyntaxException("Ошибка вычисления оператора", oper); }
public StateLexem(Lexem Parent, ref int lineNumber, string Line, int currentIndent, string[] lines) : base(Parent, ref lineNumber, Line, currentIndent, lines) { }
public LexemVariable Execute(Lexem lexem, ILexemEnvironment environment = null) { if (lexem == null) throw new InvalidOperationException("Can't execute null lexem on Variable"); if (this.Value == null) throw new InvalidOperationException("Can't execute Lexem on empty Value"); return this.Value.Execute(lexem, environment); }
public Token(string value, Lexem lexemType) { this.value = value; this.lexemType = lexemType; }
private bool simpleExpression() { Lexem currentLexem = tokens[pointer].Lexem; if (currentLexem == Lexem.DIGIT || currentLexem == Lexem.VAR) { POLIS.Add(tokens[pointer]); pointer++; } else if (currentLexem == Lexem.OP || currentLexem == Lexem.ASSIGN_OP || currentLexem == Lexem.COMP_OP) { while (stack.Count != 0 && compareOperators(tokens[pointer], stack.Peek())) { POLIS.Add(stack.Pop()); } stack.Push(tokens[pointer]); pointer++; } else if (currentLexem == Lexem.LB) { bracketIndex++; stack.Push(tokens[pointer]); pointer++; } else if (currentLexem == Lexem.RB) { bracketIndex--; while (stack.Count != 0 && stack.Peek().Lexem != Lexem.LB) { POLIS.Add(stack.Pop()); } if (stack.Count != 0) { stack.Pop(); } pointer++; } else if (currentLexem == Lexem.END) { freeStack(); POLIS.Add(tokens[pointer]); return(false); } else if (currentLexem == Lexem.IF_KW) { var pointerBeforeCondition = POLIS.Count; ifExpression(); MarkConditionIndexes(pointerBeforeCondition, POLIS.Count - 1); } else if (currentLexem == Lexem.WHILE_KW) { var pointerBeforeCondition = POLIS.Count; whileExpression(); MarkConditionIndexes(pointerBeforeCondition, POLIS.Count - 1); } else if (currentLexem == Lexem.FOR_KW) { var pointerBeforeCondition = POLIS.Count; forExpression(); MarkConditionIndexes(pointerBeforeCondition, POLIS.Count - 1); } else if (currentLexem == Lexem.OUT_KW) { pointer++; stack.Push(tokens[pointer]); pointer++; while (tokens[pointer].Lexem != Lexem.EOL) { simpleExpression(); } POLIS.Add(new Token("&", Lexem.FUNC)); POLIS.Add(new Token("out", Lexem.OUT_KW)); pointer++; } else if (currentLexem == Lexem.EOL) { freeStack(); pointer++; } else if (currentLexem == Lexem.POINT) { functionExpression(); } else if (currentLexem == Lexem.LIST_KW || currentLexem == Lexem.HT_KW) { POLIS.Add(tokens[pointer]); while (tokens[pointer].Lexem != Lexem.VAR) { pointer++; } POLIS.Add(tokens[pointer]); pointer++; } else if (currentLexem == Lexem.SPC || currentLexem == Lexem.LSB) { pointer++; } else if (currentLexem == Lexem.RETURN_KW) { var tempPointer = pointer + 1; while (tokens[tempPointer].Lexem == Lexem.SPC) { tempPointer++; } if (tokens[tempPointer].Lexem == Lexem.EOL) { POLIS.Add(new Token("RET", currentLexem)); pointer = tempPointer + 1; } else { pointer++; while (tokens[pointer].Lexem != Lexem.EOL) { simpleExpression(); } freeStack(); POLIS.Add(new Token("RET", currentLexem)); pointer++; } } else if (currentLexem == Lexem.EF_NAME) { int stackCount = stack.Count; var functToken = tokens[pointer]; while (tokens[pointer].Lexem != Lexem.LB) { pointer++; } pointer++; while (tokens[pointer].Lexem != Lexem.RB) { simpleExpression(); if (tokens[pointer].Lexem == Lexem.COMMA) { freeStack(stackCount); pointer++; } } freeStack(stackCount); POLIS.Add(functToken); } return(true); }
private bool expression() { Lexem temp = tokens[pointer].getLexemType(); switch (temp.getType()) { case "DIGIT": case "VAR": outString.Add(tokens[pointer]); pointer++; break; case "OP": case "ASSIGN_OP": case "COMPARISON_OP": while (tokenStack.Count != 0 && getPriority(tokens[pointer], tokenStack.Peek())) { outString.Add(tokenStack.Pop()); } tokenStack.Push(tokens[pointer]); pointer++; break; case "LP": tokenStack.Push(tokens[pointer]); pointer++; break; case "RP": while (tokenStack.Count != 0 && tokenStack.Peek().getLexemType().getType() != lexemTypeEnum.types["LP"].getType()) { outString.Add(tokenStack.Pop()); } tokenStack.Pop(); pointer++; break; case "IF": conditionalExpression(); int tempIfPosition = outString.Count; outString.Add(new Token("", terminalTypeEnum.types["GOTO_POINT"])); outString.Add(new Token("!F", terminalTypeEnum.types["GOTO_ON_FALSE"])); body(); if (tokens[pointer].getLexemType().getType() == lexemTypeEnum.types["ELSE"].getType()) { pointer++; int tempElsePosition = outString.Count; outString.Add(new Token("", terminalTypeEnum.types["GOTO_POINT"])); outString.Add(new Token("!", terminalTypeEnum.types["GOTO"])); outString[tempIfPosition].setValue(outString.Count.ToString()); body(); outString[tempElsePosition].setValue(outString.Count.ToString()); } else { outString[tempIfPosition].setValue(outString.Count.ToString()); } break; case "WHILE": int tempWhilePosition = outString.Count; conditionalExpression(); int tempEndPosition = outString.Count; outString.Add(new Token("", terminalTypeEnum.types["GOTO_POINT"])); outString.Add(new Token("!F", terminalTypeEnum.types["GOTO_ON_FALSE"])); body(); outString.Add(new Token(tempWhilePosition.ToString(), terminalTypeEnum.types["GOTO_POINT"])); outString.Add(new Token("!", terminalTypeEnum.types["GOTO"])); outString[tempEndPosition].setValue(outString.Count.ToString()); break; case "PRINT": pointer++; tokenStack.Push(tokens[pointer]); pointer++; while (tokens[pointer].getLexemType().getType() != lexemTypeEnum.types["EOE"].getType()) { expression(); } outString.Add(new Token("print", lexemTypeEnum.types["PRINT"])); pointer++; break; case "LIST": pointer++; while (tokens[pointer].getLexemType().getType() != lexemTypeEnum.types["EOE"].getType()) { expression(); } pointer++; outString.Add(new Token("list", lexemTypeEnum.types["LIST"])); break; case "HASHTABLE": pointer++; while (tokens[pointer].getLexemType().getType() != lexemTypeEnum.types["EOE"].getType()) { expression(); } pointer++; outString.Add(new Token("hashtable", lexemTypeEnum.types["HASHTABLE"])); break; case "INSERT": pointer++; while (tokens[pointer].getLexemType().getType() != lexemTypeEnum.types["INTO"].getType()) { expression(); } pointer++; while (tokens[pointer].getLexemType().getType() != lexemTypeEnum.types["ON"].getType()) { expression(); } pointer++; while (tokens[pointer].getLexemType().getType() != lexemTypeEnum.types["EOE"].getType()) { expression(); } pointer++; outString.Add(new Token("insert", lexemTypeEnum.types["INSERT"])); break; case "DELETE": pointer++; while (tokens[pointer].getLexemType().getType() != lexemTypeEnum.types["FROM"].getType()) { expression(); } pointer++; while (tokens[pointer].getLexemType().getType() != lexemTypeEnum.types["EOE"].getType()) { expression(); } pointer++; outString.Add(new Token("delete", lexemTypeEnum.types["DELETE"])); break; case "GET": pointer++; while (tokens[pointer].getLexemType().getType() != lexemTypeEnum.types["FROM"].getType()) { expression(); } pointer++; expression(); pointer++; outString.Add(new Token("get", lexemTypeEnum.types["GET"])); while (tokenStack.Count != 0 && getPriority(tokens[pointer], tokenStack.Peek())) { outString.Add(tokenStack.Pop()); } break; case "COUNTOF": pointer++; expression(); pointer++; outString.Add(new Token("countof", lexemTypeEnum.types["COUNTOF"])); while (tokenStack.Count != 0 && getPriority(tokens[pointer], tokenStack.Peek())) { outString.Add(tokenStack.Pop()); } break; case "EOE": while (tokenStack.Count != 0) { outString.Add(tokenStack.Pop()); } pointer++; break; case "END": while (tokenStack.Count != 0) { outString.Add(tokenStack.Pop()); } return(false); default: return(false); } return(true); }
public static bool IsUserSymbol(ref Lexem lex) { return(lex.Type == LexemType.Identifier && lex.Token == Token.NotAToken); }
private void ToRPN() { var modificators = new Stack <Lexem>(); Lexem lexem = null; Stack.Clear(); int i; for (i = 0; i < _lexems.Count; i++) { lexem = _lexems[i]; switch (lexem.LexemType) { case LexemType.ModificatorCandidate: throw new SyntaxException("Незнакомая лексема", lexem); case LexemType.Modificator: modificators.Push(lexem); break; case LexemType.SpecialWord: case LexemType.Boolean: case LexemType.String: case LexemType.Number: case LexemType.Variable: Output.Add(lexem); break; case LexemType.Operator: if (lexem.Content.Equals("]")) { var a = Stack.Peek(); while (Stack.Peek().LexemType != LexemType.LeftBrace) { Output.Add(Stack.Pop()); } if (Stack.Peek().LexemType == LexemType.LeftBrace) { Stack.Pop(); } if (Stack.Count > 0 && Stack.Peek().Content.Equals("var")) { Output.Add(Stack.Pop()); } Output.Add(lexem); break; } while (Stack.Count > 0 && Priority(Stack.Peek().Content.ToString()) >= Priority(lexem.Content.ToString())) { Output.Add(Stack.Pop()); } Stack.Push(lexem); break; case LexemType.LeftBracket: case LexemType.LeftBrace: case LexemType.Function: Stack.Push(lexem); break; case LexemType.RightBracket: while (Stack.Peek().LexemType != LexemType.LeftBracket) { Output.Add(Stack.Pop()); } if (Stack.Peek().LexemType == LexemType.LeftBracket) { Stack.Pop(); } if (Stack.Count > 0 && Stack.Peek().LexemType == LexemType.Function) { Output.Add(Stack.Pop()); } break; default: break; } } while (Stack.Count > 0) { Output.Add(Stack.Pop()); } while (modificators.Count > 0) { Output.Add(modificators.Pop()); } Output.Add(lexem); // ";", "}", "{" return; }
public static bool IsIdentifier(ref Lexem lex) { return(lex.Type == LexemType.Identifier); }
public LexemVariable Compute(Lexem argument1, Lexem argument2, ILexemEnvironment environment = null) { LexemValue result = null; if (this.OperatorType == OperationType.Arithmetic) { #region Arithmetic Operations LexemValue arg1 = LexemValue.GetValue(argument1); LexemValue arg2 = LexemValue.GetValue(argument2); if (arg1 == null || arg2 == null) return null; if (arg1 is LexemValueNumber && arg2 is LexemValueNumber) { #region number LexemValueNumber val1 = (LexemValueNumber)arg1; LexemValueNumber va12 = (LexemValueNumber)arg2; if (this.Text == "+") result = val1 + va12; else if (this.Text == "-") result = val1 - va12; else if (this.Text == "*") result = val1 * va12; else if (this.Text == "/") result = val1 / va12; #endregion } else if (arg1 is LexemValueComplex && arg2 is LexemValueComplex) { #region complex LexemValueComplex val1 = (LexemValueComplex)arg1; LexemValueComplex val2 = (LexemValueComplex)arg2; if (this.Text == "+") result = val1 + val2; else if (this.Text == "-") result = val1 - val2; else if (this.Text == "*") result = val1 * val2; else if (this.Text == "/") result = val1 / val2; if (result != null && result is LexemValueComplex && ((LexemValueComplex)result).Im == 0) result = ((LexemValueComplex)result).Re; #endregion } else if (arg1 is LexemValueDate && arg2 is LexemValueSpan) { #region date and span LexemValueDate date = (LexemValueDate)arg1; LexemValueSpan span = (LexemValueSpan)arg2; if (this.Text == "+") result = date.Value + span.Value; else if (this.Text == "-") result = date.Value - span.Value; #endregion } else if (arg1 is LexemValueSpan && arg2 is LexemValueDate) { #region span and date LexemValueDate date = (LexemValueDate)arg2; LexemValueSpan span = (LexemValueSpan)arg1; if (this.Text == "+") result = date.Value + span.Value; #endregion } else if (arg1 is LexemValueDate && arg2 is LexemValueDate) { if (this.Text == "-") result = ((LexemValueDate)arg1) - ((LexemValueDate)arg2); } else if (arg1 is LexemValueText && arg2 is LexemValueText) { if (this.Text == "+") result = ((LexemValueText)arg1) + ((LexemValueText)arg2); } #endregion } else if (this.OperatorType == OperationType.Logical) { #region Logical Operations LexemValue arg1 = LexemValue.GetValue(argument1); LexemValue arg2 = LexemValue.GetValue(argument2); if (arg1 == null || arg2 == null) return null; if (arg1 is LexemValueBool && arg2 is LexemValueBool) { if (this.Text == "||") result = ((LexemValueBool)arg1) || ((LexemValueBool)arg2); else if (this.Text == "&&") result = ((LexemValueBool)arg1) && ((LexemValueBool)arg2); else throw new InvalidOperationException($"Invalid operation {this.Text} between booleans"); } #endregion } else if (this.OperatorType == OperationType.Comparison) { #region Comparison Operations LexemValue arg1 = LexemValue.GetValue(argument1); LexemValue arg2 = LexemValue.GetValue(argument2); if (arg1 == null || arg2 == null) return null; if (arg1 is LexemValueNumber && arg2 is LexemValueNumber) { #region number LexemValueNumber number1 = (LexemValueNumber)arg1; LexemValueNumber number2 = (LexemValueNumber)arg2; if (this.Text == ">") result = number1 > number2; else if (this.Text == ">=") result = number1 >= number2; else if (this.Text == "<") result = number1 < number2; else if (this.Text == "<=") result = number1 <= number2; else if (this.Text == "==") result = number1 == number2; else if (this.Text == "!=") result = number1 != number2; #endregion } else if (arg1 is LexemValueComplex && arg2 is LexemValueComplex) { #region complex LexemValueComplex complex1 = (LexemValueComplex)arg1; LexemValueComplex complex2 = (LexemValueComplex)arg2; if (this.Text == ">") result = complex1 > complex2; else if (this.Text == ">=") result = complex1 >= complex2; else if (this.Text == "<") result = complex1 < complex2; else if (this.Text == "<=") result = complex1 <= complex2; else if (this.Text == "==") result = complex1 == complex2; else if (this.Text == "!=") result = complex1 != complex2; #endregion } else if (arg1 is LexemValueText && arg2 is LexemValueText) { #region text LexemValueText text_1 = (LexemValueText)arg1; LexemValueText text_2 = (LexemValueText)arg2; if (this.Text == ">") result = text_1 > text_2; else if (this.Text == ">=") result = text_1 >= text_2; else if (this.Text == "<") result = text_1 < text_2; else if (this.Text == "<=") result = text_1 <= text_2; else if (this.Text == "==") result = text_1 == text_2; else if (this.Text == "!=") result = text_1 != text_2; #endregion } else if (arg1 is LexemValueDate && arg2 is LexemValueDate) { #region date LexemValueDate date1 = (LexemValueDate)arg1; LexemValueDate date2 = (LexemValueDate)arg2; if (this.Text == ">") result = date1 > date2; else if (this.Text == ">=") result = date1 >= date2; else if (this.Text == "<") result = date1 < date2; else if (this.Text == "<=") result = date1 <= date2; else if (this.Text == "==") result = date1 == date2; else if (this.Text == "!=") result = date1 != date2; #endregion } else if (arg1 is LexemValueSpan && arg2 is LexemValueSpan) { #region span LexemValueSpan span1 = (LexemValueSpan)arg1; LexemValueSpan span2 = (LexemValueSpan)arg2; if (this.Text == ">") result = span1 > span2; else if (this.Text == ">=") result = span1 >= span2; else if (this.Text == "<") result = span1 < span2; else if (this.Text == "<=") result = span1 <= span2; else if (this.Text == "==") result = span1 == span2; else if (this.Text == "!=") result = span1 != span2; #endregion } #endregion } else if (this.OperatorType == OperationType.Code) { #region Code Operations if (this.Text != "->" && this.Text != ".") return null; if (argument1 is LexemVariable) return ((LexemVariable)argument1).Execute(argument2, environment); else if (argument1 is LexemValue) return ((LexemValue)argument1).Execute(argument2, environment); else return null; #endregion } return result; }
public Token(string value, Lexem lexem) { Lexem = lexem; Value = value; }
static private List <IExpression> ExtractSingleCondidtions(List <IExpression> conditionExpression, List <FuzzyVariable> input, Dictionary <string, Lexem> lexems) { List <IExpression> copyExpressions = conditionExpression.GetRange(0, conditionExpression.Count); List <IExpression> expressions = new List <IExpression>(); while (copyExpressions.Count > 0) { if (copyExpressions[0] is VarLexem <FuzzyVariable> ) { // // Разбор переменной // VarLexem <FuzzyVariable> varLexem = (VarLexem <FuzzyVariable>)copyExpressions[0]; if (copyExpressions.Count < 3) { throw new Exception(string.Format("Состояние начинается с '{0}' не корректно.", varLexem.Text)); } if (varLexem.Input == false) { throw new Exception("Переменная в состоянии должна быть входной переменной."); } // // Разбор "is" лексемы // Lexem exprIs = (Lexem)copyExpressions[1]; if (exprIs != lexems["is"]) { throw new Exception(string.Format("'is' ключевое слово должно идти после {0} идентификатора.", varLexem.Text)); } // // Разбор 'not' лексемы (если существует) // int cur = 2; bool not = false; if (copyExpressions[cur] == lexems["not"]) { not = true; cur++; if (copyExpressions.Count <= cur) { throw new Exception("Ошибка около 'not' в состоянии части правила."); } } //"slightly" - немного //"somewhat" - в некотором роде //"very" - очень //"extremely" - чрезвычайно // // Разбор hedge модификатора (если существует) // HedgeType hedge = HedgeType.None; if (copyExpressions[cur] == lexems["slightly"]) { hedge = HedgeType.Slightly; } else if (copyExpressions[cur] == lexems["somewhat"]) { hedge = HedgeType.Somewhat; } else if (copyExpressions[cur] == lexems["very"]) { hedge = HedgeType.Very; } else if (copyExpressions[cur] == lexems["extremely"]) { hedge = HedgeType.Extremely; } if (hedge != HedgeType.None) { cur++; if (copyExpressions.Count <= cur) { throw new Exception(string.Format("Ошибка около '{0}' в состоянии части правила.", hedge.ToString().ToLower())); } } // // Разбор терма // Lexem exprTerm = (Lexem)copyExpressions[cur]; if (!(exprTerm is IAltLexem)) { throw new Exception(string.Format("Неверный идентификатор '{0}' в стостоянии части правила.", exprTerm.Text)); } IAltLexem altLexem = (IAltLexem)exprTerm; TermLexem <FuzzyTerm> termLexem = null; do { if (!(altLexem is TermLexem <FuzzyTerm>)) { continue; } termLexem = (TermLexem <FuzzyTerm>)altLexem; if (!varLexem.Var.Values.Contains(termLexem.Term)) { termLexem = null; continue; } }while ((altLexem = altLexem.Alternative) != null && termLexem == null); if (termLexem == null) { throw new Exception(string.Format("Неверный идентификатор '{0}' в стостоянии части правила.", exprTerm.Text)); } // // Добавление нового выражения состояния // FuzzyCondition condition = new FuzzyCondition(varLexem.Var, termLexem.Term, not, hedge); expressions.Add(new ConditionExpression(copyExpressions.GetRange(0, cur + 1), condition)); copyExpressions.RemoveRange(0, cur + 1); } else { IExpression expr = copyExpressions[0]; if (expr == lexems["and"] || expr == lexems["or"] || expr == lexems["("] || expr == lexems[")"]) { expressions.Add(expr); copyExpressions.RemoveAt(0); } else { Lexem unknownLexem = (Lexem)expr; throw new Exception(string.Format("Лексема '{0}' найдена в ошибочном месте в состоянии части правила.", unknownLexem.Text)); } } } return(expressions); }
private List<String> Calc(List<Functions> fList, List<List<Lexem>> lOps) { List<String> res = new List<String>(); if (fList.Count==0) { foreach (List<Lexem> op in lOps) { String resOp = getResult(op); res.Add(resOp); } } else { foreach (List<Lexem> op in lOps) { for (int i=0;i<op.Count;i++) { if (op[i].Type == LexemType.Identifier) { String fName = op[i].Value.Remove(op[i].Value.IndexOf("{")); String fNumStr = op[i].Value.Remove(0, op[i].Value.IndexOf("{") + 1); fNumStr = fNumStr.Remove(fNumStr.IndexOf("}")); Int32 fNum = Int32.Parse(fNumStr); Functions func = fList[fNum]; List<String> funcRes = Calc(func.FunctionList, func.operands); List<Double> rList = new List<double>(); for (int k = 0; k < funcRes.Count; k++) { rList.Add(Double.Parse(funcRes[k])); } switch (fName) { case "If": { op[i] = new Lexem() { Type = LexemType.Number, Value = (rList[0]==1?rList[1]:rList[2]).ToString() }; break; } case "Log": { op[i] = new Lexem() { Type = LexemType.Number, Value = (rList.Count==1?(Math.Log(rList[0])):(Math.Log(rList[0], rList[1]))).ToString() }; break; } case "Sqr": { op[i] = new Lexem() { Type = LexemType.Number, Value = (rList[0] * rList[0]).ToString() }; break; } case "Sin": { op[i] = new Lexem() { Type = LexemType.Number, Value = (Math.Sin(rList[0])).ToString() }; break; } case "Cos": { op[i] = new Lexem() { Type = LexemType.Number, Value = (Math.Cos(rList[0])).ToString() }; break; } case "Tan": { op[i] = new Lexem() { Type = LexemType.Number, Value = (Math.Tan(rList[0])).ToString() }; break; } case "Asin": { op[i] = new Lexem() { Type = LexemType.Number, Value = (Math.Asin(rList[0])).ToString() }; break; } case "Acos": { op[i] = new Lexem() { Type = LexemType.Number, Value = (Math.Acos(rList[0])).ToString() }; break; } case "Atan": { op[i] = new Lexem() { Type = LexemType.Number, Value = (Math.Atan(rList[0])).ToString() }; break; } case "Pow": { op[i] = new Lexem() { Type = LexemType.Number, Value = (Math.Pow(rList[0], rList[1])).ToString() }; break; } case "Exp": { op[i] = new Lexem() { Type = LexemType.Number, Value = (Math.Exp(rList[0])).ToString() }; break; } case "Sqrt": { op[i] = new Lexem() { Type = LexemType.Number, Value = (Math.Sqrt(rList[0])).ToString() }; break; } case "Min": { Double Min = Double.MaxValue; for (int k = 0; k < rList.Count;k++) { if (rList[k] < Min) { Min = rList[k]; } } op[i] = new Lexem() { Type = LexemType.Number, Value = Min.ToString() }; break; } case "Max": { Double Max = Double.MinValue; for (int k = 0; k < rList.Count; k++) { if (rList[k] > Max) { Max = rList[k]; } } op[i] = new Lexem() { Type = LexemType.Number, Value = Max.ToString() }; break; } } } } String resOp = getResult(op); res.Add(resOp); } } return res; }
public SintaxException(string message, Lexem lexem) :base(message) { CurrentLexem = lexem; }
private String getResult(List<Lexem> _lexems) { Stack<Lexem> stack = new Stack<Lexem>(); Lexem[] postfix = ConvertToPostfixNotation(_lexems); Queue<Lexem> queue = new Queue<Lexem>(postfix); Lexem str = queue.Dequeue(); while (queue.Count >= 0) { if (operators.Contains(str.Type)) { Lexem result = new Lexem(); result.Type = LexemType.Number; try { switch (str.Type) { case LexemType.UnarMinus: { Double a = Convert.ToDouble(stack.Pop().Value); result.Value = (-a).ToString(); break; } case LexemType.Plus: { Double b = Convert.ToDouble(stack.Pop().Value); Double a = Convert.ToDouble(stack.Pop().Value); result.Value = (a + b).ToString(); break; } case LexemType.Minus: { Double b = Convert.ToDouble(stack.Pop().Value); Double a = Convert.ToDouble(stack.Pop().Value); result.Value = (a - b).ToString(); break; } case LexemType.Multiply: { Double b = Convert.ToDouble(stack.Pop().Value); Double a = Convert.ToDouble(stack.Pop().Value); result.Value = (a * b).ToString(); break; } case LexemType.Divide: { Double b = Convert.ToDouble(stack.Pop().Value); Double a = Convert.ToDouble(stack.Pop().Value); result.Value = (a / b).ToString(); break; } case LexemType.Equals: { Double b = Convert.ToDouble(stack.Pop().Value); Double a = Convert.ToDouble(stack.Pop().Value); Boolean r = (a == b); result.Value = (r ? 1 : 0).ToString(); break; } case LexemType.NotEquals: { Double b = Convert.ToDouble(stack.Pop().Value); Double a = Convert.ToDouble(stack.Pop().Value); Boolean r = (a != b); result.Value = (r ? 1 : 0).ToString(); break; } case LexemType.Greater: { Double b = Convert.ToDouble(stack.Pop().Value); Double a = Convert.ToDouble(stack.Pop().Value); Boolean r = (a > b); result.Value = (r ? 1 : 0).ToString(); break; } case LexemType.GreaterEquals: { Double b = Convert.ToDouble(stack.Pop().Value); Double a = Convert.ToDouble(stack.Pop().Value); Boolean r = (a >= b); result.Value = (r ? 1 : 0).ToString(); break; } case LexemType.Lower: { Double b = Convert.ToDouble(stack.Pop().Value); Double a = Convert.ToDouble(stack.Pop().Value); Boolean r = (a < b); result.Value = (r ? 1 : 0).ToString(); break; } case LexemType.LowerEquals: { Double b = Convert.ToDouble(stack.Pop().Value); Double a = Convert.ToDouble(stack.Pop().Value); Boolean r = (a <= b); result.Value = (r ? 1 : 0).ToString(); break; } case LexemType.Or: { Boolean b = Convert.ToBoolean(Convert.ToDouble(stack.Pop().Value) > 0 ? 1 : 0); Boolean a = Convert.ToBoolean(Convert.ToDouble(stack.Pop().Value) > 0 ? 1 : 0); Boolean r = (a || b); result.Value = (r ? 1 : 0).ToString(); break; } case LexemType.And: { Boolean b = Convert.ToBoolean(Convert.ToDouble(stack.Pop().Value) > 0 ? 1 : 0); Boolean a = Convert.ToBoolean(Convert.ToDouble(stack.Pop().Value) > 0 ? 1 : 0); Boolean r = (a && b); result.Value = (r ? 1 : 0).ToString(); break; } } } catch (Exception ex) { new InvalidOperationException(ex.Message); } stack.Push(result); if (queue.Count > 0) str = queue.Dequeue(); else break; } else { stack.Push(str); if (queue.Count > 0) { str = queue.Dequeue(); } else break; } } String rValue = stack.Pop().Value; return rValue; }
public override LexemVariable Execute(Lexem lexem, ILexemEnvironment environment = null) { if (lexem == null) throw new InvalidOperationException("Can't execute null lexem on Value"); var function = lexem as LexemFunction; if (function != null) { switch (function.Name.ToLower()) { case "tostring": return this.ToString(); } } return base.Execute(lexem, environment); }
private void Analyze(Node tree) { switch (tree.Data) { case "<signal-program>": Analyze(tree.Children.First()); break; case "<program>": Analyze(tree.Children[1]); programIdentifier = currentIdentifier; writer.WriteLine("CODE SEGMENT:"); writer.WriteLine(); Analyze(tree.Children[3]); writer.WriteLine($"{programIdentifier.value}:"); writer.WriteLine("NOP"); writer.WriteLine("CODE ENDS"); writer.WriteLine($"END {programIdentifier.value}"); break; case "<block>": Analyze(tree.Children.First()); Analyze(tree.Children[2]); break; case "<statement-list>": break; case "<declarations>": Analyze(tree.Children.First()); break; case "<procedure-declaration>": Analyze(tree.Children.First()); if (tree.Children != null && tree.Children.Count > 1) { Analyze(tree.Children[1]); } break; case "<procedure>": Analyze(tree.Children[1]); if (!isError) { procedureIdentifier = currentIdentifier; writer.WriteLine($"{procedureIdentifier.value} PROC"); writer.WriteLine("PUSH EBP"); writer.WriteLine("MOV EBP, ESP"); writer.WriteLine($"RET {procedureIdentifier.value}"); writer.WriteLine("ENDP"); } else { isError = false; } Analyze(tree.Children[2]); break; case "<parameters-list>": if (tree.Children != null && tree.Children.Count > 1) { Analyze(tree.Children[1]); localVariables.Clear(); } break; case "<declarations-list>": Analyze(tree.Children.First()); if (tree.Children != null && tree.Children.Count > 1) { Analyze(tree.Children[1]); } break; case "<declaration>": Analyze(tree.Children.First()); Analyze(tree.Children[1]); Analyze(tree.Children[3]); Analyze(tree.Children[4]); type = DataType.None; break; case "<identifiers-list>": Analyze(tree.Children.First()); if (tree.Children != null && tree.Children.Count > 1) { Analyze(tree.Children[1]); } break; case "<attribute-list>": Analyze(tree.Children.First()); if (tree.Children != null && tree.Children.Count > 1) { Analyze(tree.Children[1]); } if (CheckType(DataType.Ext)) { CheckExtVariable(); } if (!(CheckBaseTypes() || CheckType(DataType.Signal))) { Errors.Add($"Error at [{currentIdentifier.line};{currentIdentifier.column + currentIdentifier.value.Length + 1}], should have base or signal type!"); } break; case "<attribute>": var data = tree.Children.First().Data; if (mainDataTypes.Contains(data)) { if (CheckBaseTypes()) { Errors.Add($"Error at [{currentIdentifier.line};{currentIdentifier.column + currentIdentifier.value.Length + 1}], {currentIdentifier.value} already have data type!"); } else { type |= AssignType(data); } } else if (additionalDataTypes.Contains(data)) { var additionalType = AssignType(data); if (CheckType(additionalType)) { Errors.Add($"Error at [{currentIdentifier.line};{currentIdentifier.column + currentIdentifier.value.Length + 1}], {currentIdentifier.value} already have such additional type!"); } else if (additionalType == DataType.Signal) { type |= AssignType(data); } else if (CheckBaseTypes()) { Errors.Add($"Error at [{currentIdentifier.line};{currentIdentifier.column + currentIdentifier.value.Length + 1}], {currentIdentifier.value} have base datatype! Additional datatype should be the first one!"); } else { switch (additionalType) { case DataType.Complex: AnalyzeComplex(); break; case DataType.Ext: AnalyzeExt(); break; case DataType.Signal: AnalyzeSignal(); break; default: break; } } } break; case "<procedure-identifier>": case "<variable-identifier>": isError = true; Analyze(tree.Children.First()); if (currentIdentifier.value == programIdentifier.value) { Errors.Add($"Error ocurred at [{currentIdentifier.line};{currentIdentifier.column}], identifier is already used as program identifier"); Errors.Add($"Program identifier defined at [{programIdentifier.line};{programIdentifier.column}]"); } else if (globalVariables.Contains(currentIdentifier) || localVariables.Contains(currentIdentifier)) { Errors.Add($"This identifier '{currentIdentifier.value}' is already used at [{currentIdentifier.line};{currentIdentifier.column}]"); } else { isError = false; if (tree.Data == "<variable-identifier>") { localVariables.Add(currentIdentifier); } else { globalVariables.Add(currentIdentifier); } } break; case "<identifier>": currentIdentifier = tree.Children.First().Lexem; break; default: break; } }
public void calculate(List <Token> POLIS) { showHeader(); this.POLIS = POLIS; stack.Clear(); Variables.Clear(); POLIS.Add(new Token("$", Lexem.END)); pointer = 0; while (POLIS[pointer].Lexem != Lexem.END) { Lexem currentLexem = POLIS[pointer].Lexem; if (currentLexem == Lexem.VAR) { stack.Push(POLIS[pointer].Value); } else if (currentLexem == Lexem.DIGIT) { stack.Push(Convert.ToDouble(POLIS[pointer].Value)); } else if (currentLexem == Lexem.OP) { double param2 = getStackParam(); double param1 = getStackParam(); stack.Push(executeArithmeticOperation(param1, param2, POLIS[pointer].Value)); } else if (currentLexem == Lexem.ASSIGN_OP) { double param = (double)stack.Pop(); Variables[(string)stack.Pop()] = param; } else if (currentLexem == Lexem.COMP_OP) { double param2 = getStackParam(); double param1 = getStackParam(); stack.Push(executeLogicOperation(param1, param2, POLIS[pointer].Value)); } else if (currentLexem == Lexem.TRANS_LBL) { stack.Push(Convert.ToInt32(POLIS[pointer].Value)); } else if (currentLexem == Lexem.F_TRANS) { int label = (int)stack.Pop(); bool condition = (bool)stack.Pop(); if (!condition) { pointer = label; continue; } } else if (currentLexem == Lexem.UNC_TRANS) { int label = (int)stack.Pop(); pointer = label; continue; } else if (currentLexem == Lexem.FUNC) { pointer++; if (POLIS[pointer].Lexem == Lexem.OUT_KW) { Console.WriteLine(getStackParam()); } else { collectionFunction(); } } else if (currentLexem == Lexem.LIST_KW) { doublyLinkedLists.Add(POLIS[pointer + 1].Value, new DoublyLinkedList <double>()); pointer++; } else if (currentLexem == Lexem.HT_KW) { hashTables.Add(POLIS[pointer + 1].Value, new HashTable()); pointer++; } pointer++; } }
/// <summary> /// Пропарсить содержимое блочной лексемы /// </summary> private static Script parseCommandsBlock(Lexem lexemBlock, Script block) { List <Lexem> lexems = lexemBlock.childs; int lexemsCount = lexems.Count; List <Lexem> oneCommand = new List <Lexem>(); bool isOneCommandReturn = false; for (int i = 0; i < lexemsCount; i++) { Lexem lexem = lexems[i]; if (lexem.kind == LexemKind.SEMICOLON) { ICommand command = parseStatement(oneCommand); oneCommand.Clear(); if (command == null) { throw new Exception("Неизвестная операция в скрипте!"); } if (isOneCommandReturn) { block.addCommand(new CommandReturn(command)); } else { block.addCommand(command); } } else if (lexem.kind == LexemKind.IF) { if (i + 2 < lexemsCount && lexems[i + 1].kind == LexemKind.BRACE && lexems[i + 2].kind == LexemKind.BLOCK) { ICommand condition = parseStatement(lexems[i + 1].childs); ICommand ifBlock = parseCommandsBlock(lexems[i + 2], new Script().setRoot(false)); //теперь проверяем else блоки List <ICommand> elseStatements = new List <ICommand>(); int n = i + 3; while (n < lexemsCount && lexems[n].kind == LexemKind.ELSE) { if (lexems[n + 1].kind == LexemKind.IF) { //else if statement ICommand elseIfCondition = parseStatement(lexems[n + 2].childs); Script commandBlock = parseCommandsBlock(lexems[n + 3], new Script().setRoot(false)); if (commandBlock == null) { throw new Exception("Ошибка в блоке кода конструкции else if!"); } if (elseIfCondition == null) { throw new Exception("Ошибка в блоке условия конструкции else if!"); } CommandElseIf command = new CommandElseIf(elseIfCondition, commandBlock); if (command == null) { throw new Exception("Ошибка в конструкции else if!"); } elseStatements.Add(command); n += 4; } else if (lexems[n + 1].kind == LexemKind.BLOCK) { //else statement Script elseBlock = parseCommandsBlock(lexems[n + 1], new Script().setRoot(false)); if (elseBlock == null) { throw new Exception("Ошибка в блоке кода конструкции else!"); } elseStatements.Add(new CommandElse(elseBlock)); n += 2; } else { throw new Exception("Неверная конструкция else! Необходимо: else <if (условие)> {блок кода}"); } } i = n - 1; block.addCommand(new CommandIf(condition, ifBlock, elseStatements)); } else { throw new Exception("Неверная конструкция if! Необходимо: if (условие) {блок кода}"); } oneCommand.Clear(); } else if (lexem.kind == LexemKind.FOR) { if (i + 2 < lexemsCount && lexems[i + 1].kind == LexemKind.BRACE && lexems[i + 2].kind == LexemKind.BLOCK) { //заголовок цикла (начало; условие; шаг) Script head = parseCommandsBlock(lexems[i + 1], new Script().setRoot(false)); List <ICommand> headCommands = head.getCommands(); if (headCommands.Count != 3) { throw new Exception("Неверная конструкция заголовка for! Необходимо: for (начало; условие; шаг)"); } ICommand begin = headCommands[0] == null ? new CommandEmpty() : headCommands[0]; ICommand condition = headCommands[1] == null ? new CommandEmpty() : headCommands[1]; ICommand step = headCommands[2] == null ? new CommandEmpty() : headCommands[2]; ICommand command = parseCommandsBlock(lexems[i + 2], new Script().setRoot(false)); block.addCommand(new CommandFor(begin, condition, step, command)); i += 3 - 1; } else { throw new Exception("Неверная конструкция for! Необходимо: for (начало; условие; шаг) {блок кода}"); } oneCommand.Clear(); } else if (lexem.kind == LexemKind.WHILE) { if (i + 2 < lexemsCount && lexems[i + 1].kind == LexemKind.BRACE && lexems[i + 2].kind == LexemKind.BLOCK) { ICommand condition = parseStatement(lexems[i + 1].childs); ICommand command = parseCommandsBlock(lexems[i + 2], new Script().setRoot(false)); block.addCommand(new CommandWhile(condition, command)); i += 3 - 1; } else { throw new Exception("Неверная конструкция while! Необходимо: while (условие) {блок кода}"); } oneCommand.Clear(); } else if (lexem.kind == LexemKind.FUNCTION) { if (i + 3 < lexemsCount && lexems[i + 1].kind == LexemKind.IDENTIFIER && lexems[i + 2].kind == LexemKind.BRACE && lexems[i + 3].kind == LexemKind.BLOCK) { string fname = lexems[i + 1].value; List <string> fargs = parseLocalFunctionArgs(lexems[i + 2].childs); Script fcode = parseCommandsBlock(lexems[i + 3], new Script().setRoot(false)); fcode.setRoot(false); block.addLocalFunction(new LocalFunction() { name = fname, code = fcode, args = fargs }); i += 4 - 1; } else { throw new Exception("Неверная конструкция function! Необходимо: function (arg0, arg1, arg2, ...) {блок кода}"); } oneCommand.Clear(); } else if (lexem.kind == LexemKind.RETURN) { isOneCommandReturn = true; oneCommand.Clear(); } else { oneCommand.Add(lexem); } } if (oneCommand.Count > 0) { ICommand command = parseStatement(oneCommand); if (command == null) { throw new Exception("Неизвестная операция в скрипте!"); } oneCommand.Clear(); block.addCommand(command); } return(block); }
static private List <IExpression> ExtractSingleCondidtions(List <IExpression> conditionExpression, List <FuzzyVariable> input, Dictionary <string, Lexem> lexems) { List <IExpression> copyExpressions = conditionExpression.GetRange(0, conditionExpression.Count); List <IExpression> expressions = new List <IExpression>(); while (copyExpressions.Count > 0) { if (copyExpressions[0] is VarLexem <FuzzyVariable> ) { // // Parse variable // VarLexem <FuzzyVariable> varLexem = (VarLexem <FuzzyVariable>)copyExpressions[0]; if (copyExpressions.Count < 3) { throw new Exception(string.Format("Condition strated with '{0}' is incorrect.", varLexem.Text)); } if (varLexem.Input == false) { throw new Exception("The variable in condition part must be an input variable."); } // // Parse 'is' lexem // Lexem exprIs = (Lexem)copyExpressions[1]; if (exprIs != lexems["is"]) { throw new Exception(string.Format("'is' keyword must go after {0} identifier.", varLexem.Text)); } // // Parse 'not' lexem (if exists) // int cur = 2; bool not = false; if (copyExpressions[cur] == lexems["not"]) { not = true; cur++; if (copyExpressions.Count <= cur) { throw new Exception("Error at 'not' in condition part of the rule."); } } //"slightly" //"somewhat" //"very" //"extremely" // // Parse hedge modifier (if exists) // HedgeType hedge = HedgeType.None; if (copyExpressions[cur] == lexems["slightly"]) { hedge = HedgeType.Slightly; } else if (copyExpressions[cur] == lexems["somewhat"]) { hedge = HedgeType.Somewhat; } else if (copyExpressions[cur] == lexems["very"]) { hedge = HedgeType.Very; } else if (copyExpressions[cur] == lexems["extremely"]) { hedge = HedgeType.Extremely; } if (hedge != HedgeType.None) { cur++; if (copyExpressions.Count <= cur) { throw new Exception(string.Format("Error at '{0}' in condition part of the rule.", hedge.ToString().ToLower())); } } // // Parse term // Lexem exprTerm = (Lexem)copyExpressions[cur]; if (!(exprTerm is IAltLexem)) { throw new Exception(string.Format("Wrong identifier '{0}' in conditional part of the rule.", exprTerm.Text)); } IAltLexem altLexem = (IAltLexem)exprTerm; TermLexem <FuzzyTerm> termLexem = null; do { if (!(altLexem is TermLexem <FuzzyTerm>)) { continue; } termLexem = (TermLexem <FuzzyTerm>)altLexem; if (!varLexem.Var.Values.Contains(termLexem.Term)) { termLexem = null; continue; } }while ((altLexem = altLexem.Alternative) != null && termLexem == null); if (termLexem == null) { throw new Exception(string.Format("Wrong identifier '{0}' in conditional part of the rule.", exprTerm.Text)); } // // Add new condition expression // FuzzyCondition condition = new FuzzyCondition(varLexem.Var, termLexem.Term, not, hedge); expressions.Add(new ConditionExpression(copyExpressions.GetRange(0, cur + 1), condition)); copyExpressions.RemoveRange(0, cur + 1); } else { IExpression expr = copyExpressions[0]; if (expr == lexems["and"] || expr == lexems["or"] || expr == lexems["("] || expr == lexems[")"]) { expressions.Add(expr); copyExpressions.RemoveAt(0); } else { Lexem unknownLexem = (Lexem)expr; throw new Exception(string.Format("Lexem '{0}' found at the wrong place in condition part of the rule.", unknownLexem.Text)); } } } return(expressions); }
protected bool Equals(Lexem other) { return(Kind == other.Kind); }
protected abstract void OnElement(Lexem lexem);
public Lexem(Lexem Parent, ref int lineNumber, string Line, int currentIndent, string[] lines) { this.lineNumber = lineNumber; this.Line = Line; this.Parent = Parent; }
public virtual LexemVariable Execute(LexemValue argument, Lexem lexem) { if (this.OnLexemExecution != null) return this.OnLexemExecution(argument, lexem); return null; }
public override LexemVariable Execute(Lexem lexem, ILexemEnvironment environment = null) { if (lexem == null) throw new InvalidOperationException("Can't execute null lexem on Value"); if (lexem is LexemVariable) { switch (((LexemVariable)lexem).Name.Trim().ToLower()) { case "length": return this.Value.Length; } } else if (lexem is LexemFunction) { LexemFunction function = lexem as LexemFunction; Func<int, string> getFuncString = i => (function.Arguments[i].Calculate(environment).Value as LexemValueText).Value; Func<int, double> getFuncNumber = i => (function.Arguments[i].Calculate(environment).Value as LexemValueNumber).Value; switch (function.Name.Trim().ToLower()) { case "tostring": return this.Value; case "tonumber": return LexemValueNumber.ParseNumber(this.Value, true); case "todatetime": case "todate": { return LexemValueDate.ParseDateTime(this.Value); } case "trim": return this.Value.Trim(); case "tolower": return this.Value.ToLower(); case "toupper": return this.Value.ToUpper(); case "startswith": return this.Value.StartsWith(getFuncString(0)); case "endswith": return this.Value.EndsWith(getFuncString(0)); case "contains": return this.Value.Contains(getFuncString(0)); case "like": return this.Value.Like(getFuncString(0)); case "indexof": return this.Value.IndexOf(getFuncString(0)); case "replace": return this.Value.Replace(getFuncString(0), getFuncString(1)); case "substring": { if (function.Arguments.Count >= 2) return this.Value.Substring((int)getFuncNumber(0), (int)getFuncNumber(1)); else return this.Value.Substring((int)getFuncNumber(0)); } } } return base.Execute(lexem, environment); }