コード例 #1
0
        public AzureClient(
            IExecutionEngine engine,
            IReferences references,
            IEntryPointGenerator entryPointGenerator,
            IMetadataController metadataController,
            ILogger <AzureClient> logger,
            IEventService eventService)
        {
            References          = references;
            EntryPointGenerator = entryPointGenerator;
            MetadataController  = metadataController;
            Logger = logger;
            eventService?.TriggerServiceInitialized <IAzureClient>(this);

            if (engine is BaseEngine baseEngine)
            {
                baseEngine.RegisterDisplayEncoder(new CloudJobToHtmlEncoder());
                baseEngine.RegisterDisplayEncoder(new CloudJobToTextEncoder());
                baseEngine.RegisterDisplayEncoder(new TargetStatusToHtmlEncoder());
                baseEngine.RegisterDisplayEncoder(new TargetStatusToTextEncoder());
                baseEngine.RegisterDisplayEncoder(new HistogramToHtmlEncoder());
                baseEngine.RegisterDisplayEncoder(new HistogramToTextEncoder());
                baseEngine.RegisterDisplayEncoder(new AzureClientErrorToHtmlEncoder());
                baseEngine.RegisterDisplayEncoder(new AzureClientErrorToTextEncoder());
            }
        }
コード例 #2
0
 public ExecutionPlanListener(IExecutionEngine executionEngine)
 {
     _CommandBlocks   = new Dictionary <Guid, List <ICommand> >();
     _BlockIds        = new Stack <Guid>();
     _RootURL         = "";
     _ExecutionEngine = executionEngine;
 }
コード例 #3
0
 /// <summary>
 ///     Given a given snippets collection, constructs a new magic command
 ///     that queries callables defined in that snippets collection.
 /// </summary>
 public LsMagicMagic(IMagicSymbolResolver resolver, IExecutionEngine engine, ILogger <LsMagicMagic> logger) : base(
         "lsmagic",
         new Microsoft.Jupyter.Core.Documentation
 {
     Summary     = "Returns a list of all currently available magic commands.",
     Description = $@"
             This magic command lists all of the magic commands available in the IQ# kernel,
             as well as those defined in any packages that have been loaded in the current
             session via the [`%package` magic command]({KnownUris.ReferenceForMagicCommand("package")}).
         ".Dedent(),
     Examples    = new []
     {
         @"
                 Display the list of available magic commands:
                 ```
                 In []: %lsmagic
                 Out[]: <detailed list of all available magic commands>
                 ```
             ".Dedent(),
     }
 }, logger)
 {
     this.resolver = resolver;
     if (engine is IQSharpEngine iQSharpEngine)
     {
         iQSharpEngine.RegisterDisplayEncoder(new MagicSymbolSummariesToHtmlEncoder());
         iQSharpEngine.RegisterDisplayEncoder(new MagicSymbolSummariesToTextEncoder());
     }
     else
     {
         throw new Exception($"Expected execution engine to be an IQ# engine, but was {engine.GetType()}.");
     }
 }
コード例 #4
0
 /// <summary>
 ///     Given a given snippets collection, constructs a new magic command
 ///     that queries callables defined in that snippets collection.
 /// </summary>
 public LsMagicMagic(IMagicSymbolResolver resolver, IExecutionEngine engine) : base(
         "lsmagic",
         new Documentation
 {
     Summary     = "Returns a list of all currently available magic commands.",
     Description = @"
             This magic command lists all of the magic commands available in the IQ# kernel,
             as well as those defined in any packages that have been loaded in the current
             session via the [`%package` magic command](https://docs.microsoft.com/qsharp/api/iqsharp-magic/package).
         ".Dedent(),
     Examples    = new []
     {
         @"
                 Display the list of available magic commands:
                 ```
                 In []: %lsmagic
                 Out[]: <detailed list of all available magic commands>
                 ```
             ".Dedent(),
     }
 })
 {
     this.resolver = resolver;
     (engine as IQSharpEngine).RegisterDisplayEncoder(new MagicSymbolSummariesToHtmlEncoder());
     (engine as IQSharpEngine).RegisterDisplayEncoder(new MagicSymbolSummariesToTextEncoder());
 }
コード例 #5
0
ファイル: ExecutionEngine.cs プロジェクト: evelasco85/MEQS
        public static IExecutionEngine GetInstance()
        {
            if(_instance == null)
                _instance = new ExecutionEngine();

            return _instance;
        }
コード例 #6
0
        bool CheckWitness(IExecutionEngine engine)
        {
            // Fake CheckWitness

            using (var context = engine.CurrentContext)
            {
                if (context == null)
                {
                    return(false);
                }

                if (!context.EvaluationStack.TryPop(out IStackItem it))
                {
                    return(false);
                }

                using (it)
                {
                    if (!it.CanConvertToByteArray)
                    {
                        return(false);
                    }

                    using (var itb = engine.CreateBool(true))
                        context.EvaluationStack.Push(itb);
                }
            }

            return(true);
        }
コード例 #7
0
        private IStackItem DeserializeStackItem(IExecutionEngine engine, BinaryReader reader)
        {
            EStackItemType type = (EStackItemType)reader.ReadByte();

            switch (type)
            {
            case EStackItemType.ByteArray:
                return(engine.CreateByteArray(reader.ReadVarBytes()));

            case EStackItemType.Bool:
                return(engine.CreateBool(reader.ReadBoolean()));

            case EStackItemType.Integer:
                return(engine.CreateInteger(new BigInteger(reader.ReadVarBytes())));

            case EStackItemType.Array:
            case EStackItemType.Struct:
            {
                IArrayStackItem array;

                if (type == EStackItemType.Struct)
                {
                    array = engine.CreateStruct();
                }
                else
                {
                    array = engine.CreateArray();
                }

                ulong count = reader.ReadVarInt();
                while (count-- > 0)
                {
                    array.Add(DeserializeStackItem(engine, reader));
                }

                return(array);
            }

            case EStackItemType.Map:
            {
                IMapStackItem map = engine.CreateMap();

                ulong count = reader.ReadVarInt();
                while (count-- > 0)
                {
                    IStackItem key   = DeserializeStackItem(engine, reader);
                    IStackItem value = DeserializeStackItem(engine, reader);

                    map[key] = value;

                    key.Dispose();
                    value.Dispose();
                }

                return(map);
            }

            default: throw new FormatException();
            }
        }
コード例 #8
0
        /// <summary>
        /// Check if the engine is clean
        /// </summary>
        /// <param name="engine">Engine</param>
        /// <param name="invocationStack">True for Check invocationStack</param>
        protected void CheckClean(IExecutionEngine engine, bool invocationStack = true)
        {
            Assert.AreEqual(0, engine.ResultStack.Count);

            if (invocationStack)
            {
                Assert.AreEqual(0, engine.InvocationStack.Count);
            }
            else
            {
                var current = engine.CurrentContext;

                if (current == null)
                {
                    Assert.AreEqual(EVMState.Halt, engine.State);
                }
                else
                {
                    Assert.AreEqual(0, current.EvaluationStack.Count);
                    Assert.AreEqual(0, current.AltStack.Count);

                    current.Dispose();
                }
            }
        }
コード例 #9
0
 public ExecutionEnvironment(ExecutionEnvironment parent, Instance instance)
 {
     _parent      = parent;
     Engine       = parent.Engine;
     currentScope = instance.States;
     _this        = instance;
 }
コード例 #10
0
        void CheckItem(IExecutionEngine engine, IStackItem item)
        {
            int c = engine.ResultStack.Count;

            engine.ResultStack.Push(item);
            Assert.AreEqual(engine.ResultStack.Count, c + 1);

            Assert.IsTrue(engine.ResultStack.TryPeek(0, out IStackItem obj));

            // PEEK

            obj.Dispose();
            obj = engine.ResultStack.Peek(0);
            Assert.IsNotNull(obj);

            Assert.AreEqual(obj.Type, item.Type);
            Assert.IsTrue(obj.Equals(item));

            // POP

            obj.Dispose();
            obj = engine.ResultStack.Pop();
            Assert.AreEqual(engine.ResultStack.Count, c);

            Assert.IsNotNull(obj);

            Assert.AreEqual(obj.Type, item.Type);
            Assert.IsTrue(obj.Equals(item));
            obj.Dispose();
        }
コード例 #11
0
        public Trade(string tradeName, EZInstrument tradeInstrument)
        {
            this.Name            = tradeName;
            this.tradeInstrument = tradeInstrument;
            VirtualQuantity      = 1;
            QuantityMultiplier   = 1;
            BuySell = zBuySell.Buy;  // TODO: Not sure if we want this to be initialized
            this.currentTradeState = TradeState.NOT_STARTED;
            AutoRestart            = false;
            Throttle         = 5;
            this.tradeActive = true;
            this.Metrics     = null;

            throttleTimer          = new Timer();
            throttleTimer.Elapsed += throttleTimer_Elapsed;

            execution               = new SimpleExecutionEngine();
            execution.PartialFill  += execution_PartialFill;
            execution.CompleteFill += execution_CompleteFill;

            // Create the TradeSteps that make up this trade.
            tradeSteps = new Dictionary <TradeStepType, TradeStep>();
            tradeSteps[TradeStepType.PRECONDITIONS] = new TradeStep(TradeStepType.PRECONDITIONS, BooleanRuleCombination.AND);
            tradeSteps[TradeStepType.ENTRY]         = new TradeStep(TradeStepType.ENTRY);
            tradeSteps[TradeStepType.EXIT]          = new TradeStep(TradeStepType.EXIT);
            tradeSteps[TradeStepType.STOP]          = new TradeStep(TradeStepType.STOP);
        }
コード例 #12
0
        public SimulateNoiseMagic(IExecutionEngine engine, ISymbolResolver resolver, IConfigurationSource configurationSource, INoiseModelSource noiseModelSource, ILogger <SimulateNoiseMagic> logger) : base(
                "experimental.simulate_noise",
                new Microsoft.Jupyter.Core.Documentation
        {
            Summary     = "Runs a given function or operation on the OpenSystemsSimulator target machine.",
            Description = $@"
                    > **⚠ WARNING:** This magic command is **experimental**,
                    > is not supported, and may be removed from future versions without notice.

                    This magic command allows executing a given function or operation
                    on the OpenSystemsSimulator target, simulating how that function or operation
                    will perform when run on noisy quantum hardware.

                    #### See also

                    - [`%config`]({KnownUris.ReferenceForMagicCommand("config")})
                    - [`%experimental.noise_model`]({KnownUris.ReferenceForMagicCommand("experimental.noise_model")})

                    #### Required parameters

                    - Q# operation or function name. This must be the first parameter, and must be a valid Q# operation
                    or function name that has been defined either in the notebook or in a Q# file in the same folder.
                    - Arguments for the Q# operation or function must also be specified as `key=value` pairs.

                    #### Remarks

                    The behavior of this magic command can be controlled through the `%experimental.noise_model` magic command,
                    and the `opensim.nQubits` and `opensim.representation` configuration settings.
                ".Dedent(),
            Examples    = new string[]
            {
                @"
                        Simulate a Q# operation defined as `operation MyOperation() : Result`:
                        ```
                        In []: %simulate MyOperation
                        Out[]: <return value of the operation>
                        ```
                    ".Dedent(),
                @"
                        Simulate a Q# operation defined as `operation MyOperation(a : Int, b : Int) : Result`:
                        ```
                        In []: %simulate MyOperation a=5 b=10
                        Out[]: <return value of the operation>
                        ```
                    ".Dedent(),
            }
        })
        {
            this.SymbolResolver      = resolver;
            this.ConfigurationSource = configurationSource;
            this.Logger           = logger;
            this.NoiseModelSource = noiseModelSource;

            if (engine is IQSharpEngine iQSharpEngine)
            {
                iQSharpEngine.RegisterDisplayEncoder(new MixedStateToHtmlDisplayEncoder());
                iQSharpEngine.RegisterDisplayEncoder(new StabilizerStateToHtmlDisplayEncoder(configurationSource));
            }
        }
コード例 #13
0
        protected PlatformEngineBase(IExecutionEngine engine, ArchInfo archInfo, Config config)
        {
            Engine = engine;

            ArchInfo = archInfo;

            Config = config;
        }
コード例 #14
0
        public DebugSession(IExecutionEngine engine, Contract contract, ContractArgument[] arguments, ReadOnlyMemory <string> returnTypes)
        {
            this.engine      = engine;
            this.returnTypes = returnTypes;
            Contract         = contract;

            using var builder = contract.BuildInvokeScript(arguments);
            engine.LoadScript(builder.ToArray());
        }
コード例 #15
0
        public void SimpleInstructions()
        {
            //Arrange
            MethodDesc mainMethod = new MethodDesc("Main", 3)
                                    .EntryPoint()
                                    .AddInheritanceAttributeFlag(MethodInheritanceAttributes.Global)
                                    .AddLocals(new LocalVarDescription[]
            {
                new LocalVarDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
                new LocalVarDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
            })
                                    .AddArguments(new MethodArgDescription[]
            {
                new MethodArgDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
                new MethodArgDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
            })
                                    .AddInstructions(new ILInstruction[]
            {
                new ILInstruction(ByteCode.Ldc_I4, 2),
                new ILInstruction(ByteCode.Stloc, 0),
                new ILInstruction(ByteCode.Ldc_I4, 4),
                new ILInstruction(ByteCode.Stloc, 1),
                new ILInstruction(ByteCode.Ldloc, 1),
                new ILInstruction(ByteCode.Ldloc, 0),
                new ILInstruction(ByteCode.Mul),
                new ILInstruction(ByteCode.Ldloc, 1),
                new ILInstruction(ByteCode.Mul)
            });



            CompiledModel compiledModel = new CompiledModel()
                                          .AddMethod(mainMethod);

            DomainModel domainModel = new DomainModel(new GCHeap.Factory(), new TypesHeap.Factory());

            domainModel.LoadType(TempTypeLocator.Int32Desc);
            IExecutionEngine executor = domainModel.GetExecutor(compiledModel, new ILOperationSet());

            //Act
            executor.Start();

            //Assert
        }
コード例 #16
0
        public void HandleEvent(FlowManifest manifest, IExecutionEngine pIExecutionEngine)
        {
            StatusProgressItem spi0 = new StatusProgressItem {
                Description = "FlowStatus", Status = manifest.FlowStatus.ToString()
            };

            pIExecutionEngine.AddStatusInformation(spi0);

            StatusProgressItem spi = new StatusProgressItem {
                Description = "Testing .EndFlow", Status = "Running"
            };

            pIExecutionEngine.AddStatusInformation(spi);

            try
            {
                pIExecutionEngine.EndFlow = true;
                spi.Status = "SHOULD NOT WORK!";
            }
            catch (NotImplementedException)
            {
                spi.Status = "NotImplementedException";
            }

            StatusProgressItem spi2 = new StatusProgressItem {
                Description = "Testing .LogToEvents", Status = "Running"
            };

            pIExecutionEngine.AddStatusInformation(spi2);

            try
            {
                pIExecutionEngine.LogToEvents = true;
                spi2.Status = "SHOULD NOT WORK!";
            }
            catch (NotImplementedException)
            {
                spi2.Status = "NotImplementedException";
            }

            StatusProgressItem spi3 = new StatusProgressItem {
                Description = "Testing .ResponseInBrowser", Status = "Running"
            };

            pIExecutionEngine.AddStatusInformation(spi3);

            try
            {
                IResponseInBrowser i = pIExecutionEngine.ResponseInBrowser;
                spi3.Status = "SHOULD NOT WORK!";
            }
            catch (NotImplementedException)
            {
                spi3.Status = "NotImplementedException";
            }
        }
コード例 #17
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="engine">Engine</param>
        /// <param name="handle">Handle</param>
        internal StackItemStack(IExecutionEngine engine, IntPtr handle) : base(engine)
        {
            _handle = handle;
            Engine  = (ExecutionEngine)engine;

            if (handle == IntPtr.Zero)
            {
                throw new ExternalException();
            }
        }
コード例 #18
0
        private IExecutionEngine GetEngineWithResolveAndStore()
        {
            engine = engineRepository.Resolve(engineId);

            if (engine != null)
            {
                engineGetter = GetEngineDirect;
            }

            return(engine);
        }
コード例 #19
0
ファイル: ExecutionEngine.cs プロジェクト: wuzlai/WebView
 public void MergeWorkload(IExecutionEngine executionEngine)
 {
     if (this != executionEngine && executionEngine is ExecutionEngine otherEngine)
     {
         var pendingExecutions = otherEngine.PendingExecutions.ToArray();
         foreach (var execution in pendingExecutions)
         {
             PendingExecutions.Enqueue(execution);
         }
     }
 }
コード例 #20
0
ファイル: LsMagicMagic.cs プロジェクト: Samar-080301/iqsharp
 /// <summary>
 ///     Given a given snippets collection, constructs a new magic command
 ///     that queries callables defined in that snippets collection.
 /// </summary>
 public LsMagicMagic(IMagicSymbolResolver resolver, IExecutionEngine engine) : base(
         "lsmagic",
         new Documentation
 {
     Summary = "Returns a list of all currently available magic commands."
 })
 {
     this.resolver = resolver;
     (engine as IQSharpEngine).RegisterDisplayEncoder(new MagicSymbolSummariesToHtmlEncoder());
     (engine as IQSharpEngine).RegisterDisplayEncoder(new MagicSymbolSummariesToTextEncoder());
 }
コード例 #21
0
 public CompleteRequestHandler(IExecutionEngine engine, IShellServer shellServer, ILogger <CompleteRequestHandler> logger)
 {
     if (engine is BaseEngine baseEngine)
     {
         this.engine = baseEngine;
     }
     else
     {
         throw new Exception("The CompleteRequestHandler requires that the IExecutionEngine service inherits from BaseEngine.");
     }
     this.shellServer = shellServer;
     this.logger      = logger;
 }
コード例 #22
0
        public static void InitialiseDependencies(string gamePath, bool isForFullGame)
        {
            _console = new CommandConsole();

            _gameConfigurationPersistance = new ConsoleGameConfigurationPersister();
            var adventureGameSetup = _gameConfigurationPersistance.LoadGameModel(gamePath);

            _gameConfiguration = new GameConfiguration(adventureGameSetup);

            _adventureApi = new AdventureApi(_gameConfiguration, new FilePersister(), _console);

            if (isForFullGame)
            {
                _waitingToRunTask = ShowSplashScreen(adventureGameSetup.GameName);
            }

            if (!isForFullGame)
            {
                adventureGameSetup.ClearAllScripts();

                _adventureApi.GameData.IsFirstTimeThrough    = false;
                _adventureApi.GameData.EnableScore           = false;
                _adventureApi.GameData.EnableShowItemsInRoom = false;
                _adventureApi.GameData.EnableInventorySize   = false;
                _adventureApi.GameData.EnableTitles          = false;
            }

            _languageApi = new LanguageApi(_adventureApi, _gameConfiguration);

            _executionEngine = new PythonExecutionEngine(_adventureApi, _console, _languageApi);

            ((LanguageApi)_languageApi).ExecutionEngine = _executionEngine;

            _adventureGameEngine = new AdventureGameEngine(_console, _gameConfiguration,
                                                           _adventureApi, _executionEngine, _languageApi);

            if (isForFullGame)
            {
                _adventureGameEngine.StateChanged += GameStateChanged;
            }

            _adventureGameEngine.InitialiseCore();

            if (!isForFullGame)
            {
                _adventureGameEngine.InitialiseTheGame();
            }
        }
コード例 #23
0
        protected Module()
        {
            ModuleInfoAttribute attribute = GetType()
                                            .GetCustomAttributes(typeof(ModuleInfoAttribute), false)
                                            .FirstOrDefault() as ModuleInfoAttribute;

            if (attribute == null)
            {
                throw new InvalidConstraintException("Missing ModuleInfoAttribute");
            }

            Title             = attribute.Title ?? throw new ArgumentNullException(nameof(Title), "ModuleInfoAttribute.Title is missing");
            Author            = attribute.Author ?? throw new ArgumentNullException(nameof(Author), "ModuleInfoAttribute.Author is missing");
            Version           = attribute.Version ?? throw new ArgumentNullException(nameof(Version), "ModuleInfoAttribute.Version is missing");
            ExecutionEngine   = Interface.CoreModule.ServiceProvider.GetService <IExecutionEngine>() ?? throw new NullReferenceException("ExecutionEngine is missing");
            hookSubscriptions = new Dictionary <string, List <MethodBase> >(StringComparer.Ordinal);
        }
コード例 #24
0
        private bool Runtime_Deserialize(IExecutionEngine engine)
        {
            using (var context = engine.CurrentContext)
            {
                if (context == null)
                {
                    return(false);
                }

                if (!context.EvaluationStack.TryPop(out IStackItem it))
                {
                    return(false);
                }

                var data = it.ToByteArray();
                it.Dispose();

                using (MemoryStream ms = new MemoryStream(data, false))
                    using (BinaryReader reader = new BinaryReader(ms))
                    {
                        IStackItem item = null;

                        try
                        {
                            item = DeserializeStackItem(engine, reader);
                        }
                        catch
                        {
                            if (item != null)
                            {
                                item.Dispose();
                            }
                            return(false);
                        }

                        context.EvaluationStack.Push(item);
                        if (item != null)
                        {
                            item.Dispose();
                        }
                    }
            }

            return(true);
        }
コード例 #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EngineMediator"/> class.
        /// </summary>
        /// <param name="machineState">
        /// The machine State.
        /// </param>
        /// <param name="executionEngine">
        /// The execution engine.
        /// </param>
        /// <param name="inputOutputEngine">
        /// The input output engine.
        /// </param>
        /// <param name="configurationEngine">
        /// The configuration engine.
        /// </param>
        /// <param name="romService">
        /// The rom service.
        /// </param>
        public EngineMediator(
            IMachineState machineState,
            IExecutionEngine executionEngine,
            IInputOutputEngine inputOutputEngine,
            IConfigurationEngine configurationEngine,
            IRomService romService)
        {
            this.MachineState        = machineState;
            this.ExecutionEngine     = executionEngine;
            this.InputOutputEngine   = inputOutputEngine;
            this.ConfigurationEngine = configurationEngine;
            this.RomService          = romService;

            // Assign the mediator to the engines, avoiding circular dependency with IoC
            this.ExecutionEngine.SetMediator(this);
            this.InputOutputEngine.SetMediator(this);
            this.ConfigurationEngine.SetMediator(this);
        }
コード例 #26
0
        bool Storage_GetContext(IExecutionEngine engine)
        {
            using (var context = engine.CurrentContext)
            {
                if (context == null)
                {
                    return(false);
                }

                var id = context.ScriptHash.ToHexString();
                if (!Storages.TryGetValue(id, out DummyStorageContext stContext))
                {
                    stContext = new DummyStorageContext(id, context.ScriptHash);
                    Storages[stContext.Id] = stContext;
                }

                using (var i = engine.CreateInterop(stContext))
                    context.EvaluationStack.Push(i);
            }

            return(true);
        }
コード例 #27
0
        private bool Runtime_Serialize(IExecutionEngine engine)
        {
            using (var context = engine.CurrentContext)
            {
                if (context == null)
                {
                    return(false);
                }

                if (!context.EvaluationStack.TryPop(out IStackItem it))
                {
                    return(false);
                }

                using (it)
                {
                    using (MemoryStream ms = new MemoryStream())
                        using (BinaryWriter writer = new BinaryWriter(ms))
                        {
                            try
                            {
                                SerializeStackItem(it, writer);
                            }
                            catch
                            {
                                return(false);
                            }

                            writer.Flush();

                            using (var bi = engine.CreateByteArray(ms.ToArray()))
                                context.EvaluationStack.Push(bi);
                        }
                }
            }

            return(true);
        }
コード例 #28
0
        /// <summary>
        /// Execute the macro using the source saved in macro
        /// </summary>
        /// <param name="async">Bool identifying if the macro should be execute asynchronously or not (synchronous)</param>
        /// <param name="runtime">Runtime tag identifying which execution engine to use, if empty, a default will be chosen</param>
        public async Task <bool> TryExecuteFile(FileDeclaration d, bool async, string runtime = "")
        {
            d.Save();

            if (string.IsNullOrEmpty(runtime))
            {
                runtime = GetDefaultRuntime();
            }

            IExecutionEngine engine = GetExecutionEngine(runtime);

            if (engine == null)
            {
                engine = GetExecutionEngine(GetDefaultRuntime());
            }

            if (engine == null)
            {
                return(false);
            }

            return(await engine.ExecuteMacro(d.Content, async, d.Info != null?d.Info.Directory.FullName : ""));
        }
コード例 #29
0
        bool Storage_Get(IExecutionEngine engine)
        {
            using (var context = engine.CurrentContext)
            {
                if (context == null)
                {
                    return(false);
                }

                if (!context.EvaluationStack.TryPop(out InteropStackItem inter))
                {
                    return(false);
                }

                using (inter)
                {
                    if (!(inter.Value is DummyStorageContext stContext))
                    {
                        return(false);
                    }

                    if (!context.EvaluationStack.TryPop(out IStackItem it))
                    {
                        return(false);
                    }

                    using (it)
                    {
                        if (!it.CanConvertToByteArray)
                        {
                            return(false);
                        }

                        var key = it.ToByteArray();

                        if (stContext.Storage.TryGetValue(key.ToHexString(), out byte[] value))
コード例 #30
0
        public void TryFinallyInsideAnotherTryFinallyBlock()
        {
            ITest test = new CorrectOrderCheck();
            //Arrange
            MethodDesc mainMethod = new MethodDesc("Main", 3)
                                    .EntryPoint()
                                    .AddInheritanceAttributeFlag(MethodInheritanceAttributes.Global)
                                    .AddCallback(test)
                                    .AddLocals(new LocalVarDescription[]
            {
                new LocalVarDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
                new LocalVarDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
            })
                                    .AddArguments(new MethodArgDescription[]
            {
                new MethodArgDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
                new MethodArgDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
            })
                                    .AddInstructions(new ILInstruction[]
            {
                new ILInstruction(ByteCode.Nop, "1. Outer try start").Data(1),                       //0
                new ILInstruction(ByteCode.Nop, "2. Outer try leave instruction").Data(2),
                new ILInstruction(ByteCode.Leave, 13),                                               //2

                //----------outer finally begin-------------
                new ILInstruction(ByteCode.Nop, "3. Outer finally start").Data(3),               //3

                new ILInstruction(ByteCode.Nop, "4. Inner try first instruction start").Data(4), //4
                new ILInstruction(ByteCode.Nop, "5. Just before inner try leave instruction").Data(5),
                new ILInstruction(ByteCode.Leave, 11),                                           //6

                new ILInstruction(ByteCode.Nop, "Between inner try and inner finally"),

                new ILInstruction(ByteCode.Nop, "6. At the inner finally start").Data(6),               //8
                new ILInstruction(ByteCode.Nop, "7. Just before inner endfinally instruction").Data(7),
                new ILInstruction(ByteCode.Endfinally),                                                 //10

                new ILInstruction(ByteCode.Nop, "8. Just before outer endfinally instruction").Data(8), //11
                new ILInstruction(ByteCode.Endfinally),                                                 //12
                //----------outer finally end-------------

                new ILInstruction(ByteCode.Nop, "9(end). instruction where outer try's leave points").Data(9),                                //13
                new ILInstruction(ByteCode.Ret)
            });

            mainMethod.EHTable.AddFinallyHandler(4, 6, 8, 10);
            mainMethod.EHTable.AddFinallyHandler(0, 2, 3, 12);

            CompiledModel compiledModel = new CompiledModel()
                                          .AddMethod(mainMethod);

            DomainModel      domainModel = new DomainModel(new GCHeap.Factory(), new TypesHeap.Factory());
            IExecutionEngine executor    = domainModel.GetExecutor(compiledModel, new ILOperationSet());

            //Act
            executor.Start();

            //Assert
            Assert.IsTrue(test.Success());
        }
コード例 #31
0
ファイル: GeneralCore.cs プロジェクト: kapitanov/diploma
 /// <summary>
 /// Configures the execution core.
 /// </summary>
 /// <param name="configuration">
 /// An instance of <see cref="IExecutionCoreConfiguration"/> that is provides configuration information.
 /// </param>
 public void Setup(IExecutionCoreConfiguration configuration)
 {
     container.RegisterInstance(typeof(Type), "EngineType", configuration.Sandbox);
     engine = container.Resolve<IExecutionEngine>();
 }
コード例 #32
0
ファイル: PolicyFilter.cs プロジェクト: DM-TOR/nhin-d
 public PolicyFilter(ICompiler compiler, IExecutionEngine engine)
 {
     m_compiler = compiler;
     m_executionEngine = engine;
 }
コード例 #33
0
ファイル: PolicyFilter.cs プロジェクト: DM-TOR/nhin-d
 public PolicyFilter(ICompiler compiler, IExecutionEngine engine, IPolicyLexiconParser parser)
 {
     m_compiler = compiler;
     m_executionEngine = engine;
     m_parser = parser;
 }
コード例 #34
0
        public void TwoNestedTryFinallyBlocksWithinOneMethod()
        {
            ITest test = new CorrectOrderCheck();
            //Arrange
            MethodDesc mainMethod = new MethodDesc("Main", 3)
                                    .EntryPoint()
                                    .AddInheritanceAttributeFlag(MethodInheritanceAttributes.Global)
                                    .AddCallback(test)
                                    .AddLocals(new LocalVarDescription[]
            {
                new LocalVarDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
                new LocalVarDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
            })
                                    .AddArguments(new MethodArgDescription[]
            {
                new MethodArgDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
                new MethodArgDescription()
                {
                    TypeToken = TempTypeLocator.Int32Desc.Metadata
                },
            })
                                    .AddInstructions(new ILInstruction[]
            {
                new ILInstruction(ByteCode.Ldc_I4, 2),
                new ILInstruction(ByteCode.Stloc, 0),
                new ILInstruction(ByteCode.Ldc_I4, 4),
                new ILInstruction(ByteCode.Stloc, 1),
                new ILInstruction(ByteCode.Nop, "1. Just before outer try start").Data(1),
                //----------outer try begin-------------
                new ILInstruction(ByteCode.Nop, "2. At the outer try first instruction start").AddLabel("OuterTryBeg").Data(2),                            //5
                new ILInstruction(ByteCode.Ldc_I4, 5),
                new ILInstruction(ByteCode.Stloc, 0),
                //----------inner try begin-------------
                new ILInstruction(ByteCode.Nop, "3. At the inner try first instruction start").AddLabel("InnerTryBeg").Data(3),                                //8
                new ILInstruction(ByteCode.Ldc_I4, 5),
                new ILInstruction(ByteCode.Stloc, 0),
                new ILInstruction(ByteCode.Nop, "4. Just before inner leave instruction").Data(4),
                new ILInstruction(ByteCode.Leave, new Label("AfterInnerBlock")).AddLabel("InnerTryEnd"),                                        //12
                //----------inner try end-------------
                new ILInstruction(ByteCode.Nop, "Just after inner try leave instruction"),
                new ILInstruction(ByteCode.Nop, "7. Where inner try's leave points to").AddLabel("AfterInnerBlock").Data(7),                              //14
                new ILInstruction(ByteCode.Ldc_I4, 5),
                new ILInstruction(ByteCode.Stloc, 0),
                new ILInstruction(ByteCode.Nop, "8. Just before outer leave instruction").Data(8),
                new ILInstruction(ByteCode.Leave, new Label("AfterOuterBlock")).AddLabel("OuterTryEnd"),                                       //18
                //----------outer try end-------------
                new ILInstruction(ByteCode.Nop, "Between outer try and finally"),
                //----------outer finally begin-------------
                new ILInstruction(ByteCode.Nop, "9. At the outer finally start").AddLabel("OuterFinBeg").Data(9),                                    //20
                new ILInstruction(ByteCode.Ldloc, 1),
                new ILInstruction(ByteCode.Ldloc, 0),
                new ILInstruction(ByteCode.Mul),
                new ILInstruction(ByteCode.Pop),
                new ILInstruction(ByteCode.Nop, "10. Just before outer endfinally instruction").Data(10),
                new ILInstruction(ByteCode.Endfinally).AddLabel("OuterFinEnd"),                                                            //26
                //----------outer finally end-------------
                new ILInstruction(ByteCode.Nop, "Just after outer endfinally instruction"),
                new ILInstruction(ByteCode.Nop, "11(end). instruction where outer try's leave points").AddLabel("AfterOuterBlock").Data(11),                               //28
                new ILInstruction(ByteCode.Ret),

                //----------inner finally begin-------------
                new ILInstruction(ByteCode.Nop, "5. At the inner finally start").AddLabel("InnerFinBeg").Data(5),                                           //30
                new ILInstruction(ByteCode.Ldloc, 1),
                new ILInstruction(ByteCode.Ldloc, 0),
                new ILInstruction(ByteCode.Mul),
                new ILInstruction(ByteCode.Pop),
                new ILInstruction(ByteCode.Nop, "6. Just before inner endfinally instruction").Data(6),
                new ILInstruction(ByteCode.Endfinally).AddLabel("InnerFinEnd"),                                        //36
                //----------inner finally end-------------
            });

            mainMethod.EHTable.AddFinallyHandler("InnerTryBeg", "InnerTryEnd", "InnerFinBeg", "InnerFinEnd");
            mainMethod.EHTable.AddFinallyHandler("OuterTryBeg", "OuterTryEnd", "OuterFinBeg", "OuterFinEnd");

            CompiledModel compiledModel = new CompiledModel()
                                          .AddMethod(mainMethod);

            DomainModel domainModel = new DomainModel(new GCHeap.Factory(), new TypesHeap.Factory());

            domainModel.LoadType(TempTypeLocator.Int32Desc);
            IExecutionEngine executor = domainModel.GetExecutor(compiledModel, new ILOperationSet());

            //Act
            executor.Start();

            //Assert
            Assert.IsTrue(test.Success());
        }
コード例 #35
0
        //Now that we have some variables/references, we can start by declaring each one of them. So we do it here in the constructor
        public QuickModuleTutorial()
        {
            //Lets start with the receiver
            receiver = new SSLVisionReceiver(IPAddress.Parse("224.5.23.2"), 10002);
            //The constructor to receiver needs the multicast IP and port on which the SSL Vision server is multicasting its packets,
            //These can be found on SSL-Vision settings. Do make sure that your SSL-vision and network is correctly set up.
            //You can test this by first connecting the receiver
            receiver.Connect();
            //Then making a call on receive
            object packet = receiver.Receive();
            if(packet==null)
                throw new Exception("You messed up. Check your network and SSL Vision settings. ");

            //Next, we have the sender
            //Now we provide two kinds of senders, one for GRSim simulator, and another made for XBEE modules, initialize the one you need
            sender = new GRSimSender(IPAddress.Loopback, 10020);
            //Again, the IP address and port are the ones set up on GRSim. Verify them and that your network is good.
            //You can test the sender too, first connect it
            sender.Connect();
            //Now create a RobotParameters object and set some random values i.e.
            RobotParameters roboparams = new RobotParameters();
            roboparams.IsBlue = true;
            roboparams.Id = 1;
            roboparams.XVelocity = 2;
            //And send this packet through the sender
            sender.Send(roboparams);
            //If the robot specified in the robotId above doesn't show any movement, you messed up again.

            //If you need the XBEE sender, then initialize it as
            //sender = new XBeeSender("COM1");
            //where COM1 is the port you connected the XBEE module to
            //Ofcourse the XBEE sender needs the individual velocities to send them, so you need to set the angles between the wheels in each IRobotInfo's
            //WheelAngles property before sending the packet

            //Now comes the controllers, the one we provide is a PIDController, which is a modified implementation of PID by this guy Ron Beyer
            //Firstly, you need to initialize the array of the controllers with length equal to the number of robots you have, or you like to move
            //Lets say you are controlling six robots
            controllers = new PIDController[6];
            //next, initialize each controller with parameters of the robot
            for (int i = 0; i < controllers.Length; i++)
            {
                controllers[i] = new PIDController(i, 2, 0, 0, 3025, -3025, 2, -2, 2, 0, 0, 2025, -2025, 2, -2, 5, 0, 0,
                    2*Math.PI, -2*Math.PI, Math.PI, -Math.PI);
                //Yes its a hell lot of arguments and we did give out a much smaller constructor with default values, but thats the problem, they're default and may not suit
                //your environment. Try to use this constructor. As for what the parameters are, I am not going to spill it out here, I've already given it in the constructor
                //summary, go check there
            }

            //Now comes the module, which is completely your responsibility. Its the module that caused us to get into all this shit. Its the module that caused us to
            //remodel our original program to have only one button named "Deep Shit"
            //Yup you guessed it, the planner.
            //We're not giving out the complete intelligence planner yet even though it contains some basic calculation functions,
            //we do provide a manual controller, which can be used with a Joystick, so connect a joystick
            //but for now, lets stick to some basics behavior, i.e. a test behavior defined in a dummy planner is to follow all the opponent robots
            //Initialize the dummy planner as follows
            planner = new DummyPlanner();

            //Now if you have a working SSL-Vision receiver, you can also safely declare a referee receiver, its not currently being used but you'll need it
            //when you write your own logic for obeying referee commands
            //refereeReceiver = new SSLRefereeReceiver(IPAddress.Parse("224.5.23.3"), 10003);

            //At this point, you have the absolute minimum things you need to run your system.
            //Now you can make individual calls to each of the modules again and agin like

            SSL_WrapperPacket receivedPacket = (SSL_WrapperPacket) receiver.Receive();
            if (receivedPacket != null)
            {
                IRobotInfo[] plannedPoints = planner.PlanExclusive(receivedPacket);
                if (plannedPoints != null)
                {
                    for (int i = 0; i < plannedPoints.Length; i++)
                    {
                        plannedPoints[i] = controllers[i].ComputeExclusive(plannedPoints[i],
                            receivedPacket.detection.robots_blue[plannedPoints[i].Id]);
                    }
                    foreach(var pointWithVelocity in plannedPoints)
                        sender.Send(pointWithVelocity);
                }
            }
            //and putting it in an infinite loop, which is pretty hideous if you ask me
            // or you can automate the process with the rest of useful architecture we provided, for example;

            //The data repository is a kind of utility we created to parse the incomming commands and store incomming/outgoing data in an organized way,
            //its a good software practice so if you want to use it, you can initialize it too
            dataRepository = new DataRepository(3, true);
            //The repository also stores previous packets, which is useful for interpolation techniques. The size of history is given as the constructor argument
            //The repository can be plugged in each of the above modules as follows. The modules will automatically read/write on repository

            IDataSource sourceReference = (IDataSource) receiver;
            sourceReference.Repository = dataRepository;
            sourceReference = (IDataSource) sender;
            sourceReference.Repository = dataRepository;
            foreach (var controller in controllers)
            {
                sourceReference = (IDataSource) controller;
                sourceReference.Repository = dataRepository;
            }
            sourceReference = (IDataSource) planner;
            sourceReference.Repository = dataRepository;
            //To keep track of your game configuration, configure the data source too, i.e. add the id's of the robots that you are using. you can access it in your planner
            for (int i = 0; i < 6; i++)
                dataRepository.Configuration.AddRobot(i, null);
            //Its also advised to use the OnRefereeCommandChanged method to notify the planner whenever a change in referee command status occurs
            //This is done by assigning the method as follows
            dataRepository.OnRefereeCommandChanged += planner.OnRefereeCommandChanged;

            //And we provide execution engines, which, as the name says execute your tasks. All you have to do is define a sequence of tasks
            //First select an anchor task which acts as starting point and branches onto all other tasks.
            //Now each of the above modules also implements and ITask interface which is essentially what each ExecutionEngine uses
            //So, evidently, the sequence begins with reception of packet. So here's the anchor
            ITask anchor = (ITask) receiver;

            //To build the sequence of what comes next, we assign a delegate to the GetNext property of the anchor. The delegate returns an array of tasks,
            //These tasks are the ones the engine will perform after the anchor's task has been performed.
            //The next task should be to plan, so
            anchor.GetNext = () => new[] {(ITask) planner};

            //I've used the fancy lambda expression. It may look berserk but once you get to understand them they're quite handy
            //Alternately, you can create a method with a signature matching the GetNextTasks, and in its body, return an array of ITask, i.e. the tasks you want performed next
            //This is how:
            //
            //public ITask[] plannerReturner()
            //{
            //    ITask[] array = new ITask[1];
            //    array[0] = (ITask) planner;
            //    return array;
            //}
            //
            //And assign it
            //anchor.GetNext = new GetNextTasks(plannerReturner);

            //Next we take the planner and assign it a next sequence of tasks, which would be the controllers
            ITask anotherReference = (ITask) planner;
            anotherReference.GetNext = () =>
            {
                ITask[] controllerTasks = new ITask[controllers.Length];
                for (int i = 0; i < controllers.Length; i++)
                    controllerTasks[i] = (ITask) controllers[i];
                return controllerTasks;
            };

            //Next the controllers need to queue the tasks to send the data
            foreach (var controller in controllers)
            {
                anotherReference = (ITask) controller;
                anotherReference.GetNext = () => new[] {(ITask) sender};
            }

            //and the sender is the terminal
            //Now lets bring in the execution engine, i'm going to go with the single processor, parallel processor's kinda experimental. Feel free to play with it if you want
            executionEngine = new SingleProcessor(new[] {anchor});
            //The processor takes an array of starting points/anchors.
            //Now all you have to di is start the engine
            executionEngine.Start();

            //And voila, you're done. Each module's ITask interface exposes the Execute() method which is called by the processor.
            //Remember how we plugged in a repository to each module, each module's Execute() takes care of taking data and writing it.
            //Ofcourse, to keep this model working, I would advise you to follow the design pattern here. i.e. If you create a module
            //by yourself according to your needs, it needs to implement one of the module specific interfaces e.g. IPacketSender for
            //anything that sends outgoing packets, IPlanner for strategy planning/path planning modules, IController for any other
            //position to velocity generation controller. The module must also implement two additional interfaces i.e. ITask and IDataSource
            //after which the module can easily be plugged in this model.

            //This project is a work in progress, and also contains a Rig module that has all of the above done in it, and a GUI that
            //can completely configure and manage multiple Rigs. We hope to complete it soon. This tutorial is an absolute basic,
            //you can navigate to different classes for better understanding. Feel free to ask us if you don't understand anything about
            //this project, YES ONLY THIS PROJECT, don't bother us if you don't know how to work around events, or if you don't understand
            //the concept of Threads, References or environment specific stuff. Try searching for these before.

            //Finally, we're all humans and we all make mistakes. This thing is not error proof, heck its not even tested properly.
            //So if you do find any bugs do feel free to report them to us so we can reflect it here. Remember, the basic purpose is
            //to learn, so don't be selfish. We're kind enough to give our work out to you, be kind yourselves.
            //Also take into consideration to contribute to this project and become an active member of something that might help a lot
            //of generations to come.
        }
コード例 #36
0
ファイル: SandboxEngine.cs プロジェクト: kapitanov/diploma
        private void CreateSandbox()
        {
            Contract.Requires(engineType != null);
            using (Perfomance.Trace("SandboxEngine::CreateSandbox()").BindToConsole())
            {
                sandboxDomain = AppDomain.CreateDomain(SandboxDomainName);

                //sandboxDomain.AssemblyLoad += (_, e) =>
                //{
                //    Debug.Print("SANDBOX: Loaded rawAssembly {0}", e.LoadedAssembly.FullName);
                //};
                //sandboxDomain.AssemblyResolve += (_, e) =>
                //{
                //    Debug.Print("SANDBOX: Resolving rawAssembly {0}", e.Name);

                //};

                foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    sandboxDomain.Load(assembly.GetName());
                }

                var sandBoxAssembly = sandboxDomain.Load(engineType.Assembly.FullName);

                sandbox = sandboxDomain.CreateInstanceAndUnwrap(sandBoxAssembly.FullName, engineType.FullName)
                          as IExecutionEngine;
                sandbox.Repository = Repository;
                sandbox.SystemResources = SystemResources;
            }
        }