public static StackValue ConcatString(StackValue op1, StackValue op2, ProtoCore.Runtime.RuntimeMemory rmem) { StackValue[] v1 = op1.IsString ? rmem.GetArrayElements(op1) : new StackValue[] { op1 }; StackValue[] v2 = op2.IsString ? rmem.GetArrayElements(op2) : new StackValue[] { op2 }; StackValue tmp = rmem.BuildArray(v1.Concat(v2).ToArray()); return StackValue.BuildString(tmp.opdata); }
public void TestArrayLayerStatsSimple() { String code = @" a;b;c; [Imperative] { a = {1,2,3}; b = {1.0, 2.0, 3.0, 3.0}; c = {1.0, 2.0, 9}; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); var dict = ProtoCore.Utils.ArrayUtils.GetTypeStatisticsForLayer(svA, core); Assert.IsTrue(dict[dict.Keys.First()] == 3); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); var dict2 = ProtoCore.Utils.ArrayUtils.GetTypeStatisticsForLayer(svB, core); Assert.IsTrue(dict2[dict2.Keys.First()] == 4); ProtoCore.DSASM.StackValue svC = mirror.GetRawFirstValue("c"); var dict3 = ProtoCore.Utils.ArrayUtils.GetTypeStatisticsForLayer(svC, core); Assert.IsTrue(dict3[dict3.Keys.First()] == 2); Assert.IsTrue(dict3[dict3.Keys.Last()] == 1); // Assert.IsTrue((Int64)o.Payload == 5); }
public static void GCRelease(StackValue sv, Core core) { if (null != core.CurrentExecutive.CurrentDSASMExec) { core.CurrentExecutive.CurrentDSASMExec.GCRelease(sv); } }
public static void GCRetain(StackValue sv, Core core) { if (core.ExecMode != ProtoCore.DSASM.InterpreterMode.kExpressionInterpreter) { core.Heap.IncRefCount(sv); } }
public static StackValue ConcatString(StackValue op1, StackValue op2, ProtoCore.Core core) { var v1 = op1.IsString ? ArrayUtils.GetValues(op1, core) : new StackValue[] { op1 }; var v2 = op2.IsString ? ArrayUtils.GetValues(op2, core) : new StackValue[] { op2 }; StackValue tmp = core.Rmem.BuildArray(v1.Concat(v2).ToArray()); return StackValue.BuildString(tmp.opdata); }
public void StackValueDiffTestProperty01() { String code = @" class A { x : var; constructor A() { x = 20; } } [Imperative] { a = A.A(); b = 1.0; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); Assert.IsTrue(svA.metaData.type != svB.metaData.type); }
public bool RemoveKey(StackValue key) { if (key.IsNumeric) { long index = key.ToInteger().opdata; if (index < 0) { index = index + VisibleSize; } if (index >= 0 && index < VisibleSize) { SetItemAt((int)index, StackValue.Null); if (index == VisibleSize - 1) { VisibleSize -= 1; } return true; } } else { if (Dict != null && Dict.ContainsKey(key)) { Dict.Remove(key); return true; } } return false; }
public static StackValue ConcatString(StackValue op1, StackValue op2, ProtoCore.Runtime.RuntimeMemory rmem) { StackValue[] v1 = (AddressType.String == op1.optype) ? rmem.GetArrayElements(op1) : new StackValue[] { op1 }; StackValue[] v2 = (AddressType.String == op2.optype) ? rmem.GetArrayElements(op2) : new StackValue[] { op2 }; StackValue tmp = rmem.BuildArray(v1.Concat(v2).ToArray()); return StackUtils.BuildString(tmp.opdata); }
public void TestNonPointers01() { var heap = new Heap(); var values = new StackValue[] { StackValue.BuildInt(0), StackValue.BuildInt(1), StackValue.BuildInt(2) }; var array1 = heap.AllocateArray(values); var allTypes = new List<StackValue>(); var rawPointer = (int)array1.RawIntValue; for (int i = 0; i < (int)AddressType.ArrayKey; ++i) { var val = new StackValue() { optype = (AddressType)i, opdata = rawPointer }; if (!val.IsReferenceType) { allTypes.Add(val); } } var array2 = heap.AllocateArray(allTypes.ToArray()); heap.GCMarkAndSweep(new List<StackValue>() { array1}, testExecutive); Assert.IsNotNull(heap.ToHeapObject<DSArray>(array1)); heap.Free(); }
public static StackValue CoerceArray(StackValue array, Type typ, Core core) { //@TODO(Luke) handle array rank coersions Validity.Assert(IsArray(array), "Argument needs to be an array {99FB71A6-72AD-4C93-8F1E-0B1F419C1A6D}"); //This is the element on the heap that manages the data structure HeapElement heapElement = core.Heap.Heaplist[(int)array.opdata]; StackValue[] newSVs = new StackValue[heapElement.VisibleSize]; for (int i = 0; i < heapElement.VisibleSize; ++i) { StackValue sv = heapElement.Stack[i]; StackValue coercedValue; if (IsArray(sv)) { Type typ2 = new Type(); typ2.UID = typ.UID; typ2.rank = typ.rank - 1; typ2.IsIndexable = (typ2.rank == -1 || typ2.rank > 0); coercedValue = CoerceArray(sv, typ2, core); } else { coercedValue = TypeSystem.Coerce(sv, typ, core); } GCUtils.GCRetain(coercedValue, core); newSVs[i] = coercedValue; } return HeapUtils.StoreArray(newSVs, core); }
public static int CompareString(StackValue s1, StackValue s2, Core core) { if (!StackUtils.IsString(s1) || !StackUtils.IsString(s2)) { return ProtoCore.DSASM.Constants.kInvalidIndex; } HeapElement he1 = ArrayUtils.GetHeapElement(s1, core); HeapElement he2 = ArrayUtils.GetHeapElement(s2, core); int len1 = he1.VisibleSize; int len2 = he2.VisibleSize; int len = len1 > len2 ? len2 : len1; int i = 0; for (; i < len; ++i) { if (he1.Stack[i].opdata != he2.Stack[i].opdata) { return (he1.Stack[i].opdata > he2.Stack[i].opdata) ? 1 : -1; } } if (len1 > len2) return 1; else if (len1 == len2) return 0; else return -1; }
public void StackValueDiffTestDefect() { String code = @"[Imperative] { a = 1; b = 1.0; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); Assert.IsTrue(svA.metaData.type != svB.metaData.type); }
private void Init( StackValue thisPtr, int classIndex, int functionIndex, int returnAddress, int functionBlockIndex, int callerBlockIndex, StackFrameType callerStackFrameType, StackFrameType stackFrameType, int depth, int framePointer, int blockIndex, List<StackValue> registers, int execStateSize) { Frame = new StackValue[StackFrameSize]; Frame[AbsoluteIndex.ThisPtr] = thisPtr; Frame[AbsoluteIndex.ClassIndex] = StackValue.BuildClassIndex(classIndex); Frame[AbsoluteIndex.FunctionIndex] = StackValue.BuildFunctionIndex(functionIndex); Frame[AbsoluteIndex.ReturnAddress] = StackValue.BuildInt(returnAddress); Frame[AbsoluteIndex.FunctionBlockIndex] = StackValue.BuildBlockIndex(functionBlockIndex); Frame[AbsoluteIndex.CallerBlockIndex] = StackValue.BuildBlockIndex(callerBlockIndex); Frame[AbsoluteIndex.CallerStackFrameType] = StackValue.BuildFrameType((int)callerStackFrameType); Frame[AbsoluteIndex.StackFrameType] = StackValue.BuildFrameType((int)stackFrameType); Frame[AbsoluteIndex.StackFrameDepth] = StackValue.BuildInt(depth); Frame[AbsoluteIndex.LocalVariableCount] = StackValue.BuildInt(0); Frame[AbsoluteIndex.ExecutionStates] = StackValue.BuildInt(execStateSize); Frame[AbsoluteIndex.BlockIndex] = StackValue.BuildBlockIndex(blockIndex); Frame[AbsoluteIndex.RX] = registers[0]; Frame[AbsoluteIndex.TX] = registers[1]; Frame[AbsoluteIndex.FramePointer] = StackValue.BuildInt(framePointer); }
public static StackValue ConvertToString(StackValue sv, RuntimeCore runtimeCore, ProtoCore.Runtime.RuntimeMemory rmem) { StackValue returnSV; //TODO: Change Execution mirror class to have static methods, so that an instance does not have to be created ProtoCore.DSASM.Mirror.ExecutionMirror mirror = new DSASM.Mirror.ExecutionMirror(new ProtoCore.DSASM.Executive(runtimeCore), runtimeCore); returnSV = ProtoCore.DSASM.StackValue.BuildString(mirror.GetStringValue(sv, runtimeCore.RuntimeMemory.Heap, 0, true), runtimeCore.RuntimeMemory.Heap); return returnSV; }
public static ProtoCore.DSASM.StackValue ConvertToString(ProtoCore.DSASM.StackValue sv, Core core, ProtoCore.Runtime.RuntimeMemory rmem) { ProtoCore.DSASM.StackValue returnSV; //TODO: Change Execution mirror class to have static methods, so that an instance does not have to be created ProtoCore.DSASM.Mirror.ExecutionMirror mirror = new DSASM.Mirror.ExecutionMirror(new ProtoCore.DSASM.Executive(core), core); returnSV = ProtoCore.DSASM.StackUtils.BuildString(mirror.GetStringValue(sv, core.Heap, 0, true), core.Heap); return(returnSV); }
internal static void CompareCores(Core c1, Core c2) { Assert.AreEqual(c1.DSExecutable.runtimeSymbols.Length, c2.DSExecutable.runtimeSymbols.Length); for (int symTableIndex = 0; symTableIndex < c1.DSExecutable.runtimeSymbols.Length; symTableIndex++) { foreach (SymbolNode symNode in c1.DSExecutable.runtimeSymbols[symTableIndex].symbolList.Values) { ExecutionMirror runExecMirror = new ExecutionMirror(c1.CurrentExecutive.CurrentDSASMExec, c1); ExecutionMirror debugExecMirror = new ExecutionMirror(c2.CurrentExecutive.CurrentDSASMExec, c2); bool lookupOk = false; StackValue runValue = new StackValue(); if (symNode.name.StartsWith("%") || symNode.functionIndex != Constants.kInvalidIndex) continue; //Don't care about internal variables try { runValue = runExecMirror.GetGlobalValue(symNode.name); Console.WriteLine(symNode.name + ": " + runValue); lookupOk = true; } catch (NotImplementedException) { } catch (Exception ex) { if ((ex is ArgumentOutOfRangeException || ex is IndexOutOfRangeException) && (c1.RunningBlock != symNode.runtimeTableIndex)) { // Quite possible that variables defined in the inner // language block have been garbage collected and // stack frame pointer has been adjusted when return // to the outer block. } else { throw ex; } } if (lookupOk) { StackValue debugValue = debugExecMirror.GetGlobalValue(symNode.name); if (!StackUtils.CompareStackValues(debugValue, runValue, c2, c1)) { Assert.Fail(string.Format("\tThe value of variable \"{0}\" doesn't match in run mode and in debug mode.\n", symNode.name)); } } } } }
internal void Print(StackValue sv, int lineNo, string symbolName, int ci = Constants.kInvalidIndex) { //TODO: Change Execution mirror class to have static methods, so that an instance does not have to be created ProtoCore.DSASM.Mirror.ExecutionMirror mirror = new ProtoCore.DSASM.Mirror.ExecutionMirror(this, RuntimeCore); string result = mirror.GetStringValue(sv, RuntimeCore.RuntimeMemory.Heap, 0, true); TextOutputStream tStream = RuntimeCore.RuntimeStatus.MessageHandler as TextOutputStream; if (tStream != null) { Dictionary<int, List<string>> map = tStream.Map; //foreach(var kv in tStream.Map) if (!map.ContainsKey(lineNo)) return; List<string> expressions = map[lineNo]; foreach (var exp in expressions) { // Get lhs symbol name string lhsName = null; int index = exp.IndexOf('.'); if (index != -1) { string[] parts = exp.Split('.'); lhsName = parts[parts.Length - 1]; } else { Match m = Regex.Match(exp, @"(\w+)"); if (m.Success) { lhsName = m.Groups[1].Value; } } if (lhsName.Equals(symbolName)) { // Add to map Expression expStruct = new Expression(lineNo, exp, ci); if (ExpressionMap.ContainsKey(expStruct)) { List<string> values = ExpressionMap[expStruct]; values.Add(result); } else { List<string> values = new List<string>(); values.Add(result); ExpressionMap.Add(expStruct, values); } } } } }
public static StackValue ConcatString(StackValue op1, StackValue op2, ProtoCore.Core core) { var v1 = op1.IsString ? ArrayUtils.GetValues(op1, core) : new StackValue[] { op1 }; var v2 = op2.IsString ? ArrayUtils.GetValues(op2, core) : new StackValue[] { op2 }; var v = v1.Concat(v2).ToList(); v.ForEach(x => core.Heap.IncRefCount(x)); StackValue tmp = core.Heap.AllocateArray(v); return StackValue.BuildString(tmp.opdata); }
public override object Execute(ProtoCore.Runtime.Context context, ProtoCore.DSASM.Interpreter dsi) { int paramCount = mArgTypes.Count; int envSize = IsDNI ? 2 : 0; int totalParamCount = paramCount + envSize; List <Object> parameters = new List <object>(); List <ProtoCore.DSASM.StackValue> s = dsi.runtime.rmem.Stack; if (IsDNI) { parameters.Add(DLLFFIHandler.Env); parameters.Add((Int64)0); } for (int i = 0; i < mArgTypes.Count; ++i) { // Comment Jun: FFI function stack frames do not contain locals int locals = 0; int relative = 0 - ProtoCore.DSASM.StackFrame.kStackFrameSize - locals - i - 1; ProtoCore.DSASM.StackValue o = dsi.runtime.rmem.GetAtRelative(relative); if (o.optype == ProtoCore.DSASM.AddressType.Int) { if (mArgTypes[i].Name == "double") { // if the function expects a double and we have passed an int // in an int then promote it to be a double! // parameters.Add(o.opdata_d); } else { parameters.Add(o.opdata); } } else if (o.optype == ProtoCore.DSASM.AddressType.Double) { parameters.Add(o.opdata_d); } else if (o.optype == ProtoCore.DSASM.AddressType.ArrayPointer) { int size = 0; object array = GetArray(o, dsi, out size); parameters.Add(array); parameters.Add(size); } else { throw new NotSupportedException(); } } //object ret = mFunction.Invoke(parameters); object ret = mFunction.Execute(parameters.ToArray()); return(ConvertReturnValue(ret, context, dsi)); }
/// <summary> /// Take an array of already allocated StackValues and push them into the heap /// Returning the stack value that represents the array /// </summary> /// <param name="arrayElements"></param> /// <param name="core"></param> /// <returns></returns> public static StackValue StoreArray(StackValue[] arrayElements, Core core) { Heap heap = core.Heap; lock (heap.cslock) { int ptr = heap.Allocate(arrayElements); // ++heap.Heaplist[ptr].Refcount; StackValue overallSv = StackUtils.BuildArrayPointer(ptr); return overallSv; } }
/// <summary> /// Take an array of already allocated StackValues and push them into /// the heap and returning the stack value that represents the array /// </summary> /// <param name="elements"></param> /// <param name="core"></param> /// <returns></returns> public static StackValue StoreArray(StackValue[] elements, Dictionary<StackValue, StackValue> dict, Core core) { Heap heap = core.Heap; lock (heap.cslock) { int ptr = heap.Allocate(elements); StackValue overallSv = StackValue.BuildArrayPointer(ptr); heap.Heaplist[ptr].Dict = dict; return overallSv; } }
public void DecRefCount(StackValue sv) { if (!StackUtils.IsReferenceType(sv)) { return; } int ptr = (int)sv.opdata; Debug.Assert(this.Heaplist[ptr].Refcount > 0); this.Heaplist[ptr].Refcount--; }
public static int CompareString(StackValue s1, StackValue s2, RuntimeCore runtimeCore) { if (!s1.IsString || !s2.IsString) return Constants.kInvalidIndex; if (s1.Equals(s2)) return 0; string str1 = runtimeCore.RuntimeMemory.Heap.ToHeapObject<DSString>(s1).Value; string str2 = runtimeCore.RuntimeMemory.Heap.ToHeapObject<DSString>(s2).Value; return string.Compare(str1, str2); }
/// <summary> /// If the passed in value is not an array or an empty array or an array which contains only empty arrays, return false. /// Otherwise, return true; /// </summary> /// <param name="sv"></param> /// <param name="core"></param> /// <returns></returns> public static bool ContainsNonArrayElement(StackValue sv, Core core) { if (!StackUtils.IsArray(sv)) return true; StackValue[] svArray = core.Rmem.GetArrayElements(sv); foreach (var item in svArray) { if (ContainsNonArrayElement(item, core)) return true; } return false; }
public void TestArrayRankJagged() { String code = @" a;b;c;d;e; [Imperative] { a = {1,{2},3}; b = {1.0, {2.0, 3.0, 3.0}}; c = {1.0, {2.0, {9}}}; d = {{1}, {}, {1}}; e = {{1, 2, 3}, {1, {2}, 3}, {{{1}}, 2, 3}}; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); ProtoCore.DSASM.StackValue svC = mirror.GetRawFirstValue("c"); ProtoCore.DSASM.StackValue svD = mirror.GetRawFirstValue("d"); ProtoCore.DSASM.StackValue svE = mirror.GetRawFirstValue("e"); var a = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svA, core); Assert.IsTrue(a == 2); var b = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svB, core); Assert.IsTrue(b == 2); var c = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svC, core); Assert.IsTrue(c == 3); var d = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svD, core); Assert.IsTrue(d == 2); var e = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svE, core); Assert.IsTrue(e == 4); // Assert.IsTrue((Int64)o.Payload == 5); }
/// <summary> /// Returns true if array contain key or not. /// </summary> /// <param name="array"></param> /// <param name="key"></param> /// <param name="core"></param> /// <returns></returns> public bool ContainsKey(StackValue key) { if (key.IsNumeric) { int index = (int)key.ToInteger().IntegerValue; if (index < 0) { index = index + Count; } return (index >= 0 && index < Count); } else { return Dict != null && Dict.ContainsKey(key); } }
/// <summary> /// Check if an array contain key /// </summary> /// <param name="array"></param> /// <param name="key"></param> /// <param name="core"></param> /// <returns></returns> public bool ContainsKey(StackValue key) { if (key.IsNumeric) { long index = key.ToInteger().opdata; if (index < 0) { index = index + VisibleSize; } return (index >= 0 && index < VisibleSize); } else { return Dict != null && Dict.ContainsKey(key); } }
public FunctionPointerEvaluator(StackValue pointer, Interpreter dsi) { Validity.Assert(pointer.optype == AddressType.FunctionPointer); mRunTime = dsi; Core core = dsi.runtime.Core; int fptr = (int)pointer.opdata; ProtoCore.DSASM.FunctionPointerNode fptrNode; if (core.FunctionPointerTable.functionPointerDictionary.TryGetByFirst(fptr, out fptrNode)) { int blockId = fptrNode.blockId; int procId = fptrNode.procId; mProcNode = dsi.runtime.exe.procedureTable[blockId].procList[procId]; } mCallSite = new ProtoCore.CallSite(ProtoCore.DSASM.Constants.kGlobalScope, Name, core.FunctionTable, core.Options.ExecutionMode); }
public int GetType(ProtoCore.DSASM.StackValue sv) { int type = (int)ProtoCore.DSASM.Constants.kInvalidIndex; if (sv.IsReferenceType()) { type = (int)sv.metaData.type; } else { if (!addressTypeClassMap.TryGetValue(sv.optype, out type)) { type = (int)PrimitiveType.kInvalidType; } } return(type); }
public void TestBasic() { var heap = new Heap(); var values = new StackValue[] { StackValue.BuildInt(0), StackValue.BuildInt(1), StackValue.BuildInt(2) }; var array = heap.AllocateArray(values); var str = heap.AllocateString("hello world"); heap.GCMarkAndSweep(new List<StackValue>(), testExecutive); Assert.IsNull(heap.ToHeapObject<DSArray>(array)); Assert.IsNull(heap.ToHeapObject<DSArray>(str)); }
private void Init(StackValue svThisPtr, int classIndex, int funcIndex, int pc, int functionBlockDecl, int functionBlockCaller, StackFrameType callerType, StackFrameType type, int depth, int framePointer, List<StackValue> stack, List<bool> execStates) { Validity.Assert((int)StackFrame.AbsoluteIndex.kSize == kStackFrameSize); Frame = new StackValue[kStackFrameSize]; Frame[(int)AbsoluteIndex.kFramePointer] = StackValue.BuildInt(framePointer); Frame[(int)AbsoluteIndex.kStackFrameType] = StackValue.BuildFrameType((int)type); Frame[(int)AbsoluteIndex.kCallerStackFrameType] = StackValue.BuildFrameType((int)callerType); Frame[(int)AbsoluteIndex.kStackFrameDepth] = StackValue.BuildInt(depth); Frame[(int)AbsoluteIndex.kFunctionCallerBlock] = StackValue.BuildBlockIndex(functionBlockCaller); Frame[(int)AbsoluteIndex.kFunctionBlock] = StackValue.BuildBlockIndex(functionBlockDecl); Frame[(int)AbsoluteIndex.kReturnAddress] = StackValue.BuildInt(pc); Frame[(int)AbsoluteIndex.kFunction] = StackValue.BuildInt(funcIndex); Frame[(int)AbsoluteIndex.kClass] = StackValue.BuildInt(classIndex); Frame[(int)AbsoluteIndex.kThisPtr] = svThisPtr; Frame[(int)AbsoluteIndex.kRegisterAX] = stack[0]; Frame[(int)AbsoluteIndex.kRegisterBX] = stack[1]; Frame[(int)AbsoluteIndex.kRegisterCX] = stack[2]; Frame[(int)AbsoluteIndex.kRegisterDX] = stack[3]; Frame[(int)AbsoluteIndex.kRegisterEX] = stack[4]; Frame[(int)AbsoluteIndex.kRegisterFX] = stack[5]; Frame[(int)AbsoluteIndex.kRegisterLX] = stack[6]; Frame[(int)AbsoluteIndex.kRegisterRX] = stack[7]; Frame[(int)AbsoluteIndex.kRegisterSX] = stack[8]; Frame[(int)AbsoluteIndex.kRegisterTX] = stack[9]; int execStateSize = 0; if (null != execStates) { execStateSize = execStates.Count; ExecutionStates = new StackValue[execStateSize]; for (int n = 0; n < execStateSize; ++n) { ExecutionStates[n] = StackValue.BuildBoolean(execStates[n]); } } Frame[(int)AbsoluteIndex.kExecutionStates] = StackValue.BuildInt(execStateSize); Frame[(int)AbsoluteIndex.kLocalVariables] = StackValue.BuildInt(0); Validity.Assert(kStackFrameSize == Frame.Length); }
/// <summary> /// Whether sv is double or arrays contains double value. /// </summary> /// <param name="sv"></param> /// <param name="core"></param> /// <returns></returns> public static bool ContainsDoubleElement(StackValue sv, Core core) { if (!IsArray(sv)) return core.TypeSystem.GetType(sv) == (int)PrimitiveType.kTypeDouble; StackValue[] svArray = core.Rmem.GetArrayElements(sv); foreach (var item in svArray) { if (IsArray(item) && ContainsDoubleElement(item, core)) return true; if (core.TypeSystem.GetType(item) == (int)PrimitiveType.kTypeDouble) { return true; } } return false; }
private static List<ElementAtLevel> GetElementsAtLevel(StackValue argument, int level, List<int> indices, bool recordIndices, RuntimeCore runtimeCore) { var array = runtimeCore.Heap.ToHeapObject<DSArray>(argument); if (array == null) { return new List<ElementAtLevel>(); } int count = array.Values.Count(); if (level == 0) { return array.Values.Zip(Enumerable.Range(0, count), (v, i) => { if (recordIndices) { var newIndices = new List<int>(indices); newIndices.Add(i); return new ElementAtLevel(v, newIndices); } else { return new ElementAtLevel(v); } }).ToList(); } else { return array.Values.Zip(Enumerable.Range(0, count), (v, i) => { if (recordIndices) { var newIndices = new List<int>(indices); newIndices.Add(i); return GetElementsAtLevel(v, level - 1, newIndices, recordIndices, runtimeCore); } else { return GetElementsAtLevel(v, level - 1, new List<int>(), recordIndices, runtimeCore); } }).SelectMany(vs => vs).ToList(); } }
public FunctionPointerEvaluator(StackValue pointer, Interpreter dsi) { Validity.Assert(pointer.IsFunctionPointer); interpreter = dsi; RuntimeCore runtimeCore = dsi.runtime.RuntimeCore; int fptr = (int)pointer.opdata; FunctionPointerNode fptrNode; int classScope = Constants.kGlobalScope; if (runtimeCore.DSExecutable.FuncPointerTable.functionPointerDictionary.TryGetByFirst(fptr, out fptrNode)) { int blockId = fptrNode.blockId; int procId = fptrNode.procId; classScope = fptrNode.classScope; procNode = dsi.runtime.GetProcedureNode(blockId, classScope, procId); } callsite = new ProtoCore.CallSite(classScope, Name, interpreter.runtime.exe.FunctionTable, runtimeCore.Options.ExecutionMode); }
public void IsArrayTest() { String code = @"[Imperative] { a = {1,2,3}; b = 1; c = a; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); ProtoCore.DSASM.StackValue svC = mirror.GetRawFirstValue("c"); Assert.IsTrue(ProtoCore.Utils.ArrayUtils.IsArray(svA)); Assert.IsTrue(!ProtoCore.Utils.ArrayUtils.IsArray(svB)); Assert.IsTrue(ProtoCore.Utils.ArrayUtils.IsArray(svC)); }
public void TestBasic() { var heap = new Heap(); var values = new StackValue[] { StackValue.BuildInt(0), StackValue.BuildInt(1), StackValue.BuildInt(2) }; var array = heap.AllocateArray(values); var str = heap.AllocateString("hello world"); heap.GCMarkAndSweep(new List<StackValue>(), testExecutive); HeapElement arrayHeapElement; Assert.IsFalse(heap.TryGetHeapElement(array, out arrayHeapElement)); HeapElement strHeapElement; Assert.IsFalse(heap.TryGetHeapElement(str, out strHeapElement)); }
/// <summary> /// Check if an array contain key /// </summary> /// <param name="array"></param> /// <param name="key"></param> /// <param name="core"></param> /// <returns></returns> public static bool ContainsKey(StackValue array, StackValue key, Core core) { Validity.Assert(StackUtils.IsArray(array)); if (!StackUtils.IsArray(array)) { return false; } HeapElement he = GetHeapElement(array, core); if (StackUtils.IsNumeric(key)) { long index = key.AsInt().opdata; if (index < 0) { index = index + he.VisibleSize; } return (index >= 0 && index < he.VisibleSize); } else { return he.Dict != null && he.Dict.ContainsKey(key); } }
public void Push(double val) { runtime.rmem.Push(StackValue.BuildDouble(val)); }
public void Push(StackValue val) { runtime.rmem.Push(val); }
public StackFrame(StackValue svThisPtr, int classIndex, int funcIndex, int pc, int functionBlockDecl, int functionBlockCaller, StackFrameType callerType, StackFrameType type, int depth, int framePointer, List <StackValue> stack, List <bool> execStates) { Init(svThisPtr, classIndex, funcIndex, pc, functionBlockDecl, functionBlockCaller, callerType, type, depth, framePointer, stack, execStates); }
//this method compares the values of the stack variables passed public static bool CompareStackValues(StackValue sv1, StackValue sv2, RuntimeCore rtCore1, RuntimeCore rtCore2, ProtoCore.Runtime.Context context = null) { if (sv1.optype != sv2.optype) { return(false); } switch (sv1.optype) { case AddressType.Invalid: return(true); case AddressType.Int: return(sv1.IntegerValue == sv2.IntegerValue); case AddressType.Char: return(sv1.CharValue == sv2.CharValue); case AddressType.Double: var value1 = sv1.DoubleValue; var value2 = sv2.DoubleValue; if (Double.IsInfinity(value1) && Double.IsInfinity(value2)) { return(true); } return(MathUtils.Equals(value1, value2)); case AddressType.Boolean: return(sv1.BooleanValue == sv2.BooleanValue); case AddressType.ArrayPointer: if (Object.ReferenceEquals(rtCore1, rtCore2) && sv1.ArrayPointer == sv2.ArrayPointer) //if both cores are same and the stack values point to the same heap element, then the stack values are equal { return(true); } DSArray array1 = rtCore1.Heap.ToHeapObject <DSArray>(sv1); DSArray array2 = rtCore2.Heap.ToHeapObject <DSArray>(sv2); return(DSArray.CompareFromDifferentCore(array1, array2, rtCore1, rtCore2, context)); case AddressType.String: if (Object.ReferenceEquals(rtCore1, rtCore2) && sv1.StringPointer == sv2.StringPointer) //if both cores are same and the stack values point to the same heap element, then the stack values are equal { return(true); } DSString s1 = rtCore1.Heap.ToHeapObject <DSString>(sv1); DSString s2 = rtCore1.Heap.ToHeapObject <DSString>(sv2); return(s1.Equals(s2)); case AddressType.Pointer: if (sv1.metaData.type != sv2.metaData.type) //if the type of class is different, then stack values can never be equal { return(false); } if (Object.ReferenceEquals(rtCore1, rtCore2) && sv1.Pointer == sv2.Pointer) //if both cores are same and the stack values point to the same heap element, then the stack values are equal { return(true); } ClassNode classnode = rtCore1.DSExecutable.classTable.ClassNodes[sv1.metaData.type]; if (classnode.IsImportedClass) { var helper = ProtoFFI.DLLFFIHandler.GetModuleHelper(ProtoFFI.FFILanguage.CSharp); var marshaller1 = helper.GetMarshaler(rtCore1); var marshaller2 = helper.GetMarshaler(rtCore2); try { //the interpreter is passed as null as it is not expected to be sued while unmarshalling in this scenario object dsObject1 = marshaller1.UnMarshal(sv1, context, null, typeof(Object)); object dsObject2 = marshaller2.UnMarshal(sv2, context, null, typeof(Object)); //cores are different in debugger nunit testing only. Most of the imported objects don't have implementation of Object.Equals. It //also does not make sense to compare these objects deeply, as only dummy objects are created in nunit testing, and these dummy objects //might have random values. So we just check whether the object tpye is the same for this testing. if (!object.ReferenceEquals(rtCore1, rtCore2)) { return(Object.ReferenceEquals(dsObject1.GetType(), dsObject2.GetType())); } return(Object.Equals(dsObject1, dsObject2)); } catch (System.Exception) { return(false); } } else { return(ComparePointerFromHeap(sv1, sv2, rtCore1, rtCore2, context)); } default: return(sv1.Equals(sv2)); } }
public void SetPointer(StackValue pointer) { this.Pointer = pointer; }
/// <summary> /// Allocate string. /// </summary> /// <param name="str"></param> /// <returns></returns> public StackValue AllocateString(string str) { int index = AllocateStringInternal(str); return(StackValue.BuildString(index)); }
public static bool IsNull(StackValue operand) { return(operand.optype == AddressType.Null); }
public override object Execute(ProtoCore.Runtime.Context c, Interpreter dsi) { int nParamCount = mArgTypes.Length; int paramCount = mArgTypes.Length; int envSize = IsDNI ? 2 : 0; int totalParamCount = paramCount + envSize; List <Object> parameters = new List <object>(); List <ProtoCore.DSASM.StackValue> s = dsi.runtime.rmem.Stack; Object thisObject = null; FFIObjectMarshler marshaller = Module.GetMarshaller(dsi.runtime.Core); if (!ReflectionInfo.IsStatic) { try { thisObject = marshaller.UnMarshal(s.Last(), c, dsi, ReflectionInfo.DeclaringType); } catch (InvalidOperationException) { string message = String.Format(ProtoCore.RuntimeData.WarningMessage.kFFIFailedToObtainThisObject, ReflectionInfo.DeclaringType.Name, ReflectionInfo.Name); dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, message); return(null); } if (thisObject == null) { return(null); //Can't call a method on null object. } } ParameterInfo[] paraminfos = ReflectionInfo.GetParameters(); for (int i = 0; i < mArgTypes.Length; ++i) { // Comment Jun: FFI function stack frames do not contain locals int locals = 0; int relative = 0 - ProtoCore.DSASM.StackFrame.kStackFrameSize - locals - i - 1; ProtoCore.DSASM.StackValue opArg = dsi.runtime.rmem.GetAtRelative(relative); try { Type paramType = paraminfos[i].ParameterType; object param = marshaller.UnMarshal(opArg, c, dsi, paramType); //null is passed for a value type, so we must return null //rather than interpreting any value from null. fix defect 1462014 if (!paramType.IsGenericType && paramType.IsValueType && param == null) { throw new System.InvalidCastException(string.Format("Null value cannot be cast to {0}", paraminfos[i].ParameterType.Name)); } parameters.Add(param); } catch (System.InvalidCastException ex) { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ex.Message); return(null); } catch (InvalidOperationException) { string message = String.Format(ProtoCore.RuntimeData.WarningMessage.kFFIFailedToObtainObject, paraminfos[i].ParameterType.Name, ReflectionInfo.DeclaringType.Name, ReflectionInfo.Name); dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, message); return(null); } } object ret = null; StackValue dsRetValue = StackUtils.BuildNull(); try { ret = InvokeFunctionPointer(thisObject, parameters.Count > 0 ? parameters.ToArray() : null); //Reduce to singleton if the attribute is specified. ret = ReflectionInfo.ReduceReturnedCollectionToSingleton(ret); dsRetValue = marshaller.Marshal(ret, c, dsi, mReturnType); } catch (DllNotFoundException ex) { if (ex.InnerException != null) { dsi.LogSemanticError(ex.InnerException.Message); } dsi.LogSemanticError(ex.Message); } catch (System.Reflection.TargetException ex) { if (ex.InnerException != null) { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ex.InnerException.Message); } dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ex.Message); } catch (System.Reflection.TargetInvocationException ex) { if (ex.InnerException != null) { System.Exception exc = ex.InnerException; if (exc is System.ArgumentException) { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kInvalidArguments, ErrorString(exc)); } else if (exc is System.NullReferenceException) { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ErrorString(null)); } else { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ErrorString(exc)); } } else { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ErrorString(ex)); } } catch (System.Reflection.TargetParameterCountException ex) { if (ex.InnerException != null) { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ex.InnerException.Message); } dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ex.Message); } catch (System.MethodAccessException ex) { if (ex.InnerException != null) { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ex.InnerException.Message); } dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ex.Message); } catch (System.InvalidOperationException ex) { if (ex.InnerException != null) { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ex.InnerException.Message); } dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ex.Message); } catch (System.NotSupportedException ex) { if (ex.InnerException != null) { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ex.InnerException.Message); } dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kAccessViolation, ex.Message); } catch (System.ArgumentException ex) { if (ex.InnerException != null) { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kInvalidArguments, ErrorString(ex.InnerException)); } else { dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kInvalidArguments, ErrorString(ex)); } } catch (Exception ex) { if (ex.InnerException != null) { dsi.LogSemanticError(ErrorString(ex.InnerException)); } dsi.LogSemanticError(ErrorString(ex)); } return(dsRetValue); }
public static bool IsValidPointer(StackValue operand) { return(operand.optype == AddressType.Pointer && operand.opdata != ProtoCore.DSASM.Constants.kInvalidIndex); }
public static bool IsReferenceType(this StackValue operand) { return((operand.optype == AddressType.ArrayPointer || operand.optype == AddressType.Pointer || operand.optype == AddressType.String) && ProtoCore.DSASM.Constants.kInvalidIndex != operand.opdata); }
//this method compares the values of the stack variables passed public static bool CompareStackValues(StackValue sv1, StackValue sv2, Core c1, Core c2, ProtoCore.Runtime.Context context = null) { if (sv1.optype != sv2.optype) { return(false); } switch (sv1.optype) { case AddressType.Int: case AddressType.Char: return(sv1.opdata == sv2.opdata); case AddressType.Double: if (Double.IsInfinity(sv1.opdata_d) && Double.IsInfinity(sv2.opdata_d)) { return(true); } return(MathUtils.Equals(sv1.opdata_d, sv2.opdata_d)); case AddressType.Boolean: return((sv1.opdata > 0 && sv2.opdata > 0) || (sv1.opdata == 0 && sv2.opdata == 0)); case AddressType.ArrayPointer: case AddressType.String: if (Object.ReferenceEquals(c1, c2) && sv1.opdata == sv2.opdata) //if both cores are same and the stack values point to the same heap element, then the stack values are equal { return(true); } return(CompareStackValuesFromHeap(sv1, sv2, c1, c2, context)); case AddressType.Pointer: if (sv1.metaData.type != sv2.metaData.type) //if the type of class is different, then stack values can never be equal { return(false); } if (Object.ReferenceEquals(c1, c2) && sv1.opdata == sv2.opdata) //if both cores are same and the stack values point to the same heap element, then the stack values are equal { return(true); } ClassNode classnode = c1.DSExecutable.classTable.ClassNodes[(int)sv1.metaData.type]; if (classnode.IsImportedClass) { var helper = ProtoFFI.DLLFFIHandler.GetModuleHelper(ProtoFFI.FFILanguage.CSharp); var marshaller1 = helper.GetMarshaller(c1); var marshaller2 = helper.GetMarshaller(c2); try { //the interpreter is passed as null as it is not expected to be sued while unmarshalling in this scenario object dsObject1 = marshaller1.UnMarshal(sv1, context, null, typeof(Object)); object dsObject2 = marshaller2.UnMarshal(sv2, context, null, typeof(Object)); //cores are different in debugger nunit testing only. Most of the imported objects don't have implementation of Object.Equals. It //also does not make sense to compare these objects deeply, as only dummy objects are created in nunit testing, and these dummy objects //might have random values. So we just check whether the object tpye is the same for this testing. if (!object.ReferenceEquals(c1, c2)) { return(Object.ReferenceEquals(dsObject1.GetType(), dsObject2.GetType())); } return(Object.Equals(dsObject1, dsObject2)); } catch (System.Exception) { return(false); } } else { return(CompareStackValuesFromHeap(sv1, sv2, c1, c2, context)); } default: return(sv1.opdata == sv2.opdata); } }
internal void Print(ProtoCore.DSASM.StackValue sv, int lineNo, string symbolName, int ci = Constants.kInvalidIndex) { //TODO: Change Execution mirror class to have static methods, so that an instance does not have to be created ProtoCore.DSASM.Mirror.ExecutionMirror mirror = new ProtoCore.DSASM.Mirror.ExecutionMirror(this, Core); string result = mirror.GetStringValue(sv, Core.Heap, 0, true); TextOutputStream tStream = Core.RuntimeStatus.MessageHandler as TextOutputStream; if (tStream != null) { Dictionary <int, List <string> > map = tStream.Map; //foreach(var kv in tStream.Map) if (!map.ContainsKey(lineNo)) { return; } List <string> expressions = map[lineNo]; foreach (var exp in expressions) { // Get lhs symbol name string lhsName = null; int index = exp.IndexOf('.'); if (index != -1) { string[] parts = exp.Split('.'); lhsName = parts[parts.Length - 1]; } else { Match m = Regex.Match(exp, @"(\w+)"); if (m.Success) { lhsName = m.Groups[1].Value; } } if (lhsName.Equals(symbolName)) { // Add to map Expression expStruct = new Expression(lineNo, exp, ci); if (ExpressionMap.ContainsKey(expStruct)) { List <string> values = ExpressionMap[expStruct]; values.Add(result); } else { List <string> values = new List <string>(); values.Add(result); ExpressionMap.Add(expStruct, values); } } } } }
public void Push(Int64 val) { runtime.rmem.Push(StackValue.BuildInt(val)); }
public void GCMarkAndSweep(List <StackValue> rootPointers, Executive exe) { if (isGarbageCollecting) { return; } try { isGarbageCollecting = true; // Mark var count = heapElements.Count; var markBits = new BitArray(count); foreach (var index in fixedHeapElements) { markBits.Set(index, true); } var workingStack = new Stack <StackValue>(rootPointers); while (workingStack.Any()) { var pointer = workingStack.Pop(); var ptr = (int)pointer.RawIntValue; if (!pointer.IsReferenceType || markBits.Get(ptr)) { continue; } markBits.Set(ptr, true); var heapElement = heapElements[ptr]; var subElements = heapElement.VisibleItems; if (heapElement.Dict != null) { subElements = subElements.Concat(heapElement.Dict.Keys) .Concat(heapElement.Dict.Values); } foreach (var subElement in subElements) { if (subElement.IsReferenceType && !markBits.Get((int)subElement.RawIntValue)) { workingStack.Push(subElement); } } } // Sweep for (int i = 0; i < count; ++i) { if (markBits.Get(i) || heapElements[i] == null) { continue; } var metaData = heapElements[i].MetaData; if (metaData.type == (int)PrimitiveType.kTypeString) { stringTable.TryRemoveString(i); } else if (metaData.type >= (int)PrimitiveType.kMaxPrimitives) { var objPointer = StackValue.BuildPointer(i, metaData); GCDisposeObject(objPointer, exe); } heapElements[i] = null; #if !HEAP_VERIFICATION freeList.Add(i); #endif } } finally { isGarbageCollecting = false; } }
public static bool IsArray(StackValue operand) { return(operand.optype == AddressType.ArrayPointer); }
public static bool IsTrue(StackValue operand) { return(operand.optype == AddressType.Boolean && operand.opdata != 0); }
public void SetAt(AbsoluteIndex index, StackValue sv) { Validity.Assert(null != Frame); Frame[(int)index] = sv; }
public abstract void OnDispose(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi); //callback method /// <summary> /// Gets a string representation for given DS object /// </summary> /// <param name="dsObject">DS Object</param> /// <returns>string representation of a DS object</returns> public abstract string GetStringValue(ProtoCore.DSASM.StackValue dsObject);
public static string GetStringValue(ProtoCore.DSASM.StackValue sv, Core core) { ProtoCore.DSASM.Mirror.ExecutionMirror mirror = new DSASM.Mirror.ExecutionMirror(new ProtoCore.DSASM.Executive(core), core); return(mirror.GetStringValue(sv, core.Heap, 0, true)); }
public static bool IsString(StackValue operand) { return(operand.optype == AddressType.String); }
/// <summary> /// Deep comparison for two StackValue. /// </summary> /// <param name="sv1"></param> /// <param name="sv2"></param> /// <param name="core"></param> /// <returns></returns> public static bool CompareStackValues(StackValue sv1, StackValue sv2, RuntimeCore runtimeCore) { return(CompareStackValues(sv1, sv2, runtimeCore, runtimeCore)); }
/// <summary> /// Constructor to construct ClassMirror from runtime data i.e. StackValue /// </summary> /// <param name="svData">StackValue</param> /// <param name="core">ProtoCore.Core</param> internal ClassMirror(StackValue svData, ProtoCore.Core core) : base(core) { Validity.Assert(svData.IsPointer); Validity.Assert(null != core.DSExecutable.classTable); IList<ClassNode> classNodes = core.DSExecutable.classTable.ClassNodes; Validity.Assert(classNodes != null && classNodes.Count > 0); this.classNode = classNodes[svData.metaData.type]; this.ClassName = this.classNode.Name; this.Name = this.ClassName; libraryMirror = new LibraryMirror(classNode.ExternLib, core); }
public static bool IsNumeric(StackValue operand) { return(operand.optype == AddressType.Int || operand.optype == AddressType.Double); }