示例#1
0
        public void Execute(ProtoCore.Core core, ProtoCore.Runtime.Context context)
        {
            try
            {
                core.NotifyExecutionEvent(ProtoCore.ExecutionStateEventArgs.State.kExecutionBegin);
                foreach (ProtoCore.DSASM.CodeBlock codeblock in core.CodeBlockList)
                {
                    //ProtoCore.Runtime.Context context = new ProtoCore.Runtime.Context();

                    int locals = 0;


                    // Comment Jun:
                    // On first bounce, the stackframe depth is initialized to -1 in the Stackfame constructor.
                    // Passing it to bounce() increments it so the first depth is always 0
                    ProtoCore.DSASM.StackFrame stackFrame = new ProtoCore.DSASM.StackFrame(core.GlobOffset);

                    // Comment Jun: Tell the new bounce stackframe that this is an implicit bounce
                    // Register TX is used for this.
                    StackValue svCallConvention = StackValue.BuildCallingConversion((int)ProtoCore.DSASM.CallingConvention.BounceType.kImplicit);
                    stackFrame.SetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kRegisterTX, svCallConvention);

                    core.Bounce(codeblock.codeBlockId, codeblock.instrStream.entrypoint, context, stackFrame, locals, EventSink);
                }
                core.NotifyExecutionEvent(ProtoCore.ExecutionStateEventArgs.State.kExecutionEnd);
            }
            catch
            {
                core.NotifyExecutionEvent(ProtoCore.ExecutionStateEventArgs.State.kExecutionEnd);
                throw;
            }
        }
        public override object Execute(ProtoCore.Runtime.Context c, Interpreter dsi)
        {
            Object retVal = base.Execute(c, dsi);

            if (retVal == null)
            {
                return(null);
            }

            StackValue propValue  = (StackValue)retVal;
            StackValue thisObject = dsi.runtime.rmem.Stack.Last();

            if (StackUtils.IsValidPointer(thisObject) && StackUtils.IsReferenceType(propValue))
            {
                int classIndex = (int)thisObject.metaData.type;
                if (classIndex != ProtoCore.DSASM.Constants.kInvalidIndex)
                {
                    var core    = dsi.runtime.Core;
                    int thisptr = (int)thisObject.opdata;

                    int        idx      = core.ClassTable.ClassNodes[classIndex].symbols.IndexOf(PropertyName);
                    StackValue oldValue = core.Heap.Heaplist[(int)thisObject.opdata].GetValue(idx, core);
                    if (!StackUtils.Equals(oldValue, propValue))
                    {
                        GCUtils.GCRetain(propValue, core);
                        core.Heap.Heaplist[thisptr].SetValue(idx, propValue);
                    }
                }
            }

            return(retVal);
        }
示例#3
0
        private ExecutionMirror Execute(int programCounterToExecuteFrom, List <Instruction> breakpoints, bool fepRun = false)
        {
            ProtoCore.Runtime.Context context = new ProtoCore.Runtime.Context();
            runtimeCore.Breakpoints = breakpoints;
            resumeBlockID           = runtimeCore.RunningBlock;


            if (runtimeCore.DebugProps.FirstStackFrame != null)
            {
                runtimeCore.DebugProps.FirstStackFrame.FramePointer = core.GlobOffset;

                // Comment Jun: Tell the new bounce stackframe that this is an implicit bounce
                // Register TX is used for this.
                StackValue svCallConvention = StackValue.BuildCallingConversion((int)ProtoCore.DSASM.CallingConvention.BounceType.kImplicit);
                runtimeCore.DebugProps.FirstStackFrame.TX = svCallConvention;
            }

            // Initialize the entry point interpreter
            int locals = 0; // This is the global scope, there are no locals

            ProtoCore.DSASM.Interpreter interpreter = new ProtoCore.DSASM.Interpreter(runtimeCore);
            runtimeCore.CurrentExecutive.CurrentDSASMExec = interpreter.runtime;
            runtimeCore.CurrentExecutive.CurrentDSASMExec.Bounce(
                resumeBlockID,
                programCounterToExecuteFrom,
                context,
                runtimeCore.DebugProps.FirstStackFrame,
                locals,
                fepRun,
                null,
                breakpoints);

            return(new ExecutionMirror(runtimeCore.CurrentExecutive.CurrentDSASMExec, runtimeCore));
        }
示例#4
0
        /// <summary>
        /// Compile and execute the source that is stored in the static context
        /// </summary>
        /// <param name="staticContext"></param>
        /// <param name="runtimeContext"></param>
        /// <param name="core"></param>
        /// <param name="isTest"></param>
        /// <returns></returns>
        public ExecutionMirror Execute(ProtoCore.CompileTime.Context staticContext, ProtoCore.Runtime.Context runtimeContext, ProtoCore.Core core, bool isTest = true)
        {
            Validity.Assert(null != staticContext.SourceCode && String.Empty != staticContext.SourceCode);

            core.AddContextData(staticContext.GlobalVarList);

            int  blockId   = ProtoCore.DSASM.Constants.kInvalidIndex;
            bool succeeded = Compile(staticContext, core, out blockId);

            if (succeeded)
            {
                core.GenerateExecutable();
                Validity.Assert(null != runtimeContext);
                Execute(core, blockId, staticContext, runtimeContext);
                if (!isTest)
                {
                    core.Heap.Free();
                }
            }
            else
            {
                throw new ProtoCore.Exceptions.CompileErrorsOccured();
            }

            if (isTest && !core.Options.CompileToLib)
            {
                return(new ExecutionMirror(core.CurrentExecutive.CurrentDSASMExec, core));
            }

            return(null);
        }
示例#5
0
        public override StackValue Marshal(object obj, ProtoCore.Runtime.Context context, Interpreter dsi, ProtoCore.Type type)
        {
            string     str     = (string)obj;
            StackValue dsarray = PrimitiveMarshler.ConvertCSArrayToDSArray(kCharMarshaler, str.ToCharArray(), context, dsi, type);

            return(StackUtils.BuildString(dsarray.opdata));
        }
示例#6
0
        public override object Execute(ProtoCore.Runtime.Context c, Interpreter dsi)
        {
            List <StackValue>  s          = dsi.runtime.rmem.Stack;
            FFIObjectMarshaler marshaller = Module.GetMarshaler(dsi.runtime.RuntimeCore);

            var thisObject = marshaller.UnMarshal(s.Last(), c, dsi, ReflectionInfo.DeclaringType);

            //Notify marshler for dispose.
            marshaller.OnDispose(s.Last(), c, dsi);

            Object retVal = null;

            if (ReflectionInfo.IsWrapperOf(CLRModuleType.DisposeMethod))
            {
                // For those FFI objects that are disposable but don't provide
                // Dispose() method in their classes, they will share a same
                // Dispose() method from CLRModuleType.DisposeMethod. We need
                // to manually dispose them.

                if (thisObject != null && thisObject is IDisposable)
                {
                    var disposable = thisObject as IDisposable;
                    disposable.Dispose();
                }
            }
            else
            {
                retVal = InvokeFunctionPointerNoThrow(c, dsi, thisObject, null);
            }

            return(retVal);
        }
        public override object Execute(ProtoCore.Runtime.Context c, Interpreter dsi)
        {
            Object retVal = base.Execute(c, dsi);

            if (retVal == null)
            {
                return(null);
            }

            StackValue propValue  = (StackValue)retVal;
            StackValue thisObject = dsi.runtime.rmem.Stack.Last();

            bool isValidPointer = thisObject.IsPointer && thisObject.opdata != Constants.kInvalidIndex;

            if (isValidPointer && propValue.IsReferenceType)
            {
                int classIndex = thisObject.metaData.type;
                if (classIndex != ProtoCore.DSASM.Constants.kInvalidIndex)
                {
                    var        runtimeCore = dsi.runtime.RuntimeCore;
                    int        idx         = runtimeCore.DSExecutable.classTable.ClassNodes[classIndex].symbols.IndexOf(PropertyName);
                    StackValue oldValue    = dsi.runtime.rmem.Heap.GetHeapElement(thisObject).GetValue(idx, runtimeCore);
                    if (!StackUtils.Equals(oldValue, propValue))
                    {
                        dsi.runtime.rmem.Heap.GetHeapElement(thisObject).SetValue(idx, propValue);
                    }
                }
            }

            return(retVal);
        }
示例#8
0
        private ProtoRunner.ProtoVMState Execute()
        {
            // runnerCore.GlobOffset is the number of global symbols that need to be allocated on the stack
            // The argument to Reallocate is the number of ONLY THE NEW global symbols as the stack needs to accomodate this delta
            int newSymbols = runnerCore.GlobOffset - deltaSymbols;

            // If there are lesser symbols to allocate for this run, then it means nodes were deleted.
            // TODO Jun: Determine if it is safe to just leave them in the global stack
            //           as no symbols point to this memory location in the stack anyway
            if (newSymbols >= 0)
            {
                runnerCore.Rmem.ReAllocateMemory(newSymbols);
            }

            // Store the current number of global symbols
            deltaSymbols = runnerCore.GlobOffset;

            // Initialize the runtime context and pass it the execution delta list from the graph compiler
            ProtoCore.Runtime.Context runtimeContext = new ProtoCore.Runtime.Context();
            runtimeContext.execFlagList = graphCompiler.ExecutionFlagList;

            //runner.Execute(runnerCore, runtimeContext);

            // ExecutionMirror mirror = new ExecutionMirror(runnerCore.CurrentExecutive.CurrentDSASMExec, runnerCore);

            return(null);// new ProtoRunner.ProtoVMState(runnerCore);
        }
示例#9
0
        /// <summary>
        /// For a given list of formal parameters, get the function end points that resolve
        /// </summary>
        /// <param name="context"></param>
        /// <param name="formalParams"></param>
        /// <param name="replicationInstructions"></param>
        /// <param name="stackFrame"></param>
        /// <param name="core"></param>
        /// <param name="unresolvable">The number of argument sets that couldn't be resolved</param>
        /// <returns></returns>
        public Dictionary <FunctionEndPoint, int> GetExactMatchStatistics(
            ProtoCore.Runtime.Context context,
            List <List <StackValue> > reducedFormalParams, StackFrame stackFrame, Core core, out int unresolvable)
        {
            List <ReplicationInstruction> replicationInstructions = new List <ReplicationInstruction>(); //We've already done the reduction before calling this

            unresolvable = 0;
            Dictionary <FunctionEndPoint, int> ret = new Dictionary <FunctionEndPoint, int>();

            foreach (List <StackValue> formalParamSet in reducedFormalParams)
            {
                List <FunctionEndPoint> feps = GetExactTypeMatches(context,
                                                                   formalParamSet, replicationInstructions, stackFrame,
                                                                   core);
                if (feps.Count == 0)
                {
                    //We have an arugment set that couldn't be resolved
                    unresolvable++;
                }

                foreach (FunctionEndPoint fep in feps)
                {
                    if (ret.ContainsKey(fep))
                    {
                        ret[fep]++;
                    }
                    else
                    {
                        ret.Add(fep, 1);
                    }
                }
            }

            return(ret);
        }
示例#10
0
 public override ProtoCore.DSASM.StackValue Execute(int codeblock, int entry, ProtoCore.Runtime.Context callContext, System.Collections.Generic.List <ProtoCore.DSASM.Instruction> breakpoints, ProtoCore.DebugServices.EventSink sink = null, bool fepRun = false)
 {
     ProtoCore.DSASM.Interpreter interpreter = new ProtoCore.DSASM.Interpreter(core, fepRun);
     CurrentDSASMExec = interpreter.runtime;
     ProtoCore.DSASM.StackValue sv = interpreter.Run(breakpoints, codeblock, entry, Language.kAssociative);
     return(sv);
 }
示例#11
0
        public override object Execute(ProtoCore.Runtime.Context c, Interpreter dsi, List <StackValue> s)
        {
            Object retVal = base.Execute(c, dsi, s);

            if (retVal == null)
            {
                return(null);
            }

            StackValue propValue  = (StackValue)retVal;
            var        thisObject = s?.Last() ?? dsi.runtime.rmem.Stack.Last();

            bool isValidPointer = thisObject.IsPointer && thisObject.Pointer != Constants.kInvalidIndex;

            if (isValidPointer && propValue.IsReferenceType)
            {
                int classIndex = thisObject.metaData.type;
                if (classIndex != ProtoCore.DSASM.Constants.kInvalidIndex)
                {
                    var runtimeCore = dsi.runtime.RuntimeCore;
                    int idx         = runtimeCore.DSExecutable.classTable.ClassNodes[classIndex].Symbols.IndexOf(PropertyName);

                    var        obj      = runtimeCore.Heap.ToHeapObject <DSObject>(thisObject);
                    StackValue oldValue = obj.GetValueFromIndex(idx, runtimeCore);
                    if (!StackUtils.Equals(oldValue, propValue))
                    {
                        obj.SetValueAtIndex(idx, propValue, runtimeCore);
                    }
                }
            }

            return(retVal);
        }
示例#12
0
        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 <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;
                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));
        }
        public override object Execute(ProtoCore.Runtime.Context c, Interpreter dsi)
        {
            Object retVal = base.Execute(c, dsi);
            List <ProtoCore.DSASM.StackValue> s = dsi.runtime.rmem.Stack;
            FFIObjectMarshler marshaller        = Module.GetMarshaller(dsi.runtime.Core);

            marshaller.OnDispose(s.Last(), c, dsi); //Notify marshler for dispose.

            return(retVal);
        }
示例#14
0
        public override object UnMarshal(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, Type type)
        {
            if (dsObject.opdata_d > MaxValue || dsObject.opdata_d < MinValue)
            {
                string message = String.Format(ProtoCore.RuntimeData.WarningMessage.kFFIInvalidCast, dsObject.opdata_d, type.Name, MinValue, MaxValue);
                dsi.LogWarning(ProtoCore.RuntimeData.WarningID.kTypeMismatch, message);
            }

            return(CastToDouble(dsObject.opdata_d));
        }
示例#15
0
        /// <summary>
        /// Get a list of all the function end points that are type compliant, there maybe more than one due to pattern matches
        /// </summary>
        /// <returns></returns>
        public List <FunctionEndPoint> GetExactTypeMatches(ProtoCore.Runtime.Context context,
                                                           List <StackValue> formalParams, List <ReplicationInstruction> replicationInstructions, StackFrame stackFrame, RuntimeCore runtimeCore)
        {
            List <FunctionEndPoint> ret = new List <FunctionEndPoint>();


            List <List <StackValue> > allReducedParamSVs = Replicator.ComputeAllReducedParams(formalParams, replicationInstructions, runtimeCore);


            //@TODO(Luke): Need to add type statistics checks to the below if it is an array to stop int[] matching char[]

            //Now test the reduced Params over all of the available end points
            StackValue thisptr    = stackFrame.ThisPtr;
            bool       isInstance = thisptr.IsPointer && thisptr.opdata != Constants.kInvalidIndex;
            bool       isGlobal   = thisptr.IsPointer && thisptr.opdata == Constants.kInvalidIndex;

            foreach (FunctionEndPoint fep in FunctionEndPoints)
            {
                var proc = fep.procedureNode;



                // Member functions are overloaded with thisptr as the first
                // parameter, so if member function replicates on the left hand
                // side, the type matching should only be applied to overloaded
                // member functions, otherwise should only be applied to original
                // member functions.
                if (isInstance && context.IsReplicating != proc.isAutoGeneratedThisProc)
                {
                    continue;
                }
                else if (isGlobal && !proc.isConstructor && !proc.isStatic && proc.classScope != Constants.kGlobalScope)
                {
                    continue;
                }

                bool typesOK = true;
                foreach (List <StackValue> reducedParamSVs in allReducedParamSVs)
                {
                    if (!fep.DoesTypeDeepMatch(reducedParamSVs, runtimeCore))
                    {
                        typesOK = false;
                        break;
                    }
                }

                if (typesOK)
                {
                    ret.Add(fep);
                }
            }

            return(ret);
        }
示例#16
0
 public override ProtoCore.DSASM.StackValue Execute(int codeblock, int entry, ProtoCore.Runtime.Context callContext, ProtoCore.DebugServices.EventSink sink)
 {
     ProtoCore.DSASM.StackValue sv = new ProtoCore.DSASM.StackValue();
     if (!core.Options.CompileToLib)
     {
         ProtoCore.DSASM.Interpreter interpreter = new ProtoCore.DSASM.Interpreter(core);
         CurrentDSASMExec = interpreter.runtime;
         sv = interpreter.Run(codeblock, entry, Language.kAssociative);
     }
     return(sv);
 }
示例#17
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="dsObject"></param>
 /// <param name="context"></param>
 /// <param name="dsi"></param>
 public override void OnDispose(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi)
 {
     lock (DSObjectMap)
     {
         Object clrobject;
         if (DSObjectMap.TryGetValue(dsObject, out clrobject))
         {
             DSObjectMap.Remove(dsObject);
             CLRObjectMap.Remove(clrobject);
             dsi.runtime.Core.FFIPropertyChangedMonitor.RemoveFFIObject(clrobject);
         }
     }
 }
示例#18
0
        public ProtoVMState RunToNextBreakpoint(ProtoVMState state)
        {
            Validity.Assert(null != RunnerCore);
            Validity.Assert(null != ExecutionContext);
            Validity.Assert(null != Runner);

            ProtoCore.Runtime.Context runtimeContext = new ProtoCore.Runtime.Context();

            // TODO Jun: Implement as DebugRunner, where breakpoints are inserted here.
            ProtoCore.DSASM.Mirror.ExecutionMirror mirror = Runner.Execute(ExecutionContext, runtimeContext, RunnerCore);

            return(new ProtoVMState(RunnerCore));
        }
示例#19
0
        public ProtoVMState RunToNextBreakpoint(ProtoVMState state)
        {
            Validity.Assert(null != RunnerCore);
            Validity.Assert(null != ExecutionContext);
            Validity.Assert(null != Runner);

            ProtoCore.Runtime.Context runtimeContext = new ProtoCore.Runtime.Context();

            // TODO Jun: Implement as DebugRunner, where breakpoints are inserted here.
            ProtoCore.DSASM.Mirror.ExecutionMirror mirror = Runner.Execute(ExecutionContext, runtimeContext, RunnerCore);

            return new ProtoVMState(RunnerCore);
        }
示例#20
0
 public override StackValue Execute(int codeblock, int entry, ProtoCore.Runtime.Context callContext, ProtoCore.DebugServices.EventSink sink)
 {
     if (!core.Options.CompileToLib)
     {
         ProtoCore.DSASM.Interpreter interpreter = new ProtoCore.DSASM.Interpreter(core);
         CurrentDSASMExec = interpreter.runtime;
         var sv = interpreter.Run(codeblock, entry, ProtoCore.Language.kImperative);
         return(sv);
     }
     else
     {
         return(StackValue.Null);
     }
 }
示例#21
0
        public Dictionary <FunctionEndPoint, int> GetCastDistances(ProtoCore.Runtime.Context context, List <StackValue> formalParams, List <ReplicationInstruction> replicationInstructions, ClassTable classTable, Core core)
        {
            Dictionary <FunctionEndPoint, int> ret = new Dictionary <FunctionEndPoint, int>();

            //@PERF: Consider parallelising this
            List <FunctionEndPoint> feps            = FunctionEndPoints;
            List <StackValue>       reducedParamSVs = Replicator.EstimateReducedParams(formalParams, replicationInstructions, core);

            foreach (FunctionEndPoint fep in feps)
            {
                int dist = fep.ComputeCastDistance(reducedParamSVs, classTable, core);
                ret.Add(fep, dist);
            }

            return(ret);
        }
示例#22
0
        public void Execute(ProtoCore.Core core)
        {
            try
            {
                foreach (ProtoCore.DSASM.CodeBlock codeblock in core.CodeBlockList)
                {
                    ProtoCore.Runtime.Context context = new ProtoCore.Runtime.Context();

                    int locals = 0;
                    core.Bounce(codeblock.codeBlockId, codeblock.instrStream.entrypoint, context, new ProtoCore.DSASM.StackFrame(core.GlobOffset), locals, EventSink);
                }
            }
            catch
            {
                throw;
            }
        }
        public ExecutionMirror Execute(ProtoCore.CompileTime.Context staticContext, ProtoCore.Runtime.Context runtimeContext, ProtoCore.Core core, bool isTest = true)
        {
            Validity.Assert(null != staticContext.SourceCode && String.Empty != staticContext.SourceCode);

            int blockId = ProtoCore.DSASM.Constants.kInvalidIndex;

            ProtoLanguage.CompileStateTracker compileState = Compile(staticContext, core, out blockId);
            Validity.Assert(null != compileState);
            if (compileState.compileSucceeded)
            {
                // This is the boundary between compilestate and runtime core
                // Generate the executable
                compileState.GenerateExecutable();

                // Get the executable from the compileState
                core.DSExecutable = compileState.DSExecutable;

                core.Rmem.PushGlobFrame(compileState.GlobOffset);
                core.RunningBlock = blockId;
                core.InitializeContextGlobals(staticContext.GlobalVarList);

                Validity.Assert(null != runtimeContext);
                Execute(core, runtimeContext, compileState);
                if (!isTest)
                {
                    core.Heap.Free();
                }
            }
            else
            {
                throw new ProtoCore.Exceptions.CompileErrorsOccured();
            }

            if (isTest && !core.Options.CompileToLib)
            {
                return(new ExecutionMirror(core.CurrentExecutive.CurrentDSASMExec, core));
            }

            // Save the Callsite state for this execution
            if (core.EnableCallsiteExecutionState)
            {
                ProtoCore.CallsiteExecutionState.SaveState(core.csExecutionState);
            }

            return(null);
        }
示例#24
0
        private void Execute(ProtoCore.Core core)
        {
            try
            {
                foreach (ProtoCore.DSASM.CodeBlock codeblock in core.CodeBlockList)
                {
                    ProtoCore.Runtime.Context context = new ProtoCore.Runtime.Context();

                    int locals = 0;
                    core.Bounce(codeblock.codeBlockId, codeblock.instrStream.entrypoint, context, new ProtoCore.DSASM.StackFrame(core.GlobOffset), locals, EventSink);
                }
            }
            catch
            {
                throw;
            }
        }
示例#25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="context"></param>
        /// <param name="dsi"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public override StackValue Marshal(object obj, ProtoCore.Runtime.Context context, Interpreter dsi, ProtoCore.Type type)
        {
            if (obj == null)
            {
                return(StackUtils.BuildNull());
            }

            FFIObjectMarshler marshaler = null;
            StackValue        retVal;
            Type objType = obj.GetType();

            if (type.IsIndexable)
            {
                if (obj is System.Collections.ICollection)
                {
                    System.Collections.ICollection collection = obj as System.Collections.ICollection;
                    object[] array = new object[collection.Count];
                    collection.CopyTo(array, 0);
                    return(PrimitiveMarshler.ConvertCSArrayToDSArray(this, array, context, dsi, type));
                }
                else if (obj is System.Collections.IEnumerable)
                {
                    System.Collections.IEnumerable enumerable = obj as System.Collections.IEnumerable;
                    return(PrimitiveMarshler.ConvertCSArrayToDSArray(this, enumerable, context, dsi, type));
                }
            }

            Array arr = obj as Array;

            if (null != arr)
            {
                return(PrimitiveMarshler.ConvertCSArrayToDSArray(this, arr, context, dsi, type));
            }
            else if ((PrimitiveMarshler.IsPrimitiveDSType(type) || PrimitiveMarshler.IsPrimitiveObjectType(obj, type)) && mPrimitiveMarshalers.TryGetValue(objType, out marshaler))
            {
                return(marshaler.Marshal(obj, context, dsi, type));
            }
            else if (CLRObjectMap.TryGetValue(obj, out retVal))
            {
                return(retVal);
            }

            return(CreateDSObject(obj, context, dsi));
        }
示例#26
0
        /// <summary>
        /// Setup to run with customised launch options
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns>Ready to run?</returns>
        ///
        private bool _PreStart(string code, Config.RunConfiguration configuration, string fileName)
        {
            this.code = code;
            if (null == core)
            {
                core = new ProtoCore.Core(new ProtoCore.Options {
                    IDEDebugMode = true
                });
                core.Compilers.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Compiler(core));
                core.Compilers.Add(ProtoCore.Language.kImperative, new ProtoImperative.Compiler(core));
            }

            runtimeCore = core.__TempCoreHostForRefactoring;
            runtimeCore.RuntimeStatus.MessageHandler = core.BuildStatus.MessageHandler;

            if (null != fileName)
            {
                core.CurrentDSFileName          = Path.GetFullPath(fileName);
                core.Options.RootModulePathName = Path.GetFullPath(fileName);
            }

            //Run the compilation process
            if (Compile(out resumeBlockID))
            {
                inited = true;

                //int blockId = ProtoCore.DSASM.Constants.kInvalidIndex;
                //core.runningBlock = blockId;

                ProtoCore.Runtime.Context context = new ProtoCore.Runtime.Context();
                runtimeCore.SetProperties(core.Options, core.DSExecutable, core.DebuggerProperties, context, core.ExprInterpreterExe);
                runtimeCore.NotifyExecutionEvent(ProtoCore.ExecutionStateEventArgs.State.kExecutionBegin);

                FirstExec();
                diList = BuildReverseIndex();
                return(true);
            }
            else
            {
                inited = false;
                return(false);
            }
        }
示例#27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dsObject"></param>
        /// <param name="context"></param>
        /// <param name="dsi"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private object CreateCLRObject(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, System.Type type)
        {
            object clrObject = TryGetPrimitiveObject(dsObject, context, dsi, type);

            if (null != clrObject)
            {
                return(clrObject);
            }
            //Must be a user defined type, and expecting a var object
            if (type == typeof(object) && dsObject.optype == AddressType.Pointer)
            {
                //TOD: Fix GC issue, don't know how/when this will get GCed??
                dsi.runtime.rmem.Heap.IncRefCount(dsObject);
                BindObjects(dsObject, dsObject);
                return(dsObject);
            }

            throw new InvalidOperationException("Unable to locate managed object for given dsObject.");
        }
示例#28
0
        private object ConvertReturnValue(object retVal, ProtoCore.Runtime.Context context, ProtoCore.DSASM.Interpreter dsi)
        {
            object returnValue = retVal;

            //  these are arrays!
            if (mReturnType.IsIndexable)
            {
                //  we have already asserted that these can be of rank 1 only, for now
                //
                IntPtr arrPtr = (IntPtr)retVal;
                if (arrPtr == IntPtr.Zero)
                {
                    return(StackValue.Null);
                }

                _Array arr  = (_Array)Marshal.PtrToStructure(arrPtr, typeof(_Array));
                var    elem = arr.elements;

                if (mReturnType.Name == "double")
                {
                    double[] elements = new double[arr.numElems];
                    Marshal.Copy(arr.elements, elements, 0, arr.numElems);

                    //  free up the memory
                    Marshal.FreeCoTaskMem(arr.elements);
                    Marshal.FreeCoTaskMem(arrPtr);

                    returnValue = ConvertCSArrayToDSArray(elements, dsi);
                }
                else if (mReturnType.Name == "int")
                {
                    int[] elements = new int[arr.numElems];
                    Marshal.Copy(arr.elements, elements, 0, arr.numElems);
                    return(elements);
                }
                else
                {
                    throw new ArgumentException(string.Format("FFI: unknown type {0} to marshall", mReturnType.Name));
                }
            }

            return(returnValue);
        }
示例#29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dsObject"></param>
        /// <param name="context"></param>
        /// <param name="dsi"></param>
        /// <param name="arrayType"></param>
        /// <returns></returns>
        private object ConvertDSArrayToCSArray(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, System.Type arrayType)
        {
            if (arrayType.IsArray)
            {
                //  processing only for the primitive types
                //  anything else will be dealt with as it was earlier
                //
                if (arrayType.UnderlyingSystemType == typeof(int[]))
                {
                    return(PrimitiveMarshler.ConvertDSArrayToCSArray <int>(this, dsObject, context, dsi));
                }
                else if (arrayType.UnderlyingSystemType == typeof(double[]))
                {
                    return(PrimitiveMarshler.ConvertDSArrayToCSArray <double>(this, dsObject, context, dsi));
                }
                else if (arrayType.UnderlyingSystemType == typeof(bool[]))
                {
                    return(PrimitiveMarshler.ConvertDSArrayToCSArray <bool>(this, dsObject, context, dsi));
                }
            }

            int         ptr   = (int)dsObject.opdata;
            HeapElement hs    = dsi.runtime.rmem.Heap.Heaplist[ptr];
            int         count = hs.VisibleSize;

            //  use arraylist instead of object[], this allows us to correctly capture
            //  the type of objects being passed
            //
            ArrayList arrList     = new ArrayList();
            var       elementType = arrayType.GetElementType();

            if (elementType == null)
            {
                elementType = typeof(object);
            }
            for (int idx = 0; idx < count; ++idx)
            {
                arrList.Add(UnMarshal(hs.Stack[idx], context, dsi, elementType));
            }

            return(arrList.ToArray(elementType));
        }
示例#30
0
        private ExecutionMirror Execute(int programCounterToExecuteFrom, List <Instruction> breakpoints, bool fepRun = false)
        {
            ProtoCore.Runtime.Context context = new ProtoCore.Runtime.Context();
            core.Breakpoints = breakpoints;
            resumeBlockID    = core.RunningBlock;

            int locals = 0;

            if (core.DebugProps.FirstStackFrame != null)
            {
                core.DebugProps.FirstStackFrame.SetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kFramePointer, StackUtils.BuildInt(core.GlobOffset));

                // Comment Jun: Tell the new bounce stackframe that this is an implicit bounce
                // Register TX is used for this.
                StackValue svCallConvention = StackUtils.BuildNode(AddressType.CallingConvention, (long)ProtoCore.DSASM.CallingConvention.BounceType.kImplicit);
                core.DebugProps.FirstStackFrame.SetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kRegisterTX, svCallConvention);
            }
            core.Bounce(resumeBlockID, programCounterToExecuteFrom, context, breakpoints, core.DebugProps.FirstStackFrame, locals, null, EventSink, fepRun);

            return(new ExecutionMirror(core.CurrentExecutive.CurrentDSASMExec, core));
        }
示例#31
0
        private object TryGetPrimitiveObject(StackValue dsObject, ProtoCore.Runtime.Context context, Interpreter dsi, System.Type type)
        {
            FFIObjectMarshler marshaler;
            Type dsObjectType = type;

            if (dsObjectType == typeof(object))
            {
                dsObjectType = GetPrimitiveType(dsObject.optype);
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                dsObjectType = Nullable.GetUnderlyingType(type);
            }

            if (mPrimitiveMarshalers.TryGetValue(dsObjectType, out marshaler))
            {
                return(marshaler.UnMarshal(dsObject, context, dsi, type));
            }

            return(null);
        }
示例#32
0
        /// <summary>
        /// Get a dictionary of the function end points that are type compatible
        /// with the costs of the associated conversions
        /// </summary>
        /// <param name="context"></param>
        /// <param name="formalParams"></param>
        /// <param name="replicationInstructions"></param>
        /// <returns></returns>
        public Dictionary <FunctionEndPoint, int> GetConversionDistances(ProtoCore.Runtime.Context context,
                                                                         List <StackValue> formalParams, List <ReplicationInstruction> replicationInstructions,
                                                                         ProtoCore.DSASM.ClassTable classTable, Core core, bool allowArrayPromotion = false)
        {
            Dictionary <FunctionEndPoint, int> ret = new Dictionary <FunctionEndPoint, int>();

            //@PERF: Consider parallelising this
            List <FunctionEndPoint> feps            = FunctionEndPoints;
            List <StackValue>       reducedParamSVs = Replicator.EstimateReducedParams(formalParams, replicationInstructions, core);

            foreach (FunctionEndPoint fep in feps)
            {
                int distance = fep.GetConversionDistance(reducedParamSVs, classTable, allowArrayPromotion, core);
                if (distance !=
                    (int)ProcedureDistance.kInvalidDistance)
                {
                    ret.Add(fep, distance);
                }
            }

            return(ret);
        }
示例#33
0
        private ProtoRunner.ProtoVMState Execute()
        {
            // runnerCore.GlobOffset is the number of global symbols that need to be allocated on the stack
            // The argument to Reallocate is the number of ONLY THE NEW global symbols as the stack needs to accomodate this delta
            int newSymbols = runnerCore.GlobOffset - deltaSymbols;

            // If there are lesser symbols to allocate for this run, then it means nodes were deleted.
            // TODO Jun: Determine if it is safe to just leave them in the global stack 
            //           as no symbols point to this memory location in the stack anyway
            if (newSymbols >= 0)
            {
                runnerCore.Rmem.PushFrameForGlobals(newSymbols);
            }

            // Store the current number of global symbols
            deltaSymbols = runnerCore.GlobOffset;

            // Initialize the runtime context and pass it the execution delta list from the graph compiler
            ProtoCore.Runtime.Context runtimeContext = new ProtoCore.Runtime.Context();

            try
            {
                runner.Execute(runnerCore, runtimeContext);
            }
            catch (ProtoCore.Exceptions.ExecutionCancelledException)
            {
                runnerCore.Cleanup();
                ReInitializeLiveRunner();
            }

            // ExecutionMirror mirror = new ExecutionMirror(runnerCore.CurrentExecutive.CurrentDSASMExec, runnerCore);

            return new ProtoRunner.ProtoVMState(runnerCore);
        }
示例#34
0
        private void BOUNCE_Handler(Instruction instruction)
        {
            // We disallow language blocks inside watch window currently - pratapa
            Validity.Assert(DSASM.InterpreterMode.kExpressionInterpreter != Core.ExecMode);

            runtimeVerify(ProtoCore.DSASM.AddressType.BlockIndex == instruction.op1.optype);
            int blockId = (int)instruction.op1.opdata;

            // Comment Jun: On a bounce, update the debug property to reflect this.
            // Before the explicit bounce, this was done in Execute() which is now no longer the case
            // as Execute is only called once during first bounce and succeeding bounce reuse the same interpreter
            core.DebugProps.CurrentBlockId = blockId;

            runtimeVerify(ProtoCore.DSASM.AddressType.Int == instruction.op2.optype);
            int entrypoint = (int)instruction.op2.opdata;

            ProtoCore.Runtime.Context context = new ProtoCore.Runtime.Context();
            // TODO(Jun/Jiong): Considering store the orig block id to stack frame
            int origRunningBlock = core.RunningBlock;
            core.RunningBlock = blockId;

            core.Rmem = rmem;
            if (core.ExecMode != InterpreterMode.kExpressionInterpreter)
            {
                core.Rmem.PushConstructBlockId(blockId);
            }

#if ENABLE_EXCEPTION_HANDLING
                core.stackActiveExceptionRegistration.Push(core.ExceptionHandlingManager.CurrentActiveRegistration);
#endif

            int ci = ProtoCore.DSASM.Constants.kInvalidIndex;
            int fi = ProtoCore.DSASM.Constants.kInvalidIndex;
            if (rmem.Stack.Count >= ProtoCore.DSASM.StackFrame.kStackFrameSize)
            {
                StackValue sci = rmem.GetAtRelative(ProtoCore.DSASM.StackFrame.kFrameIndexClass);
                StackValue sfi = rmem.GetAtRelative(ProtoCore.DSASM.StackFrame.kFrameIndexFunction);
                if (sci.optype == AddressType.Int && sfi.optype == AddressType.Int)
                {
                    ci = (int)sci.opdata;
                    fi = (int)sfi.opdata;
                }
            }

#if ENABLE_EXCEPTION_HANDLING
            core.ExceptionHandlingManager.SwitchContextTo(blockId, fi, ci, pc);
#endif

            StackValue svThisPtr = ProtoCore.DSASM.StackValue.BuildPointer(ProtoCore.DSASM.Constants.kInvalidPointer);
            int returnAddr = pc + 1;

            Validity.Assert(ProtoCore.DSASM.Constants.kInvalidIndex != executingBlock);
            //int blockDecl = executingBlock;
            int blockDecl = (int)rmem.GetAtRelative(ProtoCore.DSASM.StackFrame.kFrameIndexFunctionBlock).opdata;
            int blockCaller = executingBlock;

            StackFrameType type = StackFrameType.kTypeLanguage;
            int depth = (int)rmem.GetAtRelative(StackFrame.kFrameIndexStackFrameDepth).opdata;
            int framePointer = core.Rmem.FramePointer;

            // Comment Jun: Use the register TX to store explicit/implicit bounce state
            bounceType = ProtoCore.DSASM.CallingConvention.BounceType.kExplicit;
            TX = StackValue.BuildCallingConversion((int)ProtoCore.DSASM.CallingConvention.BounceType.kExplicit);

            List<StackValue> registers = new List<StackValue>();
            SaveRegisters(registers);

            StackFrameType callerType = (fepRun) ? StackFrameType.kTypeFunction : StackFrameType.kTypeLanguage;


            if (core.Options.IDEDebugMode && core.ExecMode != InterpreterMode.kExpressionInterpreter)
            {
                // Comment Jun: Temporarily disable debug mode on bounce
                //Validity.Assert(false); 

                //Validity.Assert(core.Breakpoints != null);
                //blockDecl = blockCaller = core.DebugProps.CurrentBlockId;

                core.DebugProps.SetUpBounce(this, blockCaller, returnAddr);

                StackFrame stackFrame = new StackFrame(svThisPtr, ci, fi, returnAddr, blockDecl, blockCaller, callerType, type, depth + 1, framePointer, registers, null);
                ProtoCore.Language bounceLangauge = exe.instrStreamList[blockId].language;
                BounceExplicit(blockId, 0, bounceLangauge, stackFrame, core.Breakpoints);
            }
            else //if (core.Breakpoints == null)
            {
                StackFrame stackFrame = new StackFrame(svThisPtr, ci, fi, returnAddr, blockDecl, blockCaller, callerType, type, depth + 1, framePointer, registers, null);

                ProtoCore.Language bounceLangauge = exe.instrStreamList[blockId].language;
                BounceExplicit(blockId, 0, bounceLangauge, stackFrame);
            }

            return;
        }
        public ExecutionMirror Execute(string code)
        {
            code = string.Format("{0} = {1};", Constants.kWatchResultVar, code);

            // TODO Jun: Move this initaliztion of the exe into a unified function
            //Core.ExprInterpreterExe = new Executable();

            int blockId = ProtoCore.DSASM.Constants.kInvalidIndex;
            Core.Rmem.AlignStackForExprInterpreter();

            //Initialize the watch stack and watchBaseOffset
            //The watchBaseOffset is used to indexing the watch variables and related temporary variables
            Core.watchBaseOffset = 0;
            Core.watchStack.Clear();
            compileState.watchBaseOffset = 0;
            compileState.watchStack.Clear();

            compileState.ProcTable = Core.ProcTable;
            compileState.ClassTable= Core.ClassTable;


            compileState.CodeBlockList = Core.DSExecutable.CodeBlockList;
            compileState.FunctionTable = Core.DSExecutable.FunctionTable;
            compileState.CompleteCodeBlockList = Core.DSExecutable.CompleteCodeBlockList;

            compileState.Rmem = Core.Rmem;

            compileState.DebugProps = Core.DebugProps;

            //compileState.assocCodegen = Core.assocCodegen;

            compileState.ExecMode = InterpreterMode.kExpressionInterpreter;

            bool succeeded = Compile(code, out blockId);

            //Clear the warnings and errors so they will not continue impact the next compilation.
            //Fix IDE-662
            compileState.BuildStatus.Errors.Clear();
            compileState.BuildStatus.Warnings.Clear();

            for (int i = 0; i < compileState.watchBaseOffset; ++i)
            {
                Core.watchStack.Add(StackUtils.BuildNull());
            }


            // Jun: PArt of the compile tracker and core swap
            // This code that copies watch data from compilestate to core needs cleanup
            Core.watchBaseOffset = compileState.watchBaseOffset;
            //Core.watchClassScope = compileState.watchClassScope;
            //Core.watchFramePointer = compileState.watchFramePointer;
            //Core.watchFunctionScope = compileState.watchFunctionScope;
            Core.watchSymbolList = compileState.watchSymbolList;



            //Record the old function call depth
            //Fix IDE-523: part of error for watching non-existing member
            int oldFunctionCallDepth = Core.FunctionCallDepth;

            //Record the old start PC
            int oldStartPC = Core.startPC;
            if (succeeded)
            {

                //a2. Record the old start PC for restore instructions
                Core.startPC = compileState.ExprInterpreterExe.instrStreamList[blockId].instrList.Count;

                compileState.GenerateExprExeInstructions(blockId);
                Core.ExprInterpreterExe = compileState.ExprInterpreterExe; 
                
                //a3. Record the old running block
                int restoreBlock = Core.RunningBlock;
                Core.RunningBlock = blockId;

                //a4. Record the old debug entry PC and stack size of FileFepChosen
                int oldDebugEntryPC = Core.DebugProps.DebugEntryPC;

                //a5. Record the frame pointer for referencing to thisPtr
                Core.watchFramePointer = Core.Rmem.FramePointer;

                // The "Core.Bounce" below is gonna adjust the "FramePointer" 
                // based on the current size of "Core.Rmem.Stack". All that is 
                // good except that "Bounce" does not restore the previous value 
                // of frame pointer after "bouncing back". Here we make a backup
                // of it and restore it right after the "Core.Bounce" call.
                // 
                //Core.Executives[Core.CodeBlockList[Core.RunningBlock].language].
                ProtoCore.Runtime.Context context = new ProtoCore.Runtime.Context();

                try
                {
                    ProtoCore.DSASM.StackFrame stackFrame = null;
                    int locals = 0;

                    StackValue sv = Core.Bounce(blockId, Core.startPC, context, stackFrame, locals, EventSink);

                    // As Core.InterpreterProps stack member is pushed to every time the Expression Interpreter begins executing
                    // it needs to be popped off at the end for stack alignment - pratapa
                    Core.InterpreterProps.Pop();
                }
                catch
                { }

                //r5. Restore frame pointer.
                Core.Rmem.FramePointer = Core.watchFramePointer; 

                //r4. Restore the debug entry PC and stack size of FileFepChosen
                Core.DebugProps.DebugEntryPC = oldDebugEntryPC;

                //r3. Restore the running block 
                Core.RunningBlock = restoreBlock;

                //r2. Restore the instructions in Core.ExprInterpreterExe
                int from = Core.startPC;
                int elems = Core.ExprInterpreterExe.iStreamCanvas.instrList.Count;
                Core.ExprInterpreterExe.instrStreamList[blockId].instrList.RemoveRange(from, elems);

                //Restore the start PC
                Core.startPC = oldStartPC;

                //Restore the function call depth
                //Fix IDE-523: part of error for watching non-existing member
                Core.FunctionCallDepth = oldFunctionCallDepth;


                //Clear the watchSymbolList
                foreach (SymbolNode node in Core.watchSymbolList)
                {
                    if (ProtoCore.DSASM.Constants.kInvalidIndex == node.classScope)
                        Core.DSExecutable.runtimeSymbols[node.runtimeTableIndex].Remove(node);
                    else
                        Core.DSExecutable.classTable.ClassNodes[node.classScope].symbols.Remove(node);
                }
            }
            else
            {
                //Restore the start PC
                Core.startPC = oldStartPC;

                //Restore the function call depth
                //Fix IDE-523: part of error for watching non-existing member
                Core.FunctionCallDepth = oldFunctionCallDepth;

                //Clear the watchSymbolList
                foreach (SymbolNode node in Core.watchSymbolList)
                {
                    if (ProtoCore.DSASM.Constants.kInvalidIndex == node.classScope)
                        Core.DSExecutable.runtimeSymbols[node.runtimeTableIndex].Remove(node);
                    else
                        Core.DSExecutable.classTable.ClassNodes[node.classScope].symbols.Remove(node);
                }

                // TODO: investigate why additional elements are added to the stack.
                Core.Rmem.RestoreStackForExprInterpreter();

                throw new ProtoCore.Exceptions.CompileErrorsOccured();
            }

            // TODO: investigate why additional elements are added to the stack.
            Core.Rmem.RestoreStackForExprInterpreter();

            return new ExecutionMirror(Core.CurrentExecutive.CurrentDSASMExec, Core);
        }
示例#36
0
        private ProtoRunner.ProtoVMState Execute()
        {
            // runnerCore.GlobOffset is the number of global symbols that need to be allocated on the stack
            // The argument to Reallocate is the number of ONLY THE NEW global symbols as the stack needs to accomodate this delta
            int newSymbols = compileState.GlobOffset - deltaSymbols;

            // If there are lesser symbols to allocate for this run, then it means nodes were deleted.
            // TODO Jun: Determine if it is safe to just leave them in the global stack 
            //           as no symbols point to this memory location in the stack anyway
            if (newSymbols >= 0)
            {
                runnerCore.Rmem.ReAllocateMemory(newSymbols);
            }

            // Store the current number of global symbols
            deltaSymbols = compileState.GlobOffset;

            // Initialize the runtime context and pass it the execution delta list from the graph compiler
            ProtoCore.Runtime.Context runtimeContext = new ProtoCore.Runtime.Context();
            runtimeContext.execFlagList = graphCompiler.ExecutionFlagList;

            runner.Execute(runnerCore, runtimeContext, null);

            return new ProtoRunner.ProtoVMState(runnerCore);
        }
示例#37
0
        private ExecutionMirror Execute(int programCounterToExecuteFrom, List<Instruction> breakpoints, bool fepRun = false)
        {
            ProtoCore.Runtime.Context context = new ProtoCore.Runtime.Context();
            core.Breakpoints = breakpoints;
            resumeBlockID = core.RunningBlock;

            int locals = 0;

            if (core.DebugProps.FirstStackFrame != null)
            {
                core.DebugProps.FirstStackFrame.SetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kFramePointer, StackValue.BuildInt(core.GlobOffset));

                // Comment Jun: Tell the new bounce stackframe that this is an implicit bounce
                // Register TX is used for this.
                StackValue svCallConvention = StackValue.BuildCallingConversion((int)ProtoCore.DSASM.CallingConvention.BounceType.kImplicit);
                core.DebugProps.FirstStackFrame.SetAt(ProtoCore.DSASM.StackFrame.AbsoluteIndex.kRegisterTX, svCallConvention);
            }
            core.Bounce(resumeBlockID, programCounterToExecuteFrom, context, breakpoints, core.DebugProps.FirstStackFrame, locals, null, EventSink, fepRun);

            return new ExecutionMirror(core.CurrentExecutive.CurrentDSASMExec, core);
        }