public void ProcessExpressionValue(ExpressionValue exprValue) { if (ProcessExpressionValueObject != null) ProcessExpressionValueObject(exprValue); foreach (var obj in exprValue.Children) obj.AcceptVisitor(this); }
/// <summary> /// Splits the expression. /// </summary> /// <param name="cell">The cell.</param> /// <param name="numbers">The numbers.</param> /// <param name="operations">The operations.</param> /// <exception cref="System.ArgumentNullException"></exception> public static void SplitExpression(ICell cell, out int[] numbers, out char[] operations) { if (cell == null) throw new ArgumentNullException(nameof(cell)); var nums = new List<int>(); var opers = new List<char>(); int num = 0; var expressionValue = new ExpressionValue(cell.Value.ToCharArray()); for (int i = 0; i < expressionValue.Chars.Length; i++) { expressionValue.Index = i; if (CellConst.OperationSymbols.Contains(expressionValue.Chars[i])) { Operation(nums, opers, ref num, expressionValue); } else { Number(expressionValue); } } num = Convert.ToInt32(expressionValue.Value); nums.Add(num); numbers = nums.ToArray(); operations = opers.ToArray(); }
private static void Number(ExpressionValue expressionValue) { if (expressionValue == null) throw new ArgumentNullException(nameof(expressionValue)); if (CellConst.AllNumbers.Contains(expressionValue.Chars[expressionValue.Index])) { expressionValue.Value += expressionValue.Chars[expressionValue.Index]; expressionValue.IsNextShouldBeNumber = false; } }
public static Discriminator SingleConditionDiscriminator(IColumn column, Operator op, ExpressionValue val) { Discriminator dis = new DiscriminatorImpl(); dis.RootGrouping = new AndGrouping(); dis.RootGrouping.AddCondition(new ConditionImpl() { Column = column, Operator = op, ExpressionValue = val }); return dis; }
public PetriNet GetProcess(Valuation global) { Expression[] newArgs = new Expression[Args.Length]; //instance String has all information about the argument value, which is used for storing the process of definition into the DefinitionInstanceDatabase //idString store only local information about the argument (exclude the global variables) string instanceString = Name + "("; string idString = Name + "("; for (int i = 0; i < Args.Length; i++) { Expression exp = Args[i]; idString += exp.ExpressionID; if (!exp.HasVar) { newArgs[i] = exp; instanceString += exp.ExpressionID; } else { ExpressionValue v = EvaluatorDenotational.Evaluate(exp, global); newArgs[i] = v; instanceString += v.ExpressionID; } if (i < Args.Length - 1) { instanceString += ","; idString += ","; } } idString += ")"; instanceString += ")"; PetriNet ProcExpr = DataStore.DataManager.DefinitionInstanceDatabase.GetContainsKey(instanceString); if (ProcExpr != null) { return(ProcExpr); } Dictionary <string, Expression> values = new Dictionary <string, Expression>(Args.Length); for (int i = 0; i < newArgs.Length; i++) { values.Add(Def.LocalVariables[i], newArgs[i]); } ProcessID = DataStore.DataManager.InitializeProcessID(idString); //lock the data manager to prevent the multi-thread update the last Process ID at the same time. lock (DataStore.DataManager) { ProcExpr = Def.Process.ClearConstant(values); //Instantiate DataStore.DataManager.SetLastProcessID(ProcessID); } ProcExpr.ProcessID = ProcessID; DataStore.DataManager.DefinitionInstanceDatabase.Add(instanceString, ProcExpr); return(ProcExpr); }
public override object VisitLiteral(Z80AsmParser.LiteralContext context) { if (context == null) { return(null); } switch (context) { case Z80AsmParser.CurAddrLiteralContext ctx: AddSemiVar(ctx); return(new CurrentAddressNode(ctx)); case Z80AsmParser.CurCounterLiteralContext ctx: AddSemiVar(ctx); return(new CurrentLoopCounterNode(ctx)); case Z80AsmParser.BoolLiteralContext ctx: AddNumber(ctx); var boolValue = new ExpressionValue(ctx.BOOLLIT().GetText().ToLower().Contains("t")); return(new LiteralNode(ctx, boolValue)); case Z80AsmParser.RealLiteralContext ctx: AddNumber(ctx); return(double.TryParse(ctx.REALNUM().GetText(), out var realValue) ? new LiteralNode(ctx, realValue) : new LiteralNode(ctx, ExpressionValue.Error)); case Z80AsmParser.StringLiteralContext ctx: AddString(ctx); var stringValue = ctx.STRING().NormalizeString(); return(new LiteralNode(ctx, stringValue)); } var token = context.NormalizeToken(); ushort value; // --- Hexadecimal literals if (token.StartsWith("#") && token.Length > 1) { AddNumber(context); value = ushort.Parse(token.Substring(1), NumberStyles.HexNumber); } else if (token.StartsWith("0X") && token.Length > 2) { AddNumber(context); value = ushort.Parse(token.Substring(2), NumberStyles.HexNumber); } else if (token.StartsWith("$") && token.Length > 1) { AddNumber(context); value = ushort.Parse(token.Substring(1), NumberStyles.HexNumber); } else if (token.EndsWith("H", StringComparison.OrdinalIgnoreCase) && token.Length > 1) { AddNumber(context); value = (ushort)int.Parse(token.Substring(0, token.Length - 1), NumberStyles.HexNumber); } // --- Binary literals else if (token.StartsWith("%") && token.Length > 1) { AddNumber(context); value = (ushort)Convert.ToInt32(token.Substring(1).Replace("_", ""), 2); } else if (token.StartsWith("0B") && token.Length > 2) { AddNumber(context); value = (ushort)Convert.ToInt32(token.Substring(2).Replace("_", ""), 2); } else if ((token.EndsWith("b") || token.EndsWith("B")) && token.Length > 1) { AddNumber(context); value = (ushort)Convert.ToInt32(token.Substring(0, token.Length - 1).Replace("_", ""), 2); } // --- Octal literals else if ((token.EndsWith("q") || token.EndsWith("Q") || token.EndsWith("o") || token.EndsWith("O")) && token.Length > 1) { AddNumber(context); value = (ushort)Convert.ToInt32(token.Substring(0, token.Length - 1), 8); } // --- Character literals else if ((token.StartsWith("\"") || token.StartsWith("'")) && token.Length > 2) { AddString(context); var charExpr = context.GetText(); var bytes = Z80Assembler.SpectrumStringToBytes(charExpr.Substring(1, charExpr.Length - 2)); value = bytes.Count == 0 ? (ushort)0x00 : bytes[0]; } // --- Decimal literals else { AddNumber(context); value = (ushort)int.Parse(context.NormalizeToken()); } return(new LiteralNode(context, value)); }
/// <summary> /// Sets the data member with the specified id and given value /// </summary> /// <param name="id">Data member ID</param> /// <param name="value">Data memer value</param> public void SetDataMember(string id, ExpressionValue value) { _dataEntries[id] = value; }
/// <summary> /// Compute the output from the input MLData. The individual values of the /// input will be mapped to the variables defined in the context. The order /// is the same between the input and the defined variables. The input will /// be mapped to the appropriate types. Enums will use their ordinal number. /// The result will be a single number MLData. /// </summary> /// <param name="input">The input to the program.</param> /// <returns>A single numer MLData.</returns> public IMLData Compute(IMLData input) { if (input.Count != InputCount) { throw new EACompileError("Invalid input count."); } for (int i = 0; i < input.Count; i++) { _variables.SetVariable(i, input[i]); } ExpressionValue v = RootNode.Evaluate(); VariableMapping resultMapping = ResultType; var result = new BasicMLData(1); bool success = false; switch (resultMapping.VariableType) { case EPLValueType.FloatingType: if (v.IsNumeric) { result.Data[0] = v.ToFloatValue(); success = true; } break; case EPLValueType.StringType: result.Data[0] = v.ToFloatValue(); success = true; break; case EPLValueType.BooleanType: if (v.IsBoolean) { result.Data[0] = v.ToBooleanValue() ? 1.0 : 0.0; success = true; } break; case EPLValueType.IntType: if (v.IsNumeric) { result[0] = v.ToIntValue(); success = true; } break; case EPLValueType.EnumType: if (v.IsEnum) { result.Data[0] = v.ToIntValue(); success = true; } break; } if (!success) { throw new EARuntimeError("EncogProgram produced " + v.ExprType.ToString() + " but " + resultMapping.VariableType.ToString() + " was expected."); } return(result); }
private static ExpressionValue EvalPrimAppl(PrimitiveApplication application, ExpressionValue x1, Expression x2Exp, Valuation env) { try { ExpressionValue x2; switch (application.Operator) { case "<": x2 = Evaluate(x2Exp, env); return(new BoolConstant(((IntConstant)x1).Value < ((IntConstant)x2).Value)); case "<=": x2 = Evaluate(x2Exp, env); return(new BoolConstant(((IntConstant)x1).Value <= ((IntConstant)x2).Value)); case ">": x2 = Evaluate(x2Exp, env); return(new BoolConstant(((IntConstant)x1).Value > ((IntConstant)x2).Value)); case ">=": x2 = Evaluate(x2Exp, env); return(new BoolConstant(((IntConstant)x1).Value >= ((IntConstant)x2).Value)); case "==": x2 = Evaluate(x2Exp, env); return(new BoolConstant(x1.ExpressionID == x2.ExpressionID)); case "!=": x2 = Evaluate(x2Exp, env); //return new BoolConstant(((IntConstant)x1).Value != ((IntConstant)x2).Value); return(new BoolConstant(x1.ExpressionID != x2.ExpressionID)); case "&&": if (((BoolConstant)x1).Value) { x2 = Evaluate(x2Exp, env); return(new BoolConstant(((BoolConstant)x2).Value)); } else { return(new BoolConstant(false)); } case "||": if (!((BoolConstant)x1).Value) { x2 = Evaluate(x2Exp, env); return(new BoolConstant(((BoolConstant)x2).Value)); } else { return(new BoolConstant(true)); } case "xor": x2 = Evaluate(x2Exp, env); return(new BoolConstant(((BoolConstant)x1).Value ^ ((BoolConstant)x2).Value)); case "!": return(new BoolConstant(!((BoolConstant)x1).Value)); case "+": x2 = Evaluate(x2Exp, env); return(new IntConstant(((IntConstant)x1).Value + ((IntConstant)x2).Value)); case "-": x2 = Evaluate(x2Exp, env); return(new IntConstant(((IntConstant)x1).Value - ((IntConstant)x2).Value)); case "*": x2 = Evaluate(x2Exp, env); return(new IntConstant(((IntConstant)x1).Value * ((IntConstant)x2).Value)); case "/": x2 = Evaluate(x2Exp, env); if (((IntConstant)x2).Value == 0) { throw new ArithmeticException("Divide by Zero on " + application.ToString()); } else { return(new IntConstant(((IntConstant)x1).Value / ((IntConstant)x2).Value)); } case "mod": x2 = Evaluate(x2Exp, env); if (((IntConstant)x2).Value == 0) { throw new ArithmeticException("Modulo by Zero on " + application.ToString()); } else { int int_X1 = ((IntConstant)x1).Value; int int_X2 = ((IntConstant)x2).Value; int tmp = int_X1 % int_X2; return(new IntConstant((tmp >= 0) ? tmp : (tmp + int_X2))); } //case "empty" : // return new Value(((RecordValue) x1).Empty); //case "hasproperty": // return new Value(((RecordValue)x1).HasProperty(((PropertyValue)x2).PropertyName)); case ".": RecordValue record = (RecordValue)x1; x2 = Evaluate(x2Exp, env); int index = ((IntConstant)x2).Value; if (index < 0) { throw new NegativeArraySizeException("Access negative index " + index + " for variable " + application.Argument1.ToString() + " in expression " + application.ToString()); } else if (index >= record.Associations.Length) { throw new IndexOutOfBoundsException("Index " + index + " is out of range for variable " + application.Argument1.ToString() + " in expression " + application.ToString()); } return(record.Associations[index]); case "~": return(new IntConstant(-((IntConstant)x1).Value)); //Bitwise operators used by NESC module case "<<": //bitwise left shift x2 = Evaluate(x2Exp, env); return(new IntConstant(((IntConstant)x1).Value << ((IntConstant)x2).Value)); case ">>": //bitwise right shift x2 = Evaluate(x2Exp, env); return(new IntConstant(((IntConstant)x1).Value >> ((IntConstant)x2).Value)); case "&": //bitwise AND x2 = Evaluate(x2Exp, env); return(new IntConstant(((IntConstant)x1).Value & ((IntConstant)x2).Value)); case "^": //bitwise XOR x2 = Evaluate(x2Exp, env); return(new IntConstant(((IntConstant)x1).Value ^ ((IntConstant)x2).Value)); case "|": //bitwise OR x2 = Evaluate(x2Exp, env); return(new IntConstant(((IntConstant)x1).Value | ((IntConstant)x2).Value)); } } catch (InvalidCastException ex) { throw new RuntimeException("Invalid Cast Exception for " + application.ToString() + ": " + ex.Message.Replace("PAT.Common.Classes.Expressions.ExpressionClass.", "")); } //catch (Exception ex1) //{ // throw new RuntimeException("Invalid Primitive Operation: " + application.ToString() + "!"); //} throw new RuntimeException("Invalid Primitive Operation: " + application.ToString() + "!"); }
public bool Evaluate(Object o) { object propertyValue = GetPropertyValue(o); if (propertyValue == null) { throw new Exception($"Property '{PropertyName}' not found on object '{o.ToString()}'"); } TypeCode expressionValueTypeCode = Type.GetTypeCode(ExpressionValue.GetType()); TypeCode propertyValueTypeCode = Type.GetTypeCode(propertyValue.GetType()); bool typeCodesMatch = expressionValueTypeCode == propertyValueTypeCode; string propertyValueAsString = propertyValue.ToString(); string expressionValueAsString = ExpressionValue.ToString(); if (CaseSensitive) { propertyValueAsString = propertyValueAsString.ToLower(); expressionValueAsString = expressionValueAsString.ToLower(); } switch (ComparisonConditionCodes.GetEnumFromText(ComparisonCondition)) { case ComparisonConditionEnum.EqualTo: return(propertyValueAsString.IsEqualTo(expressionValueAsString, CaseSensitive)); case ComparisonConditionEnum.EqualToAny: return(propertyValueAsString.IsEqualToAnyOfTheFollowing(expressionValueAsString.Split(';'), CaseSensitive)); case ComparisonConditionEnum.NotEqual: return(!propertyValueAsString.IsEqualTo(expressionValueAsString, CaseSensitive)); case ComparisonConditionEnum.NotEqualToAny: return(!propertyValueAsString.IsEqualToAnyOfTheFollowing(expressionValueAsString.Split(';'), CaseSensitive)); case ComparisonConditionEnum.Contains: return(propertyValueAsString.Contains(expressionValueAsString, CaseSensitive)); case ComparisonConditionEnum.ContainsAny: return(propertyValueAsString.ContainsAnyOfTheFollowing(expressionValueAsString.Split(';'), CaseSensitive)); case ComparisonConditionEnum.DoesNotContain: return(!propertyValueAsString.Contains(expressionValueAsString, CaseSensitive)); case ComparisonConditionEnum.DoesNotContainAny: return(propertyValueAsString.ContainsAnyOfTheFollowing(expressionValueAsString.Split(';'), CaseSensitive)); case ComparisonConditionEnum.StartsWith: return(propertyValueAsString.StartsWith(expressionValueAsString, CaseSensitive)); case ComparisonConditionEnum.StartWithAny: return(propertyValueAsString.StartsWithAnyOfTheFollowing(expressionValueAsString.Split(';'), CaseSensitive)); case ComparisonConditionEnum.DoesNotStartWith: return(!propertyValueAsString.StartsWith(expressionValueAsString, CaseSensitive)); case ComparisonConditionEnum.DoesNotStartWithAny: return(!propertyValueAsString.StartsWithAnyOfTheFollowing(expressionValueAsString.Split(';'), CaseSensitive)); case ComparisonConditionEnum.EndsWith: return(propertyValueAsString.EndsWith(expressionValueAsString, CaseSensitive)); case ComparisonConditionEnum.EndsWithAny: return(propertyValueAsString.EndsWithAnyOfTheFollowing(expressionValueAsString.Split(';'), CaseSensitive)); case ComparisonConditionEnum.DoesNotEndWith: return(!propertyValueAsString.EndsWith(expressionValueAsString, CaseSensitive)); case ComparisonConditionEnum.DoesNotEndWithAny: return(!propertyValueAsString.EndsWithAnyOfTheFollowing(expressionValueAsString.Split(';'), CaseSensitive)); case ComparisonConditionEnum.GreaterThan: if (typeCodesMatch) { switch (propertyValueTypeCode) { case TypeCode.Boolean: break; case TypeCode.Byte: break; case TypeCode.Char: break; case TypeCode.DateTime: break; case TypeCode.DBNull: break; case TypeCode.Decimal: break; case TypeCode.Double: break; case TypeCode.Empty: break; case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return(System.Convert.ToInt64(propertyValue) > System.Convert.ToInt64(ExpressionValue)); case TypeCode.Object: break; case TypeCode.SByte: break; case TypeCode.Single: break; case TypeCode.String: break; default: break; } } return(propertyValueAsString.IsGreaterThan(expressionValueAsString)); case ComparisonConditionEnum.GreaterThanOrEqualTo: return(propertyValueAsString.IsGreaterThanOrEqualTo(expressionValueAsString)); case ComparisonConditionEnum.GreaterThanAny: return(propertyValueAsString.IsGreaterThanAnyOfTheFollowing(expressionValueAsString.Split(';'))); case ComparisonConditionEnum.GreaterThanOrEqualToAny: return(propertyValueAsString.IsGreaterThanOrEqualToAnyOfTheFollowing(expressionValueAsString.Split(';'), CaseSensitive)); case ComparisonConditionEnum.LessThan: if (typeCodesMatch) { switch (propertyValueTypeCode) { case TypeCode.Boolean: break; case TypeCode.Byte: break; case TypeCode.Char: break; case TypeCode.DateTime: break; case TypeCode.DBNull: break; case TypeCode.Decimal: break; case TypeCode.Double: break; case TypeCode.Empty: break; case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return(System.Convert.ToInt64(propertyValue) < System.Convert.ToInt64(ExpressionValue)); case TypeCode.Object: break; case TypeCode.SByte: break; case TypeCode.Single: break; case TypeCode.String: break; default: break; } } return(propertyValueAsString.IsLessThan(expressionValueAsString)); //less than any case ComparisonConditionEnum.LessThanAny: return(propertyValueAsString.IsLessThanAnyOfTheFollowing(expressionValueAsString.Split(';'))); //less than or equal to any case ComparisonConditionEnum.LessThanOrEqualToAny: return(propertyValueAsString.IsLessThanOrEqualToAnyOfTheFollowing(expressionValueAsString.Split(';'), CaseSensitive)); default: throw new Exception("Invalid comparison condition code"); } }
/// <summary> Calculates the operations that are allowed for two boolean values. /// </summary> /// <param name="oper"></param> /// <param name="elLeft"></param> /// <param name="elRight"></param> /// <param name="valLeft"></param> /// <param name="valRight"></param> /// <returns></returns> private bool CalculateBoolOperation(tkOperation oper, Element elLeft, Element elRight, ExpressionValue valLeft, ExpressionValue valRight) { switch (oper) { // logical operators case tkOperation.operOR: elLeft.calcVal.bln = valLeft.bln || valRight.bln; break; case tkOperation.operAND: elLeft.calcVal.bln = valLeft.bln && valRight.bln; break; case tkOperation.operXOR: elLeft.calcVal.bln = valLeft.bln ^ valRight.bln; break; case tkOperation.operEqual: elLeft.calcVal.bln = valLeft.bln == valRight.bln; break; case tkOperation.operNotEqual: elLeft.calcVal.bln = valLeft.bln != valRight.bln; break; default: { _errorMessage = SymbologyMessageStrings.Expression_OperationNotSupported; return false; } } elLeft.calcVal.type = tkValueType.vtBoolean; return true; }
/// <summary> /// Adds a symbol to the current scope /// </summary> /// <param name="symbol"></param> /// <param name="line">Assembly line</param> /// <param name="value"></param> public void AddSymbol(string symbol, SourceLineBase line, ExpressionValue value) { Dictionary <string, AssemblySymbolInfo> GetSymbols() => CurrentModule.LocalScopes.Count > 0 ? CurrentModule.LocalScopes.Peek().Symbols : CurrentModule.Symbols; if (symbol == "__SET_ATTR2") { var x = 1; } var currentScopeIsTemporary = CurrentModule.LocalScopes.Count != 0 && CurrentModule.LocalScopes.Peek().IsTemporaryScope; var symbolIsTemporary = symbol.StartsWith("`"); var lookup = GetSymbols(); if (currentScopeIsTemporary) { if (!symbolIsTemporary) { // --- Remove the previous temporary scope var tempScope = CurrentModule.LocalScopes.Peek(); FixupSymbols(tempScope.Fixups, tempScope.Symbols, false); CurrentModule.LocalScopes.Pop(); lookup = GetSymbols(); } } else { // --- Create a new temporary scope CurrentModule.LocalScopes.Push(new SymbolScope { IsTemporaryScope = true }); if (symbolIsTemporary) { // --- Temporary symbol should go into the new temporary scope lookup = GetSymbols(); } } if (CurrentModule.LocalScopes.Count > 0) { // --- We are in a local scope, get the next non-temporary scope var localScopes = CurrentModule.LocalScopes; var scope = localScopes.Peek(); if (scope.IsTemporaryScope) { var tmpScope = localScopes.Pop(); scope = localScopes.Count > 0 ? localScopes.Peek() : null; localScopes.Push(tmpScope); } if (scope?.LocalSymbolBookings.Count > 0) { // --- We already booked local symbols if (!scope.LocalSymbolBookings.Contains(symbol)) { lookup = CurrentModule.Symbols; } } else { if (_options.ProcExplicitLocalsOnly) { lookup = CurrentModule.Symbols; } } } // --- Check for already defined symbols if (lookup.TryGetValue(symbol, out var symbolInfo) && symbolInfo.Type == SymbolType.Label) { ReportError(Errors.Z0040, line, symbol); return; } lookup.Add(symbol, AssemblySymbolInfo.CreateLabel(symbol, value)); }
public override void MoveOneStep(Valuation GlobalEnv, List <Configuration> list) { System.Diagnostics.Debug.Assert(list.Count == 0); Valuation globalEnv = GlobalEnv; ChannelQueue Buffer = null; string channelName = this.ChannelName; if (ChannelIndex != null) { int size = ((IntConstant)EvaluatorDenotational.Evaluate(ChannelIndex, GlobalEnv)).Value; if (size >= Specification.ChannelArrayDatabase[ChannelName]) { throw new PAT.Common.Classes.Expressions.ExpressionClass.IndexOutOfBoundsException("Channel index out of bounds for expression " + this.ToString()); } channelName = channelName + "[" + size + "]"; } if (globalEnv.Channels.TryGetValue(channelName, out Buffer)) { if (Buffer.Count < Buffer.Size) { ExpressionValue[] values = new ExpressionValue[ExpressionList.Length]; string eventName = channelName + "!"; string eventID = channelName + "!"; for (int i = 0; i < ExpressionList.Length; i++) { values[i] = EvaluatorDenotational.Evaluate(ExpressionList[i], globalEnv); if (i == ExpressionList.Length - 1) { eventName += values[i].ToString(); eventID += values[i].ExpressionID; } else { eventName += values[i].ToString() + "."; eventID += values[i].ExpressionID + "."; } } ChannelQueue newBuffer = Buffer.Clone(); newBuffer.Enqueue(values); globalEnv = globalEnv.GetChannelClone(); globalEnv.Channels[channelName] = newBuffer; //program update Valuation newGlobleEnv = globalEnv.GetVariableClone(); EvaluatorDenotational.Evaluate(AssignmentExpr, newGlobleEnv); if (HasLocalVar) { Valuation tempEnv = globalEnv.GetVariableClone(); for (int i = 0; i < tempEnv.Variables._entries.Length; i++) { StringDictionaryEntryWithKey <ExpressionValue> pair = tempEnv.Variables._entries[i]; if (pair != null) { pair.Value = newGlobleEnv.Variables[pair.Key]; } } newGlobleEnv = tempEnv; } //program update if (eventID != eventName) { list.Add(new Configuration(Process, eventID, eventName, newGlobleEnv, false)); } else { list.Add(new Configuration(Process, eventID, null, newGlobleEnv, false)); } } } // return list; }
public Element(ref string floatingFormat) { wasCalculated = false; type = tkElementType.etNone; turnedOff = false; priority = 255; operation = tkOperation.operNone; isField = false; partIndex = -1; val = new ExpressionValue(ref floatingFormat); calcVal = new ExpressionValue(ref floatingFormat); }
public static Boolean EvaluateOnp( DynContext DynLanContext) { Boolean result = false; ExpressionState expState = DynLanContext.CurrentExpressionState; ExpressionContext expContext = DynLanContext.CurrentExpressionContext; // czy zakończyć i zapisać wynik if (expState.TokenIndex >= expState.Expression.OnpTokens.Count) { Object finResult = null; if (expState.ValueStack.Count > 0) { finResult = MyCollectionsExtenders.Pop(expState.ValueStack); } expState.ValueStack.Clear(); expState.Finished = true; expState.Result = InternalTypeConverter.ToOuter(finResult); MyCollectionsExtenders.Pop(expContext.Stack); if (expContext.Current != null) { expContext.Current.PushValue(InternalTypeConverter.ToOuter(finResult)); return(false); } else { expContext.Result = InternalTypeConverter.ToOuter(finResult); expContext.IsFinished = true; return(true); } } ExpressionToken token = expState.Expression.OnpTokens[expState.TokenIndex]; // wykonanie następnej operacji if (token.TokenType == TokenType.VALUE) { ExpressionValue operationValue = StringHelper. GetValueFromText(token.TokenChars); Object value = operationValue == null ? null : InternalTypeConverter.ToInner(operationValue.Value); expState.PushValue(value); } else if (token.TokenType == TokenType.PROPERTY_NAME) { expState.PushValue(token.TokenName); } if (token.TokenType == TokenType.VARIABLE) { result = ObjectValueGetter.EvaluateValue( token.TokenName, DynLanContext); } else if (token.TokenType == TokenType.OPERATOR) { Object valueA = InternalTypeConverter.ToInner( MyCollectionsExtenders.Pop(expState.ValueStack)); Object valueB = InternalTypeConverter.ToInner( MyCollectionsExtenders.Pop(expState.ValueStack)); Object value = null; OperatorType operatorType = OperatorTypeHelper. GetOperationType(token.TokenChars); try { value = OperationHelper.Do( operatorType, valueB, valueA, DynLanContext.ForceDecimals); expState.PushValue(value); } catch { throw; } } expState.TokenIndex++; return(result); }
public static Discriminator SingleConditionDiscriminator(IColumn column, Operator op, ExpressionValue val) { Discriminator dis = new DiscriminatorImpl(); dis.RootGrouping = new AndGrouping(); dis.RootGrouping.AddCondition(new ConditionImpl() { Column = column, Operator = op, ExpressionValue = val }); return(dis); }
private List <double[]> extractNodeInfos(Valuation globalVars, PAT.GenericDiff.graph.Graph configGraph, String[][] nodeInfoTemplates) { List <double[]> nodeInfos = new List <double[]>(nodeInfoTemplates.Length); for (int i = 0; i < nodeInfoTemplates.Length; i++) { nodeInfos.Add(null); } if (globalVars != null) { if (globalVars.Variables != null) { foreach (StringDictionaryEntryWithKey <ExpressionValue> pair in globalVars.Variables._entries) { if (pair != null) { string varName = pair.Key; int i = 0; int j = 0; for (; i < nodeInfoTemplates.Length; i++) { String[] keys = nodeInfoTemplates[i]; for (j = 0; j < keys.Length; j++) { if (keys[j].Equals(varName)) { break; } } if (j < keys.Length) { break; } } if (i < nodeInfoTemplates.Length) { double value = Double.NaN; ExpressionValue varValue = pair.Value; if (varValue is RecordValue) { // todo: xingzc. need to get array length and values in the array RecordValue array = varValue as RecordValue; ExpressionValue[] values = array.Associations; nodeInfos[i] = new double[values.Length]; for (int valueIndex = 0; valueIndex < values.Length; valueIndex++) { if (values[valueIndex] is IntConstant) { nodeInfos[i][valueIndex] = (values[valueIndex] as IntConstant).Value; } else if (values[valueIndex] is BoolConstant) { nodeInfos[i][valueIndex] = (values[valueIndex] as BoolConstant).Value ? 1.0 : 0.0; } else { // todo: xingzc. process other primitive types } } } else if (false) { // todo: xingzc. process other complex data type } else { if (varValue is IntConstant) { value = (varValue as IntConstant).Value; } else if (varValue is BoolConstant) { value = (varValue as BoolConstant).Value ? 1.0 : 0.0; } else { // todo: xingzc. process other primitive types } if (nodeInfos[i] == null) { nodeInfos[i] = new double[nodeInfoTemplates[i].Length]; } if (!Double.IsNaN(value)) { nodeInfos[i][j] = value; } } } } } } } if (!compareConfigGraph) { DictionaryJ <int, int[]> mapLabelindexCount = new DictionaryJ <int, int[]>(); List <String> nodeLabels = configGraph.getNodelabels(); foreach (String nodeLabel in nodeLabels) { int index = CSPConfigurationParser.mapLabelIndex.get(nodeLabel); if (0 != index) // index should not be 0 according to the way to build configGraph { int[] count = mapLabelindexCount.get(index); if (null == count) { count = new int[1]; mapLabelindexCount.put(index, count); } int[] labelIndexCount = CSPConfigurationParser.mapLabelIndexCount.get(index); // shold never be null if (labelIndexCount != null) { count[0] = count[0] + labelIndexCount[0]; } else { count[0]++; } } } int infoIndex = 0; double[] labelindexCount = new double[mapLabelindexCount.Count * 2]; foreach (int labelindex in mapLabelindexCount.Keys) { int[] count = mapLabelindexCount.get(labelindex); if (null != count) // count should not be null { labelindexCount[infoIndex] = labelindex; labelindexCount[infoIndex + 1] = count[0]; } infoIndex = infoIndex + 2; } nodeInfos[nodeInfoTemplates.Length - 1] = labelindexCount; } return(nodeInfos); }
private DialogControl DialogControlEntry() { ExpressionValue ident; Token value = null; Token ctx; System.Windows.Rect Bounds = new System.Windows.Rect(); string ctrlType = null; ExpressionValue Style = null; switch (Lexer.Peek()) { case Tokens.PushButton: case Tokens.DefPushButton: case Tokens.GroupBox: case Tokens.Control: case Tokens.LText: case Tokens.RText: case Tokens.CText: case Tokens.CheckBox: case Tokens.AutoCheckBox: case Tokens.RadioButton: case Tokens.AutoRadioButton: ctx = Lexer.Pop(); if (Lexer.Peek() == Tokens.String) { value = PopExpected(Tokens.String); } else { // resource string id Expression(); } if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } ident = Expression(); if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } if (ctx.Name == Tokens.Control) { var ctrlTypeToken = PopExpected(Tokens.String, Tokens.Ident); if (ctrlTypeToken.Name == Tokens.String) { ctrlType = ctrlTypeToken.Text; } else { ctrlType = ClassNames.Translate(ctrlTypeToken.Text); } PopExpected(Tokens.Comma); Style = StyleStatement(); PopExpected(Tokens.Comma); } break; case Tokens.Icon: case Tokens.ListBox: case Tokens.EditText: case Tokens.ComboBox: ctx = Lexer.Pop(); ident = Expression(); if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } if (ctx.Name == Tokens.Icon) { value = ident.Tokens.First(); ident = Expression(); if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } } break; default: throw new ParserException(this, $"Internal Error: Unexpected Look-Ahead {Lexer.Peek(0)}"); } Bounds = Dimensions(); if (Style == null && IsExpressionStartToken()) { Style = StyleStatement(); if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } } // Ignore all remaining expressions while (IsExpressionStartToken()) { var expr = Expression(); // ignore, we don't need it if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } } var ste = new DialogControl { Context = ctx.Context, EntryType = ctx, Identifier = ident, TextValue = value, Dimensions = Bounds, GenericControlType = ctrlType ?? string.Empty, Style = Style }; return(ste); }
/// <summary>Calculates the operations that are allowed for two double values. /// </summary> /// <param name="oper"></param> /// <param name="elLeft"></param> /// <param name="elRight"></param> /// <param name="valLeft"></param> /// <param name="valRight"></param> /// <returns></returns> private bool CalculateDoubleOperation(tkOperation oper, Element elLeft, Element elRight, ExpressionValue valLeft, ExpressionValue valRight) { elLeft.calcVal.type = tkValueType.vtDouble; switch (oper) { case tkOperation.operLess: elLeft.calcVal.bln = valLeft.dbl < valRight.dbl; elLeft.calcVal.type = tkValueType.vtBoolean; break; case tkOperation.operLessEqual: elLeft.calcVal.bln = valLeft.dbl <= valRight.dbl; elLeft.calcVal.type = tkValueType.vtBoolean; break; case tkOperation.operGreater: elLeft.calcVal.bln = valLeft.dbl > valRight.dbl; elLeft.calcVal.type = tkValueType.vtBoolean; break; case tkOperation.operGrEqual: elLeft.calcVal.bln = valLeft.dbl >= valRight.dbl; elLeft.calcVal.type = tkValueType.vtBoolean; break; case tkOperation.operEqual: elLeft.calcVal.bln = valLeft.dbl == valRight.dbl; elLeft.calcVal.type = tkValueType.vtBoolean; break; case tkOperation.operNotEqual: elLeft.calcVal.bln = valLeft.dbl != valRight.dbl; elLeft.calcVal.type = tkValueType.vtBoolean; break; case tkOperation.operMinus: elLeft.calcVal.dbl = valLeft.dbl - valRight.dbl; elLeft.calcVal.type = tkValueType.vtDouble; break; case tkOperation.operMult: elLeft.calcVal.dbl = valLeft.dbl * valRight.dbl; break; case tkOperation.operExpon: elLeft.calcVal.dbl = Math.Pow(valLeft.dbl, valRight.dbl); break; case tkOperation.operMOD: elLeft.calcVal.dbl = (double)((int)valLeft.dbl % (int)valRight.dbl); break; case tkOperation.operDiv: if (valRight.dbl == 0.0) { _errorMessage = SymbologyMessageStrings.Expression_ZeroDivision; return false; } elLeft.calcVal.dbl = valLeft.dbl / valRight.dbl; break; case tkOperation.operDivInt: if (valRight.dbl == 0.0) { _errorMessage = SymbologyMessageStrings.Expression_ZeroDivision; return false; } elLeft.calcVal.dbl = (double)((int)valLeft.dbl / (int)valRight.dbl); break; case tkOperation.operPlus: elLeft.calcVal.dbl = valLeft.dbl + valRight.dbl; break; default: { _errorMessage = SymbologyMessageStrings.Expression_OperationNotSupported; return false; } } return true; }
/// <summary> /// Initialize a double literal value /// </summary> /// <param name="value">Double value</param> /// <param name="source">Source representation</param> public LiteralNode(uint value, string source) { LiteralValue = new ExpressionValue(value); Source = source; }
/// <summary>Calculates the operations that are allowed for two string values. /// </summary> /// <param name="oper"></param> /// <param name="elLeft"></param> /// <param name="elRight"></param> /// <param name="valLeft"></param> /// <param name="valRight"></param> /// <returns></returns> private bool CalculateStringOperation(tkOperation oper, Element elLeft, Element elRight, ExpressionValue valLeft, ExpressionValue valRight) { int res = string.Compare(valLeft.str.ToLower(), valRight.str.ToLower()); elLeft.calcVal.bln = false; elLeft.calcVal.type = tkValueType.vtBoolean; switch (oper) { case tkOperation.operPlus: elLeft.calcVal.str = valLeft.str + valRight.str; elLeft.calcVal.type = tkValueType.vtString; break; case tkOperation.operLess: if (res < 0) elLeft.calcVal.bln = true; break; case tkOperation.operLessEqual: if (res <= 0) elLeft.calcVal.bln = true; break; case tkOperation.operGreater: if (res > 0) elLeft.calcVal.bln = true; break; case tkOperation.operGrEqual: if (res >= 0) elLeft.calcVal.bln = true; break; case tkOperation.operEqual: if (res == 0) elLeft.calcVal.bln = true; break; case tkOperation.operNotEqual: if (res != 0) elLeft.calcVal.bln = true; break; default: _errorMessage = SymbologyMessageStrings.Expression_OperationNotSupported; return false; } return true; }
public override void MoveOneStep(Valuation GlobalEnv, List <Configuration> list) { System.Diagnostics.Debug.Assert(list.Count == 0); ChannelQueue Buffer = null; if (GlobalEnv.Channels.TryGetValue(this.ChannelName, out Buffer)) { if (Buffer.Count > 0) { ChannelQueue newBuffer = Buffer.Clone(); ExpressionValue[] values = newBuffer.Dequeue(); if (values.Length == ExpressionList.Length) { Dictionary <string, Expression> mapping = new Dictionary <string, Expression>(values.Length); Valuation newEnv = GlobalEnv.GetChannelClone(); newEnv.Channels[ChannelName] = newBuffer; string eventName = ChannelName + "?"; string eventID = ChannelName + "?"; for (int i = 0; i < ExpressionList.Length; i++) { ExpressionValue v = values[i]; if (i == ExpressionList.Length - 1) { eventName += v; eventID += v.ExpressionID;//.GetID(); } else { eventName += v + "."; eventID += v.ExpressionID + "."; } if (ExpressionList[i] is Variable) { mapping.Add(ExpressionList[i].ExpressionID, v); //.GetID() } else { if (v.ExpressionID != ExpressionList[i].ExpressionID) //.GetID() .GetID() { return; //list } } } Process newProcess = mapping.Count > 0 ? Process.ClearConstant(mapping) : Process; if (eventID != eventName) { list.Add(new Configuration(newProcess, eventID, eventName, newEnv, false)); } else { list.Add(new Configuration(newProcess, eventID, null, newEnv, false)); } } } } //return list; }
private Expression ParseExpression() { Expression exp1; // Case (EXPRESSION) if (this.CurrentType == TokenType.L_PAREN) { this.Pop(); exp1 = this.ParseExpression(); if (this.CurrentType != TokenType.R_PAREN) { return(null); } this.Pop(); // Identifier case } else if (this.CurrentType == TokenType.ALPHANUMERIC) { Token id = this.Pop(); if (this.CurrentType == TokenType.L_PAREN) { this.Pop(); ArrayList <Expression> parameters = this.ParseFunctionParameters(); exp1 = new Expression(ExpressionType.FUNCTION, id.Value, parameters); } else { //char initial = id.Value [0]; //if (!Matcher.isValidInitialIdentifier (initial)) // return null; //else exp1 = new Expression(ExpressionType.IDENTIFIER, id); } // Integer case } else if ((this.CurrentType == TokenType.NUMBER) || ((this.NextType == TokenType.NUMBER) && ((this.CurrentType == TokenType.PLUS) || (this.CurrentType == TokenType.MINUS)))) { Token cur = this.Pop(); int sign = 1; if (cur.Type == TokenType.PLUS) { cur = this.Pop(); } else if (cur.Type == TokenType.MINUS) { cur = this.Pop(); sign = -1; } ExpressionValue value = new ExpressionValue( ExpressionValueType.NUMBER, sign * Evaluator.ToNumber(cur.Value) ); exp1 = new Expression(ExpressionType.INTEGER, value); // Boolean case } else if (this.CurrentType == TokenType.TRUE || this.CurrentType == TokenType.FALSE) { ExpressionValue value = new ExpressionValue( ExpressionValueType.BOOLEAN, Evaluator.ToBool(this.Pop().Value) ); exp1 = new Expression(ExpressionType.BOOL, value); // String case } else if (this.CurrentType == TokenType.QUOTE) { this.Pop(); if (this.CurrentType != TokenType.ALPHANUMERIC) { return(null); } Token str = this.Pop(); if (this.CurrentType != TokenType.QUOTE) { return(null); } this.Pop(); ExpressionValue value = new ExpressionValue( ExpressionValueType.STRING, str.Value ); exp1 = new Expression( ExpressionType.STRING, value ); // Expression combination case } else if (this.CurrentType == TokenType.L_BRACE && this.NextType == TokenType.R_BRACE) { this.Pop(2); return(new Expression(ExpressionType.OBJECT)); } else if (this.CurrentType == TokenType.OBJECT_ACCESS) { if (this.NextType != TokenType.L_PAREN) { exp1 = new Expression(ExpressionType.OBJECT_ACCESSOR, this.Pop().AccessKey); } else { List <string> accessor = this.Pop().AccessKey; if (this.CurrentType != TokenType.L_PAREN) { return(null); } this.Pop(); ArrayList <Expression> parameters = this.ParseFunctionParameters(); exp1 = new Expression(ExpressionType.FUNCTION, accessor, parameters); } } else if (this.CurrentType == TokenType.FUNCTION) { this.Pop(); Function fun = this.ParseFunction(); exp1 = new Expression(ExpressionType.FUNCTION_DECLARATION, fun); } else { return(null); } if (Parser.IsExpressionOperator(this.CurrentType)) { ExpressionType type = Parser.GetExpressionOperator(this.CurrentType); this.Pop(); Expression exp2 = this.ParseExpression(); if (exp2 == null) { return(null); } else { return(new Expression(type, exp1, exp2)); } } else { return(exp1); } }
// evaluate starts evaluation with fresh environment public static ExpressionValue Evaluate(Expression exp, Valuation env) { switch (exp.ExpressionType) { case ExpressionType.Constant: return(exp as ExpressionValue); case ExpressionType.Variable: // Look up variable in environment; we assume // that value is found try { return(env.Variables[exp.expressionID]); } catch (KeyNotFoundException) { throw new EvaluatingException("Access the non existing variable: " + exp.expressionID); } catch (Exception ex) { throw new EvaluatingException("Variable evaluation exception for variable '" + exp.expressionID + "':" + ex.Message); } case ExpressionType.Record: { Expression[] ass = ((Record)exp).Associations; ExpressionValue[] values = new ExpressionValue[ass.Length]; for (int i = 0; i < ass.Length; i++) { //rv.Put(association.Property, store.Extend(Eval(association.Expression, env))); //rv.Put(Eval(association, env)); values[i] = Evaluate(ass[i], env); #if !OPTIMAL_FOR_EXP if (values[i] == null) { throw new RuntimeException("Invalid expression assignment: " + exp); } #endif } RecordValue rv = new RecordValue(values); return(rv); } case ExpressionType.PrimitiveApplication: // First evaluate the first argument, then the second, and // then evaluate using evalPrimAppl. { PrimitiveApplication newexp = exp as PrimitiveApplication; ExpressionValue x1 = Evaluate(newexp.Argument1, env); Debug.Assert(x1 != null); #if !OPTIMAL_FOR_EXP if (x1 == null) { throw new RuntimeException("Invalid expression assignment: " + exp); } #endif return(EvalPrimAppl(newexp, x1, newexp.Argument2, env)); } case ExpressionType.Assignment: { //Assign the rhs to lhs String lhs = ((Assignment)exp).LeftHandSide; Expression rhs = ((Assignment)exp).RightHandSide; ExpressionValue rhsV = Evaluate(rhs, env); #if !OPTIMAL_FOR_EXP if (rhsV == null) { throw new RuntimeException("Invalid expression assignment: " + exp); } Valuation.CheckVariableRange(lhs, rhsV); #endif env.Variables[lhs] = rhsV; return(rhsV); } case ExpressionType.PropertyAssignment: { try { PropertyAssignment pa = (PropertyAssignment)exp; RecordValue rec = (RecordValue)Evaluate(pa.RecordExpression, env); IntConstant pro = (IntConstant)Evaluate(pa.PropertyExpression, env); ExpressionValue rhs = Evaluate(pa.RightHandExpression, env); //rec.Put(pro.PropertyName, store.Extend(rhs)); int index = pro.Value; if (index < 0) { throw new NegativeArraySizeException("Access negative index " + index + " for variable " + pa.RecordExpression.ToString()); } else if (index >= rec.Associations.Length) { throw new IndexOutOfBoundsException("Index " + index + " is out of range for variable " + pa.RecordExpression.ToString()); } #if !OPTIMAL_FOR_EXP if (rhs == null) { throw new RuntimeException("Invalid expression assignment: " + exp); } Valuation.CheckVariableRange(pa.RecordExpression.ToString(), rhs); #endif rec.Associations[index] = rhs; //Note:Important!!! must recalculate the ID here, otherwise ID is obsolete and the verification result is wrong rec.GetID(); return(rhs); } catch (InvalidCastException ex) { throw new RuntimeException("Invalid Cast Exception for " + exp + ": " + ex.Message.Replace("PAT.Common.Classes.Expressions.ExpressionClass.", "")); } } case ExpressionType.If: // Conditionals are evaluated by evaluating the then-part or // else-part depending of the result of evaluating the condition. { ExpressionValue cond = Evaluate(((If)exp).Condition, env); if (((BoolConstant)cond).Value) { return(Evaluate(((If)exp).ThenPart, env)); } else if (((If)exp).ElsePart != null) { return(Evaluate(((If)exp).ElsePart, env)); } else { return(null); } } case ExpressionType.Sequence: // firstPart;secondPart Expression fP = ((Sequence)exp).FirstPart; Expression sP = ((Sequence)exp).SecondPart; Evaluate(fP, env); return(Evaluate(sP, env)); case ExpressionType.While: Expression test = ((While)exp).Test; Expression body = ((While)exp).Body; // the value of test may not be a Value. // here we assume it is always a Value, which // may cause run time exception due to non-Value. if (((BoolConstant)Evaluate(test, env)).Value) { // test is ture Evaluate(body, env); // body serves to change the store return(Evaluate(exp, env)); // evaluate the While again } else { return(null); } case ExpressionType.StaticMethodCall: try { StaticMethodCall methodCall = (StaticMethodCall)exp; if (methodCall.Arguments.Length > 0) { ChannelQueue queue; string cname = null; if ((methodCall.Arguments[0] is Variable)) { cname = (methodCall.Arguments[0] as Variable).ExpressionID; } else if (methodCall.Arguments[0] is PrimitiveApplication) { PrimitiveApplication pa = (methodCall.Arguments[0] as PrimitiveApplication); ExpressionValue ind = Evaluate(pa.Argument2, env); cname = pa.Argument1 + "[" + ind + "]"; } switch (methodCall.MethodName) { case Common.Classes.Ultility.Constants.cfull: if (env.Channels.TryGetValue(cname, out queue)) { return(new BoolConstant(queue.IsFull())); } else { throw new RuntimeException("Channel " + cname + " is not used in the model. Therefore it is meaningless to query channel information using " + methodCall + "."); } case Common.Classes.Ultility.Constants.cempty: if (env.Channels.TryGetValue(cname, out queue)) { return(new BoolConstant(queue.IsEmpty())); } else { throw new RuntimeException("Channel " + cname + " is not used in the model. Therefore it is meaningless to query channel information using " + methodCall + "."); } case Common.Classes.Ultility.Constants.ccount: if (env.Channels.TryGetValue(cname, out queue)) { return(new IntConstant(queue.Count)); } else { throw new RuntimeException("Channel " + cname + " is not used in the model. Therefore it is meaningless to query channel information using " + methodCall + "."); } case Common.Classes.Ultility.Constants.csize: if (env.Channels.TryGetValue(cname, out queue)) { return(new IntConstant(queue.Size)); } else { throw new RuntimeException("Channel " + cname + " is not used in the model. Therefore it is meaningless to query channel information using " + methodCall + "."); } case Common.Classes.Ultility.Constants.cpeek: if (env.Channels.TryGetValue(cname, out queue)) { if (queue.Count == 0) { throw new IndexOutOfBoundsException("Channel " + cname + "'s buffer is empty!"); } return(new RecordValue(queue.Peek())); } else { throw new RuntimeException("Channel " + cname + " is not used in the model. Therefore it is meaningless to query channel information using " + methodCall + "."); } } } object[] paras = new object[methodCall.Arguments.Length]; for (int i = 0; i < paras.Length; i++) { ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env); paras[i] = GetValueFromExpression(x1); } string key = methodCall.MethodName + paras.Length; if (Common.Utility.Utilities.CSharpMethods.ContainsKey(key)) { object resultv = Common.Utility.Utilities.CSharpMethods[key].Invoke(null, paras); if (Common.Utility.Utilities.CSharpMethods[key].ReturnType.Name == "Void") { return(null); } if (resultv is bool) { return(new BoolConstant((bool)resultv)); } else if (resultv is int || resultv is short || resultv is byte || resultv is double) { return(new IntConstant(Convert.ToInt32(resultv))); } else if (resultv is int[]) { int[] list = resultv as int[]; ExpressionValue[] vals = new ExpressionValue[list.Length]; for (int i = 0; i < vals.Length; i++) { vals[i] = new IntConstant(list[i]); } return(new RecordValue(vals)); } else if (resultv is ExpressionValue) { return(resultv as ExpressionValue); } return(new NullConstant()); //the following check is not necessary, since we will only keep bool, int and int[] methods //else //{ // throw new Expressions.ExpressionClass.RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your methods."); //} } throw new RuntimeException("Invalid Method Call: " + methodCall + "! Make sure you have defined the method in the library."); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { RuntimeException exception = new RuntimeException("Exception happened at expression " + exp + ": " + ex.InnerException.Message); exception.InnerStackTrace = ex.InnerException.StackTrace; throw exception; } else { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } } catch (Exception ex) { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } case ExpressionType.ClassMethodCall: try { ClassMethodCall methodCall = (ClassMethodCall)exp; ExpressionValue variable = env.Variables[methodCall.Variable]; if (variable == null) { throw new RuntimeException("Exception happened at expression " + exp + ": variable " + methodCall.Variable + "'s value is null"); } object[] paras = new object[methodCall.Arguments.Length]; for (int i = 0; i < paras.Length; i++) { ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env); paras[i] = GetValueFromExpression(x1); } MethodInfo methodInfo = variable.GetType().GetMethod(methodCall.MethodName); if (methodInfo != null) { object resultv = methodInfo.Invoke(variable, BindingFlags.InvokeMethod, null, paras, CultureInfo.InvariantCulture); if (methodInfo.ReturnType.Name == "Void") { return(null); } if (resultv is bool) { return(new BoolConstant((bool)resultv)); } else if (resultv is int || resultv is short || resultv is byte || resultv is double) { return(new IntConstant(Convert.ToInt32(resultv))); } else if (resultv is int[]) { int[] list = resultv as int[]; ExpressionValue[] vals = new ExpressionValue[list.Length]; for (int i = 0; i < vals.Length; i++) { vals[i] = new IntConstant(list[i]); } return(new RecordValue(vals)); } else if (resultv is ExpressionValue) { return(resultv as ExpressionValue); } else if (resultv == null) { return(new NullConstant()); } //return null; //the following check is not necessary, since we will only keep bool, int and int[] methods throw new RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your statement: " + methodCall.ToString() + "."); } throw new RuntimeException("Invalid Method Call: " + methodCall + "! Make sure you have defined the method in the library."); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { RuntimeException exception = new RuntimeException("Exception happened at expression " + exp + ": " + ex.InnerException.Message); exception.InnerStackTrace = ex.InnerException.StackTrace; throw exception; } else { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } } catch (Exception ex) { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } case ExpressionType.ClassMethodCallInstance: try { ClassMethodCallInstance methodCall = (ClassMethodCallInstance)exp; ExpressionValue variable = Evaluate(methodCall.Variable, env); object[] paras = new object[methodCall.Arguments.Length]; for (int i = 0; i < paras.Length; i++) { ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env); paras[i] = GetValueFromExpression(x1); } MethodInfo methodInfo = variable.GetType().GetMethod(methodCall.MethodName); if (methodInfo != null) { object resultv = methodInfo.Invoke(variable, paras); if (methodInfo.ReturnType.Name == "Void") { return(null); } if (resultv is bool) { return(new BoolConstant((bool)resultv)); } else if (resultv is int || resultv is short || resultv is byte || resultv is double) { return(new IntConstant(Convert.ToInt32(resultv))); } else if (resultv is int[]) { int[] list = resultv as int[]; ExpressionValue[] vals = new ExpressionValue[list.Length]; for (int i = 0; i < vals.Length; i++) { vals[i] = new IntConstant(list[i]); } return(new RecordValue(vals)); } else if (resultv is ExpressionValue) { return(resultv as ExpressionValue); } else if (resultv == null) { return(new NullConstant()); } //return null; //the following check is not necessary, since we will only keep bool, int and int[] methods throw new RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your statement: " + methodCall.ToString() + "."); } throw new RuntimeException("Invalid Method Call: " + methodCall + "! Make sure you have defined the method in the library."); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { RuntimeException exception = new RuntimeException("Exception happened at expression " + exp + ": " + ex.InnerException.Message); exception.InnerStackTrace = ex.InnerException.StackTrace; throw exception; } else { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } } catch (Exception ex) { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } case ExpressionType.ClassProperty: try { ClassProperty property = (ClassProperty)exp; ExpressionValue variable = Evaluate(property.Variable, env); PropertyInfo propertyInfo = variable.GetType().GetProperty(property.PropertyName); object resultv = null; if (propertyInfo != null) { resultv = propertyInfo.GetValue(variable, null); } else { FieldInfo fieldInfo = variable.GetType().GetField(property.PropertyName); if (fieldInfo != null) { resultv = fieldInfo.GetValue(variable); } } if (resultv != null) { if (resultv is bool) { return(new BoolConstant((bool)resultv)); } else if (resultv is int || resultv is short || resultv is byte || resultv is double) { return(new IntConstant(Convert.ToInt32(resultv))); } else if (resultv is int[]) { int[] list = resultv as int[]; ExpressionValue[] vals = new ExpressionValue[list.Length]; for (int i = 0; i < vals.Length; i++) { vals[i] = new IntConstant(list[i]); } return(new RecordValue(vals)); } else if (resultv is ExpressionValue) { return(resultv as ExpressionValue); } //else if (resultv == null) //{ // return new NullConstant(); //} //return null; //the following check is not necessary, since we will only keep bool, int and int[] methods throw new RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your statement: " + property.ToString() + "."); } throw new RuntimeException("Invalid Property Accessing: " + property + "! Make sure you have defined the method in the library."); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { RuntimeException exception = new RuntimeException("Exception happened at expression " + exp + ": " + ex.InnerException.Message); exception.InnerStackTrace = ex.InnerException.StackTrace; throw exception; } else { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } } catch (Exception ex) { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } case ExpressionType.ClassPropertyAssignment: { try { ClassPropertyAssignment pa = (ClassPropertyAssignment)exp; ExpressionValue rhs = Evaluate(pa.RightHandExpression, env); #if !OPTIMAL_FOR_EXP if (rhs == null) { throw new RuntimeException("Invalid expression assignment: " + exp); } #endif ClassProperty property = pa.ClassProperty; ExpressionValue variable = Evaluate(property.Variable, env); PropertyInfo propertyInfo = variable.GetType().GetProperty(property.PropertyName); if (propertyInfo != null) { propertyInfo.SetValue(variable, GetValueFromExpression(rhs), null); } else { FieldInfo fieldInfo = variable.GetType().GetField(property.PropertyName); if (fieldInfo != null) { fieldInfo.SetValue(variable, GetValueFromExpression(rhs)); } else { throw new RuntimeException("Invalid expression assignment: " + exp); } } return(rhs); } catch (InvalidCastException ex) { throw new RuntimeException("Invalid Cast Exception for " + exp + ": " + ex.Message.Replace("PAT.Common.Classes.Expressions.ExpressionClass.", "")); } } case ExpressionType.Let: LetDefinition definition = exp as LetDefinition; ExpressionValue rhv = Evaluate(definition.RightHandExpression, env); env.ExtendDestructive(definition.Variable, rhv); return(null); case ExpressionType.NewObjectCreation: try { NewObjectCreation methodCall = (NewObjectCreation)exp; object[] paras = new object[methodCall.Arguments.Length]; for (int i = 0; i < paras.Length; i++) { ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env); paras[i] = GetValueFromExpression(x1); } Type classType; if (Common.Utility.Utilities.CSharpDataType.TryGetValue(methodCall.ClassName, out classType)) { object resultv = Activator.CreateInstance(classType, paras); if (resultv is ExpressionValue) { return(resultv as ExpressionValue); } //return null; //the following check is not necessary, since we will only keep bool, int and int[] methods throw new RuntimeException("Only object of class inheriting from ExpressionValue can be created. Please check your statement: " + methodCall.ToString() + "."); } throw new RuntimeException("Invalid Object Creation: " + methodCall + "! Make sure you have defined the class in the library."); } catch (Exception ex) { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } //case ExpressionType.UserDefinedDataType: // return exp as ; /* case ExpressionType.Let: * // Evaluate body with respect to environment extended by binding of leftHand to rightHand * { * Valuation newenv = env.GetVariableClone(); * foreach (LetDefinition def in ((Let) exp).Definitions) * { * Value rhv = Evaluate(def.RightHandExpression, env); * //newenv = Extend(newenv, def.Variable, rhv); * //newenv = newenv.Extend(def.Variable, rhv); * newenv.ExtendDestructive(def.Variable, rhv); * } * return Evaluate(((Let) exp).Body, newenv); * } * case ExpressionType.Fun: * return new FunValue(env, ((Fun) exp).Formals, ((Fun) exp).Body); * case ExpressionType.RecFun: * // For recursive functions, we need to place an environment * // in the function that has a binding of the function variable * // to the function itself. For this, we obtain a clone of the * // environment, making sure that a destructive change will * // not have any effect on the original environment. Then, we * // place the clone in the function value. After that, we * // destructively change the environment by a binding of the * // function variable to the constructed function value. * { * Valuation newEnv = env.GetVariableClone(); // (Valuation)env.Clone(); * Value result = new FunValue(newEnv, ((RecFun) exp).Formals, ((RecFun) exp).body); * //ExtendDestructive(newEnv, ((RecFun)exp).FunVar, result); * newEnv.ExtendDestructive(((RecFun) exp).FunVar, result); * return result; * } * case ExpressionType.Application: * // Apply the function value resulting from evaluating the operator * // (we assume that this is a function value) to * // the value resulting from evaluating the operand. * // Note that we do not need to distinguish functions from * // recursive functions. Both are represented by function values, * // recursive functions have a binding of their function variable * // to themselves in their environment. * { * FunValue fun = (FunValue) Evaluate(((Application) exp).Operator, env); * Valuation newenv = (Valuation) fun.Valuation; * * List<Expression> ops = ((Application) exp).Operands; * List<string> fe = fun.Formals; * * for (int i = 0; i < ops.Count; i++) * { * Value argvalue = Evaluate(ops[i], env); * //newenv = Extend(newenv, fe[i], argvalue); * newenv = newenv.Extend((String) fe[i], argvalue); * } * return Evaluate(fun.Body, newenv); * }*/ } // (exp instanceof NotUsed) // NotUsed is used as argument2 of PrimitiveApplication. // We assume the resulting value will not be used, // thus any value will do, here. return(new BoolConstant(true)); }
private KeyValuePair <string, IExpressionValue> InterpretComplexReference(SyneryParser.ComplexReferenceContext context, QueryMemory queryMemory) { // get the future fieldname from it's old name by removing the alias string complexIdentifier = context.GetText(); string[] path = IdentifierHelper.ParseComplexIdentifier(complexIdentifier); string fieldName = path[path.Length - 1]; // get the LINQ expression for the field reference IField schemaField = queryMemory.CurrentTable.Schema.GetField(complexIdentifier); int fieldPosition = queryMemory.CurrentTable.Schema.GetFieldPosition(complexIdentifier); if (fieldPosition != -1) { // the field was found - create an array index Expression to access the field value Expression arraySelectorExpression = Expression.ArrayIndex(queryMemory.RowExpression, Expression.Constant(fieldPosition)); ExpressionValue expressionValue = new ExpressionValue( expression: arraySelectorExpression, resultType: TypeHelper.GetSyneryType(schemaField.Type) ); return(new KeyValuePair <string, IExpressionValue>(fieldName, expressionValue)); } // search for an other kind of complex references IValue value = Controller.Interpret <SyneryParser.ComplexReferenceContext, IValue>(context); if (value != null) { // the value could be resolved // create a constant LINQ expression for the value // check whether it's a primitive type if (value.Type != typeof(IRecord)) { Expression expression; if (value.Type != null) { expression = Expression.Constant(value.Value, value.Type.UnterlyingDotNetType); } else { expression = Expression.Constant(null); } ExpressionValue expressionValue = new ExpressionValue( expression: expression, resultType: value.Type ); return(new KeyValuePair <string, IExpressionValue>(fieldName, expressionValue)); } else { throw new SyneryInterpretationException(context, String.Format( "Cannot use the reference to the record (name='{0}') inside of a query. Only primitve types are allowed." , fieldName)); } } throw new SyneryInterpretationException(context, String.Format("A field or variable with the name '{0}' wan't found.", complexIdentifier)); }
public override void MoveOneStep(Valuation GlobalEnv, List <Configuration> list) { System.Diagnostics.Debug.Assert(list.Count == 0); try { ChannelQueue Buffer = null; string channelName = this.ChannelName; if (ChannelIndex != null) { int size = ((IntConstant)EvaluatorDenotational.Evaluate(ChannelIndex, GlobalEnv)).Value; if (size >= Specification.ChannelArrayDatabase[ChannelName]) { throw new PAT.Common.Classes.Expressions.ExpressionClass.IndexOutOfBoundsException("Channel index out of bounds for expression " + this.ToString()); } channelName = channelName + "[" + size + "]"; } if (GlobalEnv.Channels.TryGetValue(channelName, out Buffer)) { if (Buffer.Count > 0) { ChannelQueue newBuffer = Buffer.Clone(); ExpressionValue[] values = newBuffer.Dequeue(); if (values.Length == ExpressionList.Length) { Dictionary <string, Expression> mapping = new Dictionary <string, Expression>(values.Length); Valuation newEnv = GlobalEnv.GetChannelClone(); newEnv.Channels[channelName] = newBuffer; string eventName = channelName + "?"; string eventID = channelName + "?"; for (int i = 0; i < ExpressionList.Length; i++) { ExpressionValue v = values[i]; if (i == ExpressionList.Length - 1) { eventName += v; eventID += v.ExpressionID;//.GetID(); } else { eventName += v + "."; eventID += v.ExpressionID + "."; } if (ExpressionList[i] is Variable) { mapping.Add(ExpressionList[i].ExpressionID, v); //.GetID() } else { if (v.ExpressionID != ExpressionList[i].ExpressionID) //.GetID() .GetID() { return; //list } } } Process newProcess = mapping.Count > 0 ? Process.ClearConstant(mapping) : Process; if (eventID != eventName) { list.Add(new Configuration(newProcess, eventID, eventName, newEnv, false)); } else { list.Add(new Configuration(newProcess, eventID, null, newEnv, false)); } } } } } catch (Exception e) { Console.WriteLine(e.ToString()); } //return list; }
public static Boolean EvaluateQueue( DynContext DynLanContext) { ExpressionState expState = DynLanContext.CurrentExpressionState; ExpressionContext expContext = DynLanContext.CurrentExpressionContext; // policzenie nastepnego parametru if (expState.AreParametersCalculating) { expState.ParameterIndex++; if (expState.ParameterIndex < expState.ParameterTokens.Count) { Boolean result = false; ExpressionToken parameterToken = expState.ParameterTokens[expState.ParameterIndex]; if (parameterToken.TokenType == TokenType.VARIABLE) { result = ObjectValueGetter.EvaluateValue( parameterToken.TokenName, DynLanContext); } else if (parameterToken.TokenType == TokenType.VALUE) { ExpressionValue operationValue = StringHelper. GetValueFromText(parameterToken.TokenChars); Object value = ( operationValue == null ? null : operationValue.Value); expState.Parameters.Add(value); } else { throw new DynLanIncorrectExpressionFormatException(); } return(result); } } // czy zakończyć i zapisać wynik if (expState.TokenIndex >= expState.Expression.Tokens.Count) { Object finResult = null; if (expState.ValueStack.Count > 0) { finResult = MyCollectionsExtenders.Pop(expState.ValueStack); } expState.ValueStack.Clear(); expState.Finished = true; expState.Result = InternalTypeConverter.ToOuter(finResult); MyCollectionsExtenders.Pop(expContext.Stack); if (expContext.Current != null) { expContext.Current.PushValue(InternalTypeConverter.ToOuter(finResult)); return(false); } else { expContext.Result = InternalTypeConverter.ToOuter(finResult); expContext.IsFinished = true; return(true); } } Boolean isFirstToken = expState.TokenIndex == 0; ExpressionToken token = expState. Expression. Tokens[expState.TokenIndex]; ExpressionTokens sequence = new ExpressionTokens( new TokenizerQueue(). GetNextTokensOnSameLevel(expState.Expression.Tokens, expState.TokenIndex)); Int32 originalSequenceCount = sequence.Count; sequence.RemoveBrackets(); // wykonanie następnej operacji if (token.TokenType == TokenType.BRACKET_BEGIN) { IList <ExpressionToken> prevSequenceTokens = new TokenizerQueue(). GetPrevTokensOnSameLevel(expState.Expression.Tokens, expState.TokenIndex - 1); ExpressionTokens prev_sequence = prevSequenceTokens == null ? null : new ExpressionTokens(prevSequenceTokens); // jeśli poprzedni operator to @ if ( prev_sequence != null && prev_sequence.Count == 1 && OnpOnpTokenHelper.IsFunctionOperatorToken(prev_sequence[0])) { Boolean result = false; if (sequence.Count == 0 || expState.AreParametersCalculated) { Object obj = expState.ValueStack.Count == 1 ? new EmptyObject() : MyCollectionsExtenders.Peek(expState.ValueStack, 1); Object methodObject = MyCollectionsExtenders. Peek(expState.ValueStack, 0); result = EvaluatorForMethods.EvaluateMethod( obj, methodObject, expState.Parameters, DynLanContext); expState.CleanParametersState(); expState.TokenIndex += originalSequenceCount; } else { expState.ParameterTokens = GetParameterTokens(sequence); expState.ParameterIndex = -1; expState.Parameters = new List <Object>(); result = false; } return(result); } // jeśli poprzedni operator to . else if ( prev_sequence != null && prev_sequence.Count == 1 && OnpOnpTokenHelper.IsPropertyOperatorToken(prev_sequence[0])) { throw new DynLanIncorrectExpressionFormatException(); } // jeśli brak poprzedniego operatora else if ( prev_sequence == null && sequence.Count == 1) { Boolean result = false; if (sequence[0].TokenType == TokenType.VARIABLE) { result = ObjectValueGetter.EvaluateValue( sequence[0].TokenName, DynLanContext); } else if (sequence[0].TokenType == TokenType.VALUE) { ExpressionValue operationValue = StringHelper. GetValueFromText(sequence[0].TokenChars); Object value = ( operationValue == null ? null : operationValue.Value); expState.PushValue(value); } else { throw new DynLanIncorrectExpressionFormatException(); } expState.TokenIndex += originalSequenceCount; // -1; return(result); } else { throw new DynLanInvalidExpressionException("Incorrect expression " + expState.Expression.Tokens.JoinToString(expState.TokenIndex) + "!"); } } else if (token.TokenType == TokenType.VALUE) { ExpressionValue operationValue = StringHelper. GetValueFromText(token.TokenChars); Object value = ( operationValue == null ? null : operationValue.Value); if (isFirstToken) { expState.PushValue(value); } else { Object prevValue = MyCollectionsExtenders.Peek(expState.ValueStack); prevValue = InternalTypeConverter. ToOuter(prevValue); Object method = ObjectValueGetter.GetValueFromObject( prevValue, UniConvert.ToString(value)); expState.PushValue(method); } expState.TokenIndex += originalSequenceCount; // -1 } else if (token.TokenType == TokenType.PROPERTY_NAME) { if (isFirstToken) { throw new DynLanIncorrectExpressionFormatException(); } else { Object prevValue = MyCollectionsExtenders.Peek(expState.ValueStack); prevValue = InternalTypeConverter. ToOuter(prevValue); Object value = ObjectValueGetter.GetValueFromObject( prevValue, token.TokenName); expState.PushValue(value); } expState.TokenIndex += originalSequenceCount; // -1 } else if (token.TokenType == TokenType.VARIABLE) { Boolean result = false; ExpressionToken next_token = expState.TokenIndex + 1 < expState.Expression.Tokens.Count ? expState.Expression.Tokens[expState.TokenIndex + 1] : null; Object prevValue = null; if (isFirstToken) { prevValue = new EmptyObject(); /*result = ObjectValueGetter.EvaluateValueOrMethod( * new EMPTY_OBJECT(), * sequence[0].TokenName, * -1, * DynLanContext);*/ } else { prevValue = ( expState.ValueStack.Count == 0 ? null : MyCollectionsExtenders.Peek(expState.ValueStack)); } prevValue = InternalTypeConverter. ToOuter(prevValue); Int32 paramCount = -1; // jeśli następny operator to operator wołania funkcji @ to pobieramy z niego liczbę parametrów dla funkcji if (OnpOnpTokenHelper.IsFunctionOperatorToken(next_token) && next_token.TokenData != null && next_token.TokenData.FunctionParametersCount != null) { paramCount = next_token.TokenData.FunctionParametersCount.Value; } else { paramCount = -1; } result = ObjectValueGetter.EvaluateValueOrMethod( prevValue, sequence[0].TokenName, paramCount, DynLanContext); if (MyCollectionsExtenders.Peek(DynLanContext.CurrentExpressionState.ValueStack) == null) { ExpressionToken next_next_token = expState.TokenIndex + 2 < expState.Expression.Tokens.Count ? expState.Expression.Tokens[expState.TokenIndex + 2] : null; if (next_token.TokenType == TokenType.OPERATOR && OnpOnpTokenHelper.IsPropertyOperatorToken(next_token) && next_next_token != null) { } else { next_next_token = null; } if (paramCount < 0) { if (next_next_token != null) { ExpressionToken next_next_next_next_next_token = expState.TokenIndex + 5 < expState.Expression.Tokens.Count ? expState.Expression.Tokens[expState.TokenIndex + 5] : null; if (next_next_token.TokenName == "__EXT_SET" && next_next_next_next_next_token != null) { throw new DynLanMethodNotFoundException("Cannot find property " + next_next_next_next_next_token.TokenName + " in undefined object '" + sequence[0].TokenName + "'"); } else { throw new DynLanMethodNotFoundException("Cannot call method '" + next_next_token.TokenName + "' in undefined object '" + sequence[0].TokenName + "'"); } } else { throw new DynLanMethodNotFoundException("Undefined object '" + sequence[0].TokenName + "'"); } } else { throw new DynLanMethodNotFoundException("Undefined method '" + sequence[0].TokenName + "' " + (prevValue == null ? "in undefined object" : ("in object of type " + prevValue.GetType().Name))); } } expState.TokenIndex += originalSequenceCount; // -1 return(result); } else if (token.TokenType == TokenType.OPERATOR) { if (!OnpOnpTokenHelper.IsFunctionOperatorToken(token) && !OnpOnpTokenHelper.IsPropertyOperatorToken(token)) { throw new DynLanIncorrectExpressionFormatException(); } expState.TokenIndex += originalSequenceCount; // -1 } if (MyCollectionsExtenders.Peek(expState.ValueStack) == null) { return(false); } return(false); }
private (Value, bool) EvaluateExpression(ExpressionValue expr) { var head = Evaluate(expr.Head); // sym is just the head, if it's a symbol var sym = head as Symbol; var attrs = sym?.Attributes ?? 0; var evalFirst = true; var evalRest = true; if (attrs.HasFlag(SymbolAttributes.HoldAll) || attrs.HasFlag(SymbolAttributes.HoldAllComplete)) { evalFirst = false; evalRest = false; } if (attrs.HasFlag(SymbolAttributes.HoldFirst)) { evalFirst = false; } if (attrs.HasFlag(SymbolAttributes.HoldRest)) { evalRest = false; } var parts = new Value[expr.Count]; for (var i = 0; i < expr.Count; i++) { if ((i == 0 && evalFirst) || (i > 0 && evalRest)) { parts[i] = Evaluate(expr[i]); } else { parts[i] = expr[i]; } } ExpressionValue evaluated; if (!attrs.HasFlag(SymbolAttributes.HoldAllComplete)) { if (!attrs.HasFlag(SymbolAttributes.SequenceHold)) { parts = parts.SelectMany(FlattenHeads(_engine.System.Sequence)).ToArray(); } if (attrs.HasFlag(SymbolAttributes.Flat)) { parts = parts.SelectMany(FlattenHeads(sym)).ToArray(); } // TODO: if Listable .... // TODO: if Orderless ... evaluated = _engine.Expr(head, parts); foreach (var part in parts) { var partSym = part.AtomHead as Symbol; if (partSym == null) { continue; } var upValued = _engine.PatternMatching.FindAndApplyRule(evaluated, partSym.UpValues); if (upValued != null) { return(upValued, true); } } foreach (var part in parts) { var partSym = part.AtomHead as Symbol; var value = partSym?.UpCode?.Invoke(_engine, evaluated); if (value.HasValue) { return(value.Value); } } } else { evaluated = _engine.Expr(head, parts); } // headsym is used for *value lookup // it's the leftmost atom in the expression // (head of head of .... till we get to atom) // THIS IS DIFFERENT FROM sym DECLARED AT THE START var headsym = head.AtomHead as Symbol; if (headsym == null) { return(evaluated, false); } var downValued = _engine.PatternMatching.FindAndApplyRule(evaluated, headsym.DownValues); if (downValued != null) { return(downValued, true); } var coded = headsym.DownCode?.Invoke(_engine, evaluated); return(coded ?? (evaluated, false)); }
public override void MoveOneStep(Valuation GlobalEnv, List <Configuration> list) { System.Diagnostics.Debug.Assert(list.Count == 0); ChannelQueue Buffer = null; string channelName = this.ChannelName; if (ChannelIndex != null) { int size = ((IntConstant)EvaluatorDenotational.Evaluate(ChannelIndex, GlobalEnv)).Value; if (size >= Specification.ChannelArrayDatabase[ChannelName]) { throw new PAT.Common.Classes.Expressions.ExpressionClass.IndexOutOfBoundsException("Channel index out of bounds for expression " + this.ToString()); } channelName = channelName + "[" + size + "]"; } if (GlobalEnv.Channels.TryGetValue(channelName, out Buffer)) { if (Buffer.Count > 0) { ChannelQueue newBuffer = Buffer.Clone(); ExpressionValue[] values = newBuffer.Dequeue(); if (values.Length == this.ExpressionList.Length) { Dictionary <string, Expression> mapping = new Dictionary <string, Expression>(values.Length); Valuation newChannelEvn = GlobalEnv.GetChannelClone(); newChannelEvn.Channels[channelName] = newBuffer; string eventName = channelName + "?"; string eventID = channelName + "?"; for (int i = 0; i < ExpressionList.Length; i++) { ExpressionValue v = values[i]; if (i == ExpressionList.Length - 1) { eventName += v; eventID += v.ExpressionID; } else { eventName += v + "."; eventID += v.ExpressionID + "."; } if (ExpressionList[i] is Variable) { mapping.Add(ExpressionList[i].ExpressionID, v); } else { if (v.ExpressionID != ExpressionList[i].ExpressionID) { return; //list } } } Expression guard = GuardExpression.ClearConstant(mapping); ExpressionValue value = EvaluatorDenotational.Evaluate(guard, newChannelEvn); if ((value as BoolConstant).Value) { Valuation newGlobleEnv = newChannelEvn.GetVariableClone(); EvaluatorDenotational.Evaluate(AssignmentExpr.ClearConstant(mapping), newGlobleEnv); if (HasLocalVar) { Valuation tempEnv = newChannelEvn.GetVariableClone(); for (int i = 0; i < tempEnv.Variables._entries.Length; i++) { StringDictionaryEntryWithKey <ExpressionValue> pair = tempEnv.Variables._entries[i]; if (pair != null) { pair.Value = newGlobleEnv.Variables[pair.Key]; } } newGlobleEnv = tempEnv; } Process newProcess = mapping.Count > 0 ? Process.ClearConstant(mapping) : Process; if (eventID != eventName) { list.Add(new Configuration(newProcess, eventID, eventName, newGlobleEnv, false)); } else { list.Add(new Configuration(newProcess, eventID, null, newGlobleEnv, false)); } } } } } //return list; }
/// <summary> /// Set a variable floating point value by index. /// </summary> /// <param name="index">The index.</param> /// <param name="value">The value.</param> public void SetVariable(int index, double value) { _variables[index] = new ExpressionValue(value); }
public static Boolean EvaluateValueOrMethod( Object Obj, String FieldOrMethodName, Int32 ParametersCount, PainContext PainContext) { Boolean seekInObject = (Obj != null && !(Obj is EmptyObject)); if (seekInObject) { Boolean foundValue = false; Object value = GetValueFromObject( Obj, FieldOrMethodName, ParametersCount, out foundValue); if (foundValue) { if (value is MethodInfo) { OnpMethodInfo methodInfo = new OnpMethodInfo(); methodInfo.Obj = Obj; methodInfo.Name = FieldOrMethodName; PainContext.CurrentExpressionState.PushValue(methodInfo); return(false); } else { PainContext.CurrentExpressionState.PushValue(value); return(false); } } } ExpressionValue expressionValue = null; Expression expression = null; expression = PainContext. CurrentExpressionGroup. FindExpression(FieldOrMethodName, PainContext); if (expression == null) { expressionValue = PainContext.GetValue( PainContext, FieldOrMethodName, seekInObject, !seekInObject, !seekInObject); } if (expression == null) { Object value = expressionValue == null ? null : expressionValue.Value; value = InternalTypeConverter.ToInner( value); PainContext.CurrentExpressionState.PushValue(value); return(false); } else { ExpressionState newExpressionState = new ExpressionState(); newExpressionState.Expression = expression; PainContext.CurrentExpressionContext.Stack.Add(newExpressionState); return(false); } }
private static void Operation(List<int> nums, List<char> opers, ref int num, ExpressionValue expressionValue) { if (nums == null) throw new ArgumentNullException(nameof(nums)); if (expressionValue == null) throw new ArgumentNullException(nameof(expressionValue)); if (expressionValue.Index == CellConst.ZeroIndex) { expressionValue.Value = expressionValue.Chars[expressionValue.Index].ToString(); } else { if (!expressionValue.IsNextShouldBeNumber) { num = Convert.ToInt32(expressionValue.Value); nums.Add(num); opers.Add(expressionValue.Chars[expressionValue.Index]); expressionValue.IsNextShouldBeNumber = true; expressionValue.Value = string.Empty; } else { expressionValue.Value += expressionValue.Chars[expressionValue.Index]; } } }
public ParallelDefinition ClearConstant(Dictionary <string, Expression> constMapping) { ParallelDefinition pd = new ParallelDefinition(Parameter, Token); try { if (LowerBound == null) { foreach (Expression expression in Domain) { Expression newExp = expression.ClearConstant(constMapping); if (!newExp.HasVar) { ExpressionValue val = EvaluatorDenotational.Evaluate(newExp, null); if (val is IntConstant) { pd.Domain.Add(val); pd.DomainValues.Add((val as IntConstant).Value); } else { throw new ParsingException("An integer value is expected, but not " + val, Token); } } else { pd.Domain.Add(newExp); } } } else { pd.LowerBound = LowerBound.ClearConstant(constMapping); pd.UpperBound = UpperBound.ClearConstant(constMapping); if (!pd.LowerBound.HasVar && !pd.UpperBound.HasVar) { ExpressionValue lower = EvaluatorDenotational.Evaluate(pd.LowerBound, null); ExpressionValue upper = EvaluatorDenotational.Evaluate(pd.UpperBound, null); if (lower is IntConstant && upper is IntConstant) { int low = (lower as IntConstant).Value; int up = (upper as IntConstant).Value; if (low > up) { throw new ParsingException("The variable range's starting value " + low + " should be smaller than ending value" + up + ".", Token); } else { pd = new ParallelDefinition(Parameter, Token); for (int i = low; i <= up; i++) { pd.Domain.Add(new IntConstant(i)); pd.DomainValues.Add(i); } } } else { throw new ParsingException("Integers value are expected, but not " + lower + " and " + upper, Token); } } } } catch (Exception ex) { throw new ParsingException(ex.Message, Token); } return(pd); }
public override void SyncInput(ConfigurationWithChannelData eStep, List <Configuration> list) { string channelName = this.ChannelName; if (ChannelIndex != null) { int size = ((IntConstant)EvaluatorDenotational.Evaluate(ChannelIndex, eStep.GlobalEnv)).Value; if (size >= Specification.ChannelArrayDatabase[ChannelName]) { throw new PAT.Common.Classes.Expressions.ExpressionClass.IndexOutOfBoundsException("Channel index out of bounds for expression " + this.ToString()); } channelName = channelName + "[" + size + "]"; } //List<Configuration> list = new List<Configuration>(1); if (eStep.ChannelName == channelName && eStep.Expressions.Length == ExpressionList.Length) { Dictionary <string, Expression> mapping = new Dictionary <string, Expression>(eStep.Expressions.Length); for (int i = 0; i < ExpressionList.Length; i++) { Expression v = eStep.Expressions[i]; if (ExpressionList[i] is Variable) { mapping.Add(ExpressionList[i].ExpressionID, v); } else { if (v.ExpressionID != ExpressionList[i].ExpressionID) { return; } } } Expression guard = GuardExpression.ClearConstant(mapping); ExpressionValue value = EvaluatorDenotational.Evaluate(guard, eStep.GlobalEnv); if ((value as BoolConstant).Value) { Valuation newGlobleEnv = eStep.GlobalEnv.GetVariableClone(); EvaluatorDenotational.Evaluate(AssignmentExpr.ClearConstant(mapping), newGlobleEnv); if (HasLocalVar) { Valuation tempEnv = eStep.GlobalEnv.GetVariableClone(); for (int i = 0; i < tempEnv.Variables._entries.Length; i++) { StringDictionaryEntryWithKey <ExpressionValue> pair = tempEnv.Variables._entries[i]; if (pair != null) { pair.Value = newGlobleEnv.Variables[pair.Key]; } } newGlobleEnv = tempEnv; } Configuration vm; if (mapping.Count > 0) { vm = new Configuration(Process.ClearConstant(mapping), null, null, newGlobleEnv, false); } else { vm = new Configuration(Process, null, null, newGlobleEnv, false); } list.Add(vm); } } //return list; }
public ExpressionValue GetMemoryIndirectValue(ExpressionValue address) { return(ExpressionValue.Error); }
private MDPStat BuildMDP() { Stack <KeyValuePair <MDPConfiguration, MDPStateStat> > working = new Stack <KeyValuePair <MDPConfiguration, MDPStateStat> >(1024); string initID = InitialStep.GetID(); MDPStateStat init = new MDPStateStat(initID); working.Push(new KeyValuePair <MDPConfiguration, MDPStateStat>(InitialStep as MDPConfiguration, init)); MDPStat mdp = new MDPStat(init, Ultility.Ultility.DEFAULT_PRECISION, Ultility.Ultility.MAX_DIFFERENCE); do { if (CancelRequested) { VerificationOutput.NoOfStates = mdp.States.Count; return(mdp); } KeyValuePair <MDPConfiguration, MDPStateStat> current = working.Pop(); IEnumerable <MDPConfiguration> list = current.Key.MakeOneMoveLocal(); VerificationOutput.Transitions += list.Count(); int currentDistriIndex = -1; DistributionStat newDis = new DistributionStat(Constants.TAU); //for (int i = 0; i < list.Length; i++) foreach (MDPConfiguration step in list) { //MDPConfiguration step = list[i]; string stepID = step.GetID(); MDPStateStat nextState; if (!mdp.States.TryGetValue(stepID, out nextState)) { nextState = new MDPStateStat(stepID); mdp.AddState(nextState); ExpressionValue v = EvaluatorDenotational.Evaluate(ReachableStateCondition, step.GlobalEnv); if ((v as BoolConstant).Value) { mdp.AddTargetStates(nextState); } else { working.Push(new KeyValuePair <MDPConfiguration, MDPStateStat>(step, nextState)); } } if (step.DisIndex == -1) { if (currentDistriIndex >= 0) { current.Value.AddDistribution(newDis); newDis = new DistributionStat(Constants.TAU); } var newTrivialDis = new DistributionStat(step.Event); newTrivialDis.AddProbStatePair(1, nextState); current.Value.AddDistribution(newTrivialDis); } else if (currentDistriIndex != -1 && step.DisIndex != currentDistriIndex) { current.Value.AddDistribution(newDis); newDis = new DistributionStat(Constants.TAU); newDis.AddProbStatePair(step.Probability, nextState); } else { newDis.AddProbStatePair(step.Probability, nextState); } currentDistriIndex = step.DisIndex; } if (currentDistriIndex >= 0) { current.Value.AddDistribution(newDis); } } while (working.Count > 0); VerificationOutput.NoOfStates = mdp.States.Count; return(mdp); }
private String HandleConst(ProgramNode node) { ExpressionValue v = node.Data[0]; return(v.ToStringValue()); }
public Process GetProcess(Valuation global) { // Console.WriteLine("GetProcess for " + this.Name +" Def:"+this.Def); Expression[] newArgs = new Expression[Args.Length]; try { //instance String has all information about the argument value, which is used for storing the process of definition into the DefinitionInstanceDatabase //idString store only local information about the argument (exclude the global variables) string instanceString = Name + "("; string idString = Name + "("; for (int i = 0; i < Args.Length; i++) { Expression exp = Args[i]; idString += exp.ExpressionID; if (!exp.HasVar) { newArgs[i] = exp; instanceString += exp.ExpressionID; } else { ExpressionValue v = EvaluatorDenotational.Evaluate(exp, global); if (v == null) { throw new RuntimeException(string.Format("The argument {0} of parameter {1} in process {2} evaluated to be null!", exp, Def.Parameters[i], Name)); } newArgs[i] = v; instanceString += v.ExpressionID; } if (newArgs[i] is IntConstant) { int val = (newArgs[i] as IntConstant).Value; // Console.WriteLine(" getting param "+i+" : "+ Def.Parameters); string x = Def.Parameters[i]; if (Def.ParameterLowerBound.ContainsKey(x)) { int bound = Def.ParameterLowerBound.GetContainsKey(x); if (bound > val) { throw new VariableValueOutOfRangeException("Argument " + x + "'s current value " + val + " is smaller than its lower bound " + bound); } } if (Def.ParameterUpperLowerBound.ContainsKey(x)) { int bound = Def.ParameterUpperLowerBound.GetContainsKey(x); if (val > bound) { throw new VariableValueOutOfRangeException("Argument " + x + "'s current value " + val + " is greater than its upper bound " + bound); } } } if (i < Args.Length - 1) { instanceString += ","; idString += ","; } } idString += ")"; instanceString += ")"; Process ProcExpr = DataStore.DataManager.DefinitionInstanceDatabase.GetContainsKey(instanceString); if (ProcExpr != null) { return(ProcExpr); } else { Dictionary <string, Expression> values = new Dictionary <string, Expression>(Args.Length); for (int i = 0; i < newArgs.Length; i++) { values.Add(Def.Parameters[i], newArgs[i]); } ProcessID = DataStore.DataManager.InitializeProcessID(idString); //lock the data manager to prevent the multi-thread update the last Process ID at the same time. lock (DataStore.DataManager) { ProcExpr = Def.Process.ClearConstant(values); //Instantiate DataStore.DataManager.SetLastProcessID(ProcessID); } ProcExpr.ProcessID = ProcessID; DataStore.DataManager.DefinitionInstanceDatabase.Add(instanceString, ProcExpr); // Console.WriteLine(" ProcExpr: " + ProcExpr); return(ProcExpr); } } catch (Exception e) { //Console.WriteLine(e.ToString()); throw e; } }
private DialogDefinition DialogStatement(ExpressionValue ident, bool isEx) { var ctx = PopExpected(isEx ? Tokens.DialogEx : Tokens.Dialog); if (Lexer.Peek() == Tokens.Discardable) { PopExpected(Tokens.Discardable); } var de = new DialogDefinition(); de.Identifier = ident; de.Context = ctx.Context; de.EntryType = ctx; de.Dimensions = Dimensions(); while (IsExpressionStartToken()) { Expression(); // ignore, we don't need it if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } } while (Lexer.Peek() != Tokens.LBrace && Lexer.Peek() != Tokens.Begin) { switch (Lexer.Peek()) { case Tokens.Style: { PopExpected(Tokens.Style); de.Style = StyleStatement(); if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } } break; case Tokens.ExStyle: { PopExpected(Tokens.ExStyle); de.ExStyle = StyleStatement(); if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } } break; case Tokens.Font: { PopExpected(Tokens.Font); var size = PopExpected(Tokens.Double, Tokens.Integer); double sizeVal; double.TryParse(size.Text, out sizeVal); if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } var name = PopExpected(Tokens.String); if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } de.Font = new Font() { Name = name.Text, Size = (float)sizeVal }; } break; case Tokens.Caption: { PopExpected(Tokens.Caption); var caption = PopExpected(Tokens.String); de.TextValue = caption; if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } } break; case Tokens.Menu: { PopExpected(Tokens.Menu); Expression(); if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } } break; case Tokens.LBrace: case Tokens.Begin: break; default: throw new ParserException(this, $"Internal Error: Unexpected Look-Ahead {Lexer.Peek(0)}"); } // Ignore all remaining expressions while (IsExpressionStartToken()) { var expr = Expression(); // ignore, we don't need it if (Lexer.Peek() == Tokens.Comma) { PopExpected(Tokens.Comma); } } } PopExpected(Tokens.LBrace, Tokens.Begin); while (Lexer.Peek() != Tokens.RBrace && Lexer.Peek() != Tokens.IdEnd) { var dc = DialogControlEntry(); if (dc != null) { de.Entries.Add(dc); } } PopExpected(Tokens.RBrace, Tokens.IdEnd); return(de); }