Ejemplo n.º 1
0
        private ScriptModuleHandle Compile(ICodeSource source)
        {
            RegisterScopeIfNeeded();

            var parser = new Parser();
            parser.Code = source.Code;

            var compiler = new Compiler.Compiler();
            compiler.DirectiveHandler = ResolveDirective;

            if (DirectiveResolver != null)
            {
                DirectiveResolver.Source = source;
            }

            ModuleImage compiledImage;
            try
            {
                compiledImage = compiler.Compile(parser, _currentContext);
            }
            catch (ScriptException e)
            {
                if(e.ModuleName == null)
                    e.ModuleName = source.SourceDescription;

                throw;
            }
            finally
            {
                if (DirectiveResolver != null)
                {
                    DirectiveResolver.Source = null;
                }
            }

            foreach (var item in _predefinedVariables)
            {
                var varDef = _scope.GetVariable(item);
                if (varDef.Type == SymbolType.ContextProperty)
                {
                    compiledImage.ExportedProperties.Add(new ExportedSymbol()
                    {
                        SymbolicName = varDef.Identifier,
                        Index = varDef.Index
                    });
                }
            }

            var mi = new ModuleInformation();
            mi.CodeIndexer = parser.GetCodeIndexer();
            // пока у модулей нет собственных имен, будет совпадать с источником модуля
            mi.ModuleName = source.SourceDescription;
            mi.Origin = source.SourceDescription;
            compiledImage.ModuleInfo = mi;

            return new ScriptModuleHandle()
            {
                Module = compiledImage
            };
        }
Ejemplo n.º 2
0
        public Process CreateProcess(IHostApplication host, ModuleImage moduleImage, ICodeSource src)
        {
            SetGlobalEnvironment(host, src);
            var module = _engine.LoadModuleImage(moduleImage);

            return(InitProcess(host, module));
        }
Ejemplo n.º 3
0
        public Process CreateProcess(IHostApplication host, ICodeSource src, CompilerService compilerSvc)
        {
            SetGlobalEnvironment(host, src);
            var module = _engine.LoadModuleImage(compilerSvc.CreateModule(src));

            return(InitProcess(host, src, ref module));
        }
Ejemplo n.º 4
0
        public void Write(TextWriter output, ICodeSource source)
        {
            var module = _compiler.CreateModule(source).Module;

            WriteImage(output, module);

        }
Ejemplo n.º 5
0
        private Process InitProcess(IHostApplication host, ICodeSource src, ref LoadedModuleHandle module)
        {
            Initialize();
            var process = new Process(host, module, _engine);

            return(process);
        }
        private LoadedModuleHandle LoadControllerCode(ICodeSource src)
        {
            var compiler = _fw.Engine.GetCompilerService();
            var byteCode = ScriptedController.CompileModule(compiler, src);

            return(_fw.Engine.LoadModuleImage(byteCode));
        }
Ejemplo n.º 7
0
        public WebGlobalContext(IHostApplication host, ICodeSource entryScript)
        {
            var sys = new SystemGlobalContext();

            sys.ApplicationHost = host;
            sys.CodeSource      = entryScript;
            _osGlobal           = new RCIRedirector(sys);
            _osGlobal.PublishProperty("Символы", null);
            _osGlobal.PublishProperty("Chars", null);
            _osGlobal.PublishProperty("ФайловыеПотоки", null);
            _osGlobal.PublishProperty("FileStreams", null);

            _osGlobal.PublishMethod("ОсвободитьОбъект", "FreeObject");
            _osGlobal.PublishMethod("ВыполнитьСборкуМусора", "RunGarbageCollection");
            _osGlobal.PublishMethod("ЗапуститьПриложение", "RunApp");
            _osGlobal.PublishMethod("СоздатьПроцесс", "CreateProcess");
            _osGlobal.PublishMethod("НайтиПроцессПоИдентификатору", "FindProcessById");
            _osGlobal.PublishMethod("НайтиПроцессыПоИмени", "FindProcessesByName");
            _osGlobal.PublishMethod("КраткоеПредставлениеОшибки", "BriefErrorDescription");
            _osGlobal.PublishMethod("КаталогПрограммы", "ProgramDirectory");
            _osGlobal.PublishMethod("ПодробноеПредставлениеОшибки", "DetailErrorDescription");
            _osGlobal.PublishMethod("ТекущаяДата", "CurrentDate");
            _osGlobal.PublishMethod("ТекущаяУниверсальнаяДатаВМиллисекундах", "CurrentUniversalDateInMilliseconds");
            _osGlobal.PublishMethod("ЗначениеЗаполнено", "IsValueFilled");
            _osGlobal.PublishMethod("ЗаполнитьЗначенияСвойств", "FillPropertyValues");
            _osGlobal.PublishMethod("ПолучитьCOMОбъект", "GetCOMObject");
            _osGlobal.PublishMethod("Приостановить", "Sleep");
            _osGlobal.PublishMethod("ПодключитьВнешнююКомпоненту", "AttachAddIn");
            _osGlobal.PublishMethod("ЗагрузитьСценарий", "LoadScript");
            _osGlobal.PublishMethod("ЗагрузитьСценарийИзСтроки", "LoadScriptFromString");
            _osGlobal.PublishMethod("ПодключитьСценарий", "AttachScript");
            _osGlobal.PublishMethod("Сообщить", "Message");

            sys.InitInstance();
        }
Ejemplo n.º 8
0
        private ModuleImage CompileInternal(ICodeSource source)
        {
            RegisterScopeIfNeeded();

            var parser = new PreprocessingLexer();

            foreach (var variable in _preprocessorVariables)
            {
                parser.Define(variable);
            }
            parser.UnknownDirective += (sender, args) =>
            {
                // все неизвестные директивы возвращать назад и обрабатывать старым кодом
                args.IsHandled = true;
            };
            parser.Code = source.Code;

            var compiler = new Compiler.Compiler();

            compiler.ProduceExtraCode = ProduceExtraCode;
            compiler.DirectiveHandler = ResolveDirective;

            if (DirectiveResolver != null)
            {
                DirectiveResolver.Source = source;
            }

            ModuleImage compiledImage;

            try
            {
                compiledImage = compiler.Compile(parser, _currentContext);
            }
            catch (ScriptException e)
            {
                if (e.ModuleName == null)
                {
                    e.ModuleName = source.SourceDescription;
                }

                throw;
            }
            finally
            {
                if (DirectiveResolver != null)
                {
                    DirectiveResolver.Source = null;
                }
            }

            var mi = new ModuleInformation();

            mi.CodeIndexer = parser.Iterator;
            // пока у модулей нет собственных имен, будет совпадать с источником модуля
            mi.ModuleName            = source.SourceDescription;
            mi.Origin                = source.SourceDescription;
            compiledImage.ModuleInfo = mi;

            return(compiledImage);
        }
Ejemplo n.º 9
0
 public ScriptModuleHandle CreateModule(ICodeSource source)
 {
     return(new ScriptModuleHandle()
     {
         Module = Compile(source)
     });
 }
 public void LoadFromSource(ICodeSource source)
 {
     codeSource = source;
     syntaxTree = typeof(ParserType)
                  //TODO: Maybe clean up this garbage so I'm not using reflection. Done to keep the class generic though in the event
                  //That someone insane wants to write VB.
                  .GetMethod("ParseText", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public, null, new Type[] { typeof(string), typeof(CSharpParseOptions), typeof(string), typeof(Encoding), typeof(CancellationToken) }, null)
                  .Invoke(null, new object[] { source.Path, null, "", null, null }) as SyntaxTree;
 }
Ejemplo n.º 11
0
        private Process InitProcess(IHostApplication host, ICodeSource src, ref LoadedModuleHandle module)
        {
            Initialize();
            _globalCtx.ApplicationHost = host;
            _globalCtx.CodeSource      = src;
            _globalCtx.InitInstance();
            var process = new Process(host, module, _engine);

            return(process);
        }
Ejemplo n.º 12
0
        public Process CreateProcess(IHostApplication host, ICodeSource src, CompilerService compilerSvc)
        {
            SetGlobalEnvironment(host, src);
            Initialize();
            _engine.DebugController?.OnMachineReady(_engine.Machine);
            _engine.DebugController?.WaitForDebugEvent(DebugEventType.BeginExecution);
            var module = _engine.LoadModuleImage(compilerSvc.CreateModule(src));

            return(InitProcess(host, ref module));
        }
Ejemplo n.º 13
0
        internal int RunTestScriptFromPath(string scriptFilePath, String argsScript = "")
        {
            if (argsScript != "")
            {
                commandLineArgs = argsScript.Split(' ');
            }

            ICodeSource sourceToCompile = engine.Loader.FromFile(scriptFilePath);

            return(RunTestScript(sourceToCompile, scriptFilePath));
        }
Ejemplo n.º 14
0
        private ScriptModuleHandle Compile(ICodeSource source)
        {
            RegisterScopeIfNeeded();

            var parser = new Parser();

            parser.Code = source.Code;

            var compiler = new Compiler.Compiler();

            compiler.DirectiveHandler = ResolveDirective;
            ModuleImage compiledImage;

            try
            {
                compiledImage = compiler.Compile(parser, _currentContext);
            }
            catch (ScriptException e)
            {
                if (e.ModuleName == null)
                {
                    e.ModuleName = source.SourceDescription;
                }

                throw;
            }

            foreach (var item in _predefinedVariables)
            {
                var varDef = _scope.GetVariable(item);
                if (varDef.Type == SymbolType.ContextProperty)
                {
                    compiledImage.ExportedProperties.Add(new ExportedSymbol()
                    {
                        SymbolicName = varDef.Identifier,
                        Index        = varDef.Index
                    });
                }
            }

            var mi = new ModuleInformation();

            mi.CodeIndexer = parser.GetCodeIndexer();
            // пока у модулей нет собственных имен, будет совпадать с источником модуля
            mi.ModuleName            = source.SourceDescription;
            mi.Origin                = source.SourceDescription;
            compiledImage.ModuleInfo = mi;

            return(new ScriptModuleHandle()
            {
                Module = compiledImage
            });
        }
Ejemplo n.º 15
0
 public ScriptModuleHandle CreateModule(ICodeSource source)
 {
     try
     {
         return(Compile(source));
     }
     finally
     {
         _currentContext.PopScope();
         _scope = null;
     }
 }
Ejemplo n.º 16
0
 public ScriptModuleHandle CreateModule(ICodeSource source)
 {
     try
     {
         return Compile(source);
     }
     finally
     {
         _currentContext.PopScope();
         _scope = null;
     }
 }
Ejemplo n.º 17
0
 public ModuleImage Compile(ICodeSource source)
 {
     try
     {
         return(CompileInternal(source));
     }
     finally
     {
         _currentContext.PopScope();
         _scope = null;
     }
 }
Ejemplo n.º 18
0
        private ModuleImage CompileInternal(ICodeSource source)
        {
            RegisterScopeIfNeeded();

            var parser = new Parser();

            parser.Code = source.Code;

            var compiler = new Compiler.Compiler();

            compiler.ProduceExtraCode = ProduceExtraCode;
            compiler.DirectiveHandler = ResolveDirective;

            if (DirectiveResolver != null)
            {
                DirectiveResolver.Source = source;
            }

            ModuleImage compiledImage;

            try
            {
                compiledImage = compiler.Compile(parser, _currentContext);
            }
            catch (ScriptException e)
            {
                if (e.ModuleName == null)
                {
                    e.ModuleName = source.SourceDescription;
                }

                throw;
            }
            finally
            {
                if (DirectiveResolver != null)
                {
                    DirectiveResolver.Source = null;
                }
            }

            var mi = new ModuleInformation();

            mi.CodeIndexer = parser.GetCodeIndexer();
            // пока у модулей нет собственных имен, будет совпадать с источником модуля
            mi.ModuleName            = source.SourceDescription;
            mi.Origin                = source.SourceDescription;
            compiledImage.ModuleInfo = mi;

            return(compiledImage);
        }
Ejemplo n.º 19
0
        public Process CreateProcess(IHostApplication host, ICodeSource src, CompilerService compilerSvc)
        {
            SetGlobalEnvironment(host, src);
            Initialize();
            if (_engine.DebugController != null)
            {
                _engine.DebugController.Init();
                _engine.DebugController.AttachToThread(_engine.Machine);
                _engine.DebugController.Wait();
            }
            var module = _engine.LoadModuleImage(compilerSvc.Compile(src));

            return(InitProcess(host, module));
        }
Ejemplo n.º 20
0
        public static AuthorizationModule CreateInstance(ICodeSource codeSource, IApplicationRuntime runtime, IFileProvider filesystem)
        {
            var compiler = runtime.Engine.GetCompilerService();

            for (int i = 0; i < _ownMethods.Count; i++)
            {
                compiler.DefineMethod(_ownMethods.GetMethodInfo(i));
            }

            var moduleImage = compiler.Compile(codeSource);
            var module      = runtime.Engine.LoadModuleImage(moduleImage);

            return(new AuthorizationModule(module, filesystem, runtime));
        }
Ejemplo n.º 21
0
        public static ScriptModuleHandle CompileModule(CompilerService compiler, ICodeSource src)
        {
            for (int i = 0; i < _ownProperties.Count; i++)
            {
                var currentProp = _ownProperties.GetProperty(i);
                compiler.DefineVariable(currentProp.Name, currentProp.Alias, SymbolType.ContextProperty);
            }

            for (int i = 0; i < _ownMethods.Count; i++)
            {
                compiler.DefineMethod(_ownMethods.GetMethodInfo(i));
            }

            return(compiler.CreateModule(src));
        }
Ejemplo n.º 22
0
        private int RunTestScript(ICodeSource source, string resourceName)
        {
            var module = Engine.GetCompilerService().Compile(source);

            Engine.LoadUserScript(new UserAddedScript
            {
                Type   = UserAddedScriptType.Class,
                Image  = module,
                Symbol = resourceName
            });

            var process = Engine.CreateProcess(this, source);

            return(process.Start());
        }
Ejemplo n.º 23
0
 public void AddDataProcessorManagers(System.Collections.Hashtable managerFiles)
 {
     ScriptEngine.HostedScript.Library.StructureImpl dataProcessors = new ScriptEngine.HostedScript.Library.StructureImpl();
     // Добавляем обработки, написанные на OneScript
     foreach (System.Collections.DictionaryEntry cm in managerFiles)
     {
         ICodeSource src             = _hostedScript.Loader.FromString(InsertMandatoryMethods((string)cm.Value, (string)cm.Key));
         var         compilerService = _hostedScript.GetCompilerService();
         var         module          = compilerService.CreateModule(src);
         var         _loaded         = _hostedScript.EngineInstance.LoadModuleImage(module);
         dataProcessors.Insert((string)cm.Key, (IValue)_hostedScript.EngineInstance.NewObject(_loaded));
     }
     // Добавляем библиотеки как обработки
     AddLibrariesAsDataProcessors(dataProcessors);
     _hostedScript.EngineInstance.Environment.SetGlobalProperty("Обработки", new ScriptEngine.HostedScript.Library.FixedStructureImpl(dataProcessors));
 }
Ejemplo n.º 24
0
        public static ApplicationInstance Create(ICodeSource src, IApplicationRuntime webApp)
        {
            var compiler = webApp.Engine.GetCompilerService();

            for (int i = 0; i < OwnMethods.Count; i++)
            {
                compiler.DefineMethod(OwnMethods.GetMethodInfo(i));
            }

            var bc  = compiler.CreateModule(src);
            var app = new ApplicationInstance(webApp.Engine.LoadModuleImage(bc));

            webApp.Engine.InitializeSDO(app);

            return(app);
        }
Ejemplo n.º 25
0
        public static ApplicationInstance Create(ICodeSource src, IApplicationRuntime webApp)
        {
            var compiler = webApp.Engine.GetCompilerService();

            for (int i = 0; i < OwnMethods.Count; i++)
            {
                compiler.DefineMethod(OwnMethods.GetMethodInfo(i));
            }

            var bc      = compiler.Compile(src);
            var app     = new ApplicationInstance(new LoadedModule(bc));
            var machine = MachineInstance.Current;

            webApp.Environment.LoadMemory(machine);
            webApp.Engine.InitializeSDO(app);

            return(app);
        }
Ejemplo n.º 26
0
        private void ThrowIfTypeExist(string typeName, ICodeSource code)
        {
            if (TypeManager.IsKnownType(typeName) && _loadedModules.ContainsKey(typeName))
            {
                using (MD5 md5Hash = MD5.Create())
                {
                    string moduleCode = code.Code;
                    string hash       = GetMd5Hash(md5Hash, moduleCode);
                    string storedHash = _fileHashes[typeName];

                    StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                    if (comparer.Compare(hash, storedHash) != 0)
                    {
                        throw new RuntimeException("Type «" + typeName + "» already registered");
                    }
                }
            }
        }
Ejemplo n.º 27
0
        System.Collections.Hashtable _dataProcessorObjectModules; // Список модулей объекта обработок

        public DataProcessorsManagerImpl(HostedScriptEngine hostedScript, System.Collections.Hashtable managerFiles, System.Collections.Hashtable objectFiles)
        {
            _hostedScript = hostedScript;
            _dataProcessorObjectModules = new System.Collections.Hashtable();

            foreach (System.Collections.DictionaryEntry co in objectFiles)
            {
                ICodeSource src = _hostedScript.Loader.FromString((string)co.Value);

                var compilerService = _hostedScript.GetCompilerService();
                var module          = compilerService.CreateModule(src);

                var _loaded = _hostedScript.EngineInstance.LoadModuleImage(module);
                _dataProcessorObjectModules.Add(co.Key, _loaded);
            }

            AddDataProcessorManagers(managerFiles);
        }
        private LoadedModule CompileControllerModule(ICodeSource codeSrc)
        {
            LoadedModule module;

            try
            {
                _fw.DebugCurrentThread();
                _classAttribResolver.BeforeCompilation();
                module = LoadControllerCode(codeSrc);
            }
            finally
            {
                _fw.StopDebugCurrentThread();
                _classAttribResolver.AfterCompilation();
            }

            return(module);
        }
Ejemplo n.º 29
0
        public void rr(string source)
        {
            ICodeSource sourceToCompile = Engine.Loader.FromFile(source);
            ModuleImage module          = Engine.GetCompilerService().Compile(sourceToCompile);

            UserAddedScript script = new UserAddedScript
            {
                Type   = UserAddedScriptType.Class,
                Image  = module,
                Symbol = source
            };

            Engine.LoadUserScript(script);

            //var builder = new ClassBuilder<UserScriptContextInstance>();
            //var reflected = builder.SetModule(module)
            //                       .SetTypeName("Dummy")
            //                       .ExportDefaults()
            //                       .Build();
        }
Ejemplo n.º 30
0
 public Process CreateProcess(IHostApplication host, ScriptModuleHandle moduleHandle, ICodeSource src)
 {
     SetGlobalEnvironment(host, src);
     var module = _engine.LoadModuleImage(moduleHandle);
     return InitProcess(host, src, ref module);
 }
Ejemplo n.º 31
0
 private Process InitProcess(IHostApplication host, ICodeSource src, ref LoadedModuleHandle module)
 {
     Initialize();
     var process = new Process(host, module, _engine);
     return process;
 }
Ejemplo n.º 32
0
        private void ThrowIfTypeExist(string typeName, ICodeSource code)
        {
            if (TypeManager.IsKnownType(typeName) && _loadedModules.ContainsKey(typeName))
            {
                using (MD5 md5Hash = MD5.Create())
                {
                    string moduleCode = code.Code;
                    string hash = GetMd5Hash(md5Hash, moduleCode);
                    string storedHash = _fileHashes[typeName];

                    StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                    if(comparer.Compare(hash, storedHash) != 0)
                        throw new RuntimeException("Type «" + typeName + "» already registered");
                }

            }
        }
Ejemplo n.º 33
0
 public void SetGlobalEnvironment(IHostApplication host, ICodeSource src)
 {
     _globalCtx.ApplicationHost = host;
     _globalCtx.CodeSource      = src;
     _globalCtx.InitInstance();
 }
Ejemplo n.º 34
0
 public Process CreateProcess(IHostApplication host, ICodeSource src, CompilerService compilerSvc)
 {
     SetGlobalEnvironment(host, src);
     var module = _engine.LoadModuleImage(compilerSvc.CreateModule(src));
     return InitProcess(host, src, ref module);
 }
Ejemplo n.º 35
0
 public Process CreateProcess(IHostApplication host, ScriptModuleHandle moduleHandle, ICodeSource src)
 {
     return(CreateProcess(host, moduleHandle.Module, src));
 }
        private void TryCreateInternal()
        {
            if (_args.Input.Is <PlanarDensity, Length, LinearDensity>("*"))
            {
                Debug.Write("");
            }

            var cc = _args.Input;
            var lu = cc.LeftMethodArgumentName + ".Unit";
            var ru = cc.RightMethodArgumentName + ".Unit";

            Scan(ValueOfSomeTypeExpressionRoot.Left, cc.Left.Unit, Kind2.Property, ExpressionPath.FromSplit(lu));
            Scan(ValueOfSomeTypeExpressionRoot.Right, cc.Right.Unit, Kind2.Property, ExpressionPath.FromSplit(ru));

            _conversionMethodScanner = ConversionMethodScanner.Scan(_resolver.Assembly);

            var reductor = new ExpressionsReductor(n =>
            {
                string varName = null;
                if (n == lu || n == ru)
                {
                    varName = n.Replace(".", "");
                }
                return(AddVariable(n, varName));
            });

            var convertType = Construct(cc.Right.Unit);

            if (convertType.Code == ru)
            {
                convertType = null;
            }
            else
            {
                reductor.AddAny(convertType);
            }
            // convertType.AddToDeleteMe(reductor);

            ICodeSource result = Construct(cc.Result.Unit);

            Func <string> addExtraValueMultiplication = null;

            ICodeSource G1()
            {
                if (!_resolver.TryGetValue(cc.Result.Unit.TypeName, out var type1))
                {
                    throw new NotImplementedException();
                }
                if (_conversionMethodScanner.Dictionary.TryGetValue(type1, out var list))
                {
                    var typesDict = TypeFinder.Make(_sink);
                    foreach (var i in list)
                    {
                        var aaa = typesDict.FindParameters(i, null, out var hl);
                        return(MethodCallCodeSource.Make(i, aaa, hl));
                    }
                }

                return(null);
            }

            if (result is null)
            {
                result = G1();
                if (result != null)
                {
                    addExtraValueMultiplication = () => { return(result.Code + "." + nameof(IUnitDefinition.Multiplication)); };
                }
            }

            if (result is null)
            {
            }
            reductor.AddAny(result);
            //result.AddToDeleteMe(reductor);
            reductor.ReduceExpressions();
            if (addExtraValueMultiplication != null)
            {
                reductor.ForceReduce(new ExpressionPath(result));
            }


            // =============================
            if (result?.Code == "specificHeatCapacity.Unit.DenominatorUnit")
            {
                Debug.WriteLine("");
            }
            switch (convertType)
            {
            case null:
                break;

            case MethodCallCodeSource _:
                _args.Result.ConvertRight(AddVariable(convertType.Code, "targetRightUnit"));
                break;

            default:
                _args.Result.ConvertRight(convertType.Code);
                break;
            }

            if (result is MethodCallCodeSource)
            {
                _args.Result.ResultUnit = AddVariable(result.Code, "resultUnit");
            }
            else
            {
                _args.Result.ResultUnit = result.Code;
            }
            if (addExtraValueMultiplication != null)
            {
                _args.Result.ResultMultiplication = addExtraValueMultiplication();
            }
        }
Ejemplo n.º 37
0
 public FakeCodeSource(ICodeSource original, string fakeFileName)
 {
     _original = original;
     _name     = fakeFileName;
 }
Ejemplo n.º 38
0
 private void SetGlobalEnvironment(IHostApplication host, ICodeSource src)
 {
     _globalCtx.ApplicationHost = host;
     _globalCtx.CodeSource = src;
     _globalCtx.InitInstance();
 }
Ejemplo n.º 39
0
 public Process CreateProcess(IHostApplication host, ICodeSource src)
 {
     return CreateProcess(host, src, GetCompilerService());
 }