public void TestInt() { var s = new IntConstant(123); var res = Util.IntConstant.Compile(s); HasValue(res, s.Value); }
// // Called back from Yield // public void MarkYield(EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point) { ILGenerator ig = ec.ig; // Store the new current ig.Emit(OpCodes.Ldarg_0); expr.Emit(ec); ig.Emit(OpCodes.Stfld, IteratorHost.CurrentField.FieldBuilder); // store resume program-counter ig.Emit(OpCodes.Ldarg_0); IntConstant.EmitInt(ig, resume_pc); ig.Emit(OpCodes.Stfld, IteratorHost.PC.FieldBuilder); // mark finally blocks as disabled if (unwind_protect && skip_finally != null) { ig.Emit(OpCodes.Ldc_I4_1); ig.Emit(OpCodes.Stloc, skip_finally); } // Return ok ig.Emit(unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok); ig.MarkLabel(resume_point); }
public static int EvaluateExpression(Expression exp, IToken token, Dictionary <string, Expression> constantDB) { try { if (constantDB.Count > 0) { exp = exp.ClearConstant(constantDB); } if (exp.HasVar) { List <string> vars = exp.GetVars(); throw new ParsingException(string.Format(Resources.Variables___0___can_not_be_used_in_this_expression_, Classes.Ultility.Ultility.PPStringList(vars)) + exp, token); } ExpressionValue rhv = EvaluatorDenotational.Evaluate(exp, null); if (rhv is IntConstant) { IntConstant v = rhv as IntConstant; return(v.Value); } else { throw new ParsingException(Resources.The_expression_should_return_an_integer_value_, token); } } catch (Exception ex) { throw new ParsingException(ex.Message, token); } }
public static void UpdateClockBounds(Expression expression, Dictionary <string, Expression> constantDB, int oldCeiling, int oldFloor, out int ceiling, out int floor) { try { if (constantDB.Count > 0) { expression = expression.ClearConstant(constantDB); } if (!expression.HasVar) { ExpressionValue rhv = EvaluatorDenotational.Evaluate(expression, null); if (rhv is IntConstant) { IntConstant v = rhv as IntConstant; ceiling = Math.Max(v.Value, oldCeiling); floor = Math.Min(v.Value, oldFloor); return; } } } catch (Exception ex) { } ceiling = oldCeiling; floor = oldFloor; }
public static void Test1() { int length = 100; int loop = 1; Valuation valuation = new Valuation(); Expression exp = new IntConstant(1); for (int i = 0; i < length; i++) { exp = new PrimitiveApplication(PrimitiveApplication.PLUS, exp, new IntConstant(1)); } Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond); for (int i = 0; i < loop; i++) { EvaluatorDenotational.Evaluate(exp, valuation); } Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond); DynamicMethod method = GetDynamicMethodOfExpression(exp); for (int i = 0; i < loop; i++) { method.Invoke(null, null); } Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond); Console.WriteLine("---------------------"); //--------------------------------------------------- exp = new Variable(var1); for (int i = 0; i < length; i++) { exp = new PrimitiveApplication(PrimitiveApplication.PLUS, exp, new Variable(var1)); } valuation.Variables = new StringDictionaryWithKey <ExpressionValue>(); valuation.Variables.Add(var1, new IntConstant(1)); Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond); for (int i = 0; i < loop; i++) { EvaluatorDenotational.Evaluate(exp, valuation); } Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond); method = GetDynamicMethodOfExpression(exp); for (int i = 0; i < loop; i++) { UpdateVarsBasedOnValuation(valuation); object value = method.Invoke(null, null); Console.WriteLine(value); UpdateValuationBasedOnClassValues(valuation); } Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond); }
public override void Emit(EmitContext ec) { // // Load Iterator storey instance // method.Storey.Instance.Emit(ec); // // Initialize iterator PC when it's unitialized // if (IsEnumerable) { ILGenerator ig = ec.ig; ig.Emit(OpCodes.Dup); IntConstant.EmitInt(ig, (int)State.Uninitialized); FieldInfo field = IteratorHost.PC.FieldBuilder; #if GMCS_SOURCE if (Storey.MemberName.IsGeneric) { field = TypeBuilder.GetField(Storey.Instance.Type, field); } #endif ig.Emit(OpCodes.Stfld, field); } }
public override Expression ClearConstant(List <string> avoidsVars, Dictionary <string, Expression> constMapping, bool needClone) { if (!needClone) { for (int j = 0; j < Matrix.Count; j++) { IntConstant[] array = Matrix[j]; for (int i = 0; i < array.Length; i++) { array[i] = array[i].ClearConstant(avoidsVars, constMapping, needClone) as IntConstant; } Matrix[j] = array; } return(this); } else { List <IntConstant[]> newmaxtrix = new List <IntConstant[]>(this.Matrix.Count); for (int j = 0; j < Matrix.Count; j++) { IntConstant[] array = Matrix[j]; IntConstant[] newArray = new IntConstant[array.Length]; for (int i = 0; i < array.Length; i++) { newArray[i] = array[i].ClearConstant(avoidsVars, constMapping, needClone) as IntConstant; } newmaxtrix.Add(newArray); } return(new Array(newmaxtrix)); } }
public override void Emit() { ResolveContext rc = new ResolveContext(this); IntConstant buffer_size_const = initializer.Resolve(rc) as IntConstant; if (buffer_size_const == null) { return; } int buffer_size = buffer_size_const.Value; if (buffer_size <= 0) { Report.Error(1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError()); return; } EmitFieldSize(buffer_size); #if STATIC if (Module.HasDefaultCharSet) { fixed_buffer_type.__SetAttributes(fixed_buffer_type.Attributes | Module.DefaultCharSetType); } #endif Module.PredefinedAttributes.UnsafeValueType.EmitAttribute(fixed_buffer_type); Module.PredefinedAttributes.CompilerGenerated.EmitAttribute(fixed_buffer_type); fixed_buffer_type.CreateType(); base.Emit(); }
//实型数组元素入栈 public void PushRealByIndexAddress() { IntConstant index = PopIntConst(); IntConstant address = PopIntConst(); operandStack.Push(heap.GetRealValue((int)address.Value, (int)index.Value)); }
protected override Expression DoResolve(ResolveContext ec) { Child = new IntConstant(ec.BuiltinTypes, (int)(flags | statement.flags), statement.loc); type = ec.Module.PredefinedTypes.BinderFlags.Resolve(); eclass = Child.eclass; return(this); }
public void ConstantTest() { var str1 = new StringConstant("abc"); var int1 = new IntConstant(1); var str2 = new StringConstant("abc"); var int2 = new IntConstant(1); Assert.True(str1.Equals(str2)); Assert.True(int1.Equals(int2)); }
public void EmitDispose(EmitContext ec) { ILGenerator ig = ec.ig; Label end = ig.DefineLabel(); Label [] labels = null; int n_resume_points = resume_points == null ? 0 : resume_points.Count; for (int i = 0; i < n_resume_points; ++i) { ResumableStatement s = (ResumableStatement)resume_points [i]; Label ret = s.PrepareForDispose(ec, end); if (ret.Equals(end) && labels == null) { continue; } if (labels == null) { labels = new Label [resume_points.Count + 1]; for (int j = 0; j <= i; ++j) { labels [j] = end; } } labels [i + 1] = ret; } if (labels != null) { current_pc = ec.GetTemporaryLocal(TypeManager.uint32_type); ig.Emit(OpCodes.Ldarg_0); ig.Emit(OpCodes.Ldfld, IteratorHost.PC.FieldBuilder); ig.Emit(OpCodes.Stloc, current_pc); } ig.Emit(OpCodes.Ldarg_0); IntConstant.EmitInt(ig, (int)State.After); ig.Emit(OpCodes.Stfld, IteratorHost.PC.FieldBuilder); if (labels != null) { //SymbolWriter.StartIteratorDispatcher (ec.ig); ig.Emit(OpCodes.Ldloc, current_pc); ig.Emit(OpCodes.Switch, labels); //SymbolWriter.EndIteratorDispatcher (ec.ig); foreach (ResumableStatement s in resume_points) { s.EmitForDispose(ec, this, end, true); } } ig.MarkLabel(end); }
/// <summary> /// Add local variable including state, and parameters /// Return the variable name encoding states /// </summary> /// <param name="encoder"></param> public string AddLocalVariables(BDDEncoder encoder) { RenameLocalVars(); for (int i = 0; i < this.Parameters.Count; i++) { string parameter = this.Parameters[i]; int min = 0; int max = 0; if (ParameterUpperBound.ContainsKey(parameter) && ParameterLowerBound.ContainsKey(parameter)) { min = ParameterLowerBound[parameter]; max = ParameterUpperBound[parameter]; } else { if (this.Arguments[i] is IntConstant) { IntConstant tempExp = (IntConstant)this.Arguments[i]; min = tempExp.Value; max = tempExp.Value; } else { throw new Exception("Symbolic Model Checking only support constant parameters!"); } } //In its old transition encoding, we don't make sure this variable must be unchanged. //We also need to add this variable to VaribleIndex of the AutomataBDD because previous process does not know this variable //if global then later processes will set this variable as unchange. encoder.model.AddLocalVar(parameter, min, max); } const string STATE = "state"; // string processVariableName = Name + Model.NAME_SEPERATOR + STATE + Model.GetNewTempVarName(); encoder.model.AddLocalVar(processVariableName, 0, this.States.Count - 1); // encoder.stateIndexOfCurrentProcess = new Dictionary <string, int>(); //collect the state index foreach (State state in this.States) { encoder.stateIndexOfCurrentProcess.Add(state.ID, encoder.stateIndexOfCurrentProcess.Count); } return(processVariableName); }
public Array(List <int> dimentions) { for (int i = 0; i < dimentions.Count; i++) { int size = dimentions[i]; IntConstant[] Associations = new IntConstant[size]; for (int j = 0; j < size; j++) { Associations[j] = new IntConstant(0); } Matrix.Add(Associations); } }
public Record2D(int size1, int size2) { Associations = new Expression[size1, size2]; for (int i = 0; i < size1; i++) { for (int j = 0; j < size2; j++) { Associations[i, j] = new IntConstant(0); } } ExpressionType = ExpressionType.Record; Size1 = size1; Size2 = size2; }
public override String ToString() { StringBuilder sb = new StringBuilder("["); foreach (IntConstant[] array in Matrix) { sb.Append("["); for (int i = 0; i < array.Length - 1; i++) { IntConstant var = array[i]; sb.Append(var + ", "); } sb.Append(array[array.Length - 1].ToString()); sb.Append("]"); } sb.Append("]"); return(sb.ToString()); }
//删除变量表 public void DeleteScope() { VariableTable variables = variableTableStack.GetTop(); List <IConstant> constants = variables.GetAll(); foreach (IConstant constant in constants) { if (constant.Type != NumericType.INT) { continue; } IntConstant intConstant = (IntConstant)constant; if (intConstant.Usage == IntUsage.ARRAYADDR) { heap.Free((int)intConstant.Value); } } variableTableStack.DropTop(); }
public override void Emit() { ResolveContext rc = new ResolveContext(this); IntConstant buffer_size_const = initializer.Resolve(rc) as IntConstant; if (buffer_size_const == null) { return; } int buffer_size = buffer_size_const.Value; if (buffer_size <= 0) { Report.Error(1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError()); return; } int type_size = Expression.GetTypeSize(MemberType); if (buffer_size > int.MaxValue / type_size) { Report.Error(1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit", GetSignatureForError(), buffer_size.ToString(), TypeManager.CSharpName(MemberType)); return; } EmitFieldSize(buffer_size); #if STATIC if (Module.HasDefaultCharSet) { fixed_buffer_type.__SetAttributes(fixed_buffer_type.Attributes | Module.DefaultCharSetType); } #endif Module.PredefinedAttributes.UnsafeValueType.EmitAttribute(fixed_buffer_type); Module.PredefinedAttributes.CompilerGenerated.EmitAttribute(fixed_buffer_type); fixed_buffer_type.CreateType(); base.Emit(); }
void EmitMoveNext_NoResumePoints(EmitContext ec, Block original_block) { ILGenerator ig = ec.ig; ig.Emit(OpCodes.Ldarg_0); ig.Emit(OpCodes.Ldfld, IteratorHost.PC.FieldBuilder); ig.Emit(OpCodes.Ldarg_0); IntConstant.EmitInt(ig, (int)State.After); ig.Emit(OpCodes.Stfld, IteratorHost.PC.FieldBuilder); // We only care if the PC is zero (start executing) or non-zero (don't do anything) ig.Emit(OpCodes.Brtrue, move_next_error); SymbolWriter.StartIteratorBody(ec.ig); original_block.Emit(ec); SymbolWriter.EndIteratorBody(ec.ig); ig.MarkLabel(move_next_error); ig.Emit(OpCodes.Ldc_I4_0); ig.Emit(OpCodes.Ret); }
protected override void DoEmit(EmitContext ec) { ILGenerator ig = ec.ig; Label label_init = ig.DefineLabel(); ig.Emit(OpCodes.Ldarg_0); ig.Emit(OpCodes.Ldflda, host.PC.FieldBuilder); IntConstant.EmitInt(ig, (int)Iterator.State.Start); IntConstant.EmitInt(ig, (int)Iterator.State.Uninitialized); ig.Emit(OpCodes.Call, TypeManager.int_interlocked_compare_exchange); IntConstant.EmitInt(ig, (int)Iterator.State.Uninitialized); ig.Emit(OpCodes.Bne_Un_S, label_init); ig.Emit(OpCodes.Ldarg_0); ig.Emit(OpCodes.Ret); ig.MarkLabel(label_init); new_storey.Emit(ec); ig.Emit(OpCodes.Ret); }
public override Node getNode(string[] args, Node parent) { Addition add = new Addition(); for (int i = 0; i < args.Length; i++) { if (Utils.IsDigitsOnly(args[i])) { IntConstant ic = new IntConstant(int.Parse(args[i])); ic.parent = add; add.branches.Add(ic); } else { VarRef iref = new IntRef(args[i]); iref.parent = add; add.branches.Add(iref); } } add.parent = parent; return(add); }
// 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 async Task <Expression> ParsePrimaryTailExpression() { Expression leftMost = null; if (await MaybeToken("statictype", true)) { if (!await MaybeToken("(", false)) { throw new NotImplementedException(); } leftMost = await ParseExpression(); if (leftMost == null) { throw new NotImplementedException(); } if (!await MaybeToken(")", false)) { throw new NotImplementedException(); } leftMost = new StaticTypeExpression { Expression = leftMost }; } else if (await MaybeToken("type", true)) { if (!await MaybeToken("(", false)) { throw new NotImplementedException(); } leftMost = await ParseType(); if (leftMost == null) { throw new NotImplementedException(); } if (!await MaybeToken(")", false)) { throw new NotImplementedException(); } } else if (await MaybeToken("tag", true)) { if (!await MaybeToken("(", false)) { throw new NotImplementedException(); } if (!await MaybeString()) { throw new NotImplementedException(); } string tag = LastString; if (!await MaybeToken(")", false)) { throw new NotImplementedException(); } return(new TagExpression { Tag = new StringConstant { Value = tag } }); } else if (await MaybeToken("(", false)) { // Parse a parenthetical expression leftMost = await ParseExpression(); if (leftMost == null) { throw new NotImplementedException(); } if (!await MaybeToken(")", false)) { throw new NotImplementedException(); } } else { leftMost = ParseUnary(); } if (leftMost != null) { } else if (await MaybeToken("null", true)) { // In theory, null cannot be dotwalked, called, etc. // but that might REALLY mess up our parsing leftMost = new NullExpression { }; } else if (await MaybeToken("true", true)) { leftMost = new BoolConstant { Value = true }; } else if (await MaybeToken("false", true)) { leftMost = new BoolConstant { Value = false }; } else if (await MaybeName()) { leftMost = new NameExpression { Name = LastName }; } else if (await MaybeInt()) { leftMost = new IntConstant { Value = LastInt }; } else if (await MaybeDouble()) { throw new NotImplementedException(); } else if (await MaybeString()) { leftMost = new StringConstant { Value = LastString }; } while (!eof) { if (leftMost is NameExpression ne && await MaybeToken("(", false)) { Expression[] args; if (await MaybeToken(")", false)) { args = new Expression[0]; } else { args = await ParseArgumentList(); if (!await MaybeToken(")", false)) { throw new NotImplementedException(); } } leftMost = new CallExpression { FunctionName = ne, Arguments = args }; }
public int CompareTo(Constant c) {//将当前常量的值与指定的常量c的值进行比较,返回它们的相对值的表示 IntConstant ic = (IntConstant)c; return(val.CompareTo(ic.val)); }
public override bool Equals(object obj) {//判断指定obj对象是否与当前常量相等 IntConstant ic = (IntConstant)obj; return(ic != null && val.Equals(ic.val)); }
//处理指令 private void ProcessIns(InstructionType insType, String arg) { switch (insType) { case InstructionType.NOP: core.Pass(); break; case InstructionType.LD_INT: core.PushIntConst(GetIntFromArg(arg), IntUsage.DEFAULT); break; case InstructionType.LD_REAL: core.PushRealConst(GetDoubleFromArg(arg)); break; case InstructionType.LD_VAR: core.PushVariable(arg); break; case InstructionType.LD_ELE_INT: core.PushIntByIndexAddress(); break; case InstructionType.LD_ELE_REAL: core.PushRealByIndexAddress(); break; case InstructionType.DUPTOP: core.Dup(); break; case InstructionType.ST_VAR: core.StoreVariable(arg); break; case InstructionType.ST_ADR: core.StoreValueIntoIndexOfArray(); break; case InstructionType.DC_VAR_INT: core.DeclareIntVar(arg); break; case InstructionType.DC_VAR_REAL: core.DeclareRealVar(arg); break; //case InstructionType.DC_VAR_ADR: // core.declareArrayVar(arg); // break; case InstructionType.DC_VAR_A_INT: core.DeclareIntArray(arg); break; case InstructionType.PUSH_VT: core.NewScope(); break; case InstructionType.POP_VT: core.DeleteScope(); break; case InstructionType.DC_FUN: core.DeclareFunction(arg, currentInsIndex + 1); currentInsIndex = FindIndexAfterEND_FC(); if(currentInsIndex == -1) { throw new Exception("cmm.vm::VirtualMachine::ProcessIns: 在定义函数指令后没有函数结束指令"); } return; case InstructionType.END_FUN: throw new Exception("cmm.vm::VirtualMachine::ProcessIns: 执行了不应该被执行的指令"); case InstructionType.ARG_INT: IConstant retAddr = core.PopOperand(); core.DeclareIntVar(arg); core.StoreVariable(arg); core.PushOperand(retAddr); break; case InstructionType.ARG_REAL: retAddr = core.PopOperand(); core.DeclareRealVar(arg); core.StoreVariable(arg); core.PushOperand(retAddr); break; case InstructionType.ARG_ADR: retAddr = core.PopOperand(); //数组地址是int类型 core.DeclareIntVar(arg); core.StoreVariable(arg); core.PushOperand(retAddr); break; case InstructionType.END_ARG: IntConstant retAddress = core.PopIntConst(); IntConstant stackFrame = new IntConstant((int)retAddress.Value, IntUsage.STACK_HEAD); core.PushOperand(stackFrame); break; case InstructionType.CALL_FUN: //存下一个地址为返回地址,供存入栈帧头使用 core.PushOperand(new IntConstant(currentInsIndex + 1, IntUsage.INSADDR)); core.NewScope(); //设置当前地址为函数地址 currentInsIndex = core.GetFunction(arg); return; case InstructionType.RETURN: IConstant retval = core.PopOperand(); IConstant stacdHeadCand = core.PopOperand(); while(stacdHeadCand.Type != NumericType.INT || ((IntConstant)stacdHeadCand).Usage != IntUsage.STACK_HEAD) { stacdHeadCand = core.PopOperand(); } core.PushOperand(retval); core.DeleteScope(); currentInsIndex = (int)stacdHeadCand.Value; return; case InstructionType.JUMPBY: currentInsIndex += GetIntFromArg(arg); return; case InstructionType.JBY_IF: int predicate = (int)core.PopIntConst().Value; if(predicate == 0) { break; } else { currentInsIndex += GetIntFromArg(arg); return; } case InstructionType.OP_ADD: CalAndPush(Add); break; case InstructionType.OP_SUB: CalAndPush(Sub); break; case InstructionType.OP_MUL: CalAndPush(Mul); break; case InstructionType.OP_DIV: CalAndPush(Div); break; case InstructionType.OP_EQL: CalAndPush(Equals); break; case InstructionType.OP_N_E: CalAndPush(NotEquals); break; case InstructionType.OP_GRT: CalAndPush(GreaterThan); break; case InstructionType.OP_G_E: CalAndPush(GreaterEquals); break; case InstructionType.OP_LES: CalAndPush(LessThan); break; case InstructionType.OP_L_E: CalAndPush(LessEquals); break; case InstructionType.OP_NOT: CalAndPush(Not); break; case InstructionType.OP_AND: CalAndPush(And); break; case InstructionType.OP_OR: CalAndPush(Or); break; case InstructionType.OP_NEG: CalAndPush(Neg); break; case InstructionType.RD_INT: ReadInt(); break; case InstructionType.RD_REAL: ReadReal(); break; case InstructionType.WRITE: Write(); break; } currentInsIndex++; }
public IntConstant makeIntegerConstantNode(int value) { IntConstant node = new IntConstant(value); return(node); }
internal void EmitMoveNext(EmitContext ec, Block original_block) { ILGenerator ig = ec.ig; move_next_ok = ig.DefineLabel(); move_next_error = ig.DefineLabel(); if (resume_points == null) { EmitMoveNext_NoResumePoints(ec, original_block); return; } current_pc = ec.GetTemporaryLocal(TypeManager.uint32_type); ig.Emit(OpCodes.Ldarg_0); ig.Emit(OpCodes.Ldfld, IteratorHost.PC.FieldBuilder); ig.Emit(OpCodes.Stloc, current_pc); // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit ig.Emit(OpCodes.Ldarg_0); IntConstant.EmitInt(ig, (int)State.After); ig.Emit(OpCodes.Stfld, IteratorHost.PC.FieldBuilder); Label [] labels = new Label [1 + resume_points.Count]; labels [0] = ig.DefineLabel(); bool need_skip_finally = false; for (int i = 0; i < resume_points.Count; ++i) { ResumableStatement s = (ResumableStatement)resume_points [i]; need_skip_finally |= s is ExceptionStatement; labels [i + 1] = s.PrepareForEmit(ec); } if (need_skip_finally) { skip_finally = ec.GetTemporaryLocal(TypeManager.bool_type); ig.Emit(OpCodes.Ldc_I4_0); ig.Emit(OpCodes.Stloc, skip_finally); } SymbolWriter.StartIteratorDispatcher(ec.ig); ig.Emit(OpCodes.Ldloc, current_pc); ig.Emit(OpCodes.Switch, labels); ig.Emit(OpCodes.Br, move_next_error); SymbolWriter.EndIteratorDispatcher(ec.ig); ig.MarkLabel(labels [0]); SymbolWriter.StartIteratorBody(ec.ig); original_block.Emit(ec); SymbolWriter.EndIteratorBody(ec.ig); SymbolWriter.StartIteratorDispatcher(ec.ig); ig.Emit(OpCodes.Ldarg_0); IntConstant.EmitInt(ig, (int)State.After); ig.Emit(OpCodes.Stfld, IteratorHost.PC.FieldBuilder); ig.MarkLabel(move_next_error); ig.Emit(OpCodes.Ldc_I4_0); ig.Emit(OpCodes.Ret); ig.MarkLabel(move_next_ok); ig.Emit(OpCodes.Ldc_I4_1); ig.Emit(OpCodes.Ret); SymbolWriter.EndIteratorDispatcher(ec.ig); }
/// <summary> /// Return Valuation in Configuration of given BDD configuration in the column form /// [ REFS: '', DEREFS: ''] /// </summary> /// <param name="currentStateDD">current BDD configuration</param> /// <param name="initialValuation">based on Initial Valuation to get the global variables</param> /// <returns>Corresponding Valuation of the BDD configuration</returns> public Valuation GetValuationFromBDD(CUDDNode currentStateDD, Valuation initialValuation) { Valuation currentValuation = initialValuation.GetClone(); if (currentValuation.Variables != null && currentValuation.Variables.Count > 0) { foreach (StringDictionaryEntryWithKey <ExpressionValue> pair in currentValuation.Variables._entries) { if (pair != null) { if (pair.Value is RecordValue) { RecordValue array = pair.Value as RecordValue; ExpressionValue[] arrayValue = new ExpressionValue[array.Associations.Length]; for (int i = 0; i < array.Associations.Length; i++) { string variableName = pair.Key + Model.NAME_SEPERATOR + i.ToString(); int value = model.GetColVarValue(currentStateDD, variableName); arrayValue[i] = new IntConstant(value); } pair.Value = new RecordValue(arrayValue); } else if (pair.Value is BoolConstant) { string variableName = pair.Key; int value = model.GetColVarValue(currentStateDD, variableName); pair.Value = new BoolConstant(value == 1); } else { string variableName = pair.Key; int value = model.GetColVarValue(currentStateDD, variableName); pair.Value = new IntConstant(value); } } } } if (currentValuation.Channels != null && currentValuation.Channels.Count > 0) { List <string> channelNames = new List <string>(currentValuation.Channels.Keys); foreach (string channelName in channelNames) { int count = model.GetColVarValue(currentStateDD, Model.GetCountVarChannel(channelName)); int top = model.GetColVarValue(currentStateDD, Model.GetTopVarChannel(channelName)); ChannelQueue currentQueue = new ChannelQueue(count); int firstElement = 0; if (top >= count) { firstElement = top - count; } else { firstElement = top - count + model.mapChannelToSize[channelName]; } for (int i = 0; i < count; i++) { int elementSize = model.GetColVarValue(currentStateDD, Model.GetArrayOfSizeElementChannel(channelName) + Model.NAME_SEPERATOR + firstElement); ExpressionValue[] elementValues = new ExpressionValue[elementSize]; //Find values in the message for (int j = 0; j < elementSize; j++) { int subElementIndex = firstElement * Model.MAX_MESSAGE_LENGTH + j; int value = model.GetColVarValue(currentStateDD, channelName + Model.NAME_SEPERATOR + subElementIndex.ToString()); elementValues[j] = new IntConstant(value); } //Add element to queue currentQueue.Enqueue(elementValues); //update to the next element firstElement = (firstElement + 1) % model.mapChannelToSize[channelName]; } currentValuation.Channels[channelName] = currentQueue; } } return(currentValuation); }
private CUDDNode EncodeIntConstant(IntConstant exp) { return(CUDD.Constant(exp.Value)); }