From d9e69fd00ed51cfba0d56628fc8648aa98a4715f Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 25 Apr 2024 10:09:02 +0300 Subject: [PATCH 01/32] =?UTF-8?q?=D0=94=D0=BE=D0=BA=D1=83=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D1=8F=20=D0=B8=20=D1=81=D0=B5?= =?UTF-8?q?=D1=80=D0=B2=D0=B8=D1=81=D0=BD=D1=8B=D0=B9=20=D0=BC=D0=B5=D1=82?= =?UTF-8?q?=D0=BE=D0=B4=20=D0=BD=D0=B0=D1=81=D1=82=D1=80=D0=BE=D0=B9=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=B2=D0=B8=D0=B6=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Compilation/ICompileTimeDependencyResolver.cs | 5 +++++ src/ScriptEngine/Hosting/EngineBuilderExtensions.cs | 6 ++++++ src/ScriptEngine/IDependencyResolver.cs | 7 +++++++ 3 files changed, 18 insertions(+) diff --git a/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs b/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs index 0fc5b30e3..2692c83de 100644 --- a/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs +++ b/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs @@ -11,6 +11,11 @@ namespace OneScript.Compilation { public interface ICompileTimeDependencyResolver { + /// + /// Загрузить библиотеку для модуля + /// + /// Модуль в котором объявлен импорт + /// имя библиотеки void Resolve(SourceCode module, string libraryName); } } \ No newline at end of file diff --git a/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs b/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs index 39b273efd..f612663ef 100644 --- a/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs +++ b/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs @@ -90,5 +90,11 @@ public static IEngineBuilder WithDebugger(this IEngineBuilder b, IDebugControlle b.Services.RegisterSingleton(debugger); return b; } + + public static IEngineBuilder SetupServices(this IEngineBuilder b, Action setup) + { + setup(b.Services); + return b; + } } } \ No newline at end of file diff --git a/src/ScriptEngine/IDependencyResolver.cs b/src/ScriptEngine/IDependencyResolver.cs index 291e36ad0..ee038a37e 100644 --- a/src/ScriptEngine/IDependencyResolver.cs +++ b/src/ScriptEngine/IDependencyResolver.cs @@ -9,8 +9,15 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine { + /// + /// Разрешитель внещних зависимостей (библиотек) + /// public interface IDependencyResolver : ICompileTimeDependencyResolver { + /// + /// Инициализировать разрешитель. Вызывается при создании ScriptingEngine + /// + /// Движок, который разрешитель может сохранить у себя void Initialize(ScriptingEngine engine); } } \ No newline at end of file From 1e3ba2beb9822119436e7595606284d55b4da5ef Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 2 Jun 2024 10:13:41 +0300 Subject: [PATCH 02/32] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7?= =?UTF-8?q?=D1=87=D0=B8=D0=BA=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D0=B8=D0=BC?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Libraries/DependencyLoader.cs | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/ScriptEngine/Libraries/DependencyLoader.cs diff --git a/src/ScriptEngine/Libraries/DependencyLoader.cs b/src/ScriptEngine/Libraries/DependencyLoader.cs new file mode 100644 index 000000000..a77558ad9 --- /dev/null +++ b/src/ScriptEngine/Libraries/DependencyLoader.cs @@ -0,0 +1,34 @@ +/*---------------------------------------------------------- +This Source Code Form is subject to the terms of the +Mozilla Public License, v.2.0. If a copy of the MPL +was not distributed with this file, You can obtain one +at http://mozilla.org/MPL/2.0/. +----------------------------------------------------------*/ + +using OneScript.Sources; +using ScriptEngine.Machine.Contexts; + +namespace ScriptEngine +{ + public class DependencyLoader + { + private readonly ScriptingEngine _engine; + private readonly RuntimeEnvironment _env; + + public DependencyLoader(ScriptingEngine engine) + { + _engine = engine; + _env = engine.Environment; + } + + public void AddClass(ICodeSource source, string className) + { + + } + + public void AddModule(ICodeSource source, string moduleName) + { + + } + } +} \ No newline at end of file From a14e4966e8414fb3be7619eece2fe87b7605440e Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 25 Apr 2024 10:09:02 +0300 Subject: [PATCH 03/32] =?UTF-8?q?=D0=94=D0=BE=D0=BA=D1=83=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D1=8F=20=D0=B8=20=D1=81=D0=B5?= =?UTF-8?q?=D1=80=D0=B2=D0=B8=D1=81=D0=BD=D1=8B=D0=B9=20=D0=BC=D0=B5=D1=82?= =?UTF-8?q?=D0=BE=D0=B4=20=D0=BD=D0=B0=D1=81=D1=82=D1=80=D0=BE=D0=B9=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=B2=D0=B8=D0=B6=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Compilation/ICompileTimeDependencyResolver.cs | 5 +++++ src/ScriptEngine/Hosting/EngineBuilderExtensions.cs | 6 ++++++ src/ScriptEngine/IDependencyResolver.cs | 7 +++++++ 3 files changed, 18 insertions(+) diff --git a/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs b/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs index 0fc5b30e3..2692c83de 100644 --- a/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs +++ b/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs @@ -11,6 +11,11 @@ namespace OneScript.Compilation { public interface ICompileTimeDependencyResolver { + /// + /// Загрузить библиотеку для модуля + /// + /// Модуль в котором объявлен импорт + /// имя библиотеки void Resolve(SourceCode module, string libraryName); } } \ No newline at end of file diff --git a/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs b/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs index dc4ba7c63..971fdff16 100644 --- a/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs +++ b/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs @@ -92,5 +92,11 @@ public static IEngineBuilder WithDebugger(this IEngineBuilder b, IDebugControlle b.Services.RegisterSingleton(debugger); return b; } + + public static IEngineBuilder SetupServices(this IEngineBuilder b, Action setup) + { + setup(b.Services); + return b; + } } } \ No newline at end of file diff --git a/src/ScriptEngine/IDependencyResolver.cs b/src/ScriptEngine/IDependencyResolver.cs index 291e36ad0..ee038a37e 100644 --- a/src/ScriptEngine/IDependencyResolver.cs +++ b/src/ScriptEngine/IDependencyResolver.cs @@ -9,8 +9,15 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine { + /// + /// Разрешитель внещних зависимостей (библиотек) + /// public interface IDependencyResolver : ICompileTimeDependencyResolver { + /// + /// Инициализировать разрешитель. Вызывается при создании ScriptingEngine + /// + /// Движок, который разрешитель может сохранить у себя void Initialize(ScriptingEngine engine); } } \ No newline at end of file From 90bce519346e1e799705b109fe315c457e6bdcb6 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 2 Jun 2024 10:13:41 +0300 Subject: [PATCH 04/32] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7?= =?UTF-8?q?=D1=87=D0=B8=D0=BA=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D0=B8=D0=BC?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Libraries/DependencyLoader.cs | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/ScriptEngine/Libraries/DependencyLoader.cs diff --git a/src/ScriptEngine/Libraries/DependencyLoader.cs b/src/ScriptEngine/Libraries/DependencyLoader.cs new file mode 100644 index 000000000..a77558ad9 --- /dev/null +++ b/src/ScriptEngine/Libraries/DependencyLoader.cs @@ -0,0 +1,34 @@ +/*---------------------------------------------------------- +This Source Code Form is subject to the terms of the +Mozilla Public License, v.2.0. If a copy of the MPL +was not distributed with this file, You can obtain one +at http://mozilla.org/MPL/2.0/. +----------------------------------------------------------*/ + +using OneScript.Sources; +using ScriptEngine.Machine.Contexts; + +namespace ScriptEngine +{ + public class DependencyLoader + { + private readonly ScriptingEngine _engine; + private readonly RuntimeEnvironment _env; + + public DependencyLoader(ScriptingEngine engine) + { + _engine = engine; + _env = engine.Environment; + } + + public void AddClass(ICodeSource source, string className) + { + + } + + public void AddModule(ICodeSource source, string moduleName) + { + + } + } +} \ No newline at end of file From 7e562ec7734e46b4a137cfa87d72fda0f2853d95 Mon Sep 17 00:00:00 2001 From: Andrey Ovsyankin Date: Tue, 17 Sep 2024 16:08:44 +0300 Subject: [PATCH 05/32] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B0=20=D0=BE=D0=BF=D0=B5=D1=87=D0=B0=D1=82?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=B8=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA=D0=B0=20?= =?UTF-8?q?=D1=81=D0=B1=D0=BE=D1=80=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/IDependencyResolver.cs | 2 +- src/ScriptEngine/Libraries/DependencyLoader.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ScriptEngine/IDependencyResolver.cs b/src/ScriptEngine/IDependencyResolver.cs index ee038a37e..76369776a 100644 --- a/src/ScriptEngine/IDependencyResolver.cs +++ b/src/ScriptEngine/IDependencyResolver.cs @@ -10,7 +10,7 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine { /// - /// Разрешитель внещних зависимостей (библиотек) + /// Разрешитель внешних зависимостей (библиотек) /// public interface IDependencyResolver : ICompileTimeDependencyResolver { diff --git a/src/ScriptEngine/Libraries/DependencyLoader.cs b/src/ScriptEngine/Libraries/DependencyLoader.cs index a77558ad9..e66a4c159 100644 --- a/src/ScriptEngine/Libraries/DependencyLoader.cs +++ b/src/ScriptEngine/Libraries/DependencyLoader.cs @@ -5,6 +5,7 @@ This Source Code Form is subject to the terms of the at http://mozilla.org/MPL/2.0/. ----------------------------------------------------------*/ +using OneScript.Contexts; using OneScript.Sources; using ScriptEngine.Machine.Contexts; @@ -13,7 +14,7 @@ namespace ScriptEngine public class DependencyLoader { private readonly ScriptingEngine _engine; - private readonly RuntimeEnvironment _env; + private readonly IRuntimeEnvironment _env; public DependencyLoader(ScriptingEngine engine) { From 2352c8d31093ee03b10eca8edd409f8c862e0e4c Mon Sep 17 00:00:00 2001 From: Andrey Ovsyankin Date: Tue, 17 Sep 2024 16:43:18 +0300 Subject: [PATCH 06/32] =?UTF-8?q?=D0=A3=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D1=8B=20=D0=BD=D0=B5=D0=B8=D1=81=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7?= =?UTF-8?q?=D1=83=D0=B5=D0=BC=D1=8B=D0=B5=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81?= =?UTF-8?q?=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SyntaxAnalysis/ParserOptions.cs | 16 ---------------- src/ScriptEngine/Compiler/CompilerFrontend.cs | 3 --- src/ScriptEngine/Compiler/CompilerOptions.cs | 16 ---------------- 3 files changed, 35 deletions(-) delete mode 100644 src/OneScript.Language/SyntaxAnalysis/ParserOptions.cs delete mode 100644 src/ScriptEngine/Compiler/CompilerOptions.cs diff --git a/src/OneScript.Language/SyntaxAnalysis/ParserOptions.cs b/src/OneScript.Language/SyntaxAnalysis/ParserOptions.cs deleted file mode 100644 index c7a32d038..000000000 --- a/src/OneScript.Language/SyntaxAnalysis/ParserOptions.cs +++ /dev/null @@ -1,16 +0,0 @@ -/*---------------------------------------------------------- -This Source Code Form is subject to the terms of the -Mozilla Public License, v.2.0. If a copy of the MPL -was not distributed with this file, You can obtain one -at http://mozilla.org/MPL/2.0/. -----------------------------------------------------------*/ - -namespace OneScript.Language.SyntaxAnalysis -{ - public class ParserOptions - { - public IErrorSink ErrorSink { get; set; } = new ThrowingErrorSink(); - - public PreprocessorHandlers PreprocessorHandlers { get; set; } - } -} \ No newline at end of file diff --git a/src/ScriptEngine/Compiler/CompilerFrontend.cs b/src/ScriptEngine/Compiler/CompilerFrontend.cs index 3f1a9d965..ba94a91d2 100644 --- a/src/ScriptEngine/Compiler/CompilerFrontend.cs +++ b/src/ScriptEngine/Compiler/CompilerFrontend.cs @@ -6,8 +6,6 @@ This Source Code Form is subject to the terms of the ----------------------------------------------------------*/ using System; using System.Collections.Generic; -using System.Linq; -using OneScript.Commons; using OneScript.Compilation; using OneScript.Compilation.Binding; using OneScript.Contexts; @@ -16,7 +14,6 @@ This Source Code Form is subject to the terms of the using OneScript.Language; using OneScript.Language.SyntaxAnalysis; using OneScript.Language.SyntaxAnalysis.AstNodes; -using ScriptEngine.Machine; using ScriptEngine.Machine.Contexts; namespace ScriptEngine.Compiler diff --git a/src/ScriptEngine/Compiler/CompilerOptions.cs b/src/ScriptEngine/Compiler/CompilerOptions.cs deleted file mode 100644 index 2ec7dbca9..000000000 --- a/src/ScriptEngine/Compiler/CompilerOptions.cs +++ /dev/null @@ -1,16 +0,0 @@ -/*---------------------------------------------------------- -This Source Code Form is subject to the terms of the -Mozilla Public License, v.2.0. If a copy of the MPL -was not distributed with this file, You can obtain one -at http://mozilla.org/MPL/2.0/. -----------------------------------------------------------*/ - -using OneScript.Language.SyntaxAnalysis; - -namespace ScriptEngine.Compiler -{ - public class CompilerOptions : ParserOptions - { - public IDependencyResolver DependencyResolver { get; set; } - } -} \ No newline at end of file From 30f4c15ca2968a90969cfc9187494666a6e42377 Mon Sep 17 00:00:00 2001 From: Andrey Ovsyankin Date: Tue, 17 Sep 2024 18:13:26 +0300 Subject: [PATCH 07/32] =?UTF-8?q?=D0=A0=D1=8F=D0=B4=20=D0=BF=D0=B5=D1=80?= =?UTF-8?q?=D0=B5=D0=B8=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B9=20=D0=B8=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5=D1=89?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine.HostedScript/LibraryLoader.cs | 1 + src/ScriptEngine/Compiler/ApplicationDump.cs | 1 + src/ScriptEngine/Compiler/CompilerFrontend.cs | 4 ++++ src/ScriptEngine/Compiler/EvalCompiler.cs | 3 +++ .../{ => Libraries}/ExternalLibraryDef.cs | 14 +++++++------- .../{ => Libraries}/ILibraryManager.cs | 2 +- src/ScriptEngine/RuntimeEnvironment.cs | 1 + src/ScriptEngine/ScriptingEngine.cs | 1 + 8 files changed, 19 insertions(+), 8 deletions(-) rename src/ScriptEngine/{ => Libraries}/ExternalLibraryDef.cs (95%) rename src/ScriptEngine/{ => Libraries}/ILibraryManager.cs (95%) diff --git a/src/ScriptEngine.HostedScript/LibraryLoader.cs b/src/ScriptEngine.HostedScript/LibraryLoader.cs index 505250d86..9501180e4 100644 --- a/src/ScriptEngine.HostedScript/LibraryLoader.cs +++ b/src/ScriptEngine.HostedScript/LibraryLoader.cs @@ -15,6 +15,7 @@ This Source Code Form is subject to the terms of the using OneScript.Contexts; using OneScript.Exceptions; using OneScript.Execution; +using ScriptEngine.Libraries; namespace ScriptEngine.HostedScript { diff --git a/src/ScriptEngine/Compiler/ApplicationDump.cs b/src/ScriptEngine/Compiler/ApplicationDump.cs index dbbfe5243..6f807ca3e 100644 --- a/src/ScriptEngine/Compiler/ApplicationDump.cs +++ b/src/ScriptEngine/Compiler/ApplicationDump.cs @@ -5,6 +5,7 @@ This Source Code Form is subject to the terms of the at http://mozilla.org/MPL/2.0/. ----------------------------------------------------------*/ +using ScriptEngine.Libraries; using System; namespace ScriptEngine.Compiler diff --git a/src/ScriptEngine/Compiler/CompilerFrontend.cs b/src/ScriptEngine/Compiler/CompilerFrontend.cs index ba94a91d2..951a93cf7 100644 --- a/src/ScriptEngine/Compiler/CompilerFrontend.cs +++ b/src/ScriptEngine/Compiler/CompilerFrontend.cs @@ -18,6 +18,10 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine.Compiler { + /// + /// Часть компилятора, независимая от рантайма (нативного или стекового) + /// Запускает компиляцию модуля, строит AST и делегирует построение кода в бэкенд компилятора под конкретный рантайм. + /// public class CompilerFrontend : CompilerFrontendBase { private readonly IDependencyResolver _dependencyResolver; diff --git a/src/ScriptEngine/Compiler/EvalCompiler.cs b/src/ScriptEngine/Compiler/EvalCompiler.cs index 603fa8702..373f60665 100644 --- a/src/ScriptEngine/Compiler/EvalCompiler.cs +++ b/src/ScriptEngine/Compiler/EvalCompiler.cs @@ -15,6 +15,9 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine.Compiler { + /// + /// Компилятор вычислимых выражений + /// public class EvalCompiler : CompilerFrontendBase { private readonly DefaultCompilerBackend _backend; diff --git a/src/ScriptEngine/ExternalLibraryDef.cs b/src/ScriptEngine/Libraries/ExternalLibraryDef.cs similarity index 95% rename from src/ScriptEngine/ExternalLibraryDef.cs rename to src/ScriptEngine/Libraries/ExternalLibraryDef.cs index 978897621..30bc701a8 100644 --- a/src/ScriptEngine/ExternalLibraryDef.cs +++ b/src/ScriptEngine/Libraries/ExternalLibraryDef.cs @@ -10,7 +10,7 @@ This Source Code Form is subject to the terms of the using OneScript.Execution; using ScriptEngine.Machine; -namespace ScriptEngine +namespace ScriptEngine.Libraries { public class ExternalLibraryDef { @@ -18,9 +18,9 @@ public ExternalLibraryDef(string name) { LibraryName = name; } - + public string LibraryName { get; } - + public IList Classes { get; } = new List(); public IList Modules { get; } = new List(); @@ -33,12 +33,12 @@ public UserAddedScript AddClass(string identifier, string filePath, StackRuntime Symbol = identifier, FilePath = filePath }; - + Classes.Add(item); return item; } - + public UserAddedScript AddModule(string identifier, string filePath, StackRuntimeModule module = null) { var item = new UserAddedScript @@ -48,13 +48,13 @@ public UserAddedScript AddModule(string identifier, string filePath, StackRuntim Symbol = identifier, FilePath = filePath }; - + Modules.Add(item); return item; } } - + public class UserAddedScript { public UserAddedScriptType Type; diff --git a/src/ScriptEngine/ILibraryManager.cs b/src/ScriptEngine/Libraries/ILibraryManager.cs similarity index 95% rename from src/ScriptEngine/ILibraryManager.cs rename to src/ScriptEngine/Libraries/ILibraryManager.cs index c3f375909..b6ab90e53 100644 --- a/src/ScriptEngine/ILibraryManager.cs +++ b/src/ScriptEngine/Libraries/ILibraryManager.cs @@ -7,7 +7,7 @@ This Source Code Form is subject to the terms of the using System.Collections.Generic; -namespace ScriptEngine +namespace ScriptEngine.Libraries { /// /// Временный класс для откусывания ответственностей от RuntimeEnvironment diff --git a/src/ScriptEngine/RuntimeEnvironment.cs b/src/ScriptEngine/RuntimeEnvironment.cs index aa1f47106..0950b088a 100644 --- a/src/ScriptEngine/RuntimeEnvironment.cs +++ b/src/ScriptEngine/RuntimeEnvironment.cs @@ -9,6 +9,7 @@ This Source Code Form is subject to the terms of the using OneScript.Commons; using OneScript.Compilation.Binding; using OneScript.Contexts; +using ScriptEngine.Libraries; using ScriptEngine.Machine; using ScriptEngine.Machine.Contexts; using SymbolScope = OneScript.Compilation.Binding.SymbolScope; diff --git a/src/ScriptEngine/ScriptingEngine.cs b/src/ScriptEngine/ScriptingEngine.cs index c49736d45..5e21149cd 100644 --- a/src/ScriptEngine/ScriptingEngine.cs +++ b/src/ScriptEngine/ScriptingEngine.cs @@ -15,6 +15,7 @@ This Source Code Form is subject to the terms of the using ScriptEngine.Machine; using ScriptEngine.Machine.Contexts; using ScriptEngine.Compiler; +using ScriptEngine.Libraries; namespace ScriptEngine { From a961a431d1f97be54b1bf44e1511dde0d3890c39 Mon Sep 17 00:00:00 2001 From: Andrey Ovsyankin Date: Fri, 4 Oct 2024 12:25:21 +0300 Subject: [PATCH 08/32] =?UTF-8?q?=D0=92=D1=8B=D0=B4=D0=B5=D0=BB=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BB=D0=BE=D0=B3=D0=B8=D0=BA=D1=83=20=D0=B1=D0=B8?= =?UTF-8?q?=D0=B1=D0=BB=D0=B8=D0=BE=D1=82=D0=B5=D0=BA=20=D0=B2=20=D0=BE?= =?UTF-8?q?=D1=82=D0=B4=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9=20=D0=BA=D0=BB?= =?UTF-8?q?=D0=B0=D1=81=D1=81,=20=D1=87=D1=82=D0=BE=D0=B1=D1=8B=20=D0=BF?= =?UTF-8?q?=D0=BE=D1=87=D0=B8=D1=81=D1=82=D0=B8=D1=82=D1=8C=20RuntimeEnvir?= =?UTF-8?q?onment?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Libraries/LibraryManager.cs | 48 ++++++++++++++++++++ src/ScriptEngine/RuntimeEnvironment.cs | 20 ++------ 2 files changed, 52 insertions(+), 16 deletions(-) create mode 100644 src/ScriptEngine/Libraries/LibraryManager.cs diff --git a/src/ScriptEngine/Libraries/LibraryManager.cs b/src/ScriptEngine/Libraries/LibraryManager.cs new file mode 100644 index 000000000..6ccfdd0b3 --- /dev/null +++ b/src/ScriptEngine/Libraries/LibraryManager.cs @@ -0,0 +1,48 @@ +using OneScript.Commons; +using OneScript.Contexts; +using ScriptEngine.Machine.Contexts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ScriptEngine.Libraries +{ + /// + /// Временная имплементация временного интерфейса ILibraryManager + /// Нужна для откусывания ответственностей от RuntimeEnvironment + /// + internal class LibraryManager : ILibraryManager + { + private readonly List _externalLibs = new List(); + private readonly IRuntimeContextInstance _contextOfGlobalSymbols; + + public LibraryManager(IRuntimeContextInstance contextOfGlobalSymbols) + { + _contextOfGlobalSymbols = contextOfGlobalSymbols; + } + + public IEnumerable GetLibraries() + { + return _externalLibs.ToArray(); + } + + public void InitExternalLibrary(ScriptingEngine runtime, ExternalLibraryDef library) + { + var loadedObjects = new ScriptDrivenObject[library.Modules.Count]; + int i = 0; + foreach (var module in library.Modules) + { + var instance = runtime.CreateUninitializedSDO(module.Module); + + var propId = _contextOfGlobalSymbols.GetPropertyNumber(module.Symbol); + _contextOfGlobalSymbols.SetPropValue(propId, instance); + loadedObjects[i++] = instance; + } + + _externalLibs.Add(library); + loadedObjects.ForEach(runtime.InitializeSDO); + } + } +} diff --git a/src/ScriptEngine/RuntimeEnvironment.cs b/src/ScriptEngine/RuntimeEnvironment.cs index 0950b088a..d54a08097 100644 --- a/src/ScriptEngine/RuntimeEnvironment.cs +++ b/src/ScriptEngine/RuntimeEnvironment.cs @@ -11,7 +11,6 @@ This Source Code Form is subject to the terms of the using OneScript.Contexts; using ScriptEngine.Libraries; using ScriptEngine.Machine; -using ScriptEngine.Machine.Contexts; using SymbolScope = OneScript.Compilation.Binding.SymbolScope; namespace ScriptEngine @@ -26,11 +25,12 @@ public class RuntimeEnvironment : IRuntimeEnvironment, ILibraryManager private readonly List _contexts = new List(); - private readonly List _externalLibs = new List(); + private readonly ILibraryManager _libraryManager; public RuntimeEnvironment() { _injectedProperties = new PropertyBag(); + _libraryManager = new LibraryManager(_injectedProperties); } private void CreateGlobalScopeIfNeeded() @@ -106,24 +106,12 @@ public IValue GetGlobalProperty(string propertyName) public IEnumerable GetLibraries() { - return _externalLibs.ToArray(); + return _libraryManager.GetLibraries(); } public void InitExternalLibrary(ScriptingEngine runtime, ExternalLibraryDef library) { - var loadedObjects = new ScriptDrivenObject[library.Modules.Count]; - int i = 0; - foreach (var module in library.Modules) - { - var instance = runtime.CreateUninitializedSDO(module.Module); - - var propId = _injectedProperties.GetPropertyNumber(module.Symbol); - _injectedProperties.SetPropValue(propId, instance); - loadedObjects[i++] = instance; - } - - _externalLibs.Add(library); - loadedObjects.ForEach(runtime.InitializeSDO); + _libraryManager.InitExternalLibrary(runtime, library); } private class WrappedPropertySymbol : IPropertySymbol From 2c8de5c4292a9eaae913939e5a0073787e5624d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D0=B8=D0=BF=D0=BE=D0=B2=20=D0=9D=D0=B8=D0=BA?= =?UTF-8?q?=D0=B8=D1=82=D0=B0?= Date: Thu, 17 Oct 2024 06:48:42 +0300 Subject: [PATCH 09/32] =?UTF-8?q?=D0=A0=D0=B0=D1=81=D1=88=D0=B8=D1=80?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BE=D0=BF=D0=B8=D1=81=D0=B0=D0=BD=D0=B8=D0=B5?= =?UTF-8?q?=20=D0=B4=D0=BB=D1=8F=20macos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 25bf3d5c1..a11c1a050 100644 --- a/README.md +++ b/README.md @@ -42,9 +42,9 @@ OneScript позволяет создавать и выполнять текст - установить [homebrew](https://brew.sh/index_ru) - установить mono командой `brew install mono` -- скачать [ovm](https://github.com/oscript-library/ovm/releases) -- выполнить команду `mono ovm.exe install stable` -- выполнить команду `mono ovm.exe use stable` +- скачать [ovm](https://github.com/oscript-library/ovm/releases). Скачиваем именно `ovm.exe` +- выполнить команду `mono path/to/ovm.exe install stable`. Чтобы корректно указать путь до `ovm.exe` можно перенести мышкой файл `ovm.exe`. Должно получится примерно так: `mono Users/username/Downloads/ovm.exe install stable` +- выполнить команду `mono path/to/ovm.exe use stable` - перезапустить терминал #### Донастройка Self-Contained варианта поставки (не требующего инсталляции dotnet) From fb86bfd920dd57114ec1f6c526bfe26c497b8e7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D0=B8=D0=BF=D0=BE=D0=B2=20=D0=9D=D0=B8=D0=BA?= =?UTF-8?q?=D0=B8=D1=82=D0=B0?= Date: Thu, 17 Oct 2024 07:04:18 +0300 Subject: [PATCH 10/32] =?UTF-8?q?=D0=9F=D0=BE=D0=B4=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D0=BB=20=D1=81=D1=82=D0=B8=D0=BB=D0=B8=D1=81=D1=82?= =?UTF-8?q?=D0=B8=D0=BA=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a11c1a050..9a7e6973b 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,10 @@ OneScript позволяет создавать и выполнять текст - установить [homebrew](https://brew.sh/index_ru) - установить mono командой `brew install mono` -- скачать [ovm](https://github.com/oscript-library/ovm/releases). Скачиваем именно `ovm.exe` -- выполнить команду `mono path/to/ovm.exe install stable`. Чтобы корректно указать путь до `ovm.exe` можно перенести мышкой файл `ovm.exe`. Должно получится примерно так: `mono Users/username/Downloads/ovm.exe install stable` +- скачать [ovm](https://github.com/oscript-library/ovm/releases). Скачать файл `ovm.exe` (несмотря на то что расширение .exe он запустится на MacOS) +- выполнить команду `mono path/to/ovm.exe install stable`. + + Совет: *Чтобы корректно указать путь до `ovm.exe` перенесите мышкой файл `ovm.exe` в терминал. Должно получится примерно так: `mono Users/username/Downloads/ovm.exe install stable`* - выполнить команду `mono path/to/ovm.exe use stable` - перезапустить терминал From 5e00ddff4fc9b4ec1b0ae4554eb366451ecdbc7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D0=B8=D0=BF=D0=BE=D0=B2=20=D0=9D=D0=B8=D0=BA?= =?UTF-8?q?=D0=B8=D1=82=D0=B0?= Date: Thu, 17 Oct 2024 07:13:17 +0300 Subject: [PATCH 11/32] =?UTF-8?q?=D0=95=D1=89=D0=B5=20=D1=83=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D0=B8=D0=BB=20=D0=B8=D0=BD=D1=81=D1=82=D1=80?= =?UTF-8?q?=D1=83=D0=BA=D1=86=D0=B8=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9a7e6973b..3dec27387 100644 --- a/README.md +++ b/README.md @@ -42,10 +42,10 @@ OneScript позволяет создавать и выполнять текст - установить [homebrew](https://brew.sh/index_ru) - установить mono командой `brew install mono` -- скачать [ovm](https://github.com/oscript-library/ovm/releases). Скачать файл `ovm.exe` (несмотря на то что расширение .exe он запустится на MacOS) -- выполнить команду `mono path/to/ovm.exe install stable`. +- скачать [ovm](https://github.com/oscript-library/ovm/releases). Скачать файл `ovm.exe` (несмотря на расширение .exe он сработает на MacOS) +- выполнить команду `mono path/to/ovm.exe install stable` - Совет: *Чтобы корректно указать путь до `ovm.exe` перенесите мышкой файл `ovm.exe` в терминал. Должно получится примерно так: `mono Users/username/Downloads/ovm.exe install stable`* + *Совет: Чтобы корректно указать путь до `ovm.exe` перенесите мышкой файл `ovm.exe` в терминал. Пример полной команды: `mono Users/username/Downloads/ovm.exe install stable`* - выполнить команду `mono path/to/ovm.exe use stable` - перезапустить терминал From 1e7f4128a975ed1bcb66d1da46e372026d3de851 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sat, 19 Oct 2024 20:14:02 +0300 Subject: [PATCH 12/32] Revert "closes #1451" This reverts commit 3d6d6d61c695357eeba4e08a7ec529c5b0db8c45. --- src/ScriptEngine/Machine/RuntimeScopes.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/ScriptEngine/Machine/RuntimeScopes.cs b/src/ScriptEngine/Machine/RuntimeScopes.cs index 88888251b..b1e175d0f 100644 --- a/src/ScriptEngine/Machine/RuntimeScopes.cs +++ b/src/ScriptEngine/Machine/RuntimeScopes.cs @@ -8,7 +8,6 @@ This Source Code Form is subject to the terms of the using System; using System.Collections; using System.Collections.Generic; -using System.Linq; using OneScript.Contexts; namespace ScriptEngine.Machine @@ -25,7 +24,7 @@ public class RuntimeScopes : IReadOnlyList public RuntimeScopes(IReadOnlyList outerScopes, AttachedContext innerScope) { - _outerScopes = outerScopes.Select(x => new AttachedContext(x.Instance)).ToList(); + _outerScopes = outerScopes; _innerScope = innerScope; _outerScopeLast = _outerScopes.Count - 1; From 3d7d4266b7c4387f8519527a49e284d6ebe737c6 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sat, 19 Oct 2024 20:14:19 +0300 Subject: [PATCH 13/32] =?UTF-8?q?=D0=98=D0=BD=D0=BA=D1=80=D0=B5=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D1=82=20=D0=B2=D0=B5=D1=80=D1=81=D0=B8=D0=B8=20?= =?UTF-8?q?=D0=BD=D0=BE=D1=87=D0=BD=D0=B8=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 2367c2a9d..312961348 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -5,7 +5,7 @@ pipeline { environment { VersionPrefix = '2.0.0' - VersionSuffix = 'rc4'+"-${(long)(currentBuild.startTimeInMillis/60000)}" + VersionSuffix = 'rc5'+"-${(long)(currentBuild.startTimeInMillis/60000)}" outputEnc = '65001' } From 48dcda84afa04960cbfb82a8870ba1095d0a2667 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sat, 19 Oct 2024 20:41:31 +0300 Subject: [PATCH 14/32] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=8B=D1=82=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=BF=D0=BE=D0=BD=D1=8F=D1=82=D1=8C,=20=D0=BF=D0=BE?= =?UTF-8?q?=D1=87=D0=B5=D0=BC=D1=83=20=D0=BD=D0=B5=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B8=D1=80=D1=83=D0=B5=D1=82=D1=81=D1=8F=20native-api?= =?UTF-8?q?=20=D0=BD=D0=B0=20=D0=B2=D0=B8=D0=BD=D0=B4=D0=BE=D1=83=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/native-api.os | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/native-api.os b/tests/native-api.os index bfebd457f..43c842e06 100644 --- a/tests/native-api.os +++ b/tests/native-api.os @@ -73,14 +73,14 @@ ИначеЕсли СистемнаяИнформация.ТипПлатформы = ТипПлатформы.Linux_x86_64 Тогда ПутьБиблиотеки = ОбъединитьПути(КаталогСборок, "build64", "AddInNativeLin64.so"); Иначе - ПутьБиблиотеки = ""; + ВызватьИсключение "Неподдерживаемый тип платформы: " + СистемнаяИнформация.ТипПлатформы; КонецЕсли; Идентификатор = "AddinNativeDLL"; ФайлКомпоненты = Новый Файл(ПутьБиблиотеки); юТест.ПроверитьИстину(ФайлКомпоненты.Существует(), - "Файл компоненты '" + ФайлКомпоненты.Путь + "' должен существовать"); + "Файл компоненты '" + ФайлКомпоненты.ПолноеИмя + "' должен существовать"); DLLПодключенаУспешно = ПодключитьВнешнююКомпоненту(ФайлКомпоненты.ПолноеИмя, Идентификатор, ТипВнешнейКомпоненты.Native); Возврат DLLПодключенаУспешно; From ddf22de826674b696a2f777c11fb43ddf4180568 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sat, 19 Oct 2024 21:05:39 +0300 Subject: [PATCH 15/32] =?UTF-8?q?=D0=A2=D0=B5=D1=81=D1=82=20=D0=BE=D1=88?= =?UTF-8?q?=D0=B8=D0=B1=D0=BA=D0=B8=20#1451?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/eval-in-libraries/entrypoint.os | 4 ++++ ...0\234\320\276\320\264\321\203\320\273\321\214.os" | 3 +++ .../\320\242\320\265\321\201\321\202.os" | 10 ++++++++++ tests/eval.os | 12 ++++++++++++ 4 files changed, 29 insertions(+) create mode 100644 tests/eval-in-libraries/entrypoint.os create mode 100644 "tests/eval-in-libraries/src/\320\234\320\276\320\264\321\203\320\273\320\270/\320\234\320\276\320\264\321\203\320\273\321\214.os" create mode 100644 "tests/eval-in-libraries/src/\320\242\320\265\321\201\321\202\321\213/\320\242\320\265\321\201\321\202.os" diff --git a/tests/eval-in-libraries/entrypoint.os b/tests/eval-in-libraries/entrypoint.os new file mode 100644 index 000000000..95d621dc3 --- /dev/null +++ b/tests/eval-in-libraries/entrypoint.os @@ -0,0 +1,4 @@ + +Перем + + diff --git "a/tests/eval-in-libraries/src/\320\234\320\276\320\264\321\203\320\273\320\270/\320\234\320\276\320\264\321\203\320\273\321\214.os" "b/tests/eval-in-libraries/src/\320\234\320\276\320\264\321\203\320\273\320\270/\320\234\320\276\320\264\321\203\320\273\321\214.os" new file mode 100644 index 000000000..d9ffe9c90 --- /dev/null +++ "b/tests/eval-in-libraries/src/\320\234\320\276\320\264\321\203\320\273\320\270/\320\234\320\276\320\264\321\203\320\273\321\214.os" @@ -0,0 +1,3 @@ +Функция Тест() Экспорт + Возврат 1; +КонецФункции diff --git "a/tests/eval-in-libraries/src/\320\242\320\265\321\201\321\202\321\213/\320\242\320\265\321\201\321\202.os" "b/tests/eval-in-libraries/src/\320\242\320\265\321\201\321\202\321\213/\320\242\320\265\321\201\321\202.os" new file mode 100644 index 000000000..7a8a0e12c --- /dev/null +++ "b/tests/eval-in-libraries/src/\320\242\320\265\321\201\321\202\321\213/\320\242\320\265\321\201\321\202.os" @@ -0,0 +1,10 @@ +#Использовать ".." + +Функция Тест() Экспорт + + Модуль.Тест(); // Работает + + А = Вычислить("Модуль"); // https://github.com/EvilBeaver/OneScript/issues/1451 Неизвестный символ: Модуль + Возврат А.Тест(); + +КонецПроцедуры diff --git a/tests/eval.os b/tests/eval.os index 8058981bc..014afd3d5 100644 --- a/tests/eval.os +++ b/tests/eval.os @@ -24,6 +24,7 @@ ВсеТесты.Добавить("ТестДолжен_ПроверитьРекурсивныйВызовВыполнить"); ВсеТесты.Добавить("ТестДолжен_ПроверитьВложенныеВызовыВыполнить"); ВсеТесты.Добавить("ТестДолжен_ПроверитьВызовыВыполнитьСПопытками"); + ВсеТесты.Добавить("ТестДолжен_ПроверитьРаботоспособностьВПодключенныхСценариях"); Возврат ВсеТесты; КонецФункции @@ -329,3 +330,14 @@ юТест.ПроверитьРавенство("0134567+", Рез); КонецПроцедуры + +Процедура ТестДолжен_ПроверитьРаботоспособностьВПодключенныхСценариях() Экспорт + + Библиотека = ОбъединитьПути(ТекущийСценарий().Каталог, "eval-in-libraries"); + + ПодключитьСценарий(Библиотека + "/src/Тесты/Тест.os", "ТестEvalInLibraries"); + + А = Новый ТестEvalInLibraries(); + А.Тест(); + +КонецПроцедуры From 8d00478bc39046d657d831114b114f51d16491c7 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sat, 19 Oct 2024 21:06:07 +0300 Subject: [PATCH 16/32] Revert "Revert "closes #1451"" This reverts commit 1e7f4128a975ed1bcb66d1da46e372026d3de851. --- src/ScriptEngine/Machine/RuntimeScopes.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ScriptEngine/Machine/RuntimeScopes.cs b/src/ScriptEngine/Machine/RuntimeScopes.cs index b1e175d0f..88888251b 100644 --- a/src/ScriptEngine/Machine/RuntimeScopes.cs +++ b/src/ScriptEngine/Machine/RuntimeScopes.cs @@ -8,6 +8,7 @@ This Source Code Form is subject to the terms of the using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using OneScript.Contexts; namespace ScriptEngine.Machine @@ -24,7 +25,7 @@ public class RuntimeScopes : IReadOnlyList public RuntimeScopes(IReadOnlyList outerScopes, AttachedContext innerScope) { - _outerScopes = outerScopes; + _outerScopes = outerScopes.Select(x => new AttachedContext(x.Instance)).ToList(); _innerScope = innerScope; _outerScopeLast = _outerScopes.Count - 1; From 162fd1b46912688ecaea77cc485efb4f03a0042b Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sat, 19 Oct 2024 21:16:09 +0300 Subject: [PATCH 17/32] =?UTF-8?q?=D0=9E=D1=88=D0=B8=D0=B1=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=B2=20=D0=BD=D0=BE=D0=B2=D0=BE=D0=BC=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/eval-in-libraries/entrypoint.os | 4 ---- .../\320\242\320\265\321\201\321\202.os" | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) delete mode 100644 tests/eval-in-libraries/entrypoint.os diff --git a/tests/eval-in-libraries/entrypoint.os b/tests/eval-in-libraries/entrypoint.os deleted file mode 100644 index 95d621dc3..000000000 --- a/tests/eval-in-libraries/entrypoint.os +++ /dev/null @@ -1,4 +0,0 @@ - -Перем - - diff --git "a/tests/eval-in-libraries/src/\320\242\320\265\321\201\321\202\321\213/\320\242\320\265\321\201\321\202.os" "b/tests/eval-in-libraries/src/\320\242\320\265\321\201\321\202\321\213/\320\242\320\265\321\201\321\202.os" index 7a8a0e12c..fc2518687 100644 --- "a/tests/eval-in-libraries/src/\320\242\320\265\321\201\321\202\321\213/\320\242\320\265\321\201\321\202.os" +++ "b/tests/eval-in-libraries/src/\320\242\320\265\321\201\321\202\321\213/\320\242\320\265\321\201\321\202.os" @@ -7,4 +7,4 @@ А = Вычислить("Модуль"); // https://github.com/EvilBeaver/OneScript/issues/1451 Неизвестный символ: Модуль Возврат А.Тест(); -КонецПроцедуры +КонецФункции From dd59f9f928a5b8c09b8f606b34ad9656fa3e0235 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sat, 19 Oct 2024 21:36:39 +0300 Subject: [PATCH 18/32] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=8B=D1=82=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D1=82=D1=8C?= =?UTF-8?q?=20=D1=82=D0=B5=D1=81=D1=82=20NativeApi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Jenkinsfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 312961348..40976b025 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -62,7 +62,8 @@ pipeline { bat "chcp $outputEnc > nul\r\n dotnet publish src/OneScriptDocumenter/OneScriptDocumenter.csproj -c Release -o doctool" bat "chcp $outputEnc > nul\r\n\"${tool 'MSBuild'}\" Build.csproj /t:CleanAll;PrepareDistributionFiles;CreateNuget" - stash includes: 'tests, built/**', name: 'buildResults' + stash includes: 'built/**', name: 'buildResults' + stash includes: 'tests/native-api/bin*/*.dll', name: 'nativeApiTestsDll' } } } @@ -132,6 +133,7 @@ pipeline { deleteDir() } unstash 'buildResults' + unstash 'nativeApiTestsDll' bat "chcp $outputEnc > nul\r\n\"${tool 'MSBuild'}\" Build.csproj /t:Test" junit 'tests/*.xml' From 44709af9317ba70c8cb9e422a48ed1639e7b92b9 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sat, 19 Oct 2024 21:53:11 +0300 Subject: [PATCH 19/32] =?UTF-8?q?=D0=92=D0=BE=D1=81=D1=81=D1=82=D0=B0?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=82=D0=B5?= =?UTF-8?q?=D1=81=D1=82=D0=B0=20=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=D0=A0=D0=B5=D0=BA=D1=83=D1=80=D1=81=D0=B8=D0=B2?= =?UTF-8?q?=D0=BD=D1=8B=D0=B9=D0=92=D1=8B=D0=B7=D0=BE=D0=B2=D0=92=D1=8B?= =?UTF-8?q?=D0=BF=D0=BE=D0=BB=D0=BD=D0=B8=D1=82=D1=8C=20=D0=B8=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B0=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B0=20=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=D0=A0=D0=B0=D0=B1=D0=BE=D1=82=D0=BE=D1=81=D0=BF=D0=BE?= =?UTF-8?q?=D1=81=D0=BE=D0=B1=D0=BD=D0=BE=D1=81=D1=82=D1=8C=D0=92=D0=9F?= =?UTF-8?q?=D0=BE=D0=B4=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=BD=D1=8B?= =?UTF-8?q?=D1=85=D0=A1=D1=86=D0=B5=D0=BD=D0=B0=D1=80=D0=B8=D1=8F=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Machine/RuntimeScopes.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ScriptEngine/Machine/RuntimeScopes.cs b/src/ScriptEngine/Machine/RuntimeScopes.cs index 88888251b..da19966ad 100644 --- a/src/ScriptEngine/Machine/RuntimeScopes.cs +++ b/src/ScriptEngine/Machine/RuntimeScopes.cs @@ -25,7 +25,7 @@ public class RuntimeScopes : IReadOnlyList public RuntimeScopes(IReadOnlyList outerScopes, AttachedContext innerScope) { - _outerScopes = outerScopes.Select(x => new AttachedContext(x.Instance)).ToList(); + _outerScopes = outerScopes; _innerScope = innerScope; _outerScopeLast = _outerScopes.Count - 1; From 2d7bef4d308070ec9242c3b8ff372304dc3ff3b6 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 25 Apr 2024 10:09:02 +0300 Subject: [PATCH 20/32] =?UTF-8?q?=D0=94=D0=BE=D0=BA=D1=83=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D1=8F=20=D0=B8=20=D1=81=D0=B5?= =?UTF-8?q?=D1=80=D0=B2=D0=B8=D1=81=D0=BD=D1=8B=D0=B9=20=D0=BC=D0=B5=D1=82?= =?UTF-8?q?=D0=BE=D0=B4=20=D0=BD=D0=B0=D1=81=D1=82=D1=80=D0=BE=D0=B9=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=B2=D0=B8=D0=B6=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Compilation/ICompileTimeDependencyResolver.cs | 5 +++++ src/ScriptEngine/Hosting/EngineBuilderExtensions.cs | 6 ++++++ src/ScriptEngine/IDependencyResolver.cs | 7 +++++++ 3 files changed, 18 insertions(+) diff --git a/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs b/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs index 0fc5b30e3..2692c83de 100644 --- a/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs +++ b/src/OneScript.Core/Compilation/ICompileTimeDependencyResolver.cs @@ -11,6 +11,11 @@ namespace OneScript.Compilation { public interface ICompileTimeDependencyResolver { + /// + /// Загрузить библиотеку для модуля + /// + /// Модуль в котором объявлен импорт + /// имя библиотеки void Resolve(SourceCode module, string libraryName); } } \ No newline at end of file diff --git a/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs b/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs index dc4ba7c63..971fdff16 100644 --- a/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs +++ b/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs @@ -92,5 +92,11 @@ public static IEngineBuilder WithDebugger(this IEngineBuilder b, IDebugControlle b.Services.RegisterSingleton(debugger); return b; } + + public static IEngineBuilder SetupServices(this IEngineBuilder b, Action setup) + { + setup(b.Services); + return b; + } } } \ No newline at end of file diff --git a/src/ScriptEngine/IDependencyResolver.cs b/src/ScriptEngine/IDependencyResolver.cs index 291e36ad0..ee038a37e 100644 --- a/src/ScriptEngine/IDependencyResolver.cs +++ b/src/ScriptEngine/IDependencyResolver.cs @@ -9,8 +9,15 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine { + /// + /// Разрешитель внещних зависимостей (библиотек) + /// public interface IDependencyResolver : ICompileTimeDependencyResolver { + /// + /// Инициализировать разрешитель. Вызывается при создании ScriptingEngine + /// + /// Движок, который разрешитель может сохранить у себя void Initialize(ScriptingEngine engine); } } \ No newline at end of file From d244f8ae0f2c28f4577035c4480739839c77c447 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 2 Jun 2024 10:13:41 +0300 Subject: [PATCH 21/32] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7?= =?UTF-8?q?=D1=87=D0=B8=D0=BA=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D0=B8=D0=BC?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Libraries/DependencyLoader.cs | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/ScriptEngine/Libraries/DependencyLoader.cs diff --git a/src/ScriptEngine/Libraries/DependencyLoader.cs b/src/ScriptEngine/Libraries/DependencyLoader.cs new file mode 100644 index 000000000..a77558ad9 --- /dev/null +++ b/src/ScriptEngine/Libraries/DependencyLoader.cs @@ -0,0 +1,34 @@ +/*---------------------------------------------------------- +This Source Code Form is subject to the terms of the +Mozilla Public License, v.2.0. If a copy of the MPL +was not distributed with this file, You can obtain one +at http://mozilla.org/MPL/2.0/. +----------------------------------------------------------*/ + +using OneScript.Sources; +using ScriptEngine.Machine.Contexts; + +namespace ScriptEngine +{ + public class DependencyLoader + { + private readonly ScriptingEngine _engine; + private readonly RuntimeEnvironment _env; + + public DependencyLoader(ScriptingEngine engine) + { + _engine = engine; + _env = engine.Environment; + } + + public void AddClass(ICodeSource source, string className) + { + + } + + public void AddModule(ICodeSource source, string moduleName) + { + + } + } +} \ No newline at end of file From 09d205458d82e8f5a2a884a44d162bec5887967d Mon Sep 17 00:00:00 2001 From: Andrey Ovsyankin Date: Tue, 17 Sep 2024 16:08:44 +0300 Subject: [PATCH 22/32] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B0=20=D0=BE=D0=BF=D0=B5=D1=87=D0=B0=D1=82?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=B8=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA=D0=B0=20?= =?UTF-8?q?=D1=81=D0=B1=D0=BE=D1=80=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/IDependencyResolver.cs | 2 +- src/ScriptEngine/Libraries/DependencyLoader.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ScriptEngine/IDependencyResolver.cs b/src/ScriptEngine/IDependencyResolver.cs index ee038a37e..76369776a 100644 --- a/src/ScriptEngine/IDependencyResolver.cs +++ b/src/ScriptEngine/IDependencyResolver.cs @@ -10,7 +10,7 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine { /// - /// Разрешитель внещних зависимостей (библиотек) + /// Разрешитель внешних зависимостей (библиотек) /// public interface IDependencyResolver : ICompileTimeDependencyResolver { diff --git a/src/ScriptEngine/Libraries/DependencyLoader.cs b/src/ScriptEngine/Libraries/DependencyLoader.cs index a77558ad9..e66a4c159 100644 --- a/src/ScriptEngine/Libraries/DependencyLoader.cs +++ b/src/ScriptEngine/Libraries/DependencyLoader.cs @@ -5,6 +5,7 @@ This Source Code Form is subject to the terms of the at http://mozilla.org/MPL/2.0/. ----------------------------------------------------------*/ +using OneScript.Contexts; using OneScript.Sources; using ScriptEngine.Machine.Contexts; @@ -13,7 +14,7 @@ namespace ScriptEngine public class DependencyLoader { private readonly ScriptingEngine _engine; - private readonly RuntimeEnvironment _env; + private readonly IRuntimeEnvironment _env; public DependencyLoader(ScriptingEngine engine) { From 39c265b13af26dd43eb13e88e24625211e09a6d9 Mon Sep 17 00:00:00 2001 From: Andrey Ovsyankin Date: Tue, 17 Sep 2024 16:43:18 +0300 Subject: [PATCH 23/32] =?UTF-8?q?=D0=A3=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D1=8B=20=D0=BD=D0=B5=D0=B8=D1=81=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7?= =?UTF-8?q?=D1=83=D0=B5=D0=BC=D1=8B=D0=B5=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81?= =?UTF-8?q?=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SyntaxAnalysis/ParserOptions.cs | 16 ---------------- src/ScriptEngine/Compiler/CompilerFrontend.cs | 3 --- src/ScriptEngine/Compiler/CompilerOptions.cs | 16 ---------------- 3 files changed, 35 deletions(-) delete mode 100644 src/OneScript.Language/SyntaxAnalysis/ParserOptions.cs delete mode 100644 src/ScriptEngine/Compiler/CompilerOptions.cs diff --git a/src/OneScript.Language/SyntaxAnalysis/ParserOptions.cs b/src/OneScript.Language/SyntaxAnalysis/ParserOptions.cs deleted file mode 100644 index c7a32d038..000000000 --- a/src/OneScript.Language/SyntaxAnalysis/ParserOptions.cs +++ /dev/null @@ -1,16 +0,0 @@ -/*---------------------------------------------------------- -This Source Code Form is subject to the terms of the -Mozilla Public License, v.2.0. If a copy of the MPL -was not distributed with this file, You can obtain one -at http://mozilla.org/MPL/2.0/. -----------------------------------------------------------*/ - -namespace OneScript.Language.SyntaxAnalysis -{ - public class ParserOptions - { - public IErrorSink ErrorSink { get; set; } = new ThrowingErrorSink(); - - public PreprocessorHandlers PreprocessorHandlers { get; set; } - } -} \ No newline at end of file diff --git a/src/ScriptEngine/Compiler/CompilerFrontend.cs b/src/ScriptEngine/Compiler/CompilerFrontend.cs index 3f1a9d965..ba94a91d2 100644 --- a/src/ScriptEngine/Compiler/CompilerFrontend.cs +++ b/src/ScriptEngine/Compiler/CompilerFrontend.cs @@ -6,8 +6,6 @@ This Source Code Form is subject to the terms of the ----------------------------------------------------------*/ using System; using System.Collections.Generic; -using System.Linq; -using OneScript.Commons; using OneScript.Compilation; using OneScript.Compilation.Binding; using OneScript.Contexts; @@ -16,7 +14,6 @@ This Source Code Form is subject to the terms of the using OneScript.Language; using OneScript.Language.SyntaxAnalysis; using OneScript.Language.SyntaxAnalysis.AstNodes; -using ScriptEngine.Machine; using ScriptEngine.Machine.Contexts; namespace ScriptEngine.Compiler diff --git a/src/ScriptEngine/Compiler/CompilerOptions.cs b/src/ScriptEngine/Compiler/CompilerOptions.cs deleted file mode 100644 index 2ec7dbca9..000000000 --- a/src/ScriptEngine/Compiler/CompilerOptions.cs +++ /dev/null @@ -1,16 +0,0 @@ -/*---------------------------------------------------------- -This Source Code Form is subject to the terms of the -Mozilla Public License, v.2.0. If a copy of the MPL -was not distributed with this file, You can obtain one -at http://mozilla.org/MPL/2.0/. -----------------------------------------------------------*/ - -using OneScript.Language.SyntaxAnalysis; - -namespace ScriptEngine.Compiler -{ - public class CompilerOptions : ParserOptions - { - public IDependencyResolver DependencyResolver { get; set; } - } -} \ No newline at end of file From f366e76379432b640979affa42fe63e76e854d46 Mon Sep 17 00:00:00 2001 From: Andrey Ovsyankin Date: Tue, 17 Sep 2024 18:13:26 +0300 Subject: [PATCH 24/32] =?UTF-8?q?=D0=A0=D1=8F=D0=B4=20=D0=BF=D0=B5=D1=80?= =?UTF-8?q?=D0=B5=D0=B8=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B9=20=D0=B8=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5=D1=89?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine.HostedScript/LibraryLoader.cs | 1 + src/ScriptEngine/Compiler/ApplicationDump.cs | 1 + src/ScriptEngine/Compiler/CompilerFrontend.cs | 4 ++++ src/ScriptEngine/Compiler/EvalCompiler.cs | 3 +++ .../{ => Libraries}/ExternalLibraryDef.cs | 14 +++++++------- .../{ => Libraries}/ILibraryManager.cs | 2 +- src/ScriptEngine/RuntimeEnvironment.cs | 1 + src/ScriptEngine/ScriptingEngine.cs | 1 + 8 files changed, 19 insertions(+), 8 deletions(-) rename src/ScriptEngine/{ => Libraries}/ExternalLibraryDef.cs (95%) rename src/ScriptEngine/{ => Libraries}/ILibraryManager.cs (95%) diff --git a/src/ScriptEngine.HostedScript/LibraryLoader.cs b/src/ScriptEngine.HostedScript/LibraryLoader.cs index 505250d86..9501180e4 100644 --- a/src/ScriptEngine.HostedScript/LibraryLoader.cs +++ b/src/ScriptEngine.HostedScript/LibraryLoader.cs @@ -15,6 +15,7 @@ This Source Code Form is subject to the terms of the using OneScript.Contexts; using OneScript.Exceptions; using OneScript.Execution; +using ScriptEngine.Libraries; namespace ScriptEngine.HostedScript { diff --git a/src/ScriptEngine/Compiler/ApplicationDump.cs b/src/ScriptEngine/Compiler/ApplicationDump.cs index dbbfe5243..6f807ca3e 100644 --- a/src/ScriptEngine/Compiler/ApplicationDump.cs +++ b/src/ScriptEngine/Compiler/ApplicationDump.cs @@ -5,6 +5,7 @@ This Source Code Form is subject to the terms of the at http://mozilla.org/MPL/2.0/. ----------------------------------------------------------*/ +using ScriptEngine.Libraries; using System; namespace ScriptEngine.Compiler diff --git a/src/ScriptEngine/Compiler/CompilerFrontend.cs b/src/ScriptEngine/Compiler/CompilerFrontend.cs index ba94a91d2..951a93cf7 100644 --- a/src/ScriptEngine/Compiler/CompilerFrontend.cs +++ b/src/ScriptEngine/Compiler/CompilerFrontend.cs @@ -18,6 +18,10 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine.Compiler { + /// + /// Часть компилятора, независимая от рантайма (нативного или стекового) + /// Запускает компиляцию модуля, строит AST и делегирует построение кода в бэкенд компилятора под конкретный рантайм. + /// public class CompilerFrontend : CompilerFrontendBase { private readonly IDependencyResolver _dependencyResolver; diff --git a/src/ScriptEngine/Compiler/EvalCompiler.cs b/src/ScriptEngine/Compiler/EvalCompiler.cs index 603fa8702..373f60665 100644 --- a/src/ScriptEngine/Compiler/EvalCompiler.cs +++ b/src/ScriptEngine/Compiler/EvalCompiler.cs @@ -15,6 +15,9 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine.Compiler { + /// + /// Компилятор вычислимых выражений + /// public class EvalCompiler : CompilerFrontendBase { private readonly DefaultCompilerBackend _backend; diff --git a/src/ScriptEngine/ExternalLibraryDef.cs b/src/ScriptEngine/Libraries/ExternalLibraryDef.cs similarity index 95% rename from src/ScriptEngine/ExternalLibraryDef.cs rename to src/ScriptEngine/Libraries/ExternalLibraryDef.cs index 978897621..30bc701a8 100644 --- a/src/ScriptEngine/ExternalLibraryDef.cs +++ b/src/ScriptEngine/Libraries/ExternalLibraryDef.cs @@ -10,7 +10,7 @@ This Source Code Form is subject to the terms of the using OneScript.Execution; using ScriptEngine.Machine; -namespace ScriptEngine +namespace ScriptEngine.Libraries { public class ExternalLibraryDef { @@ -18,9 +18,9 @@ public ExternalLibraryDef(string name) { LibraryName = name; } - + public string LibraryName { get; } - + public IList Classes { get; } = new List(); public IList Modules { get; } = new List(); @@ -33,12 +33,12 @@ public UserAddedScript AddClass(string identifier, string filePath, StackRuntime Symbol = identifier, FilePath = filePath }; - + Classes.Add(item); return item; } - + public UserAddedScript AddModule(string identifier, string filePath, StackRuntimeModule module = null) { var item = new UserAddedScript @@ -48,13 +48,13 @@ public UserAddedScript AddModule(string identifier, string filePath, StackRuntim Symbol = identifier, FilePath = filePath }; - + Modules.Add(item); return item; } } - + public class UserAddedScript { public UserAddedScriptType Type; diff --git a/src/ScriptEngine/ILibraryManager.cs b/src/ScriptEngine/Libraries/ILibraryManager.cs similarity index 95% rename from src/ScriptEngine/ILibraryManager.cs rename to src/ScriptEngine/Libraries/ILibraryManager.cs index c3f375909..b6ab90e53 100644 --- a/src/ScriptEngine/ILibraryManager.cs +++ b/src/ScriptEngine/Libraries/ILibraryManager.cs @@ -7,7 +7,7 @@ This Source Code Form is subject to the terms of the using System.Collections.Generic; -namespace ScriptEngine +namespace ScriptEngine.Libraries { /// /// Временный класс для откусывания ответственностей от RuntimeEnvironment diff --git a/src/ScriptEngine/RuntimeEnvironment.cs b/src/ScriptEngine/RuntimeEnvironment.cs index aa1f47106..0950b088a 100644 --- a/src/ScriptEngine/RuntimeEnvironment.cs +++ b/src/ScriptEngine/RuntimeEnvironment.cs @@ -9,6 +9,7 @@ This Source Code Form is subject to the terms of the using OneScript.Commons; using OneScript.Compilation.Binding; using OneScript.Contexts; +using ScriptEngine.Libraries; using ScriptEngine.Machine; using ScriptEngine.Machine.Contexts; using SymbolScope = OneScript.Compilation.Binding.SymbolScope; diff --git a/src/ScriptEngine/ScriptingEngine.cs b/src/ScriptEngine/ScriptingEngine.cs index c49736d45..5e21149cd 100644 --- a/src/ScriptEngine/ScriptingEngine.cs +++ b/src/ScriptEngine/ScriptingEngine.cs @@ -15,6 +15,7 @@ This Source Code Form is subject to the terms of the using ScriptEngine.Machine; using ScriptEngine.Machine.Contexts; using ScriptEngine.Compiler; +using ScriptEngine.Libraries; namespace ScriptEngine { From 2a1854ff3846950b2913e81d20e4786213e0a3c9 Mon Sep 17 00:00:00 2001 From: Andrey Ovsyankin Date: Fri, 4 Oct 2024 12:25:21 +0300 Subject: [PATCH 25/32] =?UTF-8?q?=D0=92=D1=8B=D0=B4=D0=B5=D0=BB=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BB=D0=BE=D0=B3=D0=B8=D0=BA=D1=83=20=D0=B1=D0=B8?= =?UTF-8?q?=D0=B1=D0=BB=D0=B8=D0=BE=D1=82=D0=B5=D0=BA=20=D0=B2=20=D0=BE?= =?UTF-8?q?=D1=82=D0=B4=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9=20=D0=BA=D0=BB?= =?UTF-8?q?=D0=B0=D1=81=D1=81,=20=D1=87=D1=82=D0=BE=D0=B1=D1=8B=20=D0=BF?= =?UTF-8?q?=D0=BE=D1=87=D0=B8=D1=81=D1=82=D0=B8=D1=82=D1=8C=20RuntimeEnvir?= =?UTF-8?q?onment?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Libraries/LibraryManager.cs | 48 ++++++++++++++++++++ src/ScriptEngine/RuntimeEnvironment.cs | 20 ++------ 2 files changed, 52 insertions(+), 16 deletions(-) create mode 100644 src/ScriptEngine/Libraries/LibraryManager.cs diff --git a/src/ScriptEngine/Libraries/LibraryManager.cs b/src/ScriptEngine/Libraries/LibraryManager.cs new file mode 100644 index 000000000..6ccfdd0b3 --- /dev/null +++ b/src/ScriptEngine/Libraries/LibraryManager.cs @@ -0,0 +1,48 @@ +using OneScript.Commons; +using OneScript.Contexts; +using ScriptEngine.Machine.Contexts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ScriptEngine.Libraries +{ + /// + /// Временная имплементация временного интерфейса ILibraryManager + /// Нужна для откусывания ответственностей от RuntimeEnvironment + /// + internal class LibraryManager : ILibraryManager + { + private readonly List _externalLibs = new List(); + private readonly IRuntimeContextInstance _contextOfGlobalSymbols; + + public LibraryManager(IRuntimeContextInstance contextOfGlobalSymbols) + { + _contextOfGlobalSymbols = contextOfGlobalSymbols; + } + + public IEnumerable GetLibraries() + { + return _externalLibs.ToArray(); + } + + public void InitExternalLibrary(ScriptingEngine runtime, ExternalLibraryDef library) + { + var loadedObjects = new ScriptDrivenObject[library.Modules.Count]; + int i = 0; + foreach (var module in library.Modules) + { + var instance = runtime.CreateUninitializedSDO(module.Module); + + var propId = _contextOfGlobalSymbols.GetPropertyNumber(module.Symbol); + _contextOfGlobalSymbols.SetPropValue(propId, instance); + loadedObjects[i++] = instance; + } + + _externalLibs.Add(library); + loadedObjects.ForEach(runtime.InitializeSDO); + } + } +} diff --git a/src/ScriptEngine/RuntimeEnvironment.cs b/src/ScriptEngine/RuntimeEnvironment.cs index 0950b088a..d54a08097 100644 --- a/src/ScriptEngine/RuntimeEnvironment.cs +++ b/src/ScriptEngine/RuntimeEnvironment.cs @@ -11,7 +11,6 @@ This Source Code Form is subject to the terms of the using OneScript.Contexts; using ScriptEngine.Libraries; using ScriptEngine.Machine; -using ScriptEngine.Machine.Contexts; using SymbolScope = OneScript.Compilation.Binding.SymbolScope; namespace ScriptEngine @@ -26,11 +25,12 @@ public class RuntimeEnvironment : IRuntimeEnvironment, ILibraryManager private readonly List _contexts = new List(); - private readonly List _externalLibs = new List(); + private readonly ILibraryManager _libraryManager; public RuntimeEnvironment() { _injectedProperties = new PropertyBag(); + _libraryManager = new LibraryManager(_injectedProperties); } private void CreateGlobalScopeIfNeeded() @@ -106,24 +106,12 @@ public IValue GetGlobalProperty(string propertyName) public IEnumerable GetLibraries() { - return _externalLibs.ToArray(); + return _libraryManager.GetLibraries(); } public void InitExternalLibrary(ScriptingEngine runtime, ExternalLibraryDef library) { - var loadedObjects = new ScriptDrivenObject[library.Modules.Count]; - int i = 0; - foreach (var module in library.Modules) - { - var instance = runtime.CreateUninitializedSDO(module.Module); - - var propId = _injectedProperties.GetPropertyNumber(module.Symbol); - _injectedProperties.SetPropValue(propId, instance); - loadedObjects[i++] = instance; - } - - _externalLibs.Add(library); - loadedObjects.ForEach(runtime.InitializeSDO); + _libraryManager.InitExternalLibrary(runtime, library); } private class WrappedPropertySymbol : IPropertySymbol From 047423ae48f4a32adc14395133badb948b19ec4a Mon Sep 17 00:00:00 2001 From: Mr-Rm Date: Fri, 11 Oct 2024 14:33:54 +0400 Subject: [PATCH 26/32] =?UTF-8?q?fix=20#1459:=20=D0=B4=D0=B8=D0=B0=D0=B3?= =?UTF-8?q?=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B0=20=D0=B8=D1=81=D0=BF?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D0=B2=D1=81=D1=82=D1=80=D0=BE=D0=B5=D0=BD=D0=BD=D0=BE=D0=B9=20?= =?UTF-8?q?=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=B8=20=D0=BA=D0=B0=D0=BA?= =?UTF-8?q?=20=D0=BF=D1=80=D0=BE=D1=86=D0=B5=D0=B4=D1=83=D1=80=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SyntaxAnalysis/DefaultBslParser.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/OneScript.Language/SyntaxAnalysis/DefaultBslParser.cs b/src/OneScript.Language/SyntaxAnalysis/DefaultBslParser.cs index 28ed3f149..75ac1439d 100644 --- a/src/OneScript.Language/SyntaxAnalysis/DefaultBslParser.cs +++ b/src/OneScript.Language/SyntaxAnalysis/DefaultBslParser.cs @@ -711,8 +711,15 @@ private void BuildComplexStructureStatement() BuildGotoOperator(); break; default: - var expected = _tokenStack.Peek(); - AddError(LocalizedErrors.TokenExpected(expected)); + if (LanguageDef.IsBuiltInFunction(_lastExtractedLexem.Token)) + { + AddError(LocalizedErrors.UseBuiltInFunctionAsProcedure()); + } + else + { + var expected = _tokenStack.Peek(); + AddError(LocalizedErrors.TokenExpected(expected)); + } break; } } From cb881db264228f0d0285c7281c86be724728ae79 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 21 Oct 2024 17:13:20 +0300 Subject: [PATCH 27/32] =?UTF-8?q?=D0=94=D0=BE=D0=BA=D0=B5=D1=80=D1=84?= =?UTF-8?q?=D0=B0=D0=B9=D0=BB=D1=8B=20=D0=B4=D0=BB=D1=8F=20=D1=80=D0=B0?= =?UTF-8?q?=D0=B7=D0=BD=D1=8B=D1=85=20=D1=80=D0=B5=D0=B4=D0=B0=D0=BA=D1=86?= =?UTF-8?q?=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- install/builders/base-image/Dockerfile.mono | 17 +++++++++++++++++ install/builders/base-image/Dockerfile_v1 | 11 +++++++++++ install/builders/base-image/Dockerfile_v2 | 20 ++++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 install/builders/base-image/Dockerfile.mono create mode 100644 install/builders/base-image/Dockerfile_v1 create mode 100644 install/builders/base-image/Dockerfile_v2 diff --git a/install/builders/base-image/Dockerfile.mono b/install/builders/base-image/Dockerfile.mono new file mode 100644 index 000000000..a0cc5e450 --- /dev/null +++ b/install/builders/base-image/Dockerfile.mono @@ -0,0 +1,17 @@ +FROM ubuntu:18.04 + +# MAINTAINER EvilBeaver + +ENV LANG ru_RU.UTF-8 + +RUN apt update \ + && apt-get -y install locales tzdata \ + && locale-gen ru_RU && locale-gen ru_RU.UTF-8 \ + && update-locale LANG=ru_RU.UTF-8 \ + && apt install -y gnupg ca-certificates \ + && apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF \ + && sh -c 'echo "deb https://download.mono-project.com/repo/ubuntu stable-bionic main" > /etc/apt/sources.list.d/mono-official-stable.list' \ + && apt-get update \ + && apt-get -y install mono-runtime binutils curl mono-devel ca-certificates-mono mono-vbnc referenceassemblies-pcl mono-fastcgi-server4 \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/* /tmp/* \ No newline at end of file diff --git a/install/builders/base-image/Dockerfile_v1 b/install/builders/base-image/Dockerfile_v1 new file mode 100644 index 000000000..513cc9222 --- /dev/null +++ b/install/builders/base-image/Dockerfile_v1 @@ -0,0 +1,11 @@ +FROM evilbeaver/mono-ru:6.12 + +# Файл базируется на моно с русской локалью +# Устанавливает через ovm версию движка + +LABEL MAINTAINER="EvilBeaver " + +ARG VERSION=stable + +RUN curl -L https://github.com/oscript-library/ovm/releases/latest/download/ovm.exe > ovm.exe \ + && mono ovm.exe use --install $VERSION \ No newline at end of file diff --git a/install/builders/base-image/Dockerfile_v2 b/install/builders/base-image/Dockerfile_v2 new file mode 100644 index 000000000..620454528 --- /dev/null +++ b/install/builders/base-image/Dockerfile_v2 @@ -0,0 +1,20 @@ +FROM evilbeaver/onescript:1.9.2 + +# Использует в качестве системы с ovm и mono образ onescript, создаваемый из файла Dockerfile_v1 (лежит рядом в репо) +# Потом копирует бинари из него в образ от Microsoft + +LABEL MAINTAINER="EvilBeaver " + +ARG VERSION="dev" + +# Установка FDD двойки через ovm, имеющийся в базовом образе +RUN mono ovm.exe install --fdd ${VERSION} + +# Основной образ +FROM mcr.microsoft.com/dotnet/aspnet:6.0 + +ARG VERSION="dev" + +RUN mkdir -p /var/oscript +COPY --from=0 /root/.local/share/ovm/${VERSION}/ /var/oscript/ +ENV PATH="$PATH:/var/oscript/bin" \ No newline at end of file From 2d33f8a1c99244dbb521a7bcf907fba17e18fc90 Mon Sep 17 00:00:00 2001 From: Mr-Rm Date: Mon, 21 Oct 2024 22:53:10 +0400 Subject: [PATCH 28/32] =?UTF-8?q?fix=20#1451:=20=D0=BE=D0=B1=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B3=D0=BB=D0=BE=D0=B1?= =?UTF-8?q?=D0=B0=D0=BB=D1=8C=D0=BD=D0=BE=D0=B3=D0=BE=20=D1=81=D0=BA=D0=BE?= =?UTF-8?q?=D1=83=D0=BF=D0=B0=20=D0=BF=D1=80=D0=B8=20=D0=B7=D0=B0=D0=B3?= =?UTF-8?q?=D1=80=D1=83=D0=B7=D0=BA=D0=B5=20=D0=B2=D0=BD=D0=B5=D1=88=D0=BD?= =?UTF-8?q?=D0=B5=D0=B3=D0=BE=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/OneScript.Core/Contexts/AttachedContext.cs | 11 ++++++++--- src/ScriptEngine.HostedScript/LibraryLoader.cs | 1 + src/ScriptEngine/Machine/MachineInstance.cs | 5 +++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/OneScript.Core/Contexts/AttachedContext.cs b/src/OneScript.Core/Contexts/AttachedContext.cs index 981a645a2..0b5c4fc97 100644 --- a/src/OneScript.Core/Contexts/AttachedContext.cs +++ b/src/OneScript.Core/Contexts/AttachedContext.cs @@ -15,13 +15,18 @@ namespace OneScript.Contexts /// public sealed class AttachedContext { - private readonly IVariable[] _variables; - private readonly BslMethodInfo[] _methods; + private IVariable[] _variables; + private BslMethodInfo[] _methods; public AttachedContext(IAttachableContext source) { - source.OnAttach(out _variables, out _methods); Instance = source; + Attach(); + } + + public void Attach() + { + Instance.OnAttach(out _variables, out _methods); } public AttachedContext(IAttachableContext target, IVariable[] vars) diff --git a/src/ScriptEngine.HostedScript/LibraryLoader.cs b/src/ScriptEngine.HostedScript/LibraryLoader.cs index 505250d86..a01075c75 100644 --- a/src/ScriptEngine.HostedScript/LibraryLoader.cs +++ b/src/ScriptEngine.HostedScript/LibraryLoader.cs @@ -113,6 +113,7 @@ public void AddModule(string file, string moduleName) $"en = 'Load module ={moduleName}= in to context from file {file}'") ); _env.InjectGlobalProperty(null, moduleName, true); + MachineInstance.Current.UpdateGlobals(); } catch (InvalidOperationException e) { diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index c85aadf00..e342cf4aa 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -69,6 +69,11 @@ public void SetMemory(ExecutionContext memory) _globalContexts = _mem.GlobalNamespace.AttachedContexts.Select(x => new AttachedContext(x)) .ToArray(); } + + public void UpdateGlobals() + { + _globalContexts.ForEach(x => x.Attach()); + } public bool IsRunning => _callStack.Count != 0; From 57f7c463413aecbb5eb66f920e1994d16ec5b8ea Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 4 Nov 2024 00:21:52 +0300 Subject: [PATCH 29/32] =?UTF-8?q?=D0=9F=D0=BE=D0=BB=D1=83=D1=80=D0=B0?= =?UTF-8?q?=D0=B1=D0=BE=D1=87=D0=B8=D0=B9=20=D0=B2=D0=B0=D1=80=D0=B8=D0=B0?= =?UTF-8?q?=D0=BD=D1=82.=20=D0=91=D1=8D=D0=BA=D0=B0=D0=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Commons/IndexedNameValueCollection.cs | 5 + .../FileSystemDependencyResolver.cs | 14 +- .../LibraryLoader.cs | 125 +++--------- .../Libraries/DependencyLoader.cs | 35 ---- .../Libraries/ExternalLibraryDef.cs | 10 - src/ScriptEngine/Libraries/ILibraryManager.cs | 1 - src/ScriptEngine/Libraries/LibraryManager.cs | 79 +++++++- .../Libraries/ModulesOrderingContext.cs | 180 ++++++++++++++++++ src/ScriptEngine/RuntimeEnvironment.cs | 5 - 9 files changed, 287 insertions(+), 167 deletions(-) delete mode 100644 src/ScriptEngine/Libraries/DependencyLoader.cs create mode 100644 src/ScriptEngine/Libraries/ModulesOrderingContext.cs diff --git a/src/OneScript.Core/Commons/IndexedNameValueCollection.cs b/src/OneScript.Core/Commons/IndexedNameValueCollection.cs index 94e2631ff..f840a75e4 100644 --- a/src/OneScript.Core/Commons/IndexedNameValueCollection.cs +++ b/src/OneScript.Core/Commons/IndexedNameValueCollection.cs @@ -73,6 +73,11 @@ public int IndexOf(string name) return index; } + public string NameOf(int index) + { + return _nameIndex.First(pair => pair.Value == index).Key; + } + public bool TryGetValue(string name, out T result) { int idx; diff --git a/src/ScriptEngine.HostedScript/FileSystemDependencyResolver.cs b/src/ScriptEngine.HostedScript/FileSystemDependencyResolver.cs index 5549026c4..d21b47f6d 100644 --- a/src/ScriptEngine.HostedScript/FileSystemDependencyResolver.cs +++ b/src/ScriptEngine.HostedScript/FileSystemDependencyResolver.cs @@ -22,7 +22,6 @@ public class FileSystemDependencyResolver : IDependencyResolver public const string PREDEFINED_LOADER_FILE = "package-loader.os"; private readonly List _libs = new List(); - private readonly Lazy _defaultLoader; #region Private classes @@ -40,11 +39,6 @@ private enum ProcessingState } #endregion - - public FileSystemDependencyResolver() - { - _defaultLoader = new Lazy(CreateDefaultLoader); - } public IList SearchDirectories { get;} = new List(); @@ -214,13 +208,9 @@ private bool LoadLibraryInternal(string libraryPath) private bool ProcessLibrary(Library lib) { - LibraryLoader loader; - if (lib.customLoader != null) - loader = lib.customLoader; - else - loader = _defaultLoader.Value; + var loader = lib.customLoader ?? CreateDefaultLoader(); - return loader.ProcessLibrary(lib.id) != default; + return loader.ProcessLibrary(lib.id); } private static string ListToStringStack(IEnumerable libs, string stopToken) diff --git a/src/ScriptEngine.HostedScript/LibraryLoader.cs b/src/ScriptEngine.HostedScript/LibraryLoader.cs index 70921c78a..a7dc52d88 100644 --- a/src/ScriptEngine.HostedScript/LibraryLoader.cs +++ b/src/ScriptEngine.HostedScript/LibraryLoader.cs @@ -21,28 +21,18 @@ namespace ScriptEngine.HostedScript { public class LibraryLoader : AutoScriptDrivenObject { - private readonly IRuntimeEnvironment _env; private readonly ILibraryManager _libManager; private readonly ScriptingEngine _engine; - readonly bool _customized; - - readonly List _delayLoadedScripts = new List(); - - private struct DelayLoadedScriptData - { - public string path; - public string identifier; - public bool asClass; - } + private readonly bool _customized; + private ExternalLibraryDef _library; + private LibraryLoader( IExecutableModule moduleHandle, - IRuntimeEnvironment env, ILibraryManager libManager, ScriptingEngine engine): base(moduleHandle) { - _env = env; _libManager = libManager; _engine = engine; _customized = true; @@ -51,11 +41,10 @@ private LibraryLoader( } - private LibraryLoader(IRuntimeEnvironment env, + private LibraryLoader( ILibraryManager libManager, ScriptingEngine engine) { - _env = env; _libManager = libManager; _engine = engine; _customized = false; @@ -69,13 +58,13 @@ public static LibraryLoader Create(ScriptingEngine engine, string processingScri var code = engine.Loader.FromFile(processingScript); var module = CompileModule(compiler, code, typeof(LibraryLoader)); - return new LibraryLoader(module, engine.Environment, engine.LibraryManager, engine); + return new LibraryLoader(module, engine.LibraryManager, engine); } public static LibraryLoader Create(ScriptingEngine engine) { - return new LibraryLoader(engine.Environment, engine.LibraryManager, engine); + return new LibraryLoader(engine.LibraryManager, engine); } #endregion @@ -86,12 +75,7 @@ public void AddClass(string file, string className) if (!Utils.IsValidIdentifier(className)) throw RuntimeException.InvalidArgumentValue(); - _delayLoadedScripts.Add(new DelayLoadedScriptData() - { - path = file, - identifier = className, - asClass = true - }); + _library.AddClass(className, file); } [ContextMethod("ДобавитьМодуль", "AddModule")] @@ -100,27 +84,22 @@ public void AddModule(string file, string moduleName) if (!Utils.IsValidIdentifier(moduleName)) throw RuntimeException.InvalidArgumentValue(); - _delayLoadedScripts.Add(new DelayLoadedScriptData() - { - path = file, - identifier = moduleName, - asClass = false - }); - - try - { - TraceLoadLibrary( - Locale.NStr($"ru = 'Загружаю модуль ={moduleName}= в область видимости из файла {file}';"+ - $"en = 'Load module ={moduleName}= in to context from file {file}'") - ); - _env.InjectGlobalProperty(null, moduleName, true); - MachineInstance.Current.UpdateGlobals(); - } - catch (InvalidOperationException e) - { - // символ уже определен - throw new RuntimeException(String.Format("Невозможно загрузить модуль {0}. Такой символ уже определен.", moduleName), e); - } + _library.AddModule(moduleName, file); + + // try + // { + // TraceLoadLibrary( + // Locale.NStr($"ru = 'Загружаю модуль ={moduleName}= в область видимости из файла {file}';"+ + // $"en = 'Load module ={moduleName}= in to context from file {file}'") + // ); + // _env.InjectGlobalProperty(null, moduleName, true); + // MachineInstance.Current.UpdateGlobals(); + // } + // catch (InvalidOperationException e) + // { + // // символ уже определен + // throw new RuntimeException(String.Format("Невозможно загрузить модуль {0}. Такой символ уже определен.", moduleName), e); + // } } [ContextMethod("ЗагрузитьБиблиотеку", "LoadLibrary")] @@ -128,7 +107,7 @@ public void LoadLibrary(string dllPath) { var context = new ComponentLoadingContext(dllPath); var assembly = context.LoadFromAssemblyPath(dllPath); - _engine.AttachExternalAssembly(assembly, _env); + _engine.AttachExternalAssembly(assembly); } [ContextMethod("ДобавитьМакет", "AddTemplate")] @@ -138,10 +117,10 @@ public void AddTemplate(string file, string name, TemplateKind kind = TemplateKi manager.RegisterTemplate(file, name, kind); } - public ExternalLibraryDef ProcessLibrary(string libraryPath) + public bool ProcessLibrary(string libraryPath) { bool success; - _delayLoadedScripts.Clear(); + _library = new ExternalLibraryDef(Path.GetFileName(libraryPath)); if(!_customized) { @@ -165,11 +144,9 @@ public ExternalLibraryDef ProcessLibrary(string libraryPath) if (!success) return default; - - var library = new ExternalLibraryDef(Path.GetFileName(libraryPath)); - CompileDelayedModules(library); + _libManager.InitExternalLibrary(_engine, _library); - return library; + return true; } private bool CustomizedProcessing(string libraryPath) @@ -223,50 +200,10 @@ private bool DefaultProcessing(string libraryPath) return hasFiles; } - private void CompileDelayedModules(ExternalLibraryDef library) - { - foreach (var scriptFile in _delayLoadedScripts) - { - if (scriptFile.asClass) - { - library.AddClass(scriptFile.identifier, scriptFile.path); - } - else - { - library.AddModule(scriptFile.identifier, scriptFile.path); - } - } - - library.Modules.ForEach(moduleFile => - { - var module = CompileFile(moduleFile.FilePath); - moduleFile.Module = module; - }); - - library.Classes.ForEach(classFile => - { - var module = CompileFile(classFile.FilePath); - _engine.AttachedScriptsFactory.RegisterTypeModule(classFile.Symbol, module); - classFile.Module = module; - }); - - _libManager.InitExternalLibrary(_engine, library); - } - - private IExecutableModule CompileFile(string path) - { - var compiler = _engine.GetCompilerService(); - - var source = _engine.Loader.FromFile(path); - var module = _engine.AttachedScriptsFactory.CompileModuleFromSource(compiler, source, null); - - return module; - } - private static Lazy TraceEnabled = - new Lazy(() => System.Environment.GetEnvironmentVariable("OS_LRE_TRACE") == "1"); - - public static void TraceLoadLibrary(string message) + new Lazy(() => Environment.GetEnvironmentVariable("OS_LRE_TRACE") == "1"); + + private static void TraceLoadLibrary(string message) { if (TraceEnabled.Value) { SystemLogger.Write("LRE: " + message); diff --git a/src/ScriptEngine/Libraries/DependencyLoader.cs b/src/ScriptEngine/Libraries/DependencyLoader.cs deleted file mode 100644 index e66a4c159..000000000 --- a/src/ScriptEngine/Libraries/DependencyLoader.cs +++ /dev/null @@ -1,35 +0,0 @@ -/*---------------------------------------------------------- -This Source Code Form is subject to the terms of the -Mozilla Public License, v.2.0. If a copy of the MPL -was not distributed with this file, You can obtain one -at http://mozilla.org/MPL/2.0/. -----------------------------------------------------------*/ - -using OneScript.Contexts; -using OneScript.Sources; -using ScriptEngine.Machine.Contexts; - -namespace ScriptEngine -{ - public class DependencyLoader - { - private readonly ScriptingEngine _engine; - private readonly IRuntimeEnvironment _env; - - public DependencyLoader(ScriptingEngine engine) - { - _engine = engine; - _env = engine.Environment; - } - - public void AddClass(ICodeSource source, string className) - { - - } - - public void AddModule(ICodeSource source, string moduleName) - { - - } - } -} \ No newline at end of file diff --git a/src/ScriptEngine/Libraries/ExternalLibraryDef.cs b/src/ScriptEngine/Libraries/ExternalLibraryDef.cs index 30bc701a8..3f204b010 100644 --- a/src/ScriptEngine/Libraries/ExternalLibraryDef.cs +++ b/src/ScriptEngine/Libraries/ExternalLibraryDef.cs @@ -28,7 +28,6 @@ public UserAddedScript AddClass(string identifier, string filePath, StackRuntime { var item = new UserAddedScript { - Type = UserAddedScriptType.Class, Module = module, Symbol = identifier, FilePath = filePath @@ -43,7 +42,6 @@ public UserAddedScript AddModule(string identifier, string filePath, StackRuntim { var item = new UserAddedScript { - Type = UserAddedScriptType.Module, Module = module, Symbol = identifier, FilePath = filePath @@ -57,17 +55,9 @@ public UserAddedScript AddModule(string identifier, string filePath, StackRuntim public class UserAddedScript { - public UserAddedScriptType Type; public string Symbol; public string FilePath; public IExecutableModule Module; } - - [Serializable] - public enum UserAddedScriptType - { - Module, - Class - } } \ No newline at end of file diff --git a/src/ScriptEngine/Libraries/ILibraryManager.cs b/src/ScriptEngine/Libraries/ILibraryManager.cs index b6ab90e53..71f24d0d3 100644 --- a/src/ScriptEngine/Libraries/ILibraryManager.cs +++ b/src/ScriptEngine/Libraries/ILibraryManager.cs @@ -14,7 +14,6 @@ namespace ScriptEngine.Libraries /// public interface ILibraryManager { - IEnumerable GetLibraries(); void InitExternalLibrary(ScriptingEngine runtime, ExternalLibraryDef library); } } \ No newline at end of file diff --git a/src/ScriptEngine/Libraries/LibraryManager.cs b/src/ScriptEngine/Libraries/LibraryManager.cs index 6ccfdd0b3..010a5a749 100644 --- a/src/ScriptEngine/Libraries/LibraryManager.cs +++ b/src/ScriptEngine/Libraries/LibraryManager.cs @@ -6,6 +6,10 @@ using System.Linq; using System.Text; using System.Threading.Tasks; +using OneScript.Compilation.Binding; +using OneScript.Exceptions; +using OneScript.Execution; +using OneScript.Localization; namespace ScriptEngine.Libraries { @@ -15,34 +19,89 @@ namespace ScriptEngine.Libraries /// internal class LibraryManager : ILibraryManager { - private readonly List _externalLibs = new List(); private readonly IRuntimeContextInstance _contextOfGlobalSymbols; public LibraryManager(IRuntimeContextInstance contextOfGlobalSymbols) { _contextOfGlobalSymbols = contextOfGlobalSymbols; } - - public IEnumerable GetLibraries() + + public LibraryManager() { - return _externalLibs.ToArray(); } public void InitExternalLibrary(ScriptingEngine runtime, ExternalLibraryDef library) { - var loadedObjects = new ScriptDrivenObject[library.Modules.Count]; + CompileDelayedModules(runtime, library); + + } + + private void CompileDelayedModules(ScriptingEngine runtime, ExternalLibraryDef library) + { + var symbols = runtime.Environment.GetSymbolTable(); + + // Зарегистрируем все символы модулей из данной библиотеки + // Попутно проверяем конфликт имен среди известных символов + var libraryScope = new SymbolScope(); int i = 0; foreach (var module in library.Modules) + { + if (symbols.FindVariable(module.Symbol, out _)) + { + // символ уже определен + throw new RuntimeException( + new BilingualString( + $"Невозможно загрузить модуль {module.Symbol}. Такой символ уже определен.", + $"Unable to load module {module.Symbol}. Symbol is already defined.") + ); + } + + libraryScope.DefineVariable( + BslPropertyBuilder.Create() + .Name(module.Symbol) + .CanRead(true) + .CanWrite(false) + .SetDispatchingIndex(i++) + .Build().ToSymbol() + ); + } + + // Получим байткоды всех классов и модулей из библиотеки + var ownerContext = new ModulesOrderingContext(libraryScope); + symbols.PushScope(libraryScope, new ModulesOrderingContext(libraryScope)); + + library.Modules.ForEach(moduleFile => + { + var module = CompileFile(runtime, moduleFile.FilePath); + moduleFile.Module = module; + }); + + library.Classes.ForEach(classFile => + { + var module = CompileFile(runtime, classFile.FilePath); + runtime.AttachedScriptsFactory.RegisterTypeModule(classFile.Symbol, module); + classFile.Module = module; + }); + + // Проведем инициализацию всех модулей + foreach (var module in library.Modules) { var instance = runtime.CreateUninitializedSDO(module.Module); - var propId = _contextOfGlobalSymbols.GetPropertyNumber(module.Symbol); - _contextOfGlobalSymbols.SetPropValue(propId, instance); - loadedObjects[i++] = instance; + ownerContext.SetUninitializedInstance(module, instance); } - _externalLibs.Add(library); - loadedObjects.ForEach(runtime.InitializeSDO); + ownerContext.InitializeModules(runtime); + } + + private IExecutableModule CompileFile(ScriptingEngine runtime, string path) + { + var compiler = runtime.GetCompilerService(); + + var source = runtime.Loader.FromFile(path); + var module = runtime.AttachedScriptsFactory.CompileModuleFromSource(compiler, source, null); + + return module; } } } diff --git a/src/ScriptEngine/Libraries/ModulesOrderingContext.cs b/src/ScriptEngine/Libraries/ModulesOrderingContext.cs new file mode 100644 index 000000000..78fa8f5ed --- /dev/null +++ b/src/ScriptEngine/Libraries/ModulesOrderingContext.cs @@ -0,0 +1,180 @@ +/*---------------------------------------------------------- +This Source Code Form is subject to the terms of the +Mozilla Public License, v.2.0. If a copy of the MPL +was not distributed with this file, You can obtain one +at http://mozilla.org/MPL/2.0/. +----------------------------------------------------------*/ + +using System; +using OneScript.Commons; +using OneScript.Compilation.Binding; +using OneScript.Contexts; +using OneScript.Values; +using ScriptEngine.Compiler; +using ScriptEngine.Machine; +using ScriptEngine.Machine.Contexts; + +namespace ScriptEngine.Libraries +{ + public class ModulesOrderingContext : IAttachableContext + { + private readonly SymbolScope _libraryScope; + + private class ModuleToLoad + { + public DiscoveryState state; + public BslValue moduleInstance; + } + + private enum DiscoveryState + { + New, + Discovered, + Processed + } + + private readonly IndexedNameValueCollection _values = + new IndexedNameValueCollection(); + + private ScriptingEngine _runtimeToInit = null; + + private IVariable[] _attachedState; + + public ModulesOrderingContext(SymbolScope libraryScope) + { + _libraryScope = libraryScope; + } + + public void SetUninitializedInstance(UserAddedScript module, ScriptDrivenObject instance) + { + var item = new ModuleToLoad + { + state = DiscoveryState.New, + moduleInstance = instance + }; + + _values.Add(item, module.Symbol); + } + + public void InitializeModules(ScriptingEngine runtime) + { + _runtimeToInit = runtime; + _attachedState = new IVariable[_values.Count]; + + int i = 0; + foreach (var moduleToLoad in _libraryScope.Variables) + { + _attachedState[i] = Variable.CreateContextPropertyReference(this, i, moduleToLoad.Name); + i++; + } + + foreach (var moduleToLoad in _values) + { + // В этот момент блок инициализации модуля + // через механизм IVariableReference может обратиться к контексту + // и затребовать какой-то другой модуль + // Метод получения значения свойства рекурсивно вызовет InitializeSDO для этого модуля + _runtimeToInit.InitializeSDO((ScriptDrivenObject)moduleToLoad.moduleInstance); + moduleToLoad.state = DiscoveryState.Processed; + } + + _runtimeToInit = null; + } + + public bool IsIndexed => false; + + public bool DynamicMethodSignatures => false; + + public IValue GetIndexedValue(IValue index) + { + throw new InvalidOperationException(); + } + + public void SetIndexedValue(IValue index, IValue val) + { + throw new InvalidOperationException(); + } + + public int GetPropertyNumber(string name) + { + var index = _values.IndexOf(name); + if (index >= 0) + { + return index; + } + else + { + throw new SymbolNotFoundException(name); + } + } + + public bool IsPropReadable(int propNum) => true; + + public bool IsPropWritable(int propNum) => false; + + public IValue GetPropValue(int propNum) + { + var item = _values[propNum]; + switch (item.state) + { + case DiscoveryState.Processed: + return item.moduleInstance; + case DiscoveryState.Discovered: + SystemLogger.Write($"Module {_values.NameOf(propNum)} is not initialized properly due to circular initialization"); + return item.moduleInstance; + } + + if (_runtimeToInit == null) + { + throw new InvalidOperationException("System error. Runtime is NULL while initializing library"); + } + + item.state = DiscoveryState.Discovered; + _runtimeToInit.InitializeSDO((ScriptDrivenObject)item.moduleInstance); + item.state = DiscoveryState.Processed; + + return item.moduleInstance; + } + + public void SetPropValue(int propNum, IValue newVal) + { + throw new System.NotImplementedException(); + } + + public int GetPropCount() => _values.Count; + + public string GetPropName(int propNum) => _values.NameOf(propNum); + + public int GetMethodNumber(string name) + { + throw new SymbolNotFoundException(name); + } + + public int GetMethodsCount() => 0; + + public BslMethodInfo GetMethodInfo(int methodNumber) + { + throw new System.NotImplementedException(); + } + + public BslPropertyInfo GetPropertyInfo(int propertyNumber) + { + return ((IPropertySymbol)_libraryScope.Variables[propertyNumber]).Property; + } + + public void CallAsProcedure(int methodNumber, IValue[] arguments) + { + throw new System.NotImplementedException(); + } + + public void CallAsFunction(int methodNumber, IValue[] arguments, out IValue retValue) + { + throw new System.NotImplementedException(); + } + + public void OnAttach(out IVariable[] variables, out BslMethodInfo[] methods) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/ScriptEngine/RuntimeEnvironment.cs b/src/ScriptEngine/RuntimeEnvironment.cs index d54a08097..8e18e476e 100644 --- a/src/ScriptEngine/RuntimeEnvironment.cs +++ b/src/ScriptEngine/RuntimeEnvironment.cs @@ -104,11 +104,6 @@ public IValue GetGlobalProperty(string propertyName) public IReadOnlyCollection AttachedContexts => _contexts; - public IEnumerable GetLibraries() - { - return _libraryManager.GetLibraries(); - } - public void InitExternalLibrary(ScriptingEngine runtime, ExternalLibraryDef library) { _libraryManager.InitExternalLibrary(runtime, library); From 081ca658d14dee89c3c11acf8ae69ea9bfe700d4 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 4 Nov 2024 13:07:21 +0300 Subject: [PATCH 30/32] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=20=D1=83=D0=BF=D0=BE=D1=80=D1=8F?= =?UTF-8?q?=D0=B4=D0=BE=D1=87=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BC=D0=BE=D0=B4?= =?UTF-8?q?=D1=83=D0=BB=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Libraries/LibraryManager.cs | 50 ++----------------- .../Libraries/ModulesOrderingContext.cs | 27 +++++----- src/ScriptEngine/Machine/MachineInstance.cs | 6 +-- src/ScriptEngine/RuntimeEnvironment.cs | 2 +- 4 files changed, 23 insertions(+), 62 deletions(-) diff --git a/src/ScriptEngine/Libraries/LibraryManager.cs b/src/ScriptEngine/Libraries/LibraryManager.cs index 010a5a749..61bad7d8f 100644 --- a/src/ScriptEngine/Libraries/LibraryManager.cs +++ b/src/ScriptEngine/Libraries/LibraryManager.cs @@ -10,6 +10,7 @@ using OneScript.Exceptions; using OneScript.Execution; using OneScript.Localization; +using ScriptEngine.Machine; namespace ScriptEngine.Libraries { @@ -19,56 +20,15 @@ namespace ScriptEngine.Libraries /// internal class LibraryManager : ILibraryManager { - private readonly IRuntimeContextInstance _contextOfGlobalSymbols; - - public LibraryManager(IRuntimeContextInstance contextOfGlobalSymbols) - { - _contextOfGlobalSymbols = contextOfGlobalSymbols; - } - - public LibraryManager() - { - } - public void InitExternalLibrary(ScriptingEngine runtime, ExternalLibraryDef library) { CompileDelayedModules(runtime, library); - + MachineInstance.Current.UpdateGlobals(); } private void CompileDelayedModules(ScriptingEngine runtime, ExternalLibraryDef library) { - var symbols = runtime.Environment.GetSymbolTable(); - - // Зарегистрируем все символы модулей из данной библиотеки - // Попутно проверяем конфликт имен среди известных символов - var libraryScope = new SymbolScope(); - int i = 0; - foreach (var module in library.Modules) - { - if (symbols.FindVariable(module.Symbol, out _)) - { - // символ уже определен - throw new RuntimeException( - new BilingualString( - $"Невозможно загрузить модуль {module.Symbol}. Такой символ уже определен.", - $"Unable to load module {module.Symbol}. Symbol is already defined.") - ); - } - - libraryScope.DefineVariable( - BslPropertyBuilder.Create() - .Name(module.Symbol) - .CanRead(true) - .CanWrite(false) - .SetDispatchingIndex(i++) - .Build().ToSymbol() - ); - } - - // Получим байткоды всех классов и модулей из библиотеки - var ownerContext = new ModulesOrderingContext(libraryScope); - symbols.PushScope(libraryScope, new ModulesOrderingContext(libraryScope)); + var ownerContext = new ModulesOrderingContext(); library.Modules.ForEach(moduleFile => { @@ -87,10 +47,10 @@ private void CompileDelayedModules(ScriptingEngine runtime, ExternalLibraryDef l foreach (var module in library.Modules) { var instance = runtime.CreateUninitializedSDO(module.Module); - ownerContext.SetUninitializedInstance(module, instance); } - + + runtime.Environment.InjectObject(ownerContext); ownerContext.InitializeModules(runtime); } diff --git a/src/ScriptEngine/Libraries/ModulesOrderingContext.cs b/src/ScriptEngine/Libraries/ModulesOrderingContext.cs index 78fa8f5ed..d101292b9 100644 --- a/src/ScriptEngine/Libraries/ModulesOrderingContext.cs +++ b/src/ScriptEngine/Libraries/ModulesOrderingContext.cs @@ -7,7 +7,6 @@ This Source Code Form is subject to the terms of the using System; using OneScript.Commons; -using OneScript.Compilation.Binding; using OneScript.Contexts; using OneScript.Values; using ScriptEngine.Compiler; @@ -18,11 +17,10 @@ namespace ScriptEngine.Libraries { public class ModulesOrderingContext : IAttachableContext { - private readonly SymbolScope _libraryScope; - private class ModuleToLoad { public DiscoveryState state; + public BslPropertyInfo propertyInfo; public BslValue moduleInstance; } @@ -40,11 +38,6 @@ private enum DiscoveryState private IVariable[] _attachedState; - public ModulesOrderingContext(SymbolScope libraryScope) - { - _libraryScope = libraryScope; - } - public void SetUninitializedInstance(UserAddedScript module, ScriptDrivenObject instance) { var item = new ModuleToLoad @@ -53,7 +46,14 @@ public void SetUninitializedInstance(UserAddedScript module, ScriptDrivenObject moduleInstance = instance }; - _values.Add(item, module.Symbol); + var index = _values.Add(item, module.Symbol); + + item.propertyInfo = BslPropertyBuilder.Create() + .Name(module.Symbol) + .CanRead(true) + .CanWrite(false) + .SetDispatchingIndex(index) + .Build(); } public void InitializeModules(ScriptingEngine runtime) @@ -62,9 +62,9 @@ public void InitializeModules(ScriptingEngine runtime) _attachedState = new IVariable[_values.Count]; int i = 0; - foreach (var moduleToLoad in _libraryScope.Variables) + foreach (var moduleToLoad in _values) { - _attachedState[i] = Variable.CreateContextPropertyReference(this, i, moduleToLoad.Name); + _attachedState[i] = Variable.CreateContextPropertyReference(this, i, moduleToLoad.propertyInfo.Name); i++; } @@ -159,7 +159,7 @@ public BslMethodInfo GetMethodInfo(int methodNumber) public BslPropertyInfo GetPropertyInfo(int propertyNumber) { - return ((IPropertySymbol)_libraryScope.Variables[propertyNumber]).Property; + return _values[propertyNumber].propertyInfo; } public void CallAsProcedure(int methodNumber, IValue[] arguments) @@ -174,7 +174,8 @@ public void CallAsFunction(int methodNumber, IValue[] arguments, out IValue retV public void OnAttach(out IVariable[] variables, out BslMethodInfo[] methods) { - throw new NotImplementedException(); + variables = _attachedState; + methods = Array.Empty(); } } } \ No newline at end of file diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index e342cf4aa..8f41a8bc7 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -66,13 +66,13 @@ public void SetMemory(ExecutionContext memory) _mem = memory; _codeStatCollector = _mem.Services.TryResolve(); - _globalContexts = _mem.GlobalNamespace.AttachedContexts.Select(x => new AttachedContext(x)) - .ToArray(); + UpdateGlobals(); } public void UpdateGlobals() { - _globalContexts.ForEach(x => x.Attach()); + _globalContexts =_mem.GlobalNamespace.AttachedContexts.Select(x => new AttachedContext(x)) + .ToArray(); } public bool IsRunning => _callStack.Count != 0; diff --git a/src/ScriptEngine/RuntimeEnvironment.cs b/src/ScriptEngine/RuntimeEnvironment.cs index 8e18e476e..930f0631f 100644 --- a/src/ScriptEngine/RuntimeEnvironment.cs +++ b/src/ScriptEngine/RuntimeEnvironment.cs @@ -30,7 +30,7 @@ public class RuntimeEnvironment : IRuntimeEnvironment, ILibraryManager public RuntimeEnvironment() { _injectedProperties = new PropertyBag(); - _libraryManager = new LibraryManager(_injectedProperties); + _libraryManager = new LibraryManager(); } private void CreateGlobalScopeIfNeeded() From 59c89831e493145801156ad6c4db0dbc55375ba4 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 4 Nov 2024 13:18:02 +0300 Subject: [PATCH 31/32] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B8=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=D0=BB=20=D0=BA=D0=BB=D0=B0=D1=81?= =?UTF-8?q?=D1=81=20=D0=B2=20=D0=B1=D0=BE=D0=BB=D0=B5=D0=B5=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=BD=D1=8F=D1=82=D0=BD=D1=8B=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Compilation/CompilerFrontendBase.cs | 2 +- ...olsProvider.cs => ITypeSymbolsProvider.cs} | 5 +++- ...vider.cs => TypeSymbolsProviderFactory.cs} | 25 +++++++++++-------- .../Hosting/EngineBuilderExtensions.cs | 2 +- .../Contexts/AutoScriptDrivenObject.cs | 4 +-- .../Contexts/ThisAwareScriptedObjectBase.cs | 2 +- .../Contexts/UserScriptContextInstance.cs | 4 +-- .../OneScript.Dynamic.Tests/NativeSdoTests.cs | 4 +-- 8 files changed, 27 insertions(+), 21 deletions(-) rename src/OneScript.Core/Compilation/{IModuleSymbolsProvider.cs => ITypeSymbolsProvider.cs} (67%) rename src/OneScript.Core/Compilation/{CompileTimeSymbolsProvider.cs => TypeSymbolsProviderFactory.cs} (66%) diff --git a/src/OneScript.Core/Compilation/CompilerFrontendBase.cs b/src/OneScript.Core/Compilation/CompilerFrontendBase.cs index 7035d267b..bed815268 100644 --- a/src/OneScript.Core/Compilation/CompilerFrontendBase.cs +++ b/src/OneScript.Core/Compilation/CompilerFrontendBase.cs @@ -45,7 +45,7 @@ protected CompilerFrontendBase( public SymbolScope FillSymbols(Type targetType) { - var symbolsProvider = Services.Resolve(); + var symbolsProvider = Services.Resolve(); var typeSymbols = symbolsProvider.Get(targetType); ModuleSymbols = new SymbolScope(); typeSymbols.FillSymbols(ModuleSymbols); diff --git a/src/OneScript.Core/Compilation/IModuleSymbolsProvider.cs b/src/OneScript.Core/Compilation/ITypeSymbolsProvider.cs similarity index 67% rename from src/OneScript.Core/Compilation/IModuleSymbolsProvider.cs rename to src/OneScript.Core/Compilation/ITypeSymbolsProvider.cs index 7919d3f5b..13fcb632e 100644 --- a/src/OneScript.Core/Compilation/IModuleSymbolsProvider.cs +++ b/src/OneScript.Core/Compilation/ITypeSymbolsProvider.cs @@ -9,7 +9,10 @@ This Source Code Form is subject to the terms of the namespace OneScript.Compilation { - public interface IModuleSymbolsProvider + /// + /// Провайдер дополнительных внешних символов для класса при компиляции. + /// + public interface ITypeSymbolsProvider { void FillSymbols(SymbolScope moduleScope); } diff --git a/src/OneScript.Core/Compilation/CompileTimeSymbolsProvider.cs b/src/OneScript.Core/Compilation/TypeSymbolsProviderFactory.cs similarity index 66% rename from src/OneScript.Core/Compilation/CompileTimeSymbolsProvider.cs rename to src/OneScript.Core/Compilation/TypeSymbolsProviderFactory.cs index f037926fd..0b73108c2 100644 --- a/src/OneScript.Core/Compilation/CompileTimeSymbolsProvider.cs +++ b/src/OneScript.Core/Compilation/TypeSymbolsProviderFactory.cs @@ -12,19 +12,22 @@ This Source Code Form is subject to the terms of the namespace OneScript.Compilation { - public class CompileTimeSymbolsProvider + /// + /// Фабрика провайдеров дополнительных внешних символов для класса при компиляции. + /// + public class TypeSymbolsProviderFactory { - private delegate void Filler(CompileTimeSymbolsProvider provider, SymbolScope scope); + private delegate void Filler(TypeSymbolsProviderFactory providerFactory, SymbolScope scope); private readonly ConcurrentDictionary _providers = new ConcurrentDictionary(); - public IModuleSymbolsProvider Get() + public ITypeSymbolsProvider Get() { return Get(typeof(T)); } - public IModuleSymbolsProvider Get(Type type) + public ITypeSymbolsProvider Get(Type type) { return _providers.GetOrAdd(type, CreateProvider); } @@ -46,7 +49,7 @@ private static Filler FindFillerMethod(Type type) return filler; } - private static void DoNothing(CompileTimeSymbolsProvider provider, SymbolScope scope) + private static void DoNothing(TypeSymbolsProviderFactory providerFactory, SymbolScope scope) { } @@ -54,24 +57,24 @@ private static bool IsFiller(MethodInfo methodInfo) { var parameters = methodInfo.GetParameters(); return parameters.Length == 2 - && parameters[0].ParameterType == typeof(CompileTimeSymbolsProvider) + && parameters[0].ParameterType == typeof(TypeSymbolsProviderFactory) && parameters[1].ParameterType == typeof(SymbolScope); } - private class SymbolProvider : IModuleSymbolsProvider + private class SymbolProvider : ITypeSymbolsProvider { - private readonly CompileTimeSymbolsProvider _provider; + private readonly TypeSymbolsProviderFactory _providerFactory; private readonly Filler _filler; - public SymbolProvider(CompileTimeSymbolsProvider provider, Filler filler) + public SymbolProvider(TypeSymbolsProviderFactory providerFactory, Filler filler) { - _provider = provider; + _providerFactory = providerFactory; _filler = filler; } public void FillSymbols(SymbolScope moduleScope) { - _filler(_provider, moduleScope); + _filler(_providerFactory, moduleScope); } } } diff --git a/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs b/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs index 971fdff16..dafa3117c 100644 --- a/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs +++ b/src/ScriptEngine/Hosting/EngineBuilderExtensions.cs @@ -51,7 +51,7 @@ public static IEngineBuilder SetDefaultOptions(this IEngineBuilder builder) services.RegisterSingleton(); services.RegisterSingleton(); services.RegisterSingleton(sp => sp.Resolve()); - services.RegisterSingleton(); + services.RegisterSingleton(); services.RegisterSingleton(svc => new ThrowingErrorSink(CompilerException.FromCodeError)); services.RegisterSingleton(); diff --git a/src/ScriptEngine/Machine/Contexts/AutoScriptDrivenObject.cs b/src/ScriptEngine/Machine/Contexts/AutoScriptDrivenObject.cs index 520eaa9ae..82902b7e2 100644 --- a/src/ScriptEngine/Machine/Contexts/AutoScriptDrivenObject.cs +++ b/src/ScriptEngine/Machine/Contexts/AutoScriptDrivenObject.cs @@ -134,9 +134,9 @@ protected override void CallOwnProcedure(int index, IValue[] arguments) #endregion [SymbolsProvider] - private static void FillSymbols(CompileTimeSymbolsProvider provider, SymbolScope moduleScope) + private static void FillSymbols(TypeSymbolsProviderFactory providerFactory, SymbolScope moduleScope) { - var baseProvider = provider.Get(); + var baseProvider = providerFactory.Get(); baseProvider.FillSymbols(moduleScope); for (int i = 0; i < _ownProperties.Count; i++) diff --git a/src/ScriptEngine/Machine/Contexts/ThisAwareScriptedObjectBase.cs b/src/ScriptEngine/Machine/Contexts/ThisAwareScriptedObjectBase.cs index de802eeed..dfa83d0cf 100644 --- a/src/ScriptEngine/Machine/Contexts/ThisAwareScriptedObjectBase.cs +++ b/src/ScriptEngine/Machine/Contexts/ThisAwareScriptedObjectBase.cs @@ -93,7 +93,7 @@ protected override BslPropertyInfo GetOwnPropertyInfo(int index) [SymbolsProvider] // ReSharper disable once UnusedMember.Local - private static void CompileTimeSymbols(CompileTimeSymbolsProvider provider, SymbolScope moduleScope) + private static void CompileTimeSymbols(TypeSymbolsProviderFactory providerFactory, SymbolScope moduleScope) { moduleScope.Variables.Add(BslFieldBuilder.Create() .Name(THISOBJ_RU) diff --git a/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs b/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs index acb163da4..401e8ed97 100644 --- a/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs +++ b/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs @@ -202,9 +202,9 @@ protected override BslPropertyInfo GetOwnPropertyInfo(int index) } [SymbolsProvider] - private static void PrepareCompilation(CompileTimeSymbolsProvider provider, SymbolScope scope) + private static void PrepareCompilation(TypeSymbolsProviderFactory providerFactory, SymbolScope scope) { - var baseSymbols = provider.Get(); + var baseSymbols = providerFactory.Get(); baseSymbols.FillSymbols(scope); GetOwnMethodsDefinition().ForEach(x => scope.DefineMethod(x.ToSymbol())); } diff --git a/src/Tests/OneScript.Dynamic.Tests/NativeSdoTests.cs b/src/Tests/OneScript.Dynamic.Tests/NativeSdoTests.cs index 91e859cf3..97d4d9376 100644 --- a/src/Tests/OneScript.Dynamic.Tests/NativeSdoTests.cs +++ b/src/Tests/OneScript.Dynamic.Tests/NativeSdoTests.cs @@ -51,7 +51,7 @@ public NativeSdoTests() testServices.Register(sp => sp); testServices.RegisterSingleton(); testServices.RegisterSingleton(); - testServices.RegisterSingleton(); + testServices.RegisterSingleton(); testServices.RegisterEnumerable(); testServices.Register(); testServices.UseImports(); @@ -437,7 +437,7 @@ Функция НайтиСовпадения(Текст) Экспорт private DynamicModule CreateModule(string code, IServiceContainer services, SymbolTable symbols) { - var symbolProvider = services.Resolve(); + var symbolProvider = services.Resolve(); var moduleScope = new SymbolScope(); symbolProvider.Get().FillSymbols(moduleScope); symbols.PushScope(moduleScope, null); From cabdcde872e289b5be2d3411db2bf8d728f7a402 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 4 Nov 2024 21:01:51 +0300 Subject: [PATCH 32/32] =?UTF-8?q?=D0=92=20=D0=B7=D0=B0=D0=B4=D0=BD=D0=B8?= =?UTF-8?q?=D1=86=D1=83=20=D1=8D=D1=82=D0=BE=20=D0=B3=D0=B8=D0=B1=D0=BB?= =?UTF-8?q?=D0=BE=D0=B5=20=D0=B4=D0=B5=D0=BB=D0=BE=20:(?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Compilation/Binding/ISymbolTable.cs | 27 ++++ .../Compilation/Binding/SymbolTable.cs | 2 +- .../Compilation/CompilerFrontendBase.cs | 19 +-- .../Compilation/CompoundSymbolTable.cs | 137 ++++++++++++++++++ .../Compilation/ICompilerBackend.cs | 2 +- .../Compiler/BslWalkerContext.cs | 2 +- .../Compiler/ExpressionTreeGeneratorBase.cs | 6 +- .../Compiler/ModuleCompiler.cs | 2 +- src/ScriptEngine/Compiler/CompilerFrontend.cs | 9 +- .../Compiler/DefaultCompilerBackend.cs | 2 +- src/ScriptEngine/Compiler/EvalCompiler.cs | 6 +- .../Compiler/NativeCompilerBackend.cs | 2 +- .../Compiler/StackMachineCodeGenerator.cs | 5 +- src/ScriptEngine/Libraries/LibraryManager.cs | 29 ++-- .../Libraries/ModulesOrderingContext.cs | 12 +- src/ScriptEngine/Machine/MachineInstance.cs | 7 +- .../Machine/StackRuntimeModule.cs | 2 + .../CompoundSymbolTableTest.cs | 85 +++++++++++ 18 files changed, 307 insertions(+), 49 deletions(-) create mode 100644 src/OneScript.Core/Compilation/Binding/ISymbolTable.cs create mode 100644 src/OneScript.Core/Compilation/CompoundSymbolTable.cs create mode 100644 src/Tests/OneScript.Core.Tests/CompoundSymbolTableTest.cs diff --git a/src/OneScript.Core/Compilation/Binding/ISymbolTable.cs b/src/OneScript.Core/Compilation/Binding/ISymbolTable.cs new file mode 100644 index 000000000..1cd346b41 --- /dev/null +++ b/src/OneScript.Core/Compilation/Binding/ISymbolTable.cs @@ -0,0 +1,27 @@ +/*---------------------------------------------------------- +This Source Code Form is subject to the terms of the +Mozilla Public License, v.2.0. If a copy of the MPL +was not distributed with this file, You can obtain one +at http://mozilla.org/MPL/2.0/. +----------------------------------------------------------*/ + +using OneScript.Contexts; + +namespace OneScript.Compilation.Binding +{ + public interface ISymbolTable + { + SymbolScope GetScope(int index); + IAttachableContext GetBinding(int scopeIndex); + int ScopeCount { get; } + int PushScope(SymbolScope scope, IAttachableContext target); + void PopScope(); + bool FindVariable(string name, out SymbolBinding binding); + bool TryFindMethodBinding(string name, out SymbolBinding binding); + bool TryFindMethod(string name, out IMethodSymbol method); + SymbolBinding DefineMethod(IMethodSymbol symbol); + SymbolBinding DefineVariable(IVariableSymbol symbol); + IVariableSymbol GetVariable(SymbolBinding binding); + IMethodSymbol GetMethod(SymbolBinding binding); + } +} \ No newline at end of file diff --git a/src/OneScript.Core/Compilation/Binding/SymbolTable.cs b/src/OneScript.Core/Compilation/Binding/SymbolTable.cs index 6f8dfced5..e0a22a9f5 100644 --- a/src/OneScript.Core/Compilation/Binding/SymbolTable.cs +++ b/src/OneScript.Core/Compilation/Binding/SymbolTable.cs @@ -11,7 +11,7 @@ This Source Code Form is subject to the terms of the namespace OneScript.Compilation.Binding { - public class SymbolTable + public class SymbolTable : ISymbolTable { private class BindingRecord { diff --git a/src/OneScript.Core/Compilation/CompilerFrontendBase.cs b/src/OneScript.Core/Compilation/CompilerFrontendBase.cs index bed815268..8fb898baa 100644 --- a/src/OneScript.Core/Compilation/CompilerFrontendBase.cs +++ b/src/OneScript.Core/Compilation/CompilerFrontendBase.cs @@ -85,23 +85,16 @@ public IExecutableModule CompileBatch(SourceCode source) return CompileBatchInternal(symbols, parsedModule); } - protected abstract IExecutableModule CompileInternal(SymbolTable symbols, ModuleNode parsedModule, Type classType); + protected abstract IExecutableModule CompileInternal(ISymbolTable symbols, ModuleNode parsedModule, Type classType); - protected abstract IExecutableModule CompileExpressionInternal(SymbolTable symbols, ModuleNode parsedModule); + protected abstract IExecutableModule CompileExpressionInternal(ISymbolTable symbols, ModuleNode parsedModule); - protected abstract IExecutableModule CompileBatchInternal(SymbolTable symbols, ModuleNode parsedModule); + protected abstract IExecutableModule CompileBatchInternal(ISymbolTable symbols, ModuleNode parsedModule); - private SymbolTable PrepareSymbols() + private ISymbolTable PrepareSymbols() { - var actualTable = new SymbolTable(); - if (SharedSymbols != default) - { - for (int i = 0; i < SharedSymbols.ScopeCount; i++) - { - actualTable.PushScope(SharedSymbols.GetScope(i), SharedSymbols.GetBinding(i)); - } - } - + var actualTable = new CompoundSymbolTable(SharedSymbols); + ModuleSymbols ??= new SymbolScope(); actualTable.PushScope(ModuleSymbols, null); diff --git a/src/OneScript.Core/Compilation/CompoundSymbolTable.cs b/src/OneScript.Core/Compilation/CompoundSymbolTable.cs new file mode 100644 index 000000000..d2af28db2 --- /dev/null +++ b/src/OneScript.Core/Compilation/CompoundSymbolTable.cs @@ -0,0 +1,137 @@ +/*---------------------------------------------------------- +This Source Code Form is subject to the terms of the +Mozilla Public License, v.2.0. If a copy of the MPL +was not distributed with this file, You can obtain one +at http://mozilla.org/MPL/2.0/. +----------------------------------------------------------*/ + +using System; +using System.Runtime.CompilerServices; +using OneScript.Compilation.Binding; +using OneScript.Contexts; + +namespace OneScript.Compilation +{ + public class CompoundSymbolTable : ISymbolTable + { + private readonly ISymbolTable _masterTable; + private readonly SymbolTable _innerTable; + + public CompoundSymbolTable(ISymbolTable masterTable) + { + _masterTable = masterTable; + _innerTable = new SymbolTable(); + } + + private int MasterSize => _masterTable.ScopeCount; + + public SymbolScope GetScope(int index) + { + return index < MasterSize ? + _masterTable.GetScope(index) : + _innerTable.GetScope(index - MasterSize); + } + + public IAttachableContext GetBinding(int scopeIndex) + { + return scopeIndex < MasterSize ? + _masterTable.GetBinding(scopeIndex) : + _innerTable.GetBinding(scopeIndex - MasterSize); + } + + public int ScopeCount => _masterTable.ScopeCount + _innerTable.ScopeCount; + + public int PushScope(SymbolScope scope, IAttachableContext target) + { + return _innerTable.PushScope(scope, target) + MasterSize; + } + + public void PopScope() + { + if (_innerTable.ScopeCount == 0) + throw new InvalidOperationException("Inner scopes are empty"); + + _innerTable.PopScope(); + } + + public bool FindVariable(string name, out SymbolBinding binding) + { + if (_innerTable.FindVariable(name, out binding)) + { + ShiftToPublicIndex(ref binding); + return true; + } + + return _masterTable.FindVariable(name, out binding); + } + + public bool TryFindMethodBinding(string name, out SymbolBinding binding) + { + if (_innerTable.TryFindMethodBinding(name, out binding)) + { + ShiftToPublicIndex(ref binding); + return true; + } + + return _masterTable.TryFindMethodBinding(name, out binding); + } + + public bool TryFindMethod(string name, out IMethodSymbol method) + { + return _innerTable.TryFindMethod(name, out method) + || _masterTable.TryFindMethod(name, out method); + } + + public SymbolBinding DefineMethod(IMethodSymbol symbol) + { + var binding = _innerTable.DefineMethod(symbol); + ShiftToPublicIndex(ref binding); + return binding; + } + + public SymbolBinding DefineVariable(IVariableSymbol symbol) + { + var binding = _innerTable.DefineVariable(symbol); + ShiftToPublicIndex(ref binding); + return binding; + } + + public IVariableSymbol GetVariable(SymbolBinding binding) + { + if (binding.ScopeNumber < MasterSize) + { + return _masterTable.GetVariable(binding); + } + else + { + UnshiftToInnerIndex(ref binding); + return _innerTable.GetVariable(binding); + } + } + + public IMethodSymbol GetMethod(SymbolBinding binding) + { + if (binding.ScopeNumber < MasterSize) + { + return _masterTable.GetMethod(binding); + } + else + { + UnshiftToInnerIndex(ref binding); + return _innerTable.GetMethod(binding); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ShiftToPublicIndex(ref SymbolBinding binding) + { + binding.ScopeNumber += MasterSize; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void UnshiftToInnerIndex(ref SymbolBinding binding) + { + binding.ScopeNumber -= MasterSize; + } + } +} \ No newline at end of file diff --git a/src/OneScript.Core/Compilation/ICompilerBackend.cs b/src/OneScript.Core/Compilation/ICompilerBackend.cs index 158210d98..6083d8f72 100644 --- a/src/OneScript.Core/Compilation/ICompilerBackend.cs +++ b/src/OneScript.Core/Compilation/ICompilerBackend.cs @@ -19,7 +19,7 @@ public interface ICompilerBackend bool GenerateCodeStat { get; set; } - public SymbolTable Symbols { get; set; } + public ISymbolTable Symbols { get; set; } IExecutableModule Compile(ModuleNode parsedModule, Type classType); } diff --git a/src/OneScript.Native/Compiler/BslWalkerContext.cs b/src/OneScript.Native/Compiler/BslWalkerContext.cs index 41cffc379..cdb5043bd 100644 --- a/src/OneScript.Native/Compiler/BslWalkerContext.cs +++ b/src/OneScript.Native/Compiler/BslWalkerContext.cs @@ -14,7 +14,7 @@ namespace OneScript.Native.Compiler { public class BslWalkerContext { - public SymbolTable Symbols { get; set; } + public ISymbolTable Symbols { get; set; } public IErrorSink Errors { get; set; } diff --git a/src/OneScript.Native/Compiler/ExpressionTreeGeneratorBase.cs b/src/OneScript.Native/Compiler/ExpressionTreeGeneratorBase.cs index e33a6968f..63334eb79 100644 --- a/src/OneScript.Native/Compiler/ExpressionTreeGeneratorBase.cs +++ b/src/OneScript.Native/Compiler/ExpressionTreeGeneratorBase.cs @@ -18,7 +18,7 @@ public abstract class ExpressionTreeGeneratorBase : BslSyntaxWalker { private IErrorSink _errors; private SourceCode _sourceCode; - private SymbolTable _ctx; + private ISymbolTable _ctx; protected ExpressionTreeGeneratorBase() { @@ -39,7 +39,7 @@ protected void InitContext(BslWalkerContext context) InitContext(context.Errors, context.Source, context.Symbols); } - protected void InitContext(IErrorSink errors, SourceCode lineInfo, SymbolTable symbols) + protected void InitContext(IErrorSink errors, SourceCode lineInfo, ISymbolTable symbols) { _errors = errors; _sourceCode = lineInfo; @@ -48,7 +48,7 @@ protected void InitContext(IErrorSink errors, SourceCode lineInfo, SymbolTable s protected IErrorSink Errors => _errors; - protected SymbolTable Symbols => _ctx; + protected ISymbolTable Symbols => _ctx; protected virtual BslWalkerContext MakeContext() { diff --git a/src/OneScript.Native/Compiler/ModuleCompiler.cs b/src/OneScript.Native/Compiler/ModuleCompiler.cs index 61acb2044..e90e505a9 100644 --- a/src/OneScript.Native/Compiler/ModuleCompiler.cs +++ b/src/OneScript.Native/Compiler/ModuleCompiler.cs @@ -40,7 +40,7 @@ public ModuleCompiler(IErrorSink errors, IServiceContainer runtimeServices, ICom public DynamicModule Compile( SourceCode moduleInfo, BslSyntaxNode moduleNode, - SymbolTable symbols + ISymbolTable symbols ) { InitContext(Errors, moduleInfo, symbols); diff --git a/src/ScriptEngine/Compiler/CompilerFrontend.cs b/src/ScriptEngine/Compiler/CompilerFrontend.cs index 951a93cf7..711d73051 100644 --- a/src/ScriptEngine/Compiler/CompilerFrontend.cs +++ b/src/ScriptEngine/Compiler/CompilerFrontend.cs @@ -33,8 +33,7 @@ public CompilerFrontend( IErrorSink errorSink, IServiceContainer services, IDependencyResolver dependencyResolver, - PredefinedInterfaceResolver interfaceResolver, - IEnumerable checkers) : base(handlers, errorSink, services) + PredefinedInterfaceResolver interfaceResolver) : base(handlers, errorSink, services) { _dependencyResolver = dependencyResolver; _interfaceResolver = interfaceResolver; @@ -68,7 +67,7 @@ private void SetDefaultOptions(ICompilerBackend backend) backend.GenerateDebugCode = GenerateDebugCode; } - protected override IExecutableModule CompileInternal(SymbolTable symbols, ModuleNode parsedModule, Type classType) + protected override IExecutableModule CompileInternal(ISymbolTable symbols, ModuleNode parsedModule, Type classType) { var backend = _backendSelector.Select(parsedModule); backend.Symbols = symbols; @@ -80,14 +79,14 @@ protected override IExecutableModule CompileInternal(SymbolTable symbols, Module return module; } - protected override IExecutableModule CompileExpressionInternal(SymbolTable symbols, ModuleNode parsedModule) + protected override IExecutableModule CompileExpressionInternal(ISymbolTable symbols, ModuleNode parsedModule) { var backend = _backendSelector.Select(parsedModule); backend.Symbols = symbols; return backend.Compile(parsedModule, typeof(UserScriptContextInstance)); } - protected override IExecutableModule CompileBatchInternal(SymbolTable symbols, ModuleNode parsedModule) + protected override IExecutableModule CompileBatchInternal(ISymbolTable symbols, ModuleNode parsedModule) { var backend = _backendSelector.Select(parsedModule); backend.Symbols = symbols; diff --git a/src/ScriptEngine/Compiler/DefaultCompilerBackend.cs b/src/ScriptEngine/Compiler/DefaultCompilerBackend.cs index ffb5456c1..fd5c8cabf 100644 --- a/src/ScriptEngine/Compiler/DefaultCompilerBackend.cs +++ b/src/ScriptEngine/Compiler/DefaultCompilerBackend.cs @@ -28,7 +28,7 @@ public DefaultCompilerBackend(IErrorSink errorSink) public bool GenerateCodeStat { get; set; } - public SymbolTable Symbols { get; set; } + public ISymbolTable Symbols { get; set; } public IExecutableModule Compile(ModuleNode parsedModule, Type classType) { diff --git a/src/ScriptEngine/Compiler/EvalCompiler.cs b/src/ScriptEngine/Compiler/EvalCompiler.cs index 373f60665..a7e2b3d7e 100644 --- a/src/ScriptEngine/Compiler/EvalCompiler.cs +++ b/src/ScriptEngine/Compiler/EvalCompiler.cs @@ -29,12 +29,12 @@ public EvalCompiler( _backend = new DefaultCompilerBackend(errorSink); } - protected override IExecutableModule CompileInternal(SymbolTable symbols, ModuleNode parsedModule, Type classType) + protected override IExecutableModule CompileInternal(ISymbolTable symbols, ModuleNode parsedModule, Type classType) { throw new NotSupportedException(); } - protected override IExecutableModule CompileExpressionInternal(SymbolTable symbols, ModuleNode parsedModule) + protected override IExecutableModule CompileExpressionInternal(ISymbolTable symbols, ModuleNode parsedModule) { _backend.Symbols = symbols; _backend.GenerateDebugCode = false; @@ -42,7 +42,7 @@ protected override IExecutableModule CompileExpressionInternal(SymbolTable symbo return _backend.Compile(parsedModule, default); } - protected override IExecutableModule CompileBatchInternal(SymbolTable symbols, ModuleNode parsedModule) + protected override IExecutableModule CompileBatchInternal(ISymbolTable symbols, ModuleNode parsedModule) { _backend.Symbols = symbols; _backend.GenerateDebugCode = false; diff --git a/src/ScriptEngine/Compiler/NativeCompilerBackend.cs b/src/ScriptEngine/Compiler/NativeCompilerBackend.cs index 6c6bb9344..0d6963e82 100644 --- a/src/ScriptEngine/Compiler/NativeCompilerBackend.cs +++ b/src/ScriptEngine/Compiler/NativeCompilerBackend.cs @@ -28,7 +28,7 @@ public NativeCompilerBackend(IErrorSink errorSink, IServiceContainer services) public bool GenerateCodeStat { get; set; } - public SymbolTable Symbols { get; set; } + public ISymbolTable Symbols { get; set; } public IExecutableModule Compile(ModuleNode parsedModule, Type classType) { diff --git a/src/ScriptEngine/Compiler/StackMachineCodeGenerator.cs b/src/ScriptEngine/Compiler/StackMachineCodeGenerator.cs index 0d25b176b..225e96235 100644 --- a/src/ScriptEngine/Compiler/StackMachineCodeGenerator.cs +++ b/src/ScriptEngine/Compiler/StackMachineCodeGenerator.cs @@ -32,7 +32,7 @@ public partial class StackMachineCodeGenerator : BslSyntaxWalker private readonly IErrorSink _errorSink; private readonly StackRuntimeModule _module; private SourceCode _sourceCode; - private SymbolTable _ctx; + private ISymbolTable _ctx; private List _constMap = new List(); private readonly List _forwardedMethods = new List(); @@ -48,7 +48,7 @@ public StackMachineCodeGenerator(IErrorSink errorSink) public IDependencyResolver DependencyResolver { get; set; } - public StackRuntimeModule CreateModule(ModuleNode moduleNode, SourceCode source, SymbolTable context) + public StackRuntimeModule CreateModule(ModuleNode moduleNode, SourceCode source, ISymbolTable context) { if (moduleNode.Kind != NodeKind.Module) { @@ -67,6 +67,7 @@ private StackRuntimeModule CreateImageInternal(ModuleNode moduleNode) CheckForwardedDeclarations(); _module.Source = _sourceCode; + _module.EnvironmentLoadingBoundary = _ctx.ScopeCount - 1; return _module; } diff --git a/src/ScriptEngine/Libraries/LibraryManager.cs b/src/ScriptEngine/Libraries/LibraryManager.cs index 61bad7d8f..5a3eb2124 100644 --- a/src/ScriptEngine/Libraries/LibraryManager.cs +++ b/src/ScriptEngine/Libraries/LibraryManager.cs @@ -1,15 +1,12 @@ -using OneScript.Commons; -using OneScript.Contexts; -using ScriptEngine.Machine.Contexts; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using OneScript.Compilation.Binding; -using OneScript.Exceptions; +/*---------------------------------------------------------- +This Source Code Form is subject to the terms of the +Mozilla Public License, v.2.0. If a copy of the MPL +was not distributed with this file, You can obtain one +at http://mozilla.org/MPL/2.0/. +----------------------------------------------------------*/ + +using OneScript.Commons; using OneScript.Execution; -using OneScript.Localization; using ScriptEngine.Machine; namespace ScriptEngine.Libraries @@ -23,12 +20,19 @@ internal class LibraryManager : ILibraryManager public void InitExternalLibrary(ScriptingEngine runtime, ExternalLibraryDef library) { CompileDelayedModules(runtime, library); - MachineInstance.Current.UpdateGlobals(); } private void CompileDelayedModules(ScriptingEngine runtime, ExternalLibraryDef library) { var ownerContext = new ModulesOrderingContext(); + + // Зарегистрируем модули, как видимые символы + foreach (var module in library.Modules) + { + ownerContext.AddKnownModule(module); + } + runtime.Environment.InjectObject(ownerContext); + MachineInstance.Current.UpdateGlobals(); library.Modules.ForEach(moduleFile => { @@ -50,7 +54,6 @@ private void CompileDelayedModules(ScriptingEngine runtime, ExternalLibraryDef l ownerContext.SetUninitializedInstance(module, instance); } - runtime.Environment.InjectObject(ownerContext); ownerContext.InitializeModules(runtime); } diff --git a/src/ScriptEngine/Libraries/ModulesOrderingContext.cs b/src/ScriptEngine/Libraries/ModulesOrderingContext.cs index d101292b9..92d5205dd 100644 --- a/src/ScriptEngine/Libraries/ModulesOrderingContext.cs +++ b/src/ScriptEngine/Libraries/ModulesOrderingContext.cs @@ -38,16 +38,16 @@ private enum DiscoveryState private IVariable[] _attachedState; - public void SetUninitializedInstance(UserAddedScript module, ScriptDrivenObject instance) + public void AddKnownModule(UserAddedScript module) { var item = new ModuleToLoad { state = DiscoveryState.New, - moduleInstance = instance + moduleInstance = null }; var index = _values.Add(item, module.Symbol); - + item.propertyInfo = BslPropertyBuilder.Create() .Name(module.Symbol) .CanRead(true) @@ -55,6 +55,12 @@ public void SetUninitializedInstance(UserAddedScript module, ScriptDrivenObject .SetDispatchingIndex(index) .Build(); } + + public void SetUninitializedInstance(UserAddedScript module, ScriptDrivenObject instance) + { + var item = _values[module.Symbol]; + item.moduleInstance = instance; + } public void InitializeModules(ScriptingEngine runtime) { diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index 8f41a8bc7..bf3da1d79 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -8,6 +8,7 @@ This Source Code Form is subject to the terms of the using ScriptEngine.Machine.Contexts; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; @@ -87,7 +88,11 @@ internal IValue ExecuteMethod(IRunnable sdo, MachineMethodInfo methodInfo, IValu Debug.Assert(module != null); var thisScope = new AttachedContext(sdo); - var scopes = CreateFrameScopes(_globalContexts, thisScope); + var scopes = CreateFrameScopes( + _globalContexts + .Take(module.EnvironmentLoadingBoundary) + .ToList(), + thisScope); var frame = new ExecutionFrame { diff --git a/src/ScriptEngine/Machine/StackRuntimeModule.cs b/src/ScriptEngine/Machine/StackRuntimeModule.cs index b4fecbf2b..e7896ae1b 100644 --- a/src/ScriptEngine/Machine/StackRuntimeModule.cs +++ b/src/ScriptEngine/Machine/StackRuntimeModule.cs @@ -26,6 +26,8 @@ public StackRuntimeModule(Type ownerType) public int EntryMethodIndex { get; set; } = -1; + public int EnvironmentLoadingBoundary { get; set; } = -1; + public List Constants { get; } = new List(); internal IList VariableRefs { get; } = new List(); diff --git a/src/Tests/OneScript.Core.Tests/CompoundSymbolTableTest.cs b/src/Tests/OneScript.Core.Tests/CompoundSymbolTableTest.cs new file mode 100644 index 000000000..cb8328f5f --- /dev/null +++ b/src/Tests/OneScript.Core.Tests/CompoundSymbolTableTest.cs @@ -0,0 +1,85 @@ +/*---------------------------------------------------------- +This Source Code Form is subject to the terms of the +Mozilla Public License, v.2.0. If a copy of the MPL +was not distributed with this file, You can obtain one +at http://mozilla.org/MPL/2.0/. +----------------------------------------------------------*/ + +using FluentAssertions; +using OneScript.Compilation; +using OneScript.Compilation.Binding; +using OneScript.Contexts; +using Xunit; + +namespace OneScript.Core.Tests; + +public class CompoundSymbolTableTest +{ + [Fact] + public void OnlyMaster() + { + var master = new SymbolTable(); + master.PushScope(new SymbolScope(), null); + + master.DefineMethod(BslMethodBuilder.Create().Name("Test").Build().ToSymbol()); + master.DefineVariable(BslFieldBuilder.Create().Name("TestField").Build().ToSymbol()); + + var compound = new CompoundSymbolTable(master); + + compound.ScopeCount.Should().Be(1); + + compound.GetScope(0).Should().BeSameAs(master.GetScope(0)); + compound.TryFindMethod("Test", out _).Should().BeTrue(); + compound.TryFindMethodBinding("Test", out var methBind).Should().BeTrue(); + methBind.ScopeNumber.Should().Be(0); + + compound.FindVariable("TestField", out var varBind).Should().BeTrue(); + varBind.ScopeNumber.Should().Be(0); + + compound.GetMethod(methBind).Name.Should().Be("Test"); + compound.GetVariable(methBind).Name.Should().Be("TestField"); + + } + + [Fact] + public void Master_With_Inner() + { + var master = new SymbolTable(); + master.PushScope(new SymbolScope(), null); + + master.DefineMethod(BslMethodBuilder.Create().Name("Test").Build().ToSymbol()); + master.DefineVariable(BslFieldBuilder.Create().Name("TestField").Build().ToSymbol()); + + var compound = new CompoundSymbolTable(master); + compound.PushScope(new SymbolScope(), null); + + compound.ScopeCount.Should().Be(2); + + compound.GetScope(0).Should().BeSameAs(master.GetScope(0)); + compound.TryFindMethod("Test", out _).Should().BeTrue(); + compound.TryFindMethodBinding("Test", out var methBind).Should().BeTrue(); + methBind.ScopeNumber.Should().Be(0); + + compound.FindVariable("TestField", out var varBind).Should().BeTrue(); + varBind.ScopeNumber.Should().Be(0); + + compound.GetMethod(methBind).Name.Should().Be("Test"); + compound.GetVariable(methBind).Name.Should().Be("TestField"); + + compound.DefineMethod(BslMethodBuilder.Create().Name("InnerTest").Build().ToSymbol()); + compound.DefineVariable(BslFieldBuilder.Create().Name("InnerTestField").Build().ToSymbol()); + + // + compound.TryFindMethod("InnerTest", out _).Should().BeTrue(); + compound.TryFindMethodBinding("InnerTest", out methBind).Should().BeTrue(); + methBind.ScopeNumber.Should().Be(1); + + compound.FindVariable("InnerTestField", out varBind).Should().BeTrue(); + varBind.ScopeNumber.Should().Be(1); + + compound.GetMethod(methBind).Name.Should().Be("InnerTest"); + compound.GetVariable(methBind).Name.Should().Be("InnerTestField"); + + + } +} \ No newline at end of file