From 081d318018c84e1f12ef7e9835f9a75aa473d7ce Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 1 Jan 2025 22:40:55 +0200 Subject: [PATCH 001/235] Remove code specific to guessing game --- ZSharpTest/Main.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index 13b28b2a..6e819292 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -176,8 +176,6 @@ var mainMethod = mainModuleGlobals.GetMethod("main", []); - Decompile(mainModuleGlobals.GetMethod("guessOnce")!); - if (mainMethod is not null) Decompile(mainMethod); From 373cd2b020cc7015bd45c22c8b2510f395195a28 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 14:53:44 +0200 Subject: [PATCH 002/235] Remove older overloading support --- .../cg objects/overloading/IOverload.cs | 16 ------- .../SimpleFunctionOverloadGroup.cs | 48 ------------------- 2 files changed, 64 deletions(-) delete mode 100644 ZSharp.Compiler/cg objects/overloading/IOverload.cs delete mode 100644 ZSharp.Compiler/cg objects/overloading/SimpleFunctionOverloadGroup.cs diff --git a/ZSharp.Compiler/cg objects/overloading/IOverload.cs b/ZSharp.Compiler/cg objects/overloading/IOverload.cs deleted file mode 100644 index 823c551d..00000000 --- a/ZSharp.Compiler/cg objects/overloading/IOverload.cs +++ /dev/null @@ -1,16 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public interface IOverload - { - /// - /// Match the given arguments to this overload. - /// If the arguments don't match, return null. - /// - /// The arguments to match. - /// A describing how to pass the arguments - /// to the overload if the arguments match the overload, otherwise - //public OverloadMatchResult? Match(Compiler.Compiler compiler, Argument[] arguments); - } -} diff --git a/ZSharp.Compiler/cg objects/overloading/SimpleFunctionOverloadGroup.cs b/ZSharp.Compiler/cg objects/overloading/SimpleFunctionOverloadGroup.cs deleted file mode 100644 index 5567a4c5..00000000 --- a/ZSharp.Compiler/cg objects/overloading/SimpleFunctionOverloadGroup.cs +++ /dev/null @@ -1,48 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class SimpleFunctionOverloadGroup(string name) - : CompilerObject - , ICTCallable - { - public string Name { get; set; } = name; - - public List Overloads { get; } = []; - - public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) - { - var (args, kwargs) = Utils.SplitArguments(arguments); - - CompilerObject? Match(RTFunction overload) - { - if (args.Count != overload.Signature.Args.Count) return null; - if (kwargs.Count != overload.Signature.KwArgs.Count) return null; - - foreach (var (arg, param) in args.Zip(overload.Signature.Args)) - { - var code = compiler.CompileIRCode(arg); - - if (compiler.CompileIRType(code.RequireValueType()) != compiler.CompileIRType(param.Type)) return null; - } - - foreach (var param in overload.Signature.KwArgs) - { - if (!kwargs.TryGetValue(param.Name, out var arg)) return null; - - var code = compiler.CompileIRCode(arg); - - if (compiler.CompileIRType(code.RequireValueType()) != compiler.CompileIRType(param.Type)) return null; - } - - return (overload as ICTCallable).Call(compiler, arguments); // TODO: overloading protocol????? - } - - var matchingOverloads = Overloads.Select(Match).Where(c => c is not null).ToList()!; - - if (matchingOverloads.Count != 1) throw new(); - - return matchingOverloads[0]!; - } - } -} From eeadaff18d2606a0629b3221fd42497619a6bcb2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 14:54:12 +0200 Subject: [PATCH 003/235] Add base compiler exception --- ZSharp.Compiler/exceptions/CompilerObjectException.cs | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 ZSharp.Compiler/exceptions/CompilerObjectException.cs diff --git a/ZSharp.Compiler/exceptions/CompilerObjectException.cs b/ZSharp.Compiler/exceptions/CompilerObjectException.cs new file mode 100644 index 00000000..6890ec67 --- /dev/null +++ b/ZSharp.Compiler/exceptions/CompilerObjectException.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public abstract class CompilerObjectException(CompilerObject @object, string? message = null) + : Exception(message) + { + public CompilerObject Object { get; } = @object; + } +} From 9e70c7695135b06852438e128b811563cb3c12d4 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 14:54:30 +0200 Subject: [PATCH 004/235] Add compiler cast exception --- .../compiler/features/Compiler.Protocols.cs | 2 +- ZSharp.Compiler/exceptions/InvalidCastException.cs | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 ZSharp.Compiler/exceptions/InvalidCastException.cs diff --git a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs index 084c29aa..2321e6c3 100644 --- a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs +++ b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs @@ -38,7 +38,7 @@ public CompilerObject Cast(CompilerObject target, CompilerObject type) if (target is ICTTypeCast typeCast) return typeCast.Cast(this, type); - throw new NotImplementedException(); + throw new InvalidCastException(target, type); } /// diff --git a/ZSharp.Compiler/exceptions/InvalidCastException.cs b/ZSharp.Compiler/exceptions/InvalidCastException.cs new file mode 100644 index 00000000..ded5950a --- /dev/null +++ b/ZSharp.Compiler/exceptions/InvalidCastException.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler +{ + public sealed class InvalidCastException(CompilerObject @object, CompilerObject type) + : CompilerObjectException(@object) + { + public CompilerObject Target => Object; + + public CompilerObject Type { get; } = type; + } +} From 7c3ac899ec728e06fc0f643b8c620e32e3e2cc97 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 14:55:06 +0200 Subject: [PATCH 005/235] Simplify Compiler.TypeSystem.Int32 construction --- ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs index 0c8ff6a6..af8c01a3 100644 --- a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs +++ b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs @@ -29,7 +29,7 @@ internal TypeSystem(Compiler compiler) Void = new RawType(compiler.RuntimeModule.TypeSystem.Void, Type); Null = new RawType(compiler.RuntimeModule.TypeSystem.Null, Type); Boolean = new RawType(compiler.RuntimeModule.TypeSystem.Boolean, Type); - Int32 = new Int32Type(compiler.RuntimeModule.TypeSystem.Int32, Type); + Int32 = new(compiler.RuntimeModule.TypeSystem.Int32, Type); Float32 = new RawType(compiler.RuntimeModule.TypeSystem.Float32, Type); } From c52b6affc009ffb00eab5bcb61c01f10dffd0928 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 14:57:19 +0200 Subject: [PATCH 006/235] Add dynamically computed types support for CO --- ZSharp.Compiler/cg objects/raw/RawCode.cs | 2 +- .../core/type system/IDynamicallyTyped.cs | 7 +++++++ .../compiler core/core/type system/ITyped.cs | 4 ++-- .../core/type system/TypeSystem.cs | 17 ++++++++--------- .../runtime code/objects/WhileLoop.cs | 2 +- 5 files changed, 19 insertions(+), 13 deletions(-) create mode 100644 ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs diff --git a/ZSharp.Compiler/cg objects/raw/RawCode.cs b/ZSharp.Compiler/cg objects/raw/RawCode.cs index 301120cd..f021954b 100644 --- a/ZSharp.Compiler/cg objects/raw/RawCode.cs +++ b/ZSharp.Compiler/cg objects/raw/RawCode.cs @@ -15,7 +15,7 @@ public sealed class RawCode(IRCode code) public IRCode Read(Compiler.Compiler _) => code; - CompilerObject ITyped.GetType(Compiler.Compiler compiler) + CompilerObject IDynamicallyTyped.GetType(Compiler.Compiler compiler) => code.IsVoid ? compiler.TypeSystem.Void : code.RequireValueType(); } } diff --git a/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs b/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs new file mode 100644 index 00000000..baa12d84 --- /dev/null +++ b/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IDynamicallyTyped + { + public CompilerObject GetType(Compiler compiler); + } +} diff --git a/ZSharp.Compiler/compiler core/core/type system/ITyped.cs b/ZSharp.Compiler/compiler core/core/type system/ITyped.cs index 6a2029ed..4d5c18e7 100644 --- a/ZSharp.Compiler/compiler core/core/type system/ITyped.cs +++ b/ZSharp.Compiler/compiler core/core/type system/ITyped.cs @@ -1,10 +1,10 @@ namespace ZSharp.Compiler { - public interface ITyped + public interface ITyped : IDynamicallyTyped { public CompilerObject Type { get; } - public CompilerObject GetType(Compiler compiler) + CompilerObject IDynamicallyTyped.GetType(Compiler compiler) => Type; } } diff --git a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs index af8c01a3..c6fc09d6 100644 --- a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs +++ b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs @@ -46,26 +46,25 @@ public CompilerObject Reference(CompilerObject type) => throw new NotImplementedException(); public bool IsTyped(CompilerObject @object) - { - throw new NotImplementedException(); - } + => @object is IDynamicallyTyped; public bool IsTyped(CompilerObject @object, [NotNullWhen(true)] out CompilerObject? type) { - if (@object is ITyped typed) + if (@object is IDynamicallyTyped typed) return (type = typed.GetType(Compiler)) is not null; return (type = null) is not null; } public bool IsTypeModifier(CompilerObject @object) - { - throw new NotImplementedException(); - } + => @object is ITypeModifier; - public bool IsTypeModifier(CompilerObject @object, [NotNullWhen(true)] out CompilerObject? type) + public bool IsTypeModifier(CompilerObject @object, [NotNullWhen(true)] out CompilerObject? innerType) { - throw new NotImplementedException(); + if (@object is ITypeModifier modifier) + return (innerType = modifier.InnerType) is not null; + + return (innerType = null) is not null; } } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs index 5e5a791d..1f595b35 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs @@ -47,7 +47,7 @@ .. compiler.CompileIRCode( ); } - CompilerObject ITyped.GetType(Compiler.Compiler compiler) + CompilerObject IDynamicallyTyped.GetType(Compiler.Compiler compiler) { if (compiler.TypeSystem.IsTyped(While, out var type)) return type; From 5695b5d549f91e2a5888bda5f1672f5f68347ce0 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 14:57:48 +0200 Subject: [PATCH 007/235] Add on-demand IR compilation for Local --- ZSharp.Compiler/cg objects/functional/body/Local.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ZSharp.Compiler/cg objects/functional/body/Local.cs b/ZSharp.Compiler/cg objects/functional/body/Local.cs index b7c40ad2..807116fc 100644 --- a/ZSharp.Compiler/cg objects/functional/body/Local.cs +++ b/ZSharp.Compiler/cg objects/functional/body/Local.cs @@ -77,12 +77,14 @@ public CompilerObject Assign(Compiler.Compiler compiler, CompilerObject value) if (Type is null) throw new(); + IR ??= CompileIRObject(compiler, null); + var code = compiler.CompileIRCode(compiler.Cast(value, Type)); code.Instructions.AddRange( [ new IR.VM.Dup(), - new IR.VM.SetLocal(IR!) + new IR.VM.SetLocal(IR) ] ); From 483275cdc38178c5e318e9e04922f306eea937d0 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 14:58:06 +0200 Subject: [PATCH 008/235] Remove support for `null` in function name --- ZSharp.Compiler/cg objects/functional/Function.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.Compiler/cg objects/functional/Function.cs b/ZSharp.Compiler/cg objects/functional/Function.cs index ff3de551..93948ca6 100644 --- a/ZSharp.Compiler/cg objects/functional/Function.cs +++ b/ZSharp.Compiler/cg objects/functional/Function.cs @@ -17,7 +17,7 @@ public abstract class Function(string? name) { public IR.Function? IR { get; set; } - public string? Name { get; set; } = name; + public string Name { get; set; } = name ?? string.Empty; public CompilerObject? Body { get; set; } From b90635eca76560776308a7ba6642df30247f4b1f Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 14:58:21 +0200 Subject: [PATCH 009/235] Add PartiallyCompiledObjectException --- .../exceptions/PartiallyCompiledObjectException.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 ZSharp.Compiler/exceptions/PartiallyCompiledObjectException.cs diff --git a/ZSharp.Compiler/exceptions/PartiallyCompiledObjectException.cs b/ZSharp.Compiler/exceptions/PartiallyCompiledObjectException.cs new file mode 100644 index 00000000..6009ba80 --- /dev/null +++ b/ZSharp.Compiler/exceptions/PartiallyCompiledObjectException.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Compiler +{ + public sealed class PartiallyCompiledObjectException( + CompilerObject @object, + string? message = null + ) + : CompilerObjectException(@object, message) + { + + } +} From 6c6af86e499a6233d7f466baa1a7d2bada3f5081 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 14:59:09 +0200 Subject: [PATCH 010/235] Add ZSharp.Compiler.Objects project --- ZSharp v1.sln | 6 ++++++ .../ZSharp.Compiler.Objects.csproj | 14 ++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj diff --git a/ZSharp v1.sln b/ZSharp v1.sln index a58e1513..5f8cb766 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -42,6 +42,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Runtime.IL", "ZSharp EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.StandardLibrary.Math", "ZSharp.CT.StandardLibrary.Math\ZSharp.CT.StandardLibrary.Math.csproj", "{AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Objects", "ZSharp.Compiler.Objects\ZSharp.Compiler.Objects.csproj", "{6B3BEDB2-F3CB-400E-A257-D79F73075AF9}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -120,6 +122,10 @@ Global {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Debug|Any CPU.Build.0 = Debug|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Release|Any CPU.ActiveCfg = Release|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Release|Any CPU.Build.0 = Release|Any CPU + {6B3BEDB2-F3CB-400E-A257-D79F73075AF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6B3BEDB2-F3CB-400E-A257-D79F73075AF9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6B3BEDB2-F3CB-400E-A257-D79F73075AF9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6B3BEDB2-F3CB-400E-A257-D79F73075AF9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj b/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj new file mode 100644 index 00000000..e4416735 --- /dev/null +++ b/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj @@ -0,0 +1,14 @@ + + + + net8.0 + enable + enable + ZSharp.Objects + + + + + + + From ad1de1689e4373e1703778c0dcbca7654e72b331 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 14:59:30 +0200 Subject: [PATCH 011/235] Add ArgumentMismatchException --- .../callables/ArgumentMismatchException.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs diff --git a/ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs b/ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs new file mode 100644 index 00000000..c5c017b1 --- /dev/null +++ b/ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs @@ -0,0 +1,12 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public class ArgumentMismatchException(CompilerObject callable, Argument[] arguments) + : CompilerObjectException(callable) + { + public CompilerObject Callable => Object; + + public Argument[] Arguments { get; } = arguments; + } +} From 60b6d74a3b970c0e14c2f16da5e0cad2393fd7bd Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 14:59:50 +0200 Subject: [PATCH 012/235] Add error messages class --- .../error messages/Errors.Compilation.cs | 8 ++++++++ ZSharp.Compiler.Objects/error messages/Errors.cs | 7 +++++++ 2 files changed, 15 insertions(+) create mode 100644 ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs create mode 100644 ZSharp.Compiler.Objects/error messages/Errors.cs diff --git a/ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs b/ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs new file mode 100644 index 00000000..f27e9de8 --- /dev/null +++ b/ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Objects +{ + internal static partial class Errors + { + public static string UndefinedReturnType(string name) + => $"Return type of function {(name == string.Empty ? "" : name)} is not defined."; + } +} diff --git a/ZSharp.Compiler.Objects/error messages/Errors.cs b/ZSharp.Compiler.Objects/error messages/Errors.cs new file mode 100644 index 00000000..1bd0f453 --- /dev/null +++ b/ZSharp.Compiler.Objects/error messages/Errors.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Objects +{ + internal static partial class Errors + { + + } +} From b1d3381cf5d9a698110c11d7f747c182b4c96cdf Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 15:00:18 +0200 Subject: [PATCH 013/235] Add simple overloading group object & support --- .../overloading/OverloadGroup.cs | 33 +++++++++++++++++++ .../exceptions/AmbiguousOverloadException.cs | 14 ++++++++ .../exceptions/NoOverloadFoundException.cs | 9 +++++ .../exceptions/OverloadException.cs | 10 ++++++ 4 files changed, 66 insertions(+) create mode 100644 ZSharp.Compiler.Objects/overloading/OverloadGroup.cs create mode 100644 ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs create mode 100644 ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs create mode 100644 ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs diff --git a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs new file mode 100644 index 00000000..1ed88ee1 --- /dev/null +++ b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs @@ -0,0 +1,33 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class OverloadGroup(string name) + : CompilerObject + , ICTCallable + { + public string Name { get; set; } = name; + + public Collection Overloads { get; } = []; + + public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) + { + var matchingOverloads = Overloads + .Select(overload => { + try { return compiler.Call(overload, arguments); } + catch (ArgumentMismatchException) { return null!; } + }) + .Where(result => result is not null) + .ToArray(); + + if (matchingOverloads.Length == 0) + throw new NoOverloadFoundException(this, arguments); + + if (matchingOverloads.Length > 1) + throw new AmbiguousOverloadException(this, arguments, matchingOverloads); + + return matchingOverloads[0]; + } + } +} diff --git a/ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs b/ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs new file mode 100644 index 00000000..7694db69 --- /dev/null +++ b/ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs @@ -0,0 +1,14 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class AmbiguousOverloadException( + OverloadGroup group, + Argument[] arguments, + CompilerObject[] overloads + ) + : OverloadException(group, arguments) + { + public CompilerObject[] Overloads { get; } = overloads; + } +} diff --git a/ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs b/ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs new file mode 100644 index 00000000..e86bd36d --- /dev/null +++ b/ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs @@ -0,0 +1,9 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class NoOverloadFoundException(OverloadGroup group, Argument[] arguments) + : OverloadException(group, arguments) + { + } +} diff --git a/ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs b/ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs new file mode 100644 index 00000000..6f9c35ab --- /dev/null +++ b/ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs @@ -0,0 +1,10 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public abstract class OverloadException(OverloadGroup group, Argument[] arguments) + : ArgumentMismatchException(group, arguments) + { + public OverloadGroup Group { get; } = group; + } +} From 29669986c242991d4e6ebcdc7606ae0d929c903b Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 15:01:44 +0200 Subject: [PATCH 014/235] Add object build state helper class --- ZSharp.Compiler.Objects/utils/ObjectBuildState.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 ZSharp.Compiler.Objects/utils/ObjectBuildState.cs diff --git a/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs b/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs new file mode 100644 index 00000000..7f3411d8 --- /dev/null +++ b/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Objects +{ + internal sealed class ObjectBuildState + where T : struct, Enum, IConvertible + { + public T State { get; private set; } + + public bool Get(T state) => State.HasFlag(state); + + public void Set(T state) + { + State = (T)(ValueType)(State.ToInt32(null) | state.ToInt32(null)); + } + } +} From ba8d4d7ee5d7a3258e7a259f1ee0e7567507a572 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 15:02:14 +0200 Subject: [PATCH 015/235] Move RTFunction from ZSharp.Compiler to ZSharp.Compiler.Objects --- .../ZSharp.Compiler.IRLoader.csproj | 1 + .../functional}/RTFunction.cs | 90 ++++++++----------- ZSharp.Compiler/cg objects/modular/Module.cs | 2 +- .../ZSharp.ZSSourceCompiler.csproj | 1 + 4 files changed, 38 insertions(+), 56 deletions(-) rename {ZSharp.Compiler/cg objects/functional/rt => ZSharp.Compiler.Objects/functional}/RTFunction.cs (64%) diff --git a/ZSharp.Compiler.IRLoader/ZSharp.Compiler.IRLoader.csproj b/ZSharp.Compiler.IRLoader/ZSharp.Compiler.IRLoader.csproj index 7e575a54..28901a0d 100644 --- a/ZSharp.Compiler.IRLoader/ZSharp.Compiler.IRLoader.csproj +++ b/ZSharp.Compiler.IRLoader/ZSharp.Compiler.IRLoader.csproj @@ -7,6 +7,7 @@ + diff --git a/ZSharp.Compiler/cg objects/functional/rt/RTFunction.cs b/ZSharp.Compiler.Objects/functional/RTFunction.cs similarity index 64% rename from ZSharp.Compiler/cg objects/functional/rt/RTFunction.cs rename to ZSharp.Compiler.Objects/functional/RTFunction.cs index 60537a27..a24127c5 100644 --- a/ZSharp.Compiler/cg objects/functional/rt/RTFunction.cs +++ b/ZSharp.Compiler.Objects/functional/RTFunction.cs @@ -1,5 +1,6 @@ -using ZSharp.Compiler; -using ZSharp.IR; +using CommonZ.Utils; +using System.Diagnostics.CodeAnalysis; +using ZSharp.Compiler; namespace ZSharp.Objects { @@ -17,7 +18,7 @@ enum BuildState Owner = 0b100, } - private BuildState _state = BuildState.None; + private readonly ObjectBuildState state = new(); CompilerObject ITyped.Type => throw new NotImplementedException(); @@ -25,50 +26,23 @@ enum BuildState public CompilerObject? ReturnType { get; set; } - public bool IsSignatureBuilt - { - get => _state.HasFlag(BuildState.Signature); - set => _state = value ? _state | BuildState.Signature : _state & ~BuildState.Signature; - } - - public bool IsBodyBuilt - { - get => _state.HasFlag(BuildState.Body); - set => _state = value ? _state | BuildState.Body : _state & ~BuildState.Body; - } - - public bool IsOwnerBuilt - { - get => _state.HasFlag(BuildState.Owner); - set => _state = value ? _state | BuildState.Owner : _state & ~BuildState.Owner; - } - - public CompilerObject Call(IRCode[] arguments) - { - if (IR is null) - throw new("Function not compiled."); - - IRCode code = new(); - - foreach (var argument in arguments) - code.Append(argument); - - code.Instructions.Add(new IR.VM.Call(IR)); - - throw new NotImplementedException(); - //return new Code(code); - } - public override CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) { var (args, kwargs) = Utils.SplitArguments(arguments); - return Call(compiler, args, kwargs); + try + { + return Call(compiler, args, kwargs); + } + catch (Compiler.InvalidCastException) + { + throw new ArgumentMismatchException(this, arguments); + } } - public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) + private RawCode Call(Compiler.Compiler compiler, Collection args, Mapping kwArgs) { - // TODO: type checking (when type system is implemented) + IR ??= CompileIRObject(compiler, null); IRCode argsCode = new(), varArgsCode = new(), @@ -83,7 +57,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) throw new($"Function {Name} takes {Signature.Args.Count} arguments, but {args.Count} were given."); for (int i = 0; i < Signature.Args.Count; i++) - argsCode.Append(compiler.CompileIRCode(args[i])); + argsCode.Append(compiler.CompileIRCode(compiler.Cast(args[i], Signature.Args[i].Type ?? throw new()))); if (kwArgs.Count > Signature.KwArgs.Count) if (Signature.VarKwArgs is null) @@ -94,7 +68,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) throw new($"Function {Name} takes {Signature.KwArgs.Count} keyword arguments, but {kwArgs.Count} were given."); foreach (var kwArgParameter in Signature.KwArgs) - kwArgsCode.Append(compiler.CompileIRCode(kwArgs[kwArgParameter.Name])); + kwArgsCode.Append(compiler.CompileIRCode(compiler.Cast(kwArgs[kwArgParameter.Name], kwArgParameter.Type ?? throw new()))); IRCode result = new(); result.Append(argsCode); @@ -102,16 +76,15 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) result.Append(kwArgsCode); result.Append(varKwArgsCode); // should be empty - result.Instructions.Add(new IR.VM.Call(IR!)); + result.Instructions.Add(new IR.VM.Call(IR)); result.Types.Clear(); if (ReturnType != compiler.TypeSystem.Void) - result.Types.Add(ReturnType ?? throw new()); // TODO: WTF?????? This is here because the - // IR -> CG loader is not yet implemented. + result.Types.Add(ReturnType!); result.MaxStackSize = Math.Max(result.MaxStackSize, result.Types.Count); - return new RawCode(result); + return new(result); } IRCode ICTReadable.Read(Compiler.Compiler compiler) @@ -122,21 +95,30 @@ IRCode ICTReadable.Read(Compiler.Compiler compiler) Types = [null!], // TODO: fix type }; + [MemberNotNull(nameof(ReturnType))] public IR.Function CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) { - IR ??= new(compiler.CompileIRType(ReturnType ?? throw new())) + IR ??= + new( + compiler.CompileIRType( + ReturnType ?? throw new PartiallyCompiledObjectException( + this, + Errors.UndefinedReturnType(Name) + ) + ) + ) { Name = Name }; - if (owner is not null && !IsOwnerBuilt) + if (owner is not null && !state.Get(BuildState.Owner)) { owner.Functions.Add(IR); - IsOwnerBuilt = true; + state.Set(BuildState.Owner); } - if (!IsSignatureBuilt) + if (!state.Get(BuildState.Signature)) { foreach (var arg in Signature.Args) IR.Signature.Args.Parameters.Add(compiler.CompileIRObject(arg, IR.Signature)); @@ -150,18 +132,16 @@ public IR.Function CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) if (Signature.VarKwArgs is not null) IR.Signature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, IR.Signature); - IsSignatureBuilt = true; + state.Set(BuildState.Signature); } - if (Body is not null && !IsBodyBuilt) + if (Body is not null && !state.Get(BuildState.Body)) { IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); - IsBodyBuilt = true; + state.Set(BuildState.Body); } - // TODO: compile signature - return IR; } } diff --git a/ZSharp.Compiler/cg objects/modular/Module.cs b/ZSharp.Compiler/cg objects/modular/Module.cs index 30402b34..fd1a1723 100644 --- a/ZSharp.Compiler/cg objects/modular/Module.cs +++ b/ZSharp.Compiler/cg objects/modular/Module.cs @@ -19,7 +19,7 @@ public sealed class Module(string name) public IR.Module? IR { get; set; } - public RTFunction InitFunction { get; } = new(null); + //public RTFunction InitFunction { get; } = new(null); public string? Name { get; set; } = name; diff --git a/ZSharp.ZSSourceCompiler/ZSharp.ZSSourceCompiler.csproj b/ZSharp.ZSSourceCompiler/ZSharp.ZSSourceCompiler.csproj index 8a2bf752..79084374 100644 --- a/ZSharp.ZSSourceCompiler/ZSharp.ZSSourceCompiler.csproj +++ b/ZSharp.ZSSourceCompiler/ZSharp.ZSSourceCompiler.csproj @@ -8,6 +8,7 @@ + From 738338b1036cabbe28c2b67a647e9f15e72b86d4 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 15:02:34 +0200 Subject: [PATCH 016/235] Add support for loading overloads from IR to CO --- ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index 23276277..8290dfdb 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -67,8 +67,16 @@ private Action Load(IR.Function function, Module owner) owner.Content.Add(result); - if (result.Name is not null && result.Name != string.Empty) - owner.Members.Add(result.Name, result); // TODO: overloading + if (result.Name != string.Empty) + { + if (!owner.Members.TryGetValue(result.Name, out var group)) + owner.Members.Add(result.Name, group = new OverloadGroup(result.Name)); + + if (group is not OverloadGroup overloadGroup) + throw new InvalidOperationException(); + + overloadGroup.Overloads.Add(result); + } return () => { From 72675d31c5150f4bad2c46102c58c45d500a2800 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 15:03:10 +0200 Subject: [PATCH 017/235] Add automatic operator overload groups creation --- ZSharpTest/Main.cs | 45 ++++++++++++++++++++------------------------- 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index 6e819292..f10b082c 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -1,4 +1,5 @@ -using ZSharp.Compiler; +using System.Text.RegularExpressions; +using ZSharp.Compiler; using ZSharp.Interpreter; using ZSharp.Parser; using ZSharp.Text; @@ -122,32 +123,26 @@ interpreter.SourceCompiler.StandardLibraryImporter.Libraries.Add("math", moduleCO_standardMath); -interpreter.SourceCompiler.Operators.Cache( - "+", - interpreter.CompilerIRLoader.Import( - runtime.Import( - ZSharp.Runtime.NET.Utils.GetMethod(Standard.IO.Impl_Globals.Concat) - ) - ) -); +foreach (var moduleIR in new[] { moduleIR_standardIO, moduleIR_standardMath }) + if (moduleIR.HasFunctions) + foreach (var function in moduleIR.Functions) + { + if (function.Name is null || function.Name == string.Empty) + continue; -interpreter.SourceCompiler.Operators.Cache( - "<", - interpreter.CompilerIRLoader.Import( - runtime.Import( - ZSharp.Runtime.NET.Utils.GetMethod(Standard.Math.Impl_Globals.LessThan) - ) - ) -); + var match = Regex.Match(function.Name, @"^_?(?[+\-*=?&^%$#@!<>|~]+)_?$"); + if (match.Success) + { + var op = match.Groups["OP"].Value; + if (!interpreter.SourceCompiler.Operators.Cache(op, out var group)) + group = interpreter.SourceCompiler.Operators.Cache(op, new ZSharp.Objects.OverloadGroup(op)); -interpreter.SourceCompiler.Operators.Cache( - "-", - interpreter.CompilerIRLoader.Import( - runtime.Import( - ZSharp.Runtime.NET.Utils.GetMethod(Standard.Math.Impl_Globals.Subtract) - ) - ) -); + if (group is not ZSharp.Objects.OverloadGroup overloadGroup) + throw new Exception("Invalid overload group!"); + + overloadGroup.Overloads.Add(interpreter.CompilerIRLoader.Import(function)); + } + } //var moduleIL_compilerAPI = typeof(ZS.CompilerAPI.Impl_Globals).Module; //var moduleIR_compilerAPI = interpreter.HostLoader.Import(moduleIL_compilerAPI); From 526c692b89c9236d380990af72ec2f773e448225 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 15:03:50 +0200 Subject: [PATCH 018/235] Add + operator overload for i32 and i32 --- ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs b/ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs index 97159d3b..8799f95e 100644 --- a/ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs +++ b/ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs @@ -17,6 +17,10 @@ public static float Log2(int x) public static int Random(int min, int max) => new System.Random().Next(min, max); + [Alias(Name = "_+_")] + public static int Add(int a, int b) + => a + b; + [Alias(Name = "_<_")] public static bool LessThan(int a, int b) => a < b; From d175d4202f7b8740791e920f2eaf9b0abfa86af5 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 2 Jan 2025 15:04:03 +0200 Subject: [PATCH 019/235] Remove the increment function --- ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs | 4 ---- ZSharpTest/guessing-game.zs | 8 ++++---- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs b/ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs index 8799f95e..bbc04fab 100644 --- a/ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs +++ b/ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs @@ -28,9 +28,5 @@ public static bool LessThan(int a, int b) [Alias(Name = "_-_")] public static int Subtract(int a, int b) => a - b; - - [Alias(Name = "increment")] - public static int Increment(int x) - => x + 1; } } diff --git a/ZSharpTest/guessing-game.zs b/ZSharpTest/guessing-game.zs index fcce44e8..93c3f480 100644 --- a/ZSharpTest/guessing-game.zs +++ b/ZSharpTest/guessing-game.zs @@ -1,5 +1,5 @@ import { input, print } from "std:io"; -import { ceil, log2, random, increment } from "std:math"; +import { ceil, log2, random } from "std:math"; //import { random } from "std:random"; module Program; @@ -16,7 +16,7 @@ fun guessOnce(guess: i32, number: i32, tries: i32): bool { return false; } - print("You got it in " + string(increment(tries)) + " tries!"); + print("You got it in " + string(tries + 1) + " tries!"); return true; } @@ -35,9 +35,9 @@ fun main(): void { while (guessOnce(guess, number, tries)) { - tries = increment(maxTries); + tries = maxTries + 1; break; - } else tries = increment(tries); + } else tries = tries + 1; } while (maxTries < tries) { break; } From d23039f16e0c1c9b39919a16591ddcbb6bdc1cc8 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 9 Jan 2025 14:33:53 +0200 Subject: [PATCH 020/235] Move Parameter and Signature to sig/ --- ZSharp.AST/nodes/{abs => sig}/Parameter.cs | 0 ZSharp.AST/nodes/{abs => sig}/Signature.cs | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename ZSharp.AST/nodes/{abs => sig}/Parameter.cs (100%) rename ZSharp.AST/nodes/{abs => sig}/Signature.cs (100%) diff --git a/ZSharp.AST/nodes/abs/Parameter.cs b/ZSharp.AST/nodes/sig/Parameter.cs similarity index 100% rename from ZSharp.AST/nodes/abs/Parameter.cs rename to ZSharp.AST/nodes/sig/Parameter.cs diff --git a/ZSharp.AST/nodes/abs/Signature.cs b/ZSharp.AST/nodes/sig/Signature.cs similarity index 100% rename from ZSharp.AST/nodes/abs/Signature.cs rename to ZSharp.AST/nodes/sig/Signature.cs From 30fac0cd68bb8e1ee1c2ea3361b10a89e92222d7 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 9 Jan 2025 14:56:41 +0200 Subject: [PATCH 021/235] Add tokens to module node --- ZSharp.AST/nodes/def/module/Module.cs | 8 +++++++- ZSharp.AST/nodes/def/module/ModuleTokens.cs | 11 +++++++++++ ZSharp.Parser/parsers/ModuleParser.cs | 12 ++++++++---- 3 files changed, 26 insertions(+), 5 deletions(-) create mode 100644 ZSharp.AST/nodes/def/module/ModuleTokens.cs diff --git a/ZSharp.AST/nodes/def/module/Module.cs b/ZSharp.AST/nodes/def/module/Module.cs index 938a9f8e..0a2ca899 100644 --- a/ZSharp.AST/nodes/def/module/Module.cs +++ b/ZSharp.AST/nodes/def/module/Module.cs @@ -1,7 +1,13 @@ namespace ZSharp.AST { - public sealed class Module : Expression + public sealed class Module(ModuleTokens tokens) : Expression(tokens) { + public new ModuleTokens TokenInfo + { + get => As(); + init => base.TokenInfo = value; + } + public List Body { get; set; } = []; public required string Name { get; set; } diff --git a/ZSharp.AST/nodes/def/module/ModuleTokens.cs b/ZSharp.AST/nodes/def/module/ModuleTokens.cs new file mode 100644 index 00000000..a7e7e418 --- /dev/null +++ b/ZSharp.AST/nodes/def/module/ModuleTokens.cs @@ -0,0 +1,11 @@ +using ZSharp.Text; + +namespace ZSharp.AST +{ + public sealed class ModuleTokens : TokenInfo + { + public Token ModuleKeyword { get; init; } + + public Token Name { get; init; } + } +} diff --git a/ZSharp.Parser/parsers/ModuleParser.cs b/ZSharp.Parser/parsers/ModuleParser.cs index e609a0aa..77c20cf3 100644 --- a/ZSharp.Parser/parsers/ModuleParser.cs +++ b/ZSharp.Parser/parsers/ModuleParser.cs @@ -8,9 +8,9 @@ public sealed class ModuleParser { public override Module Parse(Parser parser) { - parser.Eat(LangParser.Keywords.Module); + var moduleKeyword = parser.Eat(LangParser.Keywords.Module); - var name = parser.Eat(TokenType.Identifier).Value; + var name = parser.Eat(TokenType.Identifier); List body; if (parser.Is(TokenType.LCurly, eat: true)) @@ -21,10 +21,14 @@ public override Module Parse(Parser parser) body = ParseModuleBody(parser, TokenType.EOF); } - return new() + return new(new() { - Body = body, + ModuleKeyword = moduleKeyword, Name = name, + }) + { + Body = body, + Name = name.Value, }; } From 71114b668b3b93832c896bc1a1f1e6abbe2258f0 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 9 Jan 2025 14:57:00 +0200 Subject: [PATCH 022/235] Add tokens to constructor node --- ZSharp.AST/nodes/def/oop/Constructor.cs | 8 +++++++- ZSharp.AST/nodes/def/oop/ConstructorTokens.cs | 11 +++++++++++ ZSharp.Parser/parsers/oop/ConstructorParser.cs | 14 +++++++++----- 3 files changed, 27 insertions(+), 6 deletions(-) create mode 100644 ZSharp.AST/nodes/def/oop/ConstructorTokens.cs diff --git a/ZSharp.AST/nodes/def/oop/Constructor.cs b/ZSharp.AST/nodes/def/oop/Constructor.cs index 9255c23f..1d6bb6d4 100644 --- a/ZSharp.AST/nodes/def/oop/Constructor.cs +++ b/ZSharp.AST/nodes/def/oop/Constructor.cs @@ -1,7 +1,13 @@ namespace ZSharp.AST { - public sealed class Constructor : Statement + public sealed class Constructor(ConstructorTokens tokens) : Statement(tokens) { + public new ConstructorTokens TokenInfo + { + get => As(); + init => base.TokenInfo = value; + } + public string? Name { get; set; } public required Signature Signature { get; set; } diff --git a/ZSharp.AST/nodes/def/oop/ConstructorTokens.cs b/ZSharp.AST/nodes/def/oop/ConstructorTokens.cs new file mode 100644 index 00000000..00b89159 --- /dev/null +++ b/ZSharp.AST/nodes/def/oop/ConstructorTokens.cs @@ -0,0 +1,11 @@ +using ZSharp.Text; + +namespace ZSharp.AST +{ + public sealed class ConstructorTokens : TokenInfo + { + public Token NewKeyword { get; init; } + + public Token? Name { get; init; } + } +} diff --git a/ZSharp.Parser/parsers/oop/ConstructorParser.cs b/ZSharp.Parser/parsers/oop/ConstructorParser.cs index 72c2c7b1..1d7c6821 100644 --- a/ZSharp.Parser/parsers/oop/ConstructorParser.cs +++ b/ZSharp.Parser/parsers/oop/ConstructorParser.cs @@ -20,11 +20,11 @@ public ConstructorParser() public override Constructor Parse(Parser parser) { - var funKeyword = parser.Eat(LangParser.Keywords.New); + var newKeyword = parser.Eat(LangParser.Keywords.New); - string? name = null; + Token? name = null; if (parser.Is(TokenType.Identifier)) - name = parser.Eat(TokenType.Identifier).Value; + name = parser.Eat(TokenType.Identifier); parser.Eat(TokenType.LParen); @@ -41,10 +41,14 @@ public override Constructor Parse(Parser parser) var body = ParseConstructorBody(parser); - return new() + return new(new() { - Body = body, Name = name, + NewKeyword = newKeyword, + }) + { + Body = body, + Name = name?.Value ?? string.Empty, Initializers = initializers, Signature = signature, }; From 35a78b89338a247fadbdfd80693ddc367b63c6db Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 9 Jan 2025 14:57:30 +0200 Subject: [PATCH 023/235] Add tokens to oop definition node --- ZSharp.AST/nodes/def/oop/OOPDefinition.cs | 8 +++++++- ZSharp.AST/nodes/def/oop/OOPDefinitionTokens.cs | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 ZSharp.AST/nodes/def/oop/OOPDefinitionTokens.cs diff --git a/ZSharp.AST/nodes/def/oop/OOPDefinition.cs b/ZSharp.AST/nodes/def/oop/OOPDefinition.cs index c3427e08..62803624 100644 --- a/ZSharp.AST/nodes/def/oop/OOPDefinition.cs +++ b/ZSharp.AST/nodes/def/oop/OOPDefinition.cs @@ -1,7 +1,13 @@ namespace ZSharp.AST { - public class OOPDefinition : Expression + public class OOPDefinition(OOPDefinitionTokens tokens) : Expression(tokens) { + public new OOPDefinitionTokens TokenInfo + { + get => As(); + init => base.TokenInfo = value; + } + public required string Type { get; set; } public string Name { get; set; } = string.Empty; diff --git a/ZSharp.AST/nodes/def/oop/OOPDefinitionTokens.cs b/ZSharp.AST/nodes/def/oop/OOPDefinitionTokens.cs new file mode 100644 index 00000000..c3bb5568 --- /dev/null +++ b/ZSharp.AST/nodes/def/oop/OOPDefinitionTokens.cs @@ -0,0 +1,15 @@ +using ZSharp.Text; + +namespace ZSharp.AST +{ + public sealed class OOPDefinitionTokens : TokenInfo + { + public Token Type { get; init; } + + public Token? Name { get; init; } + + public Token? OfKeyword { get; init; } + + public Token? BasesSeparator { get; init; } + } +} From 77a5698506059ae28bdcdf65e762fc4612035837 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 9 Jan 2025 14:57:43 +0200 Subject: [PATCH 024/235] Add tokens to class parser --- ZSharp.Parser/parsers/oop/ClassParser.cs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/ZSharp.Parser/parsers/oop/ClassParser.cs b/ZSharp.Parser/parsers/oop/ClassParser.cs index 7819d5b5..ca195aaf 100644 --- a/ZSharp.Parser/parsers/oop/ClassParser.cs +++ b/ZSharp.Parser/parsers/oop/ClassParser.cs @@ -28,11 +28,11 @@ public ClassParser() public override OOPDefinition Parse(Parser parser) { - var type = parser.Eat(LangParser.Keywords.Class).Value; + var type = parser.Eat(LangParser.Keywords.Class); - string? name = null; + Token? name = null; if (parser.Is(TokenType.Identifier)) - name = parser.Eat(TokenType.Identifier).Value; + name = parser.Eat(TokenType.Identifier); Signature? signature = null; if (parser.Is(TokenType.LParen, eat: true)) @@ -42,8 +42,12 @@ public override OOPDefinition Parse(Parser parser) parser.Eat(TokenType.RParen); } + Expression? of = null; + if (parser.Is(LangParser.Keywords.Of, out var ofKeyword, eat: true)) + of = parser.Parse(); + List? bases = null; - if (parser.Is(TokenType.Colon, eat: true)) + if (parser.Is(TokenType.Colon, out var basesSeparator, eat: true)) { bases = []; @@ -59,13 +63,20 @@ public override OOPDefinition Parse(Parser parser) else parser.Eat(TokenType.Semicolon); - return new() + return new(new() { + BasesSeparator = basesSeparator, + Name = name, + OfKeyword = ofKeyword, Type = type, + }) + { + Type = type.Value, Signature = signature, + Of = of, Bases = bases, Content = body, - Name = name, + Name = name?.Value ?? string.Empty, }; } From 2a95ecac91c209e211b781439e67c1a830f3d40a Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 9 Jan 2025 14:58:01 +0200 Subject: [PATCH 025/235] Move if statement node to flow/ --- ZSharp.AST/nodes/stmt/{ => flow}/IfStatement.cs | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename ZSharp.AST/nodes/stmt/{ => flow}/IfStatement.cs (100%) diff --git a/ZSharp.AST/nodes/stmt/IfStatement.cs b/ZSharp.AST/nodes/stmt/flow/IfStatement.cs similarity index 100% rename from ZSharp.AST/nodes/stmt/IfStatement.cs rename to ZSharp.AST/nodes/stmt/flow/IfStatement.cs From 9168d6dab00208b68c02061b00e0be6b30d14b36 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 9 Jan 2025 14:58:19 +0200 Subject: [PATCH 026/235] Add tokens to parameter node --- ZSharp.AST/nodes/sig/Parameter.cs | 8 +++++++- ZSharp.AST/nodes/sig/ParameterTokens.cs | 15 ++++++++++++++ .../lang/abs/LangParser.Signature.cs | 20 ++++++++++++------- 3 files changed, 35 insertions(+), 8 deletions(-) create mode 100644 ZSharp.AST/nodes/sig/ParameterTokens.cs diff --git a/ZSharp.AST/nodes/sig/Parameter.cs b/ZSharp.AST/nodes/sig/Parameter.cs index 8ecf1571..22a6f1a6 100644 --- a/ZSharp.AST/nodes/sig/Parameter.cs +++ b/ZSharp.AST/nodes/sig/Parameter.cs @@ -1,7 +1,13 @@ namespace ZSharp.AST { - public sealed class Parameter : Node + public sealed class Parameter(ParameterTokens tokens) : Node(tokens) { + public new ParameterTokens TokenInfo + { + get => As(); + init => base.TokenInfo = value; + } + public string? Alias { get; set; } public required string Name { get; set; } diff --git a/ZSharp.AST/nodes/sig/ParameterTokens.cs b/ZSharp.AST/nodes/sig/ParameterTokens.cs new file mode 100644 index 00000000..3dfcc1df --- /dev/null +++ b/ZSharp.AST/nodes/sig/ParameterTokens.cs @@ -0,0 +1,15 @@ +using ZSharp.Text; + +namespace ZSharp.AST +{ + public sealed class ParameterTokens : TokenInfo + { + public Token Name { get; init; } + + public Token? AsKeyword { get; init; } + + public Token? TypeSeparator { get; init; } + + public Token? ValueSeparator { get; init; } + } +} diff --git a/ZSharp.Parser/lang/abs/LangParser.Signature.cs b/ZSharp.Parser/lang/abs/LangParser.Signature.cs index 55e76b92..78155c1c 100644 --- a/ZSharp.Parser/lang/abs/LangParser.Signature.cs +++ b/ZSharp.Parser/lang/abs/LangParser.Signature.cs @@ -63,24 +63,30 @@ public static Signature ParseSignature(Parser parser) public static Parameter ParseParameter(Parser parser) { - var name = parser.Eat(TokenType.Identifier).Value; + var name = parser.Eat(TokenType.Identifier); - string? alias = null; + Token? alias = null; if (parser.Is(Keywords.As, eat: true)) - alias = parser.Eat(TokenType.Identifier).Value; + alias = parser.Eat(TokenType.Identifier); Expression? type = null; - if (parser.Is(TokenType.Colon, eat: true)) + if (parser.Is(TokenType.Colon, out var typeSeparator, eat: true)) type = ParseType(parser); Expression? initializer = null; - if (parser.Is(Symbols.Assign, eat: true)) + if (parser.Is(Symbols.Assign, out var valueSeparator, eat: true)) initializer = parser.Parse(); - return new() + return new(new() { - Alias = alias, + AsKeyword = alias, Name = name, + TypeSeparator = typeSeparator, + ValueSeparator = valueSeparator, + }) + { + Alias = alias?.Value, + Name = name.Value, Type = type, Initializer = initializer, }; From a18740871d6a6966569bd80eaab8fe02245b06e0 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 9 Jan 2025 14:58:35 +0200 Subject: [PATCH 027/235] Remove unused class --- .../compiler core/core/ObjectCache.cs | 67 ------------------- 1 file changed, 67 deletions(-) delete mode 100644 ZSharp.Compiler/compiler core/core/ObjectCache.cs diff --git a/ZSharp.Compiler/compiler core/core/ObjectCache.cs b/ZSharp.Compiler/compiler core/core/ObjectCache.cs deleted file mode 100644 index d14bb329..00000000 --- a/ZSharp.Compiler/compiler core/core/ObjectCache.cs +++ /dev/null @@ -1,67 +0,0 @@ -using CommonZ.Utils; -using System.Diagnostics.CodeAnalysis; - -namespace ZSharp.Compiler -{ - internal sealed class ObjectCache() - { - private readonly Cache cgCache = []; - private readonly Cache irCache = []; - - public ObjectCache(ObjectCache parent) - : this() - { - cgCache = new() - { - Parent = parent.cgCache, - }; - irCache = new() - { - Parent = parent.irCache, - }; - } - - public CompilerObject? CG(IR.IRObject ir) - => cgCache.Cache(ir); - - public bool CG(IR.IRObject ir, [NotNullWhen(true)] out CompilerObject? cg) - => cgCache.Cache(ir, out cg); - - public bool CG(IR.IRObject ir, [NotNullWhen(true)] out T? cg) - where T : CompilerObject - => cgCache.Cache(ir, out cg); - - - public CompilerObject CG(IR.IRObject ir, CompilerObject cg) - => CG(ir, cg); - - public T CG(IR.IRObject ir, T cg) - where T : CompilerObject - { - cgCache.Cache(ir, cg); - irCache.Cache(cg, ir); - return cg; - } - - public IR.IRObject? IR(CompilerObject cg) - => irCache.Cache(cg); - - public bool IR(CompilerObject cg, [NotNullWhen(true)] out IR.IRObject? ir) - => irCache.Cache(cg, out ir); - - public bool IR(CompilerObject cg, [NotNullWhen(true)] out T? ir) - where T : IR.IRObject - => irCache.Cache(cg, out ir); - - public IR.IRObject IR(CompilerObject cg, IR.IRObject ir) - => IR(cg, ir); - - public T IR(CompilerObject cg, T ir) - where T : IR.IRObject - { - irCache.Cache(cg, ir); - cgCache.Cache(ir, cg); - return ir; - } - } -} From 2a7e767b3d817db4e744828655a4fdeab8ba5d72 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 11 Jan 2025 18:52:27 +0200 Subject: [PATCH 028/235] Remove unused class --- ZSharp.Compiler/cg objects/modular/ModuleMember.cs | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 ZSharp.Compiler/cg objects/modular/ModuleMember.cs diff --git a/ZSharp.Compiler/cg objects/modular/ModuleMember.cs b/ZSharp.Compiler/cg objects/modular/ModuleMember.cs deleted file mode 100644 index 39d41f32..00000000 --- a/ZSharp.Compiler/cg objects/modular/ModuleMember.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public abstract class ModuleMember - : CompilerObject - //, IImportable - { - public required Module Module { get; init; } - } -} From 8308b3d40d92f66a5906d9e894411cb973d3aa0a Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 11 Jan 2025 18:53:21 +0200 Subject: [PATCH 029/235] Remove unused usings --- .../core-compilers/expression/ExpressionCompiler.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index 67de29dd..0cd206e0 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -1,7 +1,4 @@ -using System.Numerics; -using System.Security.AccessControl; - -namespace ZSharp.ZSSourceCompiler +namespace ZSharp.ZSSourceCompiler { public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) : CompilerBase(compiler) From c02759175f848e28cd16022caa119d3a31ac0a92 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 11 Jan 2025 19:54:20 +0200 Subject: [PATCH 030/235] Make while node generic --- ZSharp.AST/nodes/expr/flow/WhileExpression.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ZSharp.AST/nodes/expr/flow/WhileExpression.cs b/ZSharp.AST/nodes/expr/flow/WhileExpression.cs index fed026a1..04dfc0b6 100644 --- a/ZSharp.AST/nodes/expr/flow/WhileExpression.cs +++ b/ZSharp.AST/nodes/expr/flow/WhileExpression.cs @@ -1,6 +1,7 @@ namespace ZSharp.AST { - public sealed class WhileExpression : Expression + public sealed class WhileExpression : Expression + where TElse : Node { public required Expression Condition { get; set; } @@ -8,6 +9,6 @@ public sealed class WhileExpression : Expression public required Statement Body { get; set; } - public Statement? Else { get; set; } + public TElse? Else { get; set; } } } From d7e78876f7a734e418ee5027528721ad354e06df Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 11 Jan 2025 19:54:41 +0200 Subject: [PATCH 031/235] Make while node parser generic --- ZSharp.Parser/lang/expr/LangParser.While.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ZSharp.Parser/lang/expr/LangParser.While.cs b/ZSharp.Parser/lang/expr/LangParser.While.cs index 1239df51..67cee9dd 100644 --- a/ZSharp.Parser/lang/expr/LangParser.While.cs +++ b/ZSharp.Parser/lang/expr/LangParser.While.cs @@ -5,7 +5,8 @@ namespace ZSharp.Parser { public static partial class LangParser { - public static WhileExpression ParseWhileExpression(Parser parser) + public static WhileExpression ParseWhileExpression(Parser parser) + where TElse : Node { parser.Eat(Keywords.While); @@ -33,9 +34,9 @@ public static WhileExpression ParseWhileExpression(Parser parser) using (parser.Stack(LoopBody.Content)) @while = parser.Parse(); - Statement? @else = null; + TElse? @else = null; if (parser.Is(Keywords.Else, eat: true)) - @else = parser.Parse(); + @else = parser.Parse(); return new() { From 62bd5a803ca1df9a38eb18fdb2bd9f7f0ecb50a7 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 11 Jan 2025 19:56:45 +0200 Subject: [PATCH 032/235] Cast local initializer to local type --- .../builtin-compilers/module/FunctionCompiler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs index ae37197f..8a3fb0c4 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs @@ -126,7 +126,7 @@ private CompilerObject CompileNode(LetExpression let) local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); - var code = Compiler.Compiler.CompileIRCode(local.Initializer); + var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.Cast(local.Initializer, local.Type!)); code.Instructions.Add(new IR.VM.Dup()); code.Instructions.Add(new IR.VM.SetLocal(local.IR)); @@ -159,7 +159,7 @@ private CompilerObject CompileNode(VarExpression var) if (local.Initializer is not null) { - var code = Compiler.Compiler.CompileIRCode(local.Initializer); + var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.Cast(local.Initializer, local.Type!)); code.Instructions.Add(new IR.VM.Dup()); code.Instructions.Add(new IR.VM.SetLocal(local.IR)); From 63f2b9b302ecf55134812b6a397c7e28e773f2e1 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 11 Jan 2025 19:57:28 +0200 Subject: [PATCH 033/235] Remove casts from WhileLoop object --- .../runtime code/objects/WhileLoop.cs | 27 +++++++------------ 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs index 1f595b35..7b73e639 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs @@ -19,7 +19,7 @@ public sealed class WhileLoop public IR.VM.Instruction EndLabel { get; } = new IR.VM.Nop(); - public CompilerObject Type => throw new(); + public required CompilerObject Type { get; set; } public IRCode CompileIRCode(Compiler.Compiler compiler) { @@ -30,29 +30,22 @@ .. compiler.CompileIRCode( ).Instructions, new IR.VM.JumpIfFalse(ElseLabel), - - .. compiler.CompileIRCode( - compiler.Cast(While, compiler.TypeSystem.Void) - ).Instructions, + + .. compiler.CompileIRCode(While).Instructions, new IR.VM.Jump(ConditionLabel), ElseLabel, - .. Else is null ? [] : compiler.CompileIRCode( - compiler.Cast(Else, compiler.TypeSystem.Void) - ).Instructions, + .. Else is null ? [] : compiler.CompileIRCode(Else).Instructions, EndLabel ] - ); - } - - CompilerObject IDynamicallyTyped.GetType(Compiler.Compiler compiler) - { - if (compiler.TypeSystem.IsTyped(While, out var type)) - return type; - - throw new(); + ) + { + Types = Type == compiler.TypeSystem.Void + ? [] + : [Type] + }; } } } From c691c325fe11235d82cb8f273e8c407abc28f33d Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 11 Jan 2025 19:57:58 +0200 Subject: [PATCH 034/235] Move while compiler to core compilers --- .../module/FunctionCompiler.cs | 3 -- .../runtime code/WhileLoopCompiler.cs | 39 ---------------- .../loops/while/WhileExpressionCompiler.cs | 45 +++++++++++++++++++ .../loops/while/WhileLoopCompiler.cs | 38 ++++++++++++++++ .../loops/while/WhileStatementCompiler.cs | 23 ++++++++++ .../expression/ExpressionCompiler.cs | 6 +++ .../statement/StatementCompiler.cs | 12 ++++- 7 files changed, 123 insertions(+), 43 deletions(-) delete mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/WhileLoopCompiler.cs create mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs create mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs create mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs index 8a3fb0c4..c3d279ed 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs @@ -71,9 +71,6 @@ private void CompileFunctionBody() public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement node) { - if (node is ExpressionStatement es && es.Expression is WhileExpression @while) - return new WhileLoopCompiler(compiler, @while).Compile(); - if (node is not Return @return) return null; diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/WhileLoopCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/WhileLoopCompiler.cs deleted file mode 100644 index 17c9d3a2..00000000 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/WhileLoopCompiler.cs +++ /dev/null @@ -1,39 +0,0 @@ - -namespace ZSharp.ZSSourceCompiler -{ - public sealed class WhileLoopCompiler(ZSSourceCompiler compiler, WhileExpression node) - : ContextCompiler(compiler, node, new()) - , IOverrideCompileStatement - { - public override WhileLoop Compile() - { - Object.Condition = Compiler.CompileNode(Node.Condition); - - using (Context.Compiler(this)) - using (Context.Scope()) - Object.While = Compiler.CompileNode(Node.Body); - - if (Node.Else is not null) - using (Context.Scope()) - Object.Else = Compiler.CompileNode(Node.Else); - - return base.Compile(); - } - - public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement node) - { - if (node is BreakStatement @break) - return new Objects.RawCode( - new([ - .. @break.Value is null ? [] : compiler.Compiler.CompileIRCode( - compiler.CompileNode(@break.Value) - ).Instructions, - - new IR.VM.Jump(Object.EndLabel) - ]) - ); - - return null; - } - } -} diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs new file mode 100644 index 00000000..9aa44142 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs @@ -0,0 +1,45 @@ +namespace ZSharp.ZSSourceCompiler +{ + public sealed class WhileExpressionCompiler(ZSSourceCompiler compiler, WhileExpression node, CompilerObject type) + : WhileLoopCompiler(compiler, node, type) + { + protected override CompilerObject CompileBreak(BreakStatement @break) + { + if (@break.Value is null) + { + Compiler.LogError("Break statement in a while expression must have a value", @break); + return new Objects.RawCode(new([new IR.VM.Jump(Object.EndLabel)])); + } + + var value = Compiler.CompileNode(@break.Value); + if (!Compiler.Compiler.TypeSystem.IsTyped(value, out var type)) + { + Compiler.LogError("Value must be a valid RT value!", @break.Value); + return new Objects.RawCode(new([new IR.VM.Jump(Object.EndLabel)])); + } + + Object.Type ??= type; + + var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.Cast(value, type)); + + return new Objects.RawCode( + new([ + .. code.Instructions, + + new IR.VM.Jump(Object.EndLabel) + ]) + ); + } + + protected override CompilerObject CompileElse() + { + if (Object.Type is null) + { + Compiler.LogError("While expression must have a type", Node); + return new Objects.RawCode(new([new IR.VM.Jump(Object.EndLabel)])); + } + + return Compiler.Compiler.Cast(Compiler.CompileNode(Node.Else!), Object.Type); + } + } +} diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs new file mode 100644 index 00000000..e76ebe1d --- /dev/null +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs @@ -0,0 +1,38 @@ + +namespace ZSharp.ZSSourceCompiler +{ + public abstract class WhileLoopCompiler(ZSSourceCompiler compiler, WhileExpression node, CompilerObject type) + : ContextCompiler, WhileLoop>(compiler, node, new() + { + Type = type + }) + , IOverrideCompileStatement + where TElse : Node + { + public override WhileLoop Compile() + { + Object.Condition = Compiler.CompileNode(Node.Condition); + + using (Context.Compiler(this)) + using (Context.Scope()) + Object.While = Compiler.CompileNode(Node.Body); + + if (Node.Else is not null) + using (Context.Scope()) + Object.Else = CompileElse(); + + return base.Compile(); + } + + protected abstract CompilerObject CompileBreak(BreakStatement @break); + + protected abstract CompilerObject CompileElse(); + + public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement node) + => node switch + { + BreakStatement @break => CompileBreak(@break), + _ => null + }; + } +} diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs new file mode 100644 index 00000000..06a065bb --- /dev/null +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs @@ -0,0 +1,23 @@ +namespace ZSharp.ZSSourceCompiler +{ + public sealed class WhileStatementCompiler(ZSSourceCompiler compiler, WhileExpression node) + : WhileLoopCompiler(compiler, node, compiler.Compiler.TypeSystem.Void) + { + protected override CompilerObject CompileBreak(BreakStatement @break) + { + // TODO: add support for 'break from' statement + + if (@break.Value is not null) + Compiler.LogError("Break statement in a while statement must not have a value", @break); + + return new Objects.RawCode( + new([ + new IR.VM.Jump(Object.EndLabel) + ]) + ); + } + + protected override CompilerObject CompileElse() + => Compiler.CompileNode(Node.Else!); + } +} diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index 0cd206e0..a4ff4039 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -10,6 +10,7 @@ public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) CallExpression call => Compile(call), IdentifierExpression identifier => Context.CurrentScope.Get(identifier.Name), LiteralExpression literal => CompileNode(literal), + WhileExpression @while => Compile(@while), _ => null }; @@ -58,5 +59,10 @@ private CompilerObject Compile(CallExpression call) return Compiler.Compiler.Call(callable, args.ToArray()); } + + private WhileLoop Compile(WhileExpression @while) + { + return new WhileExpressionCompiler(Compiler, @while, null!).Compile(); + } } } diff --git a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs index 1670bf02..f4e91db3 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs @@ -12,6 +12,13 @@ public sealed class StatementCompiler(ZSSourceCompiler compiler) _ => null }; + private CompilerObject Compile(Expression expression) + => expression switch + { + WhileExpression @while => Compile(@while), + _ => Compiler.CompileNode(expression) + }; + private CompilerObject Compile(BlockStatement block) { var result = new Compiler.IRCode(); @@ -29,7 +36,7 @@ private CompilerObject Compile(ExpressionStatement expressionStatement) if (expressionStatement.Expression is null) return new Objects.RawCode(new()); - var result = Compiler.Compiler.CompileIRCode(Compiler.CompileNode(expressionStatement.Expression)); + var result = Compiler.Compiler.CompileIRCode(Compile(expressionStatement.Expression)); if (result.IsValue) { @@ -71,5 +78,8 @@ private CompilerObject Compile(ImportStatement import) return result; } + + private WhileLoop Compile(WhileExpression @while) + => new WhileStatementCompiler(Compiler, @while).Compile(); } } From cab07e58cb140bfdef6a4853d59247cd9393546f Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 11 Jan 2025 19:58:13 +0200 Subject: [PATCH 035/235] Add while expression test file --- ZSharpTest/tests/test-while-expression.zs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 ZSharpTest/tests/test-while-expression.zs diff --git a/ZSharpTest/tests/test-while-expression.zs b/ZSharpTest/tests/test-while-expression.zs new file mode 100644 index 00000000..111f6b07 --- /dev/null +++ b/ZSharpTest/tests/test-while-expression.zs @@ -0,0 +1,16 @@ +import { print } from "std:io"; + +module Program; + + +fun main(): void { + let result = + while (false) + break "TRUE"; + else "FALSE"; + + + print(result); + + return; +} From 52ea099a2bd5ed3c9db9f23a97524ba1ece3220a Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 11 Jan 2025 19:58:28 +0200 Subject: [PATCH 036/235] Fix main to use generic while parser --- ZSharpTest/Main.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index f10b082c..bd76d7e6 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -66,12 +66,12 @@ expressionParser.AddKeywordParser( LangParser.Keywords.While, - LangParser.ParseWhileExpression + LangParser.ParseWhileExpression ); statementParser.AddKeywordParser( LangParser.Keywords.While, - Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) + Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) ); //zsharpParser.Function.AddKeywordParser( From 901e8a7c5e8d86c941d98ae771a77bd66aaa4ae3 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 11 Jan 2025 19:59:02 +0200 Subject: [PATCH 037/235] Update main test project file --- ZSharpTest/ZSharpTest.csproj | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ZSharpTest/ZSharpTest.csproj b/ZSharpTest/ZSharpTest.csproj index 93158e38..1130d759 100644 --- a/ZSharpTest/ZSharpTest.csproj +++ b/ZSharpTest/ZSharpTest.csproj @@ -30,6 +30,9 @@ PreserveNewest + + PreserveNewest + From 83c8be692d4202076a9e1e2ba1f8dadc95106f8f Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 12 Jan 2025 00:11:57 +0200 Subject: [PATCH 038/235] Add support for compiling if statements --- .../runtime code/objects/If.cs | 38 +++++++++++++++++++ .../statement/StatementCompiler.cs | 13 +++++++ 2 files changed, 51 insertions(+) create mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/If.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/If.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/If.cs new file mode 100644 index 00000000..6183cfdc --- /dev/null +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/If.cs @@ -0,0 +1,38 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class If + : CompilerObject + , ICompileIRCode + { + public CompilerObject Body { get; set; } + + public CompilerObject Condition { get; set; } + + public IR.VM.Nop ElseLabel { get; } = new(); + + public CompilerObject? Else { get; set; } + + public IR.VM.Nop EndLabel { get; } = new(); + + public IRCode CompileIRCode(Compiler.Compiler compiler) + => new([ + .. compiler.CompileIRCode(compiler.Cast(Condition, compiler.TypeSystem.Boolean)).Instructions, + + new IR.VM.JumpIfFalse(ElseLabel), + + .. compiler.CompileIRCode(Body).Instructions, + + new IR.VM.Jump(EndLabel), + + ElseLabel, + .. Else is null ? [] : compiler.CompileIRCode(Else).Instructions, + + EndLabel, + ]) + { + + }; + } +} diff --git a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs index f4e91db3..367cc1c4 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs @@ -8,6 +8,7 @@ public sealed class StatementCompiler(ZSSourceCompiler compiler) { BlockStatement block => Compile(block), ExpressionStatement expressionStatement => Compile(expressionStatement), + IfStatement @if => Compile(@if), ImportStatement import => Compile(import), _ => null }; @@ -49,6 +50,18 @@ private CompilerObject Compile(ExpressionStatement expressionStatement) return new Objects.RawCode(result); } + private CompilerObject Compile(IfStatement @if) + { + var result = new Objects.If() + { + Body = Compiler.CompileNode(@if.If), + Condition = Compiler.CompileNode(@if.Condition), + Else = @if.Else is null ? null : Compiler.CompileNode(@if.Else) + }; + + return result; + } + private CompilerObject Compile(ImportStatement import) { if (import.Arguments is not null) From c95f7f752d09bf8b0ddc65ba6a1d90fe03ac575f Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 12 Jan 2025 00:12:10 +0200 Subject: [PATCH 039/235] Add if statement to parser --- ZSharpTest/Main.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index bd76d7e6..91f4bd92 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -74,6 +74,11 @@ Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) ); + statementParser.AddKeywordParser( + LangParser.Keywords.If, + LangParser.ParseIfStatement + ); + //zsharpParser.Function.AddKeywordParser( // LangParser.Keywords.While, // Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) From 37fd91bebe971d10b2e66876d3d286d64e223ec1 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 12 Jan 2025 00:12:38 +0200 Subject: [PATCH 040/235] Add if-statement test file --- ZSharpTest/ZSharpTest.csproj | 3 +++ ZSharpTest/tests/test-if-statement.zs | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 ZSharpTest/tests/test-if-statement.zs diff --git a/ZSharpTest/ZSharpTest.csproj b/ZSharpTest/ZSharpTest.csproj index 1130d759..32d703a6 100644 --- a/ZSharpTest/ZSharpTest.csproj +++ b/ZSharpTest/ZSharpTest.csproj @@ -30,6 +30,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest diff --git a/ZSharpTest/tests/test-if-statement.zs b/ZSharpTest/tests/test-if-statement.zs new file mode 100644 index 00000000..84feef93 --- /dev/null +++ b/ZSharpTest/tests/test-if-statement.zs @@ -0,0 +1,17 @@ +import { print } from "std:io"; + +module Program; + + +fun main(): void { + let value = false; + + if (value) + print("true"); + else if (false) + print("false"); + else + print("else"); + + return; +} From 113751071439762406f5ea41603239ce36a857f2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 12 Jan 2025 00:21:14 +0200 Subject: [PATCH 041/235] Update guessing-game to use if statements --- ZSharpTest/guessing-game.zs | 27 +++++++++------------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/ZSharpTest/guessing-game.zs b/ZSharpTest/guessing-game.zs index 93c3f480..0b61db7c 100644 --- a/ZSharpTest/guessing-game.zs +++ b/ZSharpTest/guessing-game.zs @@ -1,23 +1,16 @@ import { input, print } from "std:io"; import { ceil, log2, random } from "std:math"; -//import { random } from "std:random"; module Program; fun guessOnce(guess: i32, number: i32, tries: i32): bool { - while (guess < number) - { + if (guess < number) print("Too low!"); - return false; - } - while (number < guess) - { + else if (number < guess) print("Too high!"); - return false; - } + else return true; - print("You got it in " + string(tries + 1) + " tries!"); - return true; + return false; } fun main(): void { @@ -33,15 +26,13 @@ fun main(): void { let guessString = input("Guess a number between " + string(minNumber) + " and " + string(maxNumber) + ": "); let guess = i32.parse(guessString); - while (guessOnce(guess, number, tries)) + if (guessOnce(guess, number, tries)) { - tries = maxTries + 1; + print("You got it in " + string(tries + 1) + " tries!"); break; - } else tries = tries + 1; - } - - while (maxTries < tries) { break; } - else print("You didn't get it in " + string(maxTries) + " tries. The number was " + string(number)); + } + else tries = tries + 1; + } else print("You didn't get it in " + string(maxTries) + " tries. The number was " + string(number)); return; } From f9eb86f488d91754e68017b98e1ebe628507137c Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 12 Jan 2025 00:21:32 +0200 Subject: [PATCH 042/235] Update launchSettings.json --- ZSharpTest/Properties/launchSettings.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ZSharpTest/Properties/launchSettings.json b/ZSharpTest/Properties/launchSettings.json index 99803480..2cede4b9 100644 --- a/ZSharpTest/Properties/launchSettings.json +++ b/ZSharpTest/Properties/launchSettings.json @@ -1,6 +1,10 @@ { "profiles": { - "ZSharpTest": { + "tests/": { + "commandName": "Project", + "commandLineArgs": "tests/test-" + }, + "guessing-game": { "commandName": "Project", "commandLineArgs": "guessing-game.zs" } From bcf8269cf96f11f7cd01dbb8fe14518f6c246ec5 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 1 Feb 2025 23:22:46 +0200 Subject: [PATCH 043/235] Add basic support for generic classes in IR --- ZSharp.IR/ir/GenericParameter.cs | 13 -------- ZSharp.IR/ir/oop/Class.cs | 20 ++++++++++-- ZSharp.IR/ir/typeclass/Typeclass.cs | 2 +- ZSharp.IR/ir/types/GenericParameter.cs | 8 +++++ ZSharp.IR/ir/types/OOPType.cs | 2 +- ZSharp.IR/type system/RuntimeModule.cs | 32 +++++++++---------- ZSharp.IR/type system/TypeSystem.cs | 16 +++++----- .../type system/types/ConstructedClass.cs | 12 +++++++ .../type system/types/ConstructedType.cs | 7 ---- 9 files changed, 64 insertions(+), 48 deletions(-) delete mode 100644 ZSharp.IR/ir/GenericParameter.cs create mode 100644 ZSharp.IR/ir/types/GenericParameter.cs create mode 100644 ZSharp.IR/type system/types/ConstructedClass.cs delete mode 100644 ZSharp.IR/type system/types/ConstructedType.cs diff --git a/ZSharp.IR/ir/GenericParameter.cs b/ZSharp.IR/ir/GenericParameter.cs deleted file mode 100644 index dbf30386..00000000 --- a/ZSharp.IR/ir/GenericParameter.cs +++ /dev/null @@ -1,13 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.IR -{ - public class GenericParameter - { - public string Name { get; set; } - - public GenericParameterAttributes Attributes { get; set; } = GenericParameterAttributes.None; - - //public Collection Constraints { get; set; } - } -} diff --git a/ZSharp.IR/ir/oop/Class.cs b/ZSharp.IR/ir/oop/Class.cs index 0f954792..90db76dc 100644 --- a/ZSharp.IR/ir/oop/Class.cs +++ b/ZSharp.IR/ir/oop/Class.cs @@ -4,15 +4,17 @@ namespace ZSharp.IR { public sealed class Class(string? name) : OOPType { + private Collection? _genericParameters; + private FieldCollection? _fields; public string? Name { get; set; } = name; public ClassAttributes Attributes { get; set; } = ClassAttributes.None; - public Class? Base { get; set; } + public ConstructedClass? Base { get; set; } - public Class(string? name, Class? @base) + public Class(string? name, ConstructedClass? @base) : this(name) { Base = @base; @@ -20,6 +22,20 @@ public Class(string? name, Class? @base) public Collection InterfacesImplementations { get; } = []; + public Collection GenericParameters + { + get + { + if (_genericParameters is not null) + return _genericParameters; + + Interlocked.CompareExchange(ref _genericParameters, [], null); + return _genericParameters; + } + } + + public bool HasGenericParameters => !_genericParameters.IsNullOrEmpty(); + public Collection Fields { get diff --git a/ZSharp.IR/ir/typeclass/Typeclass.cs b/ZSharp.IR/ir/typeclass/Typeclass.cs index 7a586b1e..cc8e7490 100644 --- a/ZSharp.IR/ir/typeclass/Typeclass.cs +++ b/ZSharp.IR/ir/typeclass/Typeclass.cs @@ -10,7 +10,7 @@ public sealed class Typeclass : OOPType public Collection Bases { get; } - public TemplateParameter Parameter { get; } + public GenericParameter Parameter { get; } public Collection Methods { get; } diff --git a/ZSharp.IR/ir/types/GenericParameter.cs b/ZSharp.IR/ir/types/GenericParameter.cs new file mode 100644 index 00000000..b1fdfcbc --- /dev/null +++ b/ZSharp.IR/ir/types/GenericParameter.cs @@ -0,0 +1,8 @@ +namespace ZSharp.IR +{ + public sealed class GenericParameter(string name) + : IType + { + public string Name { get; set; } = name; + } +} diff --git a/ZSharp.IR/ir/types/OOPType.cs b/ZSharp.IR/ir/types/OOPType.cs index 7a9de826..a379a235 100644 --- a/ZSharp.IR/ir/types/OOPType.cs +++ b/ZSharp.IR/ir/types/OOPType.cs @@ -1,6 +1,6 @@ namespace ZSharp.IR { - public abstract class OOPType : ModuleMember, IType + public abstract class OOPType : ModuleMember { } diff --git a/ZSharp.IR/type system/RuntimeModule.cs b/ZSharp.IR/type system/RuntimeModule.cs index e529e5e7..f5179e89 100644 --- a/ZSharp.IR/type system/RuntimeModule.cs +++ b/ZSharp.IR/type system/RuntimeModule.cs @@ -15,30 +15,30 @@ private static RuntimeModule CreateStandardRuntimeModule() { Module module = new("Runtime"); - Class @object; - Class @string; - Class type; - Class @void; - Class @null; + ConstructedClass @object; + ConstructedClass @string; + ConstructedClass type; + ConstructedClass @void; + ConstructedClass @null; - Class boolean; + ConstructedClass boolean; - Class int32; + ConstructedClass int32; - Class float32; + ConstructedClass float32; { - module.Types.Add(type = new("Type")); - module.Types.Add(@object = new("Object")); - module.Types.Add(@string = new("String")); - module.Types.Add(@void = new("Void")); - module.Types.Add(@null = new("Null")); + module.Types.Add((type = new(new("Type"))).Class); + module.Types.Add((@object = new(new("Object"))).Class); + module.Types.Add((@string = new(new("String"))).Class); + module.Types.Add((@void = new(new("Void"))).Class); + module.Types.Add((@null = new(new("Null"))).Class); - module.Types.Add(boolean = new("Boolean")); + module.Types.Add((boolean = new(new("Boolean"))).Class); - module.Types.Add(int32 = new("Int32")); + module.Types.Add((int32 = new(new("Int32"))).Class); - module.Types.Add(float32 = new("Float32")); + module.Types.Add((float32 = new(new("Float32"))).Class); } return new(module, new() diff --git a/ZSharp.IR/type system/TypeSystem.cs b/ZSharp.IR/type system/TypeSystem.cs index 46f5fa4a..acd8f9de 100644 --- a/ZSharp.IR/type system/TypeSystem.cs +++ b/ZSharp.IR/type system/TypeSystem.cs @@ -2,20 +2,20 @@ { public sealed class TypeSystem { - public Class Object { get; init; } = null!; + public ConstructedClass Object { get; init; } = null!; - public Class String { get; init; } = null!; + public ConstructedClass String { get; init; } = null!; - public Class Type { get; init; } = null!; + public ConstructedClass Type { get; init; } = null!; - public Class Void { get; init; } = null!; + public ConstructedClass Void { get; init; } = null!; - public Class Null { get; init; } = null!; + public ConstructedClass Null { get; init; } = null!; - public Class Boolean { get; init; } = null!; + public ConstructedClass Boolean { get; init; } = null!; - public Class Int32 { get; init; } = null!; + public ConstructedClass Int32 { get; init; } = null!; - public Class Float32 { get; init; } = null!; + public ConstructedClass Float32 { get; init; } = null!; } } diff --git a/ZSharp.IR/type system/types/ConstructedClass.cs b/ZSharp.IR/type system/types/ConstructedClass.cs new file mode 100644 index 00000000..49a9e9f0 --- /dev/null +++ b/ZSharp.IR/type system/types/ConstructedClass.cs @@ -0,0 +1,12 @@ +using CommonZ.Utils; + +namespace ZSharp.IR +{ + public sealed class ConstructedClass(Class @class) + : IType + { + public Class Class { get; set; } = @class; + + public Collection Arguments { get; set; } = @class.HasGenericParameters ? [] : Collection.Empty; + } +} diff --git a/ZSharp.IR/type system/types/ConstructedType.cs b/ZSharp.IR/type system/types/ConstructedType.cs deleted file mode 100644 index 6ca18645..00000000 --- a/ZSharp.IR/type system/types/ConstructedType.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.IR -{ - public sealed class ConstructedType : IType - { - - } -} From 6b29c534fd20a369d3f258ae4a341eb66e68f416 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 1 Feb 2025 23:23:01 +0200 Subject: [PATCH 044/235] Remove unused classes in IR --- ZSharp.IR/ir/templates/ITemplate.cs | 9 --------- ZSharp.IR/ir/templates/TemplateParameter.cs | 12 ------------ 2 files changed, 21 deletions(-) delete mode 100644 ZSharp.IR/ir/templates/ITemplate.cs delete mode 100644 ZSharp.IR/ir/templates/TemplateParameter.cs diff --git a/ZSharp.IR/ir/templates/ITemplate.cs b/ZSharp.IR/ir/templates/ITemplate.cs deleted file mode 100644 index c92c0321..00000000 --- a/ZSharp.IR/ir/templates/ITemplate.cs +++ /dev/null @@ -1,9 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.IR -{ - public interface ITemplate - { - public IRObject Construct(Mapping args); - } -} diff --git a/ZSharp.IR/ir/templates/TemplateParameter.cs b/ZSharp.IR/ir/templates/TemplateParameter.cs deleted file mode 100644 index 4c84d3a6..00000000 --- a/ZSharp.IR/ir/templates/TemplateParameter.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ZSharp.IR -{ - public sealed class TemplateParameter - { - public string Name { get; set; } - - public TemplateParameter(string name) - { - Name = name; - } - } -} From ae5b522b96137dbee5c56c9df9fb23a3370060e2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 1 Feb 2025 23:23:32 +0200 Subject: [PATCH 045/235] Fix type support in IR <-> IL due to changes in IR type system --- ZSharp.Runtime.IL/context/Context.IL2IR.cs | 24 +++++++++---- .../{ContextIR2IL.cs => Context.IR2IL.cs} | 17 ++++++++++ .../context/caches/ContextCache.IL2IR.cs | 4 ++- .../context/caches/ContextCache.IR2IL.cs | 4 ++- ZSharp.Runtime.IL/il2ir/core/ILLoader.cs | 12 +++++-- .../il2ir/loaders/ClassLoader.cs | 34 ++++++++++--------- .../ir2il/loaders/ModuleLoader.cs | 2 +- 7 files changed, 70 insertions(+), 27 deletions(-) rename ZSharp.Runtime.IL/context/{ContextIR2IL.cs => Context.IR2IL.cs} (85%) diff --git a/ZSharp.Runtime.IL/context/Context.IL2IR.cs b/ZSharp.Runtime.IL/context/Context.IL2IR.cs index 82061072..e1bb04e9 100644 --- a/ZSharp.Runtime.IL/context/Context.IL2IR.cs +++ b/ZSharp.Runtime.IL/context/Context.IL2IR.cs @@ -21,15 +21,12 @@ public IR.Module Cache(IL.Module il, IR.Module ir) return ir; } - public IR.IType? Cache(Type il) - => toIR.Types.Cache(il); - public bool Cache(Type il, [NotNullWhen(true)] out IR.IType? ir) => toIR.Types.Cache(il, out ir); - public bool Cache(Type il, [NotNullWhen(true)] out T? ir) - where T : class, IR.IType - => toIR.Types.Cache(il, out ir); + //public bool Cache(Type il, [NotNullWhen(true)] out T? ir) + // where T : class, IR.IType + // => toIR.Types.Cache(il, out ir); public IR.IType Cache(Type il, IR.IType ir) { @@ -42,6 +39,21 @@ public IR.IType Cache(Type il, IR.IType ir) return ir; } + public bool Cache(Type il, [NotNullWhen(true)] out T? ir) + where T : IR.OOPType + => toIR.OOPTypes.Cache(il, out ir); + + public IR.OOPType Cache(Type il, IR.OOPType ir) + { + if (!toIR.OOPTypes.Contains(il)) + toIR.OOPTypes.Cache(il, ir); + + if (!toIL.OOPTypes.Contains(ir)) + toIL.OOPTypes.Cache(ir, il); + + return ir; + } + public IR.ICallable? Cache(IL.MethodBase il) => toIR.Callables.Cache(il); diff --git a/ZSharp.Runtime.IL/context/ContextIR2IL.cs b/ZSharp.Runtime.IL/context/Context.IR2IL.cs similarity index 85% rename from ZSharp.Runtime.IL/context/ContextIR2IL.cs rename to ZSharp.Runtime.IL/context/Context.IR2IL.cs index 58c34f46..3a92da14 100644 --- a/ZSharp.Runtime.IL/context/ContextIR2IL.cs +++ b/ZSharp.Runtime.IL/context/Context.IR2IL.cs @@ -38,6 +38,23 @@ public Type Cache(IR.IType ir, Type il) return il; } + public Type? Cache(IR.OOPType ir) + => toIL.OOPTypes.Cache(ir); + + public bool Cache(IR.OOPType ir, [NotNullWhen(true)] out Type? il) + => toIL.OOPTypes.Cache(ir, out il); + + public Type Cache(IR.OOPType ir, Type il) + { + if (!toIR.OOPTypes.Contains(il)) + toIR.OOPTypes.Cache(il, ir); + + if (!toIL.OOPTypes.Contains(ir)) + toIL.OOPTypes.Cache(ir, il); + + return il; + } + public IL.MethodBase? Cache(IR.ICallable ir) => toIL.Callables.Cache(ir); diff --git a/ZSharp.Runtime.IL/context/caches/ContextCache.IL2IR.cs b/ZSharp.Runtime.IL/context/caches/ContextCache.IL2IR.cs index 796bac0d..25b4f973 100644 --- a/ZSharp.Runtime.IL/context/caches/ContextCache.IL2IR.cs +++ b/ZSharp.Runtime.IL/context/caches/ContextCache.IL2IR.cs @@ -4,9 +4,11 @@ namespace ZSharp.Runtime.NET { internal sealed class ContextCacheIL2IR { + public Cache Types { get; } = []; + public Cache Modules { get; } = []; - public Cache Types { get; } = []; + public Cache OOPTypes { get; } = []; public Cache Callables { get; } = []; diff --git a/ZSharp.Runtime.IL/context/caches/ContextCache.IR2IL.cs b/ZSharp.Runtime.IL/context/caches/ContextCache.IR2IL.cs index de623a44..a6699539 100644 --- a/ZSharp.Runtime.IL/context/caches/ContextCache.IR2IL.cs +++ b/ZSharp.Runtime.IL/context/caches/ContextCache.IR2IL.cs @@ -4,9 +4,11 @@ namespace ZSharp.Runtime.NET { internal sealed class ContextCacheIR2IL { + public Cache Types { get; } = []; + public Cache Modules { get; } = []; - public Cache Types { get; } = []; + public Cache OOPTypes { get; } = []; public Cache Callables { get; } = []; diff --git a/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs b/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs index c36bb6fb..3051f350 100644 --- a/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs @@ -15,13 +15,21 @@ public IType LoadType(Type type) if (type.IsTypeDefinition) { - if (type.IsClass) result = new ClassLoader(this, type).Load(); + if (type.IsGenericTypeDefinition) + throw new InvalidOperationException(); + + var genericArguments = type.GenericTypeArguments.Select(LoadType).ToList(); + + if (type.IsClass) result = new ConstructedClass(new ClassLoader(this, type).Load()) + { + Arguments = new(genericArguments), + }; //else if (type.IsInterface) result = new ILInterfaceLoader(this, type).Load(); //else if (type.IsEnum) result = new ILEnumLoader(this, type).Load(); //else if (type.IsValueType) result = new ILStructLoader(this, type).Load(); else throw new ArgumentException("Type must be a type definition.", nameof(type)); - return Context.Cache(type, result); + return result; } if (type.IsArray) diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs index 94c9d4ed..cf75d2f1 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs @@ -1,4 +1,6 @@ -namespace ZSharp.Runtime.NET.IL2IR +using ZSharp.IR; + +namespace ZSharp.Runtime.NET.IL2IR { internal sealed class ClassLoader(ILLoader loader, Type input) : BaseILLoader(loader, input, new(input.Name)) @@ -30,7 +32,7 @@ public override IR.Class Load() private void LoadBase() { if (Input.BaseType is not null) - Output.Base = (IR.Class)Loader.LoadType(Input.BaseType); + Output.Base = (IR.ConstructedClass)Loader.LoadType(Input.BaseType); } private void LoadInterfaceImplementations() @@ -74,18 +76,20 @@ private void LoadInterfaceImplementation(Type @interface, IL.InterfaceMapping ma if (mapping.InterfaceMethods.Length != mapping.TargetMethods.Length) throw new InvalidOperationException("Interface mapping is invalid."); - var implementation = new IR.InterfaceImplementation(Loader.LoadType(@interface)); + throw new NotImplementedException(); - for (int i = 0; i < mapping.InterfaceMethods.Length; i++) - { - var interfaceMethod = mapping.InterfaceMethods[i]; - var targetMethod = mapping.TargetMethods[i]; + //var implementation = new IR.InterfaceImplementation(Loader.LoadType(@interface)); - implementation.Implementations.Add( - LoadMethod(interfaceMethod), - LoadMethod(targetMethod) - ); - } + //for (int i = 0; i < mapping.InterfaceMethods.Length; i++) + //{ + // var interfaceMethod = mapping.InterfaceMethods[i]; + // var targetMethod = mapping.TargetMethods[i]; + + // implementation.Implementations.Add( + // LoadMethod(interfaceMethod), + // LoadMethod(targetMethod) + // ); + //} } private void LoadField(IL.FieldInfo field) @@ -136,13 +140,11 @@ private void LoadTypeDefinition(Type type) if (!type.IsTypeDefinition) throw new ArgumentException("Type must be a type definition.", nameof(type)); - var result = Context.Cache(type); - - if (result is not null) ; + if (Context.Cache(type, out OOPType? result)) ; else if (type.IsClass) result = LoadClass(type); else if (type.IsInterface) result = LoadInterface(type); else if (type.IsEnum) result = LoadEnum(type); - else if (type.IsValueType) result= LoadStruct(type); + else if (type.IsValueType) result = LoadStruct(type); else throw new NotImplementedException(); // TADA: | | | | | | | | | diff --git a/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs b/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs index d699ce81..d9f9ce09 100644 --- a/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs @@ -56,7 +56,7 @@ private void LoadTypes() LoadType(type); } - private Type LoadType(IR.IType type) + private Type LoadType(IR.OOPType type) { if (Context.Cache(type, out var result)) return result; From fcd1dc181bd89ab3018ea30aa5999558e7f232ce Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 1 Feb 2025 23:23:59 +0200 Subject: [PATCH 046/235] Make the class CO more generic --- .../features/oop/objects/class/Class.cs | 14 ++++---------- .../features/oop/objects/class/ClassMeta.cs | 2 +- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/ZSharp.Compiler/features/oop/objects/class/Class.cs b/ZSharp.Compiler/features/oop/objects/class/Class.cs index bfb3c0bc..728db12a 100644 --- a/ZSharp.Compiler/features/oop/objects/class/Class.cs +++ b/ZSharp.Compiler/features/oop/objects/class/Class.cs @@ -15,11 +15,11 @@ public sealed class Class public string? Name { get; set; } - public Class? Base { get; set; } + public CompilerObject? Base { get; set; } //public SimpleFunctionOverloadGroup? Constructor { get; set; } - public Constructor? Constructor { get; set; } + public CompilerObject? Constructor { get; set; } public Constructor? EmptyConstructor { get; set; } @@ -31,14 +31,8 @@ public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) if (EmptyConstructor is null) throw new InvalidOperationException(); else return compiler.Call(EmptyConstructor, arguments); - return new RawCode( - new([ - new IR.VM.CreateInstance(Constructor!.IR!) - ]) - { - MaxStackSize = 1, - Types = [this] - }); + if (Constructor is null) throw new InvalidOperationException(); + return compiler.Call(Constructor, arguments); } //public List? Interfaces { get; set; } diff --git a/ZSharp.Compiler/features/oop/objects/class/ClassMeta.cs b/ZSharp.Compiler/features/oop/objects/class/ClassMeta.cs index d00142ce..f045dfa6 100644 --- a/ZSharp.Compiler/features/oop/objects/class/ClassMeta.cs +++ b/ZSharp.Compiler/features/oop/objects/class/ClassMeta.cs @@ -48,7 +48,7 @@ public Class Construct(Compiler.Compiler compiler, string name, CompilerObject[] return result; } - private CompilerObject? FindSubclassInitializer(Class? @base) + private CompilerObject? FindSubclassInitializer(CompilerObject? @base) { //while (@base is not null) // if (@base.SubclassInitializer is not null) return @base.SubclassInitializer; From bf3d0dcb300c186c1e0d5a2353805fcbd8f32981 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 1 Feb 2025 23:24:18 +0200 Subject: [PATCH 047/235] Remove problematic code --- ZSharp.Compiler/cg objects/Type.cs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/ZSharp.Compiler/cg objects/Type.cs b/ZSharp.Compiler/cg objects/Type.cs index 17115f45..7544e4d1 100644 --- a/ZSharp.Compiler/cg objects/Type.cs +++ b/ZSharp.Compiler/cg objects/Type.cs @@ -5,24 +5,24 @@ namespace ZSharp.Objects { internal sealed class Type(IRType type) : CompilerObject - , ICTReadable + //, ICTReadable , ICompileIRType { private readonly IRType type = type; - private readonly IRObject ir = type as IRObject ?? throw new(); + //private readonly IRObject ir = type as IRObject ?? throw new(); - CompilerObject ITyped.Type => this; + //CompilerObject ITyped.Type => this; IType ICompileIRType.CompileIRType(Compiler.Compiler compiler) => type; - public IRCode Read(Compiler.Compiler compiler) - => new([ - new IR.VM.GetObject(ir) - ]) - { - MaxStackSize = 1, - Types = [this] - }; + //public IRCode Read(Compiler.Compiler compiler) + //=> new([ + // new IR.VM.GetObject(ir) + // ]) + // { + // MaxStackSize = 1, + // Types = [this] + // }; } } From 86c0c40830f3d1ba0aca3bfa9a56a446abf3451c Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 1 Feb 2025 23:24:37 +0200 Subject: [PATCH 048/235] Update core compiler types to use newer IR type system --- ZSharp.Compiler/cg objects/types/Int32Type.cs | 4 ++-- ZSharp.Compiler/cg objects/types/StringType.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ZSharp.Compiler/cg objects/types/Int32Type.cs b/ZSharp.Compiler/cg objects/types/Int32Type.cs index 7ee4d8c6..cfd405c7 100644 --- a/ZSharp.Compiler/cg objects/types/Int32Type.cs +++ b/ZSharp.Compiler/cg objects/types/Int32Type.cs @@ -3,12 +3,12 @@ namespace ZSharp.Objects { - public sealed class Int32Type(IR.Class ir, CompilerObject type) + public sealed class Int32Type(IR.ConstructedClass ir, CompilerObject type) : CompilerObject , ICompileIRType , ICTGetMember { - public IR.Class IR { get; } = ir; + public IR.ConstructedClass IR { get; } = ir; public CompilerObject Type { get; } = type; diff --git a/ZSharp.Compiler/cg objects/types/StringType.cs b/ZSharp.Compiler/cg objects/types/StringType.cs index 546c39d7..abe65662 100644 --- a/ZSharp.Compiler/cg objects/types/StringType.cs +++ b/ZSharp.Compiler/cg objects/types/StringType.cs @@ -2,12 +2,12 @@ namespace ZSharp.Objects { - public sealed class StringType(IR.Class stringType, CompilerObject type) + public sealed class StringType(IR.ConstructedClass stringType, CompilerObject type) : CompilerObject , ICompileIRType , ICTCallable { - public IR.Class IR { get; } = stringType; + public IR.ConstructedClass IR { get; } = stringType; public CompilerObject Type { get; } = type; From 5b74258c8eb1e7b036696a01c8009b52a5da548e Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 1 Feb 2025 23:25:16 +0200 Subject: [PATCH 049/235] Allow constructors to be called for base initialization as well --- ZSharp.Compiler/cg objects/oop/Constructor.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ZSharp.Compiler/cg objects/oop/Constructor.cs b/ZSharp.Compiler/cg objects/oop/Constructor.cs index b95456c0..34761860 100644 --- a/ZSharp.Compiler/cg objects/oop/Constructor.cs +++ b/ZSharp.Compiler/cg objects/oop/Constructor.cs @@ -57,7 +57,10 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) result.Append(kwArgsCode); result.Append(varKwArgsCode); // should be empty - result.Instructions.Add(new IR.VM.CreateInstance(IR!)); + if (kwArgs.ContainsKey(Signature.Args[0].Name)) + result.Instructions.Add(new IR.VM.Call(IR!.Method)); + else + result.Instructions.Add(new IR.VM.CreateInstance(IR!)); result.Types.Clear(); result.Types.Add(Owner ?? throw new()); From c96ceb2115b14b0cf767b349aaba7f7636380fc7 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 2 Feb 2025 22:33:26 +0200 Subject: [PATCH 050/235] Add todo project test file --- ZSharpTest/projects/todo.zs | 61 +++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 ZSharpTest/projects/todo.zs diff --git a/ZSharpTest/projects/todo.zs b/ZSharpTest/projects/todo.zs new file mode 100644 index 00000000..4acad6a9 --- /dev/null +++ b/ZSharpTest/projects/todo.zs @@ -0,0 +1,61 @@ +import { list } from "std:list"; +import { print, input } from "std:io"; + + +module Program { + + let todo: list[string] = [ + "Add list[T] type", + "Add support for generic types in CO", + "Add compiler for `for` statements", + "Fix `for.currentItem` field so that using `let` doesn't force to initialize.", + "Add compiler for `case` statements", + ]; + + fun addTodo() { + let item = input("Enter item to add: "); + + todo.add(item); + } + + fun getTodos(): list[string] { + var i = 1; + + for (let item = 0 in todo) + { + print(string(i) + ". " + item); + i = i + 1; + } + } + + fun delTodo(): void { + let index = i32.parse(input("Enter item number to remove: ")); + + todo.removeAt(index - 1); + } + + fun do(): bool { + print("Welcome to The ToDo List App! Please choose what to do:"); + print("1. Add an item."); + print("2. List all items."); + print("3. Remove an item."); + print("4. Exit program."); + + let cmd = input("> "); + + case (cmd) { + when ("1") addTodo(); + when ("2") getTodos(); + when ("3") delTodo(); + when ("4") return false; + } else + print("Unknown command: " + cmd); + + return true; + } + + fun main() { + while (do()); + else print("Thank you for using The ToDo List App!"); + } +} From 86d4f5ccd2394901f652b90ea9bcc9182fb4887d Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 2 Feb 2025 22:33:51 +0200 Subject: [PATCH 051/235] Organize test projects --- ZSharpTest/Properties/launchSettings.json | 8 ++++++-- ZSharpTest/ZSharpTest.csproj | 5 ++++- ZSharpTest/{ => projects}/guessing-game.zs | 0 3 files changed, 10 insertions(+), 3 deletions(-) rename ZSharpTest/{ => projects}/guessing-game.zs (100%) diff --git a/ZSharpTest/Properties/launchSettings.json b/ZSharpTest/Properties/launchSettings.json index 2cede4b9..4409d350 100644 --- a/ZSharpTest/Properties/launchSettings.json +++ b/ZSharpTest/Properties/launchSettings.json @@ -4,9 +4,13 @@ "commandName": "Project", "commandLineArgs": "tests/test-" }, - "guessing-game": { + "Projects/ToDo": { "commandName": "Project", - "commandLineArgs": "guessing-game.zs" + "commandLineArgs": "projects/todo.zs" + }, + "Projects/Guessing Game": { + "commandName": "Project", + "commandLineArgs": "projects/guessing-game.zs" } } } \ No newline at end of file diff --git a/ZSharpTest/ZSharpTest.csproj b/ZSharpTest/ZSharpTest.csproj index 32d703a6..ccb2f5c7 100644 --- a/ZSharpTest/ZSharpTest.csproj +++ b/ZSharpTest/ZSharpTest.csproj @@ -21,7 +21,10 @@ - + + PreserveNewest + + PreserveNewest diff --git a/ZSharpTest/guessing-game.zs b/ZSharpTest/projects/guessing-game.zs similarity index 100% rename from ZSharpTest/guessing-game.zs rename to ZSharpTest/projects/guessing-game.zs From da6502e628361615abbcfb5fef3559b4acb503af Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 2 Feb 2025 22:34:25 +0200 Subject: [PATCH 052/235] Add array literal and organize literal AST nodes files --- ZSharp.AST/nodes/expr/literals/ArrayLiteral.cs | 7 +++++++ ZSharp.AST/nodes/expr/{ => literals}/LiteralExpression.cs | 0 2 files changed, 7 insertions(+) create mode 100644 ZSharp.AST/nodes/expr/literals/ArrayLiteral.cs rename ZSharp.AST/nodes/expr/{ => literals}/LiteralExpression.cs (100%) diff --git a/ZSharp.AST/nodes/expr/literals/ArrayLiteral.cs b/ZSharp.AST/nodes/expr/literals/ArrayLiteral.cs new file mode 100644 index 00000000..9b99b92a --- /dev/null +++ b/ZSharp.AST/nodes/expr/literals/ArrayLiteral.cs @@ -0,0 +1,7 @@ +namespace ZSharp.AST +{ + public sealed class ArrayLiteral : Expression + { + public List Items { get; set; } = []; + } +} diff --git a/ZSharp.AST/nodes/expr/LiteralExpression.cs b/ZSharp.AST/nodes/expr/literals/LiteralExpression.cs similarity index 100% rename from ZSharp.AST/nodes/expr/LiteralExpression.cs rename to ZSharp.AST/nodes/expr/literals/LiteralExpression.cs From a25240aa7a83872bb6cf4b9ba6587780305d46c7 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 2 Feb 2025 22:34:37 +0200 Subject: [PATCH 053/235] Add index expression AST node --- ZSharp.AST/nodes/expr/call/IndexExpression.cs | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 ZSharp.AST/nodes/expr/call/IndexExpression.cs diff --git a/ZSharp.AST/nodes/expr/call/IndexExpression.cs b/ZSharp.AST/nodes/expr/call/IndexExpression.cs new file mode 100644 index 00000000..6ee83498 --- /dev/null +++ b/ZSharp.AST/nodes/expr/call/IndexExpression.cs @@ -0,0 +1,9 @@ +namespace ZSharp.AST +{ + public sealed class IndexExpression : Expression + { + public required Expression Target { get; set; } + + public List Arguments { get; set; } = []; + } +} From 5781e1aa7ec96e6027f1377b39eda416305fc0ba Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 2 Feb 2025 22:34:50 +0200 Subject: [PATCH 054/235] Add `for` statement AST node --- ZSharp.AST/nodes/stmt/flow/ForStatement.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 ZSharp.AST/nodes/stmt/flow/ForStatement.cs diff --git a/ZSharp.AST/nodes/stmt/flow/ForStatement.cs b/ZSharp.AST/nodes/stmt/flow/ForStatement.cs new file mode 100644 index 00000000..a6de96cf --- /dev/null +++ b/ZSharp.AST/nodes/stmt/flow/ForStatement.cs @@ -0,0 +1,13 @@ +namespace ZSharp.AST +{ + public sealed class ForStatement : Statement + { + public required Expression CurrentItem { get; set; } + + public required Expression Iterable { get; set; } + + public required Statement Body { get; set; } + + public Statement? Else { get; set; } + } +} From 2eedbdb50b4943302cc92441975107cfd415ad71 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 2 Feb 2025 22:35:13 +0200 Subject: [PATCH 055/235] Add array literal parser function --- .../lang/expr/LangParser.Literals.cs | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/ZSharp.Parser/lang/expr/LangParser.Literals.cs b/ZSharp.Parser/lang/expr/LangParser.Literals.cs index e549a812..d1d773e0 100644 --- a/ZSharp.Parser/lang/expr/LangParser.Literals.cs +++ b/ZSharp.Parser/lang/expr/LangParser.Literals.cs @@ -1,7 +1,28 @@ -namespace ZSharp.Parser +using ZSharp.AST; + +namespace ZSharp.Parser { public static partial class LangParser { + public static ArrayLiteral ParseArrayLiteral(Parser parser) + { + var lBracket = parser.Eat(Text.TokenType.LBracket); + + List items = []; + while (!parser.Is(Text.TokenType.RBracket)) + { + items.Add(parser.Parse()); + + if (!parser.Is(Text.TokenType.Comma, eat: true)) + break; + } + + var rBracket = parser.Eat(Text.TokenType.RBracket); + return new() + { + Items = items + }; + } } } From 3e513e3c491a918446162ff5519898f88ce0c5b2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 2 Feb 2025 22:35:31 +0200 Subject: [PATCH 056/235] Add index expression parser function --- ZSharp.Parser/lang/expr/LangParser.Index.cs | 33 +++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 ZSharp.Parser/lang/expr/LangParser.Index.cs diff --git a/ZSharp.Parser/lang/expr/LangParser.Index.cs b/ZSharp.Parser/lang/expr/LangParser.Index.cs new file mode 100644 index 00000000..556a47d2 --- /dev/null +++ b/ZSharp.Parser/lang/expr/LangParser.Index.cs @@ -0,0 +1,33 @@ +using ZSharp.AST; + +namespace ZSharp.Parser +{ + public static partial class LangParser + { + public static CallArgument ParseIndexArgument(Parser parser) + => ParseCallArgument(parser); + + public static IndexExpression ParseIndexExpression(Parser parser, Expression target) + { + var lBracker = parser.Eat(Text.TokenType.LBracket); + + List arguments = []; + + if (!parser.Is(Text.TokenType.RBracket)) + { + arguments.Add(ParseCallArgument(parser)); + + while (parser.Is(Text.TokenType.Comma, eat: true)) + arguments.Add(ParseCallArgument(parser)); + } + + var rBracket = parser.Eat(Text.TokenType.RBracket); + + return new() + { + Arguments = arguments, + Target = target, + }; + } + } +} From 98ccfea6c16f1c821e2eb310115c03644a146954 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 2 Feb 2025 22:35:49 +0200 Subject: [PATCH 057/235] Add `for` statement parser (and `in` keyword) --- ZSharp.Parser/lang/LangParser.Keywords.cs | 2 + ZSharp.Parser/lang/stmt/LangParser.For.cs | 48 +++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 ZSharp.Parser/lang/stmt/LangParser.For.cs diff --git a/ZSharp.Parser/lang/LangParser.Keywords.cs b/ZSharp.Parser/lang/LangParser.Keywords.cs index cacdfd2f..b88f233e 100644 --- a/ZSharp.Parser/lang/LangParser.Keywords.cs +++ b/ZSharp.Parser/lang/LangParser.Keywords.cs @@ -9,10 +9,12 @@ public static class Keywords public const string Case = "case"; public const string Class = "class"; public const string Else = "else"; + public const string For = "for"; public const string From = "from"; public const string Function = "fun"; public const string If = "if"; public const string Import = "import"; + public const string In = "in"; public const string Let = "let"; public const string Module = "module"; public const string New = "new"; diff --git a/ZSharp.Parser/lang/stmt/LangParser.For.cs b/ZSharp.Parser/lang/stmt/LangParser.For.cs new file mode 100644 index 00000000..8ee8dd33 --- /dev/null +++ b/ZSharp.Parser/lang/stmt/LangParser.For.cs @@ -0,0 +1,48 @@ +using ZSharp.AST; +#if !ZSHARP_MINIMAL_PARENTHESIS +using ZSharp.Text; +#endif + +namespace ZSharp.Parser +{ + public static partial class LangParser + { + public static ForStatement ParseForStatement(Parser parser) + { + parser.Eat(Keywords.For); + +#if !ZSHARP_MINIMAL_PARENTHESIS + parser.Eat(TokenType.LParen); +#endif + + var currentItem = parser.Parse(); + + var inKeyword = parser.Eat(Keywords.In); + + var iterable = parser.Parse(); + +#if !ZSHARP_MINIMAL_PARENTHESIS + parser.Eat(TokenType.RParen); +#endif + +#if ZSHARP_MINIMAL_PARENTHESIS + parser.Eat(Symbols.ThenDo); +#endif + + var @for = parser.Parse(); + + Statement? @else = null; + + if (parser.Is(Keywords.Else, eat: true)) + @else = parser.Parse(); + + return new() + { + CurrentItem = currentItem, + Iterable = iterable, + Body = @for, + Else = @else, + }; + } + } +} From c467cd7b2188fe4096c74632ca26dd92cd3407e5 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 2 Feb 2025 22:36:31 +0200 Subject: [PATCH 058/235] Add index and array literal parsers to test parser --- ZSharpTest/Main.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index 91f4bd92..b084d629 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -58,10 +58,13 @@ expressionParser.InfixL("**", 80); expressionParser.Led(TokenType.LParen, LangParser.ParseCallExpression, 100); + expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); + expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); expressionParser.Led(".", LangParser.ParseMemberAccess, 150); expressionParser.Separator(TokenType.Comma); expressionParser.Separator(TokenType.RParen); + expressionParser.Separator(TokenType.RBracket); expressionParser.Separator(TokenType.Semicolon); expressionParser.AddKeywordParser( From 60d775f72b22a97b2b6c1cf104ecb49679255019 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 2 Feb 2025 22:36:50 +0200 Subject: [PATCH 059/235] Add `for` statement parser to test parser --- ZSharpTest/Main.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index b084d629..1652d3dd 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -67,6 +67,8 @@ expressionParser.Separator(TokenType.RBracket); expressionParser.Separator(TokenType.Semicolon); + expressionParser.Separator(LangParser.Keywords.In); // until it's an operator + expressionParser.AddKeywordParser( LangParser.Keywords.While, LangParser.ParseWhileExpression @@ -82,6 +84,11 @@ LangParser.ParseIfStatement ); + statementParser.AddKeywordParser( + LangParser.Keywords.For, + LangParser.ParseForStatement + ); + //zsharpParser.Function.AddKeywordParser( // LangParser.Keywords.While, // Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) From be831f70dccf17fa6674775107a3d3335899f902 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 2 Feb 2025 22:37:06 +0200 Subject: [PATCH 060/235] Add `case` statement parser to test parser --- ZSharpTest/Main.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index 1652d3dd..a7900d97 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -89,6 +89,11 @@ LangParser.ParseForStatement ); + statementParser.AddKeywordParser( + LangParser.Keywords.Case, + LangParser.ParseCaseStatement + ); + //zsharpParser.Function.AddKeywordParser( // LangParser.Keywords.While, // Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) From 7fc28a60bca02d6abd0905709d4e56e02e14e669 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:33:56 +0200 Subject: [PATCH 061/235] Remove empty folder --- ZSharp.AST/ZSharp.AST.csproj | 4 ---- 1 file changed, 4 deletions(-) diff --git a/ZSharp.AST/ZSharp.AST.csproj b/ZSharp.AST/ZSharp.AST.csproj index 02f17bce..88c8bd4f 100644 --- a/ZSharp.AST/ZSharp.AST.csproj +++ b/ZSharp.AST/ZSharp.AST.csproj @@ -6,10 +6,6 @@ enable - - - - From 739f5285df9adc65abfa51d12d28b8db10a2e62a Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:34:19 +0200 Subject: [PATCH 062/235] Update constructor node to be an expression --- ZSharp.AST/nodes/def/oop/Constructor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.AST/nodes/def/oop/Constructor.cs b/ZSharp.AST/nodes/def/oop/Constructor.cs index 1d6bb6d4..6612c455 100644 --- a/ZSharp.AST/nodes/def/oop/Constructor.cs +++ b/ZSharp.AST/nodes/def/oop/Constructor.cs @@ -1,6 +1,6 @@ namespace ZSharp.AST { - public sealed class Constructor(ConstructorTokens tokens) : Statement(tokens) + public sealed class Constructor(ConstructorTokens tokens) : Expression(tokens) { public new ConstructorTokens TokenInfo { From f2484803be408413c90a4be62458a133ef66bf43 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:34:50 +0200 Subject: [PATCH 063/235] Add IR module initializer --- ZSharp.IR/ir/modular/module/Module.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/ZSharp.IR/ir/modular/module/Module.cs b/ZSharp.IR/ir/modular/module/Module.cs index 5d2a5e38..f5f0d022 100644 --- a/ZSharp.IR/ir/modular/module/Module.cs +++ b/ZSharp.IR/ir/modular/module/Module.cs @@ -4,6 +4,7 @@ namespace ZSharp.IR { public sealed class Module(string? name) : ModuleMember { + private Function? _initializer; private ModuleCollection? _importedModules; private ModuleCollection? _functions; private GlobalCollection? _globals; @@ -14,6 +15,22 @@ public sealed class Module(string? name) : ModuleMember public ModuleAttributes Attributes { get; set; } = ModuleAttributes.None; + public Function? Initializer + { + get => _initializer; + set + { + if (value is not null) + { + if (value.Owner is null) + Functions.Add(value); + else if (value.Owner != this) + throw new InvalidOperationException("Module initializer cannot reside in a different module."); + _initializer = value; + } + } + } + public Collection ImportedModules { get From 8d95eb06d34ac0b6f1d9b7b781b440fd5d56b12d Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:35:19 +0200 Subject: [PATCH 064/235] Make IR constructor an IR object --- ZSharp.IR/ir/oop/Constructor.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ZSharp.IR/ir/oop/Constructor.cs b/ZSharp.IR/ir/oop/Constructor.cs index 2becbdb2..fd941b3c 100644 --- a/ZSharp.IR/ir/oop/Constructor.cs +++ b/ZSharp.IR/ir/oop/Constructor.cs @@ -1,7 +1,10 @@ namespace ZSharp.IR { public sealed class Constructor(string? name) + : IRObject { + public override Module? Module => Method.Module; + public string? Name { get; set; } = name; public Method Method { get; set; } From 51ffa719ab9a00284a28c4d5b13fc69c7908dc1e Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:36:24 +0200 Subject: [PATCH 065/235] Fix constructor parser to wrap it in statement --- ZSharp.Parser/parsers/oop/ClassParser.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.Parser/parsers/oop/ClassParser.cs b/ZSharp.Parser/parsers/oop/ClassParser.cs index ca195aaf..4aa1578a 100644 --- a/ZSharp.Parser/parsers/oop/ClassParser.cs +++ b/ZSharp.Parser/parsers/oop/ClassParser.cs @@ -22,7 +22,7 @@ public ClassParser() ); AddKeywordParser( LangParser.Keywords.New, - Constructor.Parse + Utils.DefinitionStatement(Constructor.Parse) ); } From d113b4b7ed7dc16ec579f3bced56c47eb75b0a69 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:36:49 +0200 Subject: [PATCH 066/235] Remove unused classes --- ZSharp.ZSSourceCompiler/objects/LateCompileIRCode.cs | 12 ------------ ZSharp.ZSSourceCompiler/objects/ObjectWrapper.cs | 7 ------- 2 files changed, 19 deletions(-) delete mode 100644 ZSharp.ZSSourceCompiler/objects/LateCompileIRCode.cs delete mode 100644 ZSharp.ZSSourceCompiler/objects/ObjectWrapper.cs diff --git a/ZSharp.ZSSourceCompiler/objects/LateCompileIRCode.cs b/ZSharp.ZSSourceCompiler/objects/LateCompileIRCode.cs deleted file mode 100644 index 42f508b3..00000000 --- a/ZSharp.ZSSourceCompiler/objects/LateCompileIRCode.cs +++ /dev/null @@ -1,12 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.ZSSourceCompiler -{ - internal sealed class LateCompileIRCode(Func callback) - : CompilerObject - , ICompileIRCode - { - public IRCode CompileIRCode(Compiler.Compiler compiler) - => callback(compiler); - } -} diff --git a/ZSharp.ZSSourceCompiler/objects/ObjectWrapper.cs b/ZSharp.ZSSourceCompiler/objects/ObjectWrapper.cs deleted file mode 100644 index 085155ce..00000000 --- a/ZSharp.ZSSourceCompiler/objects/ObjectWrapper.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.ZSSourceCompiler -{ - internal class ObjectWrapper : CompilerObject - { - public CompilerObject? Object { get; set; } - } -} From 85c6ad18944a16d5b886d4356eb5edae7eb0ee07 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:37:48 +0200 Subject: [PATCH 067/235] Use evaluate when compiling callee in call expression --- .../core-compilers/expression/ExpressionCompiler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index a4ff4039..55ec57fc 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -53,7 +53,7 @@ private CompilerObject Compile(BinaryExpression binary) private CompilerObject Compile(CallExpression call) { - var callable = Compiler.CompileNode(call.Callee); + var callable = Compiler.Compiler.Evaluate(Compiler.CompileNode(call.Callee)); var args = call.Arguments.Select(arg => new Compiler.Argument(arg.Name, Compiler.CompileNode(arg.Value))); From ce8df5a62b3b95b7e885c9b72b072030780b2ae5 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:38:14 +0200 Subject: [PATCH 068/235] Add `case` CO --- .../runtime code/objects/Case.cs | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/Case.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/Case.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/Case.cs new file mode 100644 index 00000000..163cfbcd --- /dev/null +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/Case.cs @@ -0,0 +1,87 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class Case + : CompilerObject + , ICompileIRCode + { + public sealed class When + : CompilerObject + { + public required CompilerObject Value { get; set; } + + public required CompilerObject Body { get; set; } + } + + public required CompilerObject Value { get; set; } + + public required CompilerObject Of { get; set; } + + public List Clauses { get; } = []; + + public CompilerObject? Else { get; set; } + + public IRCode CompileIRCode(Compiler.Compiler compiler) + { + IRCode result = new(); + + var caseEnd = new IR.VM.Nop(); + + var valueCode = compiler.CompileIRCode(Value); + result.Append(valueCode); + + IRCode clauseBodies = new(); + + foreach (var clause in Clauses) + { + var entry = new IR.VM.Pop(); + + clauseBodies.Instructions.AddRange([ + entry, + //new IR.VM.Pop(), + ..compiler.CompileIRCode(clause.Body).Instructions, + new IR.VM.Jump(caseEnd) + ]); + + var condition = compiler.Call(Of, [ + new(new RawCode( + new([ + new IR.VM.Dup() + ]) { + Types = [valueCode.RequireValueType()] + } + //compiler.CompileIRCode(Value) + )), + new(clause.Value) + ]); + + result.Instructions.AddRange([ + ..compiler.CompileIRCode(condition).Instructions, + new IR.VM.JumpIfTrue(entry) + ]); + } + + result.Instructions.Add(new IR.VM.Pop()); + result.Types.RemoveAt(result.Types.Count - 1); + + if (Else is not null) + { + var entry = new IR.VM.Nop(); + + var elseCode = compiler.CompileIRCode(Else); + + clauseBodies.Instructions.Add(entry); + clauseBodies.Append(elseCode); + + result.Instructions.Add(new IR.VM.Jump(entry)); + } + + result.Append(clauseBodies); + + result.Instructions.Add(caseEnd); + + return result; + } + } +} From e163aeae0a92db7f2ee953648bd352e1700ab713 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:38:36 +0200 Subject: [PATCH 069/235] Add support for compiling case statements --- .../statement/StatementCompiler.cs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs index 367cc1c4..04c31967 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs @@ -7,6 +7,7 @@ public sealed class StatementCompiler(ZSSourceCompiler compiler) => statement switch { BlockStatement block => Compile(block), + CaseStatement @case => Compile(@case), ExpressionStatement expressionStatement => Compile(expressionStatement), IfStatement @if => Compile(@if), ImportStatement import => Compile(import), @@ -50,6 +51,29 @@ private CompilerObject Compile(ExpressionStatement expressionStatement) return new Objects.RawCode(result); } + private CompilerObject Compile(CaseStatement @case) + { + var result = new Objects.Case() + { + Of = @case.Of is null ? Compiler.Operators.Cache("==")! : Compiler.CompileNode(@case.Of), + Value = @case.Value is null ? Compiler.Compiler.CreateTrue() : Compiler.CompileNode(@case.Value), + Else = @case.Else is null ? null : Compiler.CompileNode(@case.Else), + }; + + foreach (var whenClause in @case.WhenClauses) + { + var clause = new Objects.Case.When() + { + Body = Compiler.CompileNode(whenClause.Body ?? throw new()), + Value = Compiler.CompileNode(whenClause.Value) + }; + + result.Clauses.Add(clause); + } + + return result; + } + private CompilerObject Compile(IfStatement @if) { var result = new Objects.If() From d7e3fc11fd170becbb36746e71d495a91f94060a Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:40:55 +0200 Subject: [PATCH 070/235] Add lots of objects --- ZSharp.Compiler.Objects/GlobalUsings.cs | 5 + .../generic/GenericParameter.cs | 8 ++ .../literals/ArrayLiteral.cs | 8 ++ ZSharp.Compiler.Objects/oop/Class.cs | 9 ++ .../oop/Constructor.cs | 81 +++++++++++- ZSharp.Compiler.Objects/oop/GenericClass.cs | 118 ++++++++++++++++++ .../oop/GenericClassInstance.cs | 64 ++++++++++ ZSharp.Compiler.Objects/oop/Implementation.cs | 16 +++ .../oop/extensibility/IAbstraction.cs | 9 ++ .../oop/extensibility/IClass.cs | 11 ++ .../oop/field/BoundField.cs | 0 .../oop/field/Field.cs | 20 +++ .../oop/meta/ClassMetaClass.cs | 39 ++++++ ZSharp.Compiler.Objects/oop/meta/ClassSpec.cs | 12 ++ .../oop/meta/ClassSpecBuilder.cs | 20 +++ .../oop/method/BoundMethod.cs | 0 .../oop/method/Method.cs | 80 +++++++++++- .../referencing/IReferencable.cs | 7 ++ .../referencing/IReference.cs | 9 ++ .../referencing/ReferenceContext.cs | 14 +++ .../utils/RuntimeHelpers.cs | 10 ++ .../functional/signature/Parameter.cs | 6 +- ZSharp.Compiler/cg objects/modular/Module.cs | 19 +++ .../cg objects/oop/class/IClass.cs | 13 -- .../features/compile-time values/Array.cs | 7 -- .../features/oop/extensibility/IClass.cs | 9 -- .../features/oop/extensibility/IMetaClass.cs | 39 ------ .../features/oop/objects/class/Class.cs | 48 ------- .../features/oop/objects/class/ClassBase.cs | 8 -- .../features/oop/objects/class/ClassMeta.cs | 60 --------- 30 files changed, 555 insertions(+), 194 deletions(-) create mode 100644 ZSharp.Compiler.Objects/GlobalUsings.cs create mode 100644 ZSharp.Compiler.Objects/generic/GenericParameter.cs create mode 100644 ZSharp.Compiler.Objects/literals/ArrayLiteral.cs create mode 100644 ZSharp.Compiler.Objects/oop/Class.cs rename {ZSharp.Compiler/cg objects => ZSharp.Compiler.Objects}/oop/Constructor.cs (50%) create mode 100644 ZSharp.Compiler.Objects/oop/GenericClass.cs create mode 100644 ZSharp.Compiler.Objects/oop/GenericClassInstance.cs create mode 100644 ZSharp.Compiler.Objects/oop/Implementation.cs create mode 100644 ZSharp.Compiler.Objects/oop/extensibility/IAbstraction.cs create mode 100644 ZSharp.Compiler.Objects/oop/extensibility/IClass.cs rename {ZSharp.Compiler/cg objects => ZSharp.Compiler.Objects}/oop/field/BoundField.cs (100%) rename {ZSharp.Compiler/cg objects => ZSharp.Compiler.Objects}/oop/field/Field.cs (53%) create mode 100644 ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs create mode 100644 ZSharp.Compiler.Objects/oop/meta/ClassSpec.cs create mode 100644 ZSharp.Compiler.Objects/oop/meta/ClassSpecBuilder.cs rename {ZSharp.Compiler/cg objects => ZSharp.Compiler.Objects}/oop/method/BoundMethod.cs (100%) rename {ZSharp.Compiler/cg objects => ZSharp.Compiler.Objects}/oop/method/Method.cs (50%) create mode 100644 ZSharp.Compiler.Objects/referencing/IReferencable.cs create mode 100644 ZSharp.Compiler.Objects/referencing/IReference.cs create mode 100644 ZSharp.Compiler.Objects/referencing/ReferenceContext.cs create mode 100644 ZSharp.Compiler.Objects/utils/RuntimeHelpers.cs delete mode 100644 ZSharp.Compiler/cg objects/oop/class/IClass.cs delete mode 100644 ZSharp.Compiler/features/compile-time values/Array.cs delete mode 100644 ZSharp.Compiler/features/oop/extensibility/IClass.cs delete mode 100644 ZSharp.Compiler/features/oop/extensibility/IMetaClass.cs delete mode 100644 ZSharp.Compiler/features/oop/objects/class/Class.cs delete mode 100644 ZSharp.Compiler/features/oop/objects/class/ClassBase.cs delete mode 100644 ZSharp.Compiler/features/oop/objects/class/ClassMeta.cs diff --git a/ZSharp.Compiler.Objects/GlobalUsings.cs b/ZSharp.Compiler.Objects/GlobalUsings.cs new file mode 100644 index 00000000..92daf4d2 --- /dev/null +++ b/ZSharp.Compiler.Objects/GlobalUsings.cs @@ -0,0 +1,5 @@ +global using MemberName = string; +global using MemberIndex = int; + +global using Args = CommonZ.Utils.Collection; +global using KwArgs = CommonZ.Utils.Mapping; diff --git a/ZSharp.Compiler.Objects/generic/GenericParameter.cs b/ZSharp.Compiler.Objects/generic/GenericParameter.cs new file mode 100644 index 00000000..b79f5602 --- /dev/null +++ b/ZSharp.Compiler.Objects/generic/GenericParameter.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Objects +{ + public sealed class GenericParameter + : CompilerObject + { + public string Name { get; set; } = string.Empty; + } +} diff --git a/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs b/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs new file mode 100644 index 00000000..b2e2a710 --- /dev/null +++ b/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Objects +{ + public sealed class ArrayLiteral(IEnumerable? items = null) + : CompilerObject + { + public List Items { get; } = new(items ?? []); + } +} diff --git a/ZSharp.Compiler.Objects/oop/Class.cs b/ZSharp.Compiler.Objects/oop/Class.cs new file mode 100644 index 00000000..8e456f3f --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/Class.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Objects +{ + public abstract class Class(Compiler.Compiler compiler, ClassSpec spec) + { + public abstract string Name { get; } + + public abstract Class Base { get; } + } +} diff --git a/ZSharp.Compiler/cg objects/oop/Constructor.cs b/ZSharp.Compiler.Objects/oop/Constructor.cs similarity index 50% rename from ZSharp.Compiler/cg objects/oop/Constructor.cs rename to ZSharp.Compiler.Objects/oop/Constructor.cs index 34761860..87f0ec76 100644 --- a/ZSharp.Compiler/cg objects/oop/Constructor.cs +++ b/ZSharp.Compiler.Objects/oop/Constructor.cs @@ -5,14 +5,28 @@ namespace ZSharp.Objects public sealed class Constructor(string? name) : CompilerObject , ICTCallable + , ICompileIRObject { + [Flags] + enum BuildState + { + None = 0, + Signature = 0b1, + Body = 0b10, + Owner = 0b100, + } + + private readonly ObjectBuildState state = new(); + public IR.Constructor? IR { get; set; } public string? Name { get; set; } = name; public Signature Signature { get; set; } = new(); - public Class? Owner { get; set; } + public GenericClass? Owner { get; set; } + + public CompilerObject? Body { get; set; } public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) { @@ -25,6 +39,24 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) { // TODO: type checking (when type system is implemented) + IR.VM.Instruction invocationInstruction; + + if (kwArgs.ContainsKey(Signature.Args[0].Name)) + { + invocationInstruction = new IR.VM.Call(IR!.Method); + } + else + { + if (Owner is null) + throw new(); + + invocationInstruction = new IR.VM.CreateInstance(IR!); + args.Insert(0, new RawCode(new() + { + Types = [Owner] + })); + } + IRCode argsCode = new(), varArgsCode = new(), kwArgsCode = new(), varKwArgsCode = new(); @@ -57,10 +89,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) result.Append(kwArgsCode); result.Append(varKwArgsCode); // should be empty - if (kwArgs.ContainsKey(Signature.Args[0].Name)) - result.Instructions.Add(new IR.VM.Call(IR!.Method)); - else - result.Instructions.Add(new IR.VM.CreateInstance(IR!)); + result.Instructions.Add(invocationInstruction); result.Types.Clear(); result.Types.Add(Owner ?? throw new()); @@ -69,5 +98,47 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) return new RawCode(result); } + + IR.Constructor ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) + { + IR ??= new(Name) + { + Method = new(compiler.RuntimeModule.TypeSystem.Void) + }; + + if (owner is not null && !state.Get(BuildState.Owner)) + { + owner.Constructors.Add(IR); + owner.Methods.Add(IR.Method); + + state.Set(BuildState.Owner); + } + + if (!state.Get(BuildState.Signature)) + { + foreach (var arg in Signature.Args) + IR.Method.Signature.Args.Parameters.Add(compiler.CompileIRObject(arg, IR.Method.Signature)); + + if (Signature.VarArgs is not null) + IR.Method.Signature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, IR.Method.Signature); + + foreach (var kwArg in Signature.KwArgs) + IR.Method.Signature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, IR.Method.Signature)); + + if (Signature.VarKwArgs is not null) + IR.Method.Signature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, IR.Method.Signature); + + state.Set(BuildState.Signature); + } + + if (Body is not null && !state.Get(BuildState.Body)) + { + IR.Method.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); + + state.Set(BuildState.Body); + } + + return IR; + } } } diff --git a/ZSharp.Compiler.Objects/oop/GenericClass.cs b/ZSharp.Compiler.Objects/oop/GenericClass.cs new file mode 100644 index 00000000..b66ea25e --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/GenericClass.cs @@ -0,0 +1,118 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public class GenericClass + : CompilerObject + , ICTGetMember + , IRTGetMember + , IReferencable + , ICompileIRObject + , IEvaluable + { + [Flags] + enum BuildState + { + None = 0, + Base = 0b1, + Interfaces = 0b10, + Body = 0b100, + Owner = 0b1000, + } + private readonly ObjectBuildState state = new(); + + public IR.ConstructedClass? IR { get; set; } + + public string Name { get; set; } + + public Collection GenericParameters { get; set; } = []; + + public GenericClassInstance? Base { get; set; } + + public Mapping Implementations { get; set; } = []; + + public CompilerObject Constructor { get; set; } + + public Collection Content { get; } = []; + + public Mapping Members { get; } = []; + + public CompilerObject Member(Compiler.Compiler compiler, MemberName member) + => Members[member]; + + public CompilerObject CreateReference(Compiler.Compiler compiler, ReferenceContext context) + { + int currentErrors = compiler.Log.Logs.Count(l => l.Level == LogLevel.Error); + + foreach (var genericParameter in GenericParameters) + if (!context.CompileTimeValues.ContainsKey(genericParameter)) + compiler.Log.Error( + $"Missing generic argument for parameter {genericParameter.Name} in type {this.Name}", + this + ); + + if (compiler.Log.Logs.Count(l => l.Level == LogLevel.Error) > currentErrors) + throw new(); // TODO: Huh??? + + Mapping genericArguments = []; + + foreach (var genericParameter in GenericParameters) + genericArguments[genericParameter] = context.CompileTimeValues[genericParameter]; + + return new GenericClassInstance(this, genericArguments) + { + Context = context, + }; + } + + IR.Class ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) + { + IR.Class @class = IR?.Class ?? new(Name); + + IR ??= new(@class); + + if (owner is not null && !state.Get(BuildState.Owner)) + { + owner.Types.Add(@class!); + + state.Set(BuildState.Owner); + } + + if (Base is not null && !state.Get(BuildState.Base)) + { + state.Set(BuildState.Base); + + @class.Base = compiler.CompileIRType(Base); + } + + if (Content.Count > 0 && !state.Get(BuildState.Body)) + { + state.Set(BuildState.Body); + + foreach (var item in Content) + compiler.CompileIRObject(item, @class); + } + + return @class; + } + + CompilerObject IEvaluable.Evaluate(Compiler.Compiler compiler) + { + if (GenericParameters.Count != 0) + return this; + + return new GenericClassInstance(this, []); + } + + CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerObject value, string member) + { + var memberObject = compiler.Member(this, member); + + if (memberObject is IRTBoundMember boundMember) + return boundMember.Bind(compiler, value); + + return memberObject; + } + } +} diff --git a/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs new file mode 100644 index 00000000..879704f7 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs @@ -0,0 +1,64 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class GenericClassInstance( + GenericClass origin, + Mapping genericArguments + ) + : CompilerObject + , ICTGetMember + , ICTCallable + , IReference + , ICompileIRType + { + CompilerObject IReference.Origin => Origin; + + public ReferenceContext? Context { get; set; } = null; + + public GenericClass Origin { get; set; } = origin; + + public Mapping Arguments { get; set; } = genericArguments; + + public Mapping Members { get; set; } = []; + + public CompilerObject Member(Compiler.Compiler compiler, string member) + { + if (Members.ContainsKey(member)) return Members[member]; + + var origin = compiler.Member(Origin, member); + + if (Arguments.Count != 0) + //origin = compiler.CreateReference(origin, Context); + throw new NotImplementedException(); + + return Members[member] = origin; + } + + IR.ConstructedClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) + { + var result = new IR.ConstructedClass( + compiler.CompileIRObject(Origin, null) + ); + + foreach (var parameter in Origin.GenericParameters) + result.Arguments.Add(compiler.CompileIRType(Arguments[parameter])); + + return result; + } + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + CompilerObject? constructor = null; + + if (Origin.GenericParameters.Count == 0) + constructor = Origin.Constructor; + + if (constructor is null) + throw new NotImplementedException(); + + return compiler.Call(constructor, arguments); + } + } +} diff --git a/ZSharp.Compiler.Objects/oop/Implementation.cs b/ZSharp.Compiler.Objects/oop/Implementation.cs new file mode 100644 index 00000000..2eb91211 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/Implementation.cs @@ -0,0 +1,16 @@ +using CommonZ.Utils; + +namespace ZSharp.Objects +{ + public sealed class Implementation( + CompilerObject @abstract, + CompilerObject concrete + ) + { + public Mapping Mapping { get; } = []; + + public CompilerObject Abstract { get; } = @abstract; + + public CompilerObject Concrete { get; } = concrete; + } +} diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IAbstraction.cs b/ZSharp.Compiler.Objects/oop/extensibility/IAbstraction.cs new file mode 100644 index 00000000..b78ad662 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/extensibility/IAbstraction.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Objects +{ + public interface IAbstraction + { + public virtual void OnDerivation(CompilerObject derived) { } + + public virtual void OnImplementation(CompilerObject implementor) { } + } +} diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IClass.cs b/ZSharp.Compiler.Objects/oop/extensibility/IClass.cs new file mode 100644 index 00000000..aa8096ca --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/extensibility/IClass.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Objects +{ + public interface IClass + { + public string Name { get; set; } + + public IClass? Base { get; set; } + + public virtual void OnDerivation(IClass derived) { } + } +} diff --git a/ZSharp.Compiler/cg objects/oop/field/BoundField.cs b/ZSharp.Compiler.Objects/oop/field/BoundField.cs similarity index 100% rename from ZSharp.Compiler/cg objects/oop/field/BoundField.cs rename to ZSharp.Compiler.Objects/oop/field/BoundField.cs diff --git a/ZSharp.Compiler/cg objects/oop/field/Field.cs b/ZSharp.Compiler.Objects/oop/field/Field.cs similarity index 53% rename from ZSharp.Compiler/cg objects/oop/field/Field.cs rename to ZSharp.Compiler.Objects/oop/field/Field.cs index 00a413c9..b3421b44 100644 --- a/ZSharp.Compiler/cg objects/oop/field/Field.cs +++ b/ZSharp.Compiler.Objects/oop/field/Field.cs @@ -6,6 +6,7 @@ public sealed class Field(string name) : CompilerObject , ICTReadable , IRTBoundMember + , ICompileIRObject { public IR.Field? IR { get; set; } @@ -15,6 +16,8 @@ public sealed class Field(string name) public CompilerObject? Type { get; set; } + public bool IsReadOnly { get; set; } + public CompilerObject Bind(Compiler.Compiler compiler, CompilerObject value) => new BoundField(this, value); @@ -22,5 +25,22 @@ public IRCode Read(Compiler.Compiler compiler) { throw new NotImplementedException(); } + + IR.Field ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) + { + if (IR is not null) + { + if (owner is not null && IR.Owner is null) + owner.Fields.Add(IR); + + return IR; + } + + IR = new(Name, compiler.CompileIRType(Type ?? throw new())); + + owner?.Fields.Add(IR); + + return IR; + } } } diff --git a/ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs b/ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs new file mode 100644 index 00000000..a98a8425 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs @@ -0,0 +1,39 @@ +using System.Xml.Linq; + +namespace ZSharp.Objects +{ + public sealed class ClassMetaClass + : CompilerObject + { + public GenericClass CreateClass(Compiler.Compiler compiler) + { + return new(); + } + + public void ConstructClass( + Compiler.Compiler compiler, + GenericClass @class, + ClassSpec spec + ) + { + @class.Name = spec.Name; + @class.Content.AddRange(spec.Content); + + var bases = spec.Bases; + + if (bases.Length > 0) + { + int interfacesIndex = 0; + if (bases[0] is GenericClassInstance) + @class.Base = (GenericClassInstance)bases[interfacesIndex++]; + + //for (; interfacesIndex < bases.Length; interfacesIndex++) + // if (bases[interfacesIndex] is not IAbstraction @abstract) + // throw new(); + // else Implementations[bases[interfacesIndex]] = new(@abstract, this); + } + + + } + } +} diff --git a/ZSharp.Compiler.Objects/oop/meta/ClassSpec.cs b/ZSharp.Compiler.Objects/oop/meta/ClassSpec.cs new file mode 100644 index 00000000..f71c8bbd --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/meta/ClassSpec.cs @@ -0,0 +1,12 @@ +namespace ZSharp.Objects +{ + public sealed class ClassSpec + : CompilerObject + { + public string Name { get; set; } = string.Empty; + + public CompilerObject[] Bases { get; set; } = []; + + public CompilerObject[] Content { get; set; } = []; + } +} diff --git a/ZSharp.Compiler.Objects/oop/meta/ClassSpecBuilder.cs b/ZSharp.Compiler.Objects/oop/meta/ClassSpecBuilder.cs new file mode 100644 index 00000000..5c72914b --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/meta/ClassSpecBuilder.cs @@ -0,0 +1,20 @@ +namespace ZSharp.Objects +{ + public sealed class ClassSpecBuilder + : CompilerObject + { + public string Name { get; set; } = string.Empty; + + public List Bases { get; } = []; + + public List Content { get; } = []; + + public ClassSpec CreateSpec() + => new() + { + Name = Name, + Bases = [.. Bases], + Content = [.. Content], + }; + } +} diff --git a/ZSharp.Compiler/cg objects/oop/method/BoundMethod.cs b/ZSharp.Compiler.Objects/oop/method/BoundMethod.cs similarity index 100% rename from ZSharp.Compiler/cg objects/oop/method/BoundMethod.cs rename to ZSharp.Compiler.Objects/oop/method/BoundMethod.cs diff --git a/ZSharp.Compiler/cg objects/oop/method/Method.cs b/ZSharp.Compiler.Objects/oop/method/Method.cs similarity index 50% rename from ZSharp.Compiler/cg objects/oop/method/Method.cs rename to ZSharp.Compiler.Objects/oop/method/Method.cs index 670aa62a..93fbc04c 100644 --- a/ZSharp.Compiler/cg objects/oop/method/Method.cs +++ b/ZSharp.Compiler.Objects/oop/method/Method.cs @@ -1,4 +1,5 @@ -using ZSharp.Compiler; +using System.Diagnostics.CodeAnalysis; +using ZSharp.Compiler; namespace ZSharp.Objects { @@ -6,7 +7,19 @@ public sealed class Method(string? name) : CompilerObject , IRTBoundMember , ICTCallable + , ICompileIRObject { + [Flags] + enum BuildState + { + None = 0, + Signature = 0b1, + Body = 0b10, + Owner = 0b100, + } + + private readonly ObjectBuildState state = new(); + public IR.Method? IR { get; set; } public string? Name { get; set; } = name; @@ -15,6 +28,8 @@ public sealed class Method(string? name) public CompilerObject? ReturnType { get; set; } + public CompilerObject? Body { get; set; } + public CompilerObject Bind(Compiler.Compiler compiler, CompilerObject value) => new BoundMethod(this, value); @@ -22,7 +37,14 @@ public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) { var (args, kwargs) = Utils.SplitArguments(arguments); - return Call(compiler, args, kwargs); + try + { + return Call(compiler, args, kwargs); + } + catch + { + throw new ArgumentMismatchException(this, arguments); + } } public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) @@ -64,11 +86,63 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) result.Instructions.Add(new IR.VM.Call(IR!)); result.Types.Clear(); - result.Types.Add(ReturnType ?? throw new()); + if (ReturnType != compiler.TypeSystem.Void) + result.Types.Add(ReturnType!); result.MaxStackSize = Math.Max(result.MaxStackSize, result.Types.Count); return new RawCode(result); } + + [MemberNotNull(nameof(ReturnType))] + public IR.Method CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) + { + IR ??= + new( + compiler.CompileIRType( + ReturnType ?? throw new PartiallyCompiledObjectException( + this, + Errors.UndefinedReturnType(Name) + ) + ) + ) + { + Name = Name, + IsInstance = true, + }; + + if (owner is not null && !state.Get(BuildState.Owner)) + { + state.Set(BuildState.Owner); + + owner.Methods.Add(IR); + } + + if (!state.Get(BuildState.Signature)) + { + state.Set(BuildState.Signature); + + foreach (var arg in Signature.Args) + IR.Signature.Args.Parameters.Add(compiler.CompileIRObject(arg, IR.Signature)); + + if (Signature.VarArgs is not null) + IR.Signature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, IR.Signature); + + foreach (var kwArg in Signature.KwArgs) + IR.Signature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, IR.Signature)); + + if (Signature.VarKwArgs is not null) + IR.Signature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, IR.Signature); + } + + if (Body is not null && !state.Get(BuildState.Body)) + { + state.Set(BuildState.Body); + + IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); + } + + return IR; + } } } diff --git a/ZSharp.Compiler.Objects/referencing/IReferencable.cs b/ZSharp.Compiler.Objects/referencing/IReferencable.cs new file mode 100644 index 00000000..7f986c64 --- /dev/null +++ b/ZSharp.Compiler.Objects/referencing/IReferencable.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Objects +{ + public interface IReferencable + { + public CompilerObject CreateReference(Compiler.Compiler compiler, ReferenceContext context); + } +} diff --git a/ZSharp.Compiler.Objects/referencing/IReference.cs b/ZSharp.Compiler.Objects/referencing/IReference.cs new file mode 100644 index 00000000..6817cb0c --- /dev/null +++ b/ZSharp.Compiler.Objects/referencing/IReference.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Objects +{ + public interface IReference + { + public CompilerObject Origin { get; } + + public ReferenceContext? Context { get; set; } + } +} diff --git a/ZSharp.Compiler.Objects/referencing/ReferenceContext.cs b/ZSharp.Compiler.Objects/referencing/ReferenceContext.cs new file mode 100644 index 00000000..1fb3e0d2 --- /dev/null +++ b/ZSharp.Compiler.Objects/referencing/ReferenceContext.cs @@ -0,0 +1,14 @@ +using CommonZ.Utils; + +namespace ZSharp.Objects +{ + public sealed class ReferenceContext + { + public Mapping CompileTimeValues { get; set; } = []; + + public static ReferenceContext Empty { get; } = new() + { + CompileTimeValues = [] + }; + } +} diff --git a/ZSharp.Compiler.Objects/utils/RuntimeHelpers.cs b/ZSharp.Compiler.Objects/utils/RuntimeHelpers.cs new file mode 100644 index 00000000..a9d6fced --- /dev/null +++ b/ZSharp.Compiler.Objects/utils/RuntimeHelpers.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Objects +{ + internal static class RuntimeHelpers + { + public static T GetUninitializedObject() + => (T)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject( + typeof(T) + ); + } +} diff --git a/ZSharp.Compiler/cg objects/functional/signature/Parameter.cs b/ZSharp.Compiler/cg objects/functional/signature/Parameter.cs index 08e8101e..882d24db 100644 --- a/ZSharp.Compiler/cg objects/functional/signature/Parameter.cs +++ b/ZSharp.Compiler/cg objects/functional/signature/Parameter.cs @@ -20,14 +20,16 @@ public IR.Parameter CompileIRObject(Compiler.Compiler compiler, IR.Signature? ow if (Type is null) throw new("Parameter type not set."); - IR ??= new(Name, compiler.CompileIRType(Type)); + IR ??= new(Name, compiler.RuntimeModule.TypeSystem.Void); + if (IR.Type == compiler.RuntimeModule.TypeSystem.Void) + IR.Type = compiler.CompileIRType(Type); return IR; } public IRCode Read(Compiler.Compiler compiler) => new([ - new IR.VM.GetArgument(IR!), + new IR.VM.GetArgument(IR ?? compiler.CompileIRObject(this, null)), ]) { MaxStackSize = 1, diff --git a/ZSharp.Compiler/cg objects/modular/Module.cs b/ZSharp.Compiler/cg objects/modular/Module.cs index fd1a1723..fc23bd9d 100644 --- a/ZSharp.Compiler/cg objects/modular/Module.cs +++ b/ZSharp.Compiler/cg objects/modular/Module.cs @@ -46,6 +46,25 @@ public IR.Module CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) foreach (var item in Content) compiler.CompileIRObject(item, IR); + if (IR.HasGlobals) + { + // TODO: initialize according to dependency order + + var initializer = IR.Initializer = new(compiler.RuntimeModule.TypeSystem.Void) + { + Name = "" + }; + + foreach (var global in IR.Globals) + if (global.Initializer is not null) + initializer.Body.Instructions.AddRange([ + .. global.Initializer, + new IR.VM.SetGlobal(global), + ]); + + initializer.Body.Instructions.Add(new IR.VM.Return()); + } + return IR; } } diff --git a/ZSharp.Compiler/cg objects/oop/class/IClass.cs b/ZSharp.Compiler/cg objects/oop/class/IClass.cs deleted file mode 100644 index 2e57d2e5..00000000 --- a/ZSharp.Compiler/cg objects/oop/class/IClass.cs +++ /dev/null @@ -1,13 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Objects -{ - public interface IClass - { - public string? Name { get; } - - public IClass? Base { get; } - - //public Collection InterfaceImplementations { get; } - } -} diff --git a/ZSharp.Compiler/features/compile-time values/Array.cs b/ZSharp.Compiler/features/compile-time values/Array.cs deleted file mode 100644 index 10c40035..00000000 --- a/ZSharp.Compiler/features/compile-time values/Array.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Objects -{ - public sealed class Array - { - - } -} diff --git a/ZSharp.Compiler/features/oop/extensibility/IClass.cs b/ZSharp.Compiler/features/oop/extensibility/IClass.cs deleted file mode 100644 index d62ce67f..00000000 --- a/ZSharp.Compiler/features/oop/extensibility/IClass.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Compiler -{ - internal interface IClass - { - public CompilerObject Meta { get; } - - public string Name { get; } - } -} diff --git a/ZSharp.Compiler/features/oop/extensibility/IMetaClass.cs b/ZSharp.Compiler/features/oop/extensibility/IMetaClass.cs deleted file mode 100644 index 47ec116f..00000000 --- a/ZSharp.Compiler/features/oop/extensibility/IMetaClass.cs +++ /dev/null @@ -1,39 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public interface IMetaClass : ICTCallable - { - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (arguments.Length != 3) - throw new($"Metaclass may only be called with exactly 3 arguments"); - - foreach (var argument in arguments) - if (argument.Name is not null) - throw new($"Metaclass's arguments must not have names"); - - if (!compiler.IsCTValue(arguments[0].Object, out var name)) - throw new($"Metaclass's first argument must be a string literal"); - - if (!compiler.IsCTValue(arguments[1].Object, out var bases)) - throw new($"Metaclass's second argument must be an array of bases"); - - if (!compiler.IsCTValue(arguments[2].Object, out var content)) - throw new($"Metaclass's third argument must be an array of content"); - - return Construct(compiler, name, bases, content); - } - - public CompilerObject Construct(Compiler.Compiler compiler, string name, CompilerObject[] bases, CompilerObject[]? content); - } - - public interface IMetaClass : IMetaClass - where T : CompilerObject - { - CompilerObject IMetaClass.Construct(Compiler.Compiler compiler, string name, CompilerObject[] bases, CompilerObject[]? content) - => Construct(compiler, name, bases, content); - - public new T Construct(Compiler.Compiler compiler, string name, CompilerObject[] bases, CompilerObject[]? content); - } -} diff --git a/ZSharp.Compiler/features/oop/objects/class/Class.cs b/ZSharp.Compiler/features/oop/objects/class/Class.cs deleted file mode 100644 index 728db12a..00000000 --- a/ZSharp.Compiler/features/oop/objects/class/Class.cs +++ /dev/null @@ -1,48 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Class - : CompilerObject - , ICTGetMember - , IRTGetMember - , ICTCallable - { - public Mapping Members { get; } = []; - - public IR.Class? IR { get; set; } - - public string? Name { get; set; } - - public CompilerObject? Base { get; set; } - - //public SimpleFunctionOverloadGroup? Constructor { get; set; } - - public CompilerObject? Constructor { get; set; } - - public Constructor? EmptyConstructor { get; set; } - - public Method? ClassConstructor { get; set; } - - public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (arguments.Length == 0) - if (EmptyConstructor is null) throw new InvalidOperationException(); - else return compiler.Call(EmptyConstructor, arguments); - - if (Constructor is null) throw new InvalidOperationException(); - return compiler.Call(Constructor, arguments); - } - - //public List? Interfaces { get; set; } - - public CompilerObject Member(Compiler.Compiler compiler, MemberName member) - => Members[member]; - - public CompilerObject Member(Compiler.Compiler compiler, CompilerObject value, MemberName member) - => Member(compiler, member) is IRTBoundMember rtBoundMember - ? rtBoundMember.Bind(compiler, value) - : throw new NotImplementedException(); - } -} diff --git a/ZSharp.Compiler/features/oop/objects/class/ClassBase.cs b/ZSharp.Compiler/features/oop/objects/class/ClassBase.cs deleted file mode 100644 index 12274daf..00000000 --- a/ZSharp.Compiler/features/oop/objects/class/ClassBase.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Objects -{ - public abstract class ClassBase - : CompilerObject - { - - } -} diff --git a/ZSharp.Compiler/features/oop/objects/class/ClassMeta.cs b/ZSharp.Compiler/features/oop/objects/class/ClassMeta.cs deleted file mode 100644 index f045dfa6..00000000 --- a/ZSharp.Compiler/features/oop/objects/class/ClassMeta.cs +++ /dev/null @@ -1,60 +0,0 @@ -namespace ZSharp.Objects -{ - /// - /// This class's instance defines the metaclass which all regular classes are - /// instances of. - /// - public sealed class ClassMeta - : CompilerObject - , IMetaClass - { - public Class DefaultBaseClass { get; set; } = new() - { - Name = "Object" - }; - - public Class Construct(Compiler.Compiler compiler, string name, CompilerObject[] bases, CompilerObject[]? content) - { - var result = new Class() - { - Name = name - }; - - bases = bases.Select(compiler.Evaluate).ToArray(); - - int baseIndex = 0; - - if (bases.Length > 1 && bases[0] is Class @base) - { - result.Base = @base; - baseIndex = 1; - } - else result.Base = DefaultBaseClass; - - for (int i = baseIndex; i < bases.Length; i++) - { - throw new NotImplementedException(); - //if (bases[i] is Interface @interface) - // throw new NotImplementedException(); - //else if (compiler.TypeSystem.IsTypeModifier(bases[i], out Class? inlineBase)) - // throw new NotImplementedException(); - } - - // TODO: prepare the class content - - if (FindSubclassInitializer(result.Base) is CompilerObject subclassInitializer) - compiler.Evaluate(compiler.Call(subclassInitializer, [new(result)])); - - return result; - } - - private CompilerObject? FindSubclassInitializer(CompilerObject? @base) - { - //while (@base is not null) - // if (@base.SubclassInitializer is not null) return @base.SubclassInitializer; - // else @base = @base.Base; - - return null; - } - } -} From f8b3e0801d1eb120974c55d77c2da5f2f244fe81 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:42:01 +0200 Subject: [PATCH 071/235] Add object type --- ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs index c6fc09d6..4726b582 100644 --- a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs +++ b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs @@ -20,6 +20,8 @@ public sealed class TypeSystem public CompilerObject Float32 { get; } + public CompilerObject Object { get; } + internal TypeSystem(Compiler compiler) : base(compiler) { @@ -31,6 +33,7 @@ internal TypeSystem(Compiler compiler) Boolean = new RawType(compiler.RuntimeModule.TypeSystem.Boolean, Type); Int32 = new(compiler.RuntimeModule.TypeSystem.Int32, Type); Float32 = new RawType(compiler.RuntimeModule.TypeSystem.Float32, Type); + Object = new RawType(compiler.RuntimeModule.TypeSystem.Object, Type); } public CompilerObject EvaluateType(CompilerObject @object) From a8100215087b734d7bc64f2e886404a96dcde101 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:45:47 +0200 Subject: [PATCH 072/235] Fix IR loader to support the newer IR type system --- .../ir loader/IRLoader.Impl.cs | 48 ++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index 8290dfdb..55c9a270 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -33,6 +33,10 @@ private Module Import(IR.Module module, Module result) foreach (var function in module.Functions) actions.Add(Load(function, result)); + if (module.HasTypes) + foreach (var type in module.Types) + actions.Add(Load(type)); + foreach (var action in actions) action(); @@ -97,7 +101,34 @@ private Action Load(IR.OOPType type) private Action Load(IR.Class @class) { - throw new NotImplementedException(); + GenericClass result = new() + { + Name = @class.Name ?? string.Empty, + }; + + Context.Objects.Cache(@class, result); + + if (@class.Base is not null) + result.Base = Load(@class.Base); + + return () => + { + if (@class.HasFields) + foreach (var field in @class.Fields) + { + Field resultField = new(field.Name) + { + IR = field, + Type = Load(field.Type), + }; + if (field.Initializer is not null) + resultField.Initializer = new RawCode(new(field.Initializer) + { + Types = [resultField.Type] + }); + result.Members.Add(resultField.Name, resultField); + }; + }; } private CompilerObject Load(IR.IType type) @@ -108,6 +139,21 @@ private CompilerObject Load(IR.IType type) throw new NotImplementedException(); } + private GenericClassInstance Load(IR.ConstructedClass constructed) + { + var origin = Context.Objects.Cache(constructed.Class) ?? throw new(); + + var args = new CommonZ.Utils.Mapping(); + + if (origin.GenericParameters.Count != constructed.Arguments.Count) + throw new(); + + for (var i = 0; i < constructed.Arguments.Count; i++) + args[origin.GenericParameters[i]] = Import(constructed.Arguments[i]); + + return new(origin, args); + } + private Signature Load(IR.Signature signature) { Signature result = new(); From 4e118c391ba7c55df3c82a0d4fada06dff5d8245 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:46:18 +0200 Subject: [PATCH 073/235] Add generic CompileIRType method --- .../compiler core/compiler/Compiler.IR.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs index 75c00026..b7990d97 100644 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs +++ b/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs @@ -56,5 +56,21 @@ public IRType CompileIRType(CompilerObject @object) throw new NotImplementedException(); // TODO: return null } + + public T CompileIRType(CompilerObject @object) + where T : IRType + { + ICompileIRType? irType; + + if ((irType = @object as ICompileIRType) is not null) + return irType.CompileIRType(this); + + @object = Evaluate(@object); + + if ((irType = @object as ICompileIRType) is not null) + return irType.CompileIRType(this); + + throw new NotImplementedException(); // TODO: return null + } } } From 45493b973228a9e12be9e82fbe88d66770b28d1f Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:46:35 +0200 Subject: [PATCH 074/235] Add generic CompileIRType protocol --- ZSharp.Compiler/ir generator/protocols/ICompileIRType.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ZSharp.Compiler/ir generator/protocols/ICompileIRType.cs b/ZSharp.Compiler/ir generator/protocols/ICompileIRType.cs index 7e19a6fe..b7bc4845 100644 --- a/ZSharp.Compiler/ir generator/protocols/ICompileIRType.cs +++ b/ZSharp.Compiler/ir generator/protocols/ICompileIRType.cs @@ -4,4 +4,13 @@ public interface ICompileIRType { public IRType CompileIRType(Compiler compiler); } + + public interface ICompileIRType : ICompileIRType + where T : IRType + { + IRType ICompileIRType.CompileIRType(Compiler compiler) + => CompileIRType(compiler); + + public new T CompileIRType(Compiler compiler); + } } From 24e2badf4e30db0374f83b762ae325aaa6afb23e Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:46:53 +0200 Subject: [PATCH 075/235] Add == operator for `string` and `bool` --- ZSharp.CT.StandardLibrary/Impl_Globals.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ZSharp.CT.StandardLibrary/Impl_Globals.cs b/ZSharp.CT.StandardLibrary/Impl_Globals.cs index e729a670..627d3dd0 100644 --- a/ZSharp.CT.StandardLibrary/Impl_Globals.cs +++ b/ZSharp.CT.StandardLibrary/Impl_Globals.cs @@ -28,5 +28,13 @@ public static string ToString(int x) [Alias(Name = "int32.parse()")] public static int ParseInt32(string s) => int.Parse(s); + + [Alias(Name = "_==_")] + public static bool Equals(string a, string b) + => a == b; + + [Alias(Name = "_==_")] + public static bool Equals(bool a, bool b) + => a == b; } } From ae76801861cfa7b0539d29594cd941fe88f811ce Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:47:55 +0200 Subject: [PATCH 076/235] Add support for `var` fields in class --- ZSharp.Parser/parsers/oop/ClassParser.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ZSharp.Parser/parsers/oop/ClassParser.cs b/ZSharp.Parser/parsers/oop/ClassParser.cs index 4aa1578a..453005e7 100644 --- a/ZSharp.Parser/parsers/oop/ClassParser.cs +++ b/ZSharp.Parser/parsers/oop/ClassParser.cs @@ -16,6 +16,10 @@ public ClassParser() LangParser.Keywords.Let, Utils.ExpressionStatement(LangParser.ParseLetExpression) ); + AddKeywordParser( + LangParser.Keywords.Var, + Utils.ExpressionStatement(LangParser.ParseVarExpression) + ); AddKeywordParser( LangParser.Keywords.Function, Utils.DefinitionStatement(Method.Parse) From 09c407ba6add69565c7c600d3a9440d5a658a23d Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:48:18 +0200 Subject: [PATCH 077/235] Fix things in the runtime --- ZSharp.Runtime.IL/Runtime.cs | 3 ++ ZSharp.Runtime.IL/ir2il/Constants.cs | 9 ++++++ ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 22 ++++++++++++++ .../ir2il/loaders/ModuleLoader.cs | 12 ++++++-- ZSharp.Runtime.IL/ir2il/loaders/TypeLoader.cs | 29 +++++++++++++++---- .../ir2il/loaders/code/CodeLoader.Compile.cs | 3 +- 6 files changed, 69 insertions(+), 9 deletions(-) create mode 100644 ZSharp.Runtime.IL/ir2il/Constants.cs diff --git a/ZSharp.Runtime.IL/Runtime.cs b/ZSharp.Runtime.IL/Runtime.cs index 5e7a90ae..8799298a 100644 --- a/ZSharp.Runtime.IL/Runtime.cs +++ b/ZSharp.Runtime.IL/Runtime.cs @@ -69,6 +69,9 @@ public IL.Module Import(IR.Module module) public Type Import(IR.IType type) => irLoader.LoadType(type); + public IR.IType Import(Type type) + => Context.Cache(type, out IR.IType? result) ? result : throw new(); + public IR.Module Import(IL.Module module) { if (!Context.Cache(module, out var result)) diff --git a/ZSharp.Runtime.IL/ir2il/Constants.cs b/ZSharp.Runtime.IL/ir2il/Constants.cs new file mode 100644 index 00000000..3e51094c --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/Constants.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Runtime.NET.IR2IL +{ + internal static class Constants + { + public const string GlobalsTypeName = ""; + + public const string AnonymousMethod = ""; + } +} diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index d69e138f..902bfd52 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -38,6 +38,12 @@ public IL.Module LoadModule(IR.Module module) thisPass.Clear(); } + if (module.Initializer is not null) + result + .GetType(Constants.GlobalsTypeName)! + .GetMethod(Context.Cache(module.Initializer)!.Name, [])! + .Invoke(null, null); + return result; } @@ -48,10 +54,26 @@ public Type LoadType(IR.IType type) return type switch { + IR.ConstructedClass constructedClass => LoadType(constructedClass), _ => throw new NotImplementedException() }; } + public Type LoadType(IR.ConstructedClass constructedClass) + { + var innerClass = Context.Cache(constructedClass.Class); + + if (innerClass is null) + throw new(); + + if (constructedClass.Arguments.Count == 0) + return innerClass; + + return innerClass.MakeGenericType([ + .. constructedClass.Arguments.Select(LoadType) + ]); + } + internal void AddToNextPass(Action action) => nextPass.Add(action); } diff --git a/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs b/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs index d9f9ce09..5a6a2ab9 100644 --- a/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs @@ -11,7 +11,7 @@ public IL.Module Load() Context.Cache(Input, Output); globals = Output.DefineType( - "", + Constants.GlobalsTypeName, IL.TypeAttributes.Public | IL.TypeAttributes.Abstract | IL.TypeAttributes.Sealed @@ -26,10 +26,10 @@ public IL.Module Load() LoadGlobals(); - LoadFunctions(); - LoadTypes(); + LoadFunctions(); + Loader.AddToNextPass(() => globals.CreateType()); return Output; @@ -72,6 +72,12 @@ private Type LoadClass(IR.Class @class) { var type = Output.DefineType(@class.Name ?? string.Empty, IL.TypeAttributes.Public); + Context.Cache(@class, type); + + new ClassLoader(Loader, @class, type).Load(); + + type.CreateType(); + return type; } diff --git a/ZSharp.Runtime.IL/ir2il/loaders/TypeLoader.cs b/ZSharp.Runtime.IL/ir2il/loaders/TypeLoader.cs index a71f46da..99c3ff7a 100644 --- a/ZSharp.Runtime.IL/ir2il/loaders/TypeLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loaders/TypeLoader.cs @@ -3,6 +3,11 @@ internal sealed class ClassLoader(IRLoader loader, IR.Class input, IL.Emit.TypeBuilder output) : BaseIRLoader(loader, input, output) { + private List thisPass = [], nextPass = []; + + private void AddToNextPass(Action action) + => nextPass.Add(action); + public void Load() { //LoadNestedTypes(); @@ -11,15 +16,24 @@ public void Load() //LoadInterfaces(); - LoadConstructors(); - LoadFields(); + LoadConstructors(); + //LoadEvents(); LoadMethods(); //LoadProperties(); + + do + { + (thisPass, nextPass) = (nextPass, thisPass); + nextPass.Clear(); + + foreach (var action in thisPass) + action(); + } while (thisPass.Count > 0); } private void LoadNestedTypes() @@ -77,7 +91,7 @@ private void LoadConstructor(IR.Constructor constructor) Position = p.Index }); - var result = Output.DefineConstructor(IL.MethodAttributes.Public, IL.CallingConventions.HasThis, irParams.Select(p => Loader.LoadType(p.Type)).ToArray()); + var result = Output.DefineConstructor(IL.MethodAttributes.Public, IL.CallingConventions.HasThis, irParams.Skip(1).Select(p => Loader.LoadType(p.Type)).ToArray()); Context.Cache(constructor.Method, result); @@ -116,7 +130,12 @@ private void LoadMethod(IR.Method method) if (method.IsStatic) attributes |= IL.MethodAttributes.Static; - var result = Output.DefineMethod(method.Name ?? string.Empty, attributes, Loader.LoadType(method.ReturnType), parameters.Select(p => p.Type).ToArray()); + var result = Output.DefineMethod( + method.Name ?? Constants.AnonymousMethod, + attributes, + Loader.LoadType(method.ReturnType), + (method.IsInstance || method.IsVirtual ? parameters.Skip(1) : parameters).Select(p => p.Type).ToArray() + ); Context.Cache(method, result); @@ -129,7 +148,7 @@ private void LoadMethod(IR.Method method) foreach (var local in method.Body.Locals) codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); - codeLoader.Load(); + AddToNextPass(() => codeLoader.Load()); } } } diff --git a/ZSharp.Runtime.IL/ir2il/loaders/code/CodeLoader.Compile.cs b/ZSharp.Runtime.IL/ir2il/loaders/code/CodeLoader.Compile.cs index 9eac2b54..bd2812ba 100644 --- a/ZSharp.Runtime.IL/ir2il/loaders/code/CodeLoader.Compile.cs +++ b/ZSharp.Runtime.IL/ir2il/loaders/code/CodeLoader.Compile.cs @@ -162,7 +162,8 @@ private void Compile(VM.Pop _) { Output.Emit(IL.Emit.OpCodes.Pop); - _stack.Pop(); + if (_stack.Count > 0) + _stack.Pop(); } private void Compile(VM.PutBoolean putBoolean) From 3721459e7cb5d239a7d558fd6e458fcd2b1c4e7b Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:49:38 +0200 Subject: [PATCH 078/235] Add more things to the source compilers --- .../class body/ClassBodyCompiler.cs | 167 +++++++++++++++++ .../class body/ConstructorCompiler.cs | 94 ++++++++++ .../class body/MethodCompiler.cs | 175 ++++++++++++++++++ .../builtin-compilers/module/ClassCompiler.cs | 38 +++- .../module/ModuleCompiler.cs | 7 +- 5 files changed, 472 insertions(+), 9 deletions(-) create mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs create mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs create mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs new file mode 100644 index 00000000..1d82dbd6 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs @@ -0,0 +1,167 @@ +using ZSharp.Objects; + +namespace ZSharp.ZSSourceCompiler +{ + public sealed class ClassBodyCompiler(ZSSourceCompiler compiler, OOPDefinition oop, GenericClass @class) + : CompilerBase(compiler) + , IMultipassCompiler + { + private List currentPass = [], nextPass = []; + + public OOPDefinition Node { get; } = oop; + + public GenericClass Class { get; } = @class; + + public void AddToNextPass(Action action) + => nextPass.Add(action); + + public void Compile() + { + using (Context.Compiler(this)) + CompileContent(); + } + + private void CompileContent() + { + if (Node.Content is null) + return; + + currentPass = Node.Content.Statements.Select(Compile).ToList(); + + while (currentPass.Count > 0) + { + foreach (var item in currentPass) + item(); + + (currentPass, nextPass) = (nextPass, currentPass); + nextPass.Clear(); + } + } + + private Action Compile(Statement statement) + => statement switch + { + ExpressionStatement expression => Compile(expression), + _ => throw new(), // TODO: could not compile node ... + }; + + private Action Compile(ExpressionStatement expression) + => expression.Expression switch + { + AST.Constructor constructor => Compile(constructor), + AST.Function function => Compile(function), + LetExpression let => Compile(let), + //OOPDefinition oop => Compile(oop), + VarExpression var => Compile(var), + _ => throw new() // TODO: Throw a proper exception of UnknownNodeType + }; + + private Action Compile(AST.Constructor constructor) + { + var compiler = new ConstructorCompiler(Compiler, constructor); + + compiler.Object.Owner = Class; + + Class.Content.Add(compiler.Object); + + if (constructor.Name is not null && constructor.Name != string.Empty) + { + Context.CurrentScope.Set(constructor.Name, compiler.Object); + Class.Members.Add(constructor.Name, compiler.Object); + } else + { + if (Class.Constructor is null) + Class.Constructor = new OverloadGroup(string.Empty); + if (Class.Constructor is not OverloadGroup group) + throw new("???"); + + group.Overloads.Add(compiler.Object); + } + + return () => compiler.Compile(); + } + + private Action Compile(AST.Function function) + { + var compiler = new MethodCompiler(Compiler, function, Class); + + Class.Content.Add(compiler.Object); + + if (function.Name != string.Empty) + { + if (!Context.CurrentScope.Get(function.Name, out var result, lookupParent: false)) + Context.CurrentScope.Set(function.Name, result = new OverloadGroup(function.Name)); + if (result is not OverloadGroup group) + throw new(); + group.Overloads.Add(compiler.Object); + + if (!Class.Members.TryGetValue(function.Name, out result)) + Class.Members.Add(function.Name, group); + } + + return () => compiler.Compile(); + } + + private Action Compile(LetExpression let) + { + var field = new Field(let.Name) + { + IsReadOnly = true, + }; + + Class.Content.Add(field); + + Context.CurrentScope.Set(let.Name, field); + Class.Members.Add(let.Name, field); + + return () => + { + field.Initializer = Compiler.CompileNode(let.Value); + + if (let.Type is not null) + field.Type = Compiler.CompileType(let.Type); + else if (Compiler.Compiler.TypeSystem.IsTyped(field.Initializer, out var type)) + field.Type = type; + + if (field.Type is null) throw new(); // TODO: Throw a proper exception of CouldNotInferType + + field.IR = Compiler.Compiler.CompileIRObject(field, null); + + if (field.Initializer is not null) + field.Initializer = Compiler.Compiler.Cast(field.Initializer, field.Type); + }; + } + + private Action Compile(VarExpression var) + { + var field = new Field(var.Name) + { + IsReadOnly = false, + }; + + Class.Content.Add(field); + + Context.CurrentScope.Set(var.Name, field); + Class.Members.Add(var.Name, field); + + return () => + { + if (var.Value is not null) + field.Initializer = Compiler.CompileNode(var.Value); + + if (var.Type is not null) + field.Type = Compiler.CompileType(var.Type); + else if (field.Initializer is not null) + if (Compiler.Compiler.TypeSystem.IsTyped(field.Initializer, out var type)) + field.Type = type; + + if (field.Type is null) throw new(); // TODO: Throw a proper exception of CouldNotInferType + + field.IR = Compiler.Compiler.CompileIRObject(field, null); + + if (field.Initializer is not null) + field.Initializer = Compiler.Compiler.Cast(field.Initializer, field.Type); + }; + } + } +} diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs new file mode 100644 index 00000000..98b014e5 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs @@ -0,0 +1,94 @@ +namespace ZSharp.ZSSourceCompiler +{ + public sealed class ConstructorCompiler(ZSSourceCompiler compiler, Constructor node) + : ContextCompiler(compiler, node, new(node.Name)) + , IOverrideCompileExpression + { + public Objects.Parameter This { get; private set; } = null!; + + public override Objects.Constructor Compile() + { + using (Context.Compiler(this)) + using (Context.Scope(Object)) + CompileConstructor(); + + return base.Compile(); + } + + private void CompileConstructor() + { + if (Node.Signature.Args is not null) + foreach (var parameter in Node.Signature.Args) + Object.Signature.Args.Add(Compile(parameter)); + + if (Node.Signature.VarArgs is not null) + Object.Signature.VarArgs = Compile(Node.Signature.VarArgs); + + if (Node.Signature.KwArgs is not null) + foreach (var parameter in Node.Signature.KwArgs) + Object.Signature.KwArgs.Add(Compile(parameter)); + + if (Node.Signature.VarKwArgs is not null) + Object.Signature.VarKwArgs = Compile(Node.Signature.VarKwArgs); + + if (Object.Signature.Args.Count == 0) + Object.Signature.Args.Add(new("this")); + + (This = Object.Signature.Args[0]).Type ??= Object.Owner; + + if (Context.ParentCompiler(out var multipassCompiler)) + multipassCompiler.AddToNextPass(() => + { + using (Context.Compiler(this)) + using (Context.Scope(Object)) + using (Context.Scope()) + CompileConstructorBody(); + }); + else using (Context.Scope()) + CompileConstructorBody(); + } + + private void CompileConstructorBody() + { + if (Node.Body is not null) + Object.Body = Compiler.CompileNode(Node.Body); + + Object.IR = Compiler.Compiler.CompileIRObject(Object, null!); + + Object.IR.Method.Body.Instructions.Add(new IR.VM.Return()); + } + + private Objects.Parameter Compile(Parameter parameter) + { + var result = new Objects.Parameter(parameter.Name); + + Context.CurrentScope.Set(parameter.Alias ?? parameter.Name, result); + + if (parameter.Type is not null) + result.Type = Compiler.CompileType(parameter.Type); + + if (parameter.Initializer is not null) + Compiler.LogError("Parameter initializers are not supported yet.", parameter); + + return result; + } + + private CompilerObject? Compile(IdentifierExpression identifier) + { + if (!Context.CurrentScope.Get(identifier.Name, out var member)) + return null; + + if (member is Objects.IRTBoundMember boundMember) + return boundMember.Bind(Compiler.Compiler, This); + + return member; + } + + CompilerObject? IOverrideCompileNode.CompileNode(ZSSourceCompiler compiler, Expression node) + => node switch + { + IdentifierExpression identifier => Compile(identifier), + _ => null, + }; + } +} diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs new file mode 100644 index 00000000..0d3bf7c3 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs @@ -0,0 +1,175 @@ +namespace ZSharp.ZSSourceCompiler +{ + public sealed class MethodCompiler(ZSSourceCompiler compiler, Function node, CompilerObject owner) + : ContextCompiler(compiler, node, new(node.Name)) + , IOverrideCompileStatement + { + public Objects.Parameter? This { get; private set; } = null; + + public override Objects.Method Compile() + { + using (Context.Compiler(this)) + using (Context.Scope(Object)) + CompileMethod(); + + return base.Compile(); + } + + private void CompileMethod() + { + if (Node.Signature.Args is not null) + foreach (var parameter in Node.Signature.Args) + Object.Signature.Args.Add(Compile(parameter)); + + if (Node.Signature.VarArgs is not null) + Object.Signature.VarArgs = Compile(Node.Signature.VarArgs); + + if (Node.Signature.KwArgs is not null) + foreach (var parameter in Node.Signature.KwArgs) + Object.Signature.KwArgs.Add(Compile(parameter)); + + if (Node.Signature.VarKwArgs is not null) + Object.Signature.VarKwArgs = Compile(Node.Signature.VarKwArgs); + + if (Node.ReturnType is not null) + Object.ReturnType = Compiler.CompileType(Node.ReturnType); + else throw new(); // TODO: Implement Infer type + + (This = Object.Signature.Args[0]).Type ??= owner; + + //Object.IR = Compiler.Compiler.CompileIRObject(Object, null); + + if (Context.ParentCompiler(out var multipassCompiler)) + multipassCompiler.AddToNextPass(() => + { + using (Context.Compiler(this)) + using (Context.Scope(Object)) + using (Context.Scope()) + CompileMethodBody(); + }); + else using (Context.Scope()) + CompileMethodBody(); + } + + private Objects.Parameter Compile(Parameter parameter) + { + var result = new Objects.Parameter(parameter.Name); + + Context.CurrentScope.Set(parameter.Alias ?? parameter.Name, result); + + if (parameter.Type is not null) + result.Type = Compiler.CompileType(parameter.Type); + + if (parameter.Initializer is not null) + Compiler.LogError("Parameter initializers are not supported yet.", parameter); + + return result; + } + + private void CompileMethodBody() + { + if (Node.Body is not null) + Object.Body = Compiler.CompileNode(Node.Body); + + Object.IR = Compiler.Compiler.CompileIRObject(Object, null); + } + + public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement node) + { + if (node is not Return @return) + return null; + + if (@return.Value is null) + return new Objects.RawCode(new([ + new IR.VM.Return() + ])); + + var valueObject = Compiler.CompileNode(@return.Value); + var valueCode = Compiler.Compiler.CompileIRCode(valueObject); + + if (valueCode is null) + { + Compiler.LogError("Return expression could not be compiled.", node); + return null; + } + + valueCode.Instructions.Add(new IR.VM.Return()); + valueCode.Types.Clear(); + + return new Objects.RawCode(valueCode); + } + + public CompilerObject? CompileNode(ZSSourceCompiler compiler, Expression node) + => node switch + { + LetExpression let => CompileNode(let), + VarExpression var => CompileNode(var), + _ => null + }; + + private CompilerObject CompileNode(LetExpression let) + { + var local = new Objects.Local + { + Name = let.Name, + Initializer = Compiler.CompileNode(let.Value), + }; + + Context.CurrentScope.Set(let.Name, local); + + local.Type = let.Type is not null + ? Compiler.CompileNode(let.Type) + : Compiler.Compiler.TypeSystem.IsTyped(local.Initializer, out var type) + ? type + : null; + + if (local.Type is null) + Compiler.LogError("Could not infer type of local variable.", let); + + local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); + + var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.Cast(local.Initializer, local.Type!)); + + code.Instructions.Add(new IR.VM.Dup()); + code.Instructions.Add(new IR.VM.SetLocal(local.IR)); + + return new Objects.RawCode(code); + } + + private CompilerObject CompileNode(VarExpression var) + { + var local = new Objects.Local + { + Name = var.Name, + Initializer = var.Value is null ? null : Compiler.CompileNode(var.Value), + }; + + Context.CurrentScope.Set(var.Name, local); + + local.Type = var.Type is not null + ? Compiler.CompileNode(var.Type) + : local.Initializer is null + ? null + : Compiler.Compiler.TypeSystem.IsTyped(local.Initializer, out var type) + ? type + : null; + + if (local.Type is null) + Compiler.LogError("Could not infer type of local variable.", var); + + local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); + + if (local.Initializer is not null) + { + var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.Cast(local.Initializer, local.Type!)); + + code.Instructions.Add(new IR.VM.Dup()); + code.Instructions.Add(new IR.VM.SetLocal(local.IR)); + + return new Objects.RawCode(code); + } + + return new Objects.RawCode(new()); + } + } +} diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs index f140b1f2..3ac9b96b 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs @@ -1,16 +1,38 @@ -namespace ZSharp.ZSSourceCompiler +using System.Linq; +using ZSharp.IR; +using ZSharp.Objects; + +namespace ZSharp.ZSSourceCompiler { - public sealed class ClassCompiler(ZSSourceCompiler compiler, OOPDefinition oop, CompilerObject @object) - : ContextCompiler(compiler, oop, @object) + public sealed class ClassCompiler( + ZSSourceCompiler compiler, + OOPDefinition node, + ClassMetaClass metaClass + ) + : ContextCompiler( + compiler, node, new() + { + Name = node.Name + } + ) { - public override CompilerObject Compile() + public override GenericClass Compile() { - var metaClass = Node.Of is null ? null : Compiler.CompileNode(Node.Of); + if (Node.Bases is not null) + { + var bases = Node.Bases.Select(Compiler.CompileType).ToArray(); - var cls = (Objects.Class)Object; + if (bases.Length > 0) + { + int interfacesIndex = 0; + if (bases[0] is GenericClassInstance) + Object.Base = (GenericClassInstance)bases[interfacesIndex++]; + } + } - if (Node.Bases is not null && Node.Bases.Count > 0) - cls.Base = (Objects.Class)Compiler.Compiler.Evaluate(Compiler.CompileNode(Node.Bases[0])); + using (Context.Compiler(this)) + using (Context.Scope(Object)) + new ClassBodyCompiler(Compiler, Node, Object).Compile(); return base.Compile(); } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs index 6afaabcf..3179d54f 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs @@ -10,6 +10,8 @@ public sealed class ModuleCompiler(ZSSourceCompiler compiler, Module node) public readonly Mapping> oopTypesCompilers = []; + public required Objects.ClassMetaClass DefaultMetaClass { get; set; } + public void AddToNextPass(Action action) => nextPass.Add(action); @@ -100,7 +102,10 @@ private Action Compile(LetExpression let) private Action Compile(Module module) { - var compiler = new ModuleCompiler(Compiler, module); + var compiler = new ModuleCompiler(Compiler, module) + { + DefaultMetaClass = DefaultMetaClass, + }; Object.Content.Add(compiler.Object); From c8bbd0e11e21651229b73523fb54fbace6758964 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:50:11 +0200 Subject: [PATCH 079/235] Add support for parsing array literals --- .../core-compilers/expression/ExpressionCompiler.Literals.cs | 5 ++++- .../core-compilers/expression/ExpressionCompiler.cs | 5 +++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.Literals.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.Literals.cs index e9ea777c..a7c35785 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.Literals.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.Literals.cs @@ -2,7 +2,10 @@ { public sealed partial class ExpressionCompiler { - public CompilerObject CompileNode(LiteralExpression literal) + public Objects.ArrayLiteral Compile(ArrayLiteral array) + => new(array.Items.Select(Compiler.CompileNode)); + + public CompilerObject Compile(LiteralExpression literal) => literal.Type switch { LiteralType.String => Compiler.Compiler.CreateString(literal.Value), diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index 55ec57fc..b085deb7 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -6,10 +6,11 @@ public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) public CompilerObject? CompileNode(Expression expression) => expression switch { + ArrayLiteral array => Compile(array), BinaryExpression binary => Compile(binary), CallExpression call => Compile(call), IdentifierExpression identifier => Context.CurrentScope.Get(identifier.Name), - LiteralExpression literal => CompileNode(literal), + LiteralExpression literal => Compile(literal), WhileExpression @while => Compile(@while), _ => null }; @@ -30,7 +31,7 @@ private CompilerObject Compile(BinaryExpression binary) else if (binary.Right is not LiteralExpression literal) throw new("Expected a literal expression on the right side of the dot operator."); - else member = CompileNode(literal); + else member = Compile(literal); if (Compiler.Compiler.IsString(member, out var memberName)) return Compiler.Compiler.Member(left, memberName); From a98911d668e7c5048ab2742a80093987a0e8918a Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:50:23 +0200 Subject: [PATCH 080/235] Add default metaclass --- .../compiler/ZSSourceCompiler.Compilers.cs | 14 ++++++-------- .../compiler/ZSSourceCompiler.OOP.cs | 7 +++++++ 2 files changed, 13 insertions(+), 8 deletions(-) create mode 100644 ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.OOP.cs diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Compilers.cs b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Compilers.cs index 7486646a..331d2c62 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Compilers.cs +++ b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Compilers.cs @@ -9,7 +9,10 @@ public DocumentCompiler CreateDocumentCompiler(AST.Document document, string pat public ModuleCompiler CreateModuleCompiler(Module module) { - var compiler = new ModuleCompiler(this, module); + var compiler = new ModuleCompiler(this, module) + { + DefaultMetaClass = DefaultMetaClass, + }; compiler.oopTypesCompilers.Add("class", (c, oop) => { @@ -17,14 +20,9 @@ public ModuleCompiler CreateModuleCompiler(Module module) // for C# types, we should create an uninitialized object via System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject // ConstructorInfo.Invoke has an overload which takes `this` as the first parameter (for late initialization). - if (metaClass is not null) c.LogError("Metaclasses are not supported yet.", oop); - - var @object = new Objects.Class() - { - Name = oop.Name, - }; + if (metaClass is not null) c.LogError("Metaclasses are not supported yet.", oop); - return new ClassCompiler(c, oop, @object); + return new ClassCompiler(c, oop, compiler.DefaultMetaClass); }); compiler.oopTypesCompilers.Add("interface", (c, oop) => diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.OOP.cs b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.OOP.cs new file mode 100644 index 00000000..364590d5 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.OOP.cs @@ -0,0 +1,7 @@ +namespace ZSharp.ZSSourceCompiler +{ + public sealed partial class ZSSourceCompiler : Compiler.Feature + { + public Objects.ClassMetaClass DefaultMetaClass { get; set; } = new(); + } +} From dfec2fe6f2f5b19901acd3b2715730434c6bb7ad Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:50:54 +0200 Subject: [PATCH 081/235] Update guessing-game.zs to use new feaures --- ZSharpTest/projects/guessing-game.zs | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/ZSharpTest/projects/guessing-game.zs b/ZSharpTest/projects/guessing-game.zs index 0b61db7c..a150d0ea 100644 --- a/ZSharpTest/projects/guessing-game.zs +++ b/ZSharpTest/projects/guessing-game.zs @@ -3,27 +3,28 @@ import { ceil, log2, random } from "std:math"; module Program; +let minNumber = 1; +let maxNumber = 100; + +let maxTries = ceil(log2(maxNumber - minNumber)); +let number = random(minNumber, maxNumber); + +let inputMessage = "Guess a number between " + string(minNumber) + " and " + string(maxNumber) + ": "; + fun guessOnce(guess: i32, number: i32, tries: i32): bool { - if (guess < number) - print("Too low!"); - else if (number < guess) - print("Too high!"); - else return true; + case (true) { + when (guess < number) print("Too low!"); + when (number < guess) print("Too high!"); + } else return true; return false; } fun main(): void { - let minNumber = 1; - let maxNumber = 100; - - let number = random(minNumber, maxNumber); - let maxTries = ceil(log2(maxNumber - minNumber)); - var tries = 0; while (tries < maxTries) { - let guessString = input("Guess a number between " + string(minNumber) + " and " + string(maxNumber) + ": "); + let guessString = input(inputMessage); let guess = i32.parse(guessString); if (guessOnce(guess, number, tries)) From 0403ae026a62953a69bc8f93c5775ff9c3f42830 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 28 Feb 2025 00:51:15 +0200 Subject: [PATCH 082/235] Add more test projects --- ZSharpTest/Properties/launchSettings.json | 8 ++ ZSharpTest/ZSharpTest.csproj | 6 ++ ZSharpTest/projects/simple-user-system.zs | 98 +++++++++++++++++++++++ ZSharpTest/projects/todo.zs | 21 ++--- ZSharpTest/tests/test-class-fields.zs | 43 ++++++++++ 5 files changed, 167 insertions(+), 9 deletions(-) create mode 100644 ZSharpTest/projects/simple-user-system.zs create mode 100644 ZSharpTest/tests/test-class-fields.zs diff --git a/ZSharpTest/Properties/launchSettings.json b/ZSharpTest/Properties/launchSettings.json index 4409d350..1174091b 100644 --- a/ZSharpTest/Properties/launchSettings.json +++ b/ZSharpTest/Properties/launchSettings.json @@ -11,6 +11,14 @@ "Projects/Guessing Game": { "commandName": "Project", "commandLineArgs": "projects/guessing-game.zs" + }, + "Projects/Simple User System": { + "commandName": "Project", + "commandLineArgs": "projects/simple-user-system.zs" + }, + "Tests/Test Class Fields": { + "commandName": "Project", + "commandLineArgs": "tests/test-class-fields.zs" } } } \ No newline at end of file diff --git a/ZSharpTest/ZSharpTest.csproj b/ZSharpTest/ZSharpTest.csproj index ccb2f5c7..b4848a0c 100644 --- a/ZSharpTest/ZSharpTest.csproj +++ b/ZSharpTest/ZSharpTest.csproj @@ -24,6 +24,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest @@ -33,6 +36,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest diff --git a/ZSharpTest/projects/simple-user-system.zs b/ZSharpTest/projects/simple-user-system.zs new file mode 100644 index 00000000..a1a6ffef --- /dev/null +++ b/ZSharpTest/projects/simple-user-system.zs @@ -0,0 +1,98 @@ +/* Required Features: + * [-] Primary constructor + * [-] Auto-fields from primary constructor parameters + * [x] Fields + * [ ] Anonymous constructor + * [ ] Named constructor + * [ ] Methods + * [x] Case-Of + * [ ] Automatic type inference for first parameter in methods + * [ ] Automatic instance binding when accessing instance method/field from instance method + * [ ] Instance method as function with `this` first parameter + * [x] Module globals initializers + */ + + +module Program; + + +class Authentication { + var username: string; + var password: string; + + new(this, username: string, password: string) { + this.username = username; + this.password = password; + } +} + + +class User { + var isAdmin: bool; + + var username: string; + var password: string; + + new(this, username: string, password: string) { + isAdmin = false; + + this.username = username; + this.password = password; + } + + new Admin(this, username: string, password: string) { + User(this: this, username, password); + + isAdmin = true; + } + + fun login(this, username: string, password: string): bool { + if (username != this.username) return false; + if (password != this.password) return false; + + return true; + } + + fun login(auth: Authentication, this: User): bool { + return this.login(auth.username, auth.password); + } +} + + +fun mainMenu(): bool { + print("|== Main Menu ==|"); + print("1. Sign In"); + print("2. Exit Program"); + + let userInput = input("> "); + + case (userInput) { + when ("1") signIn(); + when ("2") return false; + } else print("Invalid input."); + + return true; +} + + +fun signIn(): void { + let username = input("Username: "); + let password = input("Password: "); + + case (Authentication(username, password)) of (User.login) { + when (user) print("USER"); // userTerminal(); + when (admin) print("ADMIN"); // adminTerminal(); + } else print("Invalid credentials."); +} + + +fun main(): void { + while (mainMenu()) ; + else print("Thank you for using Simple User System!"); + + return; +} + + +let user = User("user", "123"); +let admin = User.Admin("admin", "321"); diff --git a/ZSharpTest/projects/todo.zs b/ZSharpTest/projects/todo.zs index 4acad6a9..eba8e6d9 100644 --- a/ZSharpTest/projects/todo.zs +++ b/ZSharpTest/projects/todo.zs @@ -1,9 +1,9 @@ -import { list } from "std:list"; +//import { list } from "std:list"; import { print, input } from "std:io"; module Program { - +/* let todo: list[string] = [ "Add list[T] type", "Add support for generic types in CO", @@ -33,29 +33,32 @@ module Program { todo.removeAt(index - 1); } - + */ fun do(): bool { print("Welcome to The ToDo List App! Please choose what to do:"); print("1. Add an item."); print("2. List all items."); print("3. Remove an item."); print("4. Exit program."); + let cmd = input("> "); + case (cmd) { - when ("1") addTodo(); - when ("2") getTodos(); - when ("3") delTodo(); + when ("1") print("ADD"); // addTodo(); + when ("2") print("GET"); // getTodos(); + when ("3") print("DEL"); // delTodo(); when ("4") return false; - } else - print("Unknown command: " + cmd); + } else print("Unknown command: " + cmd); return true; } - fun main() { + fun main(): void { while (do()); else print("Thank you for using The ToDo List App!"); + + return; } } diff --git a/ZSharpTest/tests/test-class-fields.zs b/ZSharpTest/tests/test-class-fields.zs new file mode 100644 index 00000000..99f43ed5 --- /dev/null +++ b/ZSharpTest/tests/test-class-fields.zs @@ -0,0 +1,43 @@ +import { print } from "std:io"; + +module Program; + +class MyBase { + var name: string; +} + +class MyClass : MyBase { + let age: i32 = 0; + + var base: MyBase; + + new (this, age: i32) { + base = this; + this.age = age; + } + + fun printAge(this): void { + return MyClass.printAge(this, "this.age = "); + } + + fun printAge(this, message: string): void { + print(message + string(this.age)); + + return; + } +} + + +fun main(): void { + let myClass = MyClass(15); + + print(string(myClass.age)); + + print(string(myClass.age = 20)); + + print("myClass.age = " + string(myClass.age)); + + MyClass.printAge(myClass); + + return; +} From 372a4bfac0a6d93da0f1a69a4c95e93ec1a127ff Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 3 Mar 2025 01:02:22 +0200 Subject: [PATCH 083/235] Add/fix support for object initalization delegation --- ZSharp.Compiler.Objects/oop/Constructor.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/ZSharp.Compiler.Objects/oop/Constructor.cs b/ZSharp.Compiler.Objects/oop/Constructor.cs index 87f0ec76..ce5b5ee2 100644 --- a/ZSharp.Compiler.Objects/oop/Constructor.cs +++ b/ZSharp.Compiler.Objects/oop/Constructor.cs @@ -41,15 +41,20 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) IR.VM.Instruction invocationInstruction; - if (kwArgs.ContainsKey(Signature.Args[0].Name)) + bool hasReturn = false; + if (kwArgs.TryGetValue(Signature.Args[0].Name, out var thisArgument)) { invocationInstruction = new IR.VM.Call(IR!.Method); + kwArgs.Remove(Signature.Args[0].Name); + args.Insert(0, thisArgument); } else { if (Owner is null) throw new(); + hasReturn = true; + invocationInstruction = new IR.VM.CreateInstance(IR!); args.Insert(0, new RawCode(new() { @@ -92,7 +97,8 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) result.Instructions.Add(invocationInstruction); result.Types.Clear(); - result.Types.Add(Owner ?? throw new()); + if (hasReturn) + result.Types.Add(Owner ?? throw new()); result.MaxStackSize = Math.Max(result.MaxStackSize, result.Types.Count); From 0a1aff6c5cb847c2ca931bb16425e59a50b64564 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 3 Mar 2025 01:02:35 +0200 Subject: [PATCH 084/235] Update class test file --- ZSharpTest/tests/test-class-fields.zs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ZSharpTest/tests/test-class-fields.zs b/ZSharpTest/tests/test-class-fields.zs index 99f43ed5..5ea703f0 100644 --- a/ZSharpTest/tests/test-class-fields.zs +++ b/ZSharpTest/tests/test-class-fields.zs @@ -16,6 +16,10 @@ class MyClass : MyBase { this.age = age; } + new Old(this) { + MyClass(this: this, 80); + } + fun printAge(this): void { return MyClass.printAge(this, "this.age = "); } @@ -30,6 +34,9 @@ class MyClass : MyBase { fun main(): void { let myClass = MyClass(15); + let old = MyClass.Old(); + + MyClass.printAge(old); print(string(myClass.age)); From faf0e42408324bb5720c2837071be76c7a203821 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 16 Mar 2025 20:28:31 +0200 Subject: [PATCH 085/235] Add support for binding overload group to instance on member access --- ZSharp.Compiler.Objects/oop/GenericClass.cs | 9 +++++++++ ZSharp.Compiler.Objects/overloading/OverloadGroup.cs | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/ZSharp.Compiler.Objects/oop/GenericClass.cs b/ZSharp.Compiler.Objects/oop/GenericClass.cs index b66ea25e..160b2830 100644 --- a/ZSharp.Compiler.Objects/oop/GenericClass.cs +++ b/ZSharp.Compiler.Objects/oop/GenericClass.cs @@ -112,6 +112,15 @@ CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerO if (memberObject is IRTBoundMember boundMember) return boundMember.Bind(compiler, value); + if (memberObject is OverloadGroup group) + return new OverloadGroup(group.Name) + { + Overloads = [.. group.Overloads.Select( + overload => overload is IRTBoundMember boundMember ? + boundMember.Bind(compiler, value) : overload + )], + }; + return memberObject; } } diff --git a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs index 1ed88ee1..fa1ccb62 100644 --- a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs +++ b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs @@ -9,7 +9,7 @@ public sealed class OverloadGroup(string name) { public string Name { get; set; } = name; - public Collection Overloads { get; } = []; + public Collection Overloads { get; init; } = []; public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) { From 29e9ad082dd4596b383368c2b871fe3d230e53f9 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 16 Mar 2025 20:28:54 +0200 Subject: [PATCH 086/235] Update test-class-fields.zs to use support for binding --- ZSharpTest/tests/test-class-fields.zs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ZSharpTest/tests/test-class-fields.zs b/ZSharpTest/tests/test-class-fields.zs index 5ea703f0..82fff3bb 100644 --- a/ZSharpTest/tests/test-class-fields.zs +++ b/ZSharpTest/tests/test-class-fields.zs @@ -36,7 +36,7 @@ fun main(): void { let myClass = MyClass(15); let old = MyClass.Old(); - MyClass.printAge(old); + old.printAge(); print(string(myClass.age)); @@ -44,7 +44,8 @@ fun main(): void { print("myClass.age = " + string(myClass.age)); - MyClass.printAge(myClass); + myClass.printAge(); + myClass.printAge("Hello!"); return; } From 0e27d61ef0b05a4f944cb2b4800969430b9f13a2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 16 Mar 2025 20:29:12 +0200 Subject: [PATCH 087/235] Update simple-user-system.zs to mark added features --- ZSharpTest/projects/simple-user-system.zs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ZSharpTest/projects/simple-user-system.zs b/ZSharpTest/projects/simple-user-system.zs index a1a6ffef..940f9440 100644 --- a/ZSharpTest/projects/simple-user-system.zs +++ b/ZSharpTest/projects/simple-user-system.zs @@ -2,9 +2,9 @@ * [-] Primary constructor * [-] Auto-fields from primary constructor parameters * [x] Fields - * [ ] Anonymous constructor - * [ ] Named constructor - * [ ] Methods + * [x] Anonymous constructor + * [x] Named constructor + * [x] Methods * [x] Case-Of * [ ] Automatic type inference for first parameter in methods * [ ] Automatic instance binding when accessing instance method/field from instance method From 23eadadb6042cd6631c9460808a2d7554b7493f5 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 22 Mar 2025 22:33:13 +0200 Subject: [PATCH 088/235] Fix generic class instance to support rt member access --- .../oop/GenericClassInstance.cs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs index 879704f7..d5def350 100644 --- a/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs +++ b/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs @@ -9,6 +9,7 @@ Mapping genericArguments ) : CompilerObject , ICTGetMember + , IRTGetMember , ICTCallable , IReference , ICompileIRType @@ -36,6 +37,31 @@ public CompilerObject Member(Compiler.Compiler compiler, string member) return Members[member] = origin; } + public CompilerObject Member(Compiler.Compiler compiler, CompilerObject instance, string member) + { + if (Members.ContainsKey(member)) return Members[member]; + + var origin = compiler.Member(Origin, member); + + if (Arguments.Count != 0) + //origin = compiler.CreateReference(origin, Context); + throw new NotImplementedException(); + + if (origin is IRTBoundMember boundMember) + return boundMember.Bind(compiler, instance); + + if (origin is OverloadGroup group) + return new OverloadGroup(group.Name) + { + Overloads = [.. group.Overloads.Select( + overload => overload is IRTBoundMember boundMember ? + boundMember.Bind(compiler, instance) : overload + )], + }; + + return Members[member] = origin; + } + IR.ConstructedClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) { var result = new IR.ConstructedClass( From 5abcdf59edbcb148bdc4e5448a7d984747a8d37f Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 22 Mar 2025 22:33:31 +0200 Subject: [PATCH 089/235] Add equality operator --- ZSharpTest/Main.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index a7900d97..96ecf96b 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -57,6 +57,7 @@ expressionParser.InfixL("*", 70); expressionParser.InfixL("**", 80); + expressionParser.InfixL("==", 30); expressionParser.Led(TokenType.LParen, LangParser.ParseCallExpression, 100); expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); From c2fe0f2e298a61d75162ccb5ab52b143b6343cac Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 22 Mar 2025 22:33:45 +0200 Subject: [PATCH 090/235] Add string inequality operator --- ZSharp.CT.StandardLibrary/Impl_Globals.cs | 4 ++++ ZSharpTest/Main.cs | 2 ++ 2 files changed, 6 insertions(+) diff --git a/ZSharp.CT.StandardLibrary/Impl_Globals.cs b/ZSharp.CT.StandardLibrary/Impl_Globals.cs index 627d3dd0..cb2b5592 100644 --- a/ZSharp.CT.StandardLibrary/Impl_Globals.cs +++ b/ZSharp.CT.StandardLibrary/Impl_Globals.cs @@ -36,5 +36,9 @@ public static bool Equals(string a, string b) [Alias(Name = "_==_")] public static bool Equals(bool a, bool b) => a == b; + + [Alias(Name = "_!=_")] + public static bool NotEquals(string a, string b) + => a != b; } } diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index 96ecf96b..ea80686f 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -58,6 +58,8 @@ expressionParser.InfixL("**", 80); expressionParser.InfixL("==", 30); + expressionParser.InfixL("!=", 30); + expressionParser.Led(TokenType.LParen, LangParser.ParseCallExpression, 100); expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); From b8d63efd277dda1bc078603cee3f4fa5d3a19c45 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 22 Mar 2025 22:34:09 +0200 Subject: [PATCH 091/235] Add UnexpectedTokenError exception class --- ZSharp.Parser/core/ParseError.cs | 6 ------ ZSharp.Parser/core/errors/ParseError.cs | 6 ++++++ .../core/errors/UnexpectedTokenError.cs | 20 +++++++++++++++++++ ZSharp.Parser/core/parser/Parser.Tokens.cs | 4 ++-- 4 files changed, 28 insertions(+), 8 deletions(-) delete mode 100644 ZSharp.Parser/core/ParseError.cs create mode 100644 ZSharp.Parser/core/errors/ParseError.cs create mode 100644 ZSharp.Parser/core/errors/UnexpectedTokenError.cs diff --git a/ZSharp.Parser/core/ParseError.cs b/ZSharp.Parser/core/ParseError.cs deleted file mode 100644 index bafe6fed..00000000 --- a/ZSharp.Parser/core/ParseError.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace ZSharp.Parser -{ - public class ParseError : Exception - { - } -} diff --git a/ZSharp.Parser/core/errors/ParseError.cs b/ZSharp.Parser/core/errors/ParseError.cs new file mode 100644 index 00000000..e2f1ee6f --- /dev/null +++ b/ZSharp.Parser/core/errors/ParseError.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Parser +{ + public class ParseError(string? message = null) : Exception(message) + { + } +} diff --git a/ZSharp.Parser/core/errors/UnexpectedTokenError.cs b/ZSharp.Parser/core/errors/UnexpectedTokenError.cs new file mode 100644 index 00000000..24233a45 --- /dev/null +++ b/ZSharp.Parser/core/errors/UnexpectedTokenError.cs @@ -0,0 +1,20 @@ +using ZSharp.Text; + +namespace ZSharp.Parser +{ + public sealed class UnexpectedTokenError( + string expectedToken, + Token gotToken + ) : ParseError(FormatMessage(expectedToken, gotToken)) + { + public Token GotToken { get; } = gotToken; + + private static string FormatMessage( + string expectedToken, + Token gotToken + ) + { + return $"Expected token '{expectedToken}' but got '{gotToken}'"; + } + } +} diff --git a/ZSharp.Parser/core/parser/Parser.Tokens.cs b/ZSharp.Parser/core/parser/Parser.Tokens.cs index 57cac751..17dd70fb 100644 --- a/ZSharp.Parser/core/parser/Parser.Tokens.cs +++ b/ZSharp.Parser/core/parser/Parser.Tokens.cs @@ -9,7 +9,7 @@ public sealed partial class Parser public Token Token => HasTokens ? TokenStream.PeekToken() : throw new ParseError(); public Token Eat(TokenType type) - => Is(type) ? TokenStream.Advance() : throw new ParseError(); + => Is(type) ? TokenStream.Advance() : throw new UnexpectedTokenError(type.ToString(), Token); public bool Eat(TokenType type, out Token token) { @@ -19,7 +19,7 @@ public bool Eat(TokenType type, out Token token) } public Token Eat(string value) - => Is(value) ? TokenStream.Advance() : throw new ParseError(); + => Is(value) ? TokenStream.Advance() : throw new UnexpectedTokenError(value, Token); public bool Eat(string value, out Token token) { From 2b7f1fc0caaad82630f60b99c8072637e573689c Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 22 Mar 2025 22:34:32 +0200 Subject: [PATCH 092/235] Fix IR -> IL module loader to load types first --- ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs b/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs index 5a6a2ab9..f4e34b2c 100644 --- a/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs @@ -24,10 +24,10 @@ public IL.Module Load() // IL.MethodAttributes.PrivateScope //); - LoadGlobals(); - LoadTypes(); + LoadGlobals(); + LoadFunctions(); Loader.AddToNextPass(() => globals.CreateType()); From b1603efda449785d80712f029e316894408cb8ba Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 22 Mar 2025 22:34:52 +0200 Subject: [PATCH 093/235] Fix method parser to use new parser scoping system --- ZSharp.Parser/parsers/oop/MethodParser.cs | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/ZSharp.Parser/parsers/oop/MethodParser.cs b/ZSharp.Parser/parsers/oop/MethodParser.cs index 72aa71fa..53d00cf1 100644 --- a/ZSharp.Parser/parsers/oop/MethodParser.cs +++ b/ZSharp.Parser/parsers/oop/MethodParser.cs @@ -58,20 +58,13 @@ protected override Statement ParseDefaultContextItem(Parser parser) private Statement ParseFunctionBody(Parser parser) { - if (parser.Is(LangParser.Symbols.ThenDo, eat: true)) - return ParseContextItem(parser); - - List body = []; - - parser.Eat(TokenType.LCurly); - - while (!parser.Is(TokenType.RCurly, eat: true)) - body.Add(ParseContextItem(parser)); - - return new BlockStatement() + using (parser.NewStack(MethodBody.Content, parser.GetParserFor())) { - Statements = body - }; + if (parser.Is(LangParser.Symbols.ThenDo, eat: true)) + return ParseContextItem(parser); + + return LangParser.ParseBlockStatement(parser); + } } } } From c543655bf4a55bcef191f6689b80fe89465abd4c Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 22 Mar 2025 22:35:15 +0200 Subject: [PATCH 094/235] Add support for method overload binding in constructor --- .../builtin-compilers/class body/ConstructorCompiler.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs index 98b014e5..288df598 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs @@ -81,6 +81,15 @@ private Objects.Parameter Compile(Parameter parameter) if (member is Objects.IRTBoundMember boundMember) return boundMember.Bind(Compiler.Compiler, This); + if (member is Objects.OverloadGroup group) + return new Objects.OverloadGroup(group.Name) + { + Overloads = [.. group.Overloads.Select( + overload => overload is Objects.IRTBoundMember boundMember ? + boundMember.Bind(Compiler.Compiler, This) : overload + )], + }; + return member; } From 714a562dcc18bd2ba43eae739f476d57915a71c2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 22 Mar 2025 22:35:30 +0200 Subject: [PATCH 095/235] Fix simple-user-system.zs test file --- ZSharpTest/projects/simple-user-system.zs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ZSharpTest/projects/simple-user-system.zs b/ZSharpTest/projects/simple-user-system.zs index 940f9440..c086a332 100644 --- a/ZSharpTest/projects/simple-user-system.zs +++ b/ZSharpTest/projects/simple-user-system.zs @@ -13,6 +13,9 @@ */ +import { input, print } from "std:io"; + + module Program; @@ -83,6 +86,8 @@ fun signIn(): void { when (user) print("USER"); // userTerminal(); when (admin) print("ADMIN"); // adminTerminal(); } else print("Invalid credentials."); + + return; } From 79088733c30c69cbf370fab1d78bdf8b955eed36 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen <42520501+binyamin555@users.noreply.github.com> Date: Sun, 23 Mar 2025 01:42:44 +0200 Subject: [PATCH 096/235] Update README.md --- README.md | 71 +++---------------------------------------------------- 1 file changed, 3 insertions(+), 68 deletions(-) diff --git a/README.md b/README.md index b82e3881..2fb39cb0 100644 --- a/README.md +++ b/README.md @@ -5,72 +5,7 @@ Welcome to the Z# language repository! This repository holds the first released Z# is a typesafe, interpreterd language. It is still very much a WIP so don't expect it to work smoothly. -The current state of the project is: -* [x] Tokenizer -* [x] Parser -* [x] Resolver -* [x] Compiler -* [x] IR Layer -* [x] ZSRuntime -* [ ] Platform Compiler +This repository is undergoing massive rewrites and the architecture is still under development. +Due to that, contributions are currently not accepted. -## Structure - -The whole compiler is separated to multiple modules, each with a different purpose. - -To understand the architecture of the compiler, one needs to understand the architecture of the language. - -The language is interpreted and it allows using statements in top-level scopes (e.g. document, module, etc..). -Also, it is typesafe. The compiler creates an IR of the code and the interpreter holds a runtime representation of the IR. - -The IR defines a static structure, while the runtime objects can vary during execution. - -## Running - -Simply run the main project (ZSharpTest). - -You can edit the [`test.zs`](ZSharpTest/test.zs) file. - -## ToDo - -* [ ] Add support for type-inference - - [x] Local inference - - [ ] Function return type -* [ ] Implement the overloading protocol (C#) -* [ ] Implement the `compile` protocol (both `IRObject` and `IR Type`) (C#, Z#) -* [ ] Implement better Z# RT VM API (C#) - - [x] Function calls - - [ ] Object construction, instantiation and initialization - - [x] IR loading -* [x] Organize IR loading in Z# RT VM (C#) -* [ ] Implement document-level definitions - - [ ] Functions - - [ ] Globals -* [ ] Implement OOP types - - [ ] Class - - [ ] Interface - - [ ] Typeclass - - [ ] Structure -* [ ] Add support for decorators -* [ ] Add support for custom attributes -* [ ] Implement the CG `Execute`/`Evaluate` command. -* [ ] Implement the `import(string)` CG function (C#) - - [ ] Add support for extensible `StringImporter` -* [ ] Add support for definition templates - - [ ] Functions - - [ ] Classes (which includes methods, properties, fields, etc..) -* [x] Fix module references lookup code (consider the fact that IR have 2 sources: `Read` and `EvaluateType`). - - > The way this works is by analyzing each function code right after the body is compiled. -* [ ] ZSharp.Compiler project - - [ ] IR Generator - - [ ] Generators - - [ ] Document - - [ ] Function Body - - [ ] Module - - [ ] OOP Types - - [ ] Method Body - -## ToDo (High Level) -* [ ] C# Interop with Z# (C# Reflection -> IR) -* [ ] Add more language features -* [ ] Fully implement the IR -> CG loader +However, suggestions about everything (syntax, concepts, architecture, etc..) are always welcome. \ No newline at end of file From bd97c8dd49ff10180fe324415b1062df8f3c0dbf Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen <42520501+binyamin555@users.noreply.github.com> Date: Sun, 23 Mar 2025 01:44:35 +0200 Subject: [PATCH 097/235] Update simple-user-system.zs --- ZSharpTest/projects/simple-user-system.zs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharpTest/projects/simple-user-system.zs b/ZSharpTest/projects/simple-user-system.zs index c086a332..a38d2a2d 100644 --- a/ZSharpTest/projects/simple-user-system.zs +++ b/ZSharpTest/projects/simple-user-system.zs @@ -8,7 +8,7 @@ * [x] Case-Of * [ ] Automatic type inference for first parameter in methods * [ ] Automatic instance binding when accessing instance method/field from instance method - * [ ] Instance method as function with `this` first parameter + * [x] Instance method as function with `this` first parameter * [x] Module globals initializers */ From e8b42e6222467e1dd3e7aca0369bf1d277d30ecc Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 6 Apr 2025 19:53:23 +0300 Subject: [PATCH 098/235] Move IR function body to functional/ --- ZSharp.IR/{vm/code => ir/functional}/FunctionBody.cs | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename ZSharp.IR/{vm/code => ir/functional}/FunctionBody.cs (100%) diff --git a/ZSharp.IR/vm/code/FunctionBody.cs b/ZSharp.IR/ir/functional/FunctionBody.cs similarity index 100% rename from ZSharp.IR/vm/code/FunctionBody.cs rename to ZSharp.IR/ir/functional/FunctionBody.cs From 9dc37ca58ec2dfdcbc5bbac4476b413a4e35cd6f Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 6 Apr 2025 19:54:44 +0300 Subject: [PATCH 099/235] Add base type reference interface --- .../type system/types/ConstructedClass.cs | 6 +++++- .../type system/types/ConstructedType.cs | 18 ++++++++++++++++++ .../type system/types/OOPTypeReference.cs | 19 +++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 ZSharp.IR/type system/types/ConstructedType.cs create mode 100644 ZSharp.IR/type system/types/OOPTypeReference.cs diff --git a/ZSharp.IR/type system/types/ConstructedClass.cs b/ZSharp.IR/type system/types/ConstructedClass.cs index 49a9e9f0..bd931ba0 100644 --- a/ZSharp.IR/type system/types/ConstructedClass.cs +++ b/ZSharp.IR/type system/types/ConstructedClass.cs @@ -3,10 +3,14 @@ namespace ZSharp.IR { public sealed class ConstructedClass(Class @class) - : IType + : ConstructedType { public Class Class { get; set; } = @class; + Class OOPTypeReference.Definition => Class; + + public OOPTypeReference? OwningType { get; set; } + public Collection Arguments { get; set; } = @class.HasGenericParameters ? [] : Collection.Empty; } } diff --git a/ZSharp.IR/type system/types/ConstructedType.cs b/ZSharp.IR/type system/types/ConstructedType.cs new file mode 100644 index 00000000..d89687c7 --- /dev/null +++ b/ZSharp.IR/type system/types/ConstructedType.cs @@ -0,0 +1,18 @@ +using CommonZ.Utils; + +namespace ZSharp.IR +{ + public interface ConstructedType + : OOPTypeReference + { + public abstract Collection Arguments { get; } + } + + public interface ConstructedType + : ConstructedType + , OOPTypeReference + where T : OOPType + { + + } +} diff --git a/ZSharp.IR/type system/types/OOPTypeReference.cs b/ZSharp.IR/type system/types/OOPTypeReference.cs new file mode 100644 index 00000000..fa030fe8 --- /dev/null +++ b/ZSharp.IR/type system/types/OOPTypeReference.cs @@ -0,0 +1,19 @@ +namespace ZSharp.IR +{ + public interface OOPTypeReference : IType + { + public OOPTypeReference? OwningType { get; set; } + + public OOPType Definition { get; } + } + + public interface OOPTypeReference : OOPTypeReference + where T : OOPType + { + public new T Definition { get; } + + OOPType OOPTypeReference.Definition { + get => Definition; + } + } +} From 71c55f51fe57c68f1015bebd69b6ad8d3badb085 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 6 Apr 2025 19:55:02 +0300 Subject: [PATCH 100/235] Add base member reference interface --- ZSharp.IR/ir/oop/MemberReference.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 ZSharp.IR/ir/oop/MemberReference.cs diff --git a/ZSharp.IR/ir/oop/MemberReference.cs b/ZSharp.IR/ir/oop/MemberReference.cs new file mode 100644 index 00000000..ff3ccedb --- /dev/null +++ b/ZSharp.IR/ir/oop/MemberReference.cs @@ -0,0 +1,14 @@ +namespace ZSharp.IR +{ + public interface MemberReference + { + public OOPTypeReference OwningType { get; } + } + + public interface MemberReference + : MemberReference + where T : IRObject + { + public T Member { get; } + } +} From be5c2c4dbc89972a9a4a1c38157efee026c91e92 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 6 Apr 2025 19:55:21 +0300 Subject: [PATCH 101/235] Add method reference class --- ZSharp.IR/ir/oop/method/MethodReference.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 ZSharp.IR/ir/oop/method/MethodReference.cs diff --git a/ZSharp.IR/ir/oop/method/MethodReference.cs b/ZSharp.IR/ir/oop/method/MethodReference.cs new file mode 100644 index 00000000..1ce70e0a --- /dev/null +++ b/ZSharp.IR/ir/oop/method/MethodReference.cs @@ -0,0 +1,17 @@ +namespace ZSharp.IR +{ + public sealed class MethodReference(Method method) + : MemberReference + , ICallable + { + public Method Member { get; set; } = method; + + public required OOPTypeReference OwningType { get; set; } + + public Signature Signature => Member.Signature; + + public bool HasBody => Member.HasBody; + + public ICallableBody? Body => Member.HasBody ? Member.Body : null; + } +} From d56fc5f86712a88ab6cb6ce09b74ebf89647a39a Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 6 Apr 2025 19:55:34 +0300 Subject: [PATCH 102/235] Add generic method instance class --- .../ir/oop/method/GenericMethodInstance.cs | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 ZSharp.IR/ir/oop/method/GenericMethodInstance.cs diff --git a/ZSharp.IR/ir/oop/method/GenericMethodInstance.cs b/ZSharp.IR/ir/oop/method/GenericMethodInstance.cs new file mode 100644 index 00000000..7a8eccf2 --- /dev/null +++ b/ZSharp.IR/ir/oop/method/GenericMethodInstance.cs @@ -0,0 +1,23 @@ +using CommonZ.Utils; + +namespace ZSharp.IR +{ + public sealed class GenericMethodInstance(MethodReference method) + : MemberReference + , ICallable + { + public MethodReference Method { get; set; } = method; + + public Collection Arguments { get; } = /*method.Member.HasGenericParameters*/false ? [] : Collection.Empty; + + public Method Member => Method.Member; + + public OOPTypeReference OwningType => Method.OwningType; + + public Signature Signature => Method.Signature; + + public bool HasBody => Method.HasBody; + + public ICallableBody? Body => Method.HasBody ? Method.Body : null; + } +} From 4aea0f72f99e4cc0e99a0f46c00db49fda9a9052 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 6 Apr 2025 19:55:45 +0300 Subject: [PATCH 103/235] Add field reference class --- ZSharp.IR/ir/oop/field/FieldReference.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 ZSharp.IR/ir/oop/field/FieldReference.cs diff --git a/ZSharp.IR/ir/oop/field/FieldReference.cs b/ZSharp.IR/ir/oop/field/FieldReference.cs new file mode 100644 index 00000000..778c80c8 --- /dev/null +++ b/ZSharp.IR/ir/oop/field/FieldReference.cs @@ -0,0 +1,10 @@ +namespace ZSharp.IR +{ + public sealed class FieldReference(Field field) + : MemberReference + { + public Field Member { get; set; } = field; + + public required OOPTypeReference OwningType { get; set; } + } +} From d842fcf8d09f2389dd35fcbc391a07f43f5339a6 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 6 Apr 2025 19:56:37 +0300 Subject: [PATCH 104/235] Fix IR type definitions to use the new type reference interface --- ZSharp.IR/ir/oop/Class.cs | 4 ++-- ZSharp.IR/ir/oop/Dataclass.cs | 6 +++--- ZSharp.IR/ir/oop/Structure.cs | 4 ++-- ZSharp.IR/ir/oop/interface/Interface.cs | 2 +- ZSharp.IR/ir/typeclass/Typeclass.cs | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/ZSharp.IR/ir/oop/Class.cs b/ZSharp.IR/ir/oop/Class.cs index 90db76dc..6e1aff38 100644 --- a/ZSharp.IR/ir/oop/Class.cs +++ b/ZSharp.IR/ir/oop/Class.cs @@ -12,9 +12,9 @@ public sealed class Class(string? name) : OOPType public ClassAttributes Attributes { get; set; } = ClassAttributes.None; - public ConstructedClass? Base { get; set; } + public OOPTypeReference? Base { get; set; } - public Class(string? name, ConstructedClass? @base) + public Class(string? name, OOPTypeReference? @base) : this(name) { Base = @base; diff --git a/ZSharp.IR/ir/oop/Dataclass.cs b/ZSharp.IR/ir/oop/Dataclass.cs index e82de4ba..f5bfef9d 100644 --- a/ZSharp.IR/ir/oop/Dataclass.cs +++ b/ZSharp.IR/ir/oop/Dataclass.cs @@ -2,15 +2,15 @@ namespace ZSharp.IR { - public sealed class Dataclass + public sealed class Dataclass : OOPType { public string? Name { get; set; } public DataclassAttributes Attributes { get; set; } = DataclassAttributes.None; - public Dataclass? Base { get; set; } + public OOPTypeReference? Base { get; set; } - public Collection TypeClasses { get; } + public Collection> TypeClasses { get; } public Collection Constructors { get; } } diff --git a/ZSharp.IR/ir/oop/Structure.cs b/ZSharp.IR/ir/oop/Structure.cs index 49c14d11..2db409a1 100644 --- a/ZSharp.IR/ir/oop/Structure.cs +++ b/ZSharp.IR/ir/oop/Structure.cs @@ -2,13 +2,13 @@ namespace ZSharp.IR { - public sealed class Structure + public sealed class Structure : OOPType { public string? Name { get; set; } public StructureAttributes Attributes { get; set; } = StructureAttributes.None; - public Collection Bases { get; set; } + public Collection> Bases { get; set; } public Collection Methods { get; } diff --git a/ZSharp.IR/ir/oop/interface/Interface.cs b/ZSharp.IR/ir/oop/interface/Interface.cs index 6579def4..13aff672 100644 --- a/ZSharp.IR/ir/oop/interface/Interface.cs +++ b/ZSharp.IR/ir/oop/interface/Interface.cs @@ -8,7 +8,7 @@ public sealed class Interface : OOPType public InterfaceAttributes Attributes { get; set; } = InterfaceAttributes.None; - public Collection Bases { get; set; } + public Collection> Bases { get; set; } public Collection Methods { get; } diff --git a/ZSharp.IR/ir/typeclass/Typeclass.cs b/ZSharp.IR/ir/typeclass/Typeclass.cs index cc8e7490..4e595eb2 100644 --- a/ZSharp.IR/ir/typeclass/Typeclass.cs +++ b/ZSharp.IR/ir/typeclass/Typeclass.cs @@ -8,7 +8,7 @@ public sealed class Typeclass : OOPType public TypeclassAttributes Attributes { get; set; } = TypeclassAttributes.None; - public Collection Bases { get; } + public Collection> Bases { get; } public GenericParameter Parameter { get; } From e1269bdbc2cab80f2157a8b6212da83363a75601 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 6 Apr 2025 19:57:01 +0300 Subject: [PATCH 105/235] Fix call virtual to use method reference --- ZSharp.IR/vm/instructions/flow/CallVirtual.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ZSharp.IR/vm/instructions/flow/CallVirtual.cs b/ZSharp.IR/vm/instructions/flow/CallVirtual.cs index 2ba4df1f..65362f46 100644 --- a/ZSharp.IR/vm/instructions/flow/CallVirtual.cs +++ b/ZSharp.IR/vm/instructions/flow/CallVirtual.cs @@ -1,11 +1,11 @@ namespace ZSharp.IR.VM { - public sealed class CallVirtual(Method method) + public sealed class CallVirtual(MemberReference method) : Instruction - , IHasOperand + , IHasOperand> { - public Method Method { get; set; } = method; + public MemberReference Method { get; set; } = method; - Method IHasOperand.Operand => Method; + MemberReference IHasOperand>.Operand => Method; } } From feff54123b59bebf048167487cc39938b1aeee62 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 6 Apr 2025 19:57:19 +0300 Subject: [PATCH 106/235] Fix create instance to use constructor reference --- ZSharp.IR/vm/instructions/flow/CreateInstance.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ZSharp.IR/vm/instructions/flow/CreateInstance.cs b/ZSharp.IR/vm/instructions/flow/CreateInstance.cs index 9570a9c2..a32ede6c 100644 --- a/ZSharp.IR/vm/instructions/flow/CreateInstance.cs +++ b/ZSharp.IR/vm/instructions/flow/CreateInstance.cs @@ -1,11 +1,11 @@ namespace ZSharp.IR.VM { - public sealed class CreateInstance(Constructor constructor) + public sealed class CreateInstance(MemberReference constructor) : Instruction - , IHasOperand + , IHasOperand> { - public Constructor Constructor { get; set; } = constructor; + public MemberReference Constructor { get; set; } = constructor; - Constructor IHasOperand.Operand => Constructor; + MemberReference IHasOperand>.Operand => Constructor; } } From d4db1b2d05690f0eaf313486c59ba7e0be65d63a Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 6 Apr 2025 19:57:38 +0300 Subject: [PATCH 107/235] Fix field accessors to use field reference --- ZSharp.IR/vm/instructions/stack/GetField.cs | 8 ++++---- ZSharp.IR/vm/instructions/stack/SetField.cs | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ZSharp.IR/vm/instructions/stack/GetField.cs b/ZSharp.IR/vm/instructions/stack/GetField.cs index f74c3408..b30f54e9 100644 --- a/ZSharp.IR/vm/instructions/stack/GetField.cs +++ b/ZSharp.IR/vm/instructions/stack/GetField.cs @@ -1,11 +1,11 @@ namespace ZSharp.IR.VM { - public sealed class GetField(Field field) + public sealed class GetField(MemberReference field) : Instruction - , IHasOperand + , IHasOperand> { - public Field Field { get; set; } = field; + public MemberReference Field { get; set; } = field; - Field IHasOperand.Operand => Field; + MemberReference IHasOperand>.Operand => Field; } } diff --git a/ZSharp.IR/vm/instructions/stack/SetField.cs b/ZSharp.IR/vm/instructions/stack/SetField.cs index 14b4a801..adca9104 100644 --- a/ZSharp.IR/vm/instructions/stack/SetField.cs +++ b/ZSharp.IR/vm/instructions/stack/SetField.cs @@ -1,11 +1,11 @@ namespace ZSharp.IR.VM { - public sealed class SetField(Field field) + public sealed class SetField(MemberReference field) : Instruction - , IHasOperand + , IHasOperand> { - public Field Field { get; set; } = field; + public MemberReference Field { get; set; } = field; - Field IHasOperand.Operand => Field; + MemberReference IHasOperand>.Operand => Field; } } From c438661a2273b31e3f3dc9ab83b4f3934927c985 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 00:24:47 +0300 Subject: [PATCH 108/235] Save progress --- Testing/Program.cs | 33 ++++ Testing/Testing.csproj | 15 ++ ZLoad.Test/Console.cs | 10 ++ ZLoad.Test/Globals.cs | 12 ++ ZLoad.Test/ZLoad.Test.csproj | 13 ++ ZSharp v1.sln | 18 ++ ZSharp.CT.StandardLibrary/Impl_Globals.cs | 3 +- ZSharp.CT.StandardLibrary/Standard.List.cs | 23 +++ .../ZSharp.Compiler.Features.csproj | 13 ++ ZSharp.Compiler.Features/generic/Generic.cs | 33 ++++ .../generic/IGenericParameter.cs | 9 + ZSharp.Compiler.Features/oop/IOOPMember.cs | 13 ++ ZSharp.Compiler.Features/oop/IOOPType.cs | 7 + ZSharp.Compiler.Features/oop/OOP.cs | 22 +++ .../referencing/IReferencable.cs | 16 ++ .../referencing/IReference.cs | 0 .../referencing/ReferenceContext.cs | 24 +++ .../referencing/Referencing.cs | 25 +++ .../ir loader/IRLoader.Impl.cs | 150 ++++++++++++++-- .../ir loader/IRLoader.cs | 1 + ZSharp.Compiler.Objects/GlobalUsings.cs | 3 - .../ZSharp.Compiler.Objects.csproj | 1 + .../callables/ArgumentMismatchException.cs | 4 +- .../functional/CTFunction.cs | 0 .../functional/Function.cs | 0 .../functional/PartialCall.cs | 21 +++ .../functional/body/Local.cs | 0 .../signature/KeywordVarParameter.cs | 18 ++ .../functional/signature/Parameter.cs | 25 +++ .../functional/signature/Signature.cs | 48 ++++++ .../functional/signature/VarParameter.cs | 18 ++ .../generic/GenericParameter.cs | 15 +- ZSharp.Compiler.Objects/oop/Class.cs | 64 ++++++- ZSharp.Compiler.Objects/oop/GenericClass.cs | 74 ++++++-- .../oop/GenericClassInstance.cs | 73 +++++--- .../oop/{ => constructor}/Constructor.cs | 25 ++- .../oop/constructor/ConstructorReference.cs | 43 +++++ .../oop/field/BoundField.cs | 8 +- ZSharp.Compiler.Objects/oop/method/Method.cs | 75 ++++++++ .../oop/method/MethodReference.cs | 104 ++++++++++++ .../overloading/OverloadGroup.cs | 9 + .../referencing/IReferencable.cs | 7 - .../referencing/ReferenceContext.cs | 14 -- .../signature/IKeywordVarParameter.cs | 7 + .../signature/IParameter.cs | 11 ++ .../signature/ISignature.cs | 82 +++++++++ .../signature/IVarParameter.cs | 9 + .../ArgumentsCountMismatchException.cs | 11 ++ .../utils/ObjectBuildState.cs | 13 ++ ZSharp.Compiler/GlobalUsings.cs | 3 - ZSharp.Compiler/cg objects/Utils.cs | 4 + .../functional/signature/Signature.cs | 17 -- ZSharp.Compiler/cg objects/types/Int32Type.cs | 4 +- .../cg objects/types/StringType.cs | 4 +- .../compiler core/compiler/Compiler.IR.cs | 11 ++ .../compiler/features/Compiler.Protocols.cs | 13 +- .../core/inference/Constraint.cs | 7 + .../core/inference/InferenceScope.cs | 42 +++++ .../core/inference/InferenceTarget.cs | 13 ++ ZSharp.Compiler/core/CompilerObject.cs | 2 +- ZSharp.Compiler/core/concepts/IMappable.cs | 8 + .../core/concepts/index/ICTGetIndex.cs | 7 + .../core/concepts/index/IGetIndex.cs | 7 - .../exceptions/CompilerObjectException.cs | 4 +- .../protocols/ICompileIRReference.cs | 7 + .../ir/custom metadata/CustomMetadata.cs | 9 + .../ICustomMetadataProvider.cs | 11 ++ ZSharp.IR/ir/oop/Class.cs | 55 +++++- .../ir/oop/{ => constructor}/Constructor.cs | 0 .../oop/constructor/ConstructorReference.cs | 17 ++ ZSharp.IR/ir/oop/method/MethodReference.cs | 2 +- ZSharp.IR/type system/RuntimeModule.cs | 32 ++-- ZSharp.IR/type system/TypeSystem.cs | 16 +- ZSharp.IR/type system/types/ClassReference.cs | 10 ++ ZSharp.Runtime.IL/Runtime.cs | 2 +- ZSharp.Runtime.IL/il2ir/core/ILLoader.cs | 30 +++- .../il2ir/loaders/ClassLoader.cs | 71 ++++++-- ZSharp.Runtime.IL/ir2il/Constants.cs | 4 + ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 134 +++++++++++---- .../ir2il/loader new/ClassLoader.cs | 160 ++++++++++++++++++ .../ir2il/loader new/ModuleContentLoader.cs | 17 ++ .../ir2il/loader new/ModuleLoader.cs | 116 +++++++++++++ .../ir2il/loader new/RootModuleLoader.cs | 47 +++++ .../code/CodeLoader.Compile.cs | 15 +- .../code/CodeLoader.cs | 6 +- .../code/ICodeLoader.cs | 0 .../{loaders => loader new}/code/Parameter.cs | 0 .../code/ThisParameter.cs | 0 .../ir2il/loaders/ModuleLoader.cs | 133 --------------- ZSharp.Runtime.IL/ir2il/loaders/TypeLoader.cs | 154 ----------------- .../class body/ConstructorCompiler.cs | 6 +- .../class body/MethodCompiler.cs | 6 +- .../module/FunctionCompiler.cs | 6 +- .../expression/ExpressionCompiler.cs | 14 +- .../extensibility/oop/ClassSpecification.cs | 15 ++ .../importers/StandardLibraryImporter.cs | 1 - .../import system/importers/ZSImporter.cs | 1 - ZSharpTest/DotNETImporter.cs | 53 ++++++ ZSharpTest/Main.cs | 9 + ZSharpTest/Properties/launchSettings.json | 8 + ZSharpTest/ZSharpTest.csproj | 7 + ZSharpTest/projects/better-user-system.zs | 104 ++++++++++++ ZSharpTest/tests/simple.zs | 19 +++ 103 files changed, 2140 insertions(+), 525 deletions(-) create mode 100644 Testing/Program.cs create mode 100644 Testing/Testing.csproj create mode 100644 ZLoad.Test/Console.cs create mode 100644 ZLoad.Test/Globals.cs create mode 100644 ZLoad.Test/ZLoad.Test.csproj create mode 100644 ZSharp.CT.StandardLibrary/Standard.List.cs create mode 100644 ZSharp.Compiler.Features/ZSharp.Compiler.Features.csproj create mode 100644 ZSharp.Compiler.Features/generic/Generic.cs create mode 100644 ZSharp.Compiler.Features/generic/IGenericParameter.cs create mode 100644 ZSharp.Compiler.Features/oop/IOOPMember.cs create mode 100644 ZSharp.Compiler.Features/oop/IOOPType.cs create mode 100644 ZSharp.Compiler.Features/oop/OOP.cs create mode 100644 ZSharp.Compiler.Features/referencing/IReferencable.cs rename {ZSharp.Compiler.Objects => ZSharp.Compiler.Features}/referencing/IReference.cs (100%) create mode 100644 ZSharp.Compiler.Features/referencing/ReferenceContext.cs create mode 100644 ZSharp.Compiler.Features/referencing/Referencing.cs rename {ZSharp.Compiler/cg objects => ZSharp.Compiler.Objects}/functional/CTFunction.cs (100%) rename {ZSharp.Compiler/cg objects => ZSharp.Compiler.Objects}/functional/Function.cs (100%) create mode 100644 ZSharp.Compiler.Objects/functional/PartialCall.cs rename {ZSharp.Compiler/cg objects => ZSharp.Compiler.Objects}/functional/body/Local.cs (100%) create mode 100644 ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs rename {ZSharp.Compiler/cg objects => ZSharp.Compiler.Objects}/functional/signature/Parameter.cs (57%) create mode 100644 ZSharp.Compiler.Objects/functional/signature/Signature.cs create mode 100644 ZSharp.Compiler.Objects/functional/signature/VarParameter.cs rename ZSharp.Compiler.Objects/oop/{ => constructor}/Constructor.cs (85%) create mode 100644 ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs create mode 100644 ZSharp.Compiler.Objects/oop/method/MethodReference.cs delete mode 100644 ZSharp.Compiler.Objects/referencing/IReferencable.cs delete mode 100644 ZSharp.Compiler.Objects/referencing/ReferenceContext.cs create mode 100644 ZSharp.Compiler.Objects/signature/IKeywordVarParameter.cs create mode 100644 ZSharp.Compiler.Objects/signature/IParameter.cs create mode 100644 ZSharp.Compiler.Objects/signature/ISignature.cs create mode 100644 ZSharp.Compiler.Objects/signature/IVarParameter.cs create mode 100644 ZSharp.Compiler.Objects/signature/exceptions/ArgumentsCountMismatchException.cs delete mode 100644 ZSharp.Compiler/cg objects/functional/signature/Signature.cs create mode 100644 ZSharp.Compiler/compiler core/core/inference/Constraint.cs create mode 100644 ZSharp.Compiler/compiler core/core/inference/InferenceScope.cs create mode 100644 ZSharp.Compiler/compiler core/core/inference/InferenceTarget.cs create mode 100644 ZSharp.Compiler/core/concepts/IMappable.cs create mode 100644 ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs delete mode 100644 ZSharp.Compiler/core/concepts/index/IGetIndex.cs create mode 100644 ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs create mode 100644 ZSharp.IR/ir/custom metadata/CustomMetadata.cs create mode 100644 ZSharp.IR/ir/custom metadata/ICustomMetadataProvider.cs rename ZSharp.IR/ir/oop/{ => constructor}/Constructor.cs (100%) create mode 100644 ZSharp.IR/ir/oop/constructor/ConstructorReference.cs create mode 100644 ZSharp.IR/type system/types/ClassReference.cs create mode 100644 ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs create mode 100644 ZSharp.Runtime.IL/ir2il/loader new/ModuleContentLoader.cs create mode 100644 ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs create mode 100644 ZSharp.Runtime.IL/ir2il/loader new/RootModuleLoader.cs rename ZSharp.Runtime.IL/ir2il/{loaders => loader new}/code/CodeLoader.Compile.cs (93%) rename ZSharp.Runtime.IL/ir2il/{loaders => loader new}/code/CodeLoader.cs (93%) rename ZSharp.Runtime.IL/ir2il/{loaders => loader new}/code/ICodeLoader.cs (100%) rename ZSharp.Runtime.IL/ir2il/{loaders => loader new}/code/Parameter.cs (100%) rename ZSharp.Runtime.IL/ir2il/{loaders => loader new}/code/ThisParameter.cs (100%) delete mode 100644 ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/loaders/TypeLoader.cs create mode 100644 ZSharp.ZSSourceCompiler/extensibility/oop/ClassSpecification.cs create mode 100644 ZSharpTest/DotNETImporter.cs create mode 100644 ZSharpTest/projects/better-user-system.zs create mode 100644 ZSharpTest/tests/simple.zs diff --git a/Testing/Program.cs b/Testing/Program.cs new file mode 100644 index 00000000..3f4c227f --- /dev/null +++ b/Testing/Program.cs @@ -0,0 +1,33 @@ +// See https://aka.ms/new-console-template for more information +Console.WriteLine("Hello, World!"); + + +var runtime = new ZSharp.Runtime.NET.Runtime(new()); + + +var topLevel = runtime.Import(typeof(TopLevel)); +var topLevelInner = runtime.Import(typeof(TopLevel.Inner)); +var topLevelInnerGeneric = runtime.Import(typeof(TopLevel.Inner)); + +Console.ReadLine(); + + +class TopLevel +{ + public T t; + + public T GetValue() + { + return t; + } + + public class Inner + { + + } + + public class Inner + { + + } +} diff --git a/Testing/Testing.csproj b/Testing/Testing.csproj new file mode 100644 index 00000000..7a60c6bc --- /dev/null +++ b/Testing/Testing.csproj @@ -0,0 +1,15 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + diff --git a/ZLoad.Test/Console.cs b/ZLoad.Test/Console.cs new file mode 100644 index 00000000..e0dc9f85 --- /dev/null +++ b/ZLoad.Test/Console.cs @@ -0,0 +1,10 @@ +namespace ZLoad.Test +{ + public static class Console + { + public static void WriteLine(string value) + { + System.Console.WriteLine(value); + } + } +} diff --git a/ZLoad.Test/Globals.cs b/ZLoad.Test/Globals.cs new file mode 100644 index 00000000..7c219f33 --- /dev/null +++ b/ZLoad.Test/Globals.cs @@ -0,0 +1,12 @@ +using ZSharp.Runtime.NET.IL2IR; + +namespace ZLoad.Test +{ + [ModuleGlobals] + public static partial class Globals + { + [Alias(Name = "greet")] + public static string Greet(string name) + => $"Hello, {name}!"; + } +} diff --git a/ZLoad.Test/ZLoad.Test.csproj b/ZLoad.Test/ZLoad.Test.csproj new file mode 100644 index 00000000..0aed9cf9 --- /dev/null +++ b/ZLoad.Test/ZLoad.Test.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/ZSharp v1.sln b/ZSharp v1.sln index 5f8cb766..debf3750 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -44,6 +44,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.StandardLibrary.M EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Objects", "ZSharp.Compiler.Objects\ZSharp.Compiler.Objects.csproj", "{6B3BEDB2-F3CB-400E-A257-D79F73075AF9}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Features", "ZSharp.Compiler.Features\ZSharp.Compiler.Features.csproj", "{E3DAA459-48D0-461E-A17E-453816D15090}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Testing", "Testing\Testing.csproj", "{8A5EB8BE-EDF3-444E-AC15-A3E9DEF1FC7F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZLoad.Test", "ZLoad.Test\ZLoad.Test.csproj", "{9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -126,6 +132,18 @@ Global {6B3BEDB2-F3CB-400E-A257-D79F73075AF9}.Debug|Any CPU.Build.0 = Debug|Any CPU {6B3BEDB2-F3CB-400E-A257-D79F73075AF9}.Release|Any CPU.ActiveCfg = Release|Any CPU {6B3BEDB2-F3CB-400E-A257-D79F73075AF9}.Release|Any CPU.Build.0 = Release|Any CPU + {E3DAA459-48D0-461E-A17E-453816D15090}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E3DAA459-48D0-461E-A17E-453816D15090}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E3DAA459-48D0-461E-A17E-453816D15090}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E3DAA459-48D0-461E-A17E-453816D15090}.Release|Any CPU.Build.0 = Release|Any CPU + {8A5EB8BE-EDF3-444E-AC15-A3E9DEF1FC7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8A5EB8BE-EDF3-444E-AC15-A3E9DEF1FC7F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8A5EB8BE-EDF3-444E-AC15-A3E9DEF1FC7F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8A5EB8BE-EDF3-444E-AC15-A3E9DEF1FC7F}.Release|Any CPU.Build.0 = Release|Any CPU + {9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZSharp.CT.StandardLibrary/Impl_Globals.cs b/ZSharp.CT.StandardLibrary/Impl_Globals.cs index cb2b5592..e69f035f 100644 --- a/ZSharp.CT.StandardLibrary/Impl_Globals.cs +++ b/ZSharp.CT.StandardLibrary/Impl_Globals.cs @@ -1,4 +1,5 @@ -using ZSharp.Runtime.NET.IL2IR; +using Standard.List; +using ZSharp.Runtime.NET.IL2IR; namespace Standard.IO diff --git a/ZSharp.CT.StandardLibrary/Standard.List.cs b/ZSharp.CT.StandardLibrary/Standard.List.cs new file mode 100644 index 00000000..4058527e --- /dev/null +++ b/ZSharp.CT.StandardLibrary/Standard.List.cs @@ -0,0 +1,23 @@ +using ZSharp.Runtime.NET.IL2IR; + +namespace Standard.List +{ + public sealed class List + { + private readonly System.Collections.Generic.List _inner = []; + + public List() { } + + [Alias(Name = "append")] + public void Add(T item) + { + _inner.Add(item); + } + + [Alias(Name = "get")] + public T Get(int index) + { + return _inner[index]; + } + } +} diff --git a/ZSharp.Compiler.Features/ZSharp.Compiler.Features.csproj b/ZSharp.Compiler.Features/ZSharp.Compiler.Features.csproj new file mode 100644 index 00000000..7e575a54 --- /dev/null +++ b/ZSharp.Compiler.Features/ZSharp.Compiler.Features.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/ZSharp.Compiler.Features/generic/Generic.cs b/ZSharp.Compiler.Features/generic/Generic.cs new file mode 100644 index 00000000..16d9b378 --- /dev/null +++ b/ZSharp.Compiler.Features/generic/Generic.cs @@ -0,0 +1,33 @@ +using CommonZ.Utils; +using ZSharp.Objects; + +namespace ZSharp.Compiler +{ + public sealed class Generic(Compiler compiler) : Feature(compiler) + { + public bool IsGenericDefinition(CompilerObject @object) + { + throw new NotImplementedException(); + } + + public bool IsGenericInstance(CompilerObject @object) + { + throw new NotImplementedException(); + } + + public Mapping GetGenericArguments(CompilerObject @object) + { + throw new NotImplementedException(); + } + + public CompilerObject GetGenericDefinition(CompilerObject @object) + { + throw new NotImplementedException(); + } + + public IGenericParameter[] GetGenericParameters(CompilerObject @object) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.Features/generic/IGenericParameter.cs b/ZSharp.Compiler.Features/generic/IGenericParameter.cs new file mode 100644 index 00000000..93d56593 --- /dev/null +++ b/ZSharp.Compiler.Features/generic/IGenericParameter.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Objects +{ + public interface IGenericParameter : CompilerObject + { + public string Name { get; } + + public CompilerObject Owner { get; } + } +} diff --git a/ZSharp.Compiler.Features/oop/IOOPMember.cs b/ZSharp.Compiler.Features/oop/IOOPMember.cs new file mode 100644 index 00000000..acfce5d8 --- /dev/null +++ b/ZSharp.Compiler.Features/oop/IOOPMember.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Objects +{ + public interface IOOPMember : CompilerObject + { + public IOOPType Owner { get; } + + public bool IsInstance { get; } + + public bool IsClass { get; } + + public bool IsStatic { get; } + } +} diff --git a/ZSharp.Compiler.Features/oop/IOOPType.cs b/ZSharp.Compiler.Features/oop/IOOPType.cs new file mode 100644 index 00000000..89e2955d --- /dev/null +++ b/ZSharp.Compiler.Features/oop/IOOPType.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Objects +{ + public interface IOOPType : CompilerObject + { + + } +} diff --git a/ZSharp.Compiler.Features/oop/OOP.cs b/ZSharp.Compiler.Features/oop/OOP.cs new file mode 100644 index 00000000..958d5972 --- /dev/null +++ b/ZSharp.Compiler.Features/oop/OOP.cs @@ -0,0 +1,22 @@ +using ZSharp.Objects; + +namespace ZSharp.Compiler +{ + public sealed class OOP(Compiler compiler) : Feature(compiler) + { + public bool IsClass(CompilerObject @object) + { + throw new NotImplementedException(); + } + + public CompilerObject BaseOf(CompilerObject @object) + { + throw new NotImplementedException(); + } + + public CompilerObject[] InterfacesOf(CompilerObject @object) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.Features/referencing/IReferencable.cs b/ZSharp.Compiler.Features/referencing/IReferencable.cs new file mode 100644 index 00000000..0fe6d759 --- /dev/null +++ b/ZSharp.Compiler.Features/referencing/IReferencable.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Objects +{ + public interface IReferencable : CompilerObject + { + public CompilerObject CreateReference(Compiler.Referencing @ref, ReferenceContext context); + } + + public interface IReferencable : IReferencable + where T : CompilerObject + { + CompilerObject IReferencable.CreateReference(Compiler.Referencing @ref, ReferenceContext context) + => CreateReference(@ref, context); + + public new T CreateReference(Compiler.Referencing @ref, ReferenceContext context); + } +} diff --git a/ZSharp.Compiler.Objects/referencing/IReference.cs b/ZSharp.Compiler.Features/referencing/IReference.cs similarity index 100% rename from ZSharp.Compiler.Objects/referencing/IReference.cs rename to ZSharp.Compiler.Features/referencing/IReference.cs diff --git a/ZSharp.Compiler.Features/referencing/ReferenceContext.cs b/ZSharp.Compiler.Features/referencing/ReferenceContext.cs new file mode 100644 index 00000000..1762984c --- /dev/null +++ b/ZSharp.Compiler.Features/referencing/ReferenceContext.cs @@ -0,0 +1,24 @@ +using CommonZ.Utils; + +namespace ZSharp.Objects +{ + public sealed class ReferenceContext(ReferenceContext? parent = null) + { + public Cache CompileTimeValues { get; init; } = new() + { + Parent = parent?.CompileTimeValues + }; + + public ReferenceContext? Parent { get; } = parent; + + public CompilerObject? Scope { get; init; } = null; + + public CompilerObject this[CompilerObject key] + { + get => CompileTimeValues.Cache(key) ?? throw new KeyNotFoundException( + $"Key {key} was not found in the reference context{(Scope is null ? string.Empty : $" {Scope}")}." + ); + set => CompileTimeValues.Cache(key, value); + } + } +} diff --git a/ZSharp.Compiler.Features/referencing/Referencing.cs b/ZSharp.Compiler.Features/referencing/Referencing.cs new file mode 100644 index 00000000..eb11f6b1 --- /dev/null +++ b/ZSharp.Compiler.Features/referencing/Referencing.cs @@ -0,0 +1,25 @@ +using ZSharp.Objects; + +namespace ZSharp.Compiler +{ + public sealed class Referencing(Compiler compiler) + : Feature(compiler) + { + public CompilerObject CreateReference(CompilerObject @object, ReferenceContext context) + { + if (@object is IReferencable referencable) + return referencable.CreateReference(this, context); + + return @object; + } + + public T CreateReference(CompilerObject @object, ReferenceContext context) + where T : CompilerObject + { + if (@object is IReferencable referencable) + return referencable.CreateReference(this, context); + + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index 55c9a270..cfbea350 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -35,7 +35,7 @@ private Module Import(IR.Module module, Module result) if (module.HasTypes) foreach (var type in module.Types) - actions.Add(Load(type)); + actions.Add(Load(type, result)); foreach (var action in actions) action(); @@ -90,27 +90,48 @@ private Action Load(IR.Function function, Module owner) }; } - private Action Load(IR.OOPType type) + private Action Load(IR.OOPType type, Module owner) => type switch { - IR.Class @class => Load(@class), + IR.Class @class => Load(@class, owner), //IR.Interface @interface => Load(@interface), //IR.Struct @struct => Load(@struct), _ => throw new NotImplementedException(), }; - private Action Load(IR.Class @class) + private Action Load(IR.Class @class, Module owner) { GenericClass result = new() { Name = @class.Name ?? string.Empty, + IR = new(@class), + Defined = true, }; Context.Objects.Cache(@class, result); + owner.Content.Add(result); + + if (result.Name is not null && result.Name != string.Empty) + owner.Members.Add(result.Name, result); + if (@class.Base is not null) result.Base = Load(@class.Base); + if (@class.HasGenericParameters) + foreach (var parameter in @class.GenericParameters) + { + var genericParameter = new GenericParameter() + { + Name = parameter.Name, + IR = parameter, + }; + + Context.Types.Cache(parameter, genericParameter); + + result.GenericParameters.Add(genericParameter); + } + return () => { if (@class.HasFields) @@ -128,6 +149,55 @@ private Action Load(IR.Class @class) }); result.Members.Add(resultField.Name, resultField); }; + + if (@class.Constructors.Count > 0) + foreach (var constructor in @class.Constructors) + { + Constructor resultConstructor = new(constructor.Name) + { + Owner = result, + IR = constructor, + }; + if (resultConstructor.Name is not null && resultConstructor.Name != string.Empty) + { + if (!result.Members.TryGetValue(resultConstructor.Name, out var group)) + result.Members.Add(resultConstructor.Name, group = new OverloadGroup(resultConstructor.Name)); + + if (group is not OverloadGroup overloadGroup) + throw new InvalidOperationException(); + + overloadGroup.Overloads.Add(resultConstructor); + } else + { + if (result.Constructor is not OverloadGroup group) + result.Constructor = group = new OverloadGroup(string.Empty); + + group.Overloads.Add(resultConstructor); + } + resultConstructor.Signature = Load(constructor.Method.Signature); + } + + if (@class.Methods.Count > 0) + foreach (var method in @class.Methods) + { + Method resultMethod = new(method.Name) + { + IR = method, + Defined = true, + }; + if (resultMethod.Name is not null && resultMethod.Name != string.Empty) + { + if (!result.Members.TryGetValue(resultMethod.Name, out var group)) + result.Members.Add(resultMethod.Name, group = new OverloadGroup(resultMethod.Name)); + + if (group is not OverloadGroup overloadGroup) + throw new InvalidOperationException(); + + overloadGroup.Overloads.Add(resultMethod); + } + resultMethod.Signature = Load(method.Signature); + resultMethod.ReturnType = Load(method.ReturnType); + } }; } @@ -136,22 +206,41 @@ private CompilerObject Load(IR.IType type) if (Context.Types.Cache(type, out var result)) return result; - throw new NotImplementedException(); + if (type is IR.ConstructedClass constructed) + return Load(constructed); + + return null!; + //throw new NotImplementedException(); } - private GenericClassInstance Load(IR.ConstructedClass constructed) + private CompilerObject Load(IR.ConstructedClass constructed) { - var origin = Context.Objects.Cache(constructed.Class) ?? throw new(); + var origin = + Context.Objects.Cache(constructed.Class) ?? + Context.Types.Cache(constructed) + ?? throw new(); - var args = new CommonZ.Utils.Mapping(); + var args = new CommonZ.Utils.Cache(); - if (origin.GenericParameters.Count != constructed.Arguments.Count) - throw new(); + if (origin is GenericClass genericClass) + { + if (genericClass.GenericParameters.Count != constructed.Arguments.Count) + throw new(); - for (var i = 0; i < constructed.Arguments.Count; i++) - args[origin.GenericParameters[i]] = Import(constructed.Arguments[i]); + for (var i = 0; i < constructed.Arguments.Count; i++) + args.Cache(genericClass.GenericParameters[i], Import(constructed.Arguments[i])); - return new(origin, args); + return new GenericClassInstance(genericClass) + { + Context = new() + { + Scope = genericClass, + CompileTimeValues = args + } + }; + } + + return origin; } private Signature Load(IR.Signature signature) @@ -160,22 +249,22 @@ private Signature Load(IR.Signature signature) if (signature.HasArgs) foreach (var arg in signature.Args.Parameters) - result.Args.Add(Load(arg)); + result.Args.Add(LoadParameter(arg)); if (signature.IsVarArgs) - result.VarArgs = Load(signature.Args.Var!); + result.VarArgs = LoadVarParameter(signature.Args.Var!); if (signature.HasKwArgs) foreach (var arg in signature.KwArgs.Parameters) - result.KwArgs.Add(Load(arg)); + result.KwArgs.Add(LoadParameter(arg)); if (signature.IsVarKwArgs) - result.VarKwArgs = Load(signature.KwArgs.Var!); + result.VarKwArgs = LoadKeywordVarParameter(signature.KwArgs.Var!); return result; } - private Parameter Load(IR.Parameter parameter) + private Parameter LoadParameter(IR.Parameter parameter) { var type = Load(parameter.Type); @@ -189,5 +278,30 @@ private Parameter Load(IR.Parameter parameter) Type = type, }; } + + private VarParameter LoadVarParameter(IR.Parameter parameter) + { + var type = Load(parameter.Type); + + if (parameter.Initializer is not null) + throw new NotImplementedException(); + + return new(parameter.Name) + { + IR = parameter, + Type = type, + }; + } + + private KeywordVarParameter LoadKeywordVarParameter(IR.Parameter parameter) + { + var type = Load(parameter.Type); + + return new(parameter.Name) + { + IR = parameter, + Type = type, + }; + } } } diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs index 26c9153e..c9440f2d 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs @@ -16,6 +16,7 @@ private void Initialize() Compiler.TypeSystem.Int32, Compiler.TypeSystem.Void, Compiler.TypeSystem.Boolean, + Compiler.TypeSystem.Object, }) Context.Types.Cache(Compiler.CompileIRType(type), type); } diff --git a/ZSharp.Compiler.Objects/GlobalUsings.cs b/ZSharp.Compiler.Objects/GlobalUsings.cs index 92daf4d2..c4ac3e75 100644 --- a/ZSharp.Compiler.Objects/GlobalUsings.cs +++ b/ZSharp.Compiler.Objects/GlobalUsings.cs @@ -1,5 +1,2 @@ global using MemberName = string; global using MemberIndex = int; - -global using Args = CommonZ.Utils.Collection; -global using KwArgs = CommonZ.Utils.Mapping; diff --git a/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj b/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj index e4416735..9f6c481e 100644 --- a/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj +++ b/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj @@ -8,6 +8,7 @@ + diff --git a/ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs b/ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs index c5c017b1..aba2b1cd 100644 --- a/ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs +++ b/ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs @@ -2,8 +2,8 @@ namespace ZSharp.Objects { - public class ArgumentMismatchException(CompilerObject callable, Argument[] arguments) - : CompilerObjectException(callable) + public class ArgumentMismatchException(CompilerObject callable, Argument[] arguments, Exception? innerException = null) + : CompilerObjectException(callable, innerException: innerException) { public CompilerObject Callable => Object; diff --git a/ZSharp.Compiler/cg objects/functional/CTFunction.cs b/ZSharp.Compiler.Objects/functional/CTFunction.cs similarity index 100% rename from ZSharp.Compiler/cg objects/functional/CTFunction.cs rename to ZSharp.Compiler.Objects/functional/CTFunction.cs diff --git a/ZSharp.Compiler/cg objects/functional/Function.cs b/ZSharp.Compiler.Objects/functional/Function.cs similarity index 100% rename from ZSharp.Compiler/cg objects/functional/Function.cs rename to ZSharp.Compiler.Objects/functional/Function.cs diff --git a/ZSharp.Compiler.Objects/functional/PartialCall.cs b/ZSharp.Compiler.Objects/functional/PartialCall.cs new file mode 100644 index 00000000..92908c3d --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/PartialCall.cs @@ -0,0 +1,21 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class PartialCall(CompilerObject target) + : CompilerObject + , ICTCallable + { + public CompilerObject Target { get; set; } = target; + + public Argument[] Arguments { get; set; } = []; + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + return compiler.Call(Target, [ + .. Arguments, + .. arguments + ]); + } + } +} diff --git a/ZSharp.Compiler/cg objects/functional/body/Local.cs b/ZSharp.Compiler.Objects/functional/body/Local.cs similarity index 100% rename from ZSharp.Compiler/cg objects/functional/body/Local.cs rename to ZSharp.Compiler.Objects/functional/body/Local.cs diff --git a/ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs b/ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs new file mode 100644 index 00000000..83221fd2 --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs @@ -0,0 +1,18 @@ +namespace ZSharp.Objects +{ + public sealed class KeywordVarParameter(string name) + : CompilerObject + , IKeywordVarParameter + { + public string Name { get; set; } = name; + + public IR.Parameter? IR { get; set; } + + public CompilerObject? Type { get; set; } + + CompilerObject IKeywordVarParameter.MatchArguments(Compiler.Compiler compiler, Dictionary argument) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler/cg objects/functional/signature/Parameter.cs b/ZSharp.Compiler.Objects/functional/signature/Parameter.cs similarity index 57% rename from ZSharp.Compiler/cg objects/functional/signature/Parameter.cs rename to ZSharp.Compiler.Objects/functional/signature/Parameter.cs index 882d24db..d43caa6c 100644 --- a/ZSharp.Compiler/cg objects/functional/signature/Parameter.cs +++ b/ZSharp.Compiler.Objects/functional/signature/Parameter.cs @@ -6,6 +6,8 @@ public sealed class Parameter(string name) : CompilerObject , ICTReadable , ICompileIRObject + , IReferencable + , IParameter { public IR.Parameter? IR { get; set; } @@ -15,6 +17,12 @@ public sealed class Parameter(string name) public CompilerObject? Initializer { get; set; } + public CompilerObject? Default + { + get => Initializer; + set => Initializer = value; + } + public IR.Parameter CompileIRObject(Compiler.Compiler compiler, IR.Signature? owner) { if (Type is null) @@ -35,5 +43,22 @@ public IRCode Read(Compiler.Compiler compiler) MaxStackSize = 1, Types = [Type ?? throw new()] }; + + Parameter IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + { + return new(Name) + { + Initializer = Initializer is null ? null : @ref.CreateReference(Initializer, context), + Type = Type is null ? null : @ref.CreateReference(Type, context), + }; + } + + CompilerObject IParameter.MatchArgument(Compiler.Compiler compiler, CompilerObject argument) + { + if (Type is null) + throw new InvalidOperationException($"Parameter's {Name} type is not defined"); + + return compiler.Cast(argument, Type); + } } } diff --git a/ZSharp.Compiler.Objects/functional/signature/Signature.cs b/ZSharp.Compiler.Objects/functional/signature/Signature.cs new file mode 100644 index 00000000..cc3322e4 --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/signature/Signature.cs @@ -0,0 +1,48 @@ +using ZSharp.Compiler; +using Parameters = CommonZ.Utils.Collection; + +namespace ZSharp.Objects +{ + public sealed class Signature + : CompilerObject + , IReferencable + , ISignature + { + public Parameters Args { get; init; } = []; + + public VarParameter? VarArgs { get; set; } + + public Parameters KwArgs { get; init; } = []; + + public KeywordVarParameter? VarKwArgs { get; set; } + + Signature IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + { + Signature result = new(); + + result.Args.AddRange(Args.Select(arg => @ref.CreateReference(arg, context))); + + if (VarArgs is not null) + result.VarArgs = @ref.CreateReference(VarArgs, context); + + result.KwArgs.AddRange(KwArgs.Select(arg => @ref.CreateReference(arg, context))); + + if (VarKwArgs is not null) + result.VarKwArgs = @ref.CreateReference(VarKwArgs, context); + + return result; + } + + IEnumerable? ISignature.GetArgs(Compiler.Compiler compiler) + => Args; + + IEnumerable? ISignature.GetKwArgs(Compiler.Compiler compiler) + => KwArgs; + + IVarParameter? ISignature.GetVarArgs(Compiler.Compiler compiler) + => VarArgs; + + IKeywordVarParameter? ISignature.GetVarKwArgs(Compiler.Compiler compiler) + => VarKwArgs; + } +} diff --git a/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs b/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs new file mode 100644 index 00000000..ed789852 --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs @@ -0,0 +1,18 @@ +namespace ZSharp.Objects +{ + public sealed class VarParameter(string name) + : CompilerObject + , IVarParameter + { + public string Name { get; set; } = name; + + public IR.Parameter? IR { get; set; } + + public CompilerObject? Type { get; set; } + + CompilerObject IVarParameter.MatchArguments(Compiler.Compiler compiler, CompilerObject[] argument) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.Objects/generic/GenericParameter.cs b/ZSharp.Compiler.Objects/generic/GenericParameter.cs index b79f5602..64a2beb0 100644 --- a/ZSharp.Compiler.Objects/generic/GenericParameter.cs +++ b/ZSharp.Compiler.Objects/generic/GenericParameter.cs @@ -1,8 +1,21 @@ -namespace ZSharp.Objects +using ZSharp.Compiler; +using ZSharp.IR; + +namespace ZSharp.Objects { public sealed class GenericParameter : CompilerObject + , ICompileIRType + , IReferencable { public string Name { get; set; } = string.Empty; + + public IR.GenericParameter? IR { get; set; } + + public IR.GenericParameter CompileIRType(Compiler.Compiler compiler) + => IR ??= new(Name); + + CompilerObject IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + => context.CompileTimeValues.Cache(this, out var result) ? result : this; } } diff --git a/ZSharp.Compiler.Objects/oop/Class.cs b/ZSharp.Compiler.Objects/oop/Class.cs index 8e456f3f..9b9ab7c6 100644 --- a/ZSharp.Compiler.Objects/oop/Class.cs +++ b/ZSharp.Compiler.Objects/oop/Class.cs @@ -1,9 +1,65 @@ -namespace ZSharp.Objects +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects { - public abstract class Class(Compiler.Compiler compiler, ClassSpec spec) + public sealed class Class + : CompilerObject + , ICompileIRObject { - public abstract string Name { get; } + [Flags] + enum BuildState + { + None = 0, + Base = 0b1, + Interfaces = 0b10, + Body = 0b100, + Owner = 0b1000, + } + private readonly ObjectBuildState state = new(); + + public IR.Class? IR { get; private set; } + + public string? Name { get; set; } + + public CompilerObject? Base { get; set; } + + public Collection Interfaces { get; } = []; + + public Collection Content { get; } = []; + + IR.Class ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) + { + IR ??= new(Name); + + if (Base is not null && !state[BuildState.Base]) + { + state[BuildState.Base] = true; + + IR.Base = compiler.CompileIRReference>(Base); + } + + if (Interfaces.Count > 0 && !state[BuildState.Interfaces]) + { + throw new NotImplementedException($"Interfaces are not supported yet."); + } + + if (Content.Count > 0 && !state[BuildState.Body]) + { + state[BuildState.Body] = true; + + foreach (var item in Content) + compiler.CompileIRObject(item, IR); + } + + if (owner is not null && !state[BuildState.Owner]) + { + state[BuildState.Owner] = true; + + owner.Types.Add(IR); + } - public abstract Class Base { get; } + return IR; + } } } diff --git a/ZSharp.Compiler.Objects/oop/GenericClass.cs b/ZSharp.Compiler.Objects/oop/GenericClass.cs index 160b2830..738f6e1a 100644 --- a/ZSharp.Compiler.Objects/oop/GenericClass.cs +++ b/ZSharp.Compiler.Objects/oop/GenericClass.cs @@ -5,9 +5,10 @@ namespace ZSharp.Objects { public class GenericClass : CompilerObject + , ICTGetIndex , ICTGetMember , IRTGetMember - , IReferencable + , IReferencable , ICompileIRObject , IEvaluable { @@ -19,16 +20,27 @@ enum BuildState Interfaces = 0b10, Body = 0b100, Owner = 0b1000, + Generic = 0b10000, } private readonly ObjectBuildState state = new(); public IR.ConstructedClass? IR { get; set; } - public string Name { get; set; } + public string Name { get; set; } = string.Empty; + + public bool Defined { init + { + if (value) + { + foreach (var item in Enum.GetValues()) + state[item] = true; + } + } + } public Collection GenericParameters { get; set; } = []; - public GenericClassInstance? Base { get; set; } + public CompilerObject? Base { get; set; } public Mapping Implementations { get; set; } = []; @@ -41,31 +53,39 @@ enum BuildState public CompilerObject Member(Compiler.Compiler compiler, MemberName member) => Members[member]; - public CompilerObject CreateReference(Compiler.Compiler compiler, ReferenceContext context) + public GenericClassInstance CreateReference(Referencing @ref, ReferenceContext context) { - int currentErrors = compiler.Log.Logs.Count(l => l.Level == LogLevel.Error); + int currentErrors = @ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error); foreach (var genericParameter in GenericParameters) - if (!context.CompileTimeValues.ContainsKey(genericParameter)) - compiler.Log.Error( - $"Missing generic argument for parameter {genericParameter.Name} in type {this.Name}", + if (!context.CompileTimeValues.Contains(genericParameter)) + @ref.Compiler.Log.Error( + $"Missing generic argument for parameter {genericParameter.Name} in type {Name}", this ); - if (compiler.Log.Logs.Count(l => l.Level == LogLevel.Error) > currentErrors) + if (@ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error) > currentErrors) throw new(); // TODO: Huh??? - Mapping genericArguments = []; - - foreach (var genericParameter in GenericParameters) - genericArguments[genericParameter] = context.CompileTimeValues[genericParameter]; - - return new GenericClassInstance(this, genericArguments) + return new GenericClassInstance(this) { - Context = context, + Context = new(context) + { + Scope = this + }, }; } + CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) + { + var context = new ReferenceContext(); + + foreach (var (genericParameter, genericArgument) in GenericParameters.Zip(index)) + context[genericParameter] = genericArgument.Object; + + return compiler.Feature().CreateReference(this, context); + } + IR.Class ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) { IR.Class @class = IR?.Class ?? new(Name); @@ -83,7 +103,7 @@ public CompilerObject CreateReference(Compiler.Compiler compiler, ReferenceConte { state.Set(BuildState.Base); - @class.Base = compiler.CompileIRType(Base); + @class.Base = compiler.CompileIRType>(Base); } if (Content.Count > 0 && !state.Get(BuildState.Body)) @@ -94,6 +114,15 @@ public CompilerObject CreateReference(Compiler.Compiler compiler, ReferenceConte compiler.CompileIRObject(item, @class); } + if (GenericParameters.Count > 0 && !state.Get(BuildState.Generic)) + { + state.Set(BuildState.Generic); + foreach (var parameter in GenericParameters) + @class.GenericParameters.Add( + compiler.CompileIRType(parameter) + ); + } + return @class; } @@ -102,11 +131,20 @@ CompilerObject IEvaluable.Evaluate(Compiler.Compiler compiler) if (GenericParameters.Count != 0) return this; - return new GenericClassInstance(this, []); + return new GenericClassInstance(this) + { + Context = new() + { + Scope = this + } + }; } CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerObject value, string member) { + if (GenericParameters.Count > 0) + throw new InvalidOperationException(); + var memberObject = compiler.Member(this, member); if (memberObject is IRTBoundMember boundMember) diff --git a/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs index d5def350..2c5f34ce 100644 --- a/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs +++ b/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs @@ -4,8 +4,7 @@ namespace ZSharp.Objects { public sealed class GenericClassInstance( - GenericClass origin, - Mapping genericArguments + GenericClass origin ) : CompilerObject , ICTGetMember @@ -13,15 +12,16 @@ Mapping genericArguments , ICTCallable , IReference , ICompileIRType + , ICompileIRReference> + , ICompileIRReference + , IReferencable { CompilerObject IReference.Origin => Origin; - public ReferenceContext? Context { get; set; } = null; + public required ReferenceContext Context { get; set; } = null; public GenericClass Origin { get; set; } = origin; - public Mapping Arguments { get; set; } = genericArguments; - public Mapping Members { get; set; } = []; public CompilerObject Member(Compiler.Compiler compiler, string member) @@ -30,7 +30,7 @@ public CompilerObject Member(Compiler.Compiler compiler, string member) var origin = compiler.Member(Origin, member); - if (Arguments.Count != 0) + if (Origin.GenericParameters.Count != 0) //origin = compiler.CreateReference(origin, Context); throw new NotImplementedException(); @@ -43,23 +43,9 @@ public CompilerObject Member(Compiler.Compiler compiler, CompilerObject instance var origin = compiler.Member(Origin, member); - if (Arguments.Count != 0) - //origin = compiler.CreateReference(origin, Context); - throw new NotImplementedException(); - - if (origin is IRTBoundMember boundMember) - return boundMember.Bind(compiler, instance); - - if (origin is OverloadGroup group) - return new OverloadGroup(group.Name) - { - Overloads = [.. group.Overloads.Select( - overload => overload is IRTBoundMember boundMember ? - boundMember.Bind(compiler, instance) : overload - )], - }; + Members[member] = origin = compiler.Map(origin, @object => compiler.Feature().CreateReference(@object, Context)); - return Members[member] = origin; + return compiler.Map(origin, @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, instance) : @object); } IR.ConstructedClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) @@ -69,7 +55,7 @@ public CompilerObject Member(Compiler.Compiler compiler, CompilerObject instance ); foreach (var parameter in Origin.GenericParameters) - result.Arguments.Add(compiler.CompileIRType(Arguments[parameter])); + result.Arguments.Add(compiler.CompileIRType(Context.CompileTimeValues.Cache(parameter) ?? throw new())); return result; } @@ -78,13 +64,50 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments { CompilerObject? constructor = null; - if (Origin.GenericParameters.Count == 0) - constructor = Origin.Constructor; + //if (Origin.GenericParameters.Count == 0) + constructor = Origin.Constructor; if (constructor is null) throw new NotImplementedException(); + var @ref = compiler.Feature(); + + if (Context is not null) + constructor = compiler.Map(constructor, @object => @ref.CreateReference(@object, Context)); + return compiler.Call(constructor, arguments); } + + IR.OOPTypeReference ICompileIRReference>.CompileIRReference(Compiler.Compiler compiler) + => compiler.CompileIRType(this); + + GenericClassInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + { + Mapping arguments = []; + + return new(Origin) + { + Context = context + }; + } + + public override bool Equals(object? obj) + { + // TODO: instead of type == type, use assignable to + if (obj is not GenericClassInstance other) + return false; + + if (Origin != other.Origin) + return false; + + foreach (var genericParameter in Origin.GenericParameters) + if (Context[genericParameter] != other.Context[genericParameter]) + return false; + + return true; + } + + IR.OOPTypeReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + => compiler.CompileIRType(this); } } diff --git a/ZSharp.Compiler.Objects/oop/Constructor.cs b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs similarity index 85% rename from ZSharp.Compiler.Objects/oop/Constructor.cs rename to ZSharp.Compiler.Objects/oop/constructor/Constructor.cs index ce5b5ee2..fc0dac92 100644 --- a/ZSharp.Compiler.Objects/oop/Constructor.cs +++ b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs @@ -1,11 +1,16 @@ using ZSharp.Compiler; +using Args = CommonZ.Utils.Collection; +using KwArgs = CommonZ.Utils.Mapping; + + namespace ZSharp.Objects { public sealed class Constructor(string? name) : CompilerObject , ICTCallable , ICompileIRObject + , IReferencable { [Flags] enum BuildState @@ -50,15 +55,20 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) } else { - if (Owner is null) - throw new(); + var type = Owner ?? Signature.Args[0].Type; hasReturn = true; - invocationInstruction = new IR.VM.CreateInstance(IR!); + invocationInstruction = new IR.VM.CreateInstance(new IR.ConstructorReference(IR!) + { + OwningType = (IR?.Method.Owner is null + ? IR!.Method.Signature.Args.Parameters[0].Type as IR.OOPTypeReference + : new IR.ClassReference(IR!.Method.Owner as IR.Class ?? throw new())) + ?? throw new() + }); args.Insert(0, new RawCode(new() { - Types = [Owner] + Types = [type] })); } @@ -98,7 +108,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) result.Types.Clear(); if (hasReturn) - result.Types.Add(Owner ?? throw new()); + result.Types.Add(Owner ?? Signature.Args[0].Type); result.MaxStackSize = Math.Max(result.MaxStackSize, result.Types.Count); @@ -146,5 +156,10 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) return IR; } + + ConstructorReference IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + { + return new(this, context); + } } } diff --git a/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs b/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs new file mode 100644 index 00000000..934fc214 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs @@ -0,0 +1,43 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class ConstructorReference(Constructor origin, ReferenceContext context) + : CompilerObject + , ICTCallable + { + public Constructor Origin { get; } = origin; + + public ReferenceContext Context { get; } = context; + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + var result = compiler.Call(Origin, arguments); + + if (result is not RawCode rawCode) + throw new(); + + var owner = Origin.Owner; + if (owner is null) + throw new(); + + var ownerReference = compiler.Feature().CreateReference(owner, Context); + + var invocationInstruction = rawCode.Code.Instructions.Last(); + if (invocationInstruction is IR.VM.CreateInstance createInstance) + { + var type = compiler.CompileIRReference>(ownerReference); + + createInstance.Constructor = new IR.ConstructorReference(createInstance.Constructor.Member) + { + OwningType = type + }; + + rawCode.Code.Types.Clear(); + rawCode.Code.Types.Add(ownerReference); + } + + return rawCode; + } + } +} diff --git a/ZSharp.Compiler.Objects/oop/field/BoundField.cs b/ZSharp.Compiler.Objects/oop/field/BoundField.cs index c48b48db..f666bf06 100644 --- a/ZSharp.Compiler.Objects/oop/field/BoundField.cs +++ b/ZSharp.Compiler.Objects/oop/field/BoundField.cs @@ -23,7 +23,9 @@ public CompilerObject Assign(Compiler.Compiler compiler, CompilerObject value) new IR.VM.Dup(), ..instanceCode.Instructions, new IR.VM.Swap(), - new IR.VM.SetField(Field.IR!), + new IR.VM.SetField(new IR.FieldReference(Field.IR!) { + OwningType = new IR.ClassReference(Field.IR!.Owner ?? throw new()) + }), ]) { MaxStackSize = Math.Max(Math.Max(instanceCode.MaxStackSize, valueCode.MaxStackSize), 2), @@ -37,7 +39,9 @@ public IRCode Read(Compiler.Compiler compiler) return new([ ..code.Instructions, - new IR.VM.GetField(Field.IR!) + new IR.VM.GetField(new IR.FieldReference(Field.IR!) { + OwningType = new IR.ClassReference(Field.IR!.Owner ?? throw new()) + }) ]) { MaxStackSize = Math.Max(code.MaxStackSize, 1), diff --git a/ZSharp.Compiler.Objects/oop/method/Method.cs b/ZSharp.Compiler.Objects/oop/method/Method.cs index 93fbc04c..89413a01 100644 --- a/ZSharp.Compiler.Objects/oop/method/Method.cs +++ b/ZSharp.Compiler.Objects/oop/method/Method.cs @@ -1,6 +1,10 @@ using System.Diagnostics.CodeAnalysis; using ZSharp.Compiler; +using Args = CommonZ.Utils.Collection; +using KwArgs = CommonZ.Utils.Mapping; + + namespace ZSharp.Objects { public sealed class Method(string? name) @@ -8,6 +12,8 @@ public sealed class Method(string? name) , IRTBoundMember , ICTCallable , ICompileIRObject + , ICompileIRObject + , IReferencable { [Flags] enum BuildState @@ -20,6 +26,14 @@ enum BuildState private readonly ObjectBuildState state = new(); + public bool Defined { init + { + if (value) + foreach (var item in Enum.GetValues()) + state[item] = true; + } + } + public IR.Method? IR { get; set; } public string? Name { get; set; } = name; @@ -144,5 +158,66 @@ public IR.Method CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) return IR; } + + MethodReference IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + { + if (context.Scope is not GenericClassInstance genericClassInstance) + genericClassInstance = (GenericClassInstance)@ref.CreateReference(context.Scope, context); + + return new(this, context) + { + Owner = genericClassInstance, + //ReturnType = ReturnType is null ? null : @ref.CreateReference(ReturnType, context), + Signature = @ref.CreateReference(Signature, context), + }; + } + + IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.OOPType? owner) + { + IR ??= + new( + compiler.CompileIRType( + ReturnType ?? throw new PartiallyCompiledObjectException( + this, + Errors.UndefinedReturnType(Name) + ) + ) + ) + { + Name = Name, + IsInstance = true, + }; + + if (!state.Get(BuildState.Signature)) + { + state.Set(BuildState.Signature); + + foreach (var arg in Signature.Args) + IR.Signature.Args.Parameters.Add(compiler.CompileIRObject(arg, IR.Signature)); + + if (Signature.VarArgs is not null) + IR.Signature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, IR.Signature); + + foreach (var kwArg in Signature.KwArgs) + IR.Signature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, IR.Signature)); + + if (Signature.VarKwArgs is not null) + IR.Signature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, IR.Signature); + } + + if (Body is not null && !state.Get(BuildState.Body)) + { + state.Set(BuildState.Body); + + IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); + } + + return IR; + } + + IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) + { + throw new NotImplementedException(); + } } } diff --git a/ZSharp.Compiler.Objects/oop/method/MethodReference.cs b/ZSharp.Compiler.Objects/oop/method/MethodReference.cs new file mode 100644 index 00000000..a7c234fe --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/MethodReference.cs @@ -0,0 +1,104 @@ +using ZSharp.Compiler; + +using Args = CommonZ.Utils.Collection; +using KwArgs = CommonZ.Utils.Mapping; + + +namespace ZSharp.Objects +{ + public sealed class MethodReference(Method origin, ReferenceContext context) + : CompilerObject + , ICTCallable + , ICompileIRReference> + , IRTBoundMember + { + public Method Origin { get; } = origin; + + public ReferenceContext Context { get; } = context; + + public required CompilerObject Owner { get; init; } + + public required Signature Signature { get; init; } + + public IR.Signature? SignatureIR { get; private set; } + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + if (Origin.ReturnType is null) + throw new NotImplementedException(); + + var args = (Signature as ISignature).MatchArguments(compiler, arguments); + + IRCode code = new(); + + List @params = []; + + @params.AddRange(Signature.Args); + + if (Signature.VarArgs is not null) + @params.Add(Signature.VarArgs); + + @params.AddRange(Signature.KwArgs); + + if (Signature.VarKwArgs is not null) + @params.Add(Signature.VarKwArgs); + + foreach (var param in @params) + code.Append(compiler.CompileIRCode(args[param])); + + code.Append(new([ + new IR.VM.Call((IR.MethodReference)compiler.CompileIRReference>(this)) + ])); + + code.Types.Clear(); + if (Origin.ReturnType != compiler.TypeSystem.Void) + code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); + + return new RawCode(code); + } + + IR.MemberReference ICompileIRReference>.CompileIRReference(Compiler.Compiler compiler) + { + var type = compiler.Feature().CreateReference(Owner, Context); + + return new IR.MethodReference(compiler.CompileIRObject(Origin, null!)) + { + OwningType = compiler.CompileIRReference(type), + Signature = SignatureIR ?? CompileSignature(compiler) + }; + } + + CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) + { + return new PartialCall(this) + { + Arguments = [new(value)] + }; + } + + private IR.Signature CompileSignature(Compiler.Compiler compiler) + { + if (SignatureIR is not null) + return SignatureIR; + + if (Origin.ReturnType is null) + throw new NotImplementedException(); + + SignatureIR = new(compiler.CompileIRType(compiler.Feature().CreateReference(Origin.ReturnType, Context))); + + foreach (var arg in Signature.Args) + SignatureIR.Args.Parameters.Add(compiler.CompileIRObject(arg, SignatureIR)); + + if (Signature.VarArgs is not null) + SignatureIR.Args.Var = compiler.CompileIRObject(Signature.VarArgs, SignatureIR); + + foreach (var kwArg in Signature.KwArgs) + SignatureIR.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, SignatureIR)); + + if (Signature.VarKwArgs is not null) + SignatureIR.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, SignatureIR); + + return SignatureIR; + } + } +} diff --git a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs index fa1ccb62..923744d2 100644 --- a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs +++ b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs @@ -6,6 +6,7 @@ namespace ZSharp.Objects public sealed class OverloadGroup(string name) : CompilerObject , ICTCallable + , IMappable { public string Name { get; set; } = name; @@ -29,5 +30,13 @@ public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) return matchingOverloads[0]; } + + CompilerObject IMappable.Map(Func func) + { + return new OverloadGroup(Name) + { + Overloads = [.. Overloads.Select(func)] + }; + } } } diff --git a/ZSharp.Compiler.Objects/referencing/IReferencable.cs b/ZSharp.Compiler.Objects/referencing/IReferencable.cs deleted file mode 100644 index 7f986c64..00000000 --- a/ZSharp.Compiler.Objects/referencing/IReferencable.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IReferencable - { - public CompilerObject CreateReference(Compiler.Compiler compiler, ReferenceContext context); - } -} diff --git a/ZSharp.Compiler.Objects/referencing/ReferenceContext.cs b/ZSharp.Compiler.Objects/referencing/ReferenceContext.cs deleted file mode 100644 index 1fb3e0d2..00000000 --- a/ZSharp.Compiler.Objects/referencing/ReferenceContext.cs +++ /dev/null @@ -1,14 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Objects -{ - public sealed class ReferenceContext - { - public Mapping CompileTimeValues { get; set; } = []; - - public static ReferenceContext Empty { get; } = new() - { - CompileTimeValues = [] - }; - } -} diff --git a/ZSharp.Compiler.Objects/signature/IKeywordVarParameter.cs b/ZSharp.Compiler.Objects/signature/IKeywordVarParameter.cs new file mode 100644 index 00000000..44bc39a9 --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/IKeywordVarParameter.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Objects +{ + public interface IKeywordVarParameter : CompilerObject + { + public CompilerObject MatchArguments(Compiler.Compiler compiler, Dictionary argument); + } +} diff --git a/ZSharp.Compiler.Objects/signature/IParameter.cs b/ZSharp.Compiler.Objects/signature/IParameter.cs new file mode 100644 index 00000000..a80990cc --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/IParameter.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Objects +{ + public interface IParameter : CompilerObject + { + public string Name { get; } + + public CompilerObject? Default { get; } + + public CompilerObject MatchArgument(Compiler.Compiler compiler, CompilerObject argument); + } +} diff --git a/ZSharp.Compiler.Objects/signature/ISignature.cs b/ZSharp.Compiler.Objects/signature/ISignature.cs new file mode 100644 index 00000000..1fb988c8 --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/ISignature.cs @@ -0,0 +1,82 @@ +using CommonZ.Utils; + +using Args = CommonZ.Utils.Collection; +using KwArgs = CommonZ.Utils.Mapping; + + +namespace ZSharp.Objects +{ + public interface ISignature : CompilerObject + { + public IEnumerable? GetArgs(Compiler.Compiler compiler); + + public IVarParameter? GetVarArgs(Compiler.Compiler compiler); + + public IEnumerable? GetKwArgs(Compiler.Compiler compiler); + + public IKeywordVarParameter? GetVarKwArgs(Compiler.Compiler compiler); + + public Mapping MatchArguments(Compiler.Compiler compiler, Compiler.Argument[] arguments) + { + var (args, kwArgs) = Utils.SplitArguments(arguments); + + try + { + return MatchArguments(compiler, args, kwArgs); + } catch (ArgumentsCountMismatchException argumentsCountMismatch) + { + throw new ArgumentMismatchException(this, arguments, innerException: argumentsCountMismatch); + } + } + + public Mapping MatchArguments(Compiler.Compiler compiler, Args args, KwArgs kwArgs) + { + var @params = GetArgs(compiler)?.ToList() ?? []; + var varParams = GetVarArgs(compiler); + var kwParams = GetKwArgs(compiler)?.ToList() ?? []; + var varKwParams = GetVarKwArgs(compiler); + + if (args.Count > @params.Count && varParams is null) + throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}."); + + if (kwArgs.Count > kwParams.Count && varKwParams is null) + throw new ArgumentsCountMismatchException($"Expected {kwParams.Count} named arguments but got {kwArgs.Count}."); + + Mapping result = []; + + var positionalArgumentsQueue = new Queue(args); + + foreach (var param in @params) + { + if (!positionalArgumentsQueue.TryDequeue(out var arg)) + arg = param.Default ?? throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); + + result[param] = param.MatchArgument(compiler, arg); + } + + if (varParams is not null) + result[varParams] = varParams.MatchArguments(compiler, [.. positionalArgumentsQueue]); + else if (positionalArgumentsQueue.Count > 0) + throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); + + var keywordArguments = kwArgs.ToDictionary(); + + foreach (var kwParam in kwParams) + { + if (!kwArgs.TryGetValue(kwParam.Name, out var kwArg)) + kwArg = kwParam.Default ?? throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); + else + keywordArguments.Remove(kwParam.Name); + + result[kwParam] = kwArg; + } + + if (varKwParams is not null) + result[varKwParams] = varKwParams.MatchArguments(compiler, keywordArguments); + else if (keywordArguments.Count > 0) + throw new ArgumentsCountMismatchException($"Expected {@params.Count} named arguments but got {args.Count}"); + + return result; + } + } +} diff --git a/ZSharp.Compiler.Objects/signature/IVarParameter.cs b/ZSharp.Compiler.Objects/signature/IVarParameter.cs new file mode 100644 index 00000000..8cc7776a --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/IVarParameter.cs @@ -0,0 +1,9 @@ +using CommonZ.Utils; + +namespace ZSharp.Objects +{ + public interface IVarParameter : CompilerObject + { + public CompilerObject MatchArguments(Compiler.Compiler compiler, CompilerObject[] argument); + } +} diff --git a/ZSharp.Compiler.Objects/signature/exceptions/ArgumentsCountMismatchException.cs b/ZSharp.Compiler.Objects/signature/exceptions/ArgumentsCountMismatchException.cs new file mode 100644 index 00000000..4f7962e5 --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/exceptions/ArgumentsCountMismatchException.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Objects +{ + internal sealed class ArgumentsCountMismatchException : Exception + { + public ArgumentsCountMismatchException() : base() { } + + public ArgumentsCountMismatchException(string? message) : base(message) { } + + public ArgumentsCountMismatchException(string? message, Exception? innerException) : base(message, innerException) { } + } +} diff --git a/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs b/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs index 7f3411d8..5c1f6a6b 100644 --- a/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs +++ b/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs @@ -11,5 +11,18 @@ public void Set(T state) { State = (T)(ValueType)(State.ToInt32(null) | state.ToInt32(null)); } + + public static bool operator &(ObjectBuildState instance, T value) + => instance.Get(value); + + public bool this[T flag] + { + get => Get(flag); + set + { + if (value) + Set(flag); + } + } } } diff --git a/ZSharp.Compiler/GlobalUsings.cs b/ZSharp.Compiler/GlobalUsings.cs index c6f6ef04..9fdd27c8 100644 --- a/ZSharp.Compiler/GlobalUsings.cs +++ b/ZSharp.Compiler/GlobalUsings.cs @@ -5,9 +5,6 @@ global using DefaultIntegerType = int; -global using Args = CommonZ.Utils.Collection; -global using KwArgs = CommonZ.Utils.Mapping; - global using IRInstructions = CommonZ.Utils.Collection; global using CompilerObject = ZSharp.Objects.CompilerObject; diff --git a/ZSharp.Compiler/cg objects/Utils.cs b/ZSharp.Compiler/cg objects/Utils.cs index c53a71bb..ef54a10f 100644 --- a/ZSharp.Compiler/cg objects/Utils.cs +++ b/ZSharp.Compiler/cg objects/Utils.cs @@ -1,5 +1,9 @@ using ZSharp.Compiler; +using Args = CommonZ.Utils.Collection; +using KwArgs = CommonZ.Utils.Mapping; + + namespace ZSharp.Objects { public static class Utils diff --git a/ZSharp.Compiler/cg objects/functional/signature/Signature.cs b/ZSharp.Compiler/cg objects/functional/signature/Signature.cs deleted file mode 100644 index 8313ef23..00000000 --- a/ZSharp.Compiler/cg objects/functional/signature/Signature.cs +++ /dev/null @@ -1,17 +0,0 @@ -using ZSharp.Compiler; - -using Parameters = CommonZ.Utils.Collection; - -namespace ZSharp.Objects -{ - public sealed class Signature : CompilerObject - { - public Parameters Args { get; init; } = []; - - public Parameter? VarArgs { get; set; } - - public Parameters KwArgs { get; init; } = []; - - public Parameter? VarKwArgs { get; set; } - } -} diff --git a/ZSharp.Compiler/cg objects/types/Int32Type.cs b/ZSharp.Compiler/cg objects/types/Int32Type.cs index cfd405c7..48066519 100644 --- a/ZSharp.Compiler/cg objects/types/Int32Type.cs +++ b/ZSharp.Compiler/cg objects/types/Int32Type.cs @@ -3,12 +3,12 @@ namespace ZSharp.Objects { - public sealed class Int32Type(IR.ConstructedClass ir, CompilerObject type) + public sealed class Int32Type(IR.OOPTypeReference ir, CompilerObject type) : CompilerObject , ICompileIRType , ICTGetMember { - public IR.ConstructedClass IR { get; } = ir; + public IR.OOPTypeReference IR { get; } = ir; public CompilerObject Type { get; } = type; diff --git a/ZSharp.Compiler/cg objects/types/StringType.cs b/ZSharp.Compiler/cg objects/types/StringType.cs index abe65662..e1158cfe 100644 --- a/ZSharp.Compiler/cg objects/types/StringType.cs +++ b/ZSharp.Compiler/cg objects/types/StringType.cs @@ -2,12 +2,12 @@ namespace ZSharp.Objects { - public sealed class StringType(IR.ConstructedClass stringType, CompilerObject type) + public sealed class StringType(IR.OOPTypeReference stringType, CompilerObject type) : CompilerObject , ICompileIRType , ICTCallable { - public IR.ConstructedClass IR { get; } = stringType; + public IR.OOPTypeReference IR { get; } = stringType; public CompilerObject Type { get; } = type; diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs index b7990d97..29a8cd54 100644 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs +++ b/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs @@ -70,6 +70,17 @@ public T CompileIRType(CompilerObject @object) if ((irType = @object as ICompileIRType) is not null) return irType.CompileIRType(this); + if (@object is ICompileIRType irUntypedType) + return (T)irUntypedType.CompileIRType(this); + + throw new NotImplementedException(); // TODO: return null + } + + public T CompileIRReference(CompilerObject @object) + { + if (@object is ICompileIRReference irReference) + return irReference.CompileIRReference(this); + throw new NotImplementedException(); // TODO: return null } } diff --git a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs index 2321e6c3..d34f9a2c 100644 --- a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs +++ b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs @@ -32,7 +32,7 @@ public CompilerObject Call(CompilerObject target, Argument[] arguments) public CompilerObject Cast(CompilerObject target, CompilerObject type) { - if (TypeSystem.IsTyped(target, out var targetType) && targetType == type) + if (TypeSystem.IsTyped(target, out var targetType) && targetType.Equals(type)) return target; if (target is ICTTypeCast typeCast) @@ -49,6 +49,9 @@ public CompilerObject Cast(CompilerObject target, CompilerObject type) /// public CompilerObject Index(CompilerObject instanceTarget, Argument[] index) { + if (instanceTarget is ICTGetIndex ctGetIndex) + return ctGetIndex.Index(this, index); + throw new NotImplementedException(); } @@ -64,6 +67,14 @@ public CompilerObject Index(CompilerObject instanceTarget, Argument[] index, Com throw new NotImplementedException(); } + public CompilerObject Map(CompilerObject @object, Func func) + { + if (@object is IMappable mappable) + return mappable.Map(func); + + return func(@object); + } + /// /// The member (.) operator. /// diff --git a/ZSharp.Compiler/compiler core/core/inference/Constraint.cs b/ZSharp.Compiler/compiler core/core/inference/Constraint.cs new file mode 100644 index 00000000..95273a95 --- /dev/null +++ b/ZSharp.Compiler/compiler core/core/inference/Constraint.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public abstract class Constraint + { + public CompilerObject Target { get; internal set; } = null!; + } +} diff --git a/ZSharp.Compiler/compiler core/core/inference/InferenceScope.cs b/ZSharp.Compiler/compiler core/core/inference/InferenceScope.cs new file mode 100644 index 00000000..4f20e430 --- /dev/null +++ b/ZSharp.Compiler/compiler core/core/inference/InferenceScope.cs @@ -0,0 +1,42 @@ +using CommonZ.Utils; + +namespace ZSharp.Compiler +{ + public delegate bool InferenceTargetResolver(InferenceTarget target); + + public sealed class InferenceScope(Compiler compiler, InferenceScope? parent) + : IDisposable + { + public Compiler Compiler { get; } = compiler; + + public InferenceScope? Parent { get; } = parent; + + public required InferenceTargetResolver DefaultResolver { get; set; } + + public Collection Targets { get; private set; } = []; + + public void Dispose() + { + if (!Resolve()) + PushToParent(); + } + + public bool Resolve() + { + Collection notResolved = []; + + foreach (var target in Targets) + if (!(target.Resolve ?? DefaultResolver)(target)) + notResolved.Add(target); + + return (Targets = notResolved).Count > 0; + } + + public void PushToParent() + { + Parent?.Targets.AddRange(Targets); + + Targets.Clear(); + } + } +} diff --git a/ZSharp.Compiler/compiler core/core/inference/InferenceTarget.cs b/ZSharp.Compiler/compiler core/core/inference/InferenceTarget.cs new file mode 100644 index 00000000..f8d9dea0 --- /dev/null +++ b/ZSharp.Compiler/compiler core/core/inference/InferenceTarget.cs @@ -0,0 +1,13 @@ +using CommonZ.Utils; + +namespace ZSharp.Compiler +{ + public sealed class InferenceTarget(CompilerObject target) + { + public CompilerObject Target { get; } = target; + + public Collection Constraints { get; } = new(); + + public InferenceTargetResolver? Resolve { get; set; } + } +} diff --git a/ZSharp.Compiler/core/CompilerObject.cs b/ZSharp.Compiler/core/CompilerObject.cs index 69be0950..8e238ec9 100644 --- a/ZSharp.Compiler/core/CompilerObject.cs +++ b/ZSharp.Compiler/core/CompilerObject.cs @@ -1,6 +1,6 @@ namespace ZSharp.Objects { - public abstract class CompilerObject + public interface CompilerObject { } } diff --git a/ZSharp.Compiler/core/concepts/IMappable.cs b/ZSharp.Compiler/core/concepts/IMappable.cs new file mode 100644 index 00000000..0d34c8a1 --- /dev/null +++ b/ZSharp.Compiler/core/concepts/IMappable.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IMappable + : CompilerObject + { + public CompilerObject Map(Func func); + } +} diff --git a/ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs b/ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs new file mode 100644 index 00000000..adf69aff --- /dev/null +++ b/ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTGetIndex + { + public CompilerObject Index(Compiler compiler, Argument[] index); + } +} diff --git a/ZSharp.Compiler/core/concepts/index/IGetIndex.cs b/ZSharp.Compiler/core/concepts/index/IGetIndex.cs deleted file mode 100644 index 450ddbd7..00000000 --- a/ZSharp.Compiler/core/concepts/index/IGetIndex.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - internal interface IGetIndex - { - public CompilerObject Index(T @object, Argument[] index); - } -} diff --git a/ZSharp.Compiler/exceptions/CompilerObjectException.cs b/ZSharp.Compiler/exceptions/CompilerObjectException.cs index 6890ec67..a22c3937 100644 --- a/ZSharp.Compiler/exceptions/CompilerObjectException.cs +++ b/ZSharp.Compiler/exceptions/CompilerObjectException.cs @@ -1,7 +1,7 @@ namespace ZSharp.Compiler { - public abstract class CompilerObjectException(CompilerObject @object, string? message = null) - : Exception(message) + public abstract class CompilerObjectException(CompilerObject @object, string? message = null, Exception? innerException = null) + : Exception(message, innerException) { public CompilerObject Object { get; } = @object; } diff --git a/ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs b/ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs new file mode 100644 index 00000000..5c90ba4e --- /dev/null +++ b/ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICompileIRReference + { + public T CompileIRReference(Compiler compiler); + } +} diff --git a/ZSharp.IR/ir/custom metadata/CustomMetadata.cs b/ZSharp.IR/ir/custom metadata/CustomMetadata.cs new file mode 100644 index 00000000..28438ff8 --- /dev/null +++ b/ZSharp.IR/ir/custom metadata/CustomMetadata.cs @@ -0,0 +1,9 @@ +namespace ZSharp.IR +{ + public sealed class CustomMetadata + { + public ICallable Constructor { get; set; } + + public object[] Arguments { get; set; } + } +} diff --git a/ZSharp.IR/ir/custom metadata/ICustomMetadataProvider.cs b/ZSharp.IR/ir/custom metadata/ICustomMetadataProvider.cs new file mode 100644 index 00000000..440f682c --- /dev/null +++ b/ZSharp.IR/ir/custom metadata/ICustomMetadataProvider.cs @@ -0,0 +1,11 @@ +using CommonZ.Utils; + +namespace ZSharp.IR +{ + public interface ICustomMetadataProvider + { + public Collection CustomMetadata { get; } + + public bool HasCustomMetadata => CustomMetadata.Count > 0; + } +} diff --git a/ZSharp.IR/ir/oop/Class.cs b/ZSharp.IR/ir/oop/Class.cs index 6e1aff38..4c0b7e86 100644 --- a/ZSharp.IR/ir/oop/Class.cs +++ b/ZSharp.IR/ir/oop/Class.cs @@ -2,11 +2,16 @@ namespace ZSharp.IR { - public sealed class Class(string? name) : OOPType + public sealed class Class(string? name) + : OOPType + , ICustomMetadataProvider { + private Collection? _customMetadata; private Collection? _genericParameters; + private Collection? _constructors; private FieldCollection? _fields; + private Collection? _methods; public string? Name { get; set; } = name; @@ -20,6 +25,20 @@ public Class(string? name, OOPTypeReference? @base) Base = @base; } + public Collection CustomMetadata + { + get + { + if (_customMetadata is not null) + return _customMetadata; + + Interlocked.CompareExchange(ref _customMetadata, [], null); + return _customMetadata; + } + } + + public bool HasCustomMetadata => !_customMetadata.IsNullOrEmpty(); + public Collection InterfacesImplementations { get; } = []; public Collection GenericParameters @@ -36,6 +55,21 @@ public Collection GenericParameters public bool HasGenericParameters => !_genericParameters.IsNullOrEmpty(); + public Collection Constructors + { + get + { + if (_constructors is not null) + return _constructors; + + Interlocked.CompareExchange(ref _constructors, [], null); + + return _constructors; + } + } + + public bool HasConstructors => !_constructors.IsNullOrEmpty(); + public Collection Fields { get @@ -50,14 +84,25 @@ public Collection Fields public bool HasFields => !_fields.IsNullOrEmpty(); - public Collection Methods { get; } = []; + public Collection Methods + { + get + { + if (_methods is not null) + return _methods; + + Interlocked.CompareExchange(ref _methods, [], null); + + return _methods; + } + } + + public bool HasMethods => !_methods.IsNullOrEmpty(); public Collection Properties { get; } = []; - //public Collection NestedTypes { get; } = new(); + public Collection NestedTypes { get; } = []; //public Collection Events { get; } - - public Collection Constructors { get; } = []; } } diff --git a/ZSharp.IR/ir/oop/Constructor.cs b/ZSharp.IR/ir/oop/constructor/Constructor.cs similarity index 100% rename from ZSharp.IR/ir/oop/Constructor.cs rename to ZSharp.IR/ir/oop/constructor/Constructor.cs diff --git a/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs b/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs new file mode 100644 index 00000000..5a66735a --- /dev/null +++ b/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs @@ -0,0 +1,17 @@ +namespace ZSharp.IR +{ + public sealed class ConstructorReference(Constructor constructor) + : MemberReference + , ICallable + { + public Constructor Member { get; set; } = constructor; + + public required OOPTypeReference OwningType { get; set; } + + public Signature Signature => Member.Method.Signature; + + public bool HasBody => Member.Method.HasBody; + + public ICallableBody? Body => Member.Method.HasBody ? Member.Method.Body : null; + } +} diff --git a/ZSharp.IR/ir/oop/method/MethodReference.cs b/ZSharp.IR/ir/oop/method/MethodReference.cs index 1ce70e0a..c5ad79d7 100644 --- a/ZSharp.IR/ir/oop/method/MethodReference.cs +++ b/ZSharp.IR/ir/oop/method/MethodReference.cs @@ -8,7 +8,7 @@ public sealed class MethodReference(Method method) public required OOPTypeReference OwningType { get; set; } - public Signature Signature => Member.Signature; + public Signature Signature { get; init; } = method.Signature; public bool HasBody => Member.HasBody; diff --git a/ZSharp.IR/type system/RuntimeModule.cs b/ZSharp.IR/type system/RuntimeModule.cs index f5179e89..000208c1 100644 --- a/ZSharp.IR/type system/RuntimeModule.cs +++ b/ZSharp.IR/type system/RuntimeModule.cs @@ -15,30 +15,30 @@ private static RuntimeModule CreateStandardRuntimeModule() { Module module = new("Runtime"); - ConstructedClass @object; - ConstructedClass @string; - ConstructedClass type; - ConstructedClass @void; - ConstructedClass @null; + ClassReference @object; + ClassReference @string; + ClassReference type; + ClassReference @void; + ClassReference @null; - ConstructedClass boolean; + ClassReference boolean; - ConstructedClass int32; + ClassReference int32; - ConstructedClass float32; + ClassReference float32; { - module.Types.Add((type = new(new("Type"))).Class); - module.Types.Add((@object = new(new("Object"))).Class); - module.Types.Add((@string = new(new("String"))).Class); - module.Types.Add((@void = new(new("Void"))).Class); - module.Types.Add((@null = new(new("Null"))).Class); + module.Types.Add((type = new(new("Type"))).Definition); + module.Types.Add((@object = new(new("Object"))).Definition); + module.Types.Add((@string = new(new("String"))).Definition); + module.Types.Add((@void = new(new("Void"))).Definition); + module.Types.Add((@null = new(new("Null"))).Definition); - module.Types.Add((boolean = new(new("Boolean"))).Class); + module.Types.Add((boolean = new(new("Boolean"))).Definition); - module.Types.Add((int32 = new(new("Int32"))).Class); + module.Types.Add((int32 = new(new("Int32"))).Definition); - module.Types.Add((float32 = new(new("Float32"))).Class); + module.Types.Add((float32 = new(new("Float32"))).Definition); } return new(module, new() diff --git a/ZSharp.IR/type system/TypeSystem.cs b/ZSharp.IR/type system/TypeSystem.cs index acd8f9de..eba34901 100644 --- a/ZSharp.IR/type system/TypeSystem.cs +++ b/ZSharp.IR/type system/TypeSystem.cs @@ -2,20 +2,20 @@ { public sealed class TypeSystem { - public ConstructedClass Object { get; init; } = null!; + public ClassReference Object { get; init; } = null!; - public ConstructedClass String { get; init; } = null!; + public ClassReference String { get; init; } = null!; - public ConstructedClass Type { get; init; } = null!; + public ClassReference Type { get; init; } = null!; - public ConstructedClass Void { get; init; } = null!; + public ClassReference Void { get; init; } = null!; - public ConstructedClass Null { get; init; } = null!; + public ClassReference Null { get; init; } = null!; - public ConstructedClass Boolean { get; init; } = null!; + public ClassReference Boolean { get; init; } = null!; - public ConstructedClass Int32 { get; init; } = null!; + public ClassReference Int32 { get; init; } = null!; - public ConstructedClass Float32 { get; init; } = null!; + public ClassReference Float32 { get; init; } = null!; } } diff --git a/ZSharp.IR/type system/types/ClassReference.cs b/ZSharp.IR/type system/types/ClassReference.cs new file mode 100644 index 00000000..9ee0ed93 --- /dev/null +++ b/ZSharp.IR/type system/types/ClassReference.cs @@ -0,0 +1,10 @@ +namespace ZSharp.IR +{ + public sealed class ClassReference(Class @class) + : OOPTypeReference + { + public Class Definition { get; } = @class; + + public OOPTypeReference? OwningType { get; set; } + } +} diff --git a/ZSharp.Runtime.IL/Runtime.cs b/ZSharp.Runtime.IL/Runtime.cs index 8799298a..0aed7c8d 100644 --- a/ZSharp.Runtime.IL/Runtime.cs +++ b/ZSharp.Runtime.IL/Runtime.cs @@ -70,7 +70,7 @@ public Type Import(IR.IType type) => irLoader.LoadType(type); public IR.IType Import(Type type) - => Context.Cache(type, out IR.IType? result) ? result : throw new(); + => Context.Cache(type, out IR.IType? result) ? result : ilLoader.LoadType(type); public IR.Module Import(IL.Module module) { diff --git a/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs b/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs index 3051f350..d5fcfc86 100644 --- a/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs @@ -15,14 +15,14 @@ public IType LoadType(Type type) if (type.IsTypeDefinition) { - if (type.IsGenericTypeDefinition) - throw new InvalidOperationException(); - var genericArguments = type.GenericTypeArguments.Select(LoadType).ToList(); - if (type.IsClass) result = new ConstructedClass(new ClassLoader(this, type).Load()) + var @class = new ClassLoader(this, type).Load(); + + if (genericArguments.Count == 0) result = new ClassReference(@class); + else if (type.IsClass) result = new ConstructedClass(@class) { - Arguments = new(genericArguments), + Arguments = [.. genericArguments], }; //else if (type.IsInterface) result = new ILInterfaceLoader(this, type).Load(); //else if (type.IsEnum) result = new ILEnumLoader(this, type).Load(); @@ -40,7 +40,25 @@ public IType LoadType(Type type) throw new NotImplementedException(); if (type.IsConstructedGenericType) - throw new NotImplementedException(); + { + var definition = type.GetGenericTypeDefinition(); + + var definitionIR = LoadType(definition); + + var genericArguments = type.GenericTypeArguments.Select(LoadType).ToList(); + + if (definitionIR is not OOPTypeReference typeReference) + throw new ArgumentException("Type must be a type definition.", nameof(type)); + + return typeReference.Definition switch + { + Class @class => new ConstructedClass(@class) + { + Arguments = [.. genericArguments], + }, + _ => throw new NotImplementedException() + }; + } throw new(); } diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs index cf75d2f1..07e87c3f 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs @@ -1,10 +1,14 @@ -using ZSharp.IR; +using CommonZ.Utils; +using System.Reflection; +using ZSharp.IR; namespace ZSharp.Runtime.NET.IL2IR { internal sealed class ClassLoader(ILLoader loader, Type input) : BaseILLoader(loader, input, new(input.Name)) { + private IR.OOPTypeReference Self { get; set; } + public override IR.Class Load() { if (Context.Cache(Input, out var result)) @@ -12,6 +16,10 @@ public override IR.Class Load() Context.Cache(Input, Output); + Self = new IR.ClassReference(Output); + + LoadGenericParameters(); + LoadBase(); LoadInterfaceImplementations(); @@ -32,7 +40,27 @@ public override IR.Class Load() private void LoadBase() { if (Input.BaseType is not null) - Output.Base = (IR.ConstructedClass)Loader.LoadType(Input.BaseType); + Output.Base = (OOPTypeReference)Loader.LoadType(Input.BaseType); + } + + private void LoadGenericParameters() + { + if (!Input.IsGenericTypeDefinition) + return; + + Output.Name = Input.Name.Split('`')[0]; + + foreach (var parameter in Input.GetGenericArguments()) + { + var genericParameter = new IR.GenericParameter(parameter.Name); + Context.Cache(parameter, genericParameter); + Output.GenericParameters.Add(genericParameter); + } + + Self = new IR.ConstructedClass(Output) + { + Arguments = [.. Output.GenericParameters] + }; } private void LoadInterfaceImplementations() @@ -62,7 +90,8 @@ private void LoadConstructors() private void LoadMethods() { foreach (var method in Input.GetMethods()) - LoadMethod(method); + if (method.DeclaringType == Input) + LoadMethod(method); } private void LoadTypes() @@ -76,7 +105,7 @@ private void LoadInterfaceImplementation(Type @interface, IL.InterfaceMapping ma if (mapping.InterfaceMethods.Length != mapping.TargetMethods.Length) throw new InvalidOperationException("Interface mapping is invalid."); - throw new NotImplementedException(); + //throw new NotImplementedException(); //var implementation = new IR.InterfaceImplementation(Loader.LoadType(@interface)); @@ -94,9 +123,13 @@ private void LoadInterfaceImplementation(Type @interface, IL.InterfaceMapping ma private void LoadField(IL.FieldInfo field) { - throw new NotImplementedException(); + var result = new IR.Field(field.Name, Loader.LoadType(field.FieldType)) + { + IsStatic = field.IsStatic, + IsReadOnly = field.IsInitOnly, + }; - // TODO: implement this by adding a property, since it's impossible for the VM to access C# fields directly. + Output.Fields.Add(result); } private void LoadProperty(IL.PropertyInfo property) @@ -117,6 +150,11 @@ private void LoadConstructor(IL.ConstructorInfo constructor) Method = new(Loader.RuntimeModule.TypeSystem.Void), }; + Context.Cache(constructor, result.Method); + + if (!constructor.IsStatic) + result.Method.Signature.Args.Parameters.Add(new("this", Self)); + foreach (var parameter in constructor.GetParameters()) result.Method.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); @@ -125,7 +163,15 @@ private void LoadConstructor(IL.ConstructorInfo constructor) private IR.Method LoadMethod(IL.MethodInfo method) { - var result = new IR.Method(Loader.LoadType(method.ReturnType)); + var result = new IR.Method(Loader.LoadType(method.ReturnType)) + { + Name = method.GetCustomAttribute()?.Name ?? method.Name, + }; + + Context.Cache(method, result); + + if (!method.IsStatic) + result.Signature.Args.Parameters.Add(new("this", Self)); foreach (var parameter in method.GetParameters()) result.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); @@ -147,28 +193,27 @@ private void LoadTypeDefinition(Type type) else if (type.IsValueType) result = LoadStruct(type); else throw new NotImplementedException(); - // TADA: | | | | | | | | | - // TODO: V V V V V V V V V - //Output.Types.Add(result); + Output.NestedTypes.Add(result); } private IR.Class LoadClass(Type type) - { - throw new NotImplementedException(); - } + => new ClassLoader(Loader, type).Load(); private IR.Interface LoadInterface(Type type) { + return new(); throw new NotImplementedException(); } private IR.Enumclass LoadEnum(Type type) { + return new(); throw new NotImplementedException(); } private IR.ValueType LoadStruct(Type type) { + return new(); throw new NotImplementedException(); } } diff --git a/ZSharp.Runtime.IL/ir2il/Constants.cs b/ZSharp.Runtime.IL/ir2il/Constants.cs index 3e51094c..f2e46cee 100644 --- a/ZSharp.Runtime.IL/ir2il/Constants.cs +++ b/ZSharp.Runtime.IL/ir2il/Constants.cs @@ -4,6 +4,10 @@ internal static class Constants { public const string GlobalsTypeName = ""; + public const string AnonymousClass = ""; + public const string AnonymousMethod = ""; + + public const string AnonymousModule = ""; } } diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index 902bfd52..8b86b003 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -1,12 +1,12 @@ -namespace ZSharp.Runtime.NET.IR2IL +using System.Collections.Generic; + +namespace ZSharp.Runtime.NET.IR2IL { /// /// Wraps an IR module in a C# module. /// public class IRLoader(Context context, IR.RuntimeModule? runtimeModule = null) { - private List thisPass = [], nextPass = []; - public Context Context { get; } = context; public IR.RuntimeModule RuntimeModule { get; } = runtimeModule ?? IR.RuntimeModule.Standard; @@ -18,25 +18,7 @@ public IL.Module LoadModule(IR.Module module) if (Context.Cache(module, out var result)) return result; - var assemblybuilder = IL.Emit.AssemblyBuilder.DefineDynamicAssembly( - new IL.AssemblyName(module.Name ?? ""), - IL.Emit.AssemblyBuilderAccess.RunAndCollect); - - result = new ModuleLoader(this, module, assemblybuilder.DefineDynamicModule(module.Name ?? "")).Load(); - - if (module.HasSubmodules) - foreach (var submodule in module.Submodules) - new ModuleLoader(this, submodule, assemblybuilder.DefineDynamicModule(result.Name + '.' + (module.Name ?? ""))).Load(); - - while (nextPass.Count > 0) - { - (thisPass, nextPass) = (nextPass, thisPass); - - foreach (var action in thisPass) - action(); - - thisPass.Clear(); - } + result = new RootModuleLoader(this, module).Load(); if (module.Initializer is not null) result @@ -55,26 +37,116 @@ public Type LoadType(IR.IType type) return type switch { IR.ConstructedClass constructedClass => LoadType(constructedClass), + IR.OOPTypeReference reference => LoadType(reference), _ => throw new NotImplementedException() }; } + public Type LoadType(IR.OOPTypeReference typeReference) + { + var type = Context.Cache(typeReference.Definition); + + if (type is null) + throw new(); + + List genericArguments = []; + + if (typeReference.OwningType is not null) + genericArguments.AddRange(LoadType(typeReference.OwningType).GetGenericArguments()); + + if (typeReference is IR.ConstructedType constructedType) + genericArguments.AddRange(constructedType.Arguments.Select(LoadType)); + + return type.MakeGenericType([.. genericArguments]); + } + public Type LoadType(IR.ConstructedClass constructedClass) { - var innerClass = Context.Cache(constructedClass.Class); + var result = LoadType(constructedClass as IR.OOPTypeReference); + + return result; + //var innerClass = LoadType(constructedClass as IR.OOPTypeReference); + + //if (innerClass is null) + // throw new(); + + //if (constructedClass.Arguments.Count == 0) + // return innerClass; + + //return innerClass.MakeGenericType([ + // .. constructedClass.Arguments.Select(LoadType) + //]); + } + + public IL.MethodBase LoadReference(IR.ICallable callable) + { + if (Context.Cache(callable) is IL.MethodBase result) + return result; - if (innerClass is null) + if (callable is IR.MemberReference methodReference) + return LoadReference(methodReference); + + throw new NotImplementedException(); + } + + public IL.ConstructorInfo LoadReference(IR.MemberReference @ref) + { + var type = LoadType(@ref.OwningType); + + if (!Context.Cache(@ref.Member.Method, out var def)) + throw new InvalidOperationException($"Method {@ref.Member.Name} was not loaded"); + + var method = type.GetConstructor([]); + + if (method is null) throw new(); - if (constructedClass.Arguments.Count == 0) - return innerClass; + if (method.HasSameMetadataDefinitionAs(def)) + return method; - return innerClass.MakeGenericType([ - .. constructedClass.Arguments.Select(LoadType) - ]); + throw new(); } - internal void AddToNextPass(Action action) - => nextPass.Add(action); + public IL.FieldInfo LoadReference(IR.MemberReference @ref) + { + var type = LoadType(@ref.OwningType); + + if (!Context.Cache(@ref.Member, out var def)) + throw new InvalidOperationException($"Field {@ref.Member.Name} was not loaded"); + + var field = type.GetField(def.Name); + + if (field is null) + throw new(); + + if (field.HasSameMetadataDefinitionAs(def)) + return field; + + throw new(); + } + + public IL.MethodInfo LoadReference(IR.MemberReference @ref) + { + var type = LoadType(@ref.OwningType); + + if (!Context.Cache(@ref.Member, out var def)) + throw new InvalidOperationException($"Method {@ref.Member.Name} was not loaded"); + + var types = ((IR.ICallable)@ref).Signature.GetParameters().Select(p => p.Type).Skip(@ref.Member.IsStatic ? 0 : 1).Select(LoadType).ToArray(); + + var method = type.GetMethod( + def.Name, + def.GetGenericArguments().Length, + types + ); + + if (method is null) + throw new(); + + if (method.HasSameMetadataDefinitionAs(def)) + return method; + + throw new(); + } } } diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs new file mode 100644 index 00000000..6bc2c539 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs @@ -0,0 +1,160 @@ +namespace ZSharp.Runtime.NET.IR2IL +{ + internal sealed class ClassLoader(RootModuleLoader loader, IR.Class @in, IL.Emit.TypeBuilder @out) + : ModuleContentLoader(loader, @in, @out) + { + public ClassLoader(RootModuleLoader loader, IL.Emit.ModuleBuilder module, IR.Class @in) + : this(loader, @in, CreateDefinition(module, @in)) { } + + public ClassLoader(RootModuleLoader loader, IL.Emit.TypeBuilder type, IR.Class @in) + : this(loader, @in, CreateDefinition(type, @in)) { } + + protected override void DoLoad() + { + LoadNestedTypes(); + + ModuleLoader.AddToNextPass(LoadDefinition); + + if (Input.HasConstructors) + ModuleLoader.AddToNextPass(LoadConsructors); + + if (Input.HasFields) + ModuleLoader.AddToNextPass(LoadFields); + + if (Input.HasMethods) + ModuleLoader.AddToNextPass(LoadMethods); + } + + private void LoadDefinition() + { + if (Input.Base is not null) + Output.SetParent(Loader.LoadType(Input.Base)); + + if (Input.HasGenericParameters) + LoadGenericParameters(); + } + + private void LoadGenericParameters() + { + var genericParameters = Output.DefineGenericParameters( + Input.GenericParameters.Select(gp => gp.Name).ToArray() + ); + + foreach (var (ir, il) in Input.GenericParameters.Zip(genericParameters)) + Context.Cache(ir, il); + + ModuleLoader.AddToCleanUp(() => + { + foreach (var ir in Input.GenericParameters) + { + //Context.Uncache(ir); + } + }); + } + + private void LoadNestedTypes() + { + + } + + private void LoadConsructors() + { + foreach (var constructor in Input.Constructors) + LoadConstructor(constructor); + } + + private void LoadFields() + { + foreach (var field in Input.Fields) + LoadField(field); + } + + private void LoadMethods() + { + foreach (var method in Input.Methods) + LoadMethod(method); + } + + private void LoadConstructor(IR.Constructor constructor) + { + var irParams = constructor.Method.Signature.GetParameters(); + + var parameters = irParams.Select(p => new Parameter() + { + Name = p.Name, + Type = Loader.LoadType(p.Type), + Position = p.Index + }); + + var result = Output.DefineConstructor(IL.MethodAttributes.Public, IL.CallingConventions.HasThis, [.. irParams.Skip(1).Select(p => Loader.LoadType(p.Type))]); + + Context.Cache(constructor.Method, result); + + var ilGen = result.GetILGenerator(); + var codeLoader = new CodeLoader(ModuleLoader, constructor.Method, ilGen); + + foreach (var (ir, parameter) in irParams.Zip(parameters)) + codeLoader.Args[ir] = parameter; + + foreach (var local in constructor.Method.Body.Locals) + codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); + + ModuleLoader.AddToNextPass(() => codeLoader.Load()); + } + + private void LoadField(IR.Field field) + { + var attributes = IL.FieldAttributes.Public; + + if (field.IsStatic) + attributes |= IL.FieldAttributes.Static; + + var il = Output.DefineField(field.Name, Loader.LoadType(field.Type), attributes); + + Context.Cache(field, il); + } + + private void LoadMethod(IR.Method method) + { + var irParams = method.Signature.GetParameters(); + + var parameters = irParams.Select(p => new Parameter() + { + Name = p.Name, + Type = Loader.LoadType(p.Type), + Position = p.Index, + }); + + var attributes = IL.MethodAttributes.Public; + + if (method.IsStatic) + attributes |= IL.MethodAttributes.Static; + + var result = Output.DefineMethod( + method.Name ?? Constants.AnonymousMethod, + attributes, + Loader.LoadType(method.ReturnType), + [.. (method.IsInstance || method.IsVirtual ? parameters.Skip(1) : parameters).Select(p => p.Type)] + ); + + Context.Cache(method, result); + + var ilGen = result.GetILGenerator(); + var codeLoader = new CodeLoader(ModuleLoader, method, ilGen); + + foreach (var (ir, parameter) in irParams.Zip(parameters)) + codeLoader.Args[ir] = parameter; + + foreach (var local in method.Body.Locals) + codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); + + ModuleLoader.AddToNextPass(() => codeLoader.Load()); + } + + private static IL.Emit.TypeBuilder CreateDefinition(IL.Emit.ModuleBuilder module, IR.Class @in) + => module.DefineType(@in.Name ?? Constants.AnonymousClass); + + private static IL.Emit.TypeBuilder CreateDefinition(IL.Emit.TypeBuilder type, IR.Class @in) + => type.DefineNestedType(@in.Name ?? Constants.AnonymousClass); + } +} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ModuleContentLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ModuleContentLoader.cs new file mode 100644 index 00000000..716f9a80 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/loader new/ModuleContentLoader.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Runtime.NET.IR2IL +{ + internal abstract class ModuleContentLoader(RootModuleLoader loader, In @in, Out @out) + : BaseIRLoader(loader.Loader, @in, @out) + { + public RootModuleLoader ModuleLoader { get; } = loader; + + public Out Load() + { + DoLoad(); + + return Output; + } + + protected abstract void DoLoad(); + } +} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs new file mode 100644 index 00000000..59a29747 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs @@ -0,0 +1,116 @@ +namespace ZSharp.Runtime.NET.IR2IL +{ + internal sealed class ModuleLoader( + RootModuleLoader loader, + IR.Module @in, + IL.Emit.ModuleBuilder? @out = null + ) : ModuleContentLoader( + loader, + @in, + @out ?? loader.AssemblyBuilder.DefineDynamicModule(@in.Name ?? Constants.AnonymousModule) + ) + { + protected override void DoLoad() + { + if (Input.HasSubmodules) + LoadSubModules(); + + if (Input.HasTypes) + LoadTypes(); + + if (!Input.HasFunctions && !Input.HasGlobals) + return; + + var globals = Output.DefineType(Constants.GlobalsTypeName, IL.TypeAttributes.Public | IL.TypeAttributes.Abstract | IL.TypeAttributes.Sealed); + + if (Input.HasFunctions) + ModuleLoader.AddToNextPass(() => LoadFunctions(globals)); + + if (Input.HasGlobals) + ModuleLoader.AddToNextPass(() => LoadGlobals(globals)); + + ModuleLoader.AddToCleanUp(() => + { + globals.CreateType(); + }); + } + + private void LoadSubModules() + { + foreach (var submodule in Input.Submodules) + new ModuleLoader(ModuleLoader, submodule).Load(); + } + + private void LoadTypes() + { + foreach (var type in Input.Types) + (type switch + { + IR.Class @class => new ClassLoader(ModuleLoader, Output, @class), + //IR.Interface @interface => new InterfaceLoader(loader, Output, @interface), + _ => throw new NotImplementedException() + }).Load(); + } + + private void LoadFunctions(IL.Emit.TypeBuilder globals) + { + foreach (var function in Input.Functions) + LoadFunction(globals, function); + } + + private void LoadGlobals(IL.Emit.TypeBuilder globals) + { + foreach (var global in Input.Globals) + LoadGlobal(globals, global); + } + + private IL.MethodInfo LoadFunction(IL.Emit.TypeBuilder globals, IR.Function function) + { + var irParams = function.Signature.GetParameters(); + + var attributes = IL.MethodAttributes.Public | IL.MethodAttributes.Static; + + var parameters = irParams.Select(p => new Parameter() + { + Name = p.Name, + Type = Loader.LoadType(p.Type), + Position = p.Index, + }); + + var result = globals.DefineMethod( + function.Name ?? string.Empty, + attributes, + Loader.LoadType(function.ReturnType), + parameters.Select(p => p.Type).ToArray() + ); + + Context.Cache(function, result); + + var ilGen = result.GetILGenerator(); + var codeLoader = new CodeLoader(ModuleLoader, function, ilGen); + + foreach (var (ir, parameter) in irParams.Zip(parameters)) + codeLoader.Args[ir] = parameter; + + foreach (var local in function.Body.Locals) + codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); + + ModuleLoader.AddToNextPass(() => codeLoader.Load()); + + return result; + } + + private IL.FieldInfo LoadGlobal(IL.Emit.TypeBuilder globals, IR.Global global) + { + var result = globals.DefineField( + global.Name ?? string.Empty, + Loader.LoadType(global.Type), + IL.FieldAttributes.Public | IL.FieldAttributes.Static + ); + + Context.Cache(global, result); + + return result; + } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/RootModuleLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/RootModuleLoader.cs new file mode 100644 index 00000000..2e96f2f5 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/loader new/RootModuleLoader.cs @@ -0,0 +1,47 @@ +namespace ZSharp.Runtime.NET.IR2IL +{ + internal sealed class RootModuleLoader(IRLoader loader, IR.Module @in) + { + public IRLoader Loader { get; } = loader; + + public IR.Module Input { get; } = @in; + + public IL.Emit.AssemblyBuilder AssemblyBuilder { get; } = + IL.Emit.AssemblyBuilder.DefineDynamicAssembly( + new(@in.Name ?? Constants.AnonymousModule), + IL.Emit.AssemblyBuilderAccess.RunAndCollect + ); + + private List thisPass = [], nextPass = [], cleanUp = []; + + public void AddToNextPass(Action action) + => nextPass.Add(action); + + public void AddToCleanUp(Action action) + => cleanUp.Add(action); + + public IL.Module Load() + { + var result = new ModuleLoader(this, Input).Load(); + + RunUntilComplete(); + + return result; + } + + private void RunUntilComplete() + { + while (nextPass.Count > 0) + { + (thisPass, nextPass) = (nextPass, thisPass); + nextPass.Clear(); + + foreach (var action in thisPass) + action(); + } + + foreach (var action in cleanUp) + action(); + } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/loaders/code/CodeLoader.Compile.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.Compile.cs similarity index 93% rename from ZSharp.Runtime.IL/ir2il/loaders/code/CodeLoader.Compile.cs rename to ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.Compile.cs index bd2812ba..f9f09842 100644 --- a/ZSharp.Runtime.IL/ir2il/loaders/code/CodeLoader.Compile.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.Compile.cs @@ -8,8 +8,7 @@ partial class CodeLoader private void Compile(VM.Call call) { - if (!Context.Cache(call.Callable, out var callable)) - throw new(); + var callable = Loader.LoadReference(call.Callable); foreach (var _ in call.Callable.Signature.GetParameters()) _stack.Pop(); @@ -38,8 +37,7 @@ private void Compile(VM.CallInternal callInternal) private void Compile(VM.CallVirtual callVirtual) { - if (!Context.Cache(callVirtual.Method, out var method)) - throw new(); + var method = Loader.LoadReference(callVirtual.Method); if (!method.IsVirtual && !method.IsAbstract) throw new($"Method {method} is not virtual or abstract!"); @@ -52,8 +50,7 @@ private void Compile(VM.CallVirtual callVirtual) private void Compile(VM.CreateInstance createInstance) { - if (!Context.Cache(createInstance.Constructor.Method, out var constructor)) - throw new(); + var constructor = Loader.LoadReference(createInstance.Constructor); Output.Emit(IL.Emit.OpCodes.Newobj, constructor); @@ -90,8 +87,7 @@ private void Compile(VM.GetArgument getArgument) private void Compile(VM.GetField getField) { - if (!Context.Cache(getField.Field, out var field)) - throw new(); + var field = Loader.LoadReference(getField.Field); Output.Emit(field.IsStatic ? IL.Emit.OpCodes.Ldsfld : IL.Emit.OpCodes.Ldfld, field); @@ -220,8 +216,7 @@ private void Compile(VM.SetArgument setArgument) private void Compile(VM.SetField setField) { - if (!Context.Cache(setField.Field, out var field)) - throw new(); + var field = Loader.LoadReference(setField.Field); Output.Emit(field.IsStatic ? IL.Emit.OpCodes.Stsfld : IL.Emit.OpCodes.Stfld, field); diff --git a/ZSharp.Runtime.IL/ir2il/loaders/code/CodeLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.cs similarity index 93% rename from ZSharp.Runtime.IL/ir2il/loaders/code/CodeLoader.cs rename to ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.cs index fac696ab..c78898d9 100644 --- a/ZSharp.Runtime.IL/ir2il/loaders/code/CodeLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.cs @@ -1,7 +1,7 @@ namespace ZSharp.Runtime.NET.IR2IL { - internal sealed partial class CodeLoader(IRLoader loader, IR.ICallable code, IL.Emit.ILGenerator method) - : BaseIRLoader(loader, code, method) + internal sealed partial class CodeLoader(RootModuleLoader loader, IR.ICallable code, IL.Emit.ILGenerator method) + : ModuleContentLoader(loader, code, method) , ICodeLoader { private readonly Dictionary labels = []; @@ -12,7 +12,7 @@ internal sealed partial class CodeLoader(IRLoader loader, IR.ICallable code, IL. public Dictionary Locals { get; } = []; - public void Load() + protected override void DoLoad() { CompileCode(); } diff --git a/ZSharp.Runtime.IL/ir2il/loaders/code/ICodeLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/ICodeLoader.cs similarity index 100% rename from ZSharp.Runtime.IL/ir2il/loaders/code/ICodeLoader.cs rename to ZSharp.Runtime.IL/ir2il/loader new/code/ICodeLoader.cs diff --git a/ZSharp.Runtime.IL/ir2il/loaders/code/Parameter.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/Parameter.cs similarity index 100% rename from ZSharp.Runtime.IL/ir2il/loaders/code/Parameter.cs rename to ZSharp.Runtime.IL/ir2il/loader new/code/Parameter.cs diff --git a/ZSharp.Runtime.IL/ir2il/loaders/code/ThisParameter.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/ThisParameter.cs similarity index 100% rename from ZSharp.Runtime.IL/ir2il/loaders/code/ThisParameter.cs rename to ZSharp.Runtime.IL/ir2il/loader new/code/ThisParameter.cs diff --git a/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs b/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs deleted file mode 100644 index f4e34b2c..00000000 --- a/ZSharp.Runtime.IL/ir2il/loaders/ModuleLoader.cs +++ /dev/null @@ -1,133 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal sealed class ModuleLoader(IRLoader loader, IR.Module input, IL.Emit.ModuleBuilder output) - : BaseIRLoader(loader, input, output) - { - private IL.Emit.TypeBuilder globals = null!; - private IL.Emit.MethodBuilder cctor = null!; - - public IL.Module Load() - { - Context.Cache(Input, Output); - - globals = Output.DefineType( - Constants.GlobalsTypeName, - IL.TypeAttributes.Public | - IL.TypeAttributes.Abstract | - IL.TypeAttributes.Sealed - ); - //cctor = globals.DefineMethod( - // ".cctor", - // IL.MethodAttributes.Static | - // IL.MethodAttributes.SpecialName | - // IL.MethodAttributes.RTSpecialName | - // IL.MethodAttributes.PrivateScope - //); - - LoadTypes(); - - LoadGlobals(); - - LoadFunctions(); - - Loader.AddToNextPass(() => globals.CreateType()); - - return Output; - } - - private void LoadGlobals() - { - if (Input.HasGlobals) - foreach (var global in Input.Globals) - LoadGlobal(global); - } - - private void LoadFunctions() - { - if (Input.HasFunctions) - foreach (var function in Input.Functions) - LoadFunction(function); - } - - private void LoadTypes() - { - if (Input.HasTypes) - foreach (var type in Input.Types) - LoadType(type); - } - - private Type LoadType(IR.OOPType type) - { - if (Context.Cache(type, out var result)) - return result; - - return type switch - { - IR.Class @class => LoadClass(@class), - _ => throw new NotImplementedException() - }; - } - - private Type LoadClass(IR.Class @class) - { - var type = Output.DefineType(@class.Name ?? string.Empty, IL.TypeAttributes.Public); - - Context.Cache(@class, type); - - new ClassLoader(Loader, @class, type).Load(); - - type.CreateType(); - - return type; - } - - private IL.FieldInfo LoadGlobal(IR.Global global) - { - var result = globals.DefineField( - global.Name ?? string.Empty, - Loader.LoadType(global.Type), - IL.FieldAttributes.Public | IL.FieldAttributes.Static - ); - - Context.Cache(global, result); - - return result; - } - - private IL.MethodInfo LoadFunction(IR.Function function) - { - var irParams = function.Signature.GetParameters(); - - var attributes = IL.MethodAttributes.Public | IL.MethodAttributes.Static; - - var parameters = irParams.Select(p => new Parameter() - { - Name = p.Name, - Type = Loader.LoadType(p.Type), - Position = p.Index, - }); - - var result = globals.DefineMethod( - function.Name ?? string.Empty, - attributes, - Loader.LoadType(function.ReturnType), - parameters.Select(p => p.Type).ToArray() - ); - - Context.Cache(function, result); - - var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(Loader, function, ilGen); - - foreach (var (ir, parameter) in irParams.Zip(parameters)) - codeLoader.Args[ir] = parameter; - - foreach (var local in function.Body.Locals) - codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); - - Loader.AddToNextPass(codeLoader.Load); - - return result; - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/loaders/TypeLoader.cs b/ZSharp.Runtime.IL/ir2il/loaders/TypeLoader.cs deleted file mode 100644 index 99c3ff7a..00000000 --- a/ZSharp.Runtime.IL/ir2il/loaders/TypeLoader.cs +++ /dev/null @@ -1,154 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal sealed class ClassLoader(IRLoader loader, IR.Class input, IL.Emit.TypeBuilder output) - : BaseIRLoader(loader, input, output) - { - private List thisPass = [], nextPass = []; - - private void AddToNextPass(Action action) - => nextPass.Add(action); - - public void Load() - { - //LoadNestedTypes(); - - LoadBase(); - - //LoadInterfaces(); - - LoadFields(); - - LoadConstructors(); - - //LoadEvents(); - - LoadMethods(); - - //LoadProperties(); - - do - { - (thisPass, nextPass) = (nextPass, thisPass); - nextPass.Clear(); - - foreach (var action in thisPass) - action(); - } while (thisPass.Count > 0); - } - - private void LoadNestedTypes() - { - throw new NotImplementedException(); - } - - private void LoadBase() - { - if (Input.Base != null) - Output.SetParent(Loader.LoadType(Input.Base)); - } - - private void LoadInterfaces() - { - throw new NotImplementedException(); - } - - private void LoadConstructors() - { - foreach (var constructor in Input.Constructors) - LoadConstructor(constructor); - } - - private void LoadFields() - { - foreach (var field in Input.Fields) - LoadField(field); - } - - private void LoadEvents() - { - throw new NotImplementedException(); - } - - private void LoadMethods() - { - foreach (var method in Input.Methods) - LoadMethod(method); - } - - private void LoadProperties() - { - throw new NotImplementedException(); - } - - private void LoadConstructor(IR.Constructor constructor) - { - var irParams = constructor.Method.Signature.GetParameters(); - - var parameters = irParams.Select(p => new Parameter() - { - Name = p.Name, - Type = Loader.LoadType(p.Type), - Position = p.Index - }); - - var result = Output.DefineConstructor(IL.MethodAttributes.Public, IL.CallingConventions.HasThis, irParams.Skip(1).Select(p => Loader.LoadType(p.Type)).ToArray()); - - Context.Cache(constructor.Method, result); - - var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(Loader, constructor.Method, ilGen); - - foreach (var (ir, parameter) in irParams.Zip(parameters)) - codeLoader.Args[ir] = parameter; - - foreach (var local in constructor.Method.Body.Locals) - codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); - - codeLoader.Load(); - } - - private void LoadField(IR.Field field) - { - var il = Output.DefineField(field.Name, Loader.LoadType(field.Type), IL.FieldAttributes.Public); - - Context.Cache(field, il); - } - - private void LoadMethod(IR.Method method) - { - var irParams = method.Signature.GetParameters(); - - var parameters = irParams.Select(p => new Parameter() - { - Name = p.Name, - Type = Loader.LoadType(p.Type), - Position = p.Index, - }); - - var attributes = IL.MethodAttributes.Public; - - if (method.IsStatic) - attributes |= IL.MethodAttributes.Static; - - var result = Output.DefineMethod( - method.Name ?? Constants.AnonymousMethod, - attributes, - Loader.LoadType(method.ReturnType), - (method.IsInstance || method.IsVirtual ? parameters.Skip(1) : parameters).Select(p => p.Type).ToArray() - ); - - Context.Cache(method, result); - - var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(Loader, method, ilGen); - - foreach (var (ir, parameter) in irParams.Zip(parameters)) - codeLoader.Args[ir] = parameter; - - foreach (var local in method.Body.Locals) - codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); - - AddToNextPass(() => codeLoader.Load()); - } - } -} diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs index 288df598..58805dfc 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs @@ -22,14 +22,16 @@ private void CompileConstructor() Object.Signature.Args.Add(Compile(parameter)); if (Node.Signature.VarArgs is not null) - Object.Signature.VarArgs = Compile(Node.Signature.VarArgs); + //Object.Signature.VarArgs = Compile(Node.Signature.VarArgs); + throw new NotImplementedException(); if (Node.Signature.KwArgs is not null) foreach (var parameter in Node.Signature.KwArgs) Object.Signature.KwArgs.Add(Compile(parameter)); if (Node.Signature.VarKwArgs is not null) - Object.Signature.VarKwArgs = Compile(Node.Signature.VarKwArgs); + //Object.Signature.VarKwArgs = Compile(Node.Signature.VarKwArgs); + throw new NotImplementedException(); if (Object.Signature.Args.Count == 0) Object.Signature.Args.Add(new("this")); diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs index 0d3bf7c3..5bc8057c 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs @@ -22,14 +22,16 @@ private void CompileMethod() Object.Signature.Args.Add(Compile(parameter)); if (Node.Signature.VarArgs is not null) - Object.Signature.VarArgs = Compile(Node.Signature.VarArgs); + //Object.Signature.VarArgs = Compile(Node.Signature.VarArgs); + throw new NotImplementedException(); if (Node.Signature.KwArgs is not null) foreach (var parameter in Node.Signature.KwArgs) Object.Signature.KwArgs.Add(Compile(parameter)); if (Node.Signature.VarKwArgs is not null) - Object.Signature.VarKwArgs = Compile(Node.Signature.VarKwArgs); + //Object.Signature.VarKwArgs = Compile(Node.Signature.VarKwArgs); + throw new NotImplementedException(); if (Node.ReturnType is not null) Object.ReturnType = Compiler.CompileType(Node.ReturnType); diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs index c3d279ed..a9fc1b02 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs @@ -21,14 +21,16 @@ private void CompileFunction() Object.Signature.Args.Add(Compile(parameter)); if (Node.Signature.VarArgs is not null) - Object.Signature.VarArgs = Compile(Node.Signature.VarArgs); + //Object.Signature.VarArgs = Compile(Node.Signature.VarArgs); + throw new NotImplementedException(); if (Node.Signature.KwArgs is not null) foreach (var parameter in Node.Signature.KwArgs) Object.Signature.KwArgs.Add(Compile(parameter)); if (Node.Signature.VarKwArgs is not null) - Object.Signature.VarKwArgs = Compile(Node.Signature.VarKwArgs); + //Object.Signature.VarKwArgs = Compile(Node.Signature.VarKwArgs); + throw new NotImplementedException(); if (Node.ReturnType is not null) Object.ReturnType = Compiler.CompileType(Node.ReturnType); diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index b085deb7..c80629ac 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -1,4 +1,6 @@ -namespace ZSharp.ZSSourceCompiler +using ZSharp.IR.VM; + +namespace ZSharp.ZSSourceCompiler { public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) : CompilerBase(compiler) @@ -10,6 +12,7 @@ public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) BinaryExpression binary => Compile(binary), CallExpression call => Compile(call), IdentifierExpression identifier => Context.CurrentScope.Get(identifier.Name), + IndexExpression index => Compile(index), LiteralExpression literal => Compile(literal), WhileExpression @while => Compile(@while), _ => null @@ -61,6 +64,15 @@ private CompilerObject Compile(CallExpression call) return Compiler.Compiler.Call(callable, args.ToArray()); } + private CompilerObject Compile(IndexExpression index) + { + var indexable = Compiler.Compiler.Evaluate(Compiler.CompileNode(index.Target)); + + var args = index.Arguments.Select(arg => new Compiler.Argument(arg.Name, Compiler.CompileNode(arg.Value))); + + return Compiler.Compiler.Index(indexable, args.ToArray()); + } + private WhileLoop Compile(WhileExpression @while) { return new WhileExpressionCompiler(Compiler, @while, null!).Compile(); diff --git a/ZSharp.ZSSourceCompiler/extensibility/oop/ClassSpecification.cs b/ZSharp.ZSSourceCompiler/extensibility/oop/ClassSpecification.cs new file mode 100644 index 00000000..285b553a --- /dev/null +++ b/ZSharp.ZSSourceCompiler/extensibility/oop/ClassSpecification.cs @@ -0,0 +1,15 @@ +namespace ZSharp.ZSSourceCompiler +{ + public sealed class ClassSpecification + { + public string Name { get; set; } = string.Empty; + + public Node[]? GenericParameters { get; set; } + + public Node[]? Parameters { get; set; } + + public Expression[] Bases { get; set; } = []; + + public Expression[] Content { get; set; } = []; + } +} diff --git a/ZSharp.ZSSourceCompiler/import system/importers/StandardLibraryImporter.cs b/ZSharp.ZSSourceCompiler/import system/importers/StandardLibraryImporter.cs index a9d5499c..f588e2e5 100644 --- a/ZSharp.ZSSourceCompiler/import system/importers/StandardLibraryImporter.cs +++ b/ZSharp.ZSSourceCompiler/import system/importers/StandardLibraryImporter.cs @@ -1,5 +1,4 @@ using CommonZ.Utils; -using System.Data; using ZSharp.Compiler; namespace ZSharp.ZSSourceCompiler diff --git a/ZSharp.ZSSourceCompiler/import system/importers/ZSImporter.cs b/ZSharp.ZSSourceCompiler/import system/importers/ZSImporter.cs index 3ff9ce97..b1d4db96 100644 --- a/ZSharp.ZSSourceCompiler/import system/importers/ZSImporter.cs +++ b/ZSharp.ZSSourceCompiler/import system/importers/ZSImporter.cs @@ -1,5 +1,4 @@ using CommonZ.Utils; -using System.Data; using ZSharp.Compiler; namespace ZSharp.ZSSourceCompiler diff --git a/ZSharpTest/DotNETImporter.cs b/ZSharpTest/DotNETImporter.cs new file mode 100644 index 00000000..5bfe563f --- /dev/null +++ b/ZSharpTest/DotNETImporter.cs @@ -0,0 +1,53 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp +{ + public sealed class DotNETImporter(Interpreter.Interpreter interpreter) + : Objects.CompilerObject + , ICTCallable + { + private readonly Interpreter.Interpreter interpreter = interpreter; + + public Mapping Libraries { get; } = []; + + public Objects.CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) + { + if (arguments.Length == 0) + throw new(); // TODO: proper exception + + if ( + arguments.Length > 1 || + arguments[0].Name is not null || + !compiler.IsString(compiler.Evaluate(arguments[0].Object), out var libraryName) + ) + { + compiler.Log.Error("`net` importer must have exactly 1 argument of type `string`", this); + throw new(); // TODO: proper exception + } + + if (!Libraries.TryGetValue(libraryName, out var library)) + library = Libraries[libraryName] = ImportDotNETLibrary(libraryName); + + return library; + } + + private Objects.CompilerObject ImportDotNETLibrary(string libraryName) + { + var assembly = System.Reflection.Assembly.LoadFile(Path.GetFullPath(libraryName)); + + var modules = assembly.GetModules(); + if (modules.Length != 1) + { + interpreter.Compiler.Log.Error($"Assembly {libraryName} has more than 1 module", this); + throw new(); // TODO: proper exception + } + + var module = modules[0]; + + var ir = interpreter.HostLoader.Import(module); + + return interpreter.CompilerIRLoader.Import(ir); + } + } +} diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index ea80686f..f815d19e 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -114,6 +114,15 @@ #region Compilation var interpreter = new Interpreter(); + +interpreter.SourceCompiler.StringImporter.Importers.Add( + "net", + new ZSharp.DotNETImporter(interpreter) +); + +new Referencing(interpreter.Compiler); +new OOP(interpreter.Compiler); + ZSharp.Runtime.NET.Runtime runtime = new(interpreter); interpreter.Runtime = runtime; diff --git a/ZSharpTest/Properties/launchSettings.json b/ZSharpTest/Properties/launchSettings.json index 1174091b..a7532ffc 100644 --- a/ZSharpTest/Properties/launchSettings.json +++ b/ZSharpTest/Properties/launchSettings.json @@ -19,6 +19,14 @@ "Tests/Test Class Fields": { "commandName": "Project", "commandLineArgs": "tests/test-class-fields.zs" + }, + "Projects/Better User System": { + "commandName": "Project", + "commandLineArgs": "projects/better-user-system.zs" + }, + "Simple Test": { + "commandName": "Project", + "commandLineArgs": "tests/simple.zs" } } } \ No newline at end of file diff --git a/ZSharpTest/ZSharpTest.csproj b/ZSharpTest/ZSharpTest.csproj index b4848a0c..c33a7ed1 100644 --- a/ZSharpTest/ZSharpTest.csproj +++ b/ZSharpTest/ZSharpTest.csproj @@ -12,6 +12,7 @@ + @@ -24,6 +25,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest @@ -36,6 +40,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest diff --git a/ZSharpTest/projects/better-user-system.zs b/ZSharpTest/projects/better-user-system.zs new file mode 100644 index 00000000..ef0716b5 --- /dev/null +++ b/ZSharpTest/projects/better-user-system.zs @@ -0,0 +1,104 @@ +/* Required Features: + * [-] Primary constructor + * [-] Auto-fields from primary constructor parameters + * [x] Fields + * [x] Anonymous constructor + * [x] Named constructor + * [x] Methods + * [x] Case-Of + * [ ] Automatic type inference for first parameter in methods + * [ ] Automatic instance binding when accessing instance method/field from instance method + * [ ] Instance method as function with `this` first parameter + * [x] Module globals initializers + */ + + +import { input, print } from "std:io"; +import { List } from "std:list"; + + +module Program; + + +class Authentication { + var username: string; + var password: string; + + new(this, username: string, password: string) { + this.username = username; + this.password = password; + } +} + + +class User { + var isAdmin: bool; + + var username: string; + var password: string; + + new(this, username: string, password: string) { + isAdmin = false; + + this.username = username; + this.password = password; + } + + new Admin(this, username: string, password: string) { + User(this: this, username, password); + + isAdmin = true; + } + + fun login(this, username: string, password: string): bool { + if (username != this.username) return false; + if (password != this.password) return false; + + return true; + } + + fun login(auth: Authentication, this: User): bool { + return this.login(auth.username, auth.password); + } +} + + +fun mainMenu(): bool { + print("|== Main Menu ==|"); + print("1. Sign In"); + print("2. Exit Program"); + + let userInput = input("> "); + + case (userInput) { + when ("1") signIn(); + when ("2") return false; + } else print("Invalid input."); + + return true; +} + + +fun signIn(): void { + let username = input("Username: "); + let password = input("Password: "); + + case (Authentication(username, password)) of (User.login) { + when (user) print("USER"); // userTerminal(); + when (admin) print("ADMIN"); // adminTerminal(); + } else print("Invalid credentials."); + + return; +} + + +fun main(): void { + while (mainMenu()) ; + else print("Thank you for using Simple User System!"); + + return; +} + + +let user = User("user", "123"); +let admin = User.Admin("admin", "321"); diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs new file mode 100644 index 00000000..c1550259 --- /dev/null +++ b/ZSharpTest/tests/simple.zs @@ -0,0 +1,19 @@ +import { List, input, print } from "std:io"; +import { Console, greet } from "net:ZLoad.Test.dll"; +// import { Console } from "net:C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\8.0.13\\System.Console.dll"; + +module Program; + +fun main(): void { + let x = List[string](); + + print(greet(let name = input("Please enter your name: "))); + + Console.WriteLine("Hi"); + + x.append(name); + + print("x[0] = " + x.get(0)); + + return; +} From 650dbf4f8da05f591f43649078176e8e1b9a7735 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 21:51:13 +0300 Subject: [PATCH 109/235] Add support for generic functions --- .../ir loader/IRLoader.Impl.cs | 47 +++++++ .../functional/generic/GenericFunction.cs | 128 ++++++++++++++++++ .../generic/GenericFunctionInstance.cs | 97 +++++++++++++ ZSharp.IR/ir/functional/Function.cs | 20 ++- .../ir/functional/GenericFunctionInstance.cs | 18 +++ ZSharp.Runtime.IL/context/Context.IL2IR.cs | 12 ++ ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 11 ++ .../expression/ExpressionCompiler.cs | 2 +- 8 files changed, 333 insertions(+), 2 deletions(-) create mode 100644 ZSharp.Compiler.Objects/functional/generic/GenericFunction.cs create mode 100644 ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs create mode 100644 ZSharp.IR/ir/functional/GenericFunctionInstance.cs diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index cfbea350..be691b63 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -62,6 +62,9 @@ private Action Load(IR.Module module, Module owner) private Action Load(IR.Function function, Module owner) { + if (function.HasGenericParameters) + return LoadGenericFunction(function, owner); + RTFunction result = new(function.Name) { IR = function @@ -243,6 +246,50 @@ private CompilerObject Load(IR.ConstructedClass constructed) return origin; } + private Action LoadGenericFunction(IR.Function function, Module owner) + { + GenericFunction result = new(function.Name) + { + IR = function, + Defined = true, + }; + + Context.Objects.Cache(function, result); + + owner.Content.Add(result); + + if (result.Name != string.Empty) + { + if (!owner.Members.TryGetValue(result.Name, out var group)) + owner.Members.Add(result.Name, group = new OverloadGroup(result.Name)); + + if (group is not OverloadGroup overloadGroup) + throw new InvalidOperationException(); + + overloadGroup.Overloads.Add(result); + } + + return () => + { + foreach (var parameter in function.GenericParameters) + { + var genericParameter = new GenericParameter() + { + Name = parameter.Name, + IR = parameter, + }; + + Context.Types.Cache(parameter, genericParameter); + + result.GenericParameters.Add(genericParameter); + } + + result.Signature = Load(function.Signature); + + result.ReturnType = Load(function.ReturnType); + }; + } + private Signature Load(IR.Signature signature) { Signature result = new(); diff --git a/ZSharp.Compiler.Objects/functional/generic/GenericFunction.cs b/ZSharp.Compiler.Objects/functional/generic/GenericFunction.cs new file mode 100644 index 00000000..0422a0b2 --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/generic/GenericFunction.cs @@ -0,0 +1,128 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class GenericFunction(string? name = null) + : CompilerObject + , ICompileIRObject + , ICTGetIndex + , IReferencable + { + [Flags] + enum BuildState + { + None = 0, + Signature = 0b1, + Body = 0b10, + Owner = 0b100, + Generic = 0b1000, + } + + private readonly ObjectBuildState state = new(); + + public bool Defined + { + init + { + if (value) + foreach (var item in Enum.GetValues()) + state[item] = true; + } + } + + public IR.Function? IR { get; set; } + + public string Name { get; set; } = name ?? string.Empty; + + public Collection GenericParameters { get; set; } = []; + + public CompilerObject? ReturnType { get; set; } + + public Signature Signature { get; set; } = new(); + + public CompilerObject? Body { get; set; } + + IR.Function ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) + { + IR ??= + new( + compiler.CompileIRType( + ReturnType ?? throw new PartiallyCompiledObjectException( + this, + Errors.UndefinedReturnType(Name) + ) + ) + ) + { + Name = Name + }; + + if (owner is not null && !state[BuildState.Owner]) + { + state[BuildState.Owner] = true; + + owner.Functions.Add(IR); + } + + if (!state[BuildState.Generic]) + { + state[BuildState.Generic] = true; + + foreach (var genericParameter in GenericParameters) + IR.GenericParameters.Add(compiler.CompileIRType(genericParameter)); + } + + if (!state[BuildState.Signature]) + { + state[BuildState.Signature] = true; + + foreach (var arg in Signature.Args) + IR.Signature.Args.Parameters.Add(compiler.CompileIRObject(arg, IR.Signature)); + + if (Signature.VarArgs is not null) + IR.Signature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, IR.Signature); + + foreach (var kwArg in Signature.KwArgs) + IR.Signature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, IR.Signature)); + + if (Signature.VarKwArgs is not null) + IR.Signature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, IR.Signature); + } + + if (Body is not null && !state[BuildState.Body]) + { + state[BuildState.Body] = true; + + IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); + } + + return IR; + } + + CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) + { + if (index.Length != GenericParameters.Count) + throw new(); + + ReferenceContext context = new(); + + foreach (var (arg, param) in index.Zip(GenericParameters)) + context[param] = compiler.Evaluate(arg.Object); + + return compiler.Feature().CreateReference(this, context); + } + + GenericFunctionInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + { + foreach (var genericParameter in GenericParameters) + if (!context.CompileTimeValues.Contains(genericParameter)) + throw new(); + + return new(this) + { + Context = context + }; + } + } +} diff --git a/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs b/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs new file mode 100644 index 00000000..2ebde353 --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs @@ -0,0 +1,97 @@ +using System.Diagnostics.CodeAnalysis; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class GenericFunctionInstance(GenericFunction origin) + : CompilerObject + , ICTCallable + , ICompileIRReference + { + public GenericFunction Origin { get; } = origin; + + public required ReferenceContext Context { get; init; } + + public Signature? Signature { get; set; } + + public IR.Signature? CompiledSignature { get; private set; } + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + if (Origin.ReturnType is null) + throw new NotImplementedException(); + + CompileSignature(compiler); + + var args = (Signature as ISignature).MatchArguments(compiler, arguments); + + IRCode code = new(); + + List @params = []; + + @params.AddRange(Signature.Args); + + if (Signature.VarArgs is not null) + @params.Add(Signature.VarArgs); + + @params.AddRange(Signature.KwArgs); + + if (Signature.VarKwArgs is not null) + @params.Add(Signature.VarKwArgs); + + foreach (var param in @params) + code.Append(compiler.CompileIRCode(args[param])); + + code.Append(new([ + new IR.VM.Call(compiler.CompileIRReference(this)) + ])); + + code.Types.Clear(); + if (Origin.ReturnType != compiler.TypeSystem.Void) + code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); + + return new RawCode(code); + } + + IR.GenericFunctionInstance ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + { + var arguments = Origin.GenericParameters + .Select(genericParameter => Context[genericParameter]) + .Select(compiler.CompileIRType); + + CompileSignature(compiler); + + return new(compiler.CompileIRObject(Origin, null)) + { + Arguments = [.. arguments], + Signature = CompiledSignature, + }; + } + + [MemberNotNull(nameof(Signature), nameof(CompiledSignature))] + private void CompileSignature(Compiler.Compiler compiler) + { + Signature ??= compiler.Feature().CreateReference(Origin.Signature, Context); + + if (CompiledSignature is not null) + return; + + if (Origin.ReturnType is null) + throw new NotImplementedException(); + + CompiledSignature = new(compiler.CompileIRType(compiler.Feature().CreateReference(Origin.ReturnType, Context))); + + foreach (var arg in Signature.Args) + CompiledSignature.Args.Parameters.Add(compiler.CompileIRObject(arg, CompiledSignature)); + + if (Signature.VarArgs is not null) + CompiledSignature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, CompiledSignature); + + foreach (var kwArg in Signature.KwArgs) + CompiledSignature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, CompiledSignature)); + + if (Signature.VarKwArgs is not null) + CompiledSignature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, CompiledSignature); + } + } +} diff --git a/ZSharp.IR/ir/functional/Function.cs b/ZSharp.IR/ir/functional/Function.cs index f50292f1..23010600 100644 --- a/ZSharp.IR/ir/functional/Function.cs +++ b/ZSharp.IR/ir/functional/Function.cs @@ -1,4 +1,6 @@ -namespace ZSharp.IR +using CommonZ.Utils; + +namespace ZSharp.IR { public class Function : ModuleMember @@ -7,6 +9,8 @@ public class Function private Signature _signature; private VM.FunctionBody? _body; + private Collection? _genericParameters; + public string? Name { get; set; } public FunctionAttributes Attributes { get; set; } = FunctionAttributes.None; @@ -45,6 +49,20 @@ public VM.FunctionBody Body public bool HasBody => _body is not null; + public Collection GenericParameters + { + get + { + if (_genericParameters is not null) + return _genericParameters; + + Interlocked.CompareExchange(ref _genericParameters, [], null); + return _genericParameters; + } + } + + public bool HasGenericParameters => !_genericParameters.IsNullOrEmpty(); + //public Collection Clauses { get; } public Function(IType returnType) diff --git a/ZSharp.IR/ir/functional/GenericFunctionInstance.cs b/ZSharp.IR/ir/functional/GenericFunctionInstance.cs new file mode 100644 index 00000000..f8cfbd39 --- /dev/null +++ b/ZSharp.IR/ir/functional/GenericFunctionInstance.cs @@ -0,0 +1,18 @@ +using CommonZ.Utils; + +namespace ZSharp.IR +{ + public sealed class GenericFunctionInstance(Function function) + : ICallable + { + public Function Function { get; set; } = function; + + public Collection Arguments { get; set; } = false ? [] : Collection.Empty; + + public Signature Signature { get; init; } = function.Signature; + + public bool HasBody => Function.HasBody; + + public ICallableBody? Body => Function.HasBody ? Function.Body : null; + } +} diff --git a/ZSharp.Runtime.IL/context/Context.IL2IR.cs b/ZSharp.Runtime.IL/context/Context.IL2IR.cs index e1bb04e9..f6b84d66 100644 --- a/ZSharp.Runtime.IL/context/Context.IL2IR.cs +++ b/ZSharp.Runtime.IL/context/Context.IL2IR.cs @@ -39,6 +39,18 @@ public IR.IType Cache(Type il, IR.IType ir) return ir; } + public T Cache(Type il, T ir) + where T : IR.IType + { + if (!toIR.Types.Contains(il)) + toIR.Types.Cache(il, ir); + + if (!toIL.Types.Contains(ir)) + toIL.Types.Cache(ir, il); + + return ir; + } + public bool Cache(Type il, [NotNullWhen(true)] out T? ir) where T : IR.OOPType => toIR.OOPTypes.Cache(il, out ir); diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index 8b86b003..919ae994 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -84,6 +84,9 @@ public IL.MethodBase LoadReference(IR.ICallable callable) return result; if (callable is IR.MemberReference methodReference) + if (callable is IR.GenericFunctionInstance genericFunctionInstance) + return LoadReference(genericFunctionInstance); + return LoadReference(methodReference); throw new NotImplementedException(); @@ -148,5 +151,13 @@ public IL.MethodInfo LoadReference(IR.MemberReference @ref) throw new(); } + + public IL.MethodInfo LoadReference(IR.GenericFunctionInstance @ref) + { + if (!Context.Cache(@ref.Function, out var def)) + throw new InvalidOperationException($"Method {@ref.Function.Name} was not loaded"); + + return def.MakeGenericMethod([.. @ref.Arguments.Select(LoadType)]); + } } } diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index c80629ac..936ef872 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -70,7 +70,7 @@ private CompilerObject Compile(IndexExpression index) var args = index.Arguments.Select(arg => new Compiler.Argument(arg.Name, Compiler.CompileNode(arg.Value))); - return Compiler.Compiler.Index(indexable, args.ToArray()); + return Compiler.Compiler.Map(indexable, @object => Compiler.Compiler.Index(@object, [.. args])); } private WhileLoop Compile(WhileExpression @while) From 1c0e606e135e2fd402790e2bf432a648a6aca925 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 21:51:35 +0300 Subject: [PATCH 110/235] Remove unused assignment --- ZSharp.Compiler.Objects/oop/GenericClassInstance.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs index 2c5f34ce..d823aec0 100644 --- a/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs +++ b/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs @@ -18,7 +18,7 @@ GenericClass origin { CompilerObject IReference.Origin => Origin; - public required ReferenceContext Context { get; set; } = null; + public required ReferenceContext Context { get; set; } public GenericClass Origin { get; set; } = origin; From 3e3c6e4015b017331a40f8418b03f0bf1da624e4 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 21:51:58 +0300 Subject: [PATCH 111/235] Fix overload group map --- ZSharp.Compiler.Objects/overloading/OverloadGroup.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs index 923744d2..8212587f 100644 --- a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs +++ b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs @@ -35,7 +35,7 @@ CompilerObject IMappable.Map(Func func) { return new OverloadGroup(Name) { - Overloads = [.. Overloads.Select(func)] + Overloads = [.. Overloads.Select(func).Where(item => item is not null)] }; } } From 774258104e8f8824b5261bdad04abb917bc11a84 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 21:52:19 +0300 Subject: [PATCH 112/235] Modify index protocol to return null instead of error --- .../compiler core/compiler/features/Compiler.Protocols.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs index d34f9a2c..1f94678c 100644 --- a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs +++ b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs @@ -47,12 +47,12 @@ public CompilerObject Cast(CompilerObject target, CompilerObject type) /// /// /// - public CompilerObject Index(CompilerObject instanceTarget, Argument[] index) + public CompilerObject? Index(CompilerObject instanceTarget, Argument[] index) { if (instanceTarget is ICTGetIndex ctGetIndex) return ctGetIndex.Index(this, index); - throw new NotImplementedException(); + return null; } /// From d5aaae3342caa21772353856ecc83319a7141c47 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 21:53:13 +0300 Subject: [PATCH 113/235] Remove IR.MemberReference --- .../oop/method/MethodReference.cs | 6 +++--- ZSharp.IR/ir/oop/MemberReference.cs | 14 -------------- .../ir/oop/constructor/ConstructorReference.cs | 3 +-- ZSharp.IR/ir/oop/field/FieldReference.cs | 1 - .../ir/oop/method/GenericMethodInstance.cs | 16 ++-------------- ZSharp.IR/ir/oop/method/MethodReference.cs | 11 +++++------ ZSharp.IR/vm/instructions/flow/CallVirtual.cs | 8 ++++---- .../vm/instructions/flow/CreateInstance.cs | 8 ++++---- ZSharp.IR/vm/instructions/stack/GetField.cs | 8 ++++---- ZSharp.IR/vm/instructions/stack/SetField.cs | 8 ++++---- ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 18 ++++++++---------- 11 files changed, 35 insertions(+), 66 deletions(-) delete mode 100644 ZSharp.IR/ir/oop/MemberReference.cs diff --git a/ZSharp.Compiler.Objects/oop/method/MethodReference.cs b/ZSharp.Compiler.Objects/oop/method/MethodReference.cs index a7c234fe..5b2b369e 100644 --- a/ZSharp.Compiler.Objects/oop/method/MethodReference.cs +++ b/ZSharp.Compiler.Objects/oop/method/MethodReference.cs @@ -9,7 +9,7 @@ namespace ZSharp.Objects public sealed class MethodReference(Method origin, ReferenceContext context) : CompilerObject , ICTCallable - , ICompileIRReference> + , ICompileIRReference , IRTBoundMember { public Method Origin { get; } = origin; @@ -47,7 +47,7 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments code.Append(compiler.CompileIRCode(args[param])); code.Append(new([ - new IR.VM.Call((IR.MethodReference)compiler.CompileIRReference>(this)) + new IR.VM.Call(compiler.CompileIRReference(this)) ])); code.Types.Clear(); @@ -57,7 +57,7 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments return new RawCode(code); } - IR.MemberReference ICompileIRReference>.CompileIRReference(Compiler.Compiler compiler) + IR.MethodReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) { var type = compiler.Feature().CreateReference(Owner, Context); diff --git a/ZSharp.IR/ir/oop/MemberReference.cs b/ZSharp.IR/ir/oop/MemberReference.cs deleted file mode 100644 index ff3ccedb..00000000 --- a/ZSharp.IR/ir/oop/MemberReference.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace ZSharp.IR -{ - public interface MemberReference - { - public OOPTypeReference OwningType { get; } - } - - public interface MemberReference - : MemberReference - where T : IRObject - { - public T Member { get; } - } -} diff --git a/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs b/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs index 5a66735a..4afd3897 100644 --- a/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs +++ b/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs @@ -1,8 +1,7 @@ namespace ZSharp.IR { public sealed class ConstructorReference(Constructor constructor) - : MemberReference - , ICallable + : ICallable { public Constructor Member { get; set; } = constructor; diff --git a/ZSharp.IR/ir/oop/field/FieldReference.cs b/ZSharp.IR/ir/oop/field/FieldReference.cs index 778c80c8..9d65cce9 100644 --- a/ZSharp.IR/ir/oop/field/FieldReference.cs +++ b/ZSharp.IR/ir/oop/field/FieldReference.cs @@ -1,7 +1,6 @@ namespace ZSharp.IR { public sealed class FieldReference(Field field) - : MemberReference { public Field Member { get; set; } = field; diff --git a/ZSharp.IR/ir/oop/method/GenericMethodInstance.cs b/ZSharp.IR/ir/oop/method/GenericMethodInstance.cs index 7a8eccf2..f18ac671 100644 --- a/ZSharp.IR/ir/oop/method/GenericMethodInstance.cs +++ b/ZSharp.IR/ir/oop/method/GenericMethodInstance.cs @@ -2,22 +2,10 @@ namespace ZSharp.IR { - public sealed class GenericMethodInstance(MethodReference method) - : MemberReference + public sealed class GenericMethodInstance(Method method) + : MethodReference(method) , ICallable { - public MethodReference Method { get; set; } = method; - public Collection Arguments { get; } = /*method.Member.HasGenericParameters*/false ? [] : Collection.Empty; - - public Method Member => Method.Member; - - public OOPTypeReference OwningType => Method.OwningType; - - public Signature Signature => Method.Signature; - - public bool HasBody => Method.HasBody; - - public ICallableBody? Body => Method.HasBody ? Method.Body : null; } } diff --git a/ZSharp.IR/ir/oop/method/MethodReference.cs b/ZSharp.IR/ir/oop/method/MethodReference.cs index c5ad79d7..b219a514 100644 --- a/ZSharp.IR/ir/oop/method/MethodReference.cs +++ b/ZSharp.IR/ir/oop/method/MethodReference.cs @@ -1,17 +1,16 @@ namespace ZSharp.IR { - public sealed class MethodReference(Method method) - : MemberReference - , ICallable + public class MethodReference(Method method) + : ICallable { - public Method Member { get; set; } = method; + public Method Method { get; set; } = method; public required OOPTypeReference OwningType { get; set; } public Signature Signature { get; init; } = method.Signature; - public bool HasBody => Member.HasBody; + public bool HasBody => Method.HasBody; - public ICallableBody? Body => Member.HasBody ? Member.Body : null; + public ICallableBody? Body => Method.HasBody ? Method.Body : null; } } diff --git a/ZSharp.IR/vm/instructions/flow/CallVirtual.cs b/ZSharp.IR/vm/instructions/flow/CallVirtual.cs index 65362f46..e944b2bd 100644 --- a/ZSharp.IR/vm/instructions/flow/CallVirtual.cs +++ b/ZSharp.IR/vm/instructions/flow/CallVirtual.cs @@ -1,11 +1,11 @@ namespace ZSharp.IR.VM { - public sealed class CallVirtual(MemberReference method) + public sealed class CallVirtual(MethodReference method) : Instruction - , IHasOperand> + , IHasOperand { - public MemberReference Method { get; set; } = method; + public MethodReference Method { get; set; } = method; - MemberReference IHasOperand>.Operand => Method; + MethodReference IHasOperand.Operand => Method; } } diff --git a/ZSharp.IR/vm/instructions/flow/CreateInstance.cs b/ZSharp.IR/vm/instructions/flow/CreateInstance.cs index a32ede6c..2dafe3e5 100644 --- a/ZSharp.IR/vm/instructions/flow/CreateInstance.cs +++ b/ZSharp.IR/vm/instructions/flow/CreateInstance.cs @@ -1,11 +1,11 @@ namespace ZSharp.IR.VM { - public sealed class CreateInstance(MemberReference constructor) + public sealed class CreateInstance(ConstructorReference constructor) : Instruction - , IHasOperand> + , IHasOperand { - public MemberReference Constructor { get; set; } = constructor; + public ConstructorReference Constructor { get; set; } = constructor; - MemberReference IHasOperand>.Operand => Constructor; + ConstructorReference IHasOperand.Operand => Constructor; } } diff --git a/ZSharp.IR/vm/instructions/stack/GetField.cs b/ZSharp.IR/vm/instructions/stack/GetField.cs index b30f54e9..8649850b 100644 --- a/ZSharp.IR/vm/instructions/stack/GetField.cs +++ b/ZSharp.IR/vm/instructions/stack/GetField.cs @@ -1,11 +1,11 @@ namespace ZSharp.IR.VM { - public sealed class GetField(MemberReference field) + public sealed class GetField(FieldReference field) : Instruction - , IHasOperand> + , IHasOperand { - public MemberReference Field { get; set; } = field; + public FieldReference Field { get; set; } = field; - MemberReference IHasOperand>.Operand => Field; + FieldReference IHasOperand.Operand => Field; } } diff --git a/ZSharp.IR/vm/instructions/stack/SetField.cs b/ZSharp.IR/vm/instructions/stack/SetField.cs index adca9104..f23fa198 100644 --- a/ZSharp.IR/vm/instructions/stack/SetField.cs +++ b/ZSharp.IR/vm/instructions/stack/SetField.cs @@ -1,11 +1,11 @@ namespace ZSharp.IR.VM { - public sealed class SetField(MemberReference field) + public sealed class SetField(FieldReference field) : Instruction - , IHasOperand> + , IHasOperand { - public MemberReference Field { get; set; } = field; + public FieldReference Field { get; set; } = field; - MemberReference IHasOperand>.Operand => Field; + FieldReference IHasOperand.Operand => Field; } } diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index 919ae994..c5798333 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; - -namespace ZSharp.Runtime.NET.IR2IL +namespace ZSharp.Runtime.NET.IR2IL { /// /// Wraps an IR module in a C# module. @@ -83,16 +81,16 @@ public IL.MethodBase LoadReference(IR.ICallable callable) if (Context.Cache(callable) is IL.MethodBase result) return result; - if (callable is IR.MemberReference methodReference) if (callable is IR.GenericFunctionInstance genericFunctionInstance) return LoadReference(genericFunctionInstance); + if (callable is IR.MethodReference methodReference) return LoadReference(methodReference); throw new NotImplementedException(); } - public IL.ConstructorInfo LoadReference(IR.MemberReference @ref) + public IL.ConstructorInfo LoadReference(IR.ConstructorReference @ref) { var type = LoadType(@ref.OwningType); @@ -110,7 +108,7 @@ public IL.ConstructorInfo LoadReference(IR.MemberReference @ref) throw new(); } - public IL.FieldInfo LoadReference(IR.MemberReference @ref) + public IL.FieldInfo LoadReference(IR.FieldReference @ref) { var type = LoadType(@ref.OwningType); @@ -128,14 +126,14 @@ public IL.FieldInfo LoadReference(IR.MemberReference @ref) throw new(); } - public IL.MethodInfo LoadReference(IR.MemberReference @ref) + public IL.MethodInfo LoadReference(IR.MethodReference @ref) { var type = LoadType(@ref.OwningType); - if (!Context.Cache(@ref.Member, out var def)) - throw new InvalidOperationException($"Method {@ref.Member.Name} was not loaded"); + if (!Context.Cache(@ref.Method, out var def)) + throw new InvalidOperationException($"Method {@ref.Method.Name} was not loaded"); - var types = ((IR.ICallable)@ref).Signature.GetParameters().Select(p => p.Type).Skip(@ref.Member.IsStatic ? 0 : 1).Select(LoadType).ToArray(); + var types = ((IR.ICallable)@ref).Signature.GetParameters().Select(p => p.Type).Skip(@ref.Method.IsStatic ? 0 : 1).Select(LoadType).ToArray(); var method = type.GetMethod( def.Name, From f3d62a47ce68d3c6b75b73efac077815cd93a822 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 21:53:47 +0300 Subject: [PATCH 114/235] Fix IL global function loader --- ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs index 5a923419..d9462640 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs @@ -54,11 +54,17 @@ private void LoadField(IL.FieldInfo field) private void LoadMethod(IL.MethodInfo method) { - var function = new IR.Function(Loader.LoadType(method.ReturnType)) + var function = new IR.Function(Loader.RuntimeModule.TypeSystem.Void) { Name = method.GetCustomAttribute() is AliasAttribute alias ? alias.Name : method.Name, }; + if (method.ContainsGenericParameters) + foreach (var genericParameter in method.GetGenericArguments()) + function.GenericParameters.Add(Context.Cache(genericParameter, new(genericParameter.Name))); + + function.ReturnType = Loader.LoadType(method.ReturnType); + foreach (var parameter in method.GetParameters()) function.Signature.Args.Parameters.Add(new(parameter.Name!, Loader.LoadType(parameter.ParameterType))); From 544bd67b1b022cc07fcfe358d543137cfe12af20 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 21:54:04 +0300 Subject: [PATCH 115/235] Add support for generic methods --- ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index c5798333..075e544f 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -144,6 +144,9 @@ public IL.MethodInfo LoadReference(IR.MethodReference @ref) if (method is null) throw new(); + if (@ref is IR.GenericMethodInstance genericMethodInstance) + method = method.MakeGenericMethod([.. genericMethodInstance.Arguments.Select(LoadType)]); + if (method.HasSameMetadataDefinitionAs(def)) return method; From d8f855dba928064e3a16824ad6f565b883458145 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 21:54:20 +0300 Subject: [PATCH 116/235] Add parenthesized expression support --- ZSharpTest/Main.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index f815d19e..eaf821aa 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -41,6 +41,18 @@ _ => new ZSharp.AST.IdentifierExpression(token.Value), } ); + expressionParser.Nud( + TokenType.LParen, + parser => + { + parser.Eat(TokenType.LParen); + var expression = parser.Parse(); + parser.Eat(TokenType.RParen); + + return expression; + }, + 10000 + ); expressionParser.Nud( LangParser.Keywords.Let, LangParser.ParseLetExpression From 58b3a22184bdfd254e1e4f600508988e2487d58c Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 21:54:33 +0300 Subject: [PATCH 117/235] Add generic Id function --- ZLoad.Test/Globals.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ZLoad.Test/Globals.cs b/ZLoad.Test/Globals.cs index 7c219f33..6bd49477 100644 --- a/ZLoad.Test/Globals.cs +++ b/ZLoad.Test/Globals.cs @@ -8,5 +8,9 @@ public static partial class Globals [Alias(Name = "greet")] public static string Greet(string name) => $"Hello, {name}!"; + + [Alias(Name = "id")] + public static T Id(T v) + => v; } } From 4bb02b3a2138e1b60939602655f96fea5d5dde50 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 21:54:41 +0300 Subject: [PATCH 118/235] Update main test file --- ZSharpTest/tests/simple.zs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs index c1550259..c122e6a3 100644 --- a/ZSharpTest/tests/simple.zs +++ b/ZSharpTest/tests/simple.zs @@ -1,5 +1,5 @@ import { List, input, print } from "std:io"; -import { Console, greet } from "net:ZLoad.Test.dll"; +import { Console, greet, id } from "net:ZLoad.Test.dll"; // import { Console } from "net:C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\8.0.13\\System.Console.dll"; module Program; @@ -9,7 +9,7 @@ fun main(): void { print(greet(let name = input("Please enter your name: "))); - Console.WriteLine("Hi"); + Console.WriteLine(id[string]("Hi")); x.append(name); From a1dd2c48789127614d1ec4081348effb339d5c4d Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 22 Apr 2025 22:27:54 +0300 Subject: [PATCH 119/235] Patch fix for accessing member while type not built --- ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 68 +++++++++++++------ .../ir2il/loader new/ClassLoader.cs | 4 ++ 2 files changed, 51 insertions(+), 21 deletions(-) diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index 075e544f..7d13b827 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -55,6 +55,9 @@ public Type LoadType(IR.OOPTypeReference typeReference) if (typeReference is IR.ConstructedType constructedType) genericArguments.AddRange(constructedType.Arguments.Select(LoadType)); + if (genericArguments.Count == 0) + return type; + return type.MakeGenericType([.. genericArguments]); } @@ -97,13 +100,24 @@ public IL.ConstructorInfo LoadReference(IR.ConstructorReference @ref) if (!Context.Cache(@ref.Member.Method, out var def)) throw new InvalidOperationException($"Method {@ref.Member.Name} was not loaded"); - var method = type.GetConstructor([]); + var types = @ref.Signature.GetParameters().Select(p => p.Type).Skip(1).Select(LoadType).ToArray(); - if (method is null) - throw new(); + try + { + var method = type.GetConstructor( + types + ); - if (method.HasSameMetadataDefinitionAs(def)) - return method; + if (method is null) + throw new(); + + if (method.HasSameMetadataDefinitionAs(def)) + return method; + } + catch (NotSupportedException) + { + return (IL.ConstructorInfo)def; + } throw new(); } @@ -115,13 +129,19 @@ public IL.FieldInfo LoadReference(IR.FieldReference @ref) if (!Context.Cache(@ref.Member, out var def)) throw new InvalidOperationException($"Field {@ref.Member.Name} was not loaded"); - var field = type.GetField(def.Name); + try + { + var field = type.GetField(def.Name); - if (field is null) - throw new(); + if (field is null) + throw new(); - if (field.HasSameMetadataDefinitionAs(def)) - return field; + if (field.HasSameMetadataDefinitionAs(def)) + return field; + } catch (NotSupportedException) + { + return def; + } throw new(); } @@ -135,20 +155,26 @@ public IL.MethodInfo LoadReference(IR.MethodReference @ref) var types = ((IR.ICallable)@ref).Signature.GetParameters().Select(p => p.Type).Skip(@ref.Method.IsStatic ? 0 : 1).Select(LoadType).ToArray(); - var method = type.GetMethod( - def.Name, - def.GetGenericArguments().Length, - types - ); + try + { + var method = type.GetMethod( + def.Name, + def.GetGenericArguments().Length, + types + ); - if (method is null) - throw new(); + if (method is null) + throw new(); - if (@ref is IR.GenericMethodInstance genericMethodInstance) - method = method.MakeGenericMethod([.. genericMethodInstance.Arguments.Select(LoadType)]); + if (@ref is IR.GenericMethodInstance genericMethodInstance) + method = method.MakeGenericMethod([.. genericMethodInstance.Arguments.Select(LoadType)]); - if (method.HasSameMetadataDefinitionAs(def)) - return method; + if (method.HasSameMetadataDefinitionAs(def)) + return method; + } catch (NotSupportedException) + { + return (IL.MethodInfo)def; + } throw new(); } diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs index 6bc2c539..00378fdb 100644 --- a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs @@ -11,6 +11,8 @@ public ClassLoader(RootModuleLoader loader, IL.Emit.TypeBuilder type, IR.Class @ protected override void DoLoad() { + Context.Cache(Input, Output); + LoadNestedTypes(); ModuleLoader.AddToNextPass(LoadDefinition); @@ -23,6 +25,8 @@ protected override void DoLoad() if (Input.HasMethods) ModuleLoader.AddToNextPass(LoadMethods); + + ModuleLoader.AddToCleanUp(() => Output.CreateType()); } private void LoadDefinition() From 8b9740099a7a45ea7af95e195ae69b69428b6683 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 00:10:31 +0300 Subject: [PATCH 120/235] Update simple-user-system.zs --- ZSharpTest/projects/simple-user-system.zs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ZSharpTest/projects/simple-user-system.zs b/ZSharpTest/projects/simple-user-system.zs index c086a332..d2d63f82 100644 --- a/ZSharpTest/projects/simple-user-system.zs +++ b/ZSharpTest/projects/simple-user-system.zs @@ -6,9 +6,9 @@ * [x] Named constructor * [x] Methods * [x] Case-Of - * [ ] Automatic type inference for first parameter in methods - * [ ] Automatic instance binding when accessing instance method/field from instance method - * [ ] Instance method as function with `this` first parameter + * [x] Automatic type inference for first parameter in methods + * [x] Automatic instance binding when accessing instance method/field from instance method + * [x] Instance method as function with `this` first parameter * [x] Module globals initializers */ From 3e37974c3008869e3f2428f7853d3a1c7196beb2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 00:10:51 +0300 Subject: [PATCH 121/235] Add support for array literal initialization --- .../literals/ArrayLiteral.cs | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs b/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs index b2e2a710..2d6181b4 100644 --- a/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs +++ b/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs @@ -1,8 +1,41 @@ -namespace ZSharp.Objects +using ZSharp.Compiler; + +namespace ZSharp.Objects { public sealed class ArrayLiteral(IEnumerable? items = null) : CompilerObject + , ICTTypeCast { public List Items { get; } = new(items ?? []); + + CompilerObject ICTTypeCast.Cast(Compiler.Compiler compiler, CompilerObject targetType) + { + var instance = compiler.Call(targetType, []); + + var code = new IRCode(compiler.CompileIRCode(instance).Instructions); + + var append = compiler.Member(targetType, "append"); + + foreach (var item in Items) + code.Instructions.AddRange( + compiler.CompileIRCode( + compiler.Call(append, [ + new(new RawCode(new([ + new IR.VM.Dup() + ]) + { + Types = [targetType] + }) + ), + new(item) + ]) + ).Instructions + ); + + code.Types.Clear(); + code.Types.Add(targetType); + + return new RawCode(code); + } } } From 2c4f68da70b31bf7f66c4058f709e56d7e5828f0 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 00:11:18 +0300 Subject: [PATCH 122/235] Add methods to exposed IL list --- ZSharp.CT.StandardLibrary/Standard.List.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ZSharp.CT.StandardLibrary/Standard.List.cs b/ZSharp.CT.StandardLibrary/Standard.List.cs index 4058527e..3ea5fc7a 100644 --- a/ZSharp.CT.StandardLibrary/Standard.List.cs +++ b/ZSharp.CT.StandardLibrary/Standard.List.cs @@ -8,6 +8,11 @@ public sealed class List public List() { } + [Alias(Name = "length")] + public int Length() + => _inner.Count; + + [Alias(Name = "append")] public void Add(T item) { @@ -19,5 +24,9 @@ public T Get(int index) { return _inner[index]; } + + [Alias(Name = "removeAt")] + public void RemoveAt(int index) + => _inner.RemoveAt(index); } } From 0a636db5b5af89766aba360814f6ef55968308cf Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 00:11:39 +0300 Subject: [PATCH 123/235] Fix member access from generic class instance --- ZSharp.Compiler.Objects/oop/GenericClassInstance.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs index d823aec0..510acfb2 100644 --- a/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs +++ b/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs @@ -31,15 +31,15 @@ public CompilerObject Member(Compiler.Compiler compiler, string member) var origin = compiler.Member(Origin, member); if (Origin.GenericParameters.Count != 0) - //origin = compiler.CreateReference(origin, Context); - throw new NotImplementedException(); + origin = compiler.Map(origin, @object => compiler.Feature().CreateReference(@object, Context)); return Members[member] = origin; } public CompilerObject Member(Compiler.Compiler compiler, CompilerObject instance, string member) { - if (Members.ContainsKey(member)) return Members[member]; + if (Members.ContainsKey(member)) + return compiler.Map(Members[member], @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, instance) : @object); var origin = compiler.Member(Origin, member); From d0da1041550498c98fa46bbbed738343679cc8b4 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 00:11:53 +0300 Subject: [PATCH 124/235] Fix global to cast initializer to type --- ZSharp.Compiler/cg objects/modular/Global.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.Compiler/cg objects/modular/Global.cs b/ZSharp.Compiler/cg objects/modular/Global.cs index 434dfc2d..fad25e21 100644 --- a/ZSharp.Compiler/cg objects/modular/Global.cs +++ b/ZSharp.Compiler/cg objects/modular/Global.cs @@ -56,7 +56,7 @@ public IR.Global CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) if (!IsInitializerBuilt && Initializer is not null) { - IR.Initializer = compiler.CompileIRCode(Initializer).Instructions.ToArray(); + IR.Initializer = compiler.CompileIRCode(compiler.Cast(Initializer, Type)).Instructions.ToArray(); IsInitializerBuilt = true; } From f7b77b7ff2b6c218bb2793f0554b82bab257d384 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 00:12:11 +0300 Subject: [PATCH 125/235] Fix todo.zs to work with lists --- ZSharpTest/projects/todo.zs | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/ZSharpTest/projects/todo.zs b/ZSharpTest/projects/todo.zs index eba8e6d9..d449952f 100644 --- a/ZSharpTest/projects/todo.zs +++ b/ZSharpTest/projects/todo.zs @@ -1,10 +1,9 @@ //import { list } from "std:list"; -import { print, input } from "std:io"; +import { print, input, List } from "std:io"; module Program { -/* - let todo: list[string] = [ + let todo: List[string] = [ "Add list[T] type", "Add support for generic types in CO", "Add compiler for `for` statements", @@ -12,28 +11,43 @@ module Program { "Add compiler for `case` statements", ]; - fun addTodo() { + fun addTodo(): void { let item = input("Enter item to add: "); - todo.add(item); + todo.append(item); + + return; } - fun getTodos(): list[string] { - var i = 1; + fun getTodos(): void { + var i = 0; + + while (i < todo.length()) + { + let item = todo.get(i); + print(string(i + 1) + ". " + item); + i = i + 1; + } + /* for (let item = 0 in todo) { print(string(i) + ". " + item); i = i + 1; } + */ + + return; } fun delTodo(): void { let index = i32.parse(input("Enter item number to remove: ")); todo.removeAt(index - 1); + + return; } - */ + fun do(): bool { print("Welcome to The ToDo List App! Please choose what to do:"); print("1. Add an item."); @@ -46,9 +60,9 @@ module Program { case (cmd) { - when ("1") print("ADD"); // addTodo(); - when ("2") print("GET"); // getTodos(); - when ("3") print("DEL"); // delTodo(); + when ("1") addTodo(); + when ("2") getTodos(); + when ("3") delTodo(); when ("4") return false; } else print("Unknown command: " + cmd); From 7419b7c5acb5e129204a1cfb85b2b5d911442f34 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 00:20:05 +0300 Subject: [PATCH 126/235] Move list type to an "external" dll --- {ZSharp.CT.StandardLibrary => ZLoad.Test}/Standard.List.cs | 0 ZSharp.CT.StandardLibrary/Impl_Globals.cs | 3 +-- ZSharpTest/projects/todo.zs | 4 ++-- ZSharpTest/tests/simple.zs | 4 ++-- 4 files changed, 5 insertions(+), 6 deletions(-) rename {ZSharp.CT.StandardLibrary => ZLoad.Test}/Standard.List.cs (100%) diff --git a/ZSharp.CT.StandardLibrary/Standard.List.cs b/ZLoad.Test/Standard.List.cs similarity index 100% rename from ZSharp.CT.StandardLibrary/Standard.List.cs rename to ZLoad.Test/Standard.List.cs diff --git a/ZSharp.CT.StandardLibrary/Impl_Globals.cs b/ZSharp.CT.StandardLibrary/Impl_Globals.cs index e69f035f..cb2b5592 100644 --- a/ZSharp.CT.StandardLibrary/Impl_Globals.cs +++ b/ZSharp.CT.StandardLibrary/Impl_Globals.cs @@ -1,5 +1,4 @@ -using Standard.List; -using ZSharp.Runtime.NET.IL2IR; +using ZSharp.Runtime.NET.IL2IR; namespace Standard.IO diff --git a/ZSharpTest/projects/todo.zs b/ZSharpTest/projects/todo.zs index d449952f..c02d0aeb 100644 --- a/ZSharpTest/projects/todo.zs +++ b/ZSharpTest/projects/todo.zs @@ -1,5 +1,5 @@ -//import { list } from "std:list"; -import { print, input, List } from "std:io"; +import { List } from "net:ZLoad.Test.dll"; +import { print, input } from "std:io"; module Program { diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs index c122e6a3..af0d4b0c 100644 --- a/ZSharpTest/tests/simple.zs +++ b/ZSharpTest/tests/simple.zs @@ -1,5 +1,5 @@ -import { List, input, print } from "std:io"; -import { Console, greet, id } from "net:ZLoad.Test.dll"; +import { input, print } from "std:io"; +import { Console, List, greet, id } from "net:ZLoad.Test.dll"; // import { Console } from "net:C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\8.0.13\\System.Console.dll"; module Program; From e16f81e6f19129fef30580ffa335e92fba57a621 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 15:36:14 +0300 Subject: [PATCH 127/235] Rename Member to Constructor in ConstructorReference --- .../oop/constructor/ConstructorReference.cs | 2 +- ZSharp.IR/ir/oop/constructor/ConstructorReference.cs | 8 ++++---- ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs b/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs index 934fc214..e07614d1 100644 --- a/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs +++ b/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs @@ -28,7 +28,7 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments { var type = compiler.CompileIRReference>(ownerReference); - createInstance.Constructor = new IR.ConstructorReference(createInstance.Constructor.Member) + createInstance.Constructor = new IR.ConstructorReference(createInstance.Constructor.Constructor) { OwningType = type }; diff --git a/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs b/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs index 4afd3897..b640b16c 100644 --- a/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs +++ b/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs @@ -3,14 +3,14 @@ public sealed class ConstructorReference(Constructor constructor) : ICallable { - public Constructor Member { get; set; } = constructor; + public Constructor Constructor { get; set; } = constructor; public required OOPTypeReference OwningType { get; set; } - public Signature Signature => Member.Method.Signature; + public Signature Signature => Constructor.Method.Signature; - public bool HasBody => Member.Method.HasBody; + public bool HasBody => Constructor.Method.HasBody; - public ICallableBody? Body => Member.Method.HasBody ? Member.Method.Body : null; + public ICallableBody? Body => Constructor.Method.HasBody ? Constructor.Method.Body : null; } } diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index 7d13b827..f1f4958c 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -97,8 +97,8 @@ public IL.ConstructorInfo LoadReference(IR.ConstructorReference @ref) { var type = LoadType(@ref.OwningType); - if (!Context.Cache(@ref.Member.Method, out var def)) - throw new InvalidOperationException($"Method {@ref.Member.Name} was not loaded"); + if (!Context.Cache(@ref.Constructor.Method, out var def)) + throw new InvalidOperationException($"Constructor {@ref.Constructor.Name ?? ""} was not loaded"); var types = @ref.Signature.GetParameters().Select(p => p.Type).Skip(1).Select(LoadType).ToArray(); From 34cb7cbac3405f572864c89d8afff0e1bcd4b180 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 15:36:43 +0300 Subject: [PATCH 128/235] Fix code resolving IR references to IL --- ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 101 +++++++---------------- 1 file changed, 31 insertions(+), 70 deletions(-) diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index f1f4958c..a51d5717 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -34,7 +34,6 @@ public Type LoadType(IR.IType type) return type switch { - IR.ConstructedClass constructedClass => LoadType(constructedClass), IR.OOPTypeReference reference => LoadType(reference), _ => throw new NotImplementedException() }; @@ -61,24 +60,6 @@ public Type LoadType(IR.OOPTypeReference typeReference) return type.MakeGenericType([.. genericArguments]); } - public Type LoadType(IR.ConstructedClass constructedClass) - { - var result = LoadType(constructedClass as IR.OOPTypeReference); - - return result; - //var innerClass = LoadType(constructedClass as IR.OOPTypeReference); - - //if (innerClass is null) - // throw new(); - - //if (constructedClass.Arguments.Count == 0) - // return innerClass; - - //return innerClass.MakeGenericType([ - // .. constructedClass.Arguments.Select(LoadType) - //]); - } - public IL.MethodBase LoadReference(IR.ICallable callable) { if (Context.Cache(callable) is IL.MethodBase result) @@ -100,26 +81,20 @@ public IL.ConstructorInfo LoadReference(IR.ConstructorReference @ref) if (!Context.Cache(@ref.Constructor.Method, out var def)) throw new InvalidOperationException($"Constructor {@ref.Constructor.Name ?? ""} was not loaded"); - var types = @ref.Signature.GetParameters().Select(p => p.Type).Skip(1).Select(LoadType).ToArray(); - - try - { - var method = type.GetConstructor( - types - ); + if (def is not IL.ConstructorInfo constructorInfo) + throw new InvalidOperationException($"Method {@ref.Constructor.Name ?? ""} was not compiled to an IL method"); - if (method is null) - throw new(); + if (!type.IsGenericType) + return constructorInfo; - if (method.HasSameMetadataDefinitionAs(def)) - return method; - } - catch (NotSupportedException) - { - return (IL.ConstructorInfo)def; - } + if (type.GetGenericTypeDefinition() is IL.Emit.TypeBuilder typeBuilder) + if (!typeBuilder.IsCreated()) + return IL.Emit.TypeBuilder.GetConstructor(type, constructorInfo); - throw new(); + return (IL.ConstructorInfo)(IL.MethodBase.GetMethodFromHandle( + constructorInfo.MethodHandle, + type.TypeHandle + ) ?? throw new("Could not create constructor from method handle")); } public IL.FieldInfo LoadReference(IR.FieldReference @ref) @@ -129,21 +104,17 @@ public IL.FieldInfo LoadReference(IR.FieldReference @ref) if (!Context.Cache(@ref.Member, out var def)) throw new InvalidOperationException($"Field {@ref.Member.Name} was not loaded"); - try - { - var field = type.GetField(def.Name); - - if (field is null) - throw new(); - - if (field.HasSameMetadataDefinitionAs(def)) - return field; - } catch (NotSupportedException) - { + if (!type.IsGenericType) return def; - } - throw new(); + if (type.GetGenericTypeDefinition() is IL.Emit.TypeBuilder typeBuilder) + if (!typeBuilder.IsCreated()) + return IL.Emit.TypeBuilder.GetField(type, def); + + return IL.FieldInfo.GetFieldFromHandle( + def.FieldHandle, + type.TypeHandle + ); } public IL.MethodInfo LoadReference(IR.MethodReference @ref) @@ -153,30 +124,20 @@ public IL.MethodInfo LoadReference(IR.MethodReference @ref) if (!Context.Cache(@ref.Method, out var def)) throw new InvalidOperationException($"Method {@ref.Method.Name} was not loaded"); - var types = ((IR.ICallable)@ref).Signature.GetParameters().Select(p => p.Type).Skip(@ref.Method.IsStatic ? 0 : 1).Select(LoadType).ToArray(); - - try - { - var method = type.GetMethod( - def.Name, - def.GetGenericArguments().Length, - types - ); + if (def is not IL.MethodInfo methodInfo) + throw new InvalidOperationException($"Method {@ref.Method.Name} was not compiled to an IL method"); - if (method is null) - throw new(); + if (!type.IsGenericType) + return methodInfo; - if (@ref is IR.GenericMethodInstance genericMethodInstance) - method = method.MakeGenericMethod([.. genericMethodInstance.Arguments.Select(LoadType)]); - - if (method.HasSameMetadataDefinitionAs(def)) - return method; - } catch (NotSupportedException) - { - return (IL.MethodInfo)def; - } + if (type.GetGenericTypeDefinition() is IL.Emit.TypeBuilder typeBuilder) + if (!typeBuilder.IsCreated()) + return IL.Emit.TypeBuilder.GetMethod(type, methodInfo); - throw new(); + return (IL.MethodInfo)(IL.MethodBase.GetMethodFromHandle( + methodInfo.MethodHandle, + type.TypeHandle + ) ?? throw new("Could not create method from method handle")); } public IL.MethodInfo LoadReference(IR.GenericFunctionInstance @ref) From 69baac87f5adb457674ff15f8a173c4482881724 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:26:02 +0300 Subject: [PATCH 129/235] Edit comment --- ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs index 00378fdb..a627e12f 100644 --- a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs @@ -51,7 +51,7 @@ private void LoadGenericParameters() { foreach (var ir in Input.GenericParameters) { - //Context.Uncache(ir); + // TODO: Context.Uncache(ir); } }); } From 0a097a405e2ce9f583c439b84022d3a5bdfba9d7 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:26:18 +0300 Subject: [PATCH 130/235] Add todo comment --- ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Compilers.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Compilers.cs b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Compilers.cs index 331d2c62..22530dc5 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Compilers.cs +++ b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Compilers.cs @@ -22,6 +22,8 @@ public ModuleCompiler CreateModuleCompiler(Module module) // ConstructorInfo.Invoke has an overload which takes `this` as the first parameter (for late initialization). if (metaClass is not null) c.LogError("Metaclasses are not supported yet.", oop); + // TODO: if has generic, return generic class compiler + return new ClassCompiler(c, oop, compiler.DefaultMetaClass); }); From bd04e4515d8c0a5f36e6950d821231682f0ca345 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:27:16 +0300 Subject: [PATCH 131/235] Split generic class loading from regular class loading --- .../ir loader/IRLoader.Impl.cs | 127 +++++++++++++++--- 1 file changed, 110 insertions(+), 17 deletions(-) diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index be691b63..bd9ec2bc 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -104,11 +104,14 @@ private Action Load(IR.OOPType type, Module owner) private Action Load(IR.Class @class, Module owner) { - GenericClass result = new() + if (@class.HasGenericParameters) + return LoadGenericClass(@class, owner); + + Class result = new() { Name = @class.Name ?? string.Empty, - IR = new(@class), - Defined = true, + IR = @class, + IsDefined = true, }; Context.Objects.Cache(@class, result); @@ -121,20 +124,6 @@ private Action Load(IR.Class @class, Module owner) if (@class.Base is not null) result.Base = Load(@class.Base); - if (@class.HasGenericParameters) - foreach (var parameter in @class.GenericParameters) - { - var genericParameter = new GenericParameter() - { - Name = parameter.Name, - IR = parameter, - }; - - Context.Types.Cache(parameter, genericParameter); - - result.GenericParameters.Add(genericParameter); - } - return () => { if (@class.HasFields) @@ -246,6 +235,110 @@ private CompilerObject Load(IR.ConstructedClass constructed) return origin; } + private Action LoadGenericClass(IR.Class @class, Module owner) + { + GenericClass result = new() + { + Name = @class.Name ?? string.Empty, + IR = new(@class), + Defined = true, + }; + + Context.Objects.Cache(@class, result); + + owner.Content.Add(result); + + if (result.Name is not null && result.Name != string.Empty) + owner.Members.Add(result.Name, result); + + if (@class.Base is not null) + result.Base = Load(@class.Base); + + if (@class.HasGenericParameters) + foreach (var parameter in @class.GenericParameters) + { + var genericParameter = new GenericParameter() + { + Name = parameter.Name, + IR = parameter, + }; + + Context.Types.Cache(parameter, genericParameter); + + result.GenericParameters.Add(genericParameter); + } + + return () => + { + if (@class.HasFields) + foreach (var field in @class.Fields) + { + Field resultField = new(field.Name) + { + IR = field, + Type = Load(field.Type), + }; + if (field.Initializer is not null) + resultField.Initializer = new RawCode(new(field.Initializer) + { + Types = [resultField.Type] + }); + result.Members.Add(resultField.Name, resultField); + } + ; + + if (@class.Constructors.Count > 0) + foreach (var constructor in @class.Constructors) + { + Constructor resultConstructor = new(constructor.Name) + { + Owner = result, + IR = constructor, + }; + if (resultConstructor.Name is not null && resultConstructor.Name != string.Empty) + { + if (!result.Members.TryGetValue(resultConstructor.Name, out var group)) + result.Members.Add(resultConstructor.Name, group = new OverloadGroup(resultConstructor.Name)); + + if (group is not OverloadGroup overloadGroup) + throw new InvalidOperationException(); + + overloadGroup.Overloads.Add(resultConstructor); + } + else + { + if (result.Constructor is not OverloadGroup group) + result.Constructor = group = new OverloadGroup(string.Empty); + + group.Overloads.Add(resultConstructor); + } + resultConstructor.Signature = Load(constructor.Method.Signature); + } + + if (@class.Methods.Count > 0) + foreach (var method in @class.Methods) + { + Method resultMethod = new(method.Name) + { + IR = method, + Defined = true, + }; + if (resultMethod.Name is not null && resultMethod.Name != string.Empty) + { + if (!result.Members.TryGetValue(resultMethod.Name, out var group)) + result.Members.Add(resultMethod.Name, group = new OverloadGroup(resultMethod.Name)); + + if (group is not OverloadGroup overloadGroup) + throw new InvalidOperationException(); + + overloadGroup.Overloads.Add(resultMethod); + } + resultMethod.Signature = Load(method.Signature); + resultMethod.ReturnType = Load(method.ReturnType); + } + }; + } + private Action LoadGenericFunction(IR.Function function, Module owner) { GenericFunction result = new(function.Name) From d0edb0bf866f0904ea37e7977d7644f6363647b6 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:27:31 +0300 Subject: [PATCH 132/235] Fix function loading --- ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index bd9ec2bc..f1f5d369 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -67,7 +67,8 @@ private Action Load(IR.Function function, Module owner) RTFunction result = new(function.Name) { - IR = function + IR = function, + IsDefined = true, }; Context.Objects.Cache(function, result); From 629600352ae41718d4094ae947c727852bae41e2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:28:25 +0300 Subject: [PATCH 133/235] Organize some COs --- .../error messages/Errors.Compilation.cs | 3 + .../functional/Function.cs | 4 - .../functional/RTFunction.cs | 135 ++++++++---------- .../functional/body/Local.cs | 42 +++--- .../functional/signature/Parameter.cs | 6 +- .../functional/signature/Signature.cs | 27 ++++ .../modular/Global.cs | 58 +++++--- .../modular/Module.cs | 2 +- ZSharp.Compiler.Objects/oop/Class.cs | 65 --------- ZSharp.Compiler.Objects/oop/class/Class.cs | 120 ++++++++++++++++ .../oop/{ => class}/GenericClass.cs | 0 .../oop/{ => class}/GenericClassInstance.cs | 0 .../oop/constructor/Constructor.cs | 18 +-- .../oop/interface/Interface.cs | 93 ++++++++++++ ZSharp.Compiler.Objects/oop/method/Method.cs | 111 ++++++-------- .../signature/IParameter.cs | 2 +- .../signature/ISignature.cs | 7 +- 17 files changed, 416 insertions(+), 277 deletions(-) rename {ZSharp.Compiler/cg objects => ZSharp.Compiler.Objects}/modular/Global.cs (59%) rename {ZSharp.Compiler/cg objects => ZSharp.Compiler.Objects}/modular/Module.cs (100%) delete mode 100644 ZSharp.Compiler.Objects/oop/Class.cs create mode 100644 ZSharp.Compiler.Objects/oop/class/Class.cs rename ZSharp.Compiler.Objects/oop/{ => class}/GenericClass.cs (100%) rename ZSharp.Compiler.Objects/oop/{ => class}/GenericClassInstance.cs (100%) create mode 100644 ZSharp.Compiler.Objects/oop/interface/Interface.cs diff --git a/ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs b/ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs index f27e9de8..b79f4823 100644 --- a/ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs +++ b/ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs @@ -2,6 +2,9 @@ { internal static partial class Errors { + public static string UndefinedGlobalType(string name) + => $"Type of global {name} is not defined"; + public static string UndefinedReturnType(string name) => $"Return type of function {(name == string.Empty ? "" : name)} is not defined."; } diff --git a/ZSharp.Compiler.Objects/functional/Function.cs b/ZSharp.Compiler.Objects/functional/Function.cs index 93948ca6..c52f529f 100644 --- a/ZSharp.Compiler.Objects/functional/Function.cs +++ b/ZSharp.Compiler.Objects/functional/Function.cs @@ -15,11 +15,7 @@ public abstract class Function(string? name) : CompilerObject , ICTCallable { - public IR.Function? IR { get; set; } - public string Name { get; set; } = name ?? string.Empty; - - public CompilerObject? Body { get; set; } public abstract CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments); } diff --git a/ZSharp.Compiler.Objects/functional/RTFunction.cs b/ZSharp.Compiler.Objects/functional/RTFunction.cs index a24127c5..a7056b64 100644 --- a/ZSharp.Compiler.Objects/functional/RTFunction.cs +++ b/ZSharp.Compiler.Objects/functional/RTFunction.cs @@ -5,7 +5,8 @@ namespace ZSharp.Objects { public class RTFunction(string? name) - : Function(name) + : CompilerObject + , ICTCallable , ICTReadable , ICompileIRObject { @@ -20,71 +21,66 @@ enum BuildState private readonly ObjectBuildState state = new(); + public bool IsDefined + { + init + { + if (value) + foreach (var item in Enum.GetValues()) + state[item] = true; + } + } + + public IR.Function? IR { get; set; } + + public string Name { get; set; } = name ?? string.Empty; + + public CompilerObject? Body { get; set; } + CompilerObject ITyped.Type => throw new NotImplementedException(); public Signature Signature { get; set; } = new(); public CompilerObject? ReturnType { get; set; } - public override CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { - var (args, kwargs) = Utils.SplitArguments(arguments); - - try - { - return Call(compiler, args, kwargs); - } - catch (Compiler.InvalidCastException) - { - throw new ArgumentMismatchException(this, arguments); - } + return Call(compiler, arguments); } - private RawCode Call(Compiler.Compiler compiler, Collection args, Mapping kwArgs) + private RawCode Call(Compiler.Compiler compiler, Argument[] arguments) { - IR ??= CompileIRObject(compiler, null); - - IRCode - argsCode = new(), varArgsCode = new(), - kwArgsCode = new(), varKwArgsCode = new(); - - if (args.Count > Signature.Args.Count) - if (Signature.VarArgs is null) - throw new($"Function {Name} takes {Signature.Args.Count} arguments, but {args.Count} were given."); - else - throw new NotImplementedException("var args"); - else if (args.Count < Signature.Args.Count) - throw new($"Function {Name} takes {Signature.Args.Count} arguments, but {args.Count} were given."); - - for (int i = 0; i < Signature.Args.Count; i++) - argsCode.Append(compiler.CompileIRCode(compiler.Cast(args[i], Signature.Args[i].Type ?? throw new()))); - - if (kwArgs.Count > Signature.KwArgs.Count) - if (Signature.VarKwArgs is null) - throw new($"Function {Name} takes {Signature.KwArgs.Count} keyword arguments, but {kwArgs.Count} were given."); - else - throw new NotImplementedException("var kwargs"); - else if (kwArgs.Count < Signature.KwArgs.Count) - throw new($"Function {Name} takes {Signature.KwArgs.Count} keyword arguments, but {kwArgs.Count} were given."); - - foreach (var kwArgParameter in Signature.KwArgs) - kwArgsCode.Append(compiler.CompileIRCode(compiler.Cast(kwArgs[kwArgParameter.Name], kwArgParameter.Type ?? throw new()))); - - IRCode result = new(); - result.Append(argsCode); - result.Append(varArgsCode); // should be empty - result.Append(kwArgsCode); - result.Append(varKwArgsCode); // should be empty - - result.Instructions.Add(new IR.VM.Call(IR)); - - result.Types.Clear(); - if (ReturnType != compiler.TypeSystem.Void) - result.Types.Add(ReturnType!); + if (ReturnType is null) + throw new PartiallyCompiledObjectException(this, Errors.UndefinedReturnType(Name)); + + var args = (Signature as ISignature).MatchArguments(compiler, arguments); + + IRCode code = new(); - result.MaxStackSize = Math.Max(result.MaxStackSize, result.Types.Count); + List @params = []; - return new(result); + @params.AddRange(Signature.Args); + + if (Signature.VarArgs is not null) + @params.Add(Signature.VarArgs); + + @params.AddRange(Signature.KwArgs); + + if (Signature.VarKwArgs is not null) + @params.Add(Signature.VarKwArgs); + + foreach (var param in @params) + code.Append(compiler.CompileIRCode(args[param])); + + code.Append(new([ + new IR.VM.Call(compiler.CompileIRObject(this, null)) + ])); + + code.Types.Clear(); + if (ReturnType != compiler.TypeSystem.Void) + code.Types.Add(ReturnType); + + return new RawCode(code); } IRCode ICTReadable.Read(Compiler.Compiler compiler) @@ -111,35 +107,28 @@ public IR.Function CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) Name = Name }; - if (owner is not null && !state.Get(BuildState.Owner)) + if (ReturnType is null) + throw new PartiallyCompiledObjectException(this, Errors.UndefinedReturnType(Name)); + + if (owner is not null && !state[BuildState.Owner]) { - owner.Functions.Add(IR); + state[BuildState.Owner] = true; - state.Set(BuildState.Owner); + owner.Functions.Add(IR); } - if (!state.Get(BuildState.Signature)) + if (!state[BuildState.Signature]) { - foreach (var arg in Signature.Args) - IR.Signature.Args.Parameters.Add(compiler.CompileIRObject(arg, IR.Signature)); - - if (Signature.VarArgs is not null) - IR.Signature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, IR.Signature); + state[BuildState.Signature] = true; - foreach (var kwArg in Signature.KwArgs) - IR.Signature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, IR.Signature)); - - if (Signature.VarKwArgs is not null) - IR.Signature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, IR.Signature); - - state.Set(BuildState.Signature); + compiler.CompileIRObject(Signature, IR.Signature); } - if (Body is not null && !state.Get(BuildState.Body)) + if (Body is not null && !state[BuildState.Body]) { - IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); + state[BuildState.Body] = true; - state.Set(BuildState.Body); + IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); } return IR; diff --git a/ZSharp.Compiler.Objects/functional/body/Local.cs b/ZSharp.Compiler.Objects/functional/body/Local.cs index 807116fc..035ea6f9 100644 --- a/ZSharp.Compiler.Objects/functional/body/Local.cs +++ b/ZSharp.Compiler.Objects/functional/body/Local.cs @@ -17,23 +17,13 @@ enum BuildState Initializer = 0b100, } - private BuildState _state = BuildState.None; + private readonly ObjectBuildState state = new(); public IR.VM.Local? IR { get; set; } public required string Name { get; set; } - public bool IsOwnerBuilt - { - get => _state.HasFlag(BuildState.Owner); - set => _state = value ? _state | BuildState.Owner : _state & ~BuildState.Owner; - } - - public bool IsInitializerBuilt - { - get => _state.HasFlag(BuildState.Initializer); - set => _state = value ? _state | BuildState.Initializer : _state & ~BuildState.Initializer; - } + public bool IsReadOnly { get; set; } public CompilerObject? Type { get; set; } @@ -42,22 +32,24 @@ public bool IsInitializerBuilt public IR.VM.Local CompileIRObject(Compiler.Compiler compiler, ICallableBody? owner) { if (Type is null) - throw new(); + throw new PartiallyCompiledObjectException( + this, $"Local variable {Name} does not have a type" + ); IR ??= new(Name, compiler.CompileIRType(Type)); - if (!IsOwnerBuilt && owner is not null) + if (owner is not null && !state[BuildState.Owner]) { - owner.Locals.Add(IR); + state[BuildState.Owner] = true; - IsOwnerBuilt = true; + owner.Locals.Add(IR); } - if (!IsInitializerBuilt && Initializer is not null) + if (Initializer is not null && !state[BuildState.Initializer]) { - IR.Initializer = compiler.CompileIRCode(Initializer).Instructions.ToArray(); + state[BuildState.Initializer] = true; - IsInitializerBuilt = true; + IR.Initializer = [.. compiler.CompileIRCode(Initializer).Instructions]; } return IR; @@ -72,14 +64,20 @@ public IRCode Read(Compiler.Compiler compiler) public CompilerObject Assign(Compiler.Compiler compiler, CompilerObject value) { - // TODO: check if read-only + if (IsReadOnly) + throw new(); if (Type is null) - throw new(); + if (compiler.TypeSystem.IsTyped(value, out var valueType)) + Type = valueType; + else throw new PartiallyCompiledObjectException(this, $"Local variable {Name} does not have a type"); IR ??= CompileIRObject(compiler, null); - var code = compiler.CompileIRCode(compiler.Cast(value, Type)); + if (!compiler.TypeSystem.ImplicitCast(value, Type).Ok(out var cast)) + throw new Compiler.InvalidCastException(value, Type); + + var code = compiler.CompileIRCode(cast); code.Instructions.AddRange( [ diff --git a/ZSharp.Compiler.Objects/functional/signature/Parameter.cs b/ZSharp.Compiler.Objects/functional/signature/Parameter.cs index d43caa6c..7744ceec 100644 --- a/ZSharp.Compiler.Objects/functional/signature/Parameter.cs +++ b/ZSharp.Compiler.Objects/functional/signature/Parameter.cs @@ -53,12 +53,12 @@ Parameter IReferencable.CreateReference(Referencing @ref, ReferenceCo }; } - CompilerObject IParameter.MatchArgument(Compiler.Compiler compiler, CompilerObject argument) + CompilerObjectResult IParameter.MatchArgument(Compiler.Compiler compiler, CompilerObject argument) { if (Type is null) - throw new InvalidOperationException($"Parameter's {Name} type is not defined"); + throw new PartiallyCompiledObjectException(this, $"Parameter's {Name} type is not defined"); - return compiler.Cast(argument, Type); + return compiler.TypeSystem.ImplicitCast(argument, Type); } } } diff --git a/ZSharp.Compiler.Objects/functional/signature/Signature.cs b/ZSharp.Compiler.Objects/functional/signature/Signature.cs index cc3322e4..ba8f42b5 100644 --- a/ZSharp.Compiler.Objects/functional/signature/Signature.cs +++ b/ZSharp.Compiler.Objects/functional/signature/Signature.cs @@ -5,9 +5,12 @@ namespace ZSharp.Objects { public sealed class Signature : CompilerObject + , ICompileIRObject , IReferencable , ISignature { + public IR.Signature? IR { get; private set; } + public Parameters Args { get; init; } = []; public VarParameter? VarArgs { get; set; } @@ -16,6 +19,30 @@ public sealed class Signature public KeywordVarParameter? VarKwArgs { get; set; } + IR.Signature ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Signature? owner) + { + if (IR is not null) + return IR; + + owner ??= new(compiler.RuntimeModule.TypeSystem.Void); + + IR = owner; + + foreach (var arg in Args) + IR.Args.Parameters.Add(compiler.CompileIRObject(arg, IR)); + + if (VarArgs is not null) + IR.Args.Var = compiler.CompileIRObject(VarArgs, IR); + + foreach (var kwArg in KwArgs) + IR.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, IR)); + + if (VarKwArgs is not null) + IR.KwArgs.Var = compiler.CompileIRObject(VarKwArgs, IR); + + return IR; + } + Signature IReferencable.CreateReference(Referencing @ref, ReferenceContext context) { Signature result = new(); diff --git a/ZSharp.Compiler/cg objects/modular/Global.cs b/ZSharp.Compiler.Objects/modular/Global.cs similarity index 59% rename from ZSharp.Compiler/cg objects/modular/Global.cs rename to ZSharp.Compiler.Objects/modular/Global.cs index fad25e21..8aef03f6 100644 --- a/ZSharp.Compiler/cg objects/modular/Global.cs +++ b/ZSharp.Compiler.Objects/modular/Global.cs @@ -8,6 +8,8 @@ public sealed class Global(string name) , ICTReadable , ICompileIRObject { + #region Build State + [Flags] enum BuildState { @@ -16,7 +18,19 @@ enum BuildState Initializer = 0b10, } - private BuildState _state = BuildState.None; + private readonly ObjectBuildState state = new(); + + public bool IsDefined + { + init + { + if (value) + foreach (var item in Enum.GetValues()) + state[item] = true; + } + } + + #endregion public IR.Global? IR { get; set; } @@ -24,41 +38,37 @@ enum BuildState public bool IsReadOnly { get; set; } - public bool IsOwnerBuilt - { - get => _state.HasFlag(BuildState.Owner); - set => _state = value ? _state | BuildState.Owner : _state & ~BuildState.Owner; - } - - public bool IsInitializerBuilt - { - get => _state.HasFlag(BuildState.Initializer); - set => _state = value ? _state | BuildState.Initializer : _state & ~BuildState.Initializer; - } - public CompilerObject? Initializer { get; set; } public CompilerObject? Type { get; set; } + #region Protocols + public IR.Global CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) { if (Type is null) - throw new(); + throw new PartiallyCompiledObjectException( + this, + Errors.UndefinedGlobalType(Name) + ); IR ??= new(Name, compiler.CompileIRType(Type)); - if (!IsOwnerBuilt && owner is not null) + if (owner is not null && !state[BuildState.Owner]) { - owner.Globals.Add(IR!); + state[BuildState.Owner] = true; - IsOwnerBuilt = true; + owner.Globals.Add(IR!); } - if (!IsInitializerBuilt && Initializer is not null) + if (Initializer is not null && !state[BuildState.Initializer]) { - IR.Initializer = compiler.CompileIRCode(compiler.Cast(Initializer, Type)).Instructions.ToArray(); + state[BuildState.Initializer] = true; + + if (!compiler.TypeSystem.ImplicitCast(Initializer, Type).Ok(out var initializer)) + throw new Compiler.InvalidCastException(Initializer, Type); - IsInitializerBuilt = true; + IR.Initializer = [.. compiler.CompileIRCode(initializer).Instructions]; } return IR; @@ -81,7 +91,9 @@ public CompilerObject Assign(Compiler.Compiler compiler, CompilerObject value) IR = compiler.CompileIRObject(this, null); - var cast = compiler.Cast(value, Type); + if (!compiler.TypeSystem.ImplicitCast(value, Type).Ok(out var cast)) + throw new Compiler.InvalidCastException(value, Type); + var code = compiler.CompileIRCode(cast); code.Instructions.AddRange( @@ -90,10 +102,12 @@ public CompilerObject Assign(Compiler.Compiler compiler, CompilerObject value) new IR.VM.SetGlobal(IR), ] ); - + code.RequireValueType(); return new RawCode(code); } + + #endregion } } diff --git a/ZSharp.Compiler/cg objects/modular/Module.cs b/ZSharp.Compiler.Objects/modular/Module.cs similarity index 100% rename from ZSharp.Compiler/cg objects/modular/Module.cs rename to ZSharp.Compiler.Objects/modular/Module.cs index fc23bd9d..3a32f199 100644 --- a/ZSharp.Compiler/cg objects/modular/Module.cs +++ b/ZSharp.Compiler.Objects/modular/Module.cs @@ -5,9 +5,9 @@ namespace ZSharp.Objects { public sealed class Module(string name) : CompilerObject + , ICompileIRObject , ICTGetMember , ICTReadable - , ICompileIRObject { CompilerObject ITyped.Type => throw new NotImplementedException(); diff --git a/ZSharp.Compiler.Objects/oop/Class.cs b/ZSharp.Compiler.Objects/oop/Class.cs deleted file mode 100644 index 9b9ab7c6..00000000 --- a/ZSharp.Compiler.Objects/oop/Class.cs +++ /dev/null @@ -1,65 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Class - : CompilerObject - , ICompileIRObject - { - [Flags] - enum BuildState - { - None = 0, - Base = 0b1, - Interfaces = 0b10, - Body = 0b100, - Owner = 0b1000, - } - private readonly ObjectBuildState state = new(); - - public IR.Class? IR { get; private set; } - - public string? Name { get; set; } - - public CompilerObject? Base { get; set; } - - public Collection Interfaces { get; } = []; - - public Collection Content { get; } = []; - - IR.Class ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) - { - IR ??= new(Name); - - if (Base is not null && !state[BuildState.Base]) - { - state[BuildState.Base] = true; - - IR.Base = compiler.CompileIRReference>(Base); - } - - if (Interfaces.Count > 0 && !state[BuildState.Interfaces]) - { - throw new NotImplementedException($"Interfaces are not supported yet."); - } - - if (Content.Count > 0 && !state[BuildState.Body]) - { - state[BuildState.Body] = true; - - foreach (var item in Content) - compiler.CompileIRObject(item, IR); - } - - if (owner is not null && !state[BuildState.Owner]) - { - state[BuildState.Owner] = true; - - owner.Types.Add(IR); - } - - return IR; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/class/Class.cs b/ZSharp.Compiler.Objects/oop/class/Class.cs new file mode 100644 index 00000000..5c120b5b --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/class/Class.cs @@ -0,0 +1,120 @@ +using CommonZ.Utils; +using ZSharp.Compiler; +using ZSharp.IR; + +namespace ZSharp.Objects +{ + public sealed class Class + : CompilerObject + , ICompileIRObject + , ICompileIRType> + , ICTCallable + , ICTGetMember + , IRTGetMember + { + #region Build State + + [Flags] + enum BuildState + { + None = 0, + Base = 0b1, + Interfaces = 0b10, + Body = 0b100, + Owner = 0b1000, + } + private readonly ObjectBuildState state = new(); + + public bool IsDefined + { + init + { + if (value) + foreach (var item in Enum.GetValues()) + state[item] = true; + } + } + + #endregion + + public IR.Class? IR { get; set; } + + public string? Name { get; set; } + + public CompilerObject? Base { get; set; } + + public CompilerObject? Constructor { get; set; } + + public Collection Interfaces { get; } = []; + + public Collection Content { get; } = []; + + public Mapping Members { get; } = []; + + #region Protocols + + IR.Class ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) + { + IR ??= new(Name); + + if (Base is not null && !state[BuildState.Base]) + { + state[BuildState.Base] = true; + + IR.Base = compiler.CompileIRReference>(Base); + } + + if (!state[BuildState.Interfaces]) + { + state[BuildState.Interfaces] = true; + + foreach (var @interface in Interfaces) + { + IR.InterfacesImplementations.Add(new(compiler.CompileIRReference>(@interface))); + + // TODO: check for interface implementation + } + } + + if (Content.Count > 0 && !state[BuildState.Body]) + { + state[BuildState.Body] = true; + + foreach (var item in Content) + compiler.CompileIRObject(item, IR); + } + + if (owner is not null && !state[BuildState.Owner]) + { + state[BuildState.Owner] = true; + + owner.Types.Add(IR); + } + + return IR; + } + + CompilerObject ICTGetMember.Member(Compiler.Compiler compiler, string member) + => Members[member]; + + CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerObject instance, string member) + { + return compiler.Map(Members[member], @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, instance) : @object); + } + + OOPTypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) + { + return new ClassReference(compiler.CompileIRObject(this, null)); + } + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + if (Constructor is null) + throw new InvalidOperationException($"Class {Name} is not constructible"); + + return compiler.Call(Constructor, arguments); + } + + #endregion + } +} diff --git a/ZSharp.Compiler.Objects/oop/GenericClass.cs b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs similarity index 100% rename from ZSharp.Compiler.Objects/oop/GenericClass.cs rename to ZSharp.Compiler.Objects/oop/class/GenericClass.cs diff --git a/ZSharp.Compiler.Objects/oop/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs similarity index 100% rename from ZSharp.Compiler.Objects/oop/GenericClassInstance.cs rename to ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs diff --git a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs index fc0dac92..c6ab3b4e 100644 --- a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs +++ b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs @@ -29,7 +29,7 @@ enum BuildState public Signature Signature { get; set; } = new(); - public GenericClass? Owner { get; set; } + public CompilerObject? Owner { get; set; } public CompilerObject? Body { get; set; } @@ -130,21 +130,11 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) state.Set(BuildState.Owner); } - if (!state.Get(BuildState.Signature)) + if (!state[BuildState.Signature]) { - foreach (var arg in Signature.Args) - IR.Method.Signature.Args.Parameters.Add(compiler.CompileIRObject(arg, IR.Method.Signature)); + state[BuildState.Signature] = true; - if (Signature.VarArgs is not null) - IR.Method.Signature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, IR.Method.Signature); - - foreach (var kwArg in Signature.KwArgs) - IR.Method.Signature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, IR.Method.Signature)); - - if (Signature.VarKwArgs is not null) - IR.Method.Signature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, IR.Method.Signature); - - state.Set(BuildState.Signature); + compiler.CompileIRObject(Signature, IR.Method.Signature); } if (Body is not null && !state.Get(BuildState.Body)) diff --git a/ZSharp.Compiler.Objects/oop/interface/Interface.cs b/ZSharp.Compiler.Objects/oop/interface/Interface.cs new file mode 100644 index 00000000..7bdfbb33 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/interface/Interface.cs @@ -0,0 +1,93 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class Interface(string? name) + : CompilerObject + , ICompileIRObject + , ICompileIRReference> + , ICTGetMember + , IRTGetMember + { + #region Build State + + [Flags] + enum BuildState + { + None = 0b0, + Owner = 0b1, + Bases = 0b10, + Body = 0b100, + } + + private readonly ObjectBuildState state = new(); + + public bool IsDefined + { + init + { + if (value) + foreach (var item in Enum.GetValues()) + state[item] = true; + } + } + + #endregion + + public IR.Interface? IR { get; set; } + + public string Name { get; set; } = name ?? string.Empty; + + public Collection Bases { get; } = []; + + public Collection Content { get; } = []; + + public Mapping Members = []; + + #region Protocols + + CompilerObject ICTGetMember.Member(Compiler.Compiler compiler, string member) + => Members[member]; + + CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerObject value, string member) + => compiler.Map(Members[member], @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, value) : @object); + + IR.Interface ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) + { + IR ??= new(Name); + + if (owner is not null && !state[BuildState.Owner]) + { + state[BuildState.Owner] = true; + + owner.Types.Add(IR); + } + + if (!state[BuildState.Bases]) + { + state[BuildState.Bases] = true; + + foreach (var @base in Bases) + IR.Bases.Add(compiler.CompileIRReference>(@base)); + } + + if (!state[BuildState.Body]) + { + state[BuildState.Body] = true; + + foreach (var item in Content) + compiler.CompileIRObject(item, IR); + } + + return IR; + } + + IR.OOPTypeReference ICompileIRReference>.CompileIRReference(Compiler.Compiler compiler) + => new IR.InterfaceReference( + compiler.CompileIRObject(this, null) + ); + + #endregion + } +} diff --git a/ZSharp.Compiler.Objects/oop/method/Method.cs b/ZSharp.Compiler.Objects/oop/method/Method.cs index 89413a01..be0dcf35 100644 --- a/ZSharp.Compiler.Objects/oop/method/Method.cs +++ b/ZSharp.Compiler.Objects/oop/method/Method.cs @@ -36,7 +36,7 @@ public bool Defined { init public IR.Method? IR { get; set; } - public string? Name { get; set; } = name; + public string Name { get; set; } = name ?? string.Empty; public Signature Signature { get; set; } = new(); @@ -49,63 +49,37 @@ public CompilerObject Bind(Compiler.Compiler compiler, CompilerObject value) public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) { - var (args, kwargs) = Utils.SplitArguments(arguments); + if (ReturnType is null) + throw new PartiallyCompiledObjectException(this, Errors.UndefinedReturnType(Name)); - try - { - return Call(compiler, args, kwargs); - } - catch - { - throw new ArgumentMismatchException(this, arguments); - } - } + var args = (Signature as ISignature).MatchArguments(compiler, arguments); - public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) - { - // TODO: type checking (when type system is implemented) - - IRCode - argsCode = new(), varArgsCode = new(), - kwArgsCode = new(), varKwArgsCode = new(); - - if (args.Count > Signature.Args.Count) - if (Signature.VarArgs is null) - throw new($"Function {Name} takes {Signature.Args.Count} arguments, but {args.Count} were given."); - else - throw new NotImplementedException("var args"); - else if (args.Count < Signature.Args.Count) - throw new($"Function {Name} takes {Signature.Args.Count} arguments, but {args.Count} were given."); - - for (int i = 0; i < Signature.Args.Count; i++) - argsCode.Append(compiler.CompileIRCode(args[i])); - - if (kwArgs.Count > Signature.KwArgs.Count) - if (Signature.VarKwArgs is null) - throw new($"Function {Name} takes {Signature.KwArgs.Count} keyword arguments, but {kwArgs.Count} were given."); - else - throw new NotImplementedException("var kwargs"); - else if (kwArgs.Count < Signature.KwArgs.Count) - throw new($"Function {Name} takes {Signature.KwArgs.Count} keyword arguments, but {kwArgs.Count} were given."); - - foreach (var kwArgParameter in Signature.KwArgs) - kwArgsCode.Append(compiler.CompileIRCode(kwArgs[kwArgParameter.Name])); - - IRCode result = new(); - result.Append(argsCode); - result.Append(varArgsCode); // should be empty - result.Append(kwArgsCode); - result.Append(varKwArgsCode); // should be empty - - result.Instructions.Add(new IR.VM.Call(IR!)); - - result.Types.Clear(); - if (ReturnType != compiler.TypeSystem.Void) - result.Types.Add(ReturnType!); + IRCode code = new(); + + List @params = []; - result.MaxStackSize = Math.Max(result.MaxStackSize, result.Types.Count); + @params.AddRange(Signature.Args); - return new RawCode(result); + if (Signature.VarArgs is not null) + @params.Add(Signature.VarArgs); + + @params.AddRange(Signature.KwArgs); + + if (Signature.VarKwArgs is not null) + @params.Add(Signature.VarKwArgs); + + foreach (var param in @params) + code.Append(compiler.CompileIRCode(args[param])); + + code.Append(new([ + new IR.VM.Call(compiler.CompileIRObject(this, null)) + ])); + + code.Types.Clear(); + if (ReturnType != compiler.TypeSystem.Void) + code.Types.Add(ReturnType); + + return new RawCode(code); } [MemberNotNull(nameof(ReturnType))] @@ -125,33 +99,28 @@ public IR.Method CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) IsInstance = true, }; - if (owner is not null && !state.Get(BuildState.Owner)) + if (ReturnType is null) + throw new PartiallyCompiledObjectException( + this, Errors.UndefinedReturnType(Name) + ); + + if (owner is not null && !state[BuildState.Owner]) { - state.Set(BuildState.Owner); + state[BuildState.Owner] = true; owner.Methods.Add(IR); } - if (!state.Get(BuildState.Signature)) + if (!state[BuildState.Signature]) { - state.Set(BuildState.Signature); - - foreach (var arg in Signature.Args) - IR.Signature.Args.Parameters.Add(compiler.CompileIRObject(arg, IR.Signature)); - - if (Signature.VarArgs is not null) - IR.Signature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, IR.Signature); + state[BuildState.Signature] = true; - foreach (var kwArg in Signature.KwArgs) - IR.Signature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, IR.Signature)); - - if (Signature.VarKwArgs is not null) - IR.Signature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, IR.Signature); + compiler.CompileIRObject(Signature, IR.Signature); } - if (Body is not null && !state.Get(BuildState.Body)) + if (Body is not null && !state[BuildState.Body]) { - state.Set(BuildState.Body); + state[BuildState.Body] = true; IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); } diff --git a/ZSharp.Compiler.Objects/signature/IParameter.cs b/ZSharp.Compiler.Objects/signature/IParameter.cs index a80990cc..d282198c 100644 --- a/ZSharp.Compiler.Objects/signature/IParameter.cs +++ b/ZSharp.Compiler.Objects/signature/IParameter.cs @@ -6,6 +6,6 @@ public interface IParameter : CompilerObject public CompilerObject? Default { get; } - public CompilerObject MatchArgument(Compiler.Compiler compiler, CompilerObject argument); + public CompilerObjectResult MatchArgument(Compiler.Compiler compiler, CompilerObject argument); } } diff --git a/ZSharp.Compiler.Objects/signature/ISignature.cs b/ZSharp.Compiler.Objects/signature/ISignature.cs index 1fb988c8..30852156 100644 --- a/ZSharp.Compiler.Objects/signature/ISignature.cs +++ b/ZSharp.Compiler.Objects/signature/ISignature.cs @@ -26,6 +26,9 @@ public Mapping MatchArguments(Compiler.Compiler } catch (ArgumentsCountMismatchException argumentsCountMismatch) { throw new ArgumentMismatchException(this, arguments, innerException: argumentsCountMismatch); + } catch (Compiler.InvalidCastException invalidCast) + { + throw new ArgumentMismatchException(this, arguments, innerException: invalidCast); } } @@ -51,7 +54,9 @@ public Mapping MatchArguments(Compiler.Compiler if (!positionalArgumentsQueue.TryDequeue(out var arg)) arg = param.Default ?? throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); - result[param] = param.MatchArgument(compiler, arg); + if (param.MatchArgument(compiler, arg).Ok(out var argumentResult)) + result[param] = argumentResult; + else throw new Compiler.InvalidCastException(arg, null!); } if (varParams is not null) From f5ad8a228cb970d1a41bf73a1e550c929adaba89 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:28:46 +0300 Subject: [PATCH 134/235] Add compiler Result type --- .../compiler core/compiler/Compiler.DRY.cs | 16 ++++++ ZSharp.Compiler/core/Result.cs | 55 +++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 ZSharp.Compiler/compiler core/compiler/Compiler.DRY.cs create mode 100644 ZSharp.Compiler/core/Result.cs diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.DRY.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.DRY.cs new file mode 100644 index 00000000..7c433dd2 --- /dev/null +++ b/ZSharp.Compiler/compiler core/compiler/Compiler.DRY.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Compiler +{ + public sealed partial class Compiler + { + public CompilerObjectResult Wrap(Func func) + { + try + { + return CompilerObjectResult.Ok(func(this)); + } catch (CompilerObjectException e) + { + return CompilerObjectResult.Error(e.Message); + } + } + } +} diff --git a/ZSharp.Compiler/core/Result.cs b/ZSharp.Compiler/core/Result.cs new file mode 100644 index 00000000..3ff39edf --- /dev/null +++ b/ZSharp.Compiler/core/Result.cs @@ -0,0 +1,55 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler +{ + public sealed class Result + where TResult : class + where TError : class + { + private readonly TResult? result; + private readonly TError? error; + + [MemberNotNullWhen(true, nameof(result))] + public bool IsOk => result is not null; + + [MemberNotNullWhen(true, nameof(error))] + public bool IsError => error is not null; + + private Result(TResult? result, TError? error) + { + this.result = result; + this.error = error; + } + + public static Result Ok(TResult result) + => new(result, null); + + public static Result Error(TError error) + => new(null, error); + + public bool Ok([NotNullWhen(true)] out TResult? result) + => (result = this.result) is not null; + + public bool Error([NotNullWhen(true)] out TError? error) + => (error = this.error) is not null; + + public TResult Unwrap() + => result ?? throw new InvalidOperationException(); + + public Result When(Action action) + { + if (IsOk) + action(result); + + return this; + } + + public Result Else(Action action) + { + if (IsError) + action(error); + + return this; + } + } +} From c3c3daa3abef1a654091e82b5985ab39a68a2967 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:28:54 +0300 Subject: [PATCH 135/235] Add type aliases --- ZSharp.Compiler.Objects/GlobalUsings.cs | 2 ++ ZSharp.Compiler/GlobalUsings.cs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/ZSharp.Compiler.Objects/GlobalUsings.cs b/ZSharp.Compiler.Objects/GlobalUsings.cs index c4ac3e75..21547183 100644 --- a/ZSharp.Compiler.Objects/GlobalUsings.cs +++ b/ZSharp.Compiler.Objects/GlobalUsings.cs @@ -1,2 +1,4 @@ global using MemberName = string; global using MemberIndex = int; + +global using CompilerObjectResult = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler/GlobalUsings.cs b/ZSharp.Compiler/GlobalUsings.cs index 9fdd27c8..85fe8963 100644 --- a/ZSharp.Compiler/GlobalUsings.cs +++ b/ZSharp.Compiler/GlobalUsings.cs @@ -8,3 +8,5 @@ global using IRInstructions = CommonZ.Utils.Collection; global using CompilerObject = ZSharp.Objects.CompilerObject; + +global using CompilerObjectResult = ZSharp.Compiler.Result; From 077fe5a51d8e4a2b087f44165802138f4f725603 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:29:13 +0300 Subject: [PATCH 136/235] Add implicit cast protocol for assignments --- .../core/type system/TypeSystem.cs | 37 +++++++++++++++++++ .../core/concepts/value/IImplicitCast.cs | 12 ++++++ 2 files changed, 49 insertions(+) create mode 100644 ZSharp.Compiler/core/concepts/value/IImplicitCast.cs diff --git a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs index 4726b582..de4ae01a 100644 --- a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs +++ b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs @@ -48,6 +48,43 @@ public CompilerObject Pointer(CompilerObject type) public CompilerObject Reference(CompilerObject type) => throw new NotImplementedException(); + public bool AreEqual(CompilerObject left, CompilerObject right) + { + if (ReferenceEquals(left, right)) + return true; + + if (Equals(left, right)) + return true; + + // TODO: this function should do more stuff + + return false; + } + + public CompilerObjectResult ImplicitCast(CompilerObject value, CompilerObject type) + { + CompilerObjectResult result = CompilerObjectResult.Error( + $"ImplicitCast for value:{value}, type:{type} is not supported." + ); + + if (type is IImplicitCastFromValue castFromValue) + result = Compiler.Wrap(c => castFromValue.ImplicitCastFromValue(c, value)); + + if (result.IsOk) + return result; + + if (value is IImplicitCastToType castToType) + result = Compiler.Wrap(c => castToType.ImplicitCastToType(c, type)); + + if (result.IsOk) + return result; + + if (IsTyped(value, out var valueType) && AreEqual(valueType, type)) + result = CompilerObjectResult.Ok(value); + + return result; + } + public bool IsTyped(CompilerObject @object) => @object is IDynamicallyTyped; diff --git a/ZSharp.Compiler/core/concepts/value/IImplicitCast.cs b/ZSharp.Compiler/core/concepts/value/IImplicitCast.cs new file mode 100644 index 00000000..c8503766 --- /dev/null +++ b/ZSharp.Compiler/core/concepts/value/IImplicitCast.cs @@ -0,0 +1,12 @@ +namespace ZSharp.Compiler +{ + public interface IImplicitCastFromValue + { + public CompilerObject ImplicitCastFromValue(Compiler compiler, CompilerObject value); + } + + public interface IImplicitCastToType + { + public CompilerObject ImplicitCastToType(Compiler compiler, CompilerObject type); + } +} From 888037ad9c1fbf227416fe2f38420b82ae90a54b Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:29:38 +0300 Subject: [PATCH 137/235] Implement interface reference IR --- ZSharp.IR/ir/oop/{ => class}/Class.cs | 0 .../types => ir/oop/class}/ClassReference.cs | 0 .../oop/class}/ConstructedClass.cs | 0 .../ir/oop/interface/ConstructedInterface.cs | 16 ++++++ ZSharp.IR/ir/oop/interface/Interface.cs | 50 +++++++++++++++++-- .../oop/interface/InterfaceImplementation.cs | 6 +-- .../ir/oop/interface/InterfaceReference.cs | 10 ++++ 7 files changed, 74 insertions(+), 8 deletions(-) rename ZSharp.IR/ir/oop/{ => class}/Class.cs (100%) rename ZSharp.IR/{type system/types => ir/oop/class}/ClassReference.cs (100%) rename ZSharp.IR/{type system/types => ir/oop/class}/ConstructedClass.cs (100%) create mode 100644 ZSharp.IR/ir/oop/interface/ConstructedInterface.cs create mode 100644 ZSharp.IR/ir/oop/interface/InterfaceReference.cs diff --git a/ZSharp.IR/ir/oop/Class.cs b/ZSharp.IR/ir/oop/class/Class.cs similarity index 100% rename from ZSharp.IR/ir/oop/Class.cs rename to ZSharp.IR/ir/oop/class/Class.cs diff --git a/ZSharp.IR/type system/types/ClassReference.cs b/ZSharp.IR/ir/oop/class/ClassReference.cs similarity index 100% rename from ZSharp.IR/type system/types/ClassReference.cs rename to ZSharp.IR/ir/oop/class/ClassReference.cs diff --git a/ZSharp.IR/type system/types/ConstructedClass.cs b/ZSharp.IR/ir/oop/class/ConstructedClass.cs similarity index 100% rename from ZSharp.IR/type system/types/ConstructedClass.cs rename to ZSharp.IR/ir/oop/class/ConstructedClass.cs diff --git a/ZSharp.IR/ir/oop/interface/ConstructedInterface.cs b/ZSharp.IR/ir/oop/interface/ConstructedInterface.cs new file mode 100644 index 00000000..2323076d --- /dev/null +++ b/ZSharp.IR/ir/oop/interface/ConstructedInterface.cs @@ -0,0 +1,16 @@ +using CommonZ.Utils; + +namespace ZSharp.IR +{ + public sealed class ConstructedInterface(Interface @interface) + : ConstructedType + { + public Interface Interface { get; set; } = @interface; + + Interface OOPTypeReference.Definition => Interface; + + public OOPTypeReference? OwningType { get; set; } + + public Collection Arguments { get; set; } = @interface.HasGenericParameters ? [] : Collection.Empty; + } +} diff --git a/ZSharp.IR/ir/oop/interface/Interface.cs b/ZSharp.IR/ir/oop/interface/Interface.cs index 13aff672..7939af3a 100644 --- a/ZSharp.IR/ir/oop/interface/Interface.cs +++ b/ZSharp.IR/ir/oop/interface/Interface.cs @@ -2,17 +2,57 @@ namespace ZSharp.IR { - public sealed class Interface : OOPType + public sealed class Interface(string? name) : OOPType { - public string? Name { get; set; } + private Collection? _genericParameters; + private Collection>? _bases; + private Collection? _methods; + + public string? Name { get; set; } = name; public InterfaceAttributes Attributes { get; set; } = InterfaceAttributes.None; - public Collection> Bases { get; set; } + public Collection GenericParameters + { + get + { + if (_genericParameters is not null) + return _genericParameters; + + Interlocked.CompareExchange(ref _genericParameters, [], null); + return _genericParameters; + } + } + + public bool HasGenericParameters => !_genericParameters.IsNullOrEmpty(); + + public Collection> Bases + { + get + { + if (_bases is not null) + return _bases; + + Interlocked.CompareExchange(ref _bases, [], null); + return _bases; + } + } + + public bool HasBases => !_bases.IsNullOrEmpty(); + + public Collection Methods + { + get + { + if (_methods is not null) + return _methods; - public Collection Methods { get; } + Interlocked.CompareExchange(ref _methods, [], null); + return _methods; + } + } - public Collection Properties { get; } + public bool HasMethods => !_methods.IsNullOrEmpty(); //public Collection Events { get; } diff --git a/ZSharp.IR/ir/oop/interface/InterfaceImplementation.cs b/ZSharp.IR/ir/oop/interface/InterfaceImplementation.cs index 2a78f3d2..00777ec7 100644 --- a/ZSharp.IR/ir/oop/interface/InterfaceImplementation.cs +++ b/ZSharp.IR/ir/oop/interface/InterfaceImplementation.cs @@ -2,13 +2,13 @@ namespace ZSharp.IR { - public sealed class InterfaceImplementation(Interface @interface) + public sealed class InterfaceImplementation(OOPTypeReference @interface) { - public Interface Interface { get; set; } = @interface; + public OOPTypeReference Interface { get; set; } = @interface; /// /// Mapping from interface method to implementation method. /// - public Mapping Implementations { get; } = []; + public Mapping Implementations { get; } = []; } } diff --git a/ZSharp.IR/ir/oop/interface/InterfaceReference.cs b/ZSharp.IR/ir/oop/interface/InterfaceReference.cs new file mode 100644 index 00000000..ad250466 --- /dev/null +++ b/ZSharp.IR/ir/oop/interface/InterfaceReference.cs @@ -0,0 +1,10 @@ +namespace ZSharp.IR +{ + public sealed class InterfaceReference(Interface @interface) + : OOPTypeReference + { + public Interface Definition { get; } = @interface; + + public OOPTypeReference? OwningType { get; set; } + } +} From edf2517d68911d1ce2f3a43ea3bb92cca8dcc84f Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:29:56 +0300 Subject: [PATCH 138/235] Add support for IR <-> IL interfaces --- .../il2ir/loaders/ClassLoader.cs | 35 ++-- .../il2ir/loaders/InterfaceLoader.cs | 172 ++++++++++++++++++ .../il2ir/loaders/ModuleLoader.cs | 4 +- ZSharp.Runtime.IL/ir2il/Constants.cs | 2 + .../ir2il/loader new/InterfaceLoader.cs | 153 ++++++++++++++++ .../ir2il/loader new/ModuleLoader.cs | 12 +- 6 files changed, 351 insertions(+), 27 deletions(-) create mode 100644 ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs create mode 100644 ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs index 07e87c3f..cbe1bb39 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs @@ -5,18 +5,18 @@ namespace ZSharp.Runtime.NET.IL2IR { internal sealed class ClassLoader(ILLoader loader, Type input) - : BaseILLoader(loader, input, new(input.Name)) + : BaseILLoader(loader, input, new(input.Name)) { - private IR.OOPTypeReference Self { get; set; } + private OOPTypeReference Self { get; set; } - public override IR.Class Load() + public override Class Load() { - if (Context.Cache(Input, out var result)) + if (Context.Cache(Input, out var result)) return result; Context.Cache(Input, Output); - Self = new IR.ClassReference(Output); + Self = new ClassReference(Output); LoadGenericParameters(); @@ -52,12 +52,12 @@ private void LoadGenericParameters() foreach (var parameter in Input.GetGenericArguments()) { - var genericParameter = new IR.GenericParameter(parameter.Name); + var genericParameter = new GenericParameter(parameter.Name); Context.Cache(parameter, genericParameter); Output.GenericParameters.Add(genericParameter); } - Self = new IR.ConstructedClass(Output) + Self = new ConstructedClass(Output) { Arguments = [.. Output.GenericParameters] }; @@ -123,7 +123,7 @@ private void LoadInterfaceImplementation(Type @interface, IL.InterfaceMapping ma private void LoadField(IL.FieldInfo field) { - var result = new IR.Field(field.Name, Loader.LoadType(field.FieldType)) + var result = new Field(field.Name, Loader.LoadType(field.FieldType)) { IsStatic = field.IsStatic, IsReadOnly = field.IsInitOnly, @@ -134,7 +134,7 @@ private void LoadField(IL.FieldInfo field) private void LoadProperty(IL.PropertyInfo property) { - var result = new IR.Property(property.Name, Loader.LoadType(property.PropertyType)) + var result = new Property(property.Name, Loader.LoadType(property.PropertyType)) { Getter = property.GetMethod is null ? null : LoadMethod(property.GetMethod), Setter = property.SetMethod is null ? null : LoadMethod(property.SetMethod), @@ -145,7 +145,7 @@ private void LoadProperty(IL.PropertyInfo property) private void LoadConstructor(IL.ConstructorInfo constructor) { - var result = new IR.Constructor(null) + var result = new Constructor(null) { Method = new(Loader.RuntimeModule.TypeSystem.Void), }; @@ -161,9 +161,9 @@ private void LoadConstructor(IL.ConstructorInfo constructor) Output.Constructors.Add(result); } - private IR.Method LoadMethod(IL.MethodInfo method) + private Method LoadMethod(IL.MethodInfo method) { - var result = new IR.Method(Loader.LoadType(method.ReturnType)) + var result = new Method(Loader.LoadType(method.ReturnType)) { Name = method.GetCustomAttribute()?.Name ?? method.Name, }; @@ -196,16 +196,13 @@ private void LoadTypeDefinition(Type type) Output.NestedTypes.Add(result); } - private IR.Class LoadClass(Type type) + private Class LoadClass(Type type) => new ClassLoader(Loader, type).Load(); - private IR.Interface LoadInterface(Type type) - { - return new(); - throw new NotImplementedException(); - } + private Interface LoadInterface(Type type) + => new InterfaceLoader(Loader, type).Load(); - private IR.Enumclass LoadEnum(Type type) + private Enumclass LoadEnum(Type type) { return new(); throw new NotImplementedException(); diff --git a/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs new file mode 100644 index 00000000..3c595530 --- /dev/null +++ b/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs @@ -0,0 +1,172 @@ +using System.Reflection; +using ZSharp.IR; + +namespace ZSharp.Runtime.NET.IL2IR +{ + internal sealed class InterfaceLoader(ILLoader loader, Type input) + : BaseILLoader(loader, input, new(input.Name)) + { + private OOPTypeReference Self { get; set; } + + public override Interface Load() + { + if (Context.Cache(Input, out var result)) + return result; + + Context.Cache(Input, Output); + + Self = new InterfaceReference(Output); + + LoadGenericParameters(); + + LoadBase(); + + LoadInterfaceImplementations(); + + LoadProperties(); + + LoadMethods(); + + LoadTypes(); + + return Output; + } + + private void LoadBase() + { + foreach (var @interface in Input.GetInterfaces()) + Output.Bases.Add(Loader.LoadType>(@interface)); + } + + private void LoadGenericParameters() + { + if (!Input.IsGenericTypeDefinition) + return; + + Output.Name = Input.Name.Split('`')[0]; + + foreach (var parameter in Input.GetGenericArguments()) + { + var genericParameter = new IR.GenericParameter(parameter.Name); + Context.Cache(parameter, genericParameter); + Output.GenericParameters.Add(genericParameter); + } + + Self = new ConstructedInterface(Output) + { + Arguments = [.. Output.GenericParameters] + }; + } + + private void LoadInterfaceImplementations() + { + foreach (var @interface in Input.GetInterfaces()) + LoadInterfaceImplementation(@interface, Input.GetInterfaceMap(@interface)); + } + + private void LoadProperties() + { + foreach (var property in Input.GetProperties()) + LoadProperty(property); + } + + private void LoadMethods() + { + foreach (var method in Input.GetMethods()) + if (method.DeclaringType == Input) + LoadMethod(method); + } + + private void LoadTypes() + { + foreach (var nested in Input.GetNestedTypes()) + LoadTypeDefinition(nested); + } + + private void LoadInterfaceImplementation(Type @interface, IL.InterfaceMapping mapping) + { + if (mapping.InterfaceMethods.Length != mapping.TargetMethods.Length) + throw new InvalidOperationException("Interface mapping is invalid."); + + //throw new NotImplementedException(); + + //var implementation = new IR.InterfaceImplementation(Loader.LoadType(@interface)); + + //for (int i = 0; i < mapping.InterfaceMethods.Length; i++) + //{ + // var interfaceMethod = mapping.InterfaceMethods[i]; + // var targetMethod = mapping.TargetMethods[i]; + + // implementation.Implementations.Add( + // LoadMethod(interfaceMethod), + // LoadMethod(targetMethod) + // ); + //} + } + + private void LoadProperty(PropertyInfo property) + { + var result = new Property(property.Name, Loader.LoadType(property.PropertyType)) + { + Getter = property.GetMethod is null ? null : LoadMethod(property.GetMethod), + Setter = property.SetMethod is null ? null : LoadMethod(property.SetMethod), + }; + + // TODO: add property metadata + } + + private Method LoadMethod(MethodInfo method) + { + var result = new Method(Loader.LoadType(method.ReturnType)) + { + Name = method.GetCustomAttribute()?.Name ?? method.Name, + }; + + Context.Cache(method, result); + + if (!method.IsStatic) + result.Signature.Args.Parameters.Add(new("this", Self)); + + foreach (var parameter in method.GetParameters()) + result.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); + + Output.Methods.Add(result); + + return result; + } + + private void LoadTypeDefinition(Type type) + { + if (!type.IsTypeDefinition) + throw new ArgumentException("Type must be a type definition.", nameof(type)); + + if (Context.Cache(type, out OOPType? result)) ; + else if (type.IsClass) result = LoadClass(type); + else if (type.IsInterface) result = LoadInterface(type); + else if (type.IsEnum) result = LoadEnum(type); + else if (type.IsValueType) result = LoadStruct(type); + else throw new NotImplementedException(); + + // TODO: add nested types + //Output.NestedTypes.Add(result); + } + + private Class LoadClass(Type type) + => new ClassLoader(Loader, type).Load(); + + private Interface LoadInterface(Type type) + => new InterfaceLoader(Loader, type).Load(); + + private Enumclass LoadEnum(Type type) + { + return new(); + throw new NotImplementedException(); + } + + private IR.ValueType LoadStruct(Type type) + { + return new(); + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs index d9462640..1432ceee 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs @@ -100,9 +100,7 @@ private void LoadClass(Type type) => Output.Types.Add(new ClassLoader(Loader, type).Load()); private void LoadInterface(Type type) - { - throw new NotImplementedException(); - } + => Output.Types.Add(new InterfaceLoader(Loader, type).Load()); private void LoadEnum(Type type) { diff --git a/ZSharp.Runtime.IL/ir2il/Constants.cs b/ZSharp.Runtime.IL/ir2il/Constants.cs index f2e46cee..45e865f9 100644 --- a/ZSharp.Runtime.IL/ir2il/Constants.cs +++ b/ZSharp.Runtime.IL/ir2il/Constants.cs @@ -6,6 +6,8 @@ internal static class Constants public const string AnonymousClass = ""; + public const string AnonymousInterface = ""; + public const string AnonymousMethod = ""; public const string AnonymousModule = ""; diff --git a/ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs new file mode 100644 index 00000000..35fdc9d6 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs @@ -0,0 +1,153 @@ +namespace ZSharp.Runtime.NET.IR2IL +{ + internal sealed class InterfaceLoader(RootModuleLoader loader, IR.Interface @in, IL.Emit.TypeBuilder @out) + : ModuleContentLoader(loader, @in, @out) + { + public InterfaceLoader(RootModuleLoader loader, IL.Emit.ModuleBuilder module, IR.Interface @in) + : this(loader, @in, CreateDefinition(module, @in)) { } + + public InterfaceLoader(RootModuleLoader loader, IL.Emit.TypeBuilder type, IR.Interface @in) + : this(loader, @in, CreateDefinition(type, @in)) { } + + protected override void DoLoad() + { + Context.Cache(Input, Output); + + LoadNestedTypes(); + + ModuleLoader.AddToNextPass(LoadDefinition); + + if (Input.HasMethods) + ModuleLoader.AddToNextPass(LoadMethods); + + ModuleLoader.AddToCleanUp(() => Output.CreateType()); + } + + private void LoadDefinition() + { + if (Input.HasBases) + foreach (var @base in Input.Bases) + Output.AddInterfaceImplementation(Loader.LoadType(@base)); + + if (Input.HasGenericParameters) + LoadGenericParameters(); + } + + private void LoadGenericParameters() + { + var genericParameters = Output.DefineGenericParameters( + Input.GenericParameters.Select(gp => gp.Name).ToArray() + ); + + foreach (var (ir, il) in Input.GenericParameters.Zip(genericParameters)) + Context.Cache(ir, il); + + ModuleLoader.AddToCleanUp(() => + { + foreach (var ir in Input.GenericParameters) + { + //Context.Uncache(ir); + } + }); + } + + private void LoadNestedTypes() + { + + } + + private void LoadMethods() + { + foreach (var method in Input.Methods) + LoadMethod(method); + } + + private void LoadConstructor(IR.Constructor constructor) + { + var irParams = constructor.Method.Signature.GetParameters(); + + var parameters = irParams.Select(p => new Parameter() + { + Name = p.Name, + Type = Loader.LoadType(p.Type), + Position = p.Index + }); + + var result = Output.DefineConstructor(IL.MethodAttributes.Public, IL.CallingConventions.HasThis, [.. irParams.Skip(1).Select(p => Loader.LoadType(p.Type))]); + + Context.Cache(constructor.Method, result); + + var ilGen = result.GetILGenerator(); + var codeLoader = new CodeLoader(ModuleLoader, constructor.Method, ilGen); + + foreach (var (ir, parameter) in irParams.Zip(parameters)) + codeLoader.Args[ir] = parameter; + + foreach (var local in constructor.Method.Body.Locals) + codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); + + ModuleLoader.AddToNextPass(() => codeLoader.Load()); + } + + private void LoadField(IR.Field field) + { + var attributes = IL.FieldAttributes.Public; + + if (field.IsStatic) + attributes |= IL.FieldAttributes.Static; + + var il = Output.DefineField(field.Name, Loader.LoadType(field.Type), attributes); + + Context.Cache(field, il); + } + + private void LoadMethod(IR.Method method) + { + var irParams = method.Signature.GetParameters(); + + var parameters = irParams.Select(p => new Parameter() + { + Name = p.Name, + Type = Loader.LoadType(p.Type), + Position = p.Index, + }); + + var attributes = IL.MethodAttributes.Public; + + if (method.IsStatic) + attributes |= IL.MethodAttributes.Static; + + var result = Output.DefineMethod( + method.Name ?? Constants.AnonymousMethod, + attributes, + Loader.LoadType(method.ReturnType), + [.. (method.IsInstance || method.IsVirtual ? parameters.Skip(1) : parameters).Select(p => p.Type)] + ); + + Context.Cache(method, result); + + var ilGen = result.GetILGenerator(); + var codeLoader = new CodeLoader(ModuleLoader, method, ilGen); + + foreach (var (ir, parameter) in irParams.Zip(parameters)) + codeLoader.Args[ir] = parameter; + + foreach (var local in method.Body.Locals) + codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); + + ModuleLoader.AddToNextPass(() => codeLoader.Load()); + } + + private static IL.Emit.TypeBuilder CreateDefinition(IL.Emit.ModuleBuilder module, IR.Interface @in) + => module.DefineType( + @in.Name ?? Constants.AnonymousInterface, + IL.TypeAttributes.Interface + ); + + private static IL.Emit.TypeBuilder CreateDefinition(IL.Emit.TypeBuilder type, IR.Interface @in) + => type.DefineNestedType( + @in.Name ?? Constants.AnonymousInterface, + IL.TypeAttributes.Interface + ); + } +} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs index 59a29747..4270774f 100644 --- a/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs @@ -1,4 +1,6 @@ -namespace ZSharp.Runtime.NET.IR2IL +using System; + +namespace ZSharp.Runtime.NET.IR2IL { internal sealed class ModuleLoader( RootModuleLoader loader, @@ -46,10 +48,10 @@ private void LoadTypes() foreach (var type in Input.Types) (type switch { - IR.Class @class => new ClassLoader(ModuleLoader, Output, @class), - //IR.Interface @interface => new InterfaceLoader(loader, Output, @interface), - _ => throw new NotImplementedException() - }).Load(); + IR.Class @class => new ClassLoader(ModuleLoader, Output, @class).Load, + IR.Interface @interface => new InterfaceLoader(loader, Output, @interface).Load, + _ => (Func)null! ?? throw new NotImplementedException() + })(); } private void LoadFunctions(IL.Emit.TypeBuilder globals) From adcc6aa37a78a066e306feda76048d85afeca924 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:30:09 +0300 Subject: [PATCH 139/235] Add support for loading interfaces into CO --- .../ir loader/IRLoader.Impl.cs | 62 ++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index f1f5d369..378f3c82 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -98,7 +98,7 @@ private Action Load(IR.OOPType type, Module owner) => type switch { IR.Class @class => Load(@class, owner), - //IR.Interface @interface => Load(@interface), + IR.Interface @interface => Load(@interface, owner), //IR.Struct @struct => Load(@struct), _ => throw new NotImplementedException(), }; @@ -194,6 +194,66 @@ private Action Load(IR.Class @class, Module owner) }; } + private Action Load(IR.Interface @interface, Module owner) + { + Interface result = new(@interface.Name) + { + Name = @interface.Name ?? string.Empty, + IR = @interface, + IsDefined = true, + }; + + Context.Objects.Cache(@interface, result); + + owner.Content.Add(result); + + if (result.Name is not null && result.Name != string.Empty) + owner.Members.Add(result.Name, result); + + //if (@interface.HasGenericParameters) + // foreach (var parameter in @interface.GenericParameters) + // { + // var genericParameter = new GenericParameter() + // { + // Name = parameter.Name, + // IR = parameter, + // }; + + // Context.Types.Cache(parameter, genericParameter); + + // result.GenericParameters.Add(genericParameter); + // } + + if (@interface.HasBases) + foreach (var @base in @interface.Bases) + result.Bases.Add(Load(@base)); + + return () => + { + if (@interface.HasMethods) + foreach (var method in @interface.Methods) + { + Method resultMethod = new(method.Name) + { + IR = method, + Defined = true, + }; + if (resultMethod.Name is not null && resultMethod.Name != string.Empty) + { + if (!result.Members.TryGetValue(resultMethod.Name, out var group)) + result.Members.Add(resultMethod.Name, group = new OverloadGroup(resultMethod.Name)); + + if (group is not OverloadGroup overloadGroup) + throw new InvalidOperationException(); + + overloadGroup.Overloads.Add(resultMethod); + } + resultMethod.Signature = Load(method.Signature); + resultMethod.ReturnType = Load(method.ReturnType); + } + }; + } + private CompilerObject Load(IR.IType type) { if (Context.Types.Cache(type, out var result)) From e482562ffa27c4019f14be835afa7e36c43b573f Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:30:41 +0300 Subject: [PATCH 140/235] Use implicit cast instead of cast --- .../builtin-compilers/class body/MethodCompiler.cs | 4 ++-- .../builtin-compilers/module/FunctionCompiler.cs | 4 ++-- .../builtin-compilers/module/ModuleCompiler.cs | 4 ++-- .../runtime code/loops/while/WhileExpressionCompiler.cs | 7 +++++-- .../builtin-compilers/runtime code/objects/If.cs | 2 +- .../builtin-compilers/runtime code/objects/WhileLoop.cs | 2 +- 6 files changed, 13 insertions(+), 10 deletions(-) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs index 5bc8057c..9bf96995 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs @@ -130,7 +130,7 @@ private CompilerObject CompileNode(LetExpression let) local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); - var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.Cast(local.Initializer, local.Type!)); + var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.TypeSystem.ImplicitCast(local.Initializer, local.Type!).Unwrap()); code.Instructions.Add(new IR.VM.Dup()); code.Instructions.Add(new IR.VM.SetLocal(local.IR)); @@ -163,7 +163,7 @@ private CompilerObject CompileNode(VarExpression var) if (local.Initializer is not null) { - var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.Cast(local.Initializer, local.Type!)); + var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.TypeSystem.ImplicitCast(local.Initializer, local.Type !).Unwrap()); code.Instructions.Add(new IR.VM.Dup()); code.Instructions.Add(new IR.VM.SetLocal(local.IR)); diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs index a9fc1b02..591644f7 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs @@ -125,7 +125,7 @@ private CompilerObject CompileNode(LetExpression let) local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); - var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.Cast(local.Initializer, local.Type!)); + var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.TypeSystem.ImplicitCast(local.Initializer, local.Type !).Unwrap()); code.Instructions.Add(new IR.VM.Dup()); code.Instructions.Add(new IR.VM.SetLocal(local.IR)); @@ -158,7 +158,7 @@ private CompilerObject CompileNode(VarExpression var) if (local.Initializer is not null) { - var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.Cast(local.Initializer, local.Type!)); + var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.TypeSystem.ImplicitCast(local.Initializer, local.Type !).Unwrap()); code.Instructions.Add(new IR.VM.Dup()); code.Instructions.Add(new IR.VM.SetLocal(local.IR)); diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs index 3179d54f..5261fcaf 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs @@ -96,7 +96,7 @@ private Action Compile(LetExpression let) global.IR = Compiler.Compiler.CompileIRObject(global, null); if (global.Initializer is not null) - global.Initializer = Compiler.Compiler.Cast(global.Initializer, global.Type); + global.Initializer = Compiler.Compiler.TypeSystem.ImplicitCast(global.Initializer, global.Type).Unwrap(); }; } @@ -161,7 +161,7 @@ private Action Compile(VarExpression var) global.IR = Compiler.Compiler.CompileIRObject(global, null); if (global.Initializer is not null) - global.Initializer = Compiler.Compiler.Cast(global.Initializer, global.Type); + global.Initializer = Compiler.Compiler.TypeSystem.ImplicitCast(global.Initializer, global.Type).Unwrap(); }; } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs index 9aa44142..99242bb4 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs @@ -20,7 +20,10 @@ protected override CompilerObject CompileBreak(BreakStatement @break) Object.Type ??= type; - var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.Cast(value, type)); + if (!Compiler.Compiler.TypeSystem.ImplicitCast(value, Object.Type).Ok(out var breakValue)) + throw new Compiler.InvalidCastException(value, Object.Type); + + var code = Compiler.Compiler.CompileIRCode(breakValue); return new Objects.RawCode( new([ @@ -39,7 +42,7 @@ protected override CompilerObject CompileElse() return new Objects.RawCode(new([new IR.VM.Jump(Object.EndLabel)])); } - return Compiler.Compiler.Cast(Compiler.CompileNode(Node.Else!), Object.Type); + return Compiler.Compiler.TypeSystem.ImplicitCast(Compiler.CompileNode(Node.Else!), Object.Type).Unwrap(); } } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/If.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/If.cs index 6183cfdc..1bfcd95c 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/If.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/If.cs @@ -18,7 +18,7 @@ public sealed class If public IRCode CompileIRCode(Compiler.Compiler compiler) => new([ - .. compiler.CompileIRCode(compiler.Cast(Condition, compiler.TypeSystem.Boolean)).Instructions, + .. compiler.CompileIRCode(compiler.TypeSystem.ImplicitCast(Condition, compiler.TypeSystem.Boolean).Unwrap()).Instructions, new IR.VM.JumpIfFalse(ElseLabel), diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs index 7b73e639..9b3329d8 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs @@ -26,7 +26,7 @@ public IRCode CompileIRCode(Compiler.Compiler compiler) return new([ ConditionLabel, .. compiler.CompileIRCode( - compiler.Cast(Condition, compiler.TypeSystem.Boolean) + compiler.TypeSystem.ImplicitCast(Condition, compiler.TypeSystem.Boolean).Unwrap() ).Instructions, new IR.VM.JumpIfFalse(ElseLabel), From a7078d674a72b77766c0a59214c0db67f602f6ff Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:31:02 +0300 Subject: [PATCH 141/235] Fix class compiler to create class instead of generic class --- .../builtin-compilers/class body/ClassBodyCompiler.cs | 8 ++++---- .../builtin-compilers/module/ClassCompiler.cs | 8 +++----- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs index 1d82dbd6..b81f36a1 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs @@ -2,7 +2,7 @@ namespace ZSharp.ZSSourceCompiler { - public sealed class ClassBodyCompiler(ZSSourceCompiler compiler, OOPDefinition oop, GenericClass @class) + public sealed class ClassBodyCompiler(ZSSourceCompiler compiler, OOPDefinition oop, Objects.Class @class) : CompilerBase(compiler) , IMultipassCompiler { @@ -10,7 +10,7 @@ public sealed class ClassBodyCompiler(ZSSourceCompiler compiler, OOPDefinition o public OOPDefinition Node { get; } = oop; - public GenericClass Class { get; } = @class; + public Objects.Class Class { get; } = @class; public void AddToNextPass(Action action) => nextPass.Add(action); @@ -128,7 +128,7 @@ private Action Compile(LetExpression let) field.IR = Compiler.Compiler.CompileIRObject(field, null); if (field.Initializer is not null) - field.Initializer = Compiler.Compiler.Cast(field.Initializer, field.Type); + field.Initializer = Compiler.Compiler.TypeSystem.ImplicitCast(field.Initializer, field.Type).Unwrap(); }; } @@ -160,7 +160,7 @@ private Action Compile(VarExpression var) field.IR = Compiler.Compiler.CompileIRObject(field, null); if (field.Initializer is not null) - field.Initializer = Compiler.Compiler.Cast(field.Initializer, field.Type); + field.Initializer = Compiler.Compiler.TypeSystem.ImplicitCast(field.Initializer, field.Type).Unwrap(); }; } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs index 3ac9b96b..e2b65746 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs @@ -1,6 +1,4 @@ -using System.Linq; -using ZSharp.IR; -using ZSharp.Objects; +using ZSharp.Objects; namespace ZSharp.ZSSourceCompiler { @@ -9,14 +7,14 @@ public sealed class ClassCompiler( OOPDefinition node, ClassMetaClass metaClass ) - : ContextCompiler( + : ContextCompiler( compiler, node, new() { Name = node.Name } ) { - public override GenericClass Compile() + public override Class Compile() { if (Node.Bases is not null) { From 196e90f4bfa6194d937014ac4647ecd8e7cbe031 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 23 Apr 2025 23:31:16 +0300 Subject: [PATCH 142/235] Update test case (simple.zs) --- ZLoad.Test/TestInterface.cs | 6 ++++++ ZSharpTest/tests/simple.zs | 8 +++++++- 2 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 ZLoad.Test/TestInterface.cs diff --git a/ZLoad.Test/TestInterface.cs b/ZLoad.Test/TestInterface.cs new file mode 100644 index 00000000..a7173f8c --- /dev/null +++ b/ZLoad.Test/TestInterface.cs @@ -0,0 +1,6 @@ +namespace ZLoad.Test +{ + public interface TestInterface + { + } +} diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs index af0d4b0c..f8979338 100644 --- a/ZSharpTest/tests/simple.zs +++ b/ZSharpTest/tests/simple.zs @@ -1,11 +1,17 @@ import { input, print } from "std:io"; -import { Console, List, greet, id } from "net:ZLoad.Test.dll"; +import { Console, List, TestInterface, greet, id } from "net:ZLoad.Test.dll"; // import { Console } from "net:C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\8.0.13\\System.Console.dll"; module Program; +class MyClass : TestInterface { + new(this) {} +} + fun main(): void { let x = List[string](); + + let v = MyClass(); print(greet(let name = input("Please enter your name: "))); From 6aad731b3cb02f2fe234d0545dc9f546898ab7ba Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 25 Apr 2025 12:17:47 +0300 Subject: [PATCH 143/235] Fix referencing system --- ZSharp.Compiler.Features/referencing/IReferencable.cs | 2 +- ZSharp.Compiler.Features/referencing/Referencing.cs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/ZSharp.Compiler.Features/referencing/IReferencable.cs b/ZSharp.Compiler.Features/referencing/IReferencable.cs index 0fe6d759..02b74e29 100644 --- a/ZSharp.Compiler.Features/referencing/IReferencable.cs +++ b/ZSharp.Compiler.Features/referencing/IReferencable.cs @@ -5,7 +5,7 @@ public interface IReferencable : CompilerObject public CompilerObject CreateReference(Compiler.Referencing @ref, ReferenceContext context); } - public interface IReferencable : IReferencable + public interface IReferencable : IReferencable where T : CompilerObject { CompilerObject IReferencable.CreateReference(Compiler.Referencing @ref, ReferenceContext context) diff --git a/ZSharp.Compiler.Features/referencing/Referencing.cs b/ZSharp.Compiler.Features/referencing/Referencing.cs index eb11f6b1..4dbb4217 100644 --- a/ZSharp.Compiler.Features/referencing/Referencing.cs +++ b/ZSharp.Compiler.Features/referencing/Referencing.cs @@ -19,6 +19,9 @@ public T CreateReference(CompilerObject @object, ReferenceContext context) if (@object is IReferencable referencable) return referencable.CreateReference(this, context); + if (@object is T result) + return result; + throw new NotImplementedException(); } } From e4b892b871f5ff266afd7e295878c88afc22945b Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 25 Apr 2025 12:18:17 +0300 Subject: [PATCH 144/235] Add constructor from Dictionary to Mapping --- CommonZ/collections/Mapping.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CommonZ/collections/Mapping.cs b/CommonZ/collections/Mapping.cs index 32c12345..15065108 100644 --- a/CommonZ/collections/Mapping.cs +++ b/CommonZ/collections/Mapping.cs @@ -3,6 +3,12 @@ public class Mapping : Dictionary where Key : notnull { + public Mapping() : base() { } + + public Mapping(IDictionary dictionary) : base(dictionary) { } + + public Mapping(IEnumerable> items) : base(items) { } + public virtual void OnAdd(Key key, Value value) { } public virtual void OnRemove(Key key) { } From 4fcea6822871210fc1a1030e82ede9a747552751 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 25 Apr 2025 12:21:13 +0300 Subject: [PATCH 145/235] Fix IR -> CO loader --- .../ir loader/IRLoader.Impl.cs | 47 ++++++++++++------- 1 file changed, 31 insertions(+), 16 deletions(-) diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index 378f3c82..f23d30df 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -238,6 +238,9 @@ private Action Load(IR.Interface @interface, Module owner) IR = method, Defined = true, }; + + result.Content.Add(resultMethod); + if (resultMethod.Name is not null && resultMethod.Name != string.Empty) { if (!result.Members.TryGetValue(resultMethod.Name, out var group)) @@ -254,29 +257,26 @@ private Action Load(IR.Interface @interface, Module owner) }; } - private CompilerObject Load(IR.IType type) + private IType Load(IR.IType type) { if (Context.Types.Cache(type, out var result)) return result; - if (type is IR.ConstructedClass constructed) - return Load(constructed); - - return null!; - //throw new NotImplementedException(); + return type switch + { + IR.ConstructedClass constructedClass => Load(constructedClass), + IR.InterfaceReference interfaceReference => Load(interfaceReference), + _ => null! + }; } - private CompilerObject Load(IR.ConstructedClass constructed) + private IType Load(IR.ConstructedClass constructed) { - var origin = - Context.Objects.Cache(constructed.Class) ?? - Context.Types.Cache(constructed) - ?? throw new(); - - var args = new CommonZ.Utils.Cache(); - if (origin is GenericClass genericClass) + if (Context.Objects.Cache(constructed.Class, out var genericClass)) { + var args = new CommonZ.Utils.Cache(); + if (genericClass.GenericParameters.Count != constructed.Arguments.Count) throw new(); @@ -293,9 +293,12 @@ private CompilerObject Load(IR.ConstructedClass constructed) }; } - return origin; + return Context.Types.Cache(constructed) ?? throw new(); } + private IType Load(IR.InterfaceReference interfaceReference) + => Context.Objects.Cache(interfaceReference.Definition) ?? throw new(); + private Action LoadGenericClass(IR.Class @class, Module owner) { GenericClass result = new() @@ -315,6 +318,15 @@ private Action LoadGenericClass(IR.Class @class, Module owner) if (@class.Base is not null) result.Base = Load(@class.Base); + var self = new GenericClassInstance(result) + { + Context = new() + { + Scope = result, + CompileTimeValues = new() + } + }; + if (@class.HasGenericParameters) foreach (var parameter in @class.GenericParameters) { @@ -325,12 +337,15 @@ private Action LoadGenericClass(IR.Class @class, Module owner) }; Context.Types.Cache(parameter, genericParameter); + self.Context[genericParameter] = genericParameter; result.GenericParameters.Add(genericParameter); } return () => { + + if (@class.HasFields) foreach (var field in @class.Fields) { @@ -353,7 +368,7 @@ private Action LoadGenericClass(IR.Class @class, Module owner) { Constructor resultConstructor = new(constructor.Name) { - Owner = result, + Owner = self, IR = constructor, }; if (resultConstructor.Name is not null && resultConstructor.Name != string.Empty) From 9f9c47f843e93502db9ea14d2737f153065f9519 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 25 Apr 2025 12:23:34 +0300 Subject: [PATCH 146/235] Add IType compiler protocol Add support for implementing interfaces Add type assignability check system --- ZLoad.Test/TestInterface.cs | 6 +- ZSharp.Compiler.IRLoader/Context.cs | 2 +- .../ir loader/IRLoader.cs | 2 +- .../functional/RTFunction.cs | 4 +- .../functional/body/Local.cs | 7 +- .../generic/GenericFunctionInstance.cs | 2 +- .../signature/KeywordVarParameter.cs | 2 +- .../functional/signature/Parameter.cs | 4 +- .../functional/signature/VarParameter.cs | 2 +- .../generic/GenericParameter.cs | 8 +- .../literals/ArrayLiteral.cs | 2 +- ZSharp.Compiler.Objects/modular/Global.cs | 2 +- ZSharp.Compiler.Objects/modular/Module.cs | 2 +- ZSharp.Compiler.Objects/oop/Implementation.cs | 4 +- .../oop/abstraction/IAbstraction.cs | 10 ++ ZSharp.Compiler.Objects/oop/class/Class.cs | 66 ++++++--- .../oop/class/GenericClassInstance.cs | 12 +- .../oop/constructor/Constructor.cs | 2 +- .../oop/constructor/ConstructorReference.cs | 2 +- .../oop/extensibility/IAbstraction.cs | 9 -- .../oop/extensibility/IClass.cs | 2 + .../extensibility/IImplementsSpecification.cs | 7 + .../oop/field/BoundField.cs | 2 +- ZSharp.Compiler.Objects/oop/field/Field.cs | 2 +- .../oop/interface/Interface.cs | 10 ++ ZSharp.Compiler.Objects/oop/method/Method.cs | 135 ++++++++++-------- .../oop/method/MethodReference.cs | 2 +- .../oop/method/MethodType.cs | 26 ++++ .../signature/ICallableType.cs | 68 +++++++++ .../cg objects/literals/FalseLiteral.cs | 4 +- .../cg objects/literals/Float32Literal.cs | 4 +- .../cg objects/literals/IntegerLiteral.cs | 4 +- .../cg objects/literals/Literal.cs | 2 +- .../cg objects/literals/NullLiteral.cs | 4 +- .../cg objects/literals/StringLiteral.cs | 4 +- .../cg objects/literals/TrueLiteral.cs | 4 +- ZSharp.Compiler/cg objects/raw/RawCode.cs | 4 +- ZSharp.Compiler/cg objects/raw/RawType.cs | 10 +- ZSharp.Compiler/cg objects/types/Int32Type.cs | 5 +- .../cg objects/types/StringType.cs | 5 +- .../cg objects/{ => types}/Type.cs | 4 +- .../compiler/features/Compiler.Protocols.cs | 4 +- .../compiler/literals/Compiler.Create.cs | 2 +- .../core/type system/IDynamicallyTyped.cs | 2 +- .../compiler core/core/type system/IType.cs | 9 ++ .../core/type system/ITypeAssignment.cs | 16 +++ .../compiler core/core/type system/ITyped.cs | 4 +- .../core/type system/TypeSystem.cs | 55 ++++--- ZSharp.Compiler/core/code/IRCode.cs | 6 +- .../core/concepts/value/IImplicitCast.cs | 2 +- .../core/concepts/value/IReadable.cs | 4 +- .../core/concepts/value/ITypeCast.cs | 4 +- .../il2ir/loaders/InterfaceLoader.cs | 1 + ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 4 +- .../ir2il/loader new/ClassLoader.cs | 22 +++ .../class body/ClassBodyCompiler.cs | 38 +++-- .../class body/MethodCompiler.cs | 8 +- .../builtin-compilers/module/ClassCompiler.cs | 98 ++++++++++++- .../module/FunctionCompiler.cs | 4 +- .../loops/while/WhileExpressionCompiler.cs | 2 +- .../loops/while/WhileLoopCompiler.cs | 2 +- .../runtime code/objects/WhileLoop.cs | 2 +- .../compiler/ZSSourceCompiler.cs | 2 +- 63 files changed, 541 insertions(+), 208 deletions(-) create mode 100644 ZSharp.Compiler.Objects/oop/abstraction/IAbstraction.cs delete mode 100644 ZSharp.Compiler.Objects/oop/extensibility/IAbstraction.cs create mode 100644 ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs create mode 100644 ZSharp.Compiler.Objects/oop/method/MethodType.cs create mode 100644 ZSharp.Compiler.Objects/signature/ICallableType.cs rename ZSharp.Compiler/cg objects/{ => types}/Type.cs (87%) create mode 100644 ZSharp.Compiler/compiler core/core/type system/IType.cs create mode 100644 ZSharp.Compiler/compiler core/core/type system/ITypeAssignment.cs diff --git a/ZLoad.Test/TestInterface.cs b/ZLoad.Test/TestInterface.cs index a7173f8c..dd15742f 100644 --- a/ZLoad.Test/TestInterface.cs +++ b/ZLoad.Test/TestInterface.cs @@ -1,6 +1,10 @@ -namespace ZLoad.Test +using ZSharp.Runtime.NET.IL2IR; + +namespace ZLoad.Test { public interface TestInterface { + [Alias(Name = "do")] + public void Do(); } } diff --git a/ZSharp.Compiler.IRLoader/Context.cs b/ZSharp.Compiler.IRLoader/Context.cs index a540eaa0..d92f3e89 100644 --- a/ZSharp.Compiler.IRLoader/Context.cs +++ b/ZSharp.Compiler.IRLoader/Context.cs @@ -6,6 +6,6 @@ public sealed class Context { public Cache Objects { get; } = []; - public Cache Types { get; } = []; + public Cache Types { get; } = []; } } diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs index c9440f2d..46b9396d 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs @@ -9,7 +9,7 @@ public IRLoader(Compiler compiler) : base(compiler) private void Initialize() { - foreach (var type in new CompilerObject[] { + foreach (var type in new IType[] { Compiler.TypeSystem.Type, Compiler.TypeSystem.Float32, Compiler.TypeSystem.String, diff --git a/ZSharp.Compiler.Objects/functional/RTFunction.cs b/ZSharp.Compiler.Objects/functional/RTFunction.cs index a7056b64..38f8f17b 100644 --- a/ZSharp.Compiler.Objects/functional/RTFunction.cs +++ b/ZSharp.Compiler.Objects/functional/RTFunction.cs @@ -37,11 +37,11 @@ public bool IsDefined public CompilerObject? Body { get; set; } - CompilerObject ITyped.Type => throw new NotImplementedException(); + IType ITyped.Type => throw new NotImplementedException(); public Signature Signature { get; set; } = new(); - public CompilerObject? ReturnType { get; set; } + public IType? ReturnType { get; set; } CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { diff --git a/ZSharp.Compiler.Objects/functional/body/Local.cs b/ZSharp.Compiler.Objects/functional/body/Local.cs index 035ea6f9..720e8bc9 100644 --- a/ZSharp.Compiler.Objects/functional/body/Local.cs +++ b/ZSharp.Compiler.Objects/functional/body/Local.cs @@ -1,5 +1,4 @@ using ZSharp.Compiler; -using ZSharp.IR; namespace ZSharp.Objects { @@ -7,7 +6,7 @@ public sealed class Local : CompilerObject , ICTAssignable , ICTReadable - , ICompileIRObject + , ICompileIRObject { [Flags] enum BuildState @@ -25,11 +24,11 @@ enum BuildState public bool IsReadOnly { get; set; } - public CompilerObject? Type { get; set; } + public IType? Type { get; set; } public CompilerObject? Initializer { get; set; } - public IR.VM.Local CompileIRObject(Compiler.Compiler compiler, ICallableBody? owner) + public IR.VM.Local CompileIRObject(Compiler.Compiler compiler, IR.ICallableBody? owner) { if (Type is null) throw new PartiallyCompiledObjectException( diff --git a/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs b/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs index 2ebde353..e0a1eeba 100644 --- a/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs +++ b/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs @@ -48,7 +48,7 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments code.Types.Clear(); if (Origin.ReturnType != compiler.TypeSystem.Void) - code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); + code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); return new RawCode(code); } diff --git a/ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs b/ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs index 83221fd2..6b5c2cb0 100644 --- a/ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs +++ b/ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs @@ -8,7 +8,7 @@ public sealed class KeywordVarParameter(string name) public IR.Parameter? IR { get; set; } - public CompilerObject? Type { get; set; } + public Compiler.IType? Type { get; set; } CompilerObject IKeywordVarParameter.MatchArguments(Compiler.Compiler compiler, Dictionary argument) { diff --git a/ZSharp.Compiler.Objects/functional/signature/Parameter.cs b/ZSharp.Compiler.Objects/functional/signature/Parameter.cs index 7744ceec..9529a5b5 100644 --- a/ZSharp.Compiler.Objects/functional/signature/Parameter.cs +++ b/ZSharp.Compiler.Objects/functional/signature/Parameter.cs @@ -13,7 +13,7 @@ public sealed class Parameter(string name) public string Name { get; } = name; - public CompilerObject? Type { get; set; } + public IType? Type { get; set; } public CompilerObject? Initializer { get; set; } @@ -49,7 +49,7 @@ Parameter IReferencable.CreateReference(Referencing @ref, ReferenceCo return new(Name) { Initializer = Initializer is null ? null : @ref.CreateReference(Initializer, context), - Type = Type is null ? null : @ref.CreateReference(Type, context), + Type = Type is null ? null : @ref.CreateReference(Type, context), }; } diff --git a/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs b/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs index ed789852..d5cc4b74 100644 --- a/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs +++ b/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs @@ -8,7 +8,7 @@ public sealed class VarParameter(string name) public IR.Parameter? IR { get; set; } - public CompilerObject? Type { get; set; } + public Compiler.IType? Type { get; set; } CompilerObject IVarParameter.MatchArguments(Compiler.Compiler compiler, CompilerObject[] argument) { diff --git a/ZSharp.Compiler.Objects/generic/GenericParameter.cs b/ZSharp.Compiler.Objects/generic/GenericParameter.cs index 64a2beb0..672c90b3 100644 --- a/ZSharp.Compiler.Objects/generic/GenericParameter.cs +++ b/ZSharp.Compiler.Objects/generic/GenericParameter.cs @@ -1,12 +1,12 @@ using ZSharp.Compiler; -using ZSharp.IR; namespace ZSharp.Objects { public sealed class GenericParameter : CompilerObject , ICompileIRType - , IReferencable + , IReferencable + , IType { public string Name { get; set; } = string.Empty; @@ -15,7 +15,7 @@ public sealed class GenericParameter public IR.GenericParameter CompileIRType(Compiler.Compiler compiler) => IR ??= new(Name); - CompilerObject IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - => context.CompileTimeValues.Cache(this, out var result) ? result : this; + IType IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + => context.CompileTimeValues.Cache(this, out var result) ? result : this; } } diff --git a/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs b/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs index 2d6181b4..048c6465 100644 --- a/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs +++ b/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs @@ -8,7 +8,7 @@ public sealed class ArrayLiteral(IEnumerable? items = null) { public List Items { get; } = new(items ?? []); - CompilerObject ICTTypeCast.Cast(Compiler.Compiler compiler, CompilerObject targetType) + CompilerObject ICTTypeCast.Cast(Compiler.Compiler compiler, IType targetType) { var instance = compiler.Call(targetType, []); diff --git a/ZSharp.Compiler.Objects/modular/Global.cs b/ZSharp.Compiler.Objects/modular/Global.cs index 8aef03f6..578708a4 100644 --- a/ZSharp.Compiler.Objects/modular/Global.cs +++ b/ZSharp.Compiler.Objects/modular/Global.cs @@ -40,7 +40,7 @@ public bool IsDefined public CompilerObject? Initializer { get; set; } - public CompilerObject? Type { get; set; } + public IType? Type { get; set; } #region Protocols diff --git a/ZSharp.Compiler.Objects/modular/Module.cs b/ZSharp.Compiler.Objects/modular/Module.cs index 3a32f199..50166f1b 100644 --- a/ZSharp.Compiler.Objects/modular/Module.cs +++ b/ZSharp.Compiler.Objects/modular/Module.cs @@ -9,7 +9,7 @@ public sealed class Module(string name) , ICTGetMember , ICTReadable { - CompilerObject ITyped.Type => throw new NotImplementedException(); + IType ITyped.Type => throw new NotImplementedException(); public Collection Content { get; } = []; diff --git a/ZSharp.Compiler.Objects/oop/Implementation.cs b/ZSharp.Compiler.Objects/oop/Implementation.cs index 2eb91211..41d3b58e 100644 --- a/ZSharp.Compiler.Objects/oop/Implementation.cs +++ b/ZSharp.Compiler.Objects/oop/Implementation.cs @@ -3,13 +3,13 @@ namespace ZSharp.Objects { public sealed class Implementation( - CompilerObject @abstract, + IAbstraction @abstract, CompilerObject concrete ) { public Mapping Mapping { get; } = []; - public CompilerObject Abstract { get; } = @abstract; + public IAbstraction Abstract { get; } = @abstract; public CompilerObject Concrete { get; } = concrete; } diff --git a/ZSharp.Compiler.Objects/oop/abstraction/IAbstraction.cs b/ZSharp.Compiler.Objects/oop/abstraction/IAbstraction.cs new file mode 100644 index 00000000..bcd3897f --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/abstraction/IAbstraction.cs @@ -0,0 +1,10 @@ +using CommonZ.Utils; + +namespace ZSharp.Objects +{ + public interface IAbstraction + : CompilerObject + { + public Collection Specifications { get; } + } +} diff --git a/ZSharp.Compiler.Objects/oop/class/Class.cs b/ZSharp.Compiler.Objects/oop/class/Class.cs index 5c120b5b..b7b4f57d 100644 --- a/ZSharp.Compiler.Objects/oop/class/Class.cs +++ b/ZSharp.Compiler.Objects/oop/class/Class.cs @@ -1,16 +1,17 @@ using CommonZ.Utils; using ZSharp.Compiler; -using ZSharp.IR; namespace ZSharp.Objects { public sealed class Class : CompilerObject , ICompileIRObject - , ICompileIRType> + , ICompileIRType> , ICTCallable , ICTGetMember , IRTGetMember + , IType + , ITypeAssignableToType { #region Build State @@ -41,11 +42,13 @@ public bool IsDefined public string? Name { get; set; } - public CompilerObject? Base { get; set; } + public IType? Base { get; set; } public CompilerObject? Constructor { get; set; } - public Collection Interfaces { get; } = []; + public Collection Interfaces { get; } = []; + + public Collection InterfaceImplementations { get; } = []; public Collection Content { get; } = []; @@ -57,23 +60,18 @@ public bool IsDefined { IR ??= new(Name); - if (Base is not null && !state[BuildState.Base]) + if (owner is not null && !state[BuildState.Owner]) { - state[BuildState.Base] = true; + state[BuildState.Owner] = true; - IR.Base = compiler.CompileIRReference>(Base); + owner.Types.Add(IR); } - if (!state[BuildState.Interfaces]) + if (Base is not null && !state[BuildState.Base]) { - state[BuildState.Interfaces] = true; - - foreach (var @interface in Interfaces) - { - IR.InterfacesImplementations.Add(new(compiler.CompileIRReference>(@interface))); + state[BuildState.Base] = true; - // TODO: check for interface implementation - } + IR.Base = compiler.CompileIRReference>(Base); } if (Content.Count > 0 && !state[BuildState.Body]) @@ -84,11 +82,25 @@ public bool IsDefined compiler.CompileIRObject(item, IR); } - if (owner is not null && !state[BuildState.Owner]) + if (InterfaceImplementations.Count > 0 && !state[BuildState.Interfaces]) { - state[BuildState.Owner] = true; + state[BuildState.Interfaces] = true; - owner.Types.Add(IR); + foreach (var @interfaceImplementation in InterfaceImplementations) + { + IR.InterfaceImplementation implementation = new( + compiler.CompileIRReference>(interfaceImplementation.Abstract) + ); + + IR.InterfacesImplementations.Add(implementation); + + foreach (var (@abstract, concrete) in interfaceImplementation.Mapping) + { + var abstractMethod = compiler.CompileIRReference(@abstract); + var concreteMethod = compiler.CompileIRObject(concrete, IR); + implementation.Implementations.Add(abstractMethod, concreteMethod); + } + } } return IR; @@ -102,9 +114,9 @@ CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerO return compiler.Map(Members[member], @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, instance) : @object); } - OOPTypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) + IR.OOPTypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) { - return new ClassReference(compiler.CompileIRObject(this, null)); + return new IR.ClassReference(compiler.CompileIRObject(this, null)); } CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) @@ -115,6 +127,20 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments return compiler.Call(Constructor, arguments); } + bool? ITypeAssignableToType.IsAssignableTo(Compiler.Compiler compiler, IType target) + { + if (Base is not null && compiler.TypeSystem.IsAssignableTo(Base, target)) + return true; + + foreach (var @interface in Interfaces) + { + if (compiler.TypeSystem.IsAssignableTo(@interface, target)) + return true; + } + + return null; + } + #endregion } } diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs index 510acfb2..17587b8b 100644 --- a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs +++ b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs @@ -15,6 +15,7 @@ GenericClass origin , ICompileIRReference> , ICompileIRReference , IReferencable + , IType { CompilerObject IReference.Origin => Origin; @@ -91,17 +92,20 @@ GenericClassInstance IReferencable.CreateReference(Referen }; } - public override bool Equals(object? obj) + bool IType.IsEqualTo(Compiler.Compiler compiler, IType type) { - // TODO: instead of type == type, use assignable to - if (obj is not GenericClassInstance other) + if (type is not GenericClassInstance other) return false; if (Origin != other.Origin) return false; foreach (var genericParameter in Origin.GenericParameters) - if (Context[genericParameter] != other.Context[genericParameter]) + if (Context[genericParameter] is not IType thisGenericArgument) + throw new Compiler.InvalidCastException(Context[genericParameter], compiler.TypeSystem.Type); + else if (other.Context[genericParameter] is not IType otherGenericArgument) + throw new Compiler.InvalidCastException(other.Context[genericParameter], compiler.TypeSystem.Type); + else if (!compiler.TypeSystem.AreEqual(thisGenericArgument, otherGenericArgument)) return false; return true; diff --git a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs index c6ab3b4e..a8275940 100644 --- a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs +++ b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs @@ -29,7 +29,7 @@ enum BuildState public Signature Signature { get; set; } = new(); - public CompilerObject? Owner { get; set; } + public IType? Owner { get; set; } public CompilerObject? Body { get; set; } diff --git a/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs b/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs index e07614d1..d8203243 100644 --- a/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs +++ b/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs @@ -21,7 +21,7 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments if (owner is null) throw new(); - var ownerReference = compiler.Feature().CreateReference(owner, Context); + var ownerReference = compiler.Feature().CreateReference(owner, Context); var invocationInstruction = rawCode.Code.Instructions.Last(); if (invocationInstruction is IR.VM.CreateInstance createInstance) diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IAbstraction.cs b/ZSharp.Compiler.Objects/oop/extensibility/IAbstraction.cs deleted file mode 100644 index b78ad662..00000000 --- a/ZSharp.Compiler.Objects/oop/extensibility/IAbstraction.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IAbstraction - { - public virtual void OnDerivation(CompilerObject derived) { } - - public virtual void OnImplementation(CompilerObject implementor) { } - } -} diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IClass.cs b/ZSharp.Compiler.Objects/oop/extensibility/IClass.cs index aa8096ca..c4a95022 100644 --- a/ZSharp.Compiler.Objects/oop/extensibility/IClass.cs +++ b/ZSharp.Compiler.Objects/oop/extensibility/IClass.cs @@ -1,6 +1,8 @@ namespace ZSharp.Objects { public interface IClass + : CompilerObject + , Compiler.IType { public string Name { get; set; } diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs b/ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs new file mode 100644 index 00000000..f27faef9 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Objects +{ + public interface IImplementsSpecification + { + public virtual void OnImplementSpecification(Compiler.Compiler compiler, IAbstraction abstraction, CompilerObject specification) { } + } +} diff --git a/ZSharp.Compiler.Objects/oop/field/BoundField.cs b/ZSharp.Compiler.Objects/oop/field/BoundField.cs index f666bf06..ceebe6ad 100644 --- a/ZSharp.Compiler.Objects/oop/field/BoundField.cs +++ b/ZSharp.Compiler.Objects/oop/field/BoundField.cs @@ -11,7 +11,7 @@ public sealed class BoundField(Field field, CompilerObject instance) public CompilerObject Instance { get; } = instance; - public CompilerObject? Type => Field.Type; + public IType? Type => Field.Type; public CompilerObject Assign(Compiler.Compiler compiler, CompilerObject value) { diff --git a/ZSharp.Compiler.Objects/oop/field/Field.cs b/ZSharp.Compiler.Objects/oop/field/Field.cs index b3421b44..11936a35 100644 --- a/ZSharp.Compiler.Objects/oop/field/Field.cs +++ b/ZSharp.Compiler.Objects/oop/field/Field.cs @@ -14,7 +14,7 @@ public sealed class Field(string name) public CompilerObject? Initializer { get; set; } - public CompilerObject? Type { get; set; } + public IType? Type { get; set; } public bool IsReadOnly { get; set; } diff --git a/ZSharp.Compiler.Objects/oop/interface/Interface.cs b/ZSharp.Compiler.Objects/oop/interface/Interface.cs index 7bdfbb33..1cb41ebc 100644 --- a/ZSharp.Compiler.Objects/oop/interface/Interface.cs +++ b/ZSharp.Compiler.Objects/oop/interface/Interface.cs @@ -5,10 +5,13 @@ namespace ZSharp.Objects { public sealed class Interface(string? name) : CompilerObject + , IAbstraction , ICompileIRObject , ICompileIRReference> + , ICompileIRType> , ICTGetMember , IRTGetMember + , IType { #region Build State @@ -47,6 +50,8 @@ public bool IsDefined #region Protocols + Collection IAbstraction.Specifications => Content; + CompilerObject ICTGetMember.Member(Compiler.Compiler compiler, string member) => Members[member]; @@ -88,6 +93,11 @@ CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerO compiler.CompileIRObject(this, null) ); + IR.OOPTypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) + => new IR.InterfaceReference( + compiler.CompileIRObject(this, null) + ); + #endregion } } diff --git a/ZSharp.Compiler.Objects/oop/method/Method.cs b/ZSharp.Compiler.Objects/oop/method/Method.cs index be0dcf35..612693a3 100644 --- a/ZSharp.Compiler.Objects/oop/method/Method.cs +++ b/ZSharp.Compiler.Objects/oop/method/Method.cs @@ -1,4 +1,5 @@ -using System.Diagnostics.CodeAnalysis; +using CommonZ.Utils; +using System.Diagnostics.CodeAnalysis; using ZSharp.Compiler; using Args = CommonZ.Utils.Collection; @@ -13,7 +14,11 @@ public sealed class Method(string? name) , ICTCallable , ICompileIRObject , ICompileIRObject + , ICompileIRReference + , IImplementsSpecification + , IImplicitCastToType , IReferencable + , ITyped { [Flags] enum BuildState @@ -25,6 +30,7 @@ enum BuildState } private readonly ObjectBuildState state = new(); + private bool isVirtual; public bool Defined { init { @@ -40,10 +46,23 @@ public bool Defined { init public Signature Signature { get; set; } = new(); - public CompilerObject? ReturnType { get; set; } + public IType? ReturnType { get; set; } public CompilerObject? Body { get; set; } + public Collection<(IAbstraction, CompilerObject)> Specifications { get; } = []; + + IType ITyped.Type + { + get + { + if (ReturnType is null) + throw new InvalidOperationException(); + + return new MethodType(Signature, ReturnType); + } + } + public CompilerObject Bind(Compiler.Compiler compiler, CompilerObject value) => new BoundMethod(this, value); @@ -71,8 +90,12 @@ public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) foreach (var param in @params) code.Append(compiler.CompileIRCode(args[param])); + var ir = compiler.CompileIRReference(this); + code.Append(new([ - new IR.VM.Call(compiler.CompileIRObject(this, null)) + IR.IsVirtual + ? new IR.VM.CallVirtual(ir) + : new IR.VM.Call(ir) ])); code.Types.Clear(); @@ -85,24 +108,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) [MemberNotNull(nameof(ReturnType))] public IR.Method CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) { - IR ??= - new( - compiler.CompileIRType( - ReturnType ?? throw new PartiallyCompiledObjectException( - this, - Errors.UndefinedReturnType(Name) - ) - ) - ) - { - Name = Name, - IsInstance = true, - }; - - if (ReturnType is null) - throw new PartiallyCompiledObjectException( - this, Errors.UndefinedReturnType(Name) - ); + CompileIR(compiler); if (owner is not null && !state[BuildState.Owner]) { @@ -111,19 +117,9 @@ public IR.Method CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) owner.Methods.Add(IR); } - if (!state[BuildState.Signature]) - { - state[BuildState.Signature] = true; - - compiler.CompileIRObject(Signature, IR.Signature); - } - - if (Body is not null && !state[BuildState.Body]) - { - state[BuildState.Body] = true; + CompileDefinition(compiler); - IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); - } + ReturnType ??= null!; return IR; } @@ -143,7 +139,44 @@ MethodReference IReferencable.CreateReference(Referencing @ref, IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.OOPType? owner) { - IR ??= + CompileIR(compiler); + + CompileDefinition(compiler); + + return IR; + } + + IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) + { + throw new NotImplementedException(); + } + + public override string ToString() + => $""}>"; + + CompilerObject IImplicitCastToType.ImplicitCastToType(Compiler.Compiler compiler, IType type) + { + if (type is not ICallableType callableType) + throw new Compiler.InvalidCastException(this, type); + + throw new Compiler.InvalidCastException(this, type); + } + + IR.MethodReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + => new( + compiler.CompileIRObject(this, null) + ) + { + OwningType = (IR.OOPTypeReference)IR!.Signature.Args.Parameters[0].Type, // TODO: add Owner property + }; + + void IImplementsSpecification.OnImplementSpecification(Compiler.Compiler compiler, IAbstraction abstraction, CompilerObject specification) + => Specifications.Add((abstraction, specification)); + + [MemberNotNull(nameof(IR))] + private IR.Method CompileIR(Compiler.Compiler compiler) + { + return IR ??= new( compiler.CompileIRType( ReturnType ?? throw new PartiallyCompiledObjectException( @@ -155,38 +188,28 @@ MethodReference IReferencable.CreateReference(Referencing @ref, { Name = Name, IsInstance = true, + IsVirtual = Specifications.Count > 0, }; + } - if (!state.Get(BuildState.Signature)) - { - state.Set(BuildState.Signature); - - foreach (var arg in Signature.Args) - IR.Signature.Args.Parameters.Add(compiler.CompileIRObject(arg, IR.Signature)); - - if (Signature.VarArgs is not null) - IR.Signature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, IR.Signature); + private void CompileDefinition(Compiler.Compiler compiler) + { + if (IR is null) + throw new InvalidOperationException(); - foreach (var kwArg in Signature.KwArgs) - IR.Signature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, IR.Signature)); + if (!state[BuildState.Signature]) + { + state[BuildState.Signature] = true; - if (Signature.VarKwArgs is not null) - IR.Signature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, IR.Signature); + compiler.CompileIRObject(Signature, IR.Signature); } - if (Body is not null && !state.Get(BuildState.Body)) + if (Body is not null && !state[BuildState.Body]) { - state.Set(BuildState.Body); + state[BuildState.Body] = true; IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); } - - return IR; - } - - IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) - { - throw new NotImplementedException(); } } } diff --git a/ZSharp.Compiler.Objects/oop/method/MethodReference.cs b/ZSharp.Compiler.Objects/oop/method/MethodReference.cs index 5b2b369e..a128651d 100644 --- a/ZSharp.Compiler.Objects/oop/method/MethodReference.cs +++ b/ZSharp.Compiler.Objects/oop/method/MethodReference.cs @@ -52,7 +52,7 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments code.Types.Clear(); if (Origin.ReturnType != compiler.TypeSystem.Void) - code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); + code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); return new RawCode(code); } diff --git a/ZSharp.Compiler.Objects/oop/method/MethodType.cs b/ZSharp.Compiler.Objects/oop/method/MethodType.cs new file mode 100644 index 00000000..33c81da0 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/MethodType.cs @@ -0,0 +1,26 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class MethodType(Signature signature, IType returnType) + : CompilerObject + , ICallableType + { + public Signature Signature { get; } = signature; + + Collection ICallableType.Args => [.. Signature.Args.Select(p => p.Type ?? throw new InvalidOperationException())]; + + IType? ICallableType.VarArgs => Signature.VarArgs?.Type; + + Mapping ICallableType.KwArgs => new(Signature.KwArgs + .ToDictionary( + p => p.Name, + p => p.Type ?? throw new InvalidOperationException() + )); + + IType? ICallableType.VarKwArgs => Signature.VarKwArgs?.Type; + + IType ICallableType.ReturnType { get; } = returnType; + } +} diff --git a/ZSharp.Compiler.Objects/signature/ICallableType.cs b/ZSharp.Compiler.Objects/signature/ICallableType.cs new file mode 100644 index 00000000..f48c7923 --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/ICallableType.cs @@ -0,0 +1,68 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public interface ICallableType + : IType + { + public Collection Args { get; } + + public IType? VarArgs { get; } + + public Mapping KwArgs { get; } + + public IType? VarKwArgs { get; } + + public IType ReturnType { get; } + + bool IType.IsEqualTo(Compiler.Compiler compiler, IType type) + { + if (type is not ICallableType callableType) + return false; + + if (Args.Count != callableType.Args.Count) + return false; + + if ( + VarArgs is null && callableType.VarArgs is not null || + VarArgs is not null && callableType.VarArgs is null + ) + return false; + if ( + !(VarArgs is null && callableType.VarArgs is null) && + !compiler.TypeSystem.AreEqual(VarArgs!, callableType.VarArgs!) + ) + return false; + + if (KwArgs.Count != callableType.KwArgs.Count) + return false; + + if ( + VarKwArgs is null && callableType.VarKwArgs is not null || + VarKwArgs is not null && callableType.VarKwArgs is null + ) + return false; + if ( + !(VarKwArgs is null && callableType.VarKwArgs is null) && + !compiler.TypeSystem.AreEqual(VarKwArgs!, callableType.VarKwArgs!) + ) + return false; + + if (!compiler.TypeSystem.AreEqual(ReturnType, callableType.ReturnType)) + return false; + + foreach (var (left, right) in Args.Zip(callableType.Args)) + if (!compiler.TypeSystem.AreEqual(left, right)) + return false; + + foreach (var (name, kwArgType) in KwArgs) + if (!callableType.KwArgs.TryGetValue(name, out var otherKwArgType)) + return false; + else if (!compiler.TypeSystem.AreEqual(kwArgType, otherKwArgType)) + return false; + + return true; + } + } +} diff --git a/ZSharp.Compiler/cg objects/literals/FalseLiteral.cs b/ZSharp.Compiler/cg objects/literals/FalseLiteral.cs index 247839d5..9be280f9 100644 --- a/ZSharp.Compiler/cg objects/literals/FalseLiteral.cs +++ b/ZSharp.Compiler/cg objects/literals/FalseLiteral.cs @@ -2,11 +2,11 @@ namespace ZSharp.Objects { - public sealed class FalseLiteral(CompilerObject type) + public sealed class FalseLiteral(IType type) : CompilerObject , ICTReadable { - public CompilerObject Type { get; } = type; + public IType Type { get; } = type; public IRCode Read(Compiler.Compiler compiler) => new([ diff --git a/ZSharp.Compiler/cg objects/literals/Float32Literal.cs b/ZSharp.Compiler/cg objects/literals/Float32Literal.cs index 1fb47b0d..0654ff58 100644 --- a/ZSharp.Compiler/cg objects/literals/Float32Literal.cs +++ b/ZSharp.Compiler/cg objects/literals/Float32Literal.cs @@ -2,11 +2,11 @@ namespace ZSharp.Objects { - public sealed class Float32Literal(float value, CompilerObject type) + public sealed class Float32Literal(float value, IType type) : Literal(value) , ICTReadable { - public override CompilerObject Type { get; } = type; + public override IType Type { get; } = type; public override IRCode Read(Compiler.Compiler compiler) => new( diff --git a/ZSharp.Compiler/cg objects/literals/IntegerLiteral.cs b/ZSharp.Compiler/cg objects/literals/IntegerLiteral.cs index d8c6b9f8..a4daadef 100644 --- a/ZSharp.Compiler/cg objects/literals/IntegerLiteral.cs +++ b/ZSharp.Compiler/cg objects/literals/IntegerLiteral.cs @@ -2,11 +2,11 @@ namespace ZSharp.Objects { - public sealed class IntegerLiteral(DefaultIntegerType value, CompilerObject type) + public sealed class IntegerLiteral(DefaultIntegerType value, IType type) : Literal(value) , ICTReadable { - public override CompilerObject Type { get; } = type; + public override IType Type { get; } = type; public override IRCode Read(Compiler.Compiler compiler) => new( diff --git a/ZSharp.Compiler/cg objects/literals/Literal.cs b/ZSharp.Compiler/cg objects/literals/Literal.cs index 6aac5f3b..111d28df 100644 --- a/ZSharp.Compiler/cg objects/literals/Literal.cs +++ b/ZSharp.Compiler/cg objects/literals/Literal.cs @@ -6,7 +6,7 @@ public abstract class Literal(object? value) : CompilerObject , ICTReadable { - public abstract CompilerObject Type { get; } + public abstract IType Type { get; } public object? Value { get; } = value; diff --git a/ZSharp.Compiler/cg objects/literals/NullLiteral.cs b/ZSharp.Compiler/cg objects/literals/NullLiteral.cs index 9fb03011..be238d6e 100644 --- a/ZSharp.Compiler/cg objects/literals/NullLiteral.cs +++ b/ZSharp.Compiler/cg objects/literals/NullLiteral.cs @@ -2,9 +2,9 @@ namespace ZSharp.Objects { - public sealed class NullLiteral(CompilerObject type) : Literal(null) + public sealed class NullLiteral(IType type) : Literal(null) { - public override CompilerObject Type { get; } = type; + public override IType Type { get; } = type; public override IRCode Read(Compiler.Compiler compiler) => new([ diff --git a/ZSharp.Compiler/cg objects/literals/StringLiteral.cs b/ZSharp.Compiler/cg objects/literals/StringLiteral.cs index cda5c3a2..76d22e5f 100644 --- a/ZSharp.Compiler/cg objects/literals/StringLiteral.cs +++ b/ZSharp.Compiler/cg objects/literals/StringLiteral.cs @@ -2,10 +2,10 @@ namespace ZSharp.Objects { - public sealed class StringLiteral(string value, CompilerObject type) + public sealed class StringLiteral(string value, IType type) : Literal(value) { - public override CompilerObject Type { get; } = type; + public override IType Type { get; } = type; public override IRCode Read(Compiler.Compiler compiler) => new([ diff --git a/ZSharp.Compiler/cg objects/literals/TrueLiteral.cs b/ZSharp.Compiler/cg objects/literals/TrueLiteral.cs index af0d4905..178a1a3f 100644 --- a/ZSharp.Compiler/cg objects/literals/TrueLiteral.cs +++ b/ZSharp.Compiler/cg objects/literals/TrueLiteral.cs @@ -2,11 +2,11 @@ namespace ZSharp.Objects { - public sealed class TrueLiteral(CompilerObject type) + public sealed class TrueLiteral(IType type) : CompilerObject , ICTReadable { - public CompilerObject Type { get; } = type; + public IType Type { get; } = type; public IRCode Read(Compiler.Compiler compiler) => new([ diff --git a/ZSharp.Compiler/cg objects/raw/RawCode.cs b/ZSharp.Compiler/cg objects/raw/RawCode.cs index f021954b..546e12f1 100644 --- a/ZSharp.Compiler/cg objects/raw/RawCode.cs +++ b/ZSharp.Compiler/cg objects/raw/RawCode.cs @@ -10,12 +10,12 @@ public sealed class RawCode(IRCode code) public IRCode Code => code; - public CompilerObject Type => code.RequireValueType(); + public IType Type => code.RequireValueType(); public IRCode Read(Compiler.Compiler _) => code; - CompilerObject IDynamicallyTyped.GetType(Compiler.Compiler compiler) + IType IDynamicallyTyped.GetType(Compiler.Compiler compiler) => code.IsVoid ? compiler.TypeSystem.Void : code.RequireValueType(); } } diff --git a/ZSharp.Compiler/cg objects/raw/RawType.cs b/ZSharp.Compiler/cg objects/raw/RawType.cs index 2e60a403..0effb7ea 100644 --- a/ZSharp.Compiler/cg objects/raw/RawType.cs +++ b/ZSharp.Compiler/cg objects/raw/RawType.cs @@ -1,22 +1,22 @@ using ZSharp.Compiler; -using ZSharp.IR; namespace ZSharp.Objects { - public sealed class RawType(IRType type, CompilerObject metaType) + public sealed class RawType(IRType type, IType metaType) : CompilerObject , ICTReadable , ICompileIRType + , IType { private IRType type = type; - public CompilerObject Type { get; internal set; } = metaType; + public IType Type { get; internal set; } = metaType; - public IType CompileIRType(Compiler.Compiler compiler) + public IRType CompileIRType(Compiler.Compiler compiler) => type; public IRCode Read(Compiler.Compiler compiler) - => type is IRObject ir ? new([ + => type is IR.IRObject ir ? new([ new IR.VM.GetObject(ir) ]) { diff --git a/ZSharp.Compiler/cg objects/types/Int32Type.cs b/ZSharp.Compiler/cg objects/types/Int32Type.cs index 48066519..ee1047e4 100644 --- a/ZSharp.Compiler/cg objects/types/Int32Type.cs +++ b/ZSharp.Compiler/cg objects/types/Int32Type.cs @@ -3,14 +3,15 @@ namespace ZSharp.Objects { - public sealed class Int32Type(IR.OOPTypeReference ir, CompilerObject type) + public sealed class Int32Type(IR.OOPTypeReference ir, IType type) : CompilerObject , ICompileIRType , ICTGetMember + , IType { public IR.OOPTypeReference IR { get; } = ir; - public CompilerObject Type { get; } = type; + public IType Type { get; } = type; public Mapping Members { get; } = []; diff --git a/ZSharp.Compiler/cg objects/types/StringType.cs b/ZSharp.Compiler/cg objects/types/StringType.cs index e1158cfe..a3ea2e75 100644 --- a/ZSharp.Compiler/cg objects/types/StringType.cs +++ b/ZSharp.Compiler/cg objects/types/StringType.cs @@ -2,14 +2,15 @@ namespace ZSharp.Objects { - public sealed class StringType(IR.OOPTypeReference stringType, CompilerObject type) + public sealed class StringType(IR.OOPTypeReference stringType, IType type) : CompilerObject , ICompileIRType , ICTCallable + , IType { public IR.OOPTypeReference IR { get; } = stringType; - public CompilerObject Type { get; } = type; + public IType Type { get; } = type; public new CompilerObject ToString { get; set; } = null!; diff --git a/ZSharp.Compiler/cg objects/Type.cs b/ZSharp.Compiler/cg objects/types/Type.cs similarity index 87% rename from ZSharp.Compiler/cg objects/Type.cs rename to ZSharp.Compiler/cg objects/types/Type.cs index 7544e4d1..cde6eb9e 100644 --- a/ZSharp.Compiler/cg objects/Type.cs +++ b/ZSharp.Compiler/cg objects/types/Type.cs @@ -1,5 +1,4 @@ using ZSharp.Compiler; -using ZSharp.IR; namespace ZSharp.Objects { @@ -7,13 +6,14 @@ internal sealed class Type(IRType type) : CompilerObject //, ICTReadable , ICompileIRType + , IType { private readonly IRType type = type; //private readonly IRObject ir = type as IRObject ?? throw new(); //CompilerObject ITyped.Type => this; - IType ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IRType ICompileIRType.CompileIRType(Compiler.Compiler compiler) => type; //public IRCode Read(Compiler.Compiler compiler) diff --git a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs index 1f94678c..07f3ce21 100644 --- a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs +++ b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs @@ -30,9 +30,9 @@ public CompilerObject Call(CompilerObject target, Argument[] arguments) throw new("Object of this type is not callable."); } - public CompilerObject Cast(CompilerObject target, CompilerObject type) + public CompilerObject Cast(CompilerObject target, IType type) { - if (TypeSystem.IsTyped(target, out var targetType) && targetType.Equals(type)) + if (TypeSystem.IsTyped(target, out var targetType) && TypeSystem.AreEqual(type, targetType)) return target; if (target is ICTTypeCast typeCast) diff --git a/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Create.cs b/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Create.cs index e7348a34..51dca2a0 100644 --- a/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Create.cs +++ b/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Create.cs @@ -25,7 +25,7 @@ public CompilerObject CreateString(string value) public CompilerObject CreateNull() => CreateNull(TypeSystem.Null); - public CompilerObject CreateNull(CompilerObject type) + public CompilerObject CreateNull(IType type) { if (!nullLiterals.TryGetValue(type, out var nullLiteral)) nullLiterals[type] = nullLiteral = new(type); diff --git a/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs b/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs index baa12d84..44adbfd4 100644 --- a/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs +++ b/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs @@ -2,6 +2,6 @@ { public interface IDynamicallyTyped { - public CompilerObject GetType(Compiler compiler); + public IType GetType(Compiler compiler); } } diff --git a/ZSharp.Compiler/compiler core/core/type system/IType.cs b/ZSharp.Compiler/compiler core/core/type system/IType.cs new file mode 100644 index 00000000..9961c27a --- /dev/null +++ b/ZSharp.Compiler/compiler core/core/type system/IType.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public interface IType + : CompilerObject + { + public bool IsEqualTo(Compiler compiler, IType type) + => ReferenceEquals(this, type); + } +} diff --git a/ZSharp.Compiler/compiler core/core/type system/ITypeAssignment.cs b/ZSharp.Compiler/compiler core/core/type system/ITypeAssignment.cs new file mode 100644 index 00000000..4c5e5e39 --- /dev/null +++ b/ZSharp.Compiler/compiler core/core/type system/ITypeAssignment.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Compiler +{ + public interface ITypeAssignableToType + : IType + { + public bool? IsAssignableTo(Compiler compiler, IType target) + => null; + } + + public interface ITypeAssignableFromType + : IType + { + public bool? IsAssignableFrom(Compiler compiler, IType source) + => null; + } +} diff --git a/ZSharp.Compiler/compiler core/core/type system/ITyped.cs b/ZSharp.Compiler/compiler core/core/type system/ITyped.cs index 4d5c18e7..141237c5 100644 --- a/ZSharp.Compiler/compiler core/core/type system/ITyped.cs +++ b/ZSharp.Compiler/compiler core/core/type system/ITyped.cs @@ -2,9 +2,9 @@ { public interface ITyped : IDynamicallyTyped { - public CompilerObject Type { get; } + public IType Type { get; } - CompilerObject IDynamicallyTyped.GetType(Compiler compiler) + IType IDynamicallyTyped.GetType(Compiler compiler) => Type; } } diff --git a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs index de4ae01a..735bbaa7 100644 --- a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs +++ b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs @@ -8,19 +8,19 @@ public sealed class TypeSystem { public StringType String { get; } - public CompilerObject Type { get; } + public IType Type { get; } - public CompilerObject Void { get; } + public IType Void { get; } - public CompilerObject Null { get; } + public IType Null { get; } - public CompilerObject Boolean { get; } + public IType Boolean { get; } public Int32Type Int32 { get; } - public CompilerObject Float32 { get; } + public IType Float32 { get; } - public CompilerObject Object { get; } + public IType Object { get; } internal TypeSystem(Compiler compiler) : base(compiler) @@ -36,32 +36,28 @@ internal TypeSystem(Compiler compiler) Object = new RawType(compiler.RuntimeModule.TypeSystem.Object, Type); } - public CompilerObject EvaluateType(CompilerObject @object) - => Compiler.Evaluate(@object); + public IType EvaluateType(CompilerObject @object) + => (IType)Compiler.Evaluate(@object); - public CompilerObject Array(CompilerObject type) + public IType Array(CompilerObject type) => throw new NotImplementedException(); - public CompilerObject Pointer(CompilerObject type) + public IType Pointer(CompilerObject type) => throw new NotImplementedException(); - public CompilerObject Reference(CompilerObject type) + public IType Reference(CompilerObject type) => throw new NotImplementedException(); - public bool AreEqual(CompilerObject left, CompilerObject right) + public bool AreEqual(IType left, IType right) { - if (ReferenceEquals(left, right)) + if (left.IsEqualTo(Compiler, right)) return true; - - if (Equals(left, right)) + if (right.IsEqualTo(Compiler, left)) return true; - - // TODO: this function should do more stuff - return false; } - public CompilerObjectResult ImplicitCast(CompilerObject value, CompilerObject type) + public CompilerObjectResult ImplicitCast(CompilerObject value, IType type) { CompilerObjectResult result = CompilerObjectResult.Error( $"ImplicitCast for value:{value}, type:{type} is not supported." @@ -79,16 +75,33 @@ public CompilerObjectResult ImplicitCast(CompilerObject value, CompilerObject ty if (result.IsOk) return result; - if (IsTyped(value, out var valueType) && AreEqual(valueType, type)) + if (IsTyped(value, out var valueType) && (AreEqual(valueType, type) || IsAssignableTo(valueType, type))) result = CompilerObjectResult.Ok(value); return result; } + public bool IsAssignableTo(IType source, IType target) + { + if (source is ITypeAssignableToType to && to.IsAssignableTo(Compiler, target) is bool assignableTo) + return assignableTo; + + if (target is ITypeAssignableFromType from && from.IsAssignableFrom(Compiler, source) is bool assignableFrom) + return assignableFrom; + + if (AreEqual(source, target)) + return true; + + return false; + } + + public bool IsAssignableFrom(IType target, IType source) + => IsAssignableTo(source, target); + public bool IsTyped(CompilerObject @object) => @object is IDynamicallyTyped; - public bool IsTyped(CompilerObject @object, [NotNullWhen(true)] out CompilerObject? type) + public bool IsTyped(CompilerObject @object, [NotNullWhen(true)] out IType? type) { if (@object is IDynamicallyTyped typed) return (type = typed.GetType(Compiler)) is not null; diff --git a/ZSharp.Compiler/core/code/IRCode.cs b/ZSharp.Compiler/core/code/IRCode.cs index d8d4a121..de716ed6 100644 --- a/ZSharp.Compiler/core/code/IRCode.cs +++ b/ZSharp.Compiler/core/code/IRCode.cs @@ -8,7 +8,7 @@ public sealed class IRCode public int MaxStackSize { get; set; } - public Collection Types { get; init; } = []; + public Collection Types { get; init; } = []; public bool IsVoid => Types.Count == 0; @@ -29,7 +29,7 @@ public void RequireVoidType() throw new InvalidOperationException(); } - public CompilerObject RequireValueType() + public IType RequireValueType() => IsValue ? Types[0] : throw new InvalidOperationException(); public void Append(IRCode other) @@ -46,7 +46,7 @@ public void Append(IRCode other) { Instructions = Collection.Empty, MaxStackSize = 0, - Types = Collection.Empty, + Types = [], }; } } diff --git a/ZSharp.Compiler/core/concepts/value/IImplicitCast.cs b/ZSharp.Compiler/core/concepts/value/IImplicitCast.cs index c8503766..6a7b71f1 100644 --- a/ZSharp.Compiler/core/concepts/value/IImplicitCast.cs +++ b/ZSharp.Compiler/core/concepts/value/IImplicitCast.cs @@ -7,6 +7,6 @@ public interface IImplicitCastFromValue public interface IImplicitCastToType { - public CompilerObject ImplicitCastToType(Compiler compiler, CompilerObject type); + public CompilerObject ImplicitCastToType(Compiler compiler, IType type); } } diff --git a/ZSharp.Compiler/core/concepts/value/IReadable.cs b/ZSharp.Compiler/core/concepts/value/IReadable.cs index cbd3fd65..b2ff919f 100644 --- a/ZSharp.Compiler/core/concepts/value/IReadable.cs +++ b/ZSharp.Compiler/core/concepts/value/IReadable.cs @@ -3,13 +3,13 @@ public interface ICTReadable : ITyped { - public IRCode Cast(Compiler compiler, CompilerObject type) + public IRCode Cast(Compiler compiler, IType type) => this is ICTTypeCast typeCast && typeCast.Cast(compiler, type) is ICTReadable readable ? readable.Read(compiler, type) : throw new NotImplementedException(); - public IRCode Read(Compiler compiler, CompilerObject? @as) + public IRCode Read(Compiler compiler, IType? @as) { if (@as is null || @as == Type) return Read(compiler); diff --git a/ZSharp.Compiler/core/concepts/value/ITypeCast.cs b/ZSharp.Compiler/core/concepts/value/ITypeCast.cs index 21a0e9ad..90cd4e8b 100644 --- a/ZSharp.Compiler/core/concepts/value/ITypeCast.cs +++ b/ZSharp.Compiler/core/concepts/value/ITypeCast.cs @@ -2,11 +2,11 @@ { public interface ICTTypeCast { - public CompilerObject Cast(Compiler compiler, CompilerObject targetType); + public CompilerObject Cast(Compiler compiler, IType targetType); } public interface IRTTypeCast { - public CompilerObject Cast(Compiler compiler, CompilerObject @object, CompilerObject targetType); + public CompilerObject Cast(Compiler compiler, CompilerObject @object, IType targetType); } } diff --git a/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs index 3c595530..bbea1c06 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs @@ -120,6 +120,7 @@ private Method LoadMethod(MethodInfo method) var result = new Method(Loader.LoadType(method.ReturnType)) { Name = method.GetCustomAttribute()?.Name ?? method.Name, + IsVirtual = true, }; Context.Cache(method, result); diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index a51d5717..4caf4ea4 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -34,12 +34,12 @@ public Type LoadType(IR.IType type) return type switch { - IR.OOPTypeReference reference => LoadType(reference), + IR.OOPTypeReference reference => LoadTypeReference(reference), _ => throw new NotImplementedException() }; } - public Type LoadType(IR.OOPTypeReference typeReference) + public Type LoadTypeReference(IR.OOPTypeReference typeReference) { var type = Context.Cache(typeReference.Definition); diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs index a627e12f..8dfcb5cc 100644 --- a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs @@ -26,6 +26,9 @@ protected override void DoLoad() if (Input.HasMethods) ModuleLoader.AddToNextPass(LoadMethods); + if (Input.InterfacesImplementations.Count > 0) + ModuleLoader.AddToNextPass(LoadInterfaceImplementations); + ModuleLoader.AddToCleanUp(() => Output.CreateType()); } @@ -56,6 +59,23 @@ private void LoadGenericParameters() }); } + private void LoadInterfaceImplementations() + { + foreach (var interfaceImplementation in Input.InterfacesImplementations) + { + var @interface = Loader.LoadType(interfaceImplementation.Interface); + Output.AddInterfaceImplementation(@interface); + + foreach (var (@abstract, concrete) in interfaceImplementation.Implementations) + { + var specification = Loader.LoadReference(@abstract); + var implementation = Context.Cache(concrete) ?? throw new(); + + Output.DefineMethodOverride(implementation, specification); + } + } + } + private void LoadNestedTypes() { @@ -133,6 +153,8 @@ private void LoadMethod(IR.Method method) if (method.IsStatic) attributes |= IL.MethodAttributes.Static; + if (method.IsVirtual) + attributes |= IL.MethodAttributes.Virtual | IL.MethodAttributes.NewSlot; var result = Output.DefineMethod( method.Name ?? Constants.AnonymousMethod, diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs index b81f36a1..ba0a2eb9 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs @@ -2,7 +2,7 @@ namespace ZSharp.ZSSourceCompiler { - public sealed class ClassBodyCompiler(ZSSourceCompiler compiler, OOPDefinition oop, Objects.Class @class) + public sealed class ClassBodyCompiler(ZSSourceCompiler compiler, OOPDefinition oop, Class @class) : CompilerBase(compiler) , IMultipassCompiler { @@ -10,32 +10,40 @@ public sealed class ClassBodyCompiler(ZSSourceCompiler compiler, OOPDefinition o public OOPDefinition Node { get; } = oop; - public Objects.Class Class { get; } = @class; + public Class Class { get; } = @class; public void AddToNextPass(Action action) => nextPass.Add(action); public void Compile() + { + if (Node.Content is null) + return; + + currentPass = [.. Node.Content.Statements.Select(Compile)]; + } + + public bool CompileSinglePass() { using (Context.Compiler(this)) - CompileContent(); + return CompileSinglePassImpl(); } - private void CompileContent() + public void CompileUntilComplete() { - if (Node.Content is null) - return; + using (Context.Compiler(this)) + while (CompileSinglePassImpl()) ; + } - currentPass = Node.Content.Statements.Select(Compile).ToList(); + private bool CompileSinglePassImpl() + { + foreach (var item in currentPass) + item(); - while (currentPass.Count > 0) - { - foreach (var item in currentPass) - item(); + (currentPass, nextPass) = (nextPass, currentPass); + nextPass.Clear(); - (currentPass, nextPass) = (nextPass, currentPass); - nextPass.Clear(); - } + return currentPass.Count > 0; } private Action Compile(Statement statement) @@ -83,7 +91,7 @@ private Action Compile(AST.Constructor constructor) private Action Compile(AST.Function function) { - var compiler = new MethodCompiler(Compiler, function, Class); + var compiler = new MethodCompiler(Compiler, function, Class, Class); Class.Content.Add(compiler.Object); diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs index 9bf96995..f80a584c 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs @@ -1,6 +1,6 @@ namespace ZSharp.ZSSourceCompiler { - public sealed class MethodCompiler(ZSSourceCompiler compiler, Function node, CompilerObject owner) + public sealed class MethodCompiler(ZSSourceCompiler compiler, Function node, CompilerObject owner, Compiler.IType self) : ContextCompiler(compiler, node, new(node.Name)) , IOverrideCompileStatement { @@ -37,7 +37,7 @@ private void CompileMethod() Object.ReturnType = Compiler.CompileType(Node.ReturnType); else throw new(); // TODO: Implement Infer type - (This = Object.Signature.Args[0]).Type ??= owner; + (This = Object.Signature.Args[0]).Type ??= self; //Object.IR = Compiler.Compiler.CompileIRObject(Object, null); @@ -120,7 +120,7 @@ private CompilerObject CompileNode(LetExpression let) Context.CurrentScope.Set(let.Name, local); local.Type = let.Type is not null - ? Compiler.CompileNode(let.Type) + ? Compiler.CompileType(let.Type) : Compiler.Compiler.TypeSystem.IsTyped(local.Initializer, out var type) ? type : null; @@ -149,7 +149,7 @@ private CompilerObject CompileNode(VarExpression var) Context.CurrentScope.Set(var.Name, local); local.Type = var.Type is not null - ? Compiler.CompileNode(var.Type) + ? Compiler.CompileType(var.Type) : local.Initializer is null ? null : Compiler.Compiler.TypeSystem.IsTyped(local.Initializer, out var type) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs index e2b65746..39b5ee22 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs @@ -23,16 +23,108 @@ public override Class Compile() if (bases.Length > 0) { int interfacesIndex = 0; - if (bases[0] is GenericClassInstance) - Object.Base = (GenericClassInstance)bases[interfacesIndex++]; + if (bases[0] is IClass @base) + Object.Base = (IClass)bases[interfacesIndex++]; + + for (; interfacesIndex < bases.Length; interfacesIndex++) + Object.Interfaces.Add(bases[interfacesIndex]); } } + var bodyCompiler = new ClassBodyCompiler(Compiler, Node, Object); + + using (Context.Compiler(this)) + using (Context.Scope(Object)) + { + bodyCompiler.Compile(); + bodyCompiler.CompileSinglePass(); + } + + foreach (var @interface in Object.Interfaces) + if (@interface is IAbstraction abstraction) + ResolveImplementation(abstraction); + using (Context.Compiler(this)) using (Context.Scope(Object)) - new ClassBodyCompiler(Compiler, Node, Object).Compile(); + bodyCompiler.CompileUntilComplete(); return base.Compile(); } + + private void ResolveImplementation(IAbstraction abstraction) + { + Implementation? result = null; + foreach (var implementationInfo in Object.InterfaceImplementations) + if (implementationInfo.Abstract == abstraction) + { + result = implementationInfo; + break; + } + if (result is null) + Object.InterfaceImplementations.Add(result = new(abstraction, Object)); + + foreach (var specification in abstraction.Specifications) + if (result.Mapping.ContainsKey(specification)) + continue; + else if (ResolveImplementation(specification) is not CompilerObject implementation) + Compiler.LogError( + $"Class {Object.Name} does not implement member {specification} in {abstraction}", + Node + ); + else + { + result.Mapping.Add(specification, implementation); + if (implementation is IImplementsSpecification implementsSpecification) + implementsSpecification.OnImplementSpecification(Compiler.Compiler, abstraction, specification); + } + } + + private CompilerObject? ResolveImplementation(CompilerObject specification) + { + if (!Compiler.Compiler.TypeSystem.IsTyped(specification, out var specificationType)) + { + Compiler.LogError( + $"{specification} is an invalid specification object", + Node + ); + + return null; + } + + List possibleImplementations = []; + List errors = []; + + foreach (var item in Object.Content) + if (Compiler.Compiler.TypeSystem.ImplicitCast(item, specificationType).Ok(out var implementation)) + if (!Compiler.Compiler.TypeSystem.IsTyped(implementation, out var implementationType)) + errors.Add($"Member {implementation} cannot implemenet {specification} because it is not typed"); + else if (!Compiler.Compiler.TypeSystem.AreEqual(specificationType, implementationType)) + errors.Add($"Member {implementation} cannot implement {specification} because it is not equal"); + else possibleImplementations.Add(implementation); + + if (possibleImplementations.Count == 0) + { + Compiler.LogError( + string.Join( + "\n\t", [ + $"Class {Object.Name} does not implement member {specification} in {specificationType}", + .. errors + ] + ), + Node + ); + return null; + } + else if (possibleImplementations.Count > 1) + { + Compiler.LogError( + $"Class {Object.Name} has multiple implementations of {specification} in {specificationType}", + Node + ); + return null; + } + + return possibleImplementations[0]; + } } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs index 591644f7..76f3d1f9 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs @@ -115,7 +115,7 @@ private CompilerObject CompileNode(LetExpression let) Context.CurrentScope.Set(let.Name, local); local.Type = let.Type is not null - ? Compiler.CompileNode(let.Type) + ? Compiler.CompileType(let.Type) : Compiler.Compiler.TypeSystem.IsTyped(local.Initializer, out var type) ? type : null; @@ -144,7 +144,7 @@ private CompilerObject CompileNode(VarExpression var) Context.CurrentScope.Set(var.Name, local); local.Type = var.Type is not null - ? Compiler.CompileNode(var.Type) + ? Compiler.CompileType(var.Type) : local.Initializer is null ? null : Compiler.Compiler.TypeSystem.IsTyped(local.Initializer, out var type) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs index 99242bb4..3c84ac9a 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs @@ -1,6 +1,6 @@ namespace ZSharp.ZSSourceCompiler { - public sealed class WhileExpressionCompiler(ZSSourceCompiler compiler, WhileExpression node, CompilerObject type) + public sealed class WhileExpressionCompiler(ZSSourceCompiler compiler, WhileExpression node, Compiler.IType type) : WhileLoopCompiler(compiler, node, type) { protected override CompilerObject CompileBreak(BreakStatement @break) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs index e76ebe1d..8d4aa21c 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs @@ -1,7 +1,7 @@  namespace ZSharp.ZSSourceCompiler { - public abstract class WhileLoopCompiler(ZSSourceCompiler compiler, WhileExpression node, CompilerObject type) + public abstract class WhileLoopCompiler(ZSSourceCompiler compiler, WhileExpression node, Compiler.IType type) : ContextCompiler, WhileLoop>(compiler, node, new() { Type = type diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs index 9b3329d8..e61750eb 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs @@ -19,7 +19,7 @@ public sealed class WhileLoop public IR.VM.Instruction EndLabel { get; } = new IR.VM.Nop(); - public required CompilerObject Type { get; set; } + public required IType Type { get; set; } public IRCode CompileIRCode(Compiler.Compiler compiler) { diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs index c406e284..2fda069e 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs +++ b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs @@ -35,7 +35,7 @@ private CompilerObject CompileNode(T node) throw new($"Could not find suitable compiler for node of type {node.GetType().Name}"); // TODO: proper exception: could not find suitable compiler for T } - public CompilerObject CompileType(Expression expression) + public Compiler.IType CompileType(Expression expression) => Compiler.TypeSystem.EvaluateType(CompileNode(expression)); } } From 5f58f978339db1297265efdf9b46d33c5019a913 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 25 Apr 2025 12:24:39 +0300 Subject: [PATCH 147/235] Add type disassembler --- ZSharpTest/Main.cs | 47 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index eaf821aa..501e09db 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -1,4 +1,5 @@ -using System.Text.RegularExpressions; +using System.Text; +using System.Text.RegularExpressions; using ZSharp.Compiler; using ZSharp.Interpreter; using ZSharp.Parser; @@ -213,10 +214,13 @@ var mainModuleIL = runtime.Import(mainModuleIR); var mainModuleGlobals = mainModuleIL.GetType("") ?? throw new(); - var mainMethod = mainModuleGlobals.GetMethod("main", []); + //foreach (var type in mainModuleIL.GetTypes()) + // DecompileType(type); + + //foreach (var method in mainModuleIL.GetMethods()) + // Decompile(method); - if (mainMethod is not null) - Decompile(mainMethod); + var mainMethod = mainModuleGlobals.GetMethod("main", []); mainMethod?.Invoke(null, null); } @@ -230,9 +234,42 @@ Console.ReadKey(); +static void DecompileType(Type type) +{ + Console.WriteLine("========== Type: " + type.Name + " =========="); + + foreach (var method in type.GetMethods()) + { + if (method.DeclaringType != type) + continue; + + Decompile(method); + } + + Console.WriteLine("========== Type =========="); +} + + static void Decompile(System.Reflection.MethodBase method) { - Console.WriteLine("========== Disassmebly: " + method.Name + " =========="); + StringBuilder signatureBuilder = new(); + foreach (var parameter in method.GetParameters()) + { + if (signatureBuilder.Length > 0) + signatureBuilder.Append(", "); + signatureBuilder.Append(parameter.ParameterType.Name); + } + + string modifier = string.Empty; + if (method.IsStatic) + modifier = "static "; + else if (method.IsVirtual) + modifier = "virtual "; + else if (method.IsAbstract) + modifier = "abstract "; + else modifier = "instance "; + + Console.WriteLine($"========== Disassmebly: {modifier}{method.Name}({signatureBuilder}) =========="); foreach (var instruction in Mono.Reflection.Disassembler.GetInstructions(method)) { From e8772db15ad27de9711450accab856fdd2b1f29c Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 25 Apr 2025 12:24:52 +0300 Subject: [PATCH 148/235] Update simple.zs test file --- ZSharpTest/tests/simple.zs | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs index f8979338..77e00b3b 100644 --- a/ZSharpTest/tests/simple.zs +++ b/ZSharpTest/tests/simple.zs @@ -1,25 +1,35 @@ import { input, print } from "std:io"; import { Console, List, TestInterface, greet, id } from "net:ZLoad.Test.dll"; -// import { Console } from "net:C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\8.0.13\\System.Console.dll"; module Program; class MyClass : TestInterface { new(this) {} -} -fun main(): void { - let x = List[string](); + fun do(this: TestInterface): void { + print("Hello from MyClass"); - let v = MyClass(); - - print(greet(let name = input("Please enter your name: "))); + return; + } +} - Console.WriteLine(id[string]("Hi")); +class OtherClass : TestInterface { + new(this) {} - x.append(name); + fun do(this: TestInterface): void { + print("Hello from OtherClass"); + return; + } +} - print("x[0] = " + x.get(0)); +fun testInterface(test: TestInterface): void { + test.do(); + return; +} + +fun main(): void { + testInterface(MyClass()); + testInterface(OtherClass()); return; } From 3f9542290b28ca87b4a30f738ab3e9f9c27d2a2d Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 25 Apr 2025 18:23:27 +0300 Subject: [PATCH 149/235] Add support for custom implementors Add code duplication --- ZLoad.Test/TestInterface.cs | 3 + .../ZSharp.Compiler.Objects.csproj | 4 ++ ZSharp.Compiler.Objects/oop/Implementation.cs | 2 +- ZSharp.Compiler.Objects/oop/class/Class.cs | 1 + .../extensibility/IDerivableAbstraction.cs | 9 +++ .../oop/extensibility/IImplementation.cs | 10 +++ .../extensibility/IImplementsAbstraction.cs | 33 ++++++++++ .../extensibility/IImplementsSpecification.cs | 1 + ZSharp.Compiler.Objects/oop/method/IMethod.cs | 8 +++ .../oop/method/{ => concrete}/BoundMethod.cs | 0 .../oop/method/{ => concrete}/Method.cs | 50 ++++++++++++++ .../method/{ => concrete}/MethodReference.cs | 0 .../method/group/BoundMethodOverloadGroup.cs | 19 ++++++ .../oop/method/group/MethodOverloadGroup.cs | 30 +++++++++ .../overloading/OverloadGroup.cs | 20 ++++-- .../exceptions/AmbiguousOverloadException.cs | 2 +- .../exceptions/NoOverloadFoundException.cs | 2 +- .../exceptions/OverloadException.cs | 4 +- .../signature/ICallableType.cs | 51 ++++++++++++++ .../compiler/features/Compiler.Query.cs | 16 +++++ .../core/type system/TypeSystem.cs | 2 +- ZSharp.Compiler/core/concepts/INamedObject.cs | 10 +++ .../class body/ClassBodyCompiler.cs | 4 +- .../builtin-compilers/module/ClassCompiler.cs | 66 ++----------------- ZSharpTest/tests/simple.zs | 30 +++++++-- 25 files changed, 298 insertions(+), 79 deletions(-) create mode 100644 ZSharp.Compiler.Objects/oop/extensibility/IDerivableAbstraction.cs create mode 100644 ZSharp.Compiler.Objects/oop/extensibility/IImplementation.cs create mode 100644 ZSharp.Compiler.Objects/oop/extensibility/IImplementsAbstraction.cs create mode 100644 ZSharp.Compiler.Objects/oop/method/IMethod.cs rename ZSharp.Compiler.Objects/oop/method/{ => concrete}/BoundMethod.cs (100%) rename ZSharp.Compiler.Objects/oop/method/{ => concrete}/Method.cs (75%) rename ZSharp.Compiler.Objects/oop/method/{ => concrete}/MethodReference.cs (100%) create mode 100644 ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs create mode 100644 ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs create mode 100644 ZSharp.Compiler/compiler core/compiler/features/Compiler.Query.cs create mode 100644 ZSharp.Compiler/core/concepts/INamedObject.cs diff --git a/ZLoad.Test/TestInterface.cs b/ZLoad.Test/TestInterface.cs index dd15742f..1c0215f6 100644 --- a/ZLoad.Test/TestInterface.cs +++ b/ZLoad.Test/TestInterface.cs @@ -6,5 +6,8 @@ public interface TestInterface { [Alias(Name = "do")] public void Do(); + + [Alias(Name = "do")] + public int Calc(int x); } } diff --git a/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj b/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj index 9f6c481e..54159963 100644 --- a/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj +++ b/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj @@ -12,4 +12,8 @@ + + + + diff --git a/ZSharp.Compiler.Objects/oop/Implementation.cs b/ZSharp.Compiler.Objects/oop/Implementation.cs index 41d3b58e..620eb518 100644 --- a/ZSharp.Compiler.Objects/oop/Implementation.cs +++ b/ZSharp.Compiler.Objects/oop/Implementation.cs @@ -7,7 +7,7 @@ public sealed class Implementation( CompilerObject concrete ) { - public Mapping Mapping { get; } = []; + public Mapping Mapping { get; } = []; public IAbstraction Abstract { get; } = @abstract; diff --git a/ZSharp.Compiler.Objects/oop/class/Class.cs b/ZSharp.Compiler.Objects/oop/class/Class.cs index b7b4f57d..6d5d87a6 100644 --- a/ZSharp.Compiler.Objects/oop/class/Class.cs +++ b/ZSharp.Compiler.Objects/oop/class/Class.cs @@ -10,6 +10,7 @@ public sealed class Class , ICTCallable , ICTGetMember , IRTGetMember + , IImplementsAbstraction , IType , ITypeAssignableToType { diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IDerivableAbstraction.cs b/ZSharp.Compiler.Objects/oop/extensibility/IDerivableAbstraction.cs new file mode 100644 index 00000000..26c1144a --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/extensibility/IDerivableAbstraction.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Objects +{ + public interface IDerivableAbstraction + { + public virtual void OnDerivation(CompilerObject derived) { } + + public virtual void OnImplementation(CompilerObject implementor) { } + } +} diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IImplementation.cs b/ZSharp.Compiler.Objects/oop/extensibility/IImplementation.cs new file mode 100644 index 00000000..64a2a769 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/extensibility/IImplementation.cs @@ -0,0 +1,10 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Objects +{ + public interface IImplementation + : CompilerObject + { + public bool Implements(Compiler.Compiler compiler, CompilerObject specification, [NotNullWhen(true)] out IImplementsSpecification? implementation); + } +} diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IImplementsAbstraction.cs b/ZSharp.Compiler.Objects/oop/extensibility/IImplementsAbstraction.cs new file mode 100644 index 00000000..4f070655 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/extensibility/IImplementsAbstraction.cs @@ -0,0 +1,33 @@ +namespace ZSharp.Objects +{ + public interface IImplementsAbstraction + : CompilerObject + { + public Implementation ImplementAbstraction(Compiler.Compiler compiler, IAbstraction abstraction, Implementation? result = null) + { + result ??= new(abstraction, this); + + foreach (var specification in abstraction.Specifications) + { + if (result.Mapping.ContainsKey(specification)) + continue; + + if (!compiler.NameOf(specification, out var specificationName)) + continue; // this is actually invalid but ok + + var member = compiler.Member(this, specificationName); + + if (member is not IImplementation implementationCandidate) + throw new("Not implemented!"); // TODO: on implementation missing + + if (!implementationCandidate.Implements(compiler, specification, out var implementation)) + throw new("Not implemented"); // TODO: on implementation missing + + result.Mapping.Add(specification, implementation); + implementation.OnImplementSpecification(compiler, abstraction, specification); + } + + return result; + } + } +} diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs b/ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs index f27faef9..82d86d5f 100644 --- a/ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs +++ b/ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs @@ -1,6 +1,7 @@ namespace ZSharp.Objects { public interface IImplementsSpecification + : CompilerObject { public virtual void OnImplementSpecification(Compiler.Compiler compiler, IAbstraction abstraction, CompilerObject specification) { } } diff --git a/ZSharp.Compiler.Objects/oop/method/IMethod.cs b/ZSharp.Compiler.Objects/oop/method/IMethod.cs new file mode 100644 index 00000000..508d71e5 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/IMethod.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Objects +{ + public interface IMethod + : CompilerObject + , Compiler.INamedObject + { + } +} diff --git a/ZSharp.Compiler.Objects/oop/method/BoundMethod.cs b/ZSharp.Compiler.Objects/oop/method/concrete/BoundMethod.cs similarity index 100% rename from ZSharp.Compiler.Objects/oop/method/BoundMethod.cs rename to ZSharp.Compiler.Objects/oop/method/concrete/BoundMethod.cs diff --git a/ZSharp.Compiler.Objects/oop/method/Method.cs b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs similarity index 75% rename from ZSharp.Compiler.Objects/oop/method/Method.cs rename to ZSharp.Compiler.Objects/oop/method/concrete/Method.cs index 612693a3..50eec85d 100644 --- a/ZSharp.Compiler.Objects/oop/method/Method.cs +++ b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs @@ -11,10 +11,12 @@ namespace ZSharp.Objects public sealed class Method(string? name) : CompilerObject , IRTBoundMember + , IMethod , ICTCallable , ICompileIRObject , ICompileIRObject , ICompileIRReference + , IImplementation , IImplementsSpecification , IImplicitCastToType , IReferencable @@ -211,5 +213,53 @@ private void CompileDefinition(Compiler.Compiler compiler) IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); } } + + bool IImplementation.Implements(Compiler.Compiler compiler, CompilerObject specification, [NotNullWhen(true)] out IImplementsSpecification? implementation) + { + implementation = null; + + if (!compiler.TypeSystem.IsTyped(specification, out var specificationType) || specificationType is not ICallableType callableType) + return (implementation = null) is not null; + + if (Signature.Args.Count != callableType.Args.Count) return false; + if (Signature.KwArgs.Count != callableType.KwArgs.Count) return false; + + if ( + Signature.VarArgs is null && callableType.VarArgs is not null || + Signature.VarArgs is not null && callableType.VarArgs is null + ) + return false; + if ( + !(Signature.VarArgs is null && callableType.VarArgs is null) && + !compiler.TypeSystem.IsAssignableFrom(Signature.VarArgs!.Type!, callableType.VarArgs!) + ) + return false; + + if ( + Signature.VarKwArgs is null && callableType.VarKwArgs is not null || + Signature.VarKwArgs is not null && callableType.VarKwArgs is null + ) + return false; + if ( + !(Signature.VarKwArgs is null && callableType.VarKwArgs is null) && + !compiler.TypeSystem.IsAssignableFrom(Signature.VarKwArgs!.Type!, callableType.VarKwArgs!) + ) + return false; + + if (!compiler.TypeSystem.IsAssignableTo(ReturnType!, callableType.ReturnType)) + return false; + + foreach (var (left, right) in Signature.Args.Skip(1).Zip(callableType.Args.Skip(1))) + if (!compiler.TypeSystem.IsAssignableFrom(left.Type!, right)) + return false; + + foreach (var kwArg in Signature.KwArgs) + if (!callableType.KwArgs.TryGetValue(kwArg.Name, out var otherKwArgType)) + return false; + else if (!compiler.TypeSystem.IsAssignableFrom(kwArg.Type!, otherKwArgType)) + return false; + + return (implementation = this) is not null; + } } } diff --git a/ZSharp.Compiler.Objects/oop/method/MethodReference.cs b/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs similarity index 100% rename from ZSharp.Compiler.Objects/oop/method/MethodReference.cs rename to ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs diff --git a/ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs b/ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs new file mode 100644 index 00000000..f9908bb4 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs @@ -0,0 +1,19 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class BoundMethodOverloadGroup(MethodOverloadGroup group, CompilerObject instance) + : CompilerObject + , ICTCallable + { + public MethodOverloadGroup Group { get; } = group; + + public CompilerObject Instance { get; } = instance; + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + => compiler.Call(Group, [ + new(Instance), + .. arguments + ]); + } +} diff --git a/ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs b/ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs new file mode 100644 index 00000000..bb805c01 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs @@ -0,0 +1,30 @@ +using System.Diagnostics.CodeAnalysis; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class MethodOverloadGroup(string name) + : OverloadGroup(name) + , CompilerObject + , ICTCallable + , IImplementation + , IRTBoundMember + { + CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) + => new BoundMethodOverloadGroup(this, value); // TODO: check that the value is a valid instance + + bool IImplementation.Implements(Compiler.Compiler compiler, CompilerObject specification, [NotNullWhen(true)] out IImplementsSpecification? implementation) + { + List implementations = []; + + foreach (var method in Overloads) + if (method is IImplementation implements && implements.Implements(compiler, specification, out var methodImplementation)) + implementations.Add(methodImplementation); + + if (implementations.Count == 1) + return (implementation = implementations[0]) is not null; + + return (implementation = null) is not null; + } + } +} diff --git a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs index 8212587f..bbeb1dcd 100644 --- a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs +++ b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs @@ -3,16 +3,18 @@ namespace ZSharp.Objects { - public sealed class OverloadGroup(string name) + public abstract class OverloadGroup(string name) : CompilerObject , ICTCallable , IMappable + + where T : CompilerObject { public string Name { get; set; } = name; - public Collection Overloads { get; init; } = []; + public Collection Overloads { get; init; } = []; - public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) + public virtual CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) { var matchingOverloads = Overloads .Select(overload => { @@ -35,8 +37,18 @@ CompilerObject IMappable.Map(Func func) { return new OverloadGroup(Name) { - Overloads = [.. Overloads.Select(func).Where(item => item is not null)] + Overloads = [.. Overloads.Select(item => func(item)).Where(item => item is not null)] }; } } + + public sealed class OverloadGroup(string name) + : OverloadGroup(name) + , CompilerObject + , ICTCallable + , IMappable + { + + + } } diff --git a/ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs b/ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs index 7694db69..b3141ffb 100644 --- a/ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs +++ b/ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs @@ -3,7 +3,7 @@ namespace ZSharp.Objects { public sealed class AmbiguousOverloadException( - OverloadGroup group, + CompilerObject group, Argument[] arguments, CompilerObject[] overloads ) diff --git a/ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs b/ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs index e86bd36d..9d8c3eff 100644 --- a/ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs +++ b/ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs @@ -2,7 +2,7 @@ namespace ZSharp.Objects { - public sealed class NoOverloadFoundException(OverloadGroup group, Argument[] arguments) + public sealed class NoOverloadFoundException(CompilerObject group, Argument[] arguments) : OverloadException(group, arguments) { } diff --git a/ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs b/ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs index 6f9c35ab..91906ff6 100644 --- a/ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs +++ b/ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs @@ -2,9 +2,9 @@ namespace ZSharp.Objects { - public abstract class OverloadException(OverloadGroup group, Argument[] arguments) + public abstract class OverloadException(CompilerObject group, Argument[] arguments) : ArgumentMismatchException(group, arguments) { - public OverloadGroup Group { get; } = group; + //public OverloadGroup Group { get; } = group; } } diff --git a/ZSharp.Compiler.Objects/signature/ICallableType.cs b/ZSharp.Compiler.Objects/signature/ICallableType.cs index f48c7923..c1e85ae9 100644 --- a/ZSharp.Compiler.Objects/signature/ICallableType.cs +++ b/ZSharp.Compiler.Objects/signature/ICallableType.cs @@ -5,6 +5,7 @@ namespace ZSharp.Objects { public interface ICallableType : IType + , ITypeAssignableToType { public Collection Args { get; } @@ -16,6 +17,8 @@ public interface ICallableType public IType ReturnType { get; } + #region Protocols + bool IType.IsEqualTo(Compiler.Compiler compiler, IType type) { if (type is not ICallableType callableType) @@ -64,5 +67,53 @@ VarKwArgs is not null && callableType.VarKwArgs is null return true; } + + bool? ITypeAssignableToType.IsAssignableTo(Compiler.Compiler compiler, IType target) + { + if (target is not ICallableType callableType) + return null; + + if (Args.Count != callableType.Args.Count) return false; + if (KwArgs.Count != callableType.KwArgs.Count) return false; + + if ( + VarArgs is null && callableType.VarArgs is not null || + VarArgs is not null && callableType.VarArgs is null + ) + return false; + if ( + !(VarArgs is null && callableType.VarArgs is null) && + !compiler.TypeSystem.IsAssignableFrom(VarArgs!, callableType.VarArgs!) + ) + return false; + + if ( + VarKwArgs is null && callableType.VarKwArgs is not null || + VarKwArgs is not null && callableType.VarKwArgs is null + ) + return false; + if ( + !(VarKwArgs is null && callableType.VarKwArgs is null) && + !compiler.TypeSystem.IsAssignableFrom(VarKwArgs!, callableType.VarKwArgs!) + ) + return false; + + if (!compiler.TypeSystem.IsAssignableTo(ReturnType, callableType.ReturnType)) + return false; + + foreach (var (left, right) in Args.Zip(callableType.Args)) + if (!compiler.TypeSystem.IsAssignableFrom(left, right)) + return false; + + foreach (var (name, kwArgType) in KwArgs) + if (!callableType.KwArgs.TryGetValue(name, out var otherKwArgType)) + return false; + else if (!compiler.TypeSystem.IsAssignableFrom(kwArgType, otherKwArgType)) + return false; + + return true; + } + + #endregion } } diff --git a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Query.cs b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Query.cs new file mode 100644 index 00000000..cbfda958 --- /dev/null +++ b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Query.cs @@ -0,0 +1,16 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler +{ + public sealed partial class Compiler + { + public bool IsAnonymous(CompilerObject @object) + => (NameOf(@object) ?? string.Empty) == string.Empty; + + public string? NameOf(CompilerObject @object) + => @object is INamedObject named ? named.Name : null; + + public bool NameOf(CompilerObject @object, [NotNullWhen(true)] out string? name) + => (name = NameOf(@object)) is not null; + } +} diff --git a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs index 735bbaa7..71f0e833 100644 --- a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs +++ b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs @@ -75,7 +75,7 @@ public CompilerObjectResult ImplicitCast(CompilerObject value, IType type) if (result.IsOk) return result; - if (IsTyped(value, out var valueType) && (AreEqual(valueType, type) || IsAssignableTo(valueType, type))) + if (IsTyped(value, out var valueType) && IsAssignableTo(valueType, type)) result = CompilerObjectResult.Ok(value); return result; diff --git a/ZSharp.Compiler/core/concepts/INamedObject.cs b/ZSharp.Compiler/core/concepts/INamedObject.cs new file mode 100644 index 00000000..09aa2527 --- /dev/null +++ b/ZSharp.Compiler/core/concepts/INamedObject.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler +{ + public interface INamedObject + : CompilerObject + { + public string Name { get; } + + public bool IsAnonymous => Name == string.Empty; + } +} diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs index ba0a2eb9..7653f043 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs @@ -98,8 +98,8 @@ private Action Compile(AST.Function function) if (function.Name != string.Empty) { if (!Context.CurrentScope.Get(function.Name, out var result, lookupParent: false)) - Context.CurrentScope.Set(function.Name, result = new OverloadGroup(function.Name)); - if (result is not OverloadGroup group) + Context.CurrentScope.Set(function.Name, result = new MethodOverloadGroup(function.Name)); + if (result is not MethodOverloadGroup group) throw new(); group.Overloads.Add(compiler.Object); diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs index 39b5ee22..b1d5873b 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs @@ -53,6 +53,9 @@ public override Class Compile() private void ResolveImplementation(IAbstraction abstraction) { + if (Object is not IImplementsAbstraction implementsAbstraction) + throw new(); + Implementation? result = null; foreach (var implementationInfo in Object.InterfaceImplementations) if (implementationInfo.Abstract == abstraction) @@ -63,68 +66,7 @@ private void ResolveImplementation(IAbstraction abstraction) if (result is null) Object.InterfaceImplementations.Add(result = new(abstraction, Object)); - foreach (var specification in abstraction.Specifications) - if (result.Mapping.ContainsKey(specification)) - continue; - else if (ResolveImplementation(specification) is not CompilerObject implementation) - Compiler.LogError( - $"Class {Object.Name} does not implement member {specification} in {abstraction}", - Node - ); - else - { - result.Mapping.Add(specification, implementation); - if (implementation is IImplementsSpecification implementsSpecification) - implementsSpecification.OnImplementSpecification(Compiler.Compiler, abstraction, specification); - } - } - - private CompilerObject? ResolveImplementation(CompilerObject specification) - { - if (!Compiler.Compiler.TypeSystem.IsTyped(specification, out var specificationType)) - { - Compiler.LogError( - $"{specification} is an invalid specification object", - Node - ); - - return null; - } - - List possibleImplementations = []; - List errors = []; - - foreach (var item in Object.Content) - if (Compiler.Compiler.TypeSystem.ImplicitCast(item, specificationType).Ok(out var implementation)) - if (!Compiler.Compiler.TypeSystem.IsTyped(implementation, out var implementationType)) - errors.Add($"Member {implementation} cannot implemenet {specification} because it is not typed"); - else if (!Compiler.Compiler.TypeSystem.AreEqual(specificationType, implementationType)) - errors.Add($"Member {implementation} cannot implement {specification} because it is not equal"); - else possibleImplementations.Add(implementation); - - if (possibleImplementations.Count == 0) - { - Compiler.LogError( - string.Join( - "\n\t", [ - $"Class {Object.Name} does not implement member {specification} in {specificationType}", - .. errors - ] - ), - Node - ); - return null; - } - else if (possibleImplementations.Count > 1) - { - Compiler.LogError( - $"Class {Object.Name} has multiple implementations of {specification} in {specificationType}", - Node - ); - return null; - } - - return possibleImplementations[0]; + implementsAbstraction.ImplementAbstraction(Compiler.Compiler, abstraction, result); } } } diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs index 77e00b3b..13756bf9 100644 --- a/ZSharpTest/tests/simple.zs +++ b/ZSharpTest/tests/simple.zs @@ -6,30 +6,50 @@ module Program; class MyClass : TestInterface { new(this) {} - fun do(this: TestInterface): void { + fun do(this): void { print("Hello from MyClass"); return; } + + fun do(this, x: i32): i32 { + return x + 1; + } } class OtherClass : TestInterface { - new(this) {} + var x: i32; + + new(this, number: i32) { + this.x = number; + + } - fun do(this: TestInterface): void { + fun do(this): void { print("Hello from OtherClass"); return; } + + fun do(this, x: i32): i32 { + return x + this.x; + } } fun testInterface(test: TestInterface): void { + test.do(); + print(string(test.do(number))); return; } fun main(): void { - testInterface(MyClass()); - testInterface(OtherClass()); + let c1 = MyClass(); + let c2 = OtherClass(5); + + testInterface(c1); + testInterface(c2); return; } + +let number = 10; From b2f54a4c74d760422774a3d54bc67a619296a43b Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 10 May 2025 22:51:50 +0300 Subject: [PATCH 150/235] Fix many things Add support for custom compiler context Add support for generic methods (IL, IR and CO) Add scope context for source compiler Add partial call object Fix mess in signature objects (CO) Update simple.zs test file --- ZLoad.Test/TestClass.cs | 10 + .../ir loader/IRLoader.Impl.cs | 72 ++++--- .../ZSharp.Compiler.Objects.csproj | 4 - .../functional/PartialCall.cs | 21 -- .../functional/RTFunction.cs | 6 +- .../functional/partial call/PartialCall.cs | 119 +++++++++++ .../signature/KeywordVarParameter.cs | 18 -- .../functional/signature/Signature.cs | 28 +-- .../functional/signature/VarParameter.cs | 6 +- ZSharp.Compiler.Objects/oop/class/Class.cs | 7 + .../oop/method/MethodType.cs | 16 +- .../oop/method/concrete/Method.cs | 53 ++--- .../oop/method/concrete/MethodReference.cs | 7 +- .../oop/method/generic/BoundGenericMethod.cs | 42 ++++ .../generic/BoundGenericMethodInstance.cs | 16 ++ .../generic/BoundGenericMethodReference.cs | 16 ++ .../oop/method/generic/GenericMethod.cs | 189 +++++++++++++++++ .../method/generic/GenericMethodInstance.cs | 73 +++++++ .../generic/GenericMethodInstanceReference.cs | 6 + .../method/generic/GenericMethodReference.cs | 128 ++++++++++++ .../signature/IKeywordVarParameter.cs | 7 - .../signature/ISignature.cs | 87 -------- .../signature/IVarParameter.cs | 9 - .../signature/{ => abstract}/ICallableType.cs | 57 +++-- .../signature/{ => abstract}/IParameter.cs | 8 +- .../signature/abstract/ISignature.cs | 197 ++++++++++++++++++ .../signature/abstract/IVarParameter.cs | 13 ++ .../signature/stub/StubParameter.cs | 46 ++++ .../signature/stub/StubSignature.cs | 56 +++++ .../signature/stub/StubVarParameter.cs | 30 +++ .../typing/TypedUndefined.cs | 11 + .../compiler/Compiler.Context.cs | 20 ++ .../core/context/EmptyContext.cs | 12 ++ .../compiler core/core/context/IContext.cs | 64 ++++++ .../core/context/IContextChainStrategy.cs | 7 + .../strategies/ParentContextStrategy.cs | 8 + .../core/type system/TypeSystem.cs | 4 + .../core/concepts/callable/ICallable.cs | 2 + .../protocols/ICompileIRReference.cs | 2 +- ZSharp.IR/ir/oop/method/ConstructedMethod.cs | 14 ++ .../ir/oop/method/GenericMethodInstance.cs | 11 - ZSharp.IR/ir/oop/method/Method.cs | 20 +- .../il2ir/loaders/ClassLoader.cs | 9 + ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 28 ++- .../class body/ClassBodyCompiler.cs | 16 +- .../context/Context.Scopes.cs | 41 ++-- ZSharp.ZSSourceCompiler/context/Context.cs | 6 +- .../context/scoping/Constraint.cs | 7 - .../context/scoping/Scope.cs | 77 ------- .../context/scoping/ScopeParent.cs | 11 - .../contexts/capabilities/IScopeContext.cs | 21 ++ .../contexts/concrete/ScopeContext.cs | 32 +++ .../expression/ExpressionCompiler.cs | 19 +- ZSharpTest/tests/simple.zs | 12 +- 54 files changed, 1374 insertions(+), 427 deletions(-) create mode 100644 ZLoad.Test/TestClass.cs delete mode 100644 ZSharp.Compiler.Objects/functional/PartialCall.cs create mode 100644 ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs delete mode 100644 ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs create mode 100644 ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs create mode 100644 ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs create mode 100644 ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs create mode 100644 ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs create mode 100644 ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs create mode 100644 ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstanceReference.cs create mode 100644 ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs delete mode 100644 ZSharp.Compiler.Objects/signature/IKeywordVarParameter.cs delete mode 100644 ZSharp.Compiler.Objects/signature/ISignature.cs delete mode 100644 ZSharp.Compiler.Objects/signature/IVarParameter.cs rename ZSharp.Compiler.Objects/signature/{ => abstract}/ICallableType.cs (63%) rename ZSharp.Compiler.Objects/signature/{ => abstract}/IParameter.cs (61%) create mode 100644 ZSharp.Compiler.Objects/signature/abstract/ISignature.cs create mode 100644 ZSharp.Compiler.Objects/signature/abstract/IVarParameter.cs create mode 100644 ZSharp.Compiler.Objects/signature/stub/StubParameter.cs create mode 100644 ZSharp.Compiler.Objects/signature/stub/StubSignature.cs create mode 100644 ZSharp.Compiler.Objects/signature/stub/StubVarParameter.cs create mode 100644 ZSharp.Compiler.Objects/typing/TypedUndefined.cs create mode 100644 ZSharp.Compiler/compiler core/compiler/Compiler.Context.cs create mode 100644 ZSharp.Compiler/compiler core/core/context/EmptyContext.cs create mode 100644 ZSharp.Compiler/compiler core/core/context/IContext.cs create mode 100644 ZSharp.Compiler/compiler core/core/context/IContextChainStrategy.cs create mode 100644 ZSharp.Compiler/compiler core/core/context/strategies/ParentContextStrategy.cs create mode 100644 ZSharp.IR/ir/oop/method/ConstructedMethod.cs delete mode 100644 ZSharp.IR/ir/oop/method/GenericMethodInstance.cs delete mode 100644 ZSharp.ZSSourceCompiler/context/scoping/Constraint.cs delete mode 100644 ZSharp.ZSSourceCompiler/context/scoping/Scope.cs delete mode 100644 ZSharp.ZSSourceCompiler/context/scoping/ScopeParent.cs create mode 100644 ZSharp.ZSSourceCompiler/contexts/capabilities/IScopeContext.cs create mode 100644 ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs diff --git a/ZLoad.Test/TestClass.cs b/ZLoad.Test/TestClass.cs new file mode 100644 index 00000000..ee1d4789 --- /dev/null +++ b/ZLoad.Test/TestClass.cs @@ -0,0 +1,10 @@ +using ZSharp.Runtime.NET.IL2IR; + +namespace ZLoad.Test +{ + public class TestClass + { + [Alias(Name = "id")] + public T Id(T v) => v; + } +} diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index f23d30df..814271b6 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -173,27 +173,55 @@ private Action Load(IR.Class @class, Module owner) if (@class.Methods.Count > 0) foreach (var method in @class.Methods) { - Method resultMethod = new(method.Name) + CompilerObject resultMethod; + if (method.HasGenericParameters) + resultMethod = LoadGenericMethod(method, result); + else { - IR = method, - Defined = true, - }; - if (resultMethod.Name is not null && resultMethod.Name != string.Empty) + resultMethod = new Method(method.Name) + { + IR = method, + Defined = true, + Signature = Load(method.Signature) + }; + } + if (method.Name is not null && method.Name != string.Empty) { - if (!result.Members.TryGetValue(resultMethod.Name, out var group)) - result.Members.Add(resultMethod.Name, group = new OverloadGroup(resultMethod.Name)); + if (!result.Members.TryGetValue(method.Name, out var group)) + result.Members.Add(method.Name, group = new OverloadGroup(method.Name)); if (group is not OverloadGroup overloadGroup) throw new InvalidOperationException(); overloadGroup.Overloads.Add(resultMethod); } - resultMethod.Signature = Load(method.Signature); - resultMethod.ReturnType = Load(method.ReturnType); } }; } + private GenericMethod LoadGenericMethod(IR.Method method, CompilerObject owner) + { + GenericMethod result = new(method.Name) + { + Defined = true, + IR = method, + Owner = owner + }; + + foreach (var genericParameter in method.GenericParameters) + result.GenericParameters.Add( + Context.Types.Cache(genericParameter, new GenericParameter() + { + IR = genericParameter, + Name = genericParameter.Name + }) + ); + + result.Signature = Load(method.Signature); + + return result; + } + private Action Load(IR.Interface @interface, Module owner) { Interface result = new(@interface.Name) @@ -264,12 +292,16 @@ private IType Load(IR.IType type) return type switch { + IR.ClassReference classReference => Load(classReference), IR.ConstructedClass constructedClass => Load(constructedClass), IR.InterfaceReference interfaceReference => Load(interfaceReference), _ => null! }; } + private IType Load(IR.ClassReference classReference) + => Context.Objects.Cache(classReference.Definition) ?? throw new(); + private IType Load(IR.ConstructedClass constructed) { @@ -453,15 +485,16 @@ private Action LoadGenericFunction(IR.Function function, Module owner) result.GenericParameters.Add(genericParameter); } - result.Signature = Load(function.Signature); - - result.ReturnType = Load(function.ReturnType); + result.Signature = Load(function.Signature); }; } private Signature Load(IR.Signature signature) { - Signature result = new(); + Signature result = new() + { + ReturnType = Load(signature.ReturnType) + }; if (signature.HasArgs) foreach (var arg in signature.Args.Parameters) @@ -475,7 +508,7 @@ private Signature Load(IR.Signature signature) result.KwArgs.Add(LoadParameter(arg)); if (signature.IsVarKwArgs) - result.VarKwArgs = LoadKeywordVarParameter(signature.KwArgs.Var!); + result.VarKwArgs = LoadVarParameter(signature.KwArgs.Var!); return result; } @@ -508,16 +541,5 @@ private VarParameter LoadVarParameter(IR.Parameter parameter) Type = type, }; } - - private KeywordVarParameter LoadKeywordVarParameter(IR.Parameter parameter) - { - var type = Load(parameter.Type); - - return new(parameter.Name) - { - IR = parameter, - Type = type, - }; - } } } diff --git a/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj b/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj index 54159963..9f6c481e 100644 --- a/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj +++ b/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj @@ -12,8 +12,4 @@ - - - - diff --git a/ZSharp.Compiler.Objects/functional/PartialCall.cs b/ZSharp.Compiler.Objects/functional/PartialCall.cs deleted file mode 100644 index 92908c3d..00000000 --- a/ZSharp.Compiler.Objects/functional/PartialCall.cs +++ /dev/null @@ -1,21 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class PartialCall(CompilerObject target) - : CompilerObject - , ICTCallable - { - public CompilerObject Target { get; set; } = target; - - public Argument[] Arguments { get; set; } = []; - - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) - { - return compiler.Call(Target, [ - .. Arguments, - .. arguments - ]); - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/RTFunction.cs b/ZSharp.Compiler.Objects/functional/RTFunction.cs index 38f8f17b..c419d23c 100644 --- a/ZSharp.Compiler.Objects/functional/RTFunction.cs +++ b/ZSharp.Compiler.Objects/functional/RTFunction.cs @@ -41,7 +41,11 @@ public bool IsDefined public Signature Signature { get; set; } = new(); - public IType? ReturnType { get; set; } + public IType? ReturnType + { + get => Signature.ReturnType; + set => Signature.ReturnType = value; + } CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { diff --git a/ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs b/ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs new file mode 100644 index 00000000..de5e07c5 --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs @@ -0,0 +1,119 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class PartialCall(CompilerObject target) + : CompilerObject + , ICTCallable + { + public CompilerObject Target { get; set; } = target; + + public Argument[] Arguments { get; set; } = []; + + public required ISignature Signature { get; set; } + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + return compiler.Call(Target, [ + .. Arguments, + .. arguments + ]); + } + + public static PartialCall CreateFrom(Compiler.Compiler compiler, CompilerObject target, ISignature signature, Argument[] arguments) + => new(target) + { + Signature = ApplyArguments(compiler, signature, arguments), + Arguments = arguments + }; + + private static Signature ApplyArguments(Compiler.Compiler compiler, ISignature origin, Argument[] arguments) + { + var (args, kwArgs) = Utils.SplitArguments(arguments); + + return ApplyArguments(compiler, origin, args, kwArgs); + } + + private static Signature ApplyArguments(Compiler.Compiler compiler, ISignature origin, Collection args, Mapping kwArgs) + { + if (args.Count > origin.Args.Count() && origin.VarArgs is null) + throw new ArgumentsCountMismatchException(); + + if (kwArgs.Count > origin.KwArgs.Count() && origin.VarKwArgs is null) + throw new ArgumentsCountMismatchException(); + + List varArgs = []; + if (args.Count > origin.Args.Count()) + varArgs.AddRange(args.Skip(origin.Args.Count())); + args = [.. args.Take(origin.Args.Count())]; + + Signature result = new() + { + ReturnType = origin.ReturnType, + }; + + foreach (var (arg, param) in args.Zip(origin.Args)) + if (!compiler.TypeSystem.IsTyped(arg, out var argumentType)) + throw new ArgumentException("Argument is not typed."); + else if (!compiler.TypeSystem.IsAssignableTo(argumentType, param.Type ?? throw new())) + throw new Compiler.InvalidCastException(arg, param.Type); + + foreach (var param in origin.Args.Skip(args.Count)) + result.Args.Add(new(param.Name) + { + Default = param.Default, + //Initializer = param.Initializer, + Type = param.Type, + }); + + foreach (var varArg in varArgs) + if ( + !compiler.TypeSystem.IsTyped(varArg, out var argumentType) || + !compiler.TypeSystem.IsAssignableTo(argumentType, origin.VarArgs!.Type ?? throw new()) + ) + throw new Compiler.InvalidCastException(varArg, origin.VarArgs!.Type!); + + if (origin.VarArgs is not null) + result.VarArgs = new(origin.VarArgs.Name) + { + Type = origin.VarArgs.Type, + }; + + foreach (var param in origin.KwArgs) + { + if (!kwArgs.Remove(param.Name, out var arg)) + { + result.KwArgs.Add(new(param.Name) + { + Default = param.Default, + //Initializer = param.Initializer, + Type = param.Type, + }); + continue; + } + + if ( + !compiler.TypeSystem.IsTyped(arg, out var argumentType) || + !compiler.TypeSystem.IsAssignableTo(argumentType, param.Type ?? throw new()) + ) + throw new Compiler.InvalidCastException(arg, param.Type!); + } + + foreach (var varKwArg in kwArgs.Values) + if ( + !compiler.TypeSystem.IsTyped(varKwArg, out var argumentType) || + !compiler.TypeSystem.IsAssignableTo(argumentType, origin.VarKwArgs!.Type ?? throw new()) + ) + throw new Compiler.InvalidCastException(varKwArg, origin.VarKwArgs!.Type!); + + if (origin.VarKwArgs is not null) + result.VarKwArgs = new(origin.VarKwArgs.Name) + { + Type = origin.VarKwArgs.Type, + }; + + return result; + } + } +} diff --git a/ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs b/ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs deleted file mode 100644 index 6b5c2cb0..00000000 --- a/ZSharp.Compiler.Objects/functional/signature/KeywordVarParameter.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace ZSharp.Objects -{ - public sealed class KeywordVarParameter(string name) - : CompilerObject - , IKeywordVarParameter - { - public string Name { get; set; } = name; - - public IR.Parameter? IR { get; set; } - - public Compiler.IType? Type { get; set; } - - CompilerObject IKeywordVarParameter.MatchArguments(Compiler.Compiler compiler, Dictionary argument) - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/signature/Signature.cs b/ZSharp.Compiler.Objects/functional/signature/Signature.cs index ba8f42b5..6b27249d 100644 --- a/ZSharp.Compiler.Objects/functional/signature/Signature.cs +++ b/ZSharp.Compiler.Objects/functional/signature/Signature.cs @@ -17,7 +17,19 @@ public sealed class Signature public Parameters KwArgs { get; init; } = []; - public KeywordVarParameter? VarKwArgs { get; set; } + public VarParameter? VarKwArgs { get; set; } + + public IType? ReturnType { get; set; } + + IEnumerable ISignature.Args => Args; + + IVarParameter? ISignature.VarArgs => VarArgs; + + IEnumerable ISignature.KwArgs => KwArgs; + + IVarParameter? ISignature.VarKwArgs => VarKwArgs; + + IType ISignature.ReturnType => ReturnType ?? throw new(); IR.Signature ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Signature? owner) { @@ -55,21 +67,9 @@ Signature IReferencable.CreateReference(Referencing @ref, ReferenceCo result.KwArgs.AddRange(KwArgs.Select(arg => @ref.CreateReference(arg, context))); if (VarKwArgs is not null) - result.VarKwArgs = @ref.CreateReference(VarKwArgs, context); + result.VarKwArgs = @ref.CreateReference(VarKwArgs, context); return result; } - - IEnumerable? ISignature.GetArgs(Compiler.Compiler compiler) - => Args; - - IEnumerable? ISignature.GetKwArgs(Compiler.Compiler compiler) - => KwArgs; - - IVarParameter? ISignature.GetVarArgs(Compiler.Compiler compiler) - => VarArgs; - - IKeywordVarParameter? ISignature.GetVarKwArgs(Compiler.Compiler compiler) - => VarKwArgs; } } diff --git a/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs b/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs index d5cc4b74..af630742 100644 --- a/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs +++ b/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs @@ -1,4 +1,6 @@ -namespace ZSharp.Objects +using CommonZ.Utils; + +namespace ZSharp.Objects { public sealed class VarParameter(string name) : CompilerObject @@ -10,7 +12,7 @@ public sealed class VarParameter(string name) public Compiler.IType? Type { get; set; } - CompilerObject IVarParameter.MatchArguments(Compiler.Compiler compiler, CompilerObject[] argument) + CompilerObject IVarParameter.MatchArguments(Compiler.Compiler compiler, Collection arguments) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.Objects/oop/class/Class.cs b/ZSharp.Compiler.Objects/oop/class/Class.cs index 6d5d87a6..5ef0ca67 100644 --- a/ZSharp.Compiler.Objects/oop/class/Class.cs +++ b/ZSharp.Compiler.Objects/oop/class/Class.cs @@ -6,6 +6,7 @@ namespace ZSharp.Objects public sealed class Class : CompilerObject , ICompileIRObject + , ICompileIRReference , ICompileIRType> , ICTCallable , ICTGetMember @@ -120,6 +121,12 @@ CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerO return new IR.ClassReference(compiler.CompileIRObject(this, null)); } + IR.ClassReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + { + return new IR.ClassReference(compiler.CompileIRObject(this, null)); + } + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { if (Constructor is null) diff --git a/ZSharp.Compiler.Objects/oop/method/MethodType.cs b/ZSharp.Compiler.Objects/oop/method/MethodType.cs index 33c81da0..fd9281c9 100644 --- a/ZSharp.Compiler.Objects/oop/method/MethodType.cs +++ b/ZSharp.Compiler.Objects/oop/method/MethodType.cs @@ -5,22 +5,18 @@ namespace ZSharp.Objects { public sealed class MethodType(Signature signature, IType returnType) : CompilerObject - , ICallableType + , ISignature { public Signature Signature { get; } = signature; - Collection ICallableType.Args => [.. Signature.Args.Select(p => p.Type ?? throw new InvalidOperationException())]; + IEnumerable ISignature.Args => Signature.Args; - IType? ICallableType.VarArgs => Signature.VarArgs?.Type; + IVarParameter? ISignature.VarArgs => Signature.VarArgs; - Mapping ICallableType.KwArgs => new(Signature.KwArgs - .ToDictionary( - p => p.Name, - p => p.Type ?? throw new InvalidOperationException() - )); + IEnumerable ISignature.KwArgs => Signature.KwArgs; - IType? ICallableType.VarKwArgs => Signature.VarKwArgs?.Type; + IVarParameter? ISignature.VarKwArgs => Signature.VarKwArgs; - IType ICallableType.ReturnType { get; } = returnType; + IType ISignature.ReturnType => Signature.ReturnType; } } diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs index 50eec85d..fa9f8c08 100644 --- a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs +++ b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs @@ -32,7 +32,6 @@ enum BuildState } private readonly ObjectBuildState state = new(); - private bool isVirtual; public bool Defined { init { @@ -48,7 +47,11 @@ public bool Defined { init public Signature Signature { get; set; } = new(); - public IType? ReturnType { get; set; } + public IType? ReturnType + { + get => Signature.ReturnType; + set => Signature.ReturnType = value; + } public CompilerObject? Body { get; set; } @@ -158,7 +161,7 @@ public override string ToString() CompilerObject IImplicitCastToType.ImplicitCastToType(Compiler.Compiler compiler, IType type) { - if (type is not ICallableType callableType) + if (type is not ISignature callableType) throw new Compiler.InvalidCastException(this, type); throw new Compiler.InvalidCastException(this, type); @@ -218,48 +221,18 @@ bool IImplementation.Implements(Compiler.Compiler compiler, CompilerObject speci { implementation = null; - if (!compiler.TypeSystem.IsTyped(specification, out var specificationType) || specificationType is not ICallableType callableType) + if (!compiler.TypeSystem.IsTyped(specification, out var specificationType)) return (implementation = null) is not null; - if (Signature.Args.Count != callableType.Args.Count) return false; - if (Signature.KwArgs.Count != callableType.KwArgs.Count) return false; - - if ( - Signature.VarArgs is null && callableType.VarArgs is not null || - Signature.VarArgs is not null && callableType.VarArgs is null - ) - return false; - if ( - !(Signature.VarArgs is null && callableType.VarArgs is null) && - !compiler.TypeSystem.IsAssignableFrom(Signature.VarArgs!.Type!, callableType.VarArgs!) - ) - return false; - - if ( - Signature.VarKwArgs is null && callableType.VarKwArgs is not null || - Signature.VarKwArgs is not null && callableType.VarKwArgs is null - ) - return false; - if ( - !(Signature.VarKwArgs is null && callableType.VarKwArgs is null) && - !compiler.TypeSystem.IsAssignableFrom(Signature.VarKwArgs!.Type!, callableType.VarKwArgs!) - ) - return false; + var args = (Argument[])[new Argument(new TypedUndefined(Signature.Args[0].Type ?? throw new()))]; // TODO: owner + var specificationPartial = PartialCall.CreateFrom(compiler, specification, specificationType, args); + var implementationPartial = PartialCall.CreateFrom(compiler, this, Signature, args); - if (!compiler.TypeSystem.IsAssignableTo(ReturnType!, callableType.ReturnType)) + if (!compiler.TypeSystem.AreEqual(specificationPartial.Signature, implementationPartial.Signature)) return false; - foreach (var (left, right) in Signature.Args.Skip(1).Zip(callableType.Args.Skip(1))) - if (!compiler.TypeSystem.IsAssignableFrom(left.Type!, right)) - return false; - - foreach (var kwArg in Signature.KwArgs) - if (!callableType.KwArgs.TryGetValue(kwArg.Name, out var otherKwArgType)) - return false; - else if (!compiler.TypeSystem.IsAssignableFrom(kwArg.Type!, otherKwArgType)) - return false; - - return (implementation = this) is not null; + implementation = this; + return true; } } } diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs b/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs index a128651d..ef85feba 100644 --- a/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs +++ b/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs @@ -69,12 +69,7 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments } CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) - { - return new PartialCall(this) - { - Arguments = [new(value)] - }; - } + => PartialCall.CreateFrom(compiler, this, Signature, [new(value)]); private IR.Signature CompileSignature(Compiler.Compiler compiler) { diff --git a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs new file mode 100644 index 00000000..ee455088 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs @@ -0,0 +1,42 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class BoundGenericMethod(GenericMethod method, CompilerObject instance) + : CompilerObject + , ICTCallable + , ICTGetIndex + , IReferencable + { + public GenericMethod Method { get; } = method; + + public CompilerObject Instance { get; } = instance; + + public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) + => compiler.Call(Method, [new(Instance), .. arguments]); + + #region Index + + CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) + { + var context = new ReferenceContext(); + + foreach (var (genericParameter, genericArgument) in Method.GenericParameters.Zip(index)) + context[genericParameter] = genericArgument.Object; + + return compiler.Feature().CreateReference(this, context); + } + + #endregion + + #region Reference + + BoundGenericMethodInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + => new( + @ref.CreateReference(Method, context), + Instance + ); + + #endregion + } +} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs new file mode 100644 index 00000000..b74dc67c --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs @@ -0,0 +1,16 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class BoundGenericMethodInstance(GenericMethodInstance method, CompilerObject instance) + : CompilerObject + , ICTCallable + { + public GenericMethodInstance Method { get; } = method; + + public CompilerObject Instance { get; } = instance; + + public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) + => compiler.Call(Method, [new(Instance), .. arguments]); + } +} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs new file mode 100644 index 00000000..9f17c721 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs @@ -0,0 +1,16 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class BoundGenericMethodReference(GenericMethodReference method, CompilerObject instance) + : CompilerObject + , ICTCallable + { + public GenericMethodReference Method { get; } = method; + + public CompilerObject Instance { get; } = instance; + + public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) + => compiler.Call(Method, [new(Instance), .. arguments]); + } +} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs new file mode 100644 index 00000000..e5340037 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs @@ -0,0 +1,189 @@ +using CommonZ.Utils; +using System.Diagnostics.CodeAnalysis; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class GenericMethod(string? name) + : CompilerObject + , ICompileIRObject + , ICompileIRObject + , ICTGetIndex + , INamedObject + , IReferencable + , IRTBoundMember + { + #region Build State + + [Flags] + enum BuildState + { + None = 0, + Signature = 0b1, + Body = 0b10, + Owner = 0b100, + Generic = 0b1000, + } + + private readonly ObjectBuildState state = new(); + + public bool Defined + { + init + { + if (value) + foreach (var item in Enum.GetValues()) + state[item] = true; + } + } + + #endregion + + #region Definition + + public string Name { get; set; } = name ?? string.Empty; + + public Collection GenericParameters { get; set; } = []; + + public Signature Signature { get; set; } = new(); + + public CompilerObject? Owner { get; set; } + + public IType? ReturnType + { + get => Signature.ReturnType; + set => Signature.ReturnType = value; + } + + public CompilerObject? Body { get; set; } + + #endregion + + #region IR + + public IR.Method? IR { get; set; } + + IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) + => CompileIR(compiler); + + IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) + { + CompileIR(compiler); + + if (owner is not null && !state[BuildState.Owner]) + { + state[BuildState.Owner] = true; + + owner.Methods.Add(IR); + } + + CompileDefinition(compiler); + + return IR; + } + + IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.OOPType? owner) + { + CompileIR(compiler); + + CompileDefinition(compiler); + + return IR; + } + + [MemberNotNull(nameof(IR))] + private IR.Method CompileIR(Compiler.Compiler compiler) + { + return IR ??= + new( + compiler.CompileIRType( + ReturnType ?? throw new PartiallyCompiledObjectException( + this, + Errors.UndefinedReturnType(Name) + ) + ) + ) + { + Name = Name + }; + } + + private void CompileDefinition(Compiler.Compiler compiler) + { + if (IR is null) + throw new InvalidOperationException(); + + if (!state[BuildState.Generic]) + { + state[BuildState.Generic] = true; + + foreach (var genericParameter in GenericParameters) + IR.GenericParameters.Add( + compiler.CompileIRType(genericParameter) + ); + } + + if (!state[BuildState.Signature]) + { + state[BuildState.Signature] = true; + + compiler.CompileIRObject(Signature, IR.Signature); + } + + if (Body is not null && !state[BuildState.Body]) + { + state[BuildState.Body] = true; + + IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); + } + } + + #endregion + + #region Index + + CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) + { + var context = new ReferenceContext(); + + foreach (var (genericParameter, genericArgument) in GenericParameters.Zip(index)) + context[genericParameter] = genericArgument.Object; + + return compiler.Feature().CreateReference(this, context); + } + + #endregion + + #region Reference + + GenericMethodInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + { + int currentErrors = @ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error); + + foreach (var genericParameter in GenericParameters) + if (!context.CompileTimeValues.Contains(genericParameter)) + @ref.Compiler.Log.Error( + $"Missing generic argument for parameter {genericParameter.Name} in type {Name}", + this + ); + + if (@ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error) > currentErrors) + throw new(); // TODO: Huh??? + + return new GenericMethodInstance(this) + { + Context = new(context) + { + Scope = this + }, + Signature = @ref.CreateReference(Signature, context), + Owner = Owner ?? Signature.Args.First()?.Type ?? throw new() + }; + } + + CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) + => new BoundGenericMethod(this, value); + + #endregion + } +} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs new file mode 100644 index 00000000..7b95669c --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs @@ -0,0 +1,73 @@ +using ZSharp.Compiler; +namespace ZSharp.Objects +{ + public sealed class GenericMethodInstance(GenericMethod origin) + : CompilerObject + , ICTCallable + , ICompileIRReference + , IRTBoundMember + { + public GenericMethod Origin { get; } = origin; + + public required ReferenceContext Context { get; init; } + + public required CompilerObject Owner { get; init; } + + public required Signature Signature { get; init; } + + CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) + => new BoundGenericMethodInstance(this, value); + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + if (Origin.ReturnType is null) + throw new NotImplementedException(); + + var args = (Signature as ISignature).MatchArguments(compiler, arguments); + + IRCode code = new(); + + List @params = []; + + @params.AddRange(Signature.Args); + + if (Signature.VarArgs is not null) + @params.Add(Signature.VarArgs); + + @params.AddRange(Signature.KwArgs); + + if (Signature.VarKwArgs is not null) + @params.Add(Signature.VarKwArgs); + + foreach (var param in @params) + code.Append(compiler.CompileIRCode(args[param])); + + code.Append(new([ + new IR.VM.Call(compiler.CompileIRReference(this)) + ])); + + code.Types.Clear(); + if (Origin.ReturnType != compiler.TypeSystem.Void) + code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); + + return new RawCode(code); + } + + IR.ConstructedMethod ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + { + var result = new IR.ConstructedMethod( + compiler.CompileIRObject(Origin, null) + ) + { + OwningType = compiler.CompileIRReference(Owner) + }; + + foreach (var genericParameter in Origin.GenericParameters) + result.Arguments.Add( + compiler.CompileIRType(Context.CompileTimeValues.Cache(genericParameter) ?? throw new()) + ); + + return result; + } + } +} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstanceReference.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstanceReference.cs new file mode 100644 index 00000000..38b3d264 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstanceReference.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Objects +{ + public sealed class GenericMethodInstanceReference + { + } +} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs new file mode 100644 index 00000000..96ccc805 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs @@ -0,0 +1,128 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class GenericMethodReference( + GenericMethod origin, + ReferenceContext context + ) + : CompilerObject + , ICTCallable + , ICompileIRReference + , IReferencable + , IRTBoundMember + { + public GenericMethod Origin { get; } = origin; + + public ReferenceContext Context { get; } = context; + + public required CompilerObject Owner { get; init; } + + public required Signature Signature { get; init; } + + public IR.Signature? SignatureIR { get; private set; } + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + if (Origin.ReturnType is null) + throw new NotImplementedException(); + + var args = (Signature as ISignature).MatchArguments(compiler, arguments); + + IRCode code = new(); + + List @params = []; + + @params.AddRange(Signature.Args); + + if (Signature.VarArgs is not null) + @params.Add(Signature.VarArgs); + + @params.AddRange(Signature.KwArgs); + + if (Signature.VarKwArgs is not null) + @params.Add(Signature.VarKwArgs); + + foreach (var param in @params) + code.Append(compiler.CompileIRCode(args[param])); + + code.Append(new([ + new IR.VM.Call(compiler.CompileIRReference(this)) + ])); + + code.Types.Clear(); + if (Origin.ReturnType != compiler.TypeSystem.Void) + code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); + + return new RawCode(code); + } + + IR.MethodReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + { + var type = compiler.Feature().CreateReference(Owner, Context); + + return new IR.MethodReference(compiler.CompileIRObject(Origin, null!)) + { + OwningType = compiler.CompileIRReference(type), + Signature = SignatureIR ?? CompileSignature(compiler) + }; + } + + CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) + => new BoundGenericMethodReference(this, value); + + private IR.Signature CompileSignature(Compiler.Compiler compiler) + { + if (SignatureIR is not null) + return SignatureIR; + + if (Origin.ReturnType is null) + throw new NotImplementedException(); + + SignatureIR = new(compiler.CompileIRType(compiler.Feature().CreateReference(Origin.ReturnType, Context))); + + foreach (var arg in Signature.Args) + SignatureIR.Args.Parameters.Add(compiler.CompileIRObject(arg, SignatureIR)); + + if (Signature.VarArgs is not null) + SignatureIR.Args.Var = compiler.CompileIRObject(Signature.VarArgs, SignatureIR); + + foreach (var kwArg in Signature.KwArgs) + SignatureIR.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, SignatureIR)); + + if (Signature.VarKwArgs is not null) + SignatureIR.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, SignatureIR); + + return SignatureIR; + } + + #region Reference + + GenericMethodInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + { + int currentErrors = @ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error); + + foreach (var genericParameter in Origin.GenericParameters) + if (!context.CompileTimeValues.Contains(genericParameter)) + @ref.Compiler.Log.Error( + $"Missing generic argument for parameter {genericParameter.Name} in type {Origin.Name}", + this + ); + + if (@ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error) > currentErrors) + throw new(); // TODO: Huh??? + + return new GenericMethodInstance(Origin) + { + Context = new(context) + { + Scope = this + }, + Signature = @ref.CreateReference(Signature, context), + Owner = Owner ?? Signature.Args.First()?.Type ?? throw new() + }; + } + + #endregion + } +} diff --git a/ZSharp.Compiler.Objects/signature/IKeywordVarParameter.cs b/ZSharp.Compiler.Objects/signature/IKeywordVarParameter.cs deleted file mode 100644 index 44bc39a9..00000000 --- a/ZSharp.Compiler.Objects/signature/IKeywordVarParameter.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IKeywordVarParameter : CompilerObject - { - public CompilerObject MatchArguments(Compiler.Compiler compiler, Dictionary argument); - } -} diff --git a/ZSharp.Compiler.Objects/signature/ISignature.cs b/ZSharp.Compiler.Objects/signature/ISignature.cs deleted file mode 100644 index 30852156..00000000 --- a/ZSharp.Compiler.Objects/signature/ISignature.cs +++ /dev/null @@ -1,87 +0,0 @@ -using CommonZ.Utils; - -using Args = CommonZ.Utils.Collection; -using KwArgs = CommonZ.Utils.Mapping; - - -namespace ZSharp.Objects -{ - public interface ISignature : CompilerObject - { - public IEnumerable? GetArgs(Compiler.Compiler compiler); - - public IVarParameter? GetVarArgs(Compiler.Compiler compiler); - - public IEnumerable? GetKwArgs(Compiler.Compiler compiler); - - public IKeywordVarParameter? GetVarKwArgs(Compiler.Compiler compiler); - - public Mapping MatchArguments(Compiler.Compiler compiler, Compiler.Argument[] arguments) - { - var (args, kwArgs) = Utils.SplitArguments(arguments); - - try - { - return MatchArguments(compiler, args, kwArgs); - } catch (ArgumentsCountMismatchException argumentsCountMismatch) - { - throw new ArgumentMismatchException(this, arguments, innerException: argumentsCountMismatch); - } catch (Compiler.InvalidCastException invalidCast) - { - throw new ArgumentMismatchException(this, arguments, innerException: invalidCast); - } - } - - public Mapping MatchArguments(Compiler.Compiler compiler, Args args, KwArgs kwArgs) - { - var @params = GetArgs(compiler)?.ToList() ?? []; - var varParams = GetVarArgs(compiler); - var kwParams = GetKwArgs(compiler)?.ToList() ?? []; - var varKwParams = GetVarKwArgs(compiler); - - if (args.Count > @params.Count && varParams is null) - throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}."); - - if (kwArgs.Count > kwParams.Count && varKwParams is null) - throw new ArgumentsCountMismatchException($"Expected {kwParams.Count} named arguments but got {kwArgs.Count}."); - - Mapping result = []; - - var positionalArgumentsQueue = new Queue(args); - - foreach (var param in @params) - { - if (!positionalArgumentsQueue.TryDequeue(out var arg)) - arg = param.Default ?? throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); - - if (param.MatchArgument(compiler, arg).Ok(out var argumentResult)) - result[param] = argumentResult; - else throw new Compiler.InvalidCastException(arg, null!); - } - - if (varParams is not null) - result[varParams] = varParams.MatchArguments(compiler, [.. positionalArgumentsQueue]); - else if (positionalArgumentsQueue.Count > 0) - throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); - - var keywordArguments = kwArgs.ToDictionary(); - - foreach (var kwParam in kwParams) - { - if (!kwArgs.TryGetValue(kwParam.Name, out var kwArg)) - kwArg = kwParam.Default ?? throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); - else - keywordArguments.Remove(kwParam.Name); - - result[kwParam] = kwArg; - } - - if (varKwParams is not null) - result[varKwParams] = varKwParams.MatchArguments(compiler, keywordArguments); - else if (keywordArguments.Count > 0) - throw new ArgumentsCountMismatchException($"Expected {@params.Count} named arguments but got {args.Count}"); - - return result; - } - } -} diff --git a/ZSharp.Compiler.Objects/signature/IVarParameter.cs b/ZSharp.Compiler.Objects/signature/IVarParameter.cs deleted file mode 100644 index 8cc7776a..00000000 --- a/ZSharp.Compiler.Objects/signature/IVarParameter.cs +++ /dev/null @@ -1,9 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Objects -{ - public interface IVarParameter : CompilerObject - { - public CompilerObject MatchArguments(Compiler.Compiler compiler, CompilerObject[] argument); - } -} diff --git a/ZSharp.Compiler.Objects/signature/ICallableType.cs b/ZSharp.Compiler.Objects/signature/abstract/ICallableType.cs similarity index 63% rename from ZSharp.Compiler.Objects/signature/ICallableType.cs rename to ZSharp.Compiler.Objects/signature/abstract/ICallableType.cs index c1e85ae9..6f2daa61 100644 --- a/ZSharp.Compiler.Objects/signature/ICallableType.cs +++ b/ZSharp.Compiler.Objects/signature/abstract/ICallableType.cs @@ -1,30 +1,22 @@ -using CommonZ.Utils; -using ZSharp.Compiler; +using ZSharp.Compiler; namespace ZSharp.Objects { public interface ICallableType : IType , ITypeAssignableToType + , ISignature { - public Collection Args { get; } - - public IType? VarArgs { get; } - - public Mapping KwArgs { get; } - - public IType? VarKwArgs { get; } - public IType ReturnType { get; } #region Protocols bool IType.IsEqualTo(Compiler.Compiler compiler, IType type) { - if (type is not ICallableType callableType) + if (type is not ISignature callableType) return false; - if (Args.Count != callableType.Args.Count) + if (Args.Count() != callableType.Args.Count()) return false; if ( @@ -34,11 +26,11 @@ VarArgs is not null && callableType.VarArgs is null return false; if ( !(VarArgs is null && callableType.VarArgs is null) && - !compiler.TypeSystem.AreEqual(VarArgs!, callableType.VarArgs!) + !compiler.TypeSystem.AreEqual(VarArgs!.Type, callableType.VarArgs!.Type) ) return false; - if (KwArgs.Count != callableType.KwArgs.Count) + if (KwArgs.Count() != callableType.KwArgs.Count()) return false; if ( @@ -48,7 +40,7 @@ VarKwArgs is not null && callableType.VarKwArgs is null return false; if ( !(VarKwArgs is null && callableType.VarKwArgs is null) && - !compiler.TypeSystem.AreEqual(VarKwArgs!, callableType.VarKwArgs!) + !compiler.TypeSystem.AreEqual(VarKwArgs!.Type, callableType.VarKwArgs!.Type) ) return false; @@ -56,13 +48,15 @@ VarKwArgs is not null && callableType.VarKwArgs is null return false; foreach (var (left, right) in Args.Zip(callableType.Args)) - if (!compiler.TypeSystem.AreEqual(left, right)) + if (!compiler.TypeSystem.AreEqual(left.Type, right.Type)) return false; - foreach (var (name, kwArgType) in KwArgs) - if (!callableType.KwArgs.TryGetValue(name, out var otherKwArgType)) + var otherKwArgs = callableType.KwArgs.ToDictionary(param => param.Name); + + foreach (var kwArg in KwArgs) + if (!otherKwArgs.TryGetValue(kwArg.Name, out var otherKwArg)) return false; - else if (!compiler.TypeSystem.AreEqual(kwArgType, otherKwArgType)) + else if (!compiler.TypeSystem.AreEqual(kwArg.Type, otherKwArg.Type)) return false; return true; @@ -70,11 +64,11 @@ VarKwArgs is not null && callableType.VarKwArgs is null bool? ITypeAssignableToType.IsAssignableTo(Compiler.Compiler compiler, IType target) { - if (target is not ICallableType callableType) - return null; + if (target is not ISignature callableType) + return false; - if (Args.Count != callableType.Args.Count) return false; - if (KwArgs.Count != callableType.KwArgs.Count) return false; + if (Args.Count() != callableType.Args.Count()) + return false; if ( VarArgs is null && callableType.VarArgs is not null || @@ -83,10 +77,13 @@ VarArgs is not null && callableType.VarArgs is null return false; if ( !(VarArgs is null && callableType.VarArgs is null) && - !compiler.TypeSystem.IsAssignableFrom(VarArgs!, callableType.VarArgs!) + !compiler.TypeSystem.IsAssignableFrom(VarArgs!.Type, callableType.VarArgs!.Type) ) return false; + if (KwArgs.Count() != callableType.KwArgs.Count()) + return false; + if ( VarKwArgs is null && callableType.VarKwArgs is not null || VarKwArgs is not null && callableType.VarKwArgs is null @@ -94,7 +91,7 @@ VarKwArgs is not null && callableType.VarKwArgs is null return false; if ( !(VarKwArgs is null && callableType.VarKwArgs is null) && - !compiler.TypeSystem.IsAssignableFrom(VarKwArgs!, callableType.VarKwArgs!) + !compiler.TypeSystem.IsAssignableFrom(VarKwArgs!.Type, callableType.VarKwArgs!.Type) ) return false; @@ -102,13 +99,15 @@ VarKwArgs is not null && callableType.VarKwArgs is null return false; foreach (var (left, right) in Args.Zip(callableType.Args)) - if (!compiler.TypeSystem.IsAssignableFrom(left, right)) + if (!compiler.TypeSystem.IsAssignableFrom(left.Type, right.Type)) return false; - foreach (var (name, kwArgType) in KwArgs) - if (!callableType.KwArgs.TryGetValue(name, out var otherKwArgType)) + var otherKwArgs = callableType.KwArgs.ToDictionary(param => param.Name); + + foreach (var kwArg in KwArgs) + if (!otherKwArgs.TryGetValue(kwArg.Name, out var otherKwArg)) return false; - else if (!compiler.TypeSystem.IsAssignableFrom(kwArgType, otherKwArgType)) + else if (!compiler.TypeSystem.IsAssignableFrom(kwArg.Type, otherKwArg.Type)) return false; return true; diff --git a/ZSharp.Compiler.Objects/signature/IParameter.cs b/ZSharp.Compiler.Objects/signature/abstract/IParameter.cs similarity index 61% rename from ZSharp.Compiler.Objects/signature/IParameter.cs rename to ZSharp.Compiler.Objects/signature/abstract/IParameter.cs index d282198c..8eb3e3b8 100644 --- a/ZSharp.Compiler.Objects/signature/IParameter.cs +++ b/ZSharp.Compiler.Objects/signature/abstract/IParameter.cs @@ -1,6 +1,10 @@ -namespace ZSharp.Objects +using ZSharp.Compiler; + +namespace ZSharp.Objects { - public interface IParameter : CompilerObject + public interface IParameter + : CompilerObject + , ITyped { public string Name { get; } diff --git a/ZSharp.Compiler.Objects/signature/abstract/ISignature.cs b/ZSharp.Compiler.Objects/signature/abstract/ISignature.cs new file mode 100644 index 00000000..56e18dee --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/abstract/ISignature.cs @@ -0,0 +1,197 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +using Args = CommonZ.Utils.Collection; +using KwArgs = CommonZ.Utils.Mapping; + + +namespace ZSharp.Objects +{ + public interface ISignature + : CompilerObject + , IType + , ITypeAssignableToType + { + public IEnumerable Args { get; } + + public IVarParameter? VarArgs { get; } + + public IEnumerable KwArgs { get; } + + public IVarParameter? VarKwArgs { get; } + + public IType ReturnType { get; } + + public Mapping MatchArguments(Compiler.Compiler compiler, Compiler.Argument[] arguments) + { + var (args, kwArgs) = Utils.SplitArguments(arguments); + + try + { + return MatchArguments(compiler, args, kwArgs); + } catch (ArgumentsCountMismatchException argumentsCountMismatch) + { + throw new ArgumentMismatchException(this, arguments, innerException: argumentsCountMismatch); + } catch (Compiler.InvalidCastException invalidCast) + { + throw new ArgumentMismatchException(this, arguments, innerException: invalidCast); + } + } + + public Mapping MatchArguments(Compiler.Compiler compiler, Args args, KwArgs kwArgs) + { + var @params = Args.ToList(); + var kwParams = KwArgs.ToList(); + + if (args.Count > @params.Count && VarArgs is null) + throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}."); + + if (kwArgs.Count > kwParams.Count && VarKwArgs is null) + throw new ArgumentsCountMismatchException($"Expected {kwParams.Count} named arguments but got {kwArgs.Count}."); + + Mapping result = []; + + var positionalArgumentsQueue = new Queue(args); + + foreach (var param in @params) + { + if (!positionalArgumentsQueue.TryDequeue(out var arg)) + arg = param.Default ?? throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); + + if (param.MatchArgument(compiler, arg).Ok(out var argumentResult)) + result[param] = argumentResult; + else throw new Compiler.InvalidCastException(arg, null!); + } + + if (VarArgs is not null) + result[VarArgs] = VarArgs.MatchArguments(compiler, [.. positionalArgumentsQueue.Select(arg => new Compiler.Argument(arg))]); + else if (positionalArgumentsQueue.Count > 0) + throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); + + var keywordArguments = kwArgs.ToDictionary(); + var varKeywordArguments = new Collection(); + + foreach (var kwParam in kwParams) + { + if (!kwArgs.Remove(kwParam.Name, out var kwArg)) + kwArg = kwParam.Default ?? throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); + else varKeywordArguments.Add(new(kwParam.Name, kwArg)); + + result[kwParam] = kwArg; + } + + if (VarKwArgs is not null) + result[VarKwArgs] = VarKwArgs.MatchArguments(compiler, [.. varKeywordArguments]); + else if (keywordArguments.Count > 0) + throw new ArgumentsCountMismatchException($"Expected {@params.Count} named arguments but got {args.Count}"); + + return result; + } + + #region Protocols + + bool IType.IsEqualTo(Compiler.Compiler compiler, IType type) + { + if (type is not ISignature callableType) + return false; + + if (Args.Count() != callableType.Args.Count()) + return false; + + if ( + VarArgs is null && callableType.VarArgs is not null || + VarArgs is not null && callableType.VarArgs is null + ) + return false; + if ( + !(VarArgs is null && callableType.VarArgs is null) && + !compiler.TypeSystem.AreEqual(VarArgs!.Type, callableType.VarArgs!.Type) + ) + return false; + + if (KwArgs.Count() != callableType.KwArgs.Count()) + return false; + + if ( + VarKwArgs is null && callableType.VarKwArgs is not null || + VarKwArgs is not null && callableType.VarKwArgs is null + ) + return false; + if ( + !(VarKwArgs is null && callableType.VarKwArgs is null) && + !compiler.TypeSystem.AreEqual(VarKwArgs!.Type, callableType.VarKwArgs!.Type) + ) + return false; + + if (!compiler.TypeSystem.AreEqual(ReturnType, callableType.ReturnType)) + return false; + + foreach (var (left, right) in Args.Zip(callableType.Args)) + if (!compiler.TypeSystem.AreEqual(left.Type, right.Type)) + return false; + + var otherKwArgs = callableType.KwArgs.ToDictionary(param => param.Name); + + foreach (var kwArg in KwArgs) + if (!otherKwArgs.TryGetValue(kwArg.Name, out var otherKwArg)) + return false; + else if (!compiler.TypeSystem.AreEqual(kwArg.Type, otherKwArg.Type)) + return false; + + return true; + } + + bool? ITypeAssignableToType.IsAssignableTo(Compiler.Compiler compiler, IType target) + { + if (target is not ISignature callableType) + return false; + + if (Args.Count() != callableType.Args.Count()) + return false; + + if ( + VarArgs is null && callableType.VarArgs is not null || + VarArgs is not null && callableType.VarArgs is null + ) + return false; + if ( + !(VarArgs is null && callableType.VarArgs is null) && + !compiler.TypeSystem.IsAssignableFrom(VarArgs!.Type, callableType.VarArgs!.Type) + ) + return false; + + if (KwArgs.Count() != callableType.KwArgs.Count()) + return false; + + if ( + VarKwArgs is null && callableType.VarKwArgs is not null || + VarKwArgs is not null && callableType.VarKwArgs is null + ) + return false; + if ( + !(VarKwArgs is null && callableType.VarKwArgs is null) && + !compiler.TypeSystem.IsAssignableFrom(VarKwArgs!.Type, callableType.VarKwArgs!.Type) + ) + return false; + + if (!compiler.TypeSystem.IsAssignableTo(ReturnType, callableType.ReturnType)) + return false; + + foreach (var (left, right) in Args.Zip(callableType.Args)) + if (!compiler.TypeSystem.IsAssignableFrom(left.Type, right.Type)) + return false; + + var otherKwArgs = callableType.KwArgs.ToDictionary(param => param.Name); + + foreach (var kwArg in KwArgs) + if (!otherKwArgs.TryGetValue(kwArg.Name, out var otherKwArg)) + return false; + else if (!compiler.TypeSystem.IsAssignableFrom(kwArg.Type, otherKwArg.Type)) + return false; + + return true; + } + + #endregion + } +} diff --git a/ZSharp.Compiler.Objects/signature/abstract/IVarParameter.cs b/ZSharp.Compiler.Objects/signature/abstract/IVarParameter.cs new file mode 100644 index 00000000..343afed1 --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/abstract/IVarParameter.cs @@ -0,0 +1,13 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public interface IVarParameter + : CompilerObject + , INamedObject + , ITyped + { + public CompilerObject MatchArguments(Compiler.Compiler compiler, Collection arguments); + } +} diff --git a/ZSharp.Compiler.Objects/signature/stub/StubParameter.cs b/ZSharp.Compiler.Objects/signature/stub/StubParameter.cs new file mode 100644 index 00000000..7e852e70 --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/stub/StubParameter.cs @@ -0,0 +1,46 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class StubParameter(string name) + : CompilerObject + , IParameter + , ITyped + , IReferencable + { + public string Name { get; set; } = name; + + public CompilerObject? Default { get; set; } + + public IType? Type { get; set; } + + #region Parameter + + CompilerObjectResult IParameter.MatchArgument(Compiler.Compiler compiler, CompilerObject argument) + { + if (Type is null) + return CompilerObjectResult.Error($"Parameter {Name} does not have a type"); + + return compiler.TypeSystem.ImplicitCast(argument, Type); + } + + #endregion + + #region Typed + + IType ITyped.Type => Type ?? throw new InvalidOperationException($"Parameter {Name} does not define a type"); + + #endregion + + #region Reference + + IParameter IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + => new StubParameter(Name) + { + Default = Default is null ? null : @ref.CreateReference(Default, context), + Type = Type is null ? null : @ref.CreateReference(Type, context), + }; + + #endregion + } +} diff --git a/ZSharp.Compiler.Objects/signature/stub/StubSignature.cs b/ZSharp.Compiler.Objects/signature/stub/StubSignature.cs new file mode 100644 index 00000000..a54a5204 --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/stub/StubSignature.cs @@ -0,0 +1,56 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class StubSignature + : CompilerObject + , ISignature + , IReferencable + { + public Collection Args { get; } = []; + + public StubVarParameter? VarArgs { get; set; } + + public Collection KwArgs { get; } = []; + + public StubVarParameter? VarKwArgs { get; set; } + + public IType? ReturnType { get; set; } + + #region Signature + + IEnumerable ISignature.Args => Args; + + IVarParameter? ISignature.VarArgs => VarArgs; + + IEnumerable ISignature.KwArgs => KwArgs; + + IVarParameter? ISignature.VarKwArgs => VarKwArgs; + + IType ISignature.ReturnType => ReturnType ?? throw new(); + + #endregion + + #region Reference + + ISignature IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + { + StubSignature result = new(); + + result.Args.AddRange(Args.Select(arg => @ref.CreateReference(arg, context))); + + if (VarArgs is not null) + result.VarArgs = @ref.CreateReference(VarArgs, context); + + result.KwArgs.AddRange(KwArgs.Select(arg => @ref.CreateReference(arg, context))); + + if (VarKwArgs is not null) + result.VarKwArgs = @ref.CreateReference(VarKwArgs, context); + + return result; + } + + #endregion + } +} diff --git a/ZSharp.Compiler.Objects/signature/stub/StubVarParameter.cs b/ZSharp.Compiler.Objects/signature/stub/StubVarParameter.cs new file mode 100644 index 00000000..f2f1dfcc --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/stub/StubVarParameter.cs @@ -0,0 +1,30 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class StubVarParameter(string name) + : CompilerObject + , IVarParameter + , ITyped + { + public string Name { get; set; } = name; + + public IType? Type { get; set; } + + #region Var Parameter + + CompilerObject IVarParameter.MatchArguments(Compiler.Compiler compiler, Collection arguments) + { + throw new NotImplementedException(); + } + + #endregion + + #region Typed + + IType ITyped.Type => Type ?? throw new InvalidOperationException($"Variadic parameter {Name} does not define a type"); + + #endregion + } +} diff --git a/ZSharp.Compiler.Objects/typing/TypedUndefined.cs b/ZSharp.Compiler.Objects/typing/TypedUndefined.cs new file mode 100644 index 00000000..5c0256a6 --- /dev/null +++ b/ZSharp.Compiler.Objects/typing/TypedUndefined.cs @@ -0,0 +1,11 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class TypedUndefined(IType type) + : CompilerObject + , ITyped + { + public IType Type { get; } = type; + } +} diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.Context.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.Context.cs new file mode 100644 index 00000000..387d4d56 --- /dev/null +++ b/ZSharp.Compiler/compiler core/compiler/Compiler.Context.cs @@ -0,0 +1,20 @@ +using CommonZ.Utils; + +namespace ZSharp.Compiler +{ + public sealed partial class Compiler + { + public IContext CurrentContext { get; private set; } = new EmptyContext(); + + public Action UseContext(IContext context) + { + (CurrentContext, context) = (context, CurrentContext); + CurrentContext.Parent = context; + + return () => CurrentContext = context; + } + + public ContextManager ContextScope(IContext context) + => new(UseContext(context)); + } +} diff --git a/ZSharp.Compiler/compiler core/core/context/EmptyContext.cs b/ZSharp.Compiler/compiler core/core/context/EmptyContext.cs new file mode 100644 index 00000000..07074fc1 --- /dev/null +++ b/ZSharp.Compiler/compiler core/core/context/EmptyContext.cs @@ -0,0 +1,12 @@ +namespace ZSharp.Compiler +{ + internal sealed class EmptyContext + : IContext + { + IContext? IContext.Parent + { + get => null; + set => throw new InvalidOperationException("Empty context cannot be mounted."); + } + } +} diff --git a/ZSharp.Compiler/compiler core/core/context/IContext.cs b/ZSharp.Compiler/compiler core/core/context/IContext.cs new file mode 100644 index 00000000..c7779244 --- /dev/null +++ b/ZSharp.Compiler/compiler core/core/context/IContext.cs @@ -0,0 +1,64 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler +{ + public interface IContext + { + private static IContextChainStrategy DefaultStrategy { get; } = new ParentContextStrategy(); + + public IContext? Parent { get; internal protected set; } + + public T? FindContext(IContextChainStrategy? strategy = null) + where T : class, IContext + { + strategy ??= DefaultStrategy; + + var context = this; + + do + { + if (context is T capability) return capability; + } while ((context = strategy.NextContext(context!)) is not null); + + return null; + } + + public bool PerformOperation( + Func operation, + IContextChainStrategy? strategy = null + ) + where T : class, IContext + { + strategy ??= DefaultStrategy; + + var context = this; + + do + { + if (context is T capability && operation(capability)) return true; + } while ((context = strategy.NextContext(context!)) is not null); + + + return false; + } + + public bool PerformOperation( + Func operation, + [NotNullWhen(true)] out T? ctx, + IContextChainStrategy? strategy = null + ) + where T : class, IContext + { + strategy ??= DefaultStrategy; + + var context = this; + + do + { + if (context is T capability && operation(capability)) return (ctx = capability) is not null; + } while ((context = strategy.NextContext(context!)) is not null); + + return (ctx = null) is not null; + } + } +} diff --git a/ZSharp.Compiler/compiler core/core/context/IContextChainStrategy.cs b/ZSharp.Compiler/compiler core/core/context/IContextChainStrategy.cs new file mode 100644 index 00000000..af9837f0 --- /dev/null +++ b/ZSharp.Compiler/compiler core/core/context/IContextChainStrategy.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IContextChainStrategy + { + public IContext? NextContext(IContext context); + } +} diff --git a/ZSharp.Compiler/compiler core/core/context/strategies/ParentContextStrategy.cs b/ZSharp.Compiler/compiler core/core/context/strategies/ParentContextStrategy.cs new file mode 100644 index 00000000..b9625c0c --- /dev/null +++ b/ZSharp.Compiler/compiler core/core/context/strategies/ParentContextStrategy.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public sealed class ParentContextStrategy : IContextChainStrategy + { + IContext? IContextChainStrategy.NextContext(IContext context) + => context.Parent; + } +} diff --git a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs index 71f0e833..a1c213a3 100644 --- a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs +++ b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs @@ -109,6 +109,10 @@ public bool IsTyped(CompilerObject @object, [NotNullWhen(true)] out IType? type) return (type = null) is not null; } + public bool IsTyped(CompilerObject @object, [NotNullWhen(true)] out T? type) + where T : class, IType + => (type = IsTyped(@object, out var objectType) ? objectType as T : null) is not null; + public bool IsTypeModifier(CompilerObject @object) => @object is ITypeModifier; diff --git a/ZSharp.Compiler/core/concepts/callable/ICallable.cs b/ZSharp.Compiler/core/concepts/callable/ICallable.cs index e8b76dfe..a8413fd1 100644 --- a/ZSharp.Compiler/core/concepts/callable/ICallable.cs +++ b/ZSharp.Compiler/core/concepts/callable/ICallable.cs @@ -4,6 +4,7 @@ /// Should be implemented by any binding that is callable. /// public interface ICTCallable + : CompilerObject { public CompilerObject Call(Compiler compiler, Argument[] arguments); } @@ -12,6 +13,7 @@ public interface ICTCallable /// Should be implementedby any type that is callable. /// public interface IRTCallable + : CompilerObject { public CompilerObject Call(Compiler compiler, CompilerObject callable, Argument[] arguments); } diff --git a/ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs b/ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs index 5c90ba4e..daa02ef8 100644 --- a/ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs +++ b/ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler { - public interface ICompileIRReference + public interface ICompileIRReference { public T CompileIRReference(Compiler compiler); } diff --git a/ZSharp.IR/ir/oop/method/ConstructedMethod.cs b/ZSharp.IR/ir/oop/method/ConstructedMethod.cs new file mode 100644 index 00000000..af6c7644 --- /dev/null +++ b/ZSharp.IR/ir/oop/method/ConstructedMethod.cs @@ -0,0 +1,14 @@ +using CommonZ.Utils; + +namespace ZSharp.IR +{ + public sealed class ConstructedMethod(Method method) + : MethodReference(method) + , ICallable + { + public Collection Arguments { get; } = + method.HasGenericParameters + ? [] + : throw new InvalidOperationException($"Can not create generic instance from a non-generic method"); + } +} diff --git a/ZSharp.IR/ir/oop/method/GenericMethodInstance.cs b/ZSharp.IR/ir/oop/method/GenericMethodInstance.cs deleted file mode 100644 index f18ac671..00000000 --- a/ZSharp.IR/ir/oop/method/GenericMethodInstance.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.IR -{ - public sealed class GenericMethodInstance(Method method) - : MethodReference(method) - , ICallable - { - public Collection Arguments { get; } = /*method.Member.HasGenericParameters*/false ? [] : Collection.Empty; - } -} diff --git a/ZSharp.IR/ir/oop/method/Method.cs b/ZSharp.IR/ir/oop/method/Method.cs index 91cd38e8..b1d4a391 100644 --- a/ZSharp.IR/ir/oop/method/Method.cs +++ b/ZSharp.IR/ir/oop/method/Method.cs @@ -1,9 +1,13 @@ -namespace ZSharp.IR +using CommonZ.Utils; + +namespace ZSharp.IR { public sealed class Method : IRObject , ICallable { + private Collection? _genericParameters; + private Signature _signature; private VM.MethodBody? _body; @@ -11,6 +15,20 @@ public sealed class Method public MethodAttributes Attributes { get; set; } = MethodAttributes.None; + public Collection GenericParameters + { + get + { + if (_genericParameters is not null) + return _genericParameters; + + Interlocked.CompareExchange(ref _genericParameters, [], null); + return _genericParameters; + } + } + + public bool HasGenericParameters => !_genericParameters.IsNullOrEmpty(); + public IType ReturnType { get => _signature.ReturnType; diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs index cbe1bb39..27e40af8 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs @@ -163,6 +163,12 @@ private void LoadConstructor(IL.ConstructorInfo constructor) private Method LoadMethod(IL.MethodInfo method) { + List genericParameters = []; + + if (method.IsGenericMethodDefinition) + foreach (var genericParameter in method.GetGenericArguments()) + genericParameters.Add(Context.Cache(genericParameter, new IR.GenericParameter(genericParameter.Name))); + var result = new Method(Loader.LoadType(method.ReturnType)) { Name = method.GetCustomAttribute()?.Name ?? method.Name, @@ -170,6 +176,9 @@ private Method LoadMethod(IL.MethodInfo method) Context.Cache(method, result); + if (genericParameters.Count > 0) + result.GenericParameters.AddRange(genericParameters); + if (!method.IsStatic) result.Signature.Args.Parameters.Add(new("this", Self)); diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index 4caf4ea4..7fa476b5 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -127,17 +127,23 @@ public IL.MethodInfo LoadReference(IR.MethodReference @ref) if (def is not IL.MethodInfo methodInfo) throw new InvalidOperationException($"Method {@ref.Method.Name} was not compiled to an IL method"); - if (!type.IsGenericType) - return methodInfo; - - if (type.GetGenericTypeDefinition() is IL.Emit.TypeBuilder typeBuilder) - if (!typeBuilder.IsCreated()) - return IL.Emit.TypeBuilder.GetMethod(type, methodInfo); - - return (IL.MethodInfo)(IL.MethodBase.GetMethodFromHandle( - methodInfo.MethodHandle, - type.TypeHandle - ) ?? throw new("Could not create method from method handle")); + if (type.IsGenericType) + if (type.GetGenericTypeDefinition() is IL.Emit.TypeBuilder typeBuilder) + { + if (!typeBuilder.IsCreated()) + methodInfo = IL.Emit.TypeBuilder.GetMethod(type, methodInfo); + } else + methodInfo = (IL.MethodInfo)(IL.MethodBase.GetMethodFromHandle( + methodInfo.MethodHandle, + type.TypeHandle + ) ?? throw new("Could not create method from method handle")); + + if (@ref is IR.ConstructedMethod constructed) + methodInfo = methodInfo.MakeGenericMethod([ + .. constructed.Arguments.Select(LoadType) + ]); + + return methodInfo; } public IL.MethodInfo LoadReference(IR.GenericFunctionInstance @ref) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs index 7653f043..05907445 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs @@ -97,13 +97,15 @@ private Action Compile(AST.Function function) if (function.Name != string.Empty) { - if (!Context.CurrentScope.Get(function.Name, out var result, lookupParent: false)) - Context.CurrentScope.Set(function.Name, result = new MethodOverloadGroup(function.Name)); - if (result is not MethodOverloadGroup group) - throw new(); - group.Overloads.Add(compiler.Object); - - if (!Class.Members.TryGetValue(function.Name, out result)) + MethodOverloadGroup? group = null; + if (!Compiler.Compiler.CurrentContext.PerformOperation( + scope => scope.Get(function.Name, out group) + )) + Context.CurrentScope.Set(function.Name, group = new(function.Name)); + + group!.Overloads.Add(compiler.Object); + + if (!Class.Members.TryGetValue(function.Name, out var _)) Class.Members.Add(function.Name, group); } diff --git a/ZSharp.ZSSourceCompiler/context/Context.Scopes.cs b/ZSharp.ZSSourceCompiler/context/Context.Scopes.cs index c8a1e8a0..a6c78dbf 100644 --- a/ZSharp.ZSSourceCompiler/context/Context.Scopes.cs +++ b/ZSharp.ZSSourceCompiler/context/Context.Scopes.cs @@ -4,42 +4,41 @@ namespace ZSharp.ZSSourceCompiler { public sealed partial class Context { - private readonly Mapping objectContainerScopes = []; - private readonly Mapping objectContainedScopes = []; + private readonly Mapping objectContainerScopes = []; + private readonly Mapping objectContainedScopes = []; - public Scope GlobalScope { get; } + public ScopeContext GlobalScope { get; } - public Scope CurrentScope { get; private set; } + public ScopeContext CurrentScope { get; private set; } - public Scope CreateScope(ScopeParent parent = ScopeParent.Default) - => new(parent switch - { - ScopeParent.None => null, - ScopeParent.Global => GlobalScope, - ScopeParent.Current => CurrentScope, - _ => throw new ArgumentOutOfRangeException(nameof(parent), parent, $"Unknown {nameof(ScopeParent)} value") - }); + public ScopeContext CreateScope() + => new(); - public ContextManager Scope(ScopeParent parent = ScopeParent.Default) - => Scope(CreateScope(parent)); + public ContextManager Scope() + => Scope(CreateScope()); - public ContextManager Scope(Scope scope) + public ContextManager Scope(ScopeContext scope) { (CurrentScope, scope) = (scope, CurrentScope); + var revert = CurrentCompiler.Compiler.Compiler.UseContext(CurrentScope); - return new(() => CurrentScope = scope); + return new(() => + { + CurrentScope = scope; + revert(); + }); } - public ContextManager Scope(CompilerObject @object, ScopeParent parent = ScopeParent.Default) - => Scope(ContainedScope(@object) ?? ContainedScope(@object, CreateScope(parent))); // TODO: proper exception: could not find scope for object + public ContextManager Scope(CompilerObject @object) + => Scope(ContainedScope(@object) ?? ContainedScope(@object, CreateScope())); // TODO: proper exception: could not find scope for object - public Scope? ContainerScope(CompilerObject @object) + public ScopeContext? ContainerScope(CompilerObject @object) => objectContainerScopes.GetValueOrDefault(@object); - public Scope? ContainedScope(CompilerObject @object) + public ScopeContext? ContainedScope(CompilerObject @object) => objectContainedScopes.GetValueOrDefault(@object); - public Scope ContainedScope(CompilerObject @object, Scope scope) + public ScopeContext ContainedScope(CompilerObject @object, ScopeContext scope) => objectContainedScopes[@object] = scope; } } diff --git a/ZSharp.ZSSourceCompiler/context/Context.cs b/ZSharp.ZSSourceCompiler/context/Context.cs index 31391b1d..9088a533 100644 --- a/ZSharp.ZSSourceCompiler/context/Context.cs +++ b/ZSharp.ZSSourceCompiler/context/Context.cs @@ -4,12 +4,12 @@ public sealed partial class Context { public ZSSourceCompiler SourceCompiler { get; } - public Context(ZSSourceCompiler compiler, Scope? globalScope = null) + public Context(ZSSourceCompiler compiler, ScopeContext? globalScope = null) { SourceCompiler = compiler; - GlobalScope = globalScope ?? new(null); - CurrentScope = GlobalScope; + GlobalScope = globalScope ?? new(); + compiler.Compiler.UseContext(CurrentScope = GlobalScope); compilerStack.Push(new DefaultContextCompiler(compiler)); } diff --git a/ZSharp.ZSSourceCompiler/context/scoping/Constraint.cs b/ZSharp.ZSSourceCompiler/context/scoping/Constraint.cs deleted file mode 100644 index 7780a88b..00000000 --- a/ZSharp.ZSSourceCompiler/context/scoping/Constraint.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.ZSSourceCompiler -{ - public sealed class Constraint - { - - } -} diff --git a/ZSharp.ZSSourceCompiler/context/scoping/Scope.cs b/ZSharp.ZSSourceCompiler/context/scoping/Scope.cs deleted file mode 100644 index 01279437..00000000 --- a/ZSharp.ZSSourceCompiler/context/scoping/Scope.cs +++ /dev/null @@ -1,77 +0,0 @@ -using CommonZ.Utils; -using System.Diagnostics.CodeAnalysis; - -namespace ZSharp.ZSSourceCompiler -{ - public sealed class Scope(Scope? parent) - { - private readonly Mapping scope = []; - private readonly Mapping> constraints = []; - - public Scope? Parent { get; } = parent; - - public CompilerObject? Get(string name, bool lookupParent = true) - { - if (scope.TryGetValue(name, out var result)) - return result; - - if (lookupParent && Parent is not null) - return Parent.Get(name); - - return null; - } - - public bool Get(string name, [NotNullWhen(true)] out CompilerObject? result, bool lookupParent = true) - => (result = Get(name, lookupParent: lookupParent)) is not null; - - public void Set(string name, CompilerObject value, bool @override = false) - { - if (scope.ContainsKey(name) && !@override) - throw new(); // TODO: Throw a proper exception of NameAlreadyExists - - scope[name] = value; - } - - public IEnumerable Constraints(string name, bool lookupParent = true) - => Get(name, lookupParent: lookupParent) is CompilerObject @object ? Constraints(@object, lookupParent: lookupParent) : []; - - public IEnumerable Constraints(CompilerObject @object, bool lookupParent = true) - { - if (constraints.TryGetValue(@object, out var result)) - return result; - - if (lookupParent && Parent is not null) - return Parent.Constraints(@object); - - return []; - } - - public void Constriant(string name, Constraint constraint, bool lookupParent = true) - { - if (Get(name, lookupParent: lookupParent) is CompilerObject @object) - Constriant(@object, constraint); - else throw new(); // TODO: Throw a proper exception of UnresolvedName - } - - public void Constriant(CompilerObject @object, Constraint constraint) - { - if (constraints.TryGetValue(@object, out var result)) - result.Add(constraint); - else constraints[@object] = [constraint]; - } - - public void Constraints(string name, Constraint[] constraints, bool lookupParent = true) - { - if (Get(name, lookupParent: lookupParent) is CompilerObject @object) - Constraints(@object, constraints); - else throw new(); // TODO: Throw a proper exception of UnresolvedName - } - - public void Constraints(CompilerObject @object, Constraint[] constraints) - { - if (this.constraints.TryGetValue(@object, out var result)) - result.AddRange(constraints); - else this.constraints[@object] = constraints.ToList(); - } - } -} diff --git a/ZSharp.ZSSourceCompiler/context/scoping/ScopeParent.cs b/ZSharp.ZSSourceCompiler/context/scoping/ScopeParent.cs deleted file mode 100644 index c8551286..00000000 --- a/ZSharp.ZSSourceCompiler/context/scoping/ScopeParent.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZSharp.ZSSourceCompiler -{ - public enum ScopeParent - { - None, - Current, - Global, - - Default = Current - } -} diff --git a/ZSharp.ZSSourceCompiler/contexts/capabilities/IScopeContext.cs b/ZSharp.ZSSourceCompiler/contexts/capabilities/IScopeContext.cs new file mode 100644 index 00000000..05ba08c1 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/contexts/capabilities/IScopeContext.cs @@ -0,0 +1,21 @@ +using System.Diagnostics.CodeAnalysis; +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler +{ + public interface IScopeContext + : IContext + { + public CompilerObject? Get(string name); + + public T? Get(string name) + where T : class, CompilerObject; + + public bool Get(string name, [NotNullWhen(true)] out CompilerObject? result); + + public bool Get(string name, [NotNullWhen(true)] out T? result) + where T : class, CompilerObject; + + public void Set(string name, CompilerObject @object); + } +} diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs b/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs new file mode 100644 index 00000000..9fd33dfa --- /dev/null +++ b/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs @@ -0,0 +1,32 @@ +using CommonZ.Utils; +using System.Diagnostics.CodeAnalysis; +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler +{ + public sealed class ScopeContext() + : IContext + , IScopeContext + { + private readonly Mapping scope = []; + + public IContext? Parent { get; set; } + + public CompilerObject? Get(string name) + => scope.TryGetValue(name, out var result) ? result : null; + + public T? Get(string name) + where T : class, CompilerObject + => Get(name) is T result ? result : null; + + public bool Get(string name, [NotNullWhen(true)] out CompilerObject? result) + => (result = Get(name)) is not null; + + public bool Get(string name, [NotNullWhen(true)] out T? result) + where T : class, CompilerObject + => (result = Get(name)) is not null; + + public void Set(string name, CompilerObject @object) + => scope[name] = @object; + } +} diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index 936ef872..a5ad06fb 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -11,7 +11,7 @@ public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) ArrayLiteral array => Compile(array), BinaryExpression binary => Compile(binary), CallExpression call => Compile(call), - IdentifierExpression identifier => Context.CurrentScope.Get(identifier.Name), + IdentifierExpression identifier => Compile(identifier), IndexExpression index => Compile(index), LiteralExpression literal => Compile(literal), WhileExpression @while => Compile(@while), @@ -64,6 +64,23 @@ private CompilerObject Compile(CallExpression call) return Compiler.Compiler.Call(callable, args.ToArray()); } + private CompilerObject Compile(IdentifierExpression identifier) + { + CompilerObject? result = null; + + Compiler.Compiler.CurrentContext.PerformOperation( + scope => + { + return scope.Get(identifier.Name, out result); + } + ); + + if (result is not null) return result; + + Compiler.LogError($"Could not resolve name {identifier.Name}", identifier); + return Compiler.Compiler.CreateString($""); // TODO: return an object that knows it doesn't exist. + } + private CompilerObject Compile(IndexExpression index) { var indexable = Compiler.Compiler.Evaluate(Compiler.CompileNode(index.Target)); diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs index 13756bf9..f2e40587 100644 --- a/ZSharpTest/tests/simple.zs +++ b/ZSharpTest/tests/simple.zs @@ -1,5 +1,12 @@ import { input, print } from "std:io"; -import { Console, List, TestInterface, greet, id } from "net:ZLoad.Test.dll"; +import { + Console, + List, + TestClass, + TestInterface, + greet, + id +} from "net:ZLoad.Test.dll"; module Program; @@ -49,6 +56,9 @@ fun main(): void { testInterface(c1); testInterface(c2); + let tc = TestClass(); + print(tc.id[string]("Id [T: string] of TestClass")); + return; } From 2f9844146998405b11a3cc6bb694b8fdb3f68808 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen <42520501+binyamin555@users.noreply.github.com> Date: Sat, 10 May 2025 23:05:43 +0300 Subject: [PATCH 151/235] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index b82e3881..122d14e0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,10 @@ # Z# Language +> This README file is out-of-date. I will update this once I have enough time and an acceptable working version. +> If you have any questions regarding this project, you can join the discord server [discord server](https://discord.gg/Uc3GN2bfG9). + + Welcome to the Z# language repository! This repository holds the first released version of Z#. Z# is a typesafe, interpreterd language. It is still very much a WIP so don't expect it to work smoothly. From 2cc48a797486cbba2fb1a95e035529015b2b0ff2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 13 May 2025 12:07:29 +0300 Subject: [PATCH 152/235] Add for loops Fix generic type referencing --- ZLoad.Test/BaseClass.cs | 13 ++ ZLoad.Test/Standard.List.Iterator.cs | 17 +++ ZLoad.Test/Standard.List.cs | 7 + ZLoad.Test/TestClass.cs | 7 +- .../nodes/stmt/flow/{ => for}/ForStatement.cs | 4 +- ZSharp.AST/nodes/stmt/flow/for/ForValue.cs | 6 + ZSharp.AST/nodes/stmt/flow/for/LetForValue.cs | 9 ++ .../ir loader/IRLoader.Impl.cs | 23 ++-- .../functional/body/Local.cs | 8 +- .../functional/signature/Signature.cs | 13 +- .../literals/ArrayLiteral.cs | 4 + .../oop/class/GenericClass.cs | 18 +-- .../oop/class/GenericClassInstance.cs | 48 +++++-- ZSharp.Compiler/cg objects/raw/RawCode.cs | 20 +++ ZSharp.Parser/lang/stmt/LangParser.For.cs | 31 ++++- .../il2ir/loaders/ClassLoader.cs | 3 + .../class body/MethodCompiler.cs | 25 ++-- .../module/FunctionCompiler.cs | 27 ++-- .../runtime code/loops/for/ForLoopCompiler.cs | 124 ++++++++++++++++++ .../runtime code/objects/ForLoop.cs | 65 +++++++++ .../context/Context.Scopes.cs | 6 +- .../contexts/capabilities/IMemoryAllocator.cs | 14 ++ .../contexts/capabilities/IObjectContext.cs | 20 +++ .../ILookupContext.cs} | 13 +- .../capabilities/scope/IScopeContext.cs | 11 ++ .../contexts/concrete/FunctionContext.cs | 34 +++++ .../contexts/concrete/ScopeContext.cs | 13 -- .../statement/StatementCompiler.cs | 4 + ZSharpTest/Properties/launchSettings.json | 4 + ZSharpTest/projects/todo.zs | 16 +-- ZSharpTest/tests/simple.zs | 9 ++ 31 files changed, 504 insertions(+), 112 deletions(-) create mode 100644 ZLoad.Test/BaseClass.cs create mode 100644 ZLoad.Test/Standard.List.Iterator.cs rename ZSharp.AST/nodes/stmt/flow/{ => for}/ForStatement.cs (61%) create mode 100644 ZSharp.AST/nodes/stmt/flow/for/ForValue.cs create mode 100644 ZSharp.AST/nodes/stmt/flow/for/LetForValue.cs create mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs create mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/ForLoop.cs create mode 100644 ZSharp.ZSSourceCompiler/contexts/capabilities/IMemoryAllocator.cs create mode 100644 ZSharp.ZSSourceCompiler/contexts/capabilities/IObjectContext.cs rename ZSharp.ZSSourceCompiler/contexts/capabilities/{IScopeContext.cs => scope/ILookupContext.cs} (54%) create mode 100644 ZSharp.ZSSourceCompiler/contexts/capabilities/scope/IScopeContext.cs create mode 100644 ZSharp.ZSSourceCompiler/contexts/concrete/FunctionContext.cs diff --git a/ZLoad.Test/BaseClass.cs b/ZLoad.Test/BaseClass.cs new file mode 100644 index 00000000..f48ebed2 --- /dev/null +++ b/ZLoad.Test/BaseClass.cs @@ -0,0 +1,13 @@ +using ZSharp.Runtime.NET.IL2IR; + +namespace ZLoad.Test +{ + public class BaseClass + { + [Alias(Name = "doVirtual")] + public virtual void DoVirtual() + { + Console.WriteLine("BaseClass::DoVirtual()"); + } + } +} diff --git a/ZLoad.Test/Standard.List.Iterator.cs b/ZLoad.Test/Standard.List.Iterator.cs new file mode 100644 index 00000000..96a7ce14 --- /dev/null +++ b/ZLoad.Test/Standard.List.Iterator.cs @@ -0,0 +1,17 @@ +using ZSharp.Runtime.NET.IL2IR; + +namespace Standard.List +{ + public sealed class ListIterator + { + internal IEnumerator Enumerator { get; init; } + + [Alias(Name = "moveNext")] + public bool MoveNext() + => Enumerator.MoveNext(); + + [Alias(Name = "getCurrent")] + public T GetCurrentValue() + => Enumerator.Current; + } +} diff --git a/ZLoad.Test/Standard.List.cs b/ZLoad.Test/Standard.List.cs index 3ea5fc7a..0bc9ca2b 100644 --- a/ZLoad.Test/Standard.List.cs +++ b/ZLoad.Test/Standard.List.cs @@ -28,5 +28,12 @@ public T Get(int index) [Alias(Name = "removeAt")] public void RemoveAt(int index) => _inner.RemoveAt(index); + + [Alias(Name = "getIterator")] + public ListIterator GetIterator() + => new() + { + Enumerator = _inner.GetEnumerator() + }; } } diff --git a/ZLoad.Test/TestClass.cs b/ZLoad.Test/TestClass.cs index ee1d4789..a9d1f23a 100644 --- a/ZLoad.Test/TestClass.cs +++ b/ZLoad.Test/TestClass.cs @@ -2,9 +2,14 @@ namespace ZLoad.Test { - public class TestClass + public class TestClass : BaseClass { [Alias(Name = "id")] public T Id(T v) => v; + + public override void DoVirtual() + { + Console.WriteLine("TestClass::DoVirtual"); + } } } diff --git a/ZSharp.AST/nodes/stmt/flow/ForStatement.cs b/ZSharp.AST/nodes/stmt/flow/for/ForStatement.cs similarity index 61% rename from ZSharp.AST/nodes/stmt/flow/ForStatement.cs rename to ZSharp.AST/nodes/stmt/flow/for/ForStatement.cs index a6de96cf..6f111ad4 100644 --- a/ZSharp.AST/nodes/stmt/flow/ForStatement.cs +++ b/ZSharp.AST/nodes/stmt/flow/for/ForStatement.cs @@ -2,9 +2,9 @@ { public sealed class ForStatement : Statement { - public required Expression CurrentItem { get; set; } + public required ForValue Value { get; set; } - public required Expression Iterable { get; set; } + public required Expression Source { get; set; } public required Statement Body { get; set; } diff --git a/ZSharp.AST/nodes/stmt/flow/for/ForValue.cs b/ZSharp.AST/nodes/stmt/flow/for/ForValue.cs new file mode 100644 index 00000000..684059a4 --- /dev/null +++ b/ZSharp.AST/nodes/stmt/flow/for/ForValue.cs @@ -0,0 +1,6 @@ +namespace ZSharp.AST +{ + public abstract class ForValue + { + } +} diff --git a/ZSharp.AST/nodes/stmt/flow/for/LetForValue.cs b/ZSharp.AST/nodes/stmt/flow/for/LetForValue.cs new file mode 100644 index 00000000..ae8a1871 --- /dev/null +++ b/ZSharp.AST/nodes/stmt/flow/for/LetForValue.cs @@ -0,0 +1,9 @@ +namespace ZSharp.AST +{ + public sealed class LetForValue : ForValue + { + public required string Name { get; set; } + + public Expression? Type { get; set; } + } +} diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index 814271b6..7ef1b141 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -315,14 +315,11 @@ private IType Load(IR.ConstructedClass constructed) for (var i = 0; i < constructed.Arguments.Count; i++) args.Cache(genericClass.GenericParameters[i], Import(constructed.Arguments[i])); - return new GenericClassInstance(genericClass) + return new GenericClassInstance(genericClass, new() { - Context = new() - { - Scope = genericClass, - CompileTimeValues = args - } - }; + Scope = genericClass, + CompileTimeValues = args + }); } return Context.Types.Cache(constructed) ?? throw new(); @@ -350,14 +347,11 @@ private Action LoadGenericClass(IR.Class @class, Module owner) if (@class.Base is not null) result.Base = Load(@class.Base); - var self = new GenericClassInstance(result) + var self = new GenericClassInstance(result, new() { - Context = new() - { - Scope = result, - CompileTimeValues = new() - } - }; + Scope = result, + CompileTimeValues = new() + }); if (@class.HasGenericParameters) foreach (var parameter in @class.GenericParameters) @@ -442,7 +436,6 @@ private Action LoadGenericClass(IR.Class @class, Module owner) overloadGroup.Overloads.Add(resultMethod); } resultMethod.Signature = Load(method.Signature); - resultMethod.ReturnType = Load(method.ReturnType); } }; } diff --git a/ZSharp.Compiler.Objects/functional/body/Local.cs b/ZSharp.Compiler.Objects/functional/body/Local.cs index 720e8bc9..9ab93edc 100644 --- a/ZSharp.Compiler.Objects/functional/body/Local.cs +++ b/ZSharp.Compiler.Objects/functional/body/Local.cs @@ -48,7 +48,13 @@ public IR.VM.Local CompileIRObject(Compiler.Compiler compiler, IR.ICallableBody? { state[BuildState.Initializer] = true; - IR.Initializer = [.. compiler.CompileIRCode(Initializer).Instructions]; + IR.Initializer = [.. + compiler.CompileIRCode( + compiler.TypeSystem.ImplicitCast(Initializer, Type).Unwrap() + ).Instructions, + new IR.VM.Dup(), + new IR.VM.SetLocal(IR) + ]; } return IR; diff --git a/ZSharp.Compiler.Objects/functional/signature/Signature.cs b/ZSharp.Compiler.Objects/functional/signature/Signature.cs index 6b27249d..8df7ca33 100644 --- a/ZSharp.Compiler.Objects/functional/signature/Signature.cs +++ b/ZSharp.Compiler.Objects/functional/signature/Signature.cs @@ -36,7 +36,10 @@ public sealed class Signature if (IR is not null) return IR; - owner ??= new(compiler.RuntimeModule.TypeSystem.Void); + if (ReturnType is null) + throw new PartiallyCompiledObjectException(this, "ReturnType is not defined"); + + owner ??= new(compiler.CompileIRType(ReturnType)); IR = owner; @@ -57,7 +60,13 @@ public sealed class Signature Signature IReferencable.CreateReference(Referencing @ref, ReferenceContext context) { - Signature result = new(); + if (ReturnType is null) + throw new PartiallyCompiledObjectException(this, "ReturnType is not defined"); + + Signature result = new() + { + ReturnType = @ref.CreateReference(ReturnType, context) + }; result.Args.AddRange(Args.Select(arg => @ref.CreateReference(arg, context))); diff --git a/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs b/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs index 048c6465..a0fb7c1c 100644 --- a/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs +++ b/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs @@ -5,6 +5,7 @@ namespace ZSharp.Objects public sealed class ArrayLiteral(IEnumerable? items = null) : CompilerObject , ICTTypeCast + , IImplicitCastToType { public List Items { get; } = new(items ?? []); @@ -37,5 +38,8 @@ CompilerObject ICTTypeCast.Cast(Compiler.Compiler compiler, IType targetType) return new RawCode(code); } + + CompilerObject IImplicitCastToType.ImplicitCastToType(Compiler.Compiler compiler, IType type) + => compiler.Cast(this, type); } } diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs index 738f6e1a..b8c28fe9 100644 --- a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs +++ b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs @@ -67,13 +67,10 @@ public GenericClassInstance CreateReference(Referencing @ref, ReferenceContext c if (@ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error) > currentErrors) throw new(); // TODO: Huh??? - return new GenericClassInstance(this) + return new GenericClassInstance(this, new(context) { - Context = new(context) - { - Scope = this - }, - }; + Scope = this + }); } CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) @@ -131,13 +128,10 @@ CompilerObject IEvaluable.Evaluate(Compiler.Compiler compiler) if (GenericParameters.Count != 0) return this; - return new GenericClassInstance(this) + return new GenericClassInstance(this, new() { - Context = new() - { - Scope = this - } - }; + Scope = this + }); } CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerObject value, string member) diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs index 17587b8b..702f23d6 100644 --- a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs +++ b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs @@ -3,9 +3,7 @@ namespace ZSharp.Objects { - public sealed class GenericClassInstance( - GenericClass origin - ) + public sealed class GenericClassInstance : CompilerObject , ICTGetMember , IRTGetMember @@ -19,12 +17,27 @@ GenericClass origin { CompilerObject IReference.Origin => Origin; - public required ReferenceContext Context { get; set; } + public ReferenceContext Context { get; set; } - public GenericClass Origin { get; set; } = origin; + public GenericClass Origin { get; set; } + + public Mapping GenericArguments { get; } = []; public Mapping Members { get; set; } = []; + #region Constructors + + public GenericClassInstance(GenericClass origin, ReferenceContext context) + { + Context = context; + Origin = origin; + + foreach (var genricParameter in origin.GenericParameters) + GenericArguments[genricParameter] = Context[genricParameter]; + } + + #endregion + public CompilerObject Member(Compiler.Compiler compiler, string member) { if (Members.ContainsKey(member)) return Members[member]; @@ -56,7 +69,11 @@ public CompilerObject Member(Compiler.Compiler compiler, CompilerObject instance ); foreach (var parameter in Origin.GenericParameters) - result.Arguments.Add(compiler.CompileIRType(Context.CompileTimeValues.Cache(parameter) ?? throw new())); + result.Arguments.Add( + compiler.CompileIRType( + Context.CompileTimeValues.Cache(GenericArguments[parameter]) ?? GenericArguments[parameter] + ) + ); return result; } @@ -84,12 +101,15 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments GenericClassInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) { - Mapping arguments = []; - - return new(Origin) + context = new(context) { - Context = context + Scope = this }; + + foreach (var (key, value) in GenericArguments) + context.CompileTimeValues.Cache(key, context.CompileTimeValues.Cache(value) ?? value); + + return new(Origin, context); } bool IType.IsEqualTo(Compiler.Compiler compiler, IType type) @@ -101,10 +121,10 @@ bool IType.IsEqualTo(Compiler.Compiler compiler, IType type) return false; foreach (var genericParameter in Origin.GenericParameters) - if (Context[genericParameter] is not IType thisGenericArgument) - throw new Compiler.InvalidCastException(Context[genericParameter], compiler.TypeSystem.Type); - else if (other.Context[genericParameter] is not IType otherGenericArgument) - throw new Compiler.InvalidCastException(other.Context[genericParameter], compiler.TypeSystem.Type); + if (GenericArguments[genericParameter] is not IType thisGenericArgument) + throw new Compiler.InvalidCastException(GenericArguments[genericParameter], compiler.TypeSystem.Type); + else if (other.GenericArguments[genericParameter] is not IType otherGenericArgument) + throw new Compiler.InvalidCastException(other.GenericArguments[genericParameter], compiler.TypeSystem.Type); else if (!compiler.TypeSystem.AreEqual(thisGenericArgument, otherGenericArgument)) return false; diff --git a/ZSharp.Compiler/cg objects/raw/RawCode.cs b/ZSharp.Compiler/cg objects/raw/RawCode.cs index 546e12f1..1313de15 100644 --- a/ZSharp.Compiler/cg objects/raw/RawCode.cs +++ b/ZSharp.Compiler/cg objects/raw/RawCode.cs @@ -5,6 +5,7 @@ namespace ZSharp.Objects public sealed class RawCode(IRCode code) : CompilerObject , ICTReadable + ,ICTTypeCast { private readonly IRCode code = code; @@ -15,6 +16,25 @@ public sealed class RawCode(IRCode code) public IRCode Read(Compiler.Compiler _) => code; + CompilerObject ICTTypeCast.Cast(Compiler.Compiler compiler, IType targetType) + { + if (targetType == compiler.TypeSystem.Void) + { + if (code.IsVoid) return this; + + return new RawCode(new([ + ..code.Instructions, + .. code.Types.Select(_ => new IR.VM.Pop()) + ]) + { + MaxStackSize = code.MaxStackSize, + Types = [] + }); + } + + throw new NotImplementedException(); + } + IType IDynamicallyTyped.GetType(Compiler.Compiler compiler) => code.IsVoid ? compiler.TypeSystem.Void : code.RequireValueType(); } diff --git a/ZSharp.Parser/lang/stmt/LangParser.For.cs b/ZSharp.Parser/lang/stmt/LangParser.For.cs index 8ee8dd33..d76ac139 100644 --- a/ZSharp.Parser/lang/stmt/LangParser.For.cs +++ b/ZSharp.Parser/lang/stmt/LangParser.For.cs @@ -15,7 +15,7 @@ public static ForStatement ParseForStatement(Parser parser) parser.Eat(TokenType.LParen); #endif - var currentItem = parser.Parse(); + var currentItem = ParseForValue(parser); var inKeyword = parser.Eat(Keywords.In); @@ -38,11 +38,36 @@ public static ForStatement ParseForStatement(Parser parser) return new() { - CurrentItem = currentItem, - Iterable = iterable, + Value = currentItem, + Source = iterable, Body = @for, Else = @else, }; } + + private static ForValue ParseForValue(Parser parser) + { + if (parser.Is(Keywords.Let)) + return ParseLetForValue(parser); + + throw new ParseError($"Expected 'let', got {parser.Token}"); + } + + private static LetForValue ParseLetForValue(Parser parser) + { + parser.Eat(Keywords.Let); + + var name = parser.Eat(TokenType.Identifier).Value; + + Expression? type = null; + if (parser.Is(TokenType.Colon, eat: true)) + type = parser.Parse(); + + return new() + { + Name = name, + Type = type + }; + } } } diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs index 27e40af8..6b7325c3 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs @@ -182,6 +182,9 @@ private Method LoadMethod(IL.MethodInfo method) if (!method.IsStatic) result.Signature.Args.Parameters.Add(new("this", Self)); + if (method.IsVirtual) + result.IsVirtual = true; + foreach (var parameter in method.GetParameters()) result.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs index f80a584c..2ad381bc 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs @@ -130,12 +130,13 @@ private CompilerObject CompileNode(LetExpression let) local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); - var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.TypeSystem.ImplicitCast(local.Initializer, local.Type!).Unwrap()); - - code.Instructions.Add(new IR.VM.Dup()); - code.Instructions.Add(new IR.VM.SetLocal(local.IR)); + if (local.IR.Initializer is not null) + return new Objects.RawCode(new(local.IR.Initializer) + { + Types = [local.Type] + }); - return new Objects.RawCode(code); + return new Objects.RawCode(new()); } private CompilerObject CompileNode(VarExpression var) @@ -161,15 +162,11 @@ private CompilerObject CompileNode(VarExpression var) local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); - if (local.Initializer is not null) - { - var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.TypeSystem.ImplicitCast(local.Initializer, local.Type !).Unwrap()); - - code.Instructions.Add(new IR.VM.Dup()); - code.Instructions.Add(new IR.VM.SetLocal(local.IR)); - - return new Objects.RawCode(code); - } + if (local.IR.Initializer is not null) + return new Objects.RawCode(new(local.IR.Initializer) + { + Types = [local.Type] + }); return new Objects.RawCode(new()); } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs index 76f3d1f9..e91cbefb 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs @@ -8,6 +8,7 @@ public sealed class FunctionCompiler(ZSSourceCompiler compiler, Function node) public override Objects.RTFunction Compile() { using (Context.Compiler(this)) + using (Compiler.Compiler.ContextScope(new FunctionContext(Compiler.Compiler, Object))) using (Context.Scope(Object)) CompileFunction(); @@ -42,6 +43,7 @@ private void CompileFunction() multipassCompiler.AddToNextPass(() => { using (Context.Compiler(this)) + using (Compiler.Compiler.ContextScope(new FunctionContext(Compiler.Compiler, Object))) using (Context.Scope(Object)) using (Context.Scope()) CompileFunctionBody(); @@ -125,12 +127,13 @@ private CompilerObject CompileNode(LetExpression let) local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); - var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.TypeSystem.ImplicitCast(local.Initializer, local.Type !).Unwrap()); - - code.Instructions.Add(new IR.VM.Dup()); - code.Instructions.Add(new IR.VM.SetLocal(local.IR)); + if (local.IR.Initializer is not null) + return new Objects.RawCode(new(local.IR.Initializer) + { + Types = [local.Type] + }); - return new Objects.RawCode(code); + return new Objects.RawCode(new()); } private CompilerObject CompileNode(VarExpression var) @@ -156,15 +159,11 @@ private CompilerObject CompileNode(VarExpression var) local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); - if (local.Initializer is not null) - { - var code = Compiler.Compiler.CompileIRCode(Compiler.Compiler.TypeSystem.ImplicitCast(local.Initializer, local.Type !).Unwrap()); - - code.Instructions.Add(new IR.VM.Dup()); - code.Instructions.Add(new IR.VM.SetLocal(local.IR)); - - return new Objects.RawCode(code); - } + if (local.IR.Initializer is not null) + return new Objects.RawCode(new(local.IR.Initializer) + { + Types = [local.Type] + }); return new Objects.RawCode(new()); } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs new file mode 100644 index 00000000..a1897a8d --- /dev/null +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs @@ -0,0 +1,124 @@ + +namespace ZSharp.ZSSourceCompiler +{ + public class ForStatementCompiler(ZSSourceCompiler compiler, ForStatement node) + : ContextCompiler(compiler, node, new()) + , IOverrideCompileStatement + { + private CompilerObject Iterator { get; set; } + + private CompilerObject MoveNext { get; set; } + + private CompilerObject Current { get; set; } + + public override ForLoop Compile() + { + var source = Object.Source = Compiler.CompileNode(Node.Source); + + Iterator = Compiler.Compiler.Member(source, "getIterator"); + Iterator = Compiler.Compiler.Call(Iterator, []); + if (!Compiler.Compiler.TypeSystem.IsTyped(Iterator, out var iteratorType)) + { + Compiler.LogError($"For loop source must provide a valid iterator", Node); + return Object; + } + + MoveNext = Compiler.Compiler.Member(new Objects.RawCode(new([ + new IR.VM.Dup() + ]) + { + Types = [iteratorType] + }), "moveNext"); + MoveNext = Compiler.Compiler.Call(MoveNext, []); + MoveNext = Compiler.Compiler.Cast(MoveNext, Compiler.Compiler.TypeSystem.Boolean); + + Current = Compiler.Compiler.Member(new Objects.RawCode(new([ + new IR.VM.Dup() + ]) + { + Types = [iteratorType] + }), "getCurrent"); + Current = Compiler.Compiler.Call(Current, []); + + Object.Iterator = Iterator; + Object.MoveNext = MoveNext; + Object.Current = Current; + + using (Context.Compiler(this)) + using (Context.Scope()) + { + CompileForValue(); + Object.For = Compiler.CompileNode(Node.Body); + } + + if (Node.Else is not null) + using (Context.Scope()) + Object.Else = CompileElse(); + + return base.Compile(); + } + + protected CompilerObject CompileBreak(BreakStatement @break) + { + // TODO: add support for 'break from' statement + + if (@break.Value is not null) + Compiler.LogError("Break statement in a for statement must not have a value", @break); + + return new Objects.RawCode( + new([ + new IR.VM.Jump(Object.EndLabel) + ]) + ); + } + + protected CompilerObject CompileElse() + => Compiler.CompileNode(Node.Else!); + + public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement node) + => node switch + { + BreakStatement @break => CompileBreak(@break), + _ => null + }; + + private void CompileForValue() + { + Object.Value = Node.Value switch { + LetForValue let => CompileLetForValue(let), + _ => throw new() + }; + } + + private CompilerObject CompileLetForValue(LetForValue let) + { + var allocator = Compiler.Compiler.CurrentContext.FindContext(); + if (allocator is null) + { + Compiler.LogError($"Could not find memory allocator in context chain", Node); + + throw new(); + } + + var local = allocator.Allocate( + let.Name, + let.Type is not null + ? Compiler.CompileType(let.Type) + : Compiler.Compiler.TypeSystem.IsTyped(Current, out var type) + ? type + : throw new(), + Current + ); + + if (local is not Objects.Local local1) + throw new NotImplementedException(); + + Compiler.Context.CurrentScope.Set(let.Name, local); + + return new Objects.RawCode(new(local1.IR?.Initializer!) + { + Types = [local1.Type] + }); + } + } +} diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/ForLoop.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/ForLoop.cs new file mode 100644 index 00000000..2d033bc5 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/ForLoop.cs @@ -0,0 +1,65 @@ +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler +{ + public sealed class ForLoop + : CompilerObject + , ICompileIRCode + { + public CompilerObject Iterator { get; set; } + + public CompilerObject MoveNext { get; set; } + + public CompilerObject Current { get; set; } + + public CompilerObject Value { get; set; } + + public CompilerObject Source { get; set; } + + public IR.VM.Instruction NextLabel { get; } = new IR.VM.Nop(); + + public CompilerObject For { get; set; } + + public IR.VM.Instruction ElseLabel { get; } = new IR.VM.Nop(); + + public CompilerObject? Else { get; set; } + + public IR.VM.Instruction EndLabel { get; } = new IR.VM.Nop(); + + public IRCode CompileIRCode(Compiler.Compiler compiler) + { + return new([ + .. compiler.CompileIRCode( + Iterator + ).Instructions, + + NextLabel, + + .. compiler.CompileIRCode( + MoveNext + ).Instructions, + + new IR.VM.JumpIfFalse(ElseLabel), + + .. compiler.CompileIRCode( + compiler.Cast( + Value, + compiler.TypeSystem.Void + ) + ).Instructions, + + .. compiler.CompileIRCode(For).Instructions, + + new IR.VM.Jump(NextLabel), + + ElseLabel, + .. Else is null ? [] : compiler.CompileIRCode(Else).Instructions, + + EndLabel, + + new IR.VM.Pop() // Iterator + ] + ); + } + } +} diff --git a/ZSharp.ZSSourceCompiler/context/Context.Scopes.cs b/ZSharp.ZSSourceCompiler/context/Context.Scopes.cs index a6c78dbf..1c80b446 100644 --- a/ZSharp.ZSSourceCompiler/context/Context.Scopes.cs +++ b/ZSharp.ZSSourceCompiler/context/Context.Scopes.cs @@ -7,9 +7,9 @@ public sealed partial class Context private readonly Mapping objectContainerScopes = []; private readonly Mapping objectContainedScopes = []; - public ScopeContext GlobalScope { get; } + public IScopeContext GlobalScope { get; } - public ScopeContext CurrentScope { get; private set; } + public IScopeContext CurrentScope { get; private set; } public ScopeContext CreateScope() => new(); @@ -17,7 +17,7 @@ public ScopeContext CreateScope() public ContextManager Scope() => Scope(CreateScope()); - public ContextManager Scope(ScopeContext scope) + public ContextManager Scope(IScopeContext scope) { (CurrentScope, scope) = (scope, CurrentScope); var revert = CurrentCompiler.Compiler.Compiler.UseContext(CurrentScope); diff --git a/ZSharp.ZSSourceCompiler/contexts/capabilities/IMemoryAllocator.cs b/ZSharp.ZSSourceCompiler/contexts/capabilities/IMemoryAllocator.cs new file mode 100644 index 00000000..29e00f80 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/contexts/capabilities/IMemoryAllocator.cs @@ -0,0 +1,14 @@ +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler +{ + public interface IMemoryAllocator + : IContext + { + public CompilerObject Allocate( + string name, + IType type, + CompilerObject? initializer = null + ); + } +} diff --git a/ZSharp.ZSSourceCompiler/contexts/capabilities/IObjectContext.cs b/ZSharp.ZSSourceCompiler/contexts/capabilities/IObjectContext.cs new file mode 100644 index 00000000..5692bd58 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/contexts/capabilities/IObjectContext.cs @@ -0,0 +1,20 @@ +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler +{ + public interface IObjectContext + : IContext + { + public CompilerObject Object { get; } + } + + public interface IObjectContext + : IContext + , IObjectContext + where T : CompilerObject + { + public new T Object { get; } + + CompilerObject IObjectContext.Object => Object; + } +} diff --git a/ZSharp.ZSSourceCompiler/contexts/capabilities/IScopeContext.cs b/ZSharp.ZSSourceCompiler/contexts/capabilities/scope/ILookupContext.cs similarity index 54% rename from ZSharp.ZSSourceCompiler/contexts/capabilities/IScopeContext.cs rename to ZSharp.ZSSourceCompiler/contexts/capabilities/scope/ILookupContext.cs index 05ba08c1..219fecc8 100644 --- a/ZSharp.ZSSourceCompiler/contexts/capabilities/IScopeContext.cs +++ b/ZSharp.ZSSourceCompiler/contexts/capabilities/scope/ILookupContext.cs @@ -3,19 +3,20 @@ namespace ZSharp.ZSSourceCompiler { - public interface IScopeContext + public interface ILookupContext : IContext { public CompilerObject? Get(string name); public T? Get(string name) - where T : class, CompilerObject; + where T : class, CompilerObject + => Get(name) is T value ? value : null; - public bool Get(string name, [NotNullWhen(true)] out CompilerObject? result); + public bool Get(string name, [NotNullWhen(true)] out CompilerObject? result) + => (result = Get(name)) is not null; public bool Get(string name, [NotNullWhen(true)] out T? result) - where T : class, CompilerObject; - - public void Set(string name, CompilerObject @object); + where T : class, CompilerObject + => (result = Get(name)) is not null; } } diff --git a/ZSharp.ZSSourceCompiler/contexts/capabilities/scope/IScopeContext.cs b/ZSharp.ZSSourceCompiler/contexts/capabilities/scope/IScopeContext.cs new file mode 100644 index 00000000..cc7df7dc --- /dev/null +++ b/ZSharp.ZSSourceCompiler/contexts/capabilities/scope/IScopeContext.cs @@ -0,0 +1,11 @@ +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler +{ + public interface IScopeContext + : IContext + , ILookupContext + { + public void Set(string name, CompilerObject @object); + } +} diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/FunctionContext.cs b/ZSharp.ZSSourceCompiler/contexts/concrete/FunctionContext.cs new file mode 100644 index 00000000..20a0e461 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/contexts/concrete/FunctionContext.cs @@ -0,0 +1,34 @@ +using ZSharp.Compiler; +using ZSharp.Objects; + +namespace ZSharp.ZSSourceCompiler +{ + public sealed class FunctionContext( + Compiler.Compiler compiler, + RTFunction function + ) + : IContext + , IMemoryAllocator + , IObjectContext + { + public IContext? Parent { get; set; } + + public RTFunction Function { get; } = function; + + RTFunction IObjectContext.Object => Function; + + CompilerObject IMemoryAllocator.Allocate(string name, IType type, CompilerObject? initializer) + { + Local local = new() + { + Name = name, + Initializer = initializer, + Type = type + }; + + local.IR = compiler.CompileIRObject(local, Function.IR?.Body ?? throw new()); + + return local; + } + } +} diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs b/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs index 9fd33dfa..00fc7a1a 100644 --- a/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs +++ b/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs @@ -1,5 +1,4 @@ using CommonZ.Utils; -using System.Diagnostics.CodeAnalysis; using ZSharp.Compiler; namespace ZSharp.ZSSourceCompiler @@ -14,18 +13,6 @@ public sealed class ScopeContext() public CompilerObject? Get(string name) => scope.TryGetValue(name, out var result) ? result : null; - - public T? Get(string name) - where T : class, CompilerObject - => Get(name) is T result ? result : null; - - public bool Get(string name, [NotNullWhen(true)] out CompilerObject? result) - => (result = Get(name)) is not null; - - public bool Get(string name, [NotNullWhen(true)] out T? result) - where T : class, CompilerObject - => (result = Get(name)) is not null; - public void Set(string name, CompilerObject @object) => scope[name] = @object; } diff --git a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs index 04c31967..fcceff6e 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs @@ -9,6 +9,7 @@ public sealed class StatementCompiler(ZSSourceCompiler compiler) BlockStatement block => Compile(block), CaseStatement @case => Compile(@case), ExpressionStatement expressionStatement => Compile(expressionStatement), + ForStatement @for => Compile(@for), IfStatement @if => Compile(@if), ImportStatement import => Compile(import), _ => null @@ -74,6 +75,9 @@ private CompilerObject Compile(CaseStatement @case) return result; } + private ForLoop Compile(ForStatement @for) + => new ForStatementCompiler(Compiler, @for).Compile(); + private CompilerObject Compile(IfStatement @if) { var result = new Objects.If() diff --git a/ZSharpTest/Properties/launchSettings.json b/ZSharpTest/Properties/launchSettings.json index a7532ffc..dcafed79 100644 --- a/ZSharpTest/Properties/launchSettings.json +++ b/ZSharpTest/Properties/launchSettings.json @@ -27,6 +27,10 @@ "Simple Test": { "commandName": "Project", "commandLineArgs": "tests/simple.zs" + }, + "Profile 1": { + "commandName": "Project", + "commandLineArgs": "test.zs" } } } \ No newline at end of file diff --git a/ZSharpTest/projects/todo.zs b/ZSharpTest/projects/todo.zs index c02d0aeb..3368875f 100644 --- a/ZSharpTest/projects/todo.zs +++ b/ZSharpTest/projects/todo.zs @@ -20,22 +20,12 @@ module Program { } fun getTodos(): void { - var i = 0; - - while (i < todo.length()) - { - let item = todo.get(i); - print(string(i + 1) + ". " + item); - - i = i + 1; - } - /* - for (let item = 0 in todo) + var i = 1; + for (let item in todo) { print(string(i) + ". " + item); i = i + 1; } - */ return; } @@ -45,6 +35,8 @@ module Program { todo.removeAt(index - 1); + getTodos(); + return; } diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs index f2e40587..7da81bf6 100644 --- a/ZSharpTest/tests/simple.zs +++ b/ZSharpTest/tests/simple.zs @@ -1,5 +1,6 @@ import { input, print } from "std:io"; import { + BaseClass, Console, List, TestClass, @@ -49,6 +50,11 @@ fun testInterface(test: TestInterface): void { return; } +fun testBaseClass(test: BaseClass): void { + test.doVirtual(); + return; +} + fun main(): void { let c1 = MyClass(); let c2 = OtherClass(5); @@ -59,6 +65,9 @@ fun main(): void { let tc = TestClass(); print(tc.id[string]("Id [T: string] of TestClass")); + testBaseClass(BaseClass()); + testBaseClass(tc); + return; } From 2605e3b977c04e5fd389e608920dd19cdc1d7607 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 13 May 2025 14:10:29 +0300 Subject: [PATCH 153/235] Fix method inside generic type resolution --- .../oop/constructor/Constructor.cs | 2 + ZSharp.Parser/lang/stmt/LangParser.For.cs | 4 +- ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 29 ++++++++---- .../class body/ConstructorCompiler.cs | 17 +++++-- .../builtin-compilers/module/ClassCompiler.cs | 2 + .../contexts/concrete/ClassContext.cs | 17 +++++++ .../contexts/concrete/ScopeContext.cs | 1 + .../strategies/UntilContextTypeStrategy.cs | 20 +++++++++ ZSharpTest/projects/better-user-system.zs | 44 ++++++++----------- 9 files changed, 97 insertions(+), 39 deletions(-) create mode 100644 ZSharp.ZSSourceCompiler/contexts/concrete/ClassContext.cs create mode 100644 ZSharp.ZSSourceCompiler/contexts/strategies/UntilContextTypeStrategy.cs diff --git a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs index a8275940..fc971160 100644 --- a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs +++ b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs @@ -122,6 +122,8 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) Method = new(compiler.RuntimeModule.TypeSystem.Void) }; + Signature.ReturnType ??= compiler.TypeSystem.Void; + if (owner is not null && !state.Get(BuildState.Owner)) { owner.Constructors.Add(IR); diff --git a/ZSharp.Parser/lang/stmt/LangParser.For.cs b/ZSharp.Parser/lang/stmt/LangParser.For.cs index d76ac139..c6bac4a6 100644 --- a/ZSharp.Parser/lang/stmt/LangParser.For.cs +++ b/ZSharp.Parser/lang/stmt/LangParser.For.cs @@ -29,7 +29,9 @@ public static ForStatement ParseForStatement(Parser parser) parser.Eat(Symbols.ThenDo); #endif - var @for = parser.Parse(); + Statement @for; + using (parser.Stack(LoopBody.Content)) + @for = parser.Parse(); Statement? @else = null; diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index 7fa476b5..e5f1ee9d 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -90,11 +90,16 @@ public IL.ConstructorInfo LoadReference(IR.ConstructorReference @ref) if (type.GetGenericTypeDefinition() is IL.Emit.TypeBuilder typeBuilder) if (!typeBuilder.IsCreated()) return IL.Emit.TypeBuilder.GetConstructor(type, constructorInfo); - - return (IL.ConstructorInfo)(IL.MethodBase.GetMethodFromHandle( - constructorInfo.MethodHandle, - type.TypeHandle - ) ?? throw new("Could not create constructor from method handle")); + try + { + return (IL.ConstructorInfo)(IL.MethodBase.GetMethodFromHandle( + constructorInfo.MethodHandle, + type.TypeHandle + ) ?? throw new("Could not create constructor from method handle")); + } catch (NotSupportedException) + { + return IL.Emit.TypeBuilder.GetConstructor(type, constructorInfo); + } } public IL.FieldInfo LoadReference(IR.FieldReference @ref) @@ -133,10 +138,16 @@ public IL.MethodInfo LoadReference(IR.MethodReference @ref) if (!typeBuilder.IsCreated()) methodInfo = IL.Emit.TypeBuilder.GetMethod(type, methodInfo); } else - methodInfo = (IL.MethodInfo)(IL.MethodBase.GetMethodFromHandle( - methodInfo.MethodHandle, - type.TypeHandle - ) ?? throw new("Could not create method from method handle")); + try + { + methodInfo = (IL.MethodInfo)(IL.MethodBase.GetMethodFromHandle( + methodInfo.MethodHandle, + type.TypeHandle + ) ?? throw new("Could not create method from method handle")); + } catch (NotSupportedException) + { + methodInfo = IL.Emit.TypeBuilder.GetMethod(type, methodInfo); + } if (@ref is IR.ConstructedMethod constructed) methodInfo = methodInfo.MakeGenericMethod([ diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs index 58805dfc..58774321 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs @@ -1,4 +1,6 @@ -namespace ZSharp.ZSSourceCompiler +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler { public sealed class ConstructorCompiler(ZSSourceCompiler compiler, Constructor node) : ContextCompiler(compiler, node, new(node.Name)) @@ -77,8 +79,17 @@ private Objects.Parameter Compile(Parameter parameter) private CompilerObject? Compile(IdentifierExpression identifier) { - if (!Context.CurrentScope.Get(identifier.Name, out var member)) - return null; + CompilerObject? member = null; + + Compiler.Compiler.CurrentContext.PerformOperation( + scope => + { + return scope.Get(identifier.Name, out member); + }, + new UntilContextTypeStrategy>( + new ParentContextStrategy() + ) + ); if (member is Objects.IRTBoundMember boundMember) return boundMember.Bind(Compiler.Compiler, This); diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs index b1d5873b..b0ca90b6 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs @@ -34,6 +34,7 @@ public override Class Compile() var bodyCompiler = new ClassBodyCompiler(Compiler, Node, Object); using (Context.Compiler(this)) + using (Compiler.Compiler.ContextScope(new ClassContext(Object))) using (Context.Scope(Object)) { bodyCompiler.Compile(); @@ -45,6 +46,7 @@ public override Class Compile() ResolveImplementation(abstraction); using (Context.Compiler(this)) + using (Compiler.Compiler.ContextScope(new ClassContext(Object))) using (Context.Scope(Object)) bodyCompiler.CompileUntilComplete(); diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/ClassContext.cs b/ZSharp.ZSSourceCompiler/contexts/concrete/ClassContext.cs new file mode 100644 index 00000000..d28d6c4f --- /dev/null +++ b/ZSharp.ZSSourceCompiler/contexts/concrete/ClassContext.cs @@ -0,0 +1,17 @@ +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler +{ + public sealed class ClassContext( + Objects.Class @class + ) + : IContext + , IObjectContext + { + public IContext? Parent { get; set; } + + public Objects.Class Class { get; } = @class; + + Objects.Class IObjectContext.Object => Class; + } +} diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs b/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs index 00fc7a1a..4b60a6a3 100644 --- a/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs +++ b/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs @@ -13,6 +13,7 @@ public sealed class ScopeContext() public CompilerObject? Get(string name) => scope.TryGetValue(name, out var result) ? result : null; + public void Set(string name, CompilerObject @object) => scope[name] = @object; } diff --git a/ZSharp.ZSSourceCompiler/contexts/strategies/UntilContextTypeStrategy.cs b/ZSharp.ZSSourceCompiler/contexts/strategies/UntilContextTypeStrategy.cs new file mode 100644 index 00000000..e17cb45d --- /dev/null +++ b/ZSharp.ZSSourceCompiler/contexts/strategies/UntilContextTypeStrategy.cs @@ -0,0 +1,20 @@ +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler +{ + public sealed class UntilContextTypeStrategy( + IContextChainStrategy strategy + ) + : IContextChainStrategy + where T : IContext + { + public IContextChainStrategy Strategy { get; } = strategy; + + IContext? IContextChainStrategy.NextContext(IContext context) + { + if (context is T) return null; + + return Strategy.NextContext(context); + } + } +} diff --git a/ZSharpTest/projects/better-user-system.zs b/ZSharpTest/projects/better-user-system.zs index ef0716b5..b9c95cf0 100644 --- a/ZSharpTest/projects/better-user-system.zs +++ b/ZSharpTest/projects/better-user-system.zs @@ -6,31 +6,20 @@ * [x] Named constructor * [x] Methods * [x] Case-Of - * [ ] Automatic type inference for first parameter in methods - * [ ] Automatic instance binding when accessing instance method/field from instance method - * [ ] Instance method as function with `this` first parameter + * [x] Automatic type inference for first parameter in methods + * [x] Automatic instance binding when accessing instance method/field from instance method + * [x] Instance method as function with `this` first parameter * [x] Module globals initializers */ import { input, print } from "std:io"; -import { List } from "std:list"; +import { List } from "net:ZLoad.Test.dll"; module Program; -class Authentication { - var username: string; - var password: string; - - new(this, username: string, password: string) { - this.username = username; - this.password = password; - } -} - - class User { var isAdmin: bool; @@ -56,10 +45,6 @@ class User { return true; } - - fun login(auth: Authentication, this: User): bool { - return this.login(auth.username, auth.password); - } } @@ -83,10 +68,15 @@ fun signIn(): void { let username = input("Username: "); let password = input("Password: "); - case (Authentication(username, password)) of (User.login) { - when (user) print("USER"); // userTerminal(); - when (admin) print("ADMIN"); // adminTerminal(); - } else print("Invalid credentials."); + + for (let user in users) { + if (user.login(username, password)) { + print("Successfully logged in to user: " + user.username); + break; + } + } else { + print("Could not log in with provided credentials"); + } return; } @@ -94,11 +84,13 @@ fun signIn(): void { fun main(): void { while (mainMenu()) ; - else print("Thank you for using Simple User System!"); + else print("Thank you for using Better User System!"); return; } -let user = User("user", "123"); -let admin = User.Admin("admin", "321"); +let users: List[User] = [ + User("user", "123"), + User.Admin("admin", "321") +]; From 27d27967c4a31228b1eb49b90d8797e7b954ed27 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 13 May 2025 15:39:31 +0300 Subject: [PATCH 154/235] Add simply file system module --- ZSharp v1.sln | 6 +++ .../Directory.cs | 29 ++++++++++++++ ZSharp.CT.StandardLibrary.FileSystem/File.cs | 21 ++++++++++ .../Global_Operators.cs | 16 ++++++++ ZSharp.CT.StandardLibrary.FileSystem/Path.cs | 40 +++++++++++++++++++ ...Sharp.CT.StandardLibrary.FileSystem.csproj | 14 +++++++ .../ir loader/IRLoader.Impl.cs | 3 ++ .../oop/method/concrete/Method.cs | 4 +- .../il2ir/loaders/ClassLoader.cs | 4 +- .../class body/MethodCompiler.cs | 5 ++- ZSharpTest/ZSharpTest.csproj | 1 + ZSharpTest/tests/simple.zs | 7 ++++ 12 files changed, 146 insertions(+), 4 deletions(-) create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/Directory.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/File.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/Path.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj diff --git a/ZSharp v1.sln b/ZSharp v1.sln index debf3750..b43c1142 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -50,6 +50,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Testing", "Testing\Testing. EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZLoad.Test", "ZLoad.Test\ZLoad.Test.csproj", "{9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.StandardLibrary.FileSystem", "ZSharp.CT.StandardLibrary.FileSystem\ZSharp.CT.StandardLibrary.FileSystem.csproj", "{7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -144,6 +146,10 @@ Global {9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}.Debug|Any CPU.Build.0 = Debug|Any CPU {9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}.Release|Any CPU.ActiveCfg = Release|Any CPU {9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}.Release|Any CPU.Build.0 = Release|Any CPU + {7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZSharp.CT.StandardLibrary.FileSystem/Directory.cs b/ZSharp.CT.StandardLibrary.FileSystem/Directory.cs new file mode 100644 index 00000000..ff5df999 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/Directory.cs @@ -0,0 +1,29 @@ +using ZSharp.Runtime.NET.IL2IR; + +namespace Standard.FileSystem +{ + public sealed class Directory + { + public Path path; + + internal Directory(Path path) + { + this.path = path; + } + + internal Directory(string path) + : this(new Path(path)) { } + + [Alias(Name = "sub")] + public Path SubPath(string name) + => Global_Operators.SubPath(this, name); + + [Alias(Name = "cwd")] + public static Directory CurrentWorkingDirectory() + => new(System.IO.Directory.GetCurrentDirectory()); + + [Alias(Name = "toString")] + public override string ToString() + => $"Directory<{path}>"; + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/File.cs b/ZSharp.CT.StandardLibrary.FileSystem/File.cs new file mode 100644 index 00000000..cbf45093 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/File.cs @@ -0,0 +1,21 @@ +using ZSharp.Runtime.NET.IL2IR; + +namespace Standard.FileSystem +{ + public sealed class File + { + internal Path path; + + internal File(Path path) + { + this.path = path; + } + + internal File(string path) + : this(new Path(path)) { } + + [Alias(Name = "toString")] + public override string ToString() + => $"File<{path}>"; + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs b/ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs new file mode 100644 index 00000000..e3725592 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs @@ -0,0 +1,16 @@ +using ZSharp.Runtime.NET.IL2IR; + +namespace Standard.FileSystem +{ + [ModuleGlobals] + public static class Global_Operators + { + [Alias(Name = "_/_")] + public static Path SubPath(Path path, string name) + => new(System.IO.Path.Combine(path.path, name)); + + [Alias(Name = "_/_")] + public static Path SubPath(Directory directory, string name) + => SubPath(directory.path, name); + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/Path.cs b/ZSharp.CT.StandardLibrary.FileSystem/Path.cs new file mode 100644 index 00000000..9d07b7b4 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/Path.cs @@ -0,0 +1,40 @@ +using ZSharp.Runtime.NET.IL2IR; + +namespace Standard.FileSystem +{ + public class Path + { + internal string path; + + internal Path(string path) + { + this.path = path; + } + + [Alias(Name = "asDirectory")] + public Directory? AsDirectory() + { + if (System.IO.Directory.Exists(path)) + return new(path); + + return null; + } + + [Alias(Name = "asFile")] + public File? AsFile() + { + if (System.IO.File.Exists(path)) + return new(path); + + return null; + } + + [Alias(Name = "sub")] + public Path SubPath(string name) + => Global_Operators.SubPath(this, name); + + [Alias(Name = "toString")] + public override string ToString() + => path; + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj b/ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj new file mode 100644 index 00000000..60f3ccc3 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj @@ -0,0 +1,14 @@ + + + + net8.0 + enable + enable + Standard.FileSystem + + + + + + + diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index 7ef1b141..478aa916 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -182,6 +182,7 @@ private Action Load(IR.Class @class, Module owner) { IR = method, Defined = true, + Owner = result, Signature = Load(method.Signature) }; } @@ -265,6 +266,7 @@ private Action Load(IR.Interface @interface, Module owner) { IR = method, Defined = true, + Owner = result }; result.Content.Add(resultMethod); @@ -424,6 +426,7 @@ private Action LoadGenericClass(IR.Class @class, Module owner) { IR = method, Defined = true, + Owner = result }; if (resultMethod.Name is not null && resultMethod.Name != string.Empty) { diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs index fa9f8c08..9db60cbd 100644 --- a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs +++ b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs @@ -45,6 +45,8 @@ public bool Defined { init public string Name { get; set; } = name ?? string.Empty; + public CompilerObject Owner { get; set; } + public Signature Signature { get; set; } = new(); public IType? ReturnType @@ -172,7 +174,7 @@ CompilerObject IImplicitCastToType.ImplicitCastToType(Compiler.Compiler compiler compiler.CompileIRObject(this, null) ) { - OwningType = (IR.OOPTypeReference)IR!.Signature.Args.Parameters[0].Type, // TODO: add Owner property + OwningType = compiler.CompileIRType(Owner) }; void IImplementsSpecification.OnImplementSpecification(Compiler.Compiler compiler, IAbstraction abstraction, CompilerObject specification) diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs index 6b7325c3..1157efcb 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs @@ -1,5 +1,4 @@ -using CommonZ.Utils; -using System.Reflection; +using System.Reflection; using ZSharp.IR; namespace ZSharp.Runtime.NET.IL2IR @@ -181,6 +180,7 @@ private Method LoadMethod(IL.MethodInfo method) if (!method.IsStatic) result.Signature.Args.Parameters.Add(new("this", Self)); + else result.IsStatic = true; if (method.IsVirtual) result.IsVirtual = true; diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs index 2ad381bc..e94ade80 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs @@ -1,7 +1,10 @@ namespace ZSharp.ZSSourceCompiler { public sealed class MethodCompiler(ZSSourceCompiler compiler, Function node, CompilerObject owner, Compiler.IType self) - : ContextCompiler(compiler, node, new(node.Name)) + : ContextCompiler(compiler, node, new(node.Name) + { + Owner = owner + }) , IOverrideCompileStatement { public Objects.Parameter? This { get; private set; } = null; diff --git a/ZSharpTest/ZSharpTest.csproj b/ZSharpTest/ZSharpTest.csproj index c33a7ed1..980ea137 100644 --- a/ZSharpTest/ZSharpTest.csproj +++ b/ZSharpTest/ZSharpTest.csproj @@ -15,6 +15,7 @@ + diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs index 7da81bf6..a1ab78b0 100644 --- a/ZSharpTest/tests/simple.zs +++ b/ZSharpTest/tests/simple.zs @@ -8,6 +8,7 @@ import { greet, id } from "net:ZLoad.Test.dll"; +import { Directory } from "net:ZSharp.CT.StandardLibrary.FileSystem.dll"; module Program; @@ -68,6 +69,12 @@ fun main(): void { testBaseClass(BaseClass()); testBaseClass(tc); + let cwd = Directory.cwd(); + print(cwd.toString()); + let filePath = cwd.sub("tests").sub("simple.zs"); + print(filePath.toString()); + print(filePath.asFile().toString()); + return; } From b71381db1a25b263f6cc1ce921e28483060765b1 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 18 May 2025 00:08:16 +0300 Subject: [PATCH 155/235] Add support for \t in string and char literals --- ZSharp.Tokenizer/Tokenizer.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ZSharp.Tokenizer/Tokenizer.cs b/ZSharp.Tokenizer/Tokenizer.cs index 6f77cb3b..ab07596b 100644 --- a/ZSharp.Tokenizer/Tokenizer.cs +++ b/ZSharp.Tokenizer/Tokenizer.cs @@ -20,6 +20,7 @@ public static class Tokenizer private const char LF = '\n'; private const char CR = '\r'; + private const char Tab = '\t'; private const string Operators = "./|+-=<>!@#$%^&*~?"; @@ -58,6 +59,7 @@ Token ReadString() { 'n' => LF, 'r' => CR, + 't' => Tab, StringQuotation => StringQuotation, CharQuotation => CharQuotation, BackSlash => stream.Read(), @@ -84,6 +86,7 @@ Token ReadChar() { 'n' => LF, 'r' => CR, + 't' => Tab, StringQuotation => StringQuotation, CharQuotation => CharQuotation, BackSlash => stream.Read(), @@ -197,7 +200,7 @@ Token EOF() LF => SingleChar(TokenType.NewLine), CR => SingleChar(TokenType.NewLine), ' ' => SingleChar(TokenType.Space), - '\t' => SingleChar(TokenType.Tab), + Tab => SingleChar(TokenType.Tab), '{' => SingleChar(TokenType.LCurly), '}' => SingleChar(TokenType.RCurly), '(' => SingleChar(TokenType.LParen), From 90590c8ad35da7f6446161aec62317214e43be07 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 18 May 2025 00:08:48 +0300 Subject: [PATCH 156/235] Patch document compiler to not handle statements --- .../document/compiler/DocumentCompiler.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs index 90b9210b..8f646947 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs @@ -4,6 +4,7 @@ namespace ZSharp.ZSSourceCompiler public sealed partial class DocumentCompiler(ZSSourceCompiler compiler, AST.Document node, Document document) : ContextCompiler(compiler, node, document) , IOverrideCompileExpression + , IOverrideCompileStatement { public override Document Compile() { @@ -20,11 +21,12 @@ private void CompileDocument() Compiler.CompileNode(item); } - private void Compile(Statement statement) + public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement statement) { - if (statement is ExpressionStatement expressionStatement) - Compiler.Compiler.Evaluate(Compiler.CompileNode(expressionStatement.Expression)); + //if (statement is ExpressionStatement expressionStatement) + // return Compiler.Compiler.Evaluate(Compiler.CompileNode(expressionStatement.Expression)); + return null; // if the statement is a definition, compile it } From 4fafb0cf66cda9090613cada96b80bbe9f1e8073 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 26 May 2025 21:07:22 +0300 Subject: [PATCH 157/235] Add support for loading operator from any IR module --- ZSharp.Compiler.Features/operators/Ops.cs | 10 +++++++ .../ir loader/IRLoader.Impl.cs | 26 ++++++++++++++++++- ZSharp.Interpreter/Interpreter.cs | 2 ++ .../compiler/ZSSourceCompiler.Operators.cs | 6 ++--- .../compiler/ZSSourceCompiler.cs | 6 ++++- .../expression/ExpressionCompiler.cs | 2 +- .../statement/StatementCompiler.cs | 2 +- ZSharpTest/Main.cs | 21 +-------------- 8 files changed, 47 insertions(+), 28 deletions(-) create mode 100644 ZSharp.Compiler.Features/operators/Ops.cs diff --git a/ZSharp.Compiler.Features/operators/Ops.cs b/ZSharp.Compiler.Features/operators/Ops.cs new file mode 100644 index 00000000..bc82de5d --- /dev/null +++ b/ZSharp.Compiler.Features/operators/Ops.cs @@ -0,0 +1,10 @@ +using CommonZ.Utils; +using ZSharp.Objects; + +namespace ZSharp.Compiler +{ + public sealed class Ops(Compiler compiler) : Feature(compiler) + { + public Cache Binary = []; + } +} diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index 478aa916..8759e71f 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -1,4 +1,6 @@ -namespace ZSharp.Compiler.IRLoader +using System.Text.RegularExpressions; + +namespace ZSharp.Compiler.IRLoader { public partial class IRLoader { @@ -40,6 +42,28 @@ private Module Import(IR.Module module, Module result) foreach (var action in actions) action(); + var ops = Compiler.Feature(); + + if (module.HasFunctions) + foreach (var function in module.Functions) + { + if (function.Name is null || function.Name == string.Empty) + continue; + + var match = Regex.Match(function.Name, @"^_?(?[+\-*/=?&^%$#@!<>|~]+)_?$"); + if (match.Success) + { + var op = match.Groups["OP"].Value; + if (!ops.Binary.Cache(op, out var group)) + group = ops.Binary.Cache(op, new OverloadGroup(op)); + + if (group is not OverloadGroup overloadGroup) + throw new Exception("Invalid overload group!"); + + overloadGroup.Overloads.Add(Import(function)); + } + } + return result; } diff --git a/ZSharp.Interpreter/Interpreter.cs b/ZSharp.Interpreter/Interpreter.cs index fef22b37..595b682f 100644 --- a/ZSharp.Interpreter/Interpreter.cs +++ b/ZSharp.Interpreter/Interpreter.cs @@ -22,6 +22,8 @@ public Interpreter(IR.RuntimeModule? runtimeModule = null) Compiler = new(RuntimeModule); + new Compiler.Ops(Compiler); + CompilerIRLoader = new(Compiler); SourceCompiler = new(Compiler); diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Operators.cs b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Operators.cs index 7b2b405c..fb26c5c1 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Operators.cs +++ b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Operators.cs @@ -1,9 +1,7 @@ -using CommonZ.Utils; - -namespace ZSharp.ZSSourceCompiler +namespace ZSharp.ZSSourceCompiler { public partial class ZSSourceCompiler { - public Cache Operators { get; } = []; + public Compiler.Ops Operators { get; } } } diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs index 2fda069e..071d9fac 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs +++ b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs @@ -1,4 +1,6 @@ -namespace ZSharp.ZSSourceCompiler +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler { public sealed partial class ZSSourceCompiler : Compiler.Feature { @@ -16,6 +18,8 @@ public ZSSourceCompiler(Compiler.Compiler compiler) ExpressionCompiler = new(this); StatementCompiler = new(this); + Operators = compiler.Feature(); + Initialize(); } diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index a5ad06fb..aac9b43c 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -49,7 +49,7 @@ private CompilerObject Compile(BinaryExpression binary) if (binary.Operator == "=") return Compiler.Compiler.Assign(left, right); - if (!Compiler.Operators.Cache(binary.Operator, out var @operator)) + if (!Compiler.Operators.Binary.Cache(binary.Operator, out var @operator)) Compiler.LogError($"Operator '{binary.Operator}' is not defined.", binary); return Compiler.Compiler.Call(@operator, [new(left), new(right)]); diff --git a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs index fcceff6e..9389862e 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs @@ -56,7 +56,7 @@ private CompilerObject Compile(CaseStatement @case) { var result = new Objects.Case() { - Of = @case.Of is null ? Compiler.Operators.Cache("==")! : Compiler.CompileNode(@case.Of), + Of = @case.Of is null ? Compiler.Operators.Binary.Cache("==")! : Compiler.CompileNode(@case.Of), Value = @case.Value is null ? Compiler.Compiler.CreateTrue() : Compiler.CompileNode(@case.Value), Else = @case.Else is null ? null : Compiler.CompileNode(@case.Else), }; diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index 501e09db..c26ea85e 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -68,6 +68,7 @@ expressionParser.InfixL("+", 50); expressionParser.InfixL("-", 50); expressionParser.InfixL("*", 70); + expressionParser.InfixL("/", 70); expressionParser.InfixL("**", 80); expressionParser.InfixL("==", 30); @@ -168,26 +169,6 @@ interpreter.SourceCompiler.StandardLibraryImporter.Libraries.Add("math", moduleCO_standardMath); -foreach (var moduleIR in new[] { moduleIR_standardIO, moduleIR_standardMath }) - if (moduleIR.HasFunctions) - foreach (var function in moduleIR.Functions) - { - if (function.Name is null || function.Name == string.Empty) - continue; - - var match = Regex.Match(function.Name, @"^_?(?[+\-*=?&^%$#@!<>|~]+)_?$"); - if (match.Success) - { - var op = match.Groups["OP"].Value; - if (!interpreter.SourceCompiler.Operators.Cache(op, out var group)) - group = interpreter.SourceCompiler.Operators.Cache(op, new ZSharp.Objects.OverloadGroup(op)); - - if (group is not ZSharp.Objects.OverloadGroup overloadGroup) - throw new Exception("Invalid overload group!"); - - overloadGroup.Overloads.Add(interpreter.CompilerIRLoader.Import(function)); - } - } //var moduleIL_compilerAPI = typeof(ZS.CompilerAPI.Impl_Globals).Module; //var moduleIR_compilerAPI = interpreter.HostLoader.Import(moduleIL_compilerAPI); From 4a2117e1a248c6e7be17d6524e004716f420c09b Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 26 May 2025 21:07:45 +0300 Subject: [PATCH 158/235] Add / operator for path / directory --- ZSharpTest/tests/simple.zs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs index a1ab78b0..701e81cc 100644 --- a/ZSharpTest/tests/simple.zs +++ b/ZSharpTest/tests/simple.zs @@ -10,6 +10,8 @@ import { } from "net:ZLoad.Test.dll"; import { Directory } from "net:ZSharp.CT.StandardLibrary.FileSystem.dll"; +print("Hello, Document!"); + module Program; class MyClass : TestInterface { @@ -71,7 +73,7 @@ fun main(): void { let cwd = Directory.cwd(); print(cwd.toString()); - let filePath = cwd.sub("tests").sub("simple.zs"); + let filePath = cwd / "tests" / "simple.zs"; print(filePath.toString()); print(filePath.asFile().toString()); From ab167d1af083002896df444d2b5d13ccf9c11ae8 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 28 May 2025 23:34:24 +0300 Subject: [PATCH 159/235] Update method IR to wrap function --- ZSharp.IR/ir/oop/method/Method.cs | 66 ++++++++++----------------- ZSharp.IR/ir/oop/method/MethodBody.cs | 53 --------------------- 2 files changed, 23 insertions(+), 96 deletions(-) delete mode 100644 ZSharp.IR/ir/oop/method/MethodBody.cs diff --git a/ZSharp.IR/ir/oop/method/Method.cs b/ZSharp.IR/ir/oop/method/Method.cs index b1d4a391..3d1d6332 100644 --- a/ZSharp.IR/ir/oop/method/Method.cs +++ b/ZSharp.IR/ir/oop/method/Method.cs @@ -6,62 +6,36 @@ public sealed class Method : IRObject , ICallable { - private Collection? _genericParameters; + public Function UnderlyingFunction { get; set; } - private Signature _signature; - private VM.MethodBody? _body; - - public string? Name { get; set; } + public string? Name { + get => UnderlyingFunction.Name; + set => UnderlyingFunction.Name = value; + } public MethodAttributes Attributes { get; set; } = MethodAttributes.None; - public Collection GenericParameters - { - get - { - if (_genericParameters is not null) - return _genericParameters; + public Collection GenericParameters => UnderlyingFunction.GenericParameters; - Interlocked.CompareExchange(ref _genericParameters, [], null); - return _genericParameters; - } - } - - public bool HasGenericParameters => !_genericParameters.IsNullOrEmpty(); + public bool HasGenericParameters => UnderlyingFunction.HasGenericParameters; public IType ReturnType { - get => _signature.ReturnType; - set => _signature.ReturnType = value; + get => UnderlyingFunction.ReturnType; + set => UnderlyingFunction.ReturnType = value; } public Signature Signature { - get => _signature; - set - { - if (value.Owner is not null) - throw new InvalidOperationException(); - _signature.Owner = null; - (_signature = value).Owner = this; - } + get => UnderlyingFunction.Signature; + set => UnderlyingFunction.Signature = value; } - ICallableBody? ICallable.Body => _body; + ICallableBody? ICallable.Body => UnderlyingFunction.Body; - public VM.MethodBody Body - { - get - { - if (_body is not null) - return _body; + public VM.FunctionBody Body => UnderlyingFunction.Body; - Interlocked.CompareExchange(ref _body, new(this), null); - return _body; - } - } - - public bool HasBody => _body is not null; + public bool HasBody => UnderlyingFunction.HasBody; public OOPType? Owner { get; set; } @@ -110,14 +84,20 @@ public bool IsAbstract } public Method(IType returnType) + : this(new Signature(returnType)) { - _signature = new(returnType) { Owner = this }; + } public Method(Signature signature) - : this((null as IType)!) + : this(new Function(signature)) + { + + } + + public Method(Function function) { - Signature = signature; + UnderlyingFunction = function; } } } diff --git a/ZSharp.IR/ir/oop/method/MethodBody.cs b/ZSharp.IR/ir/oop/method/MethodBody.cs deleted file mode 100644 index 3c685d14..00000000 --- a/ZSharp.IR/ir/oop/method/MethodBody.cs +++ /dev/null @@ -1,53 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.IR.VM -{ - public sealed class MethodBody : ICallableBody - { - private InstructionCollection? _instructions; - private LocalCollection? _locals; - - public Method Method { get; } - - public Collection Instructions - { - get - { - if (_instructions is not null) - return _instructions; - - Interlocked.CompareExchange(ref _instructions, [], null); - return _instructions; - } - } - - public bool HasInstructions => !_instructions.IsNullOrEmpty(); - - public Collection Locals - { - get - { - if (_locals is not null) - return _locals; - - Interlocked.CompareExchange(ref _locals, new(Method), null); - return _locals; - } - } - - public bool HasLocals => !_locals.IsNullOrEmpty(); - - public int StackSize { get; set; } - - public MethodBody(Method method, IEnumerable code) - { - Method = method; - _instructions = new(code); - } - - public MethodBody(Method method) - { - Method = method; - } - } -} From f235def98da1a28f6e57f9529fa4737b2ea442e4 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 28 May 2025 23:39:23 +0300 Subject: [PATCH 160/235] Use alias --- ZSharp.Compiler/core/code/IRCode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.Compiler/core/code/IRCode.cs b/ZSharp.Compiler/core/code/IRCode.cs index de716ed6..e149f017 100644 --- a/ZSharp.Compiler/core/code/IRCode.cs +++ b/ZSharp.Compiler/core/code/IRCode.cs @@ -44,7 +44,7 @@ public void Append(IRCode other) public static readonly IRCode Empty = new() { - Instructions = Collection.Empty, + Instructions = IRInstructions.Empty, MaxStackSize = 0, Types = [], }; From 7092a9786f3234113c49591f4df96abfe8ad669a Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 29 May 2025 13:27:32 +0300 Subject: [PATCH 161/235] Add support for `is of` operator Add CG service to compiler Add IR service to compiler --- ZSharp.AST/nodes/expr/cast/IsOfExpression.cs | 11 ++ ZSharp.Compiler.Features/GlobalUsings.cs | 1 + ZSharp.Compiler.Features/ir/IIREvaluator.cs | 34 ++++ ZSharp.Compiler.Features/ir/IR.Compile.cs | 47 +++++ ZSharp.Compiler.Features/ir/IR.cs | 19 ++ ZSharp.Compiler.IRLoader/Context.cs | 4 +- .../ir loader/IRLoader.API.cs | 2 +- .../ir loader/IRLoader.Impl.cs | 54 +++--- ZSharp.Compiler.Objects/GlobalUsings.cs | 1 + ZSharp.Compiler.Objects/nullable/Nullable.cs | 99 ++++++++++ ZSharp.Compiler.Objects/oop/class/Class.cs | 116 ++++++++++- .../oop/class/GenericClass.cs | 2 +- .../oop/class/GenericClassInstance.cs | 13 ++ .../oop/meta/ClassMetaClass.cs | 4 +- ZSharp.Compiler/GlobalUsings.cs | 1 + ZSharp.Compiler/ZSharp.Compiler.csproj | 2 +- .../cg objects/types/ObjectType.cs | 27 +++ .../compiler core/compiler/Compiler.IR.cs | 12 +- .../compiler/Compiler.Services.cs | 9 + .../compiler core/compiler/Compiler.cs | 6 +- .../core/type system/TypeSystem.cs | 4 +- ZSharp.Compiler/core/code/IRCode.cs | 2 +- ZSharp.Compiler/features/cg/CG.cs | 181 ++++++++++++++++++ .../features/cg/type casting/IRTCastFrom.cs | 8 + .../features/cg/type casting/IRTCastTo.cs | 8 + .../features/cg/type casting/TypeCast.cs | 16 ++ .../features/cg/type matching/ICTTypeMatch.cs | 8 + .../features/cg/type matching/IRTTypeMatch.cs | 8 + .../features/cg/type matching/TypeMatch.cs | 9 + ZSharp.Compiler/features/ir/IR.Code.cs | 24 +++ ZSharp.Compiler/features/ir/IR.Definition.cs | 53 +++++ ZSharp.Compiler/features/ir/IR.Reference.cs | 20 ++ ZSharp.Compiler/features/ir/IR.Type.cs | 36 ++++ ZSharp.Compiler/features/ir/IR.cs | 7 + .../features}/oop/extensibility/IClass.cs | 0 .../protocols/ICompileIRObject.cs | 10 +- ZSharp.IR/vm/instructions/misc/GetClass.cs | 11 ++ .../vm/instructions/object/CastReference.cs | 7 + .../{flow => object}/CreateInstance.cs | 0 ZSharp.IR/vm/instructions/object/IsNotNull.cs | 7 + ZSharp.IR/vm/instructions/object/IsNull.cs | 7 + ZSharp.Parser/lang/LangParser.Keywords.cs | 1 + ZSharp.Parser/lang/expr/LangParser.IsOf.cs | 27 +++ ZSharp.Runtime.IL/IRCodeEvaluator.cs | 25 ++- ZSharp.Runtime.IL/Runtime.cs | 7 +- ZSharp.Runtime.IL/ir2il/Constants.cs | 2 + .../ir2il/core/IRLoader.RuntimeServices.cs | 122 ++++++++++++ ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 2 +- .../ir2il/loader new/ClassLoader.cs | 4 +- .../ir2il/loader new/InterfaceLoader.cs | 4 +- .../ir2il/loader new/ModuleLoader.cs | 2 +- .../loader new/code/CodeLoader.Compile.cs | 43 ++++- .../ir2il/loader new/code/CodeLoader.cs | 10 +- ZSharp.Runtime.IL/objects/TypeObject.cs | 12 +- .../class body/MethodCompiler.cs | 4 +- .../compiler/ZSSourceCompiler.ResultTools.cs | 23 +++ .../expression/ExpressionCompiler.cs | 75 +++++++- .../statement/StatementCompiler.cs | 2 +- ZSharpTest/Main.cs | 2 +- ZSharpTest/tests/simple.zs | 26 +++ 60 files changed, 1201 insertions(+), 82 deletions(-) create mode 100644 ZSharp.AST/nodes/expr/cast/IsOfExpression.cs create mode 100644 ZSharp.Compiler.Features/GlobalUsings.cs create mode 100644 ZSharp.Compiler.Features/ir/IIREvaluator.cs create mode 100644 ZSharp.Compiler.Features/ir/IR.Compile.cs create mode 100644 ZSharp.Compiler.Features/ir/IR.cs create mode 100644 ZSharp.Compiler.Objects/nullable/Nullable.cs create mode 100644 ZSharp.Compiler/cg objects/types/ObjectType.cs create mode 100644 ZSharp.Compiler/compiler core/compiler/Compiler.Services.cs create mode 100644 ZSharp.Compiler/features/cg/CG.cs create mode 100644 ZSharp.Compiler/features/cg/type casting/IRTCastFrom.cs create mode 100644 ZSharp.Compiler/features/cg/type casting/IRTCastTo.cs create mode 100644 ZSharp.Compiler/features/cg/type casting/TypeCast.cs create mode 100644 ZSharp.Compiler/features/cg/type matching/ICTTypeMatch.cs create mode 100644 ZSharp.Compiler/features/cg/type matching/IRTTypeMatch.cs create mode 100644 ZSharp.Compiler/features/cg/type matching/TypeMatch.cs create mode 100644 ZSharp.Compiler/features/ir/IR.Code.cs create mode 100644 ZSharp.Compiler/features/ir/IR.Definition.cs create mode 100644 ZSharp.Compiler/features/ir/IR.Reference.cs create mode 100644 ZSharp.Compiler/features/ir/IR.Type.cs create mode 100644 ZSharp.Compiler/features/ir/IR.cs rename {ZSharp.Compiler.Objects => ZSharp.Compiler/features}/oop/extensibility/IClass.cs (100%) create mode 100644 ZSharp.IR/vm/instructions/misc/GetClass.cs create mode 100644 ZSharp.IR/vm/instructions/object/CastReference.cs rename ZSharp.IR/vm/instructions/{flow => object}/CreateInstance.cs (100%) create mode 100644 ZSharp.IR/vm/instructions/object/IsNotNull.cs create mode 100644 ZSharp.IR/vm/instructions/object/IsNull.cs create mode 100644 ZSharp.Parser/lang/expr/LangParser.IsOf.cs create mode 100644 ZSharp.Runtime.IL/ir2il/core/IRLoader.RuntimeServices.cs create mode 100644 ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.ResultTools.cs diff --git a/ZSharp.AST/nodes/expr/cast/IsOfExpression.cs b/ZSharp.AST/nodes/expr/cast/IsOfExpression.cs new file mode 100644 index 00000000..c043f1f2 --- /dev/null +++ b/ZSharp.AST/nodes/expr/cast/IsOfExpression.cs @@ -0,0 +1,11 @@ +namespace ZSharp.AST +{ + public sealed class IsOfExpression : Expression + { + public Expression Expression { get; set; } + + public string? Name { get; set; } + + public required Expression OfType { get; set; } + } +} diff --git a/ZSharp.Compiler.Features/GlobalUsings.cs b/ZSharp.Compiler.Features/GlobalUsings.cs new file mode 100644 index 00000000..98426100 --- /dev/null +++ b/ZSharp.Compiler.Features/GlobalUsings.cs @@ -0,0 +1 @@ +global using Error = string; diff --git a/ZSharp.Compiler.Features/ir/IIREvaluator.cs b/ZSharp.Compiler.Features/ir/IIREvaluator.cs new file mode 100644 index 00000000..8fccb97f --- /dev/null +++ b/ZSharp.Compiler.Features/ir/IIREvaluator.cs @@ -0,0 +1,34 @@ +using ZSharp.Objects; + +namespace ZSharp.Compiler +{ + public interface IIREvaluator + { + /// + /// Evaluate the given IR code and return the result object. + /// + /// The return value depends on the properties of the IR code. + /// + /// + /// Property + /// Result + /// + /// + /// + /// . + /// + /// + /// + /// A single . + /// + /// + /// + /// An object. + /// + /// + /// + /// The code to evaluate. + /// The result of evaluating the code. + public CompilerObject? EvaluateCT(IRCode code); + } +} diff --git a/ZSharp.Compiler.Features/ir/IR.Compile.cs b/ZSharp.Compiler.Features/ir/IR.Compile.cs new file mode 100644 index 00000000..b867f427 --- /dev/null +++ b/ZSharp.Compiler.Features/ir/IR.Compile.cs @@ -0,0 +1,47 @@ +using ZSharp.Objects; + +namespace ZSharp.Compiler +{ + public sealed partial class IRCompiler + { + public Result CompileIRCode(CompilerObject @object) + => Result.Ok( + Compiler.CompileIRCode(@object) + ); + + public Result CompileIRObject(CompilerObject @object) + => Result.Ok( + Compiler.CompileIRObject(@object) + ); + + public Result CompileIRObject(CompilerObject @object, Owner? owner) + where Owner : ZSharp.IR.IRObject + => Result.Ok( + Compiler.CompileIRObject(@object, owner) + ); + + public Result CompileIRObject(CompilerObject @object, Owner? owner) + where T : ZSharp.IR.IRObject + where Owner : class + => Result.Ok( + Compiler.CompileIRObject(@object, owner) + ); + + public Result CompileIRType(CompilerObject @object) + => Result.Ok( + Compiler.CompileIRType(@object) + ); + + public Result CompileIRType(CompilerObject @object) + where T : class, ZSharp.IR.IType + => Result.Ok( + Compiler.CompileIRType(@object) + ); + + public Result CompileIRReference(CompilerObject @object) + where T : class + => Result.Ok( + Compiler.CompileIRReference(@object) + ); + } +} diff --git a/ZSharp.Compiler.Features/ir/IR.cs b/ZSharp.Compiler.Features/ir/IR.cs new file mode 100644 index 00000000..70f28d4e --- /dev/null +++ b/ZSharp.Compiler.Features/ir/IR.cs @@ -0,0 +1,19 @@ +using ZSharp.Objects; + +namespace ZSharp.Compiler +{ + public sealed partial class IRCompiler(Compiler compiler) : Feature(compiler) + { + public ZSharp.IR.RuntimeModule RuntimeModule + => Compiler.RuntimeModule; + + public IIREvaluator? Evaluator { get; set; } + + public CompilerObject? EvaluateCO(IRCode code) + => Evaluator is not null + ? Evaluator.EvaluateCT(code) + : throw new InvalidOperationException( + "No IR evaluator was assigned." + ); + } +} diff --git a/ZSharp.Compiler.IRLoader/Context.cs b/ZSharp.Compiler.IRLoader/Context.cs index d92f3e89..b5fc5a89 100644 --- a/ZSharp.Compiler.IRLoader/Context.cs +++ b/ZSharp.Compiler.IRLoader/Context.cs @@ -4,8 +4,8 @@ namespace ZSharp.Compiler.IRLoader { public sealed class Context { - public Cache Objects { get; } = []; + public Cache Objects { get; } = []; - public Cache Types { get; } = []; + public Cache Types { get; } = []; } } diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.API.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.API.cs index 63f0dd3a..2eaa4bcb 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.API.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.API.cs @@ -2,6 +2,6 @@ { public partial class IRLoader { - public partial Module Import(IR.Module module); + public partial Module Import(ZSharp.IR.Module module); } } diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index 8759e71f..2c473e19 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -6,19 +6,19 @@ public partial class IRLoader { public Context Context { get; } = new(); - public partial Module Import(IR.Module module) + public partial Module Import(ZSharp.IR.Module module) => Import(module, new(module.Name!) { IR = module, }); - public CompilerObject Import(IR.IType type) + public CompilerObject Import(ZSharp.IR.IType type) => Load(type); - public CompilerObject Import(IR.Function function) + public CompilerObject Import(ZSharp.IR.Function function) => Context.Objects.Cache(function)!; - private Module Import(IR.Module module, Module result) + private Module Import(ZSharp.IR.Module module, Module result) { result ??= new(module.Name!) { @@ -67,7 +67,7 @@ private Module Import(IR.Module module, Module result) return result; } - private Action Load(IR.Module module, Module owner) + private Action Load(ZSharp.IR.Module module, Module owner) { Module result = new(module.Name!) { @@ -84,7 +84,7 @@ private Action Load(IR.Module module, Module owner) return () => Import(module, result); } - private Action Load(IR.Function function, Module owner) + private Action Load(ZSharp.IR.Function function, Module owner) { if (function.HasGenericParameters) return LoadGenericFunction(function, owner); @@ -118,16 +118,16 @@ private Action Load(IR.Function function, Module owner) }; } - private Action Load(IR.OOPType type, Module owner) + private Action Load(ZSharp.IR.OOPType type, Module owner) => type switch { - IR.Class @class => Load(@class, owner), - IR.Interface @interface => Load(@interface, owner), - //IR.Struct @struct => Load(@struct), + ZSharp.IR.Class @class => Load(@class, owner), + ZSharp.IR.Interface @interface => Load(@interface, owner), + //ZSharp.IR.Struct @struct => Load(@struct), _ => throw new NotImplementedException(), }; - private Action Load(IR.Class @class, Module owner) + private Action Load(ZSharp.IR.Class @class, Module owner) { if (@class.HasGenericParameters) return LoadGenericClass(@class, owner); @@ -147,7 +147,7 @@ private Action Load(IR.Class @class, Module owner) owner.Members.Add(result.Name, result); if (@class.Base is not null) - result.Base = Load(@class.Base); + result.Base = (IClass)Load(@class.Base); return () => { @@ -224,7 +224,7 @@ private Action Load(IR.Class @class, Module owner) }; } - private GenericMethod LoadGenericMethod(IR.Method method, CompilerObject owner) + private GenericMethod LoadGenericMethod(ZSharp.IR.Method method, CompilerObject owner) { GenericMethod result = new(method.Name) { @@ -247,7 +247,7 @@ private GenericMethod LoadGenericMethod(IR.Method method, CompilerObject owner) return result; } - private Action Load(IR.Interface @interface, Module owner) + private Action Load(ZSharp.IR.Interface @interface, Module owner) { Interface result = new(@interface.Name) { @@ -311,24 +311,24 @@ private Action Load(IR.Interface @interface, Module owner) }; } - private IType Load(IR.IType type) + private IType Load(ZSharp.IR.IType type) { if (Context.Types.Cache(type, out var result)) return result; return type switch { - IR.ClassReference classReference => Load(classReference), - IR.ConstructedClass constructedClass => Load(constructedClass), - IR.InterfaceReference interfaceReference => Load(interfaceReference), + ZSharp.IR.ClassReference classReference => Load(classReference), + ZSharp.IR.ConstructedClass constructedClass => Load(constructedClass), + ZSharp.IR.InterfaceReference interfaceReference => Load(interfaceReference), _ => null! }; } - private IType Load(IR.ClassReference classReference) + private IType Load(ZSharp.IR.ClassReference classReference) => Context.Objects.Cache(classReference.Definition) ?? throw new(); - private IType Load(IR.ConstructedClass constructed) + private IType Load(ZSharp.IR.ConstructedClass constructed) { if (Context.Objects.Cache(constructed.Class, out var genericClass)) @@ -351,10 +351,10 @@ private IType Load(IR.ConstructedClass constructed) return Context.Types.Cache(constructed) ?? throw new(); } - private IType Load(IR.InterfaceReference interfaceReference) + private IType Load(ZSharp.IR.InterfaceReference interfaceReference) => Context.Objects.Cache(interfaceReference.Definition) ?? throw new(); - private Action LoadGenericClass(IR.Class @class, Module owner) + private Action LoadGenericClass(ZSharp.IR.Class @class, Module owner) { GenericClass result = new() { @@ -371,7 +371,7 @@ private Action LoadGenericClass(IR.Class @class, Module owner) owner.Members.Add(result.Name, result); if (@class.Base is not null) - result.Base = Load(@class.Base); + result.Base = (IClass)Load(@class.Base); var self = new GenericClassInstance(result, new() { @@ -467,7 +467,7 @@ private Action LoadGenericClass(IR.Class @class, Module owner) }; } - private Action LoadGenericFunction(IR.Function function, Module owner) + private Action LoadGenericFunction(ZSharp.IR.Function function, Module owner) { GenericFunction result = new(function.Name) { @@ -509,7 +509,7 @@ private Action LoadGenericFunction(IR.Function function, Module owner) }; } - private Signature Load(IR.Signature signature) + private Signature Load(ZSharp.IR.Signature signature) { Signature result = new() { @@ -533,7 +533,7 @@ private Signature Load(IR.Signature signature) return result; } - private Parameter LoadParameter(IR.Parameter parameter) + private Parameter LoadParameter(ZSharp.IR.Parameter parameter) { var type = Load(parameter.Type); @@ -548,7 +548,7 @@ private Parameter LoadParameter(IR.Parameter parameter) }; } - private VarParameter LoadVarParameter(IR.Parameter parameter) + private VarParameter LoadVarParameter(ZSharp.IR.Parameter parameter) { var type = Load(parameter.Type); diff --git a/ZSharp.Compiler.Objects/GlobalUsings.cs b/ZSharp.Compiler.Objects/GlobalUsings.cs index 21547183..0fdd80b4 100644 --- a/ZSharp.Compiler.Objects/GlobalUsings.cs +++ b/ZSharp.Compiler.Objects/GlobalUsings.cs @@ -1,4 +1,5 @@ global using MemberName = string; global using MemberIndex = int; +global using Error = string; global using CompilerObjectResult = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.Objects/nullable/Nullable.cs b/ZSharp.Compiler.Objects/nullable/Nullable.cs new file mode 100644 index 00000000..e237c680 --- /dev/null +++ b/ZSharp.Compiler.Objects/nullable/Nullable.cs @@ -0,0 +1,99 @@ +using System; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class Nullable(IType underlyingType) + : CompilerObject + , IRTCastFrom + , IRTCastTo + , IType + { + public IType UnderlyingType { get; set; } = underlyingType; + + bool IType.IsEqualTo(Compiler.Compiler compiler, IType other) + { + if (other is not Nullable nullable) return false; + return compiler.TypeSystem.AreEqual(UnderlyingType, nullable.UnderlyingType); + } + + Result IRTCastFrom.Cast(Compiler.Compiler compiler, CompilerObject value) + { + var innerCastResult = compiler.CG.Cast(value, UnderlyingType); + + TypeCast innerCast; + + if (innerCastResult.Error(out var error)) + return Result.Error(error); + else innerCast = innerCastResult.Unwrap(); + + var innerCastCodeResult = compiler.IR.CompileCode(innerCast.Cast); + + IRCode innerCastCode; + + if (innerCastCodeResult.Error(out error)) + return Result.Error(error); + else innerCastCode = innerCastCodeResult.Unwrap(); + + return Result.Ok( + new() + { + Cast = new RawCode(new([ + .. innerCastCode.Instructions, + .. (IR.VM.Instruction[])(innerCast.CanFail ? [ + innerCast.OnFail, + new IR.VM.PutNull(), + ] : []), + ]) + { + Types = [this] + } + ), + OnCast = innerCast.OnCast + } + ); + } + + Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObject value, IType targetType) + { + if (targetType is not Nullable nullable) + return Result.Error( + "Nullable types can only be cast to other nullable types" + ); + + var innerCastResult = compiler.CG.Cast(value, nullable.UnderlyingType); + + TypeCast innerCast; + + if (innerCastResult.Error(out var error)) + return Result.Error(error); + else innerCast = innerCastResult.Unwrap(); + + var innerCastCodeResult = compiler.IR.CompileCode(innerCast.Cast); + + IRCode innerCastCode; + + if (innerCastCodeResult.Error(out error)) + return Result.Error(error); + else innerCastCode = innerCastCodeResult.Unwrap(); + + return Result.Ok( + new() + { + Cast = new RawCode(new([ + .. innerCastCode.Instructions, + .. (IR.VM.Instruction[])(innerCast.CanFail ? [ + innerCast.OnFail, + new IR.VM.PutNull(), + ] : []), + ]) + { + Types = [targetType] + } + ), + OnCast = innerCast.OnCast + } + ); + } + } +} diff --git a/ZSharp.Compiler.Objects/oop/class/Class.cs b/ZSharp.Compiler.Objects/oop/class/Class.cs index 5ef0ca67..6558ae7d 100644 --- a/ZSharp.Compiler.Objects/oop/class/Class.cs +++ b/ZSharp.Compiler.Objects/oop/class/Class.cs @@ -5,12 +5,15 @@ namespace ZSharp.Objects { public sealed class Class : CompilerObject + , IClass , ICompileIRObject , ICompileIRReference , ICompileIRType> , ICTCallable + , IRTCastTo , ICTGetMember , IRTGetMember + , IRTTypeMatch , IImplementsAbstraction , IType , ITypeAssignableToType @@ -44,7 +47,7 @@ public bool IsDefined public string? Name { get; set; } - public IType? Base { get; set; } + public IClass? Base { get; set; } public CompilerObject? Constructor { get; set; } @@ -149,6 +152,117 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments return null; } + Result IRTTypeMatch.Match(Compiler.Compiler compiler, CompilerObject value, IType type) + { + var nullableType = new Nullable(type); + var castToTypeResult = compiler.CG.Cast(value, nullableType); + + TypeCast castToType; + + if (castToTypeResult.Error(out var error)) + return Result.Error(error); + else castToType = castToTypeResult.Unwrap(); + + var castToTypeCodeResult = compiler.IR.CompileCode(castToType.Cast); + + IRCode castToTypeCode; + + if (castToTypeCodeResult.Error(out error)) + return Result.Error(error); + else castToTypeCode = castToTypeCodeResult.Unwrap(); + + IR.VM.Nop onMatch = new(); + + return Result.Ok(new() + { + Match = new RawCode(new([ + .. castToTypeCode.Instructions, + castToType.OnCast, + new IR.VM.Dup(), + new IR.VM.IsNotNull(), + new IR.VM.JumpIfTrue(onMatch), + ]) + { + Types = [castToTypeCode.RequireValueType()] + }), + OnMatch = onMatch + }); + } + + Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObject value, IType targetType) + { + if (targetType is not Class targetClass) + return Result.Error( + "Casting class to non-class object is not supported yet" + ); + + if (IsSubclassOf(targetClass)) + return Result.Ok( + new() + { + Cast = value, + } + ); + + var valueCodeResult = compiler.IR.CompileCode(value); + + IRCode valueCode; + + if (valueCodeResult.Error(out var error)) + return Result.Error(error); + else valueCode = valueCodeResult.Unwrap(); + + if (targetClass.IsSubclassOf(this)) + { + var targetClassIRResult = + compiler.IR.CompileReference>(targetClass); + + IR.OOPTypeReference targetClassIR; + + if (targetClassIRResult.Error(out error)) + return Result.Error(error); + else targetClassIR = targetClassIRResult.Unwrap(); + + IR.VM.Nop onCast = new(); + IR.VM.Nop onFail = new(); + + return Result.Ok( + new() + { + Cast = new RawCode(new([ + .. valueCode.Instructions, + new IR.VM.CastReference(targetClassIR), + new IR.VM.Dup(), + new IR.VM.IsNotNull(), + new IR.VM.JumpIfTrue(onCast), + new IR.VM.Pop(), + new IR.VM.Jump(onFail), + ]) + { + Types = [targetType] + }), + OnCast = onCast, + OnFail = onFail, + } + ); + } + + return Result.Error( + "Object does not support type cast to the specified type" + ); + } + #endregion + + public bool IsSubclassOf(Class @base) + { + for ( + IType? current = Base; + current is Class baseClass; + current = baseClass.Base + ) + if (current == @base) return true; + return false; + } } } diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs index b8c28fe9..f0f451e3 100644 --- a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs +++ b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs @@ -40,7 +40,7 @@ public bool Defined { init public Collection GenericParameters { get; set; } = []; - public CompilerObject? Base { get; set; } + public IClass? Base { get; set; } public Mapping Implementations { get; set; } = []; diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs index 702f23d6..c8271db5 100644 --- a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs +++ b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs @@ -5,6 +5,7 @@ namespace ZSharp.Objects { public sealed class GenericClassInstance : CompilerObject + , IClass , ICTGetMember , IRTGetMember , ICTCallable @@ -23,6 +24,18 @@ public sealed class GenericClassInstance public Mapping GenericArguments { get; } = []; + public string Name + { + get => Origin.Name; + set => Origin.Name = value; + } + + public IClass? Base + { + get => throw new NotImplementedException(); + set => throw new NotImplementedException(); + } + public Mapping Members { get; set; } = []; #region Constructors diff --git a/ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs b/ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs index a98a8425..8c579cc5 100644 --- a/ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs +++ b/ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs @@ -24,8 +24,8 @@ ClassSpec spec if (bases.Length > 0) { int interfacesIndex = 0; - if (bases[0] is GenericClassInstance) - @class.Base = (GenericClassInstance)bases[interfacesIndex++]; + if (bases[0] is IClass) + @class.Base = (IClass)bases[interfacesIndex++]; //for (; interfacesIndex < bases.Length; interfacesIndex++) // if (bases[interfacesIndex] is not IAbstraction @abstract) diff --git a/ZSharp.Compiler/GlobalUsings.cs b/ZSharp.Compiler/GlobalUsings.cs index 85fe8963..289e3e8b 100644 --- a/ZSharp.Compiler/GlobalUsings.cs +++ b/ZSharp.Compiler/GlobalUsings.cs @@ -9,4 +9,5 @@ global using CompilerObject = ZSharp.Objects.CompilerObject; +global using Error = string; global using CompilerObjectResult = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler/ZSharp.Compiler.csproj b/ZSharp.Compiler/ZSharp.Compiler.csproj index afe2b65a..5bfa5393 100644 --- a/ZSharp.Compiler/ZSharp.Compiler.csproj +++ b/ZSharp.Compiler/ZSharp.Compiler.csproj @@ -11,7 +11,7 @@ - + diff --git a/ZSharp.Compiler/cg objects/types/ObjectType.cs b/ZSharp.Compiler/cg objects/types/ObjectType.cs new file mode 100644 index 00000000..3bdb36b8 --- /dev/null +++ b/ZSharp.Compiler/cg objects/types/ObjectType.cs @@ -0,0 +1,27 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class ObjectType(IR.OOPTypeReference stringType, IType type) + : CompilerObject + , IClass + , ICompileIRType + { + public IR.OOPTypeReference IR { get; } = stringType; + + public IType Type { get; } = type; + public string Name + { + get => IR.Definition.Name!; + set => throw new InvalidOperationException(); + } + public IClass? Base + { + get => null; + set => throw new InvalidOperationException(); + } + + public IRType CompileIRType(Compiler.Compiler compiler) + => IR; + } +} diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs index 29a8cd54..b37eebe4 100644 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs +++ b/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs @@ -2,7 +2,7 @@ { public sealed partial class Compiler { - public IR.RuntimeModule RuntimeModule { get; } + public ZSharp.IR.RuntimeModule RuntimeModule { get; } public IRCode CompileIRCode(CompilerObject @object) { @@ -15,16 +15,16 @@ public IRCode CompileIRCode(CompilerObject @object) throw new NotImplementedException(); // TODO: return null } - public IR.IRObject CompileIRObject(CompilerObject @object) + public ZSharp.IR.IRObject CompileIRObject(CompilerObject @object) { if (@object is ICompileIRObject irObject) return irObject.CompileIRObject(this); - return CompileIRObject(@object, null); + return CompileIRObject(@object, null); } - public IR.IRObject CompileIRObject(CompilerObject @object, Owner? owner) - where Owner : IR.IRObject + public ZSharp.IR.IRObject CompileIRObject(CompilerObject @object, Owner? owner) + where Owner : ZSharp.IR.IRObject { if (@object is ICompileIRObject irObject) return irObject.CompileIRObject(this, owner); @@ -33,7 +33,7 @@ public IR.IRObject CompileIRObject(CompilerObject @object, Owner? owner) } public T CompileIRObject(CompilerObject @object, Owner? owner) - where T : IR.IRObject + where T : ZSharp.IR.IRObject where Owner : class { if (@object is ICompileIRObject irObject) diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.Services.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.Services.cs new file mode 100644 index 00000000..0145879b --- /dev/null +++ b/ZSharp.Compiler/compiler core/compiler/Compiler.Services.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public sealed partial class Compiler + { + public CG CG { get; } + + public IR IR { get; } + } +} diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.cs index 1cf91e3c..2a1eb795 100644 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.cs +++ b/ZSharp.Compiler/compiler core/compiler/Compiler.cs @@ -3,12 +3,14 @@ public sealed partial class Compiler { public Compiler() - : this(IR.RuntimeModule.Standard) { } + : this(ZSharp.IR.RuntimeModule.Standard) { } - public Compiler(IR.RuntimeModule runtimeModule) + public Compiler(ZSharp.IR.RuntimeModule runtimeModule) { RuntimeModule = runtimeModule; + CG = new(this); + IR = new(this); TypeSystem = new(this); Initialize(); diff --git a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs index a1c213a3..f265cbf4 100644 --- a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs +++ b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs @@ -20,7 +20,7 @@ public sealed class TypeSystem public IType Float32 { get; } - public IType Object { get; } + public ObjectType Object { get; } internal TypeSystem(Compiler compiler) : base(compiler) @@ -33,7 +33,7 @@ internal TypeSystem(Compiler compiler) Boolean = new RawType(compiler.RuntimeModule.TypeSystem.Boolean, Type); Int32 = new(compiler.RuntimeModule.TypeSystem.Int32, Type); Float32 = new RawType(compiler.RuntimeModule.TypeSystem.Float32, Type); - Object = new RawType(compiler.RuntimeModule.TypeSystem.Object, Type); + Object = new ObjectType(compiler.RuntimeModule.TypeSystem.Object, Type); } public IType EvaluateType(CompilerObject @object) diff --git a/ZSharp.Compiler/core/code/IRCode.cs b/ZSharp.Compiler/core/code/IRCode.cs index e149f017..09d15253 100644 --- a/ZSharp.Compiler/core/code/IRCode.cs +++ b/ZSharp.Compiler/core/code/IRCode.cs @@ -18,7 +18,7 @@ public sealed class IRCode public IRCode() { } - public IRCode(IEnumerable instructions) + public IRCode(IEnumerable instructions) { Instructions = [.. instructions]; } diff --git a/ZSharp.Compiler/features/cg/CG.cs b/ZSharp.Compiler/features/cg/CG.cs new file mode 100644 index 00000000..d60f5805 --- /dev/null +++ b/ZSharp.Compiler/features/cg/CG.cs @@ -0,0 +1,181 @@ +namespace ZSharp.Compiler +{ + public readonly struct CG(Compiler compiler) + { + public readonly Compiler compiler = compiler; + + public CompilerObjectResult Assign(CompilerObject target, CompilerObject value) + { + if (target is ICTAssignable ctAssignable) + return CompilerObjectResult.Ok( + ctAssignable.Assign(compiler, value) + ); + + return CompilerObjectResult.Error( + "Object does not support assignment" + ); + } + + // TODO: WTH is this? + public IRCode Assign(IRCode irCode, Assignment assignment) + => throw new NotImplementedException(); + + public CompilerObjectResult Call(CompilerObject target, Argument[] arguments) + { + CompilerObject? result = null; + + if (target is ICTCallable ctCallable) + result = ctCallable.Call(compiler, arguments); + + else if (target is ICTReadable readable) + if (readable.Type is IRTCallable rtCallable) + result = rtCallable.Call(compiler, target, arguments); + + // implements typeclass Callable? + + // overloads call operator? + + if (result is not null) + return CompilerObjectResult.Ok(result); + return CompilerObjectResult.Error( + "Object is not callable" + ); + } + + public Result Cast(CompilerObject value, IType type) + { + var result = Result.Error( + "Object cannot be cast" + ); + + if ( + compiler.TypeSystem.IsTyped(value, out var valueType) + && valueType is IRTCastTo rtCastTo + ) + result = rtCastTo.Cast(compiler, value, type); + + if (result.IsOk) return result; + + if (type is IRTCastFrom rtCastFrom) + result = rtCastFrom.Cast(compiler, value); + + if (result.IsOk) return result; + + if (valueType is not null && compiler.TypeSystem.AreEqual(type, valueType)) + result = Result.Ok(new() + { + Cast = value, + }); + + return result; + } + + /// + /// The get index ([]) operator. + /// + /// + /// + /// + public CompilerObject? Index(CompilerObject instanceTarget, Argument[] index) + { + if (instanceTarget is ICTGetIndex ctGetIndex) + return ctGetIndex.Index(compiler, index); + + return null; + } + + /// + /// The set index ([]=) operator. + /// + /// + /// + /// + /// + public CompilerObject Index(CompilerObject instanceTarget, Argument[] index, CompilerObject value) + { + throw new NotImplementedException(); + } + + public CompilerObject Map(CompilerObject @object, Func func) + { + if (@object is IMappable mappable) + return mappable.Map(func); + + return func(@object); + } + + /// + /// The member (.) operator. + /// + /// + /// + /// + public CompilerObject Member(CompilerObject instance, MemberIndex index) + { + throw new NotImplementedException(); + } + + /// + /// The set member (.=) operator. + /// + /// + /// + /// + /// + public CompilerObject Member(CompilerObject instance, MemberIndex index, CompilerObject value) + { + throw new NotImplementedException(); + } + + /// + /// The member (.) operator. + /// + /// + /// + /// + public CompilerObject Member(CompilerObject instance, MemberName member) + { + if (instance is ICTGetMember ctGetMember) + return ctGetMember.Member(compiler, member); + + if (instance is ICTReadable readable && readable.Type is IRTGetMember rtGetMember) + return rtGetMember.Member(compiler, instance, member); + + throw new NotImplementedException(); + } + + /// + /// The set member (.=) operator. + /// + /// + /// + /// + /// + public CompilerObject Member(CompilerObject instance, MemberName member, CompilerObject value) + { + throw new NotImplementedException(); + } + + public Result TypeMatch(CompilerObject @object, IType type) + { + var result = Result.Error( + "Object cannot be type matched" + ); + + if (@object is ICTTypeMatch ctTypeMatch) + result = ctTypeMatch.Match(compiler, type); + + if (result.IsOk) return result; + + if ( + compiler.TypeSystem.IsTyped(@object, out var objectType) + && objectType is IRTTypeMatch rtTypeMatch + ) + result = rtTypeMatch.Match(compiler, @object, type); + + if (result.IsOk) return result; + + return result; + } + } +} diff --git a/ZSharp.Compiler/features/cg/type casting/IRTCastFrom.cs b/ZSharp.Compiler/features/cg/type casting/IRTCastFrom.cs new file mode 100644 index 00000000..0d6f2142 --- /dev/null +++ b/ZSharp.Compiler/features/cg/type casting/IRTCastFrom.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTCastFrom + : CompilerObject + { + public Result Cast(Compiler compiler, CompilerObject value); + } +} diff --git a/ZSharp.Compiler/features/cg/type casting/IRTCastTo.cs b/ZSharp.Compiler/features/cg/type casting/IRTCastTo.cs new file mode 100644 index 00000000..50386228 --- /dev/null +++ b/ZSharp.Compiler/features/cg/type casting/IRTCastTo.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTCastTo + : CompilerObject + { + public Result Cast(Compiler compiler, CompilerObject value, IType targetType); + } +} diff --git a/ZSharp.Compiler/features/cg/type casting/TypeCast.cs b/ZSharp.Compiler/features/cg/type casting/TypeCast.cs new file mode 100644 index 00000000..2c54261c --- /dev/null +++ b/ZSharp.Compiler/features/cg/type casting/TypeCast.cs @@ -0,0 +1,16 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler +{ + public sealed class TypeCast + { + public required CompilerObject Cast { get; set; } + + public ZSharp.IR.VM.Instruction OnCast { get; init; } = new ZSharp.IR.VM.Nop(); + + public ZSharp.IR.VM.Instruction? OnFail { get; init; } = null; + + [MemberNotNullWhen(true, nameof(OnFail))] + public bool CanFail => OnFail is not null; + } +} diff --git a/ZSharp.Compiler/features/cg/type matching/ICTTypeMatch.cs b/ZSharp.Compiler/features/cg/type matching/ICTTypeMatch.cs new file mode 100644 index 00000000..f44ee43b --- /dev/null +++ b/ZSharp.Compiler/features/cg/type matching/ICTTypeMatch.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICTTypeMatch + : CompilerObject + { + public Result Match(Compiler compiler, IType type); + } +} diff --git a/ZSharp.Compiler/features/cg/type matching/IRTTypeMatch.cs b/ZSharp.Compiler/features/cg/type matching/IRTTypeMatch.cs new file mode 100644 index 00000000..b3e3b89e --- /dev/null +++ b/ZSharp.Compiler/features/cg/type matching/IRTTypeMatch.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTTypeMatch + : CompilerObject + { + public Result Match(Compiler compiler, CompilerObject value, IType type); + } +} diff --git a/ZSharp.Compiler/features/cg/type matching/TypeMatch.cs b/ZSharp.Compiler/features/cg/type matching/TypeMatch.cs new file mode 100644 index 00000000..6c46d7c9 --- /dev/null +++ b/ZSharp.Compiler/features/cg/type matching/TypeMatch.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public sealed class TypeMatch + { + public required CompilerObject Match { get; set; } + + public ZSharp.IR.VM.Instruction OnMatch { get; init; } = new ZSharp.IR.VM.Nop(); + } +} diff --git a/ZSharp.Compiler/features/ir/IR.Code.cs b/ZSharp.Compiler/features/ir/IR.Code.cs new file mode 100644 index 00000000..04f01fe2 --- /dev/null +++ b/ZSharp.Compiler/features/ir/IR.Code.cs @@ -0,0 +1,24 @@ +using IRCodeResult = ZSharp.Compiler.Result; + +namespace ZSharp.Compiler +{ + public partial struct IR + { + public IRCodeResult CompileCode(CompilerObject @object) + { + IRCode? result = null; + + if (@object is ICompileIRCode irCode) + result = irCode.CompileIRCode(compiler); + + else if (@object is ICTReadable ctReadable) + result = ctReadable.Read(compiler); + + if (result is not null) + return IRCodeResult.Ok(result); + return IRCodeResult.Error( + "Object cannot be compiled to IR code" + ); + } + } +} diff --git a/ZSharp.Compiler/features/ir/IR.Definition.cs b/ZSharp.Compiler/features/ir/IR.Definition.cs new file mode 100644 index 00000000..e8e5050d --- /dev/null +++ b/ZSharp.Compiler/features/ir/IR.Definition.cs @@ -0,0 +1,53 @@ +using CommonZ; +using IRDefinitionResult = ZSharp.Compiler.Result; + +namespace ZSharp.Compiler +{ + public partial struct IR + { + public IRDefinitionResult CompileDefinition(CompilerObject @object) + { + ZSharp.IR.IRObject? result = null; + + if (@object is ICompileIRObject irObject) + result = irObject.CompileIRObject(compiler); + + if (result is not null) + return IRDefinitionResult.Ok(result); + return IRDefinitionResult.Error( + "Object cannot be compiled to IR definition" + ); + } + + public IRDefinitionResult CompileDefinition(CompilerObject @object, Owner? owner) + where Owner : ZSharp.IR.IRObject + { + ZSharp.IR.IRObject? result = null; + + if (@object is ICompileIRObject irObject) + result = irObject.CompileIRObject(compiler, owner); + + if (result is not null) + return IRDefinitionResult.Ok(result); + return IRDefinitionResult.Error( + "Object cannot be compiled to IR definition" + ); + } + + public Result CompileDefinition(CompilerObject @object, Owner? owner) + where T : ZSharp.IR.IRObject + where Owner : class + { + T? result = null; + + if (@object is ICompileIRObject irObject) + result = irObject.CompileIRObject(compiler, owner); + + if (result is not null) + return Result.Ok(result); + return Result.Error( + "Object cannot be compiled to IR definition" + ); + } + } +} diff --git a/ZSharp.Compiler/features/ir/IR.Reference.cs b/ZSharp.Compiler/features/ir/IR.Reference.cs new file mode 100644 index 00000000..f491f187 --- /dev/null +++ b/ZSharp.Compiler/features/ir/IR.Reference.cs @@ -0,0 +1,20 @@ +namespace ZSharp.Compiler +{ + public partial struct IR + { + public Result CompileReference(CompilerObject @object) + where T : class + { + T? result = null; + + if (@object is ICompileIRReference irReference) + result = irReference.CompileIRReference(compiler); + + if (result is not null) + return Result.Ok(result); + return Result.Error( + "Object cannot be compiled to IR type" + ); + } + } +} diff --git a/ZSharp.Compiler/features/ir/IR.Type.cs b/ZSharp.Compiler/features/ir/IR.Type.cs new file mode 100644 index 00000000..7a9244b3 --- /dev/null +++ b/ZSharp.Compiler/features/ir/IR.Type.cs @@ -0,0 +1,36 @@ +using IRTypeResult = ZSharp.Compiler.Result; + +namespace ZSharp.Compiler +{ + public partial struct IR + { + public IRTypeResult CompileType(CompilerObject @object) + { + IRType? result = null; + + if (@object is ICompileIRType irType) + result = irType.CompileIRType(compiler); + + if (result is not null) + return IRTypeResult.Ok(result); + return IRTypeResult.Error( + "Object cannot be compiled to IR type" + ); + } + + public Result CompileType(CompilerObject @object) + where T : class, IRType + { + T? result = null; + + if (@object is ICompileIRType irType) + result = irType.CompileIRType(compiler); + + if (result is not null) + return Result.Ok(result); + return Result.Error( + "Object cannot be compiled to IR type" + ); + } + } +} diff --git a/ZSharp.Compiler/features/ir/IR.cs b/ZSharp.Compiler/features/ir/IR.cs new file mode 100644 index 00000000..ae7325aa --- /dev/null +++ b/ZSharp.Compiler/features/ir/IR.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public readonly partial struct IR(Compiler compiler) + { + public readonly Compiler compiler = compiler; + } +} diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IClass.cs b/ZSharp.Compiler/features/oop/extensibility/IClass.cs similarity index 100% rename from ZSharp.Compiler.Objects/oop/extensibility/IClass.cs rename to ZSharp.Compiler/features/oop/extensibility/IClass.cs diff --git a/ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs b/ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs index a7fe7cde..c76aa277 100644 --- a/ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs +++ b/ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs @@ -2,25 +2,25 @@ { public interface ICompileIRObject { - public IR.IRObject CompileIRObject(Compiler compiler); + public ZSharp.IR.IRObject CompileIRObject(Compiler compiler); } public interface ICompileIRObject : ICompileIRObject where Owner : class { - public IR.IRObject CompileIRObject(Compiler compiler, Owner? owner); + public ZSharp.IR.IRObject CompileIRObject(Compiler compiler, Owner? owner); - IR.IRObject ICompileIRObject.CompileIRObject(Compiler compiler) + ZSharp.IR.IRObject ICompileIRObject.CompileIRObject(Compiler compiler) => CompileIRObject(compiler, null); } public interface ICompileIRObject : ICompileIRObject - where T : IR.IRObject + where T : ZSharp.IR.IRObject where Owner : class { public new T CompileIRObject(Compiler compiler, Owner? owner); - IR.IRObject ICompileIRObject.CompileIRObject(Compiler compiler, Owner? owner) + ZSharp.IR.IRObject ICompileIRObject.CompileIRObject(Compiler compiler, Owner? owner) => CompileIRObject(compiler, owner); } } diff --git a/ZSharp.IR/vm/instructions/misc/GetClass.cs b/ZSharp.IR/vm/instructions/misc/GetClass.cs new file mode 100644 index 00000000..b684cbfb --- /dev/null +++ b/ZSharp.IR/vm/instructions/misc/GetClass.cs @@ -0,0 +1,11 @@ +namespace ZSharp.IR.VM +{ + public sealed class GetClass(OOPTypeReference @class) + : Instruction + , IHasOperand> + { + public OOPTypeReference Class { get; set; } = @class; + + OOPTypeReference IHasOperand>.Operand => Class; + } +} diff --git a/ZSharp.IR/vm/instructions/object/CastReference.cs b/ZSharp.IR/vm/instructions/object/CastReference.cs new file mode 100644 index 00000000..fc36d1cb --- /dev/null +++ b/ZSharp.IR/vm/instructions/object/CastReference.cs @@ -0,0 +1,7 @@ +namespace ZSharp.IR.VM +{ + public sealed class CastReference(OOPTypeReference targetType) : Instruction + { + public OOPTypeReference Type { get; set; } = targetType; + } +} diff --git a/ZSharp.IR/vm/instructions/flow/CreateInstance.cs b/ZSharp.IR/vm/instructions/object/CreateInstance.cs similarity index 100% rename from ZSharp.IR/vm/instructions/flow/CreateInstance.cs rename to ZSharp.IR/vm/instructions/object/CreateInstance.cs diff --git a/ZSharp.IR/vm/instructions/object/IsNotNull.cs b/ZSharp.IR/vm/instructions/object/IsNotNull.cs new file mode 100644 index 00000000..78db6ca3 --- /dev/null +++ b/ZSharp.IR/vm/instructions/object/IsNotNull.cs @@ -0,0 +1,7 @@ +namespace ZSharp.IR.VM +{ + public sealed class IsNotNull : Instruction + { + + } +} diff --git a/ZSharp.IR/vm/instructions/object/IsNull.cs b/ZSharp.IR/vm/instructions/object/IsNull.cs new file mode 100644 index 00000000..e1996936 --- /dev/null +++ b/ZSharp.IR/vm/instructions/object/IsNull.cs @@ -0,0 +1,7 @@ +namespace ZSharp.IR.VM +{ + public sealed class IsNull : Instruction + { + + } +} diff --git a/ZSharp.Parser/lang/LangParser.Keywords.cs b/ZSharp.Parser/lang/LangParser.Keywords.cs index b88f233e..b0d0243f 100644 --- a/ZSharp.Parser/lang/LangParser.Keywords.cs +++ b/ZSharp.Parser/lang/LangParser.Keywords.cs @@ -15,6 +15,7 @@ public static class Keywords public const string If = "if"; public const string Import = "import"; public const string In = "in"; + public const string Is = "is"; public const string Let = "let"; public const string Module = "module"; public const string New = "new"; diff --git a/ZSharp.Parser/lang/expr/LangParser.IsOf.cs b/ZSharp.Parser/lang/expr/LangParser.IsOf.cs new file mode 100644 index 00000000..fd946a32 --- /dev/null +++ b/ZSharp.Parser/lang/expr/LangParser.IsOf.cs @@ -0,0 +1,27 @@ +using ZSharp.AST; + +namespace ZSharp.Parser +{ + public static partial class LangParser + { + public static IsOfExpression ParseIsOfExpression(Parser parser, Expression expression) + { + var isKeyword = parser.Eat(Keywords.Is); + + string? name = null; + if (!parser.Is(Keywords.Of)) + name = parser.Eat(Text.TokenType.Identifier).Value; + + var ofKeyword = parser.Eat(Keywords.Of); + + var ofType = parser.Parse(); + + return new() + { + Expression = expression, + Name = name, + OfType = ofType + }; + } + } +} diff --git a/ZSharp.Runtime.IL/IRCodeEvaluator.cs b/ZSharp.Runtime.IL/IRCodeEvaluator.cs index f31d59bd..500c1e86 100644 --- a/ZSharp.Runtime.IL/IRCodeEvaluator.cs +++ b/ZSharp.Runtime.IL/IRCodeEvaluator.cs @@ -1,4 +1,5 @@ //using ZSharp.Interop.IR2IL; +using ZSharp.Compiler; using ZSharp.Objects; using ZSharp.Runtime.NET.IR2IL; @@ -7,7 +8,9 @@ namespace ZSharp.Runtime.NET { - internal sealed class IRCodeEvaluator(Runtime runtime) : Compiler.Evaluator + internal sealed class IRCodeEvaluator(Runtime runtime) + : Compiler.Evaluator + , Compiler.IIREvaluator { private readonly Runtime runtime = runtime; @@ -70,5 +73,25 @@ private void CompileGetObject(ICodeLoader loader, IR.VM.GetObject get) else throw new NotImplementedException(); } + + public CompilerObject? EvaluateCT(IRCode code) + { + throw new NotImplementedException(); + + var function = new IR.Function(Interpreter.Compiler.CompileIRType(code.RequireValueType())) + { + Name = "evaluate" + }; + + IL.Emit.DynamicMethod method = new(string.Empty, runtime.Import(function.ReturnType), null); + + CodeLoader codeLoader = new( + runtime.irLoader, + function, + method.GetILGenerator() + ); + + codeLoader.Load(); + } } } diff --git a/ZSharp.Runtime.IL/Runtime.cs b/ZSharp.Runtime.IL/Runtime.cs index 0aed7c8d..573741d6 100644 --- a/ZSharp.Runtime.IL/Runtime.cs +++ b/ZSharp.Runtime.IL/Runtime.cs @@ -6,8 +6,8 @@ public class Runtime : Interpreter.IRuntime , Interpreter.IHostLoader { - private readonly IL2IR.ILLoader ilLoader; - private readonly IR2IL.IRLoader irLoader; + internal readonly IL2IR.ILLoader ilLoader; + internal readonly IR2IL.IRLoader irLoader; private readonly Cache typeObjects = []; @@ -90,13 +90,14 @@ public IR.Function Import(IL.MethodInfo method) public object GetObject(Type type) { + throw new NotSupportedException(); if (typeObjects.Cache(type, out var result)) return result; var ir = ilLoader.LoadType(type); var co = Interpreter.CompilerIRLoader.Import(ir); - return typeObjects.Cache(type, new TypeObject(type, ir, co)); + //return typeObjects.Cache(type, new TypeObject(type, ir)); } } } diff --git a/ZSharp.Runtime.IL/ir2il/Constants.cs b/ZSharp.Runtime.IL/ir2il/Constants.cs index 45e865f9..153078fd 100644 --- a/ZSharp.Runtime.IL/ir2il/Constants.cs +++ b/ZSharp.Runtime.IL/ir2il/Constants.cs @@ -4,6 +4,8 @@ internal static class Constants { public const string GlobalsTypeName = ""; + public const string AnonymousAssembly = ""; + public const string AnonymousClass = ""; public const string AnonymousInterface = ""; diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.RuntimeServices.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.RuntimeServices.cs new file mode 100644 index 00000000..bcc96830 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.RuntimeServices.cs @@ -0,0 +1,122 @@ +using System.Reflection; +using System.Reflection.Emit; +using ZSharp.Objects; + +namespace ZSharp.Runtime.NET.IR2IL +{ + /// + /// Wraps an IR module in a C# module. + /// + public partial class IRLoader + { + private static readonly Dictionary typeObjects = []; + + private ModuleBuilder moduleBuilder = AssemblyBuilder.DefineDynamicAssembly( + new(Constants.AnonymousAssembly), AssemblyBuilderAccess.RunAndCollect + ).DefineDynamicModule("[ZSharp.Runtime.IL]::"); + + public static object _GetTypeObject(int objectId) + => typeObjects[objectId]; + + public int GetTypeObject(IR.OOPTypeReference @class) + { + var type = LoadTypeReference(@class); + + if (!HasTypeObject(type.GetHashCode())) + { + var typeObjectClass = CreateTypeObjectClass(@class); + var typeObject = Activator.CreateInstance(typeObjectClass); + SetTypeObject(type.GetHashCode(), typeObject ?? throw new()); + } + + return type.GetHashCode(); + } + + public object GetTypeObject(int objectId) + => typeObjects[objectId]; + + public bool HasTypeObject(int objectId) + => typeObjects.ContainsKey(objectId); + + public void SetTypeObject(int objectId, object @object) + => typeObjects[objectId] = (TypeObject)@object; + + private Type CreateTypeObjectClass(IR.OOPTypeReference @class) + { + if (@class.Definition.HasGenericParameters) + throw new NotImplementedException(); + + // Define the new type that inherits Base + var typeBuilder = moduleBuilder.DefineType("Derived", + TypeAttributes.Public | TypeAttributes.Class, + typeof(TypeObject) // base type + ); + + // Define constructor parameters + Type[] ctorParams = { typeof(Type), typeof(IR.IType) }; + + // Define constructor + var ctorBuilder = typeBuilder.DefineConstructor( + MethodAttributes.Public, + CallingConventions.Standard, + ctorParams + ); + + List<(IR.Field, FieldInfo)> fields = []; + + foreach (var field in @class.Definition.Fields) + { + if (!field.IsClass) continue; + + var attributes = FieldAttributes.Public; + if (field.IsReadOnly) + attributes |= FieldAttributes.InitOnly; + + var fieldType = LoadType(field.Type); + var fieldBuilder = typeBuilder.DefineField( + field.Name, + fieldType, + attributes + ); + + if (field.Initializer is not null) + fields.Add((field, fieldBuilder)); + } + + // Generate IL for constructor + var il = ctorBuilder.GetILGenerator(); + + // Load 'this' + il.Emit(OpCodes.Ldarg_0); + + // Load parameters (arg1, arg2) + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Ldarg_2); + + // Call base constructor + var baseCtor = typeof(TypeObject).GetConstructor(ctorParams); + il.Emit(OpCodes.Call, baseCtor!); + + { + IR.Function function = new(RuntimeModule.TypeSystem.Void); + + foreach (var (_ir, _il) in fields) + { + function.Body.Instructions.AddRange([ + .. _ir.Initializer!, + new IR.VM.SetField(new(_ir) { + OwningType = @class + }) + ]); + } + } + + + // Return + il.Emit(OpCodes.Ret); + + // Create the type + return typeBuilder.CreateType(); + } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index e5f1ee9d..399e9bfe 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -3,7 +3,7 @@ /// /// Wraps an IR module in a C# module. /// - public class IRLoader(Context context, IR.RuntimeModule? runtimeModule = null) + public sealed partial class IRLoader(Context context, IR.RuntimeModule? runtimeModule = null) { public Context Context { get; } = context; diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs index 8dfcb5cc..602898ea 100644 --- a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs @@ -115,7 +115,7 @@ private void LoadConstructor(IR.Constructor constructor) Context.Cache(constructor.Method, result); var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(ModuleLoader, constructor.Method, ilGen); + var codeLoader = new CodeLoader(Loader, constructor.Method, ilGen); foreach (var (ir, parameter) in irParams.Zip(parameters)) codeLoader.Args[ir] = parameter; @@ -166,7 +166,7 @@ private void LoadMethod(IR.Method method) Context.Cache(method, result); var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(ModuleLoader, method, ilGen); + var codeLoader = new CodeLoader(Loader, method, ilGen); foreach (var (ir, parameter) in irParams.Zip(parameters)) codeLoader.Args[ir] = parameter; diff --git a/ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs index 35fdc9d6..62deee21 100644 --- a/ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs @@ -78,7 +78,7 @@ private void LoadConstructor(IR.Constructor constructor) Context.Cache(constructor.Method, result); var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(ModuleLoader, constructor.Method, ilGen); + var codeLoader = new CodeLoader(Loader, constructor.Method, ilGen); foreach (var (ir, parameter) in irParams.Zip(parameters)) codeLoader.Args[ir] = parameter; @@ -127,7 +127,7 @@ private void LoadMethod(IR.Method method) Context.Cache(method, result); var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(ModuleLoader, method, ilGen); + var codeLoader = new CodeLoader(Loader, method, ilGen); foreach (var (ir, parameter) in irParams.Zip(parameters)) codeLoader.Args[ir] = parameter; diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs index 4270774f..928fe646 100644 --- a/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs @@ -89,7 +89,7 @@ private IL.MethodInfo LoadFunction(IL.Emit.TypeBuilder globals, IR.Function func Context.Cache(function, result); var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(ModuleLoader, function, ilGen); + var codeLoader = new CodeLoader(Loader, function, ilGen); foreach (var (ir, parameter) in irParams.Zip(parameters)) codeLoader.Args[ir] = parameter; diff --git a/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.Compile.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.Compile.cs index f9f09842..efe8d885 100644 --- a/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.Compile.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.Compile.cs @@ -48,6 +48,16 @@ private void Compile(VM.CallVirtual callVirtual) _stack.Push(method.ReturnType); } + private void Compile(VM.CastReference castReference) + { + var targetType = Loader.LoadType(castReference.Type); + + Output.Emit(IL.Emit.OpCodes.Isinst, targetType); + + _stack.Pop(); + _stack.Push(targetType); + } + private void Compile(VM.CreateInstance createInstance) { var constructor = Loader.LoadReference(createInstance.Constructor); @@ -85,6 +95,14 @@ private void Compile(VM.GetArgument getArgument) _stack.Push(p.Type); } + private void Compile(VM.GetClass getClass) + { + var typeObjectId = Loader.GetTypeObject(getClass.Class); + + Output.Emit(IL.Emit.OpCodes.Ldc_I4, typeObjectId); + Output.Emit(IL.Emit.OpCodes.Call, Utils.GetMethod(IRLoader._GetTypeObject)); + } + private void Compile(VM.GetField getField) { var field = Loader.LoadReference(getField.Field); @@ -127,7 +145,30 @@ private void Compile(VM.GetLocal getLocal) private void Compile(VM.GetObject getObject) { - Loader.GetObjectFunction(this, getObject); + throw new NotSupportedException( + $"The {nameof(VM.GetObject)} instruction is obsolete and being " + + $"removed. Please do not use this instruction. To get a function " + + $"you can use GetFunction. To get a class you can use {nameof(VM.GetClass)}." + + $" To get a virtual method, use GetVirtualMethod." + ); + } + + private void Compile(VM.IsNotNull _) + { + Output.Emit(IL.Emit.OpCodes.Ldnull); + Output.Emit(IL.Emit.OpCodes.Cgt_Un); + + _stack.Pop(); + _stack.Push(typeof(bool)); + } + + private void Compile(VM.IsNull _) + { + Output.Emit(IL.Emit.OpCodes.Ldnull); + Output.Emit(IL.Emit.OpCodes.Ceq); + + _stack.Pop(); + _stack.Push(typeof(bool)); } private void Compile(VM.Jump jump) diff --git a/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.cs index c78898d9..55293268 100644 --- a/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.cs @@ -1,7 +1,7 @@ namespace ZSharp.Runtime.NET.IR2IL { - internal sealed partial class CodeLoader(RootModuleLoader loader, IR.ICallable code, IL.Emit.ILGenerator method) - : ModuleContentLoader(loader, code, method) + internal sealed partial class CodeLoader(IRLoader loader, IR.ICallable code, IL.Emit.ILGenerator method) + : BaseIRLoader(loader, code, method) , ICodeLoader { private readonly Dictionary labels = []; @@ -12,7 +12,7 @@ internal sealed partial class CodeLoader(RootModuleLoader loader, IR.ICallable c public Dictionary Locals { get; } = []; - protected override void DoLoad() + public void Load() { CompileCode(); } @@ -57,13 +57,17 @@ private void Compile(IR.VM.Instruction instruction) case IR.VM.CallIndirect callIndirect: Compile(callIndirect); break; case IR.VM.CallInternal callInternal: Compile(callInternal); break; case IR.VM.CallVirtual callVirtual: Compile(callVirtual); break; + case IR.VM.CastReference castReference: Compile(castReference); break; case IR.VM.CreateInstance createInstance: Compile(createInstance); break; case IR.VM.Dup dup: Compile(dup); break; case IR.VM.GetArgument getArgument: Compile(getArgument); break; + case IR.VM.GetClass getClass: Compile(getClass); break; case IR.VM.GetField getField: Compile(getField); break; case IR.VM.GetGlobal getGlobal: Compile(getGlobal); break; case IR.VM.GetLocal getLocal: Compile(getLocal); break; case IR.VM.GetObject getObject: Compile(getObject); break; + case IR.VM.IsNotNull isNotNull: Compile(isNotNull); break; + case IR.VM.IsNull isNull: Compile(isNull); break; case IR.VM.Jump jump: Compile(jump); break; case IR.VM.JumpIfTrue jumpIfTrue: Compile(jumpIfTrue); break; case IR.VM.JumpIfFalse jumpIfFalse: Compile(jumpIfFalse); break; diff --git a/ZSharp.Runtime.IL/objects/TypeObject.cs b/ZSharp.Runtime.IL/objects/TypeObject.cs index 6426de40..b4915766 100644 --- a/ZSharp.Runtime.IL/objects/TypeObject.cs +++ b/ZSharp.Runtime.IL/objects/TypeObject.cs @@ -1,17 +1,9 @@ -using ZSharp.Objects; - -namespace ZSharp.Runtime.NET +namespace ZSharp.Runtime.NET { - internal sealed class TypeObject(Type il, IR.IType ir, CompilerObject co) - : ICompileTime + public abstract class TypeObject(Type il, IR.IType ir) { public Type IL { get; } = il; public IR.IType IR { get; } = ir; - - public CompilerObject CO { get; } = co; - - public CompilerObject GetCO() - => CO; } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs index e94ade80..a1e5a26a 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs @@ -131,7 +131,7 @@ private CompilerObject CompileNode(LetExpression let) if (local.Type is null) Compiler.LogError("Could not infer type of local variable.", let); - local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); + local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); if (local.IR.Initializer is not null) return new Objects.RawCode(new(local.IR.Initializer) @@ -163,7 +163,7 @@ private CompilerObject CompileNode(VarExpression var) if (local.Type is null) Compiler.LogError("Could not infer type of local variable.", var); - local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); + local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); if (local.IR.Initializer is not null) return new Objects.RawCode(new(local.IR.Initializer) diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.ResultTools.cs b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.ResultTools.cs new file mode 100644 index 00000000..051b8286 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.ResultTools.cs @@ -0,0 +1,23 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.ZSSourceCompiler +{ + public sealed partial class ZSSourceCompiler : Compiler.Feature + { + public bool UnpackResult( + Compiler.Result result, + [NotNullWhen(true)] out T? value, + Node origin + ) + where T : class + { + if (result.Error(out var error)) { + value = null; + LogError(error, origin); + return false; + } + value = result.Unwrap(); + return true; + } + } +} diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index aac9b43c..89ce3870 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -1,6 +1,4 @@ -using ZSharp.IR.VM; - -namespace ZSharp.ZSSourceCompiler +namespace ZSharp.ZSSourceCompiler { public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) : CompilerBase(compiler) @@ -13,6 +11,7 @@ public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) CallExpression call => Compile(call), IdentifierExpression identifier => Compile(identifier), IndexExpression index => Compile(index), + IsOfExpression isOf => Compile(isOf), LiteralExpression literal => Compile(literal), WhileExpression @while => Compile(@while), _ => null @@ -90,6 +89,76 @@ private CompilerObject Compile(IndexExpression index) return Compiler.Compiler.Map(indexable, @object => Compiler.Compiler.Index(@object, [.. args])); } + private CompilerObject Compile(IsOfExpression isOf) + { + var value = Compiler.CompileNode(isOf.Expression); + var type = Compiler.CompileType(isOf.OfType); + + if (!Compiler.UnpackResult( + Compiler.Compiler.CG.TypeMatch(value, type), + out var match, + isOf + ) + ) + return Compiler.Compiler.CreateFalse(); + + if (!Compiler.UnpackResult( + Compiler.Compiler.IR.CompileCode(match.Match), + out var matchCode, + isOf + ) + ) + return Compiler.Compiler.CreateFalse(); + + IR.VM.Nop noMatch = new(); + + matchCode.Instructions.AddRange([ + new IR.VM.Pop(), + new IR.VM.PutFalse(), + new IR.VM.Jump(noMatch), + ]); + + if (isOf.Name is not null && isOf.Name != string.Empty && isOf.Name != "_") + { + var allocator = Compiler.Compiler.CurrentContext.FindContext(); + if (allocator is null) + { + Compiler.LogError($"Could not find memory allocator in context chain", isOf); + + return Compiler.Compiler.CreateFalse(); + } + + var local = allocator.Allocate( + isOf.Name, + type, + new Objects.RawCode(new([ + match.OnMatch + ]) + { + Types = [type] + }) + ); + + if (local is not Objects.Local localObject) + throw new NotImplementedException(); + + Compiler.Context.CurrentScope.Set(isOf.Name, local); + + matchCode.Instructions.AddRange([ + .. localObject.IR!.Initializer!, + new IR.VM.Pop(), + new IR.VM.PutTrue(), + ]); + } + + matchCode.Instructions.Add(noMatch); + + matchCode.Types.Clear(); + matchCode.Types.Add(Compiler.Compiler.TypeSystem.Boolean); + + return new Objects.RawCode(matchCode); + } + private WhileLoop Compile(WhileExpression @while) { return new WhileExpressionCompiler(Compiler, @while, null!).Compile(); diff --git a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs index 9389862e..d3e57976 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs @@ -82,8 +82,8 @@ private CompilerObject Compile(IfStatement @if) { var result = new Objects.If() { - Body = Compiler.CompileNode(@if.If), Condition = Compiler.CompileNode(@if.Condition), + Body = Compiler.CompileNode(@if.If), Else = @if.Else is null ? null : Compiler.CompileNode(@if.Else) }; diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index c26ea85e..c3b67387 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -1,5 +1,4 @@ using System.Text; -using System.Text.RegularExpressions; using ZSharp.Compiler; using ZSharp.Interpreter; using ZSharp.Parser; @@ -78,6 +77,7 @@ expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); expressionParser.Led(".", LangParser.ParseMemberAccess, 150); + expressionParser.Led(LangParser.Keywords.Is, LangParser.ParseIsOfExpression, 20); expressionParser.Separator(TokenType.Comma); expressionParser.Separator(TokenType.RParen); diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs index 701e81cc..8c2a19a1 100644 --- a/ZSharpTest/tests/simple.zs +++ b/ZSharpTest/tests/simple.zs @@ -46,6 +46,25 @@ class OtherClass : TestInterface { } } +class Base { + fun baseMethod(this): void { + print("Base::baseMethod"); + + return; + } +} + +class Derived : Base { + + new() {} + + fun derivedMethod(this): void { + print("Derived::derivedMethod"); + + return; + } +} + fun testInterface(test: TestInterface): void { test.do(); @@ -59,6 +78,7 @@ fun testBaseClass(test: BaseClass): void { } fun main(): void { +/* let c1 = MyClass(); let c2 = OtherClass(5); @@ -76,6 +96,12 @@ fun main(): void { let filePath = cwd / "tests" / "simple.zs"; print(filePath.toString()); print(filePath.asFile().toString()); + */ + let base: Base = Derived(); + base.baseMethod(); + + if (base is derived of Derived) + derived.derivedMethod(); return; } From 7c32fd504fb732c64f75cc26ab81008354962a2c Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 29 May 2025 15:43:40 +0300 Subject: [PATCH 162/235] Add support for overriding values in Cache --- CommonZ/collections/CacheBase.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CommonZ/collections/CacheBase.cs b/CommonZ/collections/CacheBase.cs index 30ec9a42..a33ab80a 100644 --- a/CommonZ/collections/CacheBase.cs +++ b/CommonZ/collections/CacheBase.cs @@ -12,10 +12,13 @@ public abstract class CacheBase public Cache? Parent { get; set; } - public T Cache(Key key, T value) + public T Cache(Key key, T value, bool set = false) where T : Value { - _cache.Add(key, value); + if (set) + _cache[key] = value; + else + _cache.Add(key, value); return value; } From 4aa6cd853280e288af509dcc43d2c2088814861b Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 29 May 2025 15:46:47 +0300 Subject: [PATCH 163/235] Add very basic type inference support --- .../type inference/SimpleInferenceContext.cs | 16 ++++++ .../core/IInferredTypeResolver.cs | 9 ++++ .../core/ITypeInferenceContext.cs | 19 +++++++ .../type inference/core/InferredType.cs | 43 +++++++++++++++ .../resolvers/CommonBaseType.cs | 52 +++++++++++++++++++ .../functional/generic/GenericFunction.cs | 43 ++++++++++++++- .../contexts/concrete/ExpressionContext.cs | 17 ++++++ 7 files changed, 197 insertions(+), 2 deletions(-) create mode 100644 ZSharp.Compiler.Objects/contexts/type inference/SimpleInferenceContext.cs create mode 100644 ZSharp.Compiler.Objects/contexts/type inference/core/IInferredTypeResolver.cs create mode 100644 ZSharp.Compiler.Objects/contexts/type inference/core/ITypeInferenceContext.cs create mode 100644 ZSharp.Compiler.Objects/contexts/type inference/core/InferredType.cs create mode 100644 ZSharp.Compiler.Objects/contexts/type inference/resolvers/CommonBaseType.cs create mode 100644 ZSharp.ZSSourceCompiler/contexts/concrete/ExpressionContext.cs diff --git a/ZSharp.Compiler.Objects/contexts/type inference/SimpleInferenceContext.cs b/ZSharp.Compiler.Objects/contexts/type inference/SimpleInferenceContext.cs new file mode 100644 index 00000000..cfd622b3 --- /dev/null +++ b/ZSharp.Compiler.Objects/contexts/type inference/SimpleInferenceContext.cs @@ -0,0 +1,16 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public class SimpleInferenceContext(Compiler.Compiler compiler) + : IContext + , ITypeInferenceContext + { + private readonly Compiler.Compiler compiler = compiler; + + IContext? IContext.Parent { get; set; } + + InferredType ITypeInferenceContext.CreateInferredType(IInferredTypeResolver? resolver) + => (this as ITypeInferenceContext).CreateInferredType(compiler, resolver); + } +} diff --git a/ZSharp.Compiler.Objects/contexts/type inference/core/IInferredTypeResolver.cs b/ZSharp.Compiler.Objects/contexts/type inference/core/IInferredTypeResolver.cs new file mode 100644 index 00000000..51eecadc --- /dev/null +++ b/ZSharp.Compiler.Objects/contexts/type inference/core/IInferredTypeResolver.cs @@ -0,0 +1,9 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public interface IInferredTypeResolver + { + public IType Resolve(Compiler.Compiler compiler, InferredType inferredType); + } +} diff --git a/ZSharp.Compiler.Objects/contexts/type inference/core/ITypeInferenceContext.cs b/ZSharp.Compiler.Objects/contexts/type inference/core/ITypeInferenceContext.cs new file mode 100644 index 00000000..436b07a4 --- /dev/null +++ b/ZSharp.Compiler.Objects/contexts/type inference/core/ITypeInferenceContext.cs @@ -0,0 +1,19 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public interface ITypeInferenceContext + : IContext + { + public InferredType CreateInferredType(IInferredTypeResolver? resolver = null); + + public InferredType CreateInferredType( + Compiler.Compiler compiler, + IInferredTypeResolver? resolver = null + ) + => new(compiler, this) + { + Resolver = resolver ?? new CommonBaseType() + }; + } +} diff --git a/ZSharp.Compiler.Objects/contexts/type inference/core/InferredType.cs b/ZSharp.Compiler.Objects/contexts/type inference/core/InferredType.cs new file mode 100644 index 00000000..c24d441c --- /dev/null +++ b/ZSharp.Compiler.Objects/contexts/type inference/core/InferredType.cs @@ -0,0 +1,43 @@ +using CommonZ.Utils; +using System.Diagnostics.CodeAnalysis; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class InferredType + : CompilerObject + , IType + , IImplicitCastFromValue + { + private readonly Compiler.Compiler compiler; + + public ITypeInferenceContext Context { get; } + + public required IInferredTypeResolver Resolver { get; set; } + + public IType? ResolvedType { get; private set; } + + public bool IsResolved => ResolvedType is not null; + + public Collection CollectedTypes { get; set; } = []; + + internal InferredType(Compiler.Compiler compiler, ITypeInferenceContext context) + { + this.compiler = compiler; + Context = context; + } + + [MemberNotNull(nameof(ResolvedType))] + public IType Resolve() + => ResolvedType = Resolver.Resolve(compiler, this); + + CompilerObject IImplicitCastFromValue.ImplicitCastFromValue(Compiler.Compiler compiler, CompilerObject value) + { + if (!compiler.TypeSystem.IsTyped(value, out var type)) + throw new NotImplementedException(); + + CollectedTypes.Add(type); + return this; + } + } +} diff --git a/ZSharp.Compiler.Objects/contexts/type inference/resolvers/CommonBaseType.cs b/ZSharp.Compiler.Objects/contexts/type inference/resolvers/CommonBaseType.cs new file mode 100644 index 00000000..7ad57210 --- /dev/null +++ b/ZSharp.Compiler.Objects/contexts/type inference/resolvers/CommonBaseType.cs @@ -0,0 +1,52 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class CommonBaseType + : IInferredTypeResolver + { + IType IInferredTypeResolver.Resolve(Compiler.Compiler compiler, InferredType inferredType) + { + List<(IClass, int)> classes = []; + + IType? commonBase = null; + int minDepth = int.MaxValue; + + foreach (var type in inferredType.CollectedTypes) + { + if (type is not IClass @class) + { + if (commonBase is not null && !compiler.TypeSystem.AreEqual(commonBase, type)) + throw new(); + commonBase = type; + + continue; + } + + int depth = 0; + + for (; @class.Base is not null; @class = @class.Base) + depth++; + + if (depth < minDepth) + (commonBase, minDepth) = (@class, depth); + + classes.Add((@class, depth)); + } + + if (commonBase is null) + throw new InvalidOperationException(); + + foreach (var (@class, depth) in classes) + { + var @base = @class; + while (depth > minDepth) @base = @base!.Base; + + if (!compiler.TypeSystem.AreEqual(@base!, commonBase)) + throw new InvalidOperationException(); + } + + return commonBase; + } + } +} diff --git a/ZSharp.Compiler.Objects/functional/generic/GenericFunction.cs b/ZSharp.Compiler.Objects/functional/generic/GenericFunction.cs index 0422a0b2..3d7b6ecd 100644 --- a/ZSharp.Compiler.Objects/functional/generic/GenericFunction.cs +++ b/ZSharp.Compiler.Objects/functional/generic/GenericFunction.cs @@ -6,6 +6,7 @@ namespace ZSharp.Objects public sealed class GenericFunction(string? name = null) : CompilerObject , ICompileIRObject + , ICTCallable , ICTGetIndex , IReferencable { @@ -37,7 +38,11 @@ public bool Defined public Collection GenericParameters { get; set; } = []; - public CompilerObject? ReturnType { get; set; } + public IType? ReturnType + { + get => Signature.ReturnType; + set => Signature.ReturnType = value; + } public Signature Signature { get; set; } = new(); @@ -121,8 +126,42 @@ GenericFunctionInstance IReferencable.CreateReference(R return new(this) { - Context = context + Context = context, + Signature = @ref.CreateReference(Signature, context) }; } + + CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + ITypeInferenceContext infer; + + using var _ = compiler.ContextScope(infer = new SimpleInferenceContext(compiler)); + + List inferredTypes = []; + ReferenceContext context = new(); + + foreach (var genericParameter in GenericParameters) + { + var inferredType = infer.CreateInferredType(); + inferredTypes.Add(inferredType); + context.CompileTimeValues.Cache(genericParameter, inferredType); + } + + var reference = compiler.Feature().CreateReference(this, context); + + var args = (reference.Signature as ISignature)!.MatchArguments(compiler, arguments); + + foreach (var genericParameter in GenericParameters) + context.CompileTimeValues.Cache( + genericParameter, + context.CompileTimeValues.Cache(genericParameter)!.Resolve(), + set: true + ); + + return compiler.Call( + compiler.Feature().CreateReference(this, context), + arguments + ); + } } } diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/ExpressionContext.cs b/ZSharp.ZSSourceCompiler/contexts/concrete/ExpressionContext.cs new file mode 100644 index 00000000..d443a21e --- /dev/null +++ b/ZSharp.ZSSourceCompiler/contexts/concrete/ExpressionContext.cs @@ -0,0 +1,17 @@ +using ZSharp.Compiler; +using ZSharp.Objects; + +namespace ZSharp.ZSSourceCompiler +{ + public sealed class ExpressionContext(Compiler.Compiler compiler) + : IContext + , ITypeInferenceContext + { + private readonly Compiler.Compiler compiler = compiler; + + IContext? IContext.Parent { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + InferredType ITypeInferenceContext.CreateInferredType(IInferredTypeResolver? resolver) + => (this as ITypeInferenceContext).CreateInferredType(compiler, resolver); + } +} From 863c4d0621abac5a484c46a92d42485e09cf6d17 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 29 May 2025 16:13:17 +0300 Subject: [PATCH 164/235] Fix IsOfExpression node --- ZSharp.AST/nodes/expr/cast/IsOfExpression.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.AST/nodes/expr/cast/IsOfExpression.cs b/ZSharp.AST/nodes/expr/cast/IsOfExpression.cs index c043f1f2..f0353392 100644 --- a/ZSharp.AST/nodes/expr/cast/IsOfExpression.cs +++ b/ZSharp.AST/nodes/expr/cast/IsOfExpression.cs @@ -2,7 +2,7 @@ { public sealed class IsOfExpression : Expression { - public Expression Expression { get; set; } + public required Expression Expression { get; set; } public string? Name { get; set; } From da7b1676a486ad95ffc725426485579c50597dc6 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 29 May 2025 16:13:45 +0300 Subject: [PATCH 165/235] Remove old inference system --- .../core/inference/Constraint.cs | 7 ---- .../core/inference/InferenceScope.cs | 42 ------------------- .../core/inference/InferenceTarget.cs | 13 ------ 3 files changed, 62 deletions(-) delete mode 100644 ZSharp.Compiler/compiler core/core/inference/Constraint.cs delete mode 100644 ZSharp.Compiler/compiler core/core/inference/InferenceScope.cs delete mode 100644 ZSharp.Compiler/compiler core/core/inference/InferenceTarget.cs diff --git a/ZSharp.Compiler/compiler core/core/inference/Constraint.cs b/ZSharp.Compiler/compiler core/core/inference/Constraint.cs deleted file mode 100644 index 95273a95..00000000 --- a/ZSharp.Compiler/compiler core/core/inference/Constraint.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - public abstract class Constraint - { - public CompilerObject Target { get; internal set; } = null!; - } -} diff --git a/ZSharp.Compiler/compiler core/core/inference/InferenceScope.cs b/ZSharp.Compiler/compiler core/core/inference/InferenceScope.cs deleted file mode 100644 index 4f20e430..00000000 --- a/ZSharp.Compiler/compiler core/core/inference/InferenceScope.cs +++ /dev/null @@ -1,42 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Compiler -{ - public delegate bool InferenceTargetResolver(InferenceTarget target); - - public sealed class InferenceScope(Compiler compiler, InferenceScope? parent) - : IDisposable - { - public Compiler Compiler { get; } = compiler; - - public InferenceScope? Parent { get; } = parent; - - public required InferenceTargetResolver DefaultResolver { get; set; } - - public Collection Targets { get; private set; } = []; - - public void Dispose() - { - if (!Resolve()) - PushToParent(); - } - - public bool Resolve() - { - Collection notResolved = []; - - foreach (var target in Targets) - if (!(target.Resolve ?? DefaultResolver)(target)) - notResolved.Add(target); - - return (Targets = notResolved).Count > 0; - } - - public void PushToParent() - { - Parent?.Targets.AddRange(Targets); - - Targets.Clear(); - } - } -} diff --git a/ZSharp.Compiler/compiler core/core/inference/InferenceTarget.cs b/ZSharp.Compiler/compiler core/core/inference/InferenceTarget.cs deleted file mode 100644 index f8d9dea0..00000000 --- a/ZSharp.Compiler/compiler core/core/inference/InferenceTarget.cs +++ /dev/null @@ -1,13 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Compiler -{ - public sealed class InferenceTarget(CompilerObject target) - { - public CompilerObject Target { get; } = target; - - public Collection Constraints { get; } = new(); - - public InferenceTargetResolver? Resolve { get; set; } - } -} From 2731b22d1f602b6b5b8a3f036f2000505bd8f540 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 29 May 2025 16:14:32 +0300 Subject: [PATCH 166/235] Add prototype-grade `as` operator support --- ZSharp.AST/nodes/expr/cast/CastExpression.cs | 9 ++++ ZSharp.Parser/lang/expr/LangParser.As.cs | 20 ++++++++ .../expression/ExpressionCompiler.cs | 50 ++++++++++++++++++- ZSharpTest/Main.cs | 1 + 4 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 ZSharp.AST/nodes/expr/cast/CastExpression.cs create mode 100644 ZSharp.Parser/lang/expr/LangParser.As.cs diff --git a/ZSharp.AST/nodes/expr/cast/CastExpression.cs b/ZSharp.AST/nodes/expr/cast/CastExpression.cs new file mode 100644 index 00000000..bfa48063 --- /dev/null +++ b/ZSharp.AST/nodes/expr/cast/CastExpression.cs @@ -0,0 +1,9 @@ +namespace ZSharp.AST +{ + public sealed class CastExpression : Expression + { + public required Expression Expression { get; set; } + + public required Expression TargetType { get; set; } + } +} diff --git a/ZSharp.Parser/lang/expr/LangParser.As.cs b/ZSharp.Parser/lang/expr/LangParser.As.cs new file mode 100644 index 00000000..9874627e --- /dev/null +++ b/ZSharp.Parser/lang/expr/LangParser.As.cs @@ -0,0 +1,20 @@ +using ZSharp.AST; + +namespace ZSharp.Parser +{ + public static partial class LangParser + { + public static CastExpression ParseCastExpression(Parser parser, Expression expression) + { + var asKeyword = parser.Eat(Keywords.As); + + var targetType = parser.Parse(); + + return new() + { + Expression = expression, + TargetType = targetType, + }; + } + } +} diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index 89ce3870..4f0422db 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -1,4 +1,6 @@ -namespace ZSharp.ZSSourceCompiler +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler { public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) : CompilerBase(compiler) @@ -9,6 +11,7 @@ public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) ArrayLiteral array => Compile(array), BinaryExpression binary => Compile(binary), CallExpression call => Compile(call), + CastExpression cast => Compile(cast), IdentifierExpression identifier => Compile(identifier), IndexExpression index => Compile(index), IsOfExpression isOf => Compile(isOf), @@ -63,6 +66,51 @@ private CompilerObject Compile(CallExpression call) return Compiler.Compiler.Call(callable, args.ToArray()); } + private CompilerObject Compile(CastExpression cast) + { + var expression = Compiler.CompileNode(cast.Expression); + + var targetType = Compiler.CompileType(cast.TargetType); + + if (targetType is not Objects.Nullable) + { + Compiler.LogError("Casting to non-nullable type is not supported yet", cast); + + targetType = new Objects.Nullable(targetType); + } + + var castResult = Compiler.Compiler.CG.Cast(expression, targetType); + + TypeCast typeCast; + + if (castResult.Error(out var error)) + { + Compiler.LogError(error, cast); + + return Compiler.Compiler.CreateNull(); + } + else typeCast = castResult.Unwrap(); + + var castCodeResult = Compiler.Compiler.IR.CompileCode(typeCast.Cast); + + IRCode castCode; + + if (castCodeResult.Error(out error)) + { + Compiler.LogError(error, cast); + + return Compiler.Compiler.CreateNull(); + } else castCode = castCodeResult.Unwrap(); + + castCode.Instructions.Add(typeCast.OnCast); + if (typeCast.CanFail) + castCode.Instructions.Add(typeCast.OnFail); + + castCode.Types[0] = (targetType as Objects.Nullable)!.UnderlyingType; + + return new Objects.RawCode(castCode); // TODO: add OnCast and OnFail handlers + } + private CompilerObject Compile(IdentifierExpression identifier) { CompilerObject? result = null; diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index c3b67387..199533d1 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -77,6 +77,7 @@ expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); expressionParser.Led(".", LangParser.ParseMemberAccess, 150); + expressionParser.Led(LangParser.Keywords.As, LangParser.ParseCastExpression, 20); expressionParser.Led(LangParser.Keywords.Is, LangParser.ParseIsOfExpression, 20); expressionParser.Separator(TokenType.Comma); From 712a905d4022987e389d3a5c6bc6712a8a01cc6f Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 2 Jun 2025 23:01:27 +0300 Subject: [PATCH 167/235] Remove OnCast handler from TypeCast --- ZSharp.Compiler.Objects/nullable/Nullable.cs | 13 +++++++++---- ZSharp.Compiler.Objects/oop/class/Class.cs | 3 +-- .../cg/{ => capabilities}/type casting/TypeCast.cs | 2 -- .../core-compilers/expression/ExpressionCompiler.cs | 1 - 4 files changed, 10 insertions(+), 9 deletions(-) rename ZSharp.Compiler/features/cg/{ => capabilities}/type casting/TypeCast.cs (79%) diff --git a/ZSharp.Compiler.Objects/nullable/Nullable.cs b/ZSharp.Compiler.Objects/nullable/Nullable.cs index e237c680..2aeb9aac 100644 --- a/ZSharp.Compiler.Objects/nullable/Nullable.cs +++ b/ZSharp.Compiler.Objects/nullable/Nullable.cs @@ -1,5 +1,4 @@ -using System; -using ZSharp.Compiler; +using ZSharp.Compiler; namespace ZSharp.Objects { @@ -35,21 +34,24 @@ Result IRTCastFrom.Cast(Compiler.Compiler compiler, CompilerObj return Result.Error(error); else innerCastCode = innerCastCodeResult.Unwrap(); + IR.VM.Nop onCast = new(); + return Result.Ok( new() { Cast = new RawCode(new([ .. innerCastCode.Instructions, + new IR.VM.Jump(onCast), .. (IR.VM.Instruction[])(innerCast.CanFail ? [ innerCast.OnFail, new IR.VM.PutNull(), ] : []), + onCast, ]) { Types = [this] } ), - OnCast = innerCast.OnCast } ); } @@ -77,21 +79,24 @@ Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObjec return Result.Error(error); else innerCastCode = innerCastCodeResult.Unwrap(); + IR.VM.Nop onCast = new(); + return Result.Ok( new() { Cast = new RawCode(new([ .. innerCastCode.Instructions, + new IR.VM.Jump(onCast), .. (IR.VM.Instruction[])(innerCast.CanFail ? [ innerCast.OnFail, new IR.VM.PutNull(), ] : []), + onCast, ]) { Types = [targetType] } ), - OnCast = innerCast.OnCast } ); } diff --git a/ZSharp.Compiler.Objects/oop/class/Class.cs b/ZSharp.Compiler.Objects/oop/class/Class.cs index 6558ae7d..2f3d4c18 100644 --- a/ZSharp.Compiler.Objects/oop/class/Class.cs +++ b/ZSharp.Compiler.Objects/oop/class/Class.cs @@ -177,7 +177,6 @@ Result IRTTypeMatch.Match(Compiler.Compiler compiler, Compile { Match = new RawCode(new([ .. castToTypeCode.Instructions, - castToType.OnCast, new IR.VM.Dup(), new IR.VM.IsNotNull(), new IR.VM.JumpIfTrue(onMatch), @@ -237,11 +236,11 @@ Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObje new IR.VM.JumpIfTrue(onCast), new IR.VM.Pop(), new IR.VM.Jump(onFail), + onCast, ]) { Types = [targetType] }), - OnCast = onCast, OnFail = onFail, } ); diff --git a/ZSharp.Compiler/features/cg/type casting/TypeCast.cs b/ZSharp.Compiler/features/cg/capabilities/type casting/TypeCast.cs similarity index 79% rename from ZSharp.Compiler/features/cg/type casting/TypeCast.cs rename to ZSharp.Compiler/features/cg/capabilities/type casting/TypeCast.cs index 2c54261c..ac8d2b49 100644 --- a/ZSharp.Compiler/features/cg/type casting/TypeCast.cs +++ b/ZSharp.Compiler/features/cg/capabilities/type casting/TypeCast.cs @@ -6,8 +6,6 @@ public sealed class TypeCast { public required CompilerObject Cast { get; set; } - public ZSharp.IR.VM.Instruction OnCast { get; init; } = new ZSharp.IR.VM.Nop(); - public ZSharp.IR.VM.Instruction? OnFail { get; init; } = null; [MemberNotNullWhen(true, nameof(OnFail))] diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index 4f0422db..e69baed0 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -102,7 +102,6 @@ private CompilerObject Compile(CastExpression cast) return Compiler.Compiler.CreateNull(); } else castCode = castCodeResult.Unwrap(); - castCode.Instructions.Add(typeCast.OnCast); if (typeCast.CanFail) castCode.Instructions.Add(typeCast.OnFail); From 2c40ca471907b2071049ff48b1149bc3c90e4f16 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 8 Jun 2025 23:09:07 +0300 Subject: [PATCH 168/235] Make ImportedName a node --- ZSharp.AST/nodes/stmt/import/ImportedName.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.AST/nodes/stmt/import/ImportedName.cs b/ZSharp.AST/nodes/stmt/import/ImportedName.cs index 3891eaa0..ba4742d6 100644 --- a/ZSharp.AST/nodes/stmt/import/ImportedName.cs +++ b/ZSharp.AST/nodes/stmt/import/ImportedName.cs @@ -1,6 +1,6 @@ namespace ZSharp.AST { - public sealed class ImportedName + public sealed class ImportedName : Node { public required string Name { get; set; } From 4d6182268296b971f3e5621033f1ca4eb730d11e Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 8 Jun 2025 23:09:42 +0300 Subject: [PATCH 169/235] Fix IR loader to defer loading base type --- ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index 2c473e19..a5f28594 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -146,11 +146,11 @@ private Action Load(ZSharp.IR.Class @class, Module owner) if (result.Name is not null && result.Name != string.Empty) owner.Members.Add(result.Name, result); - if (@class.Base is not null) - result.Base = (IClass)Load(@class.Base); - return () => { + if (@class.Base is not null) + result.Base = (IClass)Load(@class.Base); + if (@class.HasFields) foreach (var field in @class.Fields) { From 92472f8b51e47bbf70a6cb2696445a23a984896d Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 8 Jun 2025 23:10:05 +0300 Subject: [PATCH 170/235] Fix source compiler --- ZSharp.ZSSourceCompiler/GlobalUsings.cs | 13 + .../class body/ClassBodyCompiler.cs | 105 ++++++-- .../class body/ConstructorCompiler.cs | 40 +-- .../class body/MethodCompiler.cs | 96 ++++--- .../document/compiler/DocumentCompiler.cs | 27 +- .../builtin-compilers/module/ClassCompiler.cs | 2 +- .../module/FunctionCompiler.cs | 84 +++--- .../module/ModuleCompiler.cs | 11 +- .../runtime code/loops/for/ForLoopCompiler.cs | 32 +-- .../loops/while/WhileExpressionCompiler.cs | 41 ++- .../loops/while/WhileLoopCompiler.cs | 12 +- .../loops/while/WhileStatementCompiler.cs | 12 +- .../runtime code/objects/Case.cs | 2 +- .../compiler/ZSSourceCompiler.Logging.cs | 14 +- .../compiler/ZSSourceCompiler.cs | 58 +++- .../context/Context.Compilers.cs | 42 +-- .../context/Context.Nodes.cs | 2 - ZSharp.ZSSourceCompiler/context/Context.cs | 2 +- .../core-compilers/DefaultContextCompiler.cs | 13 +- .../expression/ExpressionCompiler.Literals.cs | 25 +- .../expression/ExpressionCompiler.cs | 140 +++++----- .../statement/StatementCompiler.cs | 250 +++++++++++++----- .../extensibility/ContextCompiler.cs | 4 - .../overrides/IOverrideCompileNode.cs | 2 +- 24 files changed, 621 insertions(+), 408 deletions(-) diff --git a/ZSharp.ZSSourceCompiler/GlobalUsings.cs b/ZSharp.ZSSourceCompiler/GlobalUsings.cs index 9a59d6a7..959ad0f4 100644 --- a/ZSharp.ZSSourceCompiler/GlobalUsings.cs +++ b/ZSharp.ZSSourceCompiler/GlobalUsings.cs @@ -1,2 +1,15 @@ global using CompilerObject = ZSharp.Objects.CompilerObject; global using ZSharp.AST; + +global using ObjectResult = + ZSharp.Compiler.Result< + ZSharp.Objects.CompilerObject, + ZSharp.ZSSourceCompiler.Error + >; +global using TypeResult = + ZSharp.Compiler.Result< + ZSharp.Compiler.IType, + ZSharp.ZSSourceCompiler.Error + >; + +global using static ZSharp.ZSSourceCompiler.HelperFunctions; diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs index 05907445..5238e351 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs @@ -66,7 +66,7 @@ private Action Compile(ExpressionStatement expression) private Action Compile(AST.Constructor constructor) { - var compiler = new ConstructorCompiler(Compiler, constructor); + var compiler = new ConstructorCompiler(this, constructor); compiler.Object.Owner = Class; @@ -91,7 +91,7 @@ private Action Compile(AST.Constructor constructor) private Action Compile(AST.Function function) { - var compiler = new MethodCompiler(Compiler, function, Class, Class); + var compiler = new MethodCompiler(this, function, Class, Class); Class.Content.Add(compiler.Object); @@ -126,19 +126,45 @@ private Action Compile(LetExpression let) return () => { - field.Initializer = Compiler.CompileNode(let.Value); + if (Compiler.CompileNode(let.Value).Ok(out var initializer)) + field.Initializer = initializer; - if (let.Type is not null) - field.Type = Compiler.CompileType(let.Type); - else if (Compiler.Compiler.TypeSystem.IsTyped(field.Initializer, out var type)) + if ( + let.Type is not null && + Compiler.CompileType(let.Type).Ok(out var type) + ) + field.Type = type; + else if ( + field.Initializer is not null && + Compiler.Compiler.TypeSystem.IsTyped(field.Initializer, out type) + ) field.Type = type; - if (field.Type is null) throw new(); // TODO: Throw a proper exception of CouldNotInferType - - field.IR = Compiler.Compiler.CompileIRObject(field, null); - - if (field.Initializer is not null) - field.Initializer = Compiler.Compiler.TypeSystem.ImplicitCast(field.Initializer, field.Type).Unwrap(); + if (field.Type is null) + { + Compiler.LogError($"Field type could not be inferred", let); + return; + } + + if ( + Compiler.Compiler.IR.CompileDefinition(field, null) + .When(ir => field.IR = ir) + .Else(error => Compiler.LogError( + $"Could not compile IR for field {let.Name}: {error}", let + ) + ).IsError + ) + return; + + if (field.Initializer is not null && + Compiler.Compiler.CG.ImplicitCast(field.Initializer, field.Type) + .When(init => field.Initializer = init) + .Else(error => Compiler.LogError( + $"Could not initialize field {let.Name}: {error}", let + ) + ).IsError + ) + return; }; } @@ -156,21 +182,48 @@ private Action Compile(VarExpression var) return () => { - if (var.Value is not null) - field.Initializer = Compiler.CompileNode(var.Value); - - if (var.Type is not null) - field.Type = Compiler.CompileType(var.Type); - else if (field.Initializer is not null) - if (Compiler.Compiler.TypeSystem.IsTyped(field.Initializer, out var type)) - field.Type = type; - - if (field.Type is null) throw new(); // TODO: Throw a proper exception of CouldNotInferType - - field.IR = Compiler.Compiler.CompileIRObject(field, null); + if ( + var.Value is not null && + Compiler.CompileNode(var.Value).Ok(out var initializer) + ) + field.Initializer = initializer; + + if ( + var.Type is not null && + Compiler.CompileType(var.Type).Ok(out var type) + ) + field.Type = type; + else if ( + field.Initializer is not null && + Compiler.Compiler.TypeSystem.IsTyped(field.Initializer, out type) + ) + field.Type = type; - if (field.Initializer is not null) - field.Initializer = Compiler.Compiler.TypeSystem.ImplicitCast(field.Initializer, field.Type).Unwrap(); + if (field.Type is null) + { + Compiler.LogError($"Field type could not be inferred", var); + return; + } + + if ( + Compiler.Compiler.IR.CompileDefinition(field, null) + .When(ir => field.IR = ir) + .Else(error => Compiler.LogError( + $"Could not compile IR for field {var.Name}: {error}", var + ) + ).IsError + ) + return; + + if (field.Initializer is not null && + Compiler.Compiler.CG.ImplicitCast(field.Initializer, field.Type) + .When(init => field.Initializer = init) + .Else(error => Compiler.LogError( + $"Could not initialize field {var.Name}: {error}", var + ) + ).IsError + ) + return; }; } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs index 58774321..c80d9296 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs @@ -2,8 +2,8 @@ namespace ZSharp.ZSSourceCompiler { - public sealed class ConstructorCompiler(ZSSourceCompiler compiler, Constructor node) - : ContextCompiler(compiler, node, new(node.Name)) + public sealed class ConstructorCompiler(ClassBodyCompiler compiler, Constructor node) + : ContextCompiler(compiler.Compiler, node, new(node.Name)) , IOverrideCompileExpression { public Objects.Parameter This { get; private set; } = null!; @@ -40,22 +40,19 @@ private void CompileConstructor() (This = Object.Signature.Args[0]).Type ??= Object.Owner; - if (Context.ParentCompiler(out var multipassCompiler)) - multipassCompiler.AddToNextPass(() => - { - using (Context.Compiler(this)) - using (Context.Scope(Object)) - using (Context.Scope()) - CompileConstructorBody(); - }); - else using (Context.Scope()) - CompileConstructorBody(); + compiler.AddToNextPass(() => + { + using (Context.Compiler(this)) + using (Context.Scope(Object)) + using (Context.Scope()) + CompileConstructorBody(); + }); } private void CompileConstructorBody() { if (Node.Body is not null) - Object.Body = Compiler.CompileNode(Node.Body); + Object.Body = Compiler.CompileNode(Node.Body).Unwrap(); Object.IR = Compiler.Compiler.CompileIRObject(Object, null!); @@ -69,7 +66,7 @@ private Objects.Parameter Compile(Parameter parameter) Context.CurrentScope.Set(parameter.Alias ?? parameter.Name, result); if (parameter.Type is not null) - result.Type = Compiler.CompileType(parameter.Type); + result.Type = Compiler.CompileType(parameter.Type).Unwrap(); if (parameter.Initializer is not null) Compiler.LogError("Parameter initializers are not supported yet.", parameter); @@ -77,7 +74,7 @@ private Objects.Parameter Compile(Parameter parameter) return result; } - private CompilerObject? Compile(IdentifierExpression identifier) + private ObjectResult? Compile(IdentifierExpression identifier) { CompilerObject? member = null; @@ -91,22 +88,25 @@ private Objects.Parameter Compile(Parameter parameter) ) ); + if (member is null) + return null; + if (member is Objects.IRTBoundMember boundMember) - return boundMember.Bind(Compiler.Compiler, This); + return ObjectResult.Ok(boundMember.Bind(Compiler.Compiler, This)); if (member is Objects.OverloadGroup group) - return new Objects.OverloadGroup(group.Name) + return ObjectResult.Ok(new Objects.OverloadGroup(group.Name) { Overloads = [.. group.Overloads.Select( overload => overload is Objects.IRTBoundMember boundMember ? boundMember.Bind(Compiler.Compiler, This) : overload )], - }; + }); - return member; + return ObjectResult.Ok(member); } - CompilerObject? IOverrideCompileNode.CompileNode(ZSSourceCompiler compiler, Expression node) + ObjectResult? IOverrideCompileNode.CompileNode(ZSSourceCompiler compiler, Expression node) => node switch { IdentifierExpression identifier => Compile(identifier), diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs index a1e5a26a..986ba1a5 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs @@ -1,7 +1,7 @@ namespace ZSharp.ZSSourceCompiler { - public sealed class MethodCompiler(ZSSourceCompiler compiler, Function node, CompilerObject owner, Compiler.IType self) - : ContextCompiler(compiler, node, new(node.Name) + public sealed class MethodCompiler(ClassBodyCompiler compiler, Function node, CompilerObject owner, Compiler.IType self) + : ContextCompiler(compiler.Compiler, node, new(node.Name) { Owner = owner }) @@ -37,23 +37,31 @@ private void CompileMethod() throw new NotImplementedException(); if (Node.ReturnType is not null) - Object.ReturnType = Compiler.CompileType(Node.ReturnType); - else throw new(); // TODO: Implement Infer type + if ( + Compiler.CompileType(Node.ReturnType) + .When(out var returnType) + .Error(out var error) + ) + { + return; + } + else Object.ReturnType = returnType; + else + { + return; + } - (This = Object.Signature.Args[0]).Type ??= self; + (This = Object.Signature.Args[0]).Type ??= self; //Object.IR = Compiler.Compiler.CompileIRObject(Object, null); - if (Context.ParentCompiler(out var multipassCompiler)) - multipassCompiler.AddToNextPass(() => - { - using (Context.Compiler(this)) - using (Context.Scope(Object)) - using (Context.Scope()) - CompileMethodBody(); - }); - else using (Context.Scope()) + compiler.AddToNextPass(() => + { + using (Context.Compiler(this)) + using (Context.Scope(Object)) + using (Context.Scope()) CompileMethodBody(); + }); } private Objects.Parameter Compile(Parameter parameter) @@ -62,8 +70,11 @@ private Objects.Parameter Compile(Parameter parameter) Context.CurrentScope.Set(parameter.Alias ?? parameter.Name, result); - if (parameter.Type is not null) - result.Type = Compiler.CompileType(parameter.Type); + if ( + parameter.Type is not null && + Compiler.CompileType(parameter.Type).Ok(out var type) + ) + result.Type = type; if (parameter.Initializer is not null) Compiler.LogError("Parameter initializers are not supported yet.", parameter); @@ -73,35 +84,46 @@ private Objects.Parameter Compile(Parameter parameter) private void CompileMethodBody() { - if (Node.Body is not null) - Object.Body = Compiler.CompileNode(Node.Body); + if ( + Node.Body is not null && + Compiler.CompileNode(Node.Body).Ok(out var body) + ) + Object.Body = body; Object.IR = Compiler.Compiler.CompileIRObject(Object, null); } - public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement node) + public ObjectResult? CompileNode(ZSSourceCompiler compiler, Statement node) { if (node is not Return @return) return null; if (@return.Value is null) - return new Objects.RawCode(new([ + return ObjectResult.Ok(new Objects.RawCode(new([ new IR.VM.Return() - ])); - - var valueObject = Compiler.CompileNode(@return.Value); - var valueCode = Compiler.Compiler.CompileIRCode(valueObject); - - if (valueCode is null) - { - Compiler.LogError("Return expression could not be compiled.", node); - return null; - } - - valueCode.Instructions.Add(new IR.VM.Return()); + ]))); + + var valueResult = Compiler.CompileNode(@return.Value); + + if ( + valueResult + .When(out var returnValue) + .IsError + ) + return valueResult; + + if ( + Compiler.Compiler.IR.CompileCode(returnValue!) + .When(out var valueCode) + .Error(out var error) + ) + return Compiler.CompilationError(error, @return.Value); + + valueCode!.Instructions.Add(new IR.VM.Return()); + valueCode.RequireValueType(); valueCode.Types.Clear(); - return new Objects.RawCode(valueCode); + return ObjectResult.Ok(new Objects.RawCode(valueCode)); } public CompilerObject? CompileNode(ZSSourceCompiler compiler, Expression node) @@ -117,13 +139,13 @@ private CompilerObject CompileNode(LetExpression let) var local = new Objects.Local { Name = let.Name, - Initializer = Compiler.CompileNode(let.Value), + Initializer = Compiler.CompileNode(let.Value).Unwrap(), }; Context.CurrentScope.Set(let.Name, local); local.Type = let.Type is not null - ? Compiler.CompileType(let.Type) + ? Compiler.CompileType(let.Type).Unwrap() : Compiler.Compiler.TypeSystem.IsTyped(local.Initializer, out var type) ? type : null; @@ -147,13 +169,13 @@ private CompilerObject CompileNode(VarExpression var) var local = new Objects.Local { Name = var.Name, - Initializer = var.Value is null ? null : Compiler.CompileNode(var.Value), + Initializer = var.Value is null ? null : Compiler.CompileNode(var.Value).Unwrap(), }; Context.CurrentScope.Set(var.Name, local); local.Type = var.Type is not null - ? Compiler.CompileType(var.Type) + ? Compiler.CompileType(var.Type).Unwrap() : local.Initializer is null ? null : Compiler.Compiler.TypeSystem.IsTyped(local.Initializer, out var type) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs index 8f646947..8d4a650a 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs @@ -1,4 +1,6 @@  +using ZSharp.AST; + namespace ZSharp.ZSSourceCompiler { public sealed partial class DocumentCompiler(ZSSourceCompiler compiler, AST.Document node, Document document) @@ -9,6 +11,7 @@ public sealed partial class DocumentCompiler(ZSSourceCompiler compiler, AST.Docu public override Document Compile() { using (Context.Compiler(this)) + using (Compiler.Compiler.ContextScope(new ObjectContext(Object))) using (Context.Scope(Object)) CompileDocument(); @@ -21,20 +24,32 @@ private void CompileDocument() Compiler.CompileNode(item); } - public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement statement) + public ObjectResult? CompileNode(ZSSourceCompiler compiler, Statement statement) { - //if (statement is ExpressionStatement expressionStatement) - // return Compiler.Compiler.Evaluate(Compiler.CompileNode(expressionStatement.Expression)); + if (statement is ExpressionStatement expressionStatement) + return expressionStatement.Expression switch + { + Module => null, + Expression expression => ObjectResult.Ok( + Compiler.Compiler.Feature().EvaluateCO( + Compiler.Compiler.IR.CompileCode( + Compiler.CompileNode(expression).Unwrap() + ).Unwrap() + ) ?? throw new() + ), + }; return null; // if the statement is a definition, compile it } - public CompilerObject? CompileNode(ZSSourceCompiler compiler, Expression node) + public ObjectResult? CompileNode(ZSSourceCompiler compiler, Expression node) => node switch { Module module => Compile(module), - _ => null - }; + _ => null, + } is CompilerObject result + ? ObjectResult.Ok(result) + : null; } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs index b0ca90b6..62856e54 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs @@ -18,7 +18,7 @@ public override Class Compile() { if (Node.Bases is not null) { - var bases = Node.Bases.Select(Compiler.CompileType).ToArray(); + var bases = Node.Bases.Select(Compiler.CompileType).Select(result => result.Unwrap()).ToArray(); if (bases.Length > 0) { diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs index e91cbefb..ff1e1ec8 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs @@ -1,9 +1,9 @@ namespace ZSharp.ZSSourceCompiler { - public sealed class FunctionCompiler(ZSSourceCompiler compiler, Function node) - : ContextCompiler(compiler, node, new(node.Name)) + public sealed class FunctionCompiler(ModuleCompiler moduleCompiler, Function node) + : ContextCompiler(moduleCompiler.Compiler, node, new(node.Name)) , IOverrideCompileStatement - ,IOverrideCompileExpression + , IOverrideCompileExpression { public override Objects.RTFunction Compile() { @@ -34,22 +34,19 @@ private void CompileFunction() throw new NotImplementedException(); if (Node.ReturnType is not null) - Object.ReturnType = Compiler.CompileType(Node.ReturnType); + Object.ReturnType = Compiler.CompileType(Node.ReturnType).Unwrap(); else throw new(); // TODO: Implement Infer type Object.IR = Compiler.Compiler.CompileIRObject(Object, null); - if (Context.ParentCompiler(out var multipassCompiler)) - multipassCompiler.AddToNextPass(() => - { - using (Context.Compiler(this)) - using (Compiler.Compiler.ContextScope(new FunctionContext(Compiler.Compiler, Object))) - using (Context.Scope(Object)) - using (Context.Scope()) - CompileFunctionBody(); - }); - else using (Context.Scope()) - CompileFunctionBody(); + moduleCompiler.AddToNextPass(() => + { + using (Context.Compiler(this)) + using (Compiler.Compiler.ContextScope(new FunctionContext(Compiler.Compiler, Object))) + using (Context.Scope(Object)) + using (Context.Scope()) + CompileFunctionBody(); + }); } private Objects.Parameter Compile(Parameter parameter) @@ -59,7 +56,7 @@ private Objects.Parameter Compile(Parameter parameter) Context.CurrentScope.Set(parameter.Alias ?? parameter.Name, result); if (parameter.Type is not null) - result.Type = Compiler.CompileType(parameter.Type); + result.Type = Compiler.CompileType(parameter.Type).Unwrap(); if (parameter.Initializer is not null) Compiler.LogError("Parameter initializers are not supported yet.", parameter); @@ -70,54 +67,55 @@ private Objects.Parameter Compile(Parameter parameter) private void CompileFunctionBody() { if (Node.Body is not null) - Object.Body = Compiler.CompileNode(Node.Body); + Object.Body = Compiler.CompileNode(Node.Body).Unwrap(); } - public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement node) + public ObjectResult? CompileNode(ZSSourceCompiler compiler, Statement node) { if (node is not Return @return) return null; if (@return.Value is null) - return new Objects.RawCode(new([ + return ObjectResult.Ok(new Objects.RawCode(new([ new IR.VM.Return() - ])); + ]))); - var valueObject = Compiler.CompileNode(@return.Value); - var valueCode = Compiler.Compiler.CompileIRCode(valueObject); + var valueObject = Compiler.CompileNode(@return.Value).Unwrap(); + var valueCodeResult = Compiler.Compiler.IR.CompileCode(valueObject); - if (valueCode is null) - { - Compiler.LogError("Return expression could not be compiled.", node); - return null; - } + if ( + valueCodeResult + .When(out var valueCode) + .Error(out var error) + ) + return Compiler.CompilationError(error, @return.Value); - valueCode.Instructions.Add(new IR.VM.Return()); + valueCode!.Instructions.Add(new IR.VM.Return()); valueCode.Types.Clear(); - return new Objects.RawCode(valueCode); + return ObjectResult.Ok(new Objects.RawCode(valueCode)); } - public CompilerObject? CompileNode(ZSSourceCompiler compiler, Expression node) + public ObjectResult? CompileNode(ZSSourceCompiler compiler, Expression node) => node switch { LetExpression let => CompileNode(let), VarExpression var => CompileNode(var), - _ => null + _ => null, }; - private CompilerObject CompileNode(LetExpression let) + private ObjectResult CompileNode(LetExpression let) { var local = new Objects.Local { Name = let.Name, - Initializer = Compiler.CompileNode(let.Value), + Initializer = Compiler.CompileNode(let.Value).Unwrap(), }; Context.CurrentScope.Set(let.Name, local); local.Type = let.Type is not null - ? Compiler.CompileType(let.Type) + ? Compiler.CompileType(let.Type).Unwrap() : Compiler.Compiler.TypeSystem.IsTyped(local.Initializer, out var type) ? type : null; @@ -128,26 +126,26 @@ private CompilerObject CompileNode(LetExpression let) local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); if (local.IR.Initializer is not null) - return new Objects.RawCode(new(local.IR.Initializer) + return ObjectResult.Ok(new Objects.RawCode(new(local.IR.Initializer) { Types = [local.Type] - }); + })); - return new Objects.RawCode(new()); + return ObjectResult.Ok(new Objects.RawCode(new())); } - private CompilerObject CompileNode(VarExpression var) + private ObjectResult CompileNode(VarExpression var) { var local = new Objects.Local { Name = var.Name, - Initializer = var.Value is null ? null : Compiler.CompileNode(var.Value), + Initializer = var.Value is null ? null : Compiler.CompileNode(var.Value).Unwrap(), }; Context.CurrentScope.Set(var.Name, local); local.Type = var.Type is not null - ? Compiler.CompileType(var.Type) + ? Compiler.CompileType(var.Type).Unwrap() : local.Initializer is null ? null : Compiler.Compiler.TypeSystem.IsTyped(local.Initializer, out var type) @@ -160,12 +158,12 @@ private CompilerObject CompileNode(VarExpression var) local.IR = Compiler.Compiler.CompileIRObject(local, Object.IR!.Body); if (local.IR.Initializer is not null) - return new Objects.RawCode(new(local.IR.Initializer) + return ObjectResult.Ok(new Objects.RawCode(new(local.IR.Initializer) { Types = [local.Type] - }); + })); - return new Objects.RawCode(new()); + return ObjectResult.Ok(new Objects.RawCode(new())); } } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs index 5261fcaf..38fb332b 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs @@ -18,6 +18,7 @@ public void AddToNextPass(Action action) public override Objects.Module Compile() { using (Context.Compiler(this)) + using (Compiler.Compiler.ContextScope(new ObjectContext(Object))) using (Context.Scope(Object)) CompileModule(); @@ -60,7 +61,7 @@ private Action Compile(ExpressionStatement expression) private Action Compile(Function function) { - var compiler = new FunctionCompiler(Compiler, function); + var compiler = new FunctionCompiler(this, function); Object.Content.Add(compiler.Object); @@ -84,10 +85,10 @@ private Action Compile(LetExpression let) return () => { - global.Initializer = Compiler.CompileNode(let.Value); + global.Initializer = Compiler.CompileNode(let.Value).Unwrap(); if (let.Type is not null) - global.Type = Compiler.CompileType(let.Type); + global.Type = Compiler.CompileType(let.Type).Unwrap(); else if (Compiler.Compiler.TypeSystem.IsTyped(global.Initializer, out var type)) global.Type = type; @@ -148,10 +149,10 @@ private Action Compile(VarExpression var) return () => { if (var.Value is not null) - global.Initializer = Compiler.CompileNode(var.Value); + global.Initializer = Compiler.CompileNode(var.Value).Unwrap(); if (var.Type is not null) - global.Type = Compiler.CompileType(var.Type); + global.Type = Compiler.CompileType(var.Type).Unwrap(); else if (global.Initializer is not null) if (Compiler.Compiler.TypeSystem.IsTyped(global.Initializer, out var type)) global.Type = type; diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs index a1897a8d..078b4fee 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs @@ -13,7 +13,7 @@ public class ForStatementCompiler(ZSSourceCompiler compiler, ForStatement node) public override ForLoop Compile() { - var source = Object.Source = Compiler.CompileNode(Node.Source); + var source = Object.Source = Compiler.CompileNode(Node.Source).Unwrap(); Iterator = Compiler.Compiler.Member(source, "getIterator"); Iterator = Compiler.Compiler.Call(Iterator, []); @@ -48,7 +48,7 @@ public override ForLoop Compile() using (Context.Scope()) { CompileForValue(); - Object.For = Compiler.CompileNode(Node.Body); + Object.For = Compiler.CompileNode(Node.Body).Unwrap(); } if (Node.Else is not null) @@ -58,24 +58,24 @@ public override ForLoop Compile() return base.Compile(); } - protected CompilerObject CompileBreak(BreakStatement @break) + protected ObjectResult CompileBreak(BreakStatement @break) { // TODO: add support for 'break from' statement if (@break.Value is not null) Compiler.LogError("Break statement in a for statement must not have a value", @break); - return new Objects.RawCode( + return ObjectResult.Ok(new Objects.RawCode( new([ new IR.VM.Jump(Object.EndLabel) ]) - ); + )); } protected CompilerObject CompileElse() - => Compiler.CompileNode(Node.Else!); + => Compiler.CompileNode(Node.Else!).Unwrap(); - public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement node) + public ObjectResult? CompileNode(ZSSourceCompiler compiler, Statement node) => node switch { BreakStatement @break => CompileBreak(@break), @@ -84,26 +84,22 @@ protected CompilerObject CompileElse() private void CompileForValue() { - Object.Value = Node.Value switch { + Object.Value = (Node.Value switch { LetForValue let => CompileLetForValue(let), _ => throw new() - }; + }).Unwrap(); } - private CompilerObject CompileLetForValue(LetForValue let) + private ObjectResult CompileLetForValue(LetForValue let) { var allocator = Compiler.Compiler.CurrentContext.FindContext(); if (allocator is null) - { - Compiler.LogError($"Could not find memory allocator in context chain", Node); - - throw new(); - } + return Compiler.CompilationError($"Could not find memory allocator in context chain", Node); var local = allocator.Allocate( let.Name, let.Type is not null - ? Compiler.CompileType(let.Type) + ? Compiler.CompileType(let.Type).Unwrap() : Compiler.Compiler.TypeSystem.IsTyped(Current, out var type) ? type : throw new(), @@ -115,10 +111,10 @@ let.Type is not null Compiler.Context.CurrentScope.Set(let.Name, local); - return new Objects.RawCode(new(local1.IR?.Initializer!) + return ObjectResult.Ok(new Objects.RawCode(new(local1.IR?.Initializer!) { Types = [local1.Type] - }); + })); } } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs index 3c84ac9a..00040be2 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs @@ -3,46 +3,43 @@ public sealed class WhileExpressionCompiler(ZSSourceCompiler compiler, WhileExpression node, Compiler.IType type) : WhileLoopCompiler(compiler, node, type) { - protected override CompilerObject CompileBreak(BreakStatement @break) + protected override ObjectResult CompileBreak(BreakStatement @break) { if (@break.Value is null) - { - Compiler.LogError("Break statement in a while expression must have a value", @break); - return new Objects.RawCode(new([new IR.VM.Jump(Object.EndLabel)])); - } - - var value = Compiler.CompileNode(@break.Value); - if (!Compiler.Compiler.TypeSystem.IsTyped(value, out var type)) - { - Compiler.LogError("Value must be a valid RT value!", @break.Value); - return new Objects.RawCode(new([new IR.VM.Jump(Object.EndLabel)])); - } + return Compiler.CompilationError("Break statement in a while expression must have a value", @break); + + var valueResult = Compiler.CompileNode(@break.Value); + if ( + valueResult + .When(out var value) + .Error(out var error) + ) + return ObjectResult.Error(error); + if (!Compiler.Compiler.TypeSystem.IsTyped(value!, out var type)) + return Compiler.CompilationError("Value must be a valid RT value!", @break.Value); Object.Type ??= type; if (!Compiler.Compiler.TypeSystem.ImplicitCast(value, Object.Type).Ok(out var breakValue)) - throw new Compiler.InvalidCastException(value, Object.Type); + return Compiler.CompilationError("Could not cast break value to while expression type", @break.Value); - var code = Compiler.Compiler.CompileIRCode(breakValue); + var code = Compiler.Compiler.IR.CompileCode(breakValue).Unwrap(); - return new Objects.RawCode( + return ObjectResult.Ok(new Objects.RawCode( new([ .. code.Instructions, new IR.VM.Jump(Object.EndLabel) ]) - ); + )); } - protected override CompilerObject CompileElse() + protected override ObjectResult CompileElse() { if (Object.Type is null) - { - Compiler.LogError("While expression must have a type", Node); - return new Objects.RawCode(new([new IR.VM.Jump(Object.EndLabel)])); - } + return Compiler.CompilationError("While expression must have a type", Node); - return Compiler.Compiler.TypeSystem.ImplicitCast(Compiler.CompileNode(Node.Else!), Object.Type).Unwrap(); + return ObjectResult.Ok(Compiler.Compiler.TypeSystem.ImplicitCast(Compiler.CompileNode(Node.Else!).Unwrap(), Object.Type).Unwrap()); } } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs index 8d4aa21c..687dfa12 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs @@ -11,24 +11,24 @@ public abstract class WhileLoopCompiler(ZSSourceCompiler compiler, WhileE { public override WhileLoop Compile() { - Object.Condition = Compiler.CompileNode(Node.Condition); + Object.Condition = Compiler.CompileNode(Node.Condition).Unwrap(); using (Context.Compiler(this)) using (Context.Scope()) - Object.While = Compiler.CompileNode(Node.Body); + Object.While = Compiler.CompileNode(Node.Body).Unwrap(); if (Node.Else is not null) using (Context.Scope()) - Object.Else = CompileElse(); + Object.Else = CompileElse().Unwrap(); return base.Compile(); } - protected abstract CompilerObject CompileBreak(BreakStatement @break); + protected abstract ObjectResult CompileBreak(BreakStatement @break); - protected abstract CompilerObject CompileElse(); + protected abstract ObjectResult CompileElse(); - public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement node) + public ObjectResult? CompileNode(ZSSourceCompiler compiler, Statement node) => node switch { BreakStatement @break => CompileBreak(@break), diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs index 06a065bb..1f9074c2 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs @@ -3,21 +3,21 @@ public sealed class WhileStatementCompiler(ZSSourceCompiler compiler, WhileExpression node) : WhileLoopCompiler(compiler, node, compiler.Compiler.TypeSystem.Void) { - protected override CompilerObject CompileBreak(BreakStatement @break) + protected override ObjectResult CompileBreak(BreakStatement @break) { // TODO: add support for 'break from' statement if (@break.Value is not null) - Compiler.LogError("Break statement in a while statement must not have a value", @break); + return Compiler.CompilationError("Break statement in a while statement must not have a value", @break); - return new Objects.RawCode( + return ObjectResult.Ok(new Objects.RawCode( new([ new IR.VM.Jump(Object.EndLabel) ]) - ); + )); } - protected override CompilerObject CompileElse() - => Compiler.CompileNode(Node.Else!); + protected override ObjectResult CompileElse() + => Compiler.CompileNode(Node.Else!); } } diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/Case.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/Case.cs index 163cfbcd..cd27b855 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/Case.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/Case.cs @@ -18,7 +18,7 @@ public sealed class When public required CompilerObject Of { get; set; } - public List Clauses { get; } = []; + public List Clauses { get; init; } = []; public CompilerObject? Else { get; set; } diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Logging.cs b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Logging.cs index 542e0832..1794c196 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Logging.cs +++ b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Logging.cs @@ -1,10 +1,14 @@ -namespace ZSharp.ZSSourceCompiler +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler { - public sealed partial class ZSSourceCompiler : Compiler.Feature + public sealed partial class ZSSourceCompiler : Feature { + public void LogError(string message, Node origin) + where T : class + => Compiler.Log.Error(message, new NodeLogOrigin(origin)); + public void LogError(string message, Node origin) - { - Compiler.Log.Error(message, new NodeLogOrigin(origin)); - } + => LogError(message, origin); } } diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs index 071d9fac..913d526e 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs +++ b/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs @@ -23,23 +23,63 @@ public ZSSourceCompiler(Compiler.Compiler compiler) Initialize(); } - public CompilerObject CompileNode(Expression expression) + public ObjectResult CompileNode(Expression expression) => CompileNode(expression); - public CompilerObject CompileNode(Statement statement) + public ObjectResult CompileNode(Statement statement) => CompileNode(statement); - private CompilerObject CompileNode(T node) + private ObjectResult CompileNode(T node) where T : Node { - foreach (var compiler in Context.Compilers>()) - if (compiler.CompileNode(this, node) is CompilerObject result) - return result; + foreach (var compiler in (IEnumerable)[ + Context.CurrentCompiler, + Context.DefaultCompiler, + ]) + { + if (compiler is not IOverrideCompileNode compileNode) + continue; - throw new($"Could not find suitable compiler for node of type {node.GetType().Name}"); // TODO: proper exception: could not find suitable compiler for T + var result = compileNode.CompileNode(this, node); + + if (result is null) continue; + + return result; + } + + return CompilationError( + "Could not compile node", node + ); } - public Compiler.IType CompileType(Expression expression) - => Compiler.TypeSystem.EvaluateType(CompileNode(expression)); + public TypeResult CompileType(Expression expression) + { + if ( + CompileNode(expression) + .When(out var typeObject) + .Error(out var error) + ) + return TypeResult.Error(error); + + if (typeObject is IType type) + return TypeResult.Ok(type); + + return CompilationError( + "Dynamic type evaluation is not implemented yet", expression + ); + } + + public Result CompilationError( + string error, + Node node + ) + where T : class + => Result.Error(new CompilationError(node, error)); + + public ObjectResult CompilationError( + string error, + Node node + ) + => CompilationError(error, node); } } diff --git a/ZSharp.ZSSourceCompiler/context/Context.Compilers.cs b/ZSharp.ZSSourceCompiler/context/Context.Compilers.cs index b94cfcc4..04158474 100644 --- a/ZSharp.ZSSourceCompiler/context/Context.Compilers.cs +++ b/ZSharp.ZSSourceCompiler/context/Context.Compilers.cs @@ -1,52 +1,20 @@ using CommonZ.Utils; -using System.Diagnostics.CodeAnalysis; namespace ZSharp.ZSSourceCompiler { public sealed partial class Context { - private readonly Stack compilerStack = []; + private CompilerBase currentCompiler; - public CompilerBase CurrentCompiler => compilerStack.Peek(); + public CompilerBase CurrentCompiler => currentCompiler; - public CompilerBase? ParentCompiler(int level = 0) - => compilerStack.ElementAtOrDefault(level + 1); - - public T? ParentCompiler(int level = 0) - where T : class - => ParentCompiler(level) as T; - - public bool ParentCompiler([NotNullWhen(true)] out T? parent, int level = 0) - where T : class - => (parent = ParentCompiler(level)) is not null; - - public T? Compiler() - where T : class - { - foreach (var compiler in compilerStack) - if (compiler is T t) - return t; - - return null; - } - - public bool Compiler([NotNullWhen(true)] out T? compiler) - where T : class - => (compiler = Compiler()) is not null; - - public IEnumerable Compilers() - where T : class - { - foreach (var compiler in compilerStack) - if (compiler is T t) - yield return t; - } + public DefaultContextCompiler DefaultCompiler { get; } public ContextManager Compiler(CompilerBase compiler) { - compilerStack.Push(compiler); + (currentCompiler, compiler) = (compiler, currentCompiler); - return new(() => compilerStack.Pop()); + return new(() => currentCompiler = compiler); } } } diff --git a/ZSharp.ZSSourceCompiler/context/Context.Nodes.cs b/ZSharp.ZSSourceCompiler/context/Context.Nodes.cs index ade5361a..490f0e5d 100644 --- a/ZSharp.ZSSourceCompiler/context/Context.Nodes.cs +++ b/ZSharp.ZSSourceCompiler/context/Context.Nodes.cs @@ -6,8 +6,6 @@ public sealed partial class Context { private readonly Mapping nodes = []; - public Node CurrentNode => Compiler()?.ContextNode ?? throw new InvalidOperationException(); - public Node? Node(CompilerObject @object) => nodes.GetValueOrDefault(@object); diff --git a/ZSharp.ZSSourceCompiler/context/Context.cs b/ZSharp.ZSSourceCompiler/context/Context.cs index 9088a533..a322a408 100644 --- a/ZSharp.ZSSourceCompiler/context/Context.cs +++ b/ZSharp.ZSSourceCompiler/context/Context.cs @@ -11,7 +11,7 @@ public Context(ZSSourceCompiler compiler, ScopeContext? globalScope = null) GlobalScope = globalScope ?? new(); compiler.Compiler.UseContext(CurrentScope = GlobalScope); - compilerStack.Push(new DefaultContextCompiler(compiler)); + currentCompiler = DefaultCompiler = new DefaultContextCompiler(compiler); } } } diff --git a/ZSharp.ZSSourceCompiler/core-compilers/DefaultContextCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/DefaultContextCompiler.cs index 3ec07544..807bc4cb 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/DefaultContextCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/DefaultContextCompiler.cs @@ -2,21 +2,14 @@ namespace ZSharp.ZSSourceCompiler { public sealed class DefaultContextCompiler(ZSSourceCompiler compiler) - : ContextCompiler(compiler) + : CompilerBase(compiler) , IOverrideCompileExpression , IOverrideCompileStatement { - public override Node ContextNode => throw new InvalidOperationException(); - - public override CompilerObject ContextObject => throw new InvalidOperationException(); - - public CompilerObject? CompileNode(ZSSourceCompiler compiler, Expression node) + public ObjectResult CompileNode(ZSSourceCompiler compiler, Expression node) => compiler.ExpressionCompiler.CompileNode(node); - public CompilerObject? CompileNode(ZSSourceCompiler compiler, Statement node) + public ObjectResult CompileNode(ZSSourceCompiler compiler, Statement node) => compiler.StatementCompiler.CompileNode(node); - - public override CompilerObject CompileNode() - => throw new InvalidOperationException(); } } diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.Literals.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.Literals.cs index a7c35785..1aca22a2 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.Literals.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.Literals.cs @@ -2,10 +2,22 @@ { public sealed partial class ExpressionCompiler { - public Objects.ArrayLiteral Compile(ArrayLiteral array) - => new(array.Items.Select(Compiler.CompileNode)); + public ObjectResult Compile(ArrayLiteral array) + { + Objects.ArrayLiteral result = new(); - public CompilerObject Compile(LiteralExpression literal) + ObjectResult objectResult; + foreach (var item in array.Items) + if ( + (objectResult = Compiler.CompileNode(item)).IsError + ) + return objectResult; + else result.Items.Add(objectResult.Unwrap()); + + return ObjectResult.Ok(result); + } + + public ObjectResult Compile(LiteralExpression literal) => literal.Type switch { LiteralType.String => Compiler.Compiler.CreateString(literal.Value), @@ -13,7 +25,10 @@ public CompilerObject Compile(LiteralExpression literal) LiteralType.True => Compiler.Compiler.CreateTrue(), LiteralType.Null => Compiler.Compiler.CreateNull(), LiteralType.Number => Compiler.Compiler.CreateInteger(int.Parse(literal.Value)), - _ => throw new($"Could not find suitable compiler for node of type {typeof(LiteralExpression).Name}"), // TODO: proper exception: unknown literal type - }; + _ => null + } is CompilerObject result + ? ObjectResult.Ok(result) + : Compiler.CompilationError($"Could not compile literal of type {literal.Type}", literal) + ; } } diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs index e69baed0..2c32e17b 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs @@ -5,7 +5,7 @@ namespace ZSharp.ZSSourceCompiler public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) : CompilerBase(compiler) { - public CompilerObject? CompileNode(Expression expression) + public ObjectResult? CompileNode(Expression expression) => expression switch { ArrayLiteral array => Compile(array), @@ -20,11 +20,11 @@ public sealed partial class ExpressionCompiler(ZSSourceCompiler compiler) _ => null }; - private CompilerObject Compile(BinaryExpression binary) + private ObjectResult Compile(BinaryExpression binary) { // TODO: NO SPECIAL TREATMENT FOR OPERATORS . and = - var left = Compiler.CompileNode(binary.Left); + var left = Compiler.CompileNode(binary.Left).Unwrap(); if (binary.Operator == ".") { @@ -34,43 +34,47 @@ private CompilerObject Compile(BinaryExpression binary) member = Compiler.Compiler.CreateString(identifier.Name); else if (binary.Right is not LiteralExpression literal) - throw new("Expected a literal expression on the right side of the dot operator."); + return Compiler.CompilationError("Expected a literal expression on the right side of the dot operator.", binary.Right); - else member = Compile(literal); + else member = Compile(literal).Unwrap(); if (Compiler.Compiler.IsString(member, out var memberName)) - return Compiler.Compiler.Member(left, memberName); + return ObjectResult.Ok(Compiler.Compiler.CG.Member(left, memberName).Unwrap()); if (Compiler.Compiler.IsLiteral(member, out var memberIndex)) - return Compiler.Compiler.Member(left, memberIndex.Value); + return ObjectResult.Ok(Compiler.Compiler.Member(left, memberIndex.Value)); - Compiler.LogError("Expected a string or an integer literal on the right side of the dot operator.", binary.Right); + return Compiler.CompilationError("Expected a string or an integer literal on the right side of the dot operator.", binary.Right); } - var right = Compiler.CompileNode(binary.Right); + var right = Compiler.CompileNode(binary.Right).Unwrap(); if (binary.Operator == "=") - return Compiler.Compiler.Assign(left, right); + return ObjectResult.Ok(Compiler.Compiler.CG.Set(left, right).Unwrap()); if (!Compiler.Operators.Binary.Cache(binary.Operator, out var @operator)) - Compiler.LogError($"Operator '{binary.Operator}' is not defined.", binary); + return Compiler.CompilationError($"Operator '{binary.Operator}' is not defined.", binary); - return Compiler.Compiler.Call(@operator, [new(left), new(right)]); + return ObjectResult.Ok( + Compiler.Compiler.CG.Call(@operator, [new(left), new(right)]).Unwrap() + ); } - private CompilerObject Compile(CallExpression call) + private ObjectResult Compile(CallExpression call) { - var callable = Compiler.Compiler.Evaluate(Compiler.CompileNode(call.Callee)); + var callable = Compiler.Compiler.Evaluate(Compiler.CompileNode(call.Callee).Unwrap()); - var args = call.Arguments.Select(arg => new Compiler.Argument(arg.Name, Compiler.CompileNode(arg.Value))); + var args = call.Arguments.Select(arg => new Argument_NEW(arg.Name, Compiler.CompileNode(arg.Value).Unwrap())); - return Compiler.Compiler.Call(callable, args.ToArray()); + return ObjectResult.Ok( + Compiler.Compiler.CG.Call(callable, args.ToArray()).Unwrap() + ); } - private CompilerObject Compile(CastExpression cast) + private ObjectResult Compile(CastExpression cast) { - var expression = Compiler.CompileNode(cast.Expression); + var expression = Compiler.CompileNode(cast.Expression).Unwrap(); - var targetType = Compiler.CompileType(cast.TargetType); + var targetType = Compiler.CompileType(cast.TargetType).Unwrap(); if (targetType is not Objects.Nullable) { @@ -79,38 +83,29 @@ private CompilerObject Compile(CastExpression cast) targetType = new Objects.Nullable(targetType); } - var castResult = Compiler.Compiler.CG.Cast(expression, targetType); - - TypeCast typeCast; - - if (castResult.Error(out var error)) - { - Compiler.LogError(error, cast); - - return Compiler.Compiler.CreateNull(); - } - else typeCast = castResult.Unwrap(); - - var castCodeResult = Compiler.Compiler.IR.CompileCode(typeCast.Cast); - - IRCode castCode; - - if (castCodeResult.Error(out error)) - { - Compiler.LogError(error, cast); + if ( + Compiler.Compiler.CG.Cast(expression, targetType) + .When(out var typeCast) + .Error(out var error) + ) + return Compiler.CompilationError(error, cast); - return Compiler.Compiler.CreateNull(); - } else castCode = castCodeResult.Unwrap(); + if ( + Compiler.Compiler.IR.CompileCode(typeCast!.Cast) + .When(out var castCode) + .Error(out error) + ) + return Compiler.CompilationError(error, cast); if (typeCast.CanFail) - castCode.Instructions.Add(typeCast.OnFail); + castCode!.Instructions.Add(typeCast.OnFail); - castCode.Types[0] = (targetType as Objects.Nullable)!.UnderlyingType; + castCode!.Types[0] = (targetType as Objects.Nullable)!.UnderlyingType; - return new Objects.RawCode(castCode); // TODO: add OnCast and OnFail handlers + return ObjectResult.Ok(new Objects.RawCode(castCode)); } - private CompilerObject Compile(IdentifierExpression identifier) + private ObjectResult Compile(IdentifierExpression identifier) { CompilerObject? result = null; @@ -121,45 +116,42 @@ private CompilerObject Compile(IdentifierExpression identifier) } ); - if (result is not null) return result; + if (result is not null) return ObjectResult.Ok(result); - Compiler.LogError($"Could not resolve name {identifier.Name}", identifier); - return Compiler.Compiler.CreateString($""); // TODO: return an object that knows it doesn't exist. + return Compiler.CompilationError($"Could not resolve name {identifier.Name}", identifier); } - private CompilerObject Compile(IndexExpression index) + private ObjectResult Compile(IndexExpression index) { - var indexable = Compiler.Compiler.Evaluate(Compiler.CompileNode(index.Target)); + var indexable = Compiler.Compiler.Evaluate(Compiler.CompileNode(index.Target).Unwrap()); - var args = index.Arguments.Select(arg => new Compiler.Argument(arg.Name, Compiler.CompileNode(arg.Value))); + var args = index.Arguments.Select(arg => new Argument_NEW(arg.Name, Compiler.CompileNode(arg.Value).Unwrap())); - return Compiler.Compiler.Map(indexable, @object => Compiler.Compiler.Index(@object, [.. args])); + return ObjectResult.Ok(Compiler.Compiler.Map(indexable, @object => Compiler.Compiler.CG.Index(@object, [.. args]).Unwrap())); } - private CompilerObject Compile(IsOfExpression isOf) + private ObjectResult Compile(IsOfExpression isOf) { - var value = Compiler.CompileNode(isOf.Expression); - var type = Compiler.CompileType(isOf.OfType); - - if (!Compiler.UnpackResult( - Compiler.Compiler.CG.TypeMatch(value, type), - out var match, - isOf - ) + var value = Compiler.CompileNode(isOf.Expression).Unwrap(); + var type = Compiler.CompileType(isOf.OfType).Unwrap(); + + if ( + Compiler.Compiler.CG.TypeMatch(value, type) + .When(out var match) + .Error(out var error) ) - return Compiler.Compiler.CreateFalse(); + return Compiler.CompilationError(error, isOf); - if (!Compiler.UnpackResult( - Compiler.Compiler.IR.CompileCode(match.Match), - out var matchCode, - isOf - ) + if ( + Compiler.Compiler.IR.CompileCode(match!.Match) + .When(out var matchCode) + .Error(out error) ) - return Compiler.Compiler.CreateFalse(); + return Compiler.CompilationError(error, isOf); IR.VM.Nop noMatch = new(); - matchCode.Instructions.AddRange([ + matchCode!.Instructions.AddRange([ new IR.VM.Pop(), new IR.VM.PutFalse(), new IR.VM.Jump(noMatch), @@ -169,11 +161,7 @@ private CompilerObject Compile(IsOfExpression isOf) { var allocator = Compiler.Compiler.CurrentContext.FindContext(); if (allocator is null) - { - Compiler.LogError($"Could not find memory allocator in context chain", isOf); - - return Compiler.Compiler.CreateFalse(); - } + return Compiler.CompilationError($"Could not find memory allocator in context chain", isOf); var local = allocator.Allocate( isOf.Name, @@ -203,12 +191,12 @@ private CompilerObject Compile(IsOfExpression isOf) matchCode.Types.Clear(); matchCode.Types.Add(Compiler.Compiler.TypeSystem.Boolean); - return new Objects.RawCode(matchCode); + return ObjectResult.Ok(new Objects.RawCode(matchCode)); } - private WhileLoop Compile(WhileExpression @while) + private ObjectResult Compile(WhileExpression @while) { - return new WhileExpressionCompiler(Compiler, @while, null!).Compile(); + return ObjectResult.Ok(new WhileExpressionCompiler(Compiler, @while, null!).Compile()); } } } diff --git a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs index d3e57976..7465fbb4 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs +++ b/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs @@ -1,9 +1,11 @@ -namespace ZSharp.ZSSourceCompiler +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler { public sealed class StatementCompiler(ZSSourceCompiler compiler) : CompilerBase(compiler) { - public CompilerObject? CompileNode(Statement statement) + public ObjectResult? CompileNode(Statement statement) => statement switch { BlockStatement block => Compile(block), @@ -15,112 +17,226 @@ public sealed class StatementCompiler(ZSSourceCompiler compiler) _ => null }; - private CompilerObject Compile(Expression expression) + private ObjectResult Compile(Expression expression) => expression switch { WhileExpression @while => Compile(@while), _ => Compiler.CompileNode(expression) }; - private CompilerObject Compile(BlockStatement block) + private ObjectResult Compile(BlockStatement block) { - var result = new Compiler.IRCode(); + var code = new Compiler.IRCode(); + + var coResults = block.Statements + .Select(Compiler.CompileNode) + .ToArray(); + + if (CombineErrorResults(coResults, out var coErrors)) + return ObjectResult.Error(coErrors); + + var irResults = coResults + .Select(coResult => coResult.Unwrap()) + .Select(Compiler.Compiler.IR.CompileCode) + .Select(irResult => + irResult.Else(error => new CompilationError(null!, error) as Error) + ) + .ToArray(); - foreach (var statement in block.Statements) - result.Append(Compiler.Compiler.CompileIRCode(Compiler.CompileNode(statement))); + if (CombineErrorResults(irResults, out var irErrors)) + return ObjectResult.Error(irErrors); - result.RequireVoidType(); + foreach (var ir in irResults.Select(irResult => irResult.Unwrap())) + code.Append(ir); - return new Objects.RawCode(result); + if (!code.IsVoid) + return Compiler.CompilationError( + $"Block must not have a value", block + ); + + return ObjectResult.Ok(new Objects.RawCode(code)); } - private CompilerObject Compile(ExpressionStatement expressionStatement) + private ObjectResult Compile(ExpressionStatement expressionStatement) { if (expressionStatement.Expression is null) - return new Objects.RawCode(new()); - - var result = Compiler.Compiler.CompileIRCode(Compile(expressionStatement.Expression)); - - if (result.IsValue) + return ObjectResult.Ok(new Objects.RawCode(new())); + + var coResult = Compiler.CompileNode(expressionStatement.Expression); + + if ( + coResult + .When(out var co) + .IsError + ) + return coResult; + + var irResult = Compiler.Compiler.IR.CompileCode(co!); + + if ( + irResult + .When(out var ir) + .Error(out var irError) + ) + return Compiler.CompilationError( + irError, expressionStatement.Expression + ); + + if (ir!.IsArray) + return Compiler.CompilationError( + "Expression evaluated to more than 1 values", + expressionStatement.Expression + ); + + if (ir.IsValue) { - result.Instructions.Add(new IR.VM.Pop()); - result.Types.RemoveAt(result.Types.Count - 1); + ir.Instructions.Add(new IR.VM.Pop()); + ir.Types.Clear(); } - result.RequireVoidType(); - - return new Objects.RawCode(result); + return ObjectResult.Ok(new Objects.RawCode(ir)); } - private CompilerObject Compile(CaseStatement @case) + private ObjectResult Compile(CaseStatement @case) { - var result = new Objects.Case() - { - Of = @case.Of is null ? Compiler.Operators.Binary.Cache("==")! : Compiler.CompileNode(@case.Of), - Value = @case.Value is null ? Compiler.Compiler.CreateTrue() : Compiler.CompileNode(@case.Value), - Else = @case.Else is null ? null : Compiler.CompileNode(@case.Else), - }; + var ofResult = @case.Of is null + ? ObjectResult.Ok(Compiler.Operators.Binary.Cache("==") ?? throw new()) + : Compiler.CompileNode(@case.Of); - foreach (var whenClause in @case.WhenClauses) - { - var clause = new Objects.Case.When() - { - Body = Compiler.CompileNode(whenClause.Body ?? throw new()), - Value = Compiler.CompileNode(whenClause.Value) - }; + var valueResult = @case.Value is null + ? ObjectResult.Ok(Compiler.Compiler.CreateTrue()) + : Compiler.CompileNode(@case.Value); - result.Clauses.Add(clause); - } + var elseResult = @case.Else is null + ? ObjectResult.Ok(new Objects.RawCode(new())) + : Compiler.CompileNode(@case.Else); - return result; + var clausesResults = @case.WhenClauses + .Select(clause => + { + var bodyResult = Compiler.CompileNode(clause.Body ?? throw new()); + var valueResult = Compiler.CompileNode(clause.Value); + + if (CombineErrorResults([bodyResult, valueResult], out var error)) + return Result.Error(error); + + return Result.Ok(new() + { + Body = bodyResult.Unwrap(), + Value = valueResult.Unwrap(), + }); + }).ToArray(); + + if (CombineErrorResults([ + ofResult, + valueResult, + .. clausesResults.Select(r => r.When(v => v as CompilerObject)) + ], out var error)) + return ObjectResult.Error(error); + + return ObjectResult.Ok(new Objects.Case() + { + Of = ofResult.Unwrap(), + Value = valueResult.Unwrap(), + Else = elseResult.Unwrap(), + Clauses = [.. clausesResults.Select(r => r.Unwrap())], + }); } - private ForLoop Compile(ForStatement @for) - => new ForStatementCompiler(Compiler, @for).Compile(); + private ObjectResult Compile(ForStatement @for) + => ObjectResult.Ok(new ForStatementCompiler(Compiler, @for).Compile()); - private CompilerObject Compile(IfStatement @if) + private ObjectResult Compile(IfStatement @if) { - var result = new Objects.If() + var conditionResult = Compiler.CompileNode(@if.Condition); + var bodyResult = Compiler.CompileNode(@if.If); + var elseResult = @if.Else is null + ? ObjectResult.Ok(new Objects.RawCode(new())) + : Compiler.CompileNode(@if.Else); + + if (CombineErrorResults([ + conditionResult, + bodyResult, + elseResult, + ], out var error)) + return ObjectResult.Error(error); + + return ObjectResult.Ok(new Objects.If() { - Condition = Compiler.CompileNode(@if.Condition), - Body = Compiler.CompileNode(@if.If), - Else = @if.Else is null ? null : Compiler.CompileNode(@if.Else) - }; - - return result; + Condition = conditionResult.Unwrap(), + Body = bodyResult.Unwrap(), + Else = elseResult.Unwrap() + }); } - private CompilerObject Compile(ImportStatement import) + private ObjectResult Compile(ImportStatement import) { - if (import.Arguments is not null) - Compiler.LogError($"Import arguments are not supported yet.", import); + IEnumerable arguments = [ + new CallArgument() { + Value = import.Source + }, + .. import.Arguments ?? [] + ]; + + var argumentsResults = arguments + .Select(arg => + { + if ( + Compiler.CompileNode(arg.Value) + .When(out var value) + .Error(out var error) + ) + return Result, Error>.Error(error); - var source = Compiler.CompileNode(import.Source); + return Result, Error>.Ok( + new(arg.Name, value!) + ); + }) + .ToArray(); + + if (CombineErrorResults(argumentsResults, out var argumentErrors)) + return ObjectResult.Error(argumentErrors); - var result = Compiler.Compiler.Call( + var importResult = Compiler.Compiler.CG.Call( Compiler.ImportSystem.ImportFunction, - [ - new(source), - .. (import.Arguments ?? []).Select( - arg => new Compiler.Argument(arg.Name, Compiler.CompileNode(arg.Value)) - ) - ] + [.. argumentsResults.Select(r => r.Unwrap())] ); + if (importResult.When(out var result).Error(out var error)) + return Compiler.CompilationError(error, import); + + if (import.Alias is not null) + Context.CurrentScope.Set(import.Alias, result!); + if (import.ImportedNames is not null) - foreach (var importedName in import.ImportedNames) + { + var memberResults = import.ImportedNames + .Select(name => (name, Compiler.Compiler.CG.Member(result!, name.Name))) + .Select(vs => + { + var (name, r) = vs; + + return (name, result: r.Else(e => new CompilationError(name, e) as Error)); + }) + .ToArray(); + + if (CombineErrorResults( + memberResults.Select(t => t.result), + out var memberErrors + )) + return ObjectResult.Error(memberErrors); + + foreach (var (name, memberResult) in memberResults) Context.CurrentScope.Set( - importedName.Alias ?? importedName.Name, - Compiler.Compiler.Member(result, importedName.Name) + name.Alias ?? name.Name, + memberResult.Unwrap() ); + } - if (import.Alias is not null) - Context.CurrentScope.Set(import.Alias, result); - - return result; + return ObjectResult.Ok(result!); } - private WhileLoop Compile(WhileExpression @while) - => new WhileStatementCompiler(Compiler, @while).Compile(); + private ObjectResult Compile(WhileExpression @while) + => ObjectResult.Ok(new WhileStatementCompiler(Compiler, @while).Compile()); } } diff --git a/ZSharp.ZSSourceCompiler/extensibility/ContextCompiler.cs b/ZSharp.ZSSourceCompiler/extensibility/ContextCompiler.cs index 76dbde85..8db78163 100644 --- a/ZSharp.ZSSourceCompiler/extensibility/ContextCompiler.cs +++ b/ZSharp.ZSSourceCompiler/extensibility/ContextCompiler.cs @@ -3,8 +3,6 @@ public abstract class ContextCompiler(ZSSourceCompiler compiler) : CompilerBase(compiler) { - public abstract Node ContextNode { get; } - public abstract CompilerObject ContextObject { get; } public abstract CompilerObject CompileNode(); @@ -15,8 +13,6 @@ public abstract class ContextCompiler where TNode : Node where TObject : CompilerObject { - public override Node ContextNode => Node; - public override CompilerObject ContextObject => Object; public TNode Node { get; } diff --git a/ZSharp.ZSSourceCompiler/extensibility/overrides/IOverrideCompileNode.cs b/ZSharp.ZSSourceCompiler/extensibility/overrides/IOverrideCompileNode.cs index 0502a1ff..51dfbe5a 100644 --- a/ZSharp.ZSSourceCompiler/extensibility/overrides/IOverrideCompileNode.cs +++ b/ZSharp.ZSSourceCompiler/extensibility/overrides/IOverrideCompileNode.cs @@ -3,6 +3,6 @@ public interface IOverrideCompileNode where T : Node { - public CompilerObject? CompileNode(ZSSourceCompiler compiler, T node); + public ObjectResult? CompileNode(ZSSourceCompiler compiler, T node); } } From 7c83c43c7ade5239dae5e6c18643bee50f70b931 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 8 Jun 2025 23:10:53 +0300 Subject: [PATCH 171/235] Resultify the core compiler code base --- .../core/concepts/member/ISetMember_Old.cs | 7 ++ .../cg/capabilities/callable/Argument.cs | 16 ++++ .../cg/capabilities/callable/ICTCallable.cs | 8 ++ .../cg/capabilities/callable/IRTCallable.cs | 8 ++ .../implicit casting/ICTImplicitCastFrom.cs | 8 ++ .../implicit casting/ICTImplicitCastTo.cs | 8 ++ .../implicit casting/IRTImplicitCastTo.cs | 8 ++ .../cg/capabilities/index/ICTGetIndex.cs | 8 ++ .../cg/capabilities/index/ICTSetIndex.cs | 8 ++ .../cg/capabilities/index/IRTGetIndex.cs | 8 ++ .../cg/capabilities/index/IRTSetIndex.cs | 8 ++ .../member access/ICTGetMember.cs | 7 ++ .../member access/ICTSetMember.cs | 7 ++ .../member access/IRTGetMember.cs | 7 ++ .../member access/IRTSetMember.cs | 7 ++ .../runtime/IHasRuntimeDescriptor.cs | 8 ++ .../cg/capabilities/type casting/ICTCastTo.cs | 8 ++ .../capabilities/type casting/IRTCastFrom.cs | 8 ++ .../cg/capabilities/type casting/IRTCastTo.cs | 8 ++ .../type matching/ICTTypeMatch.cs | 8 ++ .../type matching/IRTTypeMatch.cs | 8 ++ .../capabilities/type matching/TypeMatch.cs | 9 ++ .../capabilities/value access/get/ICTGet.cs | 8 ++ .../capabilities/value access/get/IRTGet.cs | 8 ++ .../capabilities/value access/set/ICTSet.cs | 8 ++ .../capabilities/value access/set/IRTSet.cs | 8 ++ .../cg/capabilities/wrapper/IObjectWrapper.cs | 8 ++ .../features/cg/services/CG.Call.cs | 24 ++++++ .../features/cg/services/CG.ImplicitCast.cs | 27 ++++++ .../features/cg/services/CG.Index.cs | 46 ++++++++++ .../features/cg/services/CG.MemberAccess.cs | 83 +++++++++++++++++++ .../features/cg/services/CG.Runtime.cs | 15 ++++ .../features/cg/services/CG.TypeCast.cs | 40 +++++++++ .../features/cg/services/CG.TypeMatch.cs | 27 ++++++ .../features/cg/services/CG.ValueAccess.cs | 43 ++++++++++ 35 files changed, 525 insertions(+) create mode 100644 ZSharp.Compiler/core/concepts/member/ISetMember_Old.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/callable/Argument.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/callable/IRTCallable.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastFrom.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastTo.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/implicit casting/IRTImplicitCastTo.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/index/ICTGetIndex.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/index/ICTSetIndex.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/index/IRTGetIndex.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/index/IRTSetIndex.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/member access/ICTGetMember.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/member access/ICTSetMember.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/member access/IRTGetMember.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/member access/IRTSetMember.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/runtime/IHasRuntimeDescriptor.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/type casting/ICTCastTo.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastFrom.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastTo.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/type matching/ICTTypeMatch.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/type matching/IRTTypeMatch.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/type matching/TypeMatch.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/value access/get/ICTGet.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/value access/get/IRTGet.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/value access/set/ICTSet.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/value access/set/IRTSet.cs create mode 100644 ZSharp.Compiler/features/cg/capabilities/wrapper/IObjectWrapper.cs create mode 100644 ZSharp.Compiler/features/cg/services/CG.Call.cs create mode 100644 ZSharp.Compiler/features/cg/services/CG.ImplicitCast.cs create mode 100644 ZSharp.Compiler/features/cg/services/CG.Index.cs create mode 100644 ZSharp.Compiler/features/cg/services/CG.MemberAccess.cs create mode 100644 ZSharp.Compiler/features/cg/services/CG.Runtime.cs create mode 100644 ZSharp.Compiler/features/cg/services/CG.TypeCast.cs create mode 100644 ZSharp.Compiler/features/cg/services/CG.TypeMatch.cs create mode 100644 ZSharp.Compiler/features/cg/services/CG.ValueAccess.cs diff --git a/ZSharp.Compiler/core/concepts/member/ISetMember_Old.cs b/ZSharp.Compiler/core/concepts/member/ISetMember_Old.cs new file mode 100644 index 00000000..82c428ef --- /dev/null +++ b/ZSharp.Compiler/core/concepts/member/ISetMember_Old.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + internal interface ISetMember_Old + { + public CompilerObject Member(T @object, M member, CompilerObject value); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/callable/Argument.cs b/ZSharp.Compiler/features/cg/capabilities/callable/Argument.cs new file mode 100644 index 00000000..425cb39f --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/callable/Argument.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Compiler +{ + public class Argument_NEW(T value) + where T : CompilerObject + { + public T Value { get; set; } = value; + + public string? Name { get; set; } + + public Argument_NEW(string? name, T value) + : this(value) + { + Name = name; + } + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs b/ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs new file mode 100644 index 00000000..d858e689 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICTCallable_NEW + : CompilerObject + { + public CompilerObjectResult Call(Compiler compiler, Argument_NEW[] arguments); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/callable/IRTCallable.cs b/ZSharp.Compiler/features/cg/capabilities/callable/IRTCallable.cs new file mode 100644 index 00000000..df568091 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/callable/IRTCallable.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTCallable_NEW + : CompilerObject + { + public CompilerObjectResult Call(Compiler compiler, CompilerObject @object, Argument_NEW[] arguments); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastFrom.cs b/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastFrom.cs new file mode 100644 index 00000000..1054afcc --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastFrom.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICTImplicitCastFrom + : CompilerObject + { + public CompilerObjectResult ImplicitCast(Compiler compiler, CompilerObject value); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastTo.cs b/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastTo.cs new file mode 100644 index 00000000..aea16516 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastTo.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICTImplicitCastTo + : CompilerObject + { + public CompilerObjectResult ImplicitCast(Compiler compiler, IType type); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/implicit casting/IRTImplicitCastTo.cs b/ZSharp.Compiler/features/cg/capabilities/implicit casting/IRTImplicitCastTo.cs new file mode 100644 index 00000000..d2e47871 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/implicit casting/IRTImplicitCastTo.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTImplicitCastTo + : CompilerObject + { + public CompilerObjectResult ImplicitCast(Compiler compiler, CompilerObject @object, IType type); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/index/ICTGetIndex.cs b/ZSharp.Compiler/features/cg/capabilities/index/ICTGetIndex.cs new file mode 100644 index 00000000..a89af7ad --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/index/ICTGetIndex.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICTGetIndex_NEW + : CompilerObject + { + public CompilerObjectResult Index(Compiler compiler, Argument_NEW[] arguments); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/index/ICTSetIndex.cs b/ZSharp.Compiler/features/cg/capabilities/index/ICTSetIndex.cs new file mode 100644 index 00000000..fcd75a27 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/index/ICTSetIndex.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICTSetIndex_NEW + : CompilerObject + { + public CompilerObjectResult Index(Compiler compiler, Argument_NEW[] arguments, CompilerObject value); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/index/IRTGetIndex.cs b/ZSharp.Compiler/features/cg/capabilities/index/IRTGetIndex.cs new file mode 100644 index 00000000..afcfbf6e --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/index/IRTGetIndex.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTGetIndex_NEW + : CompilerObject + { + public CompilerObjectResult Index(Compiler compiler, CompilerObject @object, Argument_NEW[] arguments); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/index/IRTSetIndex.cs b/ZSharp.Compiler/features/cg/capabilities/index/IRTSetIndex.cs new file mode 100644 index 00000000..b323f14d --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/index/IRTSetIndex.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTSetIndex_NEW + : CompilerObject + { + public CompilerObjectResult Index(Compiler compiler, CompilerObject @object, Argument_NEW[] arguments, CompilerObject value); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/member access/ICTGetMember.cs b/ZSharp.Compiler/features/cg/capabilities/member access/ICTGetMember.cs new file mode 100644 index 00000000..6407e250 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/member access/ICTGetMember.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTGetMember + { + public CompilerObjectResult Member(Compiler compiler, M member); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/member access/ICTSetMember.cs b/ZSharp.Compiler/features/cg/capabilities/member access/ICTSetMember.cs new file mode 100644 index 00000000..4a391697 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/member access/ICTSetMember.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTSetMember + { + public CompilerObjectResult Member(Compiler compiler, M member, CompilerObject value); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/member access/IRTGetMember.cs b/ZSharp.Compiler/features/cg/capabilities/member access/IRTGetMember.cs new file mode 100644 index 00000000..0ebf140d --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/member access/IRTGetMember.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTGetMember + { + public CompilerObjectResult Member(Compiler compiler, CompilerObject @object, M member); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/member access/IRTSetMember.cs b/ZSharp.Compiler/features/cg/capabilities/member access/IRTSetMember.cs new file mode 100644 index 00000000..b7b5fe94 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/member access/IRTSetMember.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTSetMember + { + public CompilerObjectResult Member(Compiler compiler, CompilerObject @object, M member, CompilerObject value); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/runtime/IHasRuntimeDescriptor.cs b/ZSharp.Compiler/features/cg/capabilities/runtime/IHasRuntimeDescriptor.cs new file mode 100644 index 00000000..d2bce635 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/runtime/IHasRuntimeDescriptor.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IHasRuntimeDescriptor + : CompilerObject + { + public CompilerObject GetRuntimeDescriptor(Compiler compiler); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/type casting/ICTCastTo.cs b/ZSharp.Compiler/features/cg/capabilities/type casting/ICTCastTo.cs new file mode 100644 index 00000000..68ff4b8e --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/type casting/ICTCastTo.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICTCastTo + : CompilerObject + { + public Result Cast(Compiler compiler, IType targetType); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastFrom.cs b/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastFrom.cs new file mode 100644 index 00000000..0d6f2142 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastFrom.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTCastFrom + : CompilerObject + { + public Result Cast(Compiler compiler, CompilerObject value); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastTo.cs b/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastTo.cs new file mode 100644 index 00000000..50386228 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastTo.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTCastTo + : CompilerObject + { + public Result Cast(Compiler compiler, CompilerObject value, IType targetType); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/type matching/ICTTypeMatch.cs b/ZSharp.Compiler/features/cg/capabilities/type matching/ICTTypeMatch.cs new file mode 100644 index 00000000..f44ee43b --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/type matching/ICTTypeMatch.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICTTypeMatch + : CompilerObject + { + public Result Match(Compiler compiler, IType type); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/type matching/IRTTypeMatch.cs b/ZSharp.Compiler/features/cg/capabilities/type matching/IRTTypeMatch.cs new file mode 100644 index 00000000..b3e3b89e --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/type matching/IRTTypeMatch.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTTypeMatch + : CompilerObject + { + public Result Match(Compiler compiler, CompilerObject value, IType type); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/type matching/TypeMatch.cs b/ZSharp.Compiler/features/cg/capabilities/type matching/TypeMatch.cs new file mode 100644 index 00000000..6c46d7c9 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/type matching/TypeMatch.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public sealed class TypeMatch + { + public required CompilerObject Match { get; set; } + + public ZSharp.IR.VM.Instruction OnMatch { get; init; } = new ZSharp.IR.VM.Nop(); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/value access/get/ICTGet.cs b/ZSharp.Compiler/features/cg/capabilities/value access/get/ICTGet.cs new file mode 100644 index 00000000..8357c152 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/value access/get/ICTGet.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICTGet + : CompilerObject + { + public CompilerObjectResult Get(Compiler compiler); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/value access/get/IRTGet.cs b/ZSharp.Compiler/features/cg/capabilities/value access/get/IRTGet.cs new file mode 100644 index 00000000..932b8f78 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/value access/get/IRTGet.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTGet + : CompilerObject + { + public CompilerObjectResult Get(Compiler compiler, CompilerObject @object); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/value access/set/ICTSet.cs b/ZSharp.Compiler/features/cg/capabilities/value access/set/ICTSet.cs new file mode 100644 index 00000000..0cdd250f --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/value access/set/ICTSet.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICTSet + : CompilerObject + { + public CompilerObjectResult Set(Compiler compiler, CompilerObject value); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/value access/set/IRTSet.cs b/ZSharp.Compiler/features/cg/capabilities/value access/set/IRTSet.cs new file mode 100644 index 00000000..604facf6 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/value access/set/IRTSet.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IRTSet + : CompilerObject + { + public CompilerObjectResult Set(Compiler compiler, CompilerObject @object, CompilerObject value); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/wrapper/IObjectWrapper.cs b/ZSharp.Compiler/features/cg/capabilities/wrapper/IObjectWrapper.cs new file mode 100644 index 00000000..02a7b8c8 --- /dev/null +++ b/ZSharp.Compiler/features/cg/capabilities/wrapper/IObjectWrapper.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IObjectWrapper + : CompilerObject + { + public T MapWrapped(Compiler compiler, Func fn); + } +} diff --git a/ZSharp.Compiler/features/cg/services/CG.Call.cs b/ZSharp.Compiler/features/cg/services/CG.Call.cs new file mode 100644 index 00000000..d5f209d6 --- /dev/null +++ b/ZSharp.Compiler/features/cg/services/CG.Call.cs @@ -0,0 +1,24 @@ +namespace ZSharp.Compiler +{ + public partial struct CG + { + public CompilerObjectResult Call(CompilerObject @object, Argument_NEW[] arguments) + { + var result = CompilerObjectResult.Error("Object does not support calling"); + + if (@object is ICTCallable_NEW ctCallable) + result = ctCallable.Call(compiler, arguments); + + if (result.IsOk) return result; + + if (RuntimeDescriptor(@object, out var runtimeDescriptor) + && runtimeDescriptor is IRTCallable_NEW rtCallable + ) + result = rtCallable.Call(compiler, @object, arguments); + + if (result.IsOk) return result; + + return result; + } + } +} diff --git a/ZSharp.Compiler/features/cg/services/CG.ImplicitCast.cs b/ZSharp.Compiler/features/cg/services/CG.ImplicitCast.cs new file mode 100644 index 00000000..c5faa684 --- /dev/null +++ b/ZSharp.Compiler/features/cg/services/CG.ImplicitCast.cs @@ -0,0 +1,27 @@ +namespace ZSharp.Compiler +{ + public partial struct CG + { + public CompilerObjectResult ImplicitCast(CompilerObject @object, IType type) + { + var result = CompilerObjectResult.Error("Object does not support implicit cast"); + + if (@object is ICTImplicitCastTo ctCastTo) + result = ctCastTo.ImplicitCast(compiler, type); + + if (result.IsOk) return result; + + if (RuntimeDescriptor(@object, out var runtimeDescriptor) + && runtimeDescriptor is IRTImplicitCastTo rtCastTo + ) + result = rtCastTo.ImplicitCast(compiler, @object, type); + + if (result.IsOk) return result; + + if (type is ICTImplicitCastFrom ctCastFrom) + result = ctCastFrom.ImplicitCast(compiler, @object); + + return result; + } + } +} diff --git a/ZSharp.Compiler/features/cg/services/CG.Index.cs b/ZSharp.Compiler/features/cg/services/CG.Index.cs new file mode 100644 index 00000000..1f2d5851 --- /dev/null +++ b/ZSharp.Compiler/features/cg/services/CG.Index.cs @@ -0,0 +1,46 @@ +namespace ZSharp.Compiler +{ + public partial struct CG + { + public CompilerObjectResult Index(CompilerObject @object, Argument_NEW[] arguments) + { + var result = CompilerObjectResult.Error("Object does not support get index"); + + if (@object is ICTGetIndex_NEW ctGet) + result = ctGet.Index(compiler, arguments); + + if (result.IsOk) return result; + + if (RuntimeDescriptor(@object, out var runtimeDescriptor) + && runtimeDescriptor is IRTGetIndex_NEW rtGet + ) + result = rtGet.Index(compiler, @object, arguments); + + if (result.IsOk) return result; + + if (@object is IObjectWrapper wrapper && This(out var cg)) // TODO: this is in testing + result = wrapper.MapWrapped(compiler, wrapped => cg.Index(wrapped, arguments)); + + return result; + } + + public CompilerObjectResult Index(CompilerObject @object, Argument_NEW[] arguments, CompilerObject value) + { + var result = CompilerObjectResult.Error("Object does not support set index"); + + if (@object is ICTSetIndex_NEW ctGet) + result = ctGet.Index(compiler, arguments, value); + + if (result.IsOk) return result; + + if (RuntimeDescriptor(@object, out var runtimeDescriptor) + && runtimeDescriptor is IRTSetIndex_NEW rtGet + ) + result = rtGet.Index(compiler, @object, arguments, value); + + if (result.IsOk) return result; + + return result; + } + } +} diff --git a/ZSharp.Compiler/features/cg/services/CG.MemberAccess.cs b/ZSharp.Compiler/features/cg/services/CG.MemberAccess.cs new file mode 100644 index 00000000..920b4b04 --- /dev/null +++ b/ZSharp.Compiler/features/cg/services/CG.MemberAccess.cs @@ -0,0 +1,83 @@ +namespace ZSharp.Compiler +{ + public partial struct CG + { + public CompilerObjectResult Member(CompilerObject @object, M member) + { + var result = CompilerObjectResult.Error($"Object does not support get member by {typeof(M).Name}"); + + if (@object is ICTGetMember ctGet) + result = ctGet.Member(compiler, member); + + if (result.IsOk) return result; + + if ( + RuntimeDescriptor(@object, out var runtimeDescritpr) + && runtimeDescritpr is IRTGetMember rtGet + ) + result = rtGet.Member(compiler, @object, member); + + if (result.IsOk) return result; + + return result; + } + + public CompilerObjectResult Member(CompilerObject @object, M member, CompilerObject value) + { + var result = CompilerObjectResult.Error($"Object does not support set member by {typeof(M).Name}"); + + if (@object is ICTSetMember ctGet) + result = ctGet.Member(compiler, member, value); + + if (result.IsOk) return result; + + if ( + RuntimeDescriptor(@object, out var runtimeDescritpr) + && runtimeDescritpr is IRTSetMember rtGet + ) + result = rtGet.Member(compiler, @object, member, value); + + if (result.IsOk) return result; + + return result; + } + + /// + /// The get member (.) operator. + /// + /// + /// + /// + public CompilerObjectResult Member(CompilerObject @object, MemberIndex index) + => Member(@object, index); + + /// + /// The set member (.=) operator. + /// + /// + /// + /// + /// + public CompilerObjectResult Member(CompilerObject @object, MemberIndex index, CompilerObject value) + => Member(@object, index, value); + + /// + /// The member (.) operator. + /// + /// + /// + /// + public CompilerObjectResult Member(CompilerObject @object, MemberName name) + => Member(@object, name); + + /// + /// The set member (.=) operator. + /// + /// + /// + /// + /// + public CompilerObjectResult Member(CompilerObject @object, MemberName name, CompilerObject value) + => Member(@object, name, value); + } +} diff --git a/ZSharp.Compiler/features/cg/services/CG.Runtime.cs b/ZSharp.Compiler/features/cg/services/CG.Runtime.cs new file mode 100644 index 00000000..8ac8882a --- /dev/null +++ b/ZSharp.Compiler/features/cg/services/CG.Runtime.cs @@ -0,0 +1,15 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler +{ + public partial struct CG + { + public CompilerObject? RuntimeDescriptor(CompilerObject @object) + => @object is IHasRuntimeDescriptor hasRuntimeDescriptor + ? hasRuntimeDescriptor.GetRuntimeDescriptor(compiler) + : null; + + public bool RuntimeDescriptor(CompilerObject @object, [NotNullWhen(true)] out CompilerObject? rt) + => (rt = RuntimeDescriptor(@object)) is not null; + } +} diff --git a/ZSharp.Compiler/features/cg/services/CG.TypeCast.cs b/ZSharp.Compiler/features/cg/services/CG.TypeCast.cs new file mode 100644 index 00000000..c99a7477 --- /dev/null +++ b/ZSharp.Compiler/features/cg/services/CG.TypeCast.cs @@ -0,0 +1,40 @@ +namespace ZSharp.Compiler +{ + public partial struct CG + { + public Result Cast(CompilerObject @object, IType type) + { + var result = Result.Error( + "Object cannot be cast" + ); + + if (@object is ICTCastTo ctCastTo) + result = ctCastTo.Cast(compiler, type); + + if (result.IsOk) return result; + + if ( + RuntimeDescriptor(@object, out var runtimeDescriptor) + && runtimeDescriptor is IRTCastTo rtCastTo + ) + result = rtCastTo.Cast(compiler, @object, type); + + if (result.IsOk) return result; + + if (type is IRTCastFrom rtCastFrom) + result = rtCastFrom.Cast(compiler, @object); + + if (result.IsOk) return result; + + if (compiler.TypeSystem.IsTyped(@object, out var objectType) && + compiler.TypeSystem.AreEqual(type, objectType) + ) + result = Result.Ok(new() + { + Cast = @object, + }); // TODO: this is actually invalid because calling code expects OnCast to be called on cast + + return result; + } + } +} diff --git a/ZSharp.Compiler/features/cg/services/CG.TypeMatch.cs b/ZSharp.Compiler/features/cg/services/CG.TypeMatch.cs new file mode 100644 index 00000000..d237fc98 --- /dev/null +++ b/ZSharp.Compiler/features/cg/services/CG.TypeMatch.cs @@ -0,0 +1,27 @@ +namespace ZSharp.Compiler +{ + public partial struct CG + { + public Result TypeMatch(CompilerObject @object, IType type) + { + var result = Result.Error( + "Object cannot be type matched" + ); + + if (@object is ICTTypeMatch ctTypeMatch) + result = ctTypeMatch.Match(compiler, type); + + if (result.IsOk) return result; + + if ( + RuntimeDescriptor(@object, out var runtimeDescriptor) + && runtimeDescriptor is IRTTypeMatch rtTypeMatch + ) + result = rtTypeMatch.Match(compiler, @object, type); + + if (result.IsOk) return result; + + return result; + } + } +} diff --git a/ZSharp.Compiler/features/cg/services/CG.ValueAccess.cs b/ZSharp.Compiler/features/cg/services/CG.ValueAccess.cs new file mode 100644 index 00000000..3b63f816 --- /dev/null +++ b/ZSharp.Compiler/features/cg/services/CG.ValueAccess.cs @@ -0,0 +1,43 @@ +namespace ZSharp.Compiler +{ + public partial struct CG + { + public CompilerObjectResult Get(CompilerObject @object) + { + var result = CompilerObjectResult.Error("Object does not support get"); + + if (@object is ICTGet ctGet) + result = ctGet.Get(compiler); + + if (result.IsOk) return result; + + if (RuntimeDescriptor(@object, out var runtimeDescriptor) + && runtimeDescriptor is IRTGet rtGet + ) + result = rtGet.Get(compiler, @object); + + if (result.IsOk) return result; + + return result; + } + + public CompilerObjectResult Set(CompilerObject @object, CompilerObject value) + { + var result = CompilerObjectResult.Error("Object does not support set"); + + if (@object is ICTSet ctSet) + result = ctSet.Set(compiler, value); + + if (result.IsOk) return result; + + if (RuntimeDescriptor(@object, out var runtimeDescriptor) + && runtimeDescriptor is IRTSet rtSet + ) + result = rtSet.Set(compiler, @object, value); + + if (result.IsOk) return result; + + return result; + } + } +} From ee6d431e955f6fadf9232f379ef044fd027811f1 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 8 Jun 2025 23:11:18 +0300 Subject: [PATCH 172/235] Add missing file to source compiler --- ZSharp.ZSSourceCompiler/HelperFunctions.cs | 31 +++++++++++++++++++ .../contexts/concrete/ObjectContext.cs | 13 ++++++++ .../extensibility/error/Error.cs | 7 +++++ .../error/errors/CombinedCompilationError.cs | 9 ++++++ .../error/errors/CompilationError.cs | 12 +++++++ 5 files changed, 72 insertions(+) create mode 100644 ZSharp.ZSSourceCompiler/HelperFunctions.cs create mode 100644 ZSharp.ZSSourceCompiler/contexts/concrete/ObjectContext.cs create mode 100644 ZSharp.ZSSourceCompiler/extensibility/error/Error.cs create mode 100644 ZSharp.ZSSourceCompiler/extensibility/error/errors/CombinedCompilationError.cs create mode 100644 ZSharp.ZSSourceCompiler/extensibility/error/errors/CompilationError.cs diff --git a/ZSharp.ZSSourceCompiler/HelperFunctions.cs b/ZSharp.ZSSourceCompiler/HelperFunctions.cs new file mode 100644 index 00000000..d1ea5c7e --- /dev/null +++ b/ZSharp.ZSSourceCompiler/HelperFunctions.cs @@ -0,0 +1,31 @@ +using System.Diagnostics.CodeAnalysis; +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler +{ + internal static class HelperFunctions + { + public static bool CombineErrorResults( + IEnumerable> results, + [NotNullWhen(true)] out CombinedCompilationError? error + ) + where T : class + { + var errors = + results + .Where(r => r.IsError) + .Select(r => r.Error(out var e) ? e : throw new()) + .SelectMany(e => e switch + { + CompilationError compilationError => [compilationError], + CombinedCompilationError combined => combined.Errors, + _ => throw new("Unknown error type: " + e.GetType().Name) + }) + .ToArray(); + + error = errors.Length > 0 ? new(errors) : null; + + return errors.Length > 0; + } + } +} diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/ObjectContext.cs b/ZSharp.ZSSourceCompiler/contexts/concrete/ObjectContext.cs new file mode 100644 index 00000000..bb2f4cc4 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/contexts/concrete/ObjectContext.cs @@ -0,0 +1,13 @@ +using ZSharp.Compiler; + +namespace ZSharp.ZSSourceCompiler +{ + public class ObjectContext(T @object) + : IObjectContext + where T : CompilerObject + { + public IContext? Parent { get; set; } + + public T Object { get; } = @object; + } +} diff --git a/ZSharp.ZSSourceCompiler/extensibility/error/Error.cs b/ZSharp.ZSSourceCompiler/extensibility/error/Error.cs new file mode 100644 index 00000000..62f87cdb --- /dev/null +++ b/ZSharp.ZSSourceCompiler/extensibility/error/Error.cs @@ -0,0 +1,7 @@ +namespace ZSharp.ZSSourceCompiler +{ + public abstract class Error + { + + } +} diff --git a/ZSharp.ZSSourceCompiler/extensibility/error/errors/CombinedCompilationError.cs b/ZSharp.ZSSourceCompiler/extensibility/error/errors/CombinedCompilationError.cs new file mode 100644 index 00000000..491c3760 --- /dev/null +++ b/ZSharp.ZSSourceCompiler/extensibility/error/errors/CombinedCompilationError.cs @@ -0,0 +1,9 @@ +namespace ZSharp.ZSSourceCompiler +{ + public sealed class CombinedCompilationError( + params CompilationError[] errors + ) : Error + { + public List Errors { get; } = [.. errors]; + } +} diff --git a/ZSharp.ZSSourceCompiler/extensibility/error/errors/CompilationError.cs b/ZSharp.ZSSourceCompiler/extensibility/error/errors/CompilationError.cs new file mode 100644 index 00000000..d6ad14aa --- /dev/null +++ b/ZSharp.ZSSourceCompiler/extensibility/error/errors/CompilationError.cs @@ -0,0 +1,12 @@ +namespace ZSharp.ZSSourceCompiler +{ + public sealed class CompilationError( + Node node, + string error + ) : Error + { + public Node Node { get; } = node; + + public string Error { get; } = error; + } +} From ecbf68dae048cfacfa5446386e1603a4f0cd4b81 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 8 Jun 2025 23:11:53 +0300 Subject: [PATCH 173/235] Organize the IR -> IL loader --- .../attributes/KeywordParameterAttribute.cs | 7 ++ .../code contexts/FunctionCodeContext.cs | 74 +++++++++++++++++ .../ir2il/code contexts/UnboundCodeContext.cs | 23 ++++++ ZSharp.Runtime.IL/ir2il/code/CodeCompiler.cs | 70 ++++++++++++++++ .../code/branching/BranchingCodeCompiler.cs | 24 ++++++ .../code/branching/IBranchingCodeContext.cs | 10 +++ .../ir2il/code/core/CodeStack.cs | 22 +++++ .../ir2il/code/core/ICodeContext.cs | 11 +++ .../ir2il/code/frame/FrameCodeCompiler.cs | 73 +++++++++++++++++ .../ir2il/code/frame/IFrameCodeContext.cs | 10 +++ ZSharp.Runtime.IL/ir2il/code/frame/Local.cs | 11 +++ .../ir2il/code/frame/Parameter.cs | 11 +++ .../code/functional/FunctionalCodeCompiler.cs | 34 ++++++++ .../code/functional/IFunctionalCodeContext.cs | 8 ++ .../ir2il/code/modular/ModularCodeCompiler.cs | 25 ++++++ .../ir2il/code/object/OOPCodeCompiler.cs | 59 +++++++++++++ .../ir2il/code/stack/StackCodeCompiler.cs | 82 +++++++++++++++++++ 17 files changed, 554 insertions(+) create mode 100644 ZSharp.Runtime.IL/il2ir/attributes/KeywordParameterAttribute.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code contexts/FunctionCodeContext.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code contexts/UnboundCodeContext.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/CodeCompiler.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/branching/BranchingCodeCompiler.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/branching/IBranchingCodeContext.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/core/CodeStack.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/core/ICodeContext.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/frame/FrameCodeCompiler.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/frame/IFrameCodeContext.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/frame/Local.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/frame/Parameter.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/functional/FunctionalCodeCompiler.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/functional/IFunctionalCodeContext.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/modular/ModularCodeCompiler.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/object/OOPCodeCompiler.cs create mode 100644 ZSharp.Runtime.IL/ir2il/code/stack/StackCodeCompiler.cs diff --git a/ZSharp.Runtime.IL/il2ir/attributes/KeywordParameterAttribute.cs b/ZSharp.Runtime.IL/il2ir/attributes/KeywordParameterAttribute.cs new file mode 100644 index 00000000..0d098bf0 --- /dev/null +++ b/ZSharp.Runtime.IL/il2ir/attributes/KeywordParameterAttribute.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime.NET.IL2IR +{ + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] + public sealed class KeywordParameterAttribute : Attribute + { + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code contexts/FunctionCodeContext.cs b/ZSharp.Runtime.IL/ir2il/code contexts/FunctionCodeContext.cs new file mode 100644 index 00000000..8ee7b601 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code contexts/FunctionCodeContext.cs @@ -0,0 +1,74 @@ +using CommonZ.Utils; +using ZSharp.IR; + +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + internal sealed class FunctionCodeContext(IRLoader loader, IL.Emit.ILGenerator il, Function function) + : ICodeContext + , IBranchingCodeContext + , IFrameCodeContext + , IFunctionalCodeContext + { + private readonly Mapping locals = []; + private readonly Mapping parameters = []; + private readonly Mapping labels = []; + + public IL.Emit.ILGenerator IL { get; } = il; + + public CodeStack Stack { get; } = new(); + + public IRLoader Loader { get; } = loader; + + public Function Function { get; } = function; + + void IBranchingCodeContext.AddBranchTarget(IR.VM.Instruction target) + => labels[target] = IL.DefineLabel(); + + IL.Emit.Label IBranchingCodeContext.GetBranchTarget(IR.VM.Instruction target) + => labels[target]; + + Local IFrameCodeContext.GetLocal(IR.VM.Local local) + => locals[local]; + + Parameter IFrameCodeContext.GetParameter(IR.Parameter parameter) + => parameters[parameter]; + + private void SetupFromIR() + { + foreach (var parameter in Function.Signature.GetParameters()) + parameters[parameter] = new() + { + Index = parameter.Index, + Name = parameter.Name, + Type = Loader.LoadType(parameter.Type) + }; + + if (Function.HasBody && Function.Body.HasLocals) + foreach (var local in Function.Body.Locals) + locals[local] = new() + { + Index = local.Index, + Name = local.Name, + Type = Loader.LoadType(local.Type) + }; + } + + public static FunctionCodeContext From(IRLoader loader, IL.Emit.ConstructorBuilder constructor, Function function) + { + var context = new FunctionCodeContext(loader, constructor.GetILGenerator(), function); + + context.SetupFromIR(); + + return context; + } + + public static FunctionCodeContext From(IRLoader loader, IL.Emit.MethodBuilder method, Function function) + { + var context = new FunctionCodeContext(loader, method.GetILGenerator(), function); + + context.SetupFromIR(); + + return context; + } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code contexts/UnboundCodeContext.cs b/ZSharp.Runtime.IL/ir2il/code contexts/UnboundCodeContext.cs new file mode 100644 index 00000000..272f2c85 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code contexts/UnboundCodeContext.cs @@ -0,0 +1,23 @@ +using CommonZ.Utils; + +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + internal sealed class UnboundCodeContext(IRLoader loader, IL.Emit.ILGenerator il) + : ICodeContext + , IBranchingCodeContext + { + private readonly Mapping labels = []; + + public IL.Emit.ILGenerator IL { get; } = il; + + public CodeStack Stack { get; } = new(); + + public IRLoader Loader { get; } = loader; + + void IBranchingCodeContext.AddBranchTarget(IR.VM.Instruction target) + => labels[target] = IL.DefineLabel(); + + IL.Emit.Label IBranchingCodeContext.GetBranchTarget(IR.VM.Instruction target) + => labels[target]; + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/CodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/CodeCompiler.cs new file mode 100644 index 00000000..d76f0907 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/CodeCompiler.cs @@ -0,0 +1,70 @@ +using CommonZ.Utils; + +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + public sealed class CodeCompiler(ICodeContext context) + { + public ICodeContext Context { get; } = context; + + public void CompileCode(Collection instructions) + { + if (Context is IBranchingCodeContext branchingContext) + { + foreach (var instruction in instructions) + branchingContext.AddBranchTarget(instruction); + + foreach (var instruction in instructions) + { + Context.IL.MarkLabel(branchingContext.GetBranchTarget(instruction)); + + Compile(instruction); + } + } else + foreach (var instruction in instructions) + Compile(instruction); + } + + private void Compile(IR.VM.Instruction instruction) + { + switch (instruction) + { + case IR.VM.Call call: CodeCompiler_Impl.Compile(RequireContext(), call); break; + case IR.VM.CallIndirect callIndirect: CodeCompiler_Impl.Compile(RequireContext(), callIndirect); break; + case IR.VM.CallVirtual callVirtual: CodeCompiler_Impl.Compile(RequireContext(), callVirtual); break; + case IR.VM.CastReference castReference: CodeCompiler_Impl.Compile(RequireContext(), castReference); break; + case IR.VM.CreateInstance createInstance: CodeCompiler_Impl.Compile(RequireContext(), createInstance); break; + case IR.VM.Dup dup: CodeCompiler_Impl.Compile(RequireContext(), dup); break; + case IR.VM.GetArgument getArgument: CodeCompiler_Impl.Compile(RequireContext(), getArgument); break; + //case IR.VM.GetClass getClass: CodeCompiler_Impl.Compile(RequireContext(), getClass); break; + case IR.VM.GetField getField: CodeCompiler_Impl.Compile(RequireContext(), getField); break; + case IR.VM.GetGlobal getGlobal: CodeCompiler_Impl.Compile(RequireContext(), getGlobal); break; + case IR.VM.GetLocal getLocal: CodeCompiler_Impl.Compile(RequireContext(), getLocal); break; + //case IR.VM.GetObject getObject: CodeCompiler_Impl.Compile(RequireContext(), getObject); break; + case IR.VM.IsNotNull isNotNull: CodeCompiler_Impl.Compile(RequireContext(), isNotNull); break; + case IR.VM.IsNull isNull: CodeCompiler_Impl.Compile(RequireContext(), isNull); break; + case IR.VM.Jump jump: CodeCompiler_Impl.Compile(RequireContext(), jump); break; + case IR.VM.JumpIfTrue jumpIfTrue: CodeCompiler_Impl.Compile(RequireContext(), jumpIfTrue); break; + case IR.VM.JumpIfFalse jumpIfFalse: CodeCompiler_Impl.Compile(RequireContext(), jumpIfFalse); break; + case IR.VM.Nop nop: CodeCompiler_Impl.Compile(RequireContext(), nop); break; + case IR.VM.Pop pop: CodeCompiler_Impl.Compile(RequireContext(), pop); break; + case IR.VM.PutBoolean putBoolean: CodeCompiler_Impl.Compile(RequireContext(), putBoolean); break; + case IR.VM.PutFloat32 putFloat32: CodeCompiler_Impl.Compile(RequireContext(), putFloat32); break; + case IR.VM.PutInt32 putInt32: CodeCompiler_Impl.Compile(RequireContext(), putInt32); break; + case IR.VM.PutNull putNull: CodeCompiler_Impl.Compile(RequireContext(), putNull); break; + case IR.VM.PutString putString: CodeCompiler_Impl.Compile(RequireContext(), putString); break; + case IR.VM.Return @return: CodeCompiler_Impl.Compile(RequireContext(), @return); break; + case IR.VM.SetArgument setArgument: CodeCompiler_Impl.Compile(RequireContext(), setArgument); break; + case IR.VM.SetField setField: CodeCompiler_Impl.Compile(RequireContext(), setField); break; + case IR.VM.SetGlobal setGlobal: CodeCompiler_Impl.Compile(RequireContext(), setGlobal); break; + case IR.VM.SetLocal setLocal: CodeCompiler_Impl.Compile(RequireContext(), setLocal); break; + case IR.VM.Swap swap: CodeCompiler_Impl.Compile(RequireContext(), swap); break; + + default: throw new NotImplementedException(); + } + } + + private T RequireContext() + where T : ICodeContext + => Context is T required ? required : throw new InvalidOperationException(); + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/branching/BranchingCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/branching/BranchingCodeCompiler.cs new file mode 100644 index 00000000..fa6d7497 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/branching/BranchingCodeCompiler.cs @@ -0,0 +1,24 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(IBranchingCodeContext ctx, IR.VM.Jump jump) + { + ctx.IL.Emit(IL.Emit.OpCodes.Br, ctx.GetBranchTarget(jump.Target)); + } + + public static void Compile(IBranchingCodeContext ctx, IR.VM.JumpIfTrue jump) + { + ctx.IL.Emit(IL.Emit.OpCodes.Brtrue, ctx.GetBranchTarget(jump.Target)); + + ctx.Stack.Pop(typeof(bool)); + } + + public static void Compile(IBranchingCodeContext ctx, IR.VM.JumpIfFalse jump) + { + ctx.IL.Emit(IL.Emit.OpCodes.Brfalse, ctx.GetBranchTarget(jump.Target)); + + ctx.Stack.Pop(typeof(bool)); + } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/branching/IBranchingCodeContext.cs b/ZSharp.Runtime.IL/ir2il/code/branching/IBranchingCodeContext.cs new file mode 100644 index 00000000..d24e8d48 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/branching/IBranchingCodeContext.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + public interface IBranchingCodeContext + : ICodeContext + { + public void AddBranchTarget(IR.VM.Instruction target); + + public IL.Emit.Label GetBranchTarget(IR.VM.Instruction target); + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/core/CodeStack.cs b/ZSharp.Runtime.IL/ir2il/code/core/CodeStack.cs new file mode 100644 index 00000000..f2c2aff4 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/core/CodeStack.cs @@ -0,0 +1,22 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + public sealed class CodeStack + { + private readonly Stack ilStack = []; + + public void Dup() + => ilStack.Push(ilStack.Peek()); + + public void Put(Type type) + => ilStack.Push(type); + + public Type Pop() => ilStack.Pop(); + + public Type Pop(Type expect) + { + var result = Pop(); + if (result != expect) throw new(); + return result; + } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/core/ICodeContext.cs b/ZSharp.Runtime.IL/ir2il/code/core/ICodeContext.cs new file mode 100644 index 00000000..2aaebf0d --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/core/ICodeContext.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + public interface ICodeContext + { + public IL::Emit.ILGenerator IL { get; } + + public CodeStack Stack { get; } + + public IRLoader Loader { get; } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/frame/FrameCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/frame/FrameCodeCompiler.cs new file mode 100644 index 00000000..5496b36e --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/frame/FrameCodeCompiler.cs @@ -0,0 +1,73 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(IFrameCodeContext ctx, IR.VM.GetArgument get) + { + var parameter = ctx.GetParameter(get.Argument); + var index = parameter.Index; + + if (index == 0) + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_0); + else if (index == 1) + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_1); + else if (index == 2) + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_2); + else if (index == 3) + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_3); + else if (index <= byte.MaxValue) + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_S, (byte)index); + else + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg, index); + + ctx.Stack.Put(parameter.Type); + } + + public static void Compile(IFrameCodeContext ctx, IR.VM.GetLocal get) + { + var l = ctx.GetLocal(get.Local); + var index = l.Index; + + if (index == 0) + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_0); + else if (index == 1) + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_1); + else if (index == 2) + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_2); + else if (index == 3) + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_3); + else if (index <= byte.MaxValue) + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_S, (byte)index); + else + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc, index); + + ctx.Stack.Put(l.Type); + } + + public static void Compile(IFrameCodeContext ctx, IR.VM.SetArgument set) + { + var parameter = ctx.GetParameter(set.Argument); + var index = parameter.Index; + + if (index <= byte.MaxValue) + ctx.IL.Emit(IL.Emit.OpCodes.Starg_S, (byte)index); + else + ctx.IL.Emit(IL.Emit.OpCodes.Starg, index); + + ctx.Stack.Pop(parameter.Type); + } + + public static void Compile(IFrameCodeContext ctx, IR.VM.SetLocal set) + { + var local = ctx.GetLocal(set.Local); + var index = local.Index; + + if (index <= byte.MaxValue) + ctx.IL.Emit(IL.Emit.OpCodes.Stloc_S, (byte)index); + else + ctx.IL.Emit(IL.Emit.OpCodes.Stloc, index); + + ctx.Stack.Pop(local.Type); + } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/frame/IFrameCodeContext.cs b/ZSharp.Runtime.IL/ir2il/code/frame/IFrameCodeContext.cs new file mode 100644 index 00000000..5df96bdc --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/frame/IFrameCodeContext.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + public interface IFrameCodeContext + : ICodeContext + { + public Parameter GetParameter(IR.Parameter parameter); + + public Local GetLocal(IR.VM.Local local); + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/frame/Local.cs b/ZSharp.Runtime.IL/ir2il/code/frame/Local.cs new file mode 100644 index 00000000..0ed945e9 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/frame/Local.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + public sealed class Local + { + public required string Name { get; init; } + + public required int Index { get; init; } + + public required Type Type { get; init; } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/frame/Parameter.cs b/ZSharp.Runtime.IL/ir2il/code/frame/Parameter.cs new file mode 100644 index 00000000..286358c8 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/frame/Parameter.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + public sealed class Parameter + { + public required string Name { get; init; } + + public required int Index { get; init; } + + public required Type Type { get; init; } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/functional/FunctionalCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/functional/FunctionalCodeCompiler.cs new file mode 100644 index 00000000..5f016e91 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/functional/FunctionalCodeCompiler.cs @@ -0,0 +1,34 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(ICodeContext ctx, IR.VM.Call call) + { + var callable = ctx.Loader.LoadReference(call.Callable); + + foreach (var parameter in call.Callable.Signature.GetParameters()) + ctx.Stack.Pop(ctx.Loader.LoadType(parameter.Type)); + + if (callable is IL.MethodInfo method) + { + ctx.IL.Emit(IL.Emit.OpCodes.Call, method); + + if (method.ReturnType != typeof(void)) + ctx.Stack.Put(method.ReturnType); + } + else if (callable is IL.ConstructorInfo constructor) + ctx.IL.Emit(IL.Emit.OpCodes.Call, constructor); + else throw new($"Unknown callable type: {callable.GetType()}"); + } + + public static void Compile(ICodeContext ctx, IR.VM.CallIndirect call) + { + throw new NotImplementedException(); + } + + public static void Compile(ICodeContext ctx, IR.VM.Return _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ret); + } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/functional/IFunctionalCodeContext.cs b/ZSharp.Runtime.IL/ir2il/code/functional/IFunctionalCodeContext.cs new file mode 100644 index 00000000..4b6c65a5 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/functional/IFunctionalCodeContext.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + public interface IFunctionalCodeContext + : ICodeContext + { + public IR.Function Function { get; } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/modular/ModularCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/modular/ModularCodeCompiler.cs new file mode 100644 index 00000000..f8dfcab7 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/modular/ModularCodeCompiler.cs @@ -0,0 +1,25 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(ICodeContext ctx, IR.VM.GetGlobal get) + { + if (!ctx.Loader.Context.Cache(get.Global, out var global)) + throw new(); + + ctx.IL.Emit(IL.Emit.OpCodes.Ldsfld, global); + + ctx.Stack.Put(global.FieldType); + } + + public static void Compile(ICodeContext ctx, IR.VM.SetGlobal set) + { + if (!ctx.Loader.Context.Cache(set.Global, out var global)) + throw new(); + + ctx.IL.Emit(IL.Emit.OpCodes.Stsfld, global); + + ctx.Stack.Pop(global.FieldType); + } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/object/OOPCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/object/OOPCodeCompiler.cs new file mode 100644 index 00000000..4b2c44b1 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/object/OOPCodeCompiler.cs @@ -0,0 +1,59 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(ICodeContext ctx, IR.VM.CallVirtual callVirtual) + { + var method = ctx.Loader.LoadReference(callVirtual.Method); + + if (!method.IsVirtual && !method.IsAbstract) + throw new($"Method {method} is not virtual or abstract!"); + + ctx.IL.Emit(IL.Emit.OpCodes.Callvirt, method); + + if (method.ReturnType != typeof(void)) + ctx.Stack.Put(method.ReturnType); + } + + public static void Compile(ICodeContext ctx, IR.VM.CastReference castReference) + { + var targetType = ctx.Loader.LoadType(castReference.Type); + + ctx.IL.Emit(IL.Emit.OpCodes.Isinst, targetType); + + ctx.Stack.Pop(); + ctx.Stack.Put(targetType); + } + + public static void Compile(ICodeContext ctx, IR.VM.CreateInstance createInstance) + { + var constructor = ctx.Loader.LoadReference(createInstance.Constructor); + + ctx.IL.Emit(IL.Emit.OpCodes.Newobj, constructor); + + ctx.Stack.Put(constructor.DeclaringType ?? throw new()); + } + + public static void Compile(ICodeContext ctx, IR.VM.GetField get) + { + var field = ctx.Loader.LoadReference(get.Field); + + ctx.IL.Emit(field.IsStatic ? IL.Emit.OpCodes.Ldsfld : IL.Emit.OpCodes.Ldfld, field); + + if (!field.IsStatic) + ctx.Stack.Pop(field.DeclaringType ?? throw new()); + ctx.Stack.Put(field.FieldType); + } + + public static void Compile(ICodeContext ctx, IR.VM.SetField set) + { + var field = ctx.Loader.LoadReference(set.Field); + + ctx.IL.Emit(field.IsStatic ? IL.Emit.OpCodes.Stsfld : IL.Emit.OpCodes.Stfld, field); + + ctx.Stack.Pop(); + if (!field.IsStatic) + ctx.Stack.Pop(field.DeclaringType ?? throw new()); + } + } +} diff --git a/ZSharp.Runtime.IL/ir2il/code/stack/StackCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/stack/StackCodeCompiler.cs new file mode 100644 index 00000000..b9d382f2 --- /dev/null +++ b/ZSharp.Runtime.IL/ir2il/code/stack/StackCodeCompiler.cs @@ -0,0 +1,82 @@ +namespace ZSharp.Runtime.NET.IR2IL.Code +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(ICodeContext ctx, IR.VM.Dup _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Dup); + + ctx.Stack.Dup(); + } + + public static void Compile(ICodeContext ctx, IR.VM.IsNotNull _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldnull); + ctx.IL.Emit(IL.Emit.OpCodes.Cgt_Un); + + ctx.Stack.Pop(); + ctx.Stack.Put(typeof(bool)); + } + + public static void Compile(ICodeContext ctx, IR.VM.IsNull _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldnull); + ctx.IL.Emit(IL.Emit.OpCodes.Ceq); + + ctx.Stack.Pop(); + ctx.Stack.Put(typeof(bool)); + } + + public static void Compile(ICodeContext ctx, IR.VM.Nop _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Nop); + } + + public static void Compile(ICodeContext ctx, IR.VM.Pop _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Pop); + + ctx.Stack.Pop(); + } + + public static void Compile(ICodeContext ctx, IR.VM.PutBoolean put) + { + ctx.IL.Emit(put.Value ? IL.Emit.OpCodes.Ldc_I4_1 : IL.Emit.OpCodes.Ldc_I4_0); + + ctx.Stack.Put(typeof(bool)); + } + + public static void Compile(ICodeContext ctx, IR.VM.PutFloat32 put) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldc_R4, put.Value); + + ctx.Stack.Put(typeof(float)); + } + + public static void Compile(ICodeContext ctx, IR.VM.PutInt32 put) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldc_I4, put.Value); + + ctx.Stack.Put(typeof(int)); + } + + public static void Compile(ICodeContext ctx, IR.VM.PutNull _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldnull); + + ctx.Stack.Put(typeof(object)); + } + + public static void Compile(ICodeContext ctx, IR.VM.PutString put) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldstr, put.Value); + + ctx.Stack.Put(typeof(string)); + } + + public static void Compile(ICodeContext ctx, IR.VM.Swap _) + { + throw new NotImplementedException(); + } + } +} From 886ccdf811f09a9cb5b2aadeae13f23b7b31e950 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 8 Jun 2025 23:14:26 +0300 Subject: [PATCH 174/235] Add more things --- .../Directory.cs | 25 ++- ZSharp.CT.StandardLibrary.FileSystem/File.cs | 13 +- .../Global_Operators.cs | 19 +- .../ItemSpec.cs | 16 ++ ZSharp.CT.StandardLibrary.FileSystem/Path.cs | 36 ++-- .../PathSpec.cs | 10 + .../definition/GenericFunction.Generic.cs | 34 ++++ .../{ => definition}/GenericFunction.cs | 2 +- .../generic/GenericArgument.cs | 17 ++ .../generic/GenericParameter.cs | 3 + ZSharp.Compiler.Objects/modular/Module.cs | 2 +- ZSharp.Compiler.Objects/oop/class/Class.cs | 8 +- .../oop/class/GenericClass.cs | 6 +- .../oop/class/GenericClassInstance.cs | 4 +- .../oop/field/BoundField.cs | 8 +- .../oop/interface/Interface.cs | 8 +- .../signature/abstract/ISignature_NEW.cs | 7 + .../ICallableType.cs | 0 .../{abstract => abstract_old}/IParameter.cs | 0 .../{abstract => abstract_old}/ISignature.cs | 3 +- .../IVarParameter.cs | 0 ZSharp.Compiler/cg objects/types/Int32Type.cs | 2 +- .../compiler/Compiler.Evaluate.cs | 2 +- .../compiler/features/Compiler.Protocols.cs | 8 +- .../core/evaluation/DefaultEvaluator.cs | 6 +- .../core/evaluation/Evaluator.cs | 2 +- .../core/type system/IDynamicallyTyped.cs | 5 + ZSharp.Compiler/core/Result.cs | 24 +++ ZSharp.Compiler/core/code/IRCode.cs | 3 + .../core/concepts/callable/ICallable.cs | 16 +- .../core/concepts/index/ICTGetIndex.cs | 5 +- .../core/concepts/member/IGetMember.cs | 14 +- .../core/concepts/member/ISetMember.cs | 7 - .../concepts/value/assignment/IAssignable.cs | 10 +- ZSharp.Compiler/features/cg/CG.cs | 176 +----------------- .../features/cg/type casting/IRTCastFrom.cs | 8 - .../features/cg/type casting/IRTCastTo.cs | 8 - .../features/cg/type matching/ICTTypeMatch.cs | 8 - .../features/cg/type matching/IRTTypeMatch.cs | 8 - .../features/cg/type matching/TypeMatch.cs | 9 - ZSharp.Interpreter/ZSSourceEvaluator.cs | 18 +- ZSharp.Parser/lang/LangParser.Keywords.cs | 1 + ZSharp.Runtime.IL/IRCodeEvaluator.cs | 44 +++-- ZSharp.Runtime.IL/Runtime.cs | 7 +- .../il2ir/loaders/ClassLoader.cs | 10 +- .../il2ir/loaders/InterfaceLoader.cs | 5 +- .../ir2il/loader new/ClassLoader.cs | 55 +++--- 47 files changed, 315 insertions(+), 367 deletions(-) create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/ItemSpec.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/PathSpec.cs create mode 100644 ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs rename ZSharp.Compiler.Objects/functional/generic/{ => definition}/GenericFunction.cs (98%) create mode 100644 ZSharp.Compiler.Objects/generic/GenericArgument.cs create mode 100644 ZSharp.Compiler.Objects/signature/abstract/ISignature_NEW.cs rename ZSharp.Compiler.Objects/signature/{abstract => abstract_old}/ICallableType.cs (100%) rename ZSharp.Compiler.Objects/signature/{abstract => abstract_old}/IParameter.cs (100%) rename ZSharp.Compiler.Objects/signature/{abstract => abstract_old}/ISignature.cs (98%) rename ZSharp.Compiler.Objects/signature/{abstract => abstract_old}/IVarParameter.cs (100%) delete mode 100644 ZSharp.Compiler/core/concepts/member/ISetMember.cs delete mode 100644 ZSharp.Compiler/features/cg/type casting/IRTCastFrom.cs delete mode 100644 ZSharp.Compiler/features/cg/type casting/IRTCastTo.cs delete mode 100644 ZSharp.Compiler/features/cg/type matching/ICTTypeMatch.cs delete mode 100644 ZSharp.Compiler/features/cg/type matching/IRTTypeMatch.cs delete mode 100644 ZSharp.Compiler/features/cg/type matching/TypeMatch.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/Directory.cs b/ZSharp.CT.StandardLibrary.FileSystem/Directory.cs index ff5df999..778eb1dc 100644 --- a/ZSharp.CT.StandardLibrary.FileSystem/Directory.cs +++ b/ZSharp.CT.StandardLibrary.FileSystem/Directory.cs @@ -2,22 +2,27 @@ namespace Standard.FileSystem { - public sealed class Directory + public sealed class Directory(Path path) : ItemSpec(path) { - public Path path; - - internal Directory(Path path) - { - this.path = path; - } - - internal Directory(string path) + public Directory(string path) : this(new Path(path)) { } [Alias(Name = "sub")] - public Path SubPath(string name) + public ItemSpec SubPath(string name) => Global_Operators.SubPath(this, name); + [Alias(Name = "createDirectory")] + public Directory CreateDirectory(string name, [KeywordParameter] bool existsOk = false) + { + var path = this.path.SubPath(name).path; + + if (!System.IO.Directory.Exists(path.pathString)) + System.IO.Directory.CreateDirectory(path.pathString); + else if (!existsOk) throw new InvalidOperationException(); + + return new(path); + } + [Alias(Name = "cwd")] public static Directory CurrentWorkingDirectory() => new(System.IO.Directory.GetCurrentDirectory()); diff --git a/ZSharp.CT.StandardLibrary.FileSystem/File.cs b/ZSharp.CT.StandardLibrary.FileSystem/File.cs index cbf45093..95be8c66 100644 --- a/ZSharp.CT.StandardLibrary.FileSystem/File.cs +++ b/ZSharp.CT.StandardLibrary.FileSystem/File.cs @@ -2,20 +2,17 @@ namespace Standard.FileSystem { - public sealed class File + public sealed class File(Path path) : ItemSpec(path) { - internal Path path; - - internal File(Path path) - { - this.path = path; - } - internal File(string path) : this(new Path(path)) { } [Alias(Name = "toString")] public override string ToString() => $"File<{path}>"; + + [Alias(Name = "getContent")] + public string GetContent() + => System.IO.File.ReadAllText(path.pathString); } } diff --git a/ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs b/ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs index e3725592..91d4b681 100644 --- a/ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs +++ b/ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs @@ -6,11 +6,24 @@ namespace Standard.FileSystem public static class Global_Operators { [Alias(Name = "_/_")] - public static Path SubPath(Path path, string name) - => new(System.IO.Path.Combine(path.path, name)); + public static ItemSpec SubPath(Path path, string name) + { + var newPath = System.IO.Path.Combine(path.pathString, name); + + if (System.IO.Directory.Exists(newPath)) + return new Directory(newPath); + if (System.IO.File.Exists(newPath)) + return new File(newPath); + + return new PathSpec(newPath); + } [Alias(Name = "_/_")] - public static Path SubPath(Directory directory, string name) + public static ItemSpec SubPath(Directory directory, string name) => SubPath(directory.path, name); + + [Alias(Name = "_/_")] + public static ItemSpec SubPath(PathSpec pathSpec, string name) + => SubPath(pathSpec.path, name); } } diff --git a/ZSharp.CT.StandardLibrary.FileSystem/ItemSpec.cs b/ZSharp.CT.StandardLibrary.FileSystem/ItemSpec.cs new file mode 100644 index 00000000..e06ffa9f --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/ItemSpec.cs @@ -0,0 +1,16 @@ +using ZSharp.Runtime.NET.IL2IR; + +namespace Standard.FileSystem +{ + public abstract class ItemSpec(Path path) + { + public readonly Path path = path; + + public ItemSpec(string path) + : this(new Path(path)) { } + + [Alias(Name = "toString")] + public override string ToString() + => $"Path<{path}>"; + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/Path.cs b/ZSharp.CT.StandardLibrary.FileSystem/Path.cs index 9d07b7b4..a247b0ad 100644 --- a/ZSharp.CT.StandardLibrary.FileSystem/Path.cs +++ b/ZSharp.CT.StandardLibrary.FileSystem/Path.cs @@ -4,37 +4,37 @@ namespace Standard.FileSystem { public class Path { - internal string path; + internal string pathString; internal Path(string path) { - this.path = path; + this.pathString = path; } - [Alias(Name = "asDirectory")] - public Directory? AsDirectory() - { - if (System.IO.Directory.Exists(path)) - return new(path); + //[Alias(Name = "asDirectory")] + //public Directory? AsDirectory() + //{ + // if (System.IO.Directory.Exists(path)) + // return new(path); - return null; - } + // return null; + //} - [Alias(Name = "asFile")] - public File? AsFile() - { - if (System.IO.File.Exists(path)) - return new(path); + //[Alias(Name = "asFile")] + //public File? AsFile() + //{ + // if (System.IO.File.Exists(path)) + // return new(path); - return null; - } + // return null; + //} [Alias(Name = "sub")] - public Path SubPath(string name) + public ItemSpec SubPath(string name) => Global_Operators.SubPath(this, name); [Alias(Name = "toString")] public override string ToString() - => path; + => pathString; } } diff --git a/ZSharp.CT.StandardLibrary.FileSystem/PathSpec.cs b/ZSharp.CT.StandardLibrary.FileSystem/PathSpec.cs new file mode 100644 index 00000000..c3907dc5 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/PathSpec.cs @@ -0,0 +1,10 @@ +namespace Standard.FileSystem +{ + public class PathSpec(Path path) : ItemSpec(path) + { + public PathSpec(string path) + : this(new Path(path)) + { + } + } +} diff --git a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs new file mode 100644 index 00000000..f888fb05 --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs @@ -0,0 +1,34 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public partial class GenericFunction + { + public Result CreateGenericInstance(Compiler.Compiler compiler, IType[] arguments) + { + if (arguments.Length != GenericParameters.Count) + return Result.Error( + $"Invalid generic argument count: Expected {GenericParameters.Count}, got {arguments.Length}" + ); + + Mapping genericArguments = []; + foreach (var (parameter, argument) in GenericParameters.Zip(arguments)) + { + if (!parameter.Match(argument)) + return Result.Error( + $"Type {argument} cannot be assigned to generic parameter {parameter.Name}" + ); + + genericArguments[parameter] = argument; + } + + return Result.Ok( + new(this) + { + Context = new() + } + ); + } + } +} diff --git a/ZSharp.Compiler.Objects/functional/generic/GenericFunction.cs b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs similarity index 98% rename from ZSharp.Compiler.Objects/functional/generic/GenericFunction.cs rename to ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs index 3d7b6ecd..e48f6c3f 100644 --- a/ZSharp.Compiler.Objects/functional/generic/GenericFunction.cs +++ b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs @@ -3,7 +3,7 @@ namespace ZSharp.Objects { - public sealed class GenericFunction(string? name = null) + public sealed partial class GenericFunction(string? name = null) : CompilerObject , ICompileIRObject , ICTCallable diff --git a/ZSharp.Compiler.Objects/generic/GenericArgument.cs b/ZSharp.Compiler.Objects/generic/GenericArgument.cs new file mode 100644 index 00000000..64d86b48 --- /dev/null +++ b/ZSharp.Compiler.Objects/generic/GenericArgument.cs @@ -0,0 +1,17 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class GenericArgument(IType type) + { + public IType Type { get; set; } = type; + + public string? Name { get; set; } + + public GenericArgument(string name, IType type) + : this(type) + { + Name = name; + } + } +} diff --git a/ZSharp.Compiler.Objects/generic/GenericParameter.cs b/ZSharp.Compiler.Objects/generic/GenericParameter.cs index 672c90b3..c8b79c2c 100644 --- a/ZSharp.Compiler.Objects/generic/GenericParameter.cs +++ b/ZSharp.Compiler.Objects/generic/GenericParameter.cs @@ -17,5 +17,8 @@ public IR.GenericParameter CompileIRType(Compiler.Compiler compiler) IType IReferencable.CreateReference(Referencing @ref, ReferenceContext context) => context.CompileTimeValues.Cache(this, out var result) ? result : this; + + public bool Match(IType type) + => true; } } diff --git a/ZSharp.Compiler.Objects/modular/Module.cs b/ZSharp.Compiler.Objects/modular/Module.cs index 50166f1b..d7970cde 100644 --- a/ZSharp.Compiler.Objects/modular/Module.cs +++ b/ZSharp.Compiler.Objects/modular/Module.cs @@ -6,7 +6,7 @@ namespace ZSharp.Objects public sealed class Module(string name) : CompilerObject , ICompileIRObject - , ICTGetMember + , ICTGetMember_Old , ICTReadable { IType ITyped.Type => throw new NotImplementedException(); diff --git a/ZSharp.Compiler.Objects/oop/class/Class.cs b/ZSharp.Compiler.Objects/oop/class/Class.cs index 2f3d4c18..0988c617 100644 --- a/ZSharp.Compiler.Objects/oop/class/Class.cs +++ b/ZSharp.Compiler.Objects/oop/class/Class.cs @@ -11,8 +11,8 @@ public sealed class Class , ICompileIRType> , ICTCallable , IRTCastTo - , ICTGetMember - , IRTGetMember + , ICTGetMember_Old + , IRTGetMember_Old , IRTTypeMatch , IImplementsAbstraction , IType @@ -111,10 +111,10 @@ public bool IsDefined return IR; } - CompilerObject ICTGetMember.Member(Compiler.Compiler compiler, string member) + CompilerObject ICTGetMember_Old.Member(Compiler.Compiler compiler, string member) => Members[member]; - CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerObject instance, string member) + CompilerObject IRTGetMember_Old.Member(Compiler.Compiler compiler, CompilerObject instance, string member) { return compiler.Map(Members[member], @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, instance) : @object); } diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs index f0f451e3..a65edf7a 100644 --- a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs +++ b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs @@ -6,8 +6,8 @@ namespace ZSharp.Objects public class GenericClass : CompilerObject , ICTGetIndex - , ICTGetMember - , IRTGetMember + , ICTGetMember_Old + , IRTGetMember_Old , IReferencable , ICompileIRObject , IEvaluable @@ -134,7 +134,7 @@ CompilerObject IEvaluable.Evaluate(Compiler.Compiler compiler) }); } - CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerObject value, string member) + CompilerObject IRTGetMember_Old.Member(Compiler.Compiler compiler, CompilerObject value, string member) { if (GenericParameters.Count > 0) throw new InvalidOperationException(); diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs index c8271db5..e1b4cdb1 100644 --- a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs +++ b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs @@ -6,8 +6,8 @@ namespace ZSharp.Objects public sealed class GenericClassInstance : CompilerObject , IClass - , ICTGetMember - , IRTGetMember + , ICTGetMember_Old + , IRTGetMember_Old , ICTCallable , IReference , ICompileIRType diff --git a/ZSharp.Compiler.Objects/oop/field/BoundField.cs b/ZSharp.Compiler.Objects/oop/field/BoundField.cs index ceebe6ad..65d290e4 100644 --- a/ZSharp.Compiler.Objects/oop/field/BoundField.cs +++ b/ZSharp.Compiler.Objects/oop/field/BoundField.cs @@ -19,13 +19,15 @@ public CompilerObject Assign(Compiler.Compiler compiler, CompilerObject value) var valueCode = compiler.CompileIRCode(value); return new RawCode(new([ - ..valueCode.Instructions, - new IR.VM.Dup(), ..instanceCode.Instructions, - new IR.VM.Swap(), + new IR.VM.Dup(), + ..valueCode.Instructions, new IR.VM.SetField(new IR.FieldReference(Field.IR!) { OwningType = new IR.ClassReference(Field.IR!.Owner ?? throw new()) }), + new IR.VM.GetField(new IR.FieldReference(Field.IR!) { + OwningType = new IR.ClassReference(Field.IR!.Owner ?? throw new()) + }), ]) { MaxStackSize = Math.Max(Math.Max(instanceCode.MaxStackSize, valueCode.MaxStackSize), 2), diff --git a/ZSharp.Compiler.Objects/oop/interface/Interface.cs b/ZSharp.Compiler.Objects/oop/interface/Interface.cs index 1cb41ebc..0e7939d0 100644 --- a/ZSharp.Compiler.Objects/oop/interface/Interface.cs +++ b/ZSharp.Compiler.Objects/oop/interface/Interface.cs @@ -9,8 +9,8 @@ public sealed class Interface(string? name) , ICompileIRObject , ICompileIRReference> , ICompileIRType> - , ICTGetMember - , IRTGetMember + , ICTGetMember_Old + , IRTGetMember_Old , IType { #region Build State @@ -52,10 +52,10 @@ public bool IsDefined Collection IAbstraction.Specifications => Content; - CompilerObject ICTGetMember.Member(Compiler.Compiler compiler, string member) + CompilerObject ICTGetMember_Old.Member(Compiler.Compiler compiler, string member) => Members[member]; - CompilerObject IRTGetMember.Member(Compiler.Compiler compiler, CompilerObject value, string member) + CompilerObject IRTGetMember_Old.Member(Compiler.Compiler compiler, CompilerObject value, string member) => compiler.Map(Members[member], @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, value) : @object); IR.Interface ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) diff --git a/ZSharp.Compiler.Objects/signature/abstract/ISignature_NEW.cs b/ZSharp.Compiler.Objects/signature/abstract/ISignature_NEW.cs new file mode 100644 index 00000000..8e22dc94 --- /dev/null +++ b/ZSharp.Compiler.Objects/signature/abstract/ISignature_NEW.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Objects +{ + public interface ISignature_NEW + { + + } +} diff --git a/ZSharp.Compiler.Objects/signature/abstract/ICallableType.cs b/ZSharp.Compiler.Objects/signature/abstract_old/ICallableType.cs similarity index 100% rename from ZSharp.Compiler.Objects/signature/abstract/ICallableType.cs rename to ZSharp.Compiler.Objects/signature/abstract_old/ICallableType.cs diff --git a/ZSharp.Compiler.Objects/signature/abstract/IParameter.cs b/ZSharp.Compiler.Objects/signature/abstract_old/IParameter.cs similarity index 100% rename from ZSharp.Compiler.Objects/signature/abstract/IParameter.cs rename to ZSharp.Compiler.Objects/signature/abstract_old/IParameter.cs diff --git a/ZSharp.Compiler.Objects/signature/abstract/ISignature.cs b/ZSharp.Compiler.Objects/signature/abstract_old/ISignature.cs similarity index 98% rename from ZSharp.Compiler.Objects/signature/abstract/ISignature.cs rename to ZSharp.Compiler.Objects/signature/abstract_old/ISignature.cs index 56e18dee..6b0edb5b 100644 --- a/ZSharp.Compiler.Objects/signature/abstract/ISignature.cs +++ b/ZSharp.Compiler.Objects/signature/abstract_old/ISignature.cs @@ -68,7 +68,6 @@ public Mapping MatchArguments(Compiler.Compiler else if (positionalArgumentsQueue.Count > 0) throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); - var keywordArguments = kwArgs.ToDictionary(); var varKeywordArguments = new Collection(); foreach (var kwParam in kwParams) @@ -82,7 +81,7 @@ public Mapping MatchArguments(Compiler.Compiler if (VarKwArgs is not null) result[VarKwArgs] = VarKwArgs.MatchArguments(compiler, [.. varKeywordArguments]); - else if (keywordArguments.Count > 0) + else if (kwArgs.Count > 0) throw new ArgumentsCountMismatchException($"Expected {@params.Count} named arguments but got {args.Count}"); return result; diff --git a/ZSharp.Compiler.Objects/signature/abstract/IVarParameter.cs b/ZSharp.Compiler.Objects/signature/abstract_old/IVarParameter.cs similarity index 100% rename from ZSharp.Compiler.Objects/signature/abstract/IVarParameter.cs rename to ZSharp.Compiler.Objects/signature/abstract_old/IVarParameter.cs diff --git a/ZSharp.Compiler/cg objects/types/Int32Type.cs b/ZSharp.Compiler/cg objects/types/Int32Type.cs index ee1047e4..200995bf 100644 --- a/ZSharp.Compiler/cg objects/types/Int32Type.cs +++ b/ZSharp.Compiler/cg objects/types/Int32Type.cs @@ -6,7 +6,7 @@ namespace ZSharp.Objects public sealed class Int32Type(IR.OOPTypeReference ir, IType type) : CompilerObject , ICompileIRType - , ICTGetMember + , ICTGetMember_Old , IType { public IR.OOPTypeReference IR { get; } = ir; diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.Evaluate.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.Evaluate.cs index f664f43b..a8065117 100644 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.Evaluate.cs +++ b/ZSharp.Compiler/compiler core/compiler/Compiler.Evaluate.cs @@ -9,7 +9,7 @@ public CompilerObject Evaluate(CompilerObject @object) CompilerObject result = @object; foreach (var evaluator in Evaluators) - if ((result = evaluator.Evaluate(result)) != @object) break; + if ((result = evaluator.Evaluate(result).Unwrap()) != @object) break; //while (@object == result) //{ diff --git a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs index 07f3ce21..bc36852c 100644 --- a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs +++ b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs @@ -19,10 +19,6 @@ public CompilerObject Call(CompilerObject target, Argument[] arguments) if (target is ICTCallable ctCallable) return ctCallable.Call(this, arguments); - if (target is ICTReadable readable) - if (readable.Type is IRTCallable rtCallable) - return rtCallable.Call(this, target, arguments); - // implements typeclass Callable? // overloads call operator? @@ -106,10 +102,10 @@ public CompilerObject Member(CompilerObject instance, MemberIndex index, Compile /// public CompilerObject Member(CompilerObject instance, MemberName member) { - if (instance is ICTGetMember ctGetMember) + if (instance is ICTGetMember_Old ctGetMember) return ctGetMember.Member(this, member); - if (instance is ICTReadable readable && readable.Type is IRTGetMember rtGetMember) + if (instance is ICTReadable readable && readable.Type is IRTGetMember_Old rtGetMember) return rtGetMember.Member(this, instance, member); throw new NotImplementedException(); diff --git a/ZSharp.Compiler/compiler core/core/evaluation/DefaultEvaluator.cs b/ZSharp.Compiler/compiler core/core/evaluation/DefaultEvaluator.cs index d93367a3..627a0275 100644 --- a/ZSharp.Compiler/compiler core/core/evaluation/DefaultEvaluator.cs +++ b/ZSharp.Compiler/compiler core/core/evaluation/DefaultEvaluator.cs @@ -3,7 +3,9 @@ namespace ZSharp.Compiler { internal sealed class DefaultEvaluator(Compiler compiler) : Evaluator { - public override CompilerObject Evaluate(CompilerObject @object) - => @object is IEvaluable evaluable ? evaluable.Evaluate(compiler) : @object; + public override CompilerObjectResult Evaluate(CompilerObject @object) + => CompilerObjectResult.Ok( + @object is IEvaluable evaluable ? evaluable.Evaluate(compiler) : @object + ); } } diff --git a/ZSharp.Compiler/compiler core/core/evaluation/Evaluator.cs b/ZSharp.Compiler/compiler core/core/evaluation/Evaluator.cs index 49e40b5c..0b3b42ef 100644 --- a/ZSharp.Compiler/compiler core/core/evaluation/Evaluator.cs +++ b/ZSharp.Compiler/compiler core/core/evaluation/Evaluator.cs @@ -2,6 +2,6 @@ { public abstract class Evaluator { - public abstract CompilerObject Evaluate(CompilerObject @object); + public abstract CompilerObjectResult Evaluate(CompilerObject @object); } } diff --git a/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs b/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs index 44adbfd4..648086a7 100644 --- a/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs +++ b/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs @@ -1,7 +1,12 @@ namespace ZSharp.Compiler { public interface IDynamicallyTyped + : CompilerObject + , IHasRuntimeDescriptor { + CompilerObject IHasRuntimeDescriptor.GetRuntimeDescriptor(Compiler compiler) + => GetType(compiler); + public IType GetType(Compiler compiler); } } diff --git a/ZSharp.Compiler/core/Result.cs b/ZSharp.Compiler/core/Result.cs index 3ff39edf..d3b2f4f9 100644 --- a/ZSharp.Compiler/core/Result.cs +++ b/ZSharp.Compiler/core/Result.cs @@ -44,6 +44,18 @@ public Result When(Action action) return this; } + public Result When(Func map) + where R : class + => IsOk + ? Result.Ok(map(result)) + : Result.Error(error!); + + public Result When(out TResult? result) + { + result = this.result; + return this; + } + public Result Else(Action action) { if (IsError) @@ -51,5 +63,17 @@ public Result Else(Action action) return this; } + + public Result Else(Func map) + where E : class + => IsOk + ? Result.Ok(result) + : Result.Error(map(error!)); + + public Result Else(out TError? error) + { + error = this.error; + return this; + } } } diff --git a/ZSharp.Compiler/core/code/IRCode.cs b/ZSharp.Compiler/core/code/IRCode.cs index 09d15253..eb976ac0 100644 --- a/ZSharp.Compiler/core/code/IRCode.cs +++ b/ZSharp.Compiler/core/code/IRCode.cs @@ -32,6 +32,9 @@ public void RequireVoidType() public IType RequireValueType() => IsValue ? Types[0] : throw new InvalidOperationException(); + public IType RequireValueType(IType? @default) + => IsValue ? Types[0] : (@default ?? throw new InvalidOperationException()); + public void Append(IRCode other) { Instructions.AddRange(other.Instructions); diff --git a/ZSharp.Compiler/core/concepts/callable/ICallable.cs b/ZSharp.Compiler/core/concepts/callable/ICallable.cs index a8413fd1..bca0d5f5 100644 --- a/ZSharp.Compiler/core/concepts/callable/ICallable.cs +++ b/ZSharp.Compiler/core/concepts/callable/ICallable.cs @@ -4,17 +4,13 @@ /// Should be implemented by any binding that is callable. /// public interface ICTCallable - : CompilerObject + : ICTCallable_NEW { - public CompilerObject Call(Compiler compiler, Argument[] arguments); - } + CompilerObjectResult ICTCallable_NEW.Call(Compiler compiler, Argument_NEW[] arguments) + => CompilerObjectResult.Ok( + Call(compiler, arguments.Select(arg => new Argument(arg.Name, arg.Value)).ToArray()) + ); - /// - /// Should be implementedby any type that is callable. - /// - public interface IRTCallable - : CompilerObject - { - public CompilerObject Call(Compiler compiler, CompilerObject callable, Argument[] arguments); + public CompilerObject Call(Compiler compiler, Argument[] arguments); } } diff --git a/ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs b/ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs index adf69aff..aa6b2ed1 100644 --- a/ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs +++ b/ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs @@ -1,7 +1,10 @@ namespace ZSharp.Compiler { - public interface ICTGetIndex + public interface ICTGetIndex : ICTGetIndex_NEW { + CompilerObjectResult ICTGetIndex_NEW.Index(Compiler compiler, Argument_NEW[] arguments) + => CompilerObjectResult.Ok(Index(compiler, [.. arguments.Select(arg => new Argument(arg.Name, arg.Value))])); + public CompilerObject Index(Compiler compiler, Argument[] index); } } diff --git a/ZSharp.Compiler/core/concepts/member/IGetMember.cs b/ZSharp.Compiler/core/concepts/member/IGetMember.cs index 99815eee..2a936c6b 100644 --- a/ZSharp.Compiler/core/concepts/member/IGetMember.cs +++ b/ZSharp.Compiler/core/concepts/member/IGetMember.cs @@ -1,12 +1,18 @@ namespace ZSharp.Compiler { - public interface ICTGetMember + public interface ICTGetMember_Old : ICTGetMember { - public CompilerObject Member(Compiler compiler, M member); + CompilerObjectResult ICTGetMember.Member(Compiler compiler, M member) + => CompilerObjectResult.Ok(Member(compiler, member)); + + public new CompilerObject Member(Compiler compiler, M member); } - public interface IRTGetMember + public interface IRTGetMember_Old : IRTGetMember { - public CompilerObject Member(Compiler compiler, CompilerObject value, M member); + CompilerObjectResult IRTGetMember.Member(Compiler compiler, CompilerObject @object, M member) + => CompilerObjectResult.Ok(Member(compiler, @object, member)); + + public new CompilerObject Member(Compiler compiler, CompilerObject value, M member); } } diff --git a/ZSharp.Compiler/core/concepts/member/ISetMember.cs b/ZSharp.Compiler/core/concepts/member/ISetMember.cs deleted file mode 100644 index 6bffcfc8..00000000 --- a/ZSharp.Compiler/core/concepts/member/ISetMember.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - internal interface ISetMember - { - public CompilerObject Member(T @object, M member, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/core/concepts/value/assignment/IAssignable.cs b/ZSharp.Compiler/core/concepts/value/assignment/IAssignable.cs index 4ed88c26..6085ca67 100644 --- a/ZSharp.Compiler/core/concepts/value/assignment/IAssignable.cs +++ b/ZSharp.Compiler/core/concepts/value/assignment/IAssignable.cs @@ -1,12 +1,18 @@ namespace ZSharp.Compiler { - public interface ICTAssignable + public interface ICTAssignable : ICTSet { + CompilerObjectResult ICTSet.Set(Compiler compiler, CompilerObject value) + => CompilerObjectResult.Ok(Assign(compiler, value)); + public CompilerObject Assign(Compiler compiler, CompilerObject value); } - public interface IRTAssignable + public interface IRTAssignable : IRTSet { + CompilerObjectResult IRTSet.Set(Compiler compiler, CompilerObject @object, CompilerObject value) + => CompilerObjectResult.Ok(Assign(compiler, @object, value)); + public CompilerObject Assign(Compiler compiler, CompilerObject @object, CompilerObject value); } } diff --git a/ZSharp.Compiler/features/cg/CG.cs b/ZSharp.Compiler/features/cg/CG.cs index d60f5805..22daa277 100644 --- a/ZSharp.Compiler/features/cg/CG.cs +++ b/ZSharp.Compiler/features/cg/CG.cs @@ -1,181 +1,13 @@ namespace ZSharp.Compiler { - public readonly struct CG(Compiler compiler) + public readonly partial struct CG(Compiler compiler) { public readonly Compiler compiler = compiler; - public CompilerObjectResult Assign(CompilerObject target, CompilerObject value) + private bool This(out CG cg) { - if (target is ICTAssignable ctAssignable) - return CompilerObjectResult.Ok( - ctAssignable.Assign(compiler, value) - ); - - return CompilerObjectResult.Error( - "Object does not support assignment" - ); - } - - // TODO: WTH is this? - public IRCode Assign(IRCode irCode, Assignment assignment) - => throw new NotImplementedException(); - - public CompilerObjectResult Call(CompilerObject target, Argument[] arguments) - { - CompilerObject? result = null; - - if (target is ICTCallable ctCallable) - result = ctCallable.Call(compiler, arguments); - - else if (target is ICTReadable readable) - if (readable.Type is IRTCallable rtCallable) - result = rtCallable.Call(compiler, target, arguments); - - // implements typeclass Callable? - - // overloads call operator? - - if (result is not null) - return CompilerObjectResult.Ok(result); - return CompilerObjectResult.Error( - "Object is not callable" - ); - } - - public Result Cast(CompilerObject value, IType type) - { - var result = Result.Error( - "Object cannot be cast" - ); - - if ( - compiler.TypeSystem.IsTyped(value, out var valueType) - && valueType is IRTCastTo rtCastTo - ) - result = rtCastTo.Cast(compiler, value, type); - - if (result.IsOk) return result; - - if (type is IRTCastFrom rtCastFrom) - result = rtCastFrom.Cast(compiler, value); - - if (result.IsOk) return result; - - if (valueType is not null && compiler.TypeSystem.AreEqual(type, valueType)) - result = Result.Ok(new() - { - Cast = value, - }); - - return result; - } - - /// - /// The get index ([]) operator. - /// - /// - /// - /// - public CompilerObject? Index(CompilerObject instanceTarget, Argument[] index) - { - if (instanceTarget is ICTGetIndex ctGetIndex) - return ctGetIndex.Index(compiler, index); - - return null; - } - - /// - /// The set index ([]=) operator. - /// - /// - /// - /// - /// - public CompilerObject Index(CompilerObject instanceTarget, Argument[] index, CompilerObject value) - { - throw new NotImplementedException(); - } - - public CompilerObject Map(CompilerObject @object, Func func) - { - if (@object is IMappable mappable) - return mappable.Map(func); - - return func(@object); - } - - /// - /// The member (.) operator. - /// - /// - /// - /// - public CompilerObject Member(CompilerObject instance, MemberIndex index) - { - throw new NotImplementedException(); - } - - /// - /// The set member (.=) operator. - /// - /// - /// - /// - /// - public CompilerObject Member(CompilerObject instance, MemberIndex index, CompilerObject value) - { - throw new NotImplementedException(); - } - - /// - /// The member (.) operator. - /// - /// - /// - /// - public CompilerObject Member(CompilerObject instance, MemberName member) - { - if (instance is ICTGetMember ctGetMember) - return ctGetMember.Member(compiler, member); - - if (instance is ICTReadable readable && readable.Type is IRTGetMember rtGetMember) - return rtGetMember.Member(compiler, instance, member); - - throw new NotImplementedException(); - } - - /// - /// The set member (.=) operator. - /// - /// - /// - /// - /// - public CompilerObject Member(CompilerObject instance, MemberName member, CompilerObject value) - { - throw new NotImplementedException(); - } - - public Result TypeMatch(CompilerObject @object, IType type) - { - var result = Result.Error( - "Object cannot be type matched" - ); - - if (@object is ICTTypeMatch ctTypeMatch) - result = ctTypeMatch.Match(compiler, type); - - if (result.IsOk) return result; - - if ( - compiler.TypeSystem.IsTyped(@object, out var objectType) - && objectType is IRTTypeMatch rtTypeMatch - ) - result = rtTypeMatch.Match(compiler, @object, type); - - if (result.IsOk) return result; - - return result; + cg = this; + return true; } } } diff --git a/ZSharp.Compiler/features/cg/type casting/IRTCastFrom.cs b/ZSharp.Compiler/features/cg/type casting/IRTCastFrom.cs deleted file mode 100644 index 0d6f2142..00000000 --- a/ZSharp.Compiler/features/cg/type casting/IRTCastFrom.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTCastFrom - : CompilerObject - { - public Result Cast(Compiler compiler, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/features/cg/type casting/IRTCastTo.cs b/ZSharp.Compiler/features/cg/type casting/IRTCastTo.cs deleted file mode 100644 index 50386228..00000000 --- a/ZSharp.Compiler/features/cg/type casting/IRTCastTo.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTCastTo - : CompilerObject - { - public Result Cast(Compiler compiler, CompilerObject value, IType targetType); - } -} diff --git a/ZSharp.Compiler/features/cg/type matching/ICTTypeMatch.cs b/ZSharp.Compiler/features/cg/type matching/ICTTypeMatch.cs deleted file mode 100644 index f44ee43b..00000000 --- a/ZSharp.Compiler/features/cg/type matching/ICTTypeMatch.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTTypeMatch - : CompilerObject - { - public Result Match(Compiler compiler, IType type); - } -} diff --git a/ZSharp.Compiler/features/cg/type matching/IRTTypeMatch.cs b/ZSharp.Compiler/features/cg/type matching/IRTTypeMatch.cs deleted file mode 100644 index b3e3b89e..00000000 --- a/ZSharp.Compiler/features/cg/type matching/IRTTypeMatch.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTTypeMatch - : CompilerObject - { - public Result Match(Compiler compiler, CompilerObject value, IType type); - } -} diff --git a/ZSharp.Compiler/features/cg/type matching/TypeMatch.cs b/ZSharp.Compiler/features/cg/type matching/TypeMatch.cs deleted file mode 100644 index 6c46d7c9..00000000 --- a/ZSharp.Compiler/features/cg/type matching/TypeMatch.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Compiler -{ - public sealed class TypeMatch - { - public required CompilerObject Match { get; set; } - - public ZSharp.IR.VM.Instruction OnMatch { get; init; } = new ZSharp.IR.VM.Nop(); - } -} diff --git a/ZSharp.Interpreter/ZSSourceEvaluator.cs b/ZSharp.Interpreter/ZSSourceEvaluator.cs index 8f243562..42f8a8a0 100644 --- a/ZSharp.Interpreter/ZSSourceEvaluator.cs +++ b/ZSharp.Interpreter/ZSSourceEvaluator.cs @@ -1,4 +1,5 @@ -using ZSharp.Objects; +using ZSharp.Compiler; +using ZSharp.Objects; namespace ZSharp.Interpreter { @@ -6,16 +7,21 @@ internal sealed class ZSSourceEvaluator(ZSSourceCompiler.ZSSourceCompiler source { private readonly ZSSourceCompiler.ZSSourceCompiler sourceCompiler = sourceCompiler; - public override CompilerObject Evaluate(CompilerObject @object) + public override Result Evaluate(CompilerObject @object) { - if (@object is not ZSSourceCompiler.NodeObject nodeObject) return @object; + if (@object is not ZSSourceCompiler.NodeObject nodeObject) + return Result.Ok(@object); if (nodeObject.Node is AST.Expression expression) - return sourceCompiler.CompileNode(expression); + return Result.Ok( + sourceCompiler.CompileNode(expression).Unwrap() + ); if (nodeObject.Node is AST.Statement statement) - return sourceCompiler.CompileNode(statement); + return Result.Ok( + sourceCompiler.CompileNode(statement).Unwrap() + ); - return @object; + return Result.Ok(@object); } } } diff --git a/ZSharp.Parser/lang/LangParser.Keywords.cs b/ZSharp.Parser/lang/LangParser.Keywords.cs index b0d0243f..a65e2827 100644 --- a/ZSharp.Parser/lang/LangParser.Keywords.cs +++ b/ZSharp.Parser/lang/LangParser.Keywords.cs @@ -20,6 +20,7 @@ public static class Keywords public const string Module = "module"; public const string New = "new"; public const string Of = "of"; + public const string Or = "or"; public const string Return = "return"; public const string Var = "var"; public const string When = "when"; diff --git a/ZSharp.Runtime.IL/IRCodeEvaluator.cs b/ZSharp.Runtime.IL/IRCodeEvaluator.cs index 500c1e86..621521d4 100644 --- a/ZSharp.Runtime.IL/IRCodeEvaluator.cs +++ b/ZSharp.Runtime.IL/IRCodeEvaluator.cs @@ -16,10 +16,10 @@ internal sealed class IRCodeEvaluator(Runtime runtime) private Interpreter.Interpreter Interpreter => runtime.Interpreter; - public override CompilerObject Evaluate(CompilerObject @object) + public override Result Evaluate(CompilerObject @object) { if (@object is not RawCode rawCode) - return @object; + return Result.Ok(@object); var code = rawCode.Code; @@ -50,10 +50,10 @@ i is IR.VM.IHasOperand hasOperand var value = functionIL.Invoke(null, null); if (value is CompilerObject co) - return co; + return Result.Ok(co); if (value is ICompileTime coObject) - return coObject.GetCO(); + return Result.Ok(coObject.GetCO()); //if (value is Type type) // return new RawType(interpreter.IRInterop.ImportILType(type), interpreter.Compiler.TypeSystem.Type); @@ -76,22 +76,34 @@ private void CompileGetObject(ICodeLoader loader, IR.VM.GetObject get) public CompilerObject? EvaluateCT(IRCode code) { - throw new NotImplementedException(); + IL.Emit.DynamicMethod method = new( + string.Empty, + runtime.irLoader.LoadType( + runtime.Interpreter.Compiler.IR.CompileType( + code.RequireValueType(runtime.Interpreter.Compiler.TypeSystem.Void) + ).Unwrap() + ), + null + ); - var function = new IR.Function(Interpreter.Compiler.CompileIRType(code.RequireValueType())) - { - Name = "evaluate" - }; + var context = new IR2IL.Code.UnboundCodeContext(runtime.irLoader, method.GetILGenerator()); + + new IR2IL.Code.CodeCompiler(context).CompileCode([ + .. code.Instructions, + new IR.VM.Return() + ]); - IL.Emit.DynamicMethod method = new(string.Empty, runtime.Import(function.ReturnType), null); + var result = method.Invoke(null, null); - CodeLoader codeLoader = new( - runtime.irLoader, - function, - method.GetILGenerator() - ); + if (method.ReturnType == typeof(void)) return null; - codeLoader.Load(); + if (result is CompilerObject co) + return co; + + if (result is ICompileTime coObject) + return coObject.GetCO(); + + throw new NotImplementedException(); } } } diff --git a/ZSharp.Runtime.IL/Runtime.cs b/ZSharp.Runtime.IL/Runtime.cs index 573741d6..524bde56 100644 --- a/ZSharp.Runtime.IL/Runtime.cs +++ b/ZSharp.Runtime.IL/Runtime.cs @@ -24,7 +24,12 @@ public Runtime(Interpreter.Interpreter interpreter) ilLoader = new(Context, interpreter.RuntimeModule); irLoader = new(Context, interpreter.RuntimeModule); - interpreter.Compiler.Evaluators.Add(new IRCodeEvaluator(this)); + var irCompiler = new Compiler.IRCompiler(interpreter.Compiler); + var irEvaluator = new IRCodeEvaluator(this); + + irCompiler.Evaluator = irEvaluator; + + interpreter.Compiler.Evaluators.Add(irEvaluator); irLoader.GetObjectFunction = (loader, get) => { diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs index 1157efcb..51140705 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs @@ -155,7 +155,10 @@ private void LoadConstructor(IL.ConstructorInfo constructor) result.Method.Signature.Args.Parameters.Add(new("this", Self)); foreach (var parameter in constructor.GetParameters()) - result.Method.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); + if (parameter.GetCustomAttribute() is not null) + result.Method.Signature.KwArgs.Parameters.Add(new(parameter.Name ?? throw new(), Loader.LoadType(parameter.ParameterType))); + else + result.Method.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); Output.Constructors.Add(result); } @@ -186,7 +189,10 @@ private Method LoadMethod(IL.MethodInfo method) result.IsVirtual = true; foreach (var parameter in method.GetParameters()) - result.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); + if (parameter.GetCustomAttribute() is not null) + result.Signature.KwArgs.Parameters.Add(new(parameter.Name ?? throw new(), Loader.LoadType(parameter.ParameterType))); + else + result.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); Output.Methods.Add(result); diff --git a/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs index bbea1c06..c7b50d0d 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs @@ -129,7 +129,10 @@ private Method LoadMethod(MethodInfo method) result.Signature.Args.Parameters.Add(new("this", Self)); foreach (var parameter in method.GetParameters()) - result.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); + if (parameter.GetCustomAttribute() is not null) + result.Signature.KwArgs.Parameters.Add(new(parameter.Name ?? throw new(), Loader.LoadType(parameter.ParameterType))); + else + result.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); Output.Methods.Add(result); diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs index 602898ea..00798a01 100644 --- a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs @@ -101,29 +101,22 @@ private void LoadMethods() private void LoadConstructor(IR.Constructor constructor) { - var irParams = constructor.Method.Signature.GetParameters(); - - var parameters = irParams.Select(p => new Parameter() - { - Name = p.Name, - Type = Loader.LoadType(p.Type), - Position = p.Index - }); - - var result = Output.DefineConstructor(IL.MethodAttributes.Public, IL.CallingConventions.HasThis, [.. irParams.Skip(1).Select(p => Loader.LoadType(p.Type))]); + var result = Output.DefineConstructor( + IL.MethodAttributes.Public, + IL.CallingConventions.HasThis, + [.. constructor.Method.Signature.GetParameters().Skip(1).Select(p => Loader.LoadType(p.Type))] + ); Context.Cache(constructor.Method, result); - var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(Loader, constructor.Method, ilGen); - - foreach (var (ir, parameter) in irParams.Zip(parameters)) - codeLoader.Args[ir] = parameter; + var context = Code.FunctionCodeContext.From(Loader, result, constructor.Method.UnderlyingFunction); foreach (var local in constructor.Method.Body.Locals) - codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); + result.GetILGenerator().DeclareLocal(Loader.LoadType(local.Type)); + + var codeLoader = new Code.CodeCompiler(context); - ModuleLoader.AddToNextPass(() => codeLoader.Load()); + ModuleLoader.AddToNextPass(() => codeLoader.CompileCode(constructor.Method.Body.Instructions)); } private void LoadField(IR.Field field) @@ -140,15 +133,6 @@ private void LoadField(IR.Field field) private void LoadMethod(IR.Method method) { - var irParams = method.Signature.GetParameters(); - - var parameters = irParams.Select(p => new Parameter() - { - Name = p.Name, - Type = Loader.LoadType(p.Type), - Position = p.Index, - }); - var attributes = IL.MethodAttributes.Public; if (method.IsStatic) @@ -160,21 +144,24 @@ private void LoadMethod(IR.Method method) method.Name ?? Constants.AnonymousMethod, attributes, Loader.LoadType(method.ReturnType), - [.. (method.IsInstance || method.IsVirtual ? parameters.Skip(1) : parameters).Select(p => p.Type)] + [.. ( + method.IsInstance || method.IsVirtual + ? method.Signature.GetParameters().Skip(1) + : method.Signature.GetParameters() + ).Select(p => Loader.LoadType(p.Type)) + ] ); Context.Cache(method, result); - var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(Loader, method, ilGen); - - foreach (var (ir, parameter) in irParams.Zip(parameters)) - codeLoader.Args[ir] = parameter; + var context = Code.FunctionCodeContext.From(Loader, result, method.UnderlyingFunction); foreach (var local in method.Body.Locals) - codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); + result.GetILGenerator().DeclareLocal(Loader.LoadType(local.Type)); + + var codeLoader = new Code.CodeCompiler(context); - ModuleLoader.AddToNextPass(() => codeLoader.Load()); + ModuleLoader.AddToNextPass(() => codeLoader.CompileCode(method.Body.Instructions)); } private static IL.Emit.TypeBuilder CreateDefinition(IL.Emit.ModuleBuilder module, IR.Class @in) From 8de11076ead8f6ab2253de03f1647d43604204be Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 8 Jun 2025 23:14:56 +0300 Subject: [PATCH 175/235] Fix compiler crashing when document-level code returns void --- .../builtin-compilers/document/compiler/DocumentCompiler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs index 8d4a650a..e7e5835f 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs +++ b/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs @@ -35,7 +35,7 @@ private void CompileDocument() Compiler.Compiler.IR.CompileCode( Compiler.CompileNode(expression).Unwrap() ).Unwrap() - ) ?? throw new() + ) ?? new Objects.RawCode(new()) ), }; From 4235bb74762b127de18e889400e32b7fa53d7c11 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 11 Jun 2025 04:13:56 +0300 Subject: [PATCH 176/235] Organize code base --- ZSharp v1.sln | 6 -- ZSharp.AST/ZSharp.AST.csproj | 2 +- ZSharp.CT.RuntimeAPI/Fields_Globals.cs | 2 +- ZSharp.CT.RuntimeAPI/Impl_Globals.cs | 3 - .../generic/definition/GenericFunction.cs | 2 +- ZSharp.Compiler/cg objects/raw/RawCode.cs | 4 + .../compiler/Compiler.Evaluate.cs | 32 ------- .../compiler core/compiler/Compiler.IR.cs | 10 --- .../compiler core/compiler/Compiler.cs | 1 - .../core/evaluation/DefaultEvaluator.cs | 11 --- .../core/evaluation/Evaluator.cs | 7 -- .../core/type system/TypeSystem.cs | 3 - .../core/concepts/value/IReadable.cs | 4 + ZSharp.Compiler/features/ir/IR.Code.cs | 24 ----- .../ir/capabilities/code/ICTCompileIRCode.cs | 8 ++ .../features/ir/services/IR.Code.cs | 21 +++++ .../ir/{ => services}/IR.Definition.cs | 3 +- .../ir/{ => services}/IR.Reference.cs | 0 .../features/ir/{ => services}/IR.Type.cs | 0 .../ir generator/protocols/ICompileIRCode.cs | 7 +- ZSharp.Interpreter/Interpreter.cs | 50 ----------- ZSharp.Interpreter/ZSSourceEvaluator.cs | 27 ------ ZSharp.Interpreter/ZSharp.Interpreter.csproj | 2 +- .../{ => interpreter}/IHostLoader.cs | 0 ZSharp.Interpreter/interpreter/Interpreter.cs | 87 +++++++++++++++++++ .../{ => interpreter}/rt/IRuntime.cs | 0 .../source-compiler}/GlobalUsings.cs | 0 .../source-compiler}/HelperFunctions.cs | 0 .../source-compiler}/NodeLogOrigin.cs | 0 .../capabilities/IMultipassCompiler.cs | 0 .../class body/ClassBodyCompiler.cs | 0 .../class body/ConstructorCompiler.cs | 0 .../class body/MethodCompiler.cs | 0 .../compiler/DocumentCompiler.Compile.cs | 0 .../document/compiler/DocumentCompiler.cs | 13 ++- .../document/objects/Document.cs | 0 .../builtin-compilers/module/ClassCompiler.cs | 0 .../module/FunctionCompiler.cs | 0 .../module/ModuleCompiler.cs | 0 .../runtime code/loops/for/ForLoopCompiler.cs | 0 .../loops/while/WhileExpressionCompiler.cs | 0 .../loops/while/WhileLoopCompiler.cs | 0 .../loops/while/WhileStatementCompiler.cs | 0 .../runtime code/objects/Case.cs | 0 .../runtime code/objects/ForLoop.cs | 0 .../runtime code/objects/If.cs | 0 .../runtime code/objects/WhileLoop.cs | 0 .../compiler/ZSSourceCompiler.Compilers.cs | 0 .../compiler/ZSSourceCompiler.ImportSystem.cs | 6 +- .../compiler/ZSSourceCompiler.Initialize.cs | 0 .../compiler/ZSSourceCompiler.Logging.cs | 2 +- .../compiler/ZSSourceCompiler.OOP.cs | 2 +- .../compiler/ZSSourceCompiler.Operators.cs | 0 .../compiler/ZSSourceCompiler.ResultTools.cs | 2 +- .../compiler/ZSSourceCompiler.cs | 17 +++- .../context/Context.Compilers.cs | 0 .../source-compiler}/context/Context.Nodes.cs | 0 .../context/Context.Scopes.cs | 0 .../source-compiler}/context/Context.cs | 0 .../contexts/capabilities/IMemoryAllocator.cs | 0 .../contexts/capabilities/IObjectContext.cs | 0 .../capabilities/scope/ILookupContext.cs | 0 .../capabilities/scope/IScopeContext.cs | 0 .../contexts/concrete/ClassContext.cs | 0 .../contexts/concrete/ExpressionContext.cs | 0 .../contexts/concrete/FunctionContext.cs | 0 .../contexts/concrete/ObjectContext.cs | 0 .../contexts/concrete/ScopeContext.cs | 0 .../strategies/UntilContextTypeStrategy.cs | 0 .../core-compilers/DefaultContextCompiler.cs | 0 .../expression/ExpressionCompiler.Literals.cs | 0 .../expression/ExpressionCompiler.cs | 4 +- .../statement/StatementCompiler.cs | 0 .../extensibility/CompilerBase.cs | 0 .../extensibility/ContextCompiler.cs | 0 .../extensibility/error/Error.cs | 0 .../error/errors/CombinedCompilationError.cs | 0 .../error/errors/CompilationError.cs | 0 .../extensibility/oop/ClassSpecification.cs | 0 .../overrides/IOverrideCompileExpression.cs | 0 .../overrides/IOverrideCompileNode.cs | 0 .../overrides/IOverrideCompileStatement.cs | 0 .../import system/ImportSystem.cs | 0 .../importers/StandardLibraryImporter.cs | 4 +- .../import system/importers/StringImporter.cs | 4 +- .../import system/importers/ZSImporter.cs | 4 +- ZSharp.Parser/ZSharp.Parser.csproj | 2 +- ZSharp.Runtime.IL/IRCodeEvaluator.cs | 79 ++--------------- ZSharp.Runtime.IL/Runtime.cs | 57 ++++-------- ZSharp.Runtime.IL/ZSharp.Runtime.IL.csproj | 2 +- {ZSharp.Text => ZSharp.Tokenizer}/Token.cs | 0 .../TokenType.cs | 0 ZSharp.ZSSourceCompiler/NodeObject.cs | 7 -- .../ZSharp.ZSSourceCompiler.csproj | 15 ---- .../document/objects/DocumentValue.cs | 21 ----- ZSharpTest/DotNETImporter.cs | 2 +- ZSharpTest/Main.cs | 8 +- 97 files changed, 192 insertions(+), 375 deletions(-) delete mode 100644 ZSharp.Compiler/compiler core/compiler/Compiler.Evaluate.cs delete mode 100644 ZSharp.Compiler/compiler core/core/evaluation/DefaultEvaluator.cs delete mode 100644 ZSharp.Compiler/compiler core/core/evaluation/Evaluator.cs delete mode 100644 ZSharp.Compiler/features/ir/IR.Code.cs create mode 100644 ZSharp.Compiler/features/ir/capabilities/code/ICTCompileIRCode.cs create mode 100644 ZSharp.Compiler/features/ir/services/IR.Code.cs rename ZSharp.Compiler/features/ir/{ => services}/IR.Definition.cs (94%) rename ZSharp.Compiler/features/ir/{ => services}/IR.Reference.cs (100%) rename ZSharp.Compiler/features/ir/{ => services}/IR.Type.cs (100%) delete mode 100644 ZSharp.Interpreter/Interpreter.cs delete mode 100644 ZSharp.Interpreter/ZSSourceEvaluator.cs rename ZSharp.Interpreter/{ => interpreter}/IHostLoader.cs (100%) create mode 100644 ZSharp.Interpreter/interpreter/Interpreter.cs rename ZSharp.Interpreter/{ => interpreter}/rt/IRuntime.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/GlobalUsings.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/HelperFunctions.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/NodeLogOrigin.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/capabilities/IMultipassCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/class body/ClassBodyCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/class body/ConstructorCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/class body/MethodCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/document/compiler/DocumentCompiler.Compile.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/document/compiler/DocumentCompiler.cs (78%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/document/objects/Document.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/module/ClassCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/module/FunctionCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/module/ModuleCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/runtime code/objects/Case.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/runtime code/objects/ForLoop.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/runtime code/objects/If.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/builtin-compilers/runtime code/objects/WhileLoop.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/compiler/ZSSourceCompiler.Compilers.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/compiler/ZSSourceCompiler.ImportSystem.cs (62%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/compiler/ZSSourceCompiler.Initialize.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/compiler/ZSSourceCompiler.Logging.cs (85%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/compiler/ZSSourceCompiler.OOP.cs (65%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/compiler/ZSSourceCompiler.Operators.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/compiler/ZSSourceCompiler.ResultTools.cs (88%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/compiler/ZSSourceCompiler.cs (81%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/context/Context.Compilers.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/context/Context.Nodes.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/context/Context.Scopes.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/context/Context.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/contexts/capabilities/IMemoryAllocator.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/contexts/capabilities/IObjectContext.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/contexts/capabilities/scope/ILookupContext.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/contexts/capabilities/scope/IScopeContext.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/contexts/concrete/ClassContext.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/contexts/concrete/ExpressionContext.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/contexts/concrete/FunctionContext.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/contexts/concrete/ObjectContext.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/contexts/concrete/ScopeContext.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/contexts/strategies/UntilContextTypeStrategy.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/core-compilers/DefaultContextCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/core-compilers/expression/ExpressionCompiler.Literals.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/core-compilers/expression/ExpressionCompiler.cs (97%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/core-compilers/statement/StatementCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/extensibility/CompilerBase.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/extensibility/ContextCompiler.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/extensibility/error/Error.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/extensibility/error/errors/CombinedCompilationError.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/extensibility/error/errors/CompilationError.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/extensibility/oop/ClassSpecification.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/extensibility/overrides/IOverrideCompileExpression.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/extensibility/overrides/IOverrideCompileNode.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/extensibility/overrides/IOverrideCompileStatement.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/import system/ImportSystem.cs (100%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/import system/importers/StandardLibraryImporter.cs (82%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/import system/importers/StringImporter.cs (86%) rename {ZSharp.ZSSourceCompiler => ZSharp.Interpreter/source-compiler}/import system/importers/ZSImporter.cs (83%) rename {ZSharp.Text => ZSharp.Tokenizer}/Token.cs (100%) rename {ZSharp.Text => ZSharp.Tokenizer}/TokenType.cs (100%) delete mode 100644 ZSharp.ZSSourceCompiler/NodeObject.cs delete mode 100644 ZSharp.ZSSourceCompiler/ZSharp.ZSSourceCompiler.csproj delete mode 100644 ZSharp.ZSSourceCompiler/builtin-compilers/document/objects/DocumentValue.cs diff --git a/ZSharp v1.sln b/ZSharp v1.sln index b43c1142..fb24ea45 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -28,8 +28,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharpParserTest", "ZSharpP EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharp.CT.StandardLibrary", "ZSharp.CT.StandardLibrary\ZSharp.CT.StandardLibrary.csproj", "{7FCC6EEC-12BC-409C-93A9-0A4AF7B8E83B}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharp.ZSSourceCompiler", "ZSharp.ZSSourceCompiler\ZSharp.ZSSourceCompiler.csproj", "{5864E449-5E21-426C-9FA5-39BE15B4A0E0}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Interpreter", "ZSharp.Interpreter\ZSharp.Interpreter.csproj", "{F46A91F5-47BA-468A-81F0-FF6BCEB4112C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.IRLoader", "ZSharp.Compiler.IRLoader\ZSharp.Compiler.IRLoader.csproj", "{8E9A7EF0-EE8E-4481-BF60-C6BDBD5C7BB8}" @@ -102,10 +100,6 @@ Global {7FCC6EEC-12BC-409C-93A9-0A4AF7B8E83B}.Debug|Any CPU.Build.0 = Debug|Any CPU {7FCC6EEC-12BC-409C-93A9-0A4AF7B8E83B}.Release|Any CPU.ActiveCfg = Release|Any CPU {7FCC6EEC-12BC-409C-93A9-0A4AF7B8E83B}.Release|Any CPU.Build.0 = Release|Any CPU - {5864E449-5E21-426C-9FA5-39BE15B4A0E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5864E449-5E21-426C-9FA5-39BE15B4A0E0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5864E449-5E21-426C-9FA5-39BE15B4A0E0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5864E449-5E21-426C-9FA5-39BE15B4A0E0}.Release|Any CPU.Build.0 = Release|Any CPU {F46A91F5-47BA-468A-81F0-FF6BCEB4112C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F46A91F5-47BA-468A-81F0-FF6BCEB4112C}.Debug|Any CPU.Build.0 = Debug|Any CPU {F46A91F5-47BA-468A-81F0-FF6BCEB4112C}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/ZSharp.AST/ZSharp.AST.csproj b/ZSharp.AST/ZSharp.AST.csproj index 88c8bd4f..9e4f679a 100644 --- a/ZSharp.AST/ZSharp.AST.csproj +++ b/ZSharp.AST/ZSharp.AST.csproj @@ -7,7 +7,7 @@ - + diff --git a/ZSharp.CT.RuntimeAPI/Fields_Globals.cs b/ZSharp.CT.RuntimeAPI/Fields_Globals.cs index 31ac3262..3051b686 100644 --- a/ZSharp.CT.RuntimeAPI/Fields_Globals.cs +++ b/ZSharp.CT.RuntimeAPI/Fields_Globals.cs @@ -5,6 +5,6 @@ namespace ZS.RuntimeAPI [HideInIR] public static class Fields_Globals { - public static ZSharp.Runtime.NET.Runtime runtime; + //public static ZSharp.Runtime.NET.Runtime runtime; } } diff --git a/ZSharp.CT.RuntimeAPI/Impl_Globals.cs b/ZSharp.CT.RuntimeAPI/Impl_Globals.cs index 15f50ed0..feb7b186 100644 --- a/ZSharp.CT.RuntimeAPI/Impl_Globals.cs +++ b/ZSharp.CT.RuntimeAPI/Impl_Globals.cs @@ -12,8 +12,5 @@ public static ZSharp.Objects.CompilerObject InfoOf(object obj) throw new(); } - - public static object GetObject(Type type) - => Fields_Globals.runtime.GetObject(type); } } diff --git a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs index e48f6c3f..01249b4c 100644 --- a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs +++ b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs @@ -113,7 +113,7 @@ CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) ReferenceContext context = new(); foreach (var (arg, param) in index.Zip(GenericParameters)) - context[param] = compiler.Evaluate(arg.Object); + context[param] = arg.Object; return compiler.Feature().CreateReference(this, context); } diff --git a/ZSharp.Compiler/cg objects/raw/RawCode.cs b/ZSharp.Compiler/cg objects/raw/RawCode.cs index 1313de15..434facf0 100644 --- a/ZSharp.Compiler/cg objects/raw/RawCode.cs +++ b/ZSharp.Compiler/cg objects/raw/RawCode.cs @@ -6,6 +6,7 @@ public sealed class RawCode(IRCode code) : CompilerObject , ICTReadable ,ICTTypeCast + , ICTCompileIRCode { private readonly IRCode code = code; @@ -35,6 +36,9 @@ CompilerObject ICTTypeCast.Cast(Compiler.Compiler compiler, IType targetType) throw new NotImplementedException(); } + Result ICTCompileIRCode.CompileIRCode(Compiler.Compiler compiler) + => Result.Ok(code); + IType IDynamicallyTyped.GetType(Compiler.Compiler compiler) => code.IsVoid ? compiler.TypeSystem.Void : code.RequireValueType(); } diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.Evaluate.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.Evaluate.cs deleted file mode 100644 index a8065117..00000000 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.Evaluate.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - public List Evaluators { get; } = []; - - public CompilerObject Evaluate(CompilerObject @object) - { - CompilerObject result = @object; - - foreach (var evaluator in Evaluators) - if ((result = evaluator.Evaluate(result).Unwrap()) != @object) break; - - //while (@object == result) - //{ - // foreach (var evaluator in Evaluators) - // if ((result = evaluator.Evaluate(result)) != @object) goto loopAgain; - - // break; - - // loopAgain: continue; - //} - - return result; - } - - private void InitializeEvaluators() - { - Evaluators.Add(new DefaultEvaluator(this)); - } - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs index b37eebe4..c88bd876 100644 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs +++ b/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs @@ -46,11 +46,6 @@ public IRType CompileIRType(CompilerObject @object) { ICompileIRType? irType; - if ((irType = @object as ICompileIRType) is not null) - return irType.CompileIRType(this); - - @object = Evaluate(@object); - if ((irType = @object as ICompileIRType) is not null) return irType.CompileIRType(this); @@ -62,11 +57,6 @@ public T CompileIRType(CompilerObject @object) { ICompileIRType? irType; - if ((irType = @object as ICompileIRType) is not null) - return irType.CompileIRType(this); - - @object = Evaluate(@object); - if ((irType = @object as ICompileIRType) is not null) return irType.CompileIRType(this); diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.cs index 2a1eb795..6acbbf32 100644 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.cs +++ b/ZSharp.Compiler/compiler core/compiler/Compiler.cs @@ -21,7 +21,6 @@ private void Initialize() InitializeTypeSystem(); InitializeLiterals(); InitializeFeatures(); - InitializeEvaluators(); } } } diff --git a/ZSharp.Compiler/compiler core/core/evaluation/DefaultEvaluator.cs b/ZSharp.Compiler/compiler core/core/evaluation/DefaultEvaluator.cs deleted file mode 100644 index 627a0275..00000000 --- a/ZSharp.Compiler/compiler core/core/evaluation/DefaultEvaluator.cs +++ /dev/null @@ -1,11 +0,0 @@ - -namespace ZSharp.Compiler -{ - internal sealed class DefaultEvaluator(Compiler compiler) : Evaluator - { - public override CompilerObjectResult Evaluate(CompilerObject @object) - => CompilerObjectResult.Ok( - @object is IEvaluable evaluable ? evaluable.Evaluate(compiler) : @object - ); - } -} diff --git a/ZSharp.Compiler/compiler core/core/evaluation/Evaluator.cs b/ZSharp.Compiler/compiler core/core/evaluation/Evaluator.cs deleted file mode 100644 index 0b3b42ef..00000000 --- a/ZSharp.Compiler/compiler core/core/evaluation/Evaluator.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - public abstract class Evaluator - { - public abstract CompilerObjectResult Evaluate(CompilerObject @object); - } -} diff --git a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs index f265cbf4..c347780c 100644 --- a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs +++ b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs @@ -36,9 +36,6 @@ internal TypeSystem(Compiler compiler) Object = new ObjectType(compiler.RuntimeModule.TypeSystem.Object, Type); } - public IType EvaluateType(CompilerObject @object) - => (IType)Compiler.Evaluate(@object); - public IType Array(CompilerObject type) => throw new NotImplementedException(); diff --git a/ZSharp.Compiler/core/concepts/value/IReadable.cs b/ZSharp.Compiler/core/concepts/value/IReadable.cs index b2ff919f..78c41a1b 100644 --- a/ZSharp.Compiler/core/concepts/value/IReadable.cs +++ b/ZSharp.Compiler/core/concepts/value/IReadable.cs @@ -2,6 +2,7 @@ { public interface ICTReadable : ITyped + , ICTCompileIRCode { public IRCode Cast(Compiler compiler, IType type) => this is ICTTypeCast typeCast @@ -17,5 +18,8 @@ public IRCode Read(Compiler compiler, IType? @as) } public IRCode Read(Compiler compiler); + + Result ICTCompileIRCode.CompileIRCode(Compiler compiler) + => Result.Ok(Read(compiler)); } } diff --git a/ZSharp.Compiler/features/ir/IR.Code.cs b/ZSharp.Compiler/features/ir/IR.Code.cs deleted file mode 100644 index 04f01fe2..00000000 --- a/ZSharp.Compiler/features/ir/IR.Code.cs +++ /dev/null @@ -1,24 +0,0 @@ -using IRCodeResult = ZSharp.Compiler.Result; - -namespace ZSharp.Compiler -{ - public partial struct IR - { - public IRCodeResult CompileCode(CompilerObject @object) - { - IRCode? result = null; - - if (@object is ICompileIRCode irCode) - result = irCode.CompileIRCode(compiler); - - else if (@object is ICTReadable ctReadable) - result = ctReadable.Read(compiler); - - if (result is not null) - return IRCodeResult.Ok(result); - return IRCodeResult.Error( - "Object cannot be compiled to IR code" - ); - } - } -} diff --git a/ZSharp.Compiler/features/ir/capabilities/code/ICTCompileIRCode.cs b/ZSharp.Compiler/features/ir/capabilities/code/ICTCompileIRCode.cs new file mode 100644 index 00000000..18e578fc --- /dev/null +++ b/ZSharp.Compiler/features/ir/capabilities/code/ICTCompileIRCode.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICTCompileIRCode + : CompilerObject + { + public Result CompileIRCode(Compiler compiler); + } +} diff --git a/ZSharp.Compiler/features/ir/services/IR.Code.cs b/ZSharp.Compiler/features/ir/services/IR.Code.cs new file mode 100644 index 00000000..38bdcf42 --- /dev/null +++ b/ZSharp.Compiler/features/ir/services/IR.Code.cs @@ -0,0 +1,21 @@ +using IRCodeResult = ZSharp.Compiler.Result; + +namespace ZSharp.Compiler +{ + public partial struct IR + { + public IRCodeResult CompileCode(CompilerObject @object) + { + var result = IRCodeResult.Error( + "Object does not support compiling to IR code" + ); + + if (@object is ICTCompileIRCode ctIRCode) + result = ctIRCode.CompileIRCode(compiler); + + if (result.IsOk) return result; + + return result; + } + } +} diff --git a/ZSharp.Compiler/features/ir/IR.Definition.cs b/ZSharp.Compiler/features/ir/services/IR.Definition.cs similarity index 94% rename from ZSharp.Compiler/features/ir/IR.Definition.cs rename to ZSharp.Compiler/features/ir/services/IR.Definition.cs index e8e5050d..68b63b93 100644 --- a/ZSharp.Compiler/features/ir/IR.Definition.cs +++ b/ZSharp.Compiler/features/ir/services/IR.Definition.cs @@ -1,5 +1,4 @@ -using CommonZ; -using IRDefinitionResult = ZSharp.Compiler.Result; +using IRDefinitionResult = ZSharp.Compiler.Result; namespace ZSharp.Compiler { diff --git a/ZSharp.Compiler/features/ir/IR.Reference.cs b/ZSharp.Compiler/features/ir/services/IR.Reference.cs similarity index 100% rename from ZSharp.Compiler/features/ir/IR.Reference.cs rename to ZSharp.Compiler/features/ir/services/IR.Reference.cs diff --git a/ZSharp.Compiler/features/ir/IR.Type.cs b/ZSharp.Compiler/features/ir/services/IR.Type.cs similarity index 100% rename from ZSharp.Compiler/features/ir/IR.Type.cs rename to ZSharp.Compiler/features/ir/services/IR.Type.cs diff --git a/ZSharp.Compiler/ir generator/protocols/ICompileIRCode.cs b/ZSharp.Compiler/ir generator/protocols/ICompileIRCode.cs index fe879117..b5c9bb0a 100644 --- a/ZSharp.Compiler/ir generator/protocols/ICompileIRCode.cs +++ b/ZSharp.Compiler/ir generator/protocols/ICompileIRCode.cs @@ -1,7 +1,10 @@ namespace ZSharp.Compiler { - public interface ICompileIRCode + public interface ICompileIRCode : ICTCompileIRCode { - public IRCode CompileIRCode(Compiler compiler); + Result ICTCompileIRCode.CompileIRCode(Compiler compiler) + => Result.Ok(CompileIRCode(compiler)); + + public new IRCode CompileIRCode(Compiler compiler); } } diff --git a/ZSharp.Interpreter/Interpreter.cs b/ZSharp.Interpreter/Interpreter.cs deleted file mode 100644 index 595b682f..00000000 --- a/ZSharp.Interpreter/Interpreter.cs +++ /dev/null @@ -1,50 +0,0 @@ -namespace ZSharp.Interpreter -{ - public class Interpreter - { - public IHostLoader HostLoader { get; set; } = null!; - - public IRuntime Runtime { get; set; } = null!; - - public IR.RuntimeModule RuntimeModule { get; } - - public Compiler.Compiler Compiler { get; init; } - - public Compiler.IRLoader.IRLoader CompilerIRLoader { get; } - - public ZSSourceCompiler.ZSSourceCompiler SourceCompiler { get; init; } - - public Parser.ZSharpParser Parser { get; init; } - - public Interpreter(IR.RuntimeModule? runtimeModule = null) - { - RuntimeModule = runtimeModule ?? IR.RuntimeModule.Standard; - - Compiler = new(RuntimeModule); - - new Compiler.Ops(Compiler); - - CompilerIRLoader = new(Compiler); - SourceCompiler = new(Compiler); - - Parser = new(); - - Compiler.Evaluators.Add(new ZSSourceEvaluator(SourceCompiler)); - } - - public ZSSourceCompiler.Document CompileFile(string path) - { - AST.Document document; - - using (var reader = new StreamReader(path)) - document = Parser.Parse(new(Tokenizer.Tokenizer.Tokenize(new(reader)))); - - return CompileDocument(document, path); - } - - public ZSSourceCompiler.Document CompileDocument(AST.Document document, string path) - { - return SourceCompiler.CreateDocumentCompiler(document, path).Compile(); - } - } -} diff --git a/ZSharp.Interpreter/ZSSourceEvaluator.cs b/ZSharp.Interpreter/ZSSourceEvaluator.cs deleted file mode 100644 index 42f8a8a0..00000000 --- a/ZSharp.Interpreter/ZSSourceEvaluator.cs +++ /dev/null @@ -1,27 +0,0 @@ -using ZSharp.Compiler; -using ZSharp.Objects; - -namespace ZSharp.Interpreter -{ - internal sealed class ZSSourceEvaluator(ZSSourceCompiler.ZSSourceCompiler sourceCompiler) : Compiler.Evaluator - { - private readonly ZSSourceCompiler.ZSSourceCompiler sourceCompiler = sourceCompiler; - - public override Result Evaluate(CompilerObject @object) - { - if (@object is not ZSSourceCompiler.NodeObject nodeObject) - return Result.Ok(@object); - - if (nodeObject.Node is AST.Expression expression) - return Result.Ok( - sourceCompiler.CompileNode(expression).Unwrap() - ); - if (nodeObject.Node is AST.Statement statement) - return Result.Ok( - sourceCompiler.CompileNode(statement).Unwrap() - ); - - return Result.Ok(@object); - } - } -} diff --git a/ZSharp.Interpreter/ZSharp.Interpreter.csproj b/ZSharp.Interpreter/ZSharp.Interpreter.csproj index ad7155bd..90a06527 100644 --- a/ZSharp.Interpreter/ZSharp.Interpreter.csproj +++ b/ZSharp.Interpreter/ZSharp.Interpreter.csproj @@ -12,9 +12,9 @@ + - diff --git a/ZSharp.Interpreter/IHostLoader.cs b/ZSharp.Interpreter/interpreter/IHostLoader.cs similarity index 100% rename from ZSharp.Interpreter/IHostLoader.cs rename to ZSharp.Interpreter/interpreter/IHostLoader.cs diff --git a/ZSharp.Interpreter/interpreter/Interpreter.cs b/ZSharp.Interpreter/interpreter/Interpreter.cs new file mode 100644 index 00000000..c1d58645 --- /dev/null +++ b/ZSharp.Interpreter/interpreter/Interpreter.cs @@ -0,0 +1,87 @@ +using ZSharp.Compiler; + +namespace ZSharp.Interpreter +{ + public class Interpreter + { + public Runtime.NET.Runtime HostLoader => Runtime; + + public Runtime.NET.Runtime Runtime { get; } + + public IR.RuntimeModule RuntimeModule { get; } + + public Compiler.Compiler Compiler { get; init; } + + public Compiler.IRLoader.IRLoader CompilerIRLoader { get; } + + public ZSSourceCompiler.ZSSourceCompiler SourceCompiler { get; init; } + + public Parser.ZSharpParser Parser { get; init; } + + public Interpreter(IR.RuntimeModule? runtimeModule = null) + { + RuntimeModule = runtimeModule ?? IR.RuntimeModule.Standard; + + Compiler = new(RuntimeModule); + Runtime = new(RuntimeModule); + + new Ops(Compiler); + + CompilerIRLoader = new(Compiler); + SourceCompiler = new(this); + + Parser = new(); + } + + public ZSSourceCompiler.Document CompileFile(string path) + { + AST.Document document; + + using (var reader = new StreamReader(path)) + document = Parser.Parse(new(Tokenizer.Tokenizer.Tokenize(new(reader)))); + + return CompileDocument(document, path); + } + + public ZSSourceCompiler.Document CompileDocument(AST.Document document, string path) + { + return SourceCompiler.CreateDocumentCompiler(document, path).Compile(); + } + + public Result Evaluate(Expression expression) + { + if ( + SourceCompiler.CompileNode(expression) + .When(out var result) + .IsError + ) return Result.Error(string.Empty); + + return Evaluate(result!); + } + + public Result Evaluate(CompilerObject @object) + { + if ( + Compiler.IR.CompileCode(@object) + .When(out var irCode) + .Error(out var error) + ) + return Result.Ok(@object); + + var result = Runtime.Evaluator.EvaluateCT(irCode ?? throw new(), Compiler); + + if (irCode.IsVoid) + return Result + .Ok(new Objects.RawCode(new())); + + if (result is null) + return Result + .Ok(@object); + // TODO: should actually be an error! + //return Result + // .Error("Non-void expression evaluated to nothing"); + + return Result.Ok(result); + } + } +} diff --git a/ZSharp.Interpreter/rt/IRuntime.cs b/ZSharp.Interpreter/interpreter/rt/IRuntime.cs similarity index 100% rename from ZSharp.Interpreter/rt/IRuntime.cs rename to ZSharp.Interpreter/interpreter/rt/IRuntime.cs diff --git a/ZSharp.ZSSourceCompiler/GlobalUsings.cs b/ZSharp.Interpreter/source-compiler/GlobalUsings.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/GlobalUsings.cs rename to ZSharp.Interpreter/source-compiler/GlobalUsings.cs diff --git a/ZSharp.ZSSourceCompiler/HelperFunctions.cs b/ZSharp.Interpreter/source-compiler/HelperFunctions.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/HelperFunctions.cs rename to ZSharp.Interpreter/source-compiler/HelperFunctions.cs diff --git a/ZSharp.ZSSourceCompiler/NodeLogOrigin.cs b/ZSharp.Interpreter/source-compiler/NodeLogOrigin.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/NodeLogOrigin.cs rename to ZSharp.Interpreter/source-compiler/NodeLogOrigin.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/capabilities/IMultipassCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/capabilities/IMultipassCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/capabilities/IMultipassCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/capabilities/IMultipassCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/class body/ClassBodyCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/class body/ClassBodyCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/class body/ClassBodyCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/class body/ConstructorCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/class body/ConstructorCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/class body/ConstructorCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/class body/MethodCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/class body/MethodCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/class body/MethodCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.Compile.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.Compile.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.Compile.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.Compile.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.cs similarity index 78% rename from ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.cs index e7e5835f..6d537edf 100644 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/document/compiler/DocumentCompiler.cs +++ b/ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.cs @@ -30,13 +30,12 @@ private void CompileDocument() return expressionStatement.Expression switch { Module => null, - Expression expression => ObjectResult.Ok( - Compiler.Compiler.Feature().EvaluateCO( - Compiler.Compiler.IR.CompileCode( - Compiler.CompileNode(expression).Unwrap() - ).Unwrap() - ) ?? new Objects.RawCode(new()) - ), + Expression expression => + Compiler.Interpreter.Evaluate( + expression + ).When(out var result).Error(out var error) + ? Compiler.CompilationError(error, expression) + : ObjectResult.Ok(result!) }; return null; diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/document/objects/Document.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/document/objects/Document.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/document/objects/Document.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/document/objects/Document.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/module/ClassCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/module/ClassCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/module/ClassCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/module/FunctionCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/module/FunctionCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/module/FunctionCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/module/ModuleCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/module/ModuleCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/module/ModuleCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/Case.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/Case.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/Case.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/Case.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/ForLoop.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/ForLoop.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/ForLoop.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/ForLoop.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/If.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/If.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/If.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/If.cs diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/WhileLoop.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/builtin-compilers/runtime code/objects/WhileLoop.cs rename to ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/WhileLoop.cs diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Compilers.cs b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Compilers.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Compilers.cs rename to ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Compilers.cs diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.ImportSystem.cs b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.ImportSystem.cs similarity index 62% rename from ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.ImportSystem.cs rename to ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.ImportSystem.cs index 6c40c2fd..f18fc68b 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.ImportSystem.cs +++ b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.ImportSystem.cs @@ -4,10 +4,10 @@ public partial class ZSSourceCompiler { public ImportSystem ImportSystem { get; } = new(); - public StringImporter StringImporter { get; } = new(); + public StringImporter StringImporter { get; } - public StandardLibraryImporter StandardLibraryImporter { get; } = new(); + public StandardLibraryImporter StandardLibraryImporter { get; } - public ZSImporter ZSImporter { get; } = new(); + public ZSImporter ZSImporter { get; } } } diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Initialize.cs b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Initialize.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Initialize.cs rename to ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Initialize.cs diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Logging.cs b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Logging.cs similarity index 85% rename from ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Logging.cs rename to ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Logging.cs index 1794c196..64c2e08b 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Logging.cs +++ b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Logging.cs @@ -2,7 +2,7 @@ namespace ZSharp.ZSSourceCompiler { - public sealed partial class ZSSourceCompiler : Feature + public sealed partial class ZSSourceCompiler { public void LogError(string message, Node origin) where T : class diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.OOP.cs b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.OOP.cs similarity index 65% rename from ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.OOP.cs rename to ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.OOP.cs index 364590d5..ed59c06b 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.OOP.cs +++ b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.OOP.cs @@ -1,6 +1,6 @@ namespace ZSharp.ZSSourceCompiler { - public sealed partial class ZSSourceCompiler : Compiler.Feature + public sealed partial class ZSSourceCompiler { public Objects.ClassMetaClass DefaultMetaClass { get; set; } = new(); } diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Operators.cs b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Operators.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.Operators.cs rename to ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Operators.cs diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.ResultTools.cs b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.ResultTools.cs similarity index 88% rename from ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.ResultTools.cs rename to ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.ResultTools.cs index 051b8286..78cdc826 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.ResultTools.cs +++ b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.ResultTools.cs @@ -2,7 +2,7 @@ namespace ZSharp.ZSSourceCompiler { - public sealed partial class ZSSourceCompiler : Compiler.Feature + public sealed partial class ZSSourceCompiler { public bool UnpackResult( Compiler.Result result, diff --git a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.cs similarity index 81% rename from ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs rename to ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.cs index 913d526e..842a3a09 100644 --- a/ZSharp.ZSSourceCompiler/compiler/ZSSourceCompiler.cs +++ b/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.cs @@ -2,23 +2,32 @@ namespace ZSharp.ZSSourceCompiler { - public sealed partial class ZSSourceCompiler : Compiler.Feature + public sealed partial class ZSSourceCompiler { + public Interpreter.Interpreter Interpreter { get; } + + public Compiler.Compiler Compiler => Interpreter.Compiler; + public ExpressionCompiler ExpressionCompiler { get; } public StatementCompiler StatementCompiler { get; } public Context Context { get; } - public ZSSourceCompiler(Compiler.Compiler compiler) - : base(compiler) + public ZSSourceCompiler(Interpreter.Interpreter interpreter) { + Interpreter = interpreter; + Context = new(this); ExpressionCompiler = new(this); StatementCompiler = new(this); - Operators = compiler.Feature(); + Operators = Compiler.Feature(); + + StringImporter = new(interpreter); + StandardLibraryImporter = new(interpreter); + ZSImporter = new(interpreter); Initialize(); } diff --git a/ZSharp.ZSSourceCompiler/context/Context.Compilers.cs b/ZSharp.Interpreter/source-compiler/context/Context.Compilers.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/context/Context.Compilers.cs rename to ZSharp.Interpreter/source-compiler/context/Context.Compilers.cs diff --git a/ZSharp.ZSSourceCompiler/context/Context.Nodes.cs b/ZSharp.Interpreter/source-compiler/context/Context.Nodes.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/context/Context.Nodes.cs rename to ZSharp.Interpreter/source-compiler/context/Context.Nodes.cs diff --git a/ZSharp.ZSSourceCompiler/context/Context.Scopes.cs b/ZSharp.Interpreter/source-compiler/context/Context.Scopes.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/context/Context.Scopes.cs rename to ZSharp.Interpreter/source-compiler/context/Context.Scopes.cs diff --git a/ZSharp.ZSSourceCompiler/context/Context.cs b/ZSharp.Interpreter/source-compiler/context/Context.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/context/Context.cs rename to ZSharp.Interpreter/source-compiler/context/Context.cs diff --git a/ZSharp.ZSSourceCompiler/contexts/capabilities/IMemoryAllocator.cs b/ZSharp.Interpreter/source-compiler/contexts/capabilities/IMemoryAllocator.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/contexts/capabilities/IMemoryAllocator.cs rename to ZSharp.Interpreter/source-compiler/contexts/capabilities/IMemoryAllocator.cs diff --git a/ZSharp.ZSSourceCompiler/contexts/capabilities/IObjectContext.cs b/ZSharp.Interpreter/source-compiler/contexts/capabilities/IObjectContext.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/contexts/capabilities/IObjectContext.cs rename to ZSharp.Interpreter/source-compiler/contexts/capabilities/IObjectContext.cs diff --git a/ZSharp.ZSSourceCompiler/contexts/capabilities/scope/ILookupContext.cs b/ZSharp.Interpreter/source-compiler/contexts/capabilities/scope/ILookupContext.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/contexts/capabilities/scope/ILookupContext.cs rename to ZSharp.Interpreter/source-compiler/contexts/capabilities/scope/ILookupContext.cs diff --git a/ZSharp.ZSSourceCompiler/contexts/capabilities/scope/IScopeContext.cs b/ZSharp.Interpreter/source-compiler/contexts/capabilities/scope/IScopeContext.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/contexts/capabilities/scope/IScopeContext.cs rename to ZSharp.Interpreter/source-compiler/contexts/capabilities/scope/IScopeContext.cs diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/ClassContext.cs b/ZSharp.Interpreter/source-compiler/contexts/concrete/ClassContext.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/contexts/concrete/ClassContext.cs rename to ZSharp.Interpreter/source-compiler/contexts/concrete/ClassContext.cs diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/ExpressionContext.cs b/ZSharp.Interpreter/source-compiler/contexts/concrete/ExpressionContext.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/contexts/concrete/ExpressionContext.cs rename to ZSharp.Interpreter/source-compiler/contexts/concrete/ExpressionContext.cs diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/FunctionContext.cs b/ZSharp.Interpreter/source-compiler/contexts/concrete/FunctionContext.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/contexts/concrete/FunctionContext.cs rename to ZSharp.Interpreter/source-compiler/contexts/concrete/FunctionContext.cs diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/ObjectContext.cs b/ZSharp.Interpreter/source-compiler/contexts/concrete/ObjectContext.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/contexts/concrete/ObjectContext.cs rename to ZSharp.Interpreter/source-compiler/contexts/concrete/ObjectContext.cs diff --git a/ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs b/ZSharp.Interpreter/source-compiler/contexts/concrete/ScopeContext.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/contexts/concrete/ScopeContext.cs rename to ZSharp.Interpreter/source-compiler/contexts/concrete/ScopeContext.cs diff --git a/ZSharp.ZSSourceCompiler/contexts/strategies/UntilContextTypeStrategy.cs b/ZSharp.Interpreter/source-compiler/contexts/strategies/UntilContextTypeStrategy.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/contexts/strategies/UntilContextTypeStrategy.cs rename to ZSharp.Interpreter/source-compiler/contexts/strategies/UntilContextTypeStrategy.cs diff --git a/ZSharp.ZSSourceCompiler/core-compilers/DefaultContextCompiler.cs b/ZSharp.Interpreter/source-compiler/core-compilers/DefaultContextCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/core-compilers/DefaultContextCompiler.cs rename to ZSharp.Interpreter/source-compiler/core-compilers/DefaultContextCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.Literals.cs b/ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.Literals.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.Literals.cs rename to ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.Literals.cs diff --git a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.cs similarity index 97% rename from ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs rename to ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.cs index 2c32e17b..8d2282bd 100644 --- a/ZSharp.ZSSourceCompiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.cs @@ -61,7 +61,7 @@ private ObjectResult Compile(BinaryExpression binary) private ObjectResult Compile(CallExpression call) { - var callable = Compiler.Compiler.Evaluate(Compiler.CompileNode(call.Callee).Unwrap()); + var callable = Compiler.CompileNode(call.Callee).Unwrap(); var args = call.Arguments.Select(arg => new Argument_NEW(arg.Name, Compiler.CompileNode(arg.Value).Unwrap())); @@ -123,7 +123,7 @@ private ObjectResult Compile(IdentifierExpression identifier) private ObjectResult Compile(IndexExpression index) { - var indexable = Compiler.Compiler.Evaluate(Compiler.CompileNode(index.Target).Unwrap()); + var indexable = Compiler.CompileNode(index.Target).Unwrap(); var args = index.Arguments.Select(arg => new Argument_NEW(arg.Name, Compiler.CompileNode(arg.Value).Unwrap())); diff --git a/ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs b/ZSharp.Interpreter/source-compiler/core-compilers/statement/StatementCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/core-compilers/statement/StatementCompiler.cs rename to ZSharp.Interpreter/source-compiler/core-compilers/statement/StatementCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/extensibility/CompilerBase.cs b/ZSharp.Interpreter/source-compiler/extensibility/CompilerBase.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/extensibility/CompilerBase.cs rename to ZSharp.Interpreter/source-compiler/extensibility/CompilerBase.cs diff --git a/ZSharp.ZSSourceCompiler/extensibility/ContextCompiler.cs b/ZSharp.Interpreter/source-compiler/extensibility/ContextCompiler.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/extensibility/ContextCompiler.cs rename to ZSharp.Interpreter/source-compiler/extensibility/ContextCompiler.cs diff --git a/ZSharp.ZSSourceCompiler/extensibility/error/Error.cs b/ZSharp.Interpreter/source-compiler/extensibility/error/Error.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/extensibility/error/Error.cs rename to ZSharp.Interpreter/source-compiler/extensibility/error/Error.cs diff --git a/ZSharp.ZSSourceCompiler/extensibility/error/errors/CombinedCompilationError.cs b/ZSharp.Interpreter/source-compiler/extensibility/error/errors/CombinedCompilationError.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/extensibility/error/errors/CombinedCompilationError.cs rename to ZSharp.Interpreter/source-compiler/extensibility/error/errors/CombinedCompilationError.cs diff --git a/ZSharp.ZSSourceCompiler/extensibility/error/errors/CompilationError.cs b/ZSharp.Interpreter/source-compiler/extensibility/error/errors/CompilationError.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/extensibility/error/errors/CompilationError.cs rename to ZSharp.Interpreter/source-compiler/extensibility/error/errors/CompilationError.cs diff --git a/ZSharp.ZSSourceCompiler/extensibility/oop/ClassSpecification.cs b/ZSharp.Interpreter/source-compiler/extensibility/oop/ClassSpecification.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/extensibility/oop/ClassSpecification.cs rename to ZSharp.Interpreter/source-compiler/extensibility/oop/ClassSpecification.cs diff --git a/ZSharp.ZSSourceCompiler/extensibility/overrides/IOverrideCompileExpression.cs b/ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileExpression.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/extensibility/overrides/IOverrideCompileExpression.cs rename to ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileExpression.cs diff --git a/ZSharp.ZSSourceCompiler/extensibility/overrides/IOverrideCompileNode.cs b/ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileNode.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/extensibility/overrides/IOverrideCompileNode.cs rename to ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileNode.cs diff --git a/ZSharp.ZSSourceCompiler/extensibility/overrides/IOverrideCompileStatement.cs b/ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileStatement.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/extensibility/overrides/IOverrideCompileStatement.cs rename to ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileStatement.cs diff --git a/ZSharp.ZSSourceCompiler/import system/ImportSystem.cs b/ZSharp.Interpreter/source-compiler/import system/ImportSystem.cs similarity index 100% rename from ZSharp.ZSSourceCompiler/import system/ImportSystem.cs rename to ZSharp.Interpreter/source-compiler/import system/ImportSystem.cs diff --git a/ZSharp.ZSSourceCompiler/import system/importers/StandardLibraryImporter.cs b/ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs similarity index 82% rename from ZSharp.ZSSourceCompiler/import system/importers/StandardLibraryImporter.cs rename to ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs index f588e2e5..0c6aba55 100644 --- a/ZSharp.ZSSourceCompiler/import system/importers/StandardLibraryImporter.cs +++ b/ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs @@ -3,7 +3,7 @@ namespace ZSharp.ZSSourceCompiler { - public sealed class StandardLibraryImporter + public sealed class StandardLibraryImporter(Interpreter.Interpreter interpreter) : CompilerObject , ICTCallable { @@ -17,7 +17,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) if ( arguments.Length > 1 || arguments[0].Name is not null || - !compiler.IsString(compiler.Evaluate(arguments[0].Object), out var libraryName) + !compiler.IsString(interpreter.Evaluate(arguments[0].Object).Unwrap(), out var libraryName) ) { compiler.Log.Error("`std` importer must have exactly 1 argument of type `string`", this); diff --git a/ZSharp.ZSSourceCompiler/import system/importers/StringImporter.cs b/ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs similarity index 86% rename from ZSharp.ZSSourceCompiler/import system/importers/StringImporter.cs rename to ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs index ef91fcbc..794513e4 100644 --- a/ZSharp.ZSSourceCompiler/import system/importers/StringImporter.cs +++ b/ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs @@ -3,7 +3,7 @@ namespace ZSharp.ZSSourceCompiler { - public sealed class StringImporter + public sealed class StringImporter(Interpreter.Interpreter interpreter) : CompilerObject , ICTCallable { @@ -15,7 +15,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) { Argument sourceArgument = arguments.FirstOrDefault(arg => arg.Name is null) ?? throw new(); - if (!compiler.IsString(compiler.Evaluate(sourceArgument.Object), out var source)) + if (!compiler.IsString(interpreter.Evaluate(sourceArgument.Object).Unwrap(), out var source)) throw new(); // TODO: proper exception: first parameter must be a string string[] parts = source.Split(':', 2); diff --git a/ZSharp.ZSSourceCompiler/import system/importers/ZSImporter.cs b/ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs similarity index 83% rename from ZSharp.ZSSourceCompiler/import system/importers/ZSImporter.cs rename to ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs index b1d4db96..a36571af 100644 --- a/ZSharp.ZSSourceCompiler/import system/importers/ZSImporter.cs +++ b/ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs @@ -3,7 +3,7 @@ namespace ZSharp.ZSSourceCompiler { - public sealed class ZSImporter + public sealed class ZSImporter(Interpreter.Interpreter interpreter) : CompilerObject , ICTCallable { @@ -17,7 +17,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) if ( arguments.Length > 1 || arguments[0].Name is not null || - !compiler.IsString(compiler.Evaluate(arguments[0].Object), out var libraryName) + !compiler.IsString(interpreter.Evaluate(arguments[0].Object).Unwrap(), out var libraryName) ) { compiler.Log.Error("`zs` importer must have exactly 1 argument of type `string`", this); diff --git a/ZSharp.Parser/ZSharp.Parser.csproj b/ZSharp.Parser/ZSharp.Parser.csproj index ecc964da..4504d1e5 100644 --- a/ZSharp.Parser/ZSharp.Parser.csproj +++ b/ZSharp.Parser/ZSharp.Parser.csproj @@ -11,7 +11,7 @@ - + diff --git a/ZSharp.Runtime.IL/IRCodeEvaluator.cs b/ZSharp.Runtime.IL/IRCodeEvaluator.cs index 621521d4..02f25322 100644 --- a/ZSharp.Runtime.IL/IRCodeEvaluator.cs +++ b/ZSharp.Runtime.IL/IRCodeEvaluator.cs @@ -1,86 +1,19 @@ -//using ZSharp.Interop.IR2IL; -using ZSharp.Compiler; +using ZSharp.Compiler; using ZSharp.Objects; -using ZSharp.Runtime.NET.IR2IL; - -//using IL = System.Reflection.Emit; - namespace ZSharp.Runtime.NET { - internal sealed class IRCodeEvaluator(Runtime runtime) - : Compiler.Evaluator - , Compiler.IIREvaluator + public sealed class IRCodeEvaluator(Runtime runtime) { private readonly Runtime runtime = runtime; - private Interpreter.Interpreter Interpreter => runtime.Interpreter; - - public override Result Evaluate(CompilerObject @object) - { - if (@object is not RawCode rawCode) - return Result.Ok(@object); - - var code = rawCode.Code; - - var module = new IR.Module(""); - - var function = new IR.Function(Interpreter.Compiler.CompileIRType(code.RequireValueType())) - { - Name = "evaluate" - }; - - foreach (var m in code.Instructions - .Select(i => - i is IR.VM.IHasOperand hasOperand - && hasOperand.Operand is IR.IRObject ir - ? ir.Module : null) - .Where(i => i is not null) - ) - Interpreter.Runtime.Import(m!); - - function.Body.Instructions.AddRange([ - .. code.Instructions, - new IR.VM.Return() - ]); - - module.Functions.Add(function); - - var functionIL = runtime.Import(module).GetType("")!.GetMethod(function.Name)!; - var value = functionIL.Invoke(null, null); - - if (value is CompilerObject co) - return Result.Ok(co); - - if (value is ICompileTime coObject) - return Result.Ok(coObject.GetCO()); - - //if (value is Type type) - // return new RawType(interpreter.IRInterop.ImportILType(type), interpreter.Compiler.TypeSystem.Type); - - throw new NotImplementedException(); - } - - private void CompileGetObject(ICodeLoader loader, IR.VM.GetObject get) - { - - if (get.IR is IR.IType type) - { - loader.Output.Emit(IL.Emit.OpCodes.Ldtoken, runtime.Import(type)); - //loader.Output.Emit() - loader.Push(typeof(Type)); - } - - else throw new NotImplementedException(); - } - - public CompilerObject? EvaluateCT(IRCode code) + public CompilerObject? EvaluateCT(IRCode code, Compiler.Compiler compiler) { IL.Emit.DynamicMethod method = new( string.Empty, runtime.irLoader.LoadType( - runtime.Interpreter.Compiler.IR.CompileType( - code.RequireValueType(runtime.Interpreter.Compiler.TypeSystem.Void) + compiler.IR.CompileType( + code.RequireValueType(compiler.TypeSystem.Void) ).Unwrap() ), null @@ -103,7 +36,7 @@ private void CompileGetObject(ICodeLoader loader, IR.VM.GetObject get) if (result is ICompileTime coObject) return coObject.GetCO(); - throw new NotImplementedException(); + return null; } } } diff --git a/ZSharp.Runtime.IL/Runtime.cs b/ZSharp.Runtime.IL/Runtime.cs index 524bde56..dddc42eb 100644 --- a/ZSharp.Runtime.IL/Runtime.cs +++ b/ZSharp.Runtime.IL/Runtime.cs @@ -3,8 +3,6 @@ namespace ZSharp.Runtime.NET { public class Runtime - : Interpreter.IRuntime - , Interpreter.IHostLoader { internal readonly IL2IR.ILLoader ilLoader; internal readonly IR2IL.IRLoader irLoader; @@ -13,56 +11,38 @@ public class Runtime public Context Context { get; } = new(); - public Interpreter.Interpreter Interpreter { get; } - public Hooks Hooks { get; } = new(); - public Runtime(Interpreter.Interpreter interpreter) - { - Interpreter = interpreter; - - ilLoader = new(Context, interpreter.RuntimeModule); - irLoader = new(Context, interpreter.RuntimeModule); + public IRCodeEvaluator Evaluator { get; } - var irCompiler = new Compiler.IRCompiler(interpreter.Compiler); - var irEvaluator = new IRCodeEvaluator(this); + public IR.RuntimeModule RuntimeModule { get; } - irCompiler.Evaluator = irEvaluator; + public Runtime(IR.RuntimeModule runtimeModule) + { + RuntimeModule = runtimeModule; - interpreter.Compiler.Evaluators.Add(irEvaluator); + ilLoader = new(Context, runtimeModule); + irLoader = new(Context, runtimeModule); - irLoader.GetObjectFunction = (loader, get) => - { - if (get.IR is IR.IType type) - { - loader.Output.Emit(IL.Emit.OpCodes.Ldtoken, Import(type)); - loader.Output.Emit(IL.Emit.OpCodes.Call, Utils.GetMethod(Type.GetTypeFromHandle)); - loader.Output.Emit(IL.Emit.OpCodes.Call, Hooks.GetObject); - - loader.Push(typeof(object)); - } - }; + Evaluator = new(this); foreach (var (ir, il) in new (IR.IType, Type)[] { - (interpreter.RuntimeModule.TypeSystem.Type, typeof(TypeObject)), + (runtimeModule.TypeSystem.Type, typeof(TypeObject)), - (interpreter.RuntimeModule.TypeSystem.Void, typeof(void)), - (interpreter.RuntimeModule.TypeSystem.Boolean, typeof(bool)), + (runtimeModule.TypeSystem.Void, typeof(void)), + (runtimeModule.TypeSystem.Boolean, typeof(bool)), - (interpreter.RuntimeModule.TypeSystem.Int32, typeof(int)), + (runtimeModule.TypeSystem.Int32, typeof(int)), - (interpreter.RuntimeModule.TypeSystem.Float32, typeof(float)), + (runtimeModule.TypeSystem.Float32, typeof(float)), - (interpreter.RuntimeModule.TypeSystem.Object, typeof(object)), - (interpreter.RuntimeModule.TypeSystem.String, typeof(string)), + (runtimeModule.TypeSystem.Object, typeof(object)), + (runtimeModule.TypeSystem.String, typeof(string)), }) Context.Cache(ir, il); } - void Interpreter.IRuntime.Import(IR.Module module) - => Import(module); - public IL.Module Import(IR.Module module) { if (!Context.Cache(module, out var result)) @@ -96,13 +76,6 @@ public IR.Function Import(IL.MethodInfo method) public object GetObject(Type type) { throw new NotSupportedException(); - if (typeObjects.Cache(type, out var result)) - return result; - - var ir = ilLoader.LoadType(type); - var co = Interpreter.CompilerIRLoader.Import(ir); - - //return typeObjects.Cache(type, new TypeObject(type, ir)); } } } diff --git a/ZSharp.Runtime.IL/ZSharp.Runtime.IL.csproj b/ZSharp.Runtime.IL/ZSharp.Runtime.IL.csproj index 34efc948..a0d88f59 100644 --- a/ZSharp.Runtime.IL/ZSharp.Runtime.IL.csproj +++ b/ZSharp.Runtime.IL/ZSharp.Runtime.IL.csproj @@ -7,7 +7,7 @@ - + diff --git a/ZSharp.Text/Token.cs b/ZSharp.Tokenizer/Token.cs similarity index 100% rename from ZSharp.Text/Token.cs rename to ZSharp.Tokenizer/Token.cs diff --git a/ZSharp.Text/TokenType.cs b/ZSharp.Tokenizer/TokenType.cs similarity index 100% rename from ZSharp.Text/TokenType.cs rename to ZSharp.Tokenizer/TokenType.cs diff --git a/ZSharp.ZSSourceCompiler/NodeObject.cs b/ZSharp.ZSSourceCompiler/NodeObject.cs deleted file mode 100644 index 210b98ce..00000000 --- a/ZSharp.ZSSourceCompiler/NodeObject.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.ZSSourceCompiler -{ - public sealed class NodeObject(Node node) : CompilerObject - { - public Node Node { get; } = node; - } -} diff --git a/ZSharp.ZSSourceCompiler/ZSharp.ZSSourceCompiler.csproj b/ZSharp.ZSSourceCompiler/ZSharp.ZSSourceCompiler.csproj deleted file mode 100644 index 79084374..00000000 --- a/ZSharp.ZSSourceCompiler/ZSharp.ZSSourceCompiler.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - - - diff --git a/ZSharp.ZSSourceCompiler/builtin-compilers/document/objects/DocumentValue.cs b/ZSharp.ZSSourceCompiler/builtin-compilers/document/objects/DocumentValue.cs deleted file mode 100644 index 56c147b6..00000000 --- a/ZSharp.ZSSourceCompiler/builtin-compilers/document/objects/DocumentValue.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace ZSharp.ZSSourceCompiler -{ - public sealed class DocumentValue(string name, CompilerObject value) - : CompilerObject - , Compiler.ICTAssignable - , Compiler.IEvaluable - { - public string Name { get; } = name; - - public CompilerObject Value { get; set; } = value; - - public bool IsReadOnly { get; set; } - - CompilerObject Compiler.ICTAssignable.Assign(Compiler.Compiler compiler, CompilerObject value) - => IsReadOnly ? throw new InvalidOperationException() : Value = compiler.Evaluate(value); - - public CompilerObject Evaluate(Compiler.Compiler compiler) - => Value; - - } -} diff --git a/ZSharpTest/DotNETImporter.cs b/ZSharpTest/DotNETImporter.cs index 5bfe563f..8be0570a 100644 --- a/ZSharpTest/DotNETImporter.cs +++ b/ZSharpTest/DotNETImporter.cs @@ -19,7 +19,7 @@ public Objects.CompilerObject Call(Compiler.Compiler compiler, Argument[] argume if ( arguments.Length > 1 || arguments[0].Name is not null || - !compiler.IsString(compiler.Evaluate(arguments[0].Object), out var libraryName) + !compiler.IsString(interpreter.Evaluate(arguments[0].Object).Unwrap(), out var libraryName) ) { compiler.Log.Error("`net` importer must have exactly 1 argument of type `string`", this); diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index 199533d1..165fec8c 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -138,13 +138,7 @@ new Referencing(interpreter.Compiler); new OOP(interpreter.Compiler); -ZSharp.Runtime.NET.Runtime runtime = new(interpreter); - -interpreter.Runtime = runtime; -interpreter.HostLoader = runtime; - -ZS.RuntimeAPI.Fields_Globals.runtime = runtime; -runtime.Hooks.GetObject = ZSharp.Runtime.NET.Utils.GetMethod(ZS.RuntimeAPI.Impl_Globals.GetObject); +var runtime = interpreter.Runtime; var moduleIL_standardIO = typeof(Standard.IO.Impl_Globals).Module; var moduleIR_standardIO = interpreter.HostLoader.Import(moduleIL_standardIO); From 512e0c8c2f5b83ce5ddf7eca1c03df96cf366565 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 18 Jul 2025 15:02:25 +0300 Subject: [PATCH 177/235] Add new runtime --- .../il2ir/loaders/EnumerationLoader.cs | 42 ++++ .../il2ir/loaders/LiteralLoader.cs | 109 +++++++++ .../il2ir/loaders/ValueTypeLoader.cs | 230 ++++++++++++++++++ ZSharp.Runtime/GlobalUsings.cs | 1 + ZSharp.Runtime/ZSharp.Runtime.csproj | 13 + ZSharp.Runtime/loader/GlobalUsings.cs | 1 + .../loader/emit/EmitLoader.Standalone.cs | 9 + ZSharp.Runtime/loader/emit/EmitLoader.cs | 20 ++ .../loader/emit/load/EmitLoader.Load.Code.cs | 30 +++ .../emit/load/EmitLoader.Load.Function.cs | 81 ++++++ .../emit/load/EmitLoader.Load.Module.cs | 8 + .../emit/load/EmitLoader.Load.Type.Class.cs | 7 + .../emit/load/EmitLoader.Load.Type.Enum.cs | 7 + .../load/EmitLoader.Load.Type.Interface.cs | 7 + .../load/EmitLoader.Load.Type.ValueType.cs | 7 + .../loader/emit/load/EmitLoader.Load.Type.cs | 25 ++ ZSharp.Runtime/loader/loaders/LoaderBase.cs | 7 + .../loaders/class/ClassLoader.Context.cs | 9 + .../loader/loaders/class/ClassLoader.T.cs | 7 + .../loader/loaders/class/ClassLoader.Tasks.cs | 22 ++ .../loader/loaders/class/ClassLoader.cs | 16 ++ .../load/ClassLoader.Load.Constructor.cs | 22 ++ .../class/load/ClassLoader.Load.Field.cs | 17 ++ .../class/load/ClassLoader.Load.Generic.cs | 20 ++ .../class/load/ClassLoader.Load.Method.cs | 40 +++ .../class/load/ClassLoader.Load.Type.cs | 7 + .../loaders/class/load/ClassLoader.Load.cs | 60 +++++ .../code/code contexts/FunctionCodeContext.cs | 82 +++++++ .../code/code contexts/UnboundCodeContext.cs | 23 ++ .../loader/loaders/code/code/CodeCompiler.cs | 70 ++++++ .../code/branching/BranchingCodeCompiler.cs | 24 ++ .../code/branching/IBranchingCodeContext.cs | 10 + .../loaders/code/code/core/CodeStack.cs | 25 ++ .../loaders/code/code/core/ICodeContext.cs | 11 + .../code/code/frame/FrameCodeCompiler.cs | 73 ++++++ .../code/code/frame/IFrameCodeContext.cs | 10 + .../loader/loaders/code/code/frame/Local.cs | 11 + .../loaders/code/code/frame/Parameter.cs | 11 + .../code/functional/FunctionalCodeCompiler.cs | 34 +++ .../code/functional/IFunctionalCodeContext.cs | 8 + .../code/code/modular/ModularCodeCompiler.cs | 23 ++ .../code/code/object/OOPCodeCompiler.cs | 59 +++++ .../code/code/stack/StackCodeCompiler.cs | 82 +++++++ .../loaders/module/ModuleLoader.Tasks.cs | 13 + .../loader/loaders/module/ModuleLoader.cs | 28 +++ .../module/load/ModuleLoader.Load.Function.cs | 34 +++ .../module/load/ModuleLoader.Load.Global.cs | 16 ++ .../load/ModuleLoader.Load.Type.Class.cs | 19 ++ .../load/ModuleLoader.Load.Type.EnumClass.cs | 10 + .../load/ModuleLoader.Load.Type.Interface.cs | 10 + .../load/ModuleLoader.Load.Type.ValueType.cs | 10 + .../module/load/ModuleLoader.Load.Type.cs | 17 ++ .../loaders/module/load/ModuleLoader.Load.cs | 73 ++++++ ZSharp.Runtime/runtime/Runtime.IR.cs | 7 + ZSharp.Runtime/runtime/Runtime.Loader.cs | 7 + ZSharp.Runtime/runtime/Runtime.cs | 17 ++ .../runtime/cache/Runtime.Cache.Field.cs | 16 ++ .../runtime/cache/Runtime.Cache.Function.cs | 16 ++ .../runtime/cache/Runtime.Cache.Global.cs | 16 ++ .../runtime/cache/Runtime.Cache.Module.cs | 7 + .../runtime/cache/Runtime.Cache.Type.cs | 40 +++ .../runtime/import/Runtime.Import.Callable.cs | 19 ++ .../import/Runtime.Import.Constructor.cs | 45 ++++ .../runtime/import/Runtime.Import.Field.cs | 34 +++ .../runtime/import/Runtime.Import.Function.cs | 22 ++ .../runtime/import/Runtime.Import.Global.cs | 15 ++ .../runtime/import/Runtime.Import.Method.cs | 41 ++++ .../runtime/import/Runtime.Import.Module.cs | 13 + .../import/Runtime.Import.Type.Modified.cs | 29 +++ .../runtime/import/Runtime.Import.Type.cs | 54 ++++ .../runtime/load/Runtime.Load.Function.cs | 15 ++ .../runtime/load/Runtime.Load.Module.cs | 8 + .../runtime/load/Runtime.Load.Type.cs | 15 ++ ZSharp.Runtime/tasks/TaskManager.cs | 20 ++ 74 files changed, 2066 insertions(+) create mode 100644 ZSharp.Runtime.IL/il2ir/loaders/EnumerationLoader.cs create mode 100644 ZSharp.Runtime.IL/il2ir/loaders/LiteralLoader.cs create mode 100644 ZSharp.Runtime.IL/il2ir/loaders/ValueTypeLoader.cs create mode 100644 ZSharp.Runtime/GlobalUsings.cs create mode 100644 ZSharp.Runtime/ZSharp.Runtime.csproj create mode 100644 ZSharp.Runtime/loader/GlobalUsings.cs create mode 100644 ZSharp.Runtime/loader/emit/EmitLoader.Standalone.cs create mode 100644 ZSharp.Runtime/loader/emit/EmitLoader.cs create mode 100644 ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Code.cs create mode 100644 ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Function.cs create mode 100644 ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Module.cs create mode 100644 ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Class.cs create mode 100644 ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Enum.cs create mode 100644 ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Interface.cs create mode 100644 ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.ValueType.cs create mode 100644 ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs create mode 100644 ZSharp.Runtime/loader/loaders/LoaderBase.cs create mode 100644 ZSharp.Runtime/loader/loaders/class/ClassLoader.Context.cs create mode 100644 ZSharp.Runtime/loader/loaders/class/ClassLoader.T.cs create mode 100644 ZSharp.Runtime/loader/loaders/class/ClassLoader.Tasks.cs create mode 100644 ZSharp.Runtime/loader/loaders/class/ClassLoader.cs create mode 100644 ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Constructor.cs create mode 100644 ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Field.cs create mode 100644 ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Generic.cs create mode 100644 ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs create mode 100644 ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs create mode 100644 ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code contexts/FunctionCodeContext.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/CodeCompiler.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/branching/BranchingCodeCompiler.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/branching/IBranchingCodeContext.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/core/CodeStack.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/core/ICodeContext.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/frame/FrameCodeCompiler.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/frame/IFrameCodeContext.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/frame/Local.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/frame/Parameter.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/functional/IFunctionalCodeContext.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/modular/ModularCodeCompiler.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/object/OOPCodeCompiler.cs create mode 100644 ZSharp.Runtime/loader/loaders/code/code/stack/StackCodeCompiler.cs create mode 100644 ZSharp.Runtime/loader/loaders/module/ModuleLoader.Tasks.cs create mode 100644 ZSharp.Runtime/loader/loaders/module/ModuleLoader.cs create mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Function.cs create mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Global.cs create mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Class.cs create mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.EnumClass.cs create mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Interface.cs create mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.ValueType.cs create mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs create mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs create mode 100644 ZSharp.Runtime/runtime/Runtime.IR.cs create mode 100644 ZSharp.Runtime/runtime/Runtime.Loader.cs create mode 100644 ZSharp.Runtime/runtime/Runtime.cs create mode 100644 ZSharp.Runtime/runtime/cache/Runtime.Cache.Field.cs create mode 100644 ZSharp.Runtime/runtime/cache/Runtime.Cache.Function.cs create mode 100644 ZSharp.Runtime/runtime/cache/Runtime.Cache.Global.cs create mode 100644 ZSharp.Runtime/runtime/cache/Runtime.Cache.Module.cs create mode 100644 ZSharp.Runtime/runtime/cache/Runtime.Cache.Type.cs create mode 100644 ZSharp.Runtime/runtime/import/Runtime.Import.Callable.cs create mode 100644 ZSharp.Runtime/runtime/import/Runtime.Import.Constructor.cs create mode 100644 ZSharp.Runtime/runtime/import/Runtime.Import.Field.cs create mode 100644 ZSharp.Runtime/runtime/import/Runtime.Import.Function.cs create mode 100644 ZSharp.Runtime/runtime/import/Runtime.Import.Global.cs create mode 100644 ZSharp.Runtime/runtime/import/Runtime.Import.Method.cs create mode 100644 ZSharp.Runtime/runtime/import/Runtime.Import.Module.cs create mode 100644 ZSharp.Runtime/runtime/import/Runtime.Import.Type.Modified.cs create mode 100644 ZSharp.Runtime/runtime/import/Runtime.Import.Type.cs create mode 100644 ZSharp.Runtime/runtime/load/Runtime.Load.Function.cs create mode 100644 ZSharp.Runtime/runtime/load/Runtime.Load.Module.cs create mode 100644 ZSharp.Runtime/runtime/load/Runtime.Load.Type.cs create mode 100644 ZSharp.Runtime/tasks/TaskManager.cs diff --git a/ZSharp.Runtime.IL/il2ir/loaders/EnumerationLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/EnumerationLoader.cs new file mode 100644 index 00000000..78a2612f --- /dev/null +++ b/ZSharp.Runtime.IL/il2ir/loaders/EnumerationLoader.cs @@ -0,0 +1,42 @@ +using System.Reflection; +using ZSharp.IR; + +namespace ZSharp.Runtime.NET.IL2IR +{ + internal sealed class EnumerationLoader(ILLoader loader, Type input) + : BaseILLoader(loader, input, new(input.Name)) + { + public override EnumClass Load() + { + if (Context.Cache(Input, out var result)) + return result; + + Context.Cache(Input, Output); + + Output.Type = Loader.LoadType(Enum.GetUnderlyingType(Input)); + + LoadValues(); + + return Output; + } + + private void LoadValues() + { + foreach (var (name, value) in + Enum.GetNames(Input).Zip( + [ ..Enum.GetValuesAsUnderlyingType(Input) ] + ) + ) + { + LoadValue(name, value); + } + } + + private void LoadValue(string name, object value) + { + Output.Values.Add( + new(name, LiteralLoader.Load(value)) + ); + } + } +} diff --git a/ZSharp.Runtime.IL/il2ir/loaders/LiteralLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/LiteralLoader.cs new file mode 100644 index 00000000..ad304cba --- /dev/null +++ b/ZSharp.Runtime.IL/il2ir/loaders/LiteralLoader.cs @@ -0,0 +1,109 @@ +using CommonZ.Utils; +using System.Runtime.CompilerServices; +using IRCode = CommonZ.Utils.Collection; +using VM = ZSharp.IR.VM; + +namespace ZSharp.Runtime.NET.IL2IR +{ + public static class LiteralLoader + { + public static IRCode Load(object? o) + { + return o switch + { + sbyte s8 => Load(s8), + byte u8 => Load(u8), + short s16 => Load(s16), + ushort u16 => Load(u16), + int s32 => Load(s32), + uint u32 => Load(u32), + long s64 => Load(s64), + ulong u64 => Load(u64), + float f32 => Load(f32), + double f64 => Load(f64), + bool b => Load(b), + char c => Load(c), + string s => Load(s), + IntPtr i => Load(i), + UIntPtr u => Load(u), + null => [ new VM.PutNull() ], + _ => throw new NotSupportedException(), + }; + } + + public static IRCode Load(sbyte v) + { + throw new NotSupportedException(); + } + + public static IRCode Load(byte v) + { + throw new NotSupportedException(); + } + + public static IRCode Load(short v) + { + throw new NotSupportedException(); + } + + public static IRCode Load(ushort v) + { + throw new NotSupportedException(); + } + + public static IRCode Load(int v) + => [ + new VM.PutInt32(v) + ]; + + public static IRCode Load(uint v) + { + throw new NotSupportedException(); + } + + public static IRCode Load(long v) + { + throw new NotSupportedException(); + } + + public static IRCode Load(ulong v) + { + throw new NotSupportedException(); + } + + public static IRCode Load(IntPtr v) + { + throw new NotSupportedException(); + } + + public static IRCode Load(UIntPtr v) + { + throw new NotSupportedException(); + } + + public static IRCode Load(float v) + => [ + new VM.PutFloat32(v) + ]; + + public static IRCode Load(double v) + { + throw new NotSupportedException(); + } + + public static IRCode Load(bool v) + => [ + new VM.PutBoolean(v) + ]; + + public static IRCode Load(char v) + { + throw new NotSupportedException(); + } + + public static IRCode Load(string v) + => [ + new VM.PutString(v) + ]; + } +} diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ValueTypeLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ValueTypeLoader.cs new file mode 100644 index 00000000..93752e25 --- /dev/null +++ b/ZSharp.Runtime.IL/il2ir/loaders/ValueTypeLoader.cs @@ -0,0 +1,230 @@ +using System.Reflection; +using ZSharp.IR; + +using ValueType = ZSharp.IR.ValueType; + +namespace ZSharp.Runtime.NET.IL2IR +{ + internal sealed class ValueTypeLoader(ILLoader loader, Type input) + : BaseILLoader(loader, input, new(input.Name)) + { + private OOPTypeReference Self { get; set; } + + public override ValueType Load() + { + if (Context.Cache(Input, out var result)) + return result; + + Context.Cache(Input, Output); + + Self = new ValueTypeReference(Output); + + //LoadGenericParameters(); + + //if (!Input.IsInterface) + // LoadInterfaceImplementations(); + + //LoadFields(); + + //LoadProperties(); + + //LoadConstructors(); + + //LoadMethods(); + + //LoadTypes(); + + return Output; + } + + //private void LoadGenericParameters() + //{ + // //if (!Input.IsGenericTypeDefinition) + // // return; + + // //Output.Name = Input.Name.Split('`')[0]; + + // //foreach (var parameter in Input.GetGenericArguments()) + // //{ + // // var genericParameter = new GenericParameter(parameter.Name); + // // Context.Cache(parameter, genericParameter); + // // Output.GenericParameters.Add(genericParameter); + // //} + + // //Self = new ConstructedClass(Output) + // //{ + // // Arguments = [.. Output.GenericParameters] + // //}; + //} + + //private void LoadInterfaceImplementations() + //{ + // foreach (var @interface in Input.GetInterfaces()) + // LoadInterfaceImplementation(@interface, Input.GetInterfaceMap(@interface)); + //} + + //private void LoadFields() + //{ + // foreach (var field in Input.GetFields()) + // LoadField(field); + //} + + //private void LoadProperties() + //{ + // foreach (var property in Input.GetProperties()) + // LoadProperty(property); + //} + + //private void LoadConstructors() + //{ + // foreach (var constructor in Input.GetConstructors()) + // LoadConstructor(constructor); + //} + + //private void LoadMethods() + //{ + // foreach (var method in Input.GetMethods()) + // if (method.DeclaringType == Input) + // LoadMethod(method); + //} + + //private void LoadTypes() + //{ + // foreach (var nested in Input.GetNestedTypes()) + // LoadTypeDefinition(nested); + //} + + //private void LoadInterfaceImplementation(Type @interface, IL.InterfaceMapping mapping) + //{ + // if (mapping.InterfaceMethods.Length != mapping.TargetMethods.Length) + // throw new InvalidOperationException("Interface mapping is invalid."); + + // throw new NotImplementedException(); + + // var implementation = new IR.InterfaceImplementation(Loader.LoadType(@interface)); + + // for (int i = 0; i < mapping.InterfaceMethods.Length; i++) + // { + // var interfaceMethod = mapping.InterfaceMethods[i]; + // var targetMethod = mapping.TargetMethods[i]; + + // implementation.Implementations.Add( + // LoadMethod(interfaceMethod), + // LoadMethod(targetMethod) + // ); + // } + //} + + //private void LoadField(IL.FieldInfo field) + //{ + // var result = new Field(field.Name, Loader.LoadType(field.FieldType)) + // { + // IsStatic = field.IsStatic, + // IsReadOnly = field.IsInitOnly, + // }; + + // Output.Fields.Add(result); + //} + + //private void LoadProperty(IL.PropertyInfo property) + //{ + // var result = new Property(property.Name, Loader.LoadType(property.PropertyType)) + // { + // Getter = property.GetMethod is null ? null : LoadMethod(property.GetMethod), + // Setter = property.SetMethod is null ? null : LoadMethod(property.SetMethod), + // }; + + // Output.Properties.Add(result); + //} + + //private void LoadConstructor(IL.ConstructorInfo constructor) + //{ + // var result = new Constructor(null) + // { + // Method = new(Loader.RuntimeModule.TypeSystem.Void), + // }; + + // Context.Cache(constructor, result.Method); + + // if (!constructor.IsStatic) + // result.Method.Signature.Args.Parameters.Add(new("this", Self)); + + // foreach (var parameter in constructor.GetParameters()) + // if (parameter.GetCustomAttribute() is not null) + // result.Method.Signature.KwArgs.Parameters.Add(new(parameter.Name ?? throw new(), Loader.LoadType(parameter.ParameterType))); + // else + // result.Method.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); + + // Output.Constructors.Add(result); + //} + + //private Method LoadMethod(IL.MethodInfo method) + //{ + // List genericParameters = []; + + // if (method.IsGenericMethodDefinition) + // foreach (var genericParameter in method.GetGenericArguments()) + // genericParameters.Add(Context.Cache(genericParameter, new IR.GenericParameter(genericParameter.Name))); + + // var result = new Method(Loader.LoadType(method.ReturnType)) + // { + // Name = method.GetCustomAttribute()?.Name ?? method.Name, + // }; + + // Context.Cache(method, result); + + // if (genericParameters.Count > 0) + // result.GenericParameters.AddRange(genericParameters); + + // if (!method.IsStatic) + // result.Signature.Args.Parameters.Add(new("this", Self)); + // else result.IsStatic = true; + + // if (method.IsVirtual) + // result.IsVirtual = true; + + // foreach (var parameter in method.GetParameters()) + // if (parameter.GetCustomAttribute() is not null) + // result.Signature.KwArgs.Parameters.Add(new(parameter.Name ?? throw new(), Loader.LoadType(parameter.ParameterType))); + // else + // result.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); + + // Output.Methods.Add(result); + + // return result; + //} + + //private void LoadTypeDefinition(Type type) + //{ + // if (!type.IsTypeDefinition) + // throw new ArgumentException("Type must be a type definition.", nameof(type)); + + // if (Context.Cache(type, out OOPType? result)) ; + // else if (type.IsClass) result = LoadClass(type); + // else if (type.IsInterface) result = LoadInterface(type); + // else if (type.IsEnum) result = LoadEnum(type); + // else if (type.IsValueType) result = LoadStruct(type); + // else throw new NotImplementedException(); + + // Output.NestedTypes.Add(result); + //} + + //private Class LoadClass(Type type) + // => new ClassLoader(Loader, type).Load(); + + //private Interface LoadInterface(Type type) + // => new InterfaceLoader(Loader, type).Load(); + + //private EnumClass LoadEnum(Type type) + //{ + // //return new(); + // throw new NotImplementedException(); + //} + + //private IR.ValueType LoadStruct(Type type) + //{ + // return new(); + // throw new NotImplementedException(); + //} + } +} diff --git a/ZSharp.Runtime/GlobalUsings.cs b/ZSharp.Runtime/GlobalUsings.cs new file mode 100644 index 00000000..6012dc4b --- /dev/null +++ b/ZSharp.Runtime/GlobalUsings.cs @@ -0,0 +1 @@ +global using IL = System.Reflection; diff --git a/ZSharp.Runtime/ZSharp.Runtime.csproj b/ZSharp.Runtime/ZSharp.Runtime.csproj new file mode 100644 index 00000000..e0c87377 --- /dev/null +++ b/ZSharp.Runtime/ZSharp.Runtime.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/ZSharp.Runtime/loader/GlobalUsings.cs b/ZSharp.Runtime/loader/GlobalUsings.cs new file mode 100644 index 00000000..a2fedddb --- /dev/null +++ b/ZSharp.Runtime/loader/GlobalUsings.cs @@ -0,0 +1 @@ +global using Emit = System.Reflection.Emit; diff --git a/ZSharp.Runtime/loader/emit/EmitLoader.Standalone.cs b/ZSharp.Runtime/loader/emit/EmitLoader.Standalone.cs new file mode 100644 index 00000000..9918823f --- /dev/null +++ b/ZSharp.Runtime/loader/emit/EmitLoader.Standalone.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EmitLoader + { + private Emit.AssemblyBuilder StandaloneAssembly { get; } + + private Emit.ModuleBuilder StandaloneModule { get; } + } +} diff --git a/ZSharp.Runtime/loader/emit/EmitLoader.cs b/ZSharp.Runtime/loader/emit/EmitLoader.cs new file mode 100644 index 00000000..781385eb --- /dev/null +++ b/ZSharp.Runtime/loader/emit/EmitLoader.cs @@ -0,0 +1,20 @@ +namespace ZSharp.Runtime.Loaders +{ + internal sealed partial class EmitLoader + { + public Runtime Runtime { get; } + + public EmitLoader(Runtime runtime) + { + Runtime = runtime; + + StandaloneAssembly = Emit.AssemblyBuilder.DefineDynamicAssembly( + new IL.AssemblyName(""), + Emit.AssemblyBuilderAccess.RunAndCollect + ); + StandaloneModule = StandaloneAssembly.DefineDynamicModule( + "" + ); + } + } +} diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Code.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Code.cs new file mode 100644 index 00000000..4ff17bea --- /dev/null +++ b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Code.cs @@ -0,0 +1,30 @@ +using CommonZ.Utils; + +namespace ZSharp.Runtime.Loaders +{ + partial class EmitLoader + { + private delegate T CodeFunctionType(); + private delegate void VoidCodeFunction(); + + public Delegate LoadCode(Collection code, IR.IType irReturnType) + { + var ilReturnType = Runtime.ImportType(irReturnType); + var method = new Emit.DynamicMethod(string.Empty, ilReturnType, null, StandaloneModule); + + var codeLoader = new CodeCompiler(new UnboundCodeContext(Runtime, method.GetILGenerator())); + codeLoader.CompileCode(code); + + return + ilReturnType == typeof(void) + ? method.CreateDelegate( + typeof(CodeFunctionType<>) + .MakeGenericType(ilReturnType) + ) + : method.CreateDelegate( + typeof(VoidCodeFunction) + ) + ; + } + } +} diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Function.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Function.cs new file mode 100644 index 00000000..37f5e126 --- /dev/null +++ b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Function.cs @@ -0,0 +1,81 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EmitLoader + { + public IL.MethodInfo LoadStandaloneFunction(IR.Function function) + { + if (function.HasGenericParameters) + return LoadStandaloneGenericFunction(function); + return LoadStandaloneRegularFunction(function); + } + + private IL.MethodInfo LoadStandaloneRegularFunction(IR.Function function) + { + var method = new Emit.DynamicMethod( + function.Name ?? string.Empty, + Runtime.ImportType(function.ReturnType), + [ + .. function.Signature + .GetParameters() + .Select(p => p.Type) + .Select(Runtime.ImportType) + ], + StandaloneModule + ); + + foreach (var (i, parameter) in function.Signature.GetParameters().Select((v, i) => (i, v))) + method.DefineParameter(i + 1, IL.ParameterAttributes.None, parameter.Name); + + CompileFunctionCode(function, method.GetILGenerator()); + + return method; + } + + private IL.MethodInfo LoadStandaloneGenericFunction(IR.Function function) + { + var type = StandaloneModule.DefineType( + $"<{function.Name ?? string.Empty}>{StandaloneModule.GetTypes().Length}", + IL.TypeAttributes.Abstract | IL.TypeAttributes.Sealed + ); + var method = type.DefineMethod( + function.Name ?? "", + IL.MethodAttributes.Public | IL.MethodAttributes.Static, + Runtime.ImportType(function.ReturnType), + [ + .. function.Signature + .GetParameters() + .Select(p => p.Type) + .Select(Runtime.ImportType) + ] + ); + + var genericParameters = method.DefineGenericParameters( + [ + .. function.GenericParameters + .Select(p => p.Name) + ] + ); + + foreach (var (ir, il) in function.GenericParameters.Zip(genericParameters)) + Runtime.AddType(ir, il); + + foreach (var (i, parameter) in function.Signature.GetParameters().Select((v, i) => (i, v))) + method.DefineParameter(i + 1, IL.ParameterAttributes.None, parameter.Name); + + CompileFunctionCode(function, method.GetILGenerator()); + + foreach (var genericParameter in function.GenericParameters) + Runtime.DelType(genericParameter); + + type.CreateType(); + + return method; + } + + private void CompileFunctionCode(IR.Function function, Emit.ILGenerator il) + { + var codeLoader = new CodeCompiler(FunctionCodeContext.From(Runtime, il, function)); + codeLoader.CompileCode(function.Body.Instructions); + } + } +} diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Module.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Module.cs new file mode 100644 index 00000000..243bb96e --- /dev/null +++ b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Module.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EmitLoader + { + public IL.Module LoadModule(IR.Module module) + => new ModuleLoader(this, module).Load(); + } +} diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Class.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Class.cs new file mode 100644 index 00000000..2e01bae7 --- /dev/null +++ b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Class.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EmitLoader + { + + } +} diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Enum.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Enum.cs new file mode 100644 index 00000000..2e01bae7 --- /dev/null +++ b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Enum.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EmitLoader + { + + } +} diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Interface.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Interface.cs new file mode 100644 index 00000000..2e01bae7 --- /dev/null +++ b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Interface.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EmitLoader + { + + } +} diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.ValueType.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.ValueType.cs new file mode 100644 index 00000000..2e01bae7 --- /dev/null +++ b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.ValueType.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EmitLoader + { + + } +} diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs new file mode 100644 index 00000000..444051d5 --- /dev/null +++ b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs @@ -0,0 +1,25 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EmitLoader + { + public Type LoadType(IR.OOPType type) + { + var tasks = new TaskManager(() => { }); + var result = type switch + { + IR.Class def => new ClassLoader(this) + { + ILType = StandaloneModule.DefineType( + def.Name ?? throw new(), + IL.TypeAttributes.Public + ), + IRType = def, + Tasks = tasks + }.Load(), + _ => throw new NotSupportedException(), + }; + tasks.RunUntilComplete(); + return result; + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/LoaderBase.cs b/ZSharp.Runtime/loader/loaders/LoaderBase.cs new file mode 100644 index 00000000..94f27204 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/LoaderBase.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime.Loaders +{ + internal abstract class LoaderBase(EmitLoader loader) + { + public EmitLoader Loader { get; } = loader; + } +} diff --git a/ZSharp.Runtime/loader/loaders/class/ClassLoader.Context.cs b/ZSharp.Runtime/loader/loaders/class/ClassLoader.Context.cs new file mode 100644 index 00000000..4e985fc6 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/class/ClassLoader.Context.cs @@ -0,0 +1,9 @@ +using CommonZ.Utils; + +namespace ZSharp.Runtime.Loaders +{ + partial class ClassLoader + { + private Cache? genericTypeContext; + } +} diff --git a/ZSharp.Runtime/loader/loaders/class/ClassLoader.T.cs b/ZSharp.Runtime/loader/loaders/class/ClassLoader.T.cs new file mode 100644 index 00000000..02d00577 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/class/ClassLoader.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ClassLoader + { + + } +} diff --git a/ZSharp.Runtime/loader/loaders/class/ClassLoader.Tasks.cs b/ZSharp.Runtime/loader/loaders/class/ClassLoader.Tasks.cs new file mode 100644 index 00000000..1afe7476 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/class/ClassLoader.Tasks.cs @@ -0,0 +1,22 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ClassLoader + { + public required TaskManager Tasks { get; init; } + + private void AddTask(Action task) + { + if (genericTypeContext is not null) + { + var originalTask = task; + task = () => + { + using (Loader.Runtime.TypeContext(genericTypeContext)) + originalTask(); + }; + } + + Tasks.AddTask(task); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/class/ClassLoader.cs b/ZSharp.Runtime/loader/loaders/class/ClassLoader.cs new file mode 100644 index 00000000..ad0beba6 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/class/ClassLoader.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Runtime.Loaders +{ + internal sealed partial class ClassLoader + : LoaderBase + { + public required Emit.TypeBuilder ILType { get; init; } + + public required IR.Class IRType { get; init; } + + public ClassLoader(EmitLoader loader) + : base(loader) + { + + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Constructor.cs b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Constructor.cs new file mode 100644 index 00000000..5375ac26 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Constructor.cs @@ -0,0 +1,22 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ClassLoader + { + private void LoadConstructor(IR.Constructor constructor) + { + var result = ILType.DefineConstructor( + IL.MethodAttributes.Public, + IL.CallingConventions.HasThis, + [.. constructor.Method.Signature.GetParameters().Skip(1).Select(p => Loader.Runtime.ImportType(p.Type))] + ); + + Loader.Runtime.AddFunction(constructor.Method.UnderlyingFunction, result); + + var context = FunctionCodeContext.From(Loader.Runtime, result, constructor.Method.UnderlyingFunction); + + var codeLoader = new CodeCompiler(context); + + AddTask(() => codeLoader.CompileCode(constructor.Method.Body.Instructions)); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Field.cs b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Field.cs new file mode 100644 index 00000000..38c479f5 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Field.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ClassLoader + { + private void LoadField(IR.Field field) + { + var attributes = IL.FieldAttributes.Public; + + if (field.IsStatic) + attributes |= IL.FieldAttributes.Static; + + var il = ILType.DefineField(field.Name, Loader.Runtime.ImportType(field.Type), attributes); + + Loader.Runtime.AddField(field, il); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Generic.cs b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Generic.cs new file mode 100644 index 00000000..7d74ada1 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Generic.cs @@ -0,0 +1,20 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ClassLoader + { + private void LoadGenericParameters() + { + if (!IRType.HasGenericParameters) return; + + var ils = ILType.DefineGenericParameters( + [ + .. IRType.GenericParameters + .Select(p => p.Name) + ] + ); + + foreach (var (ir, il) in IRType.GenericParameters.Zip(ils)) + Loader.Runtime.AddType(ir, il); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs new file mode 100644 index 00000000..15e64b14 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs @@ -0,0 +1,40 @@ +using Microsoft.VisualBasic; + +namespace ZSharp.Runtime.Loaders +{ + partial class ClassLoader + { + private void LoadMethod(IR.Method method) + { + var attributes = IL.MethodAttributes.Public; + + if (method.IsStatic) + attributes |= IL.MethodAttributes.Static; + if (method.IsVirtual) + attributes |= IL.MethodAttributes.Virtual | IL.MethodAttributes.NewSlot; + + var result = ILType.DefineMethod( + method.Name ?? string.Empty, + attributes, + Loader.Runtime.ImportType(method.ReturnType), + [.. ( + method.IsInstance || method.IsVirtual + ? method.Signature.GetParameters().Skip(1) + : method.Signature.GetParameters() + ).Select(p => Loader.Runtime.ImportType(p.Type)) + ] + ); + + Loader.Runtime.AddFunction(method.UnderlyingFunction, result); + + var context = FunctionCodeContext.From(Loader.Runtime, result, method.UnderlyingFunction); + + foreach (var local in method.Body.Locals) + result.GetILGenerator().DeclareLocal(Loader.Runtime.ImportType(local.Type)); + + var codeLoader = new CodeCompiler(context); + + AddTask(() => codeLoader.CompileCode(method.Body.Instructions)); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs new file mode 100644 index 00000000..02d00577 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ClassLoader + { + + } +} diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs new file mode 100644 index 00000000..73f1b9f5 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs @@ -0,0 +1,60 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ClassLoader + { + public Type Load() + { + if (IRType.HasGenericParameters) + genericTypeContext = Loader.Runtime.NewTypeContext(); + + if (genericTypeContext is not null) + using (Loader.Runtime.TypeContext(genericTypeContext)) + LoadAll(); + else + LoadAll(); + + ILType.CreateType(); + + return ILType; + } + + private void LoadAll() + { + LoadGenericParameters(); + + LoadNestedTypes(); + + AddTask(LoadFields); + + AddTask(LoadConstructors); + + AddTask(LoadMethods); + } + + private void LoadNestedTypes() + { + throw new NotImplementedException(); + } + + private void LoadFields() + { + if (IRType.HasFields) + foreach (var field in IRType.Fields) + LoadField(field); + } + + private void LoadMethods() + { + if (IRType.HasMethods) + foreach (var method in IRType.Methods) + LoadMethod(method); + } + + private void LoadConstructors() + { + if (IRType.HasConstructors) + foreach (var constructor in IRType.Constructors) + LoadConstructor(constructor); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code contexts/FunctionCodeContext.cs b/ZSharp.Runtime/loader/loaders/code/code contexts/FunctionCodeContext.cs new file mode 100644 index 00000000..fc663167 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code contexts/FunctionCodeContext.cs @@ -0,0 +1,82 @@ +using CommonZ.Utils; +using ZSharp.IR; + +namespace ZSharp.Runtime.Loaders +{ + internal sealed class FunctionCodeContext + : ICodeContext + , IBranchingCodeContext + , IFrameCodeContext + , IFunctionalCodeContext + { + private readonly Mapping locals = []; + private readonly Mapping parameters = []; + private readonly Mapping labels = []; + + public Emit.ILGenerator IL { get; } + + public CodeStack Stack { get; } = new(); + + public Runtime Runtime { get; } + + public Function Function { get; } + + private FunctionCodeContext(Runtime runtime, Emit.ILGenerator il, Function function) + { + Runtime = runtime; + IL = il; + Function = function; + } + + void IBranchingCodeContext.AddBranchTarget(IR.VM.Instruction target) + => labels[target] = IL.DefineLabel(); + + Emit.Label IBranchingCodeContext.GetBranchTarget(IR.VM.Instruction target) + => labels[target]; + + Local IFrameCodeContext.GetLocal(IR.VM.Local local) + => locals[local]; + + Parameter IFrameCodeContext.GetParameter(IR.Parameter parameter) + => parameters[parameter]; + + private void SetupFromIR() + { + foreach (var parameter in Function.Signature.GetParameters()) + parameters[parameter] = new() + { + Index = parameter.Index, + Name = parameter.Name, + Type = Runtime.ImportType(parameter.Type) + }; + + if (Function.HasBody && Function.Body.HasLocals) + foreach (var local in Function.Body.Locals) + { + var il = locals[local] = new() + { + Index = local.Index, + Name = local.Name, + Type = Runtime.ImportType(local.Type) + }; + + IL.DeclareLocal(il.Type); + } + } + + public static FunctionCodeContext From(Runtime runtime, Emit.ConstructorBuilder constructor, Function function) + => From(runtime, constructor.GetILGenerator(), function); + + public static FunctionCodeContext From(Runtime runtime, Emit.MethodBuilder method, Function function) + => From(runtime, method.GetILGenerator(), function); + + public static FunctionCodeContext From(Runtime runtime, Emit.ILGenerator il, Function function) + { + var context = new FunctionCodeContext(runtime, il, function); + + context.SetupFromIR(); + + return context; + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs b/ZSharp.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs new file mode 100644 index 00000000..3904b96b --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs @@ -0,0 +1,23 @@ +using CommonZ.Utils; + +namespace ZSharp.Runtime.Loaders +{ + internal sealed class UnboundCodeContext(Runtime runtime, IL.Emit.ILGenerator il) + : ICodeContext + , IBranchingCodeContext + { + private readonly Mapping labels = []; + + public Emit.ILGenerator IL { get; } = il; + + public CodeStack Stack { get; } = new(); + + public Runtime Runtime { get; } = runtime; + + void IBranchingCodeContext.AddBranchTarget(IR.VM.Instruction target) + => labels[target] = IL.DefineLabel(); + + Emit.Label IBranchingCodeContext.GetBranchTarget(IR.VM.Instruction target) + => labels[target]; + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/CodeCompiler.cs b/ZSharp.Runtime/loader/loaders/code/code/CodeCompiler.cs new file mode 100644 index 00000000..23c1063b --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/CodeCompiler.cs @@ -0,0 +1,70 @@ +using CommonZ.Utils; + +namespace ZSharp.Runtime.Loaders +{ + public sealed class CodeCompiler(ICodeContext context) + { + public ICodeContext Context { get; } = context; + + public void CompileCode(Collection instructions) + { + if (Context is IBranchingCodeContext branchingContext) + { + foreach (var instruction in instructions) + branchingContext.AddBranchTarget(instruction); + + foreach (var instruction in instructions) + { + Context.IL.MarkLabel(branchingContext.GetBranchTarget(instruction)); + + Compile(instruction); + } + } else + foreach (var instruction in instructions) + Compile(instruction); + } + + private void Compile(IR.VM.Instruction instruction) + { + switch (instruction) + { + case IR.VM.Call call: CodeCompiler_Impl.Compile(RequireContext(), call); break; + case IR.VM.CallIndirect callIndirect: CodeCompiler_Impl.Compile(RequireContext(), callIndirect); break; + case IR.VM.CallVirtual callVirtual: CodeCompiler_Impl.Compile(RequireContext(), callVirtual); break; + case IR.VM.CastReference castReference: CodeCompiler_Impl.Compile(RequireContext(), castReference); break; + case IR.VM.CreateInstance createInstance: CodeCompiler_Impl.Compile(RequireContext(), createInstance); break; + case IR.VM.Dup dup: CodeCompiler_Impl.Compile(RequireContext(), dup); break; + case IR.VM.GetArgument getArgument: CodeCompiler_Impl.Compile(RequireContext(), getArgument); break; + //case IR.VM.GetClass getClass: CodeCompiler_Impl.Compile(RequireContext(), getClass); break; + case IR.VM.GetField getField: CodeCompiler_Impl.Compile(RequireContext(), getField); break; + case IR.VM.GetGlobal getGlobal: CodeCompiler_Impl.Compile(RequireContext(), getGlobal); break; + case IR.VM.GetLocal getLocal: CodeCompiler_Impl.Compile(RequireContext(), getLocal); break; + //case IR.VM.GetObject getObject: CodeCompiler_Impl.Compile(RequireContext(), getObject); break; + case IR.VM.IsNotNull isNotNull: CodeCompiler_Impl.Compile(RequireContext(), isNotNull); break; + case IR.VM.IsNull isNull: CodeCompiler_Impl.Compile(RequireContext(), isNull); break; + case IR.VM.Jump jump: CodeCompiler_Impl.Compile(RequireContext(), jump); break; + case IR.VM.JumpIfTrue jumpIfTrue: CodeCompiler_Impl.Compile(RequireContext(), jumpIfTrue); break; + case IR.VM.JumpIfFalse jumpIfFalse: CodeCompiler_Impl.Compile(RequireContext(), jumpIfFalse); break; + case IR.VM.Nop nop: CodeCompiler_Impl.Compile(RequireContext(), nop); break; + case IR.VM.Pop pop: CodeCompiler_Impl.Compile(RequireContext(), pop); break; + case IR.VM.PutBoolean putBoolean: CodeCompiler_Impl.Compile(RequireContext(), putBoolean); break; + case IR.VM.PutFloat32 putFloat32: CodeCompiler_Impl.Compile(RequireContext(), putFloat32); break; + case IR.VM.PutInt32 putInt32: CodeCompiler_Impl.Compile(RequireContext(), putInt32); break; + case IR.VM.PutNull putNull: CodeCompiler_Impl.Compile(RequireContext(), putNull); break; + case IR.VM.PutString putString: CodeCompiler_Impl.Compile(RequireContext(), putString); break; + case IR.VM.Return @return: CodeCompiler_Impl.Compile(RequireContext(), @return); break; + case IR.VM.SetArgument setArgument: CodeCompiler_Impl.Compile(RequireContext(), setArgument); break; + case IR.VM.SetField setField: CodeCompiler_Impl.Compile(RequireContext(), setField); break; + case IR.VM.SetGlobal setGlobal: CodeCompiler_Impl.Compile(RequireContext(), setGlobal); break; + case IR.VM.SetLocal setLocal: CodeCompiler_Impl.Compile(RequireContext(), setLocal); break; + case IR.VM.Swap swap: CodeCompiler_Impl.Compile(RequireContext(), swap); break; + + default: throw new NotImplementedException(); + } + } + + private T RequireContext() + where T : ICodeContext + => Context is T required ? required : throw new InvalidOperationException(); + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/branching/BranchingCodeCompiler.cs b/ZSharp.Runtime/loader/loaders/code/code/branching/BranchingCodeCompiler.cs new file mode 100644 index 00000000..25839f7b --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/branching/BranchingCodeCompiler.cs @@ -0,0 +1,24 @@ +namespace ZSharp.Runtime.Loaders +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(IBranchingCodeContext ctx, IR.VM.Jump jump) + { + ctx.IL.Emit(IL.Emit.OpCodes.Br, ctx.GetBranchTarget(jump.Target)); + } + + public static void Compile(IBranchingCodeContext ctx, IR.VM.JumpIfTrue jump) + { + ctx.IL.Emit(IL.Emit.OpCodes.Brtrue, ctx.GetBranchTarget(jump.Target)); + + ctx.Stack.Pop(typeof(bool)); + } + + public static void Compile(IBranchingCodeContext ctx, IR.VM.JumpIfFalse jump) + { + ctx.IL.Emit(IL.Emit.OpCodes.Brfalse, ctx.GetBranchTarget(jump.Target)); + + ctx.Stack.Pop(typeof(bool)); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/branching/IBranchingCodeContext.cs b/ZSharp.Runtime/loader/loaders/code/code/branching/IBranchingCodeContext.cs new file mode 100644 index 00000000..0a0b701e --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/branching/IBranchingCodeContext.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Runtime.Loaders +{ + public interface IBranchingCodeContext + : ICodeContext + { + public void AddBranchTarget(IR.VM.Instruction target); + + public IL.Emit.Label GetBranchTarget(IR.VM.Instruction target); + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/core/CodeStack.cs b/ZSharp.Runtime/loader/loaders/code/code/core/CodeStack.cs new file mode 100644 index 00000000..492f6778 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/core/CodeStack.cs @@ -0,0 +1,25 @@ +namespace ZSharp.Runtime.Loaders +{ + public sealed class CodeStack + { + private readonly Stack ilStack = []; + + public void Dup() + => ilStack.Push(ilStack.Peek()); + + public void Put(Type type) + => ilStack.Push(type); + + public Type Pop() => ilStack.Pop(); + + public Type Pop(Type expect) + { + var result = Pop(); + if (result != expect) throw new(); + return result; + } + + public Type? Top() + => ilStack.Count == 0 ? null : ilStack.Peek(); + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/core/ICodeContext.cs b/ZSharp.Runtime/loader/loaders/code/code/core/ICodeContext.cs new file mode 100644 index 00000000..9e1c6c49 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/core/ICodeContext.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Runtime.Loaders +{ + public interface ICodeContext + { + public Emit.ILGenerator IL { get; } + + public CodeStack Stack { get; } + + public Runtime Runtime { get; } + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/frame/FrameCodeCompiler.cs b/ZSharp.Runtime/loader/loaders/code/code/frame/FrameCodeCompiler.cs new file mode 100644 index 00000000..11e24e18 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/frame/FrameCodeCompiler.cs @@ -0,0 +1,73 @@ +namespace ZSharp.Runtime.Loaders +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(IFrameCodeContext ctx, IR.VM.GetArgument get) + { + var parameter = ctx.GetParameter(get.Argument); + var index = parameter.Index; + + if (index == 0) + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_0); + else if (index == 1) + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_1); + else if (index == 2) + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_2); + else if (index == 3) + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_3); + else if (index <= byte.MaxValue) + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_S, (byte)index); + else + ctx.IL.Emit(IL.Emit.OpCodes.Ldarg, index); + + ctx.Stack.Put(parameter.Type); + } + + public static void Compile(IFrameCodeContext ctx, IR.VM.GetLocal get) + { + var l = ctx.GetLocal(get.Local); + var index = l.Index; + + if (index == 0) + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_0); + else if (index == 1) + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_1); + else if (index == 2) + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_2); + else if (index == 3) + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_3); + else if (index <= byte.MaxValue) + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_S, (byte)index); + else + ctx.IL.Emit(IL.Emit.OpCodes.Ldloc, index); + + ctx.Stack.Put(l.Type); + } + + public static void Compile(IFrameCodeContext ctx, IR.VM.SetArgument set) + { + var parameter = ctx.GetParameter(set.Argument); + var index = parameter.Index; + + if (index <= byte.MaxValue) + ctx.IL.Emit(IL.Emit.OpCodes.Starg_S, (byte)index); + else + ctx.IL.Emit(IL.Emit.OpCodes.Starg, index); + + ctx.Stack.Pop(parameter.Type); + } + + public static void Compile(IFrameCodeContext ctx, IR.VM.SetLocal set) + { + var local = ctx.GetLocal(set.Local); + var index = local.Index; + + if (index <= byte.MaxValue) + ctx.IL.Emit(IL.Emit.OpCodes.Stloc_S, (byte)index); + else + ctx.IL.Emit(IL.Emit.OpCodes.Stloc, index); + + ctx.Stack.Pop(local.Type); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/frame/IFrameCodeContext.cs b/ZSharp.Runtime/loader/loaders/code/code/frame/IFrameCodeContext.cs new file mode 100644 index 00000000..93b10282 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/frame/IFrameCodeContext.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Runtime.Loaders +{ + public interface IFrameCodeContext + : ICodeContext + { + public Parameter GetParameter(IR.Parameter parameter); + + public Local GetLocal(IR.VM.Local local); + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/frame/Local.cs b/ZSharp.Runtime/loader/loaders/code/code/frame/Local.cs new file mode 100644 index 00000000..35c671c6 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/frame/Local.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Runtime.Loaders +{ + public sealed class Local + { + public required string Name { get; init; } + + public required int Index { get; init; } + + public required Type Type { get; init; } + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/frame/Parameter.cs b/ZSharp.Runtime/loader/loaders/code/code/frame/Parameter.cs new file mode 100644 index 00000000..6dca5a9c --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/frame/Parameter.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Runtime.Loaders +{ + public sealed class Parameter + { + public required string Name { get; init; } + + public required int Index { get; init; } + + public required Type Type { get; init; } + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs b/ZSharp.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs new file mode 100644 index 00000000..7e3d4774 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs @@ -0,0 +1,34 @@ +namespace ZSharp.Runtime.Loaders +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(ICodeContext ctx, IR.VM.Call call) + { + var callable = ctx.Runtime.ImportCallable(call.Callable); + + foreach (var parameter in call.Callable.Signature.GetParameters()) + ctx.Stack.Pop(ctx.Runtime.ImportType(parameter.Type)); + + if (callable is IL.MethodInfo method) + { + ctx.IL.Emit(Emit.OpCodes.Call, method); + + if (method.ReturnType != typeof(void)) + ctx.Stack.Put(method.ReturnType); + } + else if (callable is IL.ConstructorInfo constructor) + ctx.IL.Emit(Emit.OpCodes.Call, constructor); + else throw new($"Unknown callable type: {callable.GetType()}"); + } + + public static void Compile(ICodeContext ctx, IR.VM.CallIndirect call) + { + throw new NotImplementedException(); + } + + public static void Compile(ICodeContext ctx, IR.VM.Return _) + { + ctx.IL.Emit(Emit.OpCodes.Ret); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/functional/IFunctionalCodeContext.cs b/ZSharp.Runtime/loader/loaders/code/code/functional/IFunctionalCodeContext.cs new file mode 100644 index 00000000..2db81d09 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/functional/IFunctionalCodeContext.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Runtime.Loaders +{ + public interface IFunctionalCodeContext + : ICodeContext + { + public IR.Function Function { get; } + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/modular/ModularCodeCompiler.cs b/ZSharp.Runtime/loader/loaders/code/code/modular/ModularCodeCompiler.cs new file mode 100644 index 00000000..7a334d44 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/modular/ModularCodeCompiler.cs @@ -0,0 +1,23 @@ +namespace ZSharp.Runtime.Loaders +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(ICodeContext ctx, IR.VM.GetGlobal get) + { + var global = ctx.Runtime.ImportGlobal(get.Global); + + ctx.IL.Emit(Emit.OpCodes.Ldsfld, global); + + ctx.Stack.Put(global.FieldType); + } + + public static void Compile(ICodeContext ctx, IR.VM.SetGlobal set) + { + var global = ctx.Runtime.ImportGlobal(set.Global); + + ctx.IL.Emit(IL.Emit.OpCodes.Stsfld, global); + + ctx.Stack.Pop(global.FieldType); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/object/OOPCodeCompiler.cs b/ZSharp.Runtime/loader/loaders/code/code/object/OOPCodeCompiler.cs new file mode 100644 index 00000000..feaa21b9 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/object/OOPCodeCompiler.cs @@ -0,0 +1,59 @@ +namespace ZSharp.Runtime.Loaders +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(ICodeContext ctx, IR.VM.CallVirtual callVirtual) + { + var method = ctx.Runtime.ImportMethodReference(callVirtual.Method); + + if (!method.IsVirtual && !method.IsAbstract) + throw new($"Method {method} is not virtual or abstract!"); + + ctx.IL.Emit(Emit.OpCodes.Callvirt, method); + + if (method.ReturnType != typeof(void)) + ctx.Stack.Put(method.ReturnType); + } + + public static void Compile(ICodeContext ctx, IR.VM.CastReference castReference) + { + var targetType = ctx.Runtime.ImportType(castReference.Type); + + ctx.IL.Emit(Emit.OpCodes.Isinst, targetType); + + ctx.Stack.Pop(); + ctx.Stack.Put(targetType); + } + + public static void Compile(ICodeContext ctx, IR.VM.CreateInstance createInstance) + { + var constructor = ctx.Runtime.ImportConstructorReference(createInstance.Constructor); + + ctx.IL.Emit(Emit.OpCodes.Newobj, constructor); + + ctx.Stack.Put(constructor.DeclaringType ?? throw new()); + } + + public static void Compile(ICodeContext ctx, IR.VM.GetField get) + { + var field = ctx.Runtime.ImportFieldReference(get.Field); + + ctx.IL.Emit(field.IsStatic ? Emit.OpCodes.Ldsfld : Emit.OpCodes.Ldfld, field); + + if (!field.IsStatic) + ctx.Stack.Pop(field.DeclaringType ?? throw new()); + ctx.Stack.Put(field.FieldType); + } + + public static void Compile(ICodeContext ctx, IR.VM.SetField set) + { + var field = ctx.Runtime.ImportFieldReference(set.Field); + + ctx.IL.Emit(field.IsStatic ? Emit.OpCodes.Stsfld : Emit.OpCodes.Stfld, field); + + ctx.Stack.Pop(); + if (!field.IsStatic) + ctx.Stack.Pop(field.DeclaringType ?? throw new()); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/code/code/stack/StackCodeCompiler.cs b/ZSharp.Runtime/loader/loaders/code/code/stack/StackCodeCompiler.cs new file mode 100644 index 00000000..76a9123e --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/code/code/stack/StackCodeCompiler.cs @@ -0,0 +1,82 @@ +namespace ZSharp.Runtime.Loaders +{ + internal static partial class CodeCompiler_Impl + { + public static void Compile(ICodeContext ctx, IR.VM.Dup _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Dup); + + ctx.Stack.Dup(); + } + + public static void Compile(ICodeContext ctx, IR.VM.IsNotNull _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldnull); + ctx.IL.Emit(IL.Emit.OpCodes.Cgt_Un); + + ctx.Stack.Pop(); + ctx.Stack.Put(typeof(bool)); + } + + public static void Compile(ICodeContext ctx, IR.VM.IsNull _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldnull); + ctx.IL.Emit(IL.Emit.OpCodes.Ceq); + + ctx.Stack.Pop(); + ctx.Stack.Put(typeof(bool)); + } + + public static void Compile(ICodeContext ctx, IR.VM.Nop _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Nop); + } + + public static void Compile(ICodeContext ctx, IR.VM.Pop _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Pop); + + ctx.Stack.Pop(); + } + + public static void Compile(ICodeContext ctx, IR.VM.PutBoolean put) + { + ctx.IL.Emit(put.Value ? IL.Emit.OpCodes.Ldc_I4_1 : IL.Emit.OpCodes.Ldc_I4_0); + + ctx.Stack.Put(typeof(bool)); + } + + public static void Compile(ICodeContext ctx, IR.VM.PutFloat32 put) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldc_R4, put.Value); + + ctx.Stack.Put(typeof(float)); + } + + public static void Compile(ICodeContext ctx, IR.VM.PutInt32 put) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldc_I4, put.Value); + + ctx.Stack.Put(typeof(int)); + } + + public static void Compile(ICodeContext ctx, IR.VM.PutNull _) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldnull); + + ctx.Stack.Put(typeof(object)); + } + + public static void Compile(ICodeContext ctx, IR.VM.PutString put) + { + ctx.IL.Emit(IL.Emit.OpCodes.Ldstr, put.Value); + + ctx.Stack.Put(typeof(string)); + } + + public static void Compile(ICodeContext ctx, IR.VM.Swap _) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/module/ModuleLoader.Tasks.cs b/ZSharp.Runtime/loader/loaders/module/ModuleLoader.Tasks.cs new file mode 100644 index 00000000..a1d4db07 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/module/ModuleLoader.Tasks.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ModuleLoader + { + private readonly TaskManager tasks; + + private void AddTask(Action task) + => tasks.AddTask(task); + + private void RunUntilComplete() + => tasks.RunUntilComplete(); + } +} diff --git a/ZSharp.Runtime/loader/loaders/module/ModuleLoader.cs b/ZSharp.Runtime/loader/loaders/module/ModuleLoader.cs new file mode 100644 index 00000000..8436b1f1 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/module/ModuleLoader.cs @@ -0,0 +1,28 @@ +namespace ZSharp.Runtime.Loaders +{ + internal sealed partial class ModuleLoader + : LoaderBase + { + public Emit.AssemblyBuilder AssemblyBuilder { get; } + + public Emit.ModuleBuilder ILModule { get; } + + public Emit.TypeBuilder Globals { get; } + + public IR.Module IRModule { get; } + + public ModuleLoader(EmitLoader loader, IR.Module module) + : base(loader) + { + IRModule = module; + AssemblyBuilder = Emit.AssemblyBuilder.DefineDynamicAssembly( + new IL.AssemblyName(IRModule.Name ?? throw new()), + Emit.AssemblyBuilderAccess.RunAndCollect + ); + ILModule = AssemblyBuilder.DefineDynamicModule(IRModule.Name); + Globals = ILModule.DefineType(""); + + tasks = new(LoadAll); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Function.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Function.cs new file mode 100644 index 00000000..c421fc1e --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Function.cs @@ -0,0 +1,34 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ModuleLoader + { + public void LoadFunction(IR.Function function) + { + var returnType = Loader.Runtime.ImportType(function.ReturnType); + var parameterTypes = function + .Signature + .GetParameters() + .Select(p => p.Type) + .Select(Loader.Runtime.ImportType) + .ToArray(); + + var method = Globals.DefineMethod( + function.Name ?? "", + IL.MethodAttributes.Static | IL.MethodAttributes.Public, + returnType, + parameterTypes + ); + + Loader.Runtime.AddFunction(function, method); + + foreach (var (i, parameter) in function.Signature.GetParameters().Select((v, i) => (i, v))) + method.DefineParameter(i + 1, IL.ParameterAttributes.None, parameter.Name); + + AddTask(() => + { + var codeLoader = new CodeCompiler(FunctionCodeContext.From(Loader.Runtime, method, function)); + codeLoader.CompileCode(function.Body.Instructions); + }); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Global.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Global.cs new file mode 100644 index 00000000..9e6698b7 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Global.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ModuleLoader + { + private void LoadGlobal(IR.Global global) + { + var field = Globals.DefineField( + global.Name, + Loader.Runtime.ImportType(global.Type), + IL.FieldAttributes.Public | IL.FieldAttributes.Static + ); + + Loader.Runtime.AddGlobal(global, field); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Class.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Class.cs new file mode 100644 index 00000000..c214a4d8 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Class.cs @@ -0,0 +1,19 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ModuleLoader + { + public void LoadClass(IR.Class @class) + { + ClassLoader loader = new(Loader) + { + ILType = ILModule.DefineType(@class.Name ?? string.Empty, IL.TypeAttributes.Public), + IRType = @class, + Tasks = tasks + }; + + Loader.Runtime.AddTypeDefinition(@class, loader.ILType); + + Loader.Runtime.SetTypeDefinition(@class, loader.Load()); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.EnumClass.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.EnumClass.cs new file mode 100644 index 00000000..8e2baf5f --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.EnumClass.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ModuleLoader + { + public void LoadEnumClass(IR.EnumClass @enum) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Interface.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Interface.cs new file mode 100644 index 00000000..edda7648 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Interface.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ModuleLoader + { + public void LoadInterface(IR.Interface @interface) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.ValueType.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.ValueType.cs new file mode 100644 index 00000000..94f487a2 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.ValueType.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ModuleLoader + { + public void LoadValueType(IR.ValueType valueType) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs new file mode 100644 index 00000000..e4c2a51e --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ModuleLoader + { + public void LoadType(IR.OOPType type) + { + switch (type) + { + case IR.Class @class: LoadClass(@class); break; + case IR.Interface @interface: LoadInterface(@interface); break; + case IR.EnumClass @enum: LoadEnumClass(@enum); break; + case IR.ValueType valueType: LoadValueType(valueType); break; + default: throw new NotSupportedException(); + } + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs new file mode 100644 index 00000000..509605a6 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs @@ -0,0 +1,73 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ModuleLoader + { + public IL.Module Load() + { + RunUntilComplete(); + + Globals.CreateType(); + + return ILModule; + } + + private void LoadAll() + { + LoadTypes(); + + LoadGlobals(); + + LoadFunctions(); + + LoadInitializer(); + } + + private void LoadTypes() + { + if (IRModule.HasTypes) + foreach (var type in IRModule.Types) + LoadType(type); + } + + private void LoadGlobals() + { + if (IRModule.HasGlobals) + foreach (var global in IRModule.Globals) + LoadGlobal(global); + } + + private void LoadFunctions() + { + if (IRModule.HasFunctions) + foreach (var function in IRModule.Functions) + LoadFunction(function); + } + + private void LoadInitializer() + { + if (IRModule.Initializer is null) return; + + var typeInitializer = Globals.DefineTypeInitializer(); + + var initializationFunction = Loader.Runtime.ImportFunction(IRModule.Initializer); + + if (!initializationFunction.IsStatic) + throw new InvalidProgramException( + $"Module's {ILModule.Name} initializer function must be static" + ); + if (initializationFunction.ReturnType != typeof(void)) + throw new InvalidProgramException( + $"Module's {ILModule.Name} initializer function must return void" + ); + if (initializationFunction.GetParameters().Length != 0) + throw new InvalidProgramException( + $"Module's {ILModule.Name} initializer function must not have any parameters" + ); + + var il = typeInitializer.GetILGenerator(); + + il.Emit(Emit.OpCodes.Call, initializationFunction); + il.Emit(Emit.OpCodes.Ret); + } + } +} diff --git a/ZSharp.Runtime/runtime/Runtime.IR.cs b/ZSharp.Runtime/runtime/Runtime.IR.cs new file mode 100644 index 00000000..4d0d3bac --- /dev/null +++ b/ZSharp.Runtime/runtime/Runtime.IR.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + public required IR.RuntimeModule RuntimeModule { get; init; } + } +} diff --git a/ZSharp.Runtime/runtime/Runtime.Loader.cs b/ZSharp.Runtime/runtime/Runtime.Loader.cs new file mode 100644 index 00000000..c6f478f0 --- /dev/null +++ b/ZSharp.Runtime/runtime/Runtime.Loader.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + private Loaders.EmitLoader Loader { get; } + } +} diff --git a/ZSharp.Runtime/runtime/Runtime.cs b/ZSharp.Runtime/runtime/Runtime.cs new file mode 100644 index 00000000..544feacf --- /dev/null +++ b/ZSharp.Runtime/runtime/Runtime.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Runtime +{ + public sealed partial class Runtime + { + public Runtime() + : this(IR.RuntimeModule.Standard) + { + + } + + public Runtime(IR.RuntimeModule runtimeModule) + { + RuntimeModule = runtimeModule; + Loader = new(this); + } + } +} diff --git a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Field.cs b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Field.cs new file mode 100644 index 00000000..33716de2 --- /dev/null +++ b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Field.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + private readonly Dictionary _fieldCache = []; + + public void AddField(IR.Field ir, IL.FieldInfo il) + => _fieldCache.Add(ir, il); + + public void DelField(IR.Field ir) + => _fieldCache.Remove(ir); + + public void SetField(IR.Field ir, IL.FieldInfo il) + => _fieldCache[ir] = il; + } +} diff --git a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Function.cs b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Function.cs new file mode 100644 index 00000000..8cfd236b --- /dev/null +++ b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Function.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + private readonly Dictionary _functionCache = []; + + public void AddFunction(IR.Function ir, IL.MethodBase il) + => _functionCache.Add(ir, il); + + public void DelFunction(IR.Function ir) + => _functionCache.Remove(ir); + + public void SetFunction(IR.Function ir, IL.MethodBase il) + => _functionCache[ir] = il; + } +} diff --git a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Global.cs b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Global.cs new file mode 100644 index 00000000..1d799965 --- /dev/null +++ b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Global.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + private readonly Dictionary _globalCache = []; + + public void AddGlobal(IR.Global ir, IL.FieldInfo il) + => _globalCache.Add(ir, il); + + public void DelGlobal(IR.Global ir) + => _globalCache.Remove(ir); + + public void SetGlobal(IR.Global ir, IL.FieldInfo il) + => _globalCache[ir] = il; + } +} diff --git a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Module.cs b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Module.cs new file mode 100644 index 00000000..0db4c43c --- /dev/null +++ b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Module.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + private readonly Dictionary _moduleCache = []; + } +} diff --git a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Type.cs b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Type.cs new file mode 100644 index 00000000..ed94585a --- /dev/null +++ b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Type.cs @@ -0,0 +1,40 @@ +using CommonZ.Utils; + +namespace ZSharp.Runtime +{ + partial class Runtime + { + private Cache _typeCache = []; + private readonly Dictionary _typeDefCache = []; + + public Cache NewTypeContext() + => new() { Parent = _typeCache }; + + public ContextManager TypeContext(Cache? context = null) + { + context ??= NewTypeContext(); + + (_typeCache, context) = (context, _typeCache); + + return new(() => _typeCache = context); + } + + public void AddType(IR.IType ir, Type il) + => SetType(ir, il); + + public void DelType(IR.IType ir) + => _typeCache.Uncache(ir); + + public void SetType(IR.IType ir, Type il) + => _typeCache.Cache(ir, il); + + public void AddTypeDefinition(IR.OOPType ir, Type il) + => _typeDefCache.Add(ir, il); + + public void DelTypeDefinition(IR.OOPType ir) + => _typeDefCache.Remove(ir); + + public void SetTypeDefinition(IR.OOPType ir, Type il) + => _typeDefCache[ir] = il; + } +} diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Callable.cs b/ZSharp.Runtime/runtime/import/Runtime.Import.Callable.cs new file mode 100644 index 00000000..dc4431c2 --- /dev/null +++ b/ZSharp.Runtime/runtime/import/Runtime.Import.Callable.cs @@ -0,0 +1,19 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + public IL.MethodBase ImportCallable(IR.ICallable callable) + => callable switch + { + IR.ConstructorReference target => ImportConstructorReference(target), + IR.Method target => ImportMethod(target), + IR.MethodReference target => ImportMethodReference(target), + IR.Function target => ImportFunction(target), + IR.GenericFunctionInstance target => ImportConstructedFunction(target), + _ => throw new ArgumentException( + $"Invalid callable type: {callable.GetType()}", + nameof(callable) + ) + }; + } +} diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Constructor.cs b/ZSharp.Runtime/runtime/import/Runtime.Import.Constructor.cs new file mode 100644 index 00000000..a9237a06 --- /dev/null +++ b/ZSharp.Runtime/runtime/import/Runtime.Import.Constructor.cs @@ -0,0 +1,45 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + public IL.ConstructorInfo ImportConstructor(IR.Constructor constructor) + { + var function = constructor.Method.UnderlyingFunction; + if (!_functionCache.TryGetValue(function, out var result)) + throw new InvalidOperationException( + $"Constructor{' ' + constructor.Name ?? string.Empty} in type {constructor.Method.Owner} is not loaded" + ); + if (result is not IL.ConstructorInfo info) + throw new InvalidOperationException(); + + return info; + } + + public IL.ConstructorInfo ImportConstructorReference(IR.ConstructorReference @ref) + { + var type = ImportType(@ref.OwningType); + + var def = ImportConstructor(@ref.Constructor); + + if (!type.IsGenericType) + return def; + + if (type.GetGenericTypeDefinition() is Emit.TypeBuilder typeBuilder) + if (!typeBuilder.IsCreated()) + return Emit.TypeBuilder.GetConstructor(type, def); + try + { + def = (IL.ConstructorInfo)(IL.MethodBase.GetMethodFromHandle( + def.MethodHandle, + type.TypeHandle + ) ?? throw new("Could not create constructor from method handle")); + } + catch (NotSupportedException) + { + def = Emit.TypeBuilder.GetConstructor(type, def); + } + + return def; + } + } +} diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Field.cs b/ZSharp.Runtime/runtime/import/Runtime.Import.Field.cs new file mode 100644 index 00000000..461820a5 --- /dev/null +++ b/ZSharp.Runtime/runtime/import/Runtime.Import.Field.cs @@ -0,0 +1,34 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + public IL.FieldInfo ImportField(IR.Field field) + { + if (!_fieldCache.TryGetValue(field, out var result)) + throw new InvalidOperationException( + $"Field {field.Name} in type {field.Owner?.Name ?? ""} is not loaded" + ); + + return result; + } + + public IL.FieldInfo ImportFieldReference(IR.FieldReference @ref) + { + var type = ImportType(@ref.OwningType); + + var def = ImportField(@ref.Field); + + if (!type.IsGenericType) + return def; + + if (type.GetGenericTypeDefinition() is Emit.TypeBuilder typeBuilder) + if (!typeBuilder.IsCreated()) + return Emit.TypeBuilder.GetField(type, def); + + return IL.FieldInfo.GetFieldFromHandle( + def.FieldHandle, + type.TypeHandle + ); + } + } +} diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Function.cs b/ZSharp.Runtime/runtime/import/Runtime.Import.Function.cs new file mode 100644 index 00000000..5e367753 --- /dev/null +++ b/ZSharp.Runtime/runtime/import/Runtime.Import.Function.cs @@ -0,0 +1,22 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + public IL.MethodInfo ImportFunction(IR.Function function) + { + if (!_functionCache.TryGetValue(function, out var result)) + result = _functionCache[function] = LoadFunction(function); + if (result is not IL.MethodInfo info) + throw new InvalidOperationException(); + + return info; + } + + public IL.MethodInfo ImportConstructedFunction(IR.GenericFunctionInstance constructedFunction) + { + var def = ImportFunction(constructedFunction.Function); + + return def.MakeGenericMethod([.. constructedFunction.Arguments.Select(ImportType)]); + } + } +} diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Global.cs b/ZSharp.Runtime/runtime/import/Runtime.Import.Global.cs new file mode 100644 index 00000000..353b4a82 --- /dev/null +++ b/ZSharp.Runtime/runtime/import/Runtime.Import.Global.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + public IL.FieldInfo ImportGlobal(IR.Global global) + { + if (!_globalCache.TryGetValue(global, out var result)) + throw new InvalidOperationException( + $"Global {global.Name} in module {global.Owner?.Name ?? ""} is not loaded" + ); + + return result; + } + } +} diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Method.cs b/ZSharp.Runtime/runtime/import/Runtime.Import.Method.cs new file mode 100644 index 00000000..db257e59 --- /dev/null +++ b/ZSharp.Runtime/runtime/import/Runtime.Import.Method.cs @@ -0,0 +1,41 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + public IL.MethodInfo ImportMethod(IR.Method method) + => ImportFunction(method.UnderlyingFunction); + + public IL.MethodInfo ImportMethodReference(IR.MethodReference @ref) + { + var type = ImportType(@ref.OwningType); + + var def = ImportMethod(@ref.Method); + + if (type.IsGenericType) + if (type.GetGenericTypeDefinition() is IL.Emit.TypeBuilder typeBuilder) + { + if (!typeBuilder.IsCreated()) + def = Emit.TypeBuilder.GetMethod(type, def); + } + else + try + { + def = (IL.MethodInfo)(IL.MethodBase.GetMethodFromHandle( + def.MethodHandle, + type.TypeHandle + ) ?? throw new("Could not create method from method handle")); + } + catch (NotSupportedException) + { + def = Emit.TypeBuilder.GetMethod(type, def); + } + + if (@ref is IR.ConstructedMethod constructed) + def = def.MakeGenericMethod([ + .. constructed.Arguments.Select(ImportType) + ]); + + return def; + } + } +} diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Module.cs b/ZSharp.Runtime/runtime/import/Runtime.Import.Module.cs new file mode 100644 index 00000000..0a3d3c55 --- /dev/null +++ b/ZSharp.Runtime/runtime/import/Runtime.Import.Module.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + public IL.Module ImportModule(IR.Module module) + { + if (!_moduleCache.TryGetValue(module, out var result)) + result = _moduleCache[module] = LoadModule(module); + + return result; + } + } +} diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Type.Modified.cs b/ZSharp.Runtime/runtime/import/Runtime.Import.Type.Modified.cs new file mode 100644 index 00000000..e068849e --- /dev/null +++ b/ZSharp.Runtime/runtime/import/Runtime.Import.Type.Modified.cs @@ -0,0 +1,29 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + private Type ImportArrayType(IR.OOPTypeReference @ref) + { + var con = (IR.ConstructedType)@ref; + var elementType = ImportType(con.Arguments[0]); + + return elementType.MakeArrayType(); + } + + private Type ImportPointerType(IR.OOPTypeReference @ref) + { + var con = (IR.ConstructedType)@ref; + var elementType = ImportType(con.Arguments[0]); + + return elementType.MakePointerType(); + } + + private Type ImportReferenceType(IR.OOPTypeReference @ref) + { + var con = (IR.ConstructedType)@ref; + var elementType = ImportType(con.Arguments[0]); + + return elementType.MakeByRefType(); + } + } +} diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Type.cs b/ZSharp.Runtime/runtime/import/Runtime.Import.Type.cs new file mode 100644 index 00000000..5f682a5d --- /dev/null +++ b/ZSharp.Runtime/runtime/import/Runtime.Import.Type.cs @@ -0,0 +1,54 @@ +using System.Reflection.Metadata; + +namespace ZSharp.Runtime +{ + partial class Runtime + { + public Type ImportType(IR.IType type) + { + if (_typeCache.Cache(type, out var result)) return result; + + return type switch + { + IR.OOPTypeReference reference => ImportTypeReference(reference), + _ => throw new NotImplementedException() + }; + } + + public Type ImportTypeDefinition(IR.OOPType def) + { + if (!_typeDefCache.TryGetValue(def, out var result)) + result = _typeDefCache[def] = LoadType(def); + + return result; + } + + public Type ImportTypeReference(IR.OOPTypeReference @ref) + { + if ( + @ref.Definition == RuntimeModule.TypeSystem.Array + ) return ImportArrayType(@ref); + if ( + @ref.Definition == RuntimeModule.TypeSystem.Pointer + ) return ImportPointerType(@ref); + if ( + @ref.Definition == RuntimeModule.TypeSystem.Reference + ) return ImportReferenceType(@ref); + + var type = ImportTypeDefinition(@ref.Definition); + + List genericArguments = []; + + if (@ref.OwningType is not null) + genericArguments.AddRange(ImportType(@ref.OwningType).GetGenericArguments()); + + if (@ref is IR.ConstructedType constructedType) + genericArguments.AddRange(constructedType.Arguments.Select(ImportType)); + + if (genericArguments.Count == 0) + return type; + + return type.MakeGenericType([.. genericArguments]); + } + } +} diff --git a/ZSharp.Runtime/runtime/load/Runtime.Load.Function.cs b/ZSharp.Runtime/runtime/load/Runtime.Load.Function.cs new file mode 100644 index 00000000..e564021a --- /dev/null +++ b/ZSharp.Runtime/runtime/load/Runtime.Load.Function.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + private IL.MethodInfo LoadFunction(IR.Function function) + { + if (function.Module is not null) + throw new InvalidOperationException( + $"Cannot directly load function {function.Name} owned by module {function.Module.Name}" + ); + + return Loader.LoadStandaloneFunction(function); + } + } +} diff --git a/ZSharp.Runtime/runtime/load/Runtime.Load.Module.cs b/ZSharp.Runtime/runtime/load/Runtime.Load.Module.cs new file mode 100644 index 00000000..0372ebe5 --- /dev/null +++ b/ZSharp.Runtime/runtime/load/Runtime.Load.Module.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + private IL.Module LoadModule(IR.Module module) + => Loader.LoadModule(module); + } +} diff --git a/ZSharp.Runtime/runtime/load/Runtime.Load.Type.cs b/ZSharp.Runtime/runtime/load/Runtime.Load.Type.cs new file mode 100644 index 00000000..087d2178 --- /dev/null +++ b/ZSharp.Runtime/runtime/load/Runtime.Load.Type.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + private Type LoadType(IR.OOPType type) + { + if (type.Module is not null) + throw new InvalidOperationException( + $"Cannot directly load type {type} owned by module {type.Module.Name}" + ); + + return Loader.LoadType(type); + } + } +} diff --git a/ZSharp.Runtime/tasks/TaskManager.cs b/ZSharp.Runtime/tasks/TaskManager.cs new file mode 100644 index 00000000..aaf27db1 --- /dev/null +++ b/ZSharp.Runtime/tasks/TaskManager.cs @@ -0,0 +1,20 @@ +namespace ZSharp.Runtime +{ + internal sealed class TaskManager(Action init) + { + private List thisTasks = [init], nextTasks = []; + + public void AddTask(Action task) + => nextTasks.Add(task); + + public void RunUntilComplete() + { + while (thisTasks.Count > 0) + { + foreach (var task in thisTasks) task(); + (thisTasks, nextTasks) = (nextTasks, thisTasks); + nextTasks.Clear(); + } + } + } +} From a8b52cb805175fd6acced0bd9b8c0cacea6542fe Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 18 Jul 2025 15:02:42 +0300 Subject: [PATCH 178/235] Update IR --- ZSharp.IR/ir/oop/class/ClassAttributes.cs | 8 +++ ZSharp.IR/ir/oop/enum/EnumClass.cs | 29 ++++++++++ ZSharp.IR/ir/oop/enum/EnumValue.cs | 14 +++++ ZSharp.IR/ir/oop/enum/EnumValueCollection.cs | 55 +++++++++++++++++++ ZSharp.IR/ir/oop/enum/EnumclassAttributes.cs | 8 +++ .../ir/oop/value type/ConstructedValueType.cs | 16 ++++++ ZSharp.IR/ir/oop/value type/ValueType.cs | 7 +++ .../ir/oop/value type/ValueTypeReference.cs | 10 ++++ 8 files changed, 147 insertions(+) create mode 100644 ZSharp.IR/ir/oop/class/ClassAttributes.cs create mode 100644 ZSharp.IR/ir/oop/enum/EnumClass.cs create mode 100644 ZSharp.IR/ir/oop/enum/EnumValue.cs create mode 100644 ZSharp.IR/ir/oop/enum/EnumValueCollection.cs create mode 100644 ZSharp.IR/ir/oop/enum/EnumclassAttributes.cs create mode 100644 ZSharp.IR/ir/oop/value type/ConstructedValueType.cs create mode 100644 ZSharp.IR/ir/oop/value type/ValueType.cs create mode 100644 ZSharp.IR/ir/oop/value type/ValueTypeReference.cs diff --git a/ZSharp.IR/ir/oop/class/ClassAttributes.cs b/ZSharp.IR/ir/oop/class/ClassAttributes.cs new file mode 100644 index 00000000..51527935 --- /dev/null +++ b/ZSharp.IR/ir/oop/class/ClassAttributes.cs @@ -0,0 +1,8 @@ +namespace ZSharp.IR +{ + [Flags] + public enum ClassAttributes + { + None = 0, + } +} \ No newline at end of file diff --git a/ZSharp.IR/ir/oop/enum/EnumClass.cs b/ZSharp.IR/ir/oop/enum/EnumClass.cs new file mode 100644 index 00000000..10516001 --- /dev/null +++ b/ZSharp.IR/ir/oop/enum/EnumClass.cs @@ -0,0 +1,29 @@ +using CommonZ.Utils; + +namespace ZSharp.IR +{ + public sealed class EnumClass + : OOPType + , IType + { + public string? Name { get; set; } + + public EnumclassAttributes Attributes { get; set; } = EnumclassAttributes.None; + + public IType Type { get; set; } = null!; + + public Collection Values { get; } + + public EnumClass(string? name) + { + Name = name; + Values = new EnumValueCollection(this); + } + + public EnumClass(string? name, IType type) + : this(name) + { + Type = type; + } + } +} diff --git a/ZSharp.IR/ir/oop/enum/EnumValue.cs b/ZSharp.IR/ir/oop/enum/EnumValue.cs new file mode 100644 index 00000000..d24f8a19 --- /dev/null +++ b/ZSharp.IR/ir/oop/enum/EnumValue.cs @@ -0,0 +1,14 @@ +using CommonZ.Utils; + +namespace ZSharp.IR +{ + public sealed class EnumValue(string name, Collection valueCode) + : ModuleMember + { + internal EnumClass? _enumClass; + + public string Name { get; set; } = name; + + public Collection Value { get; set; } = valueCode; + } +} diff --git a/ZSharp.IR/ir/oop/enum/EnumValueCollection.cs b/ZSharp.IR/ir/oop/enum/EnumValueCollection.cs new file mode 100644 index 00000000..a077748b --- /dev/null +++ b/ZSharp.IR/ir/oop/enum/EnumValueCollection.cs @@ -0,0 +1,55 @@ +using CommonZ.Utils; + +namespace ZSharp.IR +{ + internal sealed class EnumValueCollection(EnumClass owner) + : Collection + { + private readonly EnumClass enumClass = owner; + + public override void OnAdd(EnumValue item) + { + AssertUnonwed(item); + SetOwner(item); + } + + public override void OnInsert(int index, EnumValue item) + { + AssertUnonwed(item); + SetOwner(item); + } + + public override void OnRemove(EnumValue item) + { + AssertOwned(item); + UnsetOwner(item); + } + + public override void OnRemoveAt(int index) + { + OnRemove(this[index]); + } + + private void SetOwner(EnumValue item) + { + item._enumClass = enumClass; + } + + private void UnsetOwner(EnumValue item) + { + item._enumClass = null; + } + + private void AssertUnonwed(EnumValue item) + { + if (item.Owner is not null) + throw new InvalidOperationException(); + } + + private void AssertOwned(EnumValue item) + { + if (item.Owner is null) + throw new InvalidOperationException(); + } + } +} diff --git a/ZSharp.IR/ir/oop/enum/EnumclassAttributes.cs b/ZSharp.IR/ir/oop/enum/EnumclassAttributes.cs new file mode 100644 index 00000000..9d6d2518 --- /dev/null +++ b/ZSharp.IR/ir/oop/enum/EnumclassAttributes.cs @@ -0,0 +1,8 @@ +namespace ZSharp.IR +{ + [Flags] + public enum EnumclassAttributes + { + None = 0, + } +} diff --git a/ZSharp.IR/ir/oop/value type/ConstructedValueType.cs b/ZSharp.IR/ir/oop/value type/ConstructedValueType.cs new file mode 100644 index 00000000..788b940a --- /dev/null +++ b/ZSharp.IR/ir/oop/value type/ConstructedValueType.cs @@ -0,0 +1,16 @@ +using CommonZ.Utils; + +namespace ZSharp.IR +{ + public sealed class ConstructedValueType(ValueType @class) + : ConstructedType + { + public ValueType ValueType { get; set; } = @class; + + ValueType OOPTypeReference.Definition => ValueType; + + public OOPTypeReference? OwningType { get; set; } + + public Collection Arguments { get; set; } = false ? [] : Collection.Empty; + } +} diff --git a/ZSharp.IR/ir/oop/value type/ValueType.cs b/ZSharp.IR/ir/oop/value type/ValueType.cs new file mode 100644 index 00000000..0a52d8ad --- /dev/null +++ b/ZSharp.IR/ir/oop/value type/ValueType.cs @@ -0,0 +1,7 @@ +namespace ZSharp.IR +{ + public sealed class ValueType(string? name) : OOPType + { + public string? Name { get; set; } = name; + } +} diff --git a/ZSharp.IR/ir/oop/value type/ValueTypeReference.cs b/ZSharp.IR/ir/oop/value type/ValueTypeReference.cs new file mode 100644 index 00000000..c447146d --- /dev/null +++ b/ZSharp.IR/ir/oop/value type/ValueTypeReference.cs @@ -0,0 +1,10 @@ +namespace ZSharp.IR +{ + public sealed class ValueTypeReference(ValueType valueType) + : OOPTypeReference + { + public ValueType Definition { get; } = valueType; + + public OOPTypeReference? OwningType { get; set; } + } +} From 73260d74743f4d549f751eb19b0b50db536e4991 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 18 Jul 2025 15:03:00 +0300 Subject: [PATCH 179/235] Add stuff --- .../ZSharp.Compiler.ILLoader.csproj | 29 +++++ .../capabilities/on add/IOnAddTo.cs | 8 ++ .../capabilities/on add/OnAddResult.cs | 9 ++ .../il loader/ILLoader.Namespaces.cs | 35 ++++++ .../il loader/ILLoader.cs | 7 ++ .../load/ILLoader.Load.Member.Constructor.cs | 10 ++ .../load/ILLoader.Load.Member.Event.cs | 10 ++ .../load/ILLoader.Load.Member.Field.cs | 10 ++ .../ILLoader.Load.Member.Method.Generic.cs | 10 ++ .../load/ILLoader.Load.Member.Method.cs | 13 +++ .../load/ILLoader.Load.Member.Property.cs | 10 ++ .../il loader/load/ILLoader.Load.Member.cs | 23 ++++ .../load/ILLoader.Load.Type.Class.Generic.cs | 10 ++ .../load/ILLoader.Load.Type.Class.cs | 13 +++ .../il loader/load/ILLoader.Load.Type.Enum.cs | 10 ++ .../load/ILLoader.Load.Type.Generic.cs | 10 ++ .../ILLoader.Load.Type.Interface.Generic.cs | 10 ++ .../load/ILLoader.Load.Type.Interface.cs | 13 +++ .../load/ILLoader.Load.Type.Modified.cs | 29 +++++ .../load/ILLoader.Load.Type.Struct.Generic.cs | 10 ++ .../load/ILLoader.Load.Type.Struct.cs | 13 +++ .../il loader/load/ILLoader.Load.Type.cs | 30 +++++ .../module loader/ModuleLoader.cs | 7 ++ .../load/ModuleLoader.Load.Field.cs | 10 ++ .../load/ModuleLoader.Load.Method.Generic.cs | 10 ++ .../load/ModuleLoader.Load.Method.cs | 13 +++ .../load/ModuleLoader.Load.Property.cs | 10 ++ .../module loader/load/ModuleLoader.Load.cs | 14 +++ .../objects/GlobalUsings.cs | 11 ++ .../objects/modular/module/Module.IL.cs | 9 ++ .../objects/modular/module/Module.LazyLoad.cs | 39 +++++++ .../objects/modular/module/Module.Member.cs | 32 ++++++ .../objects/modular/module/Module.cs | 14 +++ .../objects/namespace/Namespace.Member.cs | 30 +++++ .../objects/namespace/Namespace.OnAddTo.cs | 15 +++ .../objects/namespace/Namespace.Parent.cs | 15 +++ .../objects/namespace/Namespace.cs | 10 ++ .../generic/GenericFunctionInstance_Old.cs | 97 ++++++++++++++++ .../instance/GenericFunctionInstance.Call.cs | 50 ++++++++ .../GenericFunctionInstance.Generic.cs | 12 ++ .../instance/GenericFunctionInstance.IR.cs | 27 +++++ .../GenericFunctionInstance.Signature.cs | 11 ++ .../instance/GenericFunctionInstance.cs | 7 ++ ZSharp.Compiler.Objects/oop/enum/EnumClass.cs | 107 ++++++++++++++++++ ZSharp.Compiler.Objects/oop/enum/EnumValue.cs | 72 ++++++++++++ .../oop/value type/ValueType.cs | 54 +++++++++ .../cg objects/types/array/ArrayType.cs | 22 ++++ .../cg objects/types/array/ArrayTypeObject.cs | 41 +++++++ .../cg objects/types/pointer/PointerType.cs | 22 ++++ .../types/pointer/PointerTypeObject.cs | 41 +++++++ .../types/reference/ReferenceType.cs | 22 ++++ .../types/reference/ReferenceTypeObject.cs | 41 +++++++ .../cap/generic/IGenericInstantiable.cs | 13 +++ 53 files changed, 1200 insertions(+) create mode 100644 ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj create mode 100644 ZSharp.Compiler.ILLoader/capabilities/on add/IOnAddTo.cs create mode 100644 ZSharp.Compiler.ILLoader/capabilities/on add/OnAddResult.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/ILLoader.Namespaces.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/ILLoader.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Constructor.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Event.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Field.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.Generic.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Property.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs create mode 100644 ZSharp.Compiler.ILLoader/module loader/ModuleLoader.cs create mode 100644 ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Field.cs create mode 100644 ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs create mode 100644 ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs create mode 100644 ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Property.cs create mode 100644 ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/GlobalUsings.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/module/Module.IL.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/module/Module.Member.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/namespace/Namespace.OnAddTo.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Parent.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/namespace/Namespace.cs create mode 100644 ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs create mode 100644 ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs create mode 100644 ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Generic.cs create mode 100644 ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs create mode 100644 ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Signature.cs create mode 100644 ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.cs create mode 100644 ZSharp.Compiler.Objects/oop/enum/EnumClass.cs create mode 100644 ZSharp.Compiler.Objects/oop/enum/EnumValue.cs create mode 100644 ZSharp.Compiler.Objects/oop/value type/ValueType.cs create mode 100644 ZSharp.Compiler/cg objects/types/array/ArrayType.cs create mode 100644 ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs create mode 100644 ZSharp.Compiler/cg objects/types/pointer/PointerType.cs create mode 100644 ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs create mode 100644 ZSharp.Compiler/cg objects/types/reference/ReferenceType.cs create mode 100644 ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs create mode 100644 ZSharp.Compiler/features/cap/generic/IGenericInstantiable.cs diff --git a/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj b/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj new file mode 100644 index 00000000..84721ebd --- /dev/null +++ b/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj @@ -0,0 +1,29 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ZSharp.Compiler.ILLoader/capabilities/on add/IOnAddTo.cs b/ZSharp.Compiler.ILLoader/capabilities/on add/IOnAddTo.cs new file mode 100644 index 00000000..f9ef51c7 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/capabilities/on add/IOnAddTo.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Objects +{ + public interface IOnAddTo + where T : class, CompilerObject + { + public OnAddResult OnAddTo(T @object); + } +} diff --git a/ZSharp.Compiler.ILLoader/capabilities/on add/OnAddResult.cs b/ZSharp.Compiler.ILLoader/capabilities/on add/OnAddResult.cs new file mode 100644 index 00000000..0cd86886 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/capabilities/on add/OnAddResult.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Objects +{ + public enum OnAddResult + { + None, + Error, + Remove + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Namespaces.cs b/ZSharp.Compiler.ILLoader/il loader/ILLoader.Namespaces.cs new file mode 100644 index 00000000..4bef51e2 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/ILLoader.Namespaces.cs @@ -0,0 +1,35 @@ +using CommonZ.Utils; +using ZSharp.Compiler.ILLoader.Objects; + +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public Mapping Namespaces { get; } = []; + + public Namespace Namespace(string fullName) + { + var parts = fullName.Split('.'); + + if (parts.Length == 0) + throw new ArgumentException( + "Namespace name must contain at least 1 identifier", + nameof(fullName) + ); + + if (!Namespaces.TryGetValue(parts[0], out var @namespace)) + @namespace = Namespaces[parts[0]] = new(parts[0]); + + foreach (var part in parts.Skip(1)) + if (!@namespace.Members.TryGetValue(part, out var member)) + @namespace.AddMember(part, member = new Namespace(part)); + else if (member is not Namespace ns) + throw new ArgumentException( + $"{part} in {@namespace.FullName} is not a namespace" + ); + else @namespace = ns; + + return @namespace; + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs b/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs new file mode 100644 index 00000000..3383b47a --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + public sealed partial class ILLoader + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Constructor.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Constructor.cs new file mode 100644 index 00000000..2ddb54e8 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Constructor.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadConstructor(IL.ConstructorInfo constructor) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Event.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Event.cs new file mode 100644 index 00000000..0e402b40 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Event.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadEvent(IL.EventInfo @event) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Field.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Field.cs new file mode 100644 index 00000000..d5796c95 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Field.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadField(IL.FieldInfo field) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.Generic.cs new file mode 100644 index 00000000..753638de --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.Generic.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadGenericMethod(IL.MethodInfo method) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs new file mode 100644 index 00000000..787262eb --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadMethod(IL.MethodInfo method) + { + if (method.IsGenericMethodDefinition) + return LoadGenericMethod(method); + + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Property.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Property.cs new file mode 100644 index 00000000..a2660f2d --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Property.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadProperty(IL.PropertyInfo property) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.cs new file mode 100644 index 00000000..93901dc7 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.cs @@ -0,0 +1,23 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + private readonly Dictionary memberCache = []; + + public CompilerObject LoadMember(IL.MemberInfo member) + { + if (!memberCache.TryGetValue(member, out var @object)) + @object = memberCache[member] = member switch + { + IL.ConstructorInfo constructor => LoadConstructor(constructor), + IL.EventInfo @event => LoadEvent(@event), + IL.FieldInfo field => LoadField(field), + IL.MethodInfo method => LoadMethod(method), + IL.PropertyInfo property => LoadProperty(property), + _ => throw new NotSupportedException() + }; + + return @object; + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs new file mode 100644 index 00000000..e4ca4917 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadGenericClass(Type @class) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs new file mode 100644 index 00000000..c021918f --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadClass(Type @class) + { + if (@class.IsGenericTypeDefinition) + return LoadGenericClass(@class); + + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs new file mode 100644 index 00000000..d3bc5166 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadEnum(Type @enum) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs new file mode 100644 index 00000000..79af355b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadConstructedGenericType(Type type) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs new file mode 100644 index 00000000..e3d1a4c7 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadGenericInterface(Type @enum) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs new file mode 100644 index 00000000..a0b56a3d --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadInterface(Type @interface) + { + if (@interface.IsGenericTypeDefinition) + return LoadGenericInterface(@interface); + + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs new file mode 100644 index 00000000..60a54aa6 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs @@ -0,0 +1,29 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadModifiedType(Type type) + { + if (type.IsArray) return LoadArrayType(type); + if (type.IsPointer) return LoadPointerType(type); + if (type.IsByRef) return LoadReferenceType(type); + + throw new NotSupportedException(); + } + + public CompilerObject LoadArrayType(Type array) + { + throw new NotImplementedException(); + } + + public CompilerObject LoadPointerType(Type pointer) + { + throw new NotImplementedException(); + } + + public CompilerObject LoadReferenceType(Type reference) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs new file mode 100644 index 00000000..7b685dd2 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadGenericStruct(Type @enum) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs new file mode 100644 index 00000000..f4081f99 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public CompilerObject LoadStruct(Type @struct) + { + if (@struct.IsGenericTypeDefinition) + return LoadGenericStruct(@struct); + + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs new file mode 100644 index 00000000..659be355 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs @@ -0,0 +1,30 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + private readonly Dictionary typeCache = []; + + public CompilerObject LoadType(Type type) + { + if (!typeCache.TryGetValue(type, out var @object)) + @object = typeCache[type] = DispatchLoadType(type); + + return @object; + } + + private CompilerObject DispatchLoadType(Type type) + { + if (type.IsConstructedGenericType) + return LoadConstructedGenericType(type); + + if (type.IsClass) return LoadClass(type); + if (type.IsInterface) return LoadInterface(type); + if (type.IsValueType) return LoadStruct(type); + + if (type.HasElementType) + return LoadModifiedType(type); + + throw new NotSupportedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/module loader/ModuleLoader.cs b/ZSharp.Compiler.ILLoader/module loader/ModuleLoader.cs new file mode 100644 index 00000000..617dbbb9 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module loader/ModuleLoader.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + internal sealed partial class ModuleLoader(ILLoader loader) + { + public ILLoader Loader { get; } = loader; + } +} diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Field.cs b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Field.cs new file mode 100644 index 00000000..0855bc6f --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Field.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ModuleLoader + { + public CompilerObject LoadField(IL.FieldInfo field) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs new file mode 100644 index 00000000..7ac9a1c0 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ModuleLoader + { + public CompilerObject LoadGenericMethod(IL.MethodInfo method) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs new file mode 100644 index 00000000..bfc20fbb --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ModuleLoader + { + public CompilerObject LoadMethod(IL.MethodInfo method) + { + if (method.IsGenericMethodDefinition) + return LoadGenericMethod(method); + + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Property.cs b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Property.cs new file mode 100644 index 00000000..044bd13b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Property.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ModuleLoader + { + public CompilerObject LoadProperty(IL.PropertyInfo property) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.cs b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.cs new file mode 100644 index 00000000..7b567f2b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.cs @@ -0,0 +1,14 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ModuleLoader + { + public CompilerObject LoadMember(IL.MemberInfo member) + => member switch + { + IL.FieldInfo field => LoadField(field), + IL.MethodInfo method => LoadMethod(method), + IL.PropertyInfo property => LoadProperty(property), + _ => throw new NotSupportedException(), + }; + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/GlobalUsings.cs b/ZSharp.Compiler.ILLoader/objects/GlobalUsings.cs new file mode 100644 index 00000000..ad74d913 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/GlobalUsings.cs @@ -0,0 +1,11 @@ +global using ZSharp.Objects; + +global using IL = System.Reflection; + +global using MemberName = string; +global using MemberIndex = int; + +global using CompilerObjectResult = ZSharp.Compiler.Result< + ZSharp.Objects.CompilerObject, string +>; + diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.IL.cs b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.IL.cs new file mode 100644 index 00000000..a7477915 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.IL.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Module + { + public IL.Module IL { get; } + + public Type? Globals { get; } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs new file mode 100644 index 00000000..d8bbbe1b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs @@ -0,0 +1,39 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Module + { + private ModuleLoader? _moduleLoader; + + public required ILLoader Loader { get; init; } + + internal ModuleLoader GlobalsLoader + { + get + { + if (_moduleLoader is not null) + return _moduleLoader; + + Interlocked.CompareExchange(ref _moduleLoader, new(Loader), null); + return _moduleLoader; + } + } + + public CompilerObject? LoadMember(string name) + { + var members = Globals?.GetMember(name); + + if (members is not null && members.Length > 0) + { + foreach (var member in members) + AddMember(name, GlobalsLoader.LoadMember(member)); + + return Members[name]; + } + + var type = IL.GetType(name); + if (type is null) return null; + if (!type.IsPublic) return null; + return Loader.LoadType(type); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Member.cs b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Member.cs new file mode 100644 index 00000000..8c704e7b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Member.cs @@ -0,0 +1,32 @@ +using CommonZ.Utils; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Module + : ICTGetMember + { + public Mapping Members { get; } = []; + + public void AddMember(string name, CompilerObject member) + { + var result = OnAddResult.None; + if (member is IOnAddTo onAdd) + result = onAdd.OnAddTo(this); + + if (result == OnAddResult.None) + Members.Add(name, member); + } + + CompilerObjectResult ICTGetMember.Member(Compiler compiler, MemberName member) + { + if (!Members.TryGetValue(member, out var result)) + if ((result = LoadMember(member)) is not null) + Members.Add(member, result); + else return CompilerObjectResult.Error( + $"Could not find member {member} in module {IL.Name}" + ); + + return CompilerObjectResult.Ok(result); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs new file mode 100644 index 00000000..d4e5ad0c --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs @@ -0,0 +1,14 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Module + : CompilerObject + { + public string Name => IL.Name; + + public Module(IL.Module il) + { + IL = il; + Globals = IL.GetType(""); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs new file mode 100644 index 00000000..0cdbead2 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs @@ -0,0 +1,30 @@ +using CommonZ.Utils; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Namespace + : ICTGetMember + { + public Mapping Members { get; } = []; + + public void AddMember(string name, CompilerObject member) + { + var result = OnAddResult.None; + if (member is IOnAddTo onAdd) + result = onAdd.OnAddTo(this); + + if (result == OnAddResult.None) + Members.Add(name, member); + } + + CompilerObjectResult ICTGetMember.Member(Compiler compiler, MemberName member) + { + if (Members.TryGetValue(member, out var result)) + return CompilerObjectResult.Ok(result); + + return CompilerObjectResult.Error( + $"Can't find member {member} in namespace {Name}" + ); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.OnAddTo.cs b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.OnAddTo.cs new file mode 100644 index 00000000..0025a18c --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.OnAddTo.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Namespace + : IOnAddTo + { + OnAddResult IOnAddTo.OnAddTo(Namespace @object) + { + if (HasParent) return OnAddResult.Error; + + Parent = @object; + + return OnAddResult.None; + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Parent.cs b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Parent.cs new file mode 100644 index 00000000..69a34d30 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Parent.cs @@ -0,0 +1,15 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Namespace + { + public Namespace? Parent { get; private set; } + + [MemberNotNullWhen(true, nameof(Parent))] + public bool HasParent => Parent is not null; + + public string FullName => + Parent is null ? Name : $"{Parent.FullName}.{Name}"; + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.cs b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.cs new file mode 100644 index 00000000..92e6da02 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Namespace(string name) + : CompilerObject + { + public string Name { get; set; } = name; + + public bool IsAnonymous => Name == string.Empty; + } +} diff --git a/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs b/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs new file mode 100644 index 00000000..071e0ed6 --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs @@ -0,0 +1,97 @@ +using System.Diagnostics.CodeAnalysis; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class GenericFunctionInstance_Old(GenericFunction origin) + : CompilerObject + , ICTCallable_Old + , ICompileIRReference + { + public GenericFunction Origin { get; } = origin; + + public required ReferenceContext Context { get; init; } + + public Signature? Signature { get; set; } + + public IR.Signature? CompiledSignature { get; private set; } + + CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) + { + if (Origin.ReturnType is null) + throw new NotImplementedException(); + + CompileSignature(compiler); + + var args = (Signature as ISignature).MatchArguments(compiler, arguments); + + IRCode code = new(); + + List @params = []; + + @params.AddRange(Signature.Args); + + if (Signature.VarArgs is not null) + @params.Add(Signature.VarArgs); + + @params.AddRange(Signature.KwArgs); + + if (Signature.VarKwArgs is not null) + @params.Add(Signature.VarKwArgs); + + foreach (var param in @params) + code.Append(compiler.CompileIRCode(args[param])); + + code.Append(new([ + new IR.VM.Call(compiler.CompileIRReference(this)) + ])); + + code.Types.Clear(); + if (Origin.ReturnType != compiler.TypeSystem.Void) + code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); + + return new RawCode(code); + } + + IR.GenericFunctionInstance ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + { + var arguments = Origin.GenericParameters + .Select(genericParameter => Context[genericParameter]) + .Select(compiler.CompileIRType); + + CompileSignature(compiler); + + return new(compiler.CompileIRObject(Origin, null)) + { + Arguments = [.. arguments], + Signature = CompiledSignature, + }; + } + + [MemberNotNull(nameof(Signature), nameof(CompiledSignature))] + private void CompileSignature(Compiler.Compiler compiler) + { + Signature ??= compiler.Feature().CreateReference(Origin.Signature, Context); + + if (CompiledSignature is not null) + return; + + if (Origin.ReturnType is null) + throw new NotImplementedException(); + + CompiledSignature = new(compiler.CompileIRType(compiler.Feature().CreateReference(Origin.ReturnType, Context))); + + foreach (var arg in Signature.Args) + CompiledSignature.Args.Parameters.Add(compiler.CompileIRObject(arg, CompiledSignature)); + + if (Signature.VarArgs is not null) + CompiledSignature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, CompiledSignature); + + foreach (var kwArg in Signature.KwArgs) + CompiledSignature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, CompiledSignature)); + + if (Signature.VarKwArgs is not null) + CompiledSignature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, CompiledSignature); + } + } +} diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs new file mode 100644 index 00000000..94f462f2 --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs @@ -0,0 +1,50 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + partial class GenericFunctionInstance + : ICTCallable + { + CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument_NEW[] arguments) + { + if (ReturnType is null) + return CompilerObjectResult.Error( + "Return type is not defined" + ); + + var args = Signature.MatchArguments( + compiler, + arguments + .Select(arg => new Argument(arg.Name, arg.Value)) + .ToArray() + ); + + IRCode code = new(); + + List @params = []; + + @params.AddRange(Signature.Args); + + if (Signature.VarArgs is not null) + @params.Add(Signature.VarArgs); + + @params.AddRange(Signature.KwArgs); + + if (Signature.VarKwArgs is not null) + @params.Add(Signature.VarKwArgs); + + foreach (var param in @params) + code.Append(compiler.CompileIRCode(args[param])); + + code.Append(new([ + new IR.VM.Call(compiler.CompileIRReference(this)) + ])); + + code.Types.Clear(); + if (ReturnType != compiler.TypeSystem.Void) + code.Types.Add(ReturnType); + + return CompilerObjectResult.Ok(new RawCode(code)); + } + } +} diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Generic.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Generic.cs new file mode 100644 index 00000000..d204545c --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Generic.cs @@ -0,0 +1,12 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + partial class GenericFunctionInstance + { + public required Mapping GenericArguments { get; init; } + + public required GenericFunction GenericFunction { get; init; } + } +} diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs new file mode 100644 index 00000000..0ebe0e91 --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs @@ -0,0 +1,27 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + partial class GenericFunctionInstance + : ICompileIRReference + { + IR.GenericFunctionInstance ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + { + var argumentResults = GenericFunction.GenericParameters + .Select(p => GenericArguments[p]) + .Select(compiler.IR.CompileType); + + var arguments = argumentResults + .Select(r => r.Unwrap()); + + var functionIR = compiler.IR.CompileDefinition(GenericFunction, null).Unwrap(); + var signatureIR = compiler.IR.CompileDefinition(Signature, functionIR).Unwrap(); + + return new(functionIR) + { + Arguments = [.. arguments], + Signature = signatureIR, + }; + } + } +} diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Signature.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Signature.cs new file mode 100644 index 00000000..82d1bb23 --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Signature.cs @@ -0,0 +1,11 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + partial class GenericFunctionInstance + { + public required ISignature Signature { get; init; } + + public IType? ReturnType => Signature.ReturnType; + } +} diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.cs new file mode 100644 index 00000000..e8f7815e --- /dev/null +++ b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Objects +{ + public sealed partial class GenericFunctionInstance + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.Objects/oop/enum/EnumClass.cs b/ZSharp.Compiler.Objects/oop/enum/EnumClass.cs new file mode 100644 index 00000000..7eb024b0 --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/enum/EnumClass.cs @@ -0,0 +1,107 @@ +using CommonZ; +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class EnumClass(string? name) + : CompilerObject + , IType + , ICTGetMember + , ITypeAssignableToType + , ICompileIRObject + , ICompileIRType + { + #region Build State + + [Flags] + enum BuildState + { + None = 0, + Values = 0b1, + Owner = 0b10, + } + private readonly ObjectBuildState state = new(); + + public bool IsDefined + { + init + { + if (value) + foreach (var item in Enum.GetValues()) + state[item] = true; + } + } + + #endregion + + public IR.EnumClass? IR { get; set; } + + public string? Name { get; set; } = name; + + public IType? MemberType { get; set; } + + public Mapping Values { get; } = []; + + IR.EnumClass ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) + { + if (MemberType is null) + throw new InvalidOperationException(); + + IR ??= new(Name); + + if (IR.Type is null) + { + var underlyingType = compiler.IR.CompileType(MemberType).Unwrap(); + + IR.Type = underlyingType; + } + + if (!state[BuildState.Owner] && owner is not null) + { + state[BuildState.Owner] = true; + + owner.Types.Add(IR); + } + + if (!state[BuildState.Values]) + { + state[BuildState.Values] = true; + + foreach (var value in Values.Values) + compiler.IR.CompileDefinition(value, IR); + } + + return IR; + } + + CompilerObjectResult ICTGetMember.Member(Compiler.Compiler compiler, string member) + { + if (Values.TryGetValue(member, out var value)) + return CompilerObjectResult.Ok(value); + + return CompilerObjectResult.Error( + $"Could not find member {member} in {Name ?? ""}" + ); + } + + IR.EnumClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) + { + return + compiler.IR.CompileDefinition + + (this, null) + .Unwrap(); + } + + bool? ITypeAssignableToType.IsAssignableTo(Compiler.Compiler compiler, IType target) + { + if (compiler.TypeSystem.AreEqual(this, target)) + return true; + if (compiler.TypeSystem.AreEqual(MemberType!, target)) + return true; + + return null; + } + } +} diff --git a/ZSharp.Compiler.Objects/oop/enum/EnumValue.cs b/ZSharp.Compiler.Objects/oop/enum/EnumValue.cs new file mode 100644 index 00000000..ab4a6c4d --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/enum/EnumValue.cs @@ -0,0 +1,72 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class EnumValue(string name) + : CompilerObject + , ICTGet + , IDynamicallyTyped + , ICompileIRCode + , ICompileIRObject + { + #region Build State + + [Flags] + enum BuildState + { + None = 0, + Owner = 0b1, + } + private readonly ObjectBuildState state = new(); + + public bool IsDefined + { + init + { + if (value) + foreach (var item in Enum.GetValues()) + state[item] = true; + } + } + + #endregion + + public IR.EnumValue? IR { get; set; } + + public string Name { get; set; } = name; + + public required EnumClass Owner { get; set; } + + public required CompilerObject Value { get; set; } + + IR.EnumValue ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.EnumClass? owner) + { + if (IR is null) + { + var code = compiler.IR.CompileCode(Value).Unwrap(); + + IR = new(Name, code.Instructions); + } + + if (!state[BuildState.Owner] && owner is not null) + { + state[BuildState.Owner] = true; + + owner.Values.Add(IR); + } + + return IR; + } + + CompilerObjectResult ICTGet.Get(Compiler.Compiler compiler) + => compiler.CG.Get(Value); + + IType IDynamicallyTyped.GetType(Compiler.Compiler compiler) + => compiler.TypeSystem.IsTyped(Value, out var type) + ? type + : throw new(); + + IRCode ICompileIRCode.CompileIRCode(Compiler.Compiler compiler) + => compiler.CompileIRCode(Value); + } +} diff --git a/ZSharp.Compiler.Objects/oop/value type/ValueType.cs b/ZSharp.Compiler.Objects/oop/value type/ValueType.cs new file mode 100644 index 00000000..aa627b3c --- /dev/null +++ b/ZSharp.Compiler.Objects/oop/value type/ValueType.cs @@ -0,0 +1,54 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class ValueType(string? name) + : CompilerObject + , IType + , ICompileIRReference + , ICompileIRType> + { + #region Build State + + [Flags] + enum BuildState + { + None = 0, + } + private readonly ObjectBuildState state = new(); + + public bool IsDefined + { + init + { + if (value) + foreach (var item in Enum.GetValues()) + state[item] = true; + } + } + + #endregion + + public IR.ValueType? IR { get; set; } + + public string? Name { get; set; } = name; + + private IR.ValueType CompileIR(Compiler.Compiler compiler) + { + IR ??= new(Name); + + return IR; + } + + private IR.ValueTypeReference CompileIRReference(Compiler.Compiler compiler) + { + return new(CompileIR(compiler)); + } + + IR.OOPTypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) + => CompileIRReference(compiler); + + IR.ValueTypeReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + => CompileIRReference(compiler); + } +} diff --git a/ZSharp.Compiler/cg objects/types/array/ArrayType.cs b/ZSharp.Compiler/cg objects/types/array/ArrayType.cs new file mode 100644 index 00000000..d5dc87a3 --- /dev/null +++ b/ZSharp.Compiler/cg objects/types/array/ArrayType.cs @@ -0,0 +1,22 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class ArrayType(IType elementType) + : CompilerObject + , IType + , ICompileIRType + { + public IType ElementType { get; set; } = elementType; + + IR.ConstructedClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) + { + var elementType = compiler.IR.CompileType(ElementType).Unwrap(); + + return new(compiler.TypeSystem.ArrayType.IR) + { + Arguments = [elementType] + }; + } + } +} diff --git a/ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs b/ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs new file mode 100644 index 00000000..75597247 --- /dev/null +++ b/ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs @@ -0,0 +1,41 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class ArrayTypeObject(IR.Class ir) + : CompilerObject + , IType + , ICompileIRObject + , IGenericInstantiable + { + public IR.Class IR { get; } = ir; + + CompilerObjectResult IGenericInstantiable.Instantiate(Compiler.Compiler compiler, Argument[] arguments) + { + if (arguments.Length != 1) + return CompilerObjectResult.Error( + $"Expected exactly 1 generic argument, but got {arguments.Length}" + ); + + var elementTypeArgument = arguments[0]; + if (elementTypeArgument.Name is not null) + return CompilerObjectResult.Error( + "Array[] type argument must be positional" + ); + if (elementTypeArgument.Object is not IType elementType) + return CompilerObjectResult.Error( + "Array[] type argument must be a type" + ); + + return CompilerObjectResult.Ok( + Instantiate(elementType) + ); + } + + public ArrayType Instantiate(IType elementType) + => new(elementType); + + IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) + => IR; + } +} diff --git a/ZSharp.Compiler/cg objects/types/pointer/PointerType.cs b/ZSharp.Compiler/cg objects/types/pointer/PointerType.cs new file mode 100644 index 00000000..840cb169 --- /dev/null +++ b/ZSharp.Compiler/cg objects/types/pointer/PointerType.cs @@ -0,0 +1,22 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class PointerType(IType elementType) + : CompilerObject + , IType + , ICompileIRType + { + public IType ElementType { get; set; } = elementType; + + IR.ConstructedClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) + { + var elementType = compiler.IR.CompileType(ElementType).Unwrap(); + + return new(compiler.TypeSystem.PointerType.IR) + { + Arguments = [elementType] + }; + } + } +} diff --git a/ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs b/ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs new file mode 100644 index 00000000..101ca44b --- /dev/null +++ b/ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs @@ -0,0 +1,41 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class PointerTypeObject(IR.Class ir) + : CompilerObject + , IType + , ICompileIRObject + , IGenericInstantiable + { + public IR.Class IR { get; } = ir; + + CompilerObjectResult IGenericInstantiable.Instantiate(Compiler.Compiler compiler, Argument[] arguments) + { + if (arguments.Length != 1) + return CompilerObjectResult.Error( + $"Expected exactly 1 generic argument, but got {arguments.Length}" + ); + + var elementTypeArgument = arguments[0]; + if (elementTypeArgument.Name is not null) + return CompilerObjectResult.Error( + "Pointer[] type argument must be positional" + ); + if (elementTypeArgument.Object is not IType elementType) + return CompilerObjectResult.Error( + "Pointer[] type argument must be a type" + ); + + return CompilerObjectResult.Ok( + Instantiate(elementType) + ); + } + + public PointerType Instantiate(IType elementType) + => new(elementType); + + IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) + => IR; + } +} diff --git a/ZSharp.Compiler/cg objects/types/reference/ReferenceType.cs b/ZSharp.Compiler/cg objects/types/reference/ReferenceType.cs new file mode 100644 index 00000000..7cac23ef --- /dev/null +++ b/ZSharp.Compiler/cg objects/types/reference/ReferenceType.cs @@ -0,0 +1,22 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class ReferenceType(IType elementType) + : CompilerObject + , IType + , ICompileIRType + { + public IType ElementType { get; set; } = elementType; + + IR.ConstructedClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) + { + var elementType = compiler.IR.CompileType(ElementType).Unwrap(); + + return new(compiler.TypeSystem.ReferenceType.IR) + { + Arguments = [elementType] + }; + } + } +} diff --git a/ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs b/ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs new file mode 100644 index 00000000..ca7cddb9 --- /dev/null +++ b/ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs @@ -0,0 +1,41 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class ReferenceTypeObject(IR.Class ir) + : CompilerObject + , IType + , ICompileIRObject + , IGenericInstantiable + { + public IR.Class IR { get; } = ir; + + CompilerObjectResult IGenericInstantiable.Instantiate(Compiler.Compiler compiler, Argument[] arguments) + { + if (arguments.Length != 1) + return CompilerObjectResult.Error( + $"Expected exactly 1 generic argument, but got {arguments.Length}" + ); + + var elementTypeArgument = arguments[0]; + if (elementTypeArgument.Name is not null) + return CompilerObjectResult.Error( + "Reference[] type argument must be positional" + ); + if (elementTypeArgument.Object is not IType elementType) + return CompilerObjectResult.Error( + "Reference[] type argument must be a type" + ); + + return CompilerObjectResult.Ok( + Instantiate(elementType) + ); + } + + public ReferenceType Instantiate(IType elementType) + => new(elementType); + + IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) + => IR; + } +} diff --git a/ZSharp.Compiler/features/cap/generic/IGenericInstantiable.cs b/ZSharp.Compiler/features/cap/generic/IGenericInstantiable.cs new file mode 100644 index 00000000..3dc56cb5 --- /dev/null +++ b/ZSharp.Compiler/features/cap/generic/IGenericInstantiable.cs @@ -0,0 +1,13 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public interface IGenericInstantiable + : CompilerObject + { + public CompilerObjectResult Instantiate( + Compiler.Compiler compiler, + Argument[] arguments + ); + } +} From 07cd0adbd548991981f9f412e3440959627504fa Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 18 Jul 2025 15:03:39 +0300 Subject: [PATCH 180/235] Add more stuff --- Testing/Program.cs | 102 ++++++++++++++---- Testing/Testing.csproj | 5 - ZLoad.Test/TestEnum.cs | 4 + ZSharp v1.sln | 18 ++++ .../ir loader/IRLoader.Impl.cs | 86 ++++++++++++--- .../ir loader/IRLoader.cs | 3 + .../functional/Function.cs | 2 +- .../functional/RTFunction.cs | 7 +- .../functional/body/Local.cs | 4 +- .../generic/GenericFunctionInstance.cs | 97 ----------------- .../definition/GenericFunction.Generic.cs | 10 +- .../generic/definition/GenericFunction.cs | 10 +- .../functional/partial call/PartialCall.cs | 4 +- ZSharp.Compiler.Objects/oop/class/Class.cs | 4 +- .../oop/class/GenericClass.cs | 15 +++ .../oop/class/GenericClassInstance.cs | 4 +- .../oop/constructor/Constructor.cs | 2 +- .../oop/constructor/ConstructorReference.cs | 4 +- .../oop/method/concrete/BoundMethod.cs | 2 +- .../oop/method/concrete/Method.cs | 2 +- .../oop/method/concrete/MethodReference.cs | 4 +- .../oop/method/generic/BoundGenericMethod.cs | 2 +- .../generic/BoundGenericMethodInstance.cs | 2 +- .../generic/BoundGenericMethodReference.cs | 2 +- .../method/generic/GenericMethodInstance.cs | 4 +- .../method/generic/GenericMethodReference.cs | 4 +- .../method/group/BoundMethodOverloadGroup.cs | 4 +- .../oop/method/group/MethodOverloadGroup.cs | 2 +- .../overloading/OverloadGroup.cs | 4 +- .../utils/ObjectBuildState.cs | 2 +- .../cg objects/types/ObjectType.cs | 1 + .../cg objects/types/StringType.cs | 2 +- .../compiler/features/Compiler.Protocols.cs | 2 +- .../core/type system/TypeSystem.cs | 14 ++- ZSharp.Compiler/core/Result.cs | 2 +- .../core/concepts/callable/ICallable.cs | 6 +- .../cg/capabilities/callable/ICTCallable.cs | 2 +- .../features/cg/services/CG.Call.cs | 2 +- ZSharp.IR/ir/modular/module/Module.cs | 20 ++++ ZSharp.IR/ir/oop/Enumclass.cs | 15 --- ZSharp.IR/ir/oop/ValueType.cs | 7 -- .../ir/oop/attributes/ClassAttributes.cs | 8 -- .../ir/oop/attributes/EnumclassAttributes.cs | 8 -- ZSharp.IR/ir/oop/field/FieldReference.cs | 2 +- ZSharp.IR/type system/RuntimeModule.cs | 12 +++ ZSharp.IR/type system/TypeSystem.cs | 6 ++ .../expression/ExpressionCompiler.cs | 41 ++++++- .../statement/StatementCompiler.cs | 5 +- .../importers/StandardLibraryImporter.cs | 2 +- .../import system/importers/StringImporter.cs | 2 +- .../import system/importers/ZSImporter.cs | 2 +- ZSharp.NETCompiler/Compiler.cs | 23 ++++ ZSharp.NETCompiler/ZSharp.NETCompiler.csproj | 17 +++ .../compilers/ModuleCompiler.cs | 6 ++ .../compilers/core/CompilerBase.cs | 7 ++ ZSharp.NETCompiler/compilers/core/Context.cs | 6 ++ ZSharp.Runtime.IL/il2ir/core/ILLoader.cs | 83 +++++++++++--- .../il2ir/loaders/ClassLoader.cs | 12 +-- .../il2ir/loaders/InterfaceLoader.cs | 16 +-- .../il2ir/loaders/ModuleLoader.cs | 4 +- ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 4 +- ZSharpTest/DotNETImporter.cs | 2 +- ZSharpTest/Main.cs | 11 +- ZSharpTest/projects/better-user-system.zs | 1 - ZSharpTest/projects/build.zs | 76 +++++++++++++ ZSharpTest/projects/todo.zs | 9 +- ZSharpTest/test.zs | 77 +------------ ZSharpTest/tests/simple.zs | 35 ++++-- 68 files changed, 602 insertions(+), 363 deletions(-) create mode 100644 ZLoad.Test/TestEnum.cs delete mode 100644 ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs delete mode 100644 ZSharp.IR/ir/oop/Enumclass.cs delete mode 100644 ZSharp.IR/ir/oop/ValueType.cs delete mode 100644 ZSharp.IR/ir/oop/attributes/ClassAttributes.cs delete mode 100644 ZSharp.IR/ir/oop/attributes/EnumclassAttributes.cs create mode 100644 ZSharp.NETCompiler/Compiler.cs create mode 100644 ZSharp.NETCompiler/ZSharp.NETCompiler.csproj create mode 100644 ZSharp.NETCompiler/compilers/ModuleCompiler.cs create mode 100644 ZSharp.NETCompiler/compilers/core/CompilerBase.cs create mode 100644 ZSharp.NETCompiler/compilers/core/Context.cs create mode 100644 ZSharpTest/projects/build.zs diff --git a/Testing/Program.cs b/Testing/Program.cs index 3f4c227f..01d69b98 100644 --- a/Testing/Program.cs +++ b/Testing/Program.cs @@ -1,33 +1,97 @@ -// See https://aka.ms/new-console-template for more information -Console.WriteLine("Hello, World!"); +using System; +using System.Reflection; +using System.Reflection.Emit; +class Program +{ + static void Main() + { + // Define dynamic assembly and module + var assemblyName = new AssemblyName("DynamicAssemblyDemo"); + var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); + var moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule"); -var runtime = new ZSharp.Runtime.NET.Runtime(new()); + // ------------------------- + // Define first type: Person + // ------------------------- + var personBuilder = moduleBuilder.DefineType("Person", TypeAttributes.Public); + var nameField = personBuilder.DefineField("_name", typeof(string), FieldAttributes.Private); + // Constructor: Person(string name) + var ctorBuilder = personBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(string) }); + var ilCtor = ctorBuilder.GetILGenerator(); + ilCtor.Emit(OpCodes.Ldarg_0); + ilCtor.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)!); + ilCtor.Emit(OpCodes.Ldarg_0); + ilCtor.Emit(OpCodes.Ldarg_1); + ilCtor.Emit(OpCodes.Stfld, nameField); + ilCtor.Emit(OpCodes.Ret); -var topLevel = runtime.Import(typeof(TopLevel)); -var topLevelInner = runtime.Import(typeof(TopLevel.Inner)); -var topLevelInnerGeneric = runtime.Import(typeof(TopLevel.Inner)); + // Property: Name + var getNameMethod = personBuilder.DefineMethod("get_Name", MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, typeof(string), Type.EmptyTypes); + var ilGet = getNameMethod.GetILGenerator(); + ilGet.Emit(OpCodes.Ldarg_0); + ilGet.Emit(OpCodes.Ldfld, nameField); + ilGet.Emit(OpCodes.Ret); -Console.ReadLine(); + var nameProp = personBuilder.DefineProperty("Name", PropertyAttributes.None, typeof(string), null); + nameProp.SetGetMethod(getNameMethod); + // Method: SayHello + var sayHelloMethod = personBuilder.DefineMethod("SayHello", MethodAttributes.Public, null, Type.EmptyTypes); + var ilSay = sayHelloMethod.GetILGenerator(); + ilSay.Emit(OpCodes.Ldstr, "Hello, my name is "); + ilSay.Emit(OpCodes.Ldarg_0); + ilSay.Emit(OpCodes.Call, getNameMethod); + ilSay.Emit(OpCodes.Call, typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) })!); + ilSay.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new[] { typeof(string) })!); + ilSay.Emit(OpCodes.Ret); -class TopLevel -{ - public T t; + // Finalize Person type + var personType = personBuilder.CreateTypeInfo()!.AsType(); - public T GetValue() - { - return t; - } + // -------------------------- + // Use Person type instance + // -------------------------- + var person = Activator.CreateInstance(personType, "Alice"); + personType.GetMethod("SayHello")!.Invoke(person, null); - public class Inner - { + // -------------------------- + // Define second type: Employee + // -------------------------- + var employeeBuilder = moduleBuilder.DefineType("Employee", TypeAttributes.Public); - } + // Field: Id + var idField = employeeBuilder.DefineField("Id", typeof(int), FieldAttributes.Public); - public class Inner - { + // Constructor: Employee(int id) + var empCtor = employeeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(int) }); + var ilEmpCtor = empCtor.GetILGenerator(); + ilEmpCtor.Emit(OpCodes.Ldarg_0); + ilEmpCtor.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)!); + ilEmpCtor.Emit(OpCodes.Ldarg_0); + ilEmpCtor.Emit(OpCodes.Ldarg_1); + ilEmpCtor.Emit(OpCodes.Stfld, idField); + ilEmpCtor.Emit(OpCodes.Ret); + + // Method: ShowId() + var showIdMethod = employeeBuilder.DefineMethod("ShowId", MethodAttributes.Public, null, Type.EmptyTypes); + var ilShow = showIdMethod.GetILGenerator(); + ilShow.Emit(OpCodes.Ldstr, "Employee ID: "); + ilShow.Emit(OpCodes.Ldarg_0); + ilShow.Emit(OpCodes.Ldfld, idField); + ilShow.Emit(OpCodes.Box, typeof(int)); + ilShow.Emit(OpCodes.Call, typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(object) })!); + ilShow.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new[] { typeof(string) })!); + ilShow.Emit(OpCodes.Ret); + + // Finalize Employee type + var employeeType = employeeBuilder.CreateTypeInfo()!.AsType(); + // -------------------------- + // Use Employee type instance + // -------------------------- + var employee = Activator.CreateInstance(employeeType, 42); + employeeType.GetMethod("ShowId")!.Invoke(employee, null); } } diff --git a/Testing/Testing.csproj b/Testing/Testing.csproj index 7a60c6bc..2150e379 100644 --- a/Testing/Testing.csproj +++ b/Testing/Testing.csproj @@ -7,9 +7,4 @@ enable - - - - - diff --git a/ZLoad.Test/TestEnum.cs b/ZLoad.Test/TestEnum.cs new file mode 100644 index 00000000..1573df42 --- /dev/null +++ b/ZLoad.Test/TestEnum.cs @@ -0,0 +1,4 @@ +public enum TestEnum +{ + A, B, C +} diff --git a/ZSharp v1.sln b/ZSharp v1.sln index fb24ea45..c9a4ce61 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -50,6 +50,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZLoad.Test", "ZLoad.Test\ZL EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.StandardLibrary.FileSystem", "ZSharp.CT.StandardLibrary.FileSystem\ZSharp.CT.StandardLibrary.FileSystem.csproj", "{7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.NETCompiler", "ZSharp.NETCompiler\ZSharp.NETCompiler.csproj", "{2222D3B2-0148-4AAC-955C-679E7F20C2FA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.ILLoader", "ZSharp.Compiler.ILLoader\ZSharp.Compiler.ILLoader.csproj", "{980FAC95-52E8-499D-96A9-943EE4861EA0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Runtime", "ZSharp.Runtime\ZSharp.Runtime.csproj", "{3CD28041-00F7-4A40-BEFD-4F77809BCBF7}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -144,6 +150,18 @@ Global {7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}.Debug|Any CPU.Build.0 = Debug|Any CPU {7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}.Release|Any CPU.ActiveCfg = Release|Any CPU {7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}.Release|Any CPU.Build.0 = Release|Any CPU + {2222D3B2-0148-4AAC-955C-679E7F20C2FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2222D3B2-0148-4AAC-955C-679E7F20C2FA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2222D3B2-0148-4AAC-955C-679E7F20C2FA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2222D3B2-0148-4AAC-955C-679E7F20C2FA}.Release|Any CPU.Build.0 = Release|Any CPU + {980FAC95-52E8-499D-96A9-943EE4861EA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {980FAC95-52E8-499D-96A9-943EE4861EA0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {980FAC95-52E8-499D-96A9-943EE4861EA0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {980FAC95-52E8-499D-96A9-943EE4861EA0}.Release|Any CPU.Build.0 = Release|Any CPU + {3CD28041-00F7-4A40-BEFD-4F77809BCBF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3CD28041-00F7-4A40-BEFD-4F77809BCBF7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3CD28041-00F7-4A40-BEFD-4F77809BCBF7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3CD28041-00F7-4A40-BEFD-4F77809BCBF7}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index a5f28594..c1d09435 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -123,7 +123,8 @@ private Action Load(ZSharp.IR.OOPType type, Module owner) { ZSharp.IR.Class @class => Load(@class, owner), ZSharp.IR.Interface @interface => Load(@interface, owner), - //ZSharp.IR.Struct @struct => Load(@struct), + ZSharp.IR.EnumClass @enum => Load(@enum, owner), + ZSharp.IR.ValueType valueType => Load(valueType, owner), _ => throw new NotImplementedException(), }; @@ -311,6 +312,61 @@ private Action Load(ZSharp.IR.Interface @interface, Module owner) }; } + private Action Load(ZSharp.IR.EnumClass @enum, Module owner) + { + EnumClass result = new(@enum.Name ?? string.Empty) + { + IR = @enum, + IsDefined = true, + }; + + Context.Objects.Cache(@enum, result); + + owner.Content.Add(result); + + if (result.Name is not null && result.Name != string.Empty) + owner.Members.Add(result.Name, result); + + return () => + { + result.MemberType = Load(@enum.Type); + + foreach (var value in @enum.Values) + { + var valueResult = new EnumValue(value.Name) + { + Value = new RawCode(new(value.Value) + { + Types = [result] + }), + Owner = result + }; + result.Values[value.Name] = valueResult; + } + }; + } + + private Action Load(ZSharp.IR.ValueType valueType, Module owner) + { + Objects.ValueType result = new(valueType.Name ?? string.Empty) + { + IR = valueType, + IsDefined = true, + }; + + Context.Objects.Cache(valueType, result); + + owner.Content.Add(result); + + if (result.Name is not null && result.Name != string.Empty) + owner.Members.Add(result.Name, result); + + return () => + { + + }; + } + private IType Load(ZSharp.IR.IType type) { if (Context.Types.Cache(type, out var result)) @@ -331,21 +387,21 @@ private IType Load(ZSharp.IR.ClassReference classReference) private IType Load(ZSharp.IR.ConstructedClass constructed) { - if (Context.Objects.Cache(constructed.Class, out var genericClass)) + if (Context.Objects.Cache(constructed.Class, out var genericInstantiable)) { - var args = new CommonZ.Utils.Cache(); - - if (genericClass.GenericParameters.Count != constructed.Arguments.Count) - throw new(); - - for (var i = 0; i < constructed.Arguments.Count; i++) - args.Cache(genericClass.GenericParameters[i], Import(constructed.Arguments[i])); - - return new GenericClassInstance(genericClass, new() - { - Scope = genericClass, - CompileTimeValues = args - }); + var instance = genericInstantiable.Instantiate( + Compiler, + [.. constructed.Arguments.Select( + arg => new Argument( + Load(arg) + ) + )] + ).Unwrap(); + + if (instance is not IType type) + throw new("Generic instaitation returned a non-type object"); + + return type; } return Context.Types.Cache(constructed) ?? throw new(); diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs index 46b9396d..02af9155 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs @@ -19,6 +19,9 @@ private void Initialize() Compiler.TypeSystem.Object, }) Context.Types.Cache(Compiler.CompileIRType(type), type); + + Context.Objects.Cache(Compiler.TypeSystem.ArrayType.IR, Compiler.TypeSystem.ArrayType); + Context.Objects.Cache(Compiler.TypeSystem.ReferenceType.IR, Compiler.TypeSystem.ReferenceType); } } } diff --git a/ZSharp.Compiler.Objects/functional/Function.cs b/ZSharp.Compiler.Objects/functional/Function.cs index c52f529f..0ac3c5cc 100644 --- a/ZSharp.Compiler.Objects/functional/Function.cs +++ b/ZSharp.Compiler.Objects/functional/Function.cs @@ -13,7 +13,7 @@ namespace ZSharp.Objects /// public abstract class Function(string? name) : CompilerObject - , ICTCallable + , ICTCallable_Old { diff --git a/ZSharp.Compiler.Objects/functional/RTFunction.cs b/ZSharp.Compiler.Objects/functional/RTFunction.cs index c419d23c..0b121d2b 100644 --- a/ZSharp.Compiler.Objects/functional/RTFunction.cs +++ b/ZSharp.Compiler.Objects/functional/RTFunction.cs @@ -1,12 +1,11 @@ -using CommonZ.Utils; -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using ZSharp.Compiler; namespace ZSharp.Objects { public class RTFunction(string? name) : CompilerObject - , ICTCallable + , ICTCallable_Old , ICTReadable , ICompileIRObject { @@ -47,7 +46,7 @@ public IType? ReturnType set => Signature.ReturnType = value; } - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) { return Call(compiler, arguments); } diff --git a/ZSharp.Compiler.Objects/functional/body/Local.cs b/ZSharp.Compiler.Objects/functional/body/Local.cs index 9ab93edc..c1a9ff18 100644 --- a/ZSharp.Compiler.Objects/functional/body/Local.cs +++ b/ZSharp.Compiler.Objects/functional/body/Local.cs @@ -49,9 +49,9 @@ public IR.VM.Local CompileIRObject(Compiler.Compiler compiler, IR.ICallableBody? state[BuildState.Initializer] = true; IR.Initializer = [.. - compiler.CompileIRCode( + compiler.IR.CompileCode( compiler.TypeSystem.ImplicitCast(Initializer, Type).Unwrap() - ).Instructions, + ).Unwrap().Instructions, new IR.VM.Dup(), new IR.VM.SetLocal(IR) ]; diff --git a/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs b/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs deleted file mode 100644 index e0a1eeba..00000000 --- a/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class GenericFunctionInstance(GenericFunction origin) - : CompilerObject - , ICTCallable - , ICompileIRReference - { - public GenericFunction Origin { get; } = origin; - - public required ReferenceContext Context { get; init; } - - public Signature? Signature { get; set; } - - public IR.Signature? CompiledSignature { get; private set; } - - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (Origin.ReturnType is null) - throw new NotImplementedException(); - - CompileSignature(compiler); - - var args = (Signature as ISignature).MatchArguments(compiler, arguments); - - IRCode code = new(); - - List @params = []; - - @params.AddRange(Signature.Args); - - if (Signature.VarArgs is not null) - @params.Add(Signature.VarArgs); - - @params.AddRange(Signature.KwArgs); - - if (Signature.VarKwArgs is not null) - @params.Add(Signature.VarKwArgs); - - foreach (var param in @params) - code.Append(compiler.CompileIRCode(args[param])); - - code.Append(new([ - new IR.VM.Call(compiler.CompileIRReference(this)) - ])); - - code.Types.Clear(); - if (Origin.ReturnType != compiler.TypeSystem.Void) - code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); - - return new RawCode(code); - } - - IR.GenericFunctionInstance ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) - { - var arguments = Origin.GenericParameters - .Select(genericParameter => Context[genericParameter]) - .Select(compiler.CompileIRType); - - CompileSignature(compiler); - - return new(compiler.CompileIRObject(Origin, null)) - { - Arguments = [.. arguments], - Signature = CompiledSignature, - }; - } - - [MemberNotNull(nameof(Signature), nameof(CompiledSignature))] - private void CompileSignature(Compiler.Compiler compiler) - { - Signature ??= compiler.Feature().CreateReference(Origin.Signature, Context); - - if (CompiledSignature is not null) - return; - - if (Origin.ReturnType is null) - throw new NotImplementedException(); - - CompiledSignature = new(compiler.CompileIRType(compiler.Feature().CreateReference(Origin.ReturnType, Context))); - - foreach (var arg in Signature.Args) - CompiledSignature.Args.Parameters.Add(compiler.CompileIRObject(arg, CompiledSignature)); - - if (Signature.VarArgs is not null) - CompiledSignature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, CompiledSignature); - - foreach (var kwArg in Signature.KwArgs) - CompiledSignature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, CompiledSignature)); - - if (Signature.VarKwArgs is not null) - CompiledSignature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, CompiledSignature); - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs index f888fb05..dd667907 100644 --- a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs +++ b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs @@ -23,10 +23,16 @@ public Result CreateGenericInstance(Compiler.Com genericArguments[parameter] = argument; } + ReferenceContext context = new(); + foreach (var (p, a) in genericArguments) + context.CompileTimeValues.Cache(p, a); + return Result.Ok( - new(this) + new() { - Context = new() + GenericArguments = genericArguments, + GenericFunction = this, + Signature = compiler.Feature().CreateReference(Signature, context) } ); } diff --git a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs index 01249b4c..86aa25aa 100644 --- a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs +++ b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs @@ -6,9 +6,9 @@ namespace ZSharp.Objects public sealed partial class GenericFunction(string? name = null) : CompilerObject , ICompileIRObject - , ICTCallable + , ICTCallable_Old , ICTGetIndex - , IReferencable + , IReferencable { [Flags] enum BuildState @@ -118,7 +118,7 @@ CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) return compiler.Feature().CreateReference(this, context); } - GenericFunctionInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) + GenericFunctionInstance_Old IReferencable.CreateReference(Referencing @ref, ReferenceContext context) { foreach (var genericParameter in GenericParameters) if (!context.CompileTimeValues.Contains(genericParameter)) @@ -131,7 +131,7 @@ GenericFunctionInstance IReferencable.CreateReference(R }; } - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) { ITypeInferenceContext infer; @@ -147,7 +147,7 @@ CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments context.CompileTimeValues.Cache(genericParameter, inferredType); } - var reference = compiler.Feature().CreateReference(this, context); + var reference = compiler.Feature().CreateReference(this, context); var args = (reference.Signature as ISignature)!.MatchArguments(compiler, arguments); diff --git a/ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs b/ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs index de5e07c5..c323f7c5 100644 --- a/ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs +++ b/ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs @@ -5,7 +5,7 @@ namespace ZSharp.Objects { public sealed class PartialCall(CompilerObject target) : CompilerObject - , ICTCallable + , ICTCallable_Old { public CompilerObject Target { get; set; } = target; @@ -13,7 +13,7 @@ public sealed class PartialCall(CompilerObject target) public required ISignature Signature { get; set; } - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) { return compiler.Call(Target, [ .. Arguments, diff --git a/ZSharp.Compiler.Objects/oop/class/Class.cs b/ZSharp.Compiler.Objects/oop/class/Class.cs index 0988c617..cc838b03 100644 --- a/ZSharp.Compiler.Objects/oop/class/Class.cs +++ b/ZSharp.Compiler.Objects/oop/class/Class.cs @@ -9,7 +9,7 @@ public sealed class Class , ICompileIRObject , ICompileIRReference , ICompileIRType> - , ICTCallable + , ICTCallable_Old , IRTCastTo , ICTGetMember_Old , IRTGetMember_Old @@ -130,7 +130,7 @@ CompilerObject IRTGetMember_Old.Member(Compiler.Compiler compiler, Compi } - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) { if (Constructor is null) throw new InvalidOperationException($"Class {Name} is not constructible"); diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs index a65edf7a..7006fc82 100644 --- a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs +++ b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs @@ -1,4 +1,5 @@ using CommonZ.Utils; +using System; using ZSharp.Compiler; namespace ZSharp.Objects @@ -11,6 +12,7 @@ public class GenericClass , IReferencable , ICompileIRObject , IEvaluable + , IGenericInstantiable { [Flags] enum BuildState @@ -73,6 +75,19 @@ public GenericClassInstance CreateReference(Referencing @ref, ReferenceContext c }); } + CompilerObjectResult IGenericInstantiable.Instantiate(Compiler.Compiler compiler, Argument[] arguments) + { + var context = new ReferenceContext(); + + foreach (var (genericParameter, genericArgument) in GenericParameters.Zip(arguments)) + context[genericParameter] = genericArgument.Object; + + return CompilerObjectResult.Ok(new GenericClassInstance(this, new(context) + { + Scope = this + })); + } + CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) { var context = new ReferenceContext(); diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs index e1b4cdb1..ff149af3 100644 --- a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs +++ b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs @@ -8,7 +8,7 @@ public sealed class GenericClassInstance , IClass , ICTGetMember_Old , IRTGetMember_Old - , ICTCallable + , ICTCallable_Old , IReference , ICompileIRType , ICompileIRReference> @@ -91,7 +91,7 @@ public CompilerObject Member(Compiler.Compiler compiler, CompilerObject instance return result; } - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) { CompilerObject? constructor = null; diff --git a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs index fc971160..7d403c5e 100644 --- a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs +++ b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs @@ -8,7 +8,7 @@ namespace ZSharp.Objects { public sealed class Constructor(string? name) : CompilerObject - , ICTCallable + , ICTCallable_Old , ICompileIRObject , IReferencable { diff --git a/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs b/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs index d8203243..452578df 100644 --- a/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs +++ b/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs @@ -4,13 +4,13 @@ namespace ZSharp.Objects { public sealed class ConstructorReference(Constructor origin, ReferenceContext context) : CompilerObject - , ICTCallable + , ICTCallable_Old { public Constructor Origin { get; } = origin; public ReferenceContext Context { get; } = context; - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) { var result = compiler.Call(Origin, arguments); diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/BoundMethod.cs b/ZSharp.Compiler.Objects/oop/method/concrete/BoundMethod.cs index 3f6f99b1..b9492143 100644 --- a/ZSharp.Compiler.Objects/oop/method/concrete/BoundMethod.cs +++ b/ZSharp.Compiler.Objects/oop/method/concrete/BoundMethod.cs @@ -4,7 +4,7 @@ namespace ZSharp.Objects { internal sealed class BoundMethod(Method method, CompilerObject instance) : CompilerObject - , ICTCallable + , ICTCallable_Old { public Method Method { get; } = method; diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs index 9db60cbd..446e0b5b 100644 --- a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs +++ b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs @@ -12,7 +12,7 @@ public sealed class Method(string? name) : CompilerObject , IRTBoundMember , IMethod - , ICTCallable + , ICTCallable_Old , ICompileIRObject , ICompileIRObject , ICompileIRReference diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs b/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs index ef85feba..cfa8ebeb 100644 --- a/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs +++ b/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs @@ -8,7 +8,7 @@ namespace ZSharp.Objects { public sealed class MethodReference(Method origin, ReferenceContext context) : CompilerObject - , ICTCallable + , ICTCallable_Old , ICompileIRReference , IRTBoundMember { @@ -22,7 +22,7 @@ public sealed class MethodReference(Method origin, ReferenceContext context) public IR.Signature? SignatureIR { get; private set; } - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) { if (Origin.ReturnType is null) throw new NotImplementedException(); diff --git a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs index ee455088..c79bcc01 100644 --- a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs +++ b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs @@ -4,7 +4,7 @@ namespace ZSharp.Objects { public sealed class BoundGenericMethod(GenericMethod method, CompilerObject instance) : CompilerObject - , ICTCallable + , ICTCallable_Old , ICTGetIndex , IReferencable { diff --git a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs index b74dc67c..4fd56010 100644 --- a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs +++ b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs @@ -4,7 +4,7 @@ namespace ZSharp.Objects { public sealed class BoundGenericMethodInstance(GenericMethodInstance method, CompilerObject instance) : CompilerObject - , ICTCallable + , ICTCallable_Old { public GenericMethodInstance Method { get; } = method; diff --git a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs index 9f17c721..c1fc6866 100644 --- a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs +++ b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs @@ -4,7 +4,7 @@ namespace ZSharp.Objects { public sealed class BoundGenericMethodReference(GenericMethodReference method, CompilerObject instance) : CompilerObject - , ICTCallable + , ICTCallable_Old { public GenericMethodReference Method { get; } = method; diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs index 7b95669c..4b244274 100644 --- a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs +++ b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs @@ -3,7 +3,7 @@ namespace ZSharp.Objects { public sealed class GenericMethodInstance(GenericMethod origin) : CompilerObject - , ICTCallable + , ICTCallable_Old , ICompileIRReference , IRTBoundMember { @@ -18,7 +18,7 @@ public sealed class GenericMethodInstance(GenericMethod origin) CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) => new BoundGenericMethodInstance(this, value); - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) { if (Origin.ReturnType is null) throw new NotImplementedException(); diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs index 96ccc805..feb4c674 100644 --- a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs +++ b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs @@ -7,7 +7,7 @@ public sealed class GenericMethodReference( ReferenceContext context ) : CompilerObject - , ICTCallable + , ICTCallable_Old , ICompileIRReference , IReferencable , IRTBoundMember @@ -22,7 +22,7 @@ ReferenceContext context public IR.Signature? SignatureIR { get; private set; } - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) { if (Origin.ReturnType is null) throw new NotImplementedException(); diff --git a/ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs b/ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs index f9908bb4..3bc37182 100644 --- a/ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs +++ b/ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs @@ -4,13 +4,13 @@ namespace ZSharp.Objects { public sealed class BoundMethodOverloadGroup(MethodOverloadGroup group, CompilerObject instance) : CompilerObject - , ICTCallable + , ICTCallable_Old { public MethodOverloadGroup Group { get; } = group; public CompilerObject Instance { get; } = instance; - CompilerObject ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) => compiler.Call(Group, [ new(Instance), .. arguments diff --git a/ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs b/ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs index bb805c01..33f0133c 100644 --- a/ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs +++ b/ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs @@ -6,7 +6,7 @@ namespace ZSharp.Objects public sealed class MethodOverloadGroup(string name) : OverloadGroup(name) , CompilerObject - , ICTCallable + , ICTCallable_Old , IImplementation , IRTBoundMember { diff --git a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs index bbeb1dcd..cfdbebe8 100644 --- a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs +++ b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs @@ -5,7 +5,7 @@ namespace ZSharp.Objects { public abstract class OverloadGroup(string name) : CompilerObject - , ICTCallable + , ICTCallable_Old , IMappable where T : CompilerObject @@ -45,7 +45,7 @@ CompilerObject IMappable.Map(Func func) public sealed class OverloadGroup(string name) : OverloadGroup(name) , CompilerObject - , ICTCallable + , ICTCallable_Old , IMappable { diff --git a/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs b/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs index 5c1f6a6b..be8a8269 100644 --- a/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs +++ b/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs @@ -9,7 +9,7 @@ internal sealed class ObjectBuildState public void Set(T state) { - State = (T)(ValueType)(State.ToInt32(null) | state.ToInt32(null)); + State = (T)(System.ValueType)(State.ToInt32(null) | state.ToInt32(null)); } public static bool operator &(ObjectBuildState instance, T value) diff --git a/ZSharp.Compiler/cg objects/types/ObjectType.cs b/ZSharp.Compiler/cg objects/types/ObjectType.cs index 3bdb36b8..b1bf6547 100644 --- a/ZSharp.Compiler/cg objects/types/ObjectType.cs +++ b/ZSharp.Compiler/cg objects/types/ObjectType.cs @@ -10,6 +10,7 @@ public sealed class ObjectType(IR.OOPTypeReference stringType, IType t public IR.OOPTypeReference IR { get; } = stringType; public IType Type { get; } = type; + public string Name { get => IR.Definition.Name!; diff --git a/ZSharp.Compiler/cg objects/types/StringType.cs b/ZSharp.Compiler/cg objects/types/StringType.cs index a3ea2e75..da82a8e4 100644 --- a/ZSharp.Compiler/cg objects/types/StringType.cs +++ b/ZSharp.Compiler/cg objects/types/StringType.cs @@ -5,7 +5,7 @@ namespace ZSharp.Objects public sealed class StringType(IR.OOPTypeReference stringType, IType type) : CompilerObject , ICompileIRType - , ICTCallable + , ICTCallable_Old , IType { public IR.OOPTypeReference IR { get; } = stringType; diff --git a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs index bc36852c..5e3de68b 100644 --- a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs +++ b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs @@ -16,7 +16,7 @@ public IRCode Assign(IRCode irCode, Assignment assignment) public CompilerObject Call(CompilerObject target, Argument[] arguments) { - if (target is ICTCallable ctCallable) + if (target is ICTCallable_Old ctCallable) return ctCallable.Call(this, arguments); // implements typeclass Callable? diff --git a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs index c347780c..58d79e59 100644 --- a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs +++ b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs @@ -22,6 +22,12 @@ public sealed class TypeSystem public ObjectType Object { get; } + public ArrayTypeObject ArrayType { get; } + + public ReferenceTypeObject ReferenceType { get; } + + public PointerTypeObject PointerType { get; } + internal TypeSystem(Compiler compiler) : base(compiler) { @@ -34,10 +40,14 @@ internal TypeSystem(Compiler compiler) Int32 = new(compiler.RuntimeModule.TypeSystem.Int32, Type); Float32 = new RawType(compiler.RuntimeModule.TypeSystem.Float32, Type); Object = new ObjectType(compiler.RuntimeModule.TypeSystem.Object, Type); + + ArrayType = new ArrayTypeObject(compiler.RuntimeModule.TypeSystem.Array); + ReferenceType = new ReferenceTypeObject(compiler.RuntimeModule.TypeSystem.Reference); + PointerType = new(compiler.RuntimeModule.TypeSystem.Pointer); } - public IType Array(CompilerObject type) - => throw new NotImplementedException(); + public IType Array(IType type) + => ArrayType.Instantiate(type); public IType Pointer(CompilerObject type) => throw new NotImplementedException(); diff --git a/ZSharp.Compiler/core/Result.cs b/ZSharp.Compiler/core/Result.cs index d3b2f4f9..97dff21b 100644 --- a/ZSharp.Compiler/core/Result.cs +++ b/ZSharp.Compiler/core/Result.cs @@ -34,7 +34,7 @@ public bool Error([NotNullWhen(true)] out TError? error) => (error = this.error) is not null; public TResult Unwrap() - => result ?? throw new InvalidOperationException(); + => result ?? throw new InvalidOperationException(error!.ToString()); public Result When(Action action) { diff --git a/ZSharp.Compiler/core/concepts/callable/ICallable.cs b/ZSharp.Compiler/core/concepts/callable/ICallable.cs index bca0d5f5..a084dcc1 100644 --- a/ZSharp.Compiler/core/concepts/callable/ICallable.cs +++ b/ZSharp.Compiler/core/concepts/callable/ICallable.cs @@ -3,10 +3,10 @@ /// /// Should be implemented by any binding that is callable. /// - public interface ICTCallable - : ICTCallable_NEW + public interface ICTCallable_Old + : ICTCallable { - CompilerObjectResult ICTCallable_NEW.Call(Compiler compiler, Argument_NEW[] arguments) + CompilerObjectResult ICTCallable.Call(Compiler compiler, Argument_NEW[] arguments) => CompilerObjectResult.Ok( Call(compiler, arguments.Select(arg => new Argument(arg.Name, arg.Value)).ToArray()) ); diff --git a/ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs b/ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs index d858e689..52b19bc7 100644 --- a/ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs +++ b/ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler { - public interface ICTCallable_NEW + public interface ICTCallable : CompilerObject { public CompilerObjectResult Call(Compiler compiler, Argument_NEW[] arguments); diff --git a/ZSharp.Compiler/features/cg/services/CG.Call.cs b/ZSharp.Compiler/features/cg/services/CG.Call.cs index d5f209d6..9f3aea4a 100644 --- a/ZSharp.Compiler/features/cg/services/CG.Call.cs +++ b/ZSharp.Compiler/features/cg/services/CG.Call.cs @@ -6,7 +6,7 @@ public CompilerObjectResult Call(CompilerObject @object, Argument_NEW? _importedModules; private ModuleCollection? _functions; private GlobalCollection? _globals; @@ -45,6 +47,24 @@ public Collection ImportedModules public bool HasImportedModules => !_importedModules.IsNullOrEmpty(); + public Function? EntryPoint + { + get => _entryPoint; + set + { + if (value is not null && value.Module != this) + throw new InvalidOperationException( + "Module entry point must be a strict member of the" + + "module." + ); + + _entryPoint = value; + } + } + + [MemberNotNullWhen(true, nameof(EntryPoint))] + public bool HasEntryPoint => _entryPoint is not null; + public Collection Functions { get diff --git a/ZSharp.IR/ir/oop/Enumclass.cs b/ZSharp.IR/ir/oop/Enumclass.cs deleted file mode 100644 index e74c8c95..00000000 --- a/ZSharp.IR/ir/oop/Enumclass.cs +++ /dev/null @@ -1,15 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.IR -{ - public sealed class Enumclass : OOPType - { - public string? Name { get; set; } - - public EnumclassAttributes Attributes { get; set; } = EnumclassAttributes.None; - - public IType Type { get; set; } - - //public Collection Values { get; } - } -} diff --git a/ZSharp.IR/ir/oop/ValueType.cs b/ZSharp.IR/ir/oop/ValueType.cs deleted file mode 100644 index f11f0ee0..00000000 --- a/ZSharp.IR/ir/oop/ValueType.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.IR -{ - public sealed class ValueType : OOPType - { - - } -} diff --git a/ZSharp.IR/ir/oop/attributes/ClassAttributes.cs b/ZSharp.IR/ir/oop/attributes/ClassAttributes.cs deleted file mode 100644 index 51527935..00000000 --- a/ZSharp.IR/ir/oop/attributes/ClassAttributes.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.IR -{ - [Flags] - public enum ClassAttributes - { - None = 0, - } -} \ No newline at end of file diff --git a/ZSharp.IR/ir/oop/attributes/EnumclassAttributes.cs b/ZSharp.IR/ir/oop/attributes/EnumclassAttributes.cs deleted file mode 100644 index 9d6d2518..00000000 --- a/ZSharp.IR/ir/oop/attributes/EnumclassAttributes.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.IR -{ - [Flags] - public enum EnumclassAttributes - { - None = 0, - } -} diff --git a/ZSharp.IR/ir/oop/field/FieldReference.cs b/ZSharp.IR/ir/oop/field/FieldReference.cs index 9d65cce9..64a1298b 100644 --- a/ZSharp.IR/ir/oop/field/FieldReference.cs +++ b/ZSharp.IR/ir/oop/field/FieldReference.cs @@ -2,7 +2,7 @@ { public sealed class FieldReference(Field field) { - public Field Member { get; set; } = field; + public Field Field { get; set; } = field; public required OOPTypeReference OwningType { get; set; } } diff --git a/ZSharp.IR/type system/RuntimeModule.cs b/ZSharp.IR/type system/RuntimeModule.cs index 000208c1..235c31cd 100644 --- a/ZSharp.IR/type system/RuntimeModule.cs +++ b/ZSharp.IR/type system/RuntimeModule.cs @@ -27,6 +27,10 @@ private static RuntimeModule CreateStandardRuntimeModule() ClassReference float32; + Class array; + Class reference; + Class pointer; + { module.Types.Add((type = new(new("Type"))).Definition); module.Types.Add((@object = new(new("Object"))).Definition); @@ -39,6 +43,10 @@ private static RuntimeModule CreateStandardRuntimeModule() module.Types.Add((int32 = new(new("Int32"))).Definition); module.Types.Add((float32 = new(new("Float32"))).Definition); + + module.Types.Add(array = new("Array")); + module.Types.Add(reference = new("Reference")); + module.Types.Add(pointer = new("Pointer")); } return new(module, new() @@ -54,6 +62,10 @@ private static RuntimeModule CreateStandardRuntimeModule() Int32 = int32, Float32 = float32, + + Array = array, + Reference = reference, + Pointer = pointer, }); } } diff --git a/ZSharp.IR/type system/TypeSystem.cs b/ZSharp.IR/type system/TypeSystem.cs index eba34901..3435eaf7 100644 --- a/ZSharp.IR/type system/TypeSystem.cs +++ b/ZSharp.IR/type system/TypeSystem.cs @@ -17,5 +17,11 @@ public sealed class TypeSystem public ClassReference Int32 { get; init; } = null!; public ClassReference Float32 { get; init; } = null!; + + public Class Array { get; init; } = null!; + + public Class Reference { get; init; } = null!; + + public Class Pointer { get; init; } = null!; } } diff --git a/ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.cs index 8d2282bd..a855a893 100644 --- a/ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.cs +++ b/ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.cs @@ -61,13 +61,44 @@ private ObjectResult Compile(BinaryExpression binary) private ObjectResult Compile(CallExpression call) { - var callable = Compiler.CompileNode(call.Callee).Unwrap(); + if ( + Compiler.CompileNode(call.Callee) + .When(out var callable) + .Error(out var error) + ) + return ObjectResult.Error(error); - var args = call.Arguments.Select(arg => new Argument_NEW(arg.Name, Compiler.CompileNode(arg.Value).Unwrap())); + var argsResults = call.Arguments + .Select( + arg => + { + if ( + Compiler.CompileNode(arg.Value) + .When(out var value) + .Error(out var error) + ) + return Result, Error>.Error(error); + return Result, Error>.Ok( + new Argument_NEW(arg.Name, value!) + ); + } + ) + .ToArray(); + + if (CombineErrorResults(argsResults, out var argsError)) + return ObjectResult.Error(argsError); - return ObjectResult.Ok( - Compiler.Compiler.CG.Call(callable, args.ToArray()).Unwrap() - ); + if ( + Compiler.Compiler.CG.Call( + callable!, + [.. argsResults.Select(arg => arg.Unwrap())] + ) + .When(out var result) + .Error(out var callError) + ) + return Compiler.CompilationError(callError, call); + + return ObjectResult.Ok(result!); } private ObjectResult Compile(CastExpression cast) diff --git a/ZSharp.Interpreter/source-compiler/core-compilers/statement/StatementCompiler.cs b/ZSharp.Interpreter/source-compiler/core-compilers/statement/StatementCompiler.cs index 7465fbb4..ac4b248e 100644 --- a/ZSharp.Interpreter/source-compiler/core-compilers/statement/StatementCompiler.cs +++ b/ZSharp.Interpreter/source-compiler/core-compilers/statement/StatementCompiler.cs @@ -62,7 +62,10 @@ private ObjectResult Compile(ExpressionStatement expressionStatement) if (expressionStatement.Expression is null) return ObjectResult.Ok(new Objects.RawCode(new())); - var coResult = Compiler.CompileNode(expressionStatement.Expression); + var coResult = expressionStatement.Expression switch { + WhileExpression @while => Compile(@while), + _ => Compiler.CompileNode(expressionStatement.Expression) + }; if ( coResult diff --git a/ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs b/ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs index 0c6aba55..58a06930 100644 --- a/ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs +++ b/ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs @@ -5,7 +5,7 @@ namespace ZSharp.ZSSourceCompiler { public sealed class StandardLibraryImporter(Interpreter.Interpreter interpreter) : CompilerObject - , ICTCallable + , ICTCallable_Old { public Mapping Libraries { get; } = []; diff --git a/ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs b/ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs index 794513e4..c147d835 100644 --- a/ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs +++ b/ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs @@ -5,7 +5,7 @@ namespace ZSharp.ZSSourceCompiler { public sealed class StringImporter(Interpreter.Interpreter interpreter) : CompilerObject - , ICTCallable + , ICTCallable_Old { public Mapping Importers { get; } = []; diff --git a/ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs b/ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs index a36571af..37601b18 100644 --- a/ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs +++ b/ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs @@ -5,7 +5,7 @@ namespace ZSharp.ZSSourceCompiler { public sealed class ZSImporter(Interpreter.Interpreter interpreter) : CompilerObject - , ICTCallable + , ICTCallable_Old { public Mapping Libraries { get; } = []; diff --git a/ZSharp.NETCompiler/Compiler.cs b/ZSharp.NETCompiler/Compiler.cs new file mode 100644 index 00000000..fcf2c692 --- /dev/null +++ b/ZSharp.NETCompiler/Compiler.cs @@ -0,0 +1,23 @@ +using Mono.Cecil; + +namespace ZSharp.NETCompiler +{ + public sealed class Compiler + { + public ModuleDefinition Compile(IR.Module module) + { + if (module.HasSubmodules) + throw new NotSupportedException(); + + var result = ModuleDefinition.CreateModule( + module.Name ?? "", + new ModuleParameters() + { + Kind = module.HasEntryPoint ? ModuleKind.Console : ModuleKind.Dll + } + ); + + return result; + } + } +} diff --git a/ZSharp.NETCompiler/ZSharp.NETCompiler.csproj b/ZSharp.NETCompiler/ZSharp.NETCompiler.csproj new file mode 100644 index 00000000..215be2da --- /dev/null +++ b/ZSharp.NETCompiler/ZSharp.NETCompiler.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/ZSharp.NETCompiler/compilers/ModuleCompiler.cs b/ZSharp.NETCompiler/compilers/ModuleCompiler.cs new file mode 100644 index 00000000..7fbf13a1 --- /dev/null +++ b/ZSharp.NETCompiler/compilers/ModuleCompiler.cs @@ -0,0 +1,6 @@ +namespace ZSharp.NETCompiler +{ + internal sealed class ModuleCompiler + { + } +} diff --git a/ZSharp.NETCompiler/compilers/core/CompilerBase.cs b/ZSharp.NETCompiler/compilers/core/CompilerBase.cs new file mode 100644 index 00000000..f541b337 --- /dev/null +++ b/ZSharp.NETCompiler/compilers/core/CompilerBase.cs @@ -0,0 +1,7 @@ +namespace ZSharp.NETCompiler +{ + internal abstract class CompilerBase(Context context) + { + public Context Context { get; } = context; + } +} diff --git a/ZSharp.NETCompiler/compilers/core/Context.cs b/ZSharp.NETCompiler/compilers/core/Context.cs new file mode 100644 index 00000000..a9319975 --- /dev/null +++ b/ZSharp.NETCompiler/compilers/core/Context.cs @@ -0,0 +1,6 @@ +namespace ZSharp.NETCompiler +{ + internal sealed class Context + { + } +} diff --git a/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs b/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs index d5fcfc86..0cb97cb4 100644 --- a/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs @@ -15,29 +15,33 @@ public IType LoadType(Type type) if (type.IsTypeDefinition) { - var genericArguments = type.GenericTypeArguments.Select(LoadType).ToList(); + if (type.GenericTypeArguments.Length != 0) + throw new InvalidOperationException(); - var @class = new ClassLoader(this, type).Load(); + OOPType def; - if (genericArguments.Count == 0) result = new ClassReference(@class); - else if (type.IsClass) result = new ConstructedClass(@class) - { - Arguments = [.. genericArguments], - }; - //else if (type.IsInterface) result = new ILInterfaceLoader(this, type).Load(); - //else if (type.IsEnum) result = new ILEnumLoader(this, type).Load(); - //else if (type.IsValueType) result = new ILStructLoader(this, type).Load(); + if (type.IsClass) def = new ClassLoader(this, type).Load(); + else if (type.IsInterface) def = new InterfaceLoader(this, type).Load(); + else if (type.IsEnum) def = new EnumerationLoader(this, type).Load(); + else if (type.IsValueType) def = new ValueTypeLoader(this, type).Load(); else throw new ArgumentException("Type must be a type definition.", nameof(type)); - return result; + return def switch + { + Class @class => new ClassReference(@class), + Interface @interface => new InterfaceReference(@interface), + EnumClass @enum => @enum, + IR.ValueType valueType => new ValueTypeReference(valueType), + _ => throw new NotSupportedException() + }; } if (type.IsArray) - throw new NotImplementedException(); + return LoadArrayType(type); if (type.IsPointer) - throw new NotImplementedException(); + return LoadPointerType(type); if (type.IsByRef) - throw new NotImplementedException(); + return LoadReferenceType(type); if (type.IsConstructedGenericType) { @@ -56,6 +60,14 @@ public IType LoadType(Type type) { Arguments = [.. genericArguments], }, + Interface @interface => new ConstructedInterface(@interface) + { + Arguments = [.. genericArguments], + }, + IR.ValueType valueType => new ConstructedValueType(valueType) + { + Arguments = [.. genericArguments], + }, _ => throw new NotImplementedException() }; } @@ -67,9 +79,50 @@ public T LoadType(Type type) where T : IType => (T)LoadType(type); - public IR.Module LoadModule(IL.Module module) + public Module LoadModule(IL.Module module) { return new ModuleLoader(this, module).Load(); } + + private IType LoadArrayType(Type type) + { + var elementType = LoadType(type.GetElementType()!); + + return new ConstructedClass( + RuntimeModule.TypeSystem.Array + ) { + Arguments = [ + elementType + ] + }; + } + + private IType LoadPointerType(Type type) + { + var elementType = LoadType(type.GetElementType()!); + + return new ConstructedClass( + RuntimeModule.TypeSystem.Pointer + ) + { + Arguments = [ + elementType + ] + }; + } + + private IType LoadReferenceType(Type type) + { + var elementType = LoadType(type.GetElementType()!); + + return new ConstructedClass( + RuntimeModule.TypeSystem.Reference + ) + { + Arguments = [ + elementType + ] + }; + } } } diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs index 51140705..95911619 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs @@ -220,16 +220,10 @@ private Class LoadClass(Type type) private Interface LoadInterface(Type type) => new InterfaceLoader(Loader, type).Load(); - private Enumclass LoadEnum(Type type) - { - return new(); - throw new NotImplementedException(); - } + private EnumClass LoadEnum(Type type) + => new EnumerationLoader(Loader, type).Load(); private IR.ValueType LoadStruct(Type type) - { - return new(); - throw new NotImplementedException(); - } + => new ValueTypeLoader(Loader, type).Load(); } } diff --git a/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs index c7b50d0d..3e0f8a14 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs @@ -60,8 +60,8 @@ private void LoadGenericParameters() private void LoadInterfaceImplementations() { - foreach (var @interface in Input.GetInterfaces()) - LoadInterfaceImplementation(@interface, Input.GetInterfaceMap(@interface)); + //foreach (var @interface in Input.GetInterfaces()) + // LoadInterfaceImplementation(@interface, Input.GetInterfaceMap(@interface)); } private void LoadProperties() @@ -161,16 +161,10 @@ private Class LoadClass(Type type) private Interface LoadInterface(Type type) => new InterfaceLoader(Loader, type).Load(); - private Enumclass LoadEnum(Type type) - { - return new(); - throw new NotImplementedException(); - } + private EnumClass LoadEnum(Type type) + => new EnumerationLoader(Loader, type).Load(); private IR.ValueType LoadStruct(Type type) - { - return new(); - throw new NotImplementedException(); - } + => new ValueTypeLoader(Loader, type).Load(); } } diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs index 1432ceee..c4f8a4a2 100644 --- a/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs +++ b/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs @@ -103,9 +103,7 @@ private void LoadInterface(Type type) => Output.Types.Add(new InterfaceLoader(Loader, type).Load()); private void LoadEnum(Type type) - { - throw new NotImplementedException(); - } + => Output.Types.Add(new EnumerationLoader(Loader, type).Load()); private void LoadStruct(Type type) { diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs index 399e9bfe..cf8f86f2 100644 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs @@ -106,8 +106,8 @@ public IL.FieldInfo LoadReference(IR.FieldReference @ref) { var type = LoadType(@ref.OwningType); - if (!Context.Cache(@ref.Member, out var def)) - throw new InvalidOperationException($"Field {@ref.Member.Name} was not loaded"); + if (!Context.Cache(@ref.Field, out var def)) + throw new InvalidOperationException($"Field {@ref.Field.Name} was not loaded"); if (!type.IsGenericType) return def; diff --git a/ZSharpTest/DotNETImporter.cs b/ZSharpTest/DotNETImporter.cs index 8be0570a..cae64571 100644 --- a/ZSharpTest/DotNETImporter.cs +++ b/ZSharpTest/DotNETImporter.cs @@ -5,7 +5,7 @@ namespace ZSharp { public sealed class DotNETImporter(Interpreter.Interpreter interpreter) : Objects.CompilerObject - , ICTCallable + , ICTCallable_Old { private readonly Interpreter.Interpreter interpreter = interpreter; diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index 165fec8c..196a51a5 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -73,6 +73,8 @@ expressionParser.InfixL("==", 30); expressionParser.InfixL("!=", 30); + expressionParser.InfixL(LangParser.Keywords.Or, 15); + expressionParser.Led(TokenType.LParen, LangParser.ParseCallExpression, 100); expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); @@ -135,6 +137,7 @@ new ZSharp.DotNETImporter(interpreter) ); + new Referencing(interpreter.Compiler); new OOP(interpreter.Compiler); @@ -190,11 +193,11 @@ var mainModuleIL = runtime.Import(mainModuleIR); var mainModuleGlobals = mainModuleIL.GetType("") ?? throw new(); - //foreach (var type in mainModuleIL.GetTypes()) - // DecompileType(type); + foreach (var type in mainModuleIL.GetTypes()) + DecompileType(type); - //foreach (var method in mainModuleIL.GetMethods()) - // Decompile(method); + foreach (var method in mainModuleIL.GetMethods()) + Decompile(method); var mainMethod = mainModuleGlobals.GetMethod("main", []); diff --git a/ZSharpTest/projects/better-user-system.zs b/ZSharpTest/projects/better-user-system.zs index b9c95cf0..b06299d0 100644 --- a/ZSharpTest/projects/better-user-system.zs +++ b/ZSharpTest/projects/better-user-system.zs @@ -16,7 +16,6 @@ import { input, print } from "std:io"; import { List } from "net:ZLoad.Test.dll"; - module Program; diff --git a/ZSharpTest/projects/build.zs b/ZSharpTest/projects/build.zs new file mode 100644 index 00000000..ea30fe50 --- /dev/null +++ b/ZSharpTest/projects/build.zs @@ -0,0 +1,76 @@ +/* + * This file is responsible for building a Z# project. + * + * Requirements: + * [x] FS module + * [x] Directory Class + * [x] Operator / + * [x] Current Directory + * [x] File Class + * [x] Path Class + * [x] Operator / + * [x] `as` keyword for safe conversion + * [ ] Nullable types `T?` + * [x] `is of` operator for type matching + * [ ] custom importer for source of type `File` + * [ ] Project compiler + * [ ] Expose the compiler to Z# (even without members) + * [ ] .NET platform compiler + * [ ] Expose Mono.Cecil ModuleDefinition class (specifically, the `Write(string)` method) +*/ + + +import { + Directory, + File +} from "std:fs"; + + +// The root path of the project. This is usually where this +// script is. +let projectRoot = Directory.cwd(); + +// Source root is the root path of all project source files. +// Only files in this path are considered for discovery. +let sourceRoot = (projectRoot / "src") as Directory? or projectRoot; + +// Custom init file so users don't have to mess with this file. +if ((projectRoot / "init.zs") is initFile of File) + import initFile; + +// Project compiler is a specialized source compiler for compiling +// projects. +import { + Project, + ProjectCompiler +} from "net:ZSharp.ZSProjectCompiler.dll"; + +// The Project object holds the state of compiling the project. +let project = Project( + projectRoot.name, // project name + projectRoot, // project root directory + sourceRoot, // source files root directory +); + +project.discoverZSFiles(); // populates project.sourceFiles + +// Import the current compiler +import { compiler } from "core:compiler"; + +let projectCompiler = ProjectCompiler(compiler); +projectCompiler.compile(project); + +// Create output directory if it doesn't exist +let outDir = projectRoot.createDirectory("dist", existsOk: true); + +// Import the .NET platform compiler +import { + Compiler as NETCompiler +} from "core:platform/.net"; + +let netCompiler = NETCompiler(); + +for (let module in project.modules) { // IR + let netModule = netCompiler.compile(module); + netModule.write(module.name + if (module.entryPoint) ".exe" else ".dll"); +} diff --git a/ZSharpTest/projects/todo.zs b/ZSharpTest/projects/todo.zs index 3368875f..a5079f8a 100644 --- a/ZSharpTest/projects/todo.zs +++ b/ZSharpTest/projects/todo.zs @@ -42,10 +42,11 @@ module Program { fun do(): bool { print("Welcome to The ToDo List App! Please choose what to do:"); - print("1. Add an item."); - print("2. List all items."); - print("3. Remove an item."); - print("4. Exit program."); + print("-------------------------------------------------------"); + print("\t1. Add an item."); + print("\t2. List all items."); + print("\t3. Remove an item."); + print("\t4. Exit program."); let cmd = input("> "); diff --git a/ZSharpTest/test.zs b/ZSharpTest/test.zs index 1cb7f9b9..341c5317 100644 --- a/ZSharpTest/test.zs +++ b/ZSharpTest/test.zs @@ -1,77 +1,10 @@ -import { print as output } from "std:io"; +import { print } from "std:io"; -module Lib { - fun bar(x: string = "hello"): string { - return x; - } - - fun id(x: type): type { - output(x); - return x; - } -} module Program; -fun main(): i32 { - blah(); - - output(pi + 5.0); - - output(1 + 1); - - output(true); - output(false); - - return foo.bar(); -} - -let x = y; -let y = "Hello"; - -let exitCode = 100; - -let pi = 3.14; - -let foo = Foo(); - -fun blah(): Lib.id(string) { - let tmp = Lib.bar(x); - - return tmp; +fun main(): void { + print(hello); + + return; } - -class Foo { - let x = Lib.bar(y); - - new(self: Foo) - { - - } - - fun bar(this): i32 { - output("bar"); - - // zzz(this); - - let blah = Blah(); - blah.v = "zzz arg"; - - this.zzz(v); - - return exitCode; - } - - fun zzz(this, x: class Blah { let v: string = ""; }): void { - output(this.x = x.v); - - return; - } -} - -/* -if (isProduction) - fun foo() { } -else - import { foo } from "foo"; -*/ \ No newline at end of file diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs index 8c2a19a1..5473346f 100644 --- a/ZSharpTest/tests/simple.zs +++ b/ZSharpTest/tests/simple.zs @@ -4,11 +4,14 @@ import { Console, List, TestClass, + TestEnum, TestInterface, greet, id } from "net:ZLoad.Test.dll"; -import { Directory } from "net:ZSharp.CT.StandardLibrary.FileSystem.dll"; +import { Directory, File } from "net:ZSharp.CT.StandardLibrary.FileSystem.dll"; + +import { Expression, LiteralType } from "net:ZSharp.AST.dll"; print("Hello, Document!"); @@ -78,7 +81,7 @@ fun testBaseClass(test: BaseClass): void { } fun main(): void { -/* + let c1 = MyClass(); let c2 = OtherClass(5); @@ -93,16 +96,34 @@ fun main(): void { let cwd = Directory.cwd(); print(cwd.toString()); - let filePath = cwd / "tests" / "simple.zs"; + let testsDirectory = cwd / "tests" as Directory; + let filePath = testsDirectory / "simple.zs"; print(filePath.toString()); - print(filePath.asFile().toString()); - */ + //print(filePath.asFile().toString()); + print(id("Id [T: string]")); + + let base: Base = Derived(); base.baseMethod(); - if (base is derived of Derived) - derived.derivedMethod(); + //if (base is derived of Derived) + // derived.derivedMethod(); + + let derived = base as Derived; + derived.derivedMethod(); + + if (filePath is simpleFilePath of File) + print(simpleFilePath.getContent()); + + let testDirectory = testsDirectory.createDirectory("test", existsOk: true); + + //testsDirectory.createDirectory("test", existsOk: false); + + let testEnum = TestEnum.C; + print(string(testEnum)); + print(string(LiteralType.False)); + return; } From 08d0bc72f0d11695756c2c2714329427073293af Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 18 Jul 2025 16:40:12 +0300 Subject: [PATCH 181/235] Add more loaders to runtime --- .../load/EmitLoader.Load.Type.ValueType.cs | 7 --- .../loader/emit/load/EmitLoader.Load.Type.cs | 20 ++++++ .../loader/helpers/TypeLoaderHelper.cs | 35 +++++++++++ .../class/load/ClassLoader.Load.Method.cs | 4 +- .../class/load/ClassLoader.Load.Type.cs | 5 +- .../loaders/class/load/ClassLoader.Load.cs | 11 +++- .../enum/EnumClassLoader.T.cs} | 4 +- .../loaders/enum/EnumClassLoader.Tasks.cs | 12 ++++ .../loader/loaders/enum/EnumClassLoader.cs | 16 +++++ .../enum/load/EnumClassLoader.Load.Method.cs | 38 ++++++++++++ .../enum/load/EnumClassLoader.Load.Type.cs | 10 +++ .../enum/load/EnumClassLoader.Load.Value.cs | 17 ++++++ .../loaders/enum/load/EnumClassLoader.Load.cs | 53 ++++++++++++++++ .../interface/InterfaceLoader.Context.cs | 9 +++ .../interface/InterfaceLoader.T.cs} | 4 +- .../interface/InterfaceLoader.Tasks.cs | 22 +++++++ .../loaders/interface/InterfaceLoader.cs | 16 +++++ .../load/InterfaceLoader.Load.Generic.cs | 20 ++++++ .../load/InterfaceLoader.Load.Method.cs | 38 ++++++++++++ .../load/InterfaceLoader.Load.Type.cs | 10 +++ .../interface/load/InterfaceLoader.Load.cs | 53 ++++++++++++++++ .../loader/loaders/module/ModuleLoader.cs | 6 +- .../loaders/module/load/ModuleLoader.Load.cs | 15 +++++ .../value type/ValueTypeLoader.Context.cs | 9 +++ .../value type/ValueTypeLoader.T.cs} | 4 +- .../value type/ValueTypeLoader.Tasks.cs | 22 +++++++ .../loaders/value type/ValueTypeLoader.cs | 16 +++++ .../load/ValueTypeLoader.Load.Constructor.cs | 22 +++++++ .../load/ValueTypeLoader.Load.Field.cs | 17 ++++++ .../load/ValueTypeLoader.Load.Generic.cs | 20 ++++++ .../load/ValueTypeLoader.Load.Method.cs | 38 ++++++++++++ .../load/ValueTypeLoader.Load.Type.cs | 10 +++ .../value type/load/ValueTypeLoader.Load.cs | 61 +++++++++++++++++++ .../runtime/cache/Runtime.Cache.Module.cs | 9 +++ 34 files changed, 632 insertions(+), 21 deletions(-) delete mode 100644 ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.ValueType.cs create mode 100644 ZSharp.Runtime/loader/helpers/TypeLoaderHelper.cs rename ZSharp.Runtime/loader/{emit/load/EmitLoader.Load.Type.Class.cs => loaders/enum/EnumClassLoader.T.cs} (54%) create mode 100644 ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.Tasks.cs create mode 100644 ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.cs create mode 100644 ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Method.cs create mode 100644 ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs create mode 100644 ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Value.cs create mode 100644 ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs create mode 100644 ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Context.cs rename ZSharp.Runtime/loader/{emit/load/EmitLoader.Load.Type.Enum.cs => loaders/interface/InterfaceLoader.T.cs} (54%) create mode 100644 ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs create mode 100644 ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.cs create mode 100644 ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Generic.cs create mode 100644 ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Method.cs create mode 100644 ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs create mode 100644 ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs create mode 100644 ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Context.cs rename ZSharp.Runtime/loader/{emit/load/EmitLoader.Load.Type.Interface.cs => loaders/value type/ValueTypeLoader.T.cs} (54%) create mode 100644 ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Tasks.cs create mode 100644 ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.cs create mode 100644 ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Constructor.cs create mode 100644 ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Field.cs create mode 100644 ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Generic.cs create mode 100644 ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Method.cs create mode 100644 ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs create mode 100644 ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.cs diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.ValueType.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.ValueType.cs deleted file mode 100644 index 2e01bae7..00000000 --- a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.ValueType.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Runtime.Loaders -{ - partial class EmitLoader - { - - } -} diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs index 444051d5..590c4a88 100644 --- a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs +++ b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs @@ -16,6 +16,26 @@ public Type LoadType(IR.OOPType type) IRType = def, Tasks = tasks }.Load(), + IR.EnumClass def => new EnumClassLoader(this) + { + ILType = StandaloneModule.DefineType( + def.Name ?? throw new(), + IL.TypeAttributes.Public | IL.TypeAttributes.Sealed, + typeof(Enum) + ), + IRType = def, + Tasks = tasks + }.Load(), + IR.Interface def => new InterfaceLoader(this) + { + ILType = StandaloneModule.DefineType( + def.Name ?? throw new(), + IL.TypeAttributes.Public | IL.TypeAttributes.Interface + ), + IRType = def, + Tasks = tasks + }.Load(), + IR.ValueType def => throw new NotSupportedException(), _ => throw new NotSupportedException(), }; tasks.RunUntilComplete(); diff --git a/ZSharp.Runtime/loader/helpers/TypeLoaderHelper.cs b/ZSharp.Runtime/loader/helpers/TypeLoaderHelper.cs new file mode 100644 index 00000000..b6159aa9 --- /dev/null +++ b/ZSharp.Runtime/loader/helpers/TypeLoaderHelper.cs @@ -0,0 +1,35 @@ +namespace ZSharp.Runtime.Loaders +{ + internal static class TypeLoaderHelper + { + public static Type LoadType(EmitLoader loader, Emit.TypeBuilder parentBuilder, IR.OOPType type) + { + var tasks = new TaskManager(() => { }); + var result = type switch + { + IR.Class def => new ClassLoader(loader) + { + ILType = parentBuilder.DefineNestedType( + def.Name ?? throw new(), + IL.TypeAttributes.Public + ), + IRType = def, + Tasks = tasks + }.Load(), + IR.Interface def => new InterfaceLoader(loader) + { + ILType = parentBuilder.DefineNestedType( + def.Name ?? throw new(), + IL.TypeAttributes.Public | IL.TypeAttributes.Interface + ), + IRType = def, + Tasks = tasks + }.Load(), + _ => throw new NotSupportedException(), + }; + loader.Runtime.AddTypeDefinition(type, result); + tasks.RunUntilComplete(); + return result; + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs index 15e64b14..853f2b7f 100644 --- a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs +++ b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs @@ -1,6 +1,4 @@ -using Microsoft.VisualBasic; - -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Runtime.Loaders { partial class ClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs index 02d00577..793a6ad9 100644 --- a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs +++ b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs @@ -2,6 +2,9 @@ { partial class ClassLoader { - + private void LoadNestedType(IR.OOPType type) + { + TypeLoaderHelper.LoadType(Loader, ILType, type); + } } } diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs index 73f1b9f5..641aad01 100644 --- a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs +++ b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs @@ -24,6 +24,8 @@ private void LoadAll() LoadNestedTypes(); + AddTask(LoadBase); + AddTask(LoadFields); AddTask(LoadConstructors); @@ -31,9 +33,16 @@ private void LoadAll() AddTask(LoadMethods); } + private void LoadBase() + { + if (IRType.Base is not null) + ILType.SetParent(Loader.Runtime.ImportType(IRType.Base)); + } + private void LoadNestedTypes() { - throw new NotImplementedException(); + foreach (var type in IRType.NestedTypes) + LoadNestedType(type); } private void LoadFields() diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Class.cs b/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.T.cs similarity index 54% rename from ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Class.cs rename to ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.T.cs index 2e01bae7..3fa282e3 100644 --- a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Class.cs +++ b/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.T.cs @@ -1,7 +1,7 @@ namespace ZSharp.Runtime.Loaders { - partial class EmitLoader + partial class EnumClassLoader { - + } } diff --git a/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.Tasks.cs b/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.Tasks.cs new file mode 100644 index 00000000..1ffe9b52 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.Tasks.cs @@ -0,0 +1,12 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EnumClassLoader + { + public required TaskManager Tasks { get; init; } + + private void AddTask(Action task) + { + Tasks.AddTask(task); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.cs b/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.cs new file mode 100644 index 00000000..4622fce7 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Runtime.Loaders +{ + internal sealed partial class EnumClassLoader + : LoaderBase + { + public required Emit.TypeBuilder ILType { get; init; } + + public required IR.EnumClass IRType { get; init; } + + public EnumClassLoader(EmitLoader loader) + : base(loader) + { + + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Method.cs b/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Method.cs new file mode 100644 index 00000000..683c4c13 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Method.cs @@ -0,0 +1,38 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EnumClassLoader + { + private void LoadMethod(IR.Method method) + { + var attributes = IL.MethodAttributes.Public; + + if (method.IsStatic) + attributes |= IL.MethodAttributes.Static; + if (method.IsVirtual) + attributes |= IL.MethodAttributes.Virtual | IL.MethodAttributes.NewSlot; + + var result = ILType.DefineMethod( + method.Name ?? string.Empty, + attributes, + Loader.Runtime.ImportType(method.ReturnType), + [.. ( + method.IsInstance || method.IsVirtual + ? method.Signature.GetParameters().Skip(1) + : method.Signature.GetParameters() + ).Select(p => Loader.Runtime.ImportType(p.Type)) + ] + ); + + Loader.Runtime.AddFunction(method.UnderlyingFunction, result); + + var context = FunctionCodeContext.From(Loader.Runtime, result, method.UnderlyingFunction); + + foreach (var local in method.Body.Locals) + result.GetILGenerator().DeclareLocal(Loader.Runtime.ImportType(local.Type)); + + var codeLoader = new CodeCompiler(context); + + AddTask(() => codeLoader.CompileCode(method.Body.Instructions)); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs b/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs new file mode 100644 index 00000000..57568ffc --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EnumClassLoader + { + private void LoadNestedType(IR.OOPType type) + { + TypeLoaderHelper.LoadType(Loader, ILType, type); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Value.cs b/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Value.cs new file mode 100644 index 00000000..87cef372 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Value.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EnumClassLoader + { + private void LoadValue(IR.EnumValue value) + { + var il = ILType.DefineField( + value.Name, + ILType, + IL.FieldAttributes.Public | IL.FieldAttributes.Static + ); + + // TODO: add caching when adding IR instruction for loading enum value + //Loader.Runtime.AddField(value, il); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs b/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs new file mode 100644 index 00000000..66fb648f --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs @@ -0,0 +1,53 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class EnumClassLoader + { + public Type Load() + { + LoadAll(); + + ILType.CreateType(); + + return ILType; + } + + private void LoadAll() + { + CreateValueField(); + + LoadNestedTypes(); + + AddTask(LoadValues); + + AddTask(LoadMethods); + } + + private void CreateValueField() + { + ILType.DefineField( + "__value", + Loader.Runtime.ImportType(IRType.Type), + IL.FieldAttributes.Public | IL.FieldAttributes.SpecialName | IL.FieldAttributes.RTSpecialName + ); + } + + private void LoadNestedTypes() + { + //foreach (var type in IRType.NestedTypes) + // LoadNestedType(type); + } + + private void LoadValues() + { + foreach (var value in IRType.Values) + LoadValue(value); + } + + private void LoadMethods() + { + //if (IRType.HasMethods) + // foreach (var method in IRType.Methods) + // LoadMethod(method); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Context.cs b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Context.cs new file mode 100644 index 00000000..09e86c25 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Context.cs @@ -0,0 +1,9 @@ +using CommonZ.Utils; + +namespace ZSharp.Runtime.Loaders +{ + partial class InterfaceLoader + { + private Cache? genericTypeContext; + } +} diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Enum.cs b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.T.cs similarity index 54% rename from ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Enum.cs rename to ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.T.cs index 2e01bae7..176df975 100644 --- a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Enum.cs +++ b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.T.cs @@ -1,7 +1,7 @@ namespace ZSharp.Runtime.Loaders { - partial class EmitLoader + partial class InterfaceLoader { - + } } diff --git a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs new file mode 100644 index 00000000..5a404b2f --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs @@ -0,0 +1,22 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class InterfaceLoader + { + public required TaskManager Tasks { get; init; } + + private void AddTask(Action task) + { + if (genericTypeContext is not null) + { + var originalTask = task; + task = () => + { + using (Loader.Runtime.TypeContext(genericTypeContext)) + originalTask(); + }; + } + + Tasks.AddTask(task); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.cs b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.cs new file mode 100644 index 00000000..ec115c78 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Runtime.Loaders +{ + internal sealed partial class InterfaceLoader + : LoaderBase + { + public required Emit.TypeBuilder ILType { get; init; } + + public required IR.Interface IRType { get; init; } + + public InterfaceLoader(EmitLoader loader) + : base(loader) + { + + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Generic.cs b/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Generic.cs new file mode 100644 index 00000000..8836dcea --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Generic.cs @@ -0,0 +1,20 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class InterfaceLoader + { + private void LoadGenericParameters() + { + if (!IRType.HasGenericParameters) return; + + var ils = ILType.DefineGenericParameters( + [ + .. IRType.GenericParameters + .Select(p => p.Name) + ] + ); + + foreach (var (ir, il) in IRType.GenericParameters.Zip(ils)) + Loader.Runtime.AddType(ir, il); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Method.cs b/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Method.cs new file mode 100644 index 00000000..e797c2b2 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Method.cs @@ -0,0 +1,38 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class InterfaceLoader + { + private void LoadMethod(IR.Method method) + { + var attributes = IL.MethodAttributes.Public; + + if (method.IsStatic) + attributes |= IL.MethodAttributes.Static; + if (method.IsVirtual) + attributes |= IL.MethodAttributes.Virtual | IL.MethodAttributes.NewSlot; + + var result = ILType.DefineMethod( + method.Name ?? string.Empty, + attributes, + Loader.Runtime.ImportType(method.ReturnType), + [.. ( + method.IsInstance || method.IsVirtual + ? method.Signature.GetParameters().Skip(1) + : method.Signature.GetParameters() + ).Select(p => Loader.Runtime.ImportType(p.Type)) + ] + ); + + Loader.Runtime.AddFunction(method.UnderlyingFunction, result); + + var context = FunctionCodeContext.From(Loader.Runtime, result, method.UnderlyingFunction); + + foreach (var local in method.Body.Locals) + result.GetILGenerator().DeclareLocal(Loader.Runtime.ImportType(local.Type)); + + var codeLoader = new CodeCompiler(context); + + AddTask(() => codeLoader.CompileCode(method.Body.Instructions)); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs b/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs new file mode 100644 index 00000000..3bd28d71 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class InterfaceLoader + { + private void LoadNestedType(IR.OOPType type) + { + TypeLoaderHelper.LoadType(Loader, ILType, type); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs b/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs new file mode 100644 index 00000000..47799cc0 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs @@ -0,0 +1,53 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class InterfaceLoader + { + public Type Load() + { + if (IRType.HasGenericParameters) + genericTypeContext = Loader.Runtime.NewTypeContext(); + + if (genericTypeContext is not null) + using (Loader.Runtime.TypeContext(genericTypeContext)) + LoadAll(); + else + LoadAll(); + + ILType.CreateType(); + + return ILType; + } + + private void LoadAll() + { + LoadGenericParameters(); + + LoadNestedTypes(); + + AddTask(LoadBases); + + AddTask(LoadMethods); + } + + private void LoadBases() + { + if (IRType.HasBases) + foreach (var @base in IRType.Bases) + ILType.AddInterfaceImplementation(Loader.Runtime.ImportType(@base)); + } + + private void LoadNestedTypes() + { + throw new NotSupportedException(); + //foreach (var type in IRType.NestedTypes) + // LoadNestedType(type); + } + + private void LoadMethods() + { + if (IRType.HasMethods) + foreach (var method in IRType.Methods) + LoadMethod(method); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/module/ModuleLoader.cs b/ZSharp.Runtime/loader/loaders/module/ModuleLoader.cs index 8436b1f1..3c036e3f 100644 --- a/ZSharp.Runtime/loader/loaders/module/ModuleLoader.cs +++ b/ZSharp.Runtime/loader/loaders/module/ModuleLoader.cs @@ -3,7 +3,7 @@ internal sealed partial class ModuleLoader : LoaderBase { - public Emit.AssemblyBuilder AssemblyBuilder { get; } + public Emit.AssemblyBuilder AssemblyBuilder { get; private init; } public Emit.ModuleBuilder ILModule { get; } @@ -15,11 +15,11 @@ public ModuleLoader(EmitLoader loader, IR.Module module) : base(loader) { IRModule = module; - AssemblyBuilder = Emit.AssemblyBuilder.DefineDynamicAssembly( + AssemblyBuilder ??= Emit.AssemblyBuilder.DefineDynamicAssembly( new IL.AssemblyName(IRModule.Name ?? throw new()), Emit.AssemblyBuilderAccess.RunAndCollect ); - ILModule = AssemblyBuilder.DefineDynamicModule(IRModule.Name); + ILModule = AssemblyBuilder.DefineDynamicModule(IRModule.Name ?? throw new()); Globals = ILModule.DefineType(""); tasks = new(LoadAll); diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs index 509605a6..87cdb56b 100644 --- a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs +++ b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs @@ -13,6 +13,8 @@ public IL.Module Load() private void LoadAll() { + LoadSubmodules(); + LoadTypes(); LoadGlobals(); @@ -22,6 +24,19 @@ private void LoadAll() LoadInitializer(); } + private void LoadSubmodules() + { + if (IRModule.HasSubmodules) + foreach (var module in IRModule.Submodules) + Loader.Runtime.AddModule( + module, + new ModuleLoader(Loader, module) + { + AssemblyBuilder = AssemblyBuilder + }.Load() + ); + } + private void LoadTypes() { if (IRModule.HasTypes) diff --git a/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Context.cs b/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Context.cs new file mode 100644 index 00000000..93ea3a99 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Context.cs @@ -0,0 +1,9 @@ +using CommonZ.Utils; + +namespace ZSharp.Runtime.Loaders +{ + partial class ValueTypeLoader + { + private Cache? genericTypeContext; + } +} diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Interface.cs b/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.T.cs similarity index 54% rename from ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Interface.cs rename to ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.T.cs index 2e01bae7..60bc6565 100644 --- a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.Interface.cs +++ b/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.T.cs @@ -1,7 +1,7 @@ namespace ZSharp.Runtime.Loaders { - partial class EmitLoader + partial class ValueTypeLoader { - + } } diff --git a/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Tasks.cs b/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Tasks.cs new file mode 100644 index 00000000..6fc817a0 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Tasks.cs @@ -0,0 +1,22 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ValueTypeLoader + { + public required TaskManager Tasks { get; init; } + + private void AddTask(Action task) + { + if (genericTypeContext is not null) + { + var originalTask = task; + task = () => + { + using (Loader.Runtime.TypeContext(genericTypeContext)) + originalTask(); + }; + } + + Tasks.AddTask(task); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.cs b/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.cs new file mode 100644 index 00000000..fba25907 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Runtime.Loaders +{ + internal sealed partial class ValueTypeLoader + : LoaderBase + { + public required Emit.TypeBuilder ILType { get; init; } + + public required IR.ValueType IRType { get; init; } + + public ValueTypeLoader(EmitLoader loader) + : base(loader) + { + + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Constructor.cs b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Constructor.cs new file mode 100644 index 00000000..f4b90dfd --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Constructor.cs @@ -0,0 +1,22 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ValueTypeLoader + { + private void LoadConstructor(IR.Constructor constructor) + { + var result = ILType.DefineConstructor( + IL.MethodAttributes.Public, + IL.CallingConventions.HasThis, + [.. constructor.Method.Signature.GetParameters().Skip(1).Select(p => Loader.Runtime.ImportType(p.Type))] + ); + + Loader.Runtime.AddFunction(constructor.Method.UnderlyingFunction, result); + + var context = FunctionCodeContext.From(Loader.Runtime, result, constructor.Method.UnderlyingFunction); + + var codeLoader = new CodeCompiler(context); + + AddTask(() => codeLoader.CompileCode(constructor.Method.Body.Instructions)); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Field.cs b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Field.cs new file mode 100644 index 00000000..2b14173d --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Field.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ValueTypeLoader + { + private void LoadField(IR.Field field) + { + var attributes = IL.FieldAttributes.Public; + + if (field.IsStatic) + attributes |= IL.FieldAttributes.Static; + + var il = ILType.DefineField(field.Name, Loader.Runtime.ImportType(field.Type), attributes); + + Loader.Runtime.AddField(field, il); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Generic.cs b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Generic.cs new file mode 100644 index 00000000..16b41443 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Generic.cs @@ -0,0 +1,20 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ValueTypeLoader + { + private void LoadGenericParameters() + { + //if (!IRType.HasGenericParameters) return; + + //var ils = ILType.DefineGenericParameters( + // [ + // .. IRType.GenericParameters + // .Select(p => p.Name) + // ] + //); + + //foreach (var (ir, il) in IRType.GenericParameters.Zip(ils)) + // Loader.Runtime.AddType(ir, il); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Method.cs b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Method.cs new file mode 100644 index 00000000..8f81554d --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Method.cs @@ -0,0 +1,38 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ValueTypeLoader + { + private void LoadMethod(IR.Method method) + { + var attributes = IL.MethodAttributes.Public; + + if (method.IsStatic) + attributes |= IL.MethodAttributes.Static; + if (method.IsVirtual) + attributes |= IL.MethodAttributes.Virtual | IL.MethodAttributes.NewSlot; + + var result = ILType.DefineMethod( + method.Name ?? string.Empty, + attributes, + Loader.Runtime.ImportType(method.ReturnType), + [.. ( + method.IsInstance || method.IsVirtual + ? method.Signature.GetParameters().Skip(1) + : method.Signature.GetParameters() + ).Select(p => Loader.Runtime.ImportType(p.Type)) + ] + ); + + Loader.Runtime.AddFunction(method.UnderlyingFunction, result); + + var context = FunctionCodeContext.From(Loader.Runtime, result, method.UnderlyingFunction); + + foreach (var local in method.Body.Locals) + result.GetILGenerator().DeclareLocal(Loader.Runtime.ImportType(local.Type)); + + var codeLoader = new CodeCompiler(context); + + AddTask(() => codeLoader.CompileCode(method.Body.Instructions)); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs new file mode 100644 index 00000000..0e93cf14 --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ValueTypeLoader + { + private void LoadNestedType(IR.OOPType type) + { + TypeLoaderHelper.LoadType(Loader, ILType, type); + } + } +} diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.cs b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.cs new file mode 100644 index 00000000..4adced9b --- /dev/null +++ b/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.cs @@ -0,0 +1,61 @@ +namespace ZSharp.Runtime.Loaders +{ + partial class ValueTypeLoader + { + public Type Load() + { + //if (IRType.HasGenericParameters) + // genericTypeContext = Loader.Runtime.NewTypeContext(); + + if (genericTypeContext is not null) + using (Loader.Runtime.TypeContext(genericTypeContext)) + LoadAll(); + else + LoadAll(); + + ILType.CreateType(); + + return ILType; + } + + private void LoadAll() + { + LoadGenericParameters(); + + LoadNestedTypes(); + + AddTask(LoadFields); + + AddTask(LoadConstructors); + + AddTask(LoadMethods); + } + + private void LoadNestedTypes() + { + //foreach (var type in IRType.NestedTypes) + // LoadNestedType(type); + } + + private void LoadFields() + { + //if (IRType.HasFields) + // foreach (var field in IRType.Fields) + // LoadField(field); + } + + private void LoadMethods() + { + //if (IRType.HasMethods) + // foreach (var method in IRType.Methods) + // LoadMethod(method); + } + + private void LoadConstructors() + { + //if (IRType.HasConstructors) + // foreach (var constructor in IRType.Constructors) + // LoadConstructor(constructor); + } + } +} diff --git a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Module.cs b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Module.cs index 0db4c43c..779e418f 100644 --- a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Module.cs +++ b/ZSharp.Runtime/runtime/cache/Runtime.Cache.Module.cs @@ -3,5 +3,14 @@ partial class Runtime { private readonly Dictionary _moduleCache = []; + + public void AddModule(IR.Module ir, IL.Module il) + => _moduleCache.Add(ir, il); + + public void DelModule(IR.Module ir) + => _moduleCache.Remove(ir); + + public void SetModule(IR.Module ir, IL.Module il) + => _moduleCache[ir] = il; } } From f34f2e25140c9961082dfaa1cc71a1ed9515a7e4 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 18 Jul 2025 17:02:03 +0300 Subject: [PATCH 182/235] Remove .T template files --- ZSharp.Runtime/loader/loaders/class/ClassLoader.T.cs | 7 ------- ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.T.cs | 7 ------- .../loader/loaders/interface/InterfaceLoader.T.cs | 7 ------- 3 files changed, 21 deletions(-) delete mode 100644 ZSharp.Runtime/loader/loaders/class/ClassLoader.T.cs delete mode 100644 ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.T.cs delete mode 100644 ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.T.cs diff --git a/ZSharp.Runtime/loader/loaders/class/ClassLoader.T.cs b/ZSharp.Runtime/loader/loaders/class/ClassLoader.T.cs deleted file mode 100644 index 02d00577..00000000 --- a/ZSharp.Runtime/loader/loaders/class/ClassLoader.T.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Runtime.Loaders -{ - partial class ClassLoader - { - - } -} diff --git a/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.T.cs b/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.T.cs deleted file mode 100644 index 3fa282e3..00000000 --- a/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.T.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Runtime.Loaders -{ - partial class EnumClassLoader - { - - } -} diff --git a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.T.cs b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.T.cs deleted file mode 100644 index 176df975..00000000 --- a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.T.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Runtime.Loaders -{ - partial class InterfaceLoader - { - - } -} From 9f032552b8f17ba318f0c70793a6167fb8316aa9 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 18 Jul 2025 17:02:21 +0300 Subject: [PATCH 183/235] Add type loader helpers --- .../loader/emit/load/EmitLoader.Load.Type.cs | 39 +------------- .../loader/{loaders => helpers}/LoaderBase.cs | 0 .../loader/helpers/TypeLoaderBase.cs | 29 +++++++++++ .../loader/helpers/TypeLoaderHelper.cs | 52 ++++++++++++++++++- .../loader/loaders/class/ClassLoader.Tasks.cs | 6 +-- .../loader/loaders/class/ClassLoader.cs | 14 ++--- .../loaders/class/load/ClassLoader.Load.cs | 6 +-- .../loaders/enum/EnumClassLoader.Tasks.cs | 12 ----- .../loader/loaders/enum/EnumClassLoader.cs | 14 ++--- .../loaders/enum/load/EnumClassLoader.Load.cs | 6 +-- .../interface/InterfaceLoader.Tasks.cs | 6 +-- .../loaders/interface/InterfaceLoader.cs | 14 ++--- .../interface/load/InterfaceLoader.Load.cs | 6 +-- .../load/ModuleLoader.Load.Type.Class.cs | 19 ------- .../load/ModuleLoader.Load.Type.EnumClass.cs | 10 ---- .../load/ModuleLoader.Load.Type.Interface.cs | 10 ---- .../load/ModuleLoader.Load.Type.ValueType.cs | 10 ---- .../module/load/ModuleLoader.Load.Type.cs | 11 +--- 18 files changed, 98 insertions(+), 166 deletions(-) rename ZSharp.Runtime/loader/{loaders => helpers}/LoaderBase.cs (100%) create mode 100644 ZSharp.Runtime/loader/helpers/TypeLoaderBase.cs delete mode 100644 ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.Tasks.cs delete mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Class.cs delete mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.EnumClass.cs delete mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Interface.cs delete mode 100644 ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.ValueType.cs diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs index 590c4a88..82a86aee 100644 --- a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs +++ b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs @@ -3,43 +3,6 @@ partial class EmitLoader { public Type LoadType(IR.OOPType type) - { - var tasks = new TaskManager(() => { }); - var result = type switch - { - IR.Class def => new ClassLoader(this) - { - ILType = StandaloneModule.DefineType( - def.Name ?? throw new(), - IL.TypeAttributes.Public - ), - IRType = def, - Tasks = tasks - }.Load(), - IR.EnumClass def => new EnumClassLoader(this) - { - ILType = StandaloneModule.DefineType( - def.Name ?? throw new(), - IL.TypeAttributes.Public | IL.TypeAttributes.Sealed, - typeof(Enum) - ), - IRType = def, - Tasks = tasks - }.Load(), - IR.Interface def => new InterfaceLoader(this) - { - ILType = StandaloneModule.DefineType( - def.Name ?? throw new(), - IL.TypeAttributes.Public | IL.TypeAttributes.Interface - ), - IRType = def, - Tasks = tasks - }.Load(), - IR.ValueType def => throw new NotSupportedException(), - _ => throw new NotSupportedException(), - }; - tasks.RunUntilComplete(); - return result; - } + => TypeLoaderHelper.LoadType(this, StandaloneModule, type); } } diff --git a/ZSharp.Runtime/loader/loaders/LoaderBase.cs b/ZSharp.Runtime/loader/helpers/LoaderBase.cs similarity index 100% rename from ZSharp.Runtime/loader/loaders/LoaderBase.cs rename to ZSharp.Runtime/loader/helpers/LoaderBase.cs diff --git a/ZSharp.Runtime/loader/helpers/TypeLoaderBase.cs b/ZSharp.Runtime/loader/helpers/TypeLoaderBase.cs new file mode 100644 index 00000000..c18c8f78 --- /dev/null +++ b/ZSharp.Runtime/loader/helpers/TypeLoaderBase.cs @@ -0,0 +1,29 @@ +namespace ZSharp.Runtime.Loaders +{ + internal abstract class TypeLoaderBase(EmitLoader loader) + : LoaderBase(loader) + where T: IR.OOPType + { + public required Emit.TypeBuilder ILType { get; init; } + + public required T IRType { get; init; } + + public required TaskManager Tasks { get; init; } + + public Type Load() + { + Loader.Runtime.AddTypeDefinition(IRType, ILType); + + DoLoad(); + + AddTask(() => AddTask(() => Loader.Runtime.SetTypeDefinition(IRType, ILType.CreateType()))); + + return ILType; + } + + protected abstract void DoLoad(); + + protected virtual void AddTask(Action task) + => Tasks.AddTask(task); + } +} diff --git a/ZSharp.Runtime/loader/helpers/TypeLoaderHelper.cs b/ZSharp.Runtime/loader/helpers/TypeLoaderHelper.cs index b6159aa9..7d0bd8a4 100644 --- a/ZSharp.Runtime/loader/helpers/TypeLoaderHelper.cs +++ b/ZSharp.Runtime/loader/helpers/TypeLoaderHelper.cs @@ -16,6 +16,16 @@ public static Type LoadType(EmitLoader loader, Emit.TypeBuilder parentBuilder, I IRType = def, Tasks = tasks }.Load(), + IR.EnumClass def => new EnumClassLoader(loader) + { + ILType = parentBuilder.DefineNestedType( + def.Name ?? throw new(), + IL.TypeAttributes.Public | IL.TypeAttributes.Sealed, + typeof(Enum) + ), + IRType = def, + Tasks = tasks + }.Load(), IR.Interface def => new InterfaceLoader(loader) { ILType = parentBuilder.DefineNestedType( @@ -25,9 +35,49 @@ public static Type LoadType(EmitLoader loader, Emit.TypeBuilder parentBuilder, I IRType = def, Tasks = tasks }.Load(), + IR.ValueType def => throw new NotSupportedException(), + _ => throw new NotSupportedException(), + }; + tasks.RunUntilComplete(); + return result; + } + + public static Type LoadType(EmitLoader loader, Emit.ModuleBuilder parentBuilder, IR.OOPType type) + { + var tasks = new TaskManager(() => { }); + var result = type switch + { + IR.Class def => new ClassLoader(loader) + { + ILType = parentBuilder.DefineType( + def.Name ?? throw new(), + IL.TypeAttributes.Public + ), + IRType = def, + Tasks = tasks + }.Load(), + IR.EnumClass def => new EnumClassLoader(loader) + { + ILType = parentBuilder.DefineType( + def.Name ?? throw new(), + IL.TypeAttributes.Public | IL.TypeAttributes.Sealed, + typeof(Enum) + ), + IRType = def, + Tasks = tasks + }.Load(), + IR.Interface def => new InterfaceLoader(loader) + { + ILType = parentBuilder.DefineType( + def.Name ?? throw new(), + IL.TypeAttributes.Public | IL.TypeAttributes.Interface + ), + IRType = def, + Tasks = tasks + }.Load(), + IR.ValueType def => throw new NotSupportedException(), _ => throw new NotSupportedException(), }; - loader.Runtime.AddTypeDefinition(type, result); tasks.RunUntilComplete(); return result; } diff --git a/ZSharp.Runtime/loader/loaders/class/ClassLoader.Tasks.cs b/ZSharp.Runtime/loader/loaders/class/ClassLoader.Tasks.cs index 1afe7476..58c8320f 100644 --- a/ZSharp.Runtime/loader/loaders/class/ClassLoader.Tasks.cs +++ b/ZSharp.Runtime/loader/loaders/class/ClassLoader.Tasks.cs @@ -2,9 +2,7 @@ { partial class ClassLoader { - public required TaskManager Tasks { get; init; } - - private void AddTask(Action task) + protected override void AddTask(Action task) { if (genericTypeContext is not null) { @@ -16,7 +14,7 @@ private void AddTask(Action task) }; } - Tasks.AddTask(task); + base.AddTask(task); } } } diff --git a/ZSharp.Runtime/loader/loaders/class/ClassLoader.cs b/ZSharp.Runtime/loader/loaders/class/ClassLoader.cs index ad0beba6..0bcb0094 100644 --- a/ZSharp.Runtime/loader/loaders/class/ClassLoader.cs +++ b/ZSharp.Runtime/loader/loaders/class/ClassLoader.cs @@ -1,16 +1,8 @@ namespace ZSharp.Runtime.Loaders { - internal sealed partial class ClassLoader - : LoaderBase + internal sealed partial class ClassLoader(EmitLoader loader) + : TypeLoaderBase(loader) { - public required Emit.TypeBuilder ILType { get; init; } - - public required IR.Class IRType { get; init; } - - public ClassLoader(EmitLoader loader) - : base(loader) - { - - } + } } diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs index 641aad01..f5e74c46 100644 --- a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs +++ b/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs @@ -2,7 +2,7 @@ { partial class ClassLoader { - public Type Load() + protected override void DoLoad() { if (IRType.HasGenericParameters) genericTypeContext = Loader.Runtime.NewTypeContext(); @@ -12,10 +12,6 @@ public Type Load() LoadAll(); else LoadAll(); - - ILType.CreateType(); - - return ILType; } private void LoadAll() diff --git a/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.Tasks.cs b/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.Tasks.cs deleted file mode 100644 index 1ffe9b52..00000000 --- a/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.Tasks.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ZSharp.Runtime.Loaders -{ - partial class EnumClassLoader - { - public required TaskManager Tasks { get; init; } - - private void AddTask(Action task) - { - Tasks.AddTask(task); - } - } -} diff --git a/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.cs b/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.cs index 4622fce7..1e772eae 100644 --- a/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.cs +++ b/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.cs @@ -1,16 +1,8 @@ namespace ZSharp.Runtime.Loaders { - internal sealed partial class EnumClassLoader - : LoaderBase + internal sealed partial class EnumClassLoader(EmitLoader loader) + : TypeLoaderBase(loader) { - public required Emit.TypeBuilder ILType { get; init; } - - public required IR.EnumClass IRType { get; init; } - - public EnumClassLoader(EmitLoader loader) - : base(loader) - { - - } + } } diff --git a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs b/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs index 66fb648f..d822fd49 100644 --- a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs +++ b/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs @@ -2,13 +2,9 @@ { partial class EnumClassLoader { - public Type Load() + protected override void DoLoad() { LoadAll(); - - ILType.CreateType(); - - return ILType; } private void LoadAll() diff --git a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs index 5a404b2f..f0564274 100644 --- a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs +++ b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs @@ -2,9 +2,7 @@ { partial class InterfaceLoader { - public required TaskManager Tasks { get; init; } - - private void AddTask(Action task) + protected override void AddTask(Action task) { if (genericTypeContext is not null) { @@ -16,7 +14,7 @@ private void AddTask(Action task) }; } - Tasks.AddTask(task); + base.AddTask(task); } } } diff --git a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.cs b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.cs index ec115c78..c534ce9f 100644 --- a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.cs +++ b/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.cs @@ -1,16 +1,8 @@ namespace ZSharp.Runtime.Loaders { - internal sealed partial class InterfaceLoader - : LoaderBase + internal sealed partial class InterfaceLoader(EmitLoader loader) + : TypeLoaderBase(loader) { - public required Emit.TypeBuilder ILType { get; init; } - - public required IR.Interface IRType { get; init; } - - public InterfaceLoader(EmitLoader loader) - : base(loader) - { - - } + } } diff --git a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs b/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs index 47799cc0..237bad37 100644 --- a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs +++ b/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs @@ -2,7 +2,7 @@ { partial class InterfaceLoader { - public Type Load() + protected override void DoLoad() { if (IRType.HasGenericParameters) genericTypeContext = Loader.Runtime.NewTypeContext(); @@ -12,10 +12,6 @@ public Type Load() LoadAll(); else LoadAll(); - - ILType.CreateType(); - - return ILType; } private void LoadAll() diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Class.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Class.cs deleted file mode 100644 index c214a4d8..00000000 --- a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Class.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace ZSharp.Runtime.Loaders -{ - partial class ModuleLoader - { - public void LoadClass(IR.Class @class) - { - ClassLoader loader = new(Loader) - { - ILType = ILModule.DefineType(@class.Name ?? string.Empty, IL.TypeAttributes.Public), - IRType = @class, - Tasks = tasks - }; - - Loader.Runtime.AddTypeDefinition(@class, loader.ILType); - - Loader.Runtime.SetTypeDefinition(@class, loader.Load()); - } - } -} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.EnumClass.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.EnumClass.cs deleted file mode 100644 index 8e2baf5f..00000000 --- a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.EnumClass.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Runtime.Loaders -{ - partial class ModuleLoader - { - public void LoadEnumClass(IR.EnumClass @enum) - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Interface.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Interface.cs deleted file mode 100644 index edda7648..00000000 --- a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.Interface.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Runtime.Loaders -{ - partial class ModuleLoader - { - public void LoadInterface(IR.Interface @interface) - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.ValueType.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.ValueType.cs deleted file mode 100644 index 94f487a2..00000000 --- a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.ValueType.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Runtime.Loaders -{ - partial class ModuleLoader - { - public void LoadValueType(IR.ValueType valueType) - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs index e4c2a51e..22ded722 100644 --- a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs +++ b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs @@ -3,15 +3,6 @@ partial class ModuleLoader { public void LoadType(IR.OOPType type) - { - switch (type) - { - case IR.Class @class: LoadClass(@class); break; - case IR.Interface @interface: LoadInterface(@interface); break; - case IR.EnumClass @enum: LoadEnumClass(@enum); break; - case IR.ValueType valueType: LoadValueType(valueType); break; - default: throw new NotSupportedException(); - } - } + => TypeLoaderHelper.LoadType(Loader, ILModule, type); } } From 5af1e196c0b97ed11f7b9df53fb8bfdd4f6a8f7c Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 20 Jul 2025 23:31:00 +0300 Subject: [PATCH 184/235] Add IR compiler project --- ZSharp v1.sln | 6 ++++++ ZSharp.Compiler.IR/GlobalUsings.cs | 4 ++++ ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj | 15 +++++++++++++++ ZSharp.Compiler.IR/compile/Compile.cs | 7 +++++++ .../compile/services/Compile.Code.cs | 7 +++++++ .../compile/services/Compile.Definition.cs | 17 +++++++++++++++++ .../compile/services/Compile.Reference.cs | 11 +++++++++++ .../compile/services/Compile.Type.cs | 7 +++++++ 8 files changed, 74 insertions(+) create mode 100644 ZSharp.Compiler.IR/GlobalUsings.cs create mode 100644 ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj create mode 100644 ZSharp.Compiler.IR/compile/Compile.cs create mode 100644 ZSharp.Compiler.IR/compile/services/Compile.Code.cs create mode 100644 ZSharp.Compiler.IR/compile/services/Compile.Definition.cs create mode 100644 ZSharp.Compiler.IR/compile/services/Compile.Reference.cs create mode 100644 ZSharp.Compiler.IR/compile/services/Compile.Type.cs diff --git a/ZSharp v1.sln b/ZSharp v1.sln index c9a4ce61..b747c698 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -56,6 +56,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.ILLoader", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Runtime", "ZSharp.Runtime\ZSharp.Runtime.csproj", "{3CD28041-00F7-4A40-BEFD-4F77809BCBF7}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.IR", "ZSharp.Compiler.IR\ZSharp.Compiler.IR.csproj", "{B3E3E076-4B77-433F-9466-D0A0D8D9EAFA}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -162,6 +164,10 @@ Global {3CD28041-00F7-4A40-BEFD-4F77809BCBF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {3CD28041-00F7-4A40-BEFD-4F77809BCBF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {3CD28041-00F7-4A40-BEFD-4F77809BCBF7}.Release|Any CPU.Build.0 = Release|Any CPU + {B3E3E076-4B77-433F-9466-D0A0D8D9EAFA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B3E3E076-4B77-433F-9466-D0A0D8D9EAFA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B3E3E076-4B77-433F-9466-D0A0D8D9EAFA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B3E3E076-4B77-433F-9466-D0A0D8D9EAFA}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZSharp.Compiler.IR/GlobalUsings.cs b/ZSharp.Compiler.IR/GlobalUsings.cs new file mode 100644 index 00000000..80e8e9fd --- /dev/null +++ b/ZSharp.Compiler.IR/GlobalUsings.cs @@ -0,0 +1,4 @@ +global using CompilerObject = ZSharp.Objects.CompilerObject; +global using Error = string; + +global using TargetPlatform = object; diff --git a/ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj b/ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj new file mode 100644 index 00000000..01130ae1 --- /dev/null +++ b/ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + ZSharp.IRCompiler + + + + + + + + diff --git a/ZSharp.Compiler.IR/compile/Compile.cs b/ZSharp.Compiler.IR/compile/Compile.cs new file mode 100644 index 00000000..6f93097f --- /dev/null +++ b/ZSharp.Compiler.IR/compile/Compile.cs @@ -0,0 +1,7 @@ +namespace ZSharp.IRCompiler +{ + public static partial class Compile + { + + } +} diff --git a/ZSharp.Compiler.IR/compile/services/Compile.Code.cs b/ZSharp.Compiler.IR/compile/services/Compile.Code.cs new file mode 100644 index 00000000..c72ba395 --- /dev/null +++ b/ZSharp.Compiler.IR/compile/services/Compile.Code.cs @@ -0,0 +1,7 @@ +namespace ZSharp.IRCompiler +{ + partial class Compile + { + + } +} diff --git a/ZSharp.Compiler.IR/compile/services/Compile.Definition.cs b/ZSharp.Compiler.IR/compile/services/Compile.Definition.cs new file mode 100644 index 00000000..6ecff938 --- /dev/null +++ b/ZSharp.Compiler.IR/compile/services/Compile.Definition.cs @@ -0,0 +1,17 @@ +namespace ZSharp.IRCompiler +{ + partial class Compile + { + public static Compiler.Result Definition(CompilerObject @object, TargetPlatform? target) + where T : IR.IRObject + { + throw new NotImplementedException(); + } + + public static void Definition(CompilerObject @object, Owner owner, TargetPlatform? target) + where Owner : IR.IRObject + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.IR/compile/services/Compile.Reference.cs b/ZSharp.Compiler.IR/compile/services/Compile.Reference.cs new file mode 100644 index 00000000..ed8a29d4 --- /dev/null +++ b/ZSharp.Compiler.IR/compile/services/Compile.Reference.cs @@ -0,0 +1,11 @@ +namespace ZSharp.IRCompiler +{ + partial class Compile + { + public static Compiler.Result Reference(CompilerObject @object) + where T : class + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.IR/compile/services/Compile.Type.cs b/ZSharp.Compiler.IR/compile/services/Compile.Type.cs new file mode 100644 index 00000000..c72ba395 --- /dev/null +++ b/ZSharp.Compiler.IR/compile/services/Compile.Type.cs @@ -0,0 +1,7 @@ +namespace ZSharp.IRCompiler +{ + partial class Compile + { + + } +} From 209417cc07fa442cc37782687a4180376ee1354f Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 21 Jul 2025 12:23:18 +0300 Subject: [PATCH 185/235] Make IR compiler non-static --- ZSharp.Compiler.IR/compile/Compile.cs | 7 ------- ZSharp.Compiler.IR/compile/Compiler.cs | 7 +++++++ .../compile/services/{Compile.Code.cs => Compiler.Code.cs} | 2 +- .../{Compile.Definition.cs => Compiler.Definition.cs} | 6 +++--- .../{Compile.Reference.cs => Compiler.Reference.cs} | 4 ++-- .../compile/services/{Compile.Type.cs => Compiler.Type.cs} | 2 +- 6 files changed, 14 insertions(+), 14 deletions(-) delete mode 100644 ZSharp.Compiler.IR/compile/Compile.cs create mode 100644 ZSharp.Compiler.IR/compile/Compiler.cs rename ZSharp.Compiler.IR/compile/services/{Compile.Code.cs => Compiler.Code.cs} (67%) rename ZSharp.Compiler.IR/compile/services/{Compile.Definition.cs => Compiler.Definition.cs} (60%) rename ZSharp.Compiler.IR/compile/services/{Compile.Reference.cs => Compiler.Reference.cs} (64%) rename ZSharp.Compiler.IR/compile/services/{Compile.Type.cs => Compiler.Type.cs} (67%) diff --git a/ZSharp.Compiler.IR/compile/Compile.cs b/ZSharp.Compiler.IR/compile/Compile.cs deleted file mode 100644 index 6f93097f..00000000 --- a/ZSharp.Compiler.IR/compile/Compile.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.IRCompiler -{ - public static partial class Compile - { - - } -} diff --git a/ZSharp.Compiler.IR/compile/Compiler.cs b/ZSharp.Compiler.IR/compile/Compiler.cs new file mode 100644 index 00000000..940c4752 --- /dev/null +++ b/ZSharp.Compiler.IR/compile/Compiler.cs @@ -0,0 +1,7 @@ +namespace ZSharp.IRCompiler +{ + public sealed partial class Compiler(IR.RuntimeModule runtimeModule) + { + public IR.RuntimeModule RuntimeModule { get; } = runtimeModule; + } +} diff --git a/ZSharp.Compiler.IR/compile/services/Compile.Code.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Code.cs similarity index 67% rename from ZSharp.Compiler.IR/compile/services/Compile.Code.cs rename to ZSharp.Compiler.IR/compile/services/Compiler.Code.cs index c72ba395..624b0ea1 100644 --- a/ZSharp.Compiler.IR/compile/services/Compile.Code.cs +++ b/ZSharp.Compiler.IR/compile/services/Compiler.Code.cs @@ -1,6 +1,6 @@ namespace ZSharp.IRCompiler { - partial class Compile + partial class Compiler { } diff --git a/ZSharp.Compiler.IR/compile/services/Compile.Definition.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs similarity index 60% rename from ZSharp.Compiler.IR/compile/services/Compile.Definition.cs rename to ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs index 6ecff938..a879608f 100644 --- a/ZSharp.Compiler.IR/compile/services/Compile.Definition.cs +++ b/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs @@ -1,14 +1,14 @@ namespace ZSharp.IRCompiler { - partial class Compile + partial class Compiler { - public static Compiler.Result Definition(CompilerObject @object, TargetPlatform? target) + public ZSharp.Compiler.Result Definition(CompilerObject @object, TargetPlatform? target) where T : IR.IRObject { throw new NotImplementedException(); } - public static void Definition(CompilerObject @object, Owner owner, TargetPlatform? target) + public void Definition(CompilerObject @object, Owner owner, TargetPlatform? target) where Owner : IR.IRObject { throw new NotImplementedException(); diff --git a/ZSharp.Compiler.IR/compile/services/Compile.Reference.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs similarity index 64% rename from ZSharp.Compiler.IR/compile/services/Compile.Reference.cs rename to ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs index ed8a29d4..1136e484 100644 --- a/ZSharp.Compiler.IR/compile/services/Compile.Reference.cs +++ b/ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs @@ -1,8 +1,8 @@ namespace ZSharp.IRCompiler { - partial class Compile + partial class Compiler { - public static Compiler.Result Reference(CompilerObject @object) + public ZSharp.Compiler.Result Reference(CompilerObject @object) where T : class { throw new NotImplementedException(); diff --git a/ZSharp.Compiler.IR/compile/services/Compile.Type.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Type.cs similarity index 67% rename from ZSharp.Compiler.IR/compile/services/Compile.Type.cs rename to ZSharp.Compiler.IR/compile/services/Compiler.Type.cs index c72ba395..624b0ea1 100644 --- a/ZSharp.Compiler.IR/compile/services/Compile.Type.cs +++ b/ZSharp.Compiler.IR/compile/services/Compiler.Type.cs @@ -1,6 +1,6 @@ namespace ZSharp.IRCompiler { - partial class Compile + partial class Compiler { } From 2d925aaeaa41b13aa0354f6319201d418d97e023 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 21 Jul 2025 12:31:39 +0300 Subject: [PATCH 186/235] Add Compile prefix to methods --- ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs | 4 ++-- ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs index a879608f..9802e19c 100644 --- a/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs +++ b/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs @@ -2,13 +2,13 @@ { partial class Compiler { - public ZSharp.Compiler.Result Definition(CompilerObject @object, TargetPlatform? target) + public ZSharp.Compiler.Result CompileDefinition(CompilerObject @object, TargetPlatform? target) where T : IR.IRObject { throw new NotImplementedException(); } - public void Definition(CompilerObject @object, Owner owner, TargetPlatform? target) + public void CompileDefinition(CompilerObject @object, Owner owner, TargetPlatform? target) where Owner : IR.IRObject { throw new NotImplementedException(); diff --git a/ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs index 1136e484..12a3489c 100644 --- a/ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs +++ b/ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs @@ -2,7 +2,7 @@ { partial class Compiler { - public ZSharp.Compiler.Result Reference(CompilerObject @object) + public ZSharp.Compiler.Result CompileReference(CompilerObject @object) where T : class { throw new NotImplementedException(); From f9cce50938322c2e1f22afc1d304a1b2cb98421a Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 21 Jul 2025 12:31:51 +0300 Subject: [PATCH 187/235] Add CompileCode method --- ZSharp.Compiler.IR/compile/services/Compiler.Code.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ZSharp.Compiler.IR/compile/services/Compiler.Code.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Code.cs index 624b0ea1..6e1cb47c 100644 --- a/ZSharp.Compiler.IR/compile/services/Compiler.Code.cs +++ b/ZSharp.Compiler.IR/compile/services/Compiler.Code.cs @@ -2,6 +2,9 @@ { partial class Compiler { - + public ZSharp.Compiler.Result CompileCode(CompilerObject @object, TargetPlatform? target) + { + throw new NotImplementedException(); + } } } From 29dca0a62ca01278f6e600023f0b67aa6967c912 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 21 Jul 2025 12:32:01 +0300 Subject: [PATCH 188/235] Add CompileType methods --- ZSharp.Compiler.IR/compile/services/Compiler.Type.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/ZSharp.Compiler.IR/compile/services/Compiler.Type.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Type.cs index 624b0ea1..cb40d759 100644 --- a/ZSharp.Compiler.IR/compile/services/Compiler.Type.cs +++ b/ZSharp.Compiler.IR/compile/services/Compiler.Type.cs @@ -2,6 +2,15 @@ { partial class Compiler { - + public ZSharp.Compiler.Result CompileType(CompilerObject @object) + { + throw new NotImplementedException(); + } + + public ZSharp.Compiler.Result CompileType(CompilerObject @object) + where T : class, IR.IType + { + throw new NotImplementedException(); + } } } From 965a93db0361f22a1ff0122ad14f3b284ff2c219 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 26 Jul 2025 21:25:34 +0300 Subject: [PATCH 189/235] Fix things --- Testing/Program.cs | 101 ++---------------- Testing/Testing.csproj | 5 + .../il loader/load/ILLoader.Load.Type.cs | 1 + .../objects/modular/module/Module.LazyLoad.cs | 2 +- .../objects/modular/module/Module.cs | 8 +- .../objects/namespace/Namespace.LazyLoad.cs | 10 ++ .../objects/namespace/Namespace.Member.cs | 8 +- 7 files changed, 39 insertions(+), 96 deletions(-) create mode 100644 ZSharp.Compiler.ILLoader/objects/namespace/Namespace.LazyLoad.cs diff --git a/Testing/Program.cs b/Testing/Program.cs index 01d69b98..13307fc5 100644 --- a/Testing/Program.cs +++ b/Testing/Program.cs @@ -1,97 +1,12 @@ -using System; -using System.Reflection; -using System.Reflection.Emit; +using ZLoad.Test; +using ZSharp.Compiler.ILLoader; +using Objects = ZSharp.Compiler.ILLoader.Objects; -class Program -{ - static void Main() - { - // Define dynamic assembly and module - var assemblyName = new AssemblyName("DynamicAssemblyDemo"); - var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); - var moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule"); +var coc = new ZSharp.Compiler.Compiler(); - // ------------------------- - // Define first type: Person - // ------------------------- - var personBuilder = moduleBuilder.DefineType("Person", TypeAttributes.Public); - var nameField = personBuilder.DefineField("_name", typeof(string), FieldAttributes.Private); +var ilLoader = new ILLoader(); +var module = new Objects.Module(typeof(TestClass).Module, ilLoader); - // Constructor: Person(string name) - var ctorBuilder = personBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(string) }); - var ilCtor = ctorBuilder.GetILGenerator(); - ilCtor.Emit(OpCodes.Ldarg_0); - ilCtor.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)!); - ilCtor.Emit(OpCodes.Ldarg_0); - ilCtor.Emit(OpCodes.Ldarg_1); - ilCtor.Emit(OpCodes.Stfld, nameField); - ilCtor.Emit(OpCodes.Ret); +var zLoadTest = ilLoader.Namespace("ZLoad.Test"); - // Property: Name - var getNameMethod = personBuilder.DefineMethod("get_Name", MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, typeof(string), Type.EmptyTypes); - var ilGet = getNameMethod.GetILGenerator(); - ilGet.Emit(OpCodes.Ldarg_0); - ilGet.Emit(OpCodes.Ldfld, nameField); - ilGet.Emit(OpCodes.Ret); - - var nameProp = personBuilder.DefineProperty("Name", PropertyAttributes.None, typeof(string), null); - nameProp.SetGetMethod(getNameMethod); - - // Method: SayHello - var sayHelloMethod = personBuilder.DefineMethod("SayHello", MethodAttributes.Public, null, Type.EmptyTypes); - var ilSay = sayHelloMethod.GetILGenerator(); - ilSay.Emit(OpCodes.Ldstr, "Hello, my name is "); - ilSay.Emit(OpCodes.Ldarg_0); - ilSay.Emit(OpCodes.Call, getNameMethod); - ilSay.Emit(OpCodes.Call, typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) })!); - ilSay.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new[] { typeof(string) })!); - ilSay.Emit(OpCodes.Ret); - - // Finalize Person type - var personType = personBuilder.CreateTypeInfo()!.AsType(); - - // -------------------------- - // Use Person type instance - // -------------------------- - var person = Activator.CreateInstance(personType, "Alice"); - personType.GetMethod("SayHello")!.Invoke(person, null); - - // -------------------------- - // Define second type: Employee - // -------------------------- - var employeeBuilder = moduleBuilder.DefineType("Employee", TypeAttributes.Public); - - // Field: Id - var idField = employeeBuilder.DefineField("Id", typeof(int), FieldAttributes.Public); - - // Constructor: Employee(int id) - var empCtor = employeeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(int) }); - var ilEmpCtor = empCtor.GetILGenerator(); - ilEmpCtor.Emit(OpCodes.Ldarg_0); - ilEmpCtor.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)!); - ilEmpCtor.Emit(OpCodes.Ldarg_0); - ilEmpCtor.Emit(OpCodes.Ldarg_1); - ilEmpCtor.Emit(OpCodes.Stfld, idField); - ilEmpCtor.Emit(OpCodes.Ret); - - // Method: ShowId() - var showIdMethod = employeeBuilder.DefineMethod("ShowId", MethodAttributes.Public, null, Type.EmptyTypes); - var ilShow = showIdMethod.GetILGenerator(); - ilShow.Emit(OpCodes.Ldstr, "Employee ID: "); - ilShow.Emit(OpCodes.Ldarg_0); - ilShow.Emit(OpCodes.Ldfld, idField); - ilShow.Emit(OpCodes.Box, typeof(int)); - ilShow.Emit(OpCodes.Call, typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(object) })!); - ilShow.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new[] { typeof(string) })!); - ilShow.Emit(OpCodes.Ret); - - // Finalize Employee type - var employeeType = employeeBuilder.CreateTypeInfo()!.AsType(); - - // -------------------------- - // Use Employee type instance - // -------------------------- - var employee = Activator.CreateInstance(employeeType, 42); - employeeType.GetMethod("ShowId")!.Invoke(employee, null); - } -} +System.Console.WriteLine(string.Empty); diff --git a/Testing/Testing.csproj b/Testing/Testing.csproj index 2150e379..12ebe4ec 100644 --- a/Testing/Testing.csproj +++ b/Testing/Testing.csproj @@ -7,4 +7,9 @@ enable + + + + + diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs index 659be355..11680752 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs @@ -19,6 +19,7 @@ private CompilerObject DispatchLoadType(Type type) if (type.IsClass) return LoadClass(type); if (type.IsInterface) return LoadInterface(type); + if (type.IsEnum) return LoadEnum(type); if (type.IsValueType) return LoadStruct(type); if (type.HasElementType) diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs index d8bbbe1b..742f45af 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs +++ b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs @@ -4,7 +4,7 @@ partial class Module { private ModuleLoader? _moduleLoader; - public required ILLoader Loader { get; init; } + public ILLoader Loader { get; } internal ModuleLoader GlobalsLoader { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs index d4e5ad0c..d1c97c92 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs +++ b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs @@ -5,10 +5,16 @@ public sealed partial class Module { public string Name => IL.Name; - public Module(IL.Module il) + public Module(IL.Module il, ILLoader loader) { IL = il; Globals = IL.GetType(""); + Loader = loader; + + foreach (var type in il.GetTypes()) + if (!type.IsPublic) continue; + else if (type.Namespace is not null) + Loader.Namespace(type.Namespace).AddLazyMember(type.Name, () => Loader.LoadType(type)); } } } diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.LazyLoad.cs b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.LazyLoad.cs new file mode 100644 index 00000000..9c7910b9 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.LazyLoad.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Namespace + { + private readonly Dictionary> lazyLoadedMembers = []; + + public void AddLazyMember(MemberName member, Func lazyLoadedMember) + => lazyLoadedMembers.Add(member, lazyLoadedMember); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs index 0cdbead2..f8da7b2d 100644 --- a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs +++ b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs @@ -19,7 +19,13 @@ public void AddMember(string name, CompilerObject member) CompilerObjectResult ICTGetMember.Member(Compiler compiler, MemberName member) { - if (Members.TryGetValue(member, out var result)) + if ( + !Members.TryGetValue(member, out var result) + && lazyLoadedMembers.Remove(member, out var lazyLoad) + ) + AddMember(member, result = lazyLoad()); + + if (result is not null) return CompilerObjectResult.Ok(result); return CompilerObjectResult.Error( From aa661ba8b2d368a592c705abba2280413b4ada66 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 30 Jul 2025 20:16:14 +0300 Subject: [PATCH 190/235] Add ILLoader custom attributes They don't do anything though --- .../AliasAttribute.cs | 21 +++++++++++++++++++ .../ModuleScopeAttribute.cs | 10 +++++++++ .../SkipImportAttribute.cs | 17 +++++++++++++++ ...ZSharp.Compiler.ILLoader.Attributes.csproj | 10 +++++++++ .../namespace/MapNamespaceAttribute.cs | 13 ++++++++++++ .../namespace/SetNamespaceAttribute.cs | 17 +++++++++++++++ .../operator/OperatorAttribute.cs | 13 ++++++++++++ .../operator/OperatorKind.cs | 9 ++++++++ .../parameter/NamedParameterAttribute.cs | 11 ++++++++++ .../parameter/VarParameterAttribute.cs | 11 ++++++++++ 10 files changed, 132 insertions(+) create mode 100644 ZSharp.Compiler.ILLoader.Attributes/AliasAttribute.cs create mode 100644 ZSharp.Compiler.ILLoader.Attributes/ModuleScopeAttribute.cs create mode 100644 ZSharp.Compiler.ILLoader.Attributes/SkipImportAttribute.cs create mode 100644 ZSharp.Compiler.ILLoader.Attributes/ZSharp.Compiler.ILLoader.Attributes.csproj create mode 100644 ZSharp.Compiler.ILLoader.Attributes/namespace/MapNamespaceAttribute.cs create mode 100644 ZSharp.Compiler.ILLoader.Attributes/namespace/SetNamespaceAttribute.cs create mode 100644 ZSharp.Compiler.ILLoader.Attributes/operator/OperatorAttribute.cs create mode 100644 ZSharp.Compiler.ILLoader.Attributes/operator/OperatorKind.cs create mode 100644 ZSharp.Compiler.ILLoader.Attributes/parameter/NamedParameterAttribute.cs create mode 100644 ZSharp.Compiler.ILLoader.Attributes/parameter/VarParameterAttribute.cs diff --git a/ZSharp.Compiler.ILLoader.Attributes/AliasAttribute.cs b/ZSharp.Compiler.ILLoader.Attributes/AliasAttribute.cs new file mode 100644 index 00000000..01e9e8e8 --- /dev/null +++ b/ZSharp.Compiler.ILLoader.Attributes/AliasAttribute.cs @@ -0,0 +1,21 @@ +namespace ZSharp.Compiler.ILLoader +{ + [AttributeUsage( + AttributeTargets.Class | + AttributeTargets.Constructor | + AttributeTargets.Enum | + AttributeTargets.Field | + AttributeTargets.GenericParameter | + AttributeTargets.Interface | + AttributeTargets.Method | + AttributeTargets.Module | + AttributeTargets.Parameter | + AttributeTargets.Property | + AttributeTargets.Struct, + AllowMultiple = false + )] + public sealed class AliasAttribute(string name) : Attribute + { + public string Name { get; } = name; + } +} diff --git a/ZSharp.Compiler.ILLoader.Attributes/ModuleScopeAttribute.cs b/ZSharp.Compiler.ILLoader.Attributes/ModuleScopeAttribute.cs new file mode 100644 index 00000000..714d7d90 --- /dev/null +++ b/ZSharp.Compiler.ILLoader.Attributes/ModuleScopeAttribute.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + [AttributeUsage( + AttributeTargets.Class, + AllowMultiple = false + )] + public sealed class ModuleScopeAttribute : Attribute + { + } +} diff --git a/ZSharp.Compiler.ILLoader.Attributes/SkipImportAttribute.cs b/ZSharp.Compiler.ILLoader.Attributes/SkipImportAttribute.cs new file mode 100644 index 00000000..6a42d8a0 --- /dev/null +++ b/ZSharp.Compiler.ILLoader.Attributes/SkipImportAttribute.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Compiler.ILLoader +{ + [AttributeUsage( + AttributeTargets.Class | + AttributeTargets.Constructor | + AttributeTargets.Enum | + AttributeTargets.Field | + AttributeTargets.Interface | + AttributeTargets.Method | + AttributeTargets.Property | + AttributeTargets.Struct, + AllowMultiple = false + )] + public sealed class SkipImportAttribute : Attribute + { + } +} diff --git a/ZSharp.Compiler.ILLoader.Attributes/ZSharp.Compiler.ILLoader.Attributes.csproj b/ZSharp.Compiler.ILLoader.Attributes/ZSharp.Compiler.ILLoader.Attributes.csproj new file mode 100644 index 00000000..3c2ad080 --- /dev/null +++ b/ZSharp.Compiler.ILLoader.Attributes/ZSharp.Compiler.ILLoader.Attributes.csproj @@ -0,0 +1,10 @@ + + + + net8.0 + enable + enable + ZSharp.Compiler.ILLoader + + + diff --git a/ZSharp.Compiler.ILLoader.Attributes/namespace/MapNamespaceAttribute.cs b/ZSharp.Compiler.ILLoader.Attributes/namespace/MapNamespaceAttribute.cs new file mode 100644 index 00000000..8e53cd18 --- /dev/null +++ b/ZSharp.Compiler.ILLoader.Attributes/namespace/MapNamespaceAttribute.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler.ILLoader +{ + [AttributeUsage( + AttributeTargets.Module, + AllowMultiple = true + )] + public sealed class MapNamespaceAttribute : Attribute + { + public required string OldName { get; init; } + + public required string NewName { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader.Attributes/namespace/SetNamespaceAttribute.cs b/ZSharp.Compiler.ILLoader.Attributes/namespace/SetNamespaceAttribute.cs new file mode 100644 index 00000000..f50882dc --- /dev/null +++ b/ZSharp.Compiler.ILLoader.Attributes/namespace/SetNamespaceAttribute.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Compiler.ILLoader +{ + [AttributeUsage( + AttributeTargets.Class | + AttributeTargets.Struct | + AttributeTargets.Interface | + AttributeTargets.Enum, + AllowMultiple = false, + Inherited = false + )] + public sealed class SetNamespaceAttribute(string @namespace) : Attribute + { + public string Name { get; } = @namespace; + + public bool IsGlobalNamespace => string.IsNullOrEmpty(Name); + } +} diff --git a/ZSharp.Compiler.ILLoader.Attributes/operator/OperatorAttribute.cs b/ZSharp.Compiler.ILLoader.Attributes/operator/OperatorAttribute.cs new file mode 100644 index 00000000..716c80fe --- /dev/null +++ b/ZSharp.Compiler.ILLoader.Attributes/operator/OperatorAttribute.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler.ILLoader +{ + [AttributeUsage( + AttributeTargets.Method, + AllowMultiple = false + )] + public sealed class OperatorAttribute(string @operator) : Attribute + { + public string Operator { get; } = @operator; + + public required OperatorKind Kind { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader.Attributes/operator/OperatorKind.cs b/ZSharp.Compiler.ILLoader.Attributes/operator/OperatorKind.cs new file mode 100644 index 00000000..beb5eced --- /dev/null +++ b/ZSharp.Compiler.ILLoader.Attributes/operator/OperatorKind.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler.ILLoader +{ + public enum OperatorKind + { + Prefix, + Infix, + Postfix, + } +} diff --git a/ZSharp.Compiler.ILLoader.Attributes/parameter/NamedParameterAttribute.cs b/ZSharp.Compiler.ILLoader.Attributes/parameter/NamedParameterAttribute.cs new file mode 100644 index 00000000..8385638f --- /dev/null +++ b/ZSharp.Compiler.ILLoader.Attributes/parameter/NamedParameterAttribute.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Compiler.ILLoader +{ + [AttributeUsage( + AttributeTargets.Parameter, + AllowMultiple = false + )] + public sealed class NamedParameterAttribute : Attribute + { + + } +} diff --git a/ZSharp.Compiler.ILLoader.Attributes/parameter/VarParameterAttribute.cs b/ZSharp.Compiler.ILLoader.Attributes/parameter/VarParameterAttribute.cs new file mode 100644 index 00000000..056b6121 --- /dev/null +++ b/ZSharp.Compiler.ILLoader.Attributes/parameter/VarParameterAttribute.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Compiler.ILLoader +{ + [AttributeUsage( + AttributeTargets.Parameter, + AllowMultiple = false + )] + public sealed class VarParameterAttribute : Attribute + { + + } +} From 38839eb944a5c35105876c04b64072922a2e9a7b Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 30 Jul 2025 20:16:43 +0300 Subject: [PATCH 191/235] Add ILLoader stuff --- .../ZSharp.Compiler.ILLoader.csproj | 1 - .../il loader/ILLoader.cs | 12 +++++++++++ .../il loader/load/ILLoader.Load.Module.cs | 20 +++++++++++++++++++ .../load/ILLoader.Load.Type.Class.Generic.cs | 2 +- .../load/ILLoader.Load.Type.Class.cs | 2 +- .../il loader/load/ILLoader.Load.Type.Enum.cs | 2 +- .../load/ILLoader.Load.Type.Generic.cs | 2 +- .../ILLoader.Load.Type.Interface.Generic.cs | 2 +- .../load/ILLoader.Load.Type.Interface.cs | 2 +- .../load/ILLoader.Load.Type.Modified.cs | 8 ++++---- .../load/ILLoader.Load.Type.Struct.Generic.cs | 2 +- .../load/ILLoader.Load.Type.Struct.cs | 2 +- .../il loader/load/ILLoader.Load.Type.cs | 6 +++--- .../load/ModuleLoader.Load.Field.cs | 6 ++++-- .../load/ModuleLoader.Load.Method.Generic.cs | 4 ++-- .../load/ModuleLoader.Load.Method.cs | 6 ++++-- .../load/ModuleLoader.Load.Property.cs | 2 +- .../modular/function/concrete/Function.IL.cs | 7 +++++++ .../modular/function/concrete/Function.cs | 7 +++++++ .../function/generic/GenericFunction.IL.cs | 7 +++++++ .../function/generic/GenericFunction.cs | 7 +++++++ .../objects/modular/global/Global.IL.cs | 7 +++++++ .../objects/modular/global/Global.Type.cs | 8 ++++++++ .../objects/modular/global/Global.cs | 14 +++++++++++++ .../objects/modular/property/Property.cs | 6 ++++++ .../objects/namespace/Namespace.Member.cs | 2 +- 26 files changed, 122 insertions(+), 24 deletions(-) create mode 100644 ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Module.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IL.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.IL.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/global/Global.IL.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/global/Global.Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/global/Global.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/property/Property.cs diff --git a/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj b/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj index 84721ebd..20038b28 100644 --- a/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj +++ b/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj @@ -7,7 +7,6 @@ - diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs b/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs index 3383b47a..b9075009 100644 --- a/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs +++ b/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs @@ -2,6 +2,18 @@ { public sealed partial class ILLoader { + public Compiler Compiler { get; } + public ILLoader(Compiler compiler) + { + Compiler = compiler; + + foreach (var (il, co) in (IEnumerable<(Type, IType)>)[ + (typeof(void), Compiler.TypeSystem.Void), + ]) + { + typeCache[il] = co; + } + } } } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Module.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Module.cs new file mode 100644 index 00000000..7e435415 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Module.cs @@ -0,0 +1,20 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + private readonly Dictionary moduleCache = []; + + public CompilerObject LoadModule(IL.Module module) + { + if (!moduleCache.TryGetValue(module, out var @object)) + @object = moduleCache[module] = DispatchLoadModule(module); + + return @object; + } + + private CompilerObject DispatchLoadModule(IL.Module module) + { + return new Objects.Module(module, this); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs index e4ca4917..50bdaa94 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public CompilerObject LoadGenericClass(Type @class) + public IType LoadGenericClass(Type @class) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs index c021918f..b9dca02d 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public CompilerObject LoadClass(Type @class) + public IType LoadClass(Type @class) { if (@class.IsGenericTypeDefinition) return LoadGenericClass(@class); diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs index d3bc5166..8baf2fbd 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public CompilerObject LoadEnum(Type @enum) + public IType LoadEnum(Type @enum) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs index 79af355b..0f904650 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public CompilerObject LoadConstructedGenericType(Type type) + public IType LoadConstructedGenericType(Type type) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs index e3d1a4c7..6a67d7e0 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public CompilerObject LoadGenericInterface(Type @enum) + public IType LoadGenericInterface(Type @enum) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs index a0b56a3d..219d9484 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public CompilerObject LoadInterface(Type @interface) + public IType LoadInterface(Type @interface) { if (@interface.IsGenericTypeDefinition) return LoadGenericInterface(@interface); diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs index 60a54aa6..95a0404a 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public CompilerObject LoadModifiedType(Type type) + public IType LoadModifiedType(Type type) { if (type.IsArray) return LoadArrayType(type); if (type.IsPointer) return LoadPointerType(type); @@ -11,17 +11,17 @@ public CompilerObject LoadModifiedType(Type type) throw new NotSupportedException(); } - public CompilerObject LoadArrayType(Type array) + public IType LoadArrayType(Type array) { throw new NotImplementedException(); } - public CompilerObject LoadPointerType(Type pointer) + public IType LoadPointerType(Type pointer) { throw new NotImplementedException(); } - public CompilerObject LoadReferenceType(Type reference) + public IType LoadReferenceType(Type reference) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs index 7b685dd2..399d729e 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public CompilerObject LoadGenericStruct(Type @enum) + public IType LoadGenericStruct(Type @enum) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs index f4081f99..99e5e70c 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public CompilerObject LoadStruct(Type @struct) + public IType LoadStruct(Type @struct) { if (@struct.IsGenericTypeDefinition) return LoadGenericStruct(@struct); diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs index 11680752..2c62e9ee 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs @@ -2,9 +2,9 @@ { partial class ILLoader { - private readonly Dictionary typeCache = []; + private readonly Dictionary typeCache = []; - public CompilerObject LoadType(Type type) + public IType LoadType(Type type) { if (!typeCache.TryGetValue(type, out var @object)) @object = typeCache[type] = DispatchLoadType(type); @@ -12,7 +12,7 @@ public CompilerObject LoadType(Type type) return @object; } - private CompilerObject DispatchLoadType(Type type) + private IType DispatchLoadType(Type type) { if (type.IsConstructedGenericType) return LoadConstructedGenericType(type); diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Field.cs b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Field.cs index 0855bc6f..5fa260ba 100644 --- a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Field.cs +++ b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Field.cs @@ -2,9 +2,11 @@ { partial class ModuleLoader { - public CompilerObject LoadField(IL.FieldInfo field) + private CompilerObject LoadField(IL.FieldInfo field) { - throw new NotImplementedException(); + if (!field.IsStatic) throw new ArgumentException("Only static fields are supported.", nameof(field)); + + return new Objects.Global(field, Loader); } } } diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs index 7ac9a1c0..48ba19b6 100644 --- a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs +++ b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs @@ -2,9 +2,9 @@ { partial class ModuleLoader { - public CompilerObject LoadGenericMethod(IL.MethodInfo method) + private CompilerObject LoadGenericMethod(IL.MethodInfo method) { - throw new NotImplementedException(); + return new Objects.GenericFunction(); } } } diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs index bfc20fbb..34676c1d 100644 --- a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs +++ b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs @@ -2,12 +2,14 @@ { partial class ModuleLoader { - public CompilerObject LoadMethod(IL.MethodInfo method) + private CompilerObject LoadMethod(IL.MethodInfo method) { + if (!method.IsStatic) throw new ArgumentException("Only static methods are supported.", nameof(method)); + if (method.IsGenericMethodDefinition) return LoadGenericMethod(method); - throw new NotImplementedException(); + return new Objects.Function(); } } } diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Property.cs b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Property.cs index 044bd13b..f65156dc 100644 --- a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Property.cs +++ b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Property.cs @@ -2,7 +2,7 @@ { partial class ModuleLoader { - public CompilerObject LoadProperty(IL.PropertyInfo property) + private CompilerObject LoadProperty(IL.PropertyInfo property) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IL.cs b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IL.cs new file mode 100644 index 00000000..d1bafdd0 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IL.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Function + { + public IL.MethodInfo IL { get; } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.cs b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.cs new file mode 100644 index 00000000..6158d4ed --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Function + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.IL.cs b/ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.IL.cs new file mode 100644 index 00000000..c9b9abdb --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.IL.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class GenericFunction + { + public IL.MethodInfo IL { get; } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.cs b/ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.cs new file mode 100644 index 00000000..d76b4f2f --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class GenericFunction + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/global/Global.IL.cs b/ZSharp.Compiler.ILLoader/objects/modular/global/Global.IL.cs new file mode 100644 index 00000000..6b93e9d6 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/global/Global.IL.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Global + { + public IL.FieldInfo IL { get; } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/global/Global.Type.cs b/ZSharp.Compiler.ILLoader/objects/modular/global/Global.Type.cs new file mode 100644 index 00000000..257ad31b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/global/Global.Type.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Global + : ITyped + { + public IType Type { get; } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/global/Global.cs b/ZSharp.Compiler.ILLoader/objects/modular/global/Global.cs new file mode 100644 index 00000000..b0e6dd89 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/global/Global.cs @@ -0,0 +1,14 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Global + : CompilerObject + { + public string Name => IL.Name; + + public Global(IL.FieldInfo il, ILLoader loader) + { + IL = il; + Type = loader.LoadType(il.FieldType); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/property/Property.cs b/ZSharp.Compiler.ILLoader/objects/modular/property/Property.cs new file mode 100644 index 00000000..abd22931 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/property/Property.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Property + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs index f8da7b2d..4a9ac600 100644 --- a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs +++ b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs @@ -29,7 +29,7 @@ CompilerObjectResult ICTGetMember.Member(Compiler compiler, MemberNa return CompilerObjectResult.Ok(result); return CompilerObjectResult.Error( - $"Can't find member {member} in namespace {Name}" + $"Can't find member {member} in namespace {FullName}" ); } } From 19902c2b4a28353794dc3bc0d4dc2d51ee521ea2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 30 Jul 2025 20:17:07 +0300 Subject: [PATCH 192/235] Fix the standard filesystem library --- .../Directory.cs | 34 ---------------- ZSharp.CT.StandardLibrary.FileSystem/File.cs | 18 --------- .../GlobalUsings.cs | 1 + .../Global_Operators.cs | 29 -------------- .../ItemSpec.cs | 16 -------- .../ModuleAttributes.cs | 1 + ZSharp.CT.StandardLibrary.FileSystem/Path.cs | 40 ------------------- .../PathSpec.cs | 10 ----- ...Sharp.CT.StandardLibrary.FileSystem.csproj | 2 +- .../items/directory/Directory.From.cs | 13 ++++++ .../items/directory/Directory.Items.cs | 16 ++++++++ .../items/directory/Directory.Name.cs | 11 +++++ .../items/directory/Directory.Operators.cs | 11 +++++ .../items/directory/Directory.cs | 27 +++++++++++++ .../items/file/File.From.cs | 13 ++++++ .../items/file/File.Name.cs | 23 +++++++++++ .../items/file/File.cs | 15 +++++++ .../items/item/Item.Parent.cs | 17 ++++++++ .../items/item/Item.cs | 29 ++++++++++++++ .../items/location/Location.cs | 18 +++++++++ .../module scope/Operators.cs | 22 ++++++++++ .../path/AbsolutePath.cs | 32 +++++++++++++++ .../path/Path.cs | 26 ++++++++++++ .../path/RawPath.cs | 1 + .../path/RelativePath.cs | 24 +++++++++++ 25 files changed, 301 insertions(+), 148 deletions(-) delete mode 100644 ZSharp.CT.StandardLibrary.FileSystem/Directory.cs delete mode 100644 ZSharp.CT.StandardLibrary.FileSystem/File.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/GlobalUsings.cs delete mode 100644 ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs delete mode 100644 ZSharp.CT.StandardLibrary.FileSystem/ItemSpec.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/ModuleAttributes.cs delete mode 100644 ZSharp.CT.StandardLibrary.FileSystem/Path.cs delete mode 100644 ZSharp.CT.StandardLibrary.FileSystem/PathSpec.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.From.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Items.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Name.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Operators.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/items/file/File.From.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/items/file/File.Name.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/items/file/File.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.Parent.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/items/location/Location.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/module scope/Operators.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/path/AbsolutePath.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/path/Path.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/path/RawPath.cs create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/path/RelativePath.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/Directory.cs b/ZSharp.CT.StandardLibrary.FileSystem/Directory.cs deleted file mode 100644 index 778eb1dc..00000000 --- a/ZSharp.CT.StandardLibrary.FileSystem/Directory.cs +++ /dev/null @@ -1,34 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace Standard.FileSystem -{ - public sealed class Directory(Path path) : ItemSpec(path) - { - public Directory(string path) - : this(new Path(path)) { } - - [Alias(Name = "sub")] - public ItemSpec SubPath(string name) - => Global_Operators.SubPath(this, name); - - [Alias(Name = "createDirectory")] - public Directory CreateDirectory(string name, [KeywordParameter] bool existsOk = false) - { - var path = this.path.SubPath(name).path; - - if (!System.IO.Directory.Exists(path.pathString)) - System.IO.Directory.CreateDirectory(path.pathString); - else if (!existsOk) throw new InvalidOperationException(); - - return new(path); - } - - [Alias(Name = "cwd")] - public static Directory CurrentWorkingDirectory() - => new(System.IO.Directory.GetCurrentDirectory()); - - [Alias(Name = "toString")] - public override string ToString() - => $"Directory<{path}>"; - } -} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/File.cs b/ZSharp.CT.StandardLibrary.FileSystem/File.cs deleted file mode 100644 index 95be8c66..00000000 --- a/ZSharp.CT.StandardLibrary.FileSystem/File.cs +++ /dev/null @@ -1,18 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace Standard.FileSystem -{ - public sealed class File(Path path) : ItemSpec(path) - { - internal File(string path) - : this(new Path(path)) { } - - [Alias(Name = "toString")] - public override string ToString() - => $"File<{path}>"; - - [Alias(Name = "getContent")] - public string GetContent() - => System.IO.File.ReadAllText(path.pathString); - } -} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/GlobalUsings.cs b/ZSharp.CT.StandardLibrary.FileSystem/GlobalUsings.cs new file mode 100644 index 00000000..daef43e7 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/GlobalUsings.cs @@ -0,0 +1 @@ +global using ZSharp.Compiler.ILLoader; diff --git a/ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs b/ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs deleted file mode 100644 index 91d4b681..00000000 --- a/ZSharp.CT.StandardLibrary.FileSystem/Global_Operators.cs +++ /dev/null @@ -1,29 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace Standard.FileSystem -{ - [ModuleGlobals] - public static class Global_Operators - { - [Alias(Name = "_/_")] - public static ItemSpec SubPath(Path path, string name) - { - var newPath = System.IO.Path.Combine(path.pathString, name); - - if (System.IO.Directory.Exists(newPath)) - return new Directory(newPath); - if (System.IO.File.Exists(newPath)) - return new File(newPath); - - return new PathSpec(newPath); - } - - [Alias(Name = "_/_")] - public static ItemSpec SubPath(Directory directory, string name) - => SubPath(directory.path, name); - - [Alias(Name = "_/_")] - public static ItemSpec SubPath(PathSpec pathSpec, string name) - => SubPath(pathSpec.path, name); - } -} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/ItemSpec.cs b/ZSharp.CT.StandardLibrary.FileSystem/ItemSpec.cs deleted file mode 100644 index e06ffa9f..00000000 --- a/ZSharp.CT.StandardLibrary.FileSystem/ItemSpec.cs +++ /dev/null @@ -1,16 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace Standard.FileSystem -{ - public abstract class ItemSpec(Path path) - { - public readonly Path path = path; - - public ItemSpec(string path) - : this(new Path(path)) { } - - [Alias(Name = "toString")] - public override string ToString() - => $"Path<{path}>"; - } -} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/ModuleAttributes.cs b/ZSharp.CT.StandardLibrary.FileSystem/ModuleAttributes.cs new file mode 100644 index 00000000..69830613 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/ModuleAttributes.cs @@ -0,0 +1 @@ +[module: MapNamespace(OldName = "Standard.FileSystem", NewName = "")] diff --git a/ZSharp.CT.StandardLibrary.FileSystem/Path.cs b/ZSharp.CT.StandardLibrary.FileSystem/Path.cs deleted file mode 100644 index a247b0ad..00000000 --- a/ZSharp.CT.StandardLibrary.FileSystem/Path.cs +++ /dev/null @@ -1,40 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace Standard.FileSystem -{ - public class Path - { - internal string pathString; - - internal Path(string path) - { - this.pathString = path; - } - - //[Alias(Name = "asDirectory")] - //public Directory? AsDirectory() - //{ - // if (System.IO.Directory.Exists(path)) - // return new(path); - - // return null; - //} - - //[Alias(Name = "asFile")] - //public File? AsFile() - //{ - // if (System.IO.File.Exists(path)) - // return new(path); - - // return null; - //} - - [Alias(Name = "sub")] - public ItemSpec SubPath(string name) - => Global_Operators.SubPath(this, name); - - [Alias(Name = "toString")] - public override string ToString() - => pathString; - } -} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/PathSpec.cs b/ZSharp.CT.StandardLibrary.FileSystem/PathSpec.cs deleted file mode 100644 index c3907dc5..00000000 --- a/ZSharp.CT.StandardLibrary.FileSystem/PathSpec.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Standard.FileSystem -{ - public class PathSpec(Path path) : ItemSpec(path) - { - public PathSpec(string path) - : this(new Path(path)) - { - } - } -} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj b/ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj index 60f3ccc3..846d3599 100644 --- a/ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj +++ b/ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj @@ -8,7 +8,7 @@ - + diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.From.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.From.cs new file mode 100644 index 00000000..ed3c7fdc --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.From.cs @@ -0,0 +1,13 @@ +namespace Standard.FileSystem +{ + partial class Directory + { + public new static Directory? From(RawPath raw) + { + ArgumentNullException.ThrowIfNull(raw, nameof(raw)); + if (System.IO.Directory.Exists(raw)) + return new(raw); + return null; + } + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Items.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Items.cs new file mode 100644 index 00000000..442305b5 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Items.cs @@ -0,0 +1,16 @@ +using System.Collections; + +namespace Standard.FileSystem +{ + partial class Directory + : IEnumerable + { + IEnumerator IEnumerable.GetEnumerator() + => System.IO.Directory.EnumerateFileSystemEntries(raw) + .Select(Item.From) + .GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => (this as IEnumerable).GetEnumerator(); + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Name.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Name.cs new file mode 100644 index 00000000..b86cc23c --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Name.cs @@ -0,0 +1,11 @@ +namespace Standard.FileSystem +{ + partial class Directory + { + public string Name + { + get => System.IO.Path.GetFileName(raw); + set => System.IO.Directory.Move(raw, (Parent / value).raw); + } + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Operators.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Operators.cs new file mode 100644 index 00000000..ddbdf678 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Operators.cs @@ -0,0 +1,11 @@ +namespace Standard.FileSystem +{ + partial class Directory + { + public static Item operator /(Directory directory, RawPath path) + => Operators.Join(directory, path); + + public static Item operator/(Directory directory, RelativePath path) + => Operators.Join(directory, path.raw); + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.cs new file mode 100644 index 00000000..cddb47b7 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.cs @@ -0,0 +1,27 @@ +namespace Standard.FileSystem +{ + public sealed partial class Directory + : Item + { + private Directory(RawPath raw) : base(raw) + { + + } + + [Alias("createDirectory")] + public Directory CreateDirectory(string name, [NamedParameter] bool existsOk = false) + { + var path = (this / name).raw; + + if (!System.IO.Directory.Exists(path)) + System.IO.Directory.CreateDirectory(path); + else if (!existsOk) throw new InvalidOperationException(); + + return new(path); + } + + [Alias("cwd")] + public static Directory CurrentWorkingDirectory() + => new(System.IO.Directory.GetCurrentDirectory()); + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.From.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.From.cs new file mode 100644 index 00000000..aa38e17b --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.From.cs @@ -0,0 +1,13 @@ +namespace Standard.FileSystem +{ + partial class File + { + public new static File? From(RawPath raw) + { + ArgumentNullException.ThrowIfNull(raw, nameof(raw)); + if (System.IO.File.Exists(raw)) + return new(raw); + return null; + } + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.Name.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.Name.cs new file mode 100644 index 00000000..7af9f445 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.Name.cs @@ -0,0 +1,23 @@ +namespace Standard.FileSystem +{ + partial class File + { + public string Extension + { + get => System.IO.Path.GetExtension(raw); + set => System.IO.File.Move(raw, (Parent / $"{Stem}{value}").raw); + } + + public string Name + { + get => System.IO.Path.GetFileName(raw); + set => System.IO.File.Move(raw, (Parent / value).raw); + } + + public string Stem + { + get => System.IO.Path.GetFileNameWithoutExtension(raw); + set => System.IO.File.Move(raw, (Parent / $"{value}{Extension}").raw); + } + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.cs new file mode 100644 index 00000000..1375f4e7 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.cs @@ -0,0 +1,15 @@ +namespace Standard.FileSystem +{ + public sealed partial class File + : Item + { + private File(RawPath raw) : base(raw) + { + + } + + [Alias("getContent")] + public string GetContent() + => System.IO.File.ReadAllText(raw); + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.Parent.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.Parent.cs new file mode 100644 index 00000000..075cb9dc --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.Parent.cs @@ -0,0 +1,17 @@ +namespace Standard.FileSystem +{ + partial class Item + { + private Directory? parent; + + public Directory Parent + { + get + { + if (parent is not null) return parent; + + return parent = Directory.From(System.IO.Directory.GetParent(raw)!.FullName) ?? throw new(); + } + } + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.cs new file mode 100644 index 00000000..dc8a53f5 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.cs @@ -0,0 +1,29 @@ +namespace Standard.FileSystem +{ + public abstract partial class Item(RawPath raw) + { + protected internal readonly RawPath raw = raw ?? throw new ArgumentNullException(nameof(raw)); + + [Alias("toString")] + public override string ToString() + => $"{GetType().Name}<{raw}>"; + + internal static Item From(RawPath raw) + => Directory.From(raw) as Item + ?? File.From(raw) as Item + ?? Location.From(raw); + + public override int GetHashCode() + => (GetType(), raw).GetHashCode(); + + public override bool Equals(object? obj) + { + if (obj is Item other) + { + return raw == other.raw && GetType() == other.GetType(); + } + + return false; + } + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/location/Location.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/location/Location.cs new file mode 100644 index 00000000..375ce193 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/location/Location.cs @@ -0,0 +1,18 @@ + +namespace Standard.FileSystem +{ + public sealed class Location + : Item + { + private Location(RawPath raw) : base(raw) + { + + } + + public new static Location From(RawPath raw) + { + ArgumentNullException.ThrowIfNull(raw, nameof(raw)); + return new(raw); + } + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/module scope/Operators.cs b/ZSharp.CT.StandardLibrary.FileSystem/module scope/Operators.cs new file mode 100644 index 00000000..66137955 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/module scope/Operators.cs @@ -0,0 +1,22 @@ +namespace Standard.FileSystem +{ + [ModuleScope] + public static class Operators + { + [Operator("/", Kind = OperatorKind.Infix)] + public static Path Join(Path path, RawPath sub) + => path.JoinWith(sub); + + [Operator("/", Kind = OperatorKind.Infix)] + public static Path Join(Path path, RelativePath sub) + => path.JoinWith(sub.raw); + + [Operator("/", Kind = OperatorKind.Infix)] + public static Item Join(Directory directory, RelativePath path) + => Item.From(System.IO.Path.Combine(directory.raw, path.raw)); + + [Operator("/", Kind = OperatorKind.Infix)] + public static Item Join(Directory directory, RawPath path) + => Item.From(System.IO.Path.Combine(directory.raw, path)); + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/path/AbsolutePath.cs b/ZSharp.CT.StandardLibrary.FileSystem/path/AbsolutePath.cs new file mode 100644 index 00000000..b70af526 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/path/AbsolutePath.cs @@ -0,0 +1,32 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Standard.FileSystem +{ + public sealed class AbsolutePath : Path + { + private AbsolutePath(RawPath raw) : base(raw) + { + + } + + public new bool Is([NotNullWhen(true)] out Directory? result) + => (result = Directory.From(raw)) is not null; + + public new bool Is([NotNullWhen(true)] out File? result) + => (result = File.From(raw)) is not null; + + public override AbsolutePath Resolve() + => this; + + public override Path JoinWith(params RawPath[] raw) + => new AbsolutePath(System.IO.Path.Combine([this.raw, ..raw])); + + public new static AbsolutePath? From(RawPath raw) + { + if (!System.IO.Path.IsPathRooted(raw)) + return null; + + return new(raw); + } + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/path/Path.cs b/ZSharp.CT.StandardLibrary.FileSystem/path/Path.cs new file mode 100644 index 00000000..cebee0ec --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/path/Path.cs @@ -0,0 +1,26 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Standard.FileSystem +{ + public abstract class Path(RawPath raw) + { + protected internal readonly RawPath raw = raw ?? throw new ArgumentNullException(nameof(raw)); + + public bool Is([NotNullWhen(true)] out Directory? result) + => Resolve().Is(out result); + + public bool Is([NotNullWhen(true)] out File? result) + => Resolve().Is(out result); + + public abstract AbsolutePath Resolve(); + + public abstract Path JoinWith(params RawPath[] raw); + + public override string ToString() + => $"{GetType().Name}<{raw}>"; + + public static Path? From(RawPath raw) + => AbsolutePath.From(raw) as Path + ?? RelativePath.From(raw); + } +} diff --git a/ZSharp.CT.StandardLibrary.FileSystem/path/RawPath.cs b/ZSharp.CT.StandardLibrary.FileSystem/path/RawPath.cs new file mode 100644 index 00000000..02d2ef11 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/path/RawPath.cs @@ -0,0 +1 @@ +global using RawPath = string; diff --git a/ZSharp.CT.StandardLibrary.FileSystem/path/RelativePath.cs b/ZSharp.CT.StandardLibrary.FileSystem/path/RelativePath.cs new file mode 100644 index 00000000..a714e18a --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/path/RelativePath.cs @@ -0,0 +1,24 @@ +namespace Standard.FileSystem +{ + public sealed class RelativePath : Path + { + private RelativePath(RawPath raw) : base(raw) + { + + } + + public override AbsolutePath Resolve() + => AbsolutePath.From(System.IO.Path.GetFullPath(raw))!; + + public override Path JoinWith(params RawPath[] raw) + => new RelativePath(System.IO.Path.Combine([this.raw, .. raw])); + + public new static RelativePath? From(RawPath raw) + { + if (System.IO.Path.IsPathRooted(raw)) + return null; + + return new(raw); + } + } +} From 74c0f9ca01661c5624f488fc4875124b0eaa5b7a Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 30 Jul 2025 20:17:37 +0300 Subject: [PATCH 193/235] Fix interpreter and runtime --- ZSharp.Interpreter/CTServices.cs | 16 ++++++++++ ZSharp.Interpreter/ZSharp.Interpreter.csproj | 4 ++- ZSharp.Interpreter/interpreter/IHostLoader.cs | 7 ----- .../interpreter/Interpreter.IL.cs | 10 ++++++ .../interpreter/Interpreter.Runtime.cs | 7 +++++ .../interpreter/Interpreter.T.cs | 6 ++++ ZSharp.Interpreter/interpreter/Interpreter.cs | 31 ++++++++++--------- ZSharp.Interpreter/interpreter/rt/IRuntime.cs | 7 ----- .../document/compiler/DocumentCompiler.cs | 2 +- .../importers/StandardLibraryImporter.cs | 2 +- .../import system/importers/StringImporter.cs | 2 +- .../import system/importers/ZSImporter.cs | 2 +- ZSharp.Runtime/runtime/Runtime.Evaluate.cs | 12 +++++++ ZSharp.Runtime/runtime/Runtime.IR.cs | 2 +- 14 files changed, 75 insertions(+), 35 deletions(-) create mode 100644 ZSharp.Interpreter/CTServices.cs delete mode 100644 ZSharp.Interpreter/interpreter/IHostLoader.cs create mode 100644 ZSharp.Interpreter/interpreter/Interpreter.IL.cs create mode 100644 ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs create mode 100644 ZSharp.Interpreter/interpreter/Interpreter.T.cs delete mode 100644 ZSharp.Interpreter/interpreter/rt/IRuntime.cs create mode 100644 ZSharp.Runtime/runtime/Runtime.Evaluate.cs diff --git a/ZSharp.Interpreter/CTServices.cs b/ZSharp.Interpreter/CTServices.cs new file mode 100644 index 00000000..cbe32509 --- /dev/null +++ b/ZSharp.Interpreter/CTServices.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Interpreter +{ + public static class CTServices + { + public static CompilerObject InfoOf(object @object) + { + throw new NotImplementedException(); + } + + public static T? InfoOf(object @object) + where T : class, CompilerObject + { + return InfoOf(@object) as T; + } + } +} diff --git a/ZSharp.Interpreter/ZSharp.Interpreter.csproj b/ZSharp.Interpreter/ZSharp.Interpreter.csproj index 90a06527..d7bfa9d5 100644 --- a/ZSharp.Interpreter/ZSharp.Interpreter.csproj +++ b/ZSharp.Interpreter/ZSharp.Interpreter.csproj @@ -8,11 +8,13 @@ + + - + diff --git a/ZSharp.Interpreter/interpreter/IHostLoader.cs b/ZSharp.Interpreter/interpreter/IHostLoader.cs deleted file mode 100644 index 174a2af3..00000000 --- a/ZSharp.Interpreter/interpreter/IHostLoader.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Interpreter -{ - public interface IHostLoader - { - public IR.Module Import(System.Reflection.Module module); - } -} diff --git a/ZSharp.Interpreter/interpreter/Interpreter.IL.cs b/ZSharp.Interpreter/interpreter/Interpreter.IL.cs new file mode 100644 index 00000000..8dcf8520 --- /dev/null +++ b/ZSharp.Interpreter/interpreter/Interpreter.IL.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Interpreter +{ + partial class Interpreter + { + public Compiler.ILLoader.ILLoader ILLoader { get; } + + public CompilerObject ImportILModule(System.Reflection.Module module) + => ILLoader.LoadModule(module); + } +} diff --git a/ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs b/ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs new file mode 100644 index 00000000..0b2d6d3d --- /dev/null +++ b/ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Interpreter +{ + partial class Interpreter + { + public Runtime.Runtime Runtime { get; } + } +} diff --git a/ZSharp.Interpreter/interpreter/Interpreter.T.cs b/ZSharp.Interpreter/interpreter/Interpreter.T.cs new file mode 100644 index 00000000..3389a954 --- /dev/null +++ b/ZSharp.Interpreter/interpreter/Interpreter.T.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Interpreter +{ + partial class Interpreter + { + } +} diff --git a/ZSharp.Interpreter/interpreter/Interpreter.cs b/ZSharp.Interpreter/interpreter/Interpreter.cs index c1d58645..05981929 100644 --- a/ZSharp.Interpreter/interpreter/Interpreter.cs +++ b/ZSharp.Interpreter/interpreter/Interpreter.cs @@ -2,17 +2,15 @@ namespace ZSharp.Interpreter { - public class Interpreter + public sealed partial class Interpreter { - public Runtime.NET.Runtime HostLoader => Runtime; - - public Runtime.NET.Runtime Runtime { get; } + //public Runtime.NET.Runtime Runtime { get; } public IR.RuntimeModule RuntimeModule { get; } - public Compiler.Compiler Compiler { get; init; } + public Compiler.Compiler Compiler { get; } - public Compiler.IRLoader.IRLoader CompilerIRLoader { get; } + public IRCompiler.Compiler IRCompiler { get; } public ZSSourceCompiler.ZSSourceCompiler SourceCompiler { get; init; } @@ -24,10 +22,11 @@ public Interpreter(IR.RuntimeModule? runtimeModule = null) Compiler = new(RuntimeModule); Runtime = new(RuntimeModule); + IRCompiler = new(RuntimeModule); + ILLoader = new(Compiler); new Ops(Compiler); - CompilerIRLoader = new(Compiler); SourceCompiler = new(this); Parser = new(); @@ -48,40 +47,42 @@ public ZSSourceCompiler.Document CompileDocument(AST.Document document, string p return SourceCompiler.CreateDocumentCompiler(document, path).Compile(); } - public Result Evaluate(Expression expression) + public Result Evaluate(Expression expression) { if ( SourceCompiler.CompileNode(expression) .When(out var result) .IsError - ) return Result.Error(string.Empty); + ) return Result.Error(string.Empty); return Evaluate(result!); } - public Result Evaluate(CompilerObject @object) + public Result Evaluate(CompilerObject @object) { if ( Compiler.IR.CompileCode(@object) .When(out var irCode) .Error(out var error) ) - return Result.Ok(@object); + return Result.Ok(@object); + + var type = irCode!.IsVoid ? RuntimeModule.TypeSystem.Void : IRCompiler.CompileType(irCode.RequireValueType()).Unwrap(); - var result = Runtime.Evaluator.EvaluateCT(irCode ?? throw new(), Compiler); + var result = Runtime.Evaluate(irCode.Instructions, type); if (irCode.IsVoid) - return Result + return Result .Ok(new Objects.RawCode(new())); if (result is null) - return Result + return Result .Ok(@object); // TODO: should actually be an error! //return Result // .Error("Non-void expression evaluated to nothing"); - return Result.Ok(result); + return Result.Ok(result); } } } diff --git a/ZSharp.Interpreter/interpreter/rt/IRuntime.cs b/ZSharp.Interpreter/interpreter/rt/IRuntime.cs deleted file mode 100644 index 20317574..00000000 --- a/ZSharp.Interpreter/interpreter/rt/IRuntime.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Interpreter -{ - public interface IRuntime - { - public void Import(IR.Module module); - } -} diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.cs b/ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.cs index 6d537edf..b9352719 100644 --- a/ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.cs +++ b/ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.cs @@ -35,7 +35,7 @@ private void CompileDocument() expression ).When(out var result).Error(out var error) ? Compiler.CompilationError(error, expression) - : ObjectResult.Ok(result!) + : ObjectResult.Ok(Interpreter.CTServices.InfoOf(result!)) }; return null; diff --git a/ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs b/ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs index 58a06930..21c25bef 100644 --- a/ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs +++ b/ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs @@ -17,7 +17,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) if ( arguments.Length > 1 || arguments[0].Name is not null || - !compiler.IsString(interpreter.Evaluate(arguments[0].Object).Unwrap(), out var libraryName) + interpreter.Evaluate(arguments[0].Object).Unwrap() is not string libraryName ) { compiler.Log.Error("`std` importer must have exactly 1 argument of type `string`", this); diff --git a/ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs b/ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs index c147d835..ac653b1a 100644 --- a/ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs +++ b/ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs @@ -15,7 +15,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) { Argument sourceArgument = arguments.FirstOrDefault(arg => arg.Name is null) ?? throw new(); - if (!compiler.IsString(interpreter.Evaluate(sourceArgument.Object).Unwrap(), out var source)) + if (interpreter.Evaluate(sourceArgument.Object).Unwrap() is not string source) throw new(); // TODO: proper exception: first parameter must be a string string[] parts = source.Split(':', 2); diff --git a/ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs b/ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs index 37601b18..1888f88e 100644 --- a/ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs +++ b/ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs @@ -17,7 +17,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) if ( arguments.Length > 1 || arguments[0].Name is not null || - !compiler.IsString(interpreter.Evaluate(arguments[0].Object).Unwrap(), out var libraryName) + interpreter.Evaluate(arguments[0].Object).Unwrap() is not string libraryName ) { compiler.Log.Error("`zs` importer must have exactly 1 argument of type `string`", this); diff --git a/ZSharp.Runtime/runtime/Runtime.Evaluate.cs b/ZSharp.Runtime/runtime/Runtime.Evaluate.cs new file mode 100644 index 00000000..18ad09cf --- /dev/null +++ b/ZSharp.Runtime/runtime/Runtime.Evaluate.cs @@ -0,0 +1,12 @@ +using CommonZ.Utils; + +namespace ZSharp.Runtime +{ + partial class Runtime + { + public object? Evaluate(Collection code, IR.IType type) + { + return Loader.LoadCode(code, type).DynamicInvoke(null); + } + } +} diff --git a/ZSharp.Runtime/runtime/Runtime.IR.cs b/ZSharp.Runtime/runtime/Runtime.IR.cs index 4d0d3bac..e9742429 100644 --- a/ZSharp.Runtime/runtime/Runtime.IR.cs +++ b/ZSharp.Runtime/runtime/Runtime.IR.cs @@ -2,6 +2,6 @@ { partial class Runtime { - public required IR.RuntimeModule RuntimeModule { get; init; } + public IR.RuntimeModule RuntimeModule { get; } } } From a533b340da67d5ef4b0a09afdb36a06e4a2b549b Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 30 Jul 2025 20:17:51 +0300 Subject: [PATCH 194/235] Fix dotnet importer --- ZSharpTest/DotNETImporter.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ZSharpTest/DotNETImporter.cs b/ZSharpTest/DotNETImporter.cs index cae64571..c61bf90f 100644 --- a/ZSharpTest/DotNETImporter.cs +++ b/ZSharpTest/DotNETImporter.cs @@ -19,7 +19,7 @@ public Objects.CompilerObject Call(Compiler.Compiler compiler, Argument[] argume if ( arguments.Length > 1 || arguments[0].Name is not null || - !compiler.IsString(interpreter.Evaluate(arguments[0].Object).Unwrap(), out var libraryName) + interpreter.Evaluate(arguments[0].Object).Unwrap() is not string libraryName ) { compiler.Log.Error("`net` importer must have exactly 1 argument of type `string`", this); @@ -45,9 +45,7 @@ private Objects.CompilerObject ImportDotNETLibrary(string libraryName) var module = modules[0]; - var ir = interpreter.HostLoader.Import(module); - - return interpreter.CompilerIRLoader.Import(ir); + return interpreter.ImportILModule(module); } } } From 37b9cb585950c0939751d3eb41017654859959b4 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 30 Jul 2025 20:18:03 +0300 Subject: [PATCH 195/235] Add project compiler --- ZSharp.SourceCompiler.Project/GlobalUsings.cs | 3 ++ .../ModuleAttributes.cs | 1 + .../ZSharp.SourceCompiler.Project.csproj | 18 +++++++++ .../discovery/ProjectDiscovery.cs | 16 ++++++++ .../discovery/SubModuleDiscovery.cs | 38 +++++++++++++++++++ .../project/Project.cs | 13 +++++++ .../project/SubModule.cs | 23 +++++++++++ 7 files changed, 112 insertions(+) create mode 100644 ZSharp.SourceCompiler.Project/GlobalUsings.cs create mode 100644 ZSharp.SourceCompiler.Project/ModuleAttributes.cs create mode 100644 ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj create mode 100644 ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs create mode 100644 ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs create mode 100644 ZSharp.SourceCompiler.Project/project/Project.cs create mode 100644 ZSharp.SourceCompiler.Project/project/SubModule.cs diff --git a/ZSharp.SourceCompiler.Project/GlobalUsings.cs b/ZSharp.SourceCompiler.Project/GlobalUsings.cs new file mode 100644 index 00000000..77f26af5 --- /dev/null +++ b/ZSharp.SourceCompiler.Project/GlobalUsings.cs @@ -0,0 +1,3 @@ +global using System.Collections.Generic; + +global using ZSharp.Compiler.ILLoader; diff --git a/ZSharp.SourceCompiler.Project/ModuleAttributes.cs b/ZSharp.SourceCompiler.Project/ModuleAttributes.cs new file mode 100644 index 00000000..d32f6d8d --- /dev/null +++ b/ZSharp.SourceCompiler.Project/ModuleAttributes.cs @@ -0,0 +1 @@ +[module: MapNamespace(OldName = "ZSharp.SourceCompiler.Project", NewName = "")] diff --git a/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj b/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj new file mode 100644 index 00000000..1b43b837 --- /dev/null +++ b/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj @@ -0,0 +1,18 @@ + + + + net8.0 + disable + enable + + + + + + + + + + + + diff --git a/ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs b/ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs new file mode 100644 index 00000000..f460ca9b --- /dev/null +++ b/ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs @@ -0,0 +1,16 @@ +using Standard.FileSystem; + +namespace ZSharp.SourceCompiler.Project +{ + public sealed class ProjectDiscovery(Project project) + { + private readonly Dictionary _subModules = []; + + public Project Project { get; } = project; + + public void Discover() + { + + } + } +} diff --git a/ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs b/ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs new file mode 100644 index 00000000..85a7851e --- /dev/null +++ b/ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs @@ -0,0 +1,38 @@ +using Standard.FileSystem; + +namespace ZSharp.SourceCompiler.Project +{ + public class SubModuleDiscovery(SubModule subModule) + { + public const string SubModuleFileName = ".zs"; + + private readonly Dictionary _subModules = []; + + public SubModule SubModule { get; } = subModule; + + public void Discover() + { + Discover(SubModule.SourceDirectory, SubModule); + } + + private void Discover(Directory directory, SubModule subModule) + { + _subModules[directory] = subModule; + + foreach (var item in directory) + if (item is Directory subDirectory) + Discover( + subDirectory, + (subDirectory / SubModuleFileName) is File subModuleFule + ? new(subDirectory.Name, subDirectory) + { + SubModuleFile = subModuleFule + } + : subModule + ); + else if (item is not File file || file.Equals(subModule.SubModuleFile)) continue; + else if (file.Extension != ".zs") continue; + else subModule.SourceFiles.Add(file); + } + } +} diff --git a/ZSharp.SourceCompiler.Project/project/Project.cs b/ZSharp.SourceCompiler.Project/project/Project.cs new file mode 100644 index 00000000..bc0df322 --- /dev/null +++ b/ZSharp.SourceCompiler.Project/project/Project.cs @@ -0,0 +1,13 @@ +using Standard.FileSystem; + +namespace ZSharp.SourceCompiler.Project +{ + public sealed class Project( + string name, + Directory rootDirectory, + Directory? sourceDirectory = null + ) + : SubModule(name, rootDirectory, sourceDirectory) + { + } +} diff --git a/ZSharp.SourceCompiler.Project/project/SubModule.cs b/ZSharp.SourceCompiler.Project/project/SubModule.cs new file mode 100644 index 00000000..9561231f --- /dev/null +++ b/ZSharp.SourceCompiler.Project/project/SubModule.cs @@ -0,0 +1,23 @@ +using Standard.FileSystem; + +namespace ZSharp.SourceCompiler.Project +{ + public class SubModule( + string name, + Directory rootDirectory, + Directory? sourceDirectory = null + ) + { + public string Name { get; } = name; + + public Directory RootDirectory { get; } = rootDirectory; + + public Directory SourceDirectory { get; } = sourceDirectory ?? rootDirectory; + + public List SourceFiles { get; } = []; + + public List SubModules { get; } = []; + + public required File SubModuleFile { get; init; } + } +} From b894d7b02b68b3c15526415c12739462ae5c6cb2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 30 Jul 2025 20:18:27 +0300 Subject: [PATCH 196/235] Add question mark --- ZSharp.Compiler/core/Result.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.Compiler/core/Result.cs b/ZSharp.Compiler/core/Result.cs index 97dff21b..2ee2b10c 100644 --- a/ZSharp.Compiler/core/Result.cs +++ b/ZSharp.Compiler/core/Result.cs @@ -3,7 +3,7 @@ namespace ZSharp.Compiler { public sealed class Result - where TResult : class + where TResult : class? where TError : class { private readonly TResult? result; From 4bffa73511f890d7c7d0e1bf2c27a401704c3dab Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 30 Jul 2025 20:18:39 +0300 Subject: [PATCH 197/235] I'm tired --- Testing/Program.cs | 2 +- ZSharp v1.sln | 18 ++++++++++++------ ZSharpTest/Main.cs | 22 +++++----------------- 3 files changed, 18 insertions(+), 24 deletions(-) diff --git a/Testing/Program.cs b/Testing/Program.cs index 13307fc5..a445e998 100644 --- a/Testing/Program.cs +++ b/Testing/Program.cs @@ -4,7 +4,7 @@ var coc = new ZSharp.Compiler.Compiler(); -var ilLoader = new ILLoader(); +var ilLoader = new ILLoader(coc); var module = new Objects.Module(typeof(TestClass).Module, ilLoader); var zLoadTest = ilLoader.Namespace("ZLoad.Test"); diff --git a/ZSharp v1.sln b/ZSharp v1.sln index b747c698..3ed5dc17 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -36,8 +36,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.CompilerAPI", "ZS EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.RuntimeAPI", "ZSharp.CT.RuntimeAPI\ZSharp.CT.RuntimeAPI.csproj", "{360265D8-8811-4A25-9060-AD9B9D334D8C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Runtime.IL", "ZSharp.Runtime.IL\ZSharp.Runtime.IL.csproj", "{A3937E93-8537-4251-AF60-7DB8ECE0D99C}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.StandardLibrary.Math", "ZSharp.CT.StandardLibrary.Math\ZSharp.CT.StandardLibrary.Math.csproj", "{AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Objects", "ZSharp.Compiler.Objects\ZSharp.Compiler.Objects.csproj", "{6B3BEDB2-F3CB-400E-A257-D79F73075AF9}" @@ -58,6 +56,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Runtime", "ZSharp.Ru EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.IR", "ZSharp.Compiler.IR\ZSharp.Compiler.IR.csproj", "{B3E3E076-4B77-433F-9466-D0A0D8D9EAFA}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.SourceCompiler.Project", "ZSharp.SourceCompiler.Project\ZSharp.SourceCompiler.Project.csproj", "{FBDD6EA4-FA23-47B3-8A41-538AE2EA575E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.ILLoader.Attributes", "ZSharp.Compiler.ILLoader.Attributes\ZSharp.Compiler.ILLoader.Attributes.csproj", "{42BF3911-0DC7-4831-A989-98D48C17CC74}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -124,10 +126,6 @@ Global {360265D8-8811-4A25-9060-AD9B9D334D8C}.Debug|Any CPU.Build.0 = Debug|Any CPU {360265D8-8811-4A25-9060-AD9B9D334D8C}.Release|Any CPU.ActiveCfg = Release|Any CPU {360265D8-8811-4A25-9060-AD9B9D334D8C}.Release|Any CPU.Build.0 = Release|Any CPU - {A3937E93-8537-4251-AF60-7DB8ECE0D99C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A3937E93-8537-4251-AF60-7DB8ECE0D99C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A3937E93-8537-4251-AF60-7DB8ECE0D99C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A3937E93-8537-4251-AF60-7DB8ECE0D99C}.Release|Any CPU.Build.0 = Release|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Debug|Any CPU.Build.0 = Debug|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -168,6 +166,14 @@ Global {B3E3E076-4B77-433F-9466-D0A0D8D9EAFA}.Debug|Any CPU.Build.0 = Debug|Any CPU {B3E3E076-4B77-433F-9466-D0A0D8D9EAFA}.Release|Any CPU.ActiveCfg = Release|Any CPU {B3E3E076-4B77-433F-9466-D0A0D8D9EAFA}.Release|Any CPU.Build.0 = Release|Any CPU + {FBDD6EA4-FA23-47B3-8A41-538AE2EA575E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FBDD6EA4-FA23-47B3-8A41-538AE2EA575E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FBDD6EA4-FA23-47B3-8A41-538AE2EA575E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FBDD6EA4-FA23-47B3-8A41-538AE2EA575E}.Release|Any CPU.Build.0 = Release|Any CPU + {42BF3911-0DC7-4831-A989-98D48C17CC74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {42BF3911-0DC7-4831-A989-98D48C17CC74}.Debug|Any CPU.Build.0 = Debug|Any CPU + {42BF3911-0DC7-4831-A989-98D48C17CC74}.Release|Any CPU.ActiveCfg = Release|Any CPU + {42BF3911-0DC7-4831-A989-98D48C17CC74}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs index 196a51a5..e643f08e 100644 --- a/ZSharpTest/Main.cs +++ b/ZSharpTest/Main.cs @@ -141,29 +141,17 @@ new Referencing(interpreter.Compiler); new OOP(interpreter.Compiler); -var runtime = interpreter.Runtime; - var moduleIL_standardIO = typeof(Standard.IO.Impl_Globals).Module; -var moduleIR_standardIO = interpreter.HostLoader.Import(moduleIL_standardIO); -var moduleCO_standardIO = interpreter.CompilerIRLoader.Import(moduleIR_standardIO); +var moduleCO_standardIO = interpreter.ImportILModule(moduleIL_standardIO); -interpreter.Compiler.TypeSystem.String.ToString = interpreter.CompilerIRLoader.Import( - runtime.Import( - ZSharp.Runtime.NET.Utils.GetMethod(Standard.IO.Impl_Globals.ToString) - ) -); +interpreter.Compiler.TypeSystem.String.ToString = interpreter.ILLoader.LoadMethod(ZSharp.Runtime.NET.Utils.GetMethod(Standard.IO.Impl_Globals.ToString)); -interpreter.Compiler.TypeSystem.Int32.Members["parse"] = interpreter.CompilerIRLoader.Import( - runtime.Import( - ZSharp.Runtime.NET.Utils.GetMethod(Standard.IO.Impl_Globals.ParseInt32) - ) -); +interpreter.Compiler.TypeSystem.Int32.Members["parse"] = interpreter.ILLoader.LoadMethod(ZSharp.Runtime.NET.Utils.GetMethod(Standard.IO.Impl_Globals.ParseInt32)); interpreter.SourceCompiler.StandardLibraryImporter.Libraries.Add("io", moduleCO_standardIO); var moduleIL_standardMath = typeof(Standard.Math.Impl_Globals).Module; -var moduleIR_standardMath = interpreter.HostLoader.Import(moduleIL_standardMath); -var moduleCO_standardMath = interpreter.CompilerIRLoader.Import(moduleIR_standardMath); +var moduleCO_standardMath = interpreter.ImportILModule(moduleIL_standardMath); interpreter.SourceCompiler.StandardLibraryImporter.Libraries.Add("math", moduleCO_standardMath); @@ -190,7 +178,7 @@ var mainModuleIR = interpreter.Compiler.CompileIRObject(mainModule, null) ?? throw new(); - var mainModuleIL = runtime.Import(mainModuleIR); + var mainModuleIL = interpreter.Runtime.ImportModule(mainModuleIR); var mainModuleGlobals = mainModuleIL.GetType("") ?? throw new(); foreach (var type in mainModuleIL.GetTypes()) From 9b355a46db239ee3373fb8db8a4834849fe17ebb Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 1 Aug 2025 00:12:33 +0300 Subject: [PATCH 198/235] Remove IR submodules --- .gitignore | 1 + .../ir loader/IRLoader.Impl.cs | 4 ---- ZSharp.Compiler.Objects/modular/Module.cs | 2 -- ZSharp.IR/ir/modular/module/Module.cs | 15 --------------- ZSharp.NETCompiler/Compiler.cs | 3 --- .../loaders/module/load/ModuleLoader.Load.cs | 15 --------------- 6 files changed, 1 insertion(+), 39 deletions(-) diff --git a/.gitignore b/.gitignore index e7bd4192..c468fc76 100644 --- a/.gitignore +++ b/.gitignore @@ -398,3 +398,4 @@ FodyWeavers.xsd *.sln.iml .lh/ +/ZSharpTest/test.zs diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs index c1d09435..e7dc7d14 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs @@ -27,10 +27,6 @@ private Module Import(ZSharp.IR.Module module, Module result) List actions = []; - if (module.HasSubmodules) - foreach (var submodule in module.Submodules) - actions.Add(Load(submodule, result)); - if (module.HasFunctions) foreach (var function in module.Functions) actions.Add(Load(function, result)); diff --git a/ZSharp.Compiler.Objects/modular/Module.cs b/ZSharp.Compiler.Objects/modular/Module.cs index d7970cde..9de728d3 100644 --- a/ZSharp.Compiler.Objects/modular/Module.cs +++ b/ZSharp.Compiler.Objects/modular/Module.cs @@ -41,8 +41,6 @@ public IR.Module CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) IR = new(Name); - owner?.Submodules.Add(IR); - foreach (var item in Content) compiler.CompileIRObject(item, IR); diff --git a/ZSharp.IR/ir/modular/module/Module.cs b/ZSharp.IR/ir/modular/module/Module.cs index 8fd48439..81e21b5f 100644 --- a/ZSharp.IR/ir/modular/module/Module.cs +++ b/ZSharp.IR/ir/modular/module/Module.cs @@ -10,7 +10,6 @@ public sealed class Module(string? name) : ModuleMember private ModuleCollection? _importedModules; private ModuleCollection? _functions; private GlobalCollection? _globals; - private ModuleCollection? _submodules; private ModuleCollection? _types; public string? Name { get; set; } = name; @@ -93,20 +92,6 @@ public Collection Globals public bool HasGlobals => !_globals.IsNullOrEmpty(); - public Collection Submodules - { - get - { - if (_submodules is not null) - return _submodules; - - Interlocked.CompareExchange(ref _submodules, new(this), null); - return _submodules; - } - } - - public bool HasSubmodules => !_submodules.IsNullOrEmpty(); - public Collection Types { get diff --git a/ZSharp.NETCompiler/Compiler.cs b/ZSharp.NETCompiler/Compiler.cs index fcf2c692..dee8dd58 100644 --- a/ZSharp.NETCompiler/Compiler.cs +++ b/ZSharp.NETCompiler/Compiler.cs @@ -6,9 +6,6 @@ public sealed class Compiler { public ModuleDefinition Compile(IR.Module module) { - if (module.HasSubmodules) - throw new NotSupportedException(); - var result = ModuleDefinition.CreateModule( module.Name ?? "", new ModuleParameters() diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs index 87cdb56b..509605a6 100644 --- a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs +++ b/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs @@ -13,8 +13,6 @@ public IL.Module Load() private void LoadAll() { - LoadSubmodules(); - LoadTypes(); LoadGlobals(); @@ -24,19 +22,6 @@ private void LoadAll() LoadInitializer(); } - private void LoadSubmodules() - { - if (IRModule.HasSubmodules) - foreach (var module in IRModule.Submodules) - Loader.Runtime.AddModule( - module, - new ModuleLoader(Loader, module) - { - AssemblyBuilder = AssemblyBuilder - }.Load() - ); - } - private void LoadTypes() { if (IRModule.HasTypes) From 6b847d32670bfa56dcfe95bd930fbbb503e29ca3 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 1 Aug 2025 00:12:58 +0300 Subject: [PATCH 199/235] Implement project discovery --- .../ZSharp.SourceCompiler.Project.csproj | 1 + .../discovery/ProjectDiscovery.cs | 14 +++----- .../discovery/SubModuleDiscovery.cs | 24 ++++++------- .../project/Project.cs | 34 +++++++++++++++++-- .../project/SubModule.cs | 12 ++----- 5 files changed, 48 insertions(+), 37 deletions(-) diff --git a/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj b/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj index 1b43b837..1fdbfde6 100644 --- a/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj +++ b/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj @@ -8,6 +8,7 @@ + diff --git a/ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs b/ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs index f460ca9b..a29f9fe2 100644 --- a/ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs +++ b/ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs @@ -1,16 +1,10 @@ -using Standard.FileSystem; - -namespace ZSharp.SourceCompiler.Project +namespace ZSharp.SourceCompiler.Project { - public sealed class ProjectDiscovery(Project project) + public static class ProjectDiscovery { - private readonly Dictionary _subModules = []; - - public Project Project { get; } = project; - - public void Discover() + public static void Discover(Project project) { - + new SubModuleDiscovery(project.RootModule).Discover(); } } } diff --git a/ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs b/ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs index 85a7851e..0c697b89 100644 --- a/ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs +++ b/ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs @@ -6,30 +6,26 @@ public class SubModuleDiscovery(SubModule subModule) { public const string SubModuleFileName = ".zs"; - private readonly Dictionary _subModules = []; - public SubModule SubModule { get; } = subModule; public void Discover() { - Discover(SubModule.SourceDirectory, SubModule); + Discover(SubModule.Directory, SubModule); } private void Discover(Directory directory, SubModule subModule) { - _subModules[directory] = subModule; - foreach (var item in directory) if (item is Directory subDirectory) - Discover( - subDirectory, - (subDirectory / SubModuleFileName) is File subModuleFule - ? new(subDirectory.Name, subDirectory) - { - SubModuleFile = subModuleFule - } - : subModule - ); + { + var innerModule = subModule; + if (subDirectory / SubModuleFileName is File subModuleFule) + subModule.SubModules.Add(innerModule = new SubModule(subDirectory) + { + SubModuleFile = subModuleFule + }); + Discover(subDirectory, innerModule); + } else if (item is not File file || file.Equals(subModule.SubModuleFile)) continue; else if (file.Extension != ".zs") continue; else subModule.SourceFiles.Add(file); diff --git a/ZSharp.SourceCompiler.Project/project/Project.cs b/ZSharp.SourceCompiler.Project/project/Project.cs index bc0df322..b5b16c20 100644 --- a/ZSharp.SourceCompiler.Project/project/Project.cs +++ b/ZSharp.SourceCompiler.Project/project/Project.cs @@ -5,9 +5,37 @@ namespace ZSharp.SourceCompiler.Project public sealed class Project( string name, Directory rootDirectory, - Directory? sourceDirectory = null - ) - : SubModule(name, rootDirectory, sourceDirectory) + Directory? sourceDirectory = null, + File? subModuleFile = null + ) { + public string Name { get; } = name; + + public Directory RootDirectory { get; } = rootDirectory; + + public Directory SourceDirectory => RootModule.Directory; + + public SubModule RootModule { get; } = new(sourceDirectory ?? rootDirectory) + { + SubModuleFile = + subModuleFile + ?? (sourceDirectory ?? rootDirectory) / SubModuleDiscovery.SubModuleFileName as File + ?? throw new System.ArgumentException( + $"Could not find file at {(sourceDirectory ?? rootDirectory) / SubModuleDiscovery.SubModuleFileName}", nameof(subModuleFile) + ) + }; + + public IEnumerable GetAllSubModules() + { + static IEnumerable GetSubModules(SubModule module) + { + yield return module; + foreach (var subModule in module.SubModules) + foreach (var innerSubModule in GetSubModules(subModule)) + yield return innerSubModule; + } + + return GetSubModules(RootModule); + } } } diff --git a/ZSharp.SourceCompiler.Project/project/SubModule.cs b/ZSharp.SourceCompiler.Project/project/SubModule.cs index 9561231f..9728b5f1 100644 --- a/ZSharp.SourceCompiler.Project/project/SubModule.cs +++ b/ZSharp.SourceCompiler.Project/project/SubModule.cs @@ -2,17 +2,9 @@ namespace ZSharp.SourceCompiler.Project { - public class SubModule( - string name, - Directory rootDirectory, - Directory? sourceDirectory = null - ) + public class SubModule(Directory directory) { - public string Name { get; } = name; - - public Directory RootDirectory { get; } = rootDirectory; - - public Directory SourceDirectory { get; } = sourceDirectory ?? rootDirectory; + public Directory Directory { get; } = directory; public List SourceFiles { get; } = []; From 6a191938c8553136e156742aab4754b4fd50f8c1 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 1 Aug 2025 00:13:28 +0300 Subject: [PATCH 200/235] Add ZSC.Project --- ZSC.Project/Program.cs | 152 +++++++++++++++++++++ ZSC.Project/Properties/launchSettings.json | 11 ++ ZSC.Project/ZSC.Project.csproj | 19 +++ ZSharp v1.sln | 6 + 4 files changed, 188 insertions(+) create mode 100644 ZSC.Project/Program.cs create mode 100644 ZSC.Project/Properties/launchSettings.json create mode 100644 ZSC.Project/ZSC.Project.csproj diff --git a/ZSC.Project/Program.cs b/ZSC.Project/Program.cs new file mode 100644 index 00000000..7bcd4f39 --- /dev/null +++ b/ZSC.Project/Program.cs @@ -0,0 +1,152 @@ +using System.Text; +using ZSharp.Compiler; +using ZSharp.Interpreter; +using ZSharp.Parser; +using ZSharp.SourceCompiler.Project; +using ZSharp.Text; +using ZSharp.Tokenizer; + + +#if false +#region Parsing + +ZSharp.AST.Document documentNode; +using (StreamReader stream = File.OpenText(filePath)) +{ + var zsharpParser = new ZSharpParser(); + var parser = new Parser(Tokenizer.Tokenize(new(stream))); + + var expressionParser = zsharpParser.Expression; + var statementParser = zsharpParser.Statement; + + expressionParser.Terminal( + TokenType.String, + token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.String) + ); + expressionParser.Terminal( + TokenType.Number, + token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Number) + ); + expressionParser.Terminal( + TokenType.Decimal, + token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Decimal) + ); + expressionParser.Terminal( + TokenType.Identifier, + token => token.Value switch + { + "null" => ZSharp.AST.LiteralExpression.Null(), + "true" => ZSharp.AST.LiteralExpression.True(), + "false" => ZSharp.AST.LiteralExpression.False(), + _ => new ZSharp.AST.IdentifierExpression(token.Value), + } + ); + expressionParser.Nud( + TokenType.LParen, + parser => + { + parser.Eat(TokenType.LParen); + var expression = parser.Parse(); + parser.Eat(TokenType.RParen); + + return expression; + }, + 10000 + ); + expressionParser.Nud( + LangParser.Keywords.Let, + LangParser.ParseLetExpression + ); + expressionParser.Nud( + LangParser.Keywords.Class, + zsharpParser.Class.Parse + ); + + expressionParser.InfixR("=", 10); + expressionParser.InfixL("<", 20); + expressionParser.InfixL("+", 50); + expressionParser.InfixL("-", 50); + expressionParser.InfixL("*", 70); + expressionParser.InfixL("/", 70); + expressionParser.InfixL("**", 80); + + expressionParser.InfixL("==", 30); + expressionParser.InfixL("!=", 30); + + expressionParser.InfixL(LangParser.Keywords.Or, 15); + + expressionParser.Led(TokenType.LParen, LangParser.ParseCallExpression, 100); + expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); + expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); + expressionParser.Led(".", LangParser.ParseMemberAccess, 150); + expressionParser.Led(LangParser.Keywords.As, LangParser.ParseCastExpression, 20); + expressionParser.Led(LangParser.Keywords.Is, LangParser.ParseIsOfExpression, 20); + + expressionParser.Separator(TokenType.Comma); + expressionParser.Separator(TokenType.RParen); + expressionParser.Separator(TokenType.RBracket); + expressionParser.Separator(TokenType.Semicolon); + + expressionParser.Separator(LangParser.Keywords.In); // until it's an operator + + expressionParser.AddKeywordParser( + LangParser.Keywords.While, + LangParser.ParseWhileExpression + ); + + statementParser.AddKeywordParser( + LangParser.Keywords.While, + Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) + ); + + statementParser.AddKeywordParser( + LangParser.Keywords.If, + LangParser.ParseIfStatement + ); + + statementParser.AddKeywordParser( + LangParser.Keywords.For, + LangParser.ParseForStatement + ); + + statementParser.AddKeywordParser( + LangParser.Keywords.Case, + LangParser.ParseCaseStatement + ); + + //zsharpParser.Function.AddKeywordParser( + // LangParser.Keywords.While, + // Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) + //); + + zsharpParser.RegisterParsers(parser); + documentNode = zsharpParser.Parse(parser); + + Console.WriteLine($"Finished parsing document with {documentNode.Statements.Count} statements!"); +} + +#endregion +#endif + +#region Compilation + +var interpreter = new Interpreter(); + + +new Referencing(interpreter.Compiler); +new OOP(interpreter.Compiler); + +var projectRoot = args.Length == 0 + ? Standard.FileSystem.Directory.CurrentWorkingDirectory() + : Standard.FileSystem.Directory.From(args[0]) ?? throw new ArgumentException($"Path {args[0]} does not point to a valid directory") + ; +var project = new Project(projectRoot.Name, projectRoot, projectRoot / "src" as Standard.FileSystem.Directory); +ProjectDiscovery.Discover(project); + +#endregion + +Console.WriteLine(); + +Console.WriteLine(); +Console.WriteLine("Press any key to exit..."); +Console.ReadKey(); diff --git a/ZSC.Project/Properties/launchSettings.json b/ZSC.Project/Properties/launchSettings.json new file mode 100644 index 00000000..8d9b9a40 --- /dev/null +++ b/ZSC.Project/Properties/launchSettings.json @@ -0,0 +1,11 @@ +{ + "profiles": { + "ZSC.Project": { + "commandName": "Project" + }, + "SafeSQL": { + "commandName": "Project", + "commandLineArgs": "D:/zsharp/zsv1-design/packages/safe-sql" + } + } +} \ No newline at end of file diff --git a/ZSC.Project/ZSC.Project.csproj b/ZSC.Project/ZSC.Project.csproj new file mode 100644 index 00000000..57e19e11 --- /dev/null +++ b/ZSC.Project/ZSC.Project.csproj @@ -0,0 +1,19 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + + + + diff --git a/ZSharp v1.sln b/ZSharp v1.sln index 3ed5dc17..8470cf72 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -60,6 +60,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.SourceCompiler.Proje EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.ILLoader.Attributes", "ZSharp.Compiler.ILLoader.Attributes\ZSharp.Compiler.ILLoader.Attributes.csproj", "{42BF3911-0DC7-4831-A989-98D48C17CC74}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSC.Project", "ZSC.Project\ZSC.Project.csproj", "{A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -174,6 +176,10 @@ Global {42BF3911-0DC7-4831-A989-98D48C17CC74}.Debug|Any CPU.Build.0 = Debug|Any CPU {42BF3911-0DC7-4831-A989-98D48C17CC74}.Release|Any CPU.ActiveCfg = Release|Any CPU {42BF3911-0DC7-4831-A989-98D48C17CC74}.Release|Any CPU.Build.0 = Release|Any CPU + {A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From cf70f017cfe4f55ab290aa190bdaa3aa821da20c Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 11 Aug 2025 13:33:41 +0300 Subject: [PATCH 201/235] Make SubModuleDiscovery class static --- .../discovery/ProjectDiscovery.cs | 2 +- .../discovery/SubModuleDiscovery.cs | 10 ++++------ 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs b/ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs index a29f9fe2..c953a160 100644 --- a/ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs +++ b/ZSharp.SourceCompiler.Project/discovery/ProjectDiscovery.cs @@ -4,7 +4,7 @@ public static class ProjectDiscovery { public static void Discover(Project project) { - new SubModuleDiscovery(project.RootModule).Discover(); + SubModuleDiscovery.Discover(project.RootModule); } } } diff --git a/ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs b/ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs index 0c697b89..c8ca23ea 100644 --- a/ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs +++ b/ZSharp.SourceCompiler.Project/discovery/SubModuleDiscovery.cs @@ -2,18 +2,16 @@ namespace ZSharp.SourceCompiler.Project { - public class SubModuleDiscovery(SubModule subModule) + public static class SubModuleDiscovery { public const string SubModuleFileName = ".zs"; - public SubModule SubModule { get; } = subModule; - - public void Discover() + public static void Discover(SubModule subModule) { - Discover(SubModule.Directory, SubModule); + Discover(subModule.Directory, subModule); } - private void Discover(Directory directory, SubModule subModule) + private static void Discover(Directory directory, SubModule subModule) { foreach (var item in directory) if (item is Directory subDirectory) From 24cf08848269ae2e058a96341c4277b48a686ee0 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 11 Aug 2025 14:24:50 +0300 Subject: [PATCH 202/235] Rename IRObject to IRDefinition --- ZSharp.Compiler.Features/ir/IR.Compile.cs | 12 ++--- .../compile/services/Compiler.Definition.cs | 4 +- ZSharp.Compiler.IRLoader/Context.cs | 2 +- .../oop/method/concrete/Method.cs | 2 +- .../oop/method/generic/GenericMethod.cs | 2 +- ZSharp.Compiler/cg objects/raw/RawType.cs | 2 +- .../cg objects/types/array/ArrayTypeObject.cs | 2 +- .../types/pointer/PointerTypeObject.cs | 2 +- .../types/reference/ReferenceTypeObject.cs | 2 +- .../compiler core/compiler/Compiler.IR.cs | 10 ++-- .../features/ir/services/IR.Definition.cs | 8 +-- .../protocols/ICompileIRObject.cs | 52 +++++++++---------- .../core/{IRObject.cs => IRDefinition.cs} | 2 +- ZSharp.IR/ir/modular/module/ModuleMember.cs | 2 +- ZSharp.IR/ir/oop/constructor/Constructor.cs | 2 +- ZSharp.IR/ir/oop/field/Field.cs | 2 +- ZSharp.IR/ir/oop/method/Method.cs | 2 +- ZSharp.IR/ir/signature/Parameter.cs | 2 +- ZSharp.IR/ir/signature/Signature.cs | 6 +-- ZSharp.IR/vm/code/local/Local.cs | 4 +- ZSharp.IR/vm/code/local/LocalCollection.cs | 4 +- ZSharp.IR/vm/instructions/misc/GetObject.cs | 8 +-- 22 files changed, 67 insertions(+), 67 deletions(-) rename ZSharp.IR/core/{IRObject.cs => IRDefinition.cs} (69%) diff --git a/ZSharp.Compiler.Features/ir/IR.Compile.cs b/ZSharp.Compiler.Features/ir/IR.Compile.cs index b867f427..2e9f9435 100644 --- a/ZSharp.Compiler.Features/ir/IR.Compile.cs +++ b/ZSharp.Compiler.Features/ir/IR.Compile.cs @@ -9,19 +9,19 @@ public Result CompileIRCode(CompilerObject @object) Compiler.CompileIRCode(@object) ); - public Result CompileIRObject(CompilerObject @object) - => Result.Ok( + public Result CompileIRObject(CompilerObject @object) + => Result.Ok( Compiler.CompileIRObject(@object) ); - public Result CompileIRObject(CompilerObject @object, Owner? owner) - where Owner : ZSharp.IR.IRObject - => Result.Ok( + public Result CompileIRObject(CompilerObject @object, Owner? owner) + where Owner : ZSharp.IR.IRDefinition + => Result.Ok( Compiler.CompileIRObject(@object, owner) ); public Result CompileIRObject(CompilerObject @object, Owner? owner) - where T : ZSharp.IR.IRObject + where T : ZSharp.IR.IRDefinition where Owner : class => Result.Ok( Compiler.CompileIRObject(@object, owner) diff --git a/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs index 9802e19c..45d300d5 100644 --- a/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs +++ b/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs @@ -3,13 +3,13 @@ partial class Compiler { public ZSharp.Compiler.Result CompileDefinition(CompilerObject @object, TargetPlatform? target) - where T : IR.IRObject + where T : IR.IRDefinition { throw new NotImplementedException(); } public void CompileDefinition(CompilerObject @object, Owner owner, TargetPlatform? target) - where Owner : IR.IRObject + where Owner : IR.IRDefinition { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.IRLoader/Context.cs b/ZSharp.Compiler.IRLoader/Context.cs index b5fc5a89..262c89fd 100644 --- a/ZSharp.Compiler.IRLoader/Context.cs +++ b/ZSharp.Compiler.IRLoader/Context.cs @@ -4,7 +4,7 @@ namespace ZSharp.Compiler.IRLoader { public sealed class Context { - public Cache Objects { get; } = []; + public Cache Objects { get; } = []; public Cache Types { get; } = []; } diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs index 446e0b5b..213f3d29 100644 --- a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs +++ b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs @@ -153,7 +153,7 @@ MethodReference IReferencable.CreateReference(Referencing @ref, return IR; } - IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) + IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs index e5340037..cec25be0 100644 --- a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs +++ b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs @@ -63,7 +63,7 @@ public IType? ReturnType public IR.Method? IR { get; set; } - IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) + IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) => CompileIR(compiler); IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) diff --git a/ZSharp.Compiler/cg objects/raw/RawType.cs b/ZSharp.Compiler/cg objects/raw/RawType.cs index 0effb7ea..5de064a8 100644 --- a/ZSharp.Compiler/cg objects/raw/RawType.cs +++ b/ZSharp.Compiler/cg objects/raw/RawType.cs @@ -16,7 +16,7 @@ public IRType CompileIRType(Compiler.Compiler compiler) => type; public IRCode Read(Compiler.Compiler compiler) - => type is IR.IRObject ir ? new([ + => type is IR.IRDefinition ir ? new([ new IR.VM.GetObject(ir) ]) { diff --git a/ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs b/ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs index 75597247..a756d12b 100644 --- a/ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs +++ b/ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs @@ -35,7 +35,7 @@ CompilerObjectResult IGenericInstantiable.Instantiate(Compiler.Compiler compiler public ArrayType Instantiate(IType elementType) => new(elementType); - IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) + IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) => IR; } } diff --git a/ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs b/ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs index 101ca44b..2b18c960 100644 --- a/ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs +++ b/ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs @@ -35,7 +35,7 @@ CompilerObjectResult IGenericInstantiable.Instantiate(Compiler.Compiler compiler public PointerType Instantiate(IType elementType) => new(elementType); - IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) + IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) => IR; } } diff --git a/ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs b/ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs index ca7cddb9..f86629e7 100644 --- a/ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs +++ b/ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs @@ -35,7 +35,7 @@ CompilerObjectResult IGenericInstantiable.Instantiate(Compiler.Compiler compiler public ReferenceType Instantiate(IType elementType) => new(elementType); - IR.IRObject ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) + IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) => IR; } } diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs index c88bd876..52f76f0d 100644 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs +++ b/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs @@ -15,16 +15,16 @@ public IRCode CompileIRCode(CompilerObject @object) throw new NotImplementedException(); // TODO: return null } - public ZSharp.IR.IRObject CompileIRObject(CompilerObject @object) + public ZSharp.IR.IRDefinition CompileIRObject(CompilerObject @object) { if (@object is ICompileIRObject irObject) return irObject.CompileIRObject(this); - return CompileIRObject(@object, null); + return CompileIRObject(@object, null); } - public ZSharp.IR.IRObject CompileIRObject(CompilerObject @object, Owner? owner) - where Owner : ZSharp.IR.IRObject + public ZSharp.IR.IRDefinition CompileIRObject(CompilerObject @object, Owner? owner) + where Owner : ZSharp.IR.IRDefinition { if (@object is ICompileIRObject irObject) return irObject.CompileIRObject(this, owner); @@ -33,7 +33,7 @@ public ZSharp.IR.IRObject CompileIRObject(CompilerObject @object, Owner? } public T CompileIRObject(CompilerObject @object, Owner? owner) - where T : ZSharp.IR.IRObject + where T : ZSharp.IR.IRDefinition where Owner : class { if (@object is ICompileIRObject irObject) diff --git a/ZSharp.Compiler/features/ir/services/IR.Definition.cs b/ZSharp.Compiler/features/ir/services/IR.Definition.cs index 68b63b93..d617eacf 100644 --- a/ZSharp.Compiler/features/ir/services/IR.Definition.cs +++ b/ZSharp.Compiler/features/ir/services/IR.Definition.cs @@ -6,7 +6,7 @@ public partial struct IR { public IRDefinitionResult CompileDefinition(CompilerObject @object) { - ZSharp.IR.IRObject? result = null; + ZSharp.IR.IRDefinition? result = null; if (@object is ICompileIRObject irObject) result = irObject.CompileIRObject(compiler); @@ -19,9 +19,9 @@ public IRDefinitionResult CompileDefinition(CompilerObject @object) } public IRDefinitionResult CompileDefinition(CompilerObject @object, Owner? owner) - where Owner : ZSharp.IR.IRObject + where Owner : ZSharp.IR.IRDefinition { - ZSharp.IR.IRObject? result = null; + ZSharp.IR.IRDefinition? result = null; if (@object is ICompileIRObject irObject) result = irObject.CompileIRObject(compiler, owner); @@ -34,7 +34,7 @@ public IRDefinitionResult CompileDefinition(CompilerObject @object, Owner } public Result CompileDefinition(CompilerObject @object, Owner? owner) - where T : ZSharp.IR.IRObject + where T : ZSharp.IR.IRDefinition where Owner : class { T? result = null; diff --git a/ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs b/ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs index c76aa277..8c734533 100644 --- a/ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs +++ b/ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs @@ -1,26 +1,26 @@ -namespace ZSharp.Compiler -{ - public interface ICompileIRObject - { - public ZSharp.IR.IRObject CompileIRObject(Compiler compiler); - } - - public interface ICompileIRObject : ICompileIRObject - where Owner : class - { - public ZSharp.IR.IRObject CompileIRObject(Compiler compiler, Owner? owner); - - ZSharp.IR.IRObject ICompileIRObject.CompileIRObject(Compiler compiler) - => CompileIRObject(compiler, null); - } - - public interface ICompileIRObject : ICompileIRObject - where T : ZSharp.IR.IRObject - where Owner : class - { - public new T CompileIRObject(Compiler compiler, Owner? owner); - - ZSharp.IR.IRObject ICompileIRObject.CompileIRObject(Compiler compiler, Owner? owner) - => CompileIRObject(compiler, owner); - } -} +namespace ZSharp.Compiler +{ + public interface ICompileIRObject + { + public ZSharp.IR.IRDefinition CompileIRObject(Compiler compiler); + } + + public interface ICompileIRObject : ICompileIRObject + where Owner : class + { + public ZSharp.IR.IRDefinition CompileIRObject(Compiler compiler, Owner? owner); + + ZSharp.IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler compiler) + => CompileIRObject(compiler, null); + } + + public interface ICompileIRObject : ICompileIRObject + where T : ZSharp.IR.IRDefinition + where Owner : class + { + public new T CompileIRObject(Compiler compiler, Owner? owner); + + ZSharp.IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler compiler, Owner? owner) + => CompileIRObject(compiler, owner); + } +} diff --git a/ZSharp.IR/core/IRObject.cs b/ZSharp.IR/core/IRDefinition.cs similarity index 69% rename from ZSharp.IR/core/IRObject.cs rename to ZSharp.IR/core/IRDefinition.cs index d4310c1d..aab9e97b 100644 --- a/ZSharp.IR/core/IRObject.cs +++ b/ZSharp.IR/core/IRDefinition.cs @@ -1,6 +1,6 @@ namespace ZSharp.IR { - public abstract class IRObject + public abstract class IRDefinition { public abstract Module? Module { get; } } diff --git a/ZSharp.IR/ir/modular/module/ModuleMember.cs b/ZSharp.IR/ir/modular/module/ModuleMember.cs index 2b5f4f2c..fb08d4d3 100644 --- a/ZSharp.IR/ir/modular/module/ModuleMember.cs +++ b/ZSharp.IR/ir/modular/module/ModuleMember.cs @@ -1,6 +1,6 @@ namespace ZSharp.IR { - public abstract class ModuleMember : IRObject + public abstract class ModuleMember : IRDefinition { private Module? _module; diff --git a/ZSharp.IR/ir/oop/constructor/Constructor.cs b/ZSharp.IR/ir/oop/constructor/Constructor.cs index fd941b3c..9286db01 100644 --- a/ZSharp.IR/ir/oop/constructor/Constructor.cs +++ b/ZSharp.IR/ir/oop/constructor/Constructor.cs @@ -1,7 +1,7 @@ namespace ZSharp.IR { public sealed class Constructor(string? name) - : IRObject + : IRDefinition { public override Module? Module => Method.Module; diff --git a/ZSharp.IR/ir/oop/field/Field.cs b/ZSharp.IR/ir/oop/field/Field.cs index fa319365..3bf9075a 100644 --- a/ZSharp.IR/ir/oop/field/Field.cs +++ b/ZSharp.IR/ir/oop/field/Field.cs @@ -1,6 +1,6 @@ namespace ZSharp.IR { - public sealed class Field(string name, IType type) : IRObject + public sealed class Field(string name, IType type) : IRDefinition { internal FieldAttributes _attributes = FieldAttributes.None; diff --git a/ZSharp.IR/ir/oop/method/Method.cs b/ZSharp.IR/ir/oop/method/Method.cs index 3d1d6332..a60acced 100644 --- a/ZSharp.IR/ir/oop/method/Method.cs +++ b/ZSharp.IR/ir/oop/method/Method.cs @@ -3,7 +3,7 @@ namespace ZSharp.IR { public sealed class Method - : IRObject + : IRDefinition , ICallable { public Function UnderlyingFunction { get; set; } diff --git a/ZSharp.IR/ir/signature/Parameter.cs b/ZSharp.IR/ir/signature/Parameter.cs index d1c6f5e8..84155a9f 100644 --- a/ZSharp.IR/ir/signature/Parameter.cs +++ b/ZSharp.IR/ir/signature/Parameter.cs @@ -2,7 +2,7 @@ namespace ZSharp.IR { - public class Parameter(string name, IType type) : IRObject + public class Parameter(string name, IType type) : IRDefinition { private Signature? _signature; diff --git a/ZSharp.IR/ir/signature/Signature.cs b/ZSharp.IR/ir/signature/Signature.cs index 32e31a93..babb4bff 100644 --- a/ZSharp.IR/ir/signature/Signature.cs +++ b/ZSharp.IR/ir/signature/Signature.cs @@ -1,8 +1,8 @@ namespace ZSharp.IR { - public sealed class Signature(IType returnType) : IRObject + public sealed class Signature(IType returnType) : IRDefinition { - private IRObject? _owner; + private IRDefinition? _owner; private Args? _args; private KwArgs? _kwArgs; @@ -53,7 +53,7 @@ public KwArgs KwArgs public IType ReturnType { get; set; } = returnType; - public IRObject? Owner + public IRDefinition? Owner { get => _owner; set => _owner = value; diff --git a/ZSharp.IR/vm/code/local/Local.cs b/ZSharp.IR/vm/code/local/Local.cs index 4b7b4036..65b95578 100644 --- a/ZSharp.IR/vm/code/local/Local.cs +++ b/ZSharp.IR/vm/code/local/Local.cs @@ -1,10 +1,10 @@ namespace ZSharp.IR.VM { - public sealed class Local(string name, IType type) : IRObject + public sealed class Local(string name, IType type) : IRDefinition { public override Module? Module => Owner?.Module; - public IRObject? Owner { get; internal set; } + public IRDefinition? Owner { get; internal set; } public LocalAttributes Attributes { get; set; } diff --git a/ZSharp.IR/vm/code/local/LocalCollection.cs b/ZSharp.IR/vm/code/local/LocalCollection.cs index 29df4169..92d821dd 100644 --- a/ZSharp.IR/vm/code/local/LocalCollection.cs +++ b/ZSharp.IR/vm/code/local/LocalCollection.cs @@ -2,9 +2,9 @@ namespace ZSharp.IR.VM { - internal sealed class LocalCollection(IRObject owner) : Collection + internal sealed class LocalCollection(IRDefinition owner) : Collection { - private readonly IRObject owner = owner; + private readonly IRDefinition owner = owner; public override void OnAdd(Local item) { diff --git a/ZSharp.IR/vm/instructions/misc/GetObject.cs b/ZSharp.IR/vm/instructions/misc/GetObject.cs index e7a4137b..67bde8e6 100644 --- a/ZSharp.IR/vm/instructions/misc/GetObject.cs +++ b/ZSharp.IR/vm/instructions/misc/GetObject.cs @@ -1,11 +1,11 @@ namespace ZSharp.IR.VM { - public sealed class GetObject(IRObject ir) + public sealed class GetObject(IRDefinition ir) : Instruction - , IHasOperand + , IHasOperand { - public IRObject IR { get; set; } = ir; + public IRDefinition IR { get; set; } = ir; - IRObject IHasOperand.Operand => IR; + IRDefinition IHasOperand.Operand => IR; } } From bf1b0e9ad95cfbee1ee425b92a5b440d28715da0 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 12 Aug 2025 11:34:05 +0300 Subject: [PATCH 203/235] Make `Module` inherit `IRDefinition` --- ZSharp.IR/core/IModuleMember.cs | 7 +++++++ ZSharp.IR/core/IRDefinition.cs | 2 +- ZSharp.IR/ir/modular/module/Module.cs | 6 +++--- .../ir/modular/module/ModuleCollection.cs | 8 +++---- ZSharp.IR/ir/modular/module/ModuleMember.cs | 21 ++++--------------- ZSharp.IR/ir/oop/constructor/Constructor.cs | 5 +++-- ZSharp.IR/ir/oop/enum/EnumValueCollection.cs | 4 ++-- ZSharp.IR/ir/oop/field/Field.cs | 6 ++++-- ZSharp.IR/ir/oop/method/Method.cs | 3 ++- ZSharp.IR/ir/signature/Parameter.cs | 6 ++++-- ZSharp.IR/ir/signature/Signature.cs | 10 +++++---- ZSharp.IR/vm/code/local/Local.cs | 8 ++++--- ZSharp.IR/vm/code/local/LocalCollection.cs | 4 ++-- 13 files changed, 47 insertions(+), 43 deletions(-) create mode 100644 ZSharp.IR/core/IModuleMember.cs diff --git a/ZSharp.IR/core/IModuleMember.cs b/ZSharp.IR/core/IModuleMember.cs new file mode 100644 index 00000000..e84b1bea --- /dev/null +++ b/ZSharp.IR/core/IModuleMember.cs @@ -0,0 +1,7 @@ +namespace ZSharp.IR +{ + public interface IModuleMember + { + public Module? Module { get; } + } +} diff --git a/ZSharp.IR/core/IRDefinition.cs b/ZSharp.IR/core/IRDefinition.cs index aab9e97b..4c51f85f 100644 --- a/ZSharp.IR/core/IRDefinition.cs +++ b/ZSharp.IR/core/IRDefinition.cs @@ -2,6 +2,6 @@ { public abstract class IRDefinition { - public abstract Module? Module { get; } + } } diff --git a/ZSharp.IR/ir/modular/module/Module.cs b/ZSharp.IR/ir/modular/module/Module.cs index 81e21b5f..61364ecf 100644 --- a/ZSharp.IR/ir/modular/module/Module.cs +++ b/ZSharp.IR/ir/modular/module/Module.cs @@ -3,7 +3,7 @@ namespace ZSharp.IR { - public sealed class Module(string? name) : ModuleMember + public sealed class Module(string? name) : IRDefinition { private Function? _initializer; private Function? _entryPoint; @@ -23,9 +23,9 @@ public Function? Initializer { if (value is not null) { - if (value.Owner is null) + if (value.Module is null) Functions.Add(value); - else if (value.Owner != this) + else if (value.Module != this) throw new InvalidOperationException("Module initializer cannot reside in a different module."); _initializer = value; } diff --git a/ZSharp.IR/ir/modular/module/ModuleCollection.cs b/ZSharp.IR/ir/modular/module/ModuleCollection.cs index 1114346d..efe26b63 100644 --- a/ZSharp.IR/ir/modular/module/ModuleCollection.cs +++ b/ZSharp.IR/ir/modular/module/ModuleCollection.cs @@ -11,24 +11,24 @@ public override void OnAdd(T item) { AssertUnOwned(item); - item.Owner = Module; + item.Module = Module; } public override void OnInsert(int index, T item) { AssertUnOwned(item); - item.Owner = Module; + item.Module = Module; } public override void OnRemove(T item) { - item.Owner = null; + item.Module = null; } public override void OnRemoveAt(int index) { - this[index].Owner = null; + this[index].Module = null; } private void AssertUnOwned(T item) diff --git a/ZSharp.IR/ir/modular/module/ModuleMember.cs b/ZSharp.IR/ir/modular/module/ModuleMember.cs index fb08d4d3..af376a20 100644 --- a/ZSharp.IR/ir/modular/module/ModuleMember.cs +++ b/ZSharp.IR/ir/modular/module/ModuleMember.cs @@ -1,22 +1,9 @@ namespace ZSharp.IR { - public abstract class ModuleMember : IRDefinition + public abstract class ModuleMember + : IRDefinition + , IModuleMember { - private Module? _module; - - public override Module? Module => _module; - - public Module? Owner - { - get => _module; - internal set => _module = value; - } - - public ModuleMember() { } - - public ModuleMember(Module module) - { - _module = module; - } + public Module? Module { get; internal set; } } } diff --git a/ZSharp.IR/ir/oop/constructor/Constructor.cs b/ZSharp.IR/ir/oop/constructor/Constructor.cs index 9286db01..93b9faa2 100644 --- a/ZSharp.IR/ir/oop/constructor/Constructor.cs +++ b/ZSharp.IR/ir/oop/constructor/Constructor.cs @@ -2,11 +2,12 @@ { public sealed class Constructor(string? name) : IRDefinition + , IModuleMember { - public override Module? Module => Method.Module; + public Module? Module => Method.Module; public string? Name { get; set; } = name; - public Method Method { get; set; } + public Method Method { get; set; } } } diff --git a/ZSharp.IR/ir/oop/enum/EnumValueCollection.cs b/ZSharp.IR/ir/oop/enum/EnumValueCollection.cs index a077748b..02c556e8 100644 --- a/ZSharp.IR/ir/oop/enum/EnumValueCollection.cs +++ b/ZSharp.IR/ir/oop/enum/EnumValueCollection.cs @@ -42,13 +42,13 @@ private void UnsetOwner(EnumValue item) private void AssertUnonwed(EnumValue item) { - if (item.Owner is not null) + if (item.Module is not null) throw new InvalidOperationException(); } private void AssertOwned(EnumValue item) { - if (item.Owner is null) + if (item.Module is null) throw new InvalidOperationException(); } } diff --git a/ZSharp.IR/ir/oop/field/Field.cs b/ZSharp.IR/ir/oop/field/Field.cs index 3bf9075a..83bde576 100644 --- a/ZSharp.IR/ir/oop/field/Field.cs +++ b/ZSharp.IR/ir/oop/field/Field.cs @@ -1,6 +1,8 @@ namespace ZSharp.IR { - public sealed class Field(string name, IType type) : IRDefinition + public sealed class Field(string name, IType type) + : IRDefinition + , IModuleMember { internal FieldAttributes _attributes = FieldAttributes.None; @@ -70,7 +72,7 @@ public bool IsReadOnly public Class? Owner { get; internal set; } - public override Module? Module => Owner?.Module; + public Module? Module => Owner?.Module; public IType Type { get; set; } = type; diff --git a/ZSharp.IR/ir/oop/method/Method.cs b/ZSharp.IR/ir/oop/method/Method.cs index a60acced..246c1a5c 100644 --- a/ZSharp.IR/ir/oop/method/Method.cs +++ b/ZSharp.IR/ir/oop/method/Method.cs @@ -5,6 +5,7 @@ namespace ZSharp.IR public sealed class Method : IRDefinition , ICallable + , IModuleMember { public Function UnderlyingFunction { get; set; } @@ -39,7 +40,7 @@ public Signature Signature public OOPType? Owner { get; set; } - public override Module? Module => Owner?.Module; + public Module? Module => Owner?.Module; public bool IsClass { diff --git a/ZSharp.IR/ir/signature/Parameter.cs b/ZSharp.IR/ir/signature/Parameter.cs index 84155a9f..d078aa99 100644 --- a/ZSharp.IR/ir/signature/Parameter.cs +++ b/ZSharp.IR/ir/signature/Parameter.cs @@ -2,11 +2,13 @@ namespace ZSharp.IR { - public class Parameter(string name, IType type) : IRDefinition + public class Parameter(string name, IType type) + : IRDefinition + , IModuleMember { private Signature? _signature; - public override Module? Module => _signature?.Module; + public Module? Module => _signature?.Module; public string Name { get; } = name; diff --git a/ZSharp.IR/ir/signature/Signature.cs b/ZSharp.IR/ir/signature/Signature.cs index babb4bff..35b4dc17 100644 --- a/ZSharp.IR/ir/signature/Signature.cs +++ b/ZSharp.IR/ir/signature/Signature.cs @@ -1,13 +1,15 @@ namespace ZSharp.IR { - public sealed class Signature(IType returnType) : IRDefinition + public sealed class Signature(IType returnType) + : IRDefinition + , IModuleMember { - private IRDefinition? _owner; + private Function? _owner; private Args? _args; private KwArgs? _kwArgs; - public override Module? Module => _owner?.Module; + public Module? Module => _owner?.Module; public Args Args { @@ -53,7 +55,7 @@ public KwArgs KwArgs public IType ReturnType { get; set; } = returnType; - public IRDefinition? Owner + public Function? Owner { get => _owner; set => _owner = value; diff --git a/ZSharp.IR/vm/code/local/Local.cs b/ZSharp.IR/vm/code/local/Local.cs index 65b95578..facf54e5 100644 --- a/ZSharp.IR/vm/code/local/Local.cs +++ b/ZSharp.IR/vm/code/local/Local.cs @@ -1,10 +1,12 @@ namespace ZSharp.IR.VM { - public sealed class Local(string name, IType type) : IRDefinition + public sealed class Local(string name, IType type) + : IRDefinition + , IModuleMember { - public override Module? Module => Owner?.Module; + public Module? Module => Owner?.Module; - public IRDefinition? Owner { get; internal set; } + public Function? Owner { get; internal set; } public LocalAttributes Attributes { get; set; } diff --git a/ZSharp.IR/vm/code/local/LocalCollection.cs b/ZSharp.IR/vm/code/local/LocalCollection.cs index 92d821dd..ab31236c 100644 --- a/ZSharp.IR/vm/code/local/LocalCollection.cs +++ b/ZSharp.IR/vm/code/local/LocalCollection.cs @@ -2,9 +2,9 @@ namespace ZSharp.IR.VM { - internal sealed class LocalCollection(IRDefinition owner) : Collection + internal sealed class LocalCollection(Function owner) : Collection { - private readonly IRDefinition owner = owner; + private readonly Function owner = owner; public override void OnAdd(Local item) { From 9c88aa04af305d05be99e9664b4b4c703401e022 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Tue, 12 Aug 2025 11:41:40 +0300 Subject: [PATCH 204/235] Rename variable --- ZSharp.Compiler.Objects/oop/constructor/Constructor.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs index 7d403c5e..6b73906f 100644 --- a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs +++ b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs @@ -46,7 +46,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) IR.VM.Instruction invocationInstruction; - bool hasReturn = false; + bool isNewInstance = false; if (kwArgs.TryGetValue(Signature.Args[0].Name, out var thisArgument)) { invocationInstruction = new IR.VM.Call(IR!.Method); @@ -57,7 +57,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) { var type = Owner ?? Signature.Args[0].Type; - hasReturn = true; + isNewInstance = true; invocationInstruction = new IR.VM.CreateInstance(new IR.ConstructorReference(IR!) { @@ -107,7 +107,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) result.Instructions.Add(invocationInstruction); result.Types.Clear(); - if (hasReturn) + if (isNewInstance) result.Types.Add(Owner ?? Signature.Args[0].Type); result.MaxStackSize = Math.Max(result.MaxStackSize, result.Types.Count); From 0bdaaea015c12669ffd34853d5c5649168881291 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 11 Sep 2025 23:06:25 +0300 Subject: [PATCH 205/235] Change many many many things --- {ZSharp.Compiler/core => CommonZ}/Result.cs | 10 +- Examples/test.zs | 22 ++ Testing/Program.cs | 45 +++- ZSC.Script/CLIArgumentLogOrigin.cs | 10 + ZSC.Script/Program.cs | 219 ++++++++++++++++++ ZSC.Script/ZSC.Script.csproj | 44 ++++ ZSC.Script/ZSCScriptLogOrigin.cs | 12 + ZSharp v1.sln | 90 +++++++ .../nodes/stmt/expr/DefinitionStatement.cs | 10 + ZSharp.AST/nodes/stmt/import/ImportTokens.cs | 3 + .../items/directory/Directory.Operators.cs | 4 +- ...{Operators.cs => ModuleScope.Operators.cs} | 3 +- .../module scope/ModuleScope.cs | 7 + ZSharp.CT.StandardLibrary.IO/GlobalUsings.cs | 1 + .../ModuleAttributes.cs | 1 + .../ZSharp.CT.StandardLibrary.IO.csproj | 13 ++ .../module scope/ModuleScope.Functions.cs | 9 + .../module scope/ModuleScope.Operators.cs | 7 + .../module scope/ModuleScope.cs | 7 + ZSharp.Compiler.CO.CT/GlobalUsings.cs | 4 + .../ZSharp.Compiler.CO.CT.csproj | 15 ++ .../dispatcher/Dispatcher.cs | 28 +++ .../dispatcher/services/Dispatcher.Call.cs | 15 ++ .../dispatcher/services/Dispatcher.Cast.cs | 15 ++ .../services/Dispatcher.ImplicitCast.cs | 18 ++ .../dispatcher/services/Dispatcher.Index.cs | 25 ++ .../dispatcher/services/Dispatcher.Match.cs | 15 ++ .../services/Dispatcher.MemberAccess.cs | 45 ++++ .../services/Dispatcher.ValueAccess.cs | 25 ++ .../protocols/callable/ICTCallable.cs | 7 + .../implicit casting/ICTImplicitCastFrom.cs | 7 + .../implicit casting/ICTImplicitCastTo.cs | 7 + .../protocols/index/ICTGetIndex.cs | 7 + .../protocols/index/ICTSetIndex.cs | 7 + .../protocols}/member access/ICTGetMember.cs | 2 +- .../protocols/member access/ICTSetMember.cs | 7 + .../protocols/type casting/ICTCastTo.cs | 7 + .../protocols/type matching/ICTTypeMatch.cs | 7 + .../protocols/value access/ICTGet.cs | 7 + .../protocols/value access/ICTSet.cs | 7 + ZSharp.Compiler.CO.Proxy/GlobalUsings.cs | 4 + .../ZSharp.Compiler.CO.Proxy.csproj | 15 ++ .../dispatcher/Dispatcher.cs | 30 +++ .../dispatcher/services/Dispatcher.Call.cs | 15 ++ .../dispatcher/services/Dispatcher.Cast.cs | 15 ++ .../services/Dispatcher.ImplicitCast.cs | 15 ++ .../dispatcher/services/Dispatcher.Index.cs | 25 ++ .../dispatcher/services/Dispatcher.Match.cs | 15 ++ .../services/Dispatcher.MemberAccess.cs | 45 ++++ .../services/Dispatcher.ValueAccess.cs | 25 ++ ZSharp.Compiler.CO.Proxy/protocols/IProxy.cs | 7 + ZSharp.Compiler.CO.RT/GlobalUsings.cs | 4 + .../ZSharp.Compiler.CO.RT.csproj | 15 ++ .../dispatcher/Dispatcher.cs | 28 +++ .../dispatcher/services/Dispatcher.Call.cs | 15 ++ .../dispatcher/services/Dispatcher.Cast.cs | 15 ++ .../services/Dispatcher.ImplicitCast.cs | 21 ++ .../dispatcher/services/Dispatcher.Index.cs | 25 ++ .../dispatcher/services/Dispatcher.Match.cs | 15 ++ .../services/Dispatcher.MemberAccess.cs | 45 ++++ .../services/Dispatcher.ValueAccess.cs | 25 ++ .../extensions/CompilerExtensions.cs | 18 ++ .../protocols/callable/IRTCallable.cs | 7 + .../implicit casting/IRTImplicitCastTo.cs | 7 + .../protocols/index/IRTGetIndex.cs | 7 + .../protocols/index/IRTSetIndex.cs | 7 + .../protocols/member access/IRTGetMember.cs | 7 + .../protocols/member access/IRTSetMember.cs | 7 + .../runtime/IHasRuntimeDescriptor.cs | 7 + .../protocols/type casting/IRTCastFrom.cs | 7 + .../protocols/type casting/IRTCastTo.cs | 7 + .../protocols/type matching/IRTTypeMatch.cs | 7 + .../protocols/value access/IRTGet.cs | 7 + .../protocols/value access/IRTSet.cs | 7 + ZSharp.Compiler.CO/GlobalUsings.cs | 4 + ZSharp.Compiler.CO/ZSharp.Compiler.CO.csproj | 16 ++ ZSharp.Compiler.CO/cg/CG.cs | 7 + ZSharp.Compiler.CO/cg/services/CG.Call.cs | 9 + ZSharp.Compiler.CO/cg/services/CG.Cast.cs | 9 + .../cg/services/CG.ImplicitCast.cs | 9 + ZSharp.Compiler.CO/cg/services/CG.Index.cs | 18 ++ ZSharp.Compiler.CO/cg/services/CG.Match.cs | 9 + .../cg/services/CG.MemberAccess.cs | 55 +++++ .../cg/services/CG.ValueAccess.cs | 13 ++ .../core}/Argument.cs | 0 .../core/CastResult.cs | 2 +- .../core/MatchResult.cs | 2 +- .../dispatcher/Dispatcher.Call.cs | 10 + .../dispatcher/Dispatcher.Cast.cs | 10 + .../dispatcher/Dispatcher.ImplicitCast.cs | 10 + .../dispatcher/Dispatcher.Index.cs | 15 ++ .../dispatcher/Dispatcher.Match.cs | 10 + .../dispatcher/Dispatcher.MemberAccess.cs | 25 ++ .../dispatcher/Dispatcher.Runtime.cs | 10 + .../dispatcher/Dispatcher.ValueAccess.cs | 15 ++ ZSharp.Compiler.CO/dispatcher/Dispatcher.cs | 6 + ZSharp.Compiler.Context/GlobalUsings.cs | 4 + .../ZSharp.Compiler.Context.csproj | 14 ++ .../capabilities/object/IObjectContext.cs | 17 ++ .../capabilities/scoping/ILookupContext.cs | 13 ++ .../capabilities/scoping/IScopeContext.cs | 11 + .../capabilities/storage/IStorage.cs | 7 + .../capabilities/storage/IStorageContext.cs | 12 + .../storage/IStorageDescriptor.cs | 6 + .../capabilities/storage/StorageOptions.cs | 13 ++ .../type inference/ITypeInferenceContext.cs | 12 + .../type inference/TypeInferrer.cs | 8 + .../core}/IContext.cs | 18 +- .../core}/IContextChainStrategy.cs | 0 .../strategies/ParentContextStrategy.cs | 0 ZSharp.Compiler.Core/CompilerObject.cs | 11 + .../ZSharp.Compiler.Core.csproj | 13 ++ ZSharp.Compiler.Core/result/Error.cs | 6 + ZSharp.Compiler.Core/result/Result.cs | 64 +++++ .../result/errors/ErrorMessage.cs | 11 + ZSharp.Compiler.Features/ir/IIREvaluator.cs | 34 --- ZSharp.Compiler.Features/ir/IR.Compile.cs | 47 ---- ZSharp.Compiler.Features/ir/IR.cs | 19 -- ...ortAttribute.cs => HideImportAttribute.cs} | 3 +- .../namespace/AddNamespaceAttribute.cs | 17 ++ .../ZSharp.Compiler.ILLoader.csproj | 15 +- .../capabilities/ITypeModifier.cs | 7 + .../capabilities/internal/IAddMember.cs | 7 + .../internal/ILazilyLoadMembers.cs | 7 + .../capabilities/on add/IOnAddTo.cs | 2 +- .../extensions/ILLoaderExtensions.cs | 8 + .../extensions/InternalILMemberExtensions.cs | 41 ++++ .../il loader/ILLoader.Events.cs | 7 + .../il loader/ILLoader.Expose.cs | 77 ++++++ .../il loader/ILLoader.IR.cs | 10 + .../il loader/ILLoader.Namespaces.cs | 4 +- .../il loader/ILLoader.Runtime.cs | 10 + .../il loader/ILLoader.TypeSystem.cs | 7 + .../il loader/ILLoader.cs | 58 ++++- .../load/ILLoader.Load.Member.Method.cs | 4 +- .../il loader/load/ILLoader.Load.Member.cs | 1 + .../load/ILLoader.Load.Type.Class.Generic.cs | 2 +- .../load/ILLoader.Load.Type.Class.cs | 4 +- .../il loader/load/ILLoader.Load.Type.Enum.cs | 2 +- .../load/ILLoader.Load.Type.Generic.cs | 2 +- .../ILLoader.Load.Type.Interface.Generic.cs | 2 +- .../load/ILLoader.Load.Type.Interface.cs | 2 +- .../load/ILLoader.Load.Type.Modified.cs | 35 ++- .../load/ILLoader.Load.Type.Struct.Generic.cs | 2 +- .../load/ILLoader.Load.Type.Struct.cs | 2 +- .../il loader/load/ILLoader.Load.Type.cs | 6 +- .../ModuleBodyLoader.LazyLoad.cs | 30 +++ .../module body loader/ModuleBodyLoader.cs | 9 + .../load/ModuleBodyLoader.Load.Field.cs | 12 + .../ModuleBodyLoader.Load.Method.Generic.cs | 10 + .../load/ModuleBodyLoader.Load.Method.cs | 15 ++ .../load/ModuleBodyLoader.Load.Property.cs | 10 + .../load/ModuleBodyLoader.Load.cs | 15 ++ .../load/ModuleLoader.Load.Method.cs | 2 +- .../objects/GlobalUsings.cs | 4 +- .../function/concrete/Function.Call.cs | 29 +++ .../modular/function/concrete/Function.IL.cs | 4 +- .../modular/function/concrete/Function.IR.cs | 21 ++ .../modular/function/concrete/Function.cs | 2 +- .../objects/modular/global/Global.Type.cs | 2 +- .../objects/modular/module/Module.Globals.cs | 27 +++ .../objects/modular/module/Module.IL.cs | 2 - .../objects/modular/module/Module.LazyLoad.cs | 30 +-- .../objects/modular/module/Module.Member.cs | 9 +- .../objects/modular/module/Module.cs | 36 ++- .../modular/property/GlobalProperty.cs | 6 + .../modular/type as module/TypeAsModule.IL.cs | 7 + .../type as module/TypeAsModule.LazyLoad.cs | 17 ++ .../type as module/TypeAsModule.Member.cs | 31 +++ .../type as module/TypeAsModule.Namespace.cs | 7 + .../type as module/TypeAsModule.Prepare.cs | 33 +++ .../modular/type as module/TypeAsModule.cs | 23 ++ .../objects/namespace/Namespace.LazyLoad.cs | 15 +- .../objects/namespace/Namespace.Member.cs | 18 +- .../objects/namespace/Namespace.cs | 2 +- .../objects/oop/class/concrete/Class.IL.cs | 9 + .../objects/oop/class/concrete/Class.IR.cs | 28 +++ .../objects/oop/class/concrete/Class.T.cs | 7 + .../objects/oop/class/concrete/Class.cs | 12 + .../oop/class/generic/GenericClass.T.cs | 7 + .../objects/oop/class/generic/GenericClass.cs | 7 + .../objects/oop/constructor/Constructor.T.cs | 7 + .../objects/oop/constructor/Constructor.cs | 7 + .../objects/oop/enum/Enum.T.cs | 7 + .../objects/oop/enum/Enum.cs | 7 + .../objects/oop/field/Field.T.cs | 7 + .../objects/oop/field/Field.cs | 7 + .../oop/interface/concrete/Interface.T.cs | 7 + .../oop/interface/concrete/Interface.cs | 7 + .../interface/generic/GenericInterface.T.cs | 7 + .../oop/interface/generic/GenericInterface.cs | 7 + .../oop/method/bound/BoundMethod.Call.cs | 17 ++ .../objects/oop/method/bound/BoundMethod.T.cs | 7 + .../objects/oop/method/bound/BoundMethod.cs | 10 + .../oop/method/concrete/Method.Call.cs | 29 +++ .../objects/oop/method/concrete/Method.IL.cs | 9 + .../objects/oop/method/concrete/Method.IR.cs | 21 ++ .../objects/oop/method/concrete/Method.T.cs | 7 + .../objects/oop/method/concrete/Method.cs | 12 + .../oop/method/generic/GenericMethod.T.cs | 7 + .../oop/method/generic/GenericMethod.cs | 7 + .../objects/oop/property/Property.T.cs | 7 + .../{modular => oop}/property/Property.cs | 1 + .../objects/oop/struct/concrete/Struct.T.cs | 7 + .../objects/oop/struct/concrete/Struct.cs | 7 + .../oop/struct/generic/GenericStruct.T.cs | 7 + .../oop/struct/generic/GenericStruct.cs | 7 + .../objects/types/array/ArrayType.cs | 10 + .../objects/types/boolean/BooleanType.cs | 14 ++ .../objects/types/char/CharType.cs | 14 ++ .../objects/types/float/Float128Type.cs | 14 ++ .../objects/types/float/Float16Type.cs | 14 ++ .../objects/types/float/Float32Type.cs | 14 ++ .../objects/types/float/Float64Type.cs | 14 ++ .../objects/types/int/SInt16Type.cs | 14 ++ .../objects/types/int/SInt32Type.cs | 14 ++ .../objects/types/int/SInt64Type.cs | 14 ++ .../objects/types/int/SInt8Type.cs | 14 ++ .../objects/types/int/SIntNativeType.cs | 14 ++ .../objects/types/int/UInt16Type.cs | 14 ++ .../objects/types/int/UInt32Type.cs | 14 ++ .../objects/types/int/UInt64Type.cs | 14 ++ .../objects/types/int/UInt8Type.cs | 14 ++ .../objects/types/int/UIntNativeType.cs | 14 ++ .../objects/types/object/ObjectType.cs | 14 ++ .../objects/types/pointer/PointerType.cs | 10 + .../objects/types/reference/ReferenceType.cs | 10 + .../objects/types/string/StringType.cs | 14 ++ .../objects/types/void/VoidType.cs | 14 ++ .../type system/TypeSystem.Array.cs | 7 + .../type system/TypeSystem.Boolean.cs | 7 + .../type system/TypeSystem.Char.cs | 7 + .../type system/TypeSystem.Float.cs | 13 ++ .../type system/TypeSystem.Object.cs | 7 + .../type system/TypeSystem.Pointer.cs | 7 + .../type system/TypeSystem.Reference.cs | 7 + .../type system/TypeSystem.SInt.cs | 15 ++ .../type system/TypeSystem.String.cs | 7 + .../type system/TypeSystem.UInt.cs | 15 ++ .../type system/TypeSystem.Void.cs | 7 + .../type system/TypeSystem.cs | 7 + ZSharp.Compiler.IR/GlobalUsings.cs | 3 +- ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj | 2 +- .../common/ICompileIROOPTypeReference.cs | 11 + ZSharp.Compiler.IR/compile/Compiler.cs | 7 - .../compile/services/Compiler.Code.cs | 10 - .../compile/services/Compiler.Definition.cs | 17 -- .../compile/services/Compiler.Reference.cs | 11 - .../compile/services/Compiler.Type.cs | 16 -- .../core}/IRCode.cs | 5 +- ZSharp.Compiler.IR/ir/IR.cs | 7 + ZSharp.Compiler.IR/ir/services/IR.Code.cs | 15 ++ .../ir/services/IR.Definition.cs | 27 +++ .../ir/services/IR.Reference.cs | 16 ++ ZSharp.Compiler.IR/ir/services/IR.Type.cs | 21 ++ ZSharp.Compiler.IR/objects/RawIRCode.cs | 14 ++ .../protocols/ICompileIRCode.cs | 7 + .../protocols/ICompileIRDefinitionAs.cs | 8 + .../protocols/ICompileIRDefinitionIn.cs | 8 + .../protocols/ICompileIRReference.cs | 8 + .../protocols/ICompileIRType.cs | 17 ++ ZSharp.Compiler.IRLoader/Context.cs | 2 +- ZSharp.Compiler.Objects/GlobalUsings.cs | 4 +- .../definition/GenericFunction.Generic.cs | 8 +- ZSharp.Compiler.Objects/nullable/Nullable.cs | 18 +- ZSharp.Compiler.Objects/oop/class/Class.cs | 25 +- ZSharp.Compiler.TS.Static/GlobalUsings.cs | 1 + .../ZSharp.Compiler.TS.Static.csproj | 13 ++ .../dispatcher/Dispatcher.T.cs | 7 + .../dispatcher/Dispatcher.TypeOf.cs | 15 ++ .../dispatcher/Dispatcher.cs | 17 ++ ZSharp.Compiler.TS.Static/protocols/ITyped.cs | 7 + ZSharp.Compiler.TS/GlobalUsings.cs | 1 + ZSharp.Compiler.TS/ZSharp.Compiler.TS.csproj | 17 ++ ZSharp.Compiler.TS/dispatcher/Dispatcher.T.cs | 10 + ZSharp.Compiler.TS/dispatcher/Dispatcher.cs | 6 + .../services/Dispatcher.IsAssignable.cs | 8 + .../dispatcher/services/Dispatcher.TypeOf.cs | 10 + ZSharp.Compiler.TS/ts/TS.T.cs | 6 + ZSharp.Compiler.TS/ts/TS.cs | 6 + .../ts/services/TS.IsAssignable.cs | 12 + ZSharp.Compiler.TS/ts/services/TS.Make.cs | 20 ++ ZSharp.Compiler.TS/ts/services/TS.TypeOf.cs | 14 ++ ZSharp.Compiler.TS/ts/types/TS.Types.Float.cs | 9 + .../ts/types/TS.Types.Indirect.cs | 11 + .../ts/types/TS.Types.Others.cs | 15 ++ ZSharp.Compiler.TS/ts/types/TS.Types.SInt.cs | 13 ++ ZSharp.Compiler.TS/ts/types/TS.Types.UInt.cs | 13 ++ ZSharp.Compiler/GlobalUsings.cs | 11 +- ZSharp.Compiler/ZSharp.Compiler.csproj | 12 + ZSharp.Compiler/cg objects/Utils.cs | 27 --- ZSharp.Compiler/cg objects/imports/Import.cs | 13 -- .../cg objects/imports/ImportedName.cs | 11 - .../cg objects/literals/FalseLiteral.cs | 20 -- .../cg objects/literals/Float32Literal.cs | 22 -- .../cg objects/literals/IntegerLiteral.cs | 22 -- .../cg objects/literals/Literal.cs | 21 -- .../cg objects/literals/NullLiteral.cs | 18 -- .../cg objects/literals/StringLiteral.cs | 19 -- .../cg objects/literals/TrueLiteral.cs | 20 -- ZSharp.Compiler/cg objects/raw/RawCode.cs | 45 ---- ZSharp.Compiler/cg objects/raw/RawType.cs | 27 --- ZSharp.Compiler/cg objects/types/Int32Type.cs | 24 -- .../cg objects/types/ObjectType.cs | 28 --- .../cg objects/types/StringType.cs | 28 --- ZSharp.Compiler/cg objects/types/Type.cs | 28 --- .../cg objects/types/array/ArrayType.cs | 22 -- .../cg objects/types/array/ArrayTypeObject.cs | 41 ---- .../cg objects/types/pointer/PointerType.cs | 22 -- .../types/pointer/PointerTypeObject.cs | 41 ---- .../types/reference/ReferenceType.cs | 22 -- .../types/reference/ReferenceTypeObject.cs | 41 ---- .../compiler core/compiler/Compiler.DRY.cs | 16 -- .../compiler/Compiler.Features.cs | 25 -- .../compiler core/compiler/Compiler.IR.cs | 77 ------ .../compiler/Compiler.Services.cs | 9 - .../compiler/features/Compiler.Protocols.cs | 126 ---------- .../compiler/features/Compiler.Query.cs | 16 -- .../compiler/features/Compiler.TypeSystem.cs | 12 - .../compiler/literals/Compiler.Create.cs | 36 --- .../compiler/literals/Compiler.Is.cs | 54 ----- .../compiler/literals/Compiler.Literals.cs | 15 -- .../compiler/value/Compiler.IsCT.cs | 30 --- ZSharp.Compiler/compiler core/core/Feature.cs | 14 -- .../core/type system/IDynamicallyTyped.cs | 12 - .../compiler core/core/type system/IType.cs | 9 - .../core/type system/ITypeAssignment.cs | 16 -- .../core/type system/ITypeModifier.cs | 7 - .../compiler core/core/type system/ITyped.cs | 10 - .../core/type system/TypeSystem.cs | 134 ----------- .../compiler/Compiler.Context.cs | 2 +- .../compiler/Compiler.Logging.cs | 4 +- ZSharp.Compiler/compiler/Compiler.Services.cs | 16 ++ .../{compiler core => }/compiler/Compiler.cs | 16 +- ZSharp.Compiler/core/CompilerObject.cs | 6 - ZSharp.Compiler/core/concepts/IMappable.cs | 8 - ZSharp.Compiler/core/concepts/INamedObject.cs | 10 - .../core/concepts/callable/ICallable.cs | 16 -- .../core/concepts/index/ICTGetIndex.cs | 10 - .../core/concepts/index/ISetIndex.cs | 7 - .../core/concepts/member/IGetMember.cs | 18 -- .../core/concepts/member/ISetMember_Old.cs | 7 - .../core/concepts/value/IEvaluable.cs | 7 - .../core/concepts/value/IImplicitCast.cs | 12 - .../core/concepts/value/IReadable.cs | 25 -- .../core/concepts/value/ITypeCast.cs | 12 - .../concepts/value/assignment/Assignment.cs | 92 -------- .../concepts/value/assignment/IAssignable.cs | 18 -- .../core/context/EmptyContext.cs | 0 .../core/logging/LoggerExtensions.cs | 19 ++ .../core/logging/ObjectLogOrigin.cs | 4 +- .../exceptions/CompilerObjectException.cs | 8 - .../exceptions/InvalidCastException.cs | 10 - .../PartiallyCompiledObjectException.cs | 11 - .../cap/generic/IGenericInstantiable.cs | 13 -- ZSharp.Compiler/features/cg/CG.cs | 13 -- .../cg/capabilities/callable/Argument.cs | 16 -- .../cg/capabilities/callable/ICTCallable.cs | 8 - .../cg/capabilities/callable/IRTCallable.cs | 8 - .../implicit casting/ICTImplicitCastFrom.cs | 8 - .../implicit casting/ICTImplicitCastTo.cs | 8 - .../implicit casting/IRTImplicitCastTo.cs | 8 - .../cg/capabilities/index/ICTGetIndex.cs | 8 - .../cg/capabilities/index/ICTSetIndex.cs | 8 - .../cg/capabilities/index/IRTGetIndex.cs | 8 - .../cg/capabilities/index/IRTSetIndex.cs | 8 - .../member access/ICTSetMember.cs | 7 - .../member access/IRTGetMember.cs | 7 - .../member access/IRTSetMember.cs | 7 - .../runtime/IHasRuntimeDescriptor.cs | 8 - .../cg/capabilities/type casting/ICTCastTo.cs | 8 - .../capabilities/type casting/IRTCastFrom.cs | 8 - .../cg/capabilities/type casting/IRTCastTo.cs | 8 - .../type matching/ICTTypeMatch.cs | 8 - .../type matching/IRTTypeMatch.cs | 8 - .../capabilities/value access/get/ICTGet.cs | 8 - .../capabilities/value access/get/IRTGet.cs | 8 - .../capabilities/value access/set/ICTSet.cs | 8 - .../capabilities/value access/set/IRTSet.cs | 8 - .../cg/capabilities/wrapper/IObjectWrapper.cs | 8 - .../features/cg/services/CG.Call.cs | 24 -- .../features/cg/services/CG.ImplicitCast.cs | 27 --- .../features/cg/services/CG.Index.cs | 46 ---- .../features/cg/services/CG.MemberAccess.cs | 83 ------- .../features/cg/services/CG.Runtime.cs | 15 -- .../features/cg/services/CG.TypeCast.cs | 40 ---- .../features/cg/services/CG.TypeMatch.cs | 27 --- .../features/cg/services/CG.ValueAccess.cs | 43 ---- ZSharp.Compiler/features/ir/IR.cs | 7 - .../ir/capabilities/code/ICTCompileIRCode.cs | 8 - .../features/ir/services/IR.Code.cs | 21 -- .../features/ir/services/IR.Definition.cs | 52 ----- .../features/ir/services/IR.Reference.cs | 20 -- .../features/ir/services/IR.Type.cs | 36 --- .../features/oop/extensibility/IClass.cs | 13 -- .../oop/extensibility/IRTBoundMember.cs | 7 - .../ir generator/IRCodeGenerator.cs | 7 - .../ir generator/protocols/ICompileIRCode.cs | 10 - .../protocols/ICompileIRObject.cs | 26 --- .../protocols/ICompileIRReference.cs | 7 - .../ir generator/protocols/ICompileIRType.cs | 16 -- .../ir/functional/GenericFunctionInstance.cs | 2 +- ZSharp.IR/ir/oop/constructor/Constructor.cs | 26 +-- ZSharp.Interpreter/CTServices.cs | 3 + ZSharp.Interpreter/GlobalUsings.cs | 1 + ZSharp.Interpreter/ZSharp.Interpreter.csproj | 6 +- .../interpreter/Interpreter.Logging.cs | 9 + ZSharp.Interpreter/interpreter/Interpreter.cs | 85 +++---- .../source-compiler/GlobalUsings.cs | 15 -- .../source-compiler/NodeLogOrigin.cs | 12 - .../core/logging => ZSharp.Logging}/Log.cs | 2 +- .../logging => ZSharp.Logging}/LogLevel.cs | 2 +- .../logging => ZSharp.Logging}/LogOrigin.cs | 2 +- .../core/logging => ZSharp.Logging}/Logger.cs | 14 +- ZSharp.Logging/ZSharp.Logging.csproj | 9 + ZSharp.Parser/Utils.cs | 4 +- ZSharp.Parser/parsers/FunctionParser.cs | 10 +- ZSharp.Runtime/GlobalUsings.cs | 3 + .../loader/emit/load/EmitLoader.Load.Code.cs | 7 +- .../code/functional/FunctionalCodeCompiler.cs | 2 +- ZSharp.Runtime/runtime/Runtime.Expose.cs | 75 ++++++ .../{Runtime.IR.cs => Runtime.Singleton.cs} | 2 +- ZSharp.Runtime/runtime/Runtime.TypeSystem.cs | 7 + ZSharp.Runtime/runtime/Runtime.cs | 22 +- .../runtime/import/Runtime.Import.Global.cs | 2 +- .../runtime/import/Runtime.Import.Type.cs | 6 +- .../type system/TypeSystem.Array.cs | 7 + .../type system/TypeSystem.Boolean.cs | 7 + ZSharp.Runtime/type system/TypeSystem.Char.cs | 7 + .../type system/TypeSystem.Float.cs | 13 ++ .../type system/TypeSystem.Object.cs | 7 + .../type system/TypeSystem.Pointer.cs | 7 + .../type system/TypeSystem.Reference.cs | 7 + ZSharp.Runtime/type system/TypeSystem.SInt.cs | 15 ++ .../type system/TypeSystem.String.cs | 7 + ZSharp.Runtime/type system/TypeSystem.UInt.cs | 15 ++ ZSharp.Runtime/type system/TypeSystem.Void.cs | 7 + ZSharp.Runtime/type system/TypeSystem.cs | 7 + .../CompileExpression.cs | 4 + ZSharp.SourceCompiler.Common/GlobalUsings.cs | 3 + ZSharp.SourceCompiler.Common/TaskManager.cs | 20 ++ .../ZSharp.SourceCompiler.Common.csproj | 13 ++ .../ExpressionCompiler.Compile.cs | 18 ++ .../ExpressionCompiler.T.cs | 7 + .../expression compiler/ExpressionCompiler.cs | 7 + .../ExpressionCompiler.Compile.Call.cs | 45 ++++ .../ExpressionCompiler.Compile.Identifier.cs | 16 ++ .../ExpressionCompiler.Compile.Literal.cs | 13 ++ .../extensions/LoggerExtensions.cs | 10 + .../importers/CoreLibraryImporter.cs | 19 ++ .../importers/StandardLibraryImporter.cs | 19 ++ .../LiteralCompiler.Compile.Boolean.cs | 11 + .../LiteralCompiler.Compile.String.cs | 10 + .../LiteralCompiler.Compile.cs | 20 ++ .../literal compiler/LiteralCompiler.T.cs | 7 + .../literal compiler/LiteralCompiler.cs | 7 + .../objects/code/block/CodeBlock.Content.cs | 9 + .../objects/code/block/CodeBlock.IR.cs | 7 + .../objects/code/block/CodeBlock.cs | 7 + .../literals/bool/BooleanLiteral.IR.cs | 16 ++ .../objects/literals/bool/BooleanLiteral.cs | 8 + .../literals/string/StringLiteral.IR.cs | 16 ++ .../objects/literals/string/StringLiteral.cs | 8 + .../TopLevelExpressionCompiler.cs | 32 +++ ZSharp.SourceCompiler.Core/NodeLogOrigin.cs | 12 + .../ZSharp.SourceCompiler.Core.csproj | 15 ++ .../context/Context.ImportSystem.cs | 7 + .../context/Context.Operators.cs | 7 + .../context/Context.T.cs | 7 + ZSharp.SourceCompiler.Core/context/Context.cs | 7 + .../string importer/IStringImporter.cs | 10 + .../string importer/StringImporter.cs | 48 ++++ .../import system/ImportSystem.cs | 9 + .../operator table/OperatorTable.cs | 34 +++ ZSharp.SourceCompiler.Module/GlobalUsings.cs | 3 + .../ZSharp.SourceCompiler.Module.csproj | 31 +++ .../capabilities/IModuleMember.cs | 7 + .../capabilities/functional/IParameter.cs | 7 + .../capabilities/functional/ISignature.cs | 12 + .../contexts/modular/FunctionContext.cs | 11 + .../contexts/modular/ModuleContext.cs | 6 + .../FunctionBodyCompiler.T.cs | 7 + .../FunctionBodyCompiler.cs | 19 ++ .../compile/FunctionBodyCompiler.Compile.cs | 8 + .../FunctionBodyCompiler.Compile.Function.cs | 16 ++ .../expr/FunctionBodyCompiler.Compile.cs | 12 + .../FunctionBodyCompiler.Compile.Block.cs | 17 ++ ...FunctionBodyCompiler.Compile.Definition.cs | 8 + ...FunctionBodyCompiler.Compile.Expression.cs | 8 + .../stmt/FunctionBodyCompiler.Compile.cs | 14 ++ .../FunctionCompiler.Compile.cs | 63 +++++ .../function compiler/FunctionCompiler.T.cs | 7 + .../function compiler/FunctionCompiler.cs | 25 ++ .../module compiler/ModuleCompiler.Log.cs | 18 ++ .../module compiler/ModuleCompiler.T.cs | 7 + .../module compiler/ModuleCompiler.Tasks.cs | 7 + .../module compiler/ModuleCompiler.cs | 24 ++ .../compile/ModuleCompiler.Compile.cs | 43 ++++ .../expr/ModuleCompiler.Compile.Call.cs | 45 ++++ .../expr/ModuleCompiler.Compile.Expression.cs | 12 + .../expr/ModuleCompiler.Compile.Function.cs | 24 ++ .../stmt/ModuleCompiler.Compile.Definition.cs | 12 + .../stmt/ModuleCompiler.Compile.Expression.cs | 8 + .../modular/function/Function.Build.cs | 18 ++ .../objects/modular/function/Function.Call.cs | 11 + .../objects/modular/function/Function.IR.cs | 7 + .../modular/function/Function.ModuleMember.cs | 10 + .../objects/modular/function/Function.Name.cs | 18 ++ .../objects/modular/function/Function.T.cs | 7 + .../objects/modular/function/Function.cs | 8 + .../objects/modular/global/Global.Build.cs | 19 ++ .../objects/modular/global/Global.IR.cs | 46 ++++ .../modular/global/Global.ModuleMember.cs | 11 + .../objects/modular/global/Global.Name.cs | 20 ++ .../objects/modular/global/Global.T.cs | 7 + .../objects/modular/global/Global.Type.cs | 20 ++ .../objects/modular/global/Global.cs | 7 + .../objects/modular/module/Module.Build.cs | 18 ++ .../objects/modular/module/Module.IR.cs | 7 + .../objects/modular/module/Module.Name.cs | 17 ++ .../objects/modular/module/Module.T.cs | 7 + .../objects/modular/module/Module.cs | 8 + .../old/GlobalUsings.cs | 15 ++ .../old}/HelperFunctions.cs | 0 .../capabilities/IMultipassCompiler.cs | 0 .../class body/ClassBodyCompiler.cs | 0 .../class body/ConstructorCompiler.cs | 0 .../class body/MethodCompiler.cs | 0 .../compiler/DocumentCompiler.Compile.cs | 0 .../document/compiler/DocumentCompiler.cs | 0 .../document/objects/Document.cs | 0 .../builtin-compilers/module/ClassCompiler.cs | 0 .../module/FunctionCompiler.cs | 0 .../module/ModuleCompiler.cs | 0 .../runtime code/loops/for/ForLoopCompiler.cs | 0 .../loops/while/WhileExpressionCompiler.cs | 0 .../loops/while/WhileLoopCompiler.cs | 0 .../loops/while/WhileStatementCompiler.cs | 0 .../runtime code/objects/Case.cs | 0 .../runtime code/objects/ForLoop.cs | 0 .../runtime code/objects/If.cs | 0 .../runtime code/objects/WhileLoop.cs | 0 .../compiler/ZSSourceCompiler.Compilers.cs | 0 .../compiler/ZSSourceCompiler.ImportSystem.cs | 0 .../compiler/ZSSourceCompiler.Initialize.cs | 0 .../old}/compiler/ZSSourceCompiler.Logging.cs | 0 .../old}/compiler/ZSSourceCompiler.OOP.cs | 0 .../compiler/ZSSourceCompiler.Operators.cs | 0 .../compiler/ZSSourceCompiler.ResultTools.cs | 0 .../old}/compiler/ZSSourceCompiler.cs | 0 .../old}/context/Context.Compilers.cs | 0 .../old}/context/Context.Nodes.cs | 0 .../old}/context/Context.Scopes.cs | 0 .../old}/context/Context.cs | 0 .../contexts/capabilities/IMemoryAllocator.cs | 0 .../contexts/capabilities/IObjectContext.cs | 0 .../capabilities/scope/ILookupContext.cs | 0 .../capabilities/scope/IScopeContext.cs | 0 .../old}/contexts/concrete/ClassContext.cs | 0 .../contexts/concrete/ExpressionContext.cs | 0 .../old}/contexts/concrete/FunctionContext.cs | 0 .../old}/contexts/concrete/ObjectContext.cs | 0 .../old}/contexts/concrete/ScopeContext.cs | 0 .../strategies/UntilContextTypeStrategy.cs | 0 .../core-compilers/DefaultContextCompiler.cs | 0 .../expression/ExpressionCompiler.Literals.cs | 0 .../expression/ExpressionCompiler.cs | 0 .../statement/StatementCompiler.cs | 0 .../old}/extensibility/CompilerBase.cs | 0 .../old}/extensibility/ContextCompiler.cs | 0 .../old}/extensibility/error/Error.cs | 0 .../error/errors/CombinedCompilationError.cs | 0 .../error/errors/CompilationError.cs | 0 .../extensibility/oop/ClassSpecification.cs | 0 .../overrides/IOverrideCompileExpression.cs | 0 .../overrides/IOverrideCompileNode.cs | 0 .../overrides/IOverrideCompileStatement.cs | 0 .../old}/import system/ImportSystem.cs | 0 .../importers/StandardLibraryImporter.cs | 0 .../import system/importers/StringImporter.cs | 0 .../import system/importers/ZSImporter.cs | 0 .../utils/ObjectBuildState.cs | 28 +++ .../ZSharp.SourceCompiler.Project.csproj | 2 +- .../compiler/ProjectCompiler.T.cs | 7 + .../compiler/ProjectCompiler.cs | 19 ++ .../project/ProjectResult.cs | 7 + ZSharp.SourceCompiler.Script/GlobalUsings.cs | 1 + .../ZSharp.SourceCompiler.Script.csproj | 16 ++ .../compiler/ScriptCompiler.Context.cs | 7 + .../compiler/ScriptCompiler.Options.cs | 7 + .../compiler/ScriptCompiler.T.cs | 7 + .../compiler/ScriptCompiler.cs | 31 +++ .../compile/ScriptCompiler.Compile.cs | 25 ++ .../expr/ScriptCompiler.Compile.Call.cs | 47 ++++ .../expr/ScriptCompiler.Compile.Expression.cs | 29 +++ .../expr/ScriptCompiler.Compile.Identifier.cs | 18 ++ .../compile/expr/ScriptCompiler.Compile.If.cs | 7 + .../expr/ScriptCompiler.Compile.Literal.cs | 13 ++ .../expr/ScriptCompiler.Compile.Module.cs | 10 + .../stmt/ScriptCompiler.Compile.Block.cs | 13 ++ .../stmt/ScriptCompiler.Compile.Definition.cs | 16 ++ .../stmt/ScriptCompiler.Compile.Expression.cs | 26 +++ .../compile/stmt/ScriptCompiler.Compile.If.cs | 52 +++++ .../stmt/ScriptCompiler.Compile.Import.cs | 125 ++++++++++ .../contexts/ScopeContext.cs | 34 +++ .../options/EvaluationTarget.cs | 15 ++ .../options/ScriptingOptions.cs | 7 + 607 files changed, 5802 insertions(+), 2683 deletions(-) rename {ZSharp.Compiler/core => CommonZ}/Result.cs (90%) create mode 100644 Examples/test.zs create mode 100644 ZSC.Script/CLIArgumentLogOrigin.cs create mode 100644 ZSC.Script/Program.cs create mode 100644 ZSC.Script/ZSC.Script.csproj create mode 100644 ZSC.Script/ZSCScriptLogOrigin.cs create mode 100644 ZSharp.AST/nodes/stmt/expr/DefinitionStatement.cs rename ZSharp.CT.StandardLibrary.FileSystem/module scope/{Operators.cs => ModuleScope.Operators.cs} (93%) create mode 100644 ZSharp.CT.StandardLibrary.FileSystem/module scope/ModuleScope.cs create mode 100644 ZSharp.CT.StandardLibrary.IO/GlobalUsings.cs create mode 100644 ZSharp.CT.StandardLibrary.IO/ModuleAttributes.cs create mode 100644 ZSharp.CT.StandardLibrary.IO/ZSharp.CT.StandardLibrary.IO.csproj create mode 100644 ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Functions.cs create mode 100644 ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Operators.cs create mode 100644 ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.cs create mode 100644 ZSharp.Compiler.CO.CT/GlobalUsings.cs create mode 100644 ZSharp.Compiler.CO.CT/ZSharp.Compiler.CO.CT.csproj create mode 100644 ZSharp.Compiler.CO.CT/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Call.cs create mode 100644 ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Cast.cs create mode 100644 ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ImplicitCast.cs create mode 100644 ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Index.cs create mode 100644 ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Match.cs create mode 100644 ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.MemberAccess.cs create mode 100644 ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ValueAccess.cs create mode 100644 ZSharp.Compiler.CO.CT/protocols/callable/ICTCallable.cs create mode 100644 ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastFrom.cs create mode 100644 ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastTo.cs create mode 100644 ZSharp.Compiler.CO.CT/protocols/index/ICTGetIndex.cs create mode 100644 ZSharp.Compiler.CO.CT/protocols/index/ICTSetIndex.cs rename {ZSharp.Compiler/features/cg/capabilities => ZSharp.Compiler.CO.CT/protocols}/member access/ICTGetMember.cs (52%) create mode 100644 ZSharp.Compiler.CO.CT/protocols/member access/ICTSetMember.cs create mode 100644 ZSharp.Compiler.CO.CT/protocols/type casting/ICTCastTo.cs create mode 100644 ZSharp.Compiler.CO.CT/protocols/type matching/ICTTypeMatch.cs create mode 100644 ZSharp.Compiler.CO.CT/protocols/value access/ICTGet.cs create mode 100644 ZSharp.Compiler.CO.CT/protocols/value access/ICTSet.cs create mode 100644 ZSharp.Compiler.CO.Proxy/GlobalUsings.cs create mode 100644 ZSharp.Compiler.CO.Proxy/ZSharp.Compiler.CO.Proxy.csproj create mode 100644 ZSharp.Compiler.CO.Proxy/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Call.cs create mode 100644 ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Cast.cs create mode 100644 ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs create mode 100644 ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Index.cs create mode 100644 ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Match.cs create mode 100644 ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs create mode 100644 ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs create mode 100644 ZSharp.Compiler.CO.Proxy/protocols/IProxy.cs create mode 100644 ZSharp.Compiler.CO.RT/GlobalUsings.cs create mode 100644 ZSharp.Compiler.CO.RT/ZSharp.Compiler.CO.RT.csproj create mode 100644 ZSharp.Compiler.CO.RT/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Call.cs create mode 100644 ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Cast.cs create mode 100644 ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ImplicitCast.cs create mode 100644 ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Index.cs create mode 100644 ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Match.cs create mode 100644 ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.MemberAccess.cs create mode 100644 ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ValueAccess.cs create mode 100644 ZSharp.Compiler.CO.RT/extensions/CompilerExtensions.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/callable/IRTCallable.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/implicit casting/IRTImplicitCastTo.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/index/IRTGetIndex.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/index/IRTSetIndex.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/member access/IRTGetMember.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/member access/IRTSetMember.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/runtime/IHasRuntimeDescriptor.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastFrom.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastTo.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/type matching/IRTTypeMatch.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/value access/IRTGet.cs create mode 100644 ZSharp.Compiler.CO.RT/protocols/value access/IRTSet.cs create mode 100644 ZSharp.Compiler.CO/GlobalUsings.cs create mode 100644 ZSharp.Compiler.CO/ZSharp.Compiler.CO.csproj create mode 100644 ZSharp.Compiler.CO/cg/CG.cs create mode 100644 ZSharp.Compiler.CO/cg/services/CG.Call.cs create mode 100644 ZSharp.Compiler.CO/cg/services/CG.Cast.cs create mode 100644 ZSharp.Compiler.CO/cg/services/CG.ImplicitCast.cs create mode 100644 ZSharp.Compiler.CO/cg/services/CG.Index.cs create mode 100644 ZSharp.Compiler.CO/cg/services/CG.Match.cs create mode 100644 ZSharp.Compiler.CO/cg/services/CG.MemberAccess.cs create mode 100644 ZSharp.Compiler.CO/cg/services/CG.ValueAccess.cs rename {ZSharp.Compiler/core/concepts/callable => ZSharp.Compiler.CO/core}/Argument.cs (100%) rename ZSharp.Compiler/features/cg/capabilities/type casting/TypeCast.cs => ZSharp.Compiler.CO/core/CastResult.cs (90%) rename ZSharp.Compiler/features/cg/capabilities/type matching/TypeMatch.cs => ZSharp.Compiler.CO/core/MatchResult.cs (84%) create mode 100644 ZSharp.Compiler.CO/dispatcher/Dispatcher.Call.cs create mode 100644 ZSharp.Compiler.CO/dispatcher/Dispatcher.Cast.cs create mode 100644 ZSharp.Compiler.CO/dispatcher/Dispatcher.ImplicitCast.cs create mode 100644 ZSharp.Compiler.CO/dispatcher/Dispatcher.Index.cs create mode 100644 ZSharp.Compiler.CO/dispatcher/Dispatcher.Match.cs create mode 100644 ZSharp.Compiler.CO/dispatcher/Dispatcher.MemberAccess.cs create mode 100644 ZSharp.Compiler.CO/dispatcher/Dispatcher.Runtime.cs create mode 100644 ZSharp.Compiler.CO/dispatcher/Dispatcher.ValueAccess.cs create mode 100644 ZSharp.Compiler.CO/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.Context/GlobalUsings.cs create mode 100644 ZSharp.Compiler.Context/ZSharp.Compiler.Context.csproj create mode 100644 ZSharp.Compiler.Context/capabilities/object/IObjectContext.cs create mode 100644 ZSharp.Compiler.Context/capabilities/scoping/ILookupContext.cs create mode 100644 ZSharp.Compiler.Context/capabilities/scoping/IScopeContext.cs create mode 100644 ZSharp.Compiler.Context/capabilities/storage/IStorage.cs create mode 100644 ZSharp.Compiler.Context/capabilities/storage/IStorageContext.cs create mode 100644 ZSharp.Compiler.Context/capabilities/storage/IStorageDescriptor.cs create mode 100644 ZSharp.Compiler.Context/capabilities/storage/StorageOptions.cs create mode 100644 ZSharp.Compiler.Context/capabilities/type inference/ITypeInferenceContext.cs create mode 100644 ZSharp.Compiler.Context/capabilities/type inference/TypeInferrer.cs rename {ZSharp.Compiler/compiler core/core/context => ZSharp.Compiler.Context/core}/IContext.cs (75%) rename {ZSharp.Compiler/compiler core/core/context => ZSharp.Compiler.Context/core}/IContextChainStrategy.cs (100%) rename {ZSharp.Compiler/compiler core/core/context => ZSharp.Compiler.Context}/strategies/ParentContextStrategy.cs (100%) create mode 100644 ZSharp.Compiler.Core/CompilerObject.cs create mode 100644 ZSharp.Compiler.Core/ZSharp.Compiler.Core.csproj create mode 100644 ZSharp.Compiler.Core/result/Error.cs create mode 100644 ZSharp.Compiler.Core/result/Result.cs create mode 100644 ZSharp.Compiler.Core/result/errors/ErrorMessage.cs delete mode 100644 ZSharp.Compiler.Features/ir/IIREvaluator.cs delete mode 100644 ZSharp.Compiler.Features/ir/IR.Compile.cs delete mode 100644 ZSharp.Compiler.Features/ir/IR.cs rename ZSharp.Compiler.ILLoader.Attributes/{SkipImportAttribute.cs => HideImportAttribute.cs} (85%) create mode 100644 ZSharp.Compiler.ILLoader.Attributes/namespace/AddNamespaceAttribute.cs create mode 100644 ZSharp.Compiler.ILLoader/capabilities/ITypeModifier.cs create mode 100644 ZSharp.Compiler.ILLoader/capabilities/internal/IAddMember.cs create mode 100644 ZSharp.Compiler.ILLoader/capabilities/internal/ILazilyLoadMembers.cs create mode 100644 ZSharp.Compiler.ILLoader/extensions/ILLoaderExtensions.cs create mode 100644 ZSharp.Compiler.ILLoader/extensions/InternalILMemberExtensions.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/ILLoader.Events.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/ILLoader.Expose.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/ILLoader.IR.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/ILLoader.Runtime.cs create mode 100644 ZSharp.Compiler.ILLoader/il loader/ILLoader.TypeSystem.cs create mode 100644 ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs create mode 100644 ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.cs create mode 100644 ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs create mode 100644 ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs create mode 100644 ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs create mode 100644 ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs create mode 100644 ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.Call.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IR.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/module/Module.Globals.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/property/GlobalProperty.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.IL.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Namespace.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IL.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IR.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/field/Field.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/field/Field.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.Call.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IL.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IR.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/property/Property.T.cs rename ZSharp.Compiler.ILLoader/objects/{modular => oop}/property/Property.cs (80%) create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.T.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/array/ArrayType.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/boolean/BooleanType.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/char/CharType.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/float/Float128Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/float/Float16Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/float/Float32Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/float/Float64Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/int/SInt16Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/int/SInt32Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/int/SInt64Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/int/SInt8Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/int/SIntNativeType.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/int/UInt16Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/int/UInt32Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/int/UInt64Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/int/UInt8Type.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/int/UIntNativeType.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/object/ObjectType.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/pointer/PointerType.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/reference/ReferenceType.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/string/StringType.cs create mode 100644 ZSharp.Compiler.ILLoader/objects/types/void/VoidType.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.Array.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.Boolean.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.Char.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.Float.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.Object.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.Pointer.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.Reference.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.SInt.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.String.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.UInt.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.Void.cs create mode 100644 ZSharp.Compiler.ILLoader/type system/TypeSystem.cs create mode 100644 ZSharp.Compiler.IR/common/ICompileIROOPTypeReference.cs delete mode 100644 ZSharp.Compiler.IR/compile/Compiler.cs delete mode 100644 ZSharp.Compiler.IR/compile/services/Compiler.Code.cs delete mode 100644 ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs delete mode 100644 ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs delete mode 100644 ZSharp.Compiler.IR/compile/services/Compiler.Type.cs rename {ZSharp.Compiler/core/code => ZSharp.Compiler.IR/core}/IRCode.cs (90%) create mode 100644 ZSharp.Compiler.IR/ir/IR.cs create mode 100644 ZSharp.Compiler.IR/ir/services/IR.Code.cs create mode 100644 ZSharp.Compiler.IR/ir/services/IR.Definition.cs create mode 100644 ZSharp.Compiler.IR/ir/services/IR.Reference.cs create mode 100644 ZSharp.Compiler.IR/ir/services/IR.Type.cs create mode 100644 ZSharp.Compiler.IR/objects/RawIRCode.cs create mode 100644 ZSharp.Compiler.IR/protocols/ICompileIRCode.cs create mode 100644 ZSharp.Compiler.IR/protocols/ICompileIRDefinitionAs.cs create mode 100644 ZSharp.Compiler.IR/protocols/ICompileIRDefinitionIn.cs create mode 100644 ZSharp.Compiler.IR/protocols/ICompileIRReference.cs create mode 100644 ZSharp.Compiler.IR/protocols/ICompileIRType.cs create mode 100644 ZSharp.Compiler.TS.Static/GlobalUsings.cs create mode 100644 ZSharp.Compiler.TS.Static/ZSharp.Compiler.TS.Static.csproj create mode 100644 ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs create mode 100644 ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs create mode 100644 ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.TS.Static/protocols/ITyped.cs create mode 100644 ZSharp.Compiler.TS/GlobalUsings.cs create mode 100644 ZSharp.Compiler.TS/ZSharp.Compiler.TS.csproj create mode 100644 ZSharp.Compiler.TS/dispatcher/Dispatcher.T.cs create mode 100644 ZSharp.Compiler.TS/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.TS/dispatcher/services/Dispatcher.IsAssignable.cs create mode 100644 ZSharp.Compiler.TS/dispatcher/services/Dispatcher.TypeOf.cs create mode 100644 ZSharp.Compiler.TS/ts/TS.T.cs create mode 100644 ZSharp.Compiler.TS/ts/TS.cs create mode 100644 ZSharp.Compiler.TS/ts/services/TS.IsAssignable.cs create mode 100644 ZSharp.Compiler.TS/ts/services/TS.Make.cs create mode 100644 ZSharp.Compiler.TS/ts/services/TS.TypeOf.cs create mode 100644 ZSharp.Compiler.TS/ts/types/TS.Types.Float.cs create mode 100644 ZSharp.Compiler.TS/ts/types/TS.Types.Indirect.cs create mode 100644 ZSharp.Compiler.TS/ts/types/TS.Types.Others.cs create mode 100644 ZSharp.Compiler.TS/ts/types/TS.Types.SInt.cs create mode 100644 ZSharp.Compiler.TS/ts/types/TS.Types.UInt.cs delete mode 100644 ZSharp.Compiler/cg objects/Utils.cs delete mode 100644 ZSharp.Compiler/cg objects/imports/Import.cs delete mode 100644 ZSharp.Compiler/cg objects/imports/ImportedName.cs delete mode 100644 ZSharp.Compiler/cg objects/literals/FalseLiteral.cs delete mode 100644 ZSharp.Compiler/cg objects/literals/Float32Literal.cs delete mode 100644 ZSharp.Compiler/cg objects/literals/IntegerLiteral.cs delete mode 100644 ZSharp.Compiler/cg objects/literals/Literal.cs delete mode 100644 ZSharp.Compiler/cg objects/literals/NullLiteral.cs delete mode 100644 ZSharp.Compiler/cg objects/literals/StringLiteral.cs delete mode 100644 ZSharp.Compiler/cg objects/literals/TrueLiteral.cs delete mode 100644 ZSharp.Compiler/cg objects/raw/RawCode.cs delete mode 100644 ZSharp.Compiler/cg objects/raw/RawType.cs delete mode 100644 ZSharp.Compiler/cg objects/types/Int32Type.cs delete mode 100644 ZSharp.Compiler/cg objects/types/ObjectType.cs delete mode 100644 ZSharp.Compiler/cg objects/types/StringType.cs delete mode 100644 ZSharp.Compiler/cg objects/types/Type.cs delete mode 100644 ZSharp.Compiler/cg objects/types/array/ArrayType.cs delete mode 100644 ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs delete mode 100644 ZSharp.Compiler/cg objects/types/pointer/PointerType.cs delete mode 100644 ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs delete mode 100644 ZSharp.Compiler/cg objects/types/reference/ReferenceType.cs delete mode 100644 ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs delete mode 100644 ZSharp.Compiler/compiler core/compiler/Compiler.DRY.cs delete mode 100644 ZSharp.Compiler/compiler core/compiler/Compiler.Features.cs delete mode 100644 ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs delete mode 100644 ZSharp.Compiler/compiler core/compiler/Compiler.Services.cs delete mode 100644 ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs delete mode 100644 ZSharp.Compiler/compiler core/compiler/features/Compiler.Query.cs delete mode 100644 ZSharp.Compiler/compiler core/compiler/features/Compiler.TypeSystem.cs delete mode 100644 ZSharp.Compiler/compiler core/compiler/literals/Compiler.Create.cs delete mode 100644 ZSharp.Compiler/compiler core/compiler/literals/Compiler.Is.cs delete mode 100644 ZSharp.Compiler/compiler core/compiler/literals/Compiler.Literals.cs delete mode 100644 ZSharp.Compiler/compiler core/compiler/value/Compiler.IsCT.cs delete mode 100644 ZSharp.Compiler/compiler core/core/Feature.cs delete mode 100644 ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs delete mode 100644 ZSharp.Compiler/compiler core/core/type system/IType.cs delete mode 100644 ZSharp.Compiler/compiler core/core/type system/ITypeAssignment.cs delete mode 100644 ZSharp.Compiler/compiler core/core/type system/ITypeModifier.cs delete mode 100644 ZSharp.Compiler/compiler core/core/type system/ITyped.cs delete mode 100644 ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs rename ZSharp.Compiler/{compiler core => }/compiler/Compiler.Context.cs (91%) rename ZSharp.Compiler/{compiler core => }/compiler/Compiler.Logging.cs (67%) create mode 100644 ZSharp.Compiler/compiler/Compiler.Services.cs rename ZSharp.Compiler/{compiler core => }/compiler/Compiler.cs (51%) delete mode 100644 ZSharp.Compiler/core/CompilerObject.cs delete mode 100644 ZSharp.Compiler/core/concepts/IMappable.cs delete mode 100644 ZSharp.Compiler/core/concepts/INamedObject.cs delete mode 100644 ZSharp.Compiler/core/concepts/callable/ICallable.cs delete mode 100644 ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs delete mode 100644 ZSharp.Compiler/core/concepts/index/ISetIndex.cs delete mode 100644 ZSharp.Compiler/core/concepts/member/IGetMember.cs delete mode 100644 ZSharp.Compiler/core/concepts/member/ISetMember_Old.cs delete mode 100644 ZSharp.Compiler/core/concepts/value/IEvaluable.cs delete mode 100644 ZSharp.Compiler/core/concepts/value/IImplicitCast.cs delete mode 100644 ZSharp.Compiler/core/concepts/value/IReadable.cs delete mode 100644 ZSharp.Compiler/core/concepts/value/ITypeCast.cs delete mode 100644 ZSharp.Compiler/core/concepts/value/assignment/Assignment.cs delete mode 100644 ZSharp.Compiler/core/concepts/value/assignment/IAssignable.cs rename ZSharp.Compiler/{compiler core => }/core/context/EmptyContext.cs (100%) create mode 100644 ZSharp.Compiler/core/logging/LoggerExtensions.cs rename ZSharp.Compiler/{compiler core => }/core/logging/ObjectLogOrigin.cs (79%) delete mode 100644 ZSharp.Compiler/exceptions/CompilerObjectException.cs delete mode 100644 ZSharp.Compiler/exceptions/InvalidCastException.cs delete mode 100644 ZSharp.Compiler/exceptions/PartiallyCompiledObjectException.cs delete mode 100644 ZSharp.Compiler/features/cap/generic/IGenericInstantiable.cs delete mode 100644 ZSharp.Compiler/features/cg/CG.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/callable/Argument.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/callable/IRTCallable.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastFrom.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastTo.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/implicit casting/IRTImplicitCastTo.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/index/ICTGetIndex.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/index/ICTSetIndex.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/index/IRTGetIndex.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/index/IRTSetIndex.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/member access/ICTSetMember.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/member access/IRTGetMember.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/member access/IRTSetMember.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/runtime/IHasRuntimeDescriptor.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/type casting/ICTCastTo.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastFrom.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastTo.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/type matching/ICTTypeMatch.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/type matching/IRTTypeMatch.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/value access/get/ICTGet.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/value access/get/IRTGet.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/value access/set/ICTSet.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/value access/set/IRTSet.cs delete mode 100644 ZSharp.Compiler/features/cg/capabilities/wrapper/IObjectWrapper.cs delete mode 100644 ZSharp.Compiler/features/cg/services/CG.Call.cs delete mode 100644 ZSharp.Compiler/features/cg/services/CG.ImplicitCast.cs delete mode 100644 ZSharp.Compiler/features/cg/services/CG.Index.cs delete mode 100644 ZSharp.Compiler/features/cg/services/CG.MemberAccess.cs delete mode 100644 ZSharp.Compiler/features/cg/services/CG.Runtime.cs delete mode 100644 ZSharp.Compiler/features/cg/services/CG.TypeCast.cs delete mode 100644 ZSharp.Compiler/features/cg/services/CG.TypeMatch.cs delete mode 100644 ZSharp.Compiler/features/cg/services/CG.ValueAccess.cs delete mode 100644 ZSharp.Compiler/features/ir/IR.cs delete mode 100644 ZSharp.Compiler/features/ir/capabilities/code/ICTCompileIRCode.cs delete mode 100644 ZSharp.Compiler/features/ir/services/IR.Code.cs delete mode 100644 ZSharp.Compiler/features/ir/services/IR.Definition.cs delete mode 100644 ZSharp.Compiler/features/ir/services/IR.Reference.cs delete mode 100644 ZSharp.Compiler/features/ir/services/IR.Type.cs delete mode 100644 ZSharp.Compiler/features/oop/extensibility/IClass.cs delete mode 100644 ZSharp.Compiler/features/oop/extensibility/IRTBoundMember.cs delete mode 100644 ZSharp.Compiler/ir generator/IRCodeGenerator.cs delete mode 100644 ZSharp.Compiler/ir generator/protocols/ICompileIRCode.cs delete mode 100644 ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs delete mode 100644 ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs delete mode 100644 ZSharp.Compiler/ir generator/protocols/ICompileIRType.cs create mode 100644 ZSharp.Interpreter/GlobalUsings.cs create mode 100644 ZSharp.Interpreter/interpreter/Interpreter.Logging.cs delete mode 100644 ZSharp.Interpreter/source-compiler/GlobalUsings.cs delete mode 100644 ZSharp.Interpreter/source-compiler/NodeLogOrigin.cs rename {ZSharp.Compiler/compiler core/core/logging => ZSharp.Logging}/Log.cs (92%) rename {ZSharp.Compiler/compiler core/core/logging => ZSharp.Logging}/LogLevel.cs (74%) rename {ZSharp.Compiler/compiler core/core/logging => ZSharp.Logging}/LogOrigin.cs (64%) rename {ZSharp.Compiler/compiler core/core/logging => ZSharp.Logging}/Logger.cs (52%) create mode 100644 ZSharp.Logging/ZSharp.Logging.csproj create mode 100644 ZSharp.Runtime/runtime/Runtime.Expose.cs rename ZSharp.Runtime/runtime/{Runtime.IR.cs => Runtime.Singleton.cs} (56%) create mode 100644 ZSharp.Runtime/runtime/Runtime.TypeSystem.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.Array.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.Boolean.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.Char.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.Float.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.Object.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.Pointer.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.Reference.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.SInt.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.String.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.UInt.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.Void.cs create mode 100644 ZSharp.Runtime/type system/TypeSystem.cs create mode 100644 ZSharp.SourceCompiler.Common/CompileExpression.cs create mode 100644 ZSharp.SourceCompiler.Common/GlobalUsings.cs create mode 100644 ZSharp.SourceCompiler.Common/TaskManager.cs create mode 100644 ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj create mode 100644 ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs create mode 100644 ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.T.cs create mode 100644 ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.cs create mode 100644 ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Call.cs create mode 100644 ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Identifier.cs create mode 100644 ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs create mode 100644 ZSharp.SourceCompiler.Common/extensions/LoggerExtensions.cs create mode 100644 ZSharp.SourceCompiler.Common/importers/CoreLibraryImporter.cs create mode 100644 ZSharp.SourceCompiler.Common/importers/StandardLibraryImporter.cs create mode 100644 ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.Boolean.cs create mode 100644 ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs create mode 100644 ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.cs create mode 100644 ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.T.cs create mode 100644 ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.cs create mode 100644 ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.Content.cs create mode 100644 ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs create mode 100644 ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.cs create mode 100644 ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs create mode 100644 ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.cs create mode 100644 ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs create mode 100644 ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.cs create mode 100644 ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs create mode 100644 ZSharp.SourceCompiler.Core/NodeLogOrigin.cs create mode 100644 ZSharp.SourceCompiler.Core/ZSharp.SourceCompiler.Core.csproj create mode 100644 ZSharp.SourceCompiler.Core/context/Context.ImportSystem.cs create mode 100644 ZSharp.SourceCompiler.Core/context/Context.Operators.cs create mode 100644 ZSharp.SourceCompiler.Core/context/Context.T.cs create mode 100644 ZSharp.SourceCompiler.Core/context/Context.cs create mode 100644 ZSharp.SourceCompiler.Core/custom importer/string importer/IStringImporter.cs create mode 100644 ZSharp.SourceCompiler.Core/custom importer/string importer/StringImporter.cs create mode 100644 ZSharp.SourceCompiler.Core/import system/ImportSystem.cs create mode 100644 ZSharp.SourceCompiler.Core/operator table/OperatorTable.cs create mode 100644 ZSharp.SourceCompiler.Module/GlobalUsings.cs create mode 100644 ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj create mode 100644 ZSharp.SourceCompiler.Module/capabilities/IModuleMember.cs create mode 100644 ZSharp.SourceCompiler.Module/capabilities/functional/IParameter.cs create mode 100644 ZSharp.SourceCompiler.Module/capabilities/functional/ISignature.cs create mode 100644 ZSharp.SourceCompiler.Module/contexts/modular/FunctionContext.cs create mode 100644 ZSharp.SourceCompiler.Module/contexts/modular/ModuleContext.cs create mode 100644 ZSharp.SourceCompiler.Module/function body compiler/FunctionBodyCompiler.T.cs create mode 100644 ZSharp.SourceCompiler.Module/function body compiler/FunctionBodyCompiler.cs create mode 100644 ZSharp.SourceCompiler.Module/function body compiler/compile/FunctionBodyCompiler.Compile.cs create mode 100644 ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.Function.cs create mode 100644 ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.cs create mode 100644 ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Block.cs create mode 100644 ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Definition.cs create mode 100644 ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Expression.cs create mode 100644 ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs create mode 100644 ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs create mode 100644 ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.T.cs create mode 100644 ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.cs create mode 100644 ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.Log.cs create mode 100644 ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.T.cs create mode 100644 ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.Tasks.cs create mode 100644 ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.cs create mode 100644 ZSharp.SourceCompiler.Module/module compiler/compile/ModuleCompiler.Compile.cs create mode 100644 ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Call.cs create mode 100644 ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Expression.cs create mode 100644 ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Function.cs create mode 100644 ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Definition.cs create mode 100644 ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/function/Function.Build.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/function/Function.ModuleMember.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/function/Function.Name.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/function/Function.T.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/function/Function.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/global/Global.Build.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/global/Global.ModuleMember.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/global/Global.Name.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/global/Global.T.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/global/Global.Type.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/global/Global.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/module/Module.Build.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/module/Module.Name.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/module/Module.T.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/module/Module.cs create mode 100644 ZSharp.SourceCompiler.Module/old/GlobalUsings.cs rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/HelperFunctions.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/capabilities/IMultipassCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/class body/ClassBodyCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/class body/ConstructorCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/class body/MethodCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/document/compiler/DocumentCompiler.Compile.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/document/compiler/DocumentCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/document/objects/Document.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/module/ClassCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/module/FunctionCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/module/ModuleCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/runtime code/objects/Case.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/runtime code/objects/ForLoop.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/runtime code/objects/If.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/builtin-compilers/runtime code/objects/WhileLoop.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/compiler/ZSSourceCompiler.Compilers.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/compiler/ZSSourceCompiler.ImportSystem.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/compiler/ZSSourceCompiler.Initialize.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/compiler/ZSSourceCompiler.Logging.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/compiler/ZSSourceCompiler.OOP.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/compiler/ZSSourceCompiler.Operators.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/compiler/ZSSourceCompiler.ResultTools.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/compiler/ZSSourceCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/context/Context.Compilers.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/context/Context.Nodes.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/context/Context.Scopes.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/context/Context.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/contexts/capabilities/IMemoryAllocator.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/contexts/capabilities/IObjectContext.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/contexts/capabilities/scope/ILookupContext.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/contexts/capabilities/scope/IScopeContext.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/contexts/concrete/ClassContext.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/contexts/concrete/ExpressionContext.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/contexts/concrete/FunctionContext.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/contexts/concrete/ObjectContext.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/contexts/concrete/ScopeContext.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/contexts/strategies/UntilContextTypeStrategy.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/core-compilers/DefaultContextCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/core-compilers/expression/ExpressionCompiler.Literals.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/core-compilers/expression/ExpressionCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/core-compilers/statement/StatementCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/extensibility/CompilerBase.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/extensibility/ContextCompiler.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/extensibility/error/Error.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/extensibility/error/errors/CombinedCompilationError.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/extensibility/error/errors/CompilationError.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/extensibility/oop/ClassSpecification.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/extensibility/overrides/IOverrideCompileExpression.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/extensibility/overrides/IOverrideCompileNode.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/extensibility/overrides/IOverrideCompileStatement.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/import system/ImportSystem.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/import system/importers/StandardLibraryImporter.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/import system/importers/StringImporter.cs (100%) rename {ZSharp.Interpreter/source-compiler => ZSharp.SourceCompiler.Module/old}/import system/importers/ZSImporter.cs (100%) create mode 100644 ZSharp.SourceCompiler.Module/utils/ObjectBuildState.cs create mode 100644 ZSharp.SourceCompiler.Project/compiler/ProjectCompiler.T.cs create mode 100644 ZSharp.SourceCompiler.Project/compiler/ProjectCompiler.cs create mode 100644 ZSharp.SourceCompiler.Project/project/ProjectResult.cs create mode 100644 ZSharp.SourceCompiler.Script/GlobalUsings.cs create mode 100644 ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj create mode 100644 ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Context.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Options.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.T.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/ScriptCompiler.Compile.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Call.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.If.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Module.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Block.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Definition.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.If.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs create mode 100644 ZSharp.SourceCompiler.Script/contexts/ScopeContext.cs create mode 100644 ZSharp.SourceCompiler.Script/options/EvaluationTarget.cs create mode 100644 ZSharp.SourceCompiler.Script/options/ScriptingOptions.cs diff --git a/ZSharp.Compiler/core/Result.cs b/CommonZ/Result.cs similarity index 90% rename from ZSharp.Compiler/core/Result.cs rename to CommonZ/Result.cs index 2ee2b10c..5abb5651 100644 --- a/ZSharp.Compiler/core/Result.cs +++ b/CommonZ/Result.cs @@ -1,13 +1,13 @@ using System.Diagnostics.CodeAnalysis; -namespace ZSharp.Compiler +namespace CommonZ { - public sealed class Result + public class Result where TResult : class? where TError : class { - private readonly TResult? result; - private readonly TError? error; + protected readonly TResult? result; + protected readonly TError? error; [MemberNotNullWhen(true, nameof(result))] public bool IsOk => result is not null; @@ -15,7 +15,7 @@ public sealed class Result [MemberNotNullWhen(true, nameof(error))] public bool IsError => error is not null; - private Result(TResult? result, TError? error) + protected Result(TResult? result, TError? error) { this.result = result; this.error = error; diff --git a/Examples/test.zs b/Examples/test.zs new file mode 100644 index 00000000..b7f072ff --- /dev/null +++ b/Examples/test.zs @@ -0,0 +1,22 @@ +import { Directory } from "std:fs"; +import { print } from "std:io"; + +print("[CT] Hello, World!"); + +fun nodeTypeNotImplemented() {} + +module A { + print("[CT] Inside module A"); + + fun main() { + print("[RT] Hello, World!"); + } +} + +if (false) { + print("[CT] Condition is true"); +} else { + print("[CT] Condition is false"); +} + +A.main(); diff --git a/Testing/Program.cs b/Testing/Program.cs index a445e998..b28ee61a 100644 --- a/Testing/Program.cs +++ b/Testing/Program.cs @@ -1,12 +1,45 @@ -using ZLoad.Test; -using ZSharp.Compiler.ILLoader; +using ZSharp.Compiler.ILLoader; using Objects = ZSharp.Compiler.ILLoader.Objects; -var coc = new ZSharp.Compiler.Compiler(); +var rtm = ZSharp.IR.RuntimeModule.Standard; +var coc = new ZSharp.Compiler.Compiler(rtm); +var rt = new ZSharp.Runtime.Runtime(new() +{ + Array = rtm.TypeSystem.Array, + Boolean = rtm.TypeSystem.Boolean, + Char = null!, + Float16 = null!, + Float32 = rtm.TypeSystem.Float32, + Float64 = null!, + Float128 = null!, + Object = rtm.TypeSystem.Object, + Pointer = rtm.TypeSystem.Pointer, + Reference = rtm.TypeSystem.Reference, + SInt8 = null!, + SInt16 = null!, + SInt32 = rtm.TypeSystem.Int32, + SInt64 = null!, + SIntNative = null!, + String = rtm.TypeSystem.String, + UInt8 = null!, + UInt16 = null!, + UInt32 = null!, + UInt64 = null!, + UIntNative = null!, + Void = rtm.TypeSystem.Void +}); -var ilLoader = new ILLoader(coc); -var module = new Objects.Module(typeof(TestClass).Module, ilLoader); +var ilLoader = new ILLoader(coc.IR, rt); + +coc.TS.SInt32 = ilLoader.TypeSystem.SInt32; + +var code = rt.Expose("Hello, Exposed String!"); +var exposed = rt.Evaluate(code, rtm.TypeSystem.Object); +System.Console.WriteLine(exposed); + +var typedCode = ilLoader.ExposeAsIR(12); +var typedExposed = rt.Evaluate(typedCode, rtm.TypeSystem.Int32); +System.Console.WriteLine(typedExposed); -var zLoadTest = ilLoader.Namespace("ZLoad.Test"); System.Console.WriteLine(string.Empty); diff --git a/ZSC.Script/CLIArgumentLogOrigin.cs b/ZSC.Script/CLIArgumentLogOrigin.cs new file mode 100644 index 00000000..3848ed94 --- /dev/null +++ b/ZSC.Script/CLIArgumentLogOrigin.cs @@ -0,0 +1,10 @@ +using ZSharp.Logging; + +namespace ZSC.Script +{ + internal class CLIArgumentLogOrigin(string argument) : LogOrigin + { + public override string ToString() + => $"CLI Argument '{argument}'"; + } +} diff --git a/ZSC.Script/Program.cs b/ZSC.Script/Program.cs new file mode 100644 index 00000000..192fec62 --- /dev/null +++ b/ZSC.Script/Program.cs @@ -0,0 +1,219 @@ +using ZSC.Script; +using ZSharp.Interpreter; +using ZSharp.Parser; +using ZSharp.SourceCompiler; +using ZSharp.SourceCompiler.Script; +using ZSharp.Text; +using ZSharp.Tokenizer; + +var interpreter = new Interpreter(); + +var filePath = args.Length == 0 ? null : args[0]; + +if (filePath is null) +{ + interpreter.Log.Error("Missing input file path argument.", new CLIArgumentLogOrigin("")); +} +else +{ + #region Parsing + + ZSharp.AST.Document documentNode; + using (StreamReader stream = File.OpenText(filePath)) + { + var zsharpParser = new ZSharpParser(); + var parser = new Parser(Tokenizer.Tokenize(new(stream))); + + var expressionParser = zsharpParser.Expression; + var statementParser = zsharpParser.Statement; + + expressionParser.Terminal( + TokenType.String, + token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.String) + ); + expressionParser.Terminal( + TokenType.Number, + token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Number) + ); + expressionParser.Terminal( + TokenType.Decimal, + token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Decimal) + ); + expressionParser.Terminal( + TokenType.Identifier, + token => token.Value switch + { + "null" => ZSharp.AST.LiteralExpression.Null(), + "true" => ZSharp.AST.LiteralExpression.True(), + "false" => ZSharp.AST.LiteralExpression.False(), + _ => new ZSharp.AST.IdentifierExpression(token.Value), + } + ); + expressionParser.Nud( + TokenType.LParen, + parser => + { + parser.Eat(TokenType.LParen); + var expression = parser.Parse(); + parser.Eat(TokenType.RParen); + + return expression; + }, + 10000 + ); + expressionParser.Nud( + LangParser.Keywords.Let, + LangParser.ParseLetExpression + ); + expressionParser.Nud( + LangParser.Keywords.Class, + zsharpParser.Class.Parse + ); + + expressionParser.InfixR("=", 10); + expressionParser.InfixL("<", 20); + expressionParser.InfixL("+", 50); + expressionParser.InfixL("-", 50); + expressionParser.InfixL("*", 70); + expressionParser.InfixL("/", 70); + expressionParser.InfixL("**", 80); + + expressionParser.InfixL("==", 30); + expressionParser.InfixL("!=", 30); + + expressionParser.InfixL(LangParser.Keywords.Or, 15); + + expressionParser.Led(TokenType.LParen, LangParser.ParseCallExpression, 100); + expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); + expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); + expressionParser.Led(".", LangParser.ParseMemberAccess, 150); + expressionParser.Led(LangParser.Keywords.As, LangParser.ParseCastExpression, 20); + expressionParser.Led(LangParser.Keywords.Is, LangParser.ParseIsOfExpression, 20); + + expressionParser.Separator(TokenType.Comma); + expressionParser.Separator(TokenType.RParen); + expressionParser.Separator(TokenType.RBracket); + expressionParser.Separator(TokenType.Semicolon); + + expressionParser.Separator(LangParser.Keywords.In); // until it's an operator + + expressionParser.AddKeywordParser( + LangParser.Keywords.While, + LangParser.ParseWhileExpression + ); + + statementParser.AddKeywordParser( + LangParser.Keywords.While, + Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) + ); + + statementParser.AddKeywordParser( + LangParser.Keywords.If, + LangParser.ParseIfStatement + ); + + statementParser.AddKeywordParser( + LangParser.Keywords.For, + LangParser.ParseForStatement + ); + + statementParser.AddKeywordParser( + LangParser.Keywords.Case, + LangParser.ParseCaseStatement + ); + + zsharpParser.Document.AddKeywordParser( + LangParser.Keywords.If, + LangParser.ParseIfStatement + ); + + //zsharpParser.Function.AddKeywordParser( + // LangParser.Keywords.While, + // Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) + //); + + zsharpParser.RegisterParsers(parser); + documentNode = zsharpParser.Parse(parser); + + Console.WriteLine($"Finished parsing document with {documentNode.Statements.Count} statements!"); + } + + #endregion + + #region Setup Interpreter + + new ZSharp.Compiler.Dispatchers.CT.Dispatcher(interpreter.Compiler).Apply(); + new ZSharp.Compiler.Dispatchers.RT.Dispatcher(interpreter.Compiler).Apply(); + new ZSharp.Compiler.Dispatchers.Proxy.Dispatcher(interpreter.Compiler).Apply(); + + var scriptCompiler = new ScriptCompiler(interpreter, documentNode); + + interpreter.ILLoader.OnLoadOperator = (@operator, method) => + { + interpreter.Log.Warning( + $"Skip loading operator {@operator} ({method.GetParameters().Length} parameters)" + + $"because overloading is not implemented yet", + ZSCScriptLogOrigin.Instance + ); + //scriptCompiler.Context.Operators.Op(@operator.Operator, interpreter.ILLoader.LoadMethod(method)); + }; + + #region Import System + + var stringImporter = new StringImporter(); + + scriptCompiler.Context.ImportSystem.ImportFunction = interpreter.ILLoader.Expose( + (Delegate)( + (string source) => stringImporter.Import(source).Unwrap() as object + ) + ); + + #endregion + + #region Importers + + #region Core Library + + var coreImporter = new CoreLibraryImporter(); + stringImporter.RegisterImporter("core", coreImporter); + + #endregion + + #region Standard Library + + var stdImporter = new StandardLibraryImporter(); + stringImporter.RegisterImporter("std", stdImporter); + + stdImporter.Add( + "io", + interpreter.ILLoader.LoadModule(typeof(Standard.IO.ModuleScope).Module) + ); + stdImporter.Add( + "fs", + interpreter.ILLoader.LoadModule(typeof(Standard.FileSystem.ModuleScope).Module) + ); + + #endregion + + #endregion + + #endregion + + #region Compilation + + scriptCompiler.Compile(); + + #endregion +} + +Console.WriteLine(); + +foreach (var log in interpreter.Log.Logs) +{ + Console.WriteLine(log.ToString()); +} + +Console.WriteLine(); +Console.WriteLine("Press any key to exit..."); +if (Console.ReadKey().Key == ConsoleKey.Z) + Console.WriteLine("\bYou chose wisely :)"); diff --git a/ZSC.Script/ZSC.Script.csproj b/ZSC.Script/ZSC.Script.csproj new file mode 100644 index 00000000..700529a3 --- /dev/null +++ b/ZSC.Script/ZSC.Script.csproj @@ -0,0 +1,44 @@ + + + + Exe + net8.0 + enable + enable + + + + embedded + + + + none + + + + + + + + + + + + + + + + + PreserveNewest + + + + + + + + + + + + diff --git a/ZSC.Script/ZSCScriptLogOrigin.cs b/ZSC.Script/ZSCScriptLogOrigin.cs new file mode 100644 index 00000000..b8dd0cda --- /dev/null +++ b/ZSC.Script/ZSCScriptLogOrigin.cs @@ -0,0 +1,12 @@ +using ZSharp.Logging; + +namespace ZSC.Script +{ + internal sealed class ZSCScriptLogOrigin() : LogOrigin + { + public static ZSCScriptLogOrigin Instance = new(); + + public override string ToString() + => "[Z# Script Compiler]"; + } +} diff --git a/ZSharp v1.sln b/ZSharp v1.sln index 8470cf72..2e91894b 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -62,6 +62,36 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.ILLoader.At EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSC.Project", "ZSC.Project\ZSC.Project.csproj", "{A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.SourceCompiler.Core", "ZSharp.SourceCompiler.Core\ZSharp.SourceCompiler.Core.csproj", "{2DF6ABEC-5B49-435D-A583-4C97C61D1558}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.SourceCompiler.Module", "ZSharp.SourceCompiler.Module\ZSharp.SourceCompiler.Module.csproj", "{5C914B09-68BF-4BCD-BF9E-2F682F03590D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.SourceCompiler.Script", "ZSharp.SourceCompiler.Script\ZSharp.SourceCompiler.Script.csproj", "{51F7D757-1DBC-452B-84FF-45307ADCDF5C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSC.Script", "ZSC.Script\ZSC.Script.csproj", "{4DA26E46-B765-4A8C-BAE1-5E99D6138DAF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Core", "ZSharp.Compiler.Core\ZSharp.Compiler.Core.csproj", "{F5CCD8B1-98F4-151B-C4FA-6E651CEC6193}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Logging", "ZSharp.Logging\ZSharp.Logging.csproj", "{EF96A6E6-190B-457B-AD9C-1057CD7EDBB2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CO.RT", "ZSharp.Compiler.CO.RT\ZSharp.Compiler.CO.RT.csproj", "{731BE61E-6C43-4628-B680-10467A73B4DC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CO.CT", "ZSharp.Compiler.CO.CT\ZSharp.Compiler.CO.CT.csproj", "{30FB37EA-5FA6-A6BB-1934-49C19899D2D6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CO", "ZSharp.Compiler.CO\ZSharp.Compiler.CO.csproj", "{B8B3E775-FB6C-50B9-BD2D-2C04C9615D0D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.TS", "ZSharp.Compiler.TS\ZSharp.Compiler.TS.csproj", "{1864BBD1-5A3D-4FB1-B799-B736C5016191}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CO.Proxy", "ZSharp.Compiler.CO.Proxy\ZSharp.Compiler.CO.Proxy.csproj", "{51301FA2-449E-4666-B9DE-0EE9F4CD00EE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.TS.Static", "ZSharp.Compiler.TS.Static\ZSharp.Compiler.TS.Static.csproj", "{C6FC0FBB-6E0B-437B-82B7-294D830109EA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Context", "ZSharp.Compiler.Context\ZSharp.Compiler.Context.csproj", "{B2DD7DE5-8D23-4BA8-9AC6-808BF8FFF3CA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.SourceCompiler.Common", "ZSharp.SourceCompiler.Common\ZSharp.SourceCompiler.Common.csproj", "{A3DB8E19-9047-4FF6-87E7-69BDC09647D1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.StandardLibrary.IO", "ZSharp.CT.StandardLibrary.IO\ZSharp.CT.StandardLibrary.IO.csproj", "{8BD20BCF-DC47-4B94-B40E-1A6B7137265C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -180,6 +210,66 @@ Global {A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}.Debug|Any CPU.Build.0 = Debug|Any CPU {A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}.Release|Any CPU.ActiveCfg = Release|Any CPU {A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}.Release|Any CPU.Build.0 = Release|Any CPU + {2DF6ABEC-5B49-435D-A583-4C97C61D1558}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2DF6ABEC-5B49-435D-A583-4C97C61D1558}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2DF6ABEC-5B49-435D-A583-4C97C61D1558}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2DF6ABEC-5B49-435D-A583-4C97C61D1558}.Release|Any CPU.Build.0 = Release|Any CPU + {5C914B09-68BF-4BCD-BF9E-2F682F03590D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5C914B09-68BF-4BCD-BF9E-2F682F03590D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5C914B09-68BF-4BCD-BF9E-2F682F03590D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5C914B09-68BF-4BCD-BF9E-2F682F03590D}.Release|Any CPU.Build.0 = Release|Any CPU + {51F7D757-1DBC-452B-84FF-45307ADCDF5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {51F7D757-1DBC-452B-84FF-45307ADCDF5C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {51F7D757-1DBC-452B-84FF-45307ADCDF5C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {51F7D757-1DBC-452B-84FF-45307ADCDF5C}.Release|Any CPU.Build.0 = Release|Any CPU + {4DA26E46-B765-4A8C-BAE1-5E99D6138DAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4DA26E46-B765-4A8C-BAE1-5E99D6138DAF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4DA26E46-B765-4A8C-BAE1-5E99D6138DAF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4DA26E46-B765-4A8C-BAE1-5E99D6138DAF}.Release|Any CPU.Build.0 = Release|Any CPU + {F5CCD8B1-98F4-151B-C4FA-6E651CEC6193}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F5CCD8B1-98F4-151B-C4FA-6E651CEC6193}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F5CCD8B1-98F4-151B-C4FA-6E651CEC6193}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F5CCD8B1-98F4-151B-C4FA-6E651CEC6193}.Release|Any CPU.Build.0 = Release|Any CPU + {EF96A6E6-190B-457B-AD9C-1057CD7EDBB2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EF96A6E6-190B-457B-AD9C-1057CD7EDBB2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EF96A6E6-190B-457B-AD9C-1057CD7EDBB2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EF96A6E6-190B-457B-AD9C-1057CD7EDBB2}.Release|Any CPU.Build.0 = Release|Any CPU + {731BE61E-6C43-4628-B680-10467A73B4DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {731BE61E-6C43-4628-B680-10467A73B4DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {731BE61E-6C43-4628-B680-10467A73B4DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {731BE61E-6C43-4628-B680-10467A73B4DC}.Release|Any CPU.Build.0 = Release|Any CPU + {30FB37EA-5FA6-A6BB-1934-49C19899D2D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {30FB37EA-5FA6-A6BB-1934-49C19899D2D6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {30FB37EA-5FA6-A6BB-1934-49C19899D2D6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {30FB37EA-5FA6-A6BB-1934-49C19899D2D6}.Release|Any CPU.Build.0 = Release|Any CPU + {B8B3E775-FB6C-50B9-BD2D-2C04C9615D0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B8B3E775-FB6C-50B9-BD2D-2C04C9615D0D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B8B3E775-FB6C-50B9-BD2D-2C04C9615D0D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B8B3E775-FB6C-50B9-BD2D-2C04C9615D0D}.Release|Any CPU.Build.0 = Release|Any CPU + {1864BBD1-5A3D-4FB1-B799-B736C5016191}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1864BBD1-5A3D-4FB1-B799-B736C5016191}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1864BBD1-5A3D-4FB1-B799-B736C5016191}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1864BBD1-5A3D-4FB1-B799-B736C5016191}.Release|Any CPU.Build.0 = Release|Any CPU + {51301FA2-449E-4666-B9DE-0EE9F4CD00EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {51301FA2-449E-4666-B9DE-0EE9F4CD00EE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {51301FA2-449E-4666-B9DE-0EE9F4CD00EE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {51301FA2-449E-4666-B9DE-0EE9F4CD00EE}.Release|Any CPU.Build.0 = Release|Any CPU + {C6FC0FBB-6E0B-437B-82B7-294D830109EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C6FC0FBB-6E0B-437B-82B7-294D830109EA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C6FC0FBB-6E0B-437B-82B7-294D830109EA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C6FC0FBB-6E0B-437B-82B7-294D830109EA}.Release|Any CPU.Build.0 = Release|Any CPU + {B2DD7DE5-8D23-4BA8-9AC6-808BF8FFF3CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B2DD7DE5-8D23-4BA8-9AC6-808BF8FFF3CA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B2DD7DE5-8D23-4BA8-9AC6-808BF8FFF3CA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B2DD7DE5-8D23-4BA8-9AC6-808BF8FFF3CA}.Release|Any CPU.Build.0 = Release|Any CPU + {A3DB8E19-9047-4FF6-87E7-69BDC09647D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A3DB8E19-9047-4FF6-87E7-69BDC09647D1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A3DB8E19-9047-4FF6-87E7-69BDC09647D1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A3DB8E19-9047-4FF6-87E7-69BDC09647D1}.Release|Any CPU.Build.0 = Release|Any CPU + {8BD20BCF-DC47-4B94-B40E-1A6B7137265C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8BD20BCF-DC47-4B94-B40E-1A6B7137265C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8BD20BCF-DC47-4B94-B40E-1A6B7137265C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8BD20BCF-DC47-4B94-B40E-1A6B7137265C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZSharp.AST/nodes/stmt/expr/DefinitionStatement.cs b/ZSharp.AST/nodes/stmt/expr/DefinitionStatement.cs new file mode 100644 index 00000000..7bee9277 --- /dev/null +++ b/ZSharp.AST/nodes/stmt/expr/DefinitionStatement.cs @@ -0,0 +1,10 @@ +namespace ZSharp.AST +{ + public sealed class DefinitionStatement : Statement + { + public required Expression Definition { get; init; } + + public override string ToString() + => $"{Definition}"; + } +} diff --git a/ZSharp.AST/nodes/stmt/import/ImportTokens.cs b/ZSharp.AST/nodes/stmt/import/ImportTokens.cs index 6f9caeeb..9577a0e2 100644 --- a/ZSharp.AST/nodes/stmt/import/ImportTokens.cs +++ b/ZSharp.AST/nodes/stmt/import/ImportTokens.cs @@ -7,5 +7,8 @@ public sealed class ImportTokens : TokenInfo public required Token ImportKeyword { get; init; } public required Token Semicolon { get; init; } + + public override string ToString() + => $"{ImportKeyword.Span}"; } } diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Operators.cs b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Operators.cs index ddbdf678..bc6b5139 100644 --- a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Operators.cs +++ b/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Operators.cs @@ -3,9 +3,9 @@ partial class Directory { public static Item operator /(Directory directory, RawPath path) - => Operators.Join(directory, path); + => ModuleScope.Join(directory, path); public static Item operator/(Directory directory, RelativePath path) - => Operators.Join(directory, path.raw); + => ModuleScope.Join(directory, path.raw); } } diff --git a/ZSharp.CT.StandardLibrary.FileSystem/module scope/Operators.cs b/ZSharp.CT.StandardLibrary.FileSystem/module scope/ModuleScope.Operators.cs similarity index 93% rename from ZSharp.CT.StandardLibrary.FileSystem/module scope/Operators.cs rename to ZSharp.CT.StandardLibrary.FileSystem/module scope/ModuleScope.Operators.cs index 66137955..5aeac8c1 100644 --- a/ZSharp.CT.StandardLibrary.FileSystem/module scope/Operators.cs +++ b/ZSharp.CT.StandardLibrary.FileSystem/module scope/ModuleScope.Operators.cs @@ -1,7 +1,6 @@ namespace Standard.FileSystem { - [ModuleScope] - public static class Operators + partial class ModuleScope { [Operator("/", Kind = OperatorKind.Infix)] public static Path Join(Path path, RawPath sub) diff --git a/ZSharp.CT.StandardLibrary.FileSystem/module scope/ModuleScope.cs b/ZSharp.CT.StandardLibrary.FileSystem/module scope/ModuleScope.cs new file mode 100644 index 00000000..7bc2ab71 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.FileSystem/module scope/ModuleScope.cs @@ -0,0 +1,7 @@ +namespace Standard.FileSystem +{ + [ModuleScope] + public static partial class ModuleScope + { + } +} diff --git a/ZSharp.CT.StandardLibrary.IO/GlobalUsings.cs b/ZSharp.CT.StandardLibrary.IO/GlobalUsings.cs new file mode 100644 index 00000000..daef43e7 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.IO/GlobalUsings.cs @@ -0,0 +1 @@ +global using ZSharp.Compiler.ILLoader; diff --git a/ZSharp.CT.StandardLibrary.IO/ModuleAttributes.cs b/ZSharp.CT.StandardLibrary.IO/ModuleAttributes.cs new file mode 100644 index 00000000..92ac4d01 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.IO/ModuleAttributes.cs @@ -0,0 +1 @@ +[module: MapNamespace(OldName = "Standard.IO", NewName = "")] diff --git a/ZSharp.CT.StandardLibrary.IO/ZSharp.CT.StandardLibrary.IO.csproj b/ZSharp.CT.StandardLibrary.IO/ZSharp.CT.StandardLibrary.IO.csproj new file mode 100644 index 00000000..2828e4bc --- /dev/null +++ b/ZSharp.CT.StandardLibrary.IO/ZSharp.CT.StandardLibrary.IO.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Functions.cs b/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Functions.cs new file mode 100644 index 00000000..34556389 --- /dev/null +++ b/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Functions.cs @@ -0,0 +1,9 @@ +namespace Standard.IO +{ + partial class ModuleScope + { + [Alias("print")] + public static void Print(string message) + => System.Console.WriteLine(message); + } +} diff --git a/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Operators.cs b/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Operators.cs new file mode 100644 index 00000000..0bc0900f --- /dev/null +++ b/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Operators.cs @@ -0,0 +1,7 @@ +namespace Standard.IO +{ + partial class ModuleScope + { + + } +} diff --git a/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.cs b/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.cs new file mode 100644 index 00000000..9e73534e --- /dev/null +++ b/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.cs @@ -0,0 +1,7 @@ +namespace Standard.IO +{ + [ModuleScope] + public static partial class ModuleScope + { + } +} diff --git a/ZSharp.Compiler.CO.CT/GlobalUsings.cs b/ZSharp.Compiler.CO.CT/GlobalUsings.cs new file mode 100644 index 00000000..c1bcb323 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/GlobalUsings.cs @@ -0,0 +1,4 @@ +global using MemberName = string; +global using MemberIndex = int; + +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.CO.CT/ZSharp.Compiler.CO.CT.csproj b/ZSharp.Compiler.CO.CT/ZSharp.Compiler.CO.CT.csproj new file mode 100644 index 00000000..615e6b8a --- /dev/null +++ b/ZSharp.Compiler.CO.CT/ZSharp.Compiler.CO.CT.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + + + + + + + + + diff --git a/ZSharp.Compiler.CO.CT/dispatcher/Dispatcher.cs b/ZSharp.Compiler.CO.CT/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..e6ee9c89 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/dispatcher/Dispatcher.cs @@ -0,0 +1,28 @@ +namespace ZSharp.Compiler.Dispatchers.CT +{ + public partial class Dispatcher(Compiler compiler) + { + private readonly Compiler compiler = compiler; + private CG @base; + + public void Apply() + { + @base = compiler.CG; + + ref var cg = ref compiler.CG; + + cg.Call = Call; + cg.Cast = Cast; + cg.Get = Get; + cg.GetIndex = Index; + cg.GetMemberByIndex = Member; + cg.GetMemberByName = Member; + cg.ImplicitCast = ImplicitCast; + cg.Match = Match; + cg.Set = Set; + cg.SetIndex = Index; + cg.SetMemberByIndex = Member; + cg.SetMemberByName = Member; + } + } +} diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Call.cs new file mode 100644 index 00000000..4f852376 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Call.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.Dispatchers.CT +{ + partial class Dispatcher + { + public Result Call(CompilerObject callee, Argument[] arguments) + { + var result = @base.Call(callee, arguments); + + if (result.IsError && callee.Is(out var callable)) + result = callable.Call(compiler, arguments); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Cast.cs new file mode 100644 index 00000000..1bb14d44 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Cast.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.Dispatchers.CT +{ + partial class Dispatcher + { + public Result Cast(CompilerObject @object, CompilerObject type) + { + var result = @base.Cast(@object, type); + + if (result.IsError && @object.Is(out var castTo)) + result = castTo.Cast(compiler, type); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ImplicitCast.cs new file mode 100644 index 00000000..bacc140c --- /dev/null +++ b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -0,0 +1,18 @@ +namespace ZSharp.Compiler.Dispatchers.CT +{ + partial class Dispatcher + { + public Result ImplicitCast(CompilerObject @object, CompilerObject type) + { + var result = @base.ImplicitCast(@object, type); + + if (result.IsError && @object.Is(out var castTo)) + result = castTo.ImplicitCast(compiler, type); + + if (result.IsError && type.Is(out var castFrom)) + result = castFrom.ImplicitCast(compiler, @object); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Index.cs new file mode 100644 index 00000000..aa1ed00f --- /dev/null +++ b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Index.cs @@ -0,0 +1,25 @@ +namespace ZSharp.Compiler.Dispatchers.CT +{ + partial class Dispatcher + { + public Result Index(CompilerObject @object, Argument[] arguments) + { + var result = @base.GetIndex(@object, arguments); + + if (result.IsError && @object.Is(out var index)) + result = index.Index(compiler, arguments); + + return result; + } + + public Result Index(CompilerObject @object, Argument[] arguments, CompilerObject value) + { + var result = @base.GetIndex(@object, arguments); + + if (result.IsError && @object.Is(out var index)) + result = index.Index(compiler, arguments, value); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Match.cs new file mode 100644 index 00000000..97026571 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Match.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.Dispatchers.CT +{ + partial class Dispatcher + { + public Result Match(CompilerObject @object, CompilerObject pattern) + { + var result = @base.Match(@object, pattern); + + if (result.IsError && @object.Is(out var match)) + result = match.Match(compiler, pattern); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.MemberAccess.cs new file mode 100644 index 00000000..83830cc9 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.MemberAccess.cs @@ -0,0 +1,45 @@ +namespace ZSharp.Compiler.Dispatchers.CT +{ + partial class Dispatcher + { + public Result Member(CompilerObject @object, MemberIndex index) + { + var result = @base.GetMemberByIndex(@object, index); + + if (result.IsError && @object.Is>(out var member)) + result = member.Member(compiler, index); + + return result; + } + + public Result Member(CompilerObject @object, MemberIndex index, CompilerObject value) + { + var result = @base.SetMemberByIndex(@object, index, value); + + if (result.IsError && @object.Is>(out var member)) + result = member.Member(compiler, index, value); + + return result; + } + + public Result Member(CompilerObject @object, MemberName name) + { + var result = @base.GetMemberByName(@object, name); + + if (result.IsError && @object.Is>(out var member)) + result = member.Member(compiler, name); + + return result; + } + + public Result Member(CompilerObject @object, MemberName name, CompilerObject value) + { + var result = @base.SetMemberByName(@object, name, value); + + if (result.IsError && @object.Is>(out var member)) + result = member.Member(compiler, name, value); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ValueAccess.cs new file mode 100644 index 00000000..81fe2877 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ValueAccess.cs @@ -0,0 +1,25 @@ +namespace ZSharp.Compiler.Dispatchers.CT +{ + partial class Dispatcher + { + public Result Get(CompilerObject @object) + { + var result = @base.Get(@object); + + if (result.IsError && @object.Is(out var get)) + result = get.Get(compiler); + + return result; + } + + public Result Set(CompilerObject @object, CompilerObject value) + { + var result = @base.Set(@object, value); + + if (result.IsError && @object.Is(out var set)) + result = set.Set(compiler, value); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.CT/protocols/callable/ICTCallable.cs b/ZSharp.Compiler.CO.CT/protocols/callable/ICTCallable.cs new file mode 100644 index 00000000..c75cb205 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/protocols/callable/ICTCallable.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTCallable + { + public Result Call(Compiler compiler, Argument[] arguments); + } +} diff --git a/ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastFrom.cs b/ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastFrom.cs new file mode 100644 index 00000000..f523cf9b --- /dev/null +++ b/ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastFrom.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTImplicitCastFrom + { + public Result ImplicitCast(Compiler compiler, CompilerObject value); + } +} diff --git a/ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastTo.cs b/ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastTo.cs new file mode 100644 index 00000000..837789de --- /dev/null +++ b/ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastTo.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTImplicitCastTo + { + public Result ImplicitCast(Compiler compiler, CompilerObject type); + } +} diff --git a/ZSharp.Compiler.CO.CT/protocols/index/ICTGetIndex.cs b/ZSharp.Compiler.CO.CT/protocols/index/ICTGetIndex.cs new file mode 100644 index 00000000..734b43bb --- /dev/null +++ b/ZSharp.Compiler.CO.CT/protocols/index/ICTGetIndex.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTGetIndex + { + public Result Index(Compiler compiler, Argument[] arguments); + } +} diff --git a/ZSharp.Compiler.CO.CT/protocols/index/ICTSetIndex.cs b/ZSharp.Compiler.CO.CT/protocols/index/ICTSetIndex.cs new file mode 100644 index 00000000..90413a34 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/protocols/index/ICTSetIndex.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTSetIndex + { + public Result Index(Compiler compiler, Argument[] arguments, CompilerObject value); + } +} diff --git a/ZSharp.Compiler/features/cg/capabilities/member access/ICTGetMember.cs b/ZSharp.Compiler.CO.CT/protocols/member access/ICTGetMember.cs similarity index 52% rename from ZSharp.Compiler/features/cg/capabilities/member access/ICTGetMember.cs rename to ZSharp.Compiler.CO.CT/protocols/member access/ICTGetMember.cs index 6407e250..bf4f5b53 100644 --- a/ZSharp.Compiler/features/cg/capabilities/member access/ICTGetMember.cs +++ b/ZSharp.Compiler.CO.CT/protocols/member access/ICTGetMember.cs @@ -2,6 +2,6 @@ { public interface ICTGetMember { - public CompilerObjectResult Member(Compiler compiler, M member); + public Result Member(Compiler compiler, M member); } } diff --git a/ZSharp.Compiler.CO.CT/protocols/member access/ICTSetMember.cs b/ZSharp.Compiler.CO.CT/protocols/member access/ICTSetMember.cs new file mode 100644 index 00000000..b76ad2a9 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/protocols/member access/ICTSetMember.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTSetMember + { + public Result Member(Compiler compiler, M member, CompilerObject value); + } +} diff --git a/ZSharp.Compiler.CO.CT/protocols/type casting/ICTCastTo.cs b/ZSharp.Compiler.CO.CT/protocols/type casting/ICTCastTo.cs new file mode 100644 index 00000000..abb08a74 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/protocols/type casting/ICTCastTo.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTCastTo + { + public Result Cast(Compiler compiler, CompilerObject targetType); + } +} diff --git a/ZSharp.Compiler.CO.CT/protocols/type matching/ICTTypeMatch.cs b/ZSharp.Compiler.CO.CT/protocols/type matching/ICTTypeMatch.cs new file mode 100644 index 00000000..29a124c8 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/protocols/type matching/ICTTypeMatch.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTTypeMatch + { + public Result Match(Compiler compiler, CompilerObject type); + } +} diff --git a/ZSharp.Compiler.CO.CT/protocols/value access/ICTGet.cs b/ZSharp.Compiler.CO.CT/protocols/value access/ICTGet.cs new file mode 100644 index 00000000..e25f7914 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/protocols/value access/ICTGet.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTGet + { + public Result Get(Compiler compiler); + } +} diff --git a/ZSharp.Compiler.CO.CT/protocols/value access/ICTSet.cs b/ZSharp.Compiler.CO.CT/protocols/value access/ICTSet.cs new file mode 100644 index 00000000..5f571e87 --- /dev/null +++ b/ZSharp.Compiler.CO.CT/protocols/value access/ICTSet.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTSet + { + public Result Set(Compiler compiler, CompilerObject value); + } +} diff --git a/ZSharp.Compiler.CO.Proxy/GlobalUsings.cs b/ZSharp.Compiler.CO.Proxy/GlobalUsings.cs new file mode 100644 index 00000000..c1bcb323 --- /dev/null +++ b/ZSharp.Compiler.CO.Proxy/GlobalUsings.cs @@ -0,0 +1,4 @@ +global using MemberName = string; +global using MemberIndex = int; + +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.CO.Proxy/ZSharp.Compiler.CO.Proxy.csproj b/ZSharp.Compiler.CO.Proxy/ZSharp.Compiler.CO.Proxy.csproj new file mode 100644 index 00000000..615e6b8a --- /dev/null +++ b/ZSharp.Compiler.CO.Proxy/ZSharp.Compiler.CO.Proxy.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + + + + + + + + + diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/Dispatcher.cs b/ZSharp.Compiler.CO.Proxy/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..dab3f285 --- /dev/null +++ b/ZSharp.Compiler.CO.Proxy/dispatcher/Dispatcher.cs @@ -0,0 +1,30 @@ +namespace ZSharp.Compiler.Dispatchers.Proxy +{ + public partial class Dispatcher(Compiler compiler) + { + private readonly Compiler compiler = compiler; + private CG @base; + + private ref CG CG => ref compiler.CG; + + public void Apply() + { + @base = compiler.CG; + + ref var cg = ref CG; + + cg.Call = Call; + cg.Cast = Cast; + cg.Get = Get; + cg.GetIndex = Index; + cg.GetMemberByIndex = Member; + cg.GetMemberByName = Member; + cg.ImplicitCast = ImplicitCast; + cg.Match = Match; + cg.Set = Set; + cg.SetIndex = Index; + cg.SetMemberByIndex = Member; + cg.SetMemberByName = Member; + } + } +} diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Call.cs new file mode 100644 index 00000000..35346f17 --- /dev/null +++ b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Call.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.Dispatchers.Proxy +{ + partial class Dispatcher + { + public Result Call(CompilerObject callee, Argument[] arguments) + { + var result = @base.Call(callee, arguments); + + if (result.IsError && callee.Is(out var proxy)) + result = proxy.Apply(proxied => CG.Call(proxied, arguments)); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Cast.cs new file mode 100644 index 00000000..e05d6747 --- /dev/null +++ b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Cast.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.Dispatchers.Proxy +{ + partial class Dispatcher + { + public Result Cast(CompilerObject @object, CompilerObject type) + { + var result = @base.Cast(@object, type); + + if (result.IsError && @object.Is(out var proxy)) + result = proxy.Apply(proxied => CG.Cast(proxied, type)); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs new file mode 100644 index 00000000..9017f7eb --- /dev/null +++ b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.Dispatchers.Proxy +{ + partial class Dispatcher + { + public Result ImplicitCast(CompilerObject @object, CompilerObject type) + { + var result = @base.ImplicitCast(@object, type); + + if (result.IsError && @object.Is(out var proxy)) + result = proxy.Apply(proxied => CG.ImplicitCast(proxied, type)); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Index.cs new file mode 100644 index 00000000..5bf4775a --- /dev/null +++ b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Index.cs @@ -0,0 +1,25 @@ +namespace ZSharp.Compiler.Dispatchers.Proxy +{ + partial class Dispatcher + { + public Result Index(CompilerObject @object, Argument[] arguments) + { + var result = @base.GetIndex(@object, arguments); + + if (result.IsError && @object.Is(out var proxy)) + result = proxy.Apply(proxied => CG.Index(proxied, arguments)); + + return result; + } + + public Result Index(CompilerObject @object, Argument[] arguments, CompilerObject value) + { + var result = @base.GetIndex(@object, arguments); + + if (result.IsError && @object.Is(out var proxy)) + result = proxy.Apply(proxied => CG.Index(proxied, arguments, value)); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Match.cs new file mode 100644 index 00000000..a9b88a2a --- /dev/null +++ b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Match.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.Dispatchers.Proxy +{ + partial class Dispatcher + { + public Result Match(CompilerObject @object, CompilerObject pattern) + { + var result = @base.Match(@object, pattern); + + if (result.IsError && @object.Is(out var proxy)) + result = proxy.Apply(proxied => CG.Match(proxied, pattern)); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs new file mode 100644 index 00000000..505b8561 --- /dev/null +++ b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs @@ -0,0 +1,45 @@ +namespace ZSharp.Compiler.Dispatchers.Proxy +{ + partial class Dispatcher + { + public Result Member(CompilerObject @object, MemberIndex index) + { + var result = @base.GetMemberByIndex(@object, index); + + if (result.IsError && @object.Is(out var proxy)) + result = proxy.Apply(proxied => CG.Member(proxied, index)); + + return result; + } + + public Result Member(CompilerObject @object, MemberIndex index, CompilerObject value) + { + var result = @base.SetMemberByIndex(@object, index, value); + + if (result.IsError && @object.Is(out var proxy)) + result = proxy.Apply(proxied => CG.Member(proxied, index, value)); + + return result; + } + + public Result Member(CompilerObject @object, MemberName name) + { + var result = @base.GetMemberByName(@object, name); + + if (result.IsError && @object.Is(out var proxy)) + result = proxy.Apply(proxied => CG.Member(proxied, name)); + + return result; + } + + public Result Member(CompilerObject @object, MemberName name, CompilerObject value) + { + var result = @base.SetMemberByName(@object, name, value); + + if (result.IsError && @object.Is(out var proxy)) + result = proxy.Apply(proxied => CG.Member(proxied, name, value)); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs new file mode 100644 index 00000000..6422e640 --- /dev/null +++ b/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs @@ -0,0 +1,25 @@ +namespace ZSharp.Compiler.Dispatchers.Proxy +{ + partial class Dispatcher + { + public Result Get(CompilerObject @object) + { + var result = @base.Get(@object); + + if (result.IsError && @object.Is(out var proxy)) + result = proxy.Apply(proxied => CG.Get(proxied)); + + return result; + } + + public Result Set(CompilerObject @object, CompilerObject value) + { + var result = @base.Set(@object, value); + + if (result.IsError && @object.Is(out var proxy)) + result = proxy.Apply(proxied => CG.Set(proxied, value)); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.Proxy/protocols/IProxy.cs b/ZSharp.Compiler.CO.Proxy/protocols/IProxy.cs new file mode 100644 index 00000000..ef29a7a3 --- /dev/null +++ b/ZSharp.Compiler.CO.Proxy/protocols/IProxy.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IProxy + { + public R Apply(Func fn); + } +} diff --git a/ZSharp.Compiler.CO.RT/GlobalUsings.cs b/ZSharp.Compiler.CO.RT/GlobalUsings.cs new file mode 100644 index 00000000..c1bcb323 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/GlobalUsings.cs @@ -0,0 +1,4 @@ +global using MemberName = string; +global using MemberIndex = int; + +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.CO.RT/ZSharp.Compiler.CO.RT.csproj b/ZSharp.Compiler.CO.RT/ZSharp.Compiler.CO.RT.csproj new file mode 100644 index 00000000..615e6b8a --- /dev/null +++ b/ZSharp.Compiler.CO.RT/ZSharp.Compiler.CO.RT.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + + + + + + + + + diff --git a/ZSharp.Compiler.CO.RT/dispatcher/Dispatcher.cs b/ZSharp.Compiler.CO.RT/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..bdea2c28 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/dispatcher/Dispatcher.cs @@ -0,0 +1,28 @@ +namespace ZSharp.Compiler.Dispatchers.RT +{ + public partial class Dispatcher(Compiler compiler) + { + private readonly Compiler compiler = compiler; + private CG @base; + + public void Apply() + { + @base = compiler.CG; + + ref var cg = ref compiler.CG; + + cg.Call = Call; + cg.Cast = Cast; + cg.Get = Get; + cg.GetIndex = Index; + cg.GetMemberByIndex = Member; + cg.GetMemberByName = Member; + cg.ImplicitCast = ImplicitCast; + cg.Match = Match; + cg.Set = Set; + cg.SetIndex = Index; + cg.SetMemberByIndex = Member; + cg.SetMemberByName = Member; + } + } +} diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Call.cs new file mode 100644 index 00000000..da1e1924 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Call.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.Dispatchers.RT +{ + partial class Dispatcher + { + public Result Call(CompilerObject callee, Argument[] arguments) + { + var result = @base.Call(callee, arguments); + + if (result.IsError && compiler.RuntimeDescriptor(callee, out var rtd) && rtd.Is(out var callable)) + result = callable.Call(compiler, callee, arguments); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Cast.cs new file mode 100644 index 00000000..92210453 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Cast.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.Dispatchers.RT +{ + partial class Dispatcher + { + public Result Cast(CompilerObject @object, CompilerObject type) + { + var result = @base.Cast(@object, type); + + if (result.IsError && compiler.RuntimeDescriptor(@object, out var rtd) && rtd.Is(out var castTo)) + result = castTo.Cast(compiler, @object, type); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ImplicitCast.cs new file mode 100644 index 00000000..4c1f7775 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -0,0 +1,21 @@ +namespace ZSharp.Compiler.Dispatchers.RT +{ + partial class Dispatcher + { + public Result ImplicitCast(CompilerObject @object, CompilerObject type) + { + var result = @base.ImplicitCast(@object, type); + + if (result.IsOk || !compiler.RuntimeDescriptor(@object, out var rtd)) + return result; + + if (result.IsError && rtd.Is(out var castTo)) + result = castTo.ImplicitCast(compiler, @object, type); + + //if (result.IsError && rtd.Is(out var castFrom)) + // result = castFrom.ImplicitCast(compiler, @object); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Index.cs new file mode 100644 index 00000000..fb3cf75a --- /dev/null +++ b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Index.cs @@ -0,0 +1,25 @@ +namespace ZSharp.Compiler.Dispatchers.RT +{ + partial class Dispatcher + { + public Result Index(CompilerObject @object, Argument[] arguments) + { + var result = @base.GetIndex(@object, arguments); + + if (result.IsError && compiler.RuntimeDescriptor(@object, out var rtd) && rtd.Is(out var index)) + result = index.Index(compiler, @object, arguments); + + return result; + } + + public Result Index(CompilerObject @object, Argument[] arguments, CompilerObject value) + { + var result = @base.GetIndex(@object, arguments); + + if (result.IsError && compiler.RuntimeDescriptor(@object, out var rtd) && rtd.Is(out var index)) + result = index.Index(compiler, @object, arguments, value); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Match.cs new file mode 100644 index 00000000..d818c6e4 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Match.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.Dispatchers.RT +{ + partial class Dispatcher + { + public Result Match(CompilerObject @object, CompilerObject pattern) + { + var result = @base.Match(@object, pattern); + + if (result.IsError && compiler.RuntimeDescriptor(@object, out var rtd) && rtd.Is(out var match)) + result = match.Match(compiler, @object, pattern); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.MemberAccess.cs new file mode 100644 index 00000000..b96d3307 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.MemberAccess.cs @@ -0,0 +1,45 @@ +namespace ZSharp.Compiler.Dispatchers.RT +{ + partial class Dispatcher + { + public Result Member(CompilerObject @object, MemberIndex index) + { + var result = @base.GetMemberByIndex(@object, index); + + if (result.IsError && compiler.RuntimeDescriptor(@object, out var rtd) && rtd.Is>(out var member)) + result = member.Member(compiler, @object, index); + + return result; + } + + public Result Member(CompilerObject @object, MemberIndex index, CompilerObject value) + { + var result = @base.SetMemberByIndex(@object, index, value); + + if (result.IsError && compiler.RuntimeDescriptor(@object, out var rtd) && rtd.Is>(out var member)) + result = member.Member(compiler, @object, index, value); + + return result; + } + + public Result Member(CompilerObject @object, MemberName name) + { + var result = @base.GetMemberByName(@object, name); + + if (result.IsError && compiler.RuntimeDescriptor(@object, out var rtd) && rtd.Is>(out var member)) + result = member.Member(compiler, @object, name); + + return result; + } + + public Result Member(CompilerObject @object, MemberName name, CompilerObject value) + { + var result = @base.SetMemberByName(@object, name, value); + + if (result.IsError && compiler.RuntimeDescriptor(@object, out var rtd) && rtd.Is>(out var member)) + result = member.Member(compiler, @object, name, value); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ValueAccess.cs new file mode 100644 index 00000000..f7dd69f4 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ValueAccess.cs @@ -0,0 +1,25 @@ +namespace ZSharp.Compiler.Dispatchers.RT +{ + partial class Dispatcher + { + public Result Get(CompilerObject @object) + { + var result = @base.Get(@object); + + if (result.IsError && compiler.RuntimeDescriptor(@object, out var rtd) && rtd.Is(out var get)) + result = get.Get(compiler, @object); + + return result; + } + + public Result Set(CompilerObject @object, CompilerObject value) + { + var result = @base.Set(@object, value); + + if (result.IsError && compiler.RuntimeDescriptor(@object, out var rtd) && rtd.Is(out var set)) + result = set.Set(compiler, @object, value); + + return result; + } + } +} diff --git a/ZSharp.Compiler.CO.RT/extensions/CompilerExtensions.cs b/ZSharp.Compiler.CO.RT/extensions/CompilerExtensions.cs new file mode 100644 index 00000000..0d66e73e --- /dev/null +++ b/ZSharp.Compiler.CO.RT/extensions/CompilerExtensions.cs @@ -0,0 +1,18 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler +{ + public static class CompilerExtensions + { + public static Result GetRuntimeDescriptor(this Compiler compiler, CompilerObject @object) + { + if (@object.Is(out var hasRuntimeDescriptor)) + return hasRuntimeDescriptor.GetRuntimeDescriptor(compiler); + + return Result.Error($"No runtime descriptor found for object {@object}."); + } + + public static bool RuntimeDescriptor(this Compiler compiler, CompilerObject @object, [NotNullWhen(true)] out CompilerObject? rt) + => compiler.GetRuntimeDescriptor(@object).Ok(out rt); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/callable/IRTCallable.cs b/ZSharp.Compiler.CO.RT/protocols/callable/IRTCallable.cs new file mode 100644 index 00000000..966a6877 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/callable/IRTCallable.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTCallable + { + public Result Call(Compiler compiler, CompilerObject @object, Argument[] arguments); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/implicit casting/IRTImplicitCastTo.cs b/ZSharp.Compiler.CO.RT/protocols/implicit casting/IRTImplicitCastTo.cs new file mode 100644 index 00000000..104be28d --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/implicit casting/IRTImplicitCastTo.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTImplicitCastTo + { + public Result ImplicitCast(Compiler compiler, CompilerObject @object, CompilerObject type); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/index/IRTGetIndex.cs b/ZSharp.Compiler.CO.RT/protocols/index/IRTGetIndex.cs new file mode 100644 index 00000000..83a153b8 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/index/IRTGetIndex.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTGetIndex + { + public Result Index(Compiler compiler, CompilerObject @object, Argument[] arguments); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/index/IRTSetIndex.cs b/ZSharp.Compiler.CO.RT/protocols/index/IRTSetIndex.cs new file mode 100644 index 00000000..fa44b99a --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/index/IRTSetIndex.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTSetIndex + { + public Result Index(Compiler compiler, CompilerObject @object, Argument[] arguments, CompilerObject value); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/member access/IRTGetMember.cs b/ZSharp.Compiler.CO.RT/protocols/member access/IRTGetMember.cs new file mode 100644 index 00000000..a08d8ac5 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/member access/IRTGetMember.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTGetMember + { + public Result Member(Compiler compiler, CompilerObject @object, M member); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/member access/IRTSetMember.cs b/ZSharp.Compiler.CO.RT/protocols/member access/IRTSetMember.cs new file mode 100644 index 00000000..a082b5d9 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/member access/IRTSetMember.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTSetMember + { + public Result Member(Compiler compiler, CompilerObject @object, M member, CompilerObject value); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/runtime/IHasRuntimeDescriptor.cs b/ZSharp.Compiler.CO.RT/protocols/runtime/IHasRuntimeDescriptor.cs new file mode 100644 index 00000000..98a5336e --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/runtime/IHasRuntimeDescriptor.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IHasRuntimeDescriptor + { + public Result GetRuntimeDescriptor(Compiler compiler); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastFrom.cs b/ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastFrom.cs new file mode 100644 index 00000000..a30af3db --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastFrom.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTCastFrom + { + public Result Cast(Compiler compiler, CompilerObject value); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastTo.cs b/ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastTo.cs new file mode 100644 index 00000000..ca47ab87 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastTo.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTCastTo + { + public Result Cast(Compiler compiler, CompilerObject value, CompilerObject targetType); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/type matching/IRTTypeMatch.cs b/ZSharp.Compiler.CO.RT/protocols/type matching/IRTTypeMatch.cs new file mode 100644 index 00000000..198c6773 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/type matching/IRTTypeMatch.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTTypeMatch + { + public Result Match(Compiler compiler, CompilerObject value, CompilerObject type); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/value access/IRTGet.cs b/ZSharp.Compiler.CO.RT/protocols/value access/IRTGet.cs new file mode 100644 index 00000000..656d5b58 --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/value access/IRTGet.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTGet + { + public Result Get(Compiler compiler, CompilerObject @object); + } +} diff --git a/ZSharp.Compiler.CO.RT/protocols/value access/IRTSet.cs b/ZSharp.Compiler.CO.RT/protocols/value access/IRTSet.cs new file mode 100644 index 00000000..aab7f06f --- /dev/null +++ b/ZSharp.Compiler.CO.RT/protocols/value access/IRTSet.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IRTSet + { + public Result Set(Compiler compiler, CompilerObject @object, CompilerObject value); + } +} diff --git a/ZSharp.Compiler.CO/GlobalUsings.cs b/ZSharp.Compiler.CO/GlobalUsings.cs new file mode 100644 index 00000000..c1bcb323 --- /dev/null +++ b/ZSharp.Compiler.CO/GlobalUsings.cs @@ -0,0 +1,4 @@ +global using MemberName = string; +global using MemberIndex = int; + +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.CO/ZSharp.Compiler.CO.csproj b/ZSharp.Compiler.CO/ZSharp.Compiler.CO.csproj new file mode 100644 index 00000000..be4a9954 --- /dev/null +++ b/ZSharp.Compiler.CO/ZSharp.Compiler.CO.csproj @@ -0,0 +1,16 @@ + + + + net8.0 + enable + enable + ZSharp.Compiler + + + + + + + + + diff --git a/ZSharp.Compiler.CO/cg/CG.cs b/ZSharp.Compiler.CO/cg/CG.cs new file mode 100644 index 00000000..862012ba --- /dev/null +++ b/ZSharp.Compiler.CO/cg/CG.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public partial struct CG() + { + + } +} diff --git a/ZSharp.Compiler.CO/cg/services/CG.Call.cs b/ZSharp.Compiler.CO/cg/services/CG.Call.cs new file mode 100644 index 00000000..62e34e5d --- /dev/null +++ b/ZSharp.Compiler.CO/cg/services/CG.Call.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public delegate Result Call(CompilerObject callee, Argument[] arguments); + + partial struct CG + { + public Call Call { get; set; } = Dispatcher.Call; + } +} diff --git a/ZSharp.Compiler.CO/cg/services/CG.Cast.cs b/ZSharp.Compiler.CO/cg/services/CG.Cast.cs new file mode 100644 index 00000000..e4529a38 --- /dev/null +++ b/ZSharp.Compiler.CO/cg/services/CG.Cast.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public delegate Result Cast(CompilerObject @object, CompilerObject type); + + partial struct CG + { + public Cast Cast { get; set; } = Dispatcher.Cast; + } +} diff --git a/ZSharp.Compiler.CO/cg/services/CG.ImplicitCast.cs b/ZSharp.Compiler.CO/cg/services/CG.ImplicitCast.cs new file mode 100644 index 00000000..903a2c50 --- /dev/null +++ b/ZSharp.Compiler.CO/cg/services/CG.ImplicitCast.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public delegate Result ImplicitCast(CompilerObject @object, CompilerObject type); + + partial struct CG + { + public ImplicitCast ImplicitCast { get; set; } = Dispatcher.ImplicitCast; + } +} diff --git a/ZSharp.Compiler.CO/cg/services/CG.Index.cs b/ZSharp.Compiler.CO/cg/services/CG.Index.cs new file mode 100644 index 00000000..8e4952b1 --- /dev/null +++ b/ZSharp.Compiler.CO/cg/services/CG.Index.cs @@ -0,0 +1,18 @@ +namespace ZSharp.Compiler +{ + public delegate Result GetIndex(CompilerObject @object, Argument[] arguments); + public delegate Result SetIndex(CompilerObject @object, Argument[] arguments, CompilerObject value); + + partial struct CG + { + public GetIndex GetIndex { get; set; } = Dispatcher.Index; + + public SetIndex SetIndex { get; set; } = Dispatcher.Index; + + public readonly Result Index(CompilerObject @object, Argument[] arguments) + => GetIndex(@object, arguments); + + public readonly Result Index(CompilerObject @object, Argument[] arguments, CompilerObject value) + => SetIndex(@object, arguments, value); + } +} diff --git a/ZSharp.Compiler.CO/cg/services/CG.Match.cs b/ZSharp.Compiler.CO/cg/services/CG.Match.cs new file mode 100644 index 00000000..f8a04517 --- /dev/null +++ b/ZSharp.Compiler.CO/cg/services/CG.Match.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public delegate Result Match(CompilerObject @object, CompilerObject pattern); + + partial struct CG + { + public Match Match { get; set; } = Dispatcher.Match; + } +} diff --git a/ZSharp.Compiler.CO/cg/services/CG.MemberAccess.cs b/ZSharp.Compiler.CO/cg/services/CG.MemberAccess.cs new file mode 100644 index 00000000..a000fd1c --- /dev/null +++ b/ZSharp.Compiler.CO/cg/services/CG.MemberAccess.cs @@ -0,0 +1,55 @@ +namespace ZSharp.Compiler +{ + public delegate Result GetMember(CompilerObject @object, T member); + + public delegate Result SetMember(CompilerObject @object, T member, CompilerObject value); + + partial struct CG + { + public GetMember GetMemberByIndex { get; set; } = Dispatcher.Member; + + public SetMember SetMemberByIndex { get; set; } = Dispatcher.Member; + + public GetMember GetMemberByName { get; set; } = Dispatcher.Member; + + public SetMember SetMemberByName { get; set; } = Dispatcher.Member; + + /// + /// The get member (.) operator. + /// + /// + /// + /// + public readonly Result Member(CompilerObject @object, MemberIndex index) + => GetMemberByIndex(@object, index); + + /// + /// The set member (.=) operator. + /// + /// + /// + /// + /// + public readonly Result Member(CompilerObject @object, MemberIndex index, CompilerObject value) + => SetMemberByIndex(@object, index, value); + + /// + /// The member (.) operator. + /// + /// + /// + /// + public readonly Result Member(CompilerObject @object, MemberName name) + => GetMemberByName(@object, name); + + /// + /// The set member (.=) operator. + /// + /// + /// + /// + /// + public readonly Result Member(CompilerObject @object, MemberName name, CompilerObject value) + => SetMemberByName(@object, name, value); + } +} diff --git a/ZSharp.Compiler.CO/cg/services/CG.ValueAccess.cs b/ZSharp.Compiler.CO/cg/services/CG.ValueAccess.cs new file mode 100644 index 00000000..567ae1c0 --- /dev/null +++ b/ZSharp.Compiler.CO/cg/services/CG.ValueAccess.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler +{ + public delegate Result Get(CompilerObject @object); + + public delegate Result Set(CompilerObject @object, CompilerObject value); + + public partial struct CG + { + public Get Get { get; set; } = Dispatcher.Get; + + public Set Set { get; set; } = Dispatcher.Set; + } +} diff --git a/ZSharp.Compiler/core/concepts/callable/Argument.cs b/ZSharp.Compiler.CO/core/Argument.cs similarity index 100% rename from ZSharp.Compiler/core/concepts/callable/Argument.cs rename to ZSharp.Compiler.CO/core/Argument.cs diff --git a/ZSharp.Compiler/features/cg/capabilities/type casting/TypeCast.cs b/ZSharp.Compiler.CO/core/CastResult.cs similarity index 90% rename from ZSharp.Compiler/features/cg/capabilities/type casting/TypeCast.cs rename to ZSharp.Compiler.CO/core/CastResult.cs index ac8d2b49..ead66c23 100644 --- a/ZSharp.Compiler/features/cg/capabilities/type casting/TypeCast.cs +++ b/ZSharp.Compiler.CO/core/CastResult.cs @@ -2,7 +2,7 @@ namespace ZSharp.Compiler { - public sealed class TypeCast + public sealed class CastResult { public required CompilerObject Cast { get; set; } diff --git a/ZSharp.Compiler/features/cg/capabilities/type matching/TypeMatch.cs b/ZSharp.Compiler.CO/core/MatchResult.cs similarity index 84% rename from ZSharp.Compiler/features/cg/capabilities/type matching/TypeMatch.cs rename to ZSharp.Compiler.CO/core/MatchResult.cs index 6c46d7c9..b571fb74 100644 --- a/ZSharp.Compiler/features/cg/capabilities/type matching/TypeMatch.cs +++ b/ZSharp.Compiler.CO/core/MatchResult.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler { - public sealed class TypeMatch + public sealed class MatchResult { public required CompilerObject Match { get; set; } diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.Call.cs b/ZSharp.Compiler.CO/dispatcher/Dispatcher.Call.cs new file mode 100644 index 00000000..d915c8e5 --- /dev/null +++ b/ZSharp.Compiler.CO/dispatcher/Dispatcher.Call.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result Call(CompilerObject callee, Argument[] arguments) + => Result.Error( + $"Object [{callee}] does not support call operation." + ); + } +} diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.Cast.cs b/ZSharp.Compiler.CO/dispatcher/Dispatcher.Cast.cs new file mode 100644 index 00000000..1bf6b765 --- /dev/null +++ b/ZSharp.Compiler.CO/dispatcher/Dispatcher.Cast.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result Cast(CompilerObject @object, CompilerObject type) + => Result.Error( + "Cast operation is not supported." + ); + } +} diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CO/dispatcher/Dispatcher.ImplicitCast.cs new file mode 100644 index 00000000..63a264e9 --- /dev/null +++ b/ZSharp.Compiler.CO/dispatcher/Dispatcher.ImplicitCast.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result ImplicitCast(CompilerObject @object, CompilerObject type) + => Result.Error( + "Implicit casting is not supported for the given object and type." + ); + } +} diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.Index.cs b/ZSharp.Compiler.CO/dispatcher/Dispatcher.Index.cs new file mode 100644 index 00000000..752b2669 --- /dev/null +++ b/ZSharp.Compiler.CO/dispatcher/Dispatcher.Index.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result Index(CompilerObject @object, Argument[] arguments) + => Result.Error( + "Object does not support index operation." + ); + + public static Result Index(CompilerObject @object, Argument[] arguments, CompilerObject value) + => Result.Error( + "Object does not support index assignment operation." + ); + } +} diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.Match.cs b/ZSharp.Compiler.CO/dispatcher/Dispatcher.Match.cs new file mode 100644 index 00000000..58f27b28 --- /dev/null +++ b/ZSharp.Compiler.CO/dispatcher/Dispatcher.Match.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result Match(CompilerObject @object, CompilerObject pattern) + => Result.Error( + "Pattern matching is not supported in the current context." + ); + } +} diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CO/dispatcher/Dispatcher.MemberAccess.cs new file mode 100644 index 00000000..09d91c50 --- /dev/null +++ b/ZSharp.Compiler.CO/dispatcher/Dispatcher.MemberAccess.cs @@ -0,0 +1,25 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result Member(CompilerObject @object, MemberIndex index) + => Result.Error( + "Object does not support member access by index." + ); + + public static Result Member(CompilerObject @object, MemberIndex index, CompilerObject value) + => Result.Error( + "Object does not support member assignment by index." + ); + + public static Result Member(CompilerObject @object, MemberName name) + => Result.Error( + "Object does not support member access by name." + ); + + public static Result Member(CompilerObject @object, MemberName name, CompilerObject value) + => Result.Error( + "Object does not support member assignment by name." + ); + } +} diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.Runtime.cs b/ZSharp.Compiler.CO/dispatcher/Dispatcher.Runtime.cs new file mode 100644 index 00000000..f71a24a5 --- /dev/null +++ b/ZSharp.Compiler.CO/dispatcher/Dispatcher.Runtime.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result RuntimeDescriptor(CompilerObject @object) + => Result.Error( + "Object does not support runtime descriptor protocol" + ); + } +} diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CO/dispatcher/Dispatcher.ValueAccess.cs new file mode 100644 index 00000000..0f7a37a9 --- /dev/null +++ b/ZSharp.Compiler.CO/dispatcher/Dispatcher.ValueAccess.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result Get(CompilerObject @object) + => Result.Error( + "Object does not support get" + ); + + public static Result Set(CompilerObject @object, CompilerObject value) + => Result.Error( + "Object does not support set" + ); + } +} diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.cs b/ZSharp.Compiler.CO/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..cd652665 --- /dev/null +++ b/ZSharp.Compiler.CO/dispatcher/Dispatcher.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler +{ + internal static partial class Dispatcher + { + } +} diff --git a/ZSharp.Compiler.Context/GlobalUsings.cs b/ZSharp.Compiler.Context/GlobalUsings.cs new file mode 100644 index 00000000..c1bcb323 --- /dev/null +++ b/ZSharp.Compiler.Context/GlobalUsings.cs @@ -0,0 +1,4 @@ +global using MemberName = string; +global using MemberIndex = int; + +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.Context/ZSharp.Compiler.Context.csproj b/ZSharp.Compiler.Context/ZSharp.Compiler.Context.csproj new file mode 100644 index 00000000..4e102195 --- /dev/null +++ b/ZSharp.Compiler.Context/ZSharp.Compiler.Context.csproj @@ -0,0 +1,14 @@ + + + + net8.0 + enable + enable + ZSharp.Compiler + + + + + + + diff --git a/ZSharp.Compiler.Context/capabilities/object/IObjectContext.cs b/ZSharp.Compiler.Context/capabilities/object/IObjectContext.cs new file mode 100644 index 00000000..c825f460 --- /dev/null +++ b/ZSharp.Compiler.Context/capabilities/object/IObjectContext.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Compiler +{ + public interface IObjectContext + : IContext + { + public CompilerObject Object { get; } + } + + public interface IObjectContext + : IObjectContext + where T : CompilerObject + { + new public T Object { get; } + + CompilerObject IObjectContext.Object => Object; + } +} diff --git a/ZSharp.Compiler.Context/capabilities/scoping/ILookupContext.cs b/ZSharp.Compiler.Context/capabilities/scoping/ILookupContext.cs new file mode 100644 index 00000000..731f123c --- /dev/null +++ b/ZSharp.Compiler.Context/capabilities/scoping/ILookupContext.cs @@ -0,0 +1,13 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler +{ + public interface ILookupContext + : IContext + { + public Result Get(MemberName name); + + public sealed bool Get(MemberName name, [NotNullWhen(true)] out CompilerObject? value) + => Get(name).Ok(out value); + } +} diff --git a/ZSharp.Compiler.Context/capabilities/scoping/IScopeContext.cs b/ZSharp.Compiler.Context/capabilities/scoping/IScopeContext.cs new file mode 100644 index 00000000..fab4845e --- /dev/null +++ b/ZSharp.Compiler.Context/capabilities/scoping/IScopeContext.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Compiler +{ + public interface IScopeContext + : IContext + , ILookupContext + { + public Result Add(MemberName name, CompilerObject value); + + public Result Set(MemberName name, CompilerObject value); + } +} diff --git a/ZSharp.Compiler.Context/capabilities/storage/IStorage.cs b/ZSharp.Compiler.Context/capabilities/storage/IStorage.cs new file mode 100644 index 00000000..d61f8ee9 --- /dev/null +++ b/ZSharp.Compiler.Context/capabilities/storage/IStorage.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface IStorage + { + + } +} diff --git a/ZSharp.Compiler.Context/capabilities/storage/IStorageContext.cs b/ZSharp.Compiler.Context/capabilities/storage/IStorageContext.cs new file mode 100644 index 00000000..5c384eae --- /dev/null +++ b/ZSharp.Compiler.Context/capabilities/storage/IStorageContext.cs @@ -0,0 +1,12 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler +{ + public interface IStorageContext + { + public Result CreateStorage(StorageOptions options); + + public sealed bool CreateStorage(StorageOptions options, [NotNullWhen(true)] out CompilerObject? result) + => CreateStorage(options).Ok(out result); + } +} diff --git a/ZSharp.Compiler.Context/capabilities/storage/IStorageDescriptor.cs b/ZSharp.Compiler.Context/capabilities/storage/IStorageDescriptor.cs new file mode 100644 index 00000000..12b28250 --- /dev/null +++ b/ZSharp.Compiler.Context/capabilities/storage/IStorageDescriptor.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler +{ + public interface IStorageDescriptor + { + } +} diff --git a/ZSharp.Compiler.Context/capabilities/storage/StorageOptions.cs b/ZSharp.Compiler.Context/capabilities/storage/StorageOptions.cs new file mode 100644 index 00000000..e3e2a1c9 --- /dev/null +++ b/ZSharp.Compiler.Context/capabilities/storage/StorageOptions.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler +{ + public sealed class StorageOptions + { + public string Name { get; init; } = string.Empty; + + public required CompilerObject Type { get; init; } + + public CompilerObject? Initializer { get; init; } + + public bool? IsReadOnly { get; init; } + } +} diff --git a/ZSharp.Compiler.Context/capabilities/type inference/ITypeInferenceContext.cs b/ZSharp.Compiler.Context/capabilities/type inference/ITypeInferenceContext.cs new file mode 100644 index 00000000..e1275c11 --- /dev/null +++ b/ZSharp.Compiler.Context/capabilities/type inference/ITypeInferenceContext.cs @@ -0,0 +1,12 @@ +namespace ZSharp.Compiler +{ + public interface ITypeInferenceContext + { + protected sealed T OnCreate(T inferrer) + where T : TypeInferrer + { + inferrer.Context = this; + return inferrer; + } + } +} diff --git a/ZSharp.Compiler.Context/capabilities/type inference/TypeInferrer.cs b/ZSharp.Compiler.Context/capabilities/type inference/TypeInferrer.cs new file mode 100644 index 00000000..e6e84d71 --- /dev/null +++ b/ZSharp.Compiler.Context/capabilities/type inference/TypeInferrer.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public abstract class TypeInferrer + : CompilerObject + { + public ITypeInferenceContext Context { get; internal set; } + } +} diff --git a/ZSharp.Compiler/compiler core/core/context/IContext.cs b/ZSharp.Compiler.Context/core/IContext.cs similarity index 75% rename from ZSharp.Compiler/compiler core/core/context/IContext.cs rename to ZSharp.Compiler.Context/core/IContext.cs index c7779244..74741dfb 100644 --- a/ZSharp.Compiler/compiler core/core/context/IContext.cs +++ b/ZSharp.Compiler.Context/core/IContext.cs @@ -6,9 +6,9 @@ public interface IContext { private static IContextChainStrategy DefaultStrategy { get; } = new ParentContextStrategy(); - public IContext? Parent { get; internal protected set; } + public IContext? Parent { get; set; } - public T? FindContext(IContextChainStrategy? strategy = null) + public T? FindFirstContext(IContextChainStrategy? strategy = null) where T : class, IContext { strategy ??= DefaultStrategy; @@ -23,6 +23,20 @@ public interface IContext return null; } + public IEnumerable FindContext(IContextChainStrategy? strategy = null) + where T : class, IContext + { + strategy ??= DefaultStrategy; + + var context = this; + + do + { + if (context is T capability) + yield return capability; + } while ((context = strategy.NextContext(context!)) is not null); + } + public bool PerformOperation( Func operation, IContextChainStrategy? strategy = null diff --git a/ZSharp.Compiler/compiler core/core/context/IContextChainStrategy.cs b/ZSharp.Compiler.Context/core/IContextChainStrategy.cs similarity index 100% rename from ZSharp.Compiler/compiler core/core/context/IContextChainStrategy.cs rename to ZSharp.Compiler.Context/core/IContextChainStrategy.cs diff --git a/ZSharp.Compiler/compiler core/core/context/strategies/ParentContextStrategy.cs b/ZSharp.Compiler.Context/strategies/ParentContextStrategy.cs similarity index 100% rename from ZSharp.Compiler/compiler core/core/context/strategies/ParentContextStrategy.cs rename to ZSharp.Compiler.Context/strategies/ParentContextStrategy.cs diff --git a/ZSharp.Compiler.Core/CompilerObject.cs b/ZSharp.Compiler.Core/CompilerObject.cs new file mode 100644 index 00000000..194fc479 --- /dev/null +++ b/ZSharp.Compiler.Core/CompilerObject.cs @@ -0,0 +1,11 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler +{ + public interface CompilerObject + { + public bool Is([NotNullWhen(true)] out T? result) + where T : class + => (result = this as T) is not null; + } +} diff --git a/ZSharp.Compiler.Core/ZSharp.Compiler.Core.csproj b/ZSharp.Compiler.Core/ZSharp.Compiler.Core.csproj new file mode 100644 index 00000000..055aa435 --- /dev/null +++ b/ZSharp.Compiler.Core/ZSharp.Compiler.Core.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/ZSharp.Compiler.Core/result/Error.cs b/ZSharp.Compiler.Core/result/Error.cs new file mode 100644 index 00000000..1f6921bf --- /dev/null +++ b/ZSharp.Compiler.Core/result/Error.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler +{ + public abstract class Error + { + } +} diff --git a/ZSharp.Compiler.Core/result/Result.cs b/ZSharp.Compiler.Core/result/Result.cs new file mode 100644 index 00000000..812dc96d --- /dev/null +++ b/ZSharp.Compiler.Core/result/Result.cs @@ -0,0 +1,64 @@ +using CommonZ; + +namespace ZSharp.Compiler +{ + public class Result + : Result + where TResult : class? + { + protected Result(TResult? result, Error? error) + : base(result, error) + { + + } + + public new static Result Ok(TResult result) + => new(result, null); + + public new static Result Error(Error error) + => new(null, error); + + public static Result Error(string message) + => Error(new ErrorMessage(message)); + + public new Result When(Action action) + { + if (IsOk) + action(Unwrap()); + + return this; + } + + public new Result When(Func map) + where R : class? + => IsOk + ? Result.Ok(map(result)) + : Result.Error(error!); + + public new Result When(out TResult? result) + { + result = this.result; + return this; + } + + public new Result Else(Action action) + { + if (IsError) + action(error); + + return this; + } + + public new Result Else(Func map) + where E : class + => IsOk + ? Result.Ok(result) + : Result.Error(map(error!)); + + public new Result Else(out Error? error) + { + error = this.error; + return this; + } + } +} diff --git a/ZSharp.Compiler.Core/result/errors/ErrorMessage.cs b/ZSharp.Compiler.Core/result/errors/ErrorMessage.cs new file mode 100644 index 00000000..c6a9ca75 --- /dev/null +++ b/ZSharp.Compiler.Core/result/errors/ErrorMessage.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Compiler +{ + public class ErrorMessage(string message) + : Error + { + public string Message { get; } = message; + + public override string ToString() + => Message; + } +} diff --git a/ZSharp.Compiler.Features/ir/IIREvaluator.cs b/ZSharp.Compiler.Features/ir/IIREvaluator.cs deleted file mode 100644 index 8fccb97f..00000000 --- a/ZSharp.Compiler.Features/ir/IIREvaluator.cs +++ /dev/null @@ -1,34 +0,0 @@ -using ZSharp.Objects; - -namespace ZSharp.Compiler -{ - public interface IIREvaluator - { - /// - /// Evaluate the given IR code and return the result object. - /// - /// The return value depends on the properties of the IR code. - /// - /// - /// Property - /// Result - /// - /// - /// - /// . - /// - /// - /// - /// A single . - /// - /// - /// - /// An object. - /// - /// - /// - /// The code to evaluate. - /// The result of evaluating the code. - public CompilerObject? EvaluateCT(IRCode code); - } -} diff --git a/ZSharp.Compiler.Features/ir/IR.Compile.cs b/ZSharp.Compiler.Features/ir/IR.Compile.cs deleted file mode 100644 index 2e9f9435..00000000 --- a/ZSharp.Compiler.Features/ir/IR.Compile.cs +++ /dev/null @@ -1,47 +0,0 @@ -using ZSharp.Objects; - -namespace ZSharp.Compiler -{ - public sealed partial class IRCompiler - { - public Result CompileIRCode(CompilerObject @object) - => Result.Ok( - Compiler.CompileIRCode(@object) - ); - - public Result CompileIRObject(CompilerObject @object) - => Result.Ok( - Compiler.CompileIRObject(@object) - ); - - public Result CompileIRObject(CompilerObject @object, Owner? owner) - where Owner : ZSharp.IR.IRDefinition - => Result.Ok( - Compiler.CompileIRObject(@object, owner) - ); - - public Result CompileIRObject(CompilerObject @object, Owner? owner) - where T : ZSharp.IR.IRDefinition - where Owner : class - => Result.Ok( - Compiler.CompileIRObject(@object, owner) - ); - - public Result CompileIRType(CompilerObject @object) - => Result.Ok( - Compiler.CompileIRType(@object) - ); - - public Result CompileIRType(CompilerObject @object) - where T : class, ZSharp.IR.IType - => Result.Ok( - Compiler.CompileIRType(@object) - ); - - public Result CompileIRReference(CompilerObject @object) - where T : class - => Result.Ok( - Compiler.CompileIRReference(@object) - ); - } -} diff --git a/ZSharp.Compiler.Features/ir/IR.cs b/ZSharp.Compiler.Features/ir/IR.cs deleted file mode 100644 index 70f28d4e..00000000 --- a/ZSharp.Compiler.Features/ir/IR.cs +++ /dev/null @@ -1,19 +0,0 @@ -using ZSharp.Objects; - -namespace ZSharp.Compiler -{ - public sealed partial class IRCompiler(Compiler compiler) : Feature(compiler) - { - public ZSharp.IR.RuntimeModule RuntimeModule - => Compiler.RuntimeModule; - - public IIREvaluator? Evaluator { get; set; } - - public CompilerObject? EvaluateCO(IRCode code) - => Evaluator is not null - ? Evaluator.EvaluateCT(code) - : throw new InvalidOperationException( - "No IR evaluator was assigned." - ); - } -} diff --git a/ZSharp.Compiler.ILLoader.Attributes/SkipImportAttribute.cs b/ZSharp.Compiler.ILLoader.Attributes/HideImportAttribute.cs similarity index 85% rename from ZSharp.Compiler.ILLoader.Attributes/SkipImportAttribute.cs rename to ZSharp.Compiler.ILLoader.Attributes/HideImportAttribute.cs index 6a42d8a0..bc2b4b72 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/SkipImportAttribute.cs +++ b/ZSharp.Compiler.ILLoader.Attributes/HideImportAttribute.cs @@ -11,7 +11,8 @@ AttributeTargets.Struct, AllowMultiple = false )] - public sealed class SkipImportAttribute : Attribute + public sealed class HideImportAttribute : Attribute { + } } diff --git a/ZSharp.Compiler.ILLoader.Attributes/namespace/AddNamespaceAttribute.cs b/ZSharp.Compiler.ILLoader.Attributes/namespace/AddNamespaceAttribute.cs new file mode 100644 index 00000000..6f7223fe --- /dev/null +++ b/ZSharp.Compiler.ILLoader.Attributes/namespace/AddNamespaceAttribute.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Compiler.ILLoader +{ + [AttributeUsage( + AttributeTargets.Class | + AttributeTargets.Struct | + AttributeTargets.Interface | + AttributeTargets.Enum, + AllowMultiple = false, + Inherited = false + )] + public sealed class AddNamespaceAttribute(string @namespace) : Attribute + { + public string Name { get; } = @namespace; + + public bool IsGlobalNamespace => string.IsNullOrEmpty(Name); + } +} diff --git a/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj b/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj index 20038b28..fa615868 100644 --- a/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj +++ b/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj @@ -7,22 +7,17 @@ - - - - - - - - - - + + + + + diff --git a/ZSharp.Compiler.ILLoader/capabilities/ITypeModifier.cs b/ZSharp.Compiler.ILLoader/capabilities/ITypeModifier.cs new file mode 100644 index 00000000..785a6262 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/capabilities/ITypeModifier.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + public interface ITypeModifier + { + public CompilerObject Modify(CompilerObject type); + } +} diff --git a/ZSharp.Compiler.ILLoader/capabilities/internal/IAddMember.cs b/ZSharp.Compiler.ILLoader/capabilities/internal/IAddMember.cs new file mode 100644 index 00000000..390dae09 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/capabilities/internal/IAddMember.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + internal interface IAddMember + { + public void AddMember(string name, CompilerObject member); + } +} diff --git a/ZSharp.Compiler.ILLoader/capabilities/internal/ILazilyLoadMembers.cs b/ZSharp.Compiler.ILLoader/capabilities/internal/ILazilyLoadMembers.cs new file mode 100644 index 00000000..54f2f80f --- /dev/null +++ b/ZSharp.Compiler.ILLoader/capabilities/internal/ILazilyLoadMembers.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + internal interface ILazilyLoadMembers + { + public void AddLazyMember(MemberName member, IL.MemberInfo lazyLoadedMember); + } +} diff --git a/ZSharp.Compiler.ILLoader/capabilities/on add/IOnAddTo.cs b/ZSharp.Compiler.ILLoader/capabilities/on add/IOnAddTo.cs index f9ef51c7..31d747de 100644 --- a/ZSharp.Compiler.ILLoader/capabilities/on add/IOnAddTo.cs +++ b/ZSharp.Compiler.ILLoader/capabilities/on add/IOnAddTo.cs @@ -1,7 +1,7 @@ namespace ZSharp.Objects { public interface IOnAddTo - where T : class, CompilerObject + where T : class, Compiler.CompilerObject { public OnAddResult OnAddTo(T @object); } diff --git a/ZSharp.Compiler.ILLoader/extensions/ILLoaderExtensions.cs b/ZSharp.Compiler.ILLoader/extensions/ILLoaderExtensions.cs new file mode 100644 index 00000000..73e00dc6 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/extensions/ILLoaderExtensions.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler.ILLoader +{ + public static class ILLoaderExtensions + { + public static CompilerObject LoadTypeAsModule(this ILLoader loader, Type type) + => new Objects.TypeAsModule(type, loader); + } +} diff --git a/ZSharp.Compiler.ILLoader/extensions/InternalILMemberExtensions.cs b/ZSharp.Compiler.ILLoader/extensions/InternalILMemberExtensions.cs new file mode 100644 index 00000000..b4e2c869 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/extensions/InternalILMemberExtensions.cs @@ -0,0 +1,41 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using ZSharp.Compiler.ILLoader.Objects; + +namespace ZSharp.Compiler.ILLoader +{ + internal static class InternalILMemberExtensions + { + public static string AliasOrName(this MemberInfo member) + => member.GetCustomAttribute() is AliasAttribute alias + ? alias.Name + : member.Name; + + public static bool IsModuleScope(this Type type) + => type.GetCustomAttribute() is not null; + + public static bool IsOperator(this MethodInfo method) + => method.GetCustomAttribute() is not null; + + public static bool IsOperator(this MethodInfo method, [NotNullWhen(true)] out OperatorAttribute? @operator) + => (@operator = method.GetCustomAttribute()) is not null; + + public static string GetNamespaceOverride(this MemberInfo member, string rootNamespace) + { + if (member.GetCustomAttribute() is SetNamespaceAttribute setNamespace) + return setNamespace.Name; + + if (member.GetCustomAttribute() is AddNamespaceAttribute addNamespace) + { + if (addNamespace.IsGlobalNamespace) + return rootNamespace; + return $"{rootNamespace}.{addNamespace.Name}"; + } + + return rootNamespace; + } + + public static bool OverridesNamespace(this MemberInfo member, string rootNamespace, [NotNullWhen(true)] out string? @namespace) + => (@namespace = member.GetNamespaceOverride(rootNamespace)) != rootNamespace; + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Events.cs b/ZSharp.Compiler.ILLoader/il loader/ILLoader.Events.cs new file mode 100644 index 00000000..f0bb917b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/ILLoader.Events.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public Action OnLoadOperator; + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Expose.cs b/ZSharp.Compiler.ILLoader/il loader/ILLoader.Expose.cs new file mode 100644 index 00000000..0a6f1be2 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/ILLoader.Expose.cs @@ -0,0 +1,77 @@ +using CommonZ.Utils; +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler.ILLoader +{ + public sealed partial class ILLoader + { + [MaybeNull] + private ZSharp.IR.Function castFunction; + + public Collection ExposeAsIR(T? obj) + => ExposeAsIR(obj, typeof(T)); + + public Collection ExposeAsIR(object? obj) + => ExposeAsIR(obj, obj?.GetType() ?? typeof(object)); + + public Collection ExposeAsIR(object? obj, Type type) + { + var rt = RequireRuntime(); + var ir = RequireIR(); + + if (obj is null) return rt.Expose(null); + + var coType = LoadType(type); + var irType = ir.CompileType(coType).Unwrap(); + + var code = rt.Expose(obj); + + var function = new ZSharp.IR.GenericFunctionInstance(castFunction!); + function.Arguments.Add(irType); + + code.Add(new ZSharp.IR.VM.Call(function)); + return code; + } + + public CompilerObject Expose(T? obj) + => Expose(obj, typeof(T)); + + public CompilerObject Expose(object? obj) + => Expose(obj, obj?.GetType() ?? typeof(object)); + + public CompilerObject Expose(object? obj, Type type) + => new RawIRCode(new([.. ExposeAsIR(obj, type)]) + { + Types = [RequireIR().CompileType(LoadType(type)).Unwrap()] + }); + + public CompilerObject Expose(Delegate @delegate) + { + var methodCO = LoadMethod(@delegate.Method); + var @object = ExposeAsIR(@delegate.Target); + var objectCode = new RawIRCode(new(@object)); + + return new Objects.BoundMethod() + { + Method = methodCO, + Object = objectCode + }; + } + + [MemberNotNull(nameof(castFunction))] + private void SetupExposeSystem() + { + var rt = RequireRuntime(); + + var castFunctionReturnType = new ZSharp.IR.GenericParameter("T"); + castFunction = new(castFunctionReturnType); + castFunction.GenericParameters.Add(castFunctionReturnType); + castFunction.Signature.Args.Parameters.Add(new("obj", rt.TypeSystem.Object)); + + rt.AddFunction(castFunction, ((Delegate)Cast).Method.GetGenericMethodDefinition()); + } + + public static T Cast(object obj) + => (T)obj; + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.IR.cs b/ZSharp.Compiler.ILLoader/il loader/ILLoader.IR.cs new file mode 100644 index 00000000..be276276 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/ILLoader.IR.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public IR? IR { get; } + + public IR RequireIR() + => IR ?? throw new InvalidOperationException("ILLoader was not initialized with a Runtime"); + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Namespaces.cs b/ZSharp.Compiler.ILLoader/il loader/ILLoader.Namespaces.cs index 4bef51e2..8f393c27 100644 --- a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Namespaces.cs +++ b/ZSharp.Compiler.ILLoader/il loader/ILLoader.Namespaces.cs @@ -18,11 +18,11 @@ public Namespace Namespace(string fullName) ); if (!Namespaces.TryGetValue(parts[0], out var @namespace)) - @namespace = Namespaces[parts[0]] = new(parts[0]); + @namespace = Namespaces[parts[0]] = new(parts[0], this); foreach (var part in parts.Skip(1)) if (!@namespace.Members.TryGetValue(part, out var member)) - @namespace.AddMember(part, member = new Namespace(part)); + @namespace.AddMember(part, member = new Namespace(part, this)); else if (member is not Namespace ns) throw new ArgumentException( $"{part} in {@namespace.FullName} is not a namespace" diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Runtime.cs b/ZSharp.Compiler.ILLoader/il loader/ILLoader.Runtime.cs new file mode 100644 index 00000000..73c75336 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/ILLoader.Runtime.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public Runtime.Runtime? Runtime { get; } + + public Runtime.Runtime RequireRuntime() + => Runtime ?? throw new InvalidOperationException("ILLoader was not initialized with a Runtime"); + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.TypeSystem.cs b/ZSharp.Compiler.ILLoader/il loader/ILLoader.TypeSystem.cs new file mode 100644 index 00000000..691d4730 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/il loader/ILLoader.TypeSystem.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ILLoader + { + public TypeSystem TypeSystem { get; } + } +} diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs b/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs index b9075009..f2445f66 100644 --- a/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs +++ b/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs @@ -2,18 +2,64 @@ { public sealed partial class ILLoader { - public Compiler Compiler { get; } - - public ILLoader(Compiler compiler) + public ILLoader(IR ir, Runtime.Runtime runtime) { - Compiler = compiler; + IR = ir; + Runtime = runtime; + + TypeSystem = new() + { + Array = new Objects.ArrayType(Runtime.TypeSystem.Array), + Boolean = new Objects.BooleanType(Runtime.TypeSystem.Boolean), + Char = new Objects.CharType(Runtime.TypeSystem.Char), + Float16 = new Objects.Float16Type(Runtime.TypeSystem.Float16), + Float32 = new Objects.Float32Type(Runtime.TypeSystem.Float32), + Float64 = new Objects.Float64Type(Runtime.TypeSystem.Float64), + Float128 = new Objects.Float128Type(Runtime.TypeSystem.Float128), + Object = new Objects.ObjectType(Runtime.TypeSystem.Object), + Pointer = new Objects.PointerType(Runtime.TypeSystem.Pointer), + Reference = new Objects.ReferenceType(Runtime.TypeSystem.Reference), + SInt8 = new Objects.SInt8Type(Runtime.TypeSystem.SInt8), + SInt16 = new Objects.SInt16Type(Runtime.TypeSystem.SInt16), + SInt32 = new Objects.SInt32Type(Runtime.TypeSystem.SInt32), + SInt64 = new Objects.SInt64Type(Runtime.TypeSystem.SInt64), + SIntNative = new Objects.SIntNativeType(Runtime.TypeSystem.SIntNative), + String = new Objects.StringType(Runtime.TypeSystem.String), + UInt8 = new Objects.UInt8Type(Runtime.TypeSystem.UInt8), + UInt16 = new Objects.UInt16Type(Runtime.TypeSystem.UInt16), + UInt32 = new Objects.UInt32Type(Runtime.TypeSystem.UInt32), + UInt64 = new Objects.UInt64Type(Runtime.TypeSystem.UInt64), + UIntNative = new Objects.UIntNativeType(Runtime.TypeSystem.UIntNative), + Void = new Objects.VoidType(Runtime.TypeSystem.Void), + }; - foreach (var (il, co) in (IEnumerable<(Type, IType)>)[ - (typeof(void), Compiler.TypeSystem.Void), + foreach (var (il, co) in (IEnumerable<(Type, CompilerObject)>)[ + (typeof(bool), TypeSystem.Boolean), + (typeof(char), TypeSystem.Char), + (typeof(Half), TypeSystem.Float16), + (typeof(float), TypeSystem.Float32), + (typeof(double), TypeSystem.Float64), + (typeof(decimal), TypeSystem.Float128), + (typeof(object), TypeSystem.Object), + (typeof(sbyte), TypeSystem.SInt8), + (typeof(short), TypeSystem.SInt16), + (typeof(int), TypeSystem.SInt32), + (typeof(long), TypeSystem.SInt64), + (typeof(nint), TypeSystem.SIntNative), + (typeof(string), TypeSystem.String), + (typeof(byte), TypeSystem.UInt8), + (typeof(ushort), TypeSystem.UInt16), + (typeof(uint), TypeSystem.UInt32), + (typeof(ulong), TypeSystem.UInt64), + (typeof(nuint), TypeSystem.UIntNative), + (typeof(void), TypeSystem.Void), ]) { typeCache[il] = co; } + + if (runtime is not null) + SetupExposeSystem(); } } } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs index 787262eb..5aa3c4a8 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs @@ -7,7 +7,9 @@ public CompilerObject LoadMethod(IL.MethodInfo method) if (method.IsGenericMethodDefinition) return LoadGenericMethod(method); - throw new NotImplementedException(); + var result = new Objects.Method(method, this); + + return result; } } } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.cs index 93901dc7..081dcbbf 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.cs @@ -14,6 +14,7 @@ public CompilerObject LoadMember(IL.MemberInfo member) IL.FieldInfo field => LoadField(field), IL.MethodInfo method => LoadMethod(method), IL.PropertyInfo property => LoadProperty(property), + Type type => LoadType(type), _ => throw new NotSupportedException() }; diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs index 50bdaa94..e4ca4917 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public IType LoadGenericClass(Type @class) + public CompilerObject LoadGenericClass(Type @class) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs index b9dca02d..a02d873e 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs @@ -2,12 +2,12 @@ { partial class ILLoader { - public IType LoadClass(Type @class) + public CompilerObject LoadClass(Type @class) { if (@class.IsGenericTypeDefinition) return LoadGenericClass(@class); - throw new NotImplementedException(); + return new Objects.Class(@class, this); } } } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs index 8baf2fbd..d3bc5166 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public IType LoadEnum(Type @enum) + public CompilerObject LoadEnum(Type @enum) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs index 0f904650..79af355b 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public IType LoadConstructedGenericType(Type type) + public CompilerObject LoadConstructedGenericType(Type type) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs index 6a67d7e0..e3d1a4c7 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public IType LoadGenericInterface(Type @enum) + public CompilerObject LoadGenericInterface(Type @enum) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs index 219d9484..a0b56a3d 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public IType LoadInterface(Type @interface) + public CompilerObject LoadInterface(Type @interface) { if (@interface.IsGenericTypeDefinition) return LoadGenericInterface(@interface); diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs index 95a0404a..545fa5ec 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public IType LoadModifiedType(Type type) + public CompilerObject LoadModifiedType(Type type) { if (type.IsArray) return LoadArrayType(type); if (type.IsPointer) return LoadPointerType(type); @@ -11,19 +11,32 @@ public IType LoadModifiedType(Type type) throw new NotSupportedException(); } - public IType LoadArrayType(Type array) - { - throw new NotImplementedException(); - } + public CompilerObject LoadArrayType(Type array) + => LoadModifiedType( + TypeSystem.Array, + array.GetElementType() ?? throw new ArgumentException("Type must have an element type", nameof(array)) + ); - public IType LoadPointerType(Type pointer) - { - throw new NotImplementedException(); - } + public CompilerObject LoadPointerType(Type pointer) + => LoadModifiedType( + TypeSystem.Array, + pointer.GetElementType() ?? throw new ArgumentException("Type must have an element type", nameof(pointer)) + ); - public IType LoadReferenceType(Type reference) + public CompilerObject LoadReferenceType(Type reference) + => LoadModifiedType( + TypeSystem.Array, + reference.GetElementType() ?? throw new ArgumentException("Type must have an element type", nameof(reference)) + ); + + private CompilerObject LoadModifiedType(CompilerObject modifier, Type inner) { - throw new NotImplementedException(); + if (!modifier.Is(out var typeModifier)) + throw new NotSupportedException(); + + var typeCO = LoadType(inner); + + return typeModifier.Modify(typeCO); } } } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs index 399d729e..7b685dd2 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public IType LoadGenericStruct(Type @enum) + public CompilerObject LoadGenericStruct(Type @enum) { throw new NotImplementedException(); } diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs index 99e5e70c..f4081f99 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs @@ -2,7 +2,7 @@ { partial class ILLoader { - public IType LoadStruct(Type @struct) + public CompilerObject LoadStruct(Type @struct) { if (@struct.IsGenericTypeDefinition) return LoadGenericStruct(@struct); diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs index 2c62e9ee..11680752 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs +++ b/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs @@ -2,9 +2,9 @@ { partial class ILLoader { - private readonly Dictionary typeCache = []; + private readonly Dictionary typeCache = []; - public IType LoadType(Type type) + public CompilerObject LoadType(Type type) { if (!typeCache.TryGetValue(type, out var @object)) @object = typeCache[type] = DispatchLoadType(type); @@ -12,7 +12,7 @@ public IType LoadType(Type type) return @object; } - private IType DispatchLoadType(Type type) + private CompilerObject DispatchLoadType(Type type) { if (type.IsConstructedGenericType) return LoadConstructedGenericType(type); diff --git a/ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs b/ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs new file mode 100644 index 00000000..1b4aa3cc --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs @@ -0,0 +1,30 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ModuleBodyLoader + : ILazilyLoadMembers + { + private readonly Dictionary> ilMembers = []; + + public void AddLazyMember(string member, IL.MemberInfo lazyLoadedMember) + { + if (!ilMembers.TryGetValue(member, out var list)) + ilMembers[member] = list = []; + + list.Add(lazyLoadedMember); + } + + public void AddMember(IL.MemberInfo member) + => AddLazyMember(member.AliasOrName(), member); + + public bool LoadMember(string member) + { + if (!ilMembers.TryGetValue(member, out var list)) + return false; + + foreach (var item in list) + Container.AddMember(member, LoadMember(item)); + + return true; + } + } +} diff --git a/ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.cs b/ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.cs new file mode 100644 index 00000000..4b999250 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler.ILLoader +{ + internal sealed partial class ModuleBodyLoader(IAddMember container, ILLoader loader) + { + public ILLoader Loader { get; } = loader; + + public IAddMember Container { get; } = container; + } +} diff --git a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs b/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs new file mode 100644 index 00000000..5e7f787b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs @@ -0,0 +1,12 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ModuleBodyLoader + { + private CompilerObject LoadField(IL.FieldInfo field) + { + if (!field.IsStatic) throw new ArgumentException("Only static fields are supported.", nameof(field)); + + return new Objects.Global(field, Loader); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs b/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs new file mode 100644 index 00000000..405fdd8d --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ModuleBodyLoader + { + private CompilerObject LoadGenericMethod(IL.MethodInfo method) + { + return new Objects.GenericFunction(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs b/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs new file mode 100644 index 00000000..cf3db067 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ModuleBodyLoader + { + private CompilerObject LoadMethod(IL.MethodInfo method) + { + if (!method.IsStatic) throw new ArgumentException("Only static methods are supported.", nameof(method)); + + if (method.IsGenericMethodDefinition) + return LoadGenericMethod(method); + + return new Objects.Function(method, Loader); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs b/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs new file mode 100644 index 00000000..1e4af706 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ModuleBodyLoader + { + private CompilerObject LoadProperty(IL.PropertyInfo property) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs b/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs new file mode 100644 index 00000000..e015e4e8 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class ModuleBodyLoader + { + public CompilerObject LoadMember(IL.MemberInfo member) + => member switch + { + IL.FieldInfo field => LoadField(field), + IL.MethodInfo method => LoadMethod(method), + IL.PropertyInfo property => LoadProperty(property), + Type type => Loader.LoadType(type), + _ => throw new NotSupportedException(), + }; + } +} diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs index 34676c1d..8de6ac65 100644 --- a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs +++ b/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs @@ -9,7 +9,7 @@ private CompilerObject LoadMethod(IL.MethodInfo method) if (method.IsGenericMethodDefinition) return LoadGenericMethod(method); - return new Objects.Function(); + return new Objects.Function(method, Loader); } } } diff --git a/ZSharp.Compiler.ILLoader/objects/GlobalUsings.cs b/ZSharp.Compiler.ILLoader/objects/GlobalUsings.cs index ad74d913..cee72fe1 100644 --- a/ZSharp.Compiler.ILLoader/objects/GlobalUsings.cs +++ b/ZSharp.Compiler.ILLoader/objects/GlobalUsings.cs @@ -5,7 +5,5 @@ global using MemberName = string; global using MemberIndex = int; -global using CompilerObjectResult = ZSharp.Compiler.Result< - ZSharp.Objects.CompilerObject, string ->; +global using CompilerObjectResult = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.Call.cs b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.Call.cs new file mode 100644 index 00000000..61e876dc --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.Call.cs @@ -0,0 +1,29 @@ + +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Function + : ICTCallable + { + CompilerObjectResult ICTCallable.Call(Compiler compiler, Argument[] arguments) + { + IRCode result = new(); + + foreach (var argument in arguments) + { + if ( + compiler.IR.CompileCode(argument.Object, null) + .When(out var argumentCode) + .Error(out var error) + ) + return CompilerObjectResult.Error(error); + + result.Instructions.AddRange(argumentCode!.Instructions); + } + + result.Instructions.Add(new ZSharp.IR.VM.Call(GetIR())); + result.Types.Add(GetIR().ReturnType); + + return CompilerObjectResult.Ok(new RawIRCode(result)); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IL.cs b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IL.cs index d1bafdd0..8ccc216d 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IL.cs +++ b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IL.cs @@ -2,6 +2,8 @@ { partial class Function { - public IL.MethodInfo IL { get; } + private readonly ILLoader loader = loader; + + public IL.MethodInfo IL { get; } = il; } } diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IR.cs b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IR.cs new file mode 100644 index 00000000..cdd90da4 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IR.cs @@ -0,0 +1,21 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Function + { + private ZSharp.IR.Function? IR { get; set; } + + private ZSharp.IR.Function GetIR() + { + if (IR is null) + { + var returnTypeCO = loader.LoadType(IL.ReturnType); + if (loader.RequireIR().CompileType(returnTypeCO).When(out var returnTypeIR).Error(out var error)) + throw new InvalidOperationException($"Failed to load return type for method {IL.Name}: {error}"); + IR = new(returnTypeIR!); + loader.RequireRuntime().AddFunction(IR, IL); + } + + return IR; + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.cs b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.cs index 6158d4ed..17dc63ac 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.cs +++ b/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler.ILLoader.Objects { - public sealed partial class Function + public sealed partial class Function(IL.MethodInfo il, ILLoader loader) : CompilerObject { } diff --git a/ZSharp.Compiler.ILLoader/objects/modular/global/Global.Type.cs b/ZSharp.Compiler.ILLoader/objects/modular/global/Global.Type.cs index 257ad31b..18321fdd 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/global/Global.Type.cs +++ b/ZSharp.Compiler.ILLoader/objects/modular/global/Global.Type.cs @@ -3,6 +3,6 @@ partial class Global : ITyped { - public IType Type { get; } + public CompilerObject Type { get; } } } diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Globals.cs b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Globals.cs new file mode 100644 index 00000000..22a75e40 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Globals.cs @@ -0,0 +1,27 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Module + { + private void PrepareGlobals(IEnumerable scopes) + { + foreach (var scope in scopes) + PrepareGlobals(scope); + } + + private void PrepareGlobals(Type scope) + { + foreach (var member in scope.GetMembers()) + { + if (member.DeclaringType != scope) continue; + + if (member is IL.MethodInfo method && method.IsOperator(out var op)) + { + Loader.OnLoadOperator?.Invoke(op, method); + continue; + } + + BodyLoader.AddMember(member); + } + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.IL.cs b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.IL.cs index a7477915..de8fcbc6 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.IL.cs +++ b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.IL.cs @@ -3,7 +3,5 @@ partial class Module { public IL.Module IL { get; } - - public Type? Globals { get; } } } diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs index 742f45af..bbe2e5c2 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs +++ b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs @@ -2,38 +2,16 @@ { partial class Module { - private ModuleLoader? _moduleLoader; - public ILLoader Loader { get; } - internal ModuleLoader GlobalsLoader - { - get - { - if (_moduleLoader is not null) - return _moduleLoader; - - Interlocked.CompareExchange(ref _moduleLoader, new(Loader), null); - return _moduleLoader; - } - } + internal ModuleBodyLoader BodyLoader { get; } public CompilerObject? LoadMember(string name) { - var members = Globals?.GetMember(name); - - if (members is not null && members.Length > 0) - { - foreach (var member in members) - AddMember(name, GlobalsLoader.LoadMember(member)); - - return Members[name]; - } + if (!BodyLoader.LoadMember(name)) + return null; - var type = IL.GetType(name); - if (type is null) return null; - if (!type.IsPublic) return null; - return Loader.LoadType(type); + return Members[name]; } } } diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Member.cs b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Member.cs index 8c704e7b..59fd92c7 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Member.cs +++ b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Member.cs @@ -3,7 +3,8 @@ namespace ZSharp.Compiler.ILLoader.Objects { partial class Module - : ICTGetMember + : IAddMember + , ICTGetMember { public Mapping Members { get; } = []; @@ -19,10 +20,8 @@ public void AddMember(string name, CompilerObject member) CompilerObjectResult ICTGetMember.Member(Compiler compiler, MemberName member) { - if (!Members.TryGetValue(member, out var result)) - if ((result = LoadMember(member)) is not null) - Members.Add(member, result); - else return CompilerObjectResult.Error( + if (!Members.TryGetValue(member, out var result) && (result = LoadMember(member)) is null) + return CompilerObjectResult.Error( $"Could not find member {member} in module {IL.Name}" ); diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs index d1c97c92..60bc53dc 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs +++ b/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs @@ -1,6 +1,8 @@ -namespace ZSharp.Compiler.ILLoader.Objects +using System.Reflection; + +namespace ZSharp.Compiler.ILLoader.Objects { - public sealed partial class Module + internal sealed partial class Module : CompilerObject { public string Name => IL.Name; @@ -8,13 +10,37 @@ public sealed partial class Module public Module(IL.Module il, ILLoader loader) { IL = il; - Globals = IL.GetType(""); Loader = loader; + BodyLoader = new(this, loader); + + Dictionary mappedNamespaces = []; + foreach (var mapping in il.GetCustomAttributes()) + mappedNamespaces[mapping.OldName] = mapping.NewName; + + List moduleScopes = []; foreach (var type in il.GetTypes()) if (!type.IsPublic) continue; - else if (type.Namespace is not null) - Loader.Namespace(type.Namespace).AddLazyMember(type.Name, () => Loader.LoadType(type)); + else + { + if (type.Namespace is string ns) + ns = mappedNamespaces.GetValueOrDefault(ns, ns); + else ns = string.Empty; + + if (type.IsModuleScope()) + { + moduleScopes.Add(type); + continue; + } + + ILazilyLoadMembers lazyLoader = ns == string.Empty + ? BodyLoader + : Loader.Namespace(ns); + + lazyLoader.AddLazyMember(type.AliasOrName(), type); + } + + PrepareGlobals(moduleScopes); } } } diff --git a/ZSharp.Compiler.ILLoader/objects/modular/property/GlobalProperty.cs b/ZSharp.Compiler.ILLoader/objects/modular/property/GlobalProperty.cs new file mode 100644 index 00000000..c6cb9f4a --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/property/GlobalProperty.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class GlobalProperty + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.IL.cs b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.IL.cs new file mode 100644 index 00000000..6da65ff2 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.IL.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class TypeAsModule + { + public Type IL { get; } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs new file mode 100644 index 00000000..07b4471a --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class TypeAsModule + { + public ILLoader Loader { get; } + + internal ModuleBodyLoader BodyLoader { get; } + + public CompilerObject? LoadMember(string name) + { + if (!BodyLoader.LoadMember(name)) + return null; + + return Members[name]; + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs new file mode 100644 index 00000000..d8e5eacf --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs @@ -0,0 +1,31 @@ +using CommonZ.Utils; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class TypeAsModule + : IAddMember + , ICTGetMember + { + public Mapping Members { get; } = []; + + public void AddMember(string name, CompilerObject member) + { + var result = OnAddResult.None; + if (member is IOnAddTo onAdd) + result = onAdd.OnAddTo(this); + + if (result == OnAddResult.None) + Members.Add(name, member); + } + + CompilerObjectResult ICTGetMember.Member(Compiler compiler, MemberName member) + { + if (!Members.TryGetValue(member, out var result) && (result = LoadMember(member)) is null) + return CompilerObjectResult.Error( + $"Could not find member {member} in module {IL.Name}" + ); + + return CompilerObjectResult.Ok(result); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Namespace.cs b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Namespace.cs new file mode 100644 index 00000000..c23cd896 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Namespace.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class TypeAsModule + { + public string RootNamespace { get; } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs new file mode 100644 index 00000000..dab613e4 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs @@ -0,0 +1,33 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class TypeAsModule + { + private void Prepare() + { + foreach (var member in IL.GetMembers()) + Prepare(member); + } + + private void Prepare(IL.MemberInfo member) + { + if (member.DeclaringType != IL) + return; + + if (member is Type type && type.IsModuleScope()) + throw new InvalidOperationException($"Module scope types are not allowed: {type.FullName}"); + + if (member is IL.MethodInfo method && method.IsOperator()) + { + Console.WriteLine($"Skipping operator method: {method.Name}"); + return; + } + + var @namespace = member.GetNamespaceOverride(RootNamespace); + ILazilyLoadMembers lazyLoader = @namespace == string.Empty + ? BodyLoader + : Loader.Namespace(@namespace); + + lazyLoader.AddLazyMember(member.AliasOrName(), member); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.cs b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.cs new file mode 100644 index 00000000..fa936e47 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.cs @@ -0,0 +1,23 @@ +using System.Reflection; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + internal sealed partial class TypeAsModule + : CompilerObject + { + public string Name => IL.Name; + + public TypeAsModule(Type il, ILLoader loader) + { + IL = il; + Loader = loader; + BodyLoader = new(this, loader); + + if (il.GetCustomAttribute() is SetNamespaceAttribute setNamespace) + RootNamespace = setNamespace.Name; + else RootNamespace = string.Empty; + + Prepare(); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.LazyLoad.cs b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.LazyLoad.cs index 9c7910b9..ddb6282d 100644 --- a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.LazyLoad.cs +++ b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.LazyLoad.cs @@ -1,10 +1,21 @@ namespace ZSharp.Compiler.ILLoader.Objects { partial class Namespace + : ILazilyLoadMembers { - private readonly Dictionary> lazyLoadedMembers = []; + private readonly Dictionary lazyLoadedMembers = []; - public void AddLazyMember(MemberName member, Func lazyLoadedMember) + public ILLoader Loader { get; } = loader; + + public void AddLazyMember(MemberName member, IL.MemberInfo lazyLoadedMember) => lazyLoadedMembers.Add(member, lazyLoadedMember); + + public CompilerObject? LoadMember(string name) + { + if (!lazyLoadedMembers.TryGetValue(name, out var member)) + return null; + + return Loader.LoadMember(member); + } } } diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs index 4a9ac600..0fec91b2 100644 --- a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs +++ b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs @@ -19,18 +19,14 @@ public void AddMember(string name, CompilerObject member) CompilerObjectResult ICTGetMember.Member(Compiler compiler, MemberName member) { - if ( - !Members.TryGetValue(member, out var result) - && lazyLoadedMembers.Remove(member, out var lazyLoad) - ) - AddMember(member, result = lazyLoad()); + if (!Members.TryGetValue(member, out var result)) + if ((result = LoadMember(member)) is not null) + AddMember(member, result); + else return CompilerObjectResult.Error( + $"Could not find member {member} in namespace {FullName}" + ); - if (result is not null) - return CompilerObjectResult.Ok(result); - - return CompilerObjectResult.Error( - $"Can't find member {member} in namespace {FullName}" - ); + return CompilerObjectResult.Ok(result); } } } diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.cs b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.cs index 92e6da02..7c57318f 100644 --- a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.cs +++ b/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler.ILLoader.Objects { - public sealed partial class Namespace(string name) + public sealed partial class Namespace(string name, ILLoader loader) : CompilerObject { public string Name { get; set; } = name; diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IL.cs b/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IL.cs new file mode 100644 index 00000000..dc3c5a7f --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IL.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Class + { + public Type IL { get; } + + public ILLoader Loader { get; } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IR.cs b/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IR.cs new file mode 100644 index 00000000..cf290e47 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IR.cs @@ -0,0 +1,28 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Class + : ICompileIRDefinitionAs + , ICompileIRType> + { + private ZSharp.IR.Class? IR { get; set; } + + Result ICompileIRDefinitionAs.CompileIRDefinition(IR ir, object? target) + => Result.Ok(GetIR()); + + Result> ICompileIRType>.CompileIRType(IR ir) + => Result>.Ok(new ClassReference(GetIR())); + + private ZSharp.IR.Class GetIR() + { + if (IR is null) + { + IR = new(IL.Name); + Loader.RequireRuntime().AddTypeDefinition(IR, IL); + } + + return IR; + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.T.cs new file mode 100644 index 00000000..480e3571 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Class + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.cs b/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.cs new file mode 100644 index 00000000..52ad5e95 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.cs @@ -0,0 +1,12 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Class + : CompilerObject + { + public Class(Type il, ILLoader loader) + { + IL = il; + Loader = loader; + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.T.cs new file mode 100644 index 00000000..66aa704b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class GenericClass + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.cs b/ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.cs new file mode 100644 index 00000000..d392f0e5 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class GenericClass + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.T.cs new file mode 100644 index 00000000..f3194f43 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Constructor + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.cs b/ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.cs new file mode 100644 index 00000000..3fe8b545 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Constructor + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.T.cs new file mode 100644 index 00000000..392129bd --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Enum + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.cs b/ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.cs new file mode 100644 index 00000000..56ee35e7 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Enum + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/field/Field.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/field/Field.T.cs new file mode 100644 index 00000000..67362730 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/field/Field.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Field + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/field/Field.cs b/ZSharp.Compiler.ILLoader/objects/oop/field/Field.cs new file mode 100644 index 00000000..d8a4aa0e --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/field/Field.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Field + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.T.cs new file mode 100644 index 00000000..e7c558b1 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Interface + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.cs b/ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.cs new file mode 100644 index 00000000..732c7c8b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Interface + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.T.cs new file mode 100644 index 00000000..39fae699 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class GenericInterface + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.cs b/ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.cs new file mode 100644 index 00000000..9ec40ec6 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class GenericInterface + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs b/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs new file mode 100644 index 00000000..920a0e96 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class BoundMethod + : ICTCallable + { + CompilerObjectResult ICTCallable.Call(Compiler compiler, Argument[] arguments) + { + if (Object is not null) + arguments = [ + new(Object), + .. arguments + ]; + + return compiler.CG.Call(Method, arguments); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.T.cs new file mode 100644 index 00000000..bcaa893f --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class BoundMethod + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.cs b/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.cs new file mode 100644 index 00000000..c775e5f3 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class BoundMethod + : CompilerObject + { + public required CompilerObject Method { get; set; } + + public required CompilerObject? Object { get; set; } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.Call.cs b/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.Call.cs new file mode 100644 index 00000000..ded3ea72 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.Call.cs @@ -0,0 +1,29 @@ + +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Method + : ICTCallable + { + CompilerObjectResult ICTCallable.Call(Compiler compiler, Argument[] arguments) + { + IRCode result = new(); + + foreach (var argument in arguments) + { + if ( + compiler.IR.CompileCode(argument.Object, null) + .When(out var argumentCode) + .Error(out var error) + ) + return CompilerObjectResult.Error(error); + + result.Instructions.AddRange(argumentCode!.Instructions); + } + + result.Instructions.Add(new ZSharp.IR.VM.Call(GetIR())); + result.Types.Add(GetIR().ReturnType); + + return CompilerObjectResult.Ok(new RawIRCode(result)); + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IL.cs b/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IL.cs new file mode 100644 index 00000000..52c32535 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IL.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Method + { + public IL.MethodInfo IL { get; } + + private ILLoader Loader { get; } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IR.cs b/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IR.cs new file mode 100644 index 00000000..19fd85bb --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IR.cs @@ -0,0 +1,21 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Method + { + private ZSharp.IR.Method? IR { get; set; } + + private ZSharp.IR.Method GetIR() + { + if (IR is null) + { + var returnTypeCO = Loader.LoadType(IL.ReturnType); + if (Loader.RequireIR().CompileType(returnTypeCO).When(out var returnTypeIR).Error(out var error)) + throw new InvalidOperationException($"Failed to load return type for method {IL.Name}: {error}"); + IR = new(returnTypeIR!); + Loader.RequireRuntime().AddFunction(IR.UnderlyingFunction, IL); + } + + return IR; + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.T.cs new file mode 100644 index 00000000..085087e7 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Method + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.cs b/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.cs new file mode 100644 index 00000000..ec0c75f7 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.cs @@ -0,0 +1,12 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Method + : CompilerObject + { + public Method(IL.MethodInfo il, ILLoader loader) + { + IL = il; + Loader = loader; + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.T.cs new file mode 100644 index 00000000..2d197722 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class GenericMethod + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.cs b/ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.cs new file mode 100644 index 00000000..bba32a29 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class GenericMethod + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/property/Property.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/property/Property.T.cs new file mode 100644 index 00000000..5653ad0b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/property/Property.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Property + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/modular/property/Property.cs b/ZSharp.Compiler.ILLoader/objects/oop/property/Property.cs similarity index 80% rename from ZSharp.Compiler.ILLoader/objects/modular/property/Property.cs rename to ZSharp.Compiler.ILLoader/objects/oop/property/Property.cs index abd22931..ae20fce0 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/property/Property.cs +++ b/ZSharp.Compiler.ILLoader/objects/oop/property/Property.cs @@ -1,6 +1,7 @@ namespace ZSharp.Compiler.ILLoader.Objects { public sealed partial class Property + : CompilerObject { } } diff --git a/ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.T.cs new file mode 100644 index 00000000..ec682056 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class Struct + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.cs b/ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.cs new file mode 100644 index 00000000..39243b94 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class Struct + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.T.cs new file mode 100644 index 00000000..6c6bf285 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + partial class GenericStruct + { + + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.cs b/ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.cs new file mode 100644 index 00000000..fe32bb0f --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed partial class GenericStruct + : CompilerObject + { + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/array/ArrayType.cs b/ZSharp.Compiler.ILLoader/objects/types/array/ArrayType.cs new file mode 100644 index 00000000..b402f45c --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/array/ArrayType.cs @@ -0,0 +1,10 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class ArrayType(OOPType type) + : CompilerObject + { + private readonly OOPType type = type; + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/boolean/BooleanType.cs b/ZSharp.Compiler.ILLoader/objects/types/boolean/BooleanType.cs new file mode 100644 index 00000000..14a65d0b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/boolean/BooleanType.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class BooleanType(OOPTypeReference type) + : CompilerObject + , ICompileIRType + { + private readonly OOPTypeReference type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/char/CharType.cs b/ZSharp.Compiler.ILLoader/objects/types/char/CharType.cs new file mode 100644 index 00000000..82bc5616 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/char/CharType.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class CharType(OOPTypeReference type) + : CompilerObject + , ICompileIRType + { + private readonly OOPTypeReference type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/float/Float128Type.cs b/ZSharp.Compiler.ILLoader/objects/types/float/Float128Type.cs new file mode 100644 index 00000000..1b37d698 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/float/Float128Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class Float128Type(OOPTypeReference type) + : CompilerObject + , ICompileIRType + { + private readonly OOPTypeReference type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/float/Float16Type.cs b/ZSharp.Compiler.ILLoader/objects/types/float/Float16Type.cs new file mode 100644 index 00000000..e04c7d30 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/float/Float16Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class Float16Type(OOPTypeReference type) + : CompilerObject + , ICompileIRType + { + private readonly OOPTypeReference type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/float/Float32Type.cs b/ZSharp.Compiler.ILLoader/objects/types/float/Float32Type.cs new file mode 100644 index 00000000..318ffbf9 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/float/Float32Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class Float32Type(OOPTypeReference type) + : CompilerObject + , ICompileIRType + { + private readonly OOPTypeReference type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/float/Float64Type.cs b/ZSharp.Compiler.ILLoader/objects/types/float/Float64Type.cs new file mode 100644 index 00000000..94678dfc --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/float/Float64Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class Float64Type(OOPTypeReference type) + : CompilerObject + , ICompileIRType + { + private readonly OOPTypeReference type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/SInt16Type.cs b/ZSharp.Compiler.ILLoader/objects/types/int/SInt16Type.cs new file mode 100644 index 00000000..b6e3320e --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/int/SInt16Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class SInt16Type(IType type) + : CompilerObject + , ICompileIRType + { + private readonly IType type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/SInt32Type.cs b/ZSharp.Compiler.ILLoader/objects/types/int/SInt32Type.cs new file mode 100644 index 00000000..0ec1b45d --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/int/SInt32Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class SInt32Type(IType type) + : CompilerObject + , ICompileIRType + { + private readonly IType type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/SInt64Type.cs b/ZSharp.Compiler.ILLoader/objects/types/int/SInt64Type.cs new file mode 100644 index 00000000..49f5eae0 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/int/SInt64Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class SInt64Type(IType type) + : CompilerObject + , ICompileIRType + { + private readonly IType type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/SInt8Type.cs b/ZSharp.Compiler.ILLoader/objects/types/int/SInt8Type.cs new file mode 100644 index 00000000..3207bb88 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/int/SInt8Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class SInt8Type(IType type) + : CompilerObject + , ICompileIRType + { + private readonly IType type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/SIntNativeType.cs b/ZSharp.Compiler.ILLoader/objects/types/int/SIntNativeType.cs new file mode 100644 index 00000000..98b68c7b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/int/SIntNativeType.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class SIntNativeType(IType type) + : CompilerObject + , ICompileIRType + { + private readonly IType type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/UInt16Type.cs b/ZSharp.Compiler.ILLoader/objects/types/int/UInt16Type.cs new file mode 100644 index 00000000..24440729 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/int/UInt16Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class UInt16Type(IType type) + : CompilerObject + , ICompileIRType + { + private readonly IType type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/UInt32Type.cs b/ZSharp.Compiler.ILLoader/objects/types/int/UInt32Type.cs new file mode 100644 index 00000000..9a715f2b --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/int/UInt32Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class UInt32Type(IType type) + : CompilerObject + , ICompileIRType + { + private readonly IType type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/UInt64Type.cs b/ZSharp.Compiler.ILLoader/objects/types/int/UInt64Type.cs new file mode 100644 index 00000000..e8913cc0 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/int/UInt64Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class UInt64Type(IType type) + : CompilerObject + , ICompileIRType + { + private readonly IType type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/UInt8Type.cs b/ZSharp.Compiler.ILLoader/objects/types/int/UInt8Type.cs new file mode 100644 index 00000000..463f8b2c --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/int/UInt8Type.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class UInt8Type(IType type) + : CompilerObject + , ICompileIRType + { + private readonly IType type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/UIntNativeType.cs b/ZSharp.Compiler.ILLoader/objects/types/int/UIntNativeType.cs new file mode 100644 index 00000000..8ff169ad --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/int/UIntNativeType.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class UIntNativeType(IType type) + : CompilerObject + , ICompileIRType + { + private readonly IType type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/object/ObjectType.cs b/ZSharp.Compiler.ILLoader/objects/types/object/ObjectType.cs new file mode 100644 index 00000000..31c66e26 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/object/ObjectType.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class ObjectType(OOPTypeReference type) + : CompilerObject + , ICompileIRType + { + private readonly OOPTypeReference type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/pointer/PointerType.cs b/ZSharp.Compiler.ILLoader/objects/types/pointer/PointerType.cs new file mode 100644 index 00000000..c46aba60 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/pointer/PointerType.cs @@ -0,0 +1,10 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class PointerType(OOPType type) + : CompilerObject + { + private readonly OOPType type = type; + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/reference/ReferenceType.cs b/ZSharp.Compiler.ILLoader/objects/types/reference/ReferenceType.cs new file mode 100644 index 00000000..47037c7a --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/reference/ReferenceType.cs @@ -0,0 +1,10 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class ReferenceType(OOPType type) + : CompilerObject + { + private readonly OOPType type = type; + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/string/StringType.cs b/ZSharp.Compiler.ILLoader/objects/types/string/StringType.cs new file mode 100644 index 00000000..71d5e197 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/string/StringType.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class StringType(OOPTypeReference type) + : CompilerObject + , ICompileIRType + { + private readonly OOPTypeReference type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/types/void/VoidType.cs b/ZSharp.Compiler.ILLoader/objects/types/void/VoidType.cs new file mode 100644 index 00000000..a45312d0 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/objects/types/void/VoidType.cs @@ -0,0 +1,14 @@ +using ZSharp.IR; + +namespace ZSharp.Compiler.ILLoader.Objects +{ + public sealed class VoidType(OOPTypeReference type) + : CompilerObject + , ICompileIRType + { + private readonly OOPTypeReference type = type; + + Result ICompileIRType.CompileIRType(IR ir) + => Result.Ok(type); + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Array.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Array.cs new file mode 100644 index 00000000..e0ff40b1 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Array.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class TypeSystem + { + public required CompilerObject Array { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Boolean.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Boolean.cs new file mode 100644 index 00000000..909fe79c --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Boolean.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class TypeSystem + { + public required CompilerObject Boolean { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Char.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Char.cs new file mode 100644 index 00000000..52c357d0 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Char.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class TypeSystem + { + public required CompilerObject Char { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Float.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Float.cs new file mode 100644 index 00000000..cc5b29d3 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Float.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class TypeSystem + { + public required CompilerObject Float16 { get; init; } + + public required CompilerObject Float32 { get; init; } + + public required CompilerObject Float64 { get; init; } + + public required CompilerObject Float128 { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Object.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Object.cs new file mode 100644 index 00000000..c50ae11a --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Object.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class TypeSystem + { + public required CompilerObject Object { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Pointer.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Pointer.cs new file mode 100644 index 00000000..40040036 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Pointer.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class TypeSystem + { + public required CompilerObject Pointer { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Reference.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Reference.cs new file mode 100644 index 00000000..5b1fce9a --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Reference.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class TypeSystem + { + public required CompilerObject Reference { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.SInt.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.SInt.cs new file mode 100644 index 00000000..09c43fe7 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.SInt.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class TypeSystem + { + public required CompilerObject SInt8 { get; init; } + + public required CompilerObject SInt16 { get; init; } + + public required CompilerObject SInt32 { get; init; } + + public required CompilerObject SInt64 { get; init; } + + public required CompilerObject SIntNative { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.String.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.String.cs new file mode 100644 index 00000000..3388d09a --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.String.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class TypeSystem + { + public required CompilerObject String { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.UInt.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.UInt.cs new file mode 100644 index 00000000..f66147c4 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.UInt.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class TypeSystem + { + public required CompilerObject UInt8 { get; init; } + + public required CompilerObject UInt16 { get; init; } + + public required CompilerObject UInt32 { get; init; } + + public required CompilerObject UInt64 { get; init; } + + public required CompilerObject UIntNative { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Void.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Void.cs new file mode 100644 index 00000000..2e700da9 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.Void.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + partial class TypeSystem + { + public required CompilerObject Void { get; init; } + } +} diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.cs b/ZSharp.Compiler.ILLoader/type system/TypeSystem.cs new file mode 100644 index 00000000..5e208bd8 --- /dev/null +++ b/ZSharp.Compiler.ILLoader/type system/TypeSystem.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.ILLoader +{ + public sealed partial class TypeSystem() + { + + } +} diff --git a/ZSharp.Compiler.IR/GlobalUsings.cs b/ZSharp.Compiler.IR/GlobalUsings.cs index 80e8e9fd..6d3026e3 100644 --- a/ZSharp.Compiler.IR/GlobalUsings.cs +++ b/ZSharp.Compiler.IR/GlobalUsings.cs @@ -1,4 +1,3 @@ -global using CompilerObject = ZSharp.Objects.CompilerObject; -global using Error = string; +global using ZSharp.IR; global using TargetPlatform = object; diff --git a/ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj b/ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj index 01130ae1..dd8b2233 100644 --- a/ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj +++ b/ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj @@ -8,7 +8,7 @@ - + diff --git a/ZSharp.Compiler.IR/common/ICompileIROOPTypeReference.cs b/ZSharp.Compiler.IR/common/ICompileIROOPTypeReference.cs new file mode 100644 index 00000000..ff6a9eb7 --- /dev/null +++ b/ZSharp.Compiler.IR/common/ICompileIROOPTypeReference.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Compiler +{ + public interface ICompileIROOPTypeReference + : ICompileIRReference + , ICompileIRReference> + where T : OOPType + { + Result ICompileIRReference.CompileIRReference(IR ir) + => (this as ICompileIRReference < OOPTypeReference < T >>).CompileIRReference(ir).When(v => v as OOPTypeReference); + } +} diff --git a/ZSharp.Compiler.IR/compile/Compiler.cs b/ZSharp.Compiler.IR/compile/Compiler.cs deleted file mode 100644 index 940c4752..00000000 --- a/ZSharp.Compiler.IR/compile/Compiler.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.IRCompiler -{ - public sealed partial class Compiler(IR.RuntimeModule runtimeModule) - { - public IR.RuntimeModule RuntimeModule { get; } = runtimeModule; - } -} diff --git a/ZSharp.Compiler.IR/compile/services/Compiler.Code.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Code.cs deleted file mode 100644 index 6e1cb47c..00000000 --- a/ZSharp.Compiler.IR/compile/services/Compiler.Code.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.IRCompiler -{ - partial class Compiler - { - public ZSharp.Compiler.Result CompileCode(CompilerObject @object, TargetPlatform? target) - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs deleted file mode 100644 index 45d300d5..00000000 --- a/ZSharp.Compiler.IR/compile/services/Compiler.Definition.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace ZSharp.IRCompiler -{ - partial class Compiler - { - public ZSharp.Compiler.Result CompileDefinition(CompilerObject @object, TargetPlatform? target) - where T : IR.IRDefinition - { - throw new NotImplementedException(); - } - - public void CompileDefinition(CompilerObject @object, Owner owner, TargetPlatform? target) - where Owner : IR.IRDefinition - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs deleted file mode 100644 index 12a3489c..00000000 --- a/ZSharp.Compiler.IR/compile/services/Compiler.Reference.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZSharp.IRCompiler -{ - partial class Compiler - { - public ZSharp.Compiler.Result CompileReference(CompilerObject @object) - where T : class - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Compiler.IR/compile/services/Compiler.Type.cs b/ZSharp.Compiler.IR/compile/services/Compiler.Type.cs deleted file mode 100644 index cb40d759..00000000 --- a/ZSharp.Compiler.IR/compile/services/Compiler.Type.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ZSharp.IRCompiler -{ - partial class Compiler - { - public ZSharp.Compiler.Result CompileType(CompilerObject @object) - { - throw new NotImplementedException(); - } - - public ZSharp.Compiler.Result CompileType(CompilerObject @object) - where T : class, IR.IType - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Compiler/core/code/IRCode.cs b/ZSharp.Compiler.IR/core/IRCode.cs similarity index 90% rename from ZSharp.Compiler/core/code/IRCode.cs rename to ZSharp.Compiler.IR/core/IRCode.cs index eb976ac0..03910cc9 100644 --- a/ZSharp.Compiler/core/code/IRCode.cs +++ b/ZSharp.Compiler.IR/core/IRCode.cs @@ -1,10 +1,11 @@ using CommonZ.Utils; +using ZSharp.IR; namespace ZSharp.Compiler { public sealed class IRCode { - public IRInstructions Instructions { get; init; } = []; + public Collection Instructions { get; init; } = []; public int MaxStackSize { get; set; } @@ -47,7 +48,7 @@ public void Append(IRCode other) public static readonly IRCode Empty = new() { - Instructions = IRInstructions.Empty, + Instructions = [], MaxStackSize = 0, Types = [], }; diff --git a/ZSharp.Compiler.IR/ir/IR.cs b/ZSharp.Compiler.IR/ir/IR.cs new file mode 100644 index 00000000..c0417d05 --- /dev/null +++ b/ZSharp.Compiler.IR/ir/IR.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public sealed partial class IR(ZSharp.IR.RuntimeModule runtimeModule) + { + public ZSharp.IR.RuntimeModule RuntimeModule { get; } = runtimeModule; + } +} diff --git a/ZSharp.Compiler.IR/ir/services/IR.Code.cs b/ZSharp.Compiler.IR/ir/services/IR.Code.cs new file mode 100644 index 00000000..a81c1f81 --- /dev/null +++ b/ZSharp.Compiler.IR/ir/services/IR.Code.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler +{ + partial class IR + { + public Result CompileCode(CompilerObject @object, TargetPlatform? target) + { + if (@object.Is(out var compile)) + return compile.CompileIRCode(this, target); + + return Result.Error( + $"Object of type { @object.GetType().Name } does not implement ICompileIRCode" + ); + } + } +} diff --git a/ZSharp.Compiler.IR/ir/services/IR.Definition.cs b/ZSharp.Compiler.IR/ir/services/IR.Definition.cs new file mode 100644 index 00000000..46a1914b --- /dev/null +++ b/ZSharp.Compiler.IR/ir/services/IR.Definition.cs @@ -0,0 +1,27 @@ +namespace ZSharp.Compiler +{ + partial class IR + { + public Result CompileDefinition(CompilerObject @object, TargetPlatform? target) + where T : IRDefinition + { + if (@object.Is>(out var compile)) + return compile.CompileIRDefinition(this, target); + + return Result.Error( + $"Cannot compile definition for object of type {@object}" + ); + } + + public bool CompileDefinition(CompilerObject @object, Owner owner, TargetPlatform? target) + where Owner : IRDefinition + { + if (!@object.Is>(out var compile)) + return false; + + + compile.CompileIRDefinition(this, owner, target); + return true; + } + } +} diff --git a/ZSharp.Compiler.IR/ir/services/IR.Reference.cs b/ZSharp.Compiler.IR/ir/services/IR.Reference.cs new file mode 100644 index 00000000..1e5a97b1 --- /dev/null +++ b/ZSharp.Compiler.IR/ir/services/IR.Reference.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Compiler +{ + partial class IR + { + public Result CompileReference(CompilerObject @object) + where T : class + { + if (@object.Is>(out var compile)) + return compile.CompileIRReference(this); + + return Result.Error( + $"Cannot compile reference for object of type {@object}" + ); + } + } +} diff --git a/ZSharp.Compiler.IR/ir/services/IR.Type.cs b/ZSharp.Compiler.IR/ir/services/IR.Type.cs new file mode 100644 index 00000000..1f6c3ea9 --- /dev/null +++ b/ZSharp.Compiler.IR/ir/services/IR.Type.cs @@ -0,0 +1,21 @@ +namespace ZSharp.Compiler +{ + partial class IR + { + public Result CompileType(CompilerObject @object) + { + if (@object.Is(out var compile)) + return compile.CompileIRType(this); + + return Result.Error( + $"Cannot compile type for object of type {@object}" + ); + } + + public Result CompileType(CompilerObject @object) + where T : class, IType + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.IR/objects/RawIRCode.cs b/ZSharp.Compiler.IR/objects/RawIRCode.cs new file mode 100644 index 00000000..5d3a8f2a --- /dev/null +++ b/ZSharp.Compiler.IR/objects/RawIRCode.cs @@ -0,0 +1,14 @@ +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + public sealed class RawIRCode(IRCode code) + : CompilerObject + , ICompileIRCode + { + private readonly IRCode code = code; + + Result ICompileIRCode.CompileIRCode(Compiler.IR ir, object? target) + => Result.Ok(code); + } +} diff --git a/ZSharp.Compiler.IR/protocols/ICompileIRCode.cs b/ZSharp.Compiler.IR/protocols/ICompileIRCode.cs new file mode 100644 index 00000000..599d6960 --- /dev/null +++ b/ZSharp.Compiler.IR/protocols/ICompileIRCode.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICompileIRCode + { + public Result CompileIRCode(IR ir, TargetPlatform? target); + } +} diff --git a/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionAs.cs b/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionAs.cs new file mode 100644 index 00000000..4c198787 --- /dev/null +++ b/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionAs.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICompileIRDefinitionAs + where T : IRDefinition + { + public Result CompileIRDefinition(IR ir, TargetPlatform? target); + } +} diff --git a/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionIn.cs b/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionIn.cs new file mode 100644 index 00000000..70c7ecb1 --- /dev/null +++ b/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionIn.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICompileIRDefinitionIn + where Owner : IRDefinition + { + public void CompileIRDefinition(IR ir, Owner owner, TargetPlatform? target); + } +} diff --git a/ZSharp.Compiler.IR/protocols/ICompileIRReference.cs b/ZSharp.Compiler.IR/protocols/ICompileIRReference.cs new file mode 100644 index 00000000..54501f27 --- /dev/null +++ b/ZSharp.Compiler.IR/protocols/ICompileIRReference.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICompileIRReference + where T : class + { + public Result CompileIRReference(IR ir); + } +} diff --git a/ZSharp.Compiler.IR/protocols/ICompileIRType.cs b/ZSharp.Compiler.IR/protocols/ICompileIRType.cs new file mode 100644 index 00000000..e3e0eb29 --- /dev/null +++ b/ZSharp.Compiler.IR/protocols/ICompileIRType.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Compiler +{ + public interface ICompileIRType + { + public Result CompileIRType(IR ir); + } + + public interface ICompileIRType + : ICompileIRType + where T : class, IType + { + Result ICompileIRType.CompileIRType(IR ir) + => CompileIRType(ir).When(type => type as IType); + + public new Result CompileIRType(IR ir); + } +} \ No newline at end of file diff --git a/ZSharp.Compiler.IRLoader/Context.cs b/ZSharp.Compiler.IRLoader/Context.cs index 262c89fd..5ff8cc33 100644 --- a/ZSharp.Compiler.IRLoader/Context.cs +++ b/ZSharp.Compiler.IRLoader/Context.cs @@ -6,6 +6,6 @@ public sealed class Context { public Cache Objects { get; } = []; - public Cache Types { get; } = []; + public Cache Types { get; } = []; } } diff --git a/ZSharp.Compiler.Objects/GlobalUsings.cs b/ZSharp.Compiler.Objects/GlobalUsings.cs index 0fdd80b4..cccc780d 100644 --- a/ZSharp.Compiler.Objects/GlobalUsings.cs +++ b/ZSharp.Compiler.Objects/GlobalUsings.cs @@ -1,5 +1,5 @@ global using MemberName = string; global using MemberIndex = int; -global using Error = string; -global using CompilerObjectResult = ZSharp.Compiler.Result; +global using Error = ZSharp.Compiler.Error; +global using CompilerObjectResult = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs index dd667907..86e5b218 100644 --- a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs +++ b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs @@ -5,10 +5,10 @@ namespace ZSharp.Objects { public partial class GenericFunction { - public Result CreateGenericInstance(Compiler.Compiler compiler, IType[] arguments) + public Result CreateGenericInstance(Compiler.Compiler compiler, IType[] arguments) { if (arguments.Length != GenericParameters.Count) - return Result.Error( + return Result.Error( $"Invalid generic argument count: Expected {GenericParameters.Count}, got {arguments.Length}" ); @@ -16,7 +16,7 @@ public Result CreateGenericInstance(Compiler.Com foreach (var (parameter, argument) in GenericParameters.Zip(arguments)) { if (!parameter.Match(argument)) - return Result.Error( + return Result.Error( $"Type {argument} cannot be assigned to generic parameter {parameter.Name}" ); @@ -27,7 +27,7 @@ public Result CreateGenericInstance(Compiler.Com foreach (var (p, a) in genericArguments) context.CompileTimeValues.Cache(p, a); - return Result.Ok( + return Result.Ok( new() { GenericArguments = genericArguments, diff --git a/ZSharp.Compiler.Objects/nullable/Nullable.cs b/ZSharp.Compiler.Objects/nullable/Nullable.cs index 2aeb9aac..6ff4a6ac 100644 --- a/ZSharp.Compiler.Objects/nullable/Nullable.cs +++ b/ZSharp.Compiler.Objects/nullable/Nullable.cs @@ -16,14 +16,14 @@ bool IType.IsEqualTo(Compiler.Compiler compiler, IType other) return compiler.TypeSystem.AreEqual(UnderlyingType, nullable.UnderlyingType); } - Result IRTCastFrom.Cast(Compiler.Compiler compiler, CompilerObject value) + Result IRTCastFrom.Cast(Compiler.Compiler compiler, CompilerObject value) { var innerCastResult = compiler.CG.Cast(value, UnderlyingType); TypeCast innerCast; if (innerCastResult.Error(out var error)) - return Result.Error(error); + return Result.Error(error); else innerCast = innerCastResult.Unwrap(); var innerCastCodeResult = compiler.IR.CompileCode(innerCast.Cast); @@ -31,12 +31,12 @@ Result IRTCastFrom.Cast(Compiler.Compiler compiler, CompilerObj IRCode innerCastCode; if (innerCastCodeResult.Error(out error)) - return Result.Error(error); + return Result.Error(error); else innerCastCode = innerCastCodeResult.Unwrap(); IR.VM.Nop onCast = new(); - return Result.Ok( + return Result.Ok( new() { Cast = new RawCode(new([ @@ -56,10 +56,10 @@ Result IRTCastFrom.Cast(Compiler.Compiler compiler, CompilerObj ); } - Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObject value, IType targetType) + Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObject value, IType targetType) { if (targetType is not Nullable nullable) - return Result.Error( + return Result.Error( "Nullable types can only be cast to other nullable types" ); @@ -68,7 +68,7 @@ Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObjec TypeCast innerCast; if (innerCastResult.Error(out var error)) - return Result.Error(error); + return Result.Error(error); else innerCast = innerCastResult.Unwrap(); var innerCastCodeResult = compiler.IR.CompileCode(innerCast.Cast); @@ -76,12 +76,12 @@ Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObjec IRCode innerCastCode; if (innerCastCodeResult.Error(out error)) - return Result.Error(error); + return Result.Error(error); else innerCastCode = innerCastCodeResult.Unwrap(); IR.VM.Nop onCast = new(); - return Result.Ok( + return Result.Ok( new() { Cast = new RawCode(new([ diff --git a/ZSharp.Compiler.Objects/oop/class/Class.cs b/ZSharp.Compiler.Objects/oop/class/Class.cs index cc838b03..1f60c306 100644 --- a/ZSharp.Compiler.Objects/oop/class/Class.cs +++ b/ZSharp.Compiler.Objects/oop/class/Class.cs @@ -1,4 +1,5 @@ -using CommonZ.Utils; +using CommonZ; +using CommonZ.Utils; using ZSharp.Compiler; namespace ZSharp.Objects @@ -152,7 +153,7 @@ CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] argum return null; } - Result IRTTypeMatch.Match(Compiler.Compiler compiler, CompilerObject value, IType type) + Result IRTTypeMatch.Match(Compiler.Compiler compiler, CompilerObject value, IType type) { var nullableType = new Nullable(type); var castToTypeResult = compiler.CG.Cast(value, nullableType); @@ -160,7 +161,7 @@ Result IRTTypeMatch.Match(Compiler.Compiler compiler, Compile TypeCast castToType; if (castToTypeResult.Error(out var error)) - return Result.Error(error); + return Result.Error(error); else castToType = castToTypeResult.Unwrap(); var castToTypeCodeResult = compiler.IR.CompileCode(castToType.Cast); @@ -168,12 +169,12 @@ Result IRTTypeMatch.Match(Compiler.Compiler compiler, Compile IRCode castToTypeCode; if (castToTypeCodeResult.Error(out error)) - return Result.Error(error); + return Result.Error(error); else castToTypeCode = castToTypeCodeResult.Unwrap(); IR.VM.Nop onMatch = new(); - return Result.Ok(new() + return Result.Ok(new() { Match = new RawCode(new([ .. castToTypeCode.Instructions, @@ -188,15 +189,15 @@ Result IRTTypeMatch.Match(Compiler.Compiler compiler, Compile }); } - Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObject value, IType targetType) + Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObject value, IType targetType) { if (targetType is not Class targetClass) - return Result.Error( + return Result.Error( "Casting class to non-class object is not supported yet" ); if (IsSubclassOf(targetClass)) - return Result.Ok( + return Result.Ok( new() { Cast = value, @@ -208,7 +209,7 @@ Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObje IRCode valueCode; if (valueCodeResult.Error(out var error)) - return Result.Error(error); + return Result.Error(error); else valueCode = valueCodeResult.Unwrap(); if (targetClass.IsSubclassOf(this)) @@ -219,13 +220,13 @@ Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObje IR.OOPTypeReference targetClassIR; if (targetClassIRResult.Error(out error)) - return Result.Error(error); + return Result.Error(error); else targetClassIR = targetClassIRResult.Unwrap(); IR.VM.Nop onCast = new(); IR.VM.Nop onFail = new(); - return Result.Ok( + return Result.Ok( new() { Cast = new RawCode(new([ @@ -246,7 +247,7 @@ Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObje ); } - return Result.Error( + return Result.Error( "Object does not support type cast to the specified type" ); } diff --git a/ZSharp.Compiler.TS.Static/GlobalUsings.cs b/ZSharp.Compiler.TS.Static/GlobalUsings.cs new file mode 100644 index 00000000..05db7df2 --- /dev/null +++ b/ZSharp.Compiler.TS.Static/GlobalUsings.cs @@ -0,0 +1 @@ +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.TS.Static/ZSharp.Compiler.TS.Static.csproj b/ZSharp.Compiler.TS.Static/ZSharp.Compiler.TS.Static.csproj new file mode 100644 index 00000000..7e575a54 --- /dev/null +++ b/ZSharp.Compiler.TS.Static/ZSharp.Compiler.TS.Static.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs new file mode 100644 index 00000000..711e5457 --- /dev/null +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.Dispatchers.CT +{ + partial class Dispatcher + { + + } +} diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs new file mode 100644 index 00000000..ff61bb32 --- /dev/null +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.Dispatchers.CT +{ + partial class Dispatcher + { + public Result TypeOf(CompilerObject @object) + { + var result = @base.TypeOf(@object); + + if (result.IsError && @object.Is(out var typed)) + result = Result.Ok(typed.Type); + + return result; + } + } +} diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..939f0264 --- /dev/null +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Compiler.Dispatchers.CT +{ + internal partial class Dispatcher(Compiler compiler) + { + private readonly Compiler compiler = compiler; + private TS @base; + + public void Apply() + { + @base = compiler.TS; + + ref var ts = ref compiler.TS; + + ts.TypeOf = TypeOf; + } + } +} diff --git a/ZSharp.Compiler.TS.Static/protocols/ITyped.cs b/ZSharp.Compiler.TS.Static/protocols/ITyped.cs new file mode 100644 index 00000000..24c95fcf --- /dev/null +++ b/ZSharp.Compiler.TS.Static/protocols/ITyped.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ITyped + { + public CompilerObject Type { get; } + } +} diff --git a/ZSharp.Compiler.TS/GlobalUsings.cs b/ZSharp.Compiler.TS/GlobalUsings.cs new file mode 100644 index 00000000..05db7df2 --- /dev/null +++ b/ZSharp.Compiler.TS/GlobalUsings.cs @@ -0,0 +1 @@ +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.TS/ZSharp.Compiler.TS.csproj b/ZSharp.Compiler.TS/ZSharp.Compiler.TS.csproj new file mode 100644 index 00000000..c88af84b --- /dev/null +++ b/ZSharp.Compiler.TS/ZSharp.Compiler.TS.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/ZSharp.Compiler.TS/dispatcher/Dispatcher.T.cs b/ZSharp.Compiler.TS/dispatcher/Dispatcher.T.cs new file mode 100644 index 00000000..8cb7b400 --- /dev/null +++ b/ZSharp.Compiler.TS/dispatcher/Dispatcher.T.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result Do(CompilerObject @object) + => Result.Error( + "Object does not support do" + ); + } +} diff --git a/ZSharp.Compiler.TS/dispatcher/Dispatcher.cs b/ZSharp.Compiler.TS/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..cd652665 --- /dev/null +++ b/ZSharp.Compiler.TS/dispatcher/Dispatcher.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler +{ + internal static partial class Dispatcher + { + } +} diff --git a/ZSharp.Compiler.TS/dispatcher/services/Dispatcher.IsAssignable.cs b/ZSharp.Compiler.TS/dispatcher/services/Dispatcher.IsAssignable.cs new file mode 100644 index 00000000..c97c4c9a --- /dev/null +++ b/ZSharp.Compiler.TS/dispatcher/services/Dispatcher.IsAssignable.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static bool IsAssignableTo(CompilerObject target, CompilerObject source) + => false; + } +} diff --git a/ZSharp.Compiler.TS/dispatcher/services/Dispatcher.TypeOf.cs b/ZSharp.Compiler.TS/dispatcher/services/Dispatcher.TypeOf.cs new file mode 100644 index 00000000..fed890db --- /dev/null +++ b/ZSharp.Compiler.TS/dispatcher/services/Dispatcher.TypeOf.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result TypeOf(CompilerObject @object) + => Result.Error( + "Object does not support typeof" + ); + } +} diff --git a/ZSharp.Compiler.TS/ts/TS.T.cs b/ZSharp.Compiler.TS/ts/TS.T.cs new file mode 100644 index 00000000..e71e3dd8 --- /dev/null +++ b/ZSharp.Compiler.TS/ts/TS.T.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler +{ + partial struct TS + { + } +} diff --git a/ZSharp.Compiler.TS/ts/TS.cs b/ZSharp.Compiler.TS/ts/TS.cs new file mode 100644 index 00000000..e4a68279 --- /dev/null +++ b/ZSharp.Compiler.TS/ts/TS.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler +{ + public partial struct TS() + { + } +} diff --git a/ZSharp.Compiler.TS/ts/services/TS.IsAssignable.cs b/ZSharp.Compiler.TS/ts/services/TS.IsAssignable.cs new file mode 100644 index 00000000..1002e5f9 --- /dev/null +++ b/ZSharp.Compiler.TS/ts/services/TS.IsAssignable.cs @@ -0,0 +1,12 @@ +namespace ZSharp.Compiler +{ + public delegate bool IsAssignableTo(CompilerObject target, CompilerObject source); + + partial struct TS + { + public IsAssignableTo IsAssignableTo { get; set; } = Dispatcher.IsAssignableTo; + + public bool IsAssignableFrom(CompilerObject source, CompilerObject target) + => IsAssignableTo(target, source); + } +} diff --git a/ZSharp.Compiler.TS/ts/services/TS.Make.cs b/ZSharp.Compiler.TS/ts/services/TS.Make.cs new file mode 100644 index 00000000..125bf29b --- /dev/null +++ b/ZSharp.Compiler.TS/ts/services/TS.Make.cs @@ -0,0 +1,20 @@ +namespace ZSharp.Compiler +{ + partial struct TS + { + public CompilerObject Array(CompilerObject type) + { + throw new NotImplementedException(); + } + + public CompilerObject Pointer(CompilerObject type) + { + throw new NotImplementedException(); + } + + public CompilerObject Reference(CompilerObject type) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.Compiler.TS/ts/services/TS.TypeOf.cs b/ZSharp.Compiler.TS/ts/services/TS.TypeOf.cs new file mode 100644 index 00000000..3073b854 --- /dev/null +++ b/ZSharp.Compiler.TS/ts/services/TS.TypeOf.cs @@ -0,0 +1,14 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler +{ + public delegate Result TypeOf(CompilerObject @object); + + partial struct TS + { + public TypeOf TypeOf { get; set; } = Dispatcher.TypeOf; + + public bool IsTyped(CompilerObject @object, [NotNullWhen(true)] out CompilerObject? result) + => TypeOf(@object).Ok(out result); + } +} diff --git a/ZSharp.Compiler.TS/ts/types/TS.Types.Float.cs b/ZSharp.Compiler.TS/ts/types/TS.Types.Float.cs new file mode 100644 index 00000000..44b129e1 --- /dev/null +++ b/ZSharp.Compiler.TS/ts/types/TS.Types.Float.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + partial struct TS + { + public CompilerObject Float32 { get; set; } + + public CompilerObject Float64 { get; set; } + } +} diff --git a/ZSharp.Compiler.TS/ts/types/TS.Types.Indirect.cs b/ZSharp.Compiler.TS/ts/types/TS.Types.Indirect.cs new file mode 100644 index 00000000..c838f97d --- /dev/null +++ b/ZSharp.Compiler.TS/ts/types/TS.Types.Indirect.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Compiler +{ + partial struct TS + { + public CompilerObject ArrayType { get; set; } + + public CompilerObject PointerType { get; set; } + + public CompilerObject ReferenceType { get; set; } + } +} diff --git a/ZSharp.Compiler.TS/ts/types/TS.Types.Others.cs b/ZSharp.Compiler.TS/ts/types/TS.Types.Others.cs new file mode 100644 index 00000000..3df80918 --- /dev/null +++ b/ZSharp.Compiler.TS/ts/types/TS.Types.Others.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler +{ + partial struct TS + { + public CompilerObject Boolean { get; set; } + + public CompilerObject Null { get; set; } + + public CompilerObject String { get; set; } + + public CompilerObject Type { get; set; } + + public CompilerObject Void { get; set; } + } +} diff --git a/ZSharp.Compiler.TS/ts/types/TS.Types.SInt.cs b/ZSharp.Compiler.TS/ts/types/TS.Types.SInt.cs new file mode 100644 index 00000000..b1641480 --- /dev/null +++ b/ZSharp.Compiler.TS/ts/types/TS.Types.SInt.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler +{ + partial struct TS + { + public CompilerObject SInt8 { get; set; } + + public CompilerObject SInt16 { get; set; } + + public CompilerObject SInt32 { get; set; } + + public CompilerObject SInt64 { get; set; } + } +} diff --git a/ZSharp.Compiler.TS/ts/types/TS.Types.UInt.cs b/ZSharp.Compiler.TS/ts/types/TS.Types.UInt.cs new file mode 100644 index 00000000..c3e2b260 --- /dev/null +++ b/ZSharp.Compiler.TS/ts/types/TS.Types.UInt.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Compiler +{ + partial struct TS + { + public CompilerObject UInt8 { get; set; } + + public CompilerObject UInt16 { get; set; } + + public CompilerObject UInt32 { get; set; } + + public CompilerObject UInt64 { get; set; } + } +} diff --git a/ZSharp.Compiler/GlobalUsings.cs b/ZSharp.Compiler/GlobalUsings.cs index 289e3e8b..c1bcb323 100644 --- a/ZSharp.Compiler/GlobalUsings.cs +++ b/ZSharp.Compiler/GlobalUsings.cs @@ -1,13 +1,4 @@ global using MemberName = string; global using MemberIndex = int; -global using IRType = ZSharp.IR.IType; - -global using DefaultIntegerType = int; - -global using IRInstructions = CommonZ.Utils.Collection; - -global using CompilerObject = ZSharp.Objects.CompilerObject; - -global using Error = string; -global using CompilerObjectResult = ZSharp.Compiler.Result; +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler/ZSharp.Compiler.csproj b/ZSharp.Compiler/ZSharp.Compiler.csproj index 5bfa5393..a81dc6fe 100644 --- a/ZSharp.Compiler/ZSharp.Compiler.csproj +++ b/ZSharp.Compiler/ZSharp.Compiler.csproj @@ -7,11 +7,23 @@ + + + + + + + + + + + + diff --git a/ZSharp.Compiler/cg objects/Utils.cs b/ZSharp.Compiler/cg objects/Utils.cs deleted file mode 100644 index ef54a10f..00000000 --- a/ZSharp.Compiler/cg objects/Utils.cs +++ /dev/null @@ -1,27 +0,0 @@ -using ZSharp.Compiler; - -using Args = CommonZ.Utils.Collection; -using KwArgs = CommonZ.Utils.Mapping; - - -namespace ZSharp.Objects -{ - public static class Utils - { - public static (Args, KwArgs) SplitArguments(Argument[] arguments) - { - Args positional = []; - KwArgs named = []; - - foreach (var argument in arguments) - { - if (argument.Name is null) - positional.Add(argument.Object); - else - named[argument.Name] = argument.Object; - } - - return (positional, named); - } - } -} diff --git a/ZSharp.Compiler/cg objects/imports/Import.cs b/ZSharp.Compiler/cg objects/imports/Import.cs deleted file mode 100644 index 4b922d13..00000000 --- a/ZSharp.Compiler/cg objects/imports/Import.cs +++ /dev/null @@ -1,13 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Import : CompilerObject - { - public required List Arguments { get; set; } - - public required List ImportedNames { get; set; } - - public string? Alias { get; set; } - } -} diff --git a/ZSharp.Compiler/cg objects/imports/ImportedName.cs b/ZSharp.Compiler/cg objects/imports/ImportedName.cs deleted file mode 100644 index f092aeb3..00000000 --- a/ZSharp.Compiler/cg objects/imports/ImportedName.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class ImportedName : CompilerObject - { - public required string Name { get; set; } - - public string? Alias { get; set; } - } -} diff --git a/ZSharp.Compiler/cg objects/literals/FalseLiteral.cs b/ZSharp.Compiler/cg objects/literals/FalseLiteral.cs deleted file mode 100644 index 9be280f9..00000000 --- a/ZSharp.Compiler/cg objects/literals/FalseLiteral.cs +++ /dev/null @@ -1,20 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class FalseLiteral(IType type) - : CompilerObject - , ICTReadable - { - public IType Type { get; } = type; - - public IRCode Read(Compiler.Compiler compiler) - => new([ - new IR.VM.PutFalse() - ]) - { - MaxStackSize = 1, - Types = [Type] - }; - } -} diff --git a/ZSharp.Compiler/cg objects/literals/Float32Literal.cs b/ZSharp.Compiler/cg objects/literals/Float32Literal.cs deleted file mode 100644 index 0654ff58..00000000 --- a/ZSharp.Compiler/cg objects/literals/Float32Literal.cs +++ /dev/null @@ -1,22 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Float32Literal(float value, IType type) - : Literal(value) - , ICTReadable - { - public override IType Type { get; } = type; - - public override IRCode Read(Compiler.Compiler compiler) - => new( - [ - new IR.VM.PutFloat32(Value) - ] - ) - { - MaxStackSize = 1, - Types = [Type] - }; - } -} diff --git a/ZSharp.Compiler/cg objects/literals/IntegerLiteral.cs b/ZSharp.Compiler/cg objects/literals/IntegerLiteral.cs deleted file mode 100644 index a4daadef..00000000 --- a/ZSharp.Compiler/cg objects/literals/IntegerLiteral.cs +++ /dev/null @@ -1,22 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class IntegerLiteral(DefaultIntegerType value, IType type) - : Literal(value) - , ICTReadable - { - public override IType Type { get; } = type; - - public override IRCode Read(Compiler.Compiler compiler) - => new( - [ - new IR.VM.PutInt32(Value) - ] - ) - { - MaxStackSize = 1, - Types = [Type] - }; - } -} diff --git a/ZSharp.Compiler/cg objects/literals/Literal.cs b/ZSharp.Compiler/cg objects/literals/Literal.cs deleted file mode 100644 index 111d28df..00000000 --- a/ZSharp.Compiler/cg objects/literals/Literal.cs +++ /dev/null @@ -1,21 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public abstract class Literal(object? value) - : CompilerObject - , ICTReadable - { - public abstract IType Type { get; } - - public object? Value { get; } = value; - - public abstract IRCode Read(Compiler.Compiler compiler); - } - - public abstract class Literal(T value) - : Literal(value) - { - public new T Value => (T)base.Value!; - } -} diff --git a/ZSharp.Compiler/cg objects/literals/NullLiteral.cs b/ZSharp.Compiler/cg objects/literals/NullLiteral.cs deleted file mode 100644 index be238d6e..00000000 --- a/ZSharp.Compiler/cg objects/literals/NullLiteral.cs +++ /dev/null @@ -1,18 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class NullLiteral(IType type) : Literal(null) - { - public override IType Type { get; } = type; - - public override IRCode Read(Compiler.Compiler compiler) - => new([ - new IR.VM.PutNull() - ]) - { - MaxStackSize = 1, - Types = [Type] - }; - } -} diff --git a/ZSharp.Compiler/cg objects/literals/StringLiteral.cs b/ZSharp.Compiler/cg objects/literals/StringLiteral.cs deleted file mode 100644 index 76d22e5f..00000000 --- a/ZSharp.Compiler/cg objects/literals/StringLiteral.cs +++ /dev/null @@ -1,19 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class StringLiteral(string value, IType type) - : Literal(value) - { - public override IType Type { get; } = type; - - public override IRCode Read(Compiler.Compiler compiler) - => new([ - new IR.VM.PutString(Value) - ]) - { - MaxStackSize = 1, - Types = [Type] - }; - } -} diff --git a/ZSharp.Compiler/cg objects/literals/TrueLiteral.cs b/ZSharp.Compiler/cg objects/literals/TrueLiteral.cs deleted file mode 100644 index 178a1a3f..00000000 --- a/ZSharp.Compiler/cg objects/literals/TrueLiteral.cs +++ /dev/null @@ -1,20 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class TrueLiteral(IType type) - : CompilerObject - , ICTReadable - { - public IType Type { get; } = type; - - public IRCode Read(Compiler.Compiler compiler) - => new([ - new IR.VM.PutTrue() - ]) - { - MaxStackSize = 1, - Types = [Type] - }; - } -} diff --git a/ZSharp.Compiler/cg objects/raw/RawCode.cs b/ZSharp.Compiler/cg objects/raw/RawCode.cs deleted file mode 100644 index 434facf0..00000000 --- a/ZSharp.Compiler/cg objects/raw/RawCode.cs +++ /dev/null @@ -1,45 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class RawCode(IRCode code) - : CompilerObject - , ICTReadable - ,ICTTypeCast - , ICTCompileIRCode - { - private readonly IRCode code = code; - - public IRCode Code => code; - - public IType Type => code.RequireValueType(); - - public IRCode Read(Compiler.Compiler _) - => code; - - CompilerObject ICTTypeCast.Cast(Compiler.Compiler compiler, IType targetType) - { - if (targetType == compiler.TypeSystem.Void) - { - if (code.IsVoid) return this; - - return new RawCode(new([ - ..code.Instructions, - .. code.Types.Select(_ => new IR.VM.Pop()) - ]) - { - MaxStackSize = code.MaxStackSize, - Types = [] - }); - } - - throw new NotImplementedException(); - } - - Result ICTCompileIRCode.CompileIRCode(Compiler.Compiler compiler) - => Result.Ok(code); - - IType IDynamicallyTyped.GetType(Compiler.Compiler compiler) - => code.IsVoid ? compiler.TypeSystem.Void : code.RequireValueType(); - } -} diff --git a/ZSharp.Compiler/cg objects/raw/RawType.cs b/ZSharp.Compiler/cg objects/raw/RawType.cs deleted file mode 100644 index 5de064a8..00000000 --- a/ZSharp.Compiler/cg objects/raw/RawType.cs +++ /dev/null @@ -1,27 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class RawType(IRType type, IType metaType) - : CompilerObject - , ICTReadable - , ICompileIRType - , IType - { - private IRType type = type; - - public IType Type { get; internal set; } = metaType; - - public IRType CompileIRType(Compiler.Compiler compiler) - => type; - - public IRCode Read(Compiler.Compiler compiler) - => type is IR.IRDefinition ir ? new([ - new IR.VM.GetObject(ir) - ]) - { - MaxStackSize = 1, - Types = [Type] - } : throw new(); - } -} diff --git a/ZSharp.Compiler/cg objects/types/Int32Type.cs b/ZSharp.Compiler/cg objects/types/Int32Type.cs deleted file mode 100644 index 200995bf..00000000 --- a/ZSharp.Compiler/cg objects/types/Int32Type.cs +++ /dev/null @@ -1,24 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Int32Type(IR.OOPTypeReference ir, IType type) - : CompilerObject - , ICompileIRType - , ICTGetMember_Old - , IType - { - public IR.OOPTypeReference IR { get; } = ir; - - public IType Type { get; } = type; - - public Mapping Members { get; } = []; - - public IRType CompileIRType(Compiler.Compiler compiler) - => IR; - - public CompilerObject Member(Compiler.Compiler compiler, string member) - => Members[member]; - } -} diff --git a/ZSharp.Compiler/cg objects/types/ObjectType.cs b/ZSharp.Compiler/cg objects/types/ObjectType.cs deleted file mode 100644 index b1bf6547..00000000 --- a/ZSharp.Compiler/cg objects/types/ObjectType.cs +++ /dev/null @@ -1,28 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class ObjectType(IR.OOPTypeReference stringType, IType type) - : CompilerObject - , IClass - , ICompileIRType - { - public IR.OOPTypeReference IR { get; } = stringType; - - public IType Type { get; } = type; - - public string Name - { - get => IR.Definition.Name!; - set => throw new InvalidOperationException(); - } - public IClass? Base - { - get => null; - set => throw new InvalidOperationException(); - } - - public IRType CompileIRType(Compiler.Compiler compiler) - => IR; - } -} diff --git a/ZSharp.Compiler/cg objects/types/StringType.cs b/ZSharp.Compiler/cg objects/types/StringType.cs deleted file mode 100644 index da82a8e4..00000000 --- a/ZSharp.Compiler/cg objects/types/StringType.cs +++ /dev/null @@ -1,28 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class StringType(IR.OOPTypeReference stringType, IType type) - : CompilerObject - , ICompileIRType - , ICTCallable_Old - , IType - { - public IR.OOPTypeReference IR { get; } = stringType; - - public IType Type { get; } = type; - - public new CompilerObject ToString { get; set; } = null!; - - public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (arguments.Length != 1) - throw new(); - - return compiler.Call(ToString, arguments); - } - - public IRType CompileIRType(Compiler.Compiler compiler) - => IR; - } -} diff --git a/ZSharp.Compiler/cg objects/types/Type.cs b/ZSharp.Compiler/cg objects/types/Type.cs deleted file mode 100644 index cde6eb9e..00000000 --- a/ZSharp.Compiler/cg objects/types/Type.cs +++ /dev/null @@ -1,28 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - internal sealed class Type(IRType type) - : CompilerObject - //, ICTReadable - , ICompileIRType - , IType - { - private readonly IRType type = type; - //private readonly IRObject ir = type as IRObject ?? throw new(); - - //CompilerObject ITyped.Type => this; - - IRType ICompileIRType.CompileIRType(Compiler.Compiler compiler) - => type; - - //public IRCode Read(Compiler.Compiler compiler) - //=> new([ - // new IR.VM.GetObject(ir) - // ]) - // { - // MaxStackSize = 1, - // Types = [this] - // }; - } -} diff --git a/ZSharp.Compiler/cg objects/types/array/ArrayType.cs b/ZSharp.Compiler/cg objects/types/array/ArrayType.cs deleted file mode 100644 index d5dc87a3..00000000 --- a/ZSharp.Compiler/cg objects/types/array/ArrayType.cs +++ /dev/null @@ -1,22 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class ArrayType(IType elementType) - : CompilerObject - , IType - , ICompileIRType - { - public IType ElementType { get; set; } = elementType; - - IR.ConstructedClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) - { - var elementType = compiler.IR.CompileType(ElementType).Unwrap(); - - return new(compiler.TypeSystem.ArrayType.IR) - { - Arguments = [elementType] - }; - } - } -} diff --git a/ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs b/ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs deleted file mode 100644 index a756d12b..00000000 --- a/ZSharp.Compiler/cg objects/types/array/ArrayTypeObject.cs +++ /dev/null @@ -1,41 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class ArrayTypeObject(IR.Class ir) - : CompilerObject - , IType - , ICompileIRObject - , IGenericInstantiable - { - public IR.Class IR { get; } = ir; - - CompilerObjectResult IGenericInstantiable.Instantiate(Compiler.Compiler compiler, Argument[] arguments) - { - if (arguments.Length != 1) - return CompilerObjectResult.Error( - $"Expected exactly 1 generic argument, but got {arguments.Length}" - ); - - var elementTypeArgument = arguments[0]; - if (elementTypeArgument.Name is not null) - return CompilerObjectResult.Error( - "Array[] type argument must be positional" - ); - if (elementTypeArgument.Object is not IType elementType) - return CompilerObjectResult.Error( - "Array[] type argument must be a type" - ); - - return CompilerObjectResult.Ok( - Instantiate(elementType) - ); - } - - public ArrayType Instantiate(IType elementType) - => new(elementType); - - IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) - => IR; - } -} diff --git a/ZSharp.Compiler/cg objects/types/pointer/PointerType.cs b/ZSharp.Compiler/cg objects/types/pointer/PointerType.cs deleted file mode 100644 index 840cb169..00000000 --- a/ZSharp.Compiler/cg objects/types/pointer/PointerType.cs +++ /dev/null @@ -1,22 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class PointerType(IType elementType) - : CompilerObject - , IType - , ICompileIRType - { - public IType ElementType { get; set; } = elementType; - - IR.ConstructedClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) - { - var elementType = compiler.IR.CompileType(ElementType).Unwrap(); - - return new(compiler.TypeSystem.PointerType.IR) - { - Arguments = [elementType] - }; - } - } -} diff --git a/ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs b/ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs deleted file mode 100644 index 2b18c960..00000000 --- a/ZSharp.Compiler/cg objects/types/pointer/PointerTypeObject.cs +++ /dev/null @@ -1,41 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class PointerTypeObject(IR.Class ir) - : CompilerObject - , IType - , ICompileIRObject - , IGenericInstantiable - { - public IR.Class IR { get; } = ir; - - CompilerObjectResult IGenericInstantiable.Instantiate(Compiler.Compiler compiler, Argument[] arguments) - { - if (arguments.Length != 1) - return CompilerObjectResult.Error( - $"Expected exactly 1 generic argument, but got {arguments.Length}" - ); - - var elementTypeArgument = arguments[0]; - if (elementTypeArgument.Name is not null) - return CompilerObjectResult.Error( - "Pointer[] type argument must be positional" - ); - if (elementTypeArgument.Object is not IType elementType) - return CompilerObjectResult.Error( - "Pointer[] type argument must be a type" - ); - - return CompilerObjectResult.Ok( - Instantiate(elementType) - ); - } - - public PointerType Instantiate(IType elementType) - => new(elementType); - - IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) - => IR; - } -} diff --git a/ZSharp.Compiler/cg objects/types/reference/ReferenceType.cs b/ZSharp.Compiler/cg objects/types/reference/ReferenceType.cs deleted file mode 100644 index 7cac23ef..00000000 --- a/ZSharp.Compiler/cg objects/types/reference/ReferenceType.cs +++ /dev/null @@ -1,22 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class ReferenceType(IType elementType) - : CompilerObject - , IType - , ICompileIRType - { - public IType ElementType { get; set; } = elementType; - - IR.ConstructedClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) - { - var elementType = compiler.IR.CompileType(ElementType).Unwrap(); - - return new(compiler.TypeSystem.ReferenceType.IR) - { - Arguments = [elementType] - }; - } - } -} diff --git a/ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs b/ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs deleted file mode 100644 index f86629e7..00000000 --- a/ZSharp.Compiler/cg objects/types/reference/ReferenceTypeObject.cs +++ /dev/null @@ -1,41 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class ReferenceTypeObject(IR.Class ir) - : CompilerObject - , IType - , ICompileIRObject - , IGenericInstantiable - { - public IR.Class IR { get; } = ir; - - CompilerObjectResult IGenericInstantiable.Instantiate(Compiler.Compiler compiler, Argument[] arguments) - { - if (arguments.Length != 1) - return CompilerObjectResult.Error( - $"Expected exactly 1 generic argument, but got {arguments.Length}" - ); - - var elementTypeArgument = arguments[0]; - if (elementTypeArgument.Name is not null) - return CompilerObjectResult.Error( - "Reference[] type argument must be positional" - ); - if (elementTypeArgument.Object is not IType elementType) - return CompilerObjectResult.Error( - "Reference[] type argument must be a type" - ); - - return CompilerObjectResult.Ok( - Instantiate(elementType) - ); - } - - public ReferenceType Instantiate(IType elementType) - => new(elementType); - - IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) - => IR; - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.DRY.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.DRY.cs deleted file mode 100644 index 7c433dd2..00000000 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.DRY.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - public CompilerObjectResult Wrap(Func func) - { - try - { - return CompilerObjectResult.Ok(func(this)); - } catch (CompilerObjectException e) - { - return CompilerObjectResult.Error(e.Message); - } - } - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.Features.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.Features.cs deleted file mode 100644 index d5dc22b0..00000000 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.Features.cs +++ /dev/null @@ -1,25 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - private readonly Mapping features = []; - - private void InitializeFeatures() - { - - } - - public T Feature() - where T : class - => (T)features[typeof(T)]; - - public void Feature(T feature) - where T : Feature - => features[typeof(T)] = feature; - - public void Feature(Feature feature) - => features[feature.GetType()] = feature; - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs deleted file mode 100644 index 52f76f0d..00000000 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.IR.cs +++ /dev/null @@ -1,77 +0,0 @@ -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - public ZSharp.IR.RuntimeModule RuntimeModule { get; } - - public IRCode CompileIRCode(CompilerObject @object) - { - if (@object is ICompileIRCode irCode) - return irCode.CompileIRCode(this); - - if (@object is ICTReadable ctReadable) - return ctReadable.Read(this); - - throw new NotImplementedException(); // TODO: return null - } - - public ZSharp.IR.IRDefinition CompileIRObject(CompilerObject @object) - { - if (@object is ICompileIRObject irObject) - return irObject.CompileIRObject(this); - - return CompileIRObject(@object, null); - } - - public ZSharp.IR.IRDefinition CompileIRObject(CompilerObject @object, Owner? owner) - where Owner : ZSharp.IR.IRDefinition - { - if (@object is ICompileIRObject irObject) - return irObject.CompileIRObject(this, owner); - - throw new NotImplementedException(); // TODO: return null - } - - public T CompileIRObject(CompilerObject @object, Owner? owner) - where T : ZSharp.IR.IRDefinition - where Owner : class - { - if (@object is ICompileIRObject irObject) - return irObject.CompileIRObject(this, owner); - - throw new NotImplementedException(); // TODO: return null - } - - public IRType CompileIRType(CompilerObject @object) - { - ICompileIRType? irType; - - if ((irType = @object as ICompileIRType) is not null) - return irType.CompileIRType(this); - - throw new NotImplementedException(); // TODO: return null - } - - public T CompileIRType(CompilerObject @object) - where T : IRType - { - ICompileIRType? irType; - - if ((irType = @object as ICompileIRType) is not null) - return irType.CompileIRType(this); - - if (@object is ICompileIRType irUntypedType) - return (T)irUntypedType.CompileIRType(this); - - throw new NotImplementedException(); // TODO: return null - } - - public T CompileIRReference(CompilerObject @object) - { - if (@object is ICompileIRReference irReference) - return irReference.CompileIRReference(this); - - throw new NotImplementedException(); // TODO: return null - } - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.Services.cs b/ZSharp.Compiler/compiler core/compiler/Compiler.Services.cs deleted file mode 100644 index 0145879b..00000000 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.Services.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - public CG CG { get; } - - public IR IR { get; } - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs deleted file mode 100644 index 5e3de68b..00000000 --- a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Protocols.cs +++ /dev/null @@ -1,126 +0,0 @@ -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - public CompilerObject Assign(CompilerObject target, CompilerObject value) - { - if (target is ICTAssignable ctAssignable) - return ctAssignable.Assign(this, value); - - throw new NotImplementedException(); - } - - // TODO: WTH is this? - public IRCode Assign(IRCode irCode, Assignment assignment) - => throw new NotImplementedException(); - - public CompilerObject Call(CompilerObject target, Argument[] arguments) - { - if (target is ICTCallable_Old ctCallable) - return ctCallable.Call(this, arguments); - - // implements typeclass Callable? - - // overloads call operator? - - throw new("Object of this type is not callable."); - } - - public CompilerObject Cast(CompilerObject target, IType type) - { - if (TypeSystem.IsTyped(target, out var targetType) && TypeSystem.AreEqual(type, targetType)) - return target; - - if (target is ICTTypeCast typeCast) - return typeCast.Cast(this, type); - - throw new InvalidCastException(target, type); - } - - /// - /// The get index ([]) operator. - /// - /// - /// - /// - public CompilerObject? Index(CompilerObject instanceTarget, Argument[] index) - { - if (instanceTarget is ICTGetIndex ctGetIndex) - return ctGetIndex.Index(this, index); - - return null; - } - - /// - /// The set index ([]=) operator. - /// - /// - /// - /// - /// - public CompilerObject Index(CompilerObject instanceTarget, Argument[] index, CompilerObject value) - { - throw new NotImplementedException(); - } - - public CompilerObject Map(CompilerObject @object, Func func) - { - if (@object is IMappable mappable) - return mappable.Map(func); - - return func(@object); - } - - /// - /// The member (.) operator. - /// - /// - /// - /// - public CompilerObject Member(CompilerObject instance, MemberIndex index) - { - throw new NotImplementedException(); - } - - /// - /// The set member (.=) operator. - /// - /// - /// - /// - /// - public CompilerObject Member(CompilerObject instance, MemberIndex index, CompilerObject value) - { - throw new NotImplementedException(); - } - - /// - /// The member (.) operator. - /// - /// - /// - /// - public CompilerObject Member(CompilerObject instance, MemberName member) - { - if (instance is ICTGetMember_Old ctGetMember) - return ctGetMember.Member(this, member); - - if (instance is ICTReadable readable && readable.Type is IRTGetMember_Old rtGetMember) - return rtGetMember.Member(this, instance, member); - - throw new NotImplementedException(); - } - - /// - /// The set member (.=) operator. - /// - /// - /// - /// - /// - public CompilerObject Member(CompilerObject instance, MemberName member, CompilerObject value) - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Query.cs b/ZSharp.Compiler/compiler core/compiler/features/Compiler.Query.cs deleted file mode 100644 index cbfda958..00000000 --- a/ZSharp.Compiler/compiler core/compiler/features/Compiler.Query.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - public bool IsAnonymous(CompilerObject @object) - => (NameOf(@object) ?? string.Empty) == string.Empty; - - public string? NameOf(CompilerObject @object) - => @object is INamedObject named ? named.Name : null; - - public bool NameOf(CompilerObject @object, [NotNullWhen(true)] out string? name) - => (name = NameOf(@object)) is not null; - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/features/Compiler.TypeSystem.cs b/ZSharp.Compiler/compiler core/compiler/features/Compiler.TypeSystem.cs deleted file mode 100644 index 69250a98..00000000 --- a/ZSharp.Compiler/compiler core/compiler/features/Compiler.TypeSystem.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - public TypeSystem TypeSystem { get; } - - private void InitializeTypeSystem() - { - - } - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Create.cs b/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Create.cs deleted file mode 100644 index 51dca2a0..00000000 --- a/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Create.cs +++ /dev/null @@ -1,36 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Objects; - -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - private readonly Mapping nullLiterals = []; - - public CompilerObject CreateTrue() - => trueObject; - - public CompilerObject CreateFalse() - => falseObject; - - public CompilerObject CreateFloat32(float value) - => new Float32Literal(value, TypeSystem.Float32); - - public CompilerObject CreateInteger(DefaultIntegerType value) - => new IntegerLiteral(value, TypeSystem.Int32); // TODO: fix type here - - public CompilerObject CreateString(string value) - => new StringLiteral(value, TypeSystem.String); - - public CompilerObject CreateNull() - => CreateNull(TypeSystem.Null); - - public CompilerObject CreateNull(IType type) - { - if (!nullLiterals.TryGetValue(type, out var nullLiteral)) - nullLiterals[type] = nullLiteral = new(type); - - return nullLiteral; - } - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Is.cs b/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Is.cs deleted file mode 100644 index 34a875e3..00000000 --- a/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Is.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using ZSharp.Objects; - -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - public bool IsLiteral(CompilerObject @object) - => @object is Literal; - - public bool IsLiteral(CompilerObject @object, [NotNullWhen(true)] out Literal? result) - => (@object is Literal literal - ? (result = literal) - : (result = null) - ) is not null; - - public bool IsLiteral(CompilerObject @object, [NotNullWhen(true)] out T? value) - where T : struct - { - value = default; - - if (!IsLiteral(@object, out Literal? literal)) return false; - - if (literal.Value is not T literalValue) return false; - - value = literalValue; - - return true; - } - - public bool IsLiteral(CompilerObject @object, [NotNullWhen(true)] out T? value) - where T : class - { - if (!IsLiteral(@object, out Literal? literal)) return (value = null) is not null; - - if (literal.Value is not T literalValue) return (value = null) is not null; - - return (value = literalValue) is not null; - } - - /// - /// Checks if the given object is a literal string and unpacks it. - /// - /// - /// - /// - public bool IsString(CompilerObject @object, [NotNullWhen(true)] out string? value) - { - if (IsLiteral(@object, out value)) return true; - - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Literals.cs b/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Literals.cs deleted file mode 100644 index a6491d40..00000000 --- a/ZSharp.Compiler/compiler core/compiler/literals/Compiler.Literals.cs +++ /dev/null @@ -1,15 +0,0 @@ -using ZSharp.Objects; - -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - private CompilerObject trueObject = null!, falseObject = null!; - - private void InitializeLiterals() - { - trueObject = new TrueLiteral(TypeSystem.Boolean); - falseObject = new FalseLiteral(TypeSystem.Boolean); - } - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/value/Compiler.IsCT.cs b/ZSharp.Compiler/compiler core/compiler/value/Compiler.IsCT.cs deleted file mode 100644 index 2e290ad8..00000000 --- a/ZSharp.Compiler/compiler core/compiler/value/Compiler.IsCT.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace ZSharp.Compiler -{ - public sealed partial class Compiler - { - public bool IsCTValue(CompilerObject @object) - { - if (IsLiteral(@object)) return true; - - return false; // TODO: implement the CTValue protocol - } - - public bool IsCTValue(CompilerObject @object, [NotNullWhen(true)] out T? value) - where T : class - { - if (IsLiteral(@object, out value)) return true; - - return false; // TODO: implement CTValue protocol - } - - public bool IsCTValue(CompilerObject @object, [NotNullWhen(true)] out T? value) - where T : struct - { - if (IsLiteral(@object, out value)) return true; - - return false; // TODO: implement CTValue protocol - } - } -} diff --git a/ZSharp.Compiler/compiler core/core/Feature.cs b/ZSharp.Compiler/compiler core/core/Feature.cs deleted file mode 100644 index 7fb05137..00000000 --- a/ZSharp.Compiler/compiler core/core/Feature.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace ZSharp.Compiler -{ - public abstract class Feature - { - public Compiler Compiler { get; } - - public Feature(Compiler compiler) - { - Compiler = compiler; - - compiler.Feature(this); - } - } -} diff --git a/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs b/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs deleted file mode 100644 index 648086a7..00000000 --- a/ZSharp.Compiler/compiler core/core/type system/IDynamicallyTyped.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IDynamicallyTyped - : CompilerObject - , IHasRuntimeDescriptor - { - CompilerObject IHasRuntimeDescriptor.GetRuntimeDescriptor(Compiler compiler) - => GetType(compiler); - - public IType GetType(Compiler compiler); - } -} diff --git a/ZSharp.Compiler/compiler core/core/type system/IType.cs b/ZSharp.Compiler/compiler core/core/type system/IType.cs deleted file mode 100644 index 9961c27a..00000000 --- a/ZSharp.Compiler/compiler core/core/type system/IType.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IType - : CompilerObject - { - public bool IsEqualTo(Compiler compiler, IType type) - => ReferenceEquals(this, type); - } -} diff --git a/ZSharp.Compiler/compiler core/core/type system/ITypeAssignment.cs b/ZSharp.Compiler/compiler core/core/type system/ITypeAssignment.cs deleted file mode 100644 index 4c5e5e39..00000000 --- a/ZSharp.Compiler/compiler core/core/type system/ITypeAssignment.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ITypeAssignableToType - : IType - { - public bool? IsAssignableTo(Compiler compiler, IType target) - => null; - } - - public interface ITypeAssignableFromType - : IType - { - public bool? IsAssignableFrom(Compiler compiler, IType source) - => null; - } -} diff --git a/ZSharp.Compiler/compiler core/core/type system/ITypeModifier.cs b/ZSharp.Compiler/compiler core/core/type system/ITypeModifier.cs deleted file mode 100644 index 42938a30..00000000 --- a/ZSharp.Compiler/compiler core/core/type system/ITypeModifier.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ITypeModifier - { - public CompilerObject InnerType { get; } - } -} diff --git a/ZSharp.Compiler/compiler core/core/type system/ITyped.cs b/ZSharp.Compiler/compiler core/core/type system/ITyped.cs deleted file mode 100644 index 141237c5..00000000 --- a/ZSharp.Compiler/compiler core/core/type system/ITyped.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ITyped : IDynamicallyTyped - { - public IType Type { get; } - - IType IDynamicallyTyped.GetType(Compiler compiler) - => Type; - } -} diff --git a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs b/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs deleted file mode 100644 index 58d79e59..00000000 --- a/ZSharp.Compiler/compiler core/core/type system/TypeSystem.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using ZSharp.Objects; - -namespace ZSharp.Compiler -{ - public sealed class TypeSystem - : Feature - { - public StringType String { get; } - - public IType Type { get; } - - public IType Void { get; } - - public IType Null { get; } - - public IType Boolean { get; } - - public Int32Type Int32 { get; } - - public IType Float32 { get; } - - public ObjectType Object { get; } - - public ArrayTypeObject ArrayType { get; } - - public ReferenceTypeObject ReferenceType { get; } - - public PointerTypeObject PointerType { get; } - - internal TypeSystem(Compiler compiler) - : base(compiler) - { - Type = new Objects.Type(compiler.RuntimeModule.TypeSystem.Type); - - String = new(compiler.RuntimeModule.TypeSystem.String, Type); - Void = new RawType(compiler.RuntimeModule.TypeSystem.Void, Type); - Null = new RawType(compiler.RuntimeModule.TypeSystem.Null, Type); - Boolean = new RawType(compiler.RuntimeModule.TypeSystem.Boolean, Type); - Int32 = new(compiler.RuntimeModule.TypeSystem.Int32, Type); - Float32 = new RawType(compiler.RuntimeModule.TypeSystem.Float32, Type); - Object = new ObjectType(compiler.RuntimeModule.TypeSystem.Object, Type); - - ArrayType = new ArrayTypeObject(compiler.RuntimeModule.TypeSystem.Array); - ReferenceType = new ReferenceTypeObject(compiler.RuntimeModule.TypeSystem.Reference); - PointerType = new(compiler.RuntimeModule.TypeSystem.Pointer); - } - - public IType Array(IType type) - => ArrayType.Instantiate(type); - - public IType Pointer(CompilerObject type) - => throw new NotImplementedException(); - - public IType Reference(CompilerObject type) - => throw new NotImplementedException(); - - public bool AreEqual(IType left, IType right) - { - if (left.IsEqualTo(Compiler, right)) - return true; - if (right.IsEqualTo(Compiler, left)) - return true; - return false; - } - - public CompilerObjectResult ImplicitCast(CompilerObject value, IType type) - { - CompilerObjectResult result = CompilerObjectResult.Error( - $"ImplicitCast for value:{value}, type:{type} is not supported." - ); - - if (type is IImplicitCastFromValue castFromValue) - result = Compiler.Wrap(c => castFromValue.ImplicitCastFromValue(c, value)); - - if (result.IsOk) - return result; - - if (value is IImplicitCastToType castToType) - result = Compiler.Wrap(c => castToType.ImplicitCastToType(c, type)); - - if (result.IsOk) - return result; - - if (IsTyped(value, out var valueType) && IsAssignableTo(valueType, type)) - result = CompilerObjectResult.Ok(value); - - return result; - } - - public bool IsAssignableTo(IType source, IType target) - { - if (source is ITypeAssignableToType to && to.IsAssignableTo(Compiler, target) is bool assignableTo) - return assignableTo; - - if (target is ITypeAssignableFromType from && from.IsAssignableFrom(Compiler, source) is bool assignableFrom) - return assignableFrom; - - if (AreEqual(source, target)) - return true; - - return false; - } - - public bool IsAssignableFrom(IType target, IType source) - => IsAssignableTo(source, target); - - public bool IsTyped(CompilerObject @object) - => @object is IDynamicallyTyped; - - public bool IsTyped(CompilerObject @object, [NotNullWhen(true)] out IType? type) - { - if (@object is IDynamicallyTyped typed) - return (type = typed.GetType(Compiler)) is not null; - - return (type = null) is not null; - } - - public bool IsTyped(CompilerObject @object, [NotNullWhen(true)] out T? type) - where T : class, IType - => (type = IsTyped(@object, out var objectType) ? objectType as T : null) is not null; - - public bool IsTypeModifier(CompilerObject @object) - => @object is ITypeModifier; - - public bool IsTypeModifier(CompilerObject @object, [NotNullWhen(true)] out CompilerObject? innerType) - { - if (@object is ITypeModifier modifier) - return (innerType = modifier.InnerType) is not null; - - return (innerType = null) is not null; - } - } -} diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.Context.cs b/ZSharp.Compiler/compiler/Compiler.Context.cs similarity index 91% rename from ZSharp.Compiler/compiler core/compiler/Compiler.Context.cs rename to ZSharp.Compiler/compiler/Compiler.Context.cs index 387d4d56..7509b7dd 100644 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.Context.cs +++ b/ZSharp.Compiler/compiler/Compiler.Context.cs @@ -9,7 +9,7 @@ public sealed partial class Compiler public Action UseContext(IContext context) { (CurrentContext, context) = (context, CurrentContext); - CurrentContext.Parent = context; + CurrentContext.Parent ??= context; return () => CurrentContext = context; } diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.Logging.cs b/ZSharp.Compiler/compiler/Compiler.Logging.cs similarity index 67% rename from ZSharp.Compiler/compiler core/compiler/Compiler.Logging.cs rename to ZSharp.Compiler/compiler/Compiler.Logging.cs index cd374302..8efe38a5 100644 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.Logging.cs +++ b/ZSharp.Compiler/compiler/Compiler.Logging.cs @@ -1,4 +1,6 @@ -namespace ZSharp.Compiler +using ZSharp.Logging; + +namespace ZSharp.Compiler { public sealed partial class Compiler { diff --git a/ZSharp.Compiler/compiler/Compiler.Services.cs b/ZSharp.Compiler/compiler/Compiler.Services.cs new file mode 100644 index 00000000..65c7d986 --- /dev/null +++ b/ZSharp.Compiler/compiler/Compiler.Services.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Compiler +{ + public sealed partial class Compiler + { + private CG cg; + private TS ts; + + public ref CG CG => ref cg; + + public IR IR { get; } + + public ref TS TS => ref ts; + + public TS TypeSystem { init => ts = value; } + } +} diff --git a/ZSharp.Compiler/compiler core/compiler/Compiler.cs b/ZSharp.Compiler/compiler/Compiler.cs similarity index 51% rename from ZSharp.Compiler/compiler core/compiler/Compiler.cs rename to ZSharp.Compiler/compiler/Compiler.cs index 6acbbf32..0a4eb4fd 100644 --- a/ZSharp.Compiler/compiler core/compiler/Compiler.cs +++ b/ZSharp.Compiler/compiler/Compiler.cs @@ -2,6 +2,8 @@ { public sealed partial class Compiler { + public ZSharp.IR.RuntimeModule RuntimeModule { get; } + public Compiler() : this(ZSharp.IR.RuntimeModule.Standard) { } @@ -9,18 +11,8 @@ public Compiler(ZSharp.IR.RuntimeModule runtimeModule) { RuntimeModule = runtimeModule; - CG = new(this); - IR = new(this); - TypeSystem = new(this); - - Initialize(); - } - - private void Initialize() - { - InitializeTypeSystem(); - InitializeLiterals(); - InitializeFeatures(); + CG = new(); + IR = new(runtimeModule); } } } diff --git a/ZSharp.Compiler/core/CompilerObject.cs b/ZSharp.Compiler/core/CompilerObject.cs deleted file mode 100644 index 8e238ec9..00000000 --- a/ZSharp.Compiler/core/CompilerObject.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace ZSharp.Objects -{ - public interface CompilerObject - { - } -} diff --git a/ZSharp.Compiler/core/concepts/IMappable.cs b/ZSharp.Compiler/core/concepts/IMappable.cs deleted file mode 100644 index 0d34c8a1..00000000 --- a/ZSharp.Compiler/core/concepts/IMappable.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IMappable - : CompilerObject - { - public CompilerObject Map(Func func); - } -} diff --git a/ZSharp.Compiler/core/concepts/INamedObject.cs b/ZSharp.Compiler/core/concepts/INamedObject.cs deleted file mode 100644 index 09aa2527..00000000 --- a/ZSharp.Compiler/core/concepts/INamedObject.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface INamedObject - : CompilerObject - { - public string Name { get; } - - public bool IsAnonymous => Name == string.Empty; - } -} diff --git a/ZSharp.Compiler/core/concepts/callable/ICallable.cs b/ZSharp.Compiler/core/concepts/callable/ICallable.cs deleted file mode 100644 index a084dcc1..00000000 --- a/ZSharp.Compiler/core/concepts/callable/ICallable.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ZSharp.Compiler -{ - /// - /// Should be implemented by any binding that is callable. - /// - public interface ICTCallable_Old - : ICTCallable - { - CompilerObjectResult ICTCallable.Call(Compiler compiler, Argument_NEW[] arguments) - => CompilerObjectResult.Ok( - Call(compiler, arguments.Select(arg => new Argument(arg.Name, arg.Value)).ToArray()) - ); - - public CompilerObject Call(Compiler compiler, Argument[] arguments); - } -} diff --git a/ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs b/ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs deleted file mode 100644 index aa6b2ed1..00000000 --- a/ZSharp.Compiler/core/concepts/index/ICTGetIndex.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTGetIndex : ICTGetIndex_NEW - { - CompilerObjectResult ICTGetIndex_NEW.Index(Compiler compiler, Argument_NEW[] arguments) - => CompilerObjectResult.Ok(Index(compiler, [.. arguments.Select(arg => new Argument(arg.Name, arg.Value))])); - - public CompilerObject Index(Compiler compiler, Argument[] index); - } -} diff --git a/ZSharp.Compiler/core/concepts/index/ISetIndex.cs b/ZSharp.Compiler/core/concepts/index/ISetIndex.cs deleted file mode 100644 index fc9d622b..00000000 --- a/ZSharp.Compiler/core/concepts/index/ISetIndex.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - internal interface ISetIndex - { - public CompilerObject Index(T @object, Argument[] index, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/core/concepts/member/IGetMember.cs b/ZSharp.Compiler/core/concepts/member/IGetMember.cs deleted file mode 100644 index 2a936c6b..00000000 --- a/ZSharp.Compiler/core/concepts/member/IGetMember.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTGetMember_Old : ICTGetMember - { - CompilerObjectResult ICTGetMember.Member(Compiler compiler, M member) - => CompilerObjectResult.Ok(Member(compiler, member)); - - public new CompilerObject Member(Compiler compiler, M member); - } - - public interface IRTGetMember_Old : IRTGetMember - { - CompilerObjectResult IRTGetMember.Member(Compiler compiler, CompilerObject @object, M member) - => CompilerObjectResult.Ok(Member(compiler, @object, member)); - - public new CompilerObject Member(Compiler compiler, CompilerObject value, M member); - } -} diff --git a/ZSharp.Compiler/core/concepts/member/ISetMember_Old.cs b/ZSharp.Compiler/core/concepts/member/ISetMember_Old.cs deleted file mode 100644 index 82c428ef..00000000 --- a/ZSharp.Compiler/core/concepts/member/ISetMember_Old.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - internal interface ISetMember_Old - { - public CompilerObject Member(T @object, M member, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/core/concepts/value/IEvaluable.cs b/ZSharp.Compiler/core/concepts/value/IEvaluable.cs deleted file mode 100644 index 1e2d564d..00000000 --- a/ZSharp.Compiler/core/concepts/value/IEvaluable.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IEvaluable - { - public CompilerObject Evaluate(Compiler compiler); - } -} diff --git a/ZSharp.Compiler/core/concepts/value/IImplicitCast.cs b/ZSharp.Compiler/core/concepts/value/IImplicitCast.cs deleted file mode 100644 index 6a7b71f1..00000000 --- a/ZSharp.Compiler/core/concepts/value/IImplicitCast.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IImplicitCastFromValue - { - public CompilerObject ImplicitCastFromValue(Compiler compiler, CompilerObject value); - } - - public interface IImplicitCastToType - { - public CompilerObject ImplicitCastToType(Compiler compiler, IType type); - } -} diff --git a/ZSharp.Compiler/core/concepts/value/IReadable.cs b/ZSharp.Compiler/core/concepts/value/IReadable.cs deleted file mode 100644 index 78c41a1b..00000000 --- a/ZSharp.Compiler/core/concepts/value/IReadable.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTReadable - : ITyped - , ICTCompileIRCode - { - public IRCode Cast(Compiler compiler, IType type) - => this is ICTTypeCast typeCast - && typeCast.Cast(compiler, type) is ICTReadable readable - ? readable.Read(compiler, type) - : throw new NotImplementedException(); - - public IRCode Read(Compiler compiler, IType? @as) - { - if (@as is null || @as == Type) - return Read(compiler); - return Cast(compiler, @as); - } - - public IRCode Read(Compiler compiler); - - Result ICTCompileIRCode.CompileIRCode(Compiler compiler) - => Result.Ok(Read(compiler)); - } -} diff --git a/ZSharp.Compiler/core/concepts/value/ITypeCast.cs b/ZSharp.Compiler/core/concepts/value/ITypeCast.cs deleted file mode 100644 index 90cd4e8b..00000000 --- a/ZSharp.Compiler/core/concepts/value/ITypeCast.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTTypeCast - { - public CompilerObject Cast(Compiler compiler, IType targetType); - } - - public interface IRTTypeCast - { - public CompilerObject Cast(Compiler compiler, CompilerObject @object, IType targetType); - } -} diff --git a/ZSharp.Compiler/core/concepts/value/assignment/Assignment.cs b/ZSharp.Compiler/core/concepts/value/assignment/Assignment.cs deleted file mode 100644 index 06bf1cb5..00000000 --- a/ZSharp.Compiler/core/concepts/value/assignment/Assignment.cs +++ /dev/null @@ -1,92 +0,0 @@ -namespace ZSharp.Compiler -{ - public enum AssignmentType - { - Incompatible = 0, - Unspecified = 1, - Exact = 2, - Polymorphic = 3, - DirectImplementation = 4, - ExternalImplementation = 5, - ImplicitCast = 6, - ExplicitCast = 7, - Any = -1, - } - - public abstract class Assignment - { - public abstract AssignmentType AssignmentType { get; } - - public static Assignment Incompatible { get; } = new Incompatible(); - - public static Assignment Unspecified { get; } = new Unspecified(); - - public static Assignment Exact { get; } = new Polymorphic(0); - - public static Assignment Any { get; } = new Polymorphic(-1); - - public static Polymorphic Polymorphic(int distance) - => new(distance); - - public static DirectImplementation DirectImplementation(int distance) - => new(distance); - - public static ExternalImplementation ExternalImplementation(int distance) - => new(distance); - - public static ImplicitCast ImplicitCast(CompilerObject castFunction) - => new(castFunction); - - public static ExplicitCast ExplicitCast(CompilerObject castFunction) - => new(castFunction); - } - - public sealed class Incompatible : Assignment - { - public override AssignmentType AssignmentType => AssignmentType.Incompatible; - - internal Incompatible() { } - } - - public sealed class Unspecified : Assignment - { - public override AssignmentType AssignmentType => AssignmentType.Unspecified; - - internal Unspecified() { } - } - - public sealed class Polymorphic(int distance) : Assignment - { - public override AssignmentType AssignmentType - => Distance == 0 ? AssignmentType.Exact : AssignmentType.Polymorphic; - - public int Distance { get; } = distance; - } - - public sealed class DirectImplementation(int distance) : Assignment - { - public override AssignmentType AssignmentType => AssignmentType.DirectImplementation; - - public int Distance { get; } = distance; - } - - public sealed class ExternalImplementation(int distance) : Assignment - { - public override AssignmentType AssignmentType => AssignmentType.ExternalImplementation; - - public int Distance { get; } = distance; - } - - public abstract class Cast(CompilerObject castFunction, AssignmentType assignmentType) : Assignment - { - public override AssignmentType AssignmentType => assignmentType; - - public CompilerObject CastFunction { get; } = castFunction; - } - - public sealed class ImplicitCast(CompilerObject castFunction) - : Cast(castFunction, AssignmentType.ImplicitCast); - - public sealed class ExplicitCast(CompilerObject castFunction) - : Cast(castFunction, AssignmentType.ExplicitCast); -} diff --git a/ZSharp.Compiler/core/concepts/value/assignment/IAssignable.cs b/ZSharp.Compiler/core/concepts/value/assignment/IAssignable.cs deleted file mode 100644 index 6085ca67..00000000 --- a/ZSharp.Compiler/core/concepts/value/assignment/IAssignable.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTAssignable : ICTSet - { - CompilerObjectResult ICTSet.Set(Compiler compiler, CompilerObject value) - => CompilerObjectResult.Ok(Assign(compiler, value)); - - public CompilerObject Assign(Compiler compiler, CompilerObject value); - } - - public interface IRTAssignable : IRTSet - { - CompilerObjectResult IRTSet.Set(Compiler compiler, CompilerObject @object, CompilerObject value) - => CompilerObjectResult.Ok(Assign(compiler, @object, value)); - - public CompilerObject Assign(Compiler compiler, CompilerObject @object, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/compiler core/core/context/EmptyContext.cs b/ZSharp.Compiler/core/context/EmptyContext.cs similarity index 100% rename from ZSharp.Compiler/compiler core/core/context/EmptyContext.cs rename to ZSharp.Compiler/core/context/EmptyContext.cs diff --git a/ZSharp.Compiler/core/logging/LoggerExtensions.cs b/ZSharp.Compiler/core/logging/LoggerExtensions.cs new file mode 100644 index 00000000..9217bd8d --- /dev/null +++ b/ZSharp.Compiler/core/logging/LoggerExtensions.cs @@ -0,0 +1,19 @@ +using ZSharp.Logging; + +namespace ZSharp.Compiler +{ + public static class LoggerExtensions + { + public static void Info(this Logger logger, T message, CompilerObject origin) + => logger.Log(new() { Message = message, Level = LogLevel.Info, Origin = Origin(origin) }); + + public static void Warning(this Logger logger, T message, CompilerObject origin) + => logger.Log(new() { Message = message, Level = LogLevel.Warning, Origin = Origin(origin) }); + + public static void Error(this Logger logger, T message, CompilerObject origin) + => logger.Log(new() { Message = message, Level = LogLevel.Error, Origin = Origin(origin) }); + + public static LogOrigin Origin(CompilerObject @object) + => new ObjectLogOrigin(@object); + } +} diff --git a/ZSharp.Compiler/compiler core/core/logging/ObjectLogOrigin.cs b/ZSharp.Compiler/core/logging/ObjectLogOrigin.cs similarity index 79% rename from ZSharp.Compiler/compiler core/core/logging/ObjectLogOrigin.cs rename to ZSharp.Compiler/core/logging/ObjectLogOrigin.cs index 88ad73ea..fe6496f2 100644 --- a/ZSharp.Compiler/compiler core/core/logging/ObjectLogOrigin.cs +++ b/ZSharp.Compiler/core/logging/ObjectLogOrigin.cs @@ -1,4 +1,6 @@ -namespace ZSharp.Compiler +using ZSharp.Logging; + +namespace ZSharp.Compiler { internal sealed class ObjectLogOrigin(CompilerObject @object) : LogOrigin { diff --git a/ZSharp.Compiler/exceptions/CompilerObjectException.cs b/ZSharp.Compiler/exceptions/CompilerObjectException.cs deleted file mode 100644 index a22c3937..00000000 --- a/ZSharp.Compiler/exceptions/CompilerObjectException.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public abstract class CompilerObjectException(CompilerObject @object, string? message = null, Exception? innerException = null) - : Exception(message, innerException) - { - public CompilerObject Object { get; } = @object; - } -} diff --git a/ZSharp.Compiler/exceptions/InvalidCastException.cs b/ZSharp.Compiler/exceptions/InvalidCastException.cs deleted file mode 100644 index ded5950a..00000000 --- a/ZSharp.Compiler/exceptions/InvalidCastException.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Compiler -{ - public sealed class InvalidCastException(CompilerObject @object, CompilerObject type) - : CompilerObjectException(@object) - { - public CompilerObject Target => Object; - - public CompilerObject Type { get; } = type; - } -} diff --git a/ZSharp.Compiler/exceptions/PartiallyCompiledObjectException.cs b/ZSharp.Compiler/exceptions/PartiallyCompiledObjectException.cs deleted file mode 100644 index 6009ba80..00000000 --- a/ZSharp.Compiler/exceptions/PartiallyCompiledObjectException.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZSharp.Compiler -{ - public sealed class PartiallyCompiledObjectException( - CompilerObject @object, - string? message = null - ) - : CompilerObjectException(@object, message) - { - - } -} diff --git a/ZSharp.Compiler/features/cap/generic/IGenericInstantiable.cs b/ZSharp.Compiler/features/cap/generic/IGenericInstantiable.cs deleted file mode 100644 index 3dc56cb5..00000000 --- a/ZSharp.Compiler/features/cap/generic/IGenericInstantiable.cs +++ /dev/null @@ -1,13 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public interface IGenericInstantiable - : CompilerObject - { - public CompilerObjectResult Instantiate( - Compiler.Compiler compiler, - Argument[] arguments - ); - } -} diff --git a/ZSharp.Compiler/features/cg/CG.cs b/ZSharp.Compiler/features/cg/CG.cs deleted file mode 100644 index 22daa277..00000000 --- a/ZSharp.Compiler/features/cg/CG.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ZSharp.Compiler -{ - public readonly partial struct CG(Compiler compiler) - { - public readonly Compiler compiler = compiler; - - private bool This(out CG cg) - { - cg = this; - return true; - } - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/callable/Argument.cs b/ZSharp.Compiler/features/cg/capabilities/callable/Argument.cs deleted file mode 100644 index 425cb39f..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/callable/Argument.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ZSharp.Compiler -{ - public class Argument_NEW(T value) - where T : CompilerObject - { - public T Value { get; set; } = value; - - public string? Name { get; set; } - - public Argument_NEW(string? name, T value) - : this(value) - { - Name = name; - } - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs b/ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs deleted file mode 100644 index 52b19bc7..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/callable/ICTCallable.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTCallable - : CompilerObject - { - public CompilerObjectResult Call(Compiler compiler, Argument_NEW[] arguments); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/callable/IRTCallable.cs b/ZSharp.Compiler/features/cg/capabilities/callable/IRTCallable.cs deleted file mode 100644 index df568091..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/callable/IRTCallable.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTCallable_NEW - : CompilerObject - { - public CompilerObjectResult Call(Compiler compiler, CompilerObject @object, Argument_NEW[] arguments); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastFrom.cs b/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastFrom.cs deleted file mode 100644 index 1054afcc..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastFrom.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTImplicitCastFrom - : CompilerObject - { - public CompilerObjectResult ImplicitCast(Compiler compiler, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastTo.cs b/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastTo.cs deleted file mode 100644 index aea16516..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/implicit casting/ICTImplicitCastTo.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTImplicitCastTo - : CompilerObject - { - public CompilerObjectResult ImplicitCast(Compiler compiler, IType type); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/implicit casting/IRTImplicitCastTo.cs b/ZSharp.Compiler/features/cg/capabilities/implicit casting/IRTImplicitCastTo.cs deleted file mode 100644 index d2e47871..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/implicit casting/IRTImplicitCastTo.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTImplicitCastTo - : CompilerObject - { - public CompilerObjectResult ImplicitCast(Compiler compiler, CompilerObject @object, IType type); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/index/ICTGetIndex.cs b/ZSharp.Compiler/features/cg/capabilities/index/ICTGetIndex.cs deleted file mode 100644 index a89af7ad..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/index/ICTGetIndex.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTGetIndex_NEW - : CompilerObject - { - public CompilerObjectResult Index(Compiler compiler, Argument_NEW[] arguments); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/index/ICTSetIndex.cs b/ZSharp.Compiler/features/cg/capabilities/index/ICTSetIndex.cs deleted file mode 100644 index fcd75a27..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/index/ICTSetIndex.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTSetIndex_NEW - : CompilerObject - { - public CompilerObjectResult Index(Compiler compiler, Argument_NEW[] arguments, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/index/IRTGetIndex.cs b/ZSharp.Compiler/features/cg/capabilities/index/IRTGetIndex.cs deleted file mode 100644 index afcfbf6e..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/index/IRTGetIndex.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTGetIndex_NEW - : CompilerObject - { - public CompilerObjectResult Index(Compiler compiler, CompilerObject @object, Argument_NEW[] arguments); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/index/IRTSetIndex.cs b/ZSharp.Compiler/features/cg/capabilities/index/IRTSetIndex.cs deleted file mode 100644 index b323f14d..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/index/IRTSetIndex.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTSetIndex_NEW - : CompilerObject - { - public CompilerObjectResult Index(Compiler compiler, CompilerObject @object, Argument_NEW[] arguments, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/member access/ICTSetMember.cs b/ZSharp.Compiler/features/cg/capabilities/member access/ICTSetMember.cs deleted file mode 100644 index 4a391697..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/member access/ICTSetMember.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTSetMember - { - public CompilerObjectResult Member(Compiler compiler, M member, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/member access/IRTGetMember.cs b/ZSharp.Compiler/features/cg/capabilities/member access/IRTGetMember.cs deleted file mode 100644 index 0ebf140d..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/member access/IRTGetMember.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTGetMember - { - public CompilerObjectResult Member(Compiler compiler, CompilerObject @object, M member); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/member access/IRTSetMember.cs b/ZSharp.Compiler/features/cg/capabilities/member access/IRTSetMember.cs deleted file mode 100644 index b7b5fe94..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/member access/IRTSetMember.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTSetMember - { - public CompilerObjectResult Member(Compiler compiler, CompilerObject @object, M member, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/runtime/IHasRuntimeDescriptor.cs b/ZSharp.Compiler/features/cg/capabilities/runtime/IHasRuntimeDescriptor.cs deleted file mode 100644 index d2bce635..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/runtime/IHasRuntimeDescriptor.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IHasRuntimeDescriptor - : CompilerObject - { - public CompilerObject GetRuntimeDescriptor(Compiler compiler); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/type casting/ICTCastTo.cs b/ZSharp.Compiler/features/cg/capabilities/type casting/ICTCastTo.cs deleted file mode 100644 index 68ff4b8e..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/type casting/ICTCastTo.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTCastTo - : CompilerObject - { - public Result Cast(Compiler compiler, IType targetType); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastFrom.cs b/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastFrom.cs deleted file mode 100644 index 0d6f2142..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastFrom.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTCastFrom - : CompilerObject - { - public Result Cast(Compiler compiler, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastTo.cs b/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastTo.cs deleted file mode 100644 index 50386228..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/type casting/IRTCastTo.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTCastTo - : CompilerObject - { - public Result Cast(Compiler compiler, CompilerObject value, IType targetType); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/type matching/ICTTypeMatch.cs b/ZSharp.Compiler/features/cg/capabilities/type matching/ICTTypeMatch.cs deleted file mode 100644 index f44ee43b..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/type matching/ICTTypeMatch.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTTypeMatch - : CompilerObject - { - public Result Match(Compiler compiler, IType type); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/type matching/IRTTypeMatch.cs b/ZSharp.Compiler/features/cg/capabilities/type matching/IRTTypeMatch.cs deleted file mode 100644 index b3e3b89e..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/type matching/IRTTypeMatch.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTTypeMatch - : CompilerObject - { - public Result Match(Compiler compiler, CompilerObject value, IType type); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/value access/get/ICTGet.cs b/ZSharp.Compiler/features/cg/capabilities/value access/get/ICTGet.cs deleted file mode 100644 index 8357c152..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/value access/get/ICTGet.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTGet - : CompilerObject - { - public CompilerObjectResult Get(Compiler compiler); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/value access/get/IRTGet.cs b/ZSharp.Compiler/features/cg/capabilities/value access/get/IRTGet.cs deleted file mode 100644 index 932b8f78..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/value access/get/IRTGet.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTGet - : CompilerObject - { - public CompilerObjectResult Get(Compiler compiler, CompilerObject @object); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/value access/set/ICTSet.cs b/ZSharp.Compiler/features/cg/capabilities/value access/set/ICTSet.cs deleted file mode 100644 index 0cdd250f..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/value access/set/ICTSet.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTSet - : CompilerObject - { - public CompilerObjectResult Set(Compiler compiler, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/value access/set/IRTSet.cs b/ZSharp.Compiler/features/cg/capabilities/value access/set/IRTSet.cs deleted file mode 100644 index 604facf6..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/value access/set/IRTSet.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IRTSet - : CompilerObject - { - public CompilerObjectResult Set(Compiler compiler, CompilerObject @object, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/features/cg/capabilities/wrapper/IObjectWrapper.cs b/ZSharp.Compiler/features/cg/capabilities/wrapper/IObjectWrapper.cs deleted file mode 100644 index 02a7b8c8..00000000 --- a/ZSharp.Compiler/features/cg/capabilities/wrapper/IObjectWrapper.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface IObjectWrapper - : CompilerObject - { - public T MapWrapped(Compiler compiler, Func fn); - } -} diff --git a/ZSharp.Compiler/features/cg/services/CG.Call.cs b/ZSharp.Compiler/features/cg/services/CG.Call.cs deleted file mode 100644 index 9f3aea4a..00000000 --- a/ZSharp.Compiler/features/cg/services/CG.Call.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace ZSharp.Compiler -{ - public partial struct CG - { - public CompilerObjectResult Call(CompilerObject @object, Argument_NEW[] arguments) - { - var result = CompilerObjectResult.Error("Object does not support calling"); - - if (@object is ICTCallable ctCallable) - result = ctCallable.Call(compiler, arguments); - - if (result.IsOk) return result; - - if (RuntimeDescriptor(@object, out var runtimeDescriptor) - && runtimeDescriptor is IRTCallable_NEW rtCallable - ) - result = rtCallable.Call(compiler, @object, arguments); - - if (result.IsOk) return result; - - return result; - } - } -} diff --git a/ZSharp.Compiler/features/cg/services/CG.ImplicitCast.cs b/ZSharp.Compiler/features/cg/services/CG.ImplicitCast.cs deleted file mode 100644 index c5faa684..00000000 --- a/ZSharp.Compiler/features/cg/services/CG.ImplicitCast.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace ZSharp.Compiler -{ - public partial struct CG - { - public CompilerObjectResult ImplicitCast(CompilerObject @object, IType type) - { - var result = CompilerObjectResult.Error("Object does not support implicit cast"); - - if (@object is ICTImplicitCastTo ctCastTo) - result = ctCastTo.ImplicitCast(compiler, type); - - if (result.IsOk) return result; - - if (RuntimeDescriptor(@object, out var runtimeDescriptor) - && runtimeDescriptor is IRTImplicitCastTo rtCastTo - ) - result = rtCastTo.ImplicitCast(compiler, @object, type); - - if (result.IsOk) return result; - - if (type is ICTImplicitCastFrom ctCastFrom) - result = ctCastFrom.ImplicitCast(compiler, @object); - - return result; - } - } -} diff --git a/ZSharp.Compiler/features/cg/services/CG.Index.cs b/ZSharp.Compiler/features/cg/services/CG.Index.cs deleted file mode 100644 index 1f2d5851..00000000 --- a/ZSharp.Compiler/features/cg/services/CG.Index.cs +++ /dev/null @@ -1,46 +0,0 @@ -namespace ZSharp.Compiler -{ - public partial struct CG - { - public CompilerObjectResult Index(CompilerObject @object, Argument_NEW[] arguments) - { - var result = CompilerObjectResult.Error("Object does not support get index"); - - if (@object is ICTGetIndex_NEW ctGet) - result = ctGet.Index(compiler, arguments); - - if (result.IsOk) return result; - - if (RuntimeDescriptor(@object, out var runtimeDescriptor) - && runtimeDescriptor is IRTGetIndex_NEW rtGet - ) - result = rtGet.Index(compiler, @object, arguments); - - if (result.IsOk) return result; - - if (@object is IObjectWrapper wrapper && This(out var cg)) // TODO: this is in testing - result = wrapper.MapWrapped(compiler, wrapped => cg.Index(wrapped, arguments)); - - return result; - } - - public CompilerObjectResult Index(CompilerObject @object, Argument_NEW[] arguments, CompilerObject value) - { - var result = CompilerObjectResult.Error("Object does not support set index"); - - if (@object is ICTSetIndex_NEW ctGet) - result = ctGet.Index(compiler, arguments, value); - - if (result.IsOk) return result; - - if (RuntimeDescriptor(@object, out var runtimeDescriptor) - && runtimeDescriptor is IRTSetIndex_NEW rtGet - ) - result = rtGet.Index(compiler, @object, arguments, value); - - if (result.IsOk) return result; - - return result; - } - } -} diff --git a/ZSharp.Compiler/features/cg/services/CG.MemberAccess.cs b/ZSharp.Compiler/features/cg/services/CG.MemberAccess.cs deleted file mode 100644 index 920b4b04..00000000 --- a/ZSharp.Compiler/features/cg/services/CG.MemberAccess.cs +++ /dev/null @@ -1,83 +0,0 @@ -namespace ZSharp.Compiler -{ - public partial struct CG - { - public CompilerObjectResult Member(CompilerObject @object, M member) - { - var result = CompilerObjectResult.Error($"Object does not support get member by {typeof(M).Name}"); - - if (@object is ICTGetMember ctGet) - result = ctGet.Member(compiler, member); - - if (result.IsOk) return result; - - if ( - RuntimeDescriptor(@object, out var runtimeDescritpr) - && runtimeDescritpr is IRTGetMember rtGet - ) - result = rtGet.Member(compiler, @object, member); - - if (result.IsOk) return result; - - return result; - } - - public CompilerObjectResult Member(CompilerObject @object, M member, CompilerObject value) - { - var result = CompilerObjectResult.Error($"Object does not support set member by {typeof(M).Name}"); - - if (@object is ICTSetMember ctGet) - result = ctGet.Member(compiler, member, value); - - if (result.IsOk) return result; - - if ( - RuntimeDescriptor(@object, out var runtimeDescritpr) - && runtimeDescritpr is IRTSetMember rtGet - ) - result = rtGet.Member(compiler, @object, member, value); - - if (result.IsOk) return result; - - return result; - } - - /// - /// The get member (.) operator. - /// - /// - /// - /// - public CompilerObjectResult Member(CompilerObject @object, MemberIndex index) - => Member(@object, index); - - /// - /// The set member (.=) operator. - /// - /// - /// - /// - /// - public CompilerObjectResult Member(CompilerObject @object, MemberIndex index, CompilerObject value) - => Member(@object, index, value); - - /// - /// The member (.) operator. - /// - /// - /// - /// - public CompilerObjectResult Member(CompilerObject @object, MemberName name) - => Member(@object, name); - - /// - /// The set member (.=) operator. - /// - /// - /// - /// - /// - public CompilerObjectResult Member(CompilerObject @object, MemberName name, CompilerObject value) - => Member(@object, name, value); - } -} diff --git a/ZSharp.Compiler/features/cg/services/CG.Runtime.cs b/ZSharp.Compiler/features/cg/services/CG.Runtime.cs deleted file mode 100644 index 8ac8882a..00000000 --- a/ZSharp.Compiler/features/cg/services/CG.Runtime.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace ZSharp.Compiler -{ - public partial struct CG - { - public CompilerObject? RuntimeDescriptor(CompilerObject @object) - => @object is IHasRuntimeDescriptor hasRuntimeDescriptor - ? hasRuntimeDescriptor.GetRuntimeDescriptor(compiler) - : null; - - public bool RuntimeDescriptor(CompilerObject @object, [NotNullWhen(true)] out CompilerObject? rt) - => (rt = RuntimeDescriptor(@object)) is not null; - } -} diff --git a/ZSharp.Compiler/features/cg/services/CG.TypeCast.cs b/ZSharp.Compiler/features/cg/services/CG.TypeCast.cs deleted file mode 100644 index c99a7477..00000000 --- a/ZSharp.Compiler/features/cg/services/CG.TypeCast.cs +++ /dev/null @@ -1,40 +0,0 @@ -namespace ZSharp.Compiler -{ - public partial struct CG - { - public Result Cast(CompilerObject @object, IType type) - { - var result = Result.Error( - "Object cannot be cast" - ); - - if (@object is ICTCastTo ctCastTo) - result = ctCastTo.Cast(compiler, type); - - if (result.IsOk) return result; - - if ( - RuntimeDescriptor(@object, out var runtimeDescriptor) - && runtimeDescriptor is IRTCastTo rtCastTo - ) - result = rtCastTo.Cast(compiler, @object, type); - - if (result.IsOk) return result; - - if (type is IRTCastFrom rtCastFrom) - result = rtCastFrom.Cast(compiler, @object); - - if (result.IsOk) return result; - - if (compiler.TypeSystem.IsTyped(@object, out var objectType) && - compiler.TypeSystem.AreEqual(type, objectType) - ) - result = Result.Ok(new() - { - Cast = @object, - }); // TODO: this is actually invalid because calling code expects OnCast to be called on cast - - return result; - } - } -} diff --git a/ZSharp.Compiler/features/cg/services/CG.TypeMatch.cs b/ZSharp.Compiler/features/cg/services/CG.TypeMatch.cs deleted file mode 100644 index d237fc98..00000000 --- a/ZSharp.Compiler/features/cg/services/CG.TypeMatch.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace ZSharp.Compiler -{ - public partial struct CG - { - public Result TypeMatch(CompilerObject @object, IType type) - { - var result = Result.Error( - "Object cannot be type matched" - ); - - if (@object is ICTTypeMatch ctTypeMatch) - result = ctTypeMatch.Match(compiler, type); - - if (result.IsOk) return result; - - if ( - RuntimeDescriptor(@object, out var runtimeDescriptor) - && runtimeDescriptor is IRTTypeMatch rtTypeMatch - ) - result = rtTypeMatch.Match(compiler, @object, type); - - if (result.IsOk) return result; - - return result; - } - } -} diff --git a/ZSharp.Compiler/features/cg/services/CG.ValueAccess.cs b/ZSharp.Compiler/features/cg/services/CG.ValueAccess.cs deleted file mode 100644 index 3b63f816..00000000 --- a/ZSharp.Compiler/features/cg/services/CG.ValueAccess.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace ZSharp.Compiler -{ - public partial struct CG - { - public CompilerObjectResult Get(CompilerObject @object) - { - var result = CompilerObjectResult.Error("Object does not support get"); - - if (@object is ICTGet ctGet) - result = ctGet.Get(compiler); - - if (result.IsOk) return result; - - if (RuntimeDescriptor(@object, out var runtimeDescriptor) - && runtimeDescriptor is IRTGet rtGet - ) - result = rtGet.Get(compiler, @object); - - if (result.IsOk) return result; - - return result; - } - - public CompilerObjectResult Set(CompilerObject @object, CompilerObject value) - { - var result = CompilerObjectResult.Error("Object does not support set"); - - if (@object is ICTSet ctSet) - result = ctSet.Set(compiler, value); - - if (result.IsOk) return result; - - if (RuntimeDescriptor(@object, out var runtimeDescriptor) - && runtimeDescriptor is IRTSet rtSet - ) - result = rtSet.Set(compiler, @object, value); - - if (result.IsOk) return result; - - return result; - } - } -} diff --git a/ZSharp.Compiler/features/ir/IR.cs b/ZSharp.Compiler/features/ir/IR.cs deleted file mode 100644 index ae7325aa..00000000 --- a/ZSharp.Compiler/features/ir/IR.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - public readonly partial struct IR(Compiler compiler) - { - public readonly Compiler compiler = compiler; - } -} diff --git a/ZSharp.Compiler/features/ir/capabilities/code/ICTCompileIRCode.cs b/ZSharp.Compiler/features/ir/capabilities/code/ICTCompileIRCode.cs deleted file mode 100644 index 18e578fc..00000000 --- a/ZSharp.Compiler/features/ir/capabilities/code/ICTCompileIRCode.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICTCompileIRCode - : CompilerObject - { - public Result CompileIRCode(Compiler compiler); - } -} diff --git a/ZSharp.Compiler/features/ir/services/IR.Code.cs b/ZSharp.Compiler/features/ir/services/IR.Code.cs deleted file mode 100644 index 38bdcf42..00000000 --- a/ZSharp.Compiler/features/ir/services/IR.Code.cs +++ /dev/null @@ -1,21 +0,0 @@ -using IRCodeResult = ZSharp.Compiler.Result; - -namespace ZSharp.Compiler -{ - public partial struct IR - { - public IRCodeResult CompileCode(CompilerObject @object) - { - var result = IRCodeResult.Error( - "Object does not support compiling to IR code" - ); - - if (@object is ICTCompileIRCode ctIRCode) - result = ctIRCode.CompileIRCode(compiler); - - if (result.IsOk) return result; - - return result; - } - } -} diff --git a/ZSharp.Compiler/features/ir/services/IR.Definition.cs b/ZSharp.Compiler/features/ir/services/IR.Definition.cs deleted file mode 100644 index d617eacf..00000000 --- a/ZSharp.Compiler/features/ir/services/IR.Definition.cs +++ /dev/null @@ -1,52 +0,0 @@ -using IRDefinitionResult = ZSharp.Compiler.Result; - -namespace ZSharp.Compiler -{ - public partial struct IR - { - public IRDefinitionResult CompileDefinition(CompilerObject @object) - { - ZSharp.IR.IRDefinition? result = null; - - if (@object is ICompileIRObject irObject) - result = irObject.CompileIRObject(compiler); - - if (result is not null) - return IRDefinitionResult.Ok(result); - return IRDefinitionResult.Error( - "Object cannot be compiled to IR definition" - ); - } - - public IRDefinitionResult CompileDefinition(CompilerObject @object, Owner? owner) - where Owner : ZSharp.IR.IRDefinition - { - ZSharp.IR.IRDefinition? result = null; - - if (@object is ICompileIRObject irObject) - result = irObject.CompileIRObject(compiler, owner); - - if (result is not null) - return IRDefinitionResult.Ok(result); - return IRDefinitionResult.Error( - "Object cannot be compiled to IR definition" - ); - } - - public Result CompileDefinition(CompilerObject @object, Owner? owner) - where T : ZSharp.IR.IRDefinition - where Owner : class - { - T? result = null; - - if (@object is ICompileIRObject irObject) - result = irObject.CompileIRObject(compiler, owner); - - if (result is not null) - return Result.Ok(result); - return Result.Error( - "Object cannot be compiled to IR definition" - ); - } - } -} diff --git a/ZSharp.Compiler/features/ir/services/IR.Reference.cs b/ZSharp.Compiler/features/ir/services/IR.Reference.cs deleted file mode 100644 index f491f187..00000000 --- a/ZSharp.Compiler/features/ir/services/IR.Reference.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace ZSharp.Compiler -{ - public partial struct IR - { - public Result CompileReference(CompilerObject @object) - where T : class - { - T? result = null; - - if (@object is ICompileIRReference irReference) - result = irReference.CompileIRReference(compiler); - - if (result is not null) - return Result.Ok(result); - return Result.Error( - "Object cannot be compiled to IR type" - ); - } - } -} diff --git a/ZSharp.Compiler/features/ir/services/IR.Type.cs b/ZSharp.Compiler/features/ir/services/IR.Type.cs deleted file mode 100644 index 7a9244b3..00000000 --- a/ZSharp.Compiler/features/ir/services/IR.Type.cs +++ /dev/null @@ -1,36 +0,0 @@ -using IRTypeResult = ZSharp.Compiler.Result; - -namespace ZSharp.Compiler -{ - public partial struct IR - { - public IRTypeResult CompileType(CompilerObject @object) - { - IRType? result = null; - - if (@object is ICompileIRType irType) - result = irType.CompileIRType(compiler); - - if (result is not null) - return IRTypeResult.Ok(result); - return IRTypeResult.Error( - "Object cannot be compiled to IR type" - ); - } - - public Result CompileType(CompilerObject @object) - where T : class, IRType - { - T? result = null; - - if (@object is ICompileIRType irType) - result = irType.CompileIRType(compiler); - - if (result is not null) - return Result.Ok(result); - return Result.Error( - "Object cannot be compiled to IR type" - ); - } - } -} diff --git a/ZSharp.Compiler/features/oop/extensibility/IClass.cs b/ZSharp.Compiler/features/oop/extensibility/IClass.cs deleted file mode 100644 index c4a95022..00000000 --- a/ZSharp.Compiler/features/oop/extensibility/IClass.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IClass - : CompilerObject - , Compiler.IType - { - public string Name { get; set; } - - public IClass? Base { get; set; } - - public virtual void OnDerivation(IClass derived) { } - } -} diff --git a/ZSharp.Compiler/features/oop/extensibility/IRTBoundMember.cs b/ZSharp.Compiler/features/oop/extensibility/IRTBoundMember.cs deleted file mode 100644 index 61b007ad..00000000 --- a/ZSharp.Compiler/features/oop/extensibility/IRTBoundMember.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IRTBoundMember - { - public CompilerObject Bind(Compiler.Compiler compiler, CompilerObject value); - } -} diff --git a/ZSharp.Compiler/ir generator/IRCodeGenerator.cs b/ZSharp.Compiler/ir generator/IRCodeGenerator.cs deleted file mode 100644 index 6f23b14d..00000000 --- a/ZSharp.Compiler/ir generator/IRCodeGenerator.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - public sealed class IRCodeGenerator - { - // TODO: implement this class - } -} diff --git a/ZSharp.Compiler/ir generator/protocols/ICompileIRCode.cs b/ZSharp.Compiler/ir generator/protocols/ICompileIRCode.cs deleted file mode 100644 index b5c9bb0a..00000000 --- a/ZSharp.Compiler/ir generator/protocols/ICompileIRCode.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICompileIRCode : ICTCompileIRCode - { - Result ICTCompileIRCode.CompileIRCode(Compiler compiler) - => Result.Ok(CompileIRCode(compiler)); - - public new IRCode CompileIRCode(Compiler compiler); - } -} diff --git a/ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs b/ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs deleted file mode 100644 index 8c734533..00000000 --- a/ZSharp.Compiler/ir generator/protocols/ICompileIRObject.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICompileIRObject - { - public ZSharp.IR.IRDefinition CompileIRObject(Compiler compiler); - } - - public interface ICompileIRObject : ICompileIRObject - where Owner : class - { - public ZSharp.IR.IRDefinition CompileIRObject(Compiler compiler, Owner? owner); - - ZSharp.IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler compiler) - => CompileIRObject(compiler, null); - } - - public interface ICompileIRObject : ICompileIRObject - where T : ZSharp.IR.IRDefinition - where Owner : class - { - public new T CompileIRObject(Compiler compiler, Owner? owner); - - ZSharp.IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler compiler, Owner? owner) - => CompileIRObject(compiler, owner); - } -} diff --git a/ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs b/ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs deleted file mode 100644 index daa02ef8..00000000 --- a/ZSharp.Compiler/ir generator/protocols/ICompileIRReference.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICompileIRReference - { - public T CompileIRReference(Compiler compiler); - } -} diff --git a/ZSharp.Compiler/ir generator/protocols/ICompileIRType.cs b/ZSharp.Compiler/ir generator/protocols/ICompileIRType.cs deleted file mode 100644 index b7bc4845..00000000 --- a/ZSharp.Compiler/ir generator/protocols/ICompileIRType.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICompileIRType - { - public IRType CompileIRType(Compiler compiler); - } - - public interface ICompileIRType : ICompileIRType - where T : IRType - { - IRType ICompileIRType.CompileIRType(Compiler compiler) - => CompileIRType(compiler); - - public new T CompileIRType(Compiler compiler); - } -} diff --git a/ZSharp.IR/ir/functional/GenericFunctionInstance.cs b/ZSharp.IR/ir/functional/GenericFunctionInstance.cs index f8cfbd39..1c85e8f2 100644 --- a/ZSharp.IR/ir/functional/GenericFunctionInstance.cs +++ b/ZSharp.IR/ir/functional/GenericFunctionInstance.cs @@ -7,7 +7,7 @@ public sealed class GenericFunctionInstance(Function function) { public Function Function { get; set; } = function; - public Collection Arguments { get; set; } = false ? [] : Collection.Empty; + public Collection Arguments { get; set; } = function.HasGenericParameters ? [] : Collection.Empty; public Signature Signature { get; init; } = function.Signature; diff --git a/ZSharp.IR/ir/oop/constructor/Constructor.cs b/ZSharp.IR/ir/oop/constructor/Constructor.cs index 93b9faa2..7c9891d9 100644 --- a/ZSharp.IR/ir/oop/constructor/Constructor.cs +++ b/ZSharp.IR/ir/oop/constructor/Constructor.cs @@ -1,13 +1,13 @@ -namespace ZSharp.IR -{ - public sealed class Constructor(string? name) - : IRDefinition - , IModuleMember - { - public Module? Module => Method.Module; - - public string? Name { get; set; } = name; - - public Method Method { get; set; } - } -} +namespace ZSharp.IR +{ + public sealed class Constructor(string? name) + : IRDefinition + , IModuleMember + { + public Module? Module => Method.Module; + + public string? Name { get; set; } = name; + + public required Method Method { get; set; } + } +} diff --git a/ZSharp.Interpreter/CTServices.cs b/ZSharp.Interpreter/CTServices.cs index cbe32509..fb59b9ef 100644 --- a/ZSharp.Interpreter/CTServices.cs +++ b/ZSharp.Interpreter/CTServices.cs @@ -4,6 +4,9 @@ public static class CTServices { public static CompilerObject InfoOf(object @object) { + if (@object is CompilerObject co) + return co; + throw new NotImplementedException(); } diff --git a/ZSharp.Interpreter/GlobalUsings.cs b/ZSharp.Interpreter/GlobalUsings.cs new file mode 100644 index 00000000..3511d075 --- /dev/null +++ b/ZSharp.Interpreter/GlobalUsings.cs @@ -0,0 +1 @@ +global using CompilerObject = ZSharp.Compiler.CompilerObject; diff --git a/ZSharp.Interpreter/ZSharp.Interpreter.csproj b/ZSharp.Interpreter/ZSharp.Interpreter.csproj index d7bfa9d5..408b38b5 100644 --- a/ZSharp.Interpreter/ZSharp.Interpreter.csproj +++ b/ZSharp.Interpreter/ZSharp.Interpreter.csproj @@ -7,16 +7,12 @@ - + - - - - diff --git a/ZSharp.Interpreter/interpreter/Interpreter.Logging.cs b/ZSharp.Interpreter/interpreter/Interpreter.Logging.cs new file mode 100644 index 00000000..c461aa45 --- /dev/null +++ b/ZSharp.Interpreter/interpreter/Interpreter.Logging.cs @@ -0,0 +1,9 @@ +using ZSharp.Logging; + +namespace ZSharp.Interpreter +{ + partial class Interpreter + { + public Logger Log => Compiler.Log; + } +} diff --git a/ZSharp.Interpreter/interpreter/Interpreter.cs b/ZSharp.Interpreter/interpreter/Interpreter.cs index 05981929..3fe355fc 100644 --- a/ZSharp.Interpreter/interpreter/Interpreter.cs +++ b/ZSharp.Interpreter/interpreter/Interpreter.cs @@ -1,4 +1,5 @@ -using ZSharp.Compiler; +using System.Runtime.Intrinsics.Arm; +using ZSharp.Compiler; namespace ZSharp.Interpreter { @@ -10,79 +11,69 @@ public sealed partial class Interpreter public Compiler.Compiler Compiler { get; } - public IRCompiler.Compiler IRCompiler { get; } - - public ZSSourceCompiler.ZSSourceCompiler SourceCompiler { get; init; } - - public Parser.ZSharpParser Parser { get; init; } + public Compiler.IR IRCompiler { get; } public Interpreter(IR.RuntimeModule? runtimeModule = null) { RuntimeModule = runtimeModule ?? IR.RuntimeModule.Standard; Compiler = new(RuntimeModule); - Runtime = new(RuntimeModule); + Runtime = new(new() + { + Array = RuntimeModule.TypeSystem.Array, + Boolean = RuntimeModule.TypeSystem.Boolean, + Char = null!, + Float16 = null!, + Float32 = RuntimeModule.TypeSystem.Float32, + Float64 = null!, + Float128 = null!, + Object = RuntimeModule.TypeSystem.Object, + Pointer = RuntimeModule.TypeSystem.Pointer, + Reference = RuntimeModule.TypeSystem.Reference, + SInt8 = null!, + SInt16 = null!, + SInt32 = RuntimeModule.TypeSystem.Int32, + SInt64 = null!, + SIntNative = null!, + String = RuntimeModule.TypeSystem.String, + UInt8 = null!, + UInt16 = null!, + UInt32 = null!, + UInt64 = null!, + UIntNative = null!, + Void = RuntimeModule.TypeSystem.Void + }); IRCompiler = new(RuntimeModule); - ILLoader = new(Compiler); - - new Ops(Compiler); - - SourceCompiler = new(this); - - Parser = new(); - } - - public ZSSourceCompiler.Document CompileFile(string path) - { - AST.Document document; - - using (var reader = new StreamReader(path)) - document = Parser.Parse(new(Tokenizer.Tokenizer.Tokenize(new(reader)))); - - return CompileDocument(document, path); - } - - public ZSSourceCompiler.Document CompileDocument(AST.Document document, string path) - { - return SourceCompiler.CreateDocumentCompiler(document, path).Compile(); - } - - public Result Evaluate(Expression expression) - { - if ( - SourceCompiler.CompileNode(expression) - .When(out var result) - .IsError - ) return Result.Error(string.Empty); + ILLoader = new(Compiler.IR, Runtime); - return Evaluate(result!); + //new Ops(Compiler); } - public Result Evaluate(CompilerObject @object) + public Result Evaluate(CompilerObject @object) { if ( - Compiler.IR.CompileCode(@object) + Compiler.IR.CompileCode(@object, Runtime) .When(out var irCode) .Error(out var error) ) - return Result.Ok(@object); + return Result.Ok(@object); - var type = irCode!.IsVoid ? RuntimeModule.TypeSystem.Void : IRCompiler.CompileType(irCode.RequireValueType()).Unwrap(); + var type = irCode!.IsVoid ? RuntimeModule.TypeSystem.Void : irCode.RequireValueType(); var result = Runtime.Evaluate(irCode.Instructions, type); if (irCode.IsVoid) - return Result - .Ok(new Objects.RawCode(new())); + return Result + .Ok(new Objects.RawIRCode(new())); if (result is null) - return Result + return Result .Ok(@object); // TODO: should actually be an error! //return Result // .Error("Non-void expression evaluated to nothing"); - return Result.Ok(result); + return Result.Ok(result); } } } diff --git a/ZSharp.Interpreter/source-compiler/GlobalUsings.cs b/ZSharp.Interpreter/source-compiler/GlobalUsings.cs deleted file mode 100644 index 959ad0f4..00000000 --- a/ZSharp.Interpreter/source-compiler/GlobalUsings.cs +++ /dev/null @@ -1,15 +0,0 @@ -global using CompilerObject = ZSharp.Objects.CompilerObject; -global using ZSharp.AST; - -global using ObjectResult = - ZSharp.Compiler.Result< - ZSharp.Objects.CompilerObject, - ZSharp.ZSSourceCompiler.Error - >; -global using TypeResult = - ZSharp.Compiler.Result< - ZSharp.Compiler.IType, - ZSharp.ZSSourceCompiler.Error - >; - -global using static ZSharp.ZSSourceCompiler.HelperFunctions; diff --git a/ZSharp.Interpreter/source-compiler/NodeLogOrigin.cs b/ZSharp.Interpreter/source-compiler/NodeLogOrigin.cs deleted file mode 100644 index 66f58290..00000000 --- a/ZSharp.Interpreter/source-compiler/NodeLogOrigin.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ZSharp.ZSSourceCompiler -{ - public sealed class NodeLogOrigin(Node origin) : Compiler.LogOrigin - { - public Node Origin { get; } = origin; - - public override string? ToString() - { - return Origin.TokenInfo?.ToString(); - } - } -} diff --git a/ZSharp.Compiler/compiler core/core/logging/Log.cs b/ZSharp.Logging/Log.cs similarity index 92% rename from ZSharp.Compiler/compiler core/core/logging/Log.cs rename to ZSharp.Logging/Log.cs index 6ee0b315..ba3fab6d 100644 --- a/ZSharp.Compiler/compiler core/core/logging/Log.cs +++ b/ZSharp.Logging/Log.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler +namespace ZSharp.Logging { public readonly struct Log { diff --git a/ZSharp.Compiler/compiler core/core/logging/LogLevel.cs b/ZSharp.Logging/LogLevel.cs similarity index 74% rename from ZSharp.Compiler/compiler core/core/logging/LogLevel.cs rename to ZSharp.Logging/LogLevel.cs index 154dda15..51b029f7 100644 --- a/ZSharp.Compiler/compiler core/core/logging/LogLevel.cs +++ b/ZSharp.Logging/LogLevel.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler +namespace ZSharp.Logging { public enum LogLevel { diff --git a/ZSharp.Compiler/compiler core/core/logging/LogOrigin.cs b/ZSharp.Logging/LogOrigin.cs similarity index 64% rename from ZSharp.Compiler/compiler core/core/logging/LogOrigin.cs rename to ZSharp.Logging/LogOrigin.cs index 8b19d568..0a0fb929 100644 --- a/ZSharp.Compiler/compiler core/core/logging/LogOrigin.cs +++ b/ZSharp.Logging/LogOrigin.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler +namespace ZSharp.Logging { public abstract class LogOrigin { diff --git a/ZSharp.Compiler/compiler core/core/logging/Logger.cs b/ZSharp.Logging/Logger.cs similarity index 52% rename from ZSharp.Compiler/compiler core/core/logging/Logger.cs rename to ZSharp.Logging/Logger.cs index 5f6cd779..813f4054 100644 --- a/ZSharp.Compiler/compiler core/core/logging/Logger.cs +++ b/ZSharp.Logging/Logger.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler +namespace ZSharp.Logging { public sealed class Logger { @@ -17,17 +17,5 @@ public void Warning(T message, LogOrigin origin) public void Error(T message, LogOrigin origin) => Log(new() { Message = message, Level = LogLevel.Error, Origin = origin }); - - public void Info(T message, CompilerObject origin) - => Log(new() { Message = message, Level = LogLevel.Info, Origin = Origin(origin) }); - - public void Warning(T message, CompilerObject origin) - => Log(new() { Message = message, Level = LogLevel.Warning, Origin = Origin(origin) }); - - public void Error(T message, CompilerObject origin) - => Log(new() { Message = message, Level = LogLevel.Error, Origin = Origin(origin) }); - - public LogOrigin Origin(CompilerObject @object) - => new ObjectLogOrigin(@object); } } diff --git a/ZSharp.Logging/ZSharp.Logging.csproj b/ZSharp.Logging/ZSharp.Logging.csproj new file mode 100644 index 00000000..fa71b7ae --- /dev/null +++ b/ZSharp.Logging/ZSharp.Logging.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/ZSharp.Parser/Utils.cs b/ZSharp.Parser/Utils.cs index 5e7d5825..e6ebe66f 100644 --- a/ZSharp.Parser/Utils.cs +++ b/ZSharp.Parser/Utils.cs @@ -10,13 +10,13 @@ public static class Utils public static Parser DefinitionStatement(Parser defParser) where T : Expression => new FunctionalParser( - parser => new ExpressionStatement() { Expression = defParser.Parse(parser) } + parser => new DefinitionStatement() { Definition = defParser.Parse(parser) } ); public static Parser DefinitionStatement(ParserFunction defParser) where T : Expression => new FunctionalParser( - parser => new ExpressionStatement() { Expression = defParser(parser) } + parser => new DefinitionStatement() { Definition = defParser(parser) } ); public static ParserFunction ExpressionStatement(Func fn, bool semicolon = true) diff --git a/ZSharp.Parser/parsers/FunctionParser.cs b/ZSharp.Parser/parsers/FunctionParser.cs index 70218bac..5d2116f7 100644 --- a/ZSharp.Parser/parsers/FunctionParser.cs +++ b/ZSharp.Parser/parsers/FunctionParser.cs @@ -65,7 +65,15 @@ private Statement ParseFunctionBody(Parser parser) using (parser.NewStack(FunctionBody.Content, parser.GetParserFor())) { if (parser.Is(LangParser.Symbols.ThenDo, eat: true)) - return ParseContextItem(parser); + //return ParseContextItem(parser); + { + var result = new Return() + { + Value = parser.Parse() + }; + parser.Eat(TokenType.Semicolon); + return result; + } return LangParser.ParseBlockStatement(parser); } diff --git a/ZSharp.Runtime/GlobalUsings.cs b/ZSharp.Runtime/GlobalUsings.cs index 6012dc4b..65bb20f3 100644 --- a/ZSharp.Runtime/GlobalUsings.cs +++ b/ZSharp.Runtime/GlobalUsings.cs @@ -1 +1,4 @@ global using IL = System.Reflection; + + +global using ExposedObjectHandle = int; diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Code.cs b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Code.cs index 4ff17bea..bfcffb82 100644 --- a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Code.cs +++ b/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Code.cs @@ -9,6 +9,11 @@ partial class EmitLoader public Delegate LoadCode(Collection code, IR.IType irReturnType) { + if (code.Count == 0) return () => { }; + + if (code.Last() is not IR.VM.Return) + code.Add(new IR.VM.Return()); + var ilReturnType = Runtime.ImportType(irReturnType); var method = new Emit.DynamicMethod(string.Empty, ilReturnType, null, StandaloneModule); @@ -16,7 +21,7 @@ public Delegate LoadCode(Collection code, IR.IType irReturnTy codeLoader.CompileCode(code); return - ilReturnType == typeof(void) + ilReturnType != typeof(void) ? method.CreateDelegate( typeof(CodeFunctionType<>) .MakeGenericType(ilReturnType) diff --git a/ZSharp.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs b/ZSharp.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs index 7e3d4774..35508bee 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs +++ b/ZSharp.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs @@ -6,7 +6,7 @@ public static void Compile(ICodeContext ctx, IR.VM.Call call) { var callable = ctx.Runtime.ImportCallable(call.Callable); - foreach (var parameter in call.Callable.Signature.GetParameters()) + foreach (var parameter in call.Callable.Signature.GetParameters().Reverse()) ctx.Stack.Pop(ctx.Runtime.ImportType(parameter.Type)); if (callable is IL.MethodInfo method) diff --git a/ZSharp.Runtime/runtime/Runtime.Expose.cs b/ZSharp.Runtime/runtime/Runtime.Expose.cs new file mode 100644 index 00000000..e0ef3445 --- /dev/null +++ b/ZSharp.Runtime/runtime/Runtime.Expose.cs @@ -0,0 +1,75 @@ +using CommonZ.Utils; +using System.Diagnostics.CodeAnalysis; +using ZSharp.IR; + +namespace ZSharp.Runtime +{ + public sealed partial class Runtime + { + private readonly List _exposedObjects = []; + private readonly Queue _avialableHandles = []; + + private Class ir_runtimeType; + + private Global ir_runtimeInstance; + + private Method ir_getExposedObjectFunction; + + public ExposedObjectHandle CreateHandle(object obj) + { + if (obj is null) + throw new ArgumentNullException(nameof(obj), "Cannot create a handle for a null object."); + + ExposedObjectHandle handle = _exposedObjects.Count; + + if (_avialableHandles.Count > 0) + handle = _avialableHandles.Dequeue(); + else _exposedObjects.Add(null!); + + _exposedObjects[handle] = obj; + + return handle; + } + + public void DestroyHandle(ExposedObjectHandle handle) + { + if (handle < 0 || handle >= _exposedObjects.Count) + throw new ArgumentOutOfRangeException(nameof(handle), "Invalid exposed object handle."); + _exposedObjects[handle] = null!; + _avialableHandles.Enqueue(handle); + } + + public Collection Expose(object? obj) + { + if (obj is null) + return [ + new IR.VM.PutNull() + ]; + + var handle = CreateHandle(obj); + + return [ + new IR.VM.GetGlobal(ir_runtimeInstance), + new IR.VM.PutInt32(handle), + new IR.VM.Call(ir_getExposedObjectFunction), + ]; + } + + public object GetExposedObject(ExposedObjectHandle handle) + => _exposedObjects[handle]!; + + [MemberNotNull(nameof(ir_runtimeType), nameof(ir_getExposedObjectFunction), nameof(ir_runtimeInstance))] + private void SetupExposeSystem() + { + ir_runtimeType = new("Runtime"); + ir_runtimeType.Methods.Add(ir_getExposedObjectFunction = new(TypeSystem.Object)); + ir_getExposedObjectFunction.Signature.Args.Parameters.Add(new("this", new ClassReference(ir_runtimeType))); + ir_getExposedObjectFunction.Signature.Args.Parameters.Add(new("handle", TypeSystem.SInt32)); + ir_runtimeInstance = new("Runtime.Instance", new ClassReference(ir_runtimeType)); + + _typeDefCache[ir_runtimeType] = typeof(Runtime); + _functionCache.Add(ir_getExposedObjectFunction.UnderlyingFunction, ((Delegate)GetExposedObject).Method); + _globalCache[ir_runtimeInstance] = typeof(Runtime).GetField(nameof(_instance)) ?? throw new("Internal error"); + } + } +} diff --git a/ZSharp.Runtime/runtime/Runtime.IR.cs b/ZSharp.Runtime/runtime/Runtime.Singleton.cs similarity index 56% rename from ZSharp.Runtime/runtime/Runtime.IR.cs rename to ZSharp.Runtime/runtime/Runtime.Singleton.cs index e9742429..8b51af54 100644 --- a/ZSharp.Runtime/runtime/Runtime.IR.cs +++ b/ZSharp.Runtime/runtime/Runtime.Singleton.cs @@ -2,6 +2,6 @@ { partial class Runtime { - public IR.RuntimeModule RuntimeModule { get; } + public static Runtime _instance = null!; } } diff --git a/ZSharp.Runtime/runtime/Runtime.TypeSystem.cs b/ZSharp.Runtime/runtime/Runtime.TypeSystem.cs new file mode 100644 index 00000000..83a5f720 --- /dev/null +++ b/ZSharp.Runtime/runtime/Runtime.TypeSystem.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class Runtime + { + public TypeSystem TypeSystem { get; } + } +} diff --git a/ZSharp.Runtime/runtime/Runtime.cs b/ZSharp.Runtime/runtime/Runtime.cs index 544feacf..1d138b4b 100644 --- a/ZSharp.Runtime/runtime/Runtime.cs +++ b/ZSharp.Runtime/runtime/Runtime.cs @@ -2,16 +2,26 @@ { public sealed partial class Runtime { - public Runtime() - : this(IR.RuntimeModule.Standard) + public Runtime(TypeSystem typeSystem) { + if (_instance is not null) + throw new InvalidOperationException("Runtime instance already exists."); + _instance = this; - } + TypeSystem = typeSystem; + + SetupExposeSystem(); - public Runtime(IR.RuntimeModule runtimeModule) - { - RuntimeModule = runtimeModule; Loader = new(this); + + foreach (var (ir, il) in (IEnumerable<(IR.OOPTypeReference, Type)>)[ + (TypeSystem.Void, typeof(void)), + (TypeSystem.Boolean, typeof(bool)), + (TypeSystem.Object, typeof(object)), + (TypeSystem.String, typeof(string)), + (TypeSystem.SInt32, typeof(int)), + ]) + _typeDefCache.Add(ir.Definition, il); } } } diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Global.cs b/ZSharp.Runtime/runtime/import/Runtime.Import.Global.cs index 353b4a82..83238ad1 100644 --- a/ZSharp.Runtime/runtime/import/Runtime.Import.Global.cs +++ b/ZSharp.Runtime/runtime/import/Runtime.Import.Global.cs @@ -6,7 +6,7 @@ public IL.FieldInfo ImportGlobal(IR.Global global) { if (!_globalCache.TryGetValue(global, out var result)) throw new InvalidOperationException( - $"Global {global.Name} in module {global.Owner?.Name ?? ""} is not loaded" + $"Global {global.Name} in module {global.Module?.Name ?? ""} is not loaded" ); return result; diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Type.cs b/ZSharp.Runtime/runtime/import/Runtime.Import.Type.cs index 5f682a5d..484b5de8 100644 --- a/ZSharp.Runtime/runtime/import/Runtime.Import.Type.cs +++ b/ZSharp.Runtime/runtime/import/Runtime.Import.Type.cs @@ -26,13 +26,13 @@ public Type ImportTypeDefinition(IR.OOPType def) public Type ImportTypeReference(IR.OOPTypeReference @ref) { if ( - @ref.Definition == RuntimeModule.TypeSystem.Array + @ref.Definition == TypeSystem.Array ) return ImportArrayType(@ref); if ( - @ref.Definition == RuntimeModule.TypeSystem.Pointer + @ref.Definition == TypeSystem.Pointer ) return ImportPointerType(@ref); if ( - @ref.Definition == RuntimeModule.TypeSystem.Reference + @ref.Definition == TypeSystem.Reference ) return ImportReferenceType(@ref); var type = ImportTypeDefinition(@ref.Definition); diff --git a/ZSharp.Runtime/type system/TypeSystem.Array.cs b/ZSharp.Runtime/type system/TypeSystem.Array.cs new file mode 100644 index 00000000..324f1419 --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.Array.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class TypeSystem + { + public required IR.OOPType Array { get; init; } + } +} diff --git a/ZSharp.Runtime/type system/TypeSystem.Boolean.cs b/ZSharp.Runtime/type system/TypeSystem.Boolean.cs new file mode 100644 index 00000000..8394d743 --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.Boolean.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class TypeSystem + { + public required IR.OOPTypeReference Boolean { get; init; } + } +} diff --git a/ZSharp.Runtime/type system/TypeSystem.Char.cs b/ZSharp.Runtime/type system/TypeSystem.Char.cs new file mode 100644 index 00000000..be77b078 --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.Char.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class TypeSystem + { + public required IR.OOPTypeReference Char { get; init; } + } +} diff --git a/ZSharp.Runtime/type system/TypeSystem.Float.cs b/ZSharp.Runtime/type system/TypeSystem.Float.cs new file mode 100644 index 00000000..41215681 --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.Float.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Runtime +{ + partial class TypeSystem + { + public required IR.OOPTypeReference Float16 { get; init; } + + public required IR.OOPTypeReference Float32 { get; init; } + + public required IR.OOPTypeReference Float64 { get; init; } + + public required IR.OOPTypeReference Float128 { get; init; } + } +} diff --git a/ZSharp.Runtime/type system/TypeSystem.Object.cs b/ZSharp.Runtime/type system/TypeSystem.Object.cs new file mode 100644 index 00000000..f11ea248 --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.Object.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class TypeSystem + { + public required IR.OOPTypeReference Object { get; init; } + } +} diff --git a/ZSharp.Runtime/type system/TypeSystem.Pointer.cs b/ZSharp.Runtime/type system/TypeSystem.Pointer.cs new file mode 100644 index 00000000..5f2ac3db --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.Pointer.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class TypeSystem + { + public required IR.OOPType Pointer { get; init; } + } +} diff --git a/ZSharp.Runtime/type system/TypeSystem.Reference.cs b/ZSharp.Runtime/type system/TypeSystem.Reference.cs new file mode 100644 index 00000000..cf226361 --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.Reference.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class TypeSystem + { + public required IR.OOPType Reference { get; init; } + } +} diff --git a/ZSharp.Runtime/type system/TypeSystem.SInt.cs b/ZSharp.Runtime/type system/TypeSystem.SInt.cs new file mode 100644 index 00000000..d5f0b25a --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.SInt.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Runtime +{ + partial class TypeSystem + { + public required IR.OOPTypeReference SInt8 { get; init; } + + public required IR.OOPTypeReference SInt16 { get; init; } + + public required IR.OOPTypeReference SInt32 { get; init; } + + public required IR.OOPTypeReference SInt64 { get; init; } + + public required IR.OOPTypeReference SIntNative { get; init; } + } +} diff --git a/ZSharp.Runtime/type system/TypeSystem.String.cs b/ZSharp.Runtime/type system/TypeSystem.String.cs new file mode 100644 index 00000000..7fb03b2d --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.String.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class TypeSystem + { + public required IR.OOPTypeReference String { get; init; } + } +} diff --git a/ZSharp.Runtime/type system/TypeSystem.UInt.cs b/ZSharp.Runtime/type system/TypeSystem.UInt.cs new file mode 100644 index 00000000..4ce57841 --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.UInt.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Runtime +{ + partial class TypeSystem + { + public required IR.OOPTypeReference UInt8 { get; init; } + + public required IR.OOPTypeReference UInt16 { get; init; } + + public required IR.OOPTypeReference UInt32 { get; init; } + + public required IR.OOPTypeReference UInt64 { get; init; } + + public required IR.OOPTypeReference UIntNative { get; init; } + } +} diff --git a/ZSharp.Runtime/type system/TypeSystem.Void.cs b/ZSharp.Runtime/type system/TypeSystem.Void.cs new file mode 100644 index 00000000..35ccbccf --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.Void.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + partial class TypeSystem + { + public required IR.OOPTypeReference Void { get; init; } + } +} diff --git a/ZSharp.Runtime/type system/TypeSystem.cs b/ZSharp.Runtime/type system/TypeSystem.cs new file mode 100644 index 00000000..83205d59 --- /dev/null +++ b/ZSharp.Runtime/type system/TypeSystem.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Runtime +{ + public sealed partial class TypeSystem + { + + } +} diff --git a/ZSharp.SourceCompiler.Common/CompileExpression.cs b/ZSharp.SourceCompiler.Common/CompileExpression.cs new file mode 100644 index 00000000..cbdd8ec8 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/CompileExpression.cs @@ -0,0 +1,4 @@ +namespace ZSharp.SourceCompiler +{ + public delegate Result CompileExpression(AST.Expression expression); +} diff --git a/ZSharp.SourceCompiler.Common/GlobalUsings.cs b/ZSharp.SourceCompiler.Common/GlobalUsings.cs new file mode 100644 index 00000000..d78b7439 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/GlobalUsings.cs @@ -0,0 +1,3 @@ +global using ZSharp.Compiler; + +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.SourceCompiler.Common/TaskManager.cs b/ZSharp.SourceCompiler.Common/TaskManager.cs new file mode 100644 index 00000000..a66a4bd8 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/TaskManager.cs @@ -0,0 +1,20 @@ +namespace ZSharp.SourceCompiler +{ + public sealed class TaskManager(Action init) + { + private List thisTasks = [init], nextTasks = []; + + public void AddTask(Action task) + => nextTasks.Add(task); + + public void RunUntilComplete() + { + while (thisTasks.Count > 0) + { + foreach (var task in thisTasks) task(); + (thisTasks, nextTasks) = (nextTasks, thisTasks); + nextTasks.Clear(); + } + } + } +} diff --git a/ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj b/ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj new file mode 100644 index 00000000..0a663848 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs b/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs new file mode 100644 index 00000000..c6d78085 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs @@ -0,0 +1,18 @@ +namespace ZSharp.SourceCompiler +{ + public delegate Result PostProcess(Result result); + + partial class ExpressionCompiler + { + public PostProcess PostProcess { get; init; } = r => r; + + public Result Compile(AST.Expression expression) + => PostProcess(expression switch + { + AST.CallExpression call => Compile(call), + AST.IdentifierExpression identifier => Compile(identifier), + AST.LiteralExpression literal => Compile(literal), + _ => Result.Error($"Invalid expression type: {expression.GetType().Name}"), + }); + } +} diff --git a/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.T.cs b/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.T.cs new file mode 100644 index 00000000..ff8ea125 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + partial class ExpressionCompiler + { + + } +} diff --git a/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.cs b/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.cs new file mode 100644 index 00000000..00d42a42 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + public sealed partial class ExpressionCompiler(Interpreter.Interpreter interpreter) + { + public Interpreter.Interpreter Interpreter { get; } = interpreter; + } +} diff --git a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Call.cs b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Call.cs new file mode 100644 index 00000000..196a8e03 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Call.cs @@ -0,0 +1,45 @@ +namespace ZSharp.SourceCompiler +{ + partial class ExpressionCompiler + { + private Result Compile(AST.CallExpression call) + { + var calleeResult = Compile(call.Callee); + + if ( + calleeResult + .When(out var callee) + .Error(out var errorMessage) + ) return Result.Error( + $"Failed to compile callee: {errorMessage}" + ); + + var argumentResults = call.Arguments + .Select(arg => + { + if ( + Compile(arg.Value) + .When(out var argValue) + .Error(out var error) + ) return Result.Error(error); + + return Result.Ok( + new( + arg.Name, + argValue! + ) + ); + }) + .ToList(); + + if (argumentResults.Any(r => r.IsError)) + return Result.Error( + $"Failed to compile arguments: { + (string.Join(", ", Enumerable.Where>(argumentResults, (Func, bool>)(r => r.IsError)).Select(r => r.Error(out var error) ? error : throw new()))) + }" + ); + + return Interpreter.Compiler.CG.Call(callee!, [.. argumentResults.Select(r => r.Unwrap())]); + } + } +} diff --git a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Identifier.cs b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Identifier.cs new file mode 100644 index 00000000..29bba233 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Identifier.cs @@ -0,0 +1,16 @@ +namespace ZSharp.SourceCompiler +{ + partial class ExpressionCompiler + { + private Result Compile(AST.IdentifierExpression identifier) + { + foreach (var scope in Interpreter.Compiler.CurrentContext.FindContext()) + if (scope.Get(identifier.Name).Ok(out var result)) + return Result.Ok(result); + + return Result.Error( + $"Identifier '{identifier.Name}' not found." + ); + } + } +} diff --git a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs new file mode 100644 index 00000000..8908eec4 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs @@ -0,0 +1,13 @@ +namespace ZSharp.SourceCompiler +{ + partial class ExpressionCompiler + { + private Result Compile(AST.LiteralExpression literal) + { + if (literal.UnitType is not null) + Interpreter.Log.Warning($"Literal has a unit type '{literal.UnitType}' which will be ignored.", new NodeLogOrigin(literal)); + + return new LiteralCompiler().Compile(literal); + } + } +} diff --git a/ZSharp.SourceCompiler.Common/extensions/LoggerExtensions.cs b/ZSharp.SourceCompiler.Common/extensions/LoggerExtensions.cs new file mode 100644 index 00000000..b2577c70 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/extensions/LoggerExtensions.cs @@ -0,0 +1,10 @@ +using ZSharp.Logging; + +namespace ZSharp.SourceCompiler +{ + public static class LoggerExtensions + { + public static void Error(this Logger logger, T message, AST.Node node) + => logger.Error(message, new NodeLogOrigin(node)); + } +} diff --git a/ZSharp.SourceCompiler.Common/importers/CoreLibraryImporter.cs b/ZSharp.SourceCompiler.Common/importers/CoreLibraryImporter.cs new file mode 100644 index 00000000..6380a90a --- /dev/null +++ b/ZSharp.SourceCompiler.Common/importers/CoreLibraryImporter.cs @@ -0,0 +1,19 @@ +namespace ZSharp.SourceCompiler +{ + public sealed class CoreLibraryImporter + : IStringImporter + { + private readonly Dictionary libraries = []; + + public void Add(string name, CompilerObject obj) + => libraries.Add(name, obj); + + Result IStringImporter.Import(string source) + { + if (libraries.TryGetValue(source, out var result)) + return Result.Ok(result); + + return Result.Error($"Could not find core library '{source}'"); + } + } +} diff --git a/ZSharp.SourceCompiler.Common/importers/StandardLibraryImporter.cs b/ZSharp.SourceCompiler.Common/importers/StandardLibraryImporter.cs new file mode 100644 index 00000000..efd8f674 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/importers/StandardLibraryImporter.cs @@ -0,0 +1,19 @@ +namespace ZSharp.SourceCompiler +{ + public sealed class StandardLibraryImporter + : IStringImporter + { + private readonly Dictionary libraries = []; + + public void Add(string name, CompilerObject obj) + => libraries.Add(name, obj); + + Result IStringImporter.Import(string source) + { + if (libraries.TryGetValue(source, out var result)) + return Result.Ok(result); + + return Result.Error($"Could not find standard library '{source}'"); + } + } +} diff --git a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.Boolean.cs b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.Boolean.cs new file mode 100644 index 00000000..ae8344ed --- /dev/null +++ b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.Boolean.cs @@ -0,0 +1,11 @@ +namespace ZSharp.SourceCompiler +{ + partial class LiteralCompiler + { + private Result CompileFalse(AST.LiteralExpression expression) + => Result.Ok(new BooleanLiteral(false)); + + private Result CompileTrue(AST.LiteralExpression expression) + => Result.Ok(new BooleanLiteral(true)); + } +} diff --git a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs new file mode 100644 index 00000000..66d6ddf8 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs @@ -0,0 +1,10 @@ +namespace ZSharp.SourceCompiler +{ + partial class LiteralCompiler + { + private Result CompileString(AST.LiteralExpression expression) + { + return Result.Ok(new StringLiteral(expression.Value)); + } + } +} diff --git a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.cs b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.cs new file mode 100644 index 00000000..e17aedd1 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.cs @@ -0,0 +1,20 @@ +namespace ZSharp.SourceCompiler +{ + partial class LiteralCompiler + { + public Result Compile(AST.LiteralExpression expression) + => expression.Type switch + { + AST.LiteralType.String => CompileString(expression), + AST.LiteralType.Number => NotImplemented(expression), + AST.LiteralType.Decimal => NotImplemented(expression), + AST.LiteralType.Null => NotImplemented(expression), + AST.LiteralType.True => CompileTrue(expression), + AST.LiteralType.False => CompileFalse(expression), + _ => Result.Error($"Invalid literal type: {expression.Type}"), + }; + + private Result NotImplemented(AST.LiteralExpression expression) + => Result.Error($"Literal type not implemented: {expression.Type}"); + } +} diff --git a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.T.cs b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.T.cs new file mode 100644 index 00000000..82076324 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + partial class LiteralCompiler + { + + } +} diff --git a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.cs b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.cs new file mode 100644 index 00000000..dbe7444c --- /dev/null +++ b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + public sealed partial class LiteralCompiler + { + + } +} diff --git a/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.Content.cs b/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.Content.cs new file mode 100644 index 00000000..7a813844 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.Content.cs @@ -0,0 +1,9 @@ +using CommonZ.Utils; + +namespace ZSharp.SourceCompiler +{ + partial class CodeBlock + { + public Collection Content { get; } = []; + } +} diff --git a/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs b/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs new file mode 100644 index 00000000..fd01e5aa --- /dev/null +++ b/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + partial class CodeBlock + { + + } +} diff --git a/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.cs b/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.cs new file mode 100644 index 00000000..3583e87d --- /dev/null +++ b/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + public sealed partial class CodeBlock + : CompilerObject + { + } +} diff --git a/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs b/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs new file mode 100644 index 00000000..c09814d0 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs @@ -0,0 +1,16 @@ +namespace ZSharp.SourceCompiler +{ + partial class BooleanLiteral + : ICompileIRCode + { + Result ICompileIRCode.CompileIRCode(Compiler.IR ir, object? target) + => Result.Ok( + new([ + new IR.VM.PutBoolean(value) + ]) + { + Types = [ir.RuntimeModule.TypeSystem.Boolean] + } + ); + } +} diff --git a/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.cs b/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.cs new file mode 100644 index 00000000..00790db3 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.cs @@ -0,0 +1,8 @@ +namespace ZSharp.SourceCompiler +{ + internal sealed partial class BooleanLiteral(bool value) + : CompilerObject + { + private readonly bool value = value; + } +} diff --git a/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs b/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs new file mode 100644 index 00000000..1bc51ac4 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs @@ -0,0 +1,16 @@ +namespace ZSharp.SourceCompiler +{ + partial class StringLiteral + : ICompileIRCode + { + Result ICompileIRCode.CompileIRCode(Compiler.IR ir, object? target) + => Result.Ok( + new([ + new IR.VM.PutString(value) + ]) + { + Types = [ir.RuntimeModule.TypeSystem.String] + } + ); + } +} diff --git a/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.cs b/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.cs new file mode 100644 index 00000000..529a2471 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.cs @@ -0,0 +1,8 @@ +namespace ZSharp.SourceCompiler +{ + internal sealed partial class StringLiteral(string value) + : CompilerObject + { + private readonly string value = value; + } +} diff --git a/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs b/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs new file mode 100644 index 00000000..4ef0a24c --- /dev/null +++ b/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs @@ -0,0 +1,32 @@ +namespace ZSharp.SourceCompiler +{ + public sealed class TopLevelExpressionCompiler(Interpreter.Interpreter interpreter) + { + public Interpreter.Interpreter Interpreter { get; } = interpreter; + + public Func CompileExpression { get; init; } = new ExpressionCompiler(interpreter).Compile; + + public Func LoadCO { get; init; } = @object => Result.Ok(ZSharp.Interpreter.CTServices.InfoOf(@object!)); + + public Result Compile(AST.Expression expression) + { + var compileResult = CompileExpression(expression); + + if ( + compileResult + .When(out var co) + .IsError + ) return compileResult; + + var evaluateResult = Interpreter.Evaluate(co!); + + if ( + evaluateResult + .When(out var value) + .Error(out var error) + ) return Result.Error(error); + + return LoadCO(value); + } + } +} diff --git a/ZSharp.SourceCompiler.Core/NodeLogOrigin.cs b/ZSharp.SourceCompiler.Core/NodeLogOrigin.cs new file mode 100644 index 00000000..75ad82b8 --- /dev/null +++ b/ZSharp.SourceCompiler.Core/NodeLogOrigin.cs @@ -0,0 +1,12 @@ +namespace ZSharp.SourceCompiler +{ + public sealed class NodeLogOrigin(AST.Node origin) : Logging.LogOrigin + { + public AST.Node Origin { get; } = origin; + + public override string? ToString() + { + return Origin.TokenInfo?.ToString(); + } + } +} diff --git a/ZSharp.SourceCompiler.Core/ZSharp.SourceCompiler.Core.csproj b/ZSharp.SourceCompiler.Core/ZSharp.SourceCompiler.Core.csproj new file mode 100644 index 00000000..13363715 --- /dev/null +++ b/ZSharp.SourceCompiler.Core/ZSharp.SourceCompiler.Core.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + ZSharp.SourceCompiler + + + + + + + + diff --git a/ZSharp.SourceCompiler.Core/context/Context.ImportSystem.cs b/ZSharp.SourceCompiler.Core/context/Context.ImportSystem.cs new file mode 100644 index 00000000..26733d0d --- /dev/null +++ b/ZSharp.SourceCompiler.Core/context/Context.ImportSystem.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + partial class Context + { + public ImportSystem ImportSystem { get; init; } = new(); + } +} diff --git a/ZSharp.SourceCompiler.Core/context/Context.Operators.cs b/ZSharp.SourceCompiler.Core/context/Context.Operators.cs new file mode 100644 index 00000000..92793869 --- /dev/null +++ b/ZSharp.SourceCompiler.Core/context/Context.Operators.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + partial class Context + { + public OperatorTable Operators { get; init; } = new(); + } +} diff --git a/ZSharp.SourceCompiler.Core/context/Context.T.cs b/ZSharp.SourceCompiler.Core/context/Context.T.cs new file mode 100644 index 00000000..e7ab9d35 --- /dev/null +++ b/ZSharp.SourceCompiler.Core/context/Context.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + partial class Context + { + + } +} diff --git a/ZSharp.SourceCompiler.Core/context/Context.cs b/ZSharp.SourceCompiler.Core/context/Context.cs new file mode 100644 index 00000000..2e32d7bf --- /dev/null +++ b/ZSharp.SourceCompiler.Core/context/Context.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + public sealed partial class Context + { + + } +} diff --git a/ZSharp.SourceCompiler.Core/custom importer/string importer/IStringImporter.cs b/ZSharp.SourceCompiler.Core/custom importer/string importer/IStringImporter.cs new file mode 100644 index 00000000..00d7ea58 --- /dev/null +++ b/ZSharp.SourceCompiler.Core/custom importer/string importer/IStringImporter.cs @@ -0,0 +1,10 @@ +using ZSharp.Compiler; +using ZSharp.Objects; + +namespace ZSharp.SourceCompiler +{ + public interface IStringImporter + { + public Result Import(string source); + } +} diff --git a/ZSharp.SourceCompiler.Core/custom importer/string importer/StringImporter.cs b/ZSharp.SourceCompiler.Core/custom importer/string importer/StringImporter.cs new file mode 100644 index 00000000..9ed17139 --- /dev/null +++ b/ZSharp.SourceCompiler.Core/custom importer/string importer/StringImporter.cs @@ -0,0 +1,48 @@ +using CommonZ.Utils; +using ZSharp.Compiler; +using ZSharp.Objects; + +namespace ZSharp.SourceCompiler +{ + public sealed class StringImporter + : IStringImporter + { + private readonly Mapping customStringImporters = []; + + public IStringImporter? DefaultImporter { get; set; } + + public Result Import(string source) + { + var parts = source.Split(':', count: 2, options: StringSplitOptions.TrimEntries); + if (parts.Length > 1) + { + if (!customStringImporters.TryGetValue(parts[0], out var importer)) + return Result.Error( + $"No string importer registered for prefix '{parts[0]}'." + ); + + return importer.Import(parts[1]); + } + + if (parts.Length == 0) + return Result.Error("Source string is empty."); + + if (DefaultImporter is null) + return Result.Error("No default string importer is set."); + + if (DefaultImporter == this) + return Result.Error("Default string importer cannot be itself."); + + return DefaultImporter.Import(parts[0]); + } + + public void RegisterImporter(string prefix, IStringImporter importer) + { + if (string.IsNullOrWhiteSpace(prefix)) + throw new ArgumentException("Prefix cannot be null or whitespace.", nameof(prefix)); + if (importer is null) + throw new ArgumentNullException(nameof(importer), "Importer cannot be null."); + customStringImporters[prefix] = importer; + } + } +} diff --git a/ZSharp.SourceCompiler.Core/import system/ImportSystem.cs b/ZSharp.SourceCompiler.Core/import system/ImportSystem.cs new file mode 100644 index 00000000..9f66eb77 --- /dev/null +++ b/ZSharp.SourceCompiler.Core/import system/ImportSystem.cs @@ -0,0 +1,9 @@ +using ZSharp.Compiler; + +namespace ZSharp.SourceCompiler +{ + public sealed class ImportSystem + { + public CompilerObject? ImportFunction { get; set; } + } +} diff --git a/ZSharp.SourceCompiler.Core/operator table/OperatorTable.cs b/ZSharp.SourceCompiler.Core/operator table/OperatorTable.cs new file mode 100644 index 00000000..6fb38ca2 --- /dev/null +++ b/ZSharp.SourceCompiler.Core/operator table/OperatorTable.cs @@ -0,0 +1,34 @@ +global using Operator = string; + +using CommonZ.Utils; +using System.Diagnostics.CodeAnalysis; + +using CompilerObject = ZSharp.Compiler.CompilerObject; + +namespace ZSharp.SourceCompiler +{ + public sealed class OperatorTable() + { + private readonly Cache operators = new(); + + internal OperatorTable(OperatorTable? parent = null) + : this() + { + operators = new() + { + Parent = parent?.operators + }; + } + + public void Op(Operator op, CompilerObject obj) + => operators.Cache(op, obj); // TODO: on add + + public CompilerObject? Op(Operator op) + => operators.Cache(op); + + public bool Op(Operator op, [NotNullWhen(true)] out CompilerObject? obj) + => (obj = Op(op)) is not null; + + public OperatorTable CreateChild() => new(this); + } +} diff --git a/ZSharp.SourceCompiler.Module/GlobalUsings.cs b/ZSharp.SourceCompiler.Module/GlobalUsings.cs new file mode 100644 index 00000000..d78b7439 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/GlobalUsings.cs @@ -0,0 +1,3 @@ +global using ZSharp.Compiler; + +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj b/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj new file mode 100644 index 00000000..83130b4f --- /dev/null +++ b/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj @@ -0,0 +1,31 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ZSharp.SourceCompiler.Module/capabilities/IModuleMember.cs b/ZSharp.SourceCompiler.Module/capabilities/IModuleMember.cs new file mode 100644 index 00000000..d1f6de54 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/capabilities/IModuleMember.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module +{ + public interface IModuleMember + { + public CompilerObject Module { get; } + } +} diff --git a/ZSharp.SourceCompiler.Module/capabilities/functional/IParameter.cs b/ZSharp.SourceCompiler.Module/capabilities/functional/IParameter.cs new file mode 100644 index 00000000..a94b479a --- /dev/null +++ b/ZSharp.SourceCompiler.Module/capabilities/functional/IParameter.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module +{ + public interface IParameter + { + + } +} diff --git a/ZSharp.SourceCompiler.Module/capabilities/functional/ISignature.cs b/ZSharp.SourceCompiler.Module/capabilities/functional/ISignature.cs new file mode 100644 index 00000000..f604d198 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/capabilities/functional/ISignature.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZSharp.SourceCompiler.Module +{ + internal interface ISignature + { + } +} diff --git a/ZSharp.SourceCompiler.Module/contexts/modular/FunctionContext.cs b/ZSharp.SourceCompiler.Module/contexts/modular/FunctionContext.cs new file mode 100644 index 00000000..11433591 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/contexts/modular/FunctionContext.cs @@ -0,0 +1,11 @@ +namespace ZSharp.SourceCompiler.Module.Contexts +{ + internal sealed class FunctionContext(Objects.Function function) + : IContext + , IObjectContext + { + public IContext? Parent { get; set; } + + public Objects.Function Object { get; } = function; + } +} diff --git a/ZSharp.SourceCompiler.Module/contexts/modular/ModuleContext.cs b/ZSharp.SourceCompiler.Module/contexts/modular/ModuleContext.cs new file mode 100644 index 00000000..31c45f88 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/contexts/modular/ModuleContext.cs @@ -0,0 +1,6 @@ +namespace ZSharp.SourceCompiler.Module.Contexts +{ + internal sealed class ModuleContext + { + } +} diff --git a/ZSharp.SourceCompiler.Module/function body compiler/FunctionBodyCompiler.T.cs b/ZSharp.SourceCompiler.Module/function body compiler/FunctionBodyCompiler.T.cs new file mode 100644 index 00000000..01c990dd --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function body compiler/FunctionBodyCompiler.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class FunctionBodyCompiler + { + + } +} diff --git a/ZSharp.SourceCompiler.Module/function body compiler/FunctionBodyCompiler.cs b/ZSharp.SourceCompiler.Module/function body compiler/FunctionBodyCompiler.cs new file mode 100644 index 00000000..35207b07 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function body compiler/FunctionBodyCompiler.cs @@ -0,0 +1,19 @@ +namespace ZSharp.SourceCompiler.Module +{ + internal sealed partial class FunctionBodyCompiler + { + private Interpreter.Interpreter Interpreter { get; } + + private AST.Statement Node { get; } + + private CompileExpression CompileExpression { get; } + + public FunctionBodyCompiler(Interpreter.Interpreter interpreter, AST.Statement body) + { + Interpreter = interpreter; + Node = body; + + CompileExpression = new ExpressionCompiler(interpreter).Compile; + } + } +} diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/FunctionBodyCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/FunctionBodyCompiler.Compile.cs new file mode 100644 index 00000000..fd9fe28f --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/FunctionBodyCompiler.Compile.cs @@ -0,0 +1,8 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class FunctionBodyCompiler + { + public Result Compile() + => Compile(Node); + } +} diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.Function.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.Function.cs new file mode 100644 index 00000000..197b3665 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.Function.cs @@ -0,0 +1,16 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class FunctionBodyCompiler + { + private Result Compile(AST.Function function) + { + var compiler = new FunctionCompiler(Interpreter, function); + + var result = compiler.Declare(); + compiler.CompileSignature(); + compiler.CompileBody(); + + return result; + } + } +} diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.cs new file mode 100644 index 00000000..72c952d0 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.cs @@ -0,0 +1,12 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class FunctionBodyCompiler + { + private Result Compile(AST.Expression expression) + => expression switch + { + AST.Function function => Compile(function), + _ => CompileExpression(expression), + }; + } +} diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Block.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Block.cs new file mode 100644 index 00000000..0d977ab6 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Block.cs @@ -0,0 +1,17 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class FunctionBodyCompiler + { + private Result Compile(AST.BlockStatement block) + { + var result = new CodeBlock(); + + foreach (var statement in block.Statements ?? []) + if (Compile(statement).When(out var @object).Error(out var error)) + Interpreter.Log.Error($"{error}", statement); + else result.Content.Add(@object!); + + return Result.Ok(result); + } + } +} diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Definition.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Definition.cs new file mode 100644 index 00000000..122d6b23 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Definition.cs @@ -0,0 +1,8 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class FunctionBodyCompiler + { + private Result Compile(AST.DefinitionStatement definitionStatement) + => Compile(definitionStatement.Definition); + } +} diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Expression.cs new file mode 100644 index 00000000..a52451b7 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Expression.cs @@ -0,0 +1,8 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class FunctionBodyCompiler + { + private Result Compile(AST.ExpressionStatement expressionStatement) + => CompileExpression(expressionStatement.Expression); + } +} diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs new file mode 100644 index 00000000..c022b45d --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs @@ -0,0 +1,14 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class FunctionBodyCompiler + { + private Result Compile(AST.Statement statement) + => statement switch + { + AST.BlockStatement block => Compile(block), + AST.ExpressionStatement expression => Compile(expression), + AST.DefinitionStatement definition => Compile(definition), + _ => Result.Error($"Unknown statement type: {statement.GetType().Name}"), + }; + } +} diff --git a/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs new file mode 100644 index 00000000..64f2b0a9 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs @@ -0,0 +1,63 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class FunctionCompiler + { + public Result Declare() + { + Error? error = null; + + if (Object.Name != string.Empty) + if (!Interpreter + .Compiler + .CurrentContext + .PerformOperation( + scope => !scope.Add(Object.Name, Object).Error(out error) + ) + ) + return Result.Error($"Could not bind function {Node.Name}: {error}"); + + return Result.Ok(Object); + } + + public void CompileSignature() + { + if (Node.ReturnType is null) + Interpreter.Log.Error($"Function {Node.Name} must have a return type.", Node); + + if (Node.Signature.VarArgs is not null) + Interpreter.Log.Error("VarArgs functions are obsolete and should not be used.", Node.Signature.VarArgs); + if (Node.Signature.VarKwArgs is not null) + Interpreter.Log.Error("VarKwArgs functions are obsolete and should not be used.", Node.Signature.VarKwArgs); + + foreach (var param in Node.Signature.Args ?? []) + if (Compile(param).When(out var co).Error(out var error)) + Interpreter.Log.Error(error.ToString()!, param); + //else result.Signature.Args.Add(co!); + + foreach (var param in Node.Signature.KwArgs ?? []) + if (Compile(param).When(out var co).Error(out var error)) + Interpreter.Log.Error(error.ToString()!, param); + //else result.Signature.KwArgs.Add(co!); + } + + public void CompileBody() + { + if (Node.Body is null) + return; + + if ( + new FunctionBodyCompiler(Interpreter, Node.Body).Compile() + .When(out var body) + .Error(out var error) + ) + Interpreter.Log.Error(error.ToString()!, Node.Body); + else + Object.Body = body; + } + + private Result Compile(AST.Parameter parameter) + { + return Result.Error($"Parameter {parameter.Name} did not compile because parameter compilation is not implemented."); + } + } +} diff --git a/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.T.cs b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.T.cs new file mode 100644 index 00000000..e4952955 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class FunctionCompiler + { + + } +} diff --git a/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.cs b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.cs new file mode 100644 index 00000000..1fec9c91 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.cs @@ -0,0 +1,25 @@ +namespace ZSharp.SourceCompiler.Module +{ + internal sealed partial class FunctionCompiler + { + private Interpreter.Interpreter Interpreter { get; } + + private AST.Function Node { get; } + + private Objects.Function Object { get; } + + private CompileExpression CompileExpression { get; } + + public FunctionCompiler(Interpreter.Interpreter interpreter, AST.Function function) + { + Interpreter = interpreter; + Node = function; + Object = new() + { + Name = function.Name, + }; + + CompileExpression = new ExpressionCompiler(interpreter).Compile; + } + } +} diff --git a/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.Log.cs b/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.Log.cs new file mode 100644 index 00000000..4d97a4ea --- /dev/null +++ b/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.Log.cs @@ -0,0 +1,18 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ModuleCompiler + { + private readonly List> logs = []; + + public void Error(string message, Logging.LogOrigin origin) + => logs.Add(new() + { + Level = Logging.LogLevel.Error, + Message = message, + Origin = origin + }); + + public void Error(string message, AST.Node node) + => Error(message, new NodeLogOrigin(node)); + } +} diff --git a/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.T.cs b/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.T.cs new file mode 100644 index 00000000..d44f86f6 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ModuleCompiler + { + + } +} diff --git a/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.Tasks.cs b/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.Tasks.cs new file mode 100644 index 00000000..9696929b --- /dev/null +++ b/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.Tasks.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ModuleCompiler + { + private readonly TaskManager tasks; + } +} diff --git a/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.cs b/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.cs new file mode 100644 index 00000000..e52804cd --- /dev/null +++ b/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.cs @@ -0,0 +1,24 @@ +namespace ZSharp.SourceCompiler.Module +{ + public sealed partial class ModuleCompiler + { + private Objects.Module Object { get; } + + private Interpreter.Interpreter Interpreter { get; } + + private AST.Module Node { get; } + + private CompileExpression CompileExpression { get; } + + public ModuleCompiler(Interpreter.Interpreter interpreter, AST.Module module) + { + Interpreter = interpreter; + Node = module; + Object = new(); + + CompileExpression = new TopLevelExpressionCompiler(interpreter).Compile; + + tasks = new(InitCompile); + } + } +} diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/ModuleCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/ModuleCompiler.Compile.cs new file mode 100644 index 00000000..fc60b1fa --- /dev/null +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/ModuleCompiler.Compile.cs @@ -0,0 +1,43 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ModuleCompiler + { + public Result Compile() + { + tasks.RunUntilComplete(); + + if (logs.Count > 0) + { + // TODO: Aggregate errors properly + + var sb = new System.Text.StringBuilder(); + + foreach (var log in logs) + sb.AppendLine(log.ToString()); + + return Result.Error(sb.ToString()); + } + + + return Result.Ok(Object); + } + + private void InitCompile() + { + foreach (var statement in Node.Body) + if (Compile(statement).Error(out var error)) + Error( + $"Failed to compile statement: {error}", + new NodeLogOrigin(statement) + ); + } + + private Result Compile(AST.Statement statement) + => statement switch + { + AST.DefinitionStatement definitionStatement => Compile(definitionStatement), + AST.ExpressionStatement expressionStatement => Compile(expressionStatement), + _ => Result.Error($"Unknown statement type: {statement.GetType().Name}") + }; + } +} diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Call.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Call.cs new file mode 100644 index 00000000..c61fedda --- /dev/null +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Call.cs @@ -0,0 +1,45 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ModuleCompiler + { + private Result Compile(AST.CallExpression call) + { + var calleeResult = Compile(call.Callee); + + if ( + calleeResult + .When(out var callee) + .Error(out var errorMessage) + ) return Result.Error( + $"Failed to compile callee: {errorMessage}" + ); + + var argumentResults = call.Arguments + .Select(arg => + { + if ( + Compile(arg.Value) + .When(out var argValue) + .Error(out var error) + ) return Result.Error(error); + + return Result.Ok( + new( + arg.Name, + argValue! + ) + ); + }) + .ToList(); + + if (argumentResults.Any(r => r.IsError)) + return Result.Error( + $"Failed to compile arguments: { + (string.Join(", ", Enumerable.Where>(argumentResults, (Func, bool>)(r => r.IsError)).Select(r => r.Error(out var error) ? error : throw new()))) + }" + ); + + return Interpreter.Compiler.CG.Call(callee!, [.. argumentResults.Select(r => r.Unwrap())]); + } + } +} diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Expression.cs new file mode 100644 index 00000000..50c7819f --- /dev/null +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Expression.cs @@ -0,0 +1,12 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ModuleCompiler + { + private Result Compile(AST.Expression expression) + => expression switch + { + AST.Function function => Compile(function), + _ => CompileExpression(expression) + }; + } +} diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Function.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Function.cs new file mode 100644 index 00000000..db4e4152 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Function.cs @@ -0,0 +1,24 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ModuleCompiler + { + private Result Compile(AST.Function function) + { + var compiler = new FunctionCompiler(Interpreter, function); + + var result = compiler.Declare(); + + tasks.AddTask(() => + { + compiler.CompileSignature(); + + tasks.AddTask(() => + { + compiler.CompileBody(); + }); + }); + + return result; + } + } +} diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Definition.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Definition.cs new file mode 100644 index 00000000..bc33688a --- /dev/null +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Definition.cs @@ -0,0 +1,12 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ModuleCompiler + { + private Result Compile(AST.DefinitionStatement definitionStatement) + => definitionStatement.Definition switch + { + AST.Function function => Compile(function), + _ => Result.Error($"Unknown definition type: {definitionStatement.Definition.GetType().Name}") + }; + } +} diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs new file mode 100644 index 00000000..eadc1c5c --- /dev/null +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs @@ -0,0 +1,8 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ModuleCompiler + { + private Result Compile(AST.ExpressionStatement expressionStatement) + => CompileExpression(expressionStatement.Expression); + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Build.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Build.cs new file mode 100644 index 00000000..f99ea667 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Build.cs @@ -0,0 +1,18 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Function + { + [Flags] + private enum BuildState + { + + } + + private readonly ObjectBuildState state = new(); + + [MemberNotNullWhen(true, nameof(IR))] + public bool IsBuilt => IR is not null; + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs new file mode 100644 index 00000000..12e0523b --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs @@ -0,0 +1,11 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Function + : ICTCallable + { + Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs new file mode 100644 index 00000000..0b2e91f6 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Function + { + public IR.Function? IR { get; private set; } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.ModuleMember.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.ModuleMember.cs new file mode 100644 index 00000000..0b4f6c10 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.ModuleMember.cs @@ -0,0 +1,10 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Function + : IModuleMember + { + public Module Module { get; internal set; } + + CompilerObject IModuleMember.Module => Module; + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Name.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Name.cs new file mode 100644 index 00000000..19f70d37 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Name.cs @@ -0,0 +1,18 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Function + { + public string _name; + + public string Name + { + get => _name; + set + { + if (IsBuilt) throw new InvalidOperationException("Cannot change name after the function object is built."); + if (value is null) throw new ArgumentNullException(nameof(value), "Name cannot be null."); + _name = value; + } + } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.T.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.T.cs new file mode 100644 index 00000000..8d820eae --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Function + { + + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.cs new file mode 100644 index 00000000..ba6e1fde --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.cs @@ -0,0 +1,8 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + internal sealed partial class Function + : CompilerObject + { + public CompilerObject? Body { get; set; } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.Build.cs b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.Build.cs new file mode 100644 index 00000000..52b65d52 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.Build.cs @@ -0,0 +1,19 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Global + { + [Flags] + private enum BuildState + { + Owner = 1 << 0, + + } + + private readonly ObjectBuildState state = new(); + + [MemberNotNullWhen(true, nameof(IR))] + public bool IsBuilt => IR is not null; + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs new file mode 100644 index 00000000..a0bd6b7d --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs @@ -0,0 +1,46 @@ + +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Global + : ICompileIRDefinitionAs + , ICompileIRDefinitionIn + { + public IR.Global? IR { get; private set; } + + Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.IR ir, object? target) + { + if (IR is null) + { + var typeResult = ir.CompileType(Type); + + if ( + typeResult + .When(out var type) + .IsError + ) return typeResult.When(_ => null!); + + IR = new(Name, type!); + } + + + + return Result.Ok(IR); + } + + void ICompileIRDefinitionIn.CompileIRDefinition(Compiler.IR ir, IR.Module owner, object? target) + { + var result = ir.CompileDefinition(this, target); + + if (result.IsError) return; + + if (!state[BuildState.Owner]) + { + owner.Globals.Add(IR!); + + state.Set(BuildState.Owner); + } + } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.ModuleMember.cs b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.ModuleMember.cs new file mode 100644 index 00000000..46e3395f --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.ModuleMember.cs @@ -0,0 +1,11 @@ + +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Global + : IModuleMember + { + public Module Module { get; internal set; } + + CompilerObject IModuleMember.Module => Module; + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.Name.cs b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.Name.cs new file mode 100644 index 00000000..efa2835b --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.Name.cs @@ -0,0 +1,20 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Global + { + private string _name; + + public string Name + { + get => _name; + set + { + if (IsBuilt) throw new InvalidOperationException("Cannot change name after the global object is built."); + + if (value is null) throw new ArgumentNullException(nameof(value), "Name cannot be null."); + + _name = value; + } + } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.T.cs b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.T.cs new file mode 100644 index 00000000..a9c753e2 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Global + { + + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.Type.cs b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.Type.cs new file mode 100644 index 00000000..6bbf2e03 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.Type.cs @@ -0,0 +1,20 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Global + : ITyped + { + private CompilerObject _type; + + public CompilerObject Type + { + get => _type; + set { + if (IsBuilt) throw new InvalidOperationException("Cannot change type after the global object is built."); + + if (value is null) throw new ArgumentNullException(nameof(value), "Type cannot be null."); + + _type = value; + } + } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.cs b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.cs new file mode 100644 index 00000000..efff0c61 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + internal sealed partial class Global + : CompilerObject + { + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Build.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Build.cs new file mode 100644 index 00000000..dec25d8c --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Build.cs @@ -0,0 +1,18 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Module + { + [Flags] + private enum BuildState + { + + } + + private readonly ObjectBuildState state = new(); + + [MemberNotNullWhen(true, nameof(IR))] + public bool IsBuilt => IR is not null; + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs new file mode 100644 index 00000000..127159f3 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Module + { + public IR.Module? IR { get; private set; } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Name.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Name.cs new file mode 100644 index 00000000..a34d5d21 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Name.cs @@ -0,0 +1,17 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Module + { + private string _name; + + public string Name { + get => _name; + set + { + if (IsBuilt) throw new InvalidOperationException("Cannot change name after the module object is built."); + if (value is null) throw new ArgumentNullException(nameof(value), "Name cannot be null."); + _name = value; + } + } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.T.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.T.cs new file mode 100644 index 00000000..a1eed453 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Module + { + + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.cs new file mode 100644 index 00000000..7eccbac4 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.cs @@ -0,0 +1,8 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + internal sealed partial class Module + : CompilerObject + { + + } +} diff --git a/ZSharp.SourceCompiler.Module/old/GlobalUsings.cs b/ZSharp.SourceCompiler.Module/old/GlobalUsings.cs new file mode 100644 index 00000000..5840b125 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/old/GlobalUsings.cs @@ -0,0 +1,15 @@ +//global using CompilerObject = ZSharp.Objects.CompilerObject; +//global using ZSharp.AST; + +//global using ObjectResult = +// ZSharp.Compiler.Result< +// ZSharp.Objects.CompilerObject, +// ZSharp.ZSSourceCompiler.Error +// >; +//global using TypeResult = +// ZSharp.Compiler.Result< +// ZSharp.Compiler.IType, +// ZSharp.ZSSourceCompiler.Error +// >; + +//global using static ZSharp.ZSSourceCompiler.HelperFunctions; diff --git a/ZSharp.Interpreter/source-compiler/HelperFunctions.cs b/ZSharp.SourceCompiler.Module/old/HelperFunctions.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/HelperFunctions.cs rename to ZSharp.SourceCompiler.Module/old/HelperFunctions.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/capabilities/IMultipassCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/capabilities/IMultipassCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/capabilities/IMultipassCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/capabilities/IMultipassCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/class body/ClassBodyCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/class body/ClassBodyCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/class body/ClassBodyCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/class body/ClassBodyCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/class body/ConstructorCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/class body/ConstructorCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/class body/ConstructorCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/class body/ConstructorCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/class body/MethodCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/class body/MethodCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/class body/MethodCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/class body/MethodCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/document/compiler/DocumentCompiler.Compile.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.Compile.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/document/compiler/DocumentCompiler.Compile.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/document/compiler/DocumentCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/document/compiler/DocumentCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/document/compiler/DocumentCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/document/objects/Document.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/document/objects/Document.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/document/objects/Document.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/document/objects/Document.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/module/ClassCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/module/ClassCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/module/ClassCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/module/ClassCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/module/FunctionCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/module/FunctionCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/module/FunctionCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/module/FunctionCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/module/ModuleCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/module/ModuleCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/module/ModuleCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/module/ModuleCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/loops/for/ForLoopCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/loops/while/WhileExpressionCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/loops/while/WhileLoopCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/loops/while/WhileStatementCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/Case.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/objects/Case.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/Case.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/objects/Case.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/ForLoop.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/objects/ForLoop.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/ForLoop.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/objects/ForLoop.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/If.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/objects/If.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/If.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/objects/If.cs diff --git a/ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/WhileLoop.cs b/ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/objects/WhileLoop.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/builtin-compilers/runtime code/objects/WhileLoop.cs rename to ZSharp.SourceCompiler.Module/old/builtin-compilers/runtime code/objects/WhileLoop.cs diff --git a/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Compilers.cs b/ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.Compilers.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Compilers.cs rename to ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.Compilers.cs diff --git a/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.ImportSystem.cs b/ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.ImportSystem.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.ImportSystem.cs rename to ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.ImportSystem.cs diff --git a/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Initialize.cs b/ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.Initialize.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Initialize.cs rename to ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.Initialize.cs diff --git a/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Logging.cs b/ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.Logging.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Logging.cs rename to ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.Logging.cs diff --git a/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.OOP.cs b/ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.OOP.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.OOP.cs rename to ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.OOP.cs diff --git a/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Operators.cs b/ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.Operators.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.Operators.cs rename to ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.Operators.cs diff --git a/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.ResultTools.cs b/ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.ResultTools.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.ResultTools.cs rename to ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.ResultTools.cs diff --git a/ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.cs b/ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/compiler/ZSSourceCompiler.cs rename to ZSharp.SourceCompiler.Module/old/compiler/ZSSourceCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/context/Context.Compilers.cs b/ZSharp.SourceCompiler.Module/old/context/Context.Compilers.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/context/Context.Compilers.cs rename to ZSharp.SourceCompiler.Module/old/context/Context.Compilers.cs diff --git a/ZSharp.Interpreter/source-compiler/context/Context.Nodes.cs b/ZSharp.SourceCompiler.Module/old/context/Context.Nodes.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/context/Context.Nodes.cs rename to ZSharp.SourceCompiler.Module/old/context/Context.Nodes.cs diff --git a/ZSharp.Interpreter/source-compiler/context/Context.Scopes.cs b/ZSharp.SourceCompiler.Module/old/context/Context.Scopes.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/context/Context.Scopes.cs rename to ZSharp.SourceCompiler.Module/old/context/Context.Scopes.cs diff --git a/ZSharp.Interpreter/source-compiler/context/Context.cs b/ZSharp.SourceCompiler.Module/old/context/Context.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/context/Context.cs rename to ZSharp.SourceCompiler.Module/old/context/Context.cs diff --git a/ZSharp.Interpreter/source-compiler/contexts/capabilities/IMemoryAllocator.cs b/ZSharp.SourceCompiler.Module/old/contexts/capabilities/IMemoryAllocator.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/contexts/capabilities/IMemoryAllocator.cs rename to ZSharp.SourceCompiler.Module/old/contexts/capabilities/IMemoryAllocator.cs diff --git a/ZSharp.Interpreter/source-compiler/contexts/capabilities/IObjectContext.cs b/ZSharp.SourceCompiler.Module/old/contexts/capabilities/IObjectContext.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/contexts/capabilities/IObjectContext.cs rename to ZSharp.SourceCompiler.Module/old/contexts/capabilities/IObjectContext.cs diff --git a/ZSharp.Interpreter/source-compiler/contexts/capabilities/scope/ILookupContext.cs b/ZSharp.SourceCompiler.Module/old/contexts/capabilities/scope/ILookupContext.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/contexts/capabilities/scope/ILookupContext.cs rename to ZSharp.SourceCompiler.Module/old/contexts/capabilities/scope/ILookupContext.cs diff --git a/ZSharp.Interpreter/source-compiler/contexts/capabilities/scope/IScopeContext.cs b/ZSharp.SourceCompiler.Module/old/contexts/capabilities/scope/IScopeContext.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/contexts/capabilities/scope/IScopeContext.cs rename to ZSharp.SourceCompiler.Module/old/contexts/capabilities/scope/IScopeContext.cs diff --git a/ZSharp.Interpreter/source-compiler/contexts/concrete/ClassContext.cs b/ZSharp.SourceCompiler.Module/old/contexts/concrete/ClassContext.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/contexts/concrete/ClassContext.cs rename to ZSharp.SourceCompiler.Module/old/contexts/concrete/ClassContext.cs diff --git a/ZSharp.Interpreter/source-compiler/contexts/concrete/ExpressionContext.cs b/ZSharp.SourceCompiler.Module/old/contexts/concrete/ExpressionContext.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/contexts/concrete/ExpressionContext.cs rename to ZSharp.SourceCompiler.Module/old/contexts/concrete/ExpressionContext.cs diff --git a/ZSharp.Interpreter/source-compiler/contexts/concrete/FunctionContext.cs b/ZSharp.SourceCompiler.Module/old/contexts/concrete/FunctionContext.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/contexts/concrete/FunctionContext.cs rename to ZSharp.SourceCompiler.Module/old/contexts/concrete/FunctionContext.cs diff --git a/ZSharp.Interpreter/source-compiler/contexts/concrete/ObjectContext.cs b/ZSharp.SourceCompiler.Module/old/contexts/concrete/ObjectContext.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/contexts/concrete/ObjectContext.cs rename to ZSharp.SourceCompiler.Module/old/contexts/concrete/ObjectContext.cs diff --git a/ZSharp.Interpreter/source-compiler/contexts/concrete/ScopeContext.cs b/ZSharp.SourceCompiler.Module/old/contexts/concrete/ScopeContext.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/contexts/concrete/ScopeContext.cs rename to ZSharp.SourceCompiler.Module/old/contexts/concrete/ScopeContext.cs diff --git a/ZSharp.Interpreter/source-compiler/contexts/strategies/UntilContextTypeStrategy.cs b/ZSharp.SourceCompiler.Module/old/contexts/strategies/UntilContextTypeStrategy.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/contexts/strategies/UntilContextTypeStrategy.cs rename to ZSharp.SourceCompiler.Module/old/contexts/strategies/UntilContextTypeStrategy.cs diff --git a/ZSharp.Interpreter/source-compiler/core-compilers/DefaultContextCompiler.cs b/ZSharp.SourceCompiler.Module/old/core-compilers/DefaultContextCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/core-compilers/DefaultContextCompiler.cs rename to ZSharp.SourceCompiler.Module/old/core-compilers/DefaultContextCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.Literals.cs b/ZSharp.SourceCompiler.Module/old/core-compilers/expression/ExpressionCompiler.Literals.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.Literals.cs rename to ZSharp.SourceCompiler.Module/old/core-compilers/expression/ExpressionCompiler.Literals.cs diff --git a/ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.cs b/ZSharp.SourceCompiler.Module/old/core-compilers/expression/ExpressionCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/core-compilers/expression/ExpressionCompiler.cs rename to ZSharp.SourceCompiler.Module/old/core-compilers/expression/ExpressionCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/core-compilers/statement/StatementCompiler.cs b/ZSharp.SourceCompiler.Module/old/core-compilers/statement/StatementCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/core-compilers/statement/StatementCompiler.cs rename to ZSharp.SourceCompiler.Module/old/core-compilers/statement/StatementCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/extensibility/CompilerBase.cs b/ZSharp.SourceCompiler.Module/old/extensibility/CompilerBase.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/extensibility/CompilerBase.cs rename to ZSharp.SourceCompiler.Module/old/extensibility/CompilerBase.cs diff --git a/ZSharp.Interpreter/source-compiler/extensibility/ContextCompiler.cs b/ZSharp.SourceCompiler.Module/old/extensibility/ContextCompiler.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/extensibility/ContextCompiler.cs rename to ZSharp.SourceCompiler.Module/old/extensibility/ContextCompiler.cs diff --git a/ZSharp.Interpreter/source-compiler/extensibility/error/Error.cs b/ZSharp.SourceCompiler.Module/old/extensibility/error/Error.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/extensibility/error/Error.cs rename to ZSharp.SourceCompiler.Module/old/extensibility/error/Error.cs diff --git a/ZSharp.Interpreter/source-compiler/extensibility/error/errors/CombinedCompilationError.cs b/ZSharp.SourceCompiler.Module/old/extensibility/error/errors/CombinedCompilationError.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/extensibility/error/errors/CombinedCompilationError.cs rename to ZSharp.SourceCompiler.Module/old/extensibility/error/errors/CombinedCompilationError.cs diff --git a/ZSharp.Interpreter/source-compiler/extensibility/error/errors/CompilationError.cs b/ZSharp.SourceCompiler.Module/old/extensibility/error/errors/CompilationError.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/extensibility/error/errors/CompilationError.cs rename to ZSharp.SourceCompiler.Module/old/extensibility/error/errors/CompilationError.cs diff --git a/ZSharp.Interpreter/source-compiler/extensibility/oop/ClassSpecification.cs b/ZSharp.SourceCompiler.Module/old/extensibility/oop/ClassSpecification.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/extensibility/oop/ClassSpecification.cs rename to ZSharp.SourceCompiler.Module/old/extensibility/oop/ClassSpecification.cs diff --git a/ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileExpression.cs b/ZSharp.SourceCompiler.Module/old/extensibility/overrides/IOverrideCompileExpression.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileExpression.cs rename to ZSharp.SourceCompiler.Module/old/extensibility/overrides/IOverrideCompileExpression.cs diff --git a/ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileNode.cs b/ZSharp.SourceCompiler.Module/old/extensibility/overrides/IOverrideCompileNode.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileNode.cs rename to ZSharp.SourceCompiler.Module/old/extensibility/overrides/IOverrideCompileNode.cs diff --git a/ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileStatement.cs b/ZSharp.SourceCompiler.Module/old/extensibility/overrides/IOverrideCompileStatement.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/extensibility/overrides/IOverrideCompileStatement.cs rename to ZSharp.SourceCompiler.Module/old/extensibility/overrides/IOverrideCompileStatement.cs diff --git a/ZSharp.Interpreter/source-compiler/import system/ImportSystem.cs b/ZSharp.SourceCompiler.Module/old/import system/ImportSystem.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/import system/ImportSystem.cs rename to ZSharp.SourceCompiler.Module/old/import system/ImportSystem.cs diff --git a/ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs b/ZSharp.SourceCompiler.Module/old/import system/importers/StandardLibraryImporter.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/import system/importers/StandardLibraryImporter.cs rename to ZSharp.SourceCompiler.Module/old/import system/importers/StandardLibraryImporter.cs diff --git a/ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs b/ZSharp.SourceCompiler.Module/old/import system/importers/StringImporter.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/import system/importers/StringImporter.cs rename to ZSharp.SourceCompiler.Module/old/import system/importers/StringImporter.cs diff --git a/ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs b/ZSharp.SourceCompiler.Module/old/import system/importers/ZSImporter.cs similarity index 100% rename from ZSharp.Interpreter/source-compiler/import system/importers/ZSImporter.cs rename to ZSharp.SourceCompiler.Module/old/import system/importers/ZSImporter.cs diff --git a/ZSharp.SourceCompiler.Module/utils/ObjectBuildState.cs b/ZSharp.SourceCompiler.Module/utils/ObjectBuildState.cs new file mode 100644 index 00000000..398affb4 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/utils/ObjectBuildState.cs @@ -0,0 +1,28 @@ +namespace ZSharp.SourceCompiler.Module +{ + internal sealed class ObjectBuildState + where T : struct, Enum, IConvertible + { + public T State { get; private set; } + + public bool Get(T state) => State.HasFlag(state); + + public void Set(T state) + { + State = (T)(ValueType)(State.ToInt32(null) | state.ToInt32(null)); + } + + public static bool operator &(ObjectBuildState instance, T value) + => instance.Get(value); + + public bool this[T flag] + { + get => Get(flag); + set + { + if (value) + Set(flag); + } + } + } +} diff --git a/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj b/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj index 1fdbfde6..8840c4e0 100644 --- a/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj +++ b/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj @@ -7,13 +7,13 @@ - + diff --git a/ZSharp.SourceCompiler.Project/compiler/ProjectCompiler.T.cs b/ZSharp.SourceCompiler.Project/compiler/ProjectCompiler.T.cs new file mode 100644 index 00000000..970c61f1 --- /dev/null +++ b/ZSharp.SourceCompiler.Project/compiler/ProjectCompiler.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Project +{ + partial class ProjectCompiler + { + + } +} diff --git a/ZSharp.SourceCompiler.Project/compiler/ProjectCompiler.cs b/ZSharp.SourceCompiler.Project/compiler/ProjectCompiler.cs new file mode 100644 index 00000000..c0f5fcfd --- /dev/null +++ b/ZSharp.SourceCompiler.Project/compiler/ProjectCompiler.cs @@ -0,0 +1,19 @@ +using System; + +namespace ZSharp.SourceCompiler.Project +{ + public sealed partial class ProjectCompiler( + Interpreter.Interpreter interpreter, + Project project + ) + { + public Interpreter.Interpreter Interpreter { get; } = interpreter; + + public Project Project { get; } = project; + + public ProjectResult Compile() + { + throw new NotImplementedException(); + } + } +} diff --git a/ZSharp.SourceCompiler.Project/project/ProjectResult.cs b/ZSharp.SourceCompiler.Project/project/ProjectResult.cs new file mode 100644 index 00000000..5a97b2dc --- /dev/null +++ b/ZSharp.SourceCompiler.Project/project/ProjectResult.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Project +{ + public sealed class ProjectResult + { + + } +} diff --git a/ZSharp.SourceCompiler.Script/GlobalUsings.cs b/ZSharp.SourceCompiler.Script/GlobalUsings.cs new file mode 100644 index 00000000..05db7df2 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/GlobalUsings.cs @@ -0,0 +1 @@ +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj b/ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj new file mode 100644 index 00000000..85ac50cf --- /dev/null +++ b/ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj @@ -0,0 +1,16 @@ + + + + net8.0 + enable + enable + + + + + + + + + + diff --git a/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Context.cs b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Context.cs new file mode 100644 index 00000000..50918d7a --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Context.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + public Context Context { get; init; } = new(); + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Options.cs b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Options.cs new file mode 100644 index 00000000..7d01b1dc --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Options.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + public ScriptingOptions Options { get; init; } = new ScriptingOptions(); + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.T.cs b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.T.cs new file mode 100644 index 00000000..9920791e --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.T.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs new file mode 100644 index 00000000..34c10fdc --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs @@ -0,0 +1,31 @@ +namespace ZSharp.SourceCompiler.Script +{ + public sealed partial class ScriptCompiler + { + public Interpreter.Interpreter Interpreter { get; } + + public AST.Document Node { get; } + + public ScriptCompiler(Interpreter.Interpreter interpreter, AST.Document document) + { + Interpreter = interpreter; + Node = document; + + CompileExpression = new TopLevelExpressionCompiler(interpreter) + { + CompileExpression = new ExpressionCompiler(interpreter) + { + PostProcess = PostProcess + }.Compile + }.Compile; + } + + public void Compile() + { + //using var _ = Interpreter.Compiler.ContextScope(new DocumentContext()); + using var _ = Interpreter.Compiler.ContextScope(new ScopeContext()); + + Node.Statements.ForEach(Compile); + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/ScriptCompiler.Compile.cs b/ZSharp.SourceCompiler.Script/compiler/compile/ScriptCompiler.Compile.cs new file mode 100644 index 00000000..87ea77f6 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/ScriptCompiler.Compile.cs @@ -0,0 +1,25 @@ +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + public CompileExpression CompileExpression { get; } + + private void Compile(AST.Statement statement) + { + switch (statement) + { + case AST.BlockStatement block: Compile(block); break; + case AST.DefinitionStatement definition: Compile(definition); break; + case AST.ExpressionStatement expression: Compile(expression); break; + case AST.IfStatement @if: Compile(@if); break; + case AST.ImportStatement import: Compile(import); break; + default: + Interpreter.Log.Error( + $"Unsupported statement type: {statement.GetType().Name}.", + new NodeLogOrigin(statement) + ); + break; + } + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Call.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Call.cs new file mode 100644 index 00000000..ce47020f --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Call.cs @@ -0,0 +1,47 @@ +using ZSharp.Compiler; + +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + private Result Compile(AST.CallExpression call) + { + var calleeResult = Compile(call.Callee); + + if ( + calleeResult + .When(out var callee) + .Error(out var errorMessage) + ) return Result.Error( + $"Failed to compile callee: {errorMessage}" + ); + + var argumentResults = call.Arguments + .Select(arg => + { + if ( + Compile(arg.Value) + .When(out var argValue) + .Error(out var error) + ) return Result.Error(error); + + return Result.Ok( + new( + arg.Name, + argValue! + ) + ); + }) + .ToList(); + + if (argumentResults.Any(r => r.IsError)) + return Result.Error( + $"Failed to compile arguments: { + (string.Join(", ", Enumerable.Where>(argumentResults, (Func, bool>)(r => r.IsError)).Select(r => r.Error(out var error) ? error : throw new()))) + }" + ); + + return Interpreter.Compiler.CG.Call(callee!, [.. argumentResults.Select(r => r.Unwrap())]); + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs new file mode 100644 index 00000000..df59e704 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs @@ -0,0 +1,29 @@ +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + private Result Compile(AST.Expression expression) + => PostProcess( + expression switch + { + AST.CallExpression call => Compile(call), + AST.IdentifierExpression identifier => Compile(identifier), + AST.LiteralExpression literal => Compile(literal), + AST.Module module => Compile(module), + _ => CompileExpression(expression) + } + ); + + private Result PostProcess(Result result) + { + if (!result.Ok(out var value)) return result; + + if (Options.EvaluationTarget == EvaluationTarget.Statement) + return result; + + return Interpreter + .Evaluate(value) + .When(ZSharp.Interpreter.CTServices.InfoOf); + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs new file mode 100644 index 00000000..b0ae8c18 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs @@ -0,0 +1,18 @@ +using ZSharp.Compiler; + +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + private Result Compile(AST.IdentifierExpression identifier) + { + foreach (var scope in Interpreter.Compiler.CurrentContext.FindContext()) + if (scope.Get(identifier.Name).Ok(out var result)) + return Result.Ok(result); + + return Result.Error( + $"Identifier '{identifier.Name}' not found." + ); + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.If.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.If.cs new file mode 100644 index 00000000..9920791e --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.If.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs new file mode 100644 index 00000000..e376f4cb --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs @@ -0,0 +1,13 @@ +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + private Result Compile(AST.LiteralExpression literal) + { + if (literal.UnitType is not null) + Interpreter.Log.Warning($"Literal has a unit type '{literal.UnitType}' which will be ignored.", new NodeLogOrigin(literal)); + + return new LiteralCompiler().Compile(literal); + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Module.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Module.cs new file mode 100644 index 00000000..54a10fa9 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Module.cs @@ -0,0 +1,10 @@ +using ZSharp.Compiler; + +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + private Result Compile(AST.Module module) + => new Module.ModuleCompiler(Interpreter, module).Compile(); + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Block.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Block.cs new file mode 100644 index 00000000..e3adf890 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Block.cs @@ -0,0 +1,13 @@ +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + private void Compile(AST.BlockStatement block) + { + var _ = Interpreter.Compiler.ContextScope(new ScopeContext()); + + foreach (var statement in block.Statements) + Compile(statement); + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Definition.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Definition.cs new file mode 100644 index 00000000..a3a5b80d --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Definition.cs @@ -0,0 +1,16 @@ +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + private void Compile(AST.DefinitionStatement definitionStatement) + { + var result = Compile(definitionStatement.Definition); + + if (result.Error(out var error)) + Interpreter.Log.Error( + $"Failed to compile definition: {error}", + new NodeLogOrigin(definitionStatement) + ); + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs new file mode 100644 index 00000000..109fc499 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs @@ -0,0 +1,26 @@ +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + private void Compile(AST.ExpressionStatement expressionStatement) + { + var valueObjectResult = Compile(expressionStatement.Expression); + + if ( + valueObjectResult + .When(out var valueObject) + .Error(out var errorMessage) + ) + { + Interpreter.Log.Error( + $"Failed to compile expression: {errorMessage}", + new NodeLogOrigin(expressionStatement) + ); + + return; + } + + Interpreter.Evaluate(valueObject!); + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.If.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.If.cs new file mode 100644 index 00000000..9a1a3a84 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.If.cs @@ -0,0 +1,52 @@ +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + private void Compile(AST.IfStatement @if) + { + var conditionResult = Compile(@if.Condition); + + if ( + conditionResult + .When(out var confition) + .Error(out var error) + ) + { + Interpreter.Log.Error( + $"Failed to compile if condition: {error}", + new NodeLogOrigin(@if.Condition) + ); + return; + } + + // TODO: cast to boolean + + var conditionValueResult = Interpreter.Evaluate(confition!); + + if ( + conditionValueResult + .When(out var conditionValue) + .Error(out var error2) + ) + { + Interpreter.Log.Error( + $"Failed to evaluate if condition: {error2}", + new NodeLogOrigin(@if.Condition) + ); + return; + } + + if (conditionValue is not bool conditionBool) + { + Interpreter.Log.Error( + $"If condition does not evaluate to a boolean value.", + new NodeLogOrigin(@if.Condition) + ); + return; + } + + if (conditionBool) Compile(@if.If); + else if (@if.Else is not null) Compile(@if.Else); + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs new file mode 100644 index 00000000..fcd666a1 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs @@ -0,0 +1,125 @@ +using CommonZ; +using ZSharp.AST; +using ZSharp.Compiler; + +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + private void Compile(ImportStatement import) + { + IEnumerable arguments = [ + new CallArgument() { + Value = import.Source + }, + .. import.Arguments ?? [] + ]; + + var argumentsResults = arguments + .Select((arg, i) => + { + if ( + Compile(arg.Value) + .When(out var value) + .Error(out var error) + ) + { + Interpreter.Log.Error( + $"Failed to compile import argument '{arg.Name ?? i.ToString()}': {error}", + new NodeLogOrigin(arg.Value) + ); + return Result.Error(error); + } + + return Result.Ok( + new(arg.Name, value!) + ); + }) + .ToArray(); + + if (argumentsResults.Any(r => r.IsError)) + return; + + var importResult = Interpreter.Compiler.CG.Call( + Context.ImportSystem.ImportFunction, + [.. argumentsResults.Select(r => r.Unwrap())] + ); + + if (importResult.When(out var result).Error(out var error)) + { + Interpreter.Log.Error( + $"Failed to compile import: {error}", + new NodeLogOrigin(import) + ); + return; + } + + if ( + Interpreter.Evaluate(result!) + .When(out var importObject) + .Error(out error) + ) + { + Interpreter.Log.Error( + $"Failed to evaluate import: {error}", + new NodeLogOrigin(import) + ); + return; + } + result = ZSharp.Interpreter.CTServices.InfoOf(importObject!); + + if (import.Alias is not null) + { + if (Interpreter + .Compiler + .CurrentContext + .PerformOperation( + scope => !scope.Add(import.Alias, result).Error(out error) + ) + ) + { + Interpreter.Log.Error( + $"No scope context found to import into.", + new NodeLogOrigin(import) + ); + return; + } + } + + if (import.ImportedNames is not null) + { + var scope = Interpreter.Compiler.CurrentContext.FindFirstContext(); + if (scope is null) + { + Interpreter.Log.Error( + $"No scope context found to import into.", + new NodeLogOrigin(import) + ); + return; + } + + var memberResults = import.ImportedNames + .Select(name => (name, Interpreter.Compiler.CG.Member(result, name.Name))) + .Select(vs => + { + var (name, r) = vs; + + return (name, result: r.Else(e => Interpreter.Log.Error( + $"Failed to import member '{name.Name}': {e}", + new NodeLogOrigin(name) + ))); + }) + .ToArray(); + + if (memberResults.Any(vs => vs.result.IsError)) + return; + + foreach (var (name, memberResult) in memberResults) + scope.Set( + name.Alias ?? name.Name, + memberResult.Unwrap() + ); + } + } + } +} diff --git a/ZSharp.SourceCompiler.Script/contexts/ScopeContext.cs b/ZSharp.SourceCompiler.Script/contexts/ScopeContext.cs new file mode 100644 index 00000000..0e087414 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/contexts/ScopeContext.cs @@ -0,0 +1,34 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.SourceCompiler.Script +{ + public sealed class ScopeContext() + : IContext + , IScopeContext + { + private readonly Mapping scope = []; + + public IContext? Parent { get; set; } + + public Result Add(string name, CompilerObject value) + { + if (scope.ContainsKey(name)) + return Result.Error($"Name '{name}' is already defined in this scope."); + + return Set(name, value); + } + + public Result Get(string name) + => scope.TryGetValue(name, out var value) + ? Result.Ok(value) + : Result.Error($"Name '{name}' is not defined in this scope."); + + public Result Set(string name, CompilerObject value) + { + scope[name] = value; + + return Result.Ok(value); + } + } +} diff --git a/ZSharp.SourceCompiler.Script/options/EvaluationTarget.cs b/ZSharp.SourceCompiler.Script/options/EvaluationTarget.cs new file mode 100644 index 00000000..955ceceb --- /dev/null +++ b/ZSharp.SourceCompiler.Script/options/EvaluationTarget.cs @@ -0,0 +1,15 @@ +namespace ZSharp.SourceCompiler.Script +{ + public enum EvaluationTarget + { + /// + /// The compiler will evaluate each expression as it's compiled. + /// + Expression, + + /// + /// The compiler will only evaluate the final statement in a script. + /// + Statement, + } +} diff --git a/ZSharp.SourceCompiler.Script/options/ScriptingOptions.cs b/ZSharp.SourceCompiler.Script/options/ScriptingOptions.cs new file mode 100644 index 00000000..acb513e8 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/options/ScriptingOptions.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Script +{ + public class ScriptingOptions + { + public EvaluationTarget EvaluationTarget { get; init; } = EvaluationTarget.Statement; + } +} From efee1e4622490e1e184137fb1f992a672f726737 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen <42520501+binyamin555@users.noreply.github.com> Date: Thu, 11 Sep 2025 23:27:08 +0300 Subject: [PATCH 206/235] Revise README with updated Discord link --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f36be31c..14ead123 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ > This README file is out-of-date. I will update this once I have enough time and an acceptable working version. -> If you have any questions regarding this project, you can join the discord server [discord server](https://discord.gg/Uc3GN2bfG9). +> If you have any questions regarding this project, you can join the discord server ~~[discord server](https://discord.gg/Uc3GN2bfG9)~~ [discord channel on PLTD](https://discord.gg/Zfbzdaks2D). Welcome to the Z# language repository! This repository holds the first released version of Z#. @@ -12,4 +12,4 @@ Z# is a typesafe, interpreterd language. It is still very much a WIP so don't ex This repository is undergoing massive rewrites and the architecture is still under development. Due to that, contributions are currently not accepted. -However, suggestions about everything (syntax, concepts, architecture, etc..) are always welcome. \ No newline at end of file +However, suggestions about everything (syntax, concepts, architecture, etc..) are always welcome. From dcb9379f8bfd9fb72bed6a7ce4518c39815d06d1 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen <42520501+binyamin555@users.noreply.github.com> Date: Thu, 11 Sep 2025 23:27:40 +0300 Subject: [PATCH 207/235] Delete .vscode/settings.json --- .vscode/settings.json | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index f8332ffb..00000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "python.analysis.extraPaths": [ - "${workspaceFolder}/zsharp-miniz", - "${workspaceFolder}/zsharp-lang", - "${workspaceFolder}/zsharp-runtime", - "${workspaceFolder}/zsharp-text", - "${workspaceFolder}/zsharp-vm", - ], - "python.analysis.exclude": [ - "${workspaceFolder}/miniz", - ] -} \ No newline at end of file From 5e4c5d7e4b981b3caf8bfab81abb9b910b200db0 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 11 Sep 2025 23:31:00 +0300 Subject: [PATCH 208/235] Remove old runtime adapter code --- ZSharp.Runtime.IL/GlobalUsings.cs | 2 - ZSharp.Runtime.IL/Hooks.cs | 7 - ZSharp.Runtime.IL/ICompileTime.cs | 7 - ZSharp.Runtime.IL/IRCodeEvaluator.cs | 42 --- ZSharp.Runtime.IL/Runtime.cs | 81 ----- ZSharp.Runtime.IL/Utils.cs | 9 - ZSharp.Runtime.IL/ZSharp.Runtime.IL.csproj | 14 - ZSharp.Runtime.IL/context/Context.Cache.cs | 9 - ZSharp.Runtime.IL/context/Context.IL2IR.cs | 122 ------- ZSharp.Runtime.IL/context/Context.IR2IL.cs | 117 ------- ZSharp.Runtime.IL/context/Context.cs | 7 - .../context/caches/ContextCache.IL2IR.cs | 19 -- .../context/caches/ContextCache.IR2IL.cs | 19 -- .../il2ir/attributes/AliasAttribute.cs | 16 - .../il2ir/attributes/HideInIRAttribute.cs | 6 - .../attributes/KeywordParameterAttribute.cs | 7 - .../attributes/ModuleGlobalsAttribute.cs | 7 - ZSharp.Runtime.IL/il2ir/core/BaseILLoader.cs | 19 -- ZSharp.Runtime.IL/il2ir/core/ILLoader.cs | 128 -------- .../il2ir/loaders/ClassLoader.cs | 229 ------------- .../il2ir/loaders/EnumerationLoader.cs | 42 --- .../il2ir/loaders/InterfaceLoader.cs | 170 ---------- .../il2ir/loaders/LiteralLoader.cs | 109 ------- .../il2ir/loaders/ModuleLoader.cs | 113 ------- .../il2ir/loaders/ValueTypeLoader.cs | 230 ------------- ZSharp.Runtime.IL/ir2il/Constants.cs | 17 - .../ir2il/SignatureExtensions.cs | 13 - .../code contexts/FunctionCodeContext.cs | 74 ----- .../ir2il/code contexts/UnboundCodeContext.cs | 23 -- ZSharp.Runtime.IL/ir2il/code/CodeCompiler.cs | 70 ---- .../code/branching/BranchingCodeCompiler.cs | 24 -- .../code/branching/IBranchingCodeContext.cs | 10 - .../ir2il/code/core/CodeStack.cs | 22 -- .../ir2il/code/core/ICodeContext.cs | 11 - .../ir2il/code/frame/FrameCodeCompiler.cs | 73 ----- .../ir2il/code/frame/IFrameCodeContext.cs | 10 - ZSharp.Runtime.IL/ir2il/code/frame/Local.cs | 11 - .../ir2il/code/frame/Parameter.cs | 11 - .../code/functional/FunctionalCodeCompiler.cs | 34 -- .../code/functional/IFunctionalCodeContext.cs | 8 - .../ir2il/code/modular/ModularCodeCompiler.cs | 25 -- .../ir2il/code/object/OOPCodeCompiler.cs | 59 ---- .../ir2il/code/stack/StackCodeCompiler.cs | 82 ----- ZSharp.Runtime.IL/ir2il/core/BaseIRLoader.cs | 17 - .../ir2il/core/IRLoader.RuntimeServices.cs | 122 ------- ZSharp.Runtime.IL/ir2il/core/IRLoader.cs | 168 ---------- .../ir2il/loader new/ClassLoader.cs | 173 ---------- .../ir2il/loader new/InterfaceLoader.cs | 153 --------- .../ir2il/loader new/ModuleContentLoader.cs | 17 - .../ir2il/loader new/ModuleLoader.cs | 118 ------- .../ir2il/loader new/RootModuleLoader.cs | 47 --- .../loader new/code/CodeLoader.Compile.cs | 308 ------------------ .../ir2il/loader new/code/CodeLoader.cs | 92 ------ .../ir2il/loader new/code/ICodeLoader.cs | 15 - .../ir2il/loader new/code/Parameter.cs | 11 - .../ir2il/loader new/code/ThisParameter.cs | 17 - ZSharp.Runtime.IL/objects/TypeObject.cs | 9 - 57 files changed, 3375 deletions(-) delete mode 100644 ZSharp.Runtime.IL/GlobalUsings.cs delete mode 100644 ZSharp.Runtime.IL/Hooks.cs delete mode 100644 ZSharp.Runtime.IL/ICompileTime.cs delete mode 100644 ZSharp.Runtime.IL/IRCodeEvaluator.cs delete mode 100644 ZSharp.Runtime.IL/Runtime.cs delete mode 100644 ZSharp.Runtime.IL/Utils.cs delete mode 100644 ZSharp.Runtime.IL/ZSharp.Runtime.IL.csproj delete mode 100644 ZSharp.Runtime.IL/context/Context.Cache.cs delete mode 100644 ZSharp.Runtime.IL/context/Context.IL2IR.cs delete mode 100644 ZSharp.Runtime.IL/context/Context.IR2IL.cs delete mode 100644 ZSharp.Runtime.IL/context/Context.cs delete mode 100644 ZSharp.Runtime.IL/context/caches/ContextCache.IL2IR.cs delete mode 100644 ZSharp.Runtime.IL/context/caches/ContextCache.IR2IL.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/attributes/AliasAttribute.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/attributes/HideInIRAttribute.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/attributes/KeywordParameterAttribute.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/attributes/ModuleGlobalsAttribute.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/core/BaseILLoader.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/core/ILLoader.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/loaders/EnumerationLoader.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/loaders/LiteralLoader.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs delete mode 100644 ZSharp.Runtime.IL/il2ir/loaders/ValueTypeLoader.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/Constants.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/SignatureExtensions.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code contexts/FunctionCodeContext.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code contexts/UnboundCodeContext.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/CodeCompiler.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/branching/BranchingCodeCompiler.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/branching/IBranchingCodeContext.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/core/CodeStack.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/core/ICodeContext.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/frame/FrameCodeCompiler.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/frame/IFrameCodeContext.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/frame/Local.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/frame/Parameter.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/functional/FunctionalCodeCompiler.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/functional/IFunctionalCodeContext.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/modular/ModularCodeCompiler.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/object/OOPCodeCompiler.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/code/stack/StackCodeCompiler.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/core/BaseIRLoader.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/core/IRLoader.RuntimeServices.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/core/IRLoader.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/loader new/ModuleContentLoader.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/loader new/RootModuleLoader.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.Compile.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/loader new/code/ICodeLoader.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/loader new/code/Parameter.cs delete mode 100644 ZSharp.Runtime.IL/ir2il/loader new/code/ThisParameter.cs delete mode 100644 ZSharp.Runtime.IL/objects/TypeObject.cs diff --git a/ZSharp.Runtime.IL/GlobalUsings.cs b/ZSharp.Runtime.IL/GlobalUsings.cs deleted file mode 100644 index 8ab48f04..00000000 --- a/ZSharp.Runtime.IL/GlobalUsings.cs +++ /dev/null @@ -1,2 +0,0 @@ -global using IL = System.Reflection; -global using IR = ZSharp.IR; diff --git a/ZSharp.Runtime.IL/Hooks.cs b/ZSharp.Runtime.IL/Hooks.cs deleted file mode 100644 index 5fcb3db8..00000000 --- a/ZSharp.Runtime.IL/Hooks.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Runtime.NET -{ - public sealed class Hooks - { - public IL.MethodInfo GetObject { get; set; } = null!; - } -} diff --git a/ZSharp.Runtime.IL/ICompileTime.cs b/ZSharp.Runtime.IL/ICompileTime.cs deleted file mode 100644 index 3276e52b..00000000 --- a/ZSharp.Runtime.IL/ICompileTime.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Runtime.NET -{ - public interface ICompileTime - { - public Objects.CompilerObject GetCO(); - } -} diff --git a/ZSharp.Runtime.IL/IRCodeEvaluator.cs b/ZSharp.Runtime.IL/IRCodeEvaluator.cs deleted file mode 100644 index 02f25322..00000000 --- a/ZSharp.Runtime.IL/IRCodeEvaluator.cs +++ /dev/null @@ -1,42 +0,0 @@ -using ZSharp.Compiler; -using ZSharp.Objects; - -namespace ZSharp.Runtime.NET -{ - public sealed class IRCodeEvaluator(Runtime runtime) - { - private readonly Runtime runtime = runtime; - - public CompilerObject? EvaluateCT(IRCode code, Compiler.Compiler compiler) - { - IL.Emit.DynamicMethod method = new( - string.Empty, - runtime.irLoader.LoadType( - compiler.IR.CompileType( - code.RequireValueType(compiler.TypeSystem.Void) - ).Unwrap() - ), - null - ); - - var context = new IR2IL.Code.UnboundCodeContext(runtime.irLoader, method.GetILGenerator()); - - new IR2IL.Code.CodeCompiler(context).CompileCode([ - .. code.Instructions, - new IR.VM.Return() - ]); - - var result = method.Invoke(null, null); - - if (method.ReturnType == typeof(void)) return null; - - if (result is CompilerObject co) - return co; - - if (result is ICompileTime coObject) - return coObject.GetCO(); - - return null; - } - } -} diff --git a/ZSharp.Runtime.IL/Runtime.cs b/ZSharp.Runtime.IL/Runtime.cs deleted file mode 100644 index dddc42eb..00000000 --- a/ZSharp.Runtime.IL/Runtime.cs +++ /dev/null @@ -1,81 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Runtime.NET -{ - public class Runtime - { - internal readonly IL2IR.ILLoader ilLoader; - internal readonly IR2IL.IRLoader irLoader; - - private readonly Cache typeObjects = []; - - public Context Context { get; } = new(); - - public Hooks Hooks { get; } = new(); - - public IRCodeEvaluator Evaluator { get; } - - public IR.RuntimeModule RuntimeModule { get; } - - public Runtime(IR.RuntimeModule runtimeModule) - { - RuntimeModule = runtimeModule; - - ilLoader = new(Context, runtimeModule); - irLoader = new(Context, runtimeModule); - - Evaluator = new(this); - - foreach (var (ir, il) in new (IR.IType, Type)[] - { - (runtimeModule.TypeSystem.Type, typeof(TypeObject)), - - (runtimeModule.TypeSystem.Void, typeof(void)), - (runtimeModule.TypeSystem.Boolean, typeof(bool)), - - (runtimeModule.TypeSystem.Int32, typeof(int)), - - (runtimeModule.TypeSystem.Float32, typeof(float)), - - (runtimeModule.TypeSystem.Object, typeof(object)), - (runtimeModule.TypeSystem.String, typeof(string)), - }) - Context.Cache(ir, il); - } - - public IL.Module Import(IR.Module module) - { - if (!Context.Cache(module, out var result)) - Context.Cache(result = irLoader.LoadModule(module), module); - - return result; - } - - public Type Import(IR.IType type) - => irLoader.LoadType(type); - - public IR.IType Import(Type type) - => Context.Cache(type, out IR.IType? result) ? result : ilLoader.LoadType(type); - - public IR.Module Import(IL.Module module) - { - if (!Context.Cache(module, out var result)) - result = ilLoader.LoadModule(module); - - //foreach (var (ir, il) in loadedModule.MethodImplementations) - // irLoader.Context.Callables.Cache(ir, il); - - //irLoader.Context.Modules.Cache(loadedModule.Result, module); - - return result; - } - - public IR.Function Import(IL.MethodInfo method) - => Context.Cache(method)!; - - public object GetObject(Type type) - { - throw new NotSupportedException(); - } - } -} diff --git a/ZSharp.Runtime.IL/Utils.cs b/ZSharp.Runtime.IL/Utils.cs deleted file mode 100644 index e7057713..00000000 --- a/ZSharp.Runtime.IL/Utils.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Runtime.NET -{ - public static class Utils - { - public static IL.MethodInfo GetMethod(T t) - where T : Delegate - => t.Method; - } -} diff --git a/ZSharp.Runtime.IL/ZSharp.Runtime.IL.csproj b/ZSharp.Runtime.IL/ZSharp.Runtime.IL.csproj deleted file mode 100644 index a0d88f59..00000000 --- a/ZSharp.Runtime.IL/ZSharp.Runtime.IL.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - - diff --git a/ZSharp.Runtime.IL/context/Context.Cache.cs b/ZSharp.Runtime.IL/context/Context.Cache.cs deleted file mode 100644 index cb6fe045..00000000 --- a/ZSharp.Runtime.IL/context/Context.Cache.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Runtime.NET -{ - partial class Context - { - private readonly ContextCacheIL2IR toIR = new(); - - private readonly ContextCacheIR2IL toIL = new(); - } -} diff --git a/ZSharp.Runtime.IL/context/Context.IL2IR.cs b/ZSharp.Runtime.IL/context/Context.IL2IR.cs deleted file mode 100644 index f6b84d66..00000000 --- a/ZSharp.Runtime.IL/context/Context.IL2IR.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace ZSharp.Runtime.NET -{ - partial class Context - { - public IR.Module? Cache(IL.Module il) - => toIR.Modules.Cache(il); - - public bool Cache(IL.Module il, [NotNullWhen(true)] out IR.Module? ir) - => toIR.Modules.Cache(il, out ir); - - public IR.Module Cache(IL.Module il, IR.Module ir) - { - if (!toIR.Modules.Contains(il)) - toIR.Modules.Cache(il, ir); - - if (!toIL.Modules.Contains(ir)) - toIL.Modules.Cache(ir, il); - - return ir; - } - - public bool Cache(Type il, [NotNullWhen(true)] out IR.IType? ir) - => toIR.Types.Cache(il, out ir); - - //public bool Cache(Type il, [NotNullWhen(true)] out T? ir) - // where T : class, IR.IType - // => toIR.Types.Cache(il, out ir); - - public IR.IType Cache(Type il, IR.IType ir) - { - if (!toIR.Types.Contains(il)) - toIR.Types.Cache(il, ir); - - if (!toIL.Types.Contains(ir)) - toIL.Types.Cache(ir, il); - - return ir; - } - - public T Cache(Type il, T ir) - where T : IR.IType - { - if (!toIR.Types.Contains(il)) - toIR.Types.Cache(il, ir); - - if (!toIL.Types.Contains(ir)) - toIL.Types.Cache(ir, il); - - return ir; - } - - public bool Cache(Type il, [NotNullWhen(true)] out T? ir) - where T : IR.OOPType - => toIR.OOPTypes.Cache(il, out ir); - - public IR.OOPType Cache(Type il, IR.OOPType ir) - { - if (!toIR.OOPTypes.Contains(il)) - toIR.OOPTypes.Cache(il, ir); - - if (!toIL.OOPTypes.Contains(ir)) - toIL.OOPTypes.Cache(ir, il); - - return ir; - } - - public IR.ICallable? Cache(IL.MethodBase il) - => toIR.Callables.Cache(il); - - public T? Cache(IL.MethodBase il) - where T : class, IR.ICallable - => toIR.Callables.Cache(il); - - public bool Cache(IL.MethodBase il, [NotNullWhen(true)] out IR.ICallable? ir) - => toIR.Callables.Cache(il, out ir); - - public bool Cache(IL.MethodBase il, [NotNullWhen(true)] out T? ir) - where T : class, IR.ICallable - => toIR.Callables.Cache(il, out ir); - - public IR.ICallable Cache(IL.MethodBase il, IR.ICallable ir) - { - if (!toIR.Callables.Contains(il)) - toIR.Callables.Cache(il, ir); - - if (!toIL.Callables.Contains(ir)) - toIL.Callables.Cache(ir, il); - - return ir; - } - - public bool Cache(IL.FieldInfo il, [NotNullWhen(true)] out IR.Field? ir) - => toIR.Fields.Cache(il, out ir); - - public IR.Field Cache(IL.FieldInfo il, IR.Field ir) - { - if (!toIR.Fields.Contains(il)) - toIR.Fields.Cache(il, ir); - - if (!toIL.Fields.Contains(ir)) - toIL.Fields.Cache(ir, il); - - return ir; - } - - public bool Cache(IL.FieldInfo il, [NotNullWhen(true)] out IR.Global? ir) - => toIR.Globals.Cache(il, out ir); - - public IR.Global Cache(IL.FieldInfo il, IR.Global ir) - { - if (!toIR.Globals.Contains(il)) - toIR.Globals.Cache(il, ir); - - if (!toIL.Globals.Contains(ir)) - toIL.Globals.Cache(ir, il); - - return ir; - } - } -} diff --git a/ZSharp.Runtime.IL/context/Context.IR2IL.cs b/ZSharp.Runtime.IL/context/Context.IR2IL.cs deleted file mode 100644 index 3a92da14..00000000 --- a/ZSharp.Runtime.IL/context/Context.IR2IL.cs +++ /dev/null @@ -1,117 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace ZSharp.Runtime.NET -{ - partial class Context - { - public IL.Module? Cache(IR.Module ir) - => toIL.Modules.Cache(ir); - - public bool Cache(IR.Module ir, [NotNullWhen(true)] out IL.Module? il) - => toIL.Modules.Cache(ir, out il); - - public IL.Module Cache(IR.Module ir, IL.Module il) - { - if (!toIR.Modules.Contains(il)) - toIR.Modules.Cache(il, ir); - - if (!toIL.Modules.Contains(ir)) - toIL.Modules.Cache(ir, il); - - return il; - } - - public Type? Cache(IR.IType ir) - => toIL.Types.Cache(ir); - - public bool Cache(IR.IType ir, [NotNullWhen(true)] out Type? il) - => toIL.Types.Cache(ir, out il); - - public Type Cache(IR.IType ir, Type il) - { - if (!toIR.Types.Contains(il)) - toIR.Types.Cache(il, ir); - - if (!toIL.Types.Contains(ir)) - toIL.Types.Cache(ir, il); - - return il; - } - - public Type? Cache(IR.OOPType ir) - => toIL.OOPTypes.Cache(ir); - - public bool Cache(IR.OOPType ir, [NotNullWhen(true)] out Type? il) - => toIL.OOPTypes.Cache(ir, out il); - - public Type Cache(IR.OOPType ir, Type il) - { - if (!toIR.OOPTypes.Contains(il)) - toIR.OOPTypes.Cache(il, ir); - - if (!toIL.OOPTypes.Contains(ir)) - toIL.OOPTypes.Cache(ir, il); - - return il; - } - - public IL.MethodBase? Cache(IR.ICallable ir) - => toIL.Callables.Cache(ir); - - public T? Cache(IR.ICallable ir) - where T : IL.MethodBase - => toIL.Callables.Cache(ir); - - public bool Cache(IR.ICallable ir, [NotNullWhen(true)] out IL.MethodBase? il) - => toIL.Callables.Cache(ir, out il); - - public bool Cache(IR.ICallable ir, [NotNullWhen(true)] out T? il) - where T : IL.MethodBase - => toIL.Callables.Cache(ir, out il); - - public IL.MethodBase Cache(IR.ICallable ir, IL.MethodBase il) - { - if (!toIR.Callables.Contains(il)) - toIR.Callables.Cache(il, ir); - - if (!toIL.Callables.Contains(ir)) - toIL.Callables.Cache(ir, il); - - return il; - } - - public IL.FieldInfo? Cache(IR.Field ir) - => toIL.Fields.Cache(ir); - - public bool Cache(IR.Field ir, [NotNullWhen(true)] out IL.FieldInfo? il) - => toIL.Fields.Cache(ir, out il); - - public IL.FieldInfo Cache(IR.Field ir, IL.FieldInfo il) - { - if (!toIR.Fields.Contains(il)) - toIR.Fields.Cache(il, ir); - - if (!toIL.Fields.Contains(ir)) - toIL.Fields.Cache(ir, il); - - return il; - } - - public IL.FieldInfo? Cache(IR.Global ir) - => toIL.Globals.Cache(ir); - - public bool Cache(IR.Global ir, [NotNullWhen(true)] out IL.FieldInfo? il) - => toIL.Globals.Cache(ir, out il); - - public IL.FieldInfo Cache(IR.Global ir, IL.FieldInfo il) - { - if (!toIR.Globals.Contains(il)) - toIR.Globals.Cache(il, ir); - - if (!toIL.Globals.Contains(ir)) - toIL.Globals.Cache(ir, il); - - return il; - } - } -} diff --git a/ZSharp.Runtime.IL/context/Context.cs b/ZSharp.Runtime.IL/context/Context.cs deleted file mode 100644 index 458a9d91..00000000 --- a/ZSharp.Runtime.IL/context/Context.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Runtime.NET -{ - public sealed partial class Context - { - - } -} diff --git a/ZSharp.Runtime.IL/context/caches/ContextCache.IL2IR.cs b/ZSharp.Runtime.IL/context/caches/ContextCache.IL2IR.cs deleted file mode 100644 index 25b4f973..00000000 --- a/ZSharp.Runtime.IL/context/caches/ContextCache.IL2IR.cs +++ /dev/null @@ -1,19 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Runtime.NET -{ - internal sealed class ContextCacheIL2IR - { - public Cache Types { get; } = []; - - public Cache Modules { get; } = []; - - public Cache OOPTypes { get; } = []; - - public Cache Callables { get; } = []; - - public Cache Fields { get; } = []; - - public Cache Globals { get; } = []; - } -} diff --git a/ZSharp.Runtime.IL/context/caches/ContextCache.IR2IL.cs b/ZSharp.Runtime.IL/context/caches/ContextCache.IR2IL.cs deleted file mode 100644 index a6699539..00000000 --- a/ZSharp.Runtime.IL/context/caches/ContextCache.IR2IL.cs +++ /dev/null @@ -1,19 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Runtime.NET -{ - internal sealed class ContextCacheIR2IL - { - public Cache Types { get; } = []; - - public Cache Modules { get; } = []; - - public Cache OOPTypes { get; } = []; - - public Cache Callables { get; } = []; - - public Cache Fields { get; } = []; - - public Cache Globals { get; } = []; - } -} diff --git a/ZSharp.Runtime.IL/il2ir/attributes/AliasAttribute.cs b/ZSharp.Runtime.IL/il2ir/attributes/AliasAttribute.cs deleted file mode 100644 index 078691ba..00000000 --- a/ZSharp.Runtime.IL/il2ir/attributes/AliasAttribute.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ZSharp.Runtime.NET.IL2IR -{ - [AttributeUsage( - AttributeTargets.Module | - AttributeTargets.Class | - AttributeTargets.Struct | - AttributeTargets.Enum | - AttributeTargets.Constructor | - AttributeTargets.Method | - AttributeTargets.Property, - AllowMultiple = false)] - public sealed class AliasAttribute : Attribute - { - public required string Name { get; set; } - } -} diff --git a/ZSharp.Runtime.IL/il2ir/attributes/HideInIRAttribute.cs b/ZSharp.Runtime.IL/il2ir/attributes/HideInIRAttribute.cs deleted file mode 100644 index d7035a33..00000000 --- a/ZSharp.Runtime.IL/il2ir/attributes/HideInIRAttribute.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace ZSharp.Runtime.NET.IL2IR -{ - public sealed class HideInIRAttribute : Attribute - { - } -} diff --git a/ZSharp.Runtime.IL/il2ir/attributes/KeywordParameterAttribute.cs b/ZSharp.Runtime.IL/il2ir/attributes/KeywordParameterAttribute.cs deleted file mode 100644 index 0d098bf0..00000000 --- a/ZSharp.Runtime.IL/il2ir/attributes/KeywordParameterAttribute.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Runtime.NET.IL2IR -{ - [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] - public sealed class KeywordParameterAttribute : Attribute - { - } -} diff --git a/ZSharp.Runtime.IL/il2ir/attributes/ModuleGlobalsAttribute.cs b/ZSharp.Runtime.IL/il2ir/attributes/ModuleGlobalsAttribute.cs deleted file mode 100644 index 803bf033..00000000 --- a/ZSharp.Runtime.IL/il2ir/attributes/ModuleGlobalsAttribute.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Runtime.NET.IL2IR -{ - [AttributeUsage(AttributeTargets.Class)] - public sealed class ModuleGlobalsAttribute : Attribute - { - } -} diff --git a/ZSharp.Runtime.IL/il2ir/core/BaseILLoader.cs b/ZSharp.Runtime.IL/il2ir/core/BaseILLoader.cs deleted file mode 100644 index 1280777a..00000000 --- a/ZSharp.Runtime.IL/il2ir/core/BaseILLoader.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace ZSharp.Runtime.NET.IL2IR -{ - internal abstract class BaseILLoader(ILLoader loader) - { - public ILLoader Loader { get; } = loader; - - public Context Context => Loader.Context; - } - - internal abstract class BaseILLoader(ILLoader loader, In @in, Out @out) - : BaseILLoader(loader) - { - public In Input { get; } = @in; - - public Out Output { get; } = @out; - - public abstract Out Load(); - } -} diff --git a/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs b/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs deleted file mode 100644 index 0cb97cb4..00000000 --- a/ZSharp.Runtime.IL/il2ir/core/ILLoader.cs +++ /dev/null @@ -1,128 +0,0 @@ -using ZSharp.IR; - -namespace ZSharp.Runtime.NET.IL2IR -{ - public sealed class ILLoader(Context context, RuntimeModule? runtimeModule = null) - { - public RuntimeModule RuntimeModule { get; } = runtimeModule ?? RuntimeModule.Standard; - - public Context Context { get; } = context; - - public IType LoadType(Type type) - { - if (Context.Cache(type, out var result)) - return result; - - if (type.IsTypeDefinition) - { - if (type.GenericTypeArguments.Length != 0) - throw new InvalidOperationException(); - - OOPType def; - - if (type.IsClass) def = new ClassLoader(this, type).Load(); - else if (type.IsInterface) def = new InterfaceLoader(this, type).Load(); - else if (type.IsEnum) def = new EnumerationLoader(this, type).Load(); - else if (type.IsValueType) def = new ValueTypeLoader(this, type).Load(); - else throw new ArgumentException("Type must be a type definition.", nameof(type)); - - return def switch - { - Class @class => new ClassReference(@class), - Interface @interface => new InterfaceReference(@interface), - EnumClass @enum => @enum, - IR.ValueType valueType => new ValueTypeReference(valueType), - _ => throw new NotSupportedException() - }; - } - - if (type.IsArray) - return LoadArrayType(type); - if (type.IsPointer) - return LoadPointerType(type); - if (type.IsByRef) - return LoadReferenceType(type); - - if (type.IsConstructedGenericType) - { - var definition = type.GetGenericTypeDefinition(); - - var definitionIR = LoadType(definition); - - var genericArguments = type.GenericTypeArguments.Select(LoadType).ToList(); - - if (definitionIR is not OOPTypeReference typeReference) - throw new ArgumentException("Type must be a type definition.", nameof(type)); - - return typeReference.Definition switch - { - Class @class => new ConstructedClass(@class) - { - Arguments = [.. genericArguments], - }, - Interface @interface => new ConstructedInterface(@interface) - { - Arguments = [.. genericArguments], - }, - IR.ValueType valueType => new ConstructedValueType(valueType) - { - Arguments = [.. genericArguments], - }, - _ => throw new NotImplementedException() - }; - } - - throw new(); - } - - public T LoadType(Type type) - where T : IType - => (T)LoadType(type); - - public Module LoadModule(IL.Module module) - { - return new ModuleLoader(this, module).Load(); - } - - private IType LoadArrayType(Type type) - { - var elementType = LoadType(type.GetElementType()!); - - return new ConstructedClass( - RuntimeModule.TypeSystem.Array - ) { - Arguments = [ - elementType - ] - }; - } - - private IType LoadPointerType(Type type) - { - var elementType = LoadType(type.GetElementType()!); - - return new ConstructedClass( - RuntimeModule.TypeSystem.Pointer - ) - { - Arguments = [ - elementType - ] - }; - } - - private IType LoadReferenceType(Type type) - { - var elementType = LoadType(type.GetElementType()!); - - return new ConstructedClass( - RuntimeModule.TypeSystem.Reference - ) - { - Arguments = [ - elementType - ] - }; - } - } -} diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs deleted file mode 100644 index 95911619..00000000 --- a/ZSharp.Runtime.IL/il2ir/loaders/ClassLoader.cs +++ /dev/null @@ -1,229 +0,0 @@ -using System.Reflection; -using ZSharp.IR; - -namespace ZSharp.Runtime.NET.IL2IR -{ - internal sealed class ClassLoader(ILLoader loader, Type input) - : BaseILLoader(loader, input, new(input.Name)) - { - private OOPTypeReference Self { get; set; } - - public override Class Load() - { - if (Context.Cache(Input, out var result)) - return result; - - Context.Cache(Input, Output); - - Self = new ClassReference(Output); - - LoadGenericParameters(); - - LoadBase(); - - LoadInterfaceImplementations(); - - LoadFields(); - - LoadProperties(); - - LoadConstructors(); - - LoadMethods(); - - LoadTypes(); - - return Output; - } - - private void LoadBase() - { - if (Input.BaseType is not null) - Output.Base = (OOPTypeReference)Loader.LoadType(Input.BaseType); - } - - private void LoadGenericParameters() - { - if (!Input.IsGenericTypeDefinition) - return; - - Output.Name = Input.Name.Split('`')[0]; - - foreach (var parameter in Input.GetGenericArguments()) - { - var genericParameter = new GenericParameter(parameter.Name); - Context.Cache(parameter, genericParameter); - Output.GenericParameters.Add(genericParameter); - } - - Self = new ConstructedClass(Output) - { - Arguments = [.. Output.GenericParameters] - }; - } - - private void LoadInterfaceImplementations() - { - foreach (var @interface in Input.GetInterfaces()) - LoadInterfaceImplementation(@interface, Input.GetInterfaceMap(@interface)); - } - - private void LoadFields() - { - foreach (var field in Input.GetFields()) - LoadField(field); - } - - private void LoadProperties() - { - foreach (var property in Input.GetProperties()) - LoadProperty(property); - } - - private void LoadConstructors() - { - foreach (var constructor in Input.GetConstructors()) - LoadConstructor(constructor); - } - - private void LoadMethods() - { - foreach (var method in Input.GetMethods()) - if (method.DeclaringType == Input) - LoadMethod(method); - } - - private void LoadTypes() - { - foreach (var nested in Input.GetNestedTypes()) - LoadTypeDefinition(nested); - } - - private void LoadInterfaceImplementation(Type @interface, IL.InterfaceMapping mapping) - { - if (mapping.InterfaceMethods.Length != mapping.TargetMethods.Length) - throw new InvalidOperationException("Interface mapping is invalid."); - - //throw new NotImplementedException(); - - //var implementation = new IR.InterfaceImplementation(Loader.LoadType(@interface)); - - //for (int i = 0; i < mapping.InterfaceMethods.Length; i++) - //{ - // var interfaceMethod = mapping.InterfaceMethods[i]; - // var targetMethod = mapping.TargetMethods[i]; - - // implementation.Implementations.Add( - // LoadMethod(interfaceMethod), - // LoadMethod(targetMethod) - // ); - //} - } - - private void LoadField(IL.FieldInfo field) - { - var result = new Field(field.Name, Loader.LoadType(field.FieldType)) - { - IsStatic = field.IsStatic, - IsReadOnly = field.IsInitOnly, - }; - - Output.Fields.Add(result); - } - - private void LoadProperty(IL.PropertyInfo property) - { - var result = new Property(property.Name, Loader.LoadType(property.PropertyType)) - { - Getter = property.GetMethod is null ? null : LoadMethod(property.GetMethod), - Setter = property.SetMethod is null ? null : LoadMethod(property.SetMethod), - }; - - Output.Properties.Add(result); - } - - private void LoadConstructor(IL.ConstructorInfo constructor) - { - var result = new Constructor(null) - { - Method = new(Loader.RuntimeModule.TypeSystem.Void), - }; - - Context.Cache(constructor, result.Method); - - if (!constructor.IsStatic) - result.Method.Signature.Args.Parameters.Add(new("this", Self)); - - foreach (var parameter in constructor.GetParameters()) - if (parameter.GetCustomAttribute() is not null) - result.Method.Signature.KwArgs.Parameters.Add(new(parameter.Name ?? throw new(), Loader.LoadType(parameter.ParameterType))); - else - result.Method.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); - - Output.Constructors.Add(result); - } - - private Method LoadMethod(IL.MethodInfo method) - { - List genericParameters = []; - - if (method.IsGenericMethodDefinition) - foreach (var genericParameter in method.GetGenericArguments()) - genericParameters.Add(Context.Cache(genericParameter, new IR.GenericParameter(genericParameter.Name))); - - var result = new Method(Loader.LoadType(method.ReturnType)) - { - Name = method.GetCustomAttribute()?.Name ?? method.Name, - }; - - Context.Cache(method, result); - - if (genericParameters.Count > 0) - result.GenericParameters.AddRange(genericParameters); - - if (!method.IsStatic) - result.Signature.Args.Parameters.Add(new("this", Self)); - else result.IsStatic = true; - - if (method.IsVirtual) - result.IsVirtual = true; - - foreach (var parameter in method.GetParameters()) - if (parameter.GetCustomAttribute() is not null) - result.Signature.KwArgs.Parameters.Add(new(parameter.Name ?? throw new(), Loader.LoadType(parameter.ParameterType))); - else - result.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); - - Output.Methods.Add(result); - - return result; - } - - private void LoadTypeDefinition(Type type) - { - if (!type.IsTypeDefinition) - throw new ArgumentException("Type must be a type definition.", nameof(type)); - - if (Context.Cache(type, out OOPType? result)) ; - else if (type.IsClass) result = LoadClass(type); - else if (type.IsInterface) result = LoadInterface(type); - else if (type.IsEnum) result = LoadEnum(type); - else if (type.IsValueType) result = LoadStruct(type); - else throw new NotImplementedException(); - - Output.NestedTypes.Add(result); - } - - private Class LoadClass(Type type) - => new ClassLoader(Loader, type).Load(); - - private Interface LoadInterface(Type type) - => new InterfaceLoader(Loader, type).Load(); - - private EnumClass LoadEnum(Type type) - => new EnumerationLoader(Loader, type).Load(); - - private IR.ValueType LoadStruct(Type type) - => new ValueTypeLoader(Loader, type).Load(); - } -} diff --git a/ZSharp.Runtime.IL/il2ir/loaders/EnumerationLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/EnumerationLoader.cs deleted file mode 100644 index 78a2612f..00000000 --- a/ZSharp.Runtime.IL/il2ir/loaders/EnumerationLoader.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Reflection; -using ZSharp.IR; - -namespace ZSharp.Runtime.NET.IL2IR -{ - internal sealed class EnumerationLoader(ILLoader loader, Type input) - : BaseILLoader(loader, input, new(input.Name)) - { - public override EnumClass Load() - { - if (Context.Cache(Input, out var result)) - return result; - - Context.Cache(Input, Output); - - Output.Type = Loader.LoadType(Enum.GetUnderlyingType(Input)); - - LoadValues(); - - return Output; - } - - private void LoadValues() - { - foreach (var (name, value) in - Enum.GetNames(Input).Zip( - [ ..Enum.GetValuesAsUnderlyingType(Input) ] - ) - ) - { - LoadValue(name, value); - } - } - - private void LoadValue(string name, object value) - { - Output.Values.Add( - new(name, LiteralLoader.Load(value)) - ); - } - } -} diff --git a/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs deleted file mode 100644 index 3e0f8a14..00000000 --- a/ZSharp.Runtime.IL/il2ir/loaders/InterfaceLoader.cs +++ /dev/null @@ -1,170 +0,0 @@ -using System.Reflection; -using ZSharp.IR; - -namespace ZSharp.Runtime.NET.IL2IR -{ - internal sealed class InterfaceLoader(ILLoader loader, Type input) - : BaseILLoader(loader, input, new(input.Name)) - { - private OOPTypeReference Self { get; set; } - - public override Interface Load() - { - if (Context.Cache(Input, out var result)) - return result; - - Context.Cache(Input, Output); - - Self = new InterfaceReference(Output); - - LoadGenericParameters(); - - LoadBase(); - - LoadInterfaceImplementations(); - - LoadProperties(); - - LoadMethods(); - - LoadTypes(); - - return Output; - } - - private void LoadBase() - { - foreach (var @interface in Input.GetInterfaces()) - Output.Bases.Add(Loader.LoadType>(@interface)); - } - - private void LoadGenericParameters() - { - if (!Input.IsGenericTypeDefinition) - return; - - Output.Name = Input.Name.Split('`')[0]; - - foreach (var parameter in Input.GetGenericArguments()) - { - var genericParameter = new IR.GenericParameter(parameter.Name); - Context.Cache(parameter, genericParameter); - Output.GenericParameters.Add(genericParameter); - } - - Self = new ConstructedInterface(Output) - { - Arguments = [.. Output.GenericParameters] - }; - } - - private void LoadInterfaceImplementations() - { - //foreach (var @interface in Input.GetInterfaces()) - // LoadInterfaceImplementation(@interface, Input.GetInterfaceMap(@interface)); - } - - private void LoadProperties() - { - foreach (var property in Input.GetProperties()) - LoadProperty(property); - } - - private void LoadMethods() - { - foreach (var method in Input.GetMethods()) - if (method.DeclaringType == Input) - LoadMethod(method); - } - - private void LoadTypes() - { - foreach (var nested in Input.GetNestedTypes()) - LoadTypeDefinition(nested); - } - - private void LoadInterfaceImplementation(Type @interface, IL.InterfaceMapping mapping) - { - if (mapping.InterfaceMethods.Length != mapping.TargetMethods.Length) - throw new InvalidOperationException("Interface mapping is invalid."); - - //throw new NotImplementedException(); - - //var implementation = new IR.InterfaceImplementation(Loader.LoadType(@interface)); - - //for (int i = 0; i < mapping.InterfaceMethods.Length; i++) - //{ - // var interfaceMethod = mapping.InterfaceMethods[i]; - // var targetMethod = mapping.TargetMethods[i]; - - // implementation.Implementations.Add( - // LoadMethod(interfaceMethod), - // LoadMethod(targetMethod) - // ); - //} - } - - private void LoadProperty(PropertyInfo property) - { - var result = new Property(property.Name, Loader.LoadType(property.PropertyType)) - { - Getter = property.GetMethod is null ? null : LoadMethod(property.GetMethod), - Setter = property.SetMethod is null ? null : LoadMethod(property.SetMethod), - }; - - // TODO: add property metadata - } - - private Method LoadMethod(MethodInfo method) - { - var result = new Method(Loader.LoadType(method.ReturnType)) - { - Name = method.GetCustomAttribute()?.Name ?? method.Name, - IsVirtual = true, - }; - - Context.Cache(method, result); - - if (!method.IsStatic) - result.Signature.Args.Parameters.Add(new("this", Self)); - - foreach (var parameter in method.GetParameters()) - if (parameter.GetCustomAttribute() is not null) - result.Signature.KwArgs.Parameters.Add(new(parameter.Name ?? throw new(), Loader.LoadType(parameter.ParameterType))); - else - result.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); - - Output.Methods.Add(result); - - return result; - } - - private void LoadTypeDefinition(Type type) - { - if (!type.IsTypeDefinition) - throw new ArgumentException("Type must be a type definition.", nameof(type)); - - if (Context.Cache(type, out OOPType? result)) ; - else if (type.IsClass) result = LoadClass(type); - else if (type.IsInterface) result = LoadInterface(type); - else if (type.IsEnum) result = LoadEnum(type); - else if (type.IsValueType) result = LoadStruct(type); - else throw new NotImplementedException(); - - // TODO: add nested types - //Output.NestedTypes.Add(result); - } - - private Class LoadClass(Type type) - => new ClassLoader(Loader, type).Load(); - - private Interface LoadInterface(Type type) - => new InterfaceLoader(Loader, type).Load(); - - private EnumClass LoadEnum(Type type) - => new EnumerationLoader(Loader, type).Load(); - - private IR.ValueType LoadStruct(Type type) - => new ValueTypeLoader(Loader, type).Load(); - } -} diff --git a/ZSharp.Runtime.IL/il2ir/loaders/LiteralLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/LiteralLoader.cs deleted file mode 100644 index ad304cba..00000000 --- a/ZSharp.Runtime.IL/il2ir/loaders/LiteralLoader.cs +++ /dev/null @@ -1,109 +0,0 @@ -using CommonZ.Utils; -using System.Runtime.CompilerServices; -using IRCode = CommonZ.Utils.Collection; -using VM = ZSharp.IR.VM; - -namespace ZSharp.Runtime.NET.IL2IR -{ - public static class LiteralLoader - { - public static IRCode Load(object? o) - { - return o switch - { - sbyte s8 => Load(s8), - byte u8 => Load(u8), - short s16 => Load(s16), - ushort u16 => Load(u16), - int s32 => Load(s32), - uint u32 => Load(u32), - long s64 => Load(s64), - ulong u64 => Load(u64), - float f32 => Load(f32), - double f64 => Load(f64), - bool b => Load(b), - char c => Load(c), - string s => Load(s), - IntPtr i => Load(i), - UIntPtr u => Load(u), - null => [ new VM.PutNull() ], - _ => throw new NotSupportedException(), - }; - } - - public static IRCode Load(sbyte v) - { - throw new NotSupportedException(); - } - - public static IRCode Load(byte v) - { - throw new NotSupportedException(); - } - - public static IRCode Load(short v) - { - throw new NotSupportedException(); - } - - public static IRCode Load(ushort v) - { - throw new NotSupportedException(); - } - - public static IRCode Load(int v) - => [ - new VM.PutInt32(v) - ]; - - public static IRCode Load(uint v) - { - throw new NotSupportedException(); - } - - public static IRCode Load(long v) - { - throw new NotSupportedException(); - } - - public static IRCode Load(ulong v) - { - throw new NotSupportedException(); - } - - public static IRCode Load(IntPtr v) - { - throw new NotSupportedException(); - } - - public static IRCode Load(UIntPtr v) - { - throw new NotSupportedException(); - } - - public static IRCode Load(float v) - => [ - new VM.PutFloat32(v) - ]; - - public static IRCode Load(double v) - { - throw new NotSupportedException(); - } - - public static IRCode Load(bool v) - => [ - new VM.PutBoolean(v) - ]; - - public static IRCode Load(char v) - { - throw new NotSupportedException(); - } - - public static IRCode Load(string v) - => [ - new VM.PutString(v) - ]; - } -} diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs deleted file mode 100644 index c4f8a4a2..00000000 --- a/ZSharp.Runtime.IL/il2ir/loaders/ModuleLoader.cs +++ /dev/null @@ -1,113 +0,0 @@ -using static System.Reflection.CustomAttributeExtensions; - -namespace ZSharp.Runtime.NET.IL2IR -{ - internal sealed class ModuleLoader(ILLoader loader, IL.Module input) - : BaseILLoader(loader, input, new(input.Name)) - { - public override IR.Module Load() - { - if (Input.GetCustomAttribute() is AliasAttribute alias) - Output.Name = alias.Name; - - if (Context.Cache(Input, out var result)) - return result; - Context.Cache(Input, Output); - - LoadFields(); - - LoadMethods(); - - LoadTypes(); - - return Output; - } - - private void LoadFields() - { - foreach (var field in Input.GetFields()) - LoadField(field); - } - - private void LoadMethods() - { - foreach (var method in Input.GetMethods()) - LoadMethod(method); - } - - private void LoadTypes() - { - foreach (var type in Input.GetTypes()) - if (type.GetCustomAttribute() is null) - LoadTypeDefinition(type); - } - - private void LoadField(IL.FieldInfo field) - { - var global = new IR.Global(field.Name, Loader.LoadType(field.FieldType)) - { - //IsReadOnly = field.IsInitOnly, - }; - - Output.Globals.Add(global); - } - - private void LoadMethod(IL.MethodInfo method) - { - var function = new IR.Function(Loader.RuntimeModule.TypeSystem.Void) - { - Name = method.GetCustomAttribute() is AliasAttribute alias ? alias.Name : method.Name, - }; - - if (method.ContainsGenericParameters) - foreach (var genericParameter in method.GetGenericArguments()) - function.GenericParameters.Add(Context.Cache(genericParameter, new(genericParameter.Name))); - - function.ReturnType = Loader.LoadType(method.ReturnType); - - foreach (var parameter in method.GetParameters()) - function.Signature.Args.Parameters.Add(new(parameter.Name!, Loader.LoadType(parameter.ParameterType))); - - Output.Functions.Add(function); - - Context.Cache(function, method); - } - - private void LoadTypeDefinition(Type type) - { - if (!type.IsTypeDefinition) - throw new ArgumentException("Type must be a type definition.", nameof(type)); - - if (type.IsClass && type.IsSealed && type.IsAbstract && type.GetCustomAttribute() is not null) - LoadGlobals(type); - - else if (type.IsClass) LoadClass(type); - else if (type.IsInterface) LoadInterface(type); - else if (type.IsEnum) LoadEnum(type); - else if (type.IsValueType) LoadStruct(type); - - else throw new NotImplementedException(); - } - - private void LoadGlobals(Type type) - { - foreach (var method in type.GetMethods()) - if (method.IsStatic) - LoadMethod(method); - } - - private void LoadClass(Type type) - => Output.Types.Add(new ClassLoader(Loader, type).Load()); - - private void LoadInterface(Type type) - => Output.Types.Add(new InterfaceLoader(Loader, type).Load()); - - private void LoadEnum(Type type) - => Output.Types.Add(new EnumerationLoader(Loader, type).Load()); - - private void LoadStruct(Type type) - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Runtime.IL/il2ir/loaders/ValueTypeLoader.cs b/ZSharp.Runtime.IL/il2ir/loaders/ValueTypeLoader.cs deleted file mode 100644 index 93752e25..00000000 --- a/ZSharp.Runtime.IL/il2ir/loaders/ValueTypeLoader.cs +++ /dev/null @@ -1,230 +0,0 @@ -using System.Reflection; -using ZSharp.IR; - -using ValueType = ZSharp.IR.ValueType; - -namespace ZSharp.Runtime.NET.IL2IR -{ - internal sealed class ValueTypeLoader(ILLoader loader, Type input) - : BaseILLoader(loader, input, new(input.Name)) - { - private OOPTypeReference Self { get; set; } - - public override ValueType Load() - { - if (Context.Cache(Input, out var result)) - return result; - - Context.Cache(Input, Output); - - Self = new ValueTypeReference(Output); - - //LoadGenericParameters(); - - //if (!Input.IsInterface) - // LoadInterfaceImplementations(); - - //LoadFields(); - - //LoadProperties(); - - //LoadConstructors(); - - //LoadMethods(); - - //LoadTypes(); - - return Output; - } - - //private void LoadGenericParameters() - //{ - // //if (!Input.IsGenericTypeDefinition) - // // return; - - // //Output.Name = Input.Name.Split('`')[0]; - - // //foreach (var parameter in Input.GetGenericArguments()) - // //{ - // // var genericParameter = new GenericParameter(parameter.Name); - // // Context.Cache(parameter, genericParameter); - // // Output.GenericParameters.Add(genericParameter); - // //} - - // //Self = new ConstructedClass(Output) - // //{ - // // Arguments = [.. Output.GenericParameters] - // //}; - //} - - //private void LoadInterfaceImplementations() - //{ - // foreach (var @interface in Input.GetInterfaces()) - // LoadInterfaceImplementation(@interface, Input.GetInterfaceMap(@interface)); - //} - - //private void LoadFields() - //{ - // foreach (var field in Input.GetFields()) - // LoadField(field); - //} - - //private void LoadProperties() - //{ - // foreach (var property in Input.GetProperties()) - // LoadProperty(property); - //} - - //private void LoadConstructors() - //{ - // foreach (var constructor in Input.GetConstructors()) - // LoadConstructor(constructor); - //} - - //private void LoadMethods() - //{ - // foreach (var method in Input.GetMethods()) - // if (method.DeclaringType == Input) - // LoadMethod(method); - //} - - //private void LoadTypes() - //{ - // foreach (var nested in Input.GetNestedTypes()) - // LoadTypeDefinition(nested); - //} - - //private void LoadInterfaceImplementation(Type @interface, IL.InterfaceMapping mapping) - //{ - // if (mapping.InterfaceMethods.Length != mapping.TargetMethods.Length) - // throw new InvalidOperationException("Interface mapping is invalid."); - - // throw new NotImplementedException(); - - // var implementation = new IR.InterfaceImplementation(Loader.LoadType(@interface)); - - // for (int i = 0; i < mapping.InterfaceMethods.Length; i++) - // { - // var interfaceMethod = mapping.InterfaceMethods[i]; - // var targetMethod = mapping.TargetMethods[i]; - - // implementation.Implementations.Add( - // LoadMethod(interfaceMethod), - // LoadMethod(targetMethod) - // ); - // } - //} - - //private void LoadField(IL.FieldInfo field) - //{ - // var result = new Field(field.Name, Loader.LoadType(field.FieldType)) - // { - // IsStatic = field.IsStatic, - // IsReadOnly = field.IsInitOnly, - // }; - - // Output.Fields.Add(result); - //} - - //private void LoadProperty(IL.PropertyInfo property) - //{ - // var result = new Property(property.Name, Loader.LoadType(property.PropertyType)) - // { - // Getter = property.GetMethod is null ? null : LoadMethod(property.GetMethod), - // Setter = property.SetMethod is null ? null : LoadMethod(property.SetMethod), - // }; - - // Output.Properties.Add(result); - //} - - //private void LoadConstructor(IL.ConstructorInfo constructor) - //{ - // var result = new Constructor(null) - // { - // Method = new(Loader.RuntimeModule.TypeSystem.Void), - // }; - - // Context.Cache(constructor, result.Method); - - // if (!constructor.IsStatic) - // result.Method.Signature.Args.Parameters.Add(new("this", Self)); - - // foreach (var parameter in constructor.GetParameters()) - // if (parameter.GetCustomAttribute() is not null) - // result.Method.Signature.KwArgs.Parameters.Add(new(parameter.Name ?? throw new(), Loader.LoadType(parameter.ParameterType))); - // else - // result.Method.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); - - // Output.Constructors.Add(result); - //} - - //private Method LoadMethod(IL.MethodInfo method) - //{ - // List genericParameters = []; - - // if (method.IsGenericMethodDefinition) - // foreach (var genericParameter in method.GetGenericArguments()) - // genericParameters.Add(Context.Cache(genericParameter, new IR.GenericParameter(genericParameter.Name))); - - // var result = new Method(Loader.LoadType(method.ReturnType)) - // { - // Name = method.GetCustomAttribute()?.Name ?? method.Name, - // }; - - // Context.Cache(method, result); - - // if (genericParameters.Count > 0) - // result.GenericParameters.AddRange(genericParameters); - - // if (!method.IsStatic) - // result.Signature.Args.Parameters.Add(new("this", Self)); - // else result.IsStatic = true; - - // if (method.IsVirtual) - // result.IsVirtual = true; - - // foreach (var parameter in method.GetParameters()) - // if (parameter.GetCustomAttribute() is not null) - // result.Signature.KwArgs.Parameters.Add(new(parameter.Name ?? throw new(), Loader.LoadType(parameter.ParameterType))); - // else - // result.Signature.Args.Parameters.Add(new(parameter.Name ?? string.Empty, Loader.LoadType(parameter.ParameterType))); - - // Output.Methods.Add(result); - - // return result; - //} - - //private void LoadTypeDefinition(Type type) - //{ - // if (!type.IsTypeDefinition) - // throw new ArgumentException("Type must be a type definition.", nameof(type)); - - // if (Context.Cache(type, out OOPType? result)) ; - // else if (type.IsClass) result = LoadClass(type); - // else if (type.IsInterface) result = LoadInterface(type); - // else if (type.IsEnum) result = LoadEnum(type); - // else if (type.IsValueType) result = LoadStruct(type); - // else throw new NotImplementedException(); - - // Output.NestedTypes.Add(result); - //} - - //private Class LoadClass(Type type) - // => new ClassLoader(Loader, type).Load(); - - //private Interface LoadInterface(Type type) - // => new InterfaceLoader(Loader, type).Load(); - - //private EnumClass LoadEnum(Type type) - //{ - // //return new(); - // throw new NotImplementedException(); - //} - - //private IR.ValueType LoadStruct(Type type) - //{ - // return new(); - // throw new NotImplementedException(); - //} - } -} diff --git a/ZSharp.Runtime.IL/ir2il/Constants.cs b/ZSharp.Runtime.IL/ir2il/Constants.cs deleted file mode 100644 index 153078fd..00000000 --- a/ZSharp.Runtime.IL/ir2il/Constants.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal static class Constants - { - public const string GlobalsTypeName = ""; - - public const string AnonymousAssembly = ""; - - public const string AnonymousClass = ""; - - public const string AnonymousInterface = ""; - - public const string AnonymousMethod = ""; - - public const string AnonymousModule = ""; - } -} diff --git a/ZSharp.Runtime.IL/ir2il/SignatureExtensions.cs b/ZSharp.Runtime.IL/ir2il/SignatureExtensions.cs deleted file mode 100644 index 7fafc80f..00000000 --- a/ZSharp.Runtime.IL/ir2il/SignatureExtensions.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal static class SignatureExtensions - { - public static IR.Parameter[] GetParameters(this IR.Signature signature) - => [ - ..signature.Args.Parameters, - ..(signature.IsVarArgs ? new IR.Parameter[] { signature.Args.Var! } : []), - ..signature.KwArgs.Parameters, - ..(signature.IsVarKwArgs ? new IR.Parameter[] { signature.KwArgs.Var! } : []) - ]; - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code contexts/FunctionCodeContext.cs b/ZSharp.Runtime.IL/ir2il/code contexts/FunctionCodeContext.cs deleted file mode 100644 index 8ee7b601..00000000 --- a/ZSharp.Runtime.IL/ir2il/code contexts/FunctionCodeContext.cs +++ /dev/null @@ -1,74 +0,0 @@ -using CommonZ.Utils; -using ZSharp.IR; - -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - internal sealed class FunctionCodeContext(IRLoader loader, IL.Emit.ILGenerator il, Function function) - : ICodeContext - , IBranchingCodeContext - , IFrameCodeContext - , IFunctionalCodeContext - { - private readonly Mapping locals = []; - private readonly Mapping parameters = []; - private readonly Mapping labels = []; - - public IL.Emit.ILGenerator IL { get; } = il; - - public CodeStack Stack { get; } = new(); - - public IRLoader Loader { get; } = loader; - - public Function Function { get; } = function; - - void IBranchingCodeContext.AddBranchTarget(IR.VM.Instruction target) - => labels[target] = IL.DefineLabel(); - - IL.Emit.Label IBranchingCodeContext.GetBranchTarget(IR.VM.Instruction target) - => labels[target]; - - Local IFrameCodeContext.GetLocal(IR.VM.Local local) - => locals[local]; - - Parameter IFrameCodeContext.GetParameter(IR.Parameter parameter) - => parameters[parameter]; - - private void SetupFromIR() - { - foreach (var parameter in Function.Signature.GetParameters()) - parameters[parameter] = new() - { - Index = parameter.Index, - Name = parameter.Name, - Type = Loader.LoadType(parameter.Type) - }; - - if (Function.HasBody && Function.Body.HasLocals) - foreach (var local in Function.Body.Locals) - locals[local] = new() - { - Index = local.Index, - Name = local.Name, - Type = Loader.LoadType(local.Type) - }; - } - - public static FunctionCodeContext From(IRLoader loader, IL.Emit.ConstructorBuilder constructor, Function function) - { - var context = new FunctionCodeContext(loader, constructor.GetILGenerator(), function); - - context.SetupFromIR(); - - return context; - } - - public static FunctionCodeContext From(IRLoader loader, IL.Emit.MethodBuilder method, Function function) - { - var context = new FunctionCodeContext(loader, method.GetILGenerator(), function); - - context.SetupFromIR(); - - return context; - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code contexts/UnboundCodeContext.cs b/ZSharp.Runtime.IL/ir2il/code contexts/UnboundCodeContext.cs deleted file mode 100644 index 272f2c85..00000000 --- a/ZSharp.Runtime.IL/ir2il/code contexts/UnboundCodeContext.cs +++ /dev/null @@ -1,23 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - internal sealed class UnboundCodeContext(IRLoader loader, IL.Emit.ILGenerator il) - : ICodeContext - , IBranchingCodeContext - { - private readonly Mapping labels = []; - - public IL.Emit.ILGenerator IL { get; } = il; - - public CodeStack Stack { get; } = new(); - - public IRLoader Loader { get; } = loader; - - void IBranchingCodeContext.AddBranchTarget(IR.VM.Instruction target) - => labels[target] = IL.DefineLabel(); - - IL.Emit.Label IBranchingCodeContext.GetBranchTarget(IR.VM.Instruction target) - => labels[target]; - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/CodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/CodeCompiler.cs deleted file mode 100644 index d76f0907..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/CodeCompiler.cs +++ /dev/null @@ -1,70 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - public sealed class CodeCompiler(ICodeContext context) - { - public ICodeContext Context { get; } = context; - - public void CompileCode(Collection instructions) - { - if (Context is IBranchingCodeContext branchingContext) - { - foreach (var instruction in instructions) - branchingContext.AddBranchTarget(instruction); - - foreach (var instruction in instructions) - { - Context.IL.MarkLabel(branchingContext.GetBranchTarget(instruction)); - - Compile(instruction); - } - } else - foreach (var instruction in instructions) - Compile(instruction); - } - - private void Compile(IR.VM.Instruction instruction) - { - switch (instruction) - { - case IR.VM.Call call: CodeCompiler_Impl.Compile(RequireContext(), call); break; - case IR.VM.CallIndirect callIndirect: CodeCompiler_Impl.Compile(RequireContext(), callIndirect); break; - case IR.VM.CallVirtual callVirtual: CodeCompiler_Impl.Compile(RequireContext(), callVirtual); break; - case IR.VM.CastReference castReference: CodeCompiler_Impl.Compile(RequireContext(), castReference); break; - case IR.VM.CreateInstance createInstance: CodeCompiler_Impl.Compile(RequireContext(), createInstance); break; - case IR.VM.Dup dup: CodeCompiler_Impl.Compile(RequireContext(), dup); break; - case IR.VM.GetArgument getArgument: CodeCompiler_Impl.Compile(RequireContext(), getArgument); break; - //case IR.VM.GetClass getClass: CodeCompiler_Impl.Compile(RequireContext(), getClass); break; - case IR.VM.GetField getField: CodeCompiler_Impl.Compile(RequireContext(), getField); break; - case IR.VM.GetGlobal getGlobal: CodeCompiler_Impl.Compile(RequireContext(), getGlobal); break; - case IR.VM.GetLocal getLocal: CodeCompiler_Impl.Compile(RequireContext(), getLocal); break; - //case IR.VM.GetObject getObject: CodeCompiler_Impl.Compile(RequireContext(), getObject); break; - case IR.VM.IsNotNull isNotNull: CodeCompiler_Impl.Compile(RequireContext(), isNotNull); break; - case IR.VM.IsNull isNull: CodeCompiler_Impl.Compile(RequireContext(), isNull); break; - case IR.VM.Jump jump: CodeCompiler_Impl.Compile(RequireContext(), jump); break; - case IR.VM.JumpIfTrue jumpIfTrue: CodeCompiler_Impl.Compile(RequireContext(), jumpIfTrue); break; - case IR.VM.JumpIfFalse jumpIfFalse: CodeCompiler_Impl.Compile(RequireContext(), jumpIfFalse); break; - case IR.VM.Nop nop: CodeCompiler_Impl.Compile(RequireContext(), nop); break; - case IR.VM.Pop pop: CodeCompiler_Impl.Compile(RequireContext(), pop); break; - case IR.VM.PutBoolean putBoolean: CodeCompiler_Impl.Compile(RequireContext(), putBoolean); break; - case IR.VM.PutFloat32 putFloat32: CodeCompiler_Impl.Compile(RequireContext(), putFloat32); break; - case IR.VM.PutInt32 putInt32: CodeCompiler_Impl.Compile(RequireContext(), putInt32); break; - case IR.VM.PutNull putNull: CodeCompiler_Impl.Compile(RequireContext(), putNull); break; - case IR.VM.PutString putString: CodeCompiler_Impl.Compile(RequireContext(), putString); break; - case IR.VM.Return @return: CodeCompiler_Impl.Compile(RequireContext(), @return); break; - case IR.VM.SetArgument setArgument: CodeCompiler_Impl.Compile(RequireContext(), setArgument); break; - case IR.VM.SetField setField: CodeCompiler_Impl.Compile(RequireContext(), setField); break; - case IR.VM.SetGlobal setGlobal: CodeCompiler_Impl.Compile(RequireContext(), setGlobal); break; - case IR.VM.SetLocal setLocal: CodeCompiler_Impl.Compile(RequireContext(), setLocal); break; - case IR.VM.Swap swap: CodeCompiler_Impl.Compile(RequireContext(), swap); break; - - default: throw new NotImplementedException(); - } - } - - private T RequireContext() - where T : ICodeContext - => Context is T required ? required : throw new InvalidOperationException(); - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/branching/BranchingCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/branching/BranchingCodeCompiler.cs deleted file mode 100644 index fa6d7497..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/branching/BranchingCodeCompiler.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - internal static partial class CodeCompiler_Impl - { - public static void Compile(IBranchingCodeContext ctx, IR.VM.Jump jump) - { - ctx.IL.Emit(IL.Emit.OpCodes.Br, ctx.GetBranchTarget(jump.Target)); - } - - public static void Compile(IBranchingCodeContext ctx, IR.VM.JumpIfTrue jump) - { - ctx.IL.Emit(IL.Emit.OpCodes.Brtrue, ctx.GetBranchTarget(jump.Target)); - - ctx.Stack.Pop(typeof(bool)); - } - - public static void Compile(IBranchingCodeContext ctx, IR.VM.JumpIfFalse jump) - { - ctx.IL.Emit(IL.Emit.OpCodes.Brfalse, ctx.GetBranchTarget(jump.Target)); - - ctx.Stack.Pop(typeof(bool)); - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/branching/IBranchingCodeContext.cs b/ZSharp.Runtime.IL/ir2il/code/branching/IBranchingCodeContext.cs deleted file mode 100644 index d24e8d48..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/branching/IBranchingCodeContext.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - public interface IBranchingCodeContext - : ICodeContext - { - public void AddBranchTarget(IR.VM.Instruction target); - - public IL.Emit.Label GetBranchTarget(IR.VM.Instruction target); - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/core/CodeStack.cs b/ZSharp.Runtime.IL/ir2il/code/core/CodeStack.cs deleted file mode 100644 index f2c2aff4..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/core/CodeStack.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - public sealed class CodeStack - { - private readonly Stack ilStack = []; - - public void Dup() - => ilStack.Push(ilStack.Peek()); - - public void Put(Type type) - => ilStack.Push(type); - - public Type Pop() => ilStack.Pop(); - - public Type Pop(Type expect) - { - var result = Pop(); - if (result != expect) throw new(); - return result; - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/core/ICodeContext.cs b/ZSharp.Runtime.IL/ir2il/code/core/ICodeContext.cs deleted file mode 100644 index 2aaebf0d..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/core/ICodeContext.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - public interface ICodeContext - { - public IL::Emit.ILGenerator IL { get; } - - public CodeStack Stack { get; } - - public IRLoader Loader { get; } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/frame/FrameCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/frame/FrameCodeCompiler.cs deleted file mode 100644 index 5496b36e..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/frame/FrameCodeCompiler.cs +++ /dev/null @@ -1,73 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - internal static partial class CodeCompiler_Impl - { - public static void Compile(IFrameCodeContext ctx, IR.VM.GetArgument get) - { - var parameter = ctx.GetParameter(get.Argument); - var index = parameter.Index; - - if (index == 0) - ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_0); - else if (index == 1) - ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_1); - else if (index == 2) - ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_2); - else if (index == 3) - ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_3); - else if (index <= byte.MaxValue) - ctx.IL.Emit(IL.Emit.OpCodes.Ldarg_S, (byte)index); - else - ctx.IL.Emit(IL.Emit.OpCodes.Ldarg, index); - - ctx.Stack.Put(parameter.Type); - } - - public static void Compile(IFrameCodeContext ctx, IR.VM.GetLocal get) - { - var l = ctx.GetLocal(get.Local); - var index = l.Index; - - if (index == 0) - ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_0); - else if (index == 1) - ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_1); - else if (index == 2) - ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_2); - else if (index == 3) - ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_3); - else if (index <= byte.MaxValue) - ctx.IL.Emit(IL.Emit.OpCodes.Ldloc_S, (byte)index); - else - ctx.IL.Emit(IL.Emit.OpCodes.Ldloc, index); - - ctx.Stack.Put(l.Type); - } - - public static void Compile(IFrameCodeContext ctx, IR.VM.SetArgument set) - { - var parameter = ctx.GetParameter(set.Argument); - var index = parameter.Index; - - if (index <= byte.MaxValue) - ctx.IL.Emit(IL.Emit.OpCodes.Starg_S, (byte)index); - else - ctx.IL.Emit(IL.Emit.OpCodes.Starg, index); - - ctx.Stack.Pop(parameter.Type); - } - - public static void Compile(IFrameCodeContext ctx, IR.VM.SetLocal set) - { - var local = ctx.GetLocal(set.Local); - var index = local.Index; - - if (index <= byte.MaxValue) - ctx.IL.Emit(IL.Emit.OpCodes.Stloc_S, (byte)index); - else - ctx.IL.Emit(IL.Emit.OpCodes.Stloc, index); - - ctx.Stack.Pop(local.Type); - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/frame/IFrameCodeContext.cs b/ZSharp.Runtime.IL/ir2il/code/frame/IFrameCodeContext.cs deleted file mode 100644 index 5df96bdc..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/frame/IFrameCodeContext.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - public interface IFrameCodeContext - : ICodeContext - { - public Parameter GetParameter(IR.Parameter parameter); - - public Local GetLocal(IR.VM.Local local); - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/frame/Local.cs b/ZSharp.Runtime.IL/ir2il/code/frame/Local.cs deleted file mode 100644 index 0ed945e9..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/frame/Local.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - public sealed class Local - { - public required string Name { get; init; } - - public required int Index { get; init; } - - public required Type Type { get; init; } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/frame/Parameter.cs b/ZSharp.Runtime.IL/ir2il/code/frame/Parameter.cs deleted file mode 100644 index 286358c8..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/frame/Parameter.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - public sealed class Parameter - { - public required string Name { get; init; } - - public required int Index { get; init; } - - public required Type Type { get; init; } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/functional/FunctionalCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/functional/FunctionalCodeCompiler.cs deleted file mode 100644 index 5f016e91..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/functional/FunctionalCodeCompiler.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - internal static partial class CodeCompiler_Impl - { - public static void Compile(ICodeContext ctx, IR.VM.Call call) - { - var callable = ctx.Loader.LoadReference(call.Callable); - - foreach (var parameter in call.Callable.Signature.GetParameters()) - ctx.Stack.Pop(ctx.Loader.LoadType(parameter.Type)); - - if (callable is IL.MethodInfo method) - { - ctx.IL.Emit(IL.Emit.OpCodes.Call, method); - - if (method.ReturnType != typeof(void)) - ctx.Stack.Put(method.ReturnType); - } - else if (callable is IL.ConstructorInfo constructor) - ctx.IL.Emit(IL.Emit.OpCodes.Call, constructor); - else throw new($"Unknown callable type: {callable.GetType()}"); - } - - public static void Compile(ICodeContext ctx, IR.VM.CallIndirect call) - { - throw new NotImplementedException(); - } - - public static void Compile(ICodeContext ctx, IR.VM.Return _) - { - ctx.IL.Emit(IL.Emit.OpCodes.Ret); - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/functional/IFunctionalCodeContext.cs b/ZSharp.Runtime.IL/ir2il/code/functional/IFunctionalCodeContext.cs deleted file mode 100644 index 4b6c65a5..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/functional/IFunctionalCodeContext.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - public interface IFunctionalCodeContext - : ICodeContext - { - public IR.Function Function { get; } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/modular/ModularCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/modular/ModularCodeCompiler.cs deleted file mode 100644 index f8dfcab7..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/modular/ModularCodeCompiler.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - internal static partial class CodeCompiler_Impl - { - public static void Compile(ICodeContext ctx, IR.VM.GetGlobal get) - { - if (!ctx.Loader.Context.Cache(get.Global, out var global)) - throw new(); - - ctx.IL.Emit(IL.Emit.OpCodes.Ldsfld, global); - - ctx.Stack.Put(global.FieldType); - } - - public static void Compile(ICodeContext ctx, IR.VM.SetGlobal set) - { - if (!ctx.Loader.Context.Cache(set.Global, out var global)) - throw new(); - - ctx.IL.Emit(IL.Emit.OpCodes.Stsfld, global); - - ctx.Stack.Pop(global.FieldType); - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/object/OOPCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/object/OOPCodeCompiler.cs deleted file mode 100644 index 4b2c44b1..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/object/OOPCodeCompiler.cs +++ /dev/null @@ -1,59 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - internal static partial class CodeCompiler_Impl - { - public static void Compile(ICodeContext ctx, IR.VM.CallVirtual callVirtual) - { - var method = ctx.Loader.LoadReference(callVirtual.Method); - - if (!method.IsVirtual && !method.IsAbstract) - throw new($"Method {method} is not virtual or abstract!"); - - ctx.IL.Emit(IL.Emit.OpCodes.Callvirt, method); - - if (method.ReturnType != typeof(void)) - ctx.Stack.Put(method.ReturnType); - } - - public static void Compile(ICodeContext ctx, IR.VM.CastReference castReference) - { - var targetType = ctx.Loader.LoadType(castReference.Type); - - ctx.IL.Emit(IL.Emit.OpCodes.Isinst, targetType); - - ctx.Stack.Pop(); - ctx.Stack.Put(targetType); - } - - public static void Compile(ICodeContext ctx, IR.VM.CreateInstance createInstance) - { - var constructor = ctx.Loader.LoadReference(createInstance.Constructor); - - ctx.IL.Emit(IL.Emit.OpCodes.Newobj, constructor); - - ctx.Stack.Put(constructor.DeclaringType ?? throw new()); - } - - public static void Compile(ICodeContext ctx, IR.VM.GetField get) - { - var field = ctx.Loader.LoadReference(get.Field); - - ctx.IL.Emit(field.IsStatic ? IL.Emit.OpCodes.Ldsfld : IL.Emit.OpCodes.Ldfld, field); - - if (!field.IsStatic) - ctx.Stack.Pop(field.DeclaringType ?? throw new()); - ctx.Stack.Put(field.FieldType); - } - - public static void Compile(ICodeContext ctx, IR.VM.SetField set) - { - var field = ctx.Loader.LoadReference(set.Field); - - ctx.IL.Emit(field.IsStatic ? IL.Emit.OpCodes.Stsfld : IL.Emit.OpCodes.Stfld, field); - - ctx.Stack.Pop(); - if (!field.IsStatic) - ctx.Stack.Pop(field.DeclaringType ?? throw new()); - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/code/stack/StackCodeCompiler.cs b/ZSharp.Runtime.IL/ir2il/code/stack/StackCodeCompiler.cs deleted file mode 100644 index b9d382f2..00000000 --- a/ZSharp.Runtime.IL/ir2il/code/stack/StackCodeCompiler.cs +++ /dev/null @@ -1,82 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL.Code -{ - internal static partial class CodeCompiler_Impl - { - public static void Compile(ICodeContext ctx, IR.VM.Dup _) - { - ctx.IL.Emit(IL.Emit.OpCodes.Dup); - - ctx.Stack.Dup(); - } - - public static void Compile(ICodeContext ctx, IR.VM.IsNotNull _) - { - ctx.IL.Emit(IL.Emit.OpCodes.Ldnull); - ctx.IL.Emit(IL.Emit.OpCodes.Cgt_Un); - - ctx.Stack.Pop(); - ctx.Stack.Put(typeof(bool)); - } - - public static void Compile(ICodeContext ctx, IR.VM.IsNull _) - { - ctx.IL.Emit(IL.Emit.OpCodes.Ldnull); - ctx.IL.Emit(IL.Emit.OpCodes.Ceq); - - ctx.Stack.Pop(); - ctx.Stack.Put(typeof(bool)); - } - - public static void Compile(ICodeContext ctx, IR.VM.Nop _) - { - ctx.IL.Emit(IL.Emit.OpCodes.Nop); - } - - public static void Compile(ICodeContext ctx, IR.VM.Pop _) - { - ctx.IL.Emit(IL.Emit.OpCodes.Pop); - - ctx.Stack.Pop(); - } - - public static void Compile(ICodeContext ctx, IR.VM.PutBoolean put) - { - ctx.IL.Emit(put.Value ? IL.Emit.OpCodes.Ldc_I4_1 : IL.Emit.OpCodes.Ldc_I4_0); - - ctx.Stack.Put(typeof(bool)); - } - - public static void Compile(ICodeContext ctx, IR.VM.PutFloat32 put) - { - ctx.IL.Emit(IL.Emit.OpCodes.Ldc_R4, put.Value); - - ctx.Stack.Put(typeof(float)); - } - - public static void Compile(ICodeContext ctx, IR.VM.PutInt32 put) - { - ctx.IL.Emit(IL.Emit.OpCodes.Ldc_I4, put.Value); - - ctx.Stack.Put(typeof(int)); - } - - public static void Compile(ICodeContext ctx, IR.VM.PutNull _) - { - ctx.IL.Emit(IL.Emit.OpCodes.Ldnull); - - ctx.Stack.Put(typeof(object)); - } - - public static void Compile(ICodeContext ctx, IR.VM.PutString put) - { - ctx.IL.Emit(IL.Emit.OpCodes.Ldstr, put.Value); - - ctx.Stack.Put(typeof(string)); - } - - public static void Compile(ICodeContext ctx, IR.VM.Swap _) - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/core/BaseIRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/BaseIRLoader.cs deleted file mode 100644 index 7886dea9..00000000 --- a/ZSharp.Runtime.IL/ir2il/core/BaseIRLoader.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal abstract class BaseIRLoader(IRLoader loader) - { - public IRLoader Loader { get; } = loader; - - public Context Context => Loader.Context; - } - - internal abstract class BaseIRLoader(IRLoader loader, In @in, Out @out) - : BaseIRLoader(loader) - { - public In Input { get; } = @in; - - public Out Output { get; } = @out; - } -} diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.RuntimeServices.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.RuntimeServices.cs deleted file mode 100644 index bcc96830..00000000 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.RuntimeServices.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System.Reflection; -using System.Reflection.Emit; -using ZSharp.Objects; - -namespace ZSharp.Runtime.NET.IR2IL -{ - /// - /// Wraps an IR module in a C# module. - /// - public partial class IRLoader - { - private static readonly Dictionary typeObjects = []; - - private ModuleBuilder moduleBuilder = AssemblyBuilder.DefineDynamicAssembly( - new(Constants.AnonymousAssembly), AssemblyBuilderAccess.RunAndCollect - ).DefineDynamicModule("[ZSharp.Runtime.IL]::"); - - public static object _GetTypeObject(int objectId) - => typeObjects[objectId]; - - public int GetTypeObject(IR.OOPTypeReference @class) - { - var type = LoadTypeReference(@class); - - if (!HasTypeObject(type.GetHashCode())) - { - var typeObjectClass = CreateTypeObjectClass(@class); - var typeObject = Activator.CreateInstance(typeObjectClass); - SetTypeObject(type.GetHashCode(), typeObject ?? throw new()); - } - - return type.GetHashCode(); - } - - public object GetTypeObject(int objectId) - => typeObjects[objectId]; - - public bool HasTypeObject(int objectId) - => typeObjects.ContainsKey(objectId); - - public void SetTypeObject(int objectId, object @object) - => typeObjects[objectId] = (TypeObject)@object; - - private Type CreateTypeObjectClass(IR.OOPTypeReference @class) - { - if (@class.Definition.HasGenericParameters) - throw new NotImplementedException(); - - // Define the new type that inherits Base - var typeBuilder = moduleBuilder.DefineType("Derived", - TypeAttributes.Public | TypeAttributes.Class, - typeof(TypeObject) // base type - ); - - // Define constructor parameters - Type[] ctorParams = { typeof(Type), typeof(IR.IType) }; - - // Define constructor - var ctorBuilder = typeBuilder.DefineConstructor( - MethodAttributes.Public, - CallingConventions.Standard, - ctorParams - ); - - List<(IR.Field, FieldInfo)> fields = []; - - foreach (var field in @class.Definition.Fields) - { - if (!field.IsClass) continue; - - var attributes = FieldAttributes.Public; - if (field.IsReadOnly) - attributes |= FieldAttributes.InitOnly; - - var fieldType = LoadType(field.Type); - var fieldBuilder = typeBuilder.DefineField( - field.Name, - fieldType, - attributes - ); - - if (field.Initializer is not null) - fields.Add((field, fieldBuilder)); - } - - // Generate IL for constructor - var il = ctorBuilder.GetILGenerator(); - - // Load 'this' - il.Emit(OpCodes.Ldarg_0); - - // Load parameters (arg1, arg2) - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Ldarg_2); - - // Call base constructor - var baseCtor = typeof(TypeObject).GetConstructor(ctorParams); - il.Emit(OpCodes.Call, baseCtor!); - - { - IR.Function function = new(RuntimeModule.TypeSystem.Void); - - foreach (var (_ir, _il) in fields) - { - function.Body.Instructions.AddRange([ - .. _ir.Initializer!, - new IR.VM.SetField(new(_ir) { - OwningType = @class - }) - ]); - } - } - - - // Return - il.Emit(OpCodes.Ret); - - // Create the type - return typeBuilder.CreateType(); - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs b/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs deleted file mode 100644 index cf8f86f2..00000000 --- a/ZSharp.Runtime.IL/ir2il/core/IRLoader.cs +++ /dev/null @@ -1,168 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - /// - /// Wraps an IR module in a C# module. - /// - public sealed partial class IRLoader(Context context, IR.RuntimeModule? runtimeModule = null) - { - public Context Context { get; } = context; - - public IR.RuntimeModule RuntimeModule { get; } = runtimeModule ?? IR.RuntimeModule.Standard; - - public Action GetObjectFunction { get; set; } = (_, __) => throw new NotImplementedException(); - - public IL.Module LoadModule(IR.Module module) - { - if (Context.Cache(module, out var result)) - return result; - - result = new RootModuleLoader(this, module).Load(); - - if (module.Initializer is not null) - result - .GetType(Constants.GlobalsTypeName)! - .GetMethod(Context.Cache(module.Initializer)!.Name, [])! - .Invoke(null, null); - - return result; - } - - public Type LoadType(IR.IType type) - { - if (Context.Cache(type, out var result)) - return result; - - return type switch - { - IR.OOPTypeReference reference => LoadTypeReference(reference), - _ => throw new NotImplementedException() - }; - } - - public Type LoadTypeReference(IR.OOPTypeReference typeReference) - { - var type = Context.Cache(typeReference.Definition); - - if (type is null) - throw new(); - - List genericArguments = []; - - if (typeReference.OwningType is not null) - genericArguments.AddRange(LoadType(typeReference.OwningType).GetGenericArguments()); - - if (typeReference is IR.ConstructedType constructedType) - genericArguments.AddRange(constructedType.Arguments.Select(LoadType)); - - if (genericArguments.Count == 0) - return type; - - return type.MakeGenericType([.. genericArguments]); - } - - public IL.MethodBase LoadReference(IR.ICallable callable) - { - if (Context.Cache(callable) is IL.MethodBase result) - return result; - - if (callable is IR.GenericFunctionInstance genericFunctionInstance) - return LoadReference(genericFunctionInstance); - - if (callable is IR.MethodReference methodReference) - return LoadReference(methodReference); - - throw new NotImplementedException(); - } - - public IL.ConstructorInfo LoadReference(IR.ConstructorReference @ref) - { - var type = LoadType(@ref.OwningType); - - if (!Context.Cache(@ref.Constructor.Method, out var def)) - throw new InvalidOperationException($"Constructor {@ref.Constructor.Name ?? ""} was not loaded"); - - if (def is not IL.ConstructorInfo constructorInfo) - throw new InvalidOperationException($"Method {@ref.Constructor.Name ?? ""} was not compiled to an IL method"); - - if (!type.IsGenericType) - return constructorInfo; - - if (type.GetGenericTypeDefinition() is IL.Emit.TypeBuilder typeBuilder) - if (!typeBuilder.IsCreated()) - return IL.Emit.TypeBuilder.GetConstructor(type, constructorInfo); - try - { - return (IL.ConstructorInfo)(IL.MethodBase.GetMethodFromHandle( - constructorInfo.MethodHandle, - type.TypeHandle - ) ?? throw new("Could not create constructor from method handle")); - } catch (NotSupportedException) - { - return IL.Emit.TypeBuilder.GetConstructor(type, constructorInfo); - } - } - - public IL.FieldInfo LoadReference(IR.FieldReference @ref) - { - var type = LoadType(@ref.OwningType); - - if (!Context.Cache(@ref.Field, out var def)) - throw new InvalidOperationException($"Field {@ref.Field.Name} was not loaded"); - - if (!type.IsGenericType) - return def; - - if (type.GetGenericTypeDefinition() is IL.Emit.TypeBuilder typeBuilder) - if (!typeBuilder.IsCreated()) - return IL.Emit.TypeBuilder.GetField(type, def); - - return IL.FieldInfo.GetFieldFromHandle( - def.FieldHandle, - type.TypeHandle - ); - } - - public IL.MethodInfo LoadReference(IR.MethodReference @ref) - { - var type = LoadType(@ref.OwningType); - - if (!Context.Cache(@ref.Method, out var def)) - throw new InvalidOperationException($"Method {@ref.Method.Name} was not loaded"); - - if (def is not IL.MethodInfo methodInfo) - throw new InvalidOperationException($"Method {@ref.Method.Name} was not compiled to an IL method"); - - if (type.IsGenericType) - if (type.GetGenericTypeDefinition() is IL.Emit.TypeBuilder typeBuilder) - { - if (!typeBuilder.IsCreated()) - methodInfo = IL.Emit.TypeBuilder.GetMethod(type, methodInfo); - } else - try - { - methodInfo = (IL.MethodInfo)(IL.MethodBase.GetMethodFromHandle( - methodInfo.MethodHandle, - type.TypeHandle - ) ?? throw new("Could not create method from method handle")); - } catch (NotSupportedException) - { - methodInfo = IL.Emit.TypeBuilder.GetMethod(type, methodInfo); - } - - if (@ref is IR.ConstructedMethod constructed) - methodInfo = methodInfo.MakeGenericMethod([ - .. constructed.Arguments.Select(LoadType) - ]); - - return methodInfo; - } - - public IL.MethodInfo LoadReference(IR.GenericFunctionInstance @ref) - { - if (!Context.Cache(@ref.Function, out var def)) - throw new InvalidOperationException($"Method {@ref.Function.Name} was not loaded"); - - return def.MakeGenericMethod([.. @ref.Arguments.Select(LoadType)]); - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs deleted file mode 100644 index 00798a01..00000000 --- a/ZSharp.Runtime.IL/ir2il/loader new/ClassLoader.cs +++ /dev/null @@ -1,173 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal sealed class ClassLoader(RootModuleLoader loader, IR.Class @in, IL.Emit.TypeBuilder @out) - : ModuleContentLoader(loader, @in, @out) - { - public ClassLoader(RootModuleLoader loader, IL.Emit.ModuleBuilder module, IR.Class @in) - : this(loader, @in, CreateDefinition(module, @in)) { } - - public ClassLoader(RootModuleLoader loader, IL.Emit.TypeBuilder type, IR.Class @in) - : this(loader, @in, CreateDefinition(type, @in)) { } - - protected override void DoLoad() - { - Context.Cache(Input, Output); - - LoadNestedTypes(); - - ModuleLoader.AddToNextPass(LoadDefinition); - - if (Input.HasConstructors) - ModuleLoader.AddToNextPass(LoadConsructors); - - if (Input.HasFields) - ModuleLoader.AddToNextPass(LoadFields); - - if (Input.HasMethods) - ModuleLoader.AddToNextPass(LoadMethods); - - if (Input.InterfacesImplementations.Count > 0) - ModuleLoader.AddToNextPass(LoadInterfaceImplementations); - - ModuleLoader.AddToCleanUp(() => Output.CreateType()); - } - - private void LoadDefinition() - { - if (Input.Base is not null) - Output.SetParent(Loader.LoadType(Input.Base)); - - if (Input.HasGenericParameters) - LoadGenericParameters(); - } - - private void LoadGenericParameters() - { - var genericParameters = Output.DefineGenericParameters( - Input.GenericParameters.Select(gp => gp.Name).ToArray() - ); - - foreach (var (ir, il) in Input.GenericParameters.Zip(genericParameters)) - Context.Cache(ir, il); - - ModuleLoader.AddToCleanUp(() => - { - foreach (var ir in Input.GenericParameters) - { - // TODO: Context.Uncache(ir); - } - }); - } - - private void LoadInterfaceImplementations() - { - foreach (var interfaceImplementation in Input.InterfacesImplementations) - { - var @interface = Loader.LoadType(interfaceImplementation.Interface); - Output.AddInterfaceImplementation(@interface); - - foreach (var (@abstract, concrete) in interfaceImplementation.Implementations) - { - var specification = Loader.LoadReference(@abstract); - var implementation = Context.Cache(concrete) ?? throw new(); - - Output.DefineMethodOverride(implementation, specification); - } - } - } - - private void LoadNestedTypes() - { - - } - - private void LoadConsructors() - { - foreach (var constructor in Input.Constructors) - LoadConstructor(constructor); - } - - private void LoadFields() - { - foreach (var field in Input.Fields) - LoadField(field); - } - - private void LoadMethods() - { - foreach (var method in Input.Methods) - LoadMethod(method); - } - - private void LoadConstructor(IR.Constructor constructor) - { - var result = Output.DefineConstructor( - IL.MethodAttributes.Public, - IL.CallingConventions.HasThis, - [.. constructor.Method.Signature.GetParameters().Skip(1).Select(p => Loader.LoadType(p.Type))] - ); - - Context.Cache(constructor.Method, result); - - var context = Code.FunctionCodeContext.From(Loader, result, constructor.Method.UnderlyingFunction); - - foreach (var local in constructor.Method.Body.Locals) - result.GetILGenerator().DeclareLocal(Loader.LoadType(local.Type)); - - var codeLoader = new Code.CodeCompiler(context); - - ModuleLoader.AddToNextPass(() => codeLoader.CompileCode(constructor.Method.Body.Instructions)); - } - - private void LoadField(IR.Field field) - { - var attributes = IL.FieldAttributes.Public; - - if (field.IsStatic) - attributes |= IL.FieldAttributes.Static; - - var il = Output.DefineField(field.Name, Loader.LoadType(field.Type), attributes); - - Context.Cache(field, il); - } - - private void LoadMethod(IR.Method method) - { - var attributes = IL.MethodAttributes.Public; - - if (method.IsStatic) - attributes |= IL.MethodAttributes.Static; - if (method.IsVirtual) - attributes |= IL.MethodAttributes.Virtual | IL.MethodAttributes.NewSlot; - - var result = Output.DefineMethod( - method.Name ?? Constants.AnonymousMethod, - attributes, - Loader.LoadType(method.ReturnType), - [.. ( - method.IsInstance || method.IsVirtual - ? method.Signature.GetParameters().Skip(1) - : method.Signature.GetParameters() - ).Select(p => Loader.LoadType(p.Type)) - ] - ); - - Context.Cache(method, result); - - var context = Code.FunctionCodeContext.From(Loader, result, method.UnderlyingFunction); - - foreach (var local in method.Body.Locals) - result.GetILGenerator().DeclareLocal(Loader.LoadType(local.Type)); - - var codeLoader = new Code.CodeCompiler(context); - - ModuleLoader.AddToNextPass(() => codeLoader.CompileCode(method.Body.Instructions)); - } - - private static IL.Emit.TypeBuilder CreateDefinition(IL.Emit.ModuleBuilder module, IR.Class @in) - => module.DefineType(@in.Name ?? Constants.AnonymousClass); - - private static IL.Emit.TypeBuilder CreateDefinition(IL.Emit.TypeBuilder type, IR.Class @in) - => type.DefineNestedType(@in.Name ?? Constants.AnonymousClass); - } -} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs deleted file mode 100644 index 62deee21..00000000 --- a/ZSharp.Runtime.IL/ir2il/loader new/InterfaceLoader.cs +++ /dev/null @@ -1,153 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal sealed class InterfaceLoader(RootModuleLoader loader, IR.Interface @in, IL.Emit.TypeBuilder @out) - : ModuleContentLoader(loader, @in, @out) - { - public InterfaceLoader(RootModuleLoader loader, IL.Emit.ModuleBuilder module, IR.Interface @in) - : this(loader, @in, CreateDefinition(module, @in)) { } - - public InterfaceLoader(RootModuleLoader loader, IL.Emit.TypeBuilder type, IR.Interface @in) - : this(loader, @in, CreateDefinition(type, @in)) { } - - protected override void DoLoad() - { - Context.Cache(Input, Output); - - LoadNestedTypes(); - - ModuleLoader.AddToNextPass(LoadDefinition); - - if (Input.HasMethods) - ModuleLoader.AddToNextPass(LoadMethods); - - ModuleLoader.AddToCleanUp(() => Output.CreateType()); - } - - private void LoadDefinition() - { - if (Input.HasBases) - foreach (var @base in Input.Bases) - Output.AddInterfaceImplementation(Loader.LoadType(@base)); - - if (Input.HasGenericParameters) - LoadGenericParameters(); - } - - private void LoadGenericParameters() - { - var genericParameters = Output.DefineGenericParameters( - Input.GenericParameters.Select(gp => gp.Name).ToArray() - ); - - foreach (var (ir, il) in Input.GenericParameters.Zip(genericParameters)) - Context.Cache(ir, il); - - ModuleLoader.AddToCleanUp(() => - { - foreach (var ir in Input.GenericParameters) - { - //Context.Uncache(ir); - } - }); - } - - private void LoadNestedTypes() - { - - } - - private void LoadMethods() - { - foreach (var method in Input.Methods) - LoadMethod(method); - } - - private void LoadConstructor(IR.Constructor constructor) - { - var irParams = constructor.Method.Signature.GetParameters(); - - var parameters = irParams.Select(p => new Parameter() - { - Name = p.Name, - Type = Loader.LoadType(p.Type), - Position = p.Index - }); - - var result = Output.DefineConstructor(IL.MethodAttributes.Public, IL.CallingConventions.HasThis, [.. irParams.Skip(1).Select(p => Loader.LoadType(p.Type))]); - - Context.Cache(constructor.Method, result); - - var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(Loader, constructor.Method, ilGen); - - foreach (var (ir, parameter) in irParams.Zip(parameters)) - codeLoader.Args[ir] = parameter; - - foreach (var local in constructor.Method.Body.Locals) - codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); - - ModuleLoader.AddToNextPass(() => codeLoader.Load()); - } - - private void LoadField(IR.Field field) - { - var attributes = IL.FieldAttributes.Public; - - if (field.IsStatic) - attributes |= IL.FieldAttributes.Static; - - var il = Output.DefineField(field.Name, Loader.LoadType(field.Type), attributes); - - Context.Cache(field, il); - } - - private void LoadMethod(IR.Method method) - { - var irParams = method.Signature.GetParameters(); - - var parameters = irParams.Select(p => new Parameter() - { - Name = p.Name, - Type = Loader.LoadType(p.Type), - Position = p.Index, - }); - - var attributes = IL.MethodAttributes.Public; - - if (method.IsStatic) - attributes |= IL.MethodAttributes.Static; - - var result = Output.DefineMethod( - method.Name ?? Constants.AnonymousMethod, - attributes, - Loader.LoadType(method.ReturnType), - [.. (method.IsInstance || method.IsVirtual ? parameters.Skip(1) : parameters).Select(p => p.Type)] - ); - - Context.Cache(method, result); - - var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(Loader, method, ilGen); - - foreach (var (ir, parameter) in irParams.Zip(parameters)) - codeLoader.Args[ir] = parameter; - - foreach (var local in method.Body.Locals) - codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); - - ModuleLoader.AddToNextPass(() => codeLoader.Load()); - } - - private static IL.Emit.TypeBuilder CreateDefinition(IL.Emit.ModuleBuilder module, IR.Interface @in) - => module.DefineType( - @in.Name ?? Constants.AnonymousInterface, - IL.TypeAttributes.Interface - ); - - private static IL.Emit.TypeBuilder CreateDefinition(IL.Emit.TypeBuilder type, IR.Interface @in) - => type.DefineNestedType( - @in.Name ?? Constants.AnonymousInterface, - IL.TypeAttributes.Interface - ); - } -} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ModuleContentLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ModuleContentLoader.cs deleted file mode 100644 index 716f9a80..00000000 --- a/ZSharp.Runtime.IL/ir2il/loader new/ModuleContentLoader.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal abstract class ModuleContentLoader(RootModuleLoader loader, In @in, Out @out) - : BaseIRLoader(loader.Loader, @in, @out) - { - public RootModuleLoader ModuleLoader { get; } = loader; - - public Out Load() - { - DoLoad(); - - return Output; - } - - protected abstract void DoLoad(); - } -} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs deleted file mode 100644 index 928fe646..00000000 --- a/ZSharp.Runtime.IL/ir2il/loader new/ModuleLoader.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System; - -namespace ZSharp.Runtime.NET.IR2IL -{ - internal sealed class ModuleLoader( - RootModuleLoader loader, - IR.Module @in, - IL.Emit.ModuleBuilder? @out = null - ) : ModuleContentLoader( - loader, - @in, - @out ?? loader.AssemblyBuilder.DefineDynamicModule(@in.Name ?? Constants.AnonymousModule) - ) - { - protected override void DoLoad() - { - if (Input.HasSubmodules) - LoadSubModules(); - - if (Input.HasTypes) - LoadTypes(); - - if (!Input.HasFunctions && !Input.HasGlobals) - return; - - var globals = Output.DefineType(Constants.GlobalsTypeName, IL.TypeAttributes.Public | IL.TypeAttributes.Abstract | IL.TypeAttributes.Sealed); - - if (Input.HasFunctions) - ModuleLoader.AddToNextPass(() => LoadFunctions(globals)); - - if (Input.HasGlobals) - ModuleLoader.AddToNextPass(() => LoadGlobals(globals)); - - ModuleLoader.AddToCleanUp(() => - { - globals.CreateType(); - }); - } - - private void LoadSubModules() - { - foreach (var submodule in Input.Submodules) - new ModuleLoader(ModuleLoader, submodule).Load(); - } - - private void LoadTypes() - { - foreach (var type in Input.Types) - (type switch - { - IR.Class @class => new ClassLoader(ModuleLoader, Output, @class).Load, - IR.Interface @interface => new InterfaceLoader(loader, Output, @interface).Load, - _ => (Func)null! ?? throw new NotImplementedException() - })(); - } - - private void LoadFunctions(IL.Emit.TypeBuilder globals) - { - foreach (var function in Input.Functions) - LoadFunction(globals, function); - } - - private void LoadGlobals(IL.Emit.TypeBuilder globals) - { - foreach (var global in Input.Globals) - LoadGlobal(globals, global); - } - - private IL.MethodInfo LoadFunction(IL.Emit.TypeBuilder globals, IR.Function function) - { - var irParams = function.Signature.GetParameters(); - - var attributes = IL.MethodAttributes.Public | IL.MethodAttributes.Static; - - var parameters = irParams.Select(p => new Parameter() - { - Name = p.Name, - Type = Loader.LoadType(p.Type), - Position = p.Index, - }); - - var result = globals.DefineMethod( - function.Name ?? string.Empty, - attributes, - Loader.LoadType(function.ReturnType), - parameters.Select(p => p.Type).ToArray() - ); - - Context.Cache(function, result); - - var ilGen = result.GetILGenerator(); - var codeLoader = new CodeLoader(Loader, function, ilGen); - - foreach (var (ir, parameter) in irParams.Zip(parameters)) - codeLoader.Args[ir] = parameter; - - foreach (var local in function.Body.Locals) - codeLoader.Locals[local] = ilGen.DeclareLocal(Loader.LoadType(local.Type)); - - ModuleLoader.AddToNextPass(() => codeLoader.Load()); - - return result; - } - - private IL.FieldInfo LoadGlobal(IL.Emit.TypeBuilder globals, IR.Global global) - { - var result = globals.DefineField( - global.Name ?? string.Empty, - Loader.LoadType(global.Type), - IL.FieldAttributes.Public | IL.FieldAttributes.Static - ); - - Context.Cache(global, result); - - return result; - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/RootModuleLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/RootModuleLoader.cs deleted file mode 100644 index 2e96f2f5..00000000 --- a/ZSharp.Runtime.IL/ir2il/loader new/RootModuleLoader.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal sealed class RootModuleLoader(IRLoader loader, IR.Module @in) - { - public IRLoader Loader { get; } = loader; - - public IR.Module Input { get; } = @in; - - public IL.Emit.AssemblyBuilder AssemblyBuilder { get; } = - IL.Emit.AssemblyBuilder.DefineDynamicAssembly( - new(@in.Name ?? Constants.AnonymousModule), - IL.Emit.AssemblyBuilderAccess.RunAndCollect - ); - - private List thisPass = [], nextPass = [], cleanUp = []; - - public void AddToNextPass(Action action) - => nextPass.Add(action); - - public void AddToCleanUp(Action action) - => cleanUp.Add(action); - - public IL.Module Load() - { - var result = new ModuleLoader(this, Input).Load(); - - RunUntilComplete(); - - return result; - } - - private void RunUntilComplete() - { - while (nextPass.Count > 0) - { - (thisPass, nextPass) = (nextPass, thisPass); - nextPass.Clear(); - - foreach (var action in thisPass) - action(); - } - - foreach (var action in cleanUp) - action(); - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.Compile.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.Compile.cs deleted file mode 100644 index efe8d885..00000000 --- a/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.Compile.cs +++ /dev/null @@ -1,308 +0,0 @@ -using VM = ZSharp.IR.VM; - -namespace ZSharp.Runtime.NET.IR2IL -{ - partial class CodeLoader - { - private readonly Stack _stack = []; - - private void Compile(VM.Call call) - { - var callable = Loader.LoadReference(call.Callable); - - foreach (var _ in call.Callable.Signature.GetParameters()) - _stack.Pop(); - - if (callable is IL.MethodInfo method) - { - Output.Emit(IL.Emit.OpCodes.Call, method); - - if (method.ReturnType != typeof(void)) - _stack.Push(method.ReturnType); - } - else if (callable is IL.ConstructorInfo constructor) - Output.Emit(IL.Emit.OpCodes.Call, constructor); - else throw new($"Unknown callable type: {callable.GetType()}"); - } - - private void Compile(VM.CallIndirect callIndirect) - { - throw new NotImplementedException(); - } - - private void Compile(VM.CallInternal callInternal) - { - throw new($"Use {nameof(VM.Call)} instead!"); - } - - private void Compile(VM.CallVirtual callVirtual) - { - var method = Loader.LoadReference(callVirtual.Method); - - if (!method.IsVirtual && !method.IsAbstract) - throw new($"Method {method} is not virtual or abstract!"); - - Output.Emit(IL.Emit.OpCodes.Callvirt, method); - - if (method.ReturnType != typeof(void)) - _stack.Push(method.ReturnType); - } - - private void Compile(VM.CastReference castReference) - { - var targetType = Loader.LoadType(castReference.Type); - - Output.Emit(IL.Emit.OpCodes.Isinst, targetType); - - _stack.Pop(); - _stack.Push(targetType); - } - - private void Compile(VM.CreateInstance createInstance) - { - var constructor = Loader.LoadReference(createInstance.Constructor); - - Output.Emit(IL.Emit.OpCodes.Newobj, constructor); - - _stack.Push(constructor.DeclaringType ?? throw new()); - } - - private void Compile(VM.Dup _) - { - Output.Emit(IL.Emit.OpCodes.Dup); - - _stack.Push(_stack.Peek()); - } - - private void Compile(VM.GetArgument getArgument) - { - var p = Args[getArgument.Argument]; - var index = p.Position; - - if (index == 0) - Output.Emit(IL.Emit.OpCodes.Ldarg_0); - else if (index == 1) - Output.Emit(IL.Emit.OpCodes.Ldarg_1); - else if (index == 2) - Output.Emit(IL.Emit.OpCodes.Ldarg_2); - else if (index == 3) - Output.Emit(IL.Emit.OpCodes.Ldarg_3); - else if (index <= byte.MaxValue) - Output.Emit(IL.Emit.OpCodes.Ldarg_S, (byte)index); - else - Output.Emit(IL.Emit.OpCodes.Ldarg, index); - - _stack.Push(p.Type); - } - - private void Compile(VM.GetClass getClass) - { - var typeObjectId = Loader.GetTypeObject(getClass.Class); - - Output.Emit(IL.Emit.OpCodes.Ldc_I4, typeObjectId); - Output.Emit(IL.Emit.OpCodes.Call, Utils.GetMethod(IRLoader._GetTypeObject)); - } - - private void Compile(VM.GetField getField) - { - var field = Loader.LoadReference(getField.Field); - - Output.Emit(field.IsStatic ? IL.Emit.OpCodes.Ldsfld : IL.Emit.OpCodes.Ldfld, field); - - _stack.Push(field.FieldType); - } - - private void Compile(VM.GetGlobal getGlobal) - { - if (!Context.Cache(getGlobal.Global, out var global)) - throw new(); - - Output.Emit(IL.Emit.OpCodes.Ldsfld, global); - - _stack.Push(global.FieldType); - } - - private void Compile(VM.GetLocal getLocal) - { - var l = Locals[getLocal.Local]; - var index = l.LocalIndex; - - if (index == 0) - Output.Emit(IL.Emit.OpCodes.Ldloc_0); - else if (index == 1) - Output.Emit(IL.Emit.OpCodes.Ldloc_1); - else if (index == 2) - Output.Emit(IL.Emit.OpCodes.Ldloc_2); - else if (index == 3) - Output.Emit(IL.Emit.OpCodes.Ldloc_3); - else if (index <= byte.MaxValue) - Output.Emit(IL.Emit.OpCodes.Ldloc_S, (byte)index); - else - Output.Emit(IL.Emit.OpCodes.Ldloc, index); - - _stack.Push(l.LocalType); - } - - private void Compile(VM.GetObject getObject) - { - throw new NotSupportedException( - $"The {nameof(VM.GetObject)} instruction is obsolete and being " + - $"removed. Please do not use this instruction. To get a function " + - $"you can use GetFunction. To get a class you can use {nameof(VM.GetClass)}." + - $" To get a virtual method, use GetVirtualMethod." - ); - } - - private void Compile(VM.IsNotNull _) - { - Output.Emit(IL.Emit.OpCodes.Ldnull); - Output.Emit(IL.Emit.OpCodes.Cgt_Un); - - _stack.Pop(); - _stack.Push(typeof(bool)); - } - - private void Compile(VM.IsNull _) - { - Output.Emit(IL.Emit.OpCodes.Ldnull); - Output.Emit(IL.Emit.OpCodes.Ceq); - - _stack.Pop(); - _stack.Push(typeof(bool)); - } - - private void Compile(VM.Jump jump) - { - Output.Emit(IL.Emit.OpCodes.Br, labels[jump.Target]); - } - - private void Compile(VM.JumpIfTrue jumpIfTrue) - { - Output.Emit(IL.Emit.OpCodes.Brtrue, labels[jumpIfTrue.Target]); - - _stack.Pop(); - } - - private void Compile(VM.JumpIfFalse jumpIfFalse) - { - Output.Emit(IL.Emit.OpCodes.Brfalse, labels[jumpIfFalse.Target]); - - _stack.Pop(); - } - - private void Compile(VM.Nop _) - { - Output.Emit(IL.Emit.OpCodes.Nop); - } - - private void Compile(VM.Pop _) - { - Output.Emit(IL.Emit.OpCodes.Pop); - - if (_stack.Count > 0) - _stack.Pop(); - } - - private void Compile(VM.PutBoolean putBoolean) - { - Output.Emit(putBoolean.Value ? IL.Emit.OpCodes.Ldc_I4_1 : IL.Emit.OpCodes.Ldc_I4_0); - - _stack.Push(typeof(bool)); - } - - private void Compile(VM.PutFloat32 putFloat32) - { - Output.Emit(IL.Emit.OpCodes.Ldc_R4, putFloat32.Value); - - _stack.Push(typeof(float)); - } - - private void Compile(VM.PutInt32 putInt32) - { - Output.Emit(IL.Emit.OpCodes.Ldc_I4, putInt32.Value); - - _stack.Push(typeof(int)); - } - - private void Compile(VM.PutNull _) - { - Output.Emit(IL.Emit.OpCodes.Ldnull); - - _stack.Push(typeof(object)); - } - - private void Compile(VM.PutString putString) - { - Output.Emit(IL.Emit.OpCodes.Ldstr, putString.Value); - - _stack.Push(typeof(string)); - } - - private void Compile(VM.Return _) - { - Output.Emit(IL.Emit.OpCodes.Ret); - } - - private void Compile(VM.SetArgument setArgument) - { - var index = Args[setArgument.Argument].Position; - - if (index <= byte.MaxValue) - Output.Emit(IL.Emit.OpCodes.Starg_S, (byte)index); - else - Output.Emit(IL.Emit.OpCodes.Starg, index); - - _stack.Pop(); - } - - private void Compile(VM.SetField setField) - { - var field = Loader.LoadReference(setField.Field); - - Output.Emit(field.IsStatic ? IL.Emit.OpCodes.Stsfld : IL.Emit.OpCodes.Stfld, field); - - _stack.Pop(); - } - - private void Compile(VM.SetGlobal setGlobal) - { - if (!Context.Cache(setGlobal.Global, out var global)) - throw new(); - - Output.Emit(IL.Emit.OpCodes.Stsfld, global); - - _stack.Pop(); - } - - private void Compile(VM.SetLocal setLocal) - { - var index = Locals[setLocal.Local].LocalIndex; - - if (index <= byte.MaxValue) - Output.Emit(IL.Emit.OpCodes.Stloc_S, (byte)index); - else - Output.Emit(IL.Emit.OpCodes.Stloc, index); - - _stack.Pop(); - } - - private void Compile(VM.Swap _) - { - var tmp1 = Output.DeclareLocal(_stack.Peek()); - Output.Emit(IL.Emit.OpCodes.Stloc, tmp1.LocalIndex); - var tp1 = _stack.Pop(); - - var tmp2 = Output.DeclareLocal(_stack.Peek()); - Output.Emit(IL.Emit.OpCodes.Stloc, tmp2.LocalIndex); - var tp2 = _stack.Pop(); - - Output.Emit(IL.Emit.OpCodes.Ldloc, tmp1.LocalIndex); - - _stack.Push(tp1); - - Output.Emit(IL.Emit.OpCodes.Ldloc, tmp2.LocalIndex); - - _stack.Push(tp2); - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.cs deleted file mode 100644 index 55293268..00000000 --- a/ZSharp.Runtime.IL/ir2il/loader new/code/CodeLoader.cs +++ /dev/null @@ -1,92 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal sealed partial class CodeLoader(IRLoader loader, IR.ICallable code, IL.Emit.ILGenerator method) - : BaseIRLoader(loader, code, method) - , ICodeLoader - { - private readonly Dictionary labels = []; - - public Stack Stack => _stack; - - public Dictionary Args { get; } = []; - - public Dictionary Locals { get; } = []; - - public void Load() - { - CompileCode(); - } - - private void CompileCode() - { - if (!Input.HasBody || !Input.Body.HasInstructions) return; - - foreach (var instruction in Input.Body.Instructions) - labels[instruction] = Output.DefineLabel(); - - - foreach (var instruction in Input.Body.Instructions) - Compile(instruction); - } - - public void Push(Type type) - => _stack.Push(type); - - public void Pop() - => _stack.Pop(); - - public void Pop(Type type) - { - if (_stack.Pop() != type) - throw new($"Expected type {type} on the stack!"); - } - - public void Pop(params Type[] types) - { - foreach (var type in types.Reverse()) - Pop(type); - } - - private void Compile(IR.VM.Instruction instruction) - { - Output.MarkLabel(labels[instruction]); - - switch (instruction) - { - case IR.VM.Call call: Compile(call); break; - case IR.VM.CallIndirect callIndirect: Compile(callIndirect); break; - case IR.VM.CallInternal callInternal: Compile(callInternal); break; - case IR.VM.CallVirtual callVirtual: Compile(callVirtual); break; - case IR.VM.CastReference castReference: Compile(castReference); break; - case IR.VM.CreateInstance createInstance: Compile(createInstance); break; - case IR.VM.Dup dup: Compile(dup); break; - case IR.VM.GetArgument getArgument: Compile(getArgument); break; - case IR.VM.GetClass getClass: Compile(getClass); break; - case IR.VM.GetField getField: Compile(getField); break; - case IR.VM.GetGlobal getGlobal: Compile(getGlobal); break; - case IR.VM.GetLocal getLocal: Compile(getLocal); break; - case IR.VM.GetObject getObject: Compile(getObject); break; - case IR.VM.IsNotNull isNotNull: Compile(isNotNull); break; - case IR.VM.IsNull isNull: Compile(isNull); break; - case IR.VM.Jump jump: Compile(jump); break; - case IR.VM.JumpIfTrue jumpIfTrue: Compile(jumpIfTrue); break; - case IR.VM.JumpIfFalse jumpIfFalse: Compile(jumpIfFalse); break; - case IR.VM.Nop nop: Compile(nop); break; - case IR.VM.Pop pop: Compile(pop); break; - case IR.VM.PutBoolean putBoolean: Compile(putBoolean); break; - case IR.VM.PutFloat32 putFloat32: Compile(putFloat32); break; - case IR.VM.PutInt32 putInt32: Compile(putInt32); break; - case IR.VM.PutNull putNull: Compile(putNull); break; - case IR.VM.PutString putString: Compile(putString); break; - case IR.VM.Return @return: Compile(@return); break; - case IR.VM.SetArgument setArgument: Compile(setArgument); break; - case IR.VM.SetField setField: Compile(setField); break; - case IR.VM.SetGlobal setGlobal: Compile(setGlobal); break; - case IR.VM.SetLocal setLocal: Compile(setLocal); break; - case IR.VM.Swap swap: Compile(swap); break; - - default: throw new NotImplementedException(); - } - } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/code/ICodeLoader.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/ICodeLoader.cs deleted file mode 100644 index 4003409d..00000000 --- a/ZSharp.Runtime.IL/ir2il/loader new/code/ICodeLoader.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - public interface ICodeLoader - { - public IL.Emit.ILGenerator Output { get; } - - public void Push(Type type); - - public void Pop(); - - public void Pop(Type type); - - public void Pop(params Type[] types); - } -} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/code/Parameter.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/Parameter.cs deleted file mode 100644 index 8d5f8a5e..00000000 --- a/ZSharp.Runtime.IL/ir2il/loader new/code/Parameter.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal sealed class Parameter - { - public required string Name { get; set; } - - public required Type Type { get; set; } - - public int Position { get; set; } - } -} diff --git a/ZSharp.Runtime.IL/ir2il/loader new/code/ThisParameter.cs b/ZSharp.Runtime.IL/ir2il/loader new/code/ThisParameter.cs deleted file mode 100644 index a0e224d3..00000000 --- a/ZSharp.Runtime.IL/ir2il/loader new/code/ThisParameter.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace ZSharp.Runtime.NET.IR2IL -{ - internal class ThisParameter(Type declaringType) : IL.ParameterInfo - { - public override Type ParameterType => declaringType; - - public override string Name => "this"; - - public override int Position => 0; - - public override IL.ParameterAttributes Attributes => IL.ParameterAttributes.None; - - public override object? DefaultValue => null; - - public override bool HasDefaultValue => false; - } -} diff --git a/ZSharp.Runtime.IL/objects/TypeObject.cs b/ZSharp.Runtime.IL/objects/TypeObject.cs deleted file mode 100644 index b4915766..00000000 --- a/ZSharp.Runtime.IL/objects/TypeObject.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Runtime.NET -{ - public abstract class TypeObject(Type il, IR.IType ir) - { - public Type IL { get; } = il; - - public IR.IType IR { get; } = ir; - } -} From 9d52bdda33f74ba207e50905c0af8900e0df57a7 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen <42520501+binyamin555@users.noreply.github.com> Date: Fri, 12 Sep 2025 11:32:04 +0300 Subject: [PATCH 209/235] Create test.zs using my phone --- ZSC.Script/test.zs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 ZSC.Script/test.zs diff --git a/ZSC.Script/test.zs b/ZSC.Script/test.zs new file mode 100644 index 00000000..14dac70f --- /dev/null +++ b/ZSC.Script/test.zs @@ -0,0 +1,22 @@ +import { Directory } from "std:fs"; +import { print } from "std:io"; + +print("[CT] Hello, World!"); + +fun nodeTypeNotImplemented() {} + +module A { + print("[CT] Inside module A"); + + fun main() { + print("[RT] Hello, World!"); + } +} + +if (false) { + print("[CT] Condition is true"); +} else { + print("[CT] Condition is false"); +} + +A.main(); \ No newline at end of file From 65de05fe63f22f8571da23d1b4ce86c1e1614f3d Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 14 Sep 2025 16:22:51 +0300 Subject: [PATCH 210/235] See https://tenor.com/view/order-star-wars-mas-amedda-galactic-republic-gif-11861411253243837220 --- Testing/Program.cs | 6 +- Testing/Testing.csproj | 3 +- ZLoad.Test/BaseClass.cs | 13 - ZLoad.Test/Console.cs | 10 - ZLoad.Test/Globals.cs | 16 - ZLoad.Test/Standard.List.Iterator.cs | 17 - ZLoad.Test/Standard.List.cs | 39 -- ZLoad.Test/TestClass.cs | 15 - ZLoad.Test/TestEnum.cs | 4 - ZLoad.Test/TestInterface.cs | 13 - ZSC.Project/Program.cs | 152 ------- ZSC.Project/Properties/launchSettings.json | 11 - ZSC.Project/ZSC.Project.csproj | 19 - ZSharp v1.sln | 123 ++---- .../CLIArgumentLogOrigin.cs | 2 +- {ZSC.Script => ZSharp.CLI}/Program.cs | 6 +- .../ZSCScriptLogOrigin.cs | 2 +- .../ZSharp.CLI.csproj | 13 +- ZSharp.CT.CompilerAPI/Fields_Globals.cs | 10 - ZSharp.CT.CompilerAPI/Impl_Globals.cs | 10 - .../ZSharp.CT.CompilerAPI.csproj | 14 - ZSharp.CT.RuntimeAPI/Fields_Globals.cs | 10 - ZSharp.CT.RuntimeAPI/Impl_Globals.cs | 16 - .../ZSharp.CT.RuntimeAPI.csproj | 13 - .../GlobalUsings.cs | 1 - ZSharp.CT.StandardLibrary.IO/GlobalUsings.cs | 1 - ZSharp.CT.StandardLibrary/Impl_Globals.cs | 44 -- .../ZSharp.CT.StandardLibrary.csproj | 13 - .../GlobalUsings.cs | 0 .../ZSharp.Compiler.CG.Direct.csproj | 1 - .../dispatcher/Dispatcher.cs | 2 +- .../dispatcher/services/Dispatcher.Call.cs | 2 +- .../dispatcher/services/Dispatcher.Cast.cs | 2 +- .../services/Dispatcher.ImplicitCast.cs | 2 +- .../dispatcher/services/Dispatcher.Index.cs | 2 +- .../dispatcher/services/Dispatcher.Match.cs | 2 +- .../services/Dispatcher.MemberAccess.cs | 2 +- .../services/Dispatcher.ValueAccess.cs | 2 +- .../protocols/callable/ICTCallable.cs | 0 .../implicit casting/ICTImplicitCastFrom.cs | 0 .../implicit casting/ICTImplicitCastTo.cs | 0 .../protocols/index/ICTGetIndex.cs | 0 .../protocols/index/ICTSetIndex.cs | 0 .../protocols/member access/ICTGetMember.cs | 0 .../protocols/member access/ICTSetMember.cs | 0 .../protocols/type casting/ICTCastTo.cs | 0 .../protocols/type matching/ICTTypeMatch.cs | 0 .../protocols/value access/ICTGet.cs | 0 .../protocols/value access/ICTSet.cs | 0 .../GlobalUsings.cs | 0 .../ZSharp.Compiler.CG.Proxy.csproj | 1 - .../dispatcher/Dispatcher.cs | 0 .../dispatcher/services/Dispatcher.Call.cs | 0 .../dispatcher/services/Dispatcher.Cast.cs | 0 .../services/Dispatcher.ImplicitCast.cs | 0 .../dispatcher/services/Dispatcher.Index.cs | 0 .../dispatcher/services/Dispatcher.Match.cs | 0 .../services/Dispatcher.MemberAccess.cs | 0 .../services/Dispatcher.ValueAccess.cs | 0 .../protocols/IProxy.cs | 0 .../GlobalUsings.cs | 0 .../ZSharp.Compiler.CG.Typed.csproj | 1 - .../dispatcher/Dispatcher.cs | 2 +- .../dispatcher/services/Dispatcher.Call.cs | 2 +- .../dispatcher/services/Dispatcher.Cast.cs | 2 +- .../services/Dispatcher.ImplicitCast.cs | 2 +- .../dispatcher/services/Dispatcher.Index.cs | 2 +- .../dispatcher/services/Dispatcher.Match.cs | 2 +- .../services/Dispatcher.MemberAccess.cs | 2 +- .../services/Dispatcher.ValueAccess.cs | 2 +- .../extensions/CompilerExtensions.cs | 3 + .../protocols/callable/IRTCallable.cs | 0 .../implicit casting/IRTImplicitCastTo.cs | 0 .../protocols/index/IRTGetIndex.cs | 0 .../protocols/index/IRTSetIndex.cs | 0 .../protocols/member access/IRTGetMember.cs | 0 .../protocols/member access/IRTSetMember.cs | 0 .../runtime/IHasRuntimeDescriptor.cs | 0 .../protocols/type casting/IRTCastFrom.cs | 0 .../protocols/type casting/IRTCastTo.cs | 0 .../protocols/type matching/IRTTypeMatch.cs | 0 .../protocols/value access/IRTGet.cs | 0 .../protocols/value access/IRTSet.cs | 0 .../GlobalUsings.cs | 0 .../ZSharp.Compiler.CG.csproj | 0 .../cg/CG.cs | 0 .../cg/services/CG.Call.cs | 0 .../cg/services/CG.Cast.cs | 0 .../cg/services/CG.ImplicitCast.cs | 0 .../cg/services/CG.Index.cs | 0 .../cg/services/CG.Match.cs | 0 .../cg/services/CG.MemberAccess.cs | 0 .../cg/services/CG.ValueAccess.cs | 0 .../core/Argument.cs | 0 .../core/CastResult.cs | 0 .../core/MatchResult.cs | 0 .../dispatcher/Dispatcher.Call.cs | 0 .../dispatcher/Dispatcher.Cast.cs | 0 .../dispatcher/Dispatcher.ImplicitCast.cs | 0 .../dispatcher/Dispatcher.Index.cs | 0 .../dispatcher/Dispatcher.Match.cs | 0 .../dispatcher/Dispatcher.MemberAccess.cs | 0 .../dispatcher/Dispatcher.Runtime.cs | 0 .../dispatcher/Dispatcher.ValueAccess.cs | 0 .../dispatcher/Dispatcher.cs | 0 .../objects/oop/class/concrete/Class.IR.cs | 28 -- .../objects/oop/class/concrete/Class.T.cs | 7 - .../objects/oop/enum/Enum.T.cs | 7 - .../objects/oop/field/Field.T.cs | 7 - .../oop/interface/concrete/Interface.T.cs | 7 - .../objects/oop/method/concrete/Method.T.cs | 7 - .../objects/oop/property/Property.T.cs | 7 - .../objects/oop/struct/concrete/Struct.T.cs | 7 - ZSharp.Compiler.IRLoader/GlobalUsings.cs | 1 - .../ZSharp.Compiler.Overloading.csproj | 1 - .../dispatcher/Dispatcher.T.cs | 2 +- .../dispatcher/Dispatcher.TypeOf.cs | 2 +- .../dispatcher/Dispatcher.cs | 2 +- ZSharp.Compiler/ZSharp.Compiler.csproj | 2 +- .../AliasAttribute.cs | 2 +- .../HideImportAttribute.cs | 2 +- .../ModuleScopeAttribute.cs | 2 +- ...ZSharp.Importer.ILLoader.Attributes.csproj | 5 +- .../namespace/AddNamespaceAttribute.cs | 2 +- .../namespace/MapNamespaceAttribute.cs | 2 +- .../namespace/SetNamespaceAttribute.cs | 2 +- .../operator/OperatorAttribute.cs | 2 +- .../operator/OperatorKind.cs | 2 +- .../parameter/NamedParameterAttribute.cs | 2 +- .../parameter/VarParameterAttribute.cs | 2 +- ZSharp.Importer.ILLoader/GlobalUsings.cs | 1 + .../ZSharp.Importer.ILLoader.csproj | 8 +- .../capabilities/ITypeModifier.cs | 2 +- .../capabilities/internal/IAddMember.cs | 2 +- .../internal/ILazilyLoadMembers.cs | 2 +- .../capabilities/on add/IOnAddTo.cs | 0 .../capabilities/on add/OnAddResult.cs | 0 .../extensions/ILLoaderExtensions.cs | 2 +- .../extensions/InternalILMemberExtensions.cs | 4 +- .../il loader/ILLoader.Events.cs | 2 +- .../il loader/ILLoader.Expose.cs | 2 +- .../il loader/ILLoader.IR.cs | 6 +- .../il loader/ILLoader.Namespaces.cs | 4 +- .../il loader/ILLoader.Runtime.cs | 6 +- .../il loader/ILLoader.TypeSystem.cs | 2 +- .../il loader/ILLoader.cs | 4 +- .../load/ILLoader.Load.Member.Constructor.cs | 2 +- .../load/ILLoader.Load.Member.Event.cs | 2 +- .../load/ILLoader.Load.Member.Field.cs | 2 +- .../ILLoader.Load.Member.Method.Generic.cs | 2 +- .../load/ILLoader.Load.Member.Method.cs | 2 +- .../load/ILLoader.Load.Member.Property.cs | 2 +- .../il loader/load/ILLoader.Load.Member.cs | 2 +- .../il loader/load/ILLoader.Load.Module.cs | 2 +- .../load/ILLoader.Load.Type.Class.Generic.cs | 2 +- .../load/ILLoader.Load.Type.Class.cs | 2 +- .../il loader/load/ILLoader.Load.Type.Enum.cs | 2 +- .../load/ILLoader.Load.Type.Generic.cs | 2 +- .../ILLoader.Load.Type.Interface.Generic.cs | 2 +- .../load/ILLoader.Load.Type.Interface.cs | 2 +- .../load/ILLoader.Load.Type.Modified.cs | 2 +- .../load/ILLoader.Load.Type.Struct.Generic.cs | 2 +- .../load/ILLoader.Load.Type.Struct.cs | 2 +- .../il loader/load/ILLoader.Load.Type.cs | 2 +- .../ModuleBodyLoader.LazyLoad.cs | 2 +- .../module body loader/ModuleBodyLoader.cs | 2 +- .../load/ModuleBodyLoader.Load.Field.cs | 2 +- .../ModuleBodyLoader.Load.Method.Generic.cs | 2 +- .../load/ModuleBodyLoader.Load.Method.cs | 2 +- .../load/ModuleBodyLoader.Load.Property.cs | 2 +- .../load/ModuleBodyLoader.Load.cs | 2 +- .../module loader/ModuleLoader.cs | 2 +- .../load/ModuleLoader.Load.Field.cs | 2 +- .../load/ModuleLoader.Load.Method.Generic.cs | 2 +- .../load/ModuleLoader.Load.Method.cs | 2 +- .../load/ModuleLoader.Load.Property.cs | 2 +- .../module loader/load/ModuleLoader.Load.cs | 2 +- .../objects/GlobalUsings.cs | 0 .../function/concrete/Function.Call.cs | 9 +- .../modular/function/concrete/Function.IL.cs | 2 +- .../modular/function/concrete/Function.IR.cs | 2 +- .../modular/function/concrete/Function.cs | 2 +- .../function/generic/GenericFunction.IL.cs | 2 +- .../function/generic/GenericFunction.cs | 2 +- .../objects/modular/global/Global.IL.cs | 2 +- .../objects/modular/global/Global.Type.cs | 4 +- .../objects/modular/global/Global.cs | 2 +- .../objects/modular/module/Module.Globals.cs | 2 +- .../objects/modular/module/Module.IL.cs | 2 +- .../objects/modular/module/Module.LazyLoad.cs | 2 +- .../objects/modular/module/Module.Member.cs | 5 +- .../objects/modular/module/Module.cs | 2 +- .../modular/property/GlobalProperty.cs | 2 +- .../modular/type as module/TypeAsModule.IL.cs | 2 +- .../type as module/TypeAsModule.LazyLoad.cs | 2 +- .../type as module/TypeAsModule.Member.cs | 5 +- .../type as module/TypeAsModule.Namespace.cs | 2 +- .../type as module/TypeAsModule.Prepare.cs | 2 +- .../modular/type as module/TypeAsModule.cs | 2 +- .../objects/namespace/Namespace.LazyLoad.cs | 2 +- .../objects/namespace/Namespace.Member.cs | 5 +- .../objects/namespace/Namespace.OnAddTo.cs | 2 +- .../objects/namespace/Namespace.Parent.cs | 2 +- .../objects/namespace/Namespace.cs | 2 +- .../objects/oop/class/concrete/Class.IL.cs | 2 +- .../objects/oop/class/concrete/Class.IR.cs | 29 ++ .../objects/oop/class/concrete/Class.cs | 2 +- .../oop/class/generic/GenericClass.T.cs | 2 +- .../objects/oop/class/generic/GenericClass.cs | 2 +- .../objects/oop/constructor/Constructor.T.cs | 2 +- .../objects/oop/constructor/Constructor.cs | 2 +- .../objects/oop/enum/Enum.cs | 2 +- .../objects/oop/field/Field.cs | 2 +- .../oop/interface/concrete/Interface.cs | 2 +- .../interface/generic/GenericInterface.T.cs | 2 +- .../oop/interface/generic/GenericInterface.cs | 2 +- .../oop/method/bound/BoundMethod.Call.cs | 6 +- .../objects/oop/method/bound/BoundMethod.T.cs | 2 +- .../objects/oop/method/bound/BoundMethod.cs | 2 +- .../oop/method/concrete/Method.Call.cs | 8 +- .../objects/oop/method/concrete/Method.IL.cs | 2 +- .../objects/oop/method/concrete/Method.IR.cs | 2 +- .../objects/oop/method/concrete/Method.cs | 2 +- .../oop/method/generic/GenericMethod.T.cs | 2 +- .../oop/method/generic/GenericMethod.cs | 2 +- .../objects/oop/property/Property.cs | 2 +- .../objects/oop/struct/concrete/Struct.cs | 2 +- .../oop/struct/generic/GenericStruct.T.cs | 2 +- .../oop/struct/generic/GenericStruct.cs | 2 +- .../objects/types/array/ArrayType.cs | 2 +- .../objects/types/boolean/BooleanType.cs | 7 +- .../objects/types/char/CharType.cs | 7 +- .../objects/types/float/Float128Type.cs | 7 +- .../objects/types/float/Float16Type.cs | 7 +- .../objects/types/float/Float32Type.cs | 7 +- .../objects/types/float/Float64Type.cs | 7 +- .../objects/types/int/SInt16Type.cs | 7 +- .../objects/types/int/SInt32Type.cs | 7 +- .../objects/types/int/SInt64Type.cs | 7 +- .../objects/types/int/SInt8Type.cs | 7 +- .../objects/types/int/SIntNativeType.cs | 7 +- .../objects/types/int/UInt16Type.cs | 7 +- .../objects/types/int/UInt32Type.cs | 7 +- .../objects/types/int/UInt64Type.cs | 7 +- .../objects/types/int/UInt8Type.cs | 7 +- .../objects/types/int/UIntNativeType.cs | 7 +- .../objects/types/object/ObjectType.cs | 7 +- .../objects/types/pointer/PointerType.cs | 2 +- .../objects/types/reference/ReferenceType.cs | 2 +- .../objects/types/string/StringType.cs | 7 +- .../objects/types/void/VoidType.cs | 7 +- .../type system/TypeSystem.Array.cs | 2 +- .../type system/TypeSystem.Boolean.cs | 2 +- .../type system/TypeSystem.Char.cs | 2 +- .../type system/TypeSystem.Float.cs | 2 +- .../type system/TypeSystem.Object.cs | 2 +- .../type system/TypeSystem.Pointer.cs | 2 +- .../type system/TypeSystem.Reference.cs | 2 +- .../type system/TypeSystem.SInt.cs | 2 +- .../type system/TypeSystem.String.cs | 2 +- .../type system/TypeSystem.UInt.cs | 2 +- .../type system/TypeSystem.Void.cs | 2 +- .../type system/TypeSystem.cs | 2 +- .../Context.cs | 2 +- ZSharp.Importer.IRLoader/GlobalUsings.cs | 3 + .../ZSharp.Importer.IRLoader.csproj | 0 .../ir loader/IRLoader.API.cs | 2 +- .../ir loader/IRLoader.Impl.cs | 2 +- .../ir loader/IRLoader.cs | 2 +- ZSharp.Interpreter/ZSharp.Interpreter.csproj | 4 +- .../interpreter/Interpreter.IL.cs | 2 +- .../interpreter/Interpreter.Runtime.cs | 2 +- .../GlobalUsings.cs | 1 + .../ModuleAttributes.cs | 0 .../ZSharp.Library.Standard.FileSystem.csproj | 2 +- .../items/directory/Directory.From.cs | 0 .../items/directory/Directory.Items.cs | 0 .../items/directory/Directory.Name.cs | 0 .../items/directory/Directory.Operators.cs | 0 .../items/directory/Directory.cs | 0 .../items/file/File.From.cs | 0 .../items/file/File.Name.cs | 0 .../items/file/File.cs | 0 .../items/item/Item.Parent.cs | 0 .../items/item/Item.cs | 0 .../items/location/Location.cs | 0 .../module scope/ModuleScope.Operators.cs | 0 .../module scope/ModuleScope.cs | 0 .../path/AbsolutePath.cs | 0 .../path/Path.cs | 0 .../path/RawPath.cs | 0 .../path/RelativePath.cs | 0 ZSharp.Library.Standard.IO/GlobalUsings.cs | 1 + .../ModuleAttributes.cs | 0 .../ZSharp.Library.Standard.IO.csproj | 2 +- .../module scope/ModuleScope.Functions.cs | 0 .../module scope/ModuleScope.Operators.cs | 0 .../module scope/ModuleScope.cs | 0 ZSharp.Library.Standard.Math/GlobalUsings.cs | 1 + .../ModuleScope.cs | 20 +- .../ZSharp.Library.Standard.Math.csproj | 2 +- .../Compiler.cs | 2 +- .../ZSharp.Platform.IL.csproj | 0 .../compilers/ModuleCompiler.cs | 2 +- .../compilers/core/CompilerBase.cs | 2 +- .../compilers/core/Context.cs | 2 +- .../GlobalUsings.cs | 0 .../ZSharp.Platform.Runtime.csproj | 0 .../loader/GlobalUsings.cs | 0 .../loader/emit/EmitLoader.Standalone.cs | 2 +- .../loader/emit/EmitLoader.cs | 2 +- .../loader/emit/load/EmitLoader.Load.Code.cs | 2 +- .../emit/load/EmitLoader.Load.Function.cs | 2 +- .../emit/load/EmitLoader.Load.Module.cs | 2 +- .../loader/emit/load/EmitLoader.Load.Type.cs | 2 +- .../loader/helpers/LoaderBase.cs | 2 +- .../loader/helpers/TypeLoaderBase.cs | 2 +- .../loader/helpers/TypeLoaderHelper.cs | 2 +- .../loaders/class/ClassLoader.Context.cs | 2 +- .../loader/loaders/class/ClassLoader.Tasks.cs | 2 +- .../loader/loaders/class/ClassLoader.cs | 2 +- .../load/ClassLoader.Load.Constructor.cs | 2 +- .../class/load/ClassLoader.Load.Field.cs | 2 +- .../class/load/ClassLoader.Load.Generic.cs | 2 +- .../class/load/ClassLoader.Load.Method.cs | 2 +- .../class/load/ClassLoader.Load.Type.cs | 2 +- .../loaders/class/load/ClassLoader.Load.cs | 2 +- .../code/code contexts/FunctionCodeContext.cs | 2 +- .../code/code contexts/UnboundCodeContext.cs | 2 +- .../loader/loaders/code/code/CodeCompiler.cs | 2 +- .../code/branching/BranchingCodeCompiler.cs | 2 +- .../code/branching/IBranchingCodeContext.cs | 2 +- .../loaders/code/code/core/CodeStack.cs | 2 +- .../loaders/code/code/core/ICodeContext.cs | 2 +- .../code/code/frame/FrameCodeCompiler.cs | 2 +- .../code/code/frame/IFrameCodeContext.cs | 2 +- .../loader/loaders/code/code/frame/Local.cs | 2 +- .../loaders/code/code/frame/Parameter.cs | 2 +- .../code/functional/FunctionalCodeCompiler.cs | 2 +- .../code/functional/IFunctionalCodeContext.cs | 2 +- .../code/code/modular/ModularCodeCompiler.cs | 2 +- .../code/code/object/OOPCodeCompiler.cs | 2 +- .../code/code/stack/StackCodeCompiler.cs | 2 +- .../loader/loaders/enum/EnumClassLoader.cs | 2 +- .../enum/load/EnumClassLoader.Load.Method.cs | 2 +- .../enum/load/EnumClassLoader.Load.Type.cs | 2 +- .../enum/load/EnumClassLoader.Load.Value.cs | 2 +- .../loaders/enum/load/EnumClassLoader.Load.cs | 2 +- .../interface/InterfaceLoader.Context.cs | 2 +- .../interface/InterfaceLoader.Tasks.cs | 2 +- .../loaders/interface/InterfaceLoader.cs | 2 +- .../load/InterfaceLoader.Load.Generic.cs | 2 +- .../load/InterfaceLoader.Load.Method.cs | 2 +- .../load/InterfaceLoader.Load.Type.cs | 2 +- .../interface/load/InterfaceLoader.Load.cs | 2 +- .../loaders/module/ModuleLoader.Tasks.cs | 2 +- .../loader/loaders/module/ModuleLoader.cs | 2 +- .../module/load/ModuleLoader.Load.Function.cs | 2 +- .../module/load/ModuleLoader.Load.Global.cs | 2 +- .../module/load/ModuleLoader.Load.Type.cs | 2 +- .../loaders/module/load/ModuleLoader.Load.cs | 2 +- .../value type/ValueTypeLoader.Context.cs | 2 +- .../loaders/value type/ValueTypeLoader.T.cs | 2 +- .../value type/ValueTypeLoader.Tasks.cs | 2 +- .../loaders/value type/ValueTypeLoader.cs | 2 +- .../load/ValueTypeLoader.Load.Constructor.cs | 2 +- .../load/ValueTypeLoader.Load.Field.cs | 2 +- .../load/ValueTypeLoader.Load.Generic.cs | 2 +- .../load/ValueTypeLoader.Load.Method.cs | 2 +- .../load/ValueTypeLoader.Load.Type.cs | 2 +- .../value type/load/ValueTypeLoader.Load.cs | 2 +- .../runtime/Runtime.Evaluate.cs | 2 +- .../runtime/Runtime.Expose.cs | 2 +- .../runtime/Runtime.Loader.cs | 2 +- .../runtime/Runtime.Singleton.cs | 2 +- .../runtime/Runtime.TypeSystem.cs | 2 +- .../runtime/Runtime.cs | 2 +- .../runtime/cache/Runtime.Cache.Field.cs | 2 +- .../runtime/cache/Runtime.Cache.Function.cs | 2 +- .../runtime/cache/Runtime.Cache.Global.cs | 2 +- .../runtime/cache/Runtime.Cache.Module.cs | 2 +- .../runtime/cache/Runtime.Cache.Type.cs | 2 +- .../runtime/import/Runtime.Import.Callable.cs | 2 +- .../import/Runtime.Import.Constructor.cs | 2 +- .../runtime/import/Runtime.Import.Field.cs | 2 +- .../runtime/import/Runtime.Import.Function.cs | 2 +- .../runtime/import/Runtime.Import.Global.cs | 2 +- .../runtime/import/Runtime.Import.Method.cs | 2 +- .../runtime/import/Runtime.Import.Module.cs | 2 +- .../import/Runtime.Import.Type.Modified.cs | 2 +- .../runtime/import/Runtime.Import.Type.cs | 2 +- .../runtime/load/Runtime.Load.Function.cs | 2 +- .../runtime/load/Runtime.Load.Module.cs | 2 +- .../runtime/load/Runtime.Load.Type.cs | 2 +- .../tasks/TaskManager.cs | 2 +- .../type system/TypeSystem.Array.cs | 2 +- .../type system/TypeSystem.Boolean.cs | 2 +- .../type system/TypeSystem.Char.cs | 2 +- .../type system/TypeSystem.Float.cs | 2 +- .../type system/TypeSystem.Object.cs | 2 +- .../type system/TypeSystem.Pointer.cs | 2 +- .../type system/TypeSystem.Reference.cs | 2 +- .../type system/TypeSystem.SInt.cs | 2 +- .../type system/TypeSystem.String.cs | 2 +- .../type system/TypeSystem.UInt.cs | 2 +- .../type system/TypeSystem.Void.cs | 2 +- .../type system/TypeSystem.cs | 2 +- .../ZSharp.SourceCompiler.Module.csproj | 4 +- ZSharp.SourceCompiler.Project/GlobalUsings.cs | 2 +- .../ZSharp.SourceCompiler.Project.csproj | 4 +- ZSharpParserTest/Program.cs | 40 -- ZSharpParserTest/ZSharpParserTest.csproj | 21 - ZSharpParserTest/parserText.txt | 89 ---- ZSharpTest/DotNETImporter.cs | 51 --- ZSharpTest/Main.cs | 247 ----------- ZSharpTest/Program.cs | 417 ------------------ ZSharpTest/Properties/launchSettings.json | 36 -- ZSharpTest/ZSharpTest.csproj | 58 --- ZSharpTest/projects/better-user-system.zs | 95 ---- ZSharpTest/projects/build.zs | 76 ---- ZSharpTest/projects/guessing-game.zs | 39 -- ZSharpTest/projects/simple-user-system.zs | 103 ----- ZSharpTest/projects/todo.zs | 71 --- ZSharpTest/test.zs | 10 - ZSharpTest/test2.zs | 60 --- ZSharpTest/tests/simple.zs | 130 ------ ZSharpTest/tests/test-class-fields.zs | 51 --- ZSharpTest/tests/test-if-statement.zs | 17 - ZSharpTest/tests/test-while-expression.zs | 16 - ZSharpTokenizerTest/Program.cs | 11 - .../ZSharpTokenizerTest.csproj | 20 - ZSharpTokenizerTest/tokenizerText.txt | 10 - 432 files changed, 466 insertions(+), 2639 deletions(-) delete mode 100644 ZLoad.Test/BaseClass.cs delete mode 100644 ZLoad.Test/Console.cs delete mode 100644 ZLoad.Test/Globals.cs delete mode 100644 ZLoad.Test/Standard.List.Iterator.cs delete mode 100644 ZLoad.Test/Standard.List.cs delete mode 100644 ZLoad.Test/TestClass.cs delete mode 100644 ZLoad.Test/TestEnum.cs delete mode 100644 ZLoad.Test/TestInterface.cs delete mode 100644 ZSC.Project/Program.cs delete mode 100644 ZSC.Project/Properties/launchSettings.json delete mode 100644 ZSC.Project/ZSC.Project.csproj rename {ZSC.Script => ZSharp.CLI}/CLIArgumentLogOrigin.cs (90%) rename {ZSC.Script => ZSharp.CLI}/Program.cs (97%) rename {ZSC.Script => ZSharp.CLI}/ZSCScriptLogOrigin.cs (92%) rename ZSC.Script/ZSC.Script.csproj => ZSharp.CLI/ZSharp.CLI.csproj (66%) delete mode 100644 ZSharp.CT.CompilerAPI/Fields_Globals.cs delete mode 100644 ZSharp.CT.CompilerAPI/Impl_Globals.cs delete mode 100644 ZSharp.CT.CompilerAPI/ZSharp.CT.CompilerAPI.csproj delete mode 100644 ZSharp.CT.RuntimeAPI/Fields_Globals.cs delete mode 100644 ZSharp.CT.RuntimeAPI/Impl_Globals.cs delete mode 100644 ZSharp.CT.RuntimeAPI/ZSharp.CT.RuntimeAPI.csproj delete mode 100644 ZSharp.CT.StandardLibrary.FileSystem/GlobalUsings.cs delete mode 100644 ZSharp.CT.StandardLibrary.IO/GlobalUsings.cs delete mode 100644 ZSharp.CT.StandardLibrary/Impl_Globals.cs delete mode 100644 ZSharp.CT.StandardLibrary/ZSharp.CT.StandardLibrary.csproj rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/GlobalUsings.cs (100%) rename ZSharp.Compiler.CO.CT/ZSharp.Compiler.CO.CT.csproj => ZSharp.Compiler.CG.Direct/ZSharp.Compiler.CG.Direct.csproj (82%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Direct}/dispatcher/Dispatcher.cs (93%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/dispatcher/services/Dispatcher.Call.cs (88%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/dispatcher/services/Dispatcher.Cast.cs (88%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/dispatcher/services/Dispatcher.ImplicitCast.cs (91%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/dispatcher/services/Dispatcher.Index.cs (93%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/dispatcher/services/Dispatcher.Match.cs (88%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/dispatcher/services/Dispatcher.MemberAccess.cs (96%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/dispatcher/services/Dispatcher.ValueAccess.cs (92%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/protocols/callable/ICTCallable.cs (100%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/protocols/implicit casting/ICTImplicitCastFrom.cs (100%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/protocols/implicit casting/ICTImplicitCastTo.cs (100%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/protocols/index/ICTGetIndex.cs (100%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/protocols/index/ICTSetIndex.cs (100%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/protocols/member access/ICTGetMember.cs (100%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/protocols/member access/ICTSetMember.cs (100%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/protocols/type casting/ICTCastTo.cs (100%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/protocols/type matching/ICTTypeMatch.cs (100%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/protocols/value access/ICTGet.cs (100%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Direct}/protocols/value access/ICTSet.cs (100%) rename {ZSharp.Compiler.CO.Proxy => ZSharp.Compiler.CG.Proxy}/GlobalUsings.cs (100%) rename ZSharp.Compiler.CO.Proxy/ZSharp.Compiler.CO.Proxy.csproj => ZSharp.Compiler.CG.Proxy/ZSharp.Compiler.CG.Proxy.csproj (82%) rename {ZSharp.Compiler.CO.Proxy => ZSharp.Compiler.CG.Proxy}/dispatcher/Dispatcher.cs (100%) rename {ZSharp.Compiler.CO.Proxy => ZSharp.Compiler.CG.Proxy}/dispatcher/services/Dispatcher.Call.cs (100%) rename {ZSharp.Compiler.CO.Proxy => ZSharp.Compiler.CG.Proxy}/dispatcher/services/Dispatcher.Cast.cs (100%) rename {ZSharp.Compiler.CO.Proxy => ZSharp.Compiler.CG.Proxy}/dispatcher/services/Dispatcher.ImplicitCast.cs (100%) rename {ZSharp.Compiler.CO.Proxy => ZSharp.Compiler.CG.Proxy}/dispatcher/services/Dispatcher.Index.cs (100%) rename {ZSharp.Compiler.CO.Proxy => ZSharp.Compiler.CG.Proxy}/dispatcher/services/Dispatcher.Match.cs (100%) rename {ZSharp.Compiler.CO.Proxy => ZSharp.Compiler.CG.Proxy}/dispatcher/services/Dispatcher.MemberAccess.cs (100%) rename {ZSharp.Compiler.CO.Proxy => ZSharp.Compiler.CG.Proxy}/dispatcher/services/Dispatcher.ValueAccess.cs (100%) rename {ZSharp.Compiler.CO.Proxy => ZSharp.Compiler.CG.Proxy}/protocols/IProxy.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/GlobalUsings.cs (100%) rename ZSharp.Compiler.CO.RT/ZSharp.Compiler.CO.RT.csproj => ZSharp.Compiler.CG.Typed/ZSharp.Compiler.CG.Typed.csproj (82%) rename {ZSharp.Compiler.CO.CT => ZSharp.Compiler.CG.Typed}/dispatcher/Dispatcher.cs (93%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/dispatcher/services/Dispatcher.Call.cs (89%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/dispatcher/services/Dispatcher.Cast.cs (89%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/dispatcher/services/Dispatcher.ImplicitCast.cs (93%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/dispatcher/services/Dispatcher.Index.cs (94%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/dispatcher/services/Dispatcher.Match.cs (90%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/dispatcher/services/Dispatcher.MemberAccess.cs (97%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/dispatcher/services/Dispatcher.ValueAccess.cs (93%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/extensions/CompilerExtensions.cs (87%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/callable/IRTCallable.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/implicit casting/IRTImplicitCastTo.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/index/IRTGetIndex.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/index/IRTSetIndex.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/member access/IRTGetMember.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/member access/IRTSetMember.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/runtime/IHasRuntimeDescriptor.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/type casting/IRTCastFrom.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/type casting/IRTCastTo.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/type matching/IRTTypeMatch.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/value access/IRTGet.cs (100%) rename {ZSharp.Compiler.CO.RT => ZSharp.Compiler.CG.Typed}/protocols/value access/IRTSet.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/GlobalUsings.cs (100%) rename ZSharp.Compiler.CO/ZSharp.Compiler.CO.csproj => ZSharp.Compiler.CG/ZSharp.Compiler.CG.csproj (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/cg/CG.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/cg/services/CG.Call.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/cg/services/CG.Cast.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/cg/services/CG.ImplicitCast.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/cg/services/CG.Index.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/cg/services/CG.Match.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/cg/services/CG.MemberAccess.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/cg/services/CG.ValueAccess.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/core/Argument.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/core/CastResult.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/core/MatchResult.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/dispatcher/Dispatcher.Call.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/dispatcher/Dispatcher.Cast.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/dispatcher/Dispatcher.ImplicitCast.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/dispatcher/Dispatcher.Index.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/dispatcher/Dispatcher.Match.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/dispatcher/Dispatcher.MemberAccess.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/dispatcher/Dispatcher.Runtime.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/dispatcher/Dispatcher.ValueAccess.cs (100%) rename {ZSharp.Compiler.CO => ZSharp.Compiler.CG}/dispatcher/Dispatcher.cs (100%) delete mode 100644 ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IR.cs delete mode 100644 ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.T.cs delete mode 100644 ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.T.cs delete mode 100644 ZSharp.Compiler.ILLoader/objects/oop/field/Field.T.cs delete mode 100644 ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.T.cs delete mode 100644 ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.T.cs delete mode 100644 ZSharp.Compiler.ILLoader/objects/oop/property/Property.T.cs delete mode 100644 ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.T.cs delete mode 100644 ZSharp.Compiler.IRLoader/GlobalUsings.cs rename ZSharp.Compiler.ILLoader.Attributes/ZSharp.Compiler.ILLoader.Attributes.csproj => ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj (77%) rename {ZSharp.Compiler.ILLoader.Attributes => ZSharp.Importer.ILLoader.Attributes}/AliasAttribute.cs (93%) rename {ZSharp.Compiler.ILLoader.Attributes => ZSharp.Importer.ILLoader.Attributes}/HideImportAttribute.cs (91%) rename {ZSharp.Compiler.ILLoader.Attributes => ZSharp.Importer.ILLoader.Attributes}/ModuleScopeAttribute.cs (81%) rename ZSharp.CT.StandardLibrary.Math/ZSharp.CT.StandardLibrary.Math.csproj => ZSharp.Importer.ILLoader.Attributes/ZSharp.Importer.ILLoader.Attributes.csproj (65%) rename {ZSharp.Compiler.ILLoader.Attributes => ZSharp.Importer.ILLoader.Attributes}/namespace/AddNamespaceAttribute.cs (92%) rename {ZSharp.Compiler.ILLoader.Attributes => ZSharp.Importer.ILLoader.Attributes}/namespace/MapNamespaceAttribute.cs (87%) rename {ZSharp.Compiler.ILLoader.Attributes => ZSharp.Importer.ILLoader.Attributes}/namespace/SetNamespaceAttribute.cs (92%) rename {ZSharp.Compiler.ILLoader.Attributes => ZSharp.Importer.ILLoader.Attributes}/operator/OperatorAttribute.cs (88%) rename {ZSharp.Compiler.ILLoader.Attributes => ZSharp.Importer.ILLoader.Attributes}/operator/OperatorKind.cs (70%) rename {ZSharp.Compiler.ILLoader.Attributes => ZSharp.Importer.ILLoader.Attributes}/parameter/NamedParameterAttribute.cs (82%) rename {ZSharp.Compiler.ILLoader.Attributes => ZSharp.Importer.ILLoader.Attributes}/parameter/VarParameterAttribute.cs (81%) create mode 100644 ZSharp.Importer.ILLoader/GlobalUsings.cs rename ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj => ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/capabilities/ITypeModifier.cs (74%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/capabilities/internal/IAddMember.cs (75%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/capabilities/internal/ILazilyLoadMembers.cs (79%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/capabilities/on add/IOnAddTo.cs (100%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/capabilities/on add/OnAddResult.cs (100%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/extensions/ILLoaderExtensions.cs (84%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/extensions/InternalILMemberExtensions.cs (95%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/ILLoader.Events.cs (75%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/ILLoader.Expose.cs (98%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/ILLoader.IR.cs (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/ILLoader.Namespaces.cs (93%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/ILLoader.Runtime.cs (50%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/ILLoader.TypeSystem.cs (70%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/ILLoader.cs (96%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Member.Constructor.cs (83%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Member.Event.cs (81%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Member.Field.cs (81%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Member.Method.Generic.cs (82%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Member.Method.cs (89%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Member.Property.cs (82%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Member.cs (95%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Module.cs (93%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Type.Class.Generic.cs (81%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Type.Class.cs (87%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Type.Enum.cs (81%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Type.Generic.cs (82%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Type.Interface.Generic.cs (82%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Type.Interface.cs (88%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Type.Modified.cs (97%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Type.Struct.Generic.cs (81%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Type.Struct.cs (87%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/il loader/load/ILLoader.Load.Type.cs (95%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module body loader/ModuleBodyLoader.LazyLoad.cs (95%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module body loader/ModuleBodyLoader.cs (84%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module body loader/load/ModuleBodyLoader.Load.Field.cs (88%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs (83%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module body loader/load/ModuleBodyLoader.Load.Method.cs (91%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module body loader/load/ModuleBodyLoader.Load.Property.cs (83%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module body loader/load/ModuleBodyLoader.Load.cs (92%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module loader/ModuleLoader.cs (77%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module loader/load/ModuleLoader.Load.Field.cs (88%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module loader/load/ModuleLoader.Load.Method.Generic.cs (83%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module loader/load/ModuleLoader.Load.Method.cs (91%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module loader/load/ModuleLoader.Load.Property.cs (83%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/module loader/load/ModuleLoader.Load.cs (91%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/GlobalUsings.cs (100%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/function/concrete/Function.Call.cs (74%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/function/concrete/Function.IL.cs (75%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/function/concrete/Function.IR.cs (93%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/function/concrete/Function.cs (71%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/function/generic/GenericFunction.IL.cs (66%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/function/generic/GenericFunction.cs (65%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/global/Global.IL.cs (63%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/global/Global.Type.cs (59%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/global/Global.cs (85%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/module/Module.Globals.cs (93%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/module/Module.IL.cs (62%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/module/Module.LazyLoad.cs (87%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/module/Module.Member.cs (89%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/module/Module.cs (96%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/property/GlobalProperty.cs (57%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/type as module/TypeAsModule.IL.cs (63%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/type as module/TypeAsModule.LazyLoad.cs (87%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/type as module/TypeAsModule.Member.cs (89%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/type as module/TypeAsModule.Namespace.cs (66%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/type as module/TypeAsModule.Prepare.cs (95%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/modular/type as module/TypeAsModule.cs (92%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/namespace/Namespace.LazyLoad.cs (92%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/namespace/Namespace.Member.cs (89%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/namespace/Namespace.OnAddTo.cs (86%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/namespace/Namespace.Parent.cs (88%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/namespace/Namespace.cs (82%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/class/concrete/Class.IL.cs (71%) create mode 100644 ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/class/concrete/Class.cs (80%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/class/generic/GenericClass.T.cs (51%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/class/generic/GenericClass.cs (65%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/constructor/Constructor.T.cs (50%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/constructor/Constructor.cs (64%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/enum/Enum.cs (62%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/field/Field.cs (63%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/interface/concrete/Interface.cs (64%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/interface/generic/GenericInterface.T.cs (53%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/interface/generic/GenericInterface.cs (66%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/method/bound/BoundMethod.Call.cs (64%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/method/bound/BoundMethod.T.cs (50%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/method/bound/BoundMethod.cs (81%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/method/concrete/Method.Call.cs (74%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/method/concrete/Method.IL.cs (72%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/method/concrete/Method.IR.cs (93%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/method/concrete/Method.cs (81%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/method/generic/GenericMethod.T.cs (51%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/method/generic/GenericMethod.cs (65%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/property/Property.cs (64%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/struct/concrete/Struct.cs (63%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/struct/generic/GenericStruct.T.cs (51%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/oop/struct/generic/GenericStruct.cs (65%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/array/ArrayType.cs (78%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/boolean/BooleanType.cs (59%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/char/CharType.cs (58%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/float/Float128Type.cs (59%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/float/Float16Type.cs (59%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/float/Float32Type.cs (59%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/float/Float64Type.cs (59%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/int/SInt16Type.cs (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/int/SInt32Type.cs (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/int/SInt64Type.cs (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/int/SInt8Type.cs (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/int/SIntNativeType.cs (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/int/UInt16Type.cs (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/int/UInt32Type.cs (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/int/UInt64Type.cs (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/int/UInt8Type.cs (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/int/UIntNativeType.cs (56%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/object/ObjectType.cs (58%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/pointer/PointerType.cs (78%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/reference/ReferenceType.cs (78%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/string/StringType.cs (58%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/objects/types/void/VoidType.cs (58%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.Array.cs (73%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.Boolean.cs (73%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.Char.cs (73%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.Float.cs (88%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.Object.cs (73%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.Pointer.cs (73%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.Reference.cs (74%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.SInt.cs (90%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.String.cs (73%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.UInt.cs (90%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.Void.cs (73%) rename {ZSharp.Compiler.ILLoader => ZSharp.Importer.ILLoader}/type system/TypeSystem.cs (64%) rename {ZSharp.Compiler.IRLoader => ZSharp.Importer.IRLoader}/Context.cs (86%) create mode 100644 ZSharp.Importer.IRLoader/GlobalUsings.cs rename ZSharp.Compiler.IRLoader/ZSharp.Compiler.IRLoader.csproj => ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj (100%) rename {ZSharp.Compiler.IRLoader => ZSharp.Importer.IRLoader}/ir loader/IRLoader.API.cs (74%) rename {ZSharp.Compiler.IRLoader => ZSharp.Importer.IRLoader}/ir loader/IRLoader.Impl.cs (99%) rename {ZSharp.Compiler.IRLoader => ZSharp.Importer.IRLoader}/ir loader/IRLoader.cs (95%) create mode 100644 ZSharp.Library.Standard.FileSystem/GlobalUsings.cs rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/ModuleAttributes.cs (100%) rename ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj => ZSharp.Library.Standard.FileSystem/ZSharp.Library.Standard.FileSystem.csproj (71%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/items/directory/Directory.From.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/items/directory/Directory.Items.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/items/directory/Directory.Name.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/items/directory/Directory.Operators.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/items/directory/Directory.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/items/file/File.From.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/items/file/File.Name.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/items/file/File.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/items/item/Item.Parent.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/items/item/Item.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/items/location/Location.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/module scope/ModuleScope.Operators.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/module scope/ModuleScope.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/path/AbsolutePath.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/path/Path.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/path/RawPath.cs (100%) rename {ZSharp.CT.StandardLibrary.FileSystem => ZSharp.Library.Standard.FileSystem}/path/RelativePath.cs (100%) create mode 100644 ZSharp.Library.Standard.IO/GlobalUsings.cs rename {ZSharp.CT.StandardLibrary.IO => ZSharp.Library.Standard.IO}/ModuleAttributes.cs (100%) rename ZLoad.Test/ZLoad.Test.csproj => ZSharp.Library.Standard.IO/ZSharp.Library.Standard.IO.csproj (67%) rename {ZSharp.CT.StandardLibrary.IO => ZSharp.Library.Standard.IO}/module scope/ModuleScope.Functions.cs (100%) rename {ZSharp.CT.StandardLibrary.IO => ZSharp.Library.Standard.IO}/module scope/ModuleScope.Operators.cs (100%) rename {ZSharp.CT.StandardLibrary.IO => ZSharp.Library.Standard.IO}/module scope/ModuleScope.cs (100%) create mode 100644 ZSharp.Library.Standard.Math/GlobalUsings.cs rename ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs => ZSharp.Library.Standard.Math/ModuleScope.cs (61%) rename ZSharp.CT.StandardLibrary.IO/ZSharp.CT.StandardLibrary.IO.csproj => ZSharp.Library.Standard.Math/ZSharp.Library.Standard.Math.csproj (67%) rename {ZSharp.NETCompiler => ZSharp.Platform.IL}/Compiler.cs (94%) rename ZSharp.NETCompiler/ZSharp.NETCompiler.csproj => ZSharp.Platform.IL/ZSharp.Platform.IL.csproj (100%) rename {ZSharp.NETCompiler => ZSharp.Platform.IL}/compilers/ModuleCompiler.cs (64%) rename {ZSharp.NETCompiler => ZSharp.Platform.IL}/compilers/core/CompilerBase.cs (79%) rename {ZSharp.NETCompiler => ZSharp.Platform.IL}/compilers/core/Context.cs (60%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/GlobalUsings.cs (100%) rename ZSharp.Runtime/ZSharp.Runtime.csproj => ZSharp.Platform.Runtime/ZSharp.Platform.Runtime.csproj (100%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/GlobalUsings.cs (100%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/emit/EmitLoader.Standalone.cs (79%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/emit/EmitLoader.cs (92%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/emit/load/EmitLoader.Load.Code.cs (96%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/emit/load/EmitLoader.Load.Function.cs (98%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/emit/load/EmitLoader.Load.Module.cs (77%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/emit/load/EmitLoader.Load.Type.cs (78%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/helpers/LoaderBase.cs (73%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/helpers/TypeLoaderBase.cs (94%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/helpers/TypeLoaderHelper.cs (98%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/class/ClassLoader.Context.cs (75%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/class/ClassLoader.Tasks.cs (90%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/class/ClassLoader.cs (74%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/class/load/ClassLoader.Load.Constructor.cs (94%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/class/load/ClassLoader.Load.Field.cs (90%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/class/load/ClassLoader.Load.Generic.cs (91%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/class/load/ClassLoader.Load.Method.cs (96%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/class/load/ClassLoader.Load.Type.cs (80%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/class/load/ClassLoader.Load.cs (97%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code contexts/FunctionCodeContext.cs (98%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code contexts/UnboundCodeContext.cs (93%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/CodeCompiler.cs (99%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/branching/BranchingCodeCompiler.cs (94%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/branching/IBranchingCodeContext.cs (82%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/core/CodeStack.cs (92%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/core/ICodeContext.cs (79%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/frame/FrameCodeCompiler.cs (98%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/frame/IFrameCodeContext.cs (81%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/frame/Local.cs (81%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/frame/Parameter.cs (81%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs (96%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/functional/IFunctionalCodeContext.cs (73%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/modular/ModularCodeCompiler.cs (92%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/object/OOPCodeCompiler.cs (97%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/code/code/stack/StackCodeCompiler.cs (97%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/enum/EnumClassLoader.cs (75%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/enum/load/EnumClassLoader.Load.Method.cs (96%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs (80%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/enum/load/EnumClassLoader.Load.Value.cs (90%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/enum/load/EnumClassLoader.Load.cs (96%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/interface/InterfaceLoader.Context.cs (76%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/interface/InterfaceLoader.Tasks.cs (90%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/interface/InterfaceLoader.cs (75%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/interface/load/InterfaceLoader.Load.Generic.cs (91%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/interface/load/InterfaceLoader.Load.Method.cs (96%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs (80%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/interface/load/InterfaceLoader.Load.cs (96%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/module/ModuleLoader.Tasks.cs (84%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/module/ModuleLoader.cs (94%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/module/load/ModuleLoader.Load.Function.cs (96%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/module/load/ModuleLoader.Load.Global.cs (89%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/module/load/ModuleLoader.Load.Type.cs (77%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/module/load/ModuleLoader.Load.cs (97%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/value type/ValueTypeLoader.Context.cs (76%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/value type/ValueTypeLoader.T.cs (56%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/value type/ValueTypeLoader.Tasks.cs (91%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/value type/ValueTypeLoader.cs (87%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/value type/load/ValueTypeLoader.Load.Constructor.cs (94%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/value type/load/ValueTypeLoader.Load.Field.cs (90%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/value type/load/ValueTypeLoader.Load.Generic.cs (91%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/value type/load/ValueTypeLoader.Load.Method.cs (96%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs (80%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/loader/loaders/value type/load/ValueTypeLoader.Load.cs (97%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/Runtime.Evaluate.cs (87%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/Runtime.Expose.cs (98%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/Runtime.Loader.cs (71%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/Runtime.Singleton.cs (71%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/Runtime.TypeSystem.cs (70%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/Runtime.cs (95%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/cache/Runtime.Cache.Field.cs (91%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/cache/Runtime.Cache.Function.cs (92%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/cache/Runtime.Cache.Global.cs (91%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/cache/Runtime.Cache.Module.cs (91%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/cache/Runtime.Cache.Type.cs (97%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/import/Runtime.Import.Callable.cs (95%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/import/Runtime.Import.Constructor.cs (97%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/import/Runtime.Import.Field.cs (96%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/import/Runtime.Import.Function.cs (94%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/import/Runtime.Import.Global.cs (91%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/import/Runtime.Import.Method.cs (97%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/import/Runtime.Import.Module.cs (88%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/import/Runtime.Import.Type.Modified.cs (95%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/import/Runtime.Import.Type.cs (97%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/load/Runtime.Load.Function.cs (91%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/load/Runtime.Load.Module.cs (78%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/runtime/load/Runtime.Load.Type.cs (90%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/tasks/TaskManager.cs (93%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.Array.cs (73%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.Boolean.cs (75%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.Char.cs (74%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.Float.cs (89%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.Object.cs (75%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.Pointer.cs (73%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.Reference.cs (73%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.SInt.cs (91%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.String.cs (75%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.UInt.cs (91%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.Void.cs (74%) rename {ZSharp.Runtime => ZSharp.Platform.Runtime}/type system/TypeSystem.cs (64%) delete mode 100644 ZSharpParserTest/Program.cs delete mode 100644 ZSharpParserTest/ZSharpParserTest.csproj delete mode 100644 ZSharpParserTest/parserText.txt delete mode 100644 ZSharpTest/DotNETImporter.cs delete mode 100644 ZSharpTest/Main.cs delete mode 100644 ZSharpTest/Program.cs delete mode 100644 ZSharpTest/Properties/launchSettings.json delete mode 100644 ZSharpTest/ZSharpTest.csproj delete mode 100644 ZSharpTest/projects/better-user-system.zs delete mode 100644 ZSharpTest/projects/build.zs delete mode 100644 ZSharpTest/projects/guessing-game.zs delete mode 100644 ZSharpTest/projects/simple-user-system.zs delete mode 100644 ZSharpTest/projects/todo.zs delete mode 100644 ZSharpTest/test.zs delete mode 100644 ZSharpTest/test2.zs delete mode 100644 ZSharpTest/tests/simple.zs delete mode 100644 ZSharpTest/tests/test-class-fields.zs delete mode 100644 ZSharpTest/tests/test-if-statement.zs delete mode 100644 ZSharpTest/tests/test-while-expression.zs delete mode 100644 ZSharpTokenizerTest/Program.cs delete mode 100644 ZSharpTokenizerTest/ZSharpTokenizerTest.csproj delete mode 100644 ZSharpTokenizerTest/tokenizerText.txt diff --git a/Testing/Program.cs b/Testing/Program.cs index b28ee61a..b5b49cac 100644 --- a/Testing/Program.cs +++ b/Testing/Program.cs @@ -1,9 +1,9 @@ -using ZSharp.Compiler.ILLoader; -using Objects = ZSharp.Compiler.ILLoader.Objects; +using ZSharp.Importer.ILLoader; +using Objects = ZSharp.Importer.ILLoader.Objects; var rtm = ZSharp.IR.RuntimeModule.Standard; var coc = new ZSharp.Compiler.Compiler(rtm); -var rt = new ZSharp.Runtime.Runtime(new() +var rt = new ZSharp.Platform.Runtime.Runtime(new() { Array = rtm.TypeSystem.Array, Boolean = rtm.TypeSystem.Boolean, diff --git a/Testing/Testing.csproj b/Testing/Testing.csproj index 12ebe4ec..7a1bad7a 100644 --- a/Testing/Testing.csproj +++ b/Testing/Testing.csproj @@ -8,8 +8,7 @@ - - + diff --git a/ZLoad.Test/BaseClass.cs b/ZLoad.Test/BaseClass.cs deleted file mode 100644 index f48ebed2..00000000 --- a/ZLoad.Test/BaseClass.cs +++ /dev/null @@ -1,13 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace ZLoad.Test -{ - public class BaseClass - { - [Alias(Name = "doVirtual")] - public virtual void DoVirtual() - { - Console.WriteLine("BaseClass::DoVirtual()"); - } - } -} diff --git a/ZLoad.Test/Console.cs b/ZLoad.Test/Console.cs deleted file mode 100644 index e0dc9f85..00000000 --- a/ZLoad.Test/Console.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZLoad.Test -{ - public static class Console - { - public static void WriteLine(string value) - { - System.Console.WriteLine(value); - } - } -} diff --git a/ZLoad.Test/Globals.cs b/ZLoad.Test/Globals.cs deleted file mode 100644 index 6bd49477..00000000 --- a/ZLoad.Test/Globals.cs +++ /dev/null @@ -1,16 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace ZLoad.Test -{ - [ModuleGlobals] - public static partial class Globals - { - [Alias(Name = "greet")] - public static string Greet(string name) - => $"Hello, {name}!"; - - [Alias(Name = "id")] - public static T Id(T v) - => v; - } -} diff --git a/ZLoad.Test/Standard.List.Iterator.cs b/ZLoad.Test/Standard.List.Iterator.cs deleted file mode 100644 index 96a7ce14..00000000 --- a/ZLoad.Test/Standard.List.Iterator.cs +++ /dev/null @@ -1,17 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace Standard.List -{ - public sealed class ListIterator - { - internal IEnumerator Enumerator { get; init; } - - [Alias(Name = "moveNext")] - public bool MoveNext() - => Enumerator.MoveNext(); - - [Alias(Name = "getCurrent")] - public T GetCurrentValue() - => Enumerator.Current; - } -} diff --git a/ZLoad.Test/Standard.List.cs b/ZLoad.Test/Standard.List.cs deleted file mode 100644 index 0bc9ca2b..00000000 --- a/ZLoad.Test/Standard.List.cs +++ /dev/null @@ -1,39 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace Standard.List -{ - public sealed class List - { - private readonly System.Collections.Generic.List _inner = []; - - public List() { } - - [Alias(Name = "length")] - public int Length() - => _inner.Count; - - - [Alias(Name = "append")] - public void Add(T item) - { - _inner.Add(item); - } - - [Alias(Name = "get")] - public T Get(int index) - { - return _inner[index]; - } - - [Alias(Name = "removeAt")] - public void RemoveAt(int index) - => _inner.RemoveAt(index); - - [Alias(Name = "getIterator")] - public ListIterator GetIterator() - => new() - { - Enumerator = _inner.GetEnumerator() - }; - } -} diff --git a/ZLoad.Test/TestClass.cs b/ZLoad.Test/TestClass.cs deleted file mode 100644 index a9d1f23a..00000000 --- a/ZLoad.Test/TestClass.cs +++ /dev/null @@ -1,15 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace ZLoad.Test -{ - public class TestClass : BaseClass - { - [Alias(Name = "id")] - public T Id(T v) => v; - - public override void DoVirtual() - { - Console.WriteLine("TestClass::DoVirtual"); - } - } -} diff --git a/ZLoad.Test/TestEnum.cs b/ZLoad.Test/TestEnum.cs deleted file mode 100644 index 1573df42..00000000 --- a/ZLoad.Test/TestEnum.cs +++ /dev/null @@ -1,4 +0,0 @@ -public enum TestEnum -{ - A, B, C -} diff --git a/ZLoad.Test/TestInterface.cs b/ZLoad.Test/TestInterface.cs deleted file mode 100644 index 1c0215f6..00000000 --- a/ZLoad.Test/TestInterface.cs +++ /dev/null @@ -1,13 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace ZLoad.Test -{ - public interface TestInterface - { - [Alias(Name = "do")] - public void Do(); - - [Alias(Name = "do")] - public int Calc(int x); - } -} diff --git a/ZSC.Project/Program.cs b/ZSC.Project/Program.cs deleted file mode 100644 index 7bcd4f39..00000000 --- a/ZSC.Project/Program.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System.Text; -using ZSharp.Compiler; -using ZSharp.Interpreter; -using ZSharp.Parser; -using ZSharp.SourceCompiler.Project; -using ZSharp.Text; -using ZSharp.Tokenizer; - - -#if false -#region Parsing - -ZSharp.AST.Document documentNode; -using (StreamReader stream = File.OpenText(filePath)) -{ - var zsharpParser = new ZSharpParser(); - var parser = new Parser(Tokenizer.Tokenize(new(stream))); - - var expressionParser = zsharpParser.Expression; - var statementParser = zsharpParser.Statement; - - expressionParser.Terminal( - TokenType.String, - token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.String) - ); - expressionParser.Terminal( - TokenType.Number, - token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Number) - ); - expressionParser.Terminal( - TokenType.Decimal, - token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Decimal) - ); - expressionParser.Terminal( - TokenType.Identifier, - token => token.Value switch - { - "null" => ZSharp.AST.LiteralExpression.Null(), - "true" => ZSharp.AST.LiteralExpression.True(), - "false" => ZSharp.AST.LiteralExpression.False(), - _ => new ZSharp.AST.IdentifierExpression(token.Value), - } - ); - expressionParser.Nud( - TokenType.LParen, - parser => - { - parser.Eat(TokenType.LParen); - var expression = parser.Parse(); - parser.Eat(TokenType.RParen); - - return expression; - }, - 10000 - ); - expressionParser.Nud( - LangParser.Keywords.Let, - LangParser.ParseLetExpression - ); - expressionParser.Nud( - LangParser.Keywords.Class, - zsharpParser.Class.Parse - ); - - expressionParser.InfixR("=", 10); - expressionParser.InfixL("<", 20); - expressionParser.InfixL("+", 50); - expressionParser.InfixL("-", 50); - expressionParser.InfixL("*", 70); - expressionParser.InfixL("/", 70); - expressionParser.InfixL("**", 80); - - expressionParser.InfixL("==", 30); - expressionParser.InfixL("!=", 30); - - expressionParser.InfixL(LangParser.Keywords.Or, 15); - - expressionParser.Led(TokenType.LParen, LangParser.ParseCallExpression, 100); - expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); - expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); - expressionParser.Led(".", LangParser.ParseMemberAccess, 150); - expressionParser.Led(LangParser.Keywords.As, LangParser.ParseCastExpression, 20); - expressionParser.Led(LangParser.Keywords.Is, LangParser.ParseIsOfExpression, 20); - - expressionParser.Separator(TokenType.Comma); - expressionParser.Separator(TokenType.RParen); - expressionParser.Separator(TokenType.RBracket); - expressionParser.Separator(TokenType.Semicolon); - - expressionParser.Separator(LangParser.Keywords.In); // until it's an operator - - expressionParser.AddKeywordParser( - LangParser.Keywords.While, - LangParser.ParseWhileExpression - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.While, - Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.If, - LangParser.ParseIfStatement - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.For, - LangParser.ParseForStatement - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.Case, - LangParser.ParseCaseStatement - ); - - //zsharpParser.Function.AddKeywordParser( - // LangParser.Keywords.While, - // Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) - //); - - zsharpParser.RegisterParsers(parser); - documentNode = zsharpParser.Parse(parser); - - Console.WriteLine($"Finished parsing document with {documentNode.Statements.Count} statements!"); -} - -#endregion -#endif - -#region Compilation - -var interpreter = new Interpreter(); - - -new Referencing(interpreter.Compiler); -new OOP(interpreter.Compiler); - -var projectRoot = args.Length == 0 - ? Standard.FileSystem.Directory.CurrentWorkingDirectory() - : Standard.FileSystem.Directory.From(args[0]) ?? throw new ArgumentException($"Path {args[0]} does not point to a valid directory") - ; -var project = new Project(projectRoot.Name, projectRoot, projectRoot / "src" as Standard.FileSystem.Directory); -ProjectDiscovery.Discover(project); - -#endregion - -Console.WriteLine(); - -Console.WriteLine(); -Console.WriteLine("Press any key to exit..."); -Console.ReadKey(); diff --git a/ZSC.Project/Properties/launchSettings.json b/ZSC.Project/Properties/launchSettings.json deleted file mode 100644 index 8d9b9a40..00000000 --- a/ZSC.Project/Properties/launchSettings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "profiles": { - "ZSC.Project": { - "commandName": "Project" - }, - "SafeSQL": { - "commandName": "Project", - "commandLineArgs": "D:/zsharp/zsv1-design/packages/safe-sql" - } - } -} \ No newline at end of file diff --git a/ZSC.Project/ZSC.Project.csproj b/ZSC.Project/ZSC.Project.csproj deleted file mode 100644 index 57e19e11..00000000 --- a/ZSC.Project/ZSC.Project.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - Exe - net8.0 - enable - enable - - - - - - - - - - - - diff --git a/ZSharp v1.sln b/ZSharp v1.sln index 2e91894b..268753bb 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -9,34 +9,19 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharp.AST", "ZSharp.AST\ZS EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharp.Text", "ZSharp.Text\ZSharp.Text.csproj", "{E81AC1F8-9CED-4E6E-B1F2-A9E66A1EBF63}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharpTest", "ZSharpTest\ZSharpTest.csproj", "{F89D890B-AC10-4CC1-A07D-E54CE0115F54}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharp.IR", "ZSharp.IR\ZSharp.IR.csproj", "{A6987B24-D697-4F9F-9615-9BE8641065A8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharp.Compiler", "ZSharp.Compiler\ZSharp.Compiler.csproj", "{678634DE-CD65-4020-AB16-CCC77E013299}" - ProjectSection(ProjectDependencies) = postProject - {50A7F0CE-AFEE-418E-89E3-96F41D45BF8A} = {50A7F0CE-AFEE-418E-89E3-96F41D45BF8A} - EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharp.Tokenizer", "ZSharp.Tokenizer\ZSharp.Tokenizer.csproj", "{2A7DE2EA-2347-465B-AFC4-62F46B380F30}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharpTokenizerTest", "ZSharpTokenizerTest\ZSharpTokenizerTest.csproj", "{DFE6B315-DF3D-4EE9-990C-068404AB9F83}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharp.Parser", "ZSharp.Parser\ZSharp.Parser.csproj", "{8523CD79-8272-4331-A49F-947B0269A42D}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharpParserTest", "ZSharpParserTest\ZSharpParserTest.csproj", "{0DC3D462-5240-4670-A5C2-04FCD7093F2E}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharp.CT.StandardLibrary", "ZSharp.CT.StandardLibrary\ZSharp.CT.StandardLibrary.csproj", "{7FCC6EEC-12BC-409C-93A9-0A4AF7B8E83B}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Interpreter", "ZSharp.Interpreter\ZSharp.Interpreter.csproj", "{F46A91F5-47BA-468A-81F0-FF6BCEB4112C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.IRLoader", "ZSharp.Compiler.IRLoader\ZSharp.Compiler.IRLoader.csproj", "{8E9A7EF0-EE8E-4481-BF60-C6BDBD5C7BB8}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.CompilerAPI", "ZSharp.CT.CompilerAPI\ZSharp.CT.CompilerAPI.csproj", "{7A85DEFF-0453-4252-8FFB-C8365AA84615}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Importer.IRLoader", "ZSharp.Importer.IRLoader\ZSharp.Importer.IRLoader.csproj", "{8E9A7EF0-EE8E-4481-BF60-C6BDBD5C7BB8}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.RuntimeAPI", "ZSharp.CT.RuntimeAPI\ZSharp.CT.RuntimeAPI.csproj", "{360265D8-8811-4A25-9060-AD9B9D334D8C}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.StandardLibrary.Math", "ZSharp.CT.StandardLibrary.Math\ZSharp.CT.StandardLibrary.Math.csproj", "{AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Library.Standard.Math", "ZSharp.Library.Standard.Math\ZSharp.Library.Standard.Math.csproj", "{AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Objects", "ZSharp.Compiler.Objects\ZSharp.Compiler.Objects.csproj", "{6B3BEDB2-F3CB-400E-A257-D79F73075AF9}" EndProject @@ -44,23 +29,19 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Features", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Testing", "Testing\Testing.csproj", "{8A5EB8BE-EDF3-444E-AC15-A3E9DEF1FC7F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZLoad.Test", "ZLoad.Test\ZLoad.Test.csproj", "{9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.StandardLibrary.FileSystem", "ZSharp.CT.StandardLibrary.FileSystem\ZSharp.CT.StandardLibrary.FileSystem.csproj", "{7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Library.Standard.FileSystem", "ZSharp.Library.Standard.FileSystem\ZSharp.Library.Standard.FileSystem.csproj", "{7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.NETCompiler", "ZSharp.NETCompiler\ZSharp.NETCompiler.csproj", "{2222D3B2-0148-4AAC-955C-679E7F20C2FA}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Platform.IL", "ZSharp.Platform.IL\ZSharp.Platform.IL.csproj", "{2222D3B2-0148-4AAC-955C-679E7F20C2FA}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.ILLoader", "ZSharp.Compiler.ILLoader\ZSharp.Compiler.ILLoader.csproj", "{980FAC95-52E8-499D-96A9-943EE4861EA0}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Importer.ILLoader", "ZSharp.Importer.ILLoader\ZSharp.Importer.ILLoader.csproj", "{980FAC95-52E8-499D-96A9-943EE4861EA0}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Runtime", "ZSharp.Runtime\ZSharp.Runtime.csproj", "{3CD28041-00F7-4A40-BEFD-4F77809BCBF7}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Platform.Runtime", "ZSharp.Platform.Runtime\ZSharp.Platform.Runtime.csproj", "{3CD28041-00F7-4A40-BEFD-4F77809BCBF7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.IR", "ZSharp.Compiler.IR\ZSharp.Compiler.IR.csproj", "{B3E3E076-4B77-433F-9466-D0A0D8D9EAFA}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.SourceCompiler.Project", "ZSharp.SourceCompiler.Project\ZSharp.SourceCompiler.Project.csproj", "{FBDD6EA4-FA23-47B3-8A41-538AE2EA575E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.ILLoader.Attributes", "ZSharp.Compiler.ILLoader.Attributes\ZSharp.Compiler.ILLoader.Attributes.csproj", "{42BF3911-0DC7-4831-A989-98D48C17CC74}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSC.Project", "ZSC.Project\ZSC.Project.csproj", "{A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Importer.ILLoader.Attributes", "ZSharp.Importer.ILLoader.Attributes\ZSharp.Importer.ILLoader.Attributes.csproj", "{42BF3911-0DC7-4831-A989-98D48C17CC74}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.SourceCompiler.Core", "ZSharp.SourceCompiler.Core\ZSharp.SourceCompiler.Core.csproj", "{2DF6ABEC-5B49-435D-A583-4C97C61D1558}" EndProject @@ -68,29 +49,31 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.SourceCompiler.Modul EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.SourceCompiler.Script", "ZSharp.SourceCompiler.Script\ZSharp.SourceCompiler.Script.csproj", "{51F7D757-1DBC-452B-84FF-45307ADCDF5C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSC.Script", "ZSC.Script\ZSC.Script.csproj", "{4DA26E46-B765-4A8C-BAE1-5E99D6138DAF}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CLI", "ZSharp.CLI\ZSharp.CLI.csproj", "{4DA26E46-B765-4A8C-BAE1-5E99D6138DAF}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Core", "ZSharp.Compiler.Core\ZSharp.Compiler.Core.csproj", "{F5CCD8B1-98F4-151B-C4FA-6E651CEC6193}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Logging", "ZSharp.Logging\ZSharp.Logging.csproj", "{EF96A6E6-190B-457B-AD9C-1057CD7EDBB2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CO.RT", "ZSharp.Compiler.CO.RT\ZSharp.Compiler.CO.RT.csproj", "{731BE61E-6C43-4628-B680-10467A73B4DC}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CO.CT", "ZSharp.Compiler.CO.CT\ZSharp.Compiler.CO.CT.csproj", "{30FB37EA-5FA6-A6BB-1934-49C19899D2D6}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CO", "ZSharp.Compiler.CO\ZSharp.Compiler.CO.csproj", "{B8B3E775-FB6C-50B9-BD2D-2C04C9615D0D}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.TS", "ZSharp.Compiler.TS\ZSharp.Compiler.TS.csproj", "{1864BBD1-5A3D-4FB1-B799-B736C5016191}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CO.Proxy", "ZSharp.Compiler.CO.Proxy\ZSharp.Compiler.CO.Proxy.csproj", "{51301FA2-449E-4666-B9DE-0EE9F4CD00EE}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.TS.Static", "ZSharp.Compiler.TS.Static\ZSharp.Compiler.TS.Static.csproj", "{C6FC0FBB-6E0B-437B-82B7-294D830109EA}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Context", "ZSharp.Compiler.Context\ZSharp.Compiler.Context.csproj", "{B2DD7DE5-8D23-4BA8-9AC6-808BF8FFF3CA}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.SourceCompiler.Common", "ZSharp.SourceCompiler.Common\ZSharp.SourceCompiler.Common.csproj", "{A3DB8E19-9047-4FF6-87E7-69BDC09647D1}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.CT.StandardLibrary.IO", "ZSharp.CT.StandardLibrary.IO\ZSharp.CT.StandardLibrary.IO.csproj", "{8BD20BCF-DC47-4B94-B40E-1A6B7137265C}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Library.Standard.IO", "ZSharp.Library.Standard.IO\ZSharp.Library.Standard.IO.csproj", "{8BD20BCF-DC47-4B94-B40E-1A6B7137265C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Overloading", "ZSharp.Compiler.Overloading\ZSharp.Compiler.Overloading.csproj", "{51026F8A-3101-41C7-BDD0-9275FE436410}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CG", "ZSharp.Compiler.CG\ZSharp.Compiler.CG.csproj", "{5653B9BD-331E-C526-0DA7-BD8CB9C9274C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CG.Direct", "ZSharp.Compiler.CG.Direct\ZSharp.Compiler.CG.Direct.csproj", "{4C08CAB6-8668-5DC7-96F5-0335E6AEF680}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CG.Proxy", "ZSharp.Compiler.CG.Proxy\ZSharp.Compiler.CG.Proxy.csproj", "{708FB37D-DCFE-2FEB-DADE-F5C80ACDE10F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CG.Typed", "ZSharp.Compiler.CG.Typed\ZSharp.Compiler.CG.Typed.csproj", "{62E6B22B-2057-8EFC-30D4-B6F497FEF9D8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -110,10 +93,6 @@ Global {E81AC1F8-9CED-4E6E-B1F2-A9E66A1EBF63}.Debug|Any CPU.Build.0 = Debug|Any CPU {E81AC1F8-9CED-4E6E-B1F2-A9E66A1EBF63}.Release|Any CPU.ActiveCfg = Release|Any CPU {E81AC1F8-9CED-4E6E-B1F2-A9E66A1EBF63}.Release|Any CPU.Build.0 = Release|Any CPU - {F89D890B-AC10-4CC1-A07D-E54CE0115F54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F89D890B-AC10-4CC1-A07D-E54CE0115F54}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F89D890B-AC10-4CC1-A07D-E54CE0115F54}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F89D890B-AC10-4CC1-A07D-E54CE0115F54}.Release|Any CPU.Build.0 = Release|Any CPU {A6987B24-D697-4F9F-9615-9BE8641065A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A6987B24-D697-4F9F-9615-9BE8641065A8}.Debug|Any CPU.Build.0 = Debug|Any CPU {A6987B24-D697-4F9F-9615-9BE8641065A8}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -126,22 +105,10 @@ Global {2A7DE2EA-2347-465B-AFC4-62F46B380F30}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A7DE2EA-2347-465B-AFC4-62F46B380F30}.Release|Any CPU.ActiveCfg = Release|Any CPU {2A7DE2EA-2347-465B-AFC4-62F46B380F30}.Release|Any CPU.Build.0 = Release|Any CPU - {DFE6B315-DF3D-4EE9-990C-068404AB9F83}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DFE6B315-DF3D-4EE9-990C-068404AB9F83}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DFE6B315-DF3D-4EE9-990C-068404AB9F83}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DFE6B315-DF3D-4EE9-990C-068404AB9F83}.Release|Any CPU.Build.0 = Release|Any CPU {8523CD79-8272-4331-A49F-947B0269A42D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8523CD79-8272-4331-A49F-947B0269A42D}.Debug|Any CPU.Build.0 = Debug|Any CPU {8523CD79-8272-4331-A49F-947B0269A42D}.Release|Any CPU.ActiveCfg = Release|Any CPU {8523CD79-8272-4331-A49F-947B0269A42D}.Release|Any CPU.Build.0 = Release|Any CPU - {0DC3D462-5240-4670-A5C2-04FCD7093F2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0DC3D462-5240-4670-A5C2-04FCD7093F2E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0DC3D462-5240-4670-A5C2-04FCD7093F2E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0DC3D462-5240-4670-A5C2-04FCD7093F2E}.Release|Any CPU.Build.0 = Release|Any CPU - {7FCC6EEC-12BC-409C-93A9-0A4AF7B8E83B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7FCC6EEC-12BC-409C-93A9-0A4AF7B8E83B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7FCC6EEC-12BC-409C-93A9-0A4AF7B8E83B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7FCC6EEC-12BC-409C-93A9-0A4AF7B8E83B}.Release|Any CPU.Build.0 = Release|Any CPU {F46A91F5-47BA-468A-81F0-FF6BCEB4112C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F46A91F5-47BA-468A-81F0-FF6BCEB4112C}.Debug|Any CPU.Build.0 = Debug|Any CPU {F46A91F5-47BA-468A-81F0-FF6BCEB4112C}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -150,14 +117,6 @@ Global {8E9A7EF0-EE8E-4481-BF60-C6BDBD5C7BB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {8E9A7EF0-EE8E-4481-BF60-C6BDBD5C7BB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {8E9A7EF0-EE8E-4481-BF60-C6BDBD5C7BB8}.Release|Any CPU.Build.0 = Release|Any CPU - {7A85DEFF-0453-4252-8FFB-C8365AA84615}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7A85DEFF-0453-4252-8FFB-C8365AA84615}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7A85DEFF-0453-4252-8FFB-C8365AA84615}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7A85DEFF-0453-4252-8FFB-C8365AA84615}.Release|Any CPU.Build.0 = Release|Any CPU - {360265D8-8811-4A25-9060-AD9B9D334D8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {360265D8-8811-4A25-9060-AD9B9D334D8C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {360265D8-8811-4A25-9060-AD9B9D334D8C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {360265D8-8811-4A25-9060-AD9B9D334D8C}.Release|Any CPU.Build.0 = Release|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Debug|Any CPU.Build.0 = Debug|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -174,10 +133,6 @@ Global {8A5EB8BE-EDF3-444E-AC15-A3E9DEF1FC7F}.Debug|Any CPU.Build.0 = Debug|Any CPU {8A5EB8BE-EDF3-444E-AC15-A3E9DEF1FC7F}.Release|Any CPU.ActiveCfg = Release|Any CPU {8A5EB8BE-EDF3-444E-AC15-A3E9DEF1FC7F}.Release|Any CPU.Build.0 = Release|Any CPU - {9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9BF2A06B-C3D5-4BF9-BD44-84FAD008D2E3}.Release|Any CPU.Build.0 = Release|Any CPU {7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}.Debug|Any CPU.Build.0 = Debug|Any CPU {7E9F2ABB-373C-40BF-8D62-CBDD64DA8E36}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -206,10 +161,6 @@ Global {42BF3911-0DC7-4831-A989-98D48C17CC74}.Debug|Any CPU.Build.0 = Debug|Any CPU {42BF3911-0DC7-4831-A989-98D48C17CC74}.Release|Any CPU.ActiveCfg = Release|Any CPU {42BF3911-0DC7-4831-A989-98D48C17CC74}.Release|Any CPU.Build.0 = Release|Any CPU - {A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A5715FB6-CC7C-489C-BFC7-D17B1F2926A6}.Release|Any CPU.Build.0 = Release|Any CPU {2DF6ABEC-5B49-435D-A583-4C97C61D1558}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2DF6ABEC-5B49-435D-A583-4C97C61D1558}.Debug|Any CPU.Build.0 = Debug|Any CPU {2DF6ABEC-5B49-435D-A583-4C97C61D1558}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -234,26 +185,10 @@ Global {EF96A6E6-190B-457B-AD9C-1057CD7EDBB2}.Debug|Any CPU.Build.0 = Debug|Any CPU {EF96A6E6-190B-457B-AD9C-1057CD7EDBB2}.Release|Any CPU.ActiveCfg = Release|Any CPU {EF96A6E6-190B-457B-AD9C-1057CD7EDBB2}.Release|Any CPU.Build.0 = Release|Any CPU - {731BE61E-6C43-4628-B680-10467A73B4DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {731BE61E-6C43-4628-B680-10467A73B4DC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {731BE61E-6C43-4628-B680-10467A73B4DC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {731BE61E-6C43-4628-B680-10467A73B4DC}.Release|Any CPU.Build.0 = Release|Any CPU - {30FB37EA-5FA6-A6BB-1934-49C19899D2D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {30FB37EA-5FA6-A6BB-1934-49C19899D2D6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {30FB37EA-5FA6-A6BB-1934-49C19899D2D6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {30FB37EA-5FA6-A6BB-1934-49C19899D2D6}.Release|Any CPU.Build.0 = Release|Any CPU - {B8B3E775-FB6C-50B9-BD2D-2C04C9615D0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B8B3E775-FB6C-50B9-BD2D-2C04C9615D0D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B8B3E775-FB6C-50B9-BD2D-2C04C9615D0D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B8B3E775-FB6C-50B9-BD2D-2C04C9615D0D}.Release|Any CPU.Build.0 = Release|Any CPU {1864BBD1-5A3D-4FB1-B799-B736C5016191}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1864BBD1-5A3D-4FB1-B799-B736C5016191}.Debug|Any CPU.Build.0 = Debug|Any CPU {1864BBD1-5A3D-4FB1-B799-B736C5016191}.Release|Any CPU.ActiveCfg = Release|Any CPU {1864BBD1-5A3D-4FB1-B799-B736C5016191}.Release|Any CPU.Build.0 = Release|Any CPU - {51301FA2-449E-4666-B9DE-0EE9F4CD00EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {51301FA2-449E-4666-B9DE-0EE9F4CD00EE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {51301FA2-449E-4666-B9DE-0EE9F4CD00EE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {51301FA2-449E-4666-B9DE-0EE9F4CD00EE}.Release|Any CPU.Build.0 = Release|Any CPU {C6FC0FBB-6E0B-437B-82B7-294D830109EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C6FC0FBB-6E0B-437B-82B7-294D830109EA}.Debug|Any CPU.Build.0 = Debug|Any CPU {C6FC0FBB-6E0B-437B-82B7-294D830109EA}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -270,6 +205,26 @@ Global {8BD20BCF-DC47-4B94-B40E-1A6B7137265C}.Debug|Any CPU.Build.0 = Debug|Any CPU {8BD20BCF-DC47-4B94-B40E-1A6B7137265C}.Release|Any CPU.ActiveCfg = Release|Any CPU {8BD20BCF-DC47-4B94-B40E-1A6B7137265C}.Release|Any CPU.Build.0 = Release|Any CPU + {51026F8A-3101-41C7-BDD0-9275FE436410}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {51026F8A-3101-41C7-BDD0-9275FE436410}.Debug|Any CPU.Build.0 = Debug|Any CPU + {51026F8A-3101-41C7-BDD0-9275FE436410}.Release|Any CPU.ActiveCfg = Release|Any CPU + {51026F8A-3101-41C7-BDD0-9275FE436410}.Release|Any CPU.Build.0 = Release|Any CPU + {5653B9BD-331E-C526-0DA7-BD8CB9C9274C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5653B9BD-331E-C526-0DA7-BD8CB9C9274C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5653B9BD-331E-C526-0DA7-BD8CB9C9274C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5653B9BD-331E-C526-0DA7-BD8CB9C9274C}.Release|Any CPU.Build.0 = Release|Any CPU + {4C08CAB6-8668-5DC7-96F5-0335E6AEF680}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4C08CAB6-8668-5DC7-96F5-0335E6AEF680}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4C08CAB6-8668-5DC7-96F5-0335E6AEF680}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4C08CAB6-8668-5DC7-96F5-0335E6AEF680}.Release|Any CPU.Build.0 = Release|Any CPU + {708FB37D-DCFE-2FEB-DADE-F5C80ACDE10F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {708FB37D-DCFE-2FEB-DADE-F5C80ACDE10F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {708FB37D-DCFE-2FEB-DADE-F5C80ACDE10F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {708FB37D-DCFE-2FEB-DADE-F5C80ACDE10F}.Release|Any CPU.Build.0 = Release|Any CPU + {62E6B22B-2057-8EFC-30D4-B6F497FEF9D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {62E6B22B-2057-8EFC-30D4-B6F497FEF9D8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {62E6B22B-2057-8EFC-30D4-B6F497FEF9D8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {62E6B22B-2057-8EFC-30D4-B6F497FEF9D8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZSC.Script/CLIArgumentLogOrigin.cs b/ZSharp.CLI/CLIArgumentLogOrigin.cs similarity index 90% rename from ZSC.Script/CLIArgumentLogOrigin.cs rename to ZSharp.CLI/CLIArgumentLogOrigin.cs index 3848ed94..8f61f73f 100644 --- a/ZSC.Script/CLIArgumentLogOrigin.cs +++ b/ZSharp.CLI/CLIArgumentLogOrigin.cs @@ -1,6 +1,6 @@ using ZSharp.Logging; -namespace ZSC.Script +namespace ZSharp.CLI { internal class CLIArgumentLogOrigin(string argument) : LogOrigin { diff --git a/ZSC.Script/Program.cs b/ZSharp.CLI/Program.cs similarity index 97% rename from ZSC.Script/Program.cs rename to ZSharp.CLI/Program.cs index 192fec62..48fde44c 100644 --- a/ZSC.Script/Program.cs +++ b/ZSharp.CLI/Program.cs @@ -1,4 +1,4 @@ -using ZSC.Script; +using ZSharp.CLI; using ZSharp.Interpreter; using ZSharp.Parser; using ZSharp.SourceCompiler; @@ -142,8 +142,8 @@ #region Setup Interpreter - new ZSharp.Compiler.Dispatchers.CT.Dispatcher(interpreter.Compiler).Apply(); - new ZSharp.Compiler.Dispatchers.RT.Dispatcher(interpreter.Compiler).Apply(); + new ZSharp.Compiler.Dispatchers.Direct.Dispatcher(interpreter.Compiler).Apply(); + new ZSharp.Compiler.Dispatchers.Typed.Dispatcher(interpreter.Compiler).Apply(); new ZSharp.Compiler.Dispatchers.Proxy.Dispatcher(interpreter.Compiler).Apply(); var scriptCompiler = new ScriptCompiler(interpreter, documentNode); diff --git a/ZSC.Script/ZSCScriptLogOrigin.cs b/ZSharp.CLI/ZSCScriptLogOrigin.cs similarity index 92% rename from ZSC.Script/ZSCScriptLogOrigin.cs rename to ZSharp.CLI/ZSCScriptLogOrigin.cs index b8dd0cda..407c0b18 100644 --- a/ZSC.Script/ZSCScriptLogOrigin.cs +++ b/ZSharp.CLI/ZSCScriptLogOrigin.cs @@ -1,6 +1,6 @@ using ZSharp.Logging; -namespace ZSC.Script +namespace ZSharp.CLI { internal sealed class ZSCScriptLogOrigin() : LogOrigin { diff --git a/ZSC.Script/ZSC.Script.csproj b/ZSharp.CLI/ZSharp.CLI.csproj similarity index 66% rename from ZSC.Script/ZSC.Script.csproj rename to ZSharp.CLI/ZSharp.CLI.csproj index 700529a3..b7d49b25 100644 --- a/ZSC.Script/ZSC.Script.csproj +++ b/ZSharp.CLI/ZSharp.CLI.csproj @@ -5,6 +5,7 @@ net8.0 enable enable + zs @@ -16,12 +17,12 @@ - - - - - + + + + + @@ -34,7 +35,7 @@ - + diff --git a/ZSharp.CT.CompilerAPI/Fields_Globals.cs b/ZSharp.CT.CompilerAPI/Fields_Globals.cs deleted file mode 100644 index eed1e082..00000000 --- a/ZSharp.CT.CompilerAPI/Fields_Globals.cs +++ /dev/null @@ -1,10 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace ZS.CompilerAPI -{ - [HideInIR] - public static class Fields_Globals - { - public static ZSharp.Compiler.Compiler compiler; - } -} diff --git a/ZSharp.CT.CompilerAPI/Impl_Globals.cs b/ZSharp.CT.CompilerAPI/Impl_Globals.cs deleted file mode 100644 index dd8b6e0c..00000000 --- a/ZSharp.CT.CompilerAPI/Impl_Globals.cs +++ /dev/null @@ -1,10 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace ZS.CompilerAPI -{ - [ModuleGlobals] - public static class Impl_Globals - { - public static ZSharp.Compiler.Compiler GetCompiler() => Fields_Globals.compiler; - } -} diff --git a/ZSharp.CT.CompilerAPI/ZSharp.CT.CompilerAPI.csproj b/ZSharp.CT.CompilerAPI/ZSharp.CT.CompilerAPI.csproj deleted file mode 100644 index bf34e599..00000000 --- a/ZSharp.CT.CompilerAPI/ZSharp.CT.CompilerAPI.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - - diff --git a/ZSharp.CT.RuntimeAPI/Fields_Globals.cs b/ZSharp.CT.RuntimeAPI/Fields_Globals.cs deleted file mode 100644 index 3051b686..00000000 --- a/ZSharp.CT.RuntimeAPI/Fields_Globals.cs +++ /dev/null @@ -1,10 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace ZS.RuntimeAPI -{ - [HideInIR] - public static class Fields_Globals - { - //public static ZSharp.Runtime.NET.Runtime runtime; - } -} diff --git a/ZSharp.CT.RuntimeAPI/Impl_Globals.cs b/ZSharp.CT.RuntimeAPI/Impl_Globals.cs deleted file mode 100644 index feb7b186..00000000 --- a/ZSharp.CT.RuntimeAPI/Impl_Globals.cs +++ /dev/null @@ -1,16 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace ZS.RuntimeAPI -{ - [ModuleGlobals] - public static class Impl_Globals - { - public static ZSharp.Objects.CompilerObject InfoOf(object obj) - { - if (obj is ZSharp.Runtime.NET.ICompileTime ct) - return ct.GetCO(); - - throw new(); - } - } -} diff --git a/ZSharp.CT.RuntimeAPI/ZSharp.CT.RuntimeAPI.csproj b/ZSharp.CT.RuntimeAPI/ZSharp.CT.RuntimeAPI.csproj deleted file mode 100644 index 0aed9cf9..00000000 --- a/ZSharp.CT.RuntimeAPI/ZSharp.CT.RuntimeAPI.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - diff --git a/ZSharp.CT.StandardLibrary.FileSystem/GlobalUsings.cs b/ZSharp.CT.StandardLibrary.FileSystem/GlobalUsings.cs deleted file mode 100644 index daef43e7..00000000 --- a/ZSharp.CT.StandardLibrary.FileSystem/GlobalUsings.cs +++ /dev/null @@ -1 +0,0 @@ -global using ZSharp.Compiler.ILLoader; diff --git a/ZSharp.CT.StandardLibrary.IO/GlobalUsings.cs b/ZSharp.CT.StandardLibrary.IO/GlobalUsings.cs deleted file mode 100644 index daef43e7..00000000 --- a/ZSharp.CT.StandardLibrary.IO/GlobalUsings.cs +++ /dev/null @@ -1 +0,0 @@ -global using ZSharp.Compiler.ILLoader; diff --git a/ZSharp.CT.StandardLibrary/Impl_Globals.cs b/ZSharp.CT.StandardLibrary/Impl_Globals.cs deleted file mode 100644 index cb2b5592..00000000 --- a/ZSharp.CT.StandardLibrary/Impl_Globals.cs +++ /dev/null @@ -1,44 +0,0 @@ -using ZSharp.Runtime.NET.IL2IR; - - -namespace Standard.IO -{ - [ModuleGlobals] - public static class Impl_Globals - { - [Alias(Name = "print")] - public static void Print(string value) - => Console.WriteLine(value); - - [Alias(Name = "input")] - public static string Input(string prompt) - { - Console.Write(prompt); - return Console.ReadLine()!; - } - - [Alias(Name = "_+_")] - public static string Concat(string a, string b) - => a + b; - - [Alias(Name = "string()")] - public static string ToString(int x) - => x.ToString(); - - [Alias(Name = "int32.parse()")] - public static int ParseInt32(string s) - => int.Parse(s); - - [Alias(Name = "_==_")] - public static bool Equals(string a, string b) - => a == b; - - [Alias(Name = "_==_")] - public static bool Equals(bool a, bool b) - => a == b; - - [Alias(Name = "_!=_")] - public static bool NotEquals(string a, string b) - => a != b; - } -} diff --git a/ZSharp.CT.StandardLibrary/ZSharp.CT.StandardLibrary.csproj b/ZSharp.CT.StandardLibrary/ZSharp.CT.StandardLibrary.csproj deleted file mode 100644 index 0aed9cf9..00000000 --- a/ZSharp.CT.StandardLibrary/ZSharp.CT.StandardLibrary.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - diff --git a/ZSharp.Compiler.CO.CT/GlobalUsings.cs b/ZSharp.Compiler.CG.Direct/GlobalUsings.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/GlobalUsings.cs rename to ZSharp.Compiler.CG.Direct/GlobalUsings.cs diff --git a/ZSharp.Compiler.CO.CT/ZSharp.Compiler.CO.CT.csproj b/ZSharp.Compiler.CG.Direct/ZSharp.Compiler.CG.Direct.csproj similarity index 82% rename from ZSharp.Compiler.CO.CT/ZSharp.Compiler.CO.CT.csproj rename to ZSharp.Compiler.CG.Direct/ZSharp.Compiler.CG.Direct.csproj index 615e6b8a..29b16973 100644 --- a/ZSharp.Compiler.CO.CT/ZSharp.Compiler.CO.CT.csproj +++ b/ZSharp.Compiler.CG.Direct/ZSharp.Compiler.CG.Direct.csproj @@ -8,7 +8,6 @@ - diff --git a/ZSharp.Compiler.CO.RT/dispatcher/Dispatcher.cs b/ZSharp.Compiler.CG.Direct/dispatcher/Dispatcher.cs similarity index 93% rename from ZSharp.Compiler.CO.RT/dispatcher/Dispatcher.cs rename to ZSharp.Compiler.CG.Direct/dispatcher/Dispatcher.cs index bdea2c28..3d5c47a6 100644 --- a/ZSharp.Compiler.CO.RT/dispatcher/Dispatcher.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/Dispatcher.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.RT +namespace ZSharp.Compiler.Dispatchers.Direct { public partial class Dispatcher(Compiler compiler) { diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Call.cs similarity index 88% rename from ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Call.cs rename to ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Call.cs index 4f852376..adae7770 100644 --- a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Call.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Call.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.CT +namespace ZSharp.Compiler.Dispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Cast.cs similarity index 88% rename from ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Cast.cs rename to ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Cast.cs index 1bb14d44..0b55b314 100644 --- a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Cast.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Cast.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.CT +namespace ZSharp.Compiler.Dispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ImplicitCast.cs similarity index 91% rename from ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ImplicitCast.cs rename to ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ImplicitCast.cs index bacc140c..b615b953 100644 --- a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ImplicitCast.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.CT +namespace ZSharp.Compiler.Dispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Index.cs similarity index 93% rename from ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Index.cs rename to ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Index.cs index aa1ed00f..8fc1ac29 100644 --- a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Index.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Index.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.CT +namespace ZSharp.Compiler.Dispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Match.cs similarity index 88% rename from ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Match.cs rename to ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Match.cs index 97026571..937af126 100644 --- a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.Match.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Match.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.CT +namespace ZSharp.Compiler.Dispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.MemberAccess.cs similarity index 96% rename from ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.MemberAccess.cs rename to ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.MemberAccess.cs index 83830cc9..43b344fd 100644 --- a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.MemberAccess.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.MemberAccess.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.CT +namespace ZSharp.Compiler.Dispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ValueAccess.cs similarity index 92% rename from ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ValueAccess.cs rename to ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ValueAccess.cs index 81fe2877..fab43a40 100644 --- a/ZSharp.Compiler.CO.CT/dispatcher/services/Dispatcher.ValueAccess.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ValueAccess.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.CT +namespace ZSharp.Compiler.Dispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.CT/protocols/callable/ICTCallable.cs b/ZSharp.Compiler.CG.Direct/protocols/callable/ICTCallable.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/protocols/callable/ICTCallable.cs rename to ZSharp.Compiler.CG.Direct/protocols/callable/ICTCallable.cs diff --git a/ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastFrom.cs b/ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastFrom.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastFrom.cs rename to ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastFrom.cs diff --git a/ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastTo.cs b/ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastTo.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/protocols/implicit casting/ICTImplicitCastTo.cs rename to ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastTo.cs diff --git a/ZSharp.Compiler.CO.CT/protocols/index/ICTGetIndex.cs b/ZSharp.Compiler.CG.Direct/protocols/index/ICTGetIndex.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/protocols/index/ICTGetIndex.cs rename to ZSharp.Compiler.CG.Direct/protocols/index/ICTGetIndex.cs diff --git a/ZSharp.Compiler.CO.CT/protocols/index/ICTSetIndex.cs b/ZSharp.Compiler.CG.Direct/protocols/index/ICTSetIndex.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/protocols/index/ICTSetIndex.cs rename to ZSharp.Compiler.CG.Direct/protocols/index/ICTSetIndex.cs diff --git a/ZSharp.Compiler.CO.CT/protocols/member access/ICTGetMember.cs b/ZSharp.Compiler.CG.Direct/protocols/member access/ICTGetMember.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/protocols/member access/ICTGetMember.cs rename to ZSharp.Compiler.CG.Direct/protocols/member access/ICTGetMember.cs diff --git a/ZSharp.Compiler.CO.CT/protocols/member access/ICTSetMember.cs b/ZSharp.Compiler.CG.Direct/protocols/member access/ICTSetMember.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/protocols/member access/ICTSetMember.cs rename to ZSharp.Compiler.CG.Direct/protocols/member access/ICTSetMember.cs diff --git a/ZSharp.Compiler.CO.CT/protocols/type casting/ICTCastTo.cs b/ZSharp.Compiler.CG.Direct/protocols/type casting/ICTCastTo.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/protocols/type casting/ICTCastTo.cs rename to ZSharp.Compiler.CG.Direct/protocols/type casting/ICTCastTo.cs diff --git a/ZSharp.Compiler.CO.CT/protocols/type matching/ICTTypeMatch.cs b/ZSharp.Compiler.CG.Direct/protocols/type matching/ICTTypeMatch.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/protocols/type matching/ICTTypeMatch.cs rename to ZSharp.Compiler.CG.Direct/protocols/type matching/ICTTypeMatch.cs diff --git a/ZSharp.Compiler.CO.CT/protocols/value access/ICTGet.cs b/ZSharp.Compiler.CG.Direct/protocols/value access/ICTGet.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/protocols/value access/ICTGet.cs rename to ZSharp.Compiler.CG.Direct/protocols/value access/ICTGet.cs diff --git a/ZSharp.Compiler.CO.CT/protocols/value access/ICTSet.cs b/ZSharp.Compiler.CG.Direct/protocols/value access/ICTSet.cs similarity index 100% rename from ZSharp.Compiler.CO.CT/protocols/value access/ICTSet.cs rename to ZSharp.Compiler.CG.Direct/protocols/value access/ICTSet.cs diff --git a/ZSharp.Compiler.CO.Proxy/GlobalUsings.cs b/ZSharp.Compiler.CG.Proxy/GlobalUsings.cs similarity index 100% rename from ZSharp.Compiler.CO.Proxy/GlobalUsings.cs rename to ZSharp.Compiler.CG.Proxy/GlobalUsings.cs diff --git a/ZSharp.Compiler.CO.Proxy/ZSharp.Compiler.CO.Proxy.csproj b/ZSharp.Compiler.CG.Proxy/ZSharp.Compiler.CG.Proxy.csproj similarity index 82% rename from ZSharp.Compiler.CO.Proxy/ZSharp.Compiler.CO.Proxy.csproj rename to ZSharp.Compiler.CG.Proxy/ZSharp.Compiler.CG.Proxy.csproj index 615e6b8a..29b16973 100644 --- a/ZSharp.Compiler.CO.Proxy/ZSharp.Compiler.CO.Proxy.csproj +++ b/ZSharp.Compiler.CG.Proxy/ZSharp.Compiler.CG.Proxy.csproj @@ -8,7 +8,6 @@ - diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/Dispatcher.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/Dispatcher.cs similarity index 100% rename from ZSharp.Compiler.CO.Proxy/dispatcher/Dispatcher.cs rename to ZSharp.Compiler.CG.Proxy/dispatcher/Dispatcher.cs diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Call.cs similarity index 100% rename from ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Call.cs rename to ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Call.cs diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Cast.cs similarity index 100% rename from ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Cast.cs rename to ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Cast.cs diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs similarity index 100% rename from ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs rename to ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Index.cs similarity index 100% rename from ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Index.cs rename to ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Index.cs diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Match.cs similarity index 100% rename from ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.Match.cs rename to ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Match.cs diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs similarity index 100% rename from ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs rename to ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs diff --git a/ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs similarity index 100% rename from ZSharp.Compiler.CO.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs rename to ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs diff --git a/ZSharp.Compiler.CO.Proxy/protocols/IProxy.cs b/ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs similarity index 100% rename from ZSharp.Compiler.CO.Proxy/protocols/IProxy.cs rename to ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs diff --git a/ZSharp.Compiler.CO.RT/GlobalUsings.cs b/ZSharp.Compiler.CG.Typed/GlobalUsings.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/GlobalUsings.cs rename to ZSharp.Compiler.CG.Typed/GlobalUsings.cs diff --git a/ZSharp.Compiler.CO.RT/ZSharp.Compiler.CO.RT.csproj b/ZSharp.Compiler.CG.Typed/ZSharp.Compiler.CG.Typed.csproj similarity index 82% rename from ZSharp.Compiler.CO.RT/ZSharp.Compiler.CO.RT.csproj rename to ZSharp.Compiler.CG.Typed/ZSharp.Compiler.CG.Typed.csproj index 615e6b8a..29b16973 100644 --- a/ZSharp.Compiler.CO.RT/ZSharp.Compiler.CO.RT.csproj +++ b/ZSharp.Compiler.CG.Typed/ZSharp.Compiler.CG.Typed.csproj @@ -8,7 +8,6 @@ - diff --git a/ZSharp.Compiler.CO.CT/dispatcher/Dispatcher.cs b/ZSharp.Compiler.CG.Typed/dispatcher/Dispatcher.cs similarity index 93% rename from ZSharp.Compiler.CO.CT/dispatcher/Dispatcher.cs rename to ZSharp.Compiler.CG.Typed/dispatcher/Dispatcher.cs index e6ee9c89..7f66d517 100644 --- a/ZSharp.Compiler.CO.CT/dispatcher/Dispatcher.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/Dispatcher.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.CT +namespace ZSharp.Compiler.Dispatchers.Typed { public partial class Dispatcher(Compiler compiler) { diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Call.cs similarity index 89% rename from ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Call.cs rename to ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Call.cs index da1e1924..2da827ee 100644 --- a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Call.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Call.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.RT +namespace ZSharp.Compiler.Dispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Cast.cs similarity index 89% rename from ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Cast.cs rename to ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Cast.cs index 92210453..7afd8bcc 100644 --- a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Cast.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Cast.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.RT +namespace ZSharp.Compiler.Dispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs similarity index 93% rename from ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ImplicitCast.cs rename to ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs index 4c1f7775..554c5ccf 100644 --- a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ImplicitCast.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.RT +namespace ZSharp.Compiler.Dispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Index.cs similarity index 94% rename from ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Index.cs rename to ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Index.cs index fb3cf75a..7a604efd 100644 --- a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Index.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Index.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.RT +namespace ZSharp.Compiler.Dispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Match.cs similarity index 90% rename from ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Match.cs rename to ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Match.cs index d818c6e4..3e185238 100644 --- a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.Match.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Match.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.RT +namespace ZSharp.Compiler.Dispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.MemberAccess.cs similarity index 97% rename from ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.MemberAccess.cs rename to ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.MemberAccess.cs index b96d3307..e74952c6 100644 --- a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.MemberAccess.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.MemberAccess.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.RT +namespace ZSharp.Compiler.Dispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ValueAccess.cs similarity index 93% rename from ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ValueAccess.cs rename to ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ValueAccess.cs index f7dd69f4..587cb748 100644 --- a/ZSharp.Compiler.CO.RT/dispatcher/services/Dispatcher.ValueAccess.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ValueAccess.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.RT +namespace ZSharp.Compiler.Dispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CO.RT/extensions/CompilerExtensions.cs b/ZSharp.Compiler.CG.Typed/extensions/CompilerExtensions.cs similarity index 87% rename from ZSharp.Compiler.CO.RT/extensions/CompilerExtensions.cs rename to ZSharp.Compiler.CG.Typed/extensions/CompilerExtensions.cs index 0d66e73e..d3c29faa 100644 --- a/ZSharp.Compiler.CO.RT/extensions/CompilerExtensions.cs +++ b/ZSharp.Compiler.CG.Typed/extensions/CompilerExtensions.cs @@ -9,6 +9,9 @@ public static Result GetRuntimeDescriptor(this Compiler compiler, CompilerObject if (@object.Is(out var hasRuntimeDescriptor)) return hasRuntimeDescriptor.GetRuntimeDescriptor(compiler); + if (compiler.TS.IsTyped(@object, out var type)) + return Result.Ok(type); + return Result.Error($"No runtime descriptor found for object {@object}."); } diff --git a/ZSharp.Compiler.CO.RT/protocols/callable/IRTCallable.cs b/ZSharp.Compiler.CG.Typed/protocols/callable/IRTCallable.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/callable/IRTCallable.cs rename to ZSharp.Compiler.CG.Typed/protocols/callable/IRTCallable.cs diff --git a/ZSharp.Compiler.CO.RT/protocols/implicit casting/IRTImplicitCastTo.cs b/ZSharp.Compiler.CG.Typed/protocols/implicit casting/IRTImplicitCastTo.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/implicit casting/IRTImplicitCastTo.cs rename to ZSharp.Compiler.CG.Typed/protocols/implicit casting/IRTImplicitCastTo.cs diff --git a/ZSharp.Compiler.CO.RT/protocols/index/IRTGetIndex.cs b/ZSharp.Compiler.CG.Typed/protocols/index/IRTGetIndex.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/index/IRTGetIndex.cs rename to ZSharp.Compiler.CG.Typed/protocols/index/IRTGetIndex.cs diff --git a/ZSharp.Compiler.CO.RT/protocols/index/IRTSetIndex.cs b/ZSharp.Compiler.CG.Typed/protocols/index/IRTSetIndex.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/index/IRTSetIndex.cs rename to ZSharp.Compiler.CG.Typed/protocols/index/IRTSetIndex.cs diff --git a/ZSharp.Compiler.CO.RT/protocols/member access/IRTGetMember.cs b/ZSharp.Compiler.CG.Typed/protocols/member access/IRTGetMember.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/member access/IRTGetMember.cs rename to ZSharp.Compiler.CG.Typed/protocols/member access/IRTGetMember.cs diff --git a/ZSharp.Compiler.CO.RT/protocols/member access/IRTSetMember.cs b/ZSharp.Compiler.CG.Typed/protocols/member access/IRTSetMember.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/member access/IRTSetMember.cs rename to ZSharp.Compiler.CG.Typed/protocols/member access/IRTSetMember.cs diff --git a/ZSharp.Compiler.CO.RT/protocols/runtime/IHasRuntimeDescriptor.cs b/ZSharp.Compiler.CG.Typed/protocols/runtime/IHasRuntimeDescriptor.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/runtime/IHasRuntimeDescriptor.cs rename to ZSharp.Compiler.CG.Typed/protocols/runtime/IHasRuntimeDescriptor.cs diff --git a/ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastFrom.cs b/ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastFrom.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastFrom.cs rename to ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastFrom.cs diff --git a/ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastTo.cs b/ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastTo.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/type casting/IRTCastTo.cs rename to ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastTo.cs diff --git a/ZSharp.Compiler.CO.RT/protocols/type matching/IRTTypeMatch.cs b/ZSharp.Compiler.CG.Typed/protocols/type matching/IRTTypeMatch.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/type matching/IRTTypeMatch.cs rename to ZSharp.Compiler.CG.Typed/protocols/type matching/IRTTypeMatch.cs diff --git a/ZSharp.Compiler.CO.RT/protocols/value access/IRTGet.cs b/ZSharp.Compiler.CG.Typed/protocols/value access/IRTGet.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/value access/IRTGet.cs rename to ZSharp.Compiler.CG.Typed/protocols/value access/IRTGet.cs diff --git a/ZSharp.Compiler.CO.RT/protocols/value access/IRTSet.cs b/ZSharp.Compiler.CG.Typed/protocols/value access/IRTSet.cs similarity index 100% rename from ZSharp.Compiler.CO.RT/protocols/value access/IRTSet.cs rename to ZSharp.Compiler.CG.Typed/protocols/value access/IRTSet.cs diff --git a/ZSharp.Compiler.CO/GlobalUsings.cs b/ZSharp.Compiler.CG/GlobalUsings.cs similarity index 100% rename from ZSharp.Compiler.CO/GlobalUsings.cs rename to ZSharp.Compiler.CG/GlobalUsings.cs diff --git a/ZSharp.Compiler.CO/ZSharp.Compiler.CO.csproj b/ZSharp.Compiler.CG/ZSharp.Compiler.CG.csproj similarity index 100% rename from ZSharp.Compiler.CO/ZSharp.Compiler.CO.csproj rename to ZSharp.Compiler.CG/ZSharp.Compiler.CG.csproj diff --git a/ZSharp.Compiler.CO/cg/CG.cs b/ZSharp.Compiler.CG/cg/CG.cs similarity index 100% rename from ZSharp.Compiler.CO/cg/CG.cs rename to ZSharp.Compiler.CG/cg/CG.cs diff --git a/ZSharp.Compiler.CO/cg/services/CG.Call.cs b/ZSharp.Compiler.CG/cg/services/CG.Call.cs similarity index 100% rename from ZSharp.Compiler.CO/cg/services/CG.Call.cs rename to ZSharp.Compiler.CG/cg/services/CG.Call.cs diff --git a/ZSharp.Compiler.CO/cg/services/CG.Cast.cs b/ZSharp.Compiler.CG/cg/services/CG.Cast.cs similarity index 100% rename from ZSharp.Compiler.CO/cg/services/CG.Cast.cs rename to ZSharp.Compiler.CG/cg/services/CG.Cast.cs diff --git a/ZSharp.Compiler.CO/cg/services/CG.ImplicitCast.cs b/ZSharp.Compiler.CG/cg/services/CG.ImplicitCast.cs similarity index 100% rename from ZSharp.Compiler.CO/cg/services/CG.ImplicitCast.cs rename to ZSharp.Compiler.CG/cg/services/CG.ImplicitCast.cs diff --git a/ZSharp.Compiler.CO/cg/services/CG.Index.cs b/ZSharp.Compiler.CG/cg/services/CG.Index.cs similarity index 100% rename from ZSharp.Compiler.CO/cg/services/CG.Index.cs rename to ZSharp.Compiler.CG/cg/services/CG.Index.cs diff --git a/ZSharp.Compiler.CO/cg/services/CG.Match.cs b/ZSharp.Compiler.CG/cg/services/CG.Match.cs similarity index 100% rename from ZSharp.Compiler.CO/cg/services/CG.Match.cs rename to ZSharp.Compiler.CG/cg/services/CG.Match.cs diff --git a/ZSharp.Compiler.CO/cg/services/CG.MemberAccess.cs b/ZSharp.Compiler.CG/cg/services/CG.MemberAccess.cs similarity index 100% rename from ZSharp.Compiler.CO/cg/services/CG.MemberAccess.cs rename to ZSharp.Compiler.CG/cg/services/CG.MemberAccess.cs diff --git a/ZSharp.Compiler.CO/cg/services/CG.ValueAccess.cs b/ZSharp.Compiler.CG/cg/services/CG.ValueAccess.cs similarity index 100% rename from ZSharp.Compiler.CO/cg/services/CG.ValueAccess.cs rename to ZSharp.Compiler.CG/cg/services/CG.ValueAccess.cs diff --git a/ZSharp.Compiler.CO/core/Argument.cs b/ZSharp.Compiler.CG/core/Argument.cs similarity index 100% rename from ZSharp.Compiler.CO/core/Argument.cs rename to ZSharp.Compiler.CG/core/Argument.cs diff --git a/ZSharp.Compiler.CO/core/CastResult.cs b/ZSharp.Compiler.CG/core/CastResult.cs similarity index 100% rename from ZSharp.Compiler.CO/core/CastResult.cs rename to ZSharp.Compiler.CG/core/CastResult.cs diff --git a/ZSharp.Compiler.CO/core/MatchResult.cs b/ZSharp.Compiler.CG/core/MatchResult.cs similarity index 100% rename from ZSharp.Compiler.CO/core/MatchResult.cs rename to ZSharp.Compiler.CG/core/MatchResult.cs diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.Call.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Call.cs similarity index 100% rename from ZSharp.Compiler.CO/dispatcher/Dispatcher.Call.cs rename to ZSharp.Compiler.CG/dispatcher/Dispatcher.Call.cs diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.Cast.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Cast.cs similarity index 100% rename from ZSharp.Compiler.CO/dispatcher/Dispatcher.Cast.cs rename to ZSharp.Compiler.CG/dispatcher/Dispatcher.Cast.cs diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.ImplicitCast.cs similarity index 100% rename from ZSharp.Compiler.CO/dispatcher/Dispatcher.ImplicitCast.cs rename to ZSharp.Compiler.CG/dispatcher/Dispatcher.ImplicitCast.cs diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.Index.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Index.cs similarity index 100% rename from ZSharp.Compiler.CO/dispatcher/Dispatcher.Index.cs rename to ZSharp.Compiler.CG/dispatcher/Dispatcher.Index.cs diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.Match.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Match.cs similarity index 100% rename from ZSharp.Compiler.CO/dispatcher/Dispatcher.Match.cs rename to ZSharp.Compiler.CG/dispatcher/Dispatcher.Match.cs diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.MemberAccess.cs similarity index 100% rename from ZSharp.Compiler.CO/dispatcher/Dispatcher.MemberAccess.cs rename to ZSharp.Compiler.CG/dispatcher/Dispatcher.MemberAccess.cs diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.Runtime.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Runtime.cs similarity index 100% rename from ZSharp.Compiler.CO/dispatcher/Dispatcher.Runtime.cs rename to ZSharp.Compiler.CG/dispatcher/Dispatcher.Runtime.cs diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.ValueAccess.cs similarity index 100% rename from ZSharp.Compiler.CO/dispatcher/Dispatcher.ValueAccess.cs rename to ZSharp.Compiler.CG/dispatcher/Dispatcher.ValueAccess.cs diff --git a/ZSharp.Compiler.CO/dispatcher/Dispatcher.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.cs similarity index 100% rename from ZSharp.Compiler.CO/dispatcher/Dispatcher.cs rename to ZSharp.Compiler.CG/dispatcher/Dispatcher.cs diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IR.cs b/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IR.cs deleted file mode 100644 index cf290e47..00000000 --- a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IR.cs +++ /dev/null @@ -1,28 +0,0 @@ -using ZSharp.IR; - -namespace ZSharp.Compiler.ILLoader.Objects -{ - partial class Class - : ICompileIRDefinitionAs - , ICompileIRType> - { - private ZSharp.IR.Class? IR { get; set; } - - Result ICompileIRDefinitionAs.CompileIRDefinition(IR ir, object? target) - => Result.Ok(GetIR()); - - Result> ICompileIRType>.CompileIRType(IR ir) - => Result>.Ok(new ClassReference(GetIR())); - - private ZSharp.IR.Class GetIR() - { - if (IR is null) - { - IR = new(IL.Name); - Loader.RequireRuntime().AddTypeDefinition(IR, IL); - } - - return IR; - } - } -} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.T.cs deleted file mode 100644 index 480e3571..00000000 --- a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.T.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler.ILLoader.Objects -{ - partial class Class - { - - } -} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.T.cs deleted file mode 100644 index 392129bd..00000000 --- a/ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.T.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler.ILLoader.Objects -{ - partial class Enum - { - - } -} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/field/Field.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/field/Field.T.cs deleted file mode 100644 index 67362730..00000000 --- a/ZSharp.Compiler.ILLoader/objects/oop/field/Field.T.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler.ILLoader.Objects -{ - partial class Field - { - - } -} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.T.cs deleted file mode 100644 index e7c558b1..00000000 --- a/ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.T.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler.ILLoader.Objects -{ - partial class Interface - { - - } -} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.T.cs deleted file mode 100644 index 085087e7..00000000 --- a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.T.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler.ILLoader.Objects -{ - partial class Method - { - - } -} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/property/Property.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/property/Property.T.cs deleted file mode 100644 index 5653ad0b..00000000 --- a/ZSharp.Compiler.ILLoader/objects/oop/property/Property.T.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler.ILLoader.Objects -{ - partial class Property - { - - } -} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.T.cs b/ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.T.cs deleted file mode 100644 index ec682056..00000000 --- a/ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.T.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler.ILLoader.Objects -{ - partial class Struct - { - - } -} diff --git a/ZSharp.Compiler.IRLoader/GlobalUsings.cs b/ZSharp.Compiler.IRLoader/GlobalUsings.cs deleted file mode 100644 index c747969f..00000000 --- a/ZSharp.Compiler.IRLoader/GlobalUsings.cs +++ /dev/null @@ -1 +0,0 @@ -global using ZSharp.Objects; diff --git a/ZSharp.Compiler.ILLoader.Attributes/ZSharp.Compiler.ILLoader.Attributes.csproj b/ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj similarity index 77% rename from ZSharp.Compiler.ILLoader.Attributes/ZSharp.Compiler.ILLoader.Attributes.csproj rename to ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj index 3c2ad080..fa71b7ae 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/ZSharp.Compiler.ILLoader.Attributes.csproj +++ b/ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj @@ -4,7 +4,6 @@ net8.0 enable enable - ZSharp.Compiler.ILLoader diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs index 711e5457..067bd79c 100644 --- a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.CT +namespace ZSharp.Compiler.Dispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs index ff61bb32..cfa3b09e 100644 --- a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.CT +namespace ZSharp.Compiler.Dispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs index 939f0264..fa510138 100644 --- a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.CT +namespace ZSharp.Compiler.Dispatchers.Direct { internal partial class Dispatcher(Compiler compiler) { diff --git a/ZSharp.Compiler/ZSharp.Compiler.csproj b/ZSharp.Compiler/ZSharp.Compiler.csproj index a81dc6fe..28df3c3d 100644 --- a/ZSharp.Compiler/ZSharp.Compiler.csproj +++ b/ZSharp.Compiler/ZSharp.Compiler.csproj @@ -13,9 +13,9 @@ + - diff --git a/ZSharp.Compiler.ILLoader.Attributes/AliasAttribute.cs b/ZSharp.Importer.ILLoader.Attributes/AliasAttribute.cs similarity index 93% rename from ZSharp.Compiler.ILLoader.Attributes/AliasAttribute.cs rename to ZSharp.Importer.ILLoader.Attributes/AliasAttribute.cs index 01e9e8e8..1749f0b2 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/AliasAttribute.cs +++ b/ZSharp.Importer.ILLoader.Attributes/AliasAttribute.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { [AttributeUsage( AttributeTargets.Class | diff --git a/ZSharp.Compiler.ILLoader.Attributes/HideImportAttribute.cs b/ZSharp.Importer.ILLoader.Attributes/HideImportAttribute.cs similarity index 91% rename from ZSharp.Compiler.ILLoader.Attributes/HideImportAttribute.cs rename to ZSharp.Importer.ILLoader.Attributes/HideImportAttribute.cs index bc2b4b72..1c1380bd 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/HideImportAttribute.cs +++ b/ZSharp.Importer.ILLoader.Attributes/HideImportAttribute.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { [AttributeUsage( AttributeTargets.Class | diff --git a/ZSharp.Compiler.ILLoader.Attributes/ModuleScopeAttribute.cs b/ZSharp.Importer.ILLoader.Attributes/ModuleScopeAttribute.cs similarity index 81% rename from ZSharp.Compiler.ILLoader.Attributes/ModuleScopeAttribute.cs rename to ZSharp.Importer.ILLoader.Attributes/ModuleScopeAttribute.cs index 714d7d90..856958e0 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/ModuleScopeAttribute.cs +++ b/ZSharp.Importer.ILLoader.Attributes/ModuleScopeAttribute.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { [AttributeUsage( AttributeTargets.Class, diff --git a/ZSharp.CT.StandardLibrary.Math/ZSharp.CT.StandardLibrary.Math.csproj b/ZSharp.Importer.ILLoader.Attributes/ZSharp.Importer.ILLoader.Attributes.csproj similarity index 65% rename from ZSharp.CT.StandardLibrary.Math/ZSharp.CT.StandardLibrary.Math.csproj rename to ZSharp.Importer.ILLoader.Attributes/ZSharp.Importer.ILLoader.Attributes.csproj index 0aed9cf9..3bbf45a4 100644 --- a/ZSharp.CT.StandardLibrary.Math/ZSharp.CT.StandardLibrary.Math.csproj +++ b/ZSharp.Importer.ILLoader.Attributes/ZSharp.Importer.ILLoader.Attributes.csproj @@ -4,10 +4,7 @@ net8.0 enable enable + ZSharp.Importer.ILLoader - - - - diff --git a/ZSharp.Compiler.ILLoader.Attributes/namespace/AddNamespaceAttribute.cs b/ZSharp.Importer.ILLoader.Attributes/namespace/AddNamespaceAttribute.cs similarity index 92% rename from ZSharp.Compiler.ILLoader.Attributes/namespace/AddNamespaceAttribute.cs rename to ZSharp.Importer.ILLoader.Attributes/namespace/AddNamespaceAttribute.cs index 6f7223fe..6c609620 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/namespace/AddNamespaceAttribute.cs +++ b/ZSharp.Importer.ILLoader.Attributes/namespace/AddNamespaceAttribute.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { [AttributeUsage( AttributeTargets.Class | diff --git a/ZSharp.Compiler.ILLoader.Attributes/namespace/MapNamespaceAttribute.cs b/ZSharp.Importer.ILLoader.Attributes/namespace/MapNamespaceAttribute.cs similarity index 87% rename from ZSharp.Compiler.ILLoader.Attributes/namespace/MapNamespaceAttribute.cs rename to ZSharp.Importer.ILLoader.Attributes/namespace/MapNamespaceAttribute.cs index 8e53cd18..9c54dd06 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/namespace/MapNamespaceAttribute.cs +++ b/ZSharp.Importer.ILLoader.Attributes/namespace/MapNamespaceAttribute.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { [AttributeUsage( AttributeTargets.Module, diff --git a/ZSharp.Compiler.ILLoader.Attributes/namespace/SetNamespaceAttribute.cs b/ZSharp.Importer.ILLoader.Attributes/namespace/SetNamespaceAttribute.cs similarity index 92% rename from ZSharp.Compiler.ILLoader.Attributes/namespace/SetNamespaceAttribute.cs rename to ZSharp.Importer.ILLoader.Attributes/namespace/SetNamespaceAttribute.cs index f50882dc..5e1c84a1 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/namespace/SetNamespaceAttribute.cs +++ b/ZSharp.Importer.ILLoader.Attributes/namespace/SetNamespaceAttribute.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { [AttributeUsage( AttributeTargets.Class | diff --git a/ZSharp.Compiler.ILLoader.Attributes/operator/OperatorAttribute.cs b/ZSharp.Importer.ILLoader.Attributes/operator/OperatorAttribute.cs similarity index 88% rename from ZSharp.Compiler.ILLoader.Attributes/operator/OperatorAttribute.cs rename to ZSharp.Importer.ILLoader.Attributes/operator/OperatorAttribute.cs index 716c80fe..0d8cc251 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/operator/OperatorAttribute.cs +++ b/ZSharp.Importer.ILLoader.Attributes/operator/OperatorAttribute.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { [AttributeUsage( AttributeTargets.Method, diff --git a/ZSharp.Compiler.ILLoader.Attributes/operator/OperatorKind.cs b/ZSharp.Importer.ILLoader.Attributes/operator/OperatorKind.cs similarity index 70% rename from ZSharp.Compiler.ILLoader.Attributes/operator/OperatorKind.cs rename to ZSharp.Importer.ILLoader.Attributes/operator/OperatorKind.cs index beb5eced..42be7b25 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/operator/OperatorKind.cs +++ b/ZSharp.Importer.ILLoader.Attributes/operator/OperatorKind.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { public enum OperatorKind { diff --git a/ZSharp.Compiler.ILLoader.Attributes/parameter/NamedParameterAttribute.cs b/ZSharp.Importer.ILLoader.Attributes/parameter/NamedParameterAttribute.cs similarity index 82% rename from ZSharp.Compiler.ILLoader.Attributes/parameter/NamedParameterAttribute.cs rename to ZSharp.Importer.ILLoader.Attributes/parameter/NamedParameterAttribute.cs index 8385638f..c199dfc1 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/parameter/NamedParameterAttribute.cs +++ b/ZSharp.Importer.ILLoader.Attributes/parameter/NamedParameterAttribute.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { [AttributeUsage( AttributeTargets.Parameter, diff --git a/ZSharp.Compiler.ILLoader.Attributes/parameter/VarParameterAttribute.cs b/ZSharp.Importer.ILLoader.Attributes/parameter/VarParameterAttribute.cs similarity index 81% rename from ZSharp.Compiler.ILLoader.Attributes/parameter/VarParameterAttribute.cs rename to ZSharp.Importer.ILLoader.Attributes/parameter/VarParameterAttribute.cs index 056b6121..7c065993 100644 --- a/ZSharp.Compiler.ILLoader.Attributes/parameter/VarParameterAttribute.cs +++ b/ZSharp.Importer.ILLoader.Attributes/parameter/VarParameterAttribute.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { [AttributeUsage( AttributeTargets.Parameter, diff --git a/ZSharp.Importer.ILLoader/GlobalUsings.cs b/ZSharp.Importer.ILLoader/GlobalUsings.cs new file mode 100644 index 00000000..3511d075 --- /dev/null +++ b/ZSharp.Importer.ILLoader/GlobalUsings.cs @@ -0,0 +1 @@ +global using CompilerObject = ZSharp.Compiler.CompilerObject; diff --git a/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj b/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj similarity index 56% rename from ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj rename to ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj index fa615868..18eb5ec3 100644 --- a/ZSharp.Compiler.ILLoader/ZSharp.Compiler.ILLoader.csproj +++ b/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj @@ -12,12 +12,12 @@ - - - + + - + + diff --git a/ZSharp.Compiler.ILLoader/capabilities/ITypeModifier.cs b/ZSharp.Importer.ILLoader/capabilities/ITypeModifier.cs similarity index 74% rename from ZSharp.Compiler.ILLoader/capabilities/ITypeModifier.cs rename to ZSharp.Importer.ILLoader/capabilities/ITypeModifier.cs index 785a6262..842add77 100644 --- a/ZSharp.Compiler.ILLoader/capabilities/ITypeModifier.cs +++ b/ZSharp.Importer.ILLoader/capabilities/ITypeModifier.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { public interface ITypeModifier { diff --git a/ZSharp.Compiler.ILLoader/capabilities/internal/IAddMember.cs b/ZSharp.Importer.ILLoader/capabilities/internal/IAddMember.cs similarity index 75% rename from ZSharp.Compiler.ILLoader/capabilities/internal/IAddMember.cs rename to ZSharp.Importer.ILLoader/capabilities/internal/IAddMember.cs index 390dae09..86e8cc59 100644 --- a/ZSharp.Compiler.ILLoader/capabilities/internal/IAddMember.cs +++ b/ZSharp.Importer.ILLoader/capabilities/internal/IAddMember.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { internal interface IAddMember { diff --git a/ZSharp.Compiler.ILLoader/capabilities/internal/ILazilyLoadMembers.cs b/ZSharp.Importer.ILLoader/capabilities/internal/ILazilyLoadMembers.cs similarity index 79% rename from ZSharp.Compiler.ILLoader/capabilities/internal/ILazilyLoadMembers.cs rename to ZSharp.Importer.ILLoader/capabilities/internal/ILazilyLoadMembers.cs index 54f2f80f..753b8e54 100644 --- a/ZSharp.Compiler.ILLoader/capabilities/internal/ILazilyLoadMembers.cs +++ b/ZSharp.Importer.ILLoader/capabilities/internal/ILazilyLoadMembers.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { internal interface ILazilyLoadMembers { diff --git a/ZSharp.Compiler.ILLoader/capabilities/on add/IOnAddTo.cs b/ZSharp.Importer.ILLoader/capabilities/on add/IOnAddTo.cs similarity index 100% rename from ZSharp.Compiler.ILLoader/capabilities/on add/IOnAddTo.cs rename to ZSharp.Importer.ILLoader/capabilities/on add/IOnAddTo.cs diff --git a/ZSharp.Compiler.ILLoader/capabilities/on add/OnAddResult.cs b/ZSharp.Importer.ILLoader/capabilities/on add/OnAddResult.cs similarity index 100% rename from ZSharp.Compiler.ILLoader/capabilities/on add/OnAddResult.cs rename to ZSharp.Importer.ILLoader/capabilities/on add/OnAddResult.cs diff --git a/ZSharp.Compiler.ILLoader/extensions/ILLoaderExtensions.cs b/ZSharp.Importer.ILLoader/extensions/ILLoaderExtensions.cs similarity index 84% rename from ZSharp.Compiler.ILLoader/extensions/ILLoaderExtensions.cs rename to ZSharp.Importer.ILLoader/extensions/ILLoaderExtensions.cs index 73e00dc6..2a64f787 100644 --- a/ZSharp.Compiler.ILLoader/extensions/ILLoaderExtensions.cs +++ b/ZSharp.Importer.ILLoader/extensions/ILLoaderExtensions.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { public static class ILLoaderExtensions { diff --git a/ZSharp.Compiler.ILLoader/extensions/InternalILMemberExtensions.cs b/ZSharp.Importer.ILLoader/extensions/InternalILMemberExtensions.cs similarity index 95% rename from ZSharp.Compiler.ILLoader/extensions/InternalILMemberExtensions.cs rename to ZSharp.Importer.ILLoader/extensions/InternalILMemberExtensions.cs index b4e2c869..80935a92 100644 --- a/ZSharp.Compiler.ILLoader/extensions/InternalILMemberExtensions.cs +++ b/ZSharp.Importer.ILLoader/extensions/InternalILMemberExtensions.cs @@ -1,8 +1,8 @@ using System.Diagnostics.CodeAnalysis; using System.Reflection; -using ZSharp.Compiler.ILLoader.Objects; +using ZSharp.Importer.ILLoader.Objects; -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { internal static class InternalILMemberExtensions { diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Events.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.Events.cs similarity index 75% rename from ZSharp.Compiler.ILLoader/il loader/ILLoader.Events.cs rename to ZSharp.Importer.ILLoader/il loader/ILLoader.Events.cs index f0bb917b..900b0b45 100644 --- a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Events.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.Events.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Expose.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs similarity index 98% rename from ZSharp.Compiler.ILLoader/il loader/ILLoader.Expose.cs rename to ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs index 0a6f1be2..bbb63fc5 100644 --- a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Expose.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs @@ -1,7 +1,7 @@ using CommonZ.Utils; using System.Diagnostics.CodeAnalysis; -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { public sealed partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.IR.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.IR.cs similarity index 56% rename from ZSharp.Compiler.ILLoader/il loader/ILLoader.IR.cs rename to ZSharp.Importer.ILLoader/il loader/ILLoader.IR.cs index be276276..10f29d8b 100644 --- a/ZSharp.Compiler.ILLoader/il loader/ILLoader.IR.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.IR.cs @@ -1,10 +1,10 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { - public IR? IR { get; } + public Compiler.IR? IR { get; } - public IR RequireIR() + public Compiler.IR RequireIR() => IR ?? throw new InvalidOperationException("ILLoader was not initialized with a Runtime"); } } diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Namespaces.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.Namespaces.cs similarity index 93% rename from ZSharp.Compiler.ILLoader/il loader/ILLoader.Namespaces.cs rename to ZSharp.Importer.ILLoader/il loader/ILLoader.Namespaces.cs index 8f393c27..c518b068 100644 --- a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Namespaces.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.Namespaces.cs @@ -1,7 +1,7 @@ using CommonZ.Utils; -using ZSharp.Compiler.ILLoader.Objects; +using ZSharp.Importer.ILLoader.Objects; -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Runtime.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.Runtime.cs similarity index 50% rename from ZSharp.Compiler.ILLoader/il loader/ILLoader.Runtime.cs rename to ZSharp.Importer.ILLoader/il loader/ILLoader.Runtime.cs index 73c75336..da5be176 100644 --- a/ZSharp.Compiler.ILLoader/il loader/ILLoader.Runtime.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.Runtime.cs @@ -1,10 +1,10 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { - public Runtime.Runtime? Runtime { get; } + public Platform.Runtime.Runtime? Runtime { get; } - public Runtime.Runtime RequireRuntime() + public Platform.Runtime.Runtime RequireRuntime() => Runtime ?? throw new InvalidOperationException("ILLoader was not initialized with a Runtime"); } } diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.TypeSystem.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.TypeSystem.cs similarity index 70% rename from ZSharp.Compiler.ILLoader/il loader/ILLoader.TypeSystem.cs rename to ZSharp.Importer.ILLoader/il loader/ILLoader.TypeSystem.cs index 691d4730..18c4ae68 100644 --- a/ZSharp.Compiler.ILLoader/il loader/ILLoader.TypeSystem.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.TypeSystem.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.cs similarity index 96% rename from ZSharp.Compiler.ILLoader/il loader/ILLoader.cs rename to ZSharp.Importer.ILLoader/il loader/ILLoader.cs index f2445f66..b37d56d0 100644 --- a/ZSharp.Compiler.ILLoader/il loader/ILLoader.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.cs @@ -1,8 +1,8 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { public sealed partial class ILLoader { - public ILLoader(IR ir, Runtime.Runtime runtime) + public ILLoader(Compiler.IR ir, Platform.Runtime.Runtime runtime) { IR = ir; Runtime = runtime; diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Constructor.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Constructor.cs similarity index 83% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Constructor.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Constructor.cs index 2ddb54e8..25c677ed 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Constructor.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Constructor.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Event.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Event.cs similarity index 81% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Event.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Event.cs index 0e402b40..cb502e7f 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Event.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Event.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Field.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Field.cs similarity index 81% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Field.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Field.cs index d5796c95..9982820e 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Field.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Field.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.Generic.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Method.Generic.cs similarity index 82% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.Generic.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Method.Generic.cs index 753638de..a42de207 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.Generic.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Method.Generic.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs similarity index 89% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs index 5aa3c4a8..f4b0cf93 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Method.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Property.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Property.cs similarity index 82% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Property.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Property.cs index a2660f2d..4ac45447 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.Property.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.Property.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.cs similarity index 95% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.cs index 081dcbbf..4f519a0f 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Member.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Member.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Module.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Module.cs similarity index 93% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Module.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Module.cs index 7e435415..84573ff6 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Module.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Module.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs similarity index 81% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs index e4ca4917..5dfb70c5 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Class.Generic.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs similarity index 87% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs index a02d873e..dbbbc95a 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Class.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs similarity index 81% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs index d3bc5166..22aadad3 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Enum.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs similarity index 82% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs index 79af355b..4a1d047f 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Generic.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs similarity index 82% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs index e3d1a4c7..f6fddbc6 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Interface.Generic.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs similarity index 88% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs index a0b56a3d..c625e366 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs similarity index 97% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs index 545fa5ec..f92ce484 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Modified.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs similarity index 81% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs index 7b685dd2..f55e75e1 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Struct.Generic.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs similarity index 87% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs index f4081f99..0e0c5796 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Struct.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.cs similarity index 95% rename from ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs rename to ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.cs index 11680752..d6b90235 100644 --- a/ZSharp.Compiler.ILLoader/il loader/load/ILLoader.Load.Type.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ILLoader { diff --git a/ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs b/ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs similarity index 95% rename from ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs rename to ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs index 1b4aa3cc..624aa09a 100644 --- a/ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs +++ b/ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ModuleBodyLoader : ILazilyLoadMembers diff --git a/ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.cs b/ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.cs similarity index 84% rename from ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.cs rename to ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.cs index 4b999250..5dcb481a 100644 --- a/ZSharp.Compiler.ILLoader/module body loader/ModuleBodyLoader.cs +++ b/ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { internal sealed partial class ModuleBodyLoader(IAddMember container, ILLoader loader) { diff --git a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs b/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs similarity index 88% rename from ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs rename to ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs index 5e7f787b..c234b3cb 100644 --- a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs +++ b/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ModuleBodyLoader { diff --git a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs b/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs similarity index 83% rename from ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs rename to ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs index 405fdd8d..5f8ba89c 100644 --- a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs +++ b/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ModuleBodyLoader { diff --git a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs b/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs similarity index 91% rename from ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs rename to ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs index cf3db067..6a6d0ecb 100644 --- a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs +++ b/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ModuleBodyLoader { diff --git a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs b/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs similarity index 83% rename from ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs rename to ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs index 1e4af706..61a64f84 100644 --- a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs +++ b/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ModuleBodyLoader { diff --git a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs b/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs similarity index 92% rename from ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs rename to ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs index e015e4e8..41255873 100644 --- a/ZSharp.Compiler.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs +++ b/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ModuleBodyLoader { diff --git a/ZSharp.Compiler.ILLoader/module loader/ModuleLoader.cs b/ZSharp.Importer.ILLoader/module loader/ModuleLoader.cs similarity index 77% rename from ZSharp.Compiler.ILLoader/module loader/ModuleLoader.cs rename to ZSharp.Importer.ILLoader/module loader/ModuleLoader.cs index 617dbbb9..bcd5cb3c 100644 --- a/ZSharp.Compiler.ILLoader/module loader/ModuleLoader.cs +++ b/ZSharp.Importer.ILLoader/module loader/ModuleLoader.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { internal sealed partial class ModuleLoader(ILLoader loader) { diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Field.cs b/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Field.cs similarity index 88% rename from ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Field.cs rename to ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Field.cs index 5fa260ba..c4594694 100644 --- a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Field.cs +++ b/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Field.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ModuleLoader { diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs b/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs similarity index 83% rename from ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs rename to ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs index 48ba19b6..1414f6e1 100644 --- a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs +++ b/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ModuleLoader { diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs b/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.cs similarity index 91% rename from ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs rename to ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.cs index 8de6ac65..6bf80511 100644 --- a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Method.cs +++ b/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ModuleLoader { diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Property.cs b/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Property.cs similarity index 83% rename from ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Property.cs rename to ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Property.cs index f65156dc..fcb56d01 100644 --- a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.Property.cs +++ b/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Property.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ModuleLoader { diff --git a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.cs b/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.cs similarity index 91% rename from ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.cs rename to ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.cs index 7b567f2b..279e2561 100644 --- a/ZSharp.Compiler.ILLoader/module loader/load/ModuleLoader.Load.cs +++ b/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class ModuleLoader { diff --git a/ZSharp.Compiler.ILLoader/objects/GlobalUsings.cs b/ZSharp.Importer.ILLoader/objects/GlobalUsings.cs similarity index 100% rename from ZSharp.Compiler.ILLoader/objects/GlobalUsings.cs rename to ZSharp.Importer.ILLoader/objects/GlobalUsings.cs diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.Call.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs similarity index 74% rename from ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.Call.cs rename to ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs index 61e876dc..994e85a0 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs @@ -1,10 +1,11 @@ - -namespace ZSharp.Compiler.ILLoader.Objects +using ZSharp.Compiler; + +namespace ZSharp.Importer.ILLoader.Objects { partial class Function : ICTCallable { - CompilerObjectResult ICTCallable.Call(Compiler compiler, Argument[] arguments) + CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { IRCode result = new(); @@ -20,7 +21,7 @@ CompilerObjectResult ICTCallable.Call(Compiler compiler, Argument[] arguments) result.Instructions.AddRange(argumentCode!.Instructions); } - result.Instructions.Add(new ZSharp.IR.VM.Call(GetIR())); + result.Instructions.Add(new IR.VM.Call(GetIR())); result.Types.Add(GetIR().ReturnType); return CompilerObjectResult.Ok(new RawIRCode(result)); diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IL.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IL.cs similarity index 75% rename from ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IL.cs rename to ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IL.cs index 8ccc216d..81a95d51 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IL.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IL.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Function { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IR.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IR.cs similarity index 93% rename from ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IR.cs rename to ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IR.cs index cdd90da4..fbba7ba8 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.IR.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IR.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Function { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.cs similarity index 71% rename from ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.cs rename to ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.cs index 17dc63ac..ac8ba5e6 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/function/concrete/Function.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class Function(IL.MethodInfo il, ILLoader loader) : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.IL.cs b/ZSharp.Importer.ILLoader/objects/modular/function/generic/GenericFunction.IL.cs similarity index 66% rename from ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.IL.cs rename to ZSharp.Importer.ILLoader/objects/modular/function/generic/GenericFunction.IL.cs index c9b9abdb..80a87127 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.IL.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/generic/GenericFunction.IL.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class GenericFunction { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.cs b/ZSharp.Importer.ILLoader/objects/modular/function/generic/GenericFunction.cs similarity index 65% rename from ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.cs rename to ZSharp.Importer.ILLoader/objects/modular/function/generic/GenericFunction.cs index d76b4f2f..a5111105 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/function/generic/GenericFunction.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/generic/GenericFunction.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class GenericFunction : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/modular/global/Global.IL.cs b/ZSharp.Importer.ILLoader/objects/modular/global/Global.IL.cs similarity index 63% rename from ZSharp.Compiler.ILLoader/objects/modular/global/Global.IL.cs rename to ZSharp.Importer.ILLoader/objects/modular/global/Global.IL.cs index 6b93e9d6..46f542a7 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/global/Global.IL.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/global/Global.IL.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Global { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/global/Global.Type.cs b/ZSharp.Importer.ILLoader/objects/modular/global/Global.Type.cs similarity index 59% rename from ZSharp.Compiler.ILLoader/objects/modular/global/Global.Type.cs rename to ZSharp.Importer.ILLoader/objects/modular/global/Global.Type.cs index 18321fdd..a97632ff 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/global/Global.Type.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/global/Global.Type.cs @@ -1,4 +1,6 @@ -namespace ZSharp.Compiler.ILLoader.Objects +using ZSharp.Compiler; + +namespace ZSharp.Importer.ILLoader.Objects { partial class Global : ITyped diff --git a/ZSharp.Compiler.ILLoader/objects/modular/global/Global.cs b/ZSharp.Importer.ILLoader/objects/modular/global/Global.cs similarity index 85% rename from ZSharp.Compiler.ILLoader/objects/modular/global/Global.cs rename to ZSharp.Importer.ILLoader/objects/modular/global/Global.cs index b0e6dd89..0f015c72 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/global/Global.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/global/Global.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class Global : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Globals.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Globals.cs similarity index 93% rename from ZSharp.Compiler.ILLoader/objects/modular/module/Module.Globals.cs rename to ZSharp.Importer.ILLoader/objects/modular/module/Module.Globals.cs index 22a75e40..6423c385 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Globals.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Globals.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Module { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.IL.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.IL.cs similarity index 62% rename from ZSharp.Compiler.ILLoader/objects/modular/module/Module.IL.cs rename to ZSharp.Importer.ILLoader/objects/modular/module/Module.IL.cs index de8fcbc6..37e56a84 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.IL.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/module/Module.IL.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Module { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.LazyLoad.cs similarity index 87% rename from ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs rename to ZSharp.Importer.ILLoader/objects/modular/module/Module.LazyLoad.cs index bbe2e5c2..1bfdcd77 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.LazyLoad.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/module/Module.LazyLoad.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Module { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Member.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs similarity index 89% rename from ZSharp.Compiler.ILLoader/objects/modular/module/Module.Member.cs rename to ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs index 59fd92c7..c7aaa9ee 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs @@ -1,6 +1,7 @@ using CommonZ.Utils; +using ZSharp.Compiler; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Module : IAddMember @@ -18,7 +19,7 @@ public void AddMember(string name, CompilerObject member) Members.Add(name, member); } - CompilerObjectResult ICTGetMember.Member(Compiler compiler, MemberName member) + CompilerObjectResult ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) { if (!Members.TryGetValue(member, out var result) && (result = LoadMember(member)) is null) return CompilerObjectResult.Error( diff --git a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.cs similarity index 96% rename from ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs rename to ZSharp.Importer.ILLoader/objects/modular/module/Module.cs index 60bc53dc..10061afc 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/module/Module.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/module/Module.cs @@ -1,6 +1,6 @@ using System.Reflection; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { internal sealed partial class Module : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/modular/property/GlobalProperty.cs b/ZSharp.Importer.ILLoader/objects/modular/property/GlobalProperty.cs similarity index 57% rename from ZSharp.Compiler.ILLoader/objects/modular/property/GlobalProperty.cs rename to ZSharp.Importer.ILLoader/objects/modular/property/GlobalProperty.cs index c6cb9f4a..739243c4 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/property/GlobalProperty.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/property/GlobalProperty.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class GlobalProperty { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.IL.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.IL.cs similarity index 63% rename from ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.IL.cs rename to ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.IL.cs index 6da65ff2..4dd1cb7d 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.IL.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.IL.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class TypeAsModule { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs similarity index 87% rename from ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs rename to ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs index 07b4471a..9eca7ff3 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class TypeAsModule { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs similarity index 89% rename from ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs rename to ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs index d8e5eacf..ddcd90f4 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs @@ -1,6 +1,7 @@ using CommonZ.Utils; +using ZSharp.Compiler; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class TypeAsModule : IAddMember @@ -18,7 +19,7 @@ public void AddMember(string name, CompilerObject member) Members.Add(name, member); } - CompilerObjectResult ICTGetMember.Member(Compiler compiler, MemberName member) + CompilerObjectResult ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) { if (!Members.TryGetValue(member, out var result) && (result = LoadMember(member)) is null) return CompilerObjectResult.Error( diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Namespace.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Namespace.cs similarity index 66% rename from ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Namespace.cs rename to ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Namespace.cs index c23cd896..a7a6e291 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Namespace.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Namespace.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class TypeAsModule { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs similarity index 95% rename from ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs rename to ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs index dab613e4..010d241d 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class TypeAsModule { diff --git a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.cs similarity index 92% rename from ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.cs rename to ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.cs index fa936e47..23218d93 100644 --- a/ZSharp.Compiler.ILLoader/objects/modular/type as module/TypeAsModule.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.cs @@ -1,6 +1,6 @@ using System.Reflection; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { internal sealed partial class TypeAsModule : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.LazyLoad.cs b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.LazyLoad.cs similarity index 92% rename from ZSharp.Compiler.ILLoader/objects/namespace/Namespace.LazyLoad.cs rename to ZSharp.Importer.ILLoader/objects/namespace/Namespace.LazyLoad.cs index ddb6282d..eaa833c8 100644 --- a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.LazyLoad.cs +++ b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.LazyLoad.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Namespace : ILazilyLoadMembers diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs similarity index 89% rename from ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs rename to ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs index 0fec91b2..7c93cfa2 100644 --- a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs @@ -1,6 +1,7 @@ using CommonZ.Utils; +using ZSharp.Compiler; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Namespace : ICTGetMember @@ -17,7 +18,7 @@ public void AddMember(string name, CompilerObject member) Members.Add(name, member); } - CompilerObjectResult ICTGetMember.Member(Compiler compiler, MemberName member) + CompilerObjectResult ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) { if (!Members.TryGetValue(member, out var result)) if ((result = LoadMember(member)) is not null) diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.OnAddTo.cs b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.OnAddTo.cs similarity index 86% rename from ZSharp.Compiler.ILLoader/objects/namespace/Namespace.OnAddTo.cs rename to ZSharp.Importer.ILLoader/objects/namespace/Namespace.OnAddTo.cs index 0025a18c..f9f6809c 100644 --- a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.OnAddTo.cs +++ b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.OnAddTo.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Namespace : IOnAddTo diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Parent.cs b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Parent.cs similarity index 88% rename from ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Parent.cs rename to ZSharp.Importer.ILLoader/objects/namespace/Namespace.Parent.cs index 69a34d30..2fa160cc 100644 --- a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.Parent.cs +++ b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Parent.cs @@ -1,6 +1,6 @@ using System.Diagnostics.CodeAnalysis; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Namespace { diff --git a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.cs b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.cs similarity index 82% rename from ZSharp.Compiler.ILLoader/objects/namespace/Namespace.cs rename to ZSharp.Importer.ILLoader/objects/namespace/Namespace.cs index 7c57318f..1df1501f 100644 --- a/ZSharp.Compiler.ILLoader/objects/namespace/Namespace.cs +++ b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class Namespace(string name, ILLoader loader) : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IL.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IL.cs similarity index 71% rename from ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IL.cs rename to ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IL.cs index dc3c5a7f..1107cd66 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.IL.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IL.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Class { diff --git a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs new file mode 100644 index 00000000..6e808a21 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs @@ -0,0 +1,29 @@ +using ZSharp.Compiler; +using ZSharp.IR; + +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Class + : ICompileIRDefinitionAs + , ICompileIRType> + { + private IR.Class? IR { get; set; } + + Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.IR ir, object? target) + => Result.Ok(GetIR()); + + Result> ICompileIRType>.CompileIRType(Compiler.IR ir) + => Result>.Ok(new ClassReference(GetIR())); + + private IR.Class GetIR() + { + if (IR is null) + { + IR = new(IL.Name); + Loader.RequireRuntime().AddTypeDefinition(IR, IL); + } + + return IR; + } + } +} diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.cs similarity index 80% rename from ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.cs rename to ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.cs index 52ad5e95..b3fc5835 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/class/concrete/Class.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class Class : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.T.cs b/ZSharp.Importer.ILLoader/objects/oop/class/generic/GenericClass.T.cs similarity index 51% rename from ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.T.cs rename to ZSharp.Importer.ILLoader/objects/oop/class/generic/GenericClass.T.cs index 66aa704b..c3d7431d 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.T.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/class/generic/GenericClass.T.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class GenericClass { diff --git a/ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.cs b/ZSharp.Importer.ILLoader/objects/oop/class/generic/GenericClass.cs similarity index 65% rename from ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.cs rename to ZSharp.Importer.ILLoader/objects/oop/class/generic/GenericClass.cs index d392f0e5..bd040795 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/class/generic/GenericClass.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/class/generic/GenericClass.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class GenericClass : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.T.cs b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.T.cs similarity index 50% rename from ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.T.cs rename to ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.T.cs index f3194f43..bb763919 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.T.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.T.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Constructor { diff --git a/ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.cs b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.cs similarity index 64% rename from ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.cs rename to ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.cs index 3fe8b545..62e1e48f 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/constructor/Constructor.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class Constructor : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.cs b/ZSharp.Importer.ILLoader/objects/oop/enum/Enum.cs similarity index 62% rename from ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.cs rename to ZSharp.Importer.ILLoader/objects/oop/enum/Enum.cs index 56ee35e7..d6b186b3 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/enum/Enum.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/enum/Enum.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class Enum : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/field/Field.cs b/ZSharp.Importer.ILLoader/objects/oop/field/Field.cs similarity index 63% rename from ZSharp.Compiler.ILLoader/objects/oop/field/Field.cs rename to ZSharp.Importer.ILLoader/objects/oop/field/Field.cs index d8a4aa0e..8917ea76 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/field/Field.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/field/Field.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class Field : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.cs b/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.cs similarity index 64% rename from ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.cs rename to ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.cs index 732c7c8b..c4bc234a 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/interface/concrete/Interface.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class Interface : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.T.cs b/ZSharp.Importer.ILLoader/objects/oop/interface/generic/GenericInterface.T.cs similarity index 53% rename from ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.T.cs rename to ZSharp.Importer.ILLoader/objects/oop/interface/generic/GenericInterface.T.cs index 39fae699..ebf3403a 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.T.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/interface/generic/GenericInterface.T.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class GenericInterface { diff --git a/ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.cs b/ZSharp.Importer.ILLoader/objects/oop/interface/generic/GenericInterface.cs similarity index 66% rename from ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.cs rename to ZSharp.Importer.ILLoader/objects/oop/interface/generic/GenericInterface.cs index 9ec40ec6..d531a16e 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/interface/generic/GenericInterface.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/interface/generic/GenericInterface.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class GenericInterface : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs b/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs similarity index 64% rename from ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs rename to ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs index 920a0e96..e5541b70 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs @@ -1,9 +1,11 @@ -namespace ZSharp.Compiler.ILLoader.Objects +using ZSharp.Compiler; + +namespace ZSharp.Importer.ILLoader.Objects { partial class BoundMethod : ICTCallable { - CompilerObjectResult ICTCallable.Call(Compiler compiler, Argument[] arguments) + CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { if (Object is not null) arguments = [ diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.T.cs b/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.T.cs similarity index 50% rename from ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.T.cs rename to ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.T.cs index bcaa893f..3faaa4dc 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.T.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.T.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class BoundMethod { diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.cs b/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.cs similarity index 81% rename from ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.cs rename to ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.cs index c775e5f3..25b27ebe 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/method/bound/BoundMethod.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class BoundMethod : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.Call.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs similarity index 74% rename from ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.Call.cs rename to ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs index ded3ea72..13b74495 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs @@ -1,10 +1,12 @@  -namespace ZSharp.Compiler.ILLoader.Objects +using ZSharp.Compiler; + +namespace ZSharp.Importer.ILLoader.Objects { partial class Method : ICTCallable { - CompilerObjectResult ICTCallable.Call(Compiler compiler, Argument[] arguments) + CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { IRCode result = new(); @@ -20,7 +22,7 @@ CompilerObjectResult ICTCallable.Call(Compiler compiler, Argument[] arguments) result.Instructions.AddRange(argumentCode!.Instructions); } - result.Instructions.Add(new ZSharp.IR.VM.Call(GetIR())); + result.Instructions.Add(new IR.VM.Call(GetIR())); result.Types.Add(GetIR().ReturnType); return CompilerObjectResult.Ok(new RawIRCode(result)); diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IL.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.IL.cs similarity index 72% rename from ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IL.cs rename to ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.IL.cs index 52c32535..82bb99a3 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IL.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.IL.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Method { diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IR.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.IR.cs similarity index 93% rename from ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IR.cs rename to ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.IR.cs index 19fd85bb..0a8ecd1b 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.IR.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.IR.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class Method { diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.cs similarity index 81% rename from ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.cs rename to ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.cs index ec0c75f7..5632c90f 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/method/concrete/Method.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class Method : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.T.cs b/ZSharp.Importer.ILLoader/objects/oop/method/generic/GenericMethod.T.cs similarity index 51% rename from ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.T.cs rename to ZSharp.Importer.ILLoader/objects/oop/method/generic/GenericMethod.T.cs index 2d197722..b009d8ff 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.T.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/generic/GenericMethod.T.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class GenericMethod { diff --git a/ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.cs b/ZSharp.Importer.ILLoader/objects/oop/method/generic/GenericMethod.cs similarity index 65% rename from ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.cs rename to ZSharp.Importer.ILLoader/objects/oop/method/generic/GenericMethod.cs index bba32a29..ce413669 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/method/generic/GenericMethod.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/generic/GenericMethod.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class GenericMethod : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/property/Property.cs b/ZSharp.Importer.ILLoader/objects/oop/property/Property.cs similarity index 64% rename from ZSharp.Compiler.ILLoader/objects/oop/property/Property.cs rename to ZSharp.Importer.ILLoader/objects/oop/property/Property.cs index ae20fce0..9f61bbb4 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/property/Property.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/property/Property.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class Property : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.cs b/ZSharp.Importer.ILLoader/objects/oop/struct/concrete/Struct.cs similarity index 63% rename from ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.cs rename to ZSharp.Importer.ILLoader/objects/oop/struct/concrete/Struct.cs index 39243b94..e0f1de9e 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/struct/concrete/Struct.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/struct/concrete/Struct.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class Struct : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.T.cs b/ZSharp.Importer.ILLoader/objects/oop/struct/generic/GenericStruct.T.cs similarity index 51% rename from ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.T.cs rename to ZSharp.Importer.ILLoader/objects/oop/struct/generic/GenericStruct.T.cs index 6c6bf285..8fee7d18 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.T.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/struct/generic/GenericStruct.T.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { partial class GenericStruct { diff --git a/ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.cs b/ZSharp.Importer.ILLoader/objects/oop/struct/generic/GenericStruct.cs similarity index 65% rename from ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.cs rename to ZSharp.Importer.ILLoader/objects/oop/struct/generic/GenericStruct.cs index fe32bb0f..299ba4e2 100644 --- a/ZSharp.Compiler.ILLoader/objects/oop/struct/generic/GenericStruct.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/struct/generic/GenericStruct.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class GenericStruct : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/types/array/ArrayType.cs b/ZSharp.Importer.ILLoader/objects/types/array/ArrayType.cs similarity index 78% rename from ZSharp.Compiler.ILLoader/objects/types/array/ArrayType.cs rename to ZSharp.Importer.ILLoader/objects/types/array/ArrayType.cs index b402f45c..3baf6970 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/array/ArrayType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/array/ArrayType.cs @@ -1,6 +1,6 @@ using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class ArrayType(OOPType type) : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/types/boolean/BooleanType.cs b/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs similarity index 59% rename from ZSharp.Compiler.ILLoader/objects/types/boolean/BooleanType.cs rename to ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs index 14a65d0b..a6f101d7 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/boolean/BooleanType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class BooleanType(OOPTypeReference type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class BooleanType(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/char/CharType.cs b/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs similarity index 58% rename from ZSharp.Compiler.ILLoader/objects/types/char/CharType.cs rename to ZSharp.Importer.ILLoader/objects/types/char/CharType.cs index 82bc5616..dfb63029 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/char/CharType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class CharType(OOPTypeReference type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class CharType(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/float/Float128Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs similarity index 59% rename from ZSharp.Compiler.ILLoader/objects/types/float/Float128Type.cs rename to ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs index 1b37d698..55859bc9 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/float/Float128Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class Float128Type(OOPTypeReference type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class Float128Type(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/float/Float16Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs similarity index 59% rename from ZSharp.Compiler.ILLoader/objects/types/float/Float16Type.cs rename to ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs index e04c7d30..909cd240 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/float/Float16Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class Float16Type(OOPTypeReference type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class Float16Type(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/float/Float32Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs similarity index 59% rename from ZSharp.Compiler.ILLoader/objects/types/float/Float32Type.cs rename to ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs index 318ffbf9..24c564d7 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/float/Float32Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class Float32Type(OOPTypeReference type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class Float32Type(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/float/Float64Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs similarity index 59% rename from ZSharp.Compiler.ILLoader/objects/types/float/Float64Type.cs rename to ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs index 94678dfc..852e3e83 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/float/Float64Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class Float64Type(OOPTypeReference type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class Float64Type(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/SInt16Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt16Type.cs similarity index 56% rename from ZSharp.Compiler.ILLoader/objects/types/int/SInt16Type.cs rename to ZSharp.Importer.ILLoader/objects/types/int/SInt16Type.cs index b6e3320e..865e4a74 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/int/SInt16Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt16Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class SInt16Type(IType type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class SInt16Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/SInt32Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt32Type.cs similarity index 56% rename from ZSharp.Compiler.ILLoader/objects/types/int/SInt32Type.cs rename to ZSharp.Importer.ILLoader/objects/types/int/SInt32Type.cs index 0ec1b45d..cdadcb0e 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/int/SInt32Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt32Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class SInt32Type(IType type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class SInt32Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/SInt64Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt64Type.cs similarity index 56% rename from ZSharp.Compiler.ILLoader/objects/types/int/SInt64Type.cs rename to ZSharp.Importer.ILLoader/objects/types/int/SInt64Type.cs index 49f5eae0..95ee7852 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/int/SInt64Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt64Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class SInt64Type(IType type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class SInt64Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/SInt8Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt8Type.cs similarity index 56% rename from ZSharp.Compiler.ILLoader/objects/types/int/SInt8Type.cs rename to ZSharp.Importer.ILLoader/objects/types/int/SInt8Type.cs index 3207bb88..f28dbff8 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/int/SInt8Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt8Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class SInt8Type(IType type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class SInt8Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/SIntNativeType.cs b/ZSharp.Importer.ILLoader/objects/types/int/SIntNativeType.cs similarity index 56% rename from ZSharp.Compiler.ILLoader/objects/types/int/SIntNativeType.cs rename to ZSharp.Importer.ILLoader/objects/types/int/SIntNativeType.cs index 98b68c7b..c79f9ee7 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/int/SIntNativeType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SIntNativeType.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class SIntNativeType(IType type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class SIntNativeType(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/UInt16Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt16Type.cs similarity index 56% rename from ZSharp.Compiler.ILLoader/objects/types/int/UInt16Type.cs rename to ZSharp.Importer.ILLoader/objects/types/int/UInt16Type.cs index 24440729..0f956987 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/int/UInt16Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt16Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class UInt16Type(IType type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class UInt16Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/UInt32Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt32Type.cs similarity index 56% rename from ZSharp.Compiler.ILLoader/objects/types/int/UInt32Type.cs rename to ZSharp.Importer.ILLoader/objects/types/int/UInt32Type.cs index 9a715f2b..7f7f426c 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/int/UInt32Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt32Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class UInt32Type(IType type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class UInt32Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/UInt64Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt64Type.cs similarity index 56% rename from ZSharp.Compiler.ILLoader/objects/types/int/UInt64Type.cs rename to ZSharp.Importer.ILLoader/objects/types/int/UInt64Type.cs index e8913cc0..064f6894 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/int/UInt64Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt64Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class UInt64Type(IType type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class UInt64Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/UInt8Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt8Type.cs similarity index 56% rename from ZSharp.Compiler.ILLoader/objects/types/int/UInt8Type.cs rename to ZSharp.Importer.ILLoader/objects/types/int/UInt8Type.cs index 463f8b2c..3945cab7 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/int/UInt8Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt8Type.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class UInt8Type(IType type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class UInt8Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/int/UIntNativeType.cs b/ZSharp.Importer.ILLoader/objects/types/int/UIntNativeType.cs similarity index 56% rename from ZSharp.Compiler.ILLoader/objects/types/int/UIntNativeType.cs rename to ZSharp.Importer.ILLoader/objects/types/int/UIntNativeType.cs index 8ff169ad..76971f1a 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/int/UIntNativeType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UIntNativeType.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class UIntNativeType(IType type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class UIntNativeType(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/object/ObjectType.cs b/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs similarity index 58% rename from ZSharp.Compiler.ILLoader/objects/types/object/ObjectType.cs rename to ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs index 31c66e26..c1400016 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/object/ObjectType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class ObjectType(OOPTypeReference type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class ObjectType(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/pointer/PointerType.cs b/ZSharp.Importer.ILLoader/objects/types/pointer/PointerType.cs similarity index 78% rename from ZSharp.Compiler.ILLoader/objects/types/pointer/PointerType.cs rename to ZSharp.Importer.ILLoader/objects/types/pointer/PointerType.cs index c46aba60..a308210c 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/pointer/PointerType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/pointer/PointerType.cs @@ -1,6 +1,6 @@ using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class PointerType(OOPType type) : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/types/reference/ReferenceType.cs b/ZSharp.Importer.ILLoader/objects/types/reference/ReferenceType.cs similarity index 78% rename from ZSharp.Compiler.ILLoader/objects/types/reference/ReferenceType.cs rename to ZSharp.Importer.ILLoader/objects/types/reference/ReferenceType.cs index 47037c7a..ff2a3a61 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/reference/ReferenceType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/reference/ReferenceType.cs @@ -1,6 +1,6 @@ using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class ReferenceType(OOPType type) : CompilerObject diff --git a/ZSharp.Compiler.ILLoader/objects/types/string/StringType.cs b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs similarity index 58% rename from ZSharp.Compiler.ILLoader/objects/types/string/StringType.cs rename to ZSharp.Importer.ILLoader/objects/types/string/StringType.cs index 71d5e197..988a7b62 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/string/StringType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class StringType(OOPTypeReference type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class StringType(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/objects/types/void/VoidType.cs b/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs similarity index 58% rename from ZSharp.Compiler.ILLoader/objects/types/void/VoidType.cs rename to ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs index a45312d0..1b0edb62 100644 --- a/ZSharp.Compiler.ILLoader/objects/types/void/VoidType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs @@ -1,6 +1,7 @@ -using ZSharp.IR; +using ZSharp.Compiler; +using ZSharp.IR; -namespace ZSharp.Compiler.ILLoader.Objects +namespace ZSharp.Importer.ILLoader.Objects { public sealed class VoidType(OOPTypeReference type) : CompilerObject @@ -8,7 +9,7 @@ public sealed class VoidType(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(IR ir) + Result ICompileIRType.CompileIRType(Compiler.IR ir) => Result.Ok(type); } } diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Array.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.Array.cs similarity index 73% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.Array.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.Array.cs index e0ff40b1..9d3592a1 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Array.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.Array.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class TypeSystem { diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Boolean.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.Boolean.cs similarity index 73% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.Boolean.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.Boolean.cs index 909fe79c..dbe478e8 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Boolean.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.Boolean.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class TypeSystem { diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Char.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.Char.cs similarity index 73% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.Char.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.Char.cs index 52c357d0..33ac997e 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Char.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.Char.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class TypeSystem { diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Float.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.Float.cs similarity index 88% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.Float.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.Float.cs index cc5b29d3..e0d2e4d4 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Float.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.Float.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class TypeSystem { diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Object.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.Object.cs similarity index 73% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.Object.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.Object.cs index c50ae11a..043f5fdf 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Object.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.Object.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class TypeSystem { diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Pointer.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.Pointer.cs similarity index 73% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.Pointer.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.Pointer.cs index 40040036..e82250fa 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Pointer.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.Pointer.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class TypeSystem { diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Reference.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.Reference.cs similarity index 74% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.Reference.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.Reference.cs index 5b1fce9a..204d5f44 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Reference.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.Reference.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class TypeSystem { diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.SInt.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.SInt.cs similarity index 90% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.SInt.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.SInt.cs index 09c43fe7..c293befa 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.SInt.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.SInt.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class TypeSystem { diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.String.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.String.cs similarity index 73% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.String.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.String.cs index 3388d09a..8ed543c0 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.String.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.String.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class TypeSystem { diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.UInt.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.UInt.cs similarity index 90% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.UInt.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.UInt.cs index f66147c4..12a1b14e 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.UInt.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.UInt.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class TypeSystem { diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Void.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.Void.cs similarity index 73% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.Void.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.Void.cs index 2e700da9..1437fd39 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.Void.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.Void.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { partial class TypeSystem { diff --git a/ZSharp.Compiler.ILLoader/type system/TypeSystem.cs b/ZSharp.Importer.ILLoader/type system/TypeSystem.cs similarity index 64% rename from ZSharp.Compiler.ILLoader/type system/TypeSystem.cs rename to ZSharp.Importer.ILLoader/type system/TypeSystem.cs index 5e208bd8..33d36bfb 100644 --- a/ZSharp.Compiler.ILLoader/type system/TypeSystem.cs +++ b/ZSharp.Importer.ILLoader/type system/TypeSystem.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.ILLoader +namespace ZSharp.Importer.ILLoader { public sealed partial class TypeSystem() { diff --git a/ZSharp.Compiler.IRLoader/Context.cs b/ZSharp.Importer.IRLoader/Context.cs similarity index 86% rename from ZSharp.Compiler.IRLoader/Context.cs rename to ZSharp.Importer.IRLoader/Context.cs index 5ff8cc33..74681437 100644 --- a/ZSharp.Compiler.IRLoader/Context.cs +++ b/ZSharp.Importer.IRLoader/Context.cs @@ -1,6 +1,6 @@ using CommonZ.Utils; -namespace ZSharp.Compiler.IRLoader +namespace ZSharp.Importer.IRLoader { public sealed class Context { diff --git a/ZSharp.Importer.IRLoader/GlobalUsings.cs b/ZSharp.Importer.IRLoader/GlobalUsings.cs new file mode 100644 index 00000000..aeed8fe6 --- /dev/null +++ b/ZSharp.Importer.IRLoader/GlobalUsings.cs @@ -0,0 +1,3 @@ +global using ZSharp.Objects; + +global using CompilerObject = ZSharp.Compiler.CompilerObject; diff --git a/ZSharp.Compiler.IRLoader/ZSharp.Compiler.IRLoader.csproj b/ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj similarity index 100% rename from ZSharp.Compiler.IRLoader/ZSharp.Compiler.IRLoader.csproj rename to ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.API.cs b/ZSharp.Importer.IRLoader/ir loader/IRLoader.API.cs similarity index 74% rename from ZSharp.Compiler.IRLoader/ir loader/IRLoader.API.cs rename to ZSharp.Importer.IRLoader/ir loader/IRLoader.API.cs index 2eaa4bcb..2e51bfa6 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.API.cs +++ b/ZSharp.Importer.IRLoader/ir loader/IRLoader.API.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.IRLoader +namespace ZSharp.Importer.IRLoader { public partial class IRLoader { diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Importer.IRLoader/ir loader/IRLoader.Impl.cs similarity index 99% rename from ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs rename to ZSharp.Importer.IRLoader/ir loader/IRLoader.Impl.cs index e7dc7d14..461581ea 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Importer.IRLoader/ir loader/IRLoader.Impl.cs @@ -1,6 +1,6 @@ using System.Text.RegularExpressions; -namespace ZSharp.Compiler.IRLoader +namespace ZSharp.Importer.IRLoader { public partial class IRLoader { diff --git a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs b/ZSharp.Importer.IRLoader/ir loader/IRLoader.cs similarity index 95% rename from ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs rename to ZSharp.Importer.IRLoader/ir loader/IRLoader.cs index 02af9155..4537aa31 100644 --- a/ZSharp.Compiler.IRLoader/ir loader/IRLoader.cs +++ b/ZSharp.Importer.IRLoader/ir loader/IRLoader.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.IRLoader +namespace ZSharp.Importer.IRLoader { public sealed partial class IRLoader : Feature { diff --git a/ZSharp.Interpreter/ZSharp.Interpreter.csproj b/ZSharp.Interpreter/ZSharp.Interpreter.csproj index 408b38b5..bf462573 100644 --- a/ZSharp.Interpreter/ZSharp.Interpreter.csproj +++ b/ZSharp.Interpreter/ZSharp.Interpreter.csproj @@ -8,11 +8,11 @@ - + - + diff --git a/ZSharp.Interpreter/interpreter/Interpreter.IL.cs b/ZSharp.Interpreter/interpreter/Interpreter.IL.cs index 8dcf8520..f164a2d7 100644 --- a/ZSharp.Interpreter/interpreter/Interpreter.IL.cs +++ b/ZSharp.Interpreter/interpreter/Interpreter.IL.cs @@ -2,7 +2,7 @@ { partial class Interpreter { - public Compiler.ILLoader.ILLoader ILLoader { get; } + public Importer.ILLoader.ILLoader ILLoader { get; } public CompilerObject ImportILModule(System.Reflection.Module module) => ILLoader.LoadModule(module); diff --git a/ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs b/ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs index 0b2d6d3d..c03f6290 100644 --- a/ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs +++ b/ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs @@ -2,6 +2,6 @@ { partial class Interpreter { - public Runtime.Runtime Runtime { get; } + public Platform.Runtime.Runtime Runtime { get; } } } diff --git a/ZSharp.Library.Standard.FileSystem/GlobalUsings.cs b/ZSharp.Library.Standard.FileSystem/GlobalUsings.cs new file mode 100644 index 00000000..aaaf8106 --- /dev/null +++ b/ZSharp.Library.Standard.FileSystem/GlobalUsings.cs @@ -0,0 +1 @@ +global using ZSharp.Importer.ILLoader; diff --git a/ZSharp.CT.StandardLibrary.FileSystem/ModuleAttributes.cs b/ZSharp.Library.Standard.FileSystem/ModuleAttributes.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/ModuleAttributes.cs rename to ZSharp.Library.Standard.FileSystem/ModuleAttributes.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj b/ZSharp.Library.Standard.FileSystem/ZSharp.Library.Standard.FileSystem.csproj similarity index 71% rename from ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj rename to ZSharp.Library.Standard.FileSystem/ZSharp.Library.Standard.FileSystem.csproj index 846d3599..a7c03949 100644 --- a/ZSharp.CT.StandardLibrary.FileSystem/ZSharp.CT.StandardLibrary.FileSystem.csproj +++ b/ZSharp.Library.Standard.FileSystem/ZSharp.Library.Standard.FileSystem.csproj @@ -8,7 +8,7 @@ - + diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.From.cs b/ZSharp.Library.Standard.FileSystem/items/directory/Directory.From.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.From.cs rename to ZSharp.Library.Standard.FileSystem/items/directory/Directory.From.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Items.cs b/ZSharp.Library.Standard.FileSystem/items/directory/Directory.Items.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Items.cs rename to ZSharp.Library.Standard.FileSystem/items/directory/Directory.Items.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Name.cs b/ZSharp.Library.Standard.FileSystem/items/directory/Directory.Name.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Name.cs rename to ZSharp.Library.Standard.FileSystem/items/directory/Directory.Name.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Operators.cs b/ZSharp.Library.Standard.FileSystem/items/directory/Directory.Operators.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.Operators.cs rename to ZSharp.Library.Standard.FileSystem/items/directory/Directory.Operators.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.cs b/ZSharp.Library.Standard.FileSystem/items/directory/Directory.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/items/directory/Directory.cs rename to ZSharp.Library.Standard.FileSystem/items/directory/Directory.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.From.cs b/ZSharp.Library.Standard.FileSystem/items/file/File.From.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/items/file/File.From.cs rename to ZSharp.Library.Standard.FileSystem/items/file/File.From.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.Name.cs b/ZSharp.Library.Standard.FileSystem/items/file/File.Name.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/items/file/File.Name.cs rename to ZSharp.Library.Standard.FileSystem/items/file/File.Name.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/file/File.cs b/ZSharp.Library.Standard.FileSystem/items/file/File.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/items/file/File.cs rename to ZSharp.Library.Standard.FileSystem/items/file/File.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.Parent.cs b/ZSharp.Library.Standard.FileSystem/items/item/Item.Parent.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.Parent.cs rename to ZSharp.Library.Standard.FileSystem/items/item/Item.Parent.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.cs b/ZSharp.Library.Standard.FileSystem/items/item/Item.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/items/item/Item.cs rename to ZSharp.Library.Standard.FileSystem/items/item/Item.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/items/location/Location.cs b/ZSharp.Library.Standard.FileSystem/items/location/Location.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/items/location/Location.cs rename to ZSharp.Library.Standard.FileSystem/items/location/Location.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/module scope/ModuleScope.Operators.cs b/ZSharp.Library.Standard.FileSystem/module scope/ModuleScope.Operators.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/module scope/ModuleScope.Operators.cs rename to ZSharp.Library.Standard.FileSystem/module scope/ModuleScope.Operators.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/module scope/ModuleScope.cs b/ZSharp.Library.Standard.FileSystem/module scope/ModuleScope.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/module scope/ModuleScope.cs rename to ZSharp.Library.Standard.FileSystem/module scope/ModuleScope.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/path/AbsolutePath.cs b/ZSharp.Library.Standard.FileSystem/path/AbsolutePath.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/path/AbsolutePath.cs rename to ZSharp.Library.Standard.FileSystem/path/AbsolutePath.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/path/Path.cs b/ZSharp.Library.Standard.FileSystem/path/Path.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/path/Path.cs rename to ZSharp.Library.Standard.FileSystem/path/Path.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/path/RawPath.cs b/ZSharp.Library.Standard.FileSystem/path/RawPath.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/path/RawPath.cs rename to ZSharp.Library.Standard.FileSystem/path/RawPath.cs diff --git a/ZSharp.CT.StandardLibrary.FileSystem/path/RelativePath.cs b/ZSharp.Library.Standard.FileSystem/path/RelativePath.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.FileSystem/path/RelativePath.cs rename to ZSharp.Library.Standard.FileSystem/path/RelativePath.cs diff --git a/ZSharp.Library.Standard.IO/GlobalUsings.cs b/ZSharp.Library.Standard.IO/GlobalUsings.cs new file mode 100644 index 00000000..aaaf8106 --- /dev/null +++ b/ZSharp.Library.Standard.IO/GlobalUsings.cs @@ -0,0 +1 @@ +global using ZSharp.Importer.ILLoader; diff --git a/ZSharp.CT.StandardLibrary.IO/ModuleAttributes.cs b/ZSharp.Library.Standard.IO/ModuleAttributes.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.IO/ModuleAttributes.cs rename to ZSharp.Library.Standard.IO/ModuleAttributes.cs diff --git a/ZLoad.Test/ZLoad.Test.csproj b/ZSharp.Library.Standard.IO/ZSharp.Library.Standard.IO.csproj similarity index 67% rename from ZLoad.Test/ZLoad.Test.csproj rename to ZSharp.Library.Standard.IO/ZSharp.Library.Standard.IO.csproj index 0aed9cf9..a91e61d8 100644 --- a/ZLoad.Test/ZLoad.Test.csproj +++ b/ZSharp.Library.Standard.IO/ZSharp.Library.Standard.IO.csproj @@ -7,7 +7,7 @@ - + diff --git a/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Functions.cs b/ZSharp.Library.Standard.IO/module scope/ModuleScope.Functions.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Functions.cs rename to ZSharp.Library.Standard.IO/module scope/ModuleScope.Functions.cs diff --git a/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Operators.cs b/ZSharp.Library.Standard.IO/module scope/ModuleScope.Operators.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.Operators.cs rename to ZSharp.Library.Standard.IO/module scope/ModuleScope.Operators.cs diff --git a/ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.cs b/ZSharp.Library.Standard.IO/module scope/ModuleScope.cs similarity index 100% rename from ZSharp.CT.StandardLibrary.IO/module scope/ModuleScope.cs rename to ZSharp.Library.Standard.IO/module scope/ModuleScope.cs diff --git a/ZSharp.Library.Standard.Math/GlobalUsings.cs b/ZSharp.Library.Standard.Math/GlobalUsings.cs new file mode 100644 index 00000000..aaaf8106 --- /dev/null +++ b/ZSharp.Library.Standard.Math/GlobalUsings.cs @@ -0,0 +1 @@ +global using ZSharp.Importer.ILLoader; diff --git a/ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs b/ZSharp.Library.Standard.Math/ModuleScope.cs similarity index 61% rename from ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs rename to ZSharp.Library.Standard.Math/ModuleScope.cs index bbc04fab..a4820d6b 100644 --- a/ZSharp.CT.StandardLibrary.Math/Impl_Globals.cs +++ b/ZSharp.Library.Standard.Math/ModuleScope.cs @@ -1,31 +1,29 @@ -using ZSharp.Runtime.NET.IL2IR; - -namespace Standard.Math +namespace Standard.Math { - [ModuleGlobals] - public static class Impl_Globals + [ModuleScope] + public static class ModuleScope { - [Alias(Name = "ceil")] + [Alias("ceil")] public static int Ceil(float x) => (int)System.Math.Ceiling(x); - [Alias(Name = "log2")] + [Alias("log2")] public static float Log2(int x) => (float)System.Math.Log(x, 2); - [Alias(Name = "random")] + [Alias("random")] public static int Random(int min, int max) => new System.Random().Next(min, max); - [Alias(Name = "_+_")] + [Operator("+", Kind = OperatorKind.Infix)] public static int Add(int a, int b) => a + b; - [Alias(Name = "_<_")] + [Operator("<", Kind = OperatorKind.Infix)] public static bool LessThan(int a, int b) => a < b; - [Alias(Name = "_-_")] + [Operator("-", Kind = OperatorKind.Infix)] public static int Subtract(int a, int b) => a - b; } diff --git a/ZSharp.CT.StandardLibrary.IO/ZSharp.CT.StandardLibrary.IO.csproj b/ZSharp.Library.Standard.Math/ZSharp.Library.Standard.Math.csproj similarity index 67% rename from ZSharp.CT.StandardLibrary.IO/ZSharp.CT.StandardLibrary.IO.csproj rename to ZSharp.Library.Standard.Math/ZSharp.Library.Standard.Math.csproj index 2828e4bc..a91e61d8 100644 --- a/ZSharp.CT.StandardLibrary.IO/ZSharp.CT.StandardLibrary.IO.csproj +++ b/ZSharp.Library.Standard.Math/ZSharp.Library.Standard.Math.csproj @@ -7,7 +7,7 @@ - + diff --git a/ZSharp.NETCompiler/Compiler.cs b/ZSharp.Platform.IL/Compiler.cs similarity index 94% rename from ZSharp.NETCompiler/Compiler.cs rename to ZSharp.Platform.IL/Compiler.cs index dee8dd58..942224d4 100644 --- a/ZSharp.NETCompiler/Compiler.cs +++ b/ZSharp.Platform.IL/Compiler.cs @@ -1,6 +1,6 @@ using Mono.Cecil; -namespace ZSharp.NETCompiler +namespace ZSharp.Platform.IL { public sealed class Compiler { diff --git a/ZSharp.NETCompiler/ZSharp.NETCompiler.csproj b/ZSharp.Platform.IL/ZSharp.Platform.IL.csproj similarity index 100% rename from ZSharp.NETCompiler/ZSharp.NETCompiler.csproj rename to ZSharp.Platform.IL/ZSharp.Platform.IL.csproj diff --git a/ZSharp.NETCompiler/compilers/ModuleCompiler.cs b/ZSharp.Platform.IL/compilers/ModuleCompiler.cs similarity index 64% rename from ZSharp.NETCompiler/compilers/ModuleCompiler.cs rename to ZSharp.Platform.IL/compilers/ModuleCompiler.cs index 7fbf13a1..f72e1fae 100644 --- a/ZSharp.NETCompiler/compilers/ModuleCompiler.cs +++ b/ZSharp.Platform.IL/compilers/ModuleCompiler.cs @@ -1,4 +1,4 @@ -namespace ZSharp.NETCompiler +namespace ZSharp.Platform.IL { internal sealed class ModuleCompiler { diff --git a/ZSharp.NETCompiler/compilers/core/CompilerBase.cs b/ZSharp.Platform.IL/compilers/core/CompilerBase.cs similarity index 79% rename from ZSharp.NETCompiler/compilers/core/CompilerBase.cs rename to ZSharp.Platform.IL/compilers/core/CompilerBase.cs index f541b337..b08d49ab 100644 --- a/ZSharp.NETCompiler/compilers/core/CompilerBase.cs +++ b/ZSharp.Platform.IL/compilers/core/CompilerBase.cs @@ -1,4 +1,4 @@ -namespace ZSharp.NETCompiler +namespace ZSharp.Platform.IL { internal abstract class CompilerBase(Context context) { diff --git a/ZSharp.NETCompiler/compilers/core/Context.cs b/ZSharp.Platform.IL/compilers/core/Context.cs similarity index 60% rename from ZSharp.NETCompiler/compilers/core/Context.cs rename to ZSharp.Platform.IL/compilers/core/Context.cs index a9319975..04216d4f 100644 --- a/ZSharp.NETCompiler/compilers/core/Context.cs +++ b/ZSharp.Platform.IL/compilers/core/Context.cs @@ -1,4 +1,4 @@ -namespace ZSharp.NETCompiler +namespace ZSharp.Platform.IL { internal sealed class Context { diff --git a/ZSharp.Runtime/GlobalUsings.cs b/ZSharp.Platform.Runtime/GlobalUsings.cs similarity index 100% rename from ZSharp.Runtime/GlobalUsings.cs rename to ZSharp.Platform.Runtime/GlobalUsings.cs diff --git a/ZSharp.Runtime/ZSharp.Runtime.csproj b/ZSharp.Platform.Runtime/ZSharp.Platform.Runtime.csproj similarity index 100% rename from ZSharp.Runtime/ZSharp.Runtime.csproj rename to ZSharp.Platform.Runtime/ZSharp.Platform.Runtime.csproj diff --git a/ZSharp.Runtime/loader/GlobalUsings.cs b/ZSharp.Platform.Runtime/loader/GlobalUsings.cs similarity index 100% rename from ZSharp.Runtime/loader/GlobalUsings.cs rename to ZSharp.Platform.Runtime/loader/GlobalUsings.cs diff --git a/ZSharp.Runtime/loader/emit/EmitLoader.Standalone.cs b/ZSharp.Platform.Runtime/loader/emit/EmitLoader.Standalone.cs similarity index 79% rename from ZSharp.Runtime/loader/emit/EmitLoader.Standalone.cs rename to ZSharp.Platform.Runtime/loader/emit/EmitLoader.Standalone.cs index 9918823f..dd010d78 100644 --- a/ZSharp.Runtime/loader/emit/EmitLoader.Standalone.cs +++ b/ZSharp.Platform.Runtime/loader/emit/EmitLoader.Standalone.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class EmitLoader { diff --git a/ZSharp.Runtime/loader/emit/EmitLoader.cs b/ZSharp.Platform.Runtime/loader/emit/EmitLoader.cs similarity index 92% rename from ZSharp.Runtime/loader/emit/EmitLoader.cs rename to ZSharp.Platform.Runtime/loader/emit/EmitLoader.cs index 781385eb..b4fedea8 100644 --- a/ZSharp.Runtime/loader/emit/EmitLoader.cs +++ b/ZSharp.Platform.Runtime/loader/emit/EmitLoader.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal sealed partial class EmitLoader { diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Code.cs b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Code.cs similarity index 96% rename from ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Code.cs rename to ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Code.cs index bfcffb82..99f8bdf6 100644 --- a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Code.cs +++ b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Code.cs @@ -1,6 +1,6 @@ using CommonZ.Utils; -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class EmitLoader { diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Function.cs b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Function.cs similarity index 98% rename from ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Function.cs rename to ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Function.cs index 37f5e126..130baa57 100644 --- a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Function.cs +++ b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Function.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class EmitLoader { diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Module.cs b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Module.cs similarity index 77% rename from ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Module.cs rename to ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Module.cs index 243bb96e..43f659e4 100644 --- a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Module.cs +++ b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Module.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class EmitLoader { diff --git a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Type.cs similarity index 78% rename from ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs rename to ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Type.cs index 82a86aee..3ed2ef8a 100644 --- a/ZSharp.Runtime/loader/emit/load/EmitLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Type.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class EmitLoader { diff --git a/ZSharp.Runtime/loader/helpers/LoaderBase.cs b/ZSharp.Platform.Runtime/loader/helpers/LoaderBase.cs similarity index 73% rename from ZSharp.Runtime/loader/helpers/LoaderBase.cs rename to ZSharp.Platform.Runtime/loader/helpers/LoaderBase.cs index 94f27204..2974eb53 100644 --- a/ZSharp.Runtime/loader/helpers/LoaderBase.cs +++ b/ZSharp.Platform.Runtime/loader/helpers/LoaderBase.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal abstract class LoaderBase(EmitLoader loader) { diff --git a/ZSharp.Runtime/loader/helpers/TypeLoaderBase.cs b/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderBase.cs similarity index 94% rename from ZSharp.Runtime/loader/helpers/TypeLoaderBase.cs rename to ZSharp.Platform.Runtime/loader/helpers/TypeLoaderBase.cs index c18c8f78..57d13304 100644 --- a/ZSharp.Runtime/loader/helpers/TypeLoaderBase.cs +++ b/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderBase.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal abstract class TypeLoaderBase(EmitLoader loader) : LoaderBase(loader) diff --git a/ZSharp.Runtime/loader/helpers/TypeLoaderHelper.cs b/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderHelper.cs similarity index 98% rename from ZSharp.Runtime/loader/helpers/TypeLoaderHelper.cs rename to ZSharp.Platform.Runtime/loader/helpers/TypeLoaderHelper.cs index 7d0bd8a4..a353d13c 100644 --- a/ZSharp.Runtime/loader/helpers/TypeLoaderHelper.cs +++ b/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderHelper.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal static class TypeLoaderHelper { diff --git a/ZSharp.Runtime/loader/loaders/class/ClassLoader.Context.cs b/ZSharp.Platform.Runtime/loader/loaders/class/ClassLoader.Context.cs similarity index 75% rename from ZSharp.Runtime/loader/loaders/class/ClassLoader.Context.cs rename to ZSharp.Platform.Runtime/loader/loaders/class/ClassLoader.Context.cs index 4e985fc6..ac0e4fb7 100644 --- a/ZSharp.Runtime/loader/loaders/class/ClassLoader.Context.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/class/ClassLoader.Context.cs @@ -1,6 +1,6 @@ using CommonZ.Utils; -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/class/ClassLoader.Tasks.cs b/ZSharp.Platform.Runtime/loader/loaders/class/ClassLoader.Tasks.cs similarity index 90% rename from ZSharp.Runtime/loader/loaders/class/ClassLoader.Tasks.cs rename to ZSharp.Platform.Runtime/loader/loaders/class/ClassLoader.Tasks.cs index 58c8320f..38ee2933 100644 --- a/ZSharp.Runtime/loader/loaders/class/ClassLoader.Tasks.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/class/ClassLoader.Tasks.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/class/ClassLoader.cs b/ZSharp.Platform.Runtime/loader/loaders/class/ClassLoader.cs similarity index 74% rename from ZSharp.Runtime/loader/loaders/class/ClassLoader.cs rename to ZSharp.Platform.Runtime/loader/loaders/class/ClassLoader.cs index 0bcb0094..499e65b7 100644 --- a/ZSharp.Runtime/loader/loaders/class/ClassLoader.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/class/ClassLoader.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal sealed partial class ClassLoader(EmitLoader loader) : TypeLoaderBase(loader) diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Constructor.cs b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Constructor.cs similarity index 94% rename from ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Constructor.cs rename to ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Constructor.cs index 5375ac26..0ad0297b 100644 --- a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Constructor.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Constructor.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Field.cs b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Field.cs similarity index 90% rename from ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Field.cs rename to ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Field.cs index 38c479f5..cc7c4b3a 100644 --- a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Field.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Field.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Generic.cs b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Generic.cs similarity index 91% rename from ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Generic.cs rename to ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Generic.cs index 7d74ada1..39cee374 100644 --- a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Generic.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Generic.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs similarity index 96% rename from ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs rename to ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs index 853f2b7f..dea1826a 100644 --- a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Method.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs similarity index 80% rename from ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs rename to ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs index 793a6ad9..eabaa431 100644 --- a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.cs similarity index 97% rename from ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs rename to ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.cs index f5e74c46..35297072 100644 --- a/ZSharp.Runtime/loader/loaders/class/load/ClassLoader.Load.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/code/code contexts/FunctionCodeContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/FunctionCodeContext.cs similarity index 98% rename from ZSharp.Runtime/loader/loaders/code/code contexts/FunctionCodeContext.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code contexts/FunctionCodeContext.cs index fc663167..f5a1a1e1 100644 --- a/ZSharp.Runtime/loader/loaders/code/code contexts/FunctionCodeContext.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/FunctionCodeContext.cs @@ -1,7 +1,7 @@ using CommonZ.Utils; using ZSharp.IR; -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal sealed class FunctionCodeContext : ICodeContext diff --git a/ZSharp.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs similarity index 93% rename from ZSharp.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs index 3904b96b..3693269f 100644 --- a/ZSharp.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs @@ -1,6 +1,6 @@ using CommonZ.Utils; -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal sealed class UnboundCodeContext(Runtime runtime, IL.Emit.ILGenerator il) : ICodeContext diff --git a/ZSharp.Runtime/loader/loaders/code/code/CodeCompiler.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/CodeCompiler.cs similarity index 99% rename from ZSharp.Runtime/loader/loaders/code/code/CodeCompiler.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/CodeCompiler.cs index 23c1063b..31046418 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/CodeCompiler.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/CodeCompiler.cs @@ -1,6 +1,6 @@ using CommonZ.Utils; -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { public sealed class CodeCompiler(ICodeContext context) { diff --git a/ZSharp.Runtime/loader/loaders/code/code/branching/BranchingCodeCompiler.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/branching/BranchingCodeCompiler.cs similarity index 94% rename from ZSharp.Runtime/loader/loaders/code/code/branching/BranchingCodeCompiler.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/branching/BranchingCodeCompiler.cs index 25839f7b..67326da2 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/branching/BranchingCodeCompiler.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/branching/BranchingCodeCompiler.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal static partial class CodeCompiler_Impl { diff --git a/ZSharp.Runtime/loader/loaders/code/code/branching/IBranchingCodeContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/branching/IBranchingCodeContext.cs similarity index 82% rename from ZSharp.Runtime/loader/loaders/code/code/branching/IBranchingCodeContext.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/branching/IBranchingCodeContext.cs index 0a0b701e..9fc357e2 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/branching/IBranchingCodeContext.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/branching/IBranchingCodeContext.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { public interface IBranchingCodeContext : ICodeContext diff --git a/ZSharp.Runtime/loader/loaders/code/code/core/CodeStack.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/core/CodeStack.cs similarity index 92% rename from ZSharp.Runtime/loader/loaders/code/code/core/CodeStack.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/core/CodeStack.cs index 492f6778..c774bc58 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/core/CodeStack.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/core/CodeStack.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { public sealed class CodeStack { diff --git a/ZSharp.Runtime/loader/loaders/code/code/core/ICodeContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/core/ICodeContext.cs similarity index 79% rename from ZSharp.Runtime/loader/loaders/code/code/core/ICodeContext.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/core/ICodeContext.cs index 9e1c6c49..048d13e7 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/core/ICodeContext.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/core/ICodeContext.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { public interface ICodeContext { diff --git a/ZSharp.Runtime/loader/loaders/code/code/frame/FrameCodeCompiler.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/frame/FrameCodeCompiler.cs similarity index 98% rename from ZSharp.Runtime/loader/loaders/code/code/frame/FrameCodeCompiler.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/frame/FrameCodeCompiler.cs index 11e24e18..0fd3aa89 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/frame/FrameCodeCompiler.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/frame/FrameCodeCompiler.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal static partial class CodeCompiler_Impl { diff --git a/ZSharp.Runtime/loader/loaders/code/code/frame/IFrameCodeContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/frame/IFrameCodeContext.cs similarity index 81% rename from ZSharp.Runtime/loader/loaders/code/code/frame/IFrameCodeContext.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/frame/IFrameCodeContext.cs index 93b10282..831eb0ab 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/frame/IFrameCodeContext.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/frame/IFrameCodeContext.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { public interface IFrameCodeContext : ICodeContext diff --git a/ZSharp.Runtime/loader/loaders/code/code/frame/Local.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/frame/Local.cs similarity index 81% rename from ZSharp.Runtime/loader/loaders/code/code/frame/Local.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/frame/Local.cs index 35c671c6..587e18ec 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/frame/Local.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/frame/Local.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { public sealed class Local { diff --git a/ZSharp.Runtime/loader/loaders/code/code/frame/Parameter.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/frame/Parameter.cs similarity index 81% rename from ZSharp.Runtime/loader/loaders/code/code/frame/Parameter.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/frame/Parameter.cs index 6dca5a9c..54dda7e5 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/frame/Parameter.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/frame/Parameter.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { public sealed class Parameter { diff --git a/ZSharp.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs similarity index 96% rename from ZSharp.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs index 35508bee..8c077c8d 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/functional/FunctionalCodeCompiler.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal static partial class CodeCompiler_Impl { diff --git a/ZSharp.Runtime/loader/loaders/code/code/functional/IFunctionalCodeContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/functional/IFunctionalCodeContext.cs similarity index 73% rename from ZSharp.Runtime/loader/loaders/code/code/functional/IFunctionalCodeContext.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/functional/IFunctionalCodeContext.cs index 2db81d09..aa6d8a66 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/functional/IFunctionalCodeContext.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/functional/IFunctionalCodeContext.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { public interface IFunctionalCodeContext : ICodeContext diff --git a/ZSharp.Runtime/loader/loaders/code/code/modular/ModularCodeCompiler.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/modular/ModularCodeCompiler.cs similarity index 92% rename from ZSharp.Runtime/loader/loaders/code/code/modular/ModularCodeCompiler.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/modular/ModularCodeCompiler.cs index 7a334d44..87529349 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/modular/ModularCodeCompiler.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/modular/ModularCodeCompiler.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal static partial class CodeCompiler_Impl { diff --git a/ZSharp.Runtime/loader/loaders/code/code/object/OOPCodeCompiler.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/object/OOPCodeCompiler.cs similarity index 97% rename from ZSharp.Runtime/loader/loaders/code/code/object/OOPCodeCompiler.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/object/OOPCodeCompiler.cs index feaa21b9..d760beb8 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/object/OOPCodeCompiler.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/object/OOPCodeCompiler.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal static partial class CodeCompiler_Impl { diff --git a/ZSharp.Runtime/loader/loaders/code/code/stack/StackCodeCompiler.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/stack/StackCodeCompiler.cs similarity index 97% rename from ZSharp.Runtime/loader/loaders/code/code/stack/StackCodeCompiler.cs rename to ZSharp.Platform.Runtime/loader/loaders/code/code/stack/StackCodeCompiler.cs index 76a9123e..f59eba5d 100644 --- a/ZSharp.Runtime/loader/loaders/code/code/stack/StackCodeCompiler.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/stack/StackCodeCompiler.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal static partial class CodeCompiler_Impl { diff --git a/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.cs b/ZSharp.Platform.Runtime/loader/loaders/enum/EnumClassLoader.cs similarity index 75% rename from ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.cs rename to ZSharp.Platform.Runtime/loader/loaders/enum/EnumClassLoader.cs index 1e772eae..e5806b40 100644 --- a/ZSharp.Runtime/loader/loaders/enum/EnumClassLoader.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/enum/EnumClassLoader.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal sealed partial class EnumClassLoader(EmitLoader loader) : TypeLoaderBase(loader) diff --git a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Method.cs b/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Method.cs similarity index 96% rename from ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Method.cs rename to ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Method.cs index 683c4c13..26eb80b6 100644 --- a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Method.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Method.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class EnumClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs similarity index 80% rename from ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs rename to ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs index 57568ffc..b538acc9 100644 --- a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class EnumClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Value.cs b/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Value.cs similarity index 90% rename from ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Value.cs rename to ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Value.cs index 87cef372..56c69b7f 100644 --- a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Value.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Value.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class EnumClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs b/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs similarity index 96% rename from ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs rename to ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs index d822fd49..b672abc8 100644 --- a/ZSharp.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class EnumClassLoader { diff --git a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Context.cs b/ZSharp.Platform.Runtime/loader/loaders/interface/InterfaceLoader.Context.cs similarity index 76% rename from ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Context.cs rename to ZSharp.Platform.Runtime/loader/loaders/interface/InterfaceLoader.Context.cs index 09e86c25..6f780de9 100644 --- a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Context.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/interface/InterfaceLoader.Context.cs @@ -1,6 +1,6 @@ using CommonZ.Utils; -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class InterfaceLoader { diff --git a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs b/ZSharp.Platform.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs similarity index 90% rename from ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs rename to ZSharp.Platform.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs index f0564274..6b653549 100644 --- a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/interface/InterfaceLoader.Tasks.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class InterfaceLoader { diff --git a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.cs b/ZSharp.Platform.Runtime/loader/loaders/interface/InterfaceLoader.cs similarity index 75% rename from ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.cs rename to ZSharp.Platform.Runtime/loader/loaders/interface/InterfaceLoader.cs index c534ce9f..29f36957 100644 --- a/ZSharp.Runtime/loader/loaders/interface/InterfaceLoader.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/interface/InterfaceLoader.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal sealed partial class InterfaceLoader(EmitLoader loader) : TypeLoaderBase(loader) diff --git a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Generic.cs b/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Generic.cs similarity index 91% rename from ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Generic.cs rename to ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Generic.cs index 8836dcea..547ea5aa 100644 --- a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Generic.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Generic.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class InterfaceLoader { diff --git a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Method.cs b/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Method.cs similarity index 96% rename from ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Method.cs rename to ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Method.cs index e797c2b2..fb009903 100644 --- a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Method.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Method.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class InterfaceLoader { diff --git a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs similarity index 80% rename from ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs rename to ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs index 3bd28d71..0ef79a09 100644 --- a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class InterfaceLoader { diff --git a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs b/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs similarity index 96% rename from ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs rename to ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs index 237bad37..2a1edebc 100644 --- a/ZSharp.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class InterfaceLoader { diff --git a/ZSharp.Runtime/loader/loaders/module/ModuleLoader.Tasks.cs b/ZSharp.Platform.Runtime/loader/loaders/module/ModuleLoader.Tasks.cs similarity index 84% rename from ZSharp.Runtime/loader/loaders/module/ModuleLoader.Tasks.cs rename to ZSharp.Platform.Runtime/loader/loaders/module/ModuleLoader.Tasks.cs index a1d4db07..36f6dd85 100644 --- a/ZSharp.Runtime/loader/loaders/module/ModuleLoader.Tasks.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/module/ModuleLoader.Tasks.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ModuleLoader { diff --git a/ZSharp.Runtime/loader/loaders/module/ModuleLoader.cs b/ZSharp.Platform.Runtime/loader/loaders/module/ModuleLoader.cs similarity index 94% rename from ZSharp.Runtime/loader/loaders/module/ModuleLoader.cs rename to ZSharp.Platform.Runtime/loader/loaders/module/ModuleLoader.cs index 3c036e3f..3f2c03b8 100644 --- a/ZSharp.Runtime/loader/loaders/module/ModuleLoader.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/module/ModuleLoader.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal sealed partial class ModuleLoader : LoaderBase diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Function.cs b/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Function.cs similarity index 96% rename from ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Function.cs rename to ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Function.cs index c421fc1e..85739f44 100644 --- a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Function.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Function.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ModuleLoader { diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Global.cs b/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Global.cs similarity index 89% rename from ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Global.cs rename to ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Global.cs index 9e6698b7..3478b4d5 100644 --- a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Global.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Global.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ModuleLoader { diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs similarity index 77% rename from ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs rename to ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs index 22ded722..7630ef71 100644 --- a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ModuleLoader { diff --git a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs b/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs similarity index 97% rename from ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs rename to ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs index 509605a6..a0cb03d7 100644 --- a/ZSharp.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ModuleLoader { diff --git a/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Context.cs b/ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.Context.cs similarity index 76% rename from ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Context.cs rename to ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.Context.cs index 93ea3a99..01cb52e8 100644 --- a/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Context.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.Context.cs @@ -1,6 +1,6 @@ using CommonZ.Utils; -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ValueTypeLoader { diff --git a/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.T.cs b/ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.T.cs similarity index 56% rename from ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.T.cs rename to ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.T.cs index 60bc6565..91f66e3e 100644 --- a/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.T.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.T.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ValueTypeLoader { diff --git a/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Tasks.cs b/ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.Tasks.cs similarity index 91% rename from ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Tasks.cs rename to ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.Tasks.cs index 6fc817a0..463e5874 100644 --- a/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.Tasks.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.Tasks.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ValueTypeLoader { diff --git a/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.cs b/ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.cs similarity index 87% rename from ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.cs rename to ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.cs index fba25907..bdbf8394 100644 --- a/ZSharp.Runtime/loader/loaders/value type/ValueTypeLoader.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/value type/ValueTypeLoader.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { internal sealed partial class ValueTypeLoader : LoaderBase diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Constructor.cs b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Constructor.cs similarity index 94% rename from ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Constructor.cs rename to ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Constructor.cs index f4b90dfd..059494ed 100644 --- a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Constructor.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Constructor.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ValueTypeLoader { diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Field.cs b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Field.cs similarity index 90% rename from ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Field.cs rename to ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Field.cs index 2b14173d..4a00059d 100644 --- a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Field.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Field.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ValueTypeLoader { diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Generic.cs b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Generic.cs similarity index 91% rename from ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Generic.cs rename to ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Generic.cs index 16b41443..4c46cd20 100644 --- a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Generic.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Generic.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ValueTypeLoader { diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Method.cs b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Method.cs similarity index 96% rename from ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Method.cs rename to ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Method.cs index 8f81554d..0b780e3b 100644 --- a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Method.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Method.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ValueTypeLoader { diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs similarity index 80% rename from ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs rename to ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs index 0e93cf14..ea914e6e 100644 --- a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ValueTypeLoader { diff --git a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.cs b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.cs similarity index 97% rename from ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.cs rename to ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.cs index 4adced9b..38a7031e 100644 --- a/ZSharp.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime.Loaders +namespace ZSharp.Platform.Runtime.Loaders { partial class ValueTypeLoader { diff --git a/ZSharp.Runtime/runtime/Runtime.Evaluate.cs b/ZSharp.Platform.Runtime/runtime/Runtime.Evaluate.cs similarity index 87% rename from ZSharp.Runtime/runtime/Runtime.Evaluate.cs rename to ZSharp.Platform.Runtime/runtime/Runtime.Evaluate.cs index 18ad09cf..b271ee58 100644 --- a/ZSharp.Runtime/runtime/Runtime.Evaluate.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.Evaluate.cs @@ -1,6 +1,6 @@ using CommonZ.Utils; -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/Runtime.Expose.cs b/ZSharp.Platform.Runtime/runtime/Runtime.Expose.cs similarity index 98% rename from ZSharp.Runtime/runtime/Runtime.Expose.cs rename to ZSharp.Platform.Runtime/runtime/Runtime.Expose.cs index e0ef3445..1b603357 100644 --- a/ZSharp.Runtime/runtime/Runtime.Expose.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.Expose.cs @@ -2,7 +2,7 @@ using System.Diagnostics.CodeAnalysis; using ZSharp.IR; -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { public sealed partial class Runtime { diff --git a/ZSharp.Runtime/runtime/Runtime.Loader.cs b/ZSharp.Platform.Runtime/runtime/Runtime.Loader.cs similarity index 71% rename from ZSharp.Runtime/runtime/Runtime.Loader.cs rename to ZSharp.Platform.Runtime/runtime/Runtime.Loader.cs index c6f478f0..c11fbd72 100644 --- a/ZSharp.Runtime/runtime/Runtime.Loader.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.Loader.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/Runtime.Singleton.cs b/ZSharp.Platform.Runtime/runtime/Runtime.Singleton.cs similarity index 71% rename from ZSharp.Runtime/runtime/Runtime.Singleton.cs rename to ZSharp.Platform.Runtime/runtime/Runtime.Singleton.cs index 8b51af54..15601c6a 100644 --- a/ZSharp.Runtime/runtime/Runtime.Singleton.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.Singleton.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/Runtime.TypeSystem.cs b/ZSharp.Platform.Runtime/runtime/Runtime.TypeSystem.cs similarity index 70% rename from ZSharp.Runtime/runtime/Runtime.TypeSystem.cs rename to ZSharp.Platform.Runtime/runtime/Runtime.TypeSystem.cs index 83a5f720..e5833ad6 100644 --- a/ZSharp.Runtime/runtime/Runtime.TypeSystem.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.TypeSystem.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/Runtime.cs b/ZSharp.Platform.Runtime/runtime/Runtime.cs similarity index 95% rename from ZSharp.Runtime/runtime/Runtime.cs rename to ZSharp.Platform.Runtime/runtime/Runtime.cs index 1d138b4b..dc0920ef 100644 --- a/ZSharp.Runtime/runtime/Runtime.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { public sealed partial class Runtime { diff --git a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Field.cs b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Field.cs similarity index 91% rename from ZSharp.Runtime/runtime/cache/Runtime.Cache.Field.cs rename to ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Field.cs index 33716de2..30342be1 100644 --- a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Field.cs +++ b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Field.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Function.cs b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Function.cs similarity index 92% rename from ZSharp.Runtime/runtime/cache/Runtime.Cache.Function.cs rename to ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Function.cs index 8cfd236b..888b7d0a 100644 --- a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Function.cs +++ b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Function.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Global.cs b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Global.cs similarity index 91% rename from ZSharp.Runtime/runtime/cache/Runtime.Cache.Global.cs rename to ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Global.cs index 1d799965..7e44db5a 100644 --- a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Global.cs +++ b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Global.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Module.cs b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Module.cs similarity index 91% rename from ZSharp.Runtime/runtime/cache/Runtime.Cache.Module.cs rename to ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Module.cs index 779e418f..c695a315 100644 --- a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Module.cs +++ b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Module.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Type.cs b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Type.cs similarity index 97% rename from ZSharp.Runtime/runtime/cache/Runtime.Cache.Type.cs rename to ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Type.cs index ed94585a..7d43d09c 100644 --- a/ZSharp.Runtime/runtime/cache/Runtime.Cache.Type.cs +++ b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Type.cs @@ -1,6 +1,6 @@ using CommonZ.Utils; -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Callable.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Callable.cs similarity index 95% rename from ZSharp.Runtime/runtime/import/Runtime.Import.Callable.cs rename to ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Callable.cs index dc4431c2..1b5b2e1b 100644 --- a/ZSharp.Runtime/runtime/import/Runtime.Import.Callable.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Callable.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Constructor.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Constructor.cs similarity index 97% rename from ZSharp.Runtime/runtime/import/Runtime.Import.Constructor.cs rename to ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Constructor.cs index a9237a06..ea5ac412 100644 --- a/ZSharp.Runtime/runtime/import/Runtime.Import.Constructor.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Constructor.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Field.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Field.cs similarity index 96% rename from ZSharp.Runtime/runtime/import/Runtime.Import.Field.cs rename to ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Field.cs index 461820a5..f15fb04f 100644 --- a/ZSharp.Runtime/runtime/import/Runtime.Import.Field.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Field.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Function.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Function.cs similarity index 94% rename from ZSharp.Runtime/runtime/import/Runtime.Import.Function.cs rename to ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Function.cs index 5e367753..dc321f17 100644 --- a/ZSharp.Runtime/runtime/import/Runtime.Import.Function.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Function.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Global.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Global.cs similarity index 91% rename from ZSharp.Runtime/runtime/import/Runtime.Import.Global.cs rename to ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Global.cs index 83238ad1..07920877 100644 --- a/ZSharp.Runtime/runtime/import/Runtime.Import.Global.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Global.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Method.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Method.cs similarity index 97% rename from ZSharp.Runtime/runtime/import/Runtime.Import.Method.cs rename to ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Method.cs index db257e59..bd7677fb 100644 --- a/ZSharp.Runtime/runtime/import/Runtime.Import.Method.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Method.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Module.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Module.cs similarity index 88% rename from ZSharp.Runtime/runtime/import/Runtime.Import.Module.cs rename to ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Module.cs index 0a3d3c55..8b7e4db1 100644 --- a/ZSharp.Runtime/runtime/import/Runtime.Import.Module.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Module.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Type.Modified.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.Modified.cs similarity index 95% rename from ZSharp.Runtime/runtime/import/Runtime.Import.Type.Modified.cs rename to ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.Modified.cs index e068849e..266f01c2 100644 --- a/ZSharp.Runtime/runtime/import/Runtime.Import.Type.Modified.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.Modified.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/import/Runtime.Import.Type.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.cs similarity index 97% rename from ZSharp.Runtime/runtime/import/Runtime.Import.Type.cs rename to ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.cs index 484b5de8..fc704ef6 100644 --- a/ZSharp.Runtime/runtime/import/Runtime.Import.Type.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.cs @@ -1,6 +1,6 @@ using System.Reflection.Metadata; -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/load/Runtime.Load.Function.cs b/ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Function.cs similarity index 91% rename from ZSharp.Runtime/runtime/load/Runtime.Load.Function.cs rename to ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Function.cs index e564021a..7bc0bdc9 100644 --- a/ZSharp.Runtime/runtime/load/Runtime.Load.Function.cs +++ b/ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Function.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/load/Runtime.Load.Module.cs b/ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Module.cs similarity index 78% rename from ZSharp.Runtime/runtime/load/Runtime.Load.Module.cs rename to ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Module.cs index 0372ebe5..73a70906 100644 --- a/ZSharp.Runtime/runtime/load/Runtime.Load.Module.cs +++ b/ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Module.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/runtime/load/Runtime.Load.Type.cs b/ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Type.cs similarity index 90% rename from ZSharp.Runtime/runtime/load/Runtime.Load.Type.cs rename to ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Type.cs index 087d2178..8549fbba 100644 --- a/ZSharp.Runtime/runtime/load/Runtime.Load.Type.cs +++ b/ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Type.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class Runtime { diff --git a/ZSharp.Runtime/tasks/TaskManager.cs b/ZSharp.Platform.Runtime/tasks/TaskManager.cs similarity index 93% rename from ZSharp.Runtime/tasks/TaskManager.cs rename to ZSharp.Platform.Runtime/tasks/TaskManager.cs index aaf27db1..738e0744 100644 --- a/ZSharp.Runtime/tasks/TaskManager.cs +++ b/ZSharp.Platform.Runtime/tasks/TaskManager.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { internal sealed class TaskManager(Action init) { diff --git a/ZSharp.Runtime/type system/TypeSystem.Array.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Array.cs similarity index 73% rename from ZSharp.Runtime/type system/TypeSystem.Array.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.Array.cs index 324f1419..7fd3e0e5 100644 --- a/ZSharp.Runtime/type system/TypeSystem.Array.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Array.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class TypeSystem { diff --git a/ZSharp.Runtime/type system/TypeSystem.Boolean.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Boolean.cs similarity index 75% rename from ZSharp.Runtime/type system/TypeSystem.Boolean.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.Boolean.cs index 8394d743..44e809c1 100644 --- a/ZSharp.Runtime/type system/TypeSystem.Boolean.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Boolean.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class TypeSystem { diff --git a/ZSharp.Runtime/type system/TypeSystem.Char.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Char.cs similarity index 74% rename from ZSharp.Runtime/type system/TypeSystem.Char.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.Char.cs index be77b078..0df7d0f4 100644 --- a/ZSharp.Runtime/type system/TypeSystem.Char.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Char.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class TypeSystem { diff --git a/ZSharp.Runtime/type system/TypeSystem.Float.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Float.cs similarity index 89% rename from ZSharp.Runtime/type system/TypeSystem.Float.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.Float.cs index 41215681..6838cbec 100644 --- a/ZSharp.Runtime/type system/TypeSystem.Float.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Float.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class TypeSystem { diff --git a/ZSharp.Runtime/type system/TypeSystem.Object.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Object.cs similarity index 75% rename from ZSharp.Runtime/type system/TypeSystem.Object.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.Object.cs index f11ea248..4eb6a5e0 100644 --- a/ZSharp.Runtime/type system/TypeSystem.Object.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Object.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class TypeSystem { diff --git a/ZSharp.Runtime/type system/TypeSystem.Pointer.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Pointer.cs similarity index 73% rename from ZSharp.Runtime/type system/TypeSystem.Pointer.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.Pointer.cs index 5f2ac3db..120e5ea2 100644 --- a/ZSharp.Runtime/type system/TypeSystem.Pointer.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Pointer.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class TypeSystem { diff --git a/ZSharp.Runtime/type system/TypeSystem.Reference.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Reference.cs similarity index 73% rename from ZSharp.Runtime/type system/TypeSystem.Reference.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.Reference.cs index cf226361..63a2fa79 100644 --- a/ZSharp.Runtime/type system/TypeSystem.Reference.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Reference.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class TypeSystem { diff --git a/ZSharp.Runtime/type system/TypeSystem.SInt.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.SInt.cs similarity index 91% rename from ZSharp.Runtime/type system/TypeSystem.SInt.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.SInt.cs index d5f0b25a..cb7b6166 100644 --- a/ZSharp.Runtime/type system/TypeSystem.SInt.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.SInt.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class TypeSystem { diff --git a/ZSharp.Runtime/type system/TypeSystem.String.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.String.cs similarity index 75% rename from ZSharp.Runtime/type system/TypeSystem.String.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.String.cs index 7fb03b2d..f70538bf 100644 --- a/ZSharp.Runtime/type system/TypeSystem.String.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.String.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class TypeSystem { diff --git a/ZSharp.Runtime/type system/TypeSystem.UInt.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.UInt.cs similarity index 91% rename from ZSharp.Runtime/type system/TypeSystem.UInt.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.UInt.cs index 4ce57841..4bcba4f5 100644 --- a/ZSharp.Runtime/type system/TypeSystem.UInt.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.UInt.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class TypeSystem { diff --git a/ZSharp.Runtime/type system/TypeSystem.Void.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Void.cs similarity index 74% rename from ZSharp.Runtime/type system/TypeSystem.Void.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.Void.cs index 35ccbccf..0b8b3eb6 100644 --- a/ZSharp.Runtime/type system/TypeSystem.Void.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Void.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { partial class TypeSystem { diff --git a/ZSharp.Runtime/type system/TypeSystem.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.cs similarity index 64% rename from ZSharp.Runtime/type system/TypeSystem.cs rename to ZSharp.Platform.Runtime/type system/TypeSystem.cs index 83205d59..822d67c5 100644 --- a/ZSharp.Runtime/type system/TypeSystem.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Runtime +namespace ZSharp.Platform.Runtime { public sealed partial class TypeSystem { diff --git a/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj b/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj index 83130b4f..968109c9 100644 --- a/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj +++ b/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj @@ -14,8 +14,8 @@ - - + + diff --git a/ZSharp.SourceCompiler.Project/GlobalUsings.cs b/ZSharp.SourceCompiler.Project/GlobalUsings.cs index 77f26af5..3cde0950 100644 --- a/ZSharp.SourceCompiler.Project/GlobalUsings.cs +++ b/ZSharp.SourceCompiler.Project/GlobalUsings.cs @@ -1,3 +1,3 @@ global using System.Collections.Generic; -global using ZSharp.Compiler.ILLoader; +global using ZSharp.Importer.ILLoader; diff --git a/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj b/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj index 8840c4e0..0410f51d 100644 --- a/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj +++ b/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj @@ -11,9 +11,9 @@ - - + + diff --git a/ZSharpParserTest/Program.cs b/ZSharpParserTest/Program.cs deleted file mode 100644 index dbf3743a..00000000 --- a/ZSharpParserTest/Program.cs +++ /dev/null @@ -1,40 +0,0 @@ -using ZSharp.AST; -using ZSharp.Parser; -using ZSharp.Text; -using ZSharp.Tokenizer; - - -using (StreamReader stream = File.OpenText("./parserText.txt")) -{ - var zsharpParser = new ZSharpParser(); - var parser = new Parser(Tokenizer.Tokenize(new(stream))); - - var expressionParser = zsharpParser.Expression; - - expressionParser.Terminal(TokenType.String, token => new LiteralExpression(token.Value, LiteralType.String)); - //expressionParser.Terminal(TokenType.Identifier, token => new IdentifierExpression(token.Value)); - - expressionParser.InfixL("+", 50); - expressionParser.InfixL("*", 70); - expressionParser.InfixL("**", 80); - - expressionParser.Led(TokenType.LParen, LangParser.ParseCallExpression, 100); - - expressionParser.Separator(TokenType.Comma); - expressionParser.Separator(TokenType.RParen); - expressionParser.Separator(TokenType.Semicolon); - - zsharpParser.RegisterParsers(parser); - var documentNode = zsharpParser.Parse(parser); - - Console.WriteLine($"Finished parsing document with {documentNode.Statements.Count} statements!"); - - Console.WriteLine(); - - foreach (var statement in documentNode.Statements) - { - Console.WriteLine(); - Console.WriteLine(statement.GetType().Name); - Console.WriteLine(statement); - } -} diff --git a/ZSharpParserTest/ZSharpParserTest.csproj b/ZSharpParserTest/ZSharpParserTest.csproj deleted file mode 100644 index 07e72643..00000000 --- a/ZSharpParserTest/ZSharpParserTest.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - Exe - net8.0 - enable - enable - - - - - - - - - - PreserveNewest - - - - diff --git a/ZSharpParserTest/parserText.txt b/ZSharpParserTest/parserText.txt deleted file mode 100644 index d662554d..00000000 --- a/ZSharpParserTest/parserText.txt +++ /dev/null @@ -1,89 +0,0 @@ -module Foo; - -import { a as A, b as B } from "std:test"; - -import("A", b: "B") "std:test"; - -import "std:test" as test; - -import {} from "std:test"; - -import {a as A} from "std:test"; - -import {a, b} from "std:test"; - -let myVar = "foo" + "bar" ** "goo" * "baz"; - -let yourVar = "it's actually mine"; - -let otherVar = "other"; - -"expressionStatement!"; - -"CALLABLE"(); - -"CALLABLE"("ARG1"); -"CALLABLE"("ARG1", "ARG2"); - - -"CALLABLE"("ARG1", "ARG2", arg3: "ARG3"); -"CALLABLE"("ARG1", "ARG2", arg3: "ARG3", arg4: "ARG4"); - -"CALLABLE"(arg1: "ARG1", "ARG2"); - - -fun() {} - -fun foo() {} - -fun foo(x) {} - -fun foo(x, y) {} - -fun foo(x, y, z) {} - -fun foo(x, y, ...z) {} - -fun foo(x, y, ...z,) {} - -fun foo(x, y,) {} - -fun foo({}) {} - -fun foo({x}) {} - -fun foo({x, y}) {} - -fun foo({x, y, z}) {} - -fun foo({x, y, ...z}) {} - -fun foo(x, y, {}) {} - -fun foo(x, y, {z}) {} - -fun foo(x, y, {z, w}) {} - -fun foo(x, y, {z, w, v}) {} - -fun foo(x, y, {z, w, ...v}) {} - -fun foo(x, y, ...z, {w, v, ...u}) {} - -class {} - -class Foo {} - -class; - -class Foo; - -class Foo : "Base"; - -class Foo : "Base"; - -class Foo : "Base", "Mixin"; - -class Foo : "Base", "Mixin" { - let x = "x"; -} diff --git a/ZSharpTest/DotNETImporter.cs b/ZSharpTest/DotNETImporter.cs deleted file mode 100644 index c61bf90f..00000000 --- a/ZSharpTest/DotNETImporter.cs +++ /dev/null @@ -1,51 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp -{ - public sealed class DotNETImporter(Interpreter.Interpreter interpreter) - : Objects.CompilerObject - , ICTCallable_Old - { - private readonly Interpreter.Interpreter interpreter = interpreter; - - public Mapping Libraries { get; } = []; - - public Objects.CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (arguments.Length == 0) - throw new(); // TODO: proper exception - - if ( - arguments.Length > 1 || - arguments[0].Name is not null || - interpreter.Evaluate(arguments[0].Object).Unwrap() is not string libraryName - ) - { - compiler.Log.Error("`net` importer must have exactly 1 argument of type `string`", this); - throw new(); // TODO: proper exception - } - - if (!Libraries.TryGetValue(libraryName, out var library)) - library = Libraries[libraryName] = ImportDotNETLibrary(libraryName); - - return library; - } - - private Objects.CompilerObject ImportDotNETLibrary(string libraryName) - { - var assembly = System.Reflection.Assembly.LoadFile(Path.GetFullPath(libraryName)); - - var modules = assembly.GetModules(); - if (modules.Length != 1) - { - interpreter.Compiler.Log.Error($"Assembly {libraryName} has more than 1 module", this); - throw new(); // TODO: proper exception - } - - var module = modules[0]; - - return interpreter.ImportILModule(module); - } - } -} diff --git a/ZSharpTest/Main.cs b/ZSharpTest/Main.cs deleted file mode 100644 index e643f08e..00000000 --- a/ZSharpTest/Main.cs +++ /dev/null @@ -1,247 +0,0 @@ -using System.Text; -using ZSharp.Compiler; -using ZSharp.Interpreter; -using ZSharp.Parser; -using ZSharp.Text; -using ZSharp.Tokenizer; - -string fileName = args.Length == 0 ? "test.zs" : args[0]; -string filePath = Path.GetFullPath(fileName); - -#region Parsing - -ZSharp.AST.Document documentNode; -using (StreamReader stream = File.OpenText(filePath)) -{ - var zsharpParser = new ZSharpParser(); - var parser = new Parser(Tokenizer.Tokenize(new(stream))); - - var expressionParser = zsharpParser.Expression; - var statementParser = zsharpParser.Statement; - - expressionParser.Terminal( - TokenType.String, - token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.String) - ); - expressionParser.Terminal( - TokenType.Number, - token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Number) - ); - expressionParser.Terminal( - TokenType.Decimal, - token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Decimal) - ); - expressionParser.Terminal( - TokenType.Identifier, - token => token.Value switch - { - "null" => ZSharp.AST.LiteralExpression.Null(), - "true" => ZSharp.AST.LiteralExpression.True(), - "false" => ZSharp.AST.LiteralExpression.False(), - _ => new ZSharp.AST.IdentifierExpression(token.Value), - } - ); - expressionParser.Nud( - TokenType.LParen, - parser => - { - parser.Eat(TokenType.LParen); - var expression = parser.Parse(); - parser.Eat(TokenType.RParen); - - return expression; - }, - 10000 - ); - expressionParser.Nud( - LangParser.Keywords.Let, - LangParser.ParseLetExpression - ); - expressionParser.Nud( - LangParser.Keywords.Class, - zsharpParser.Class.Parse - ); - - expressionParser.InfixR("=", 10); - expressionParser.InfixL("<", 20); - expressionParser.InfixL("+", 50); - expressionParser.InfixL("-", 50); - expressionParser.InfixL("*", 70); - expressionParser.InfixL("/", 70); - expressionParser.InfixL("**", 80); - - expressionParser.InfixL("==", 30); - expressionParser.InfixL("!=", 30); - - expressionParser.InfixL(LangParser.Keywords.Or, 15); - - expressionParser.Led(TokenType.LParen, LangParser.ParseCallExpression, 100); - expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); - expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); - expressionParser.Led(".", LangParser.ParseMemberAccess, 150); - expressionParser.Led(LangParser.Keywords.As, LangParser.ParseCastExpression, 20); - expressionParser.Led(LangParser.Keywords.Is, LangParser.ParseIsOfExpression, 20); - - expressionParser.Separator(TokenType.Comma); - expressionParser.Separator(TokenType.RParen); - expressionParser.Separator(TokenType.RBracket); - expressionParser.Separator(TokenType.Semicolon); - - expressionParser.Separator(LangParser.Keywords.In); // until it's an operator - - expressionParser.AddKeywordParser( - LangParser.Keywords.While, - LangParser.ParseWhileExpression - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.While, - Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.If, - LangParser.ParseIfStatement - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.For, - LangParser.ParseForStatement - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.Case, - LangParser.ParseCaseStatement - ); - - //zsharpParser.Function.AddKeywordParser( - // LangParser.Keywords.While, - // Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) - //); - - zsharpParser.RegisterParsers(parser); - documentNode = zsharpParser.Parse(parser); - - Console.WriteLine($"Finished parsing document with {documentNode.Statements.Count} statements!"); -} - -#endregion - - -#region Compilation - -var interpreter = new Interpreter(); - -interpreter.SourceCompiler.StringImporter.Importers.Add( - "net", - new ZSharp.DotNETImporter(interpreter) -); - - -new Referencing(interpreter.Compiler); -new OOP(interpreter.Compiler); - -var moduleIL_standardIO = typeof(Standard.IO.Impl_Globals).Module; -var moduleCO_standardIO = interpreter.ImportILModule(moduleIL_standardIO); - -interpreter.Compiler.TypeSystem.String.ToString = interpreter.ILLoader.LoadMethod(ZSharp.Runtime.NET.Utils.GetMethod(Standard.IO.Impl_Globals.ToString)); - -interpreter.Compiler.TypeSystem.Int32.Members["parse"] = interpreter.ILLoader.LoadMethod(ZSharp.Runtime.NET.Utils.GetMethod(Standard.IO.Impl_Globals.ParseInt32)); - -interpreter.SourceCompiler.StandardLibraryImporter.Libraries.Add("io", moduleCO_standardIO); - -var moduleIL_standardMath = typeof(Standard.Math.Impl_Globals).Module; -var moduleCO_standardMath = interpreter.ImportILModule(moduleIL_standardMath); - -interpreter.SourceCompiler.StandardLibraryImporter.Libraries.Add("math", moduleCO_standardMath); - - -//var moduleIL_compilerAPI = typeof(ZS.CompilerAPI.Impl_Globals).Module; -//var moduleIR_compilerAPI = interpreter.HostLoader.Import(moduleIL_compilerAPI); -//var moduleCO_compilerAPI = interpreter.CompilerIRLoader.Import(moduleIR_compilerAPI); - -//interpreter.SourceCompiler.ZSImporter.Libraries.Add("compiler", moduleCO_compilerAPI); - -var document = interpreter.CompileDocument(documentNode, filePath); - -Console.WriteLine($"Compilation finished with {interpreter.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error)} errors!"); - -foreach (var log in interpreter.Compiler.Log.Logs) - Console.WriteLine(log); - -ZSharp.Objects.Module? mainModule = document.Content.FirstOrDefault( - item => item is ZSharp.Objects.Module module && module.Name == "Program" -) as ZSharp.Objects.Module; - -if (mainModule is not null) -{ - var mainModuleIR = - interpreter.Compiler.CompileIRObject(mainModule, null) ?? throw new(); - - var mainModuleIL = interpreter.Runtime.ImportModule(mainModuleIR); - var mainModuleGlobals = mainModuleIL.GetType("") ?? throw new(); - - foreach (var type in mainModuleIL.GetTypes()) - DecompileType(type); - - foreach (var method in mainModuleIL.GetMethods()) - Decompile(method); - - var mainMethod = mainModuleGlobals.GetMethod("main", []); - - mainMethod?.Invoke(null, null); -} - -#endregion - -Console.WriteLine(); - -Console.WriteLine(); -Console.WriteLine("Press any key to exit..."); -Console.ReadKey(); - - -static void DecompileType(Type type) -{ - Console.WriteLine("========== Type: " + type.Name + " =========="); - - foreach (var method in type.GetMethods()) - { - if (method.DeclaringType != type) - continue; - - Decompile(method); - } - - Console.WriteLine("========== Type =========="); -} - - -static void Decompile(System.Reflection.MethodBase method) -{ - StringBuilder signatureBuilder = new(); - foreach (var parameter in method.GetParameters()) - { - if (signatureBuilder.Length > 0) - signatureBuilder.Append(", "); - signatureBuilder.Append(parameter.ParameterType.Name); - } - - string modifier = string.Empty; - if (method.IsStatic) - modifier = "static "; - else if (method.IsVirtual) - modifier = "virtual "; - else if (method.IsAbstract) - modifier = "abstract "; - else modifier = "instance "; - - Console.WriteLine($"========== Disassmebly: {modifier}{method.Name}({signatureBuilder}) =========="); - - foreach (var instruction in Mono.Reflection.Disassembler.GetInstructions(method)) - { - Console.WriteLine(instruction); - } - - Console.WriteLine("========== Disassmebly =========="); -} diff --git a/ZSharpTest/Program.cs b/ZSharpTest/Program.cs deleted file mode 100644 index 0f2bc0b5..00000000 --- a/ZSharpTest/Program.cs +++ /dev/null @@ -1,417 +0,0 @@ -//using CommonZ.Utils; -//using ZSharp.CTRuntime; -//using ZSharp.IR.Standard; -//using ZSharp.RAST; -//using ZSharp.VM; - -//using IR = ZSharp.IR; - - -///* -// * Interpreter -// */ - -//var runtime = IR.RuntimeModule.Standard; - -//Interpreter interpreter = new(runtime); - -//{ -// interpreter.SetIR(runtime.TypeSystem.Any, TypeSystem.Any); -// interpreter.SetIR(runtime.TypeSystem.String, TypeSystem.String); -// interpreter.SetIR(runtime.TypeSystem.Void, TypeSystem.Void); -//} - -///* -// * Toolchain -// */ - -//Desugarer desugarer = new(); -////Instantiator instantiator = new(); -//ZSCompiler compiler = new(interpreter); - - -//#region Internal Functions - -//var importSystem = new StringImporter(); -//ModuleImporter moduleImporter; - -//importSystem.AddImporter("std", moduleImporter = new()); - - -//Mapping internalFunctions = []; - -//if (true) { -// IR.InternalFunction @internal; -// ZSInternalFunction impl = new( -// args => -// { -// if (args.Length != 1) -// throw new("import: expected 1 argument"); - -// var sourceObject = args[0]; - -// if (sourceObject is not ZSString sourceString) -// throw new("import: expected string"); - -// var source = sourceString.Value; - -// return importSystem.Import(source); -// } -// ); - -// @internal = new(runtime.TypeSystem.Void) -// { -// Name = "import", -// }; -// @internal.Signature.Args.Parameters.Add(new("source", runtime.TypeSystem.Void)); - -// interpreter.SetIR(@internal, impl); -// internalFunctions.Add("import", @internal); -//} - -//if (true) -//{ -// IR.InternalFunction @internal; -// ZSInternalFunction impl = new( -// args => -// { -// if (args.Length != 2) -// throw new("getattr: expected 2 arguments"); - -// var @object = args[0]; -// var name = args[1]; - -// if (name is not ZSString nameString) -// throw new("getattr: name must be a string"); - -// if (@object is not ZSModule module) -// throw new("getattr: object must be a valid module"); - -// var binding = compiler.Context.Bindings.Cache(module.Module); - -// if (binding is not ICTGetMember getMember) -// throw new("getattr: object does not support get member"); - -// return new ZSHandle(getMember.Member(compiler, nameString.Value)); - -// //IR.IRObject result; - -// //result = -// // (module.Module.Globals.FirstOrDefault(g => g.Name == nameString.Value) -// // as IR.IRObject -// // ) -// // ?? -// // (module.Module.Functions.FirstOrDefault(f => f.Name == nameString.Value) -// // as IR.IRObject -// // ) ?? -// // throw new($"Could not find attribute {nameString.Value} in {module}"); - -// //Code code = new(1, [ -// // new IR.VM.GetObject(result) -// // ], TypeSystem.Any); - -// //return new ZSHandle(code); -// } -// ); - -// @internal = new(runtime.TypeSystem.Any) -// { -// Name = "getAttribute", -// }; -// @internal.Signature.Args.Parameters.Add(new("object", runtime.TypeSystem.Any)); -// @internal.Signature.Args.Parameters.Add(new("name", runtime.TypeSystem.String)); -// interpreter.SetIR(@internal, impl); -// internalFunctions.Add("getAttribute", @internal); -//} - -//if (true) -//{ -// IR.InternalFunction @internal; - -// @internal = new(runtime.TypeSystem.Void) -// { -// Name = "print", -// }; -// @internal.Signature.Args.Parameters.Add(new("message", runtime.TypeSystem.String)); - -// ZSInternalFunction impl = new( -// args => -// { -// if (args.Length != 1) -// throw new("print: expected 1 argument"); - -// var messageObject = args[0]; - -// if (messageObject is not ZSString messageString) -// throw new("print: expected string"); - -// var message = messageString.Value; - -// Console.WriteLine(message); - -// return null; -// }, -// new RTFunctionType(LoadSignature(@internal.Signature)) -// ); - -// interpreter.SetIR(@internal, impl); -// internalFunctions.Add("print", @internal); -//} - - -//#endregion - - -//#region Standard Library - - -//var ioModule = new IR.Module("io"); - -//if (true) { -// IR.Function printFunction; - -// printFunction = new(runtime.TypeSystem.Void) -// { -// Name = "print", -// }; - -// var sig = printFunction.Signature; -// sig.Args.Parameters.Add(new("message", runtime.TypeSystem.String)); - -// printFunction.Body.Instructions.AddRange([ -// new IR.VM.GetArgument(sig.Args.Parameters[0]), -// new IR.VM.CallInternal(internalFunctions["print"]), -// new IR.VM.Return(), -// ]); - -// printFunction.Body.StackSize = 2; - -// ioModule.Functions.Add(printFunction); -//} - -//interpreter.SetIR(ioModule, moduleImporter.AddModule(ioModule)); -//compiler.Load(ioModule); - - -//#endregion - - -//#region Global Scope - - -//if (true) { -// IR.Function importFunction; -// IR.Parameter source; - -// importFunction = new(runtime.TypeSystem.Any) -// { -// Name = "import", -// }; - -// var sig = importFunction.Signature; -// sig.Args.Parameters.Add(source = new("source", runtime.TypeSystem.String)); - -// importFunction.Body.Instructions.AddRange([ -// new IR.VM.GetArgument(source), -// new IR.VM.CallInternal(internalFunctions["import"]), -// new IR.VM.Return(), -// ]); - -// importFunction.Body.StackSize = 2; -// compiler.DefineGlobal( -// desugarer.Context.ImportFunction, -// new RTFunction(importFunction, LoadSignature(sig)) -// ); -//} - -//if (true) -//{ -// IR.Function getattrFunction; -// IR.Parameter @object, name; - -// getattrFunction = new(runtime.TypeSystem.Any) -// { -// Name = "_._" -// }; - -// var sig = getattrFunction.Signature; -// sig.Args.Parameters.Add(@object = new("object", runtime.TypeSystem.Any)); -// sig.Args.Parameters.Add(name = new("name", runtime.TypeSystem.String)); - -// getattrFunction.Body.Instructions.AddRange([ -// new IR.VM.GetArgument(@object), -// new IR.VM.GetArgument(name), -// new IR.VM.CallInternal(internalFunctions["getAttribute"]), -// new IR.VM.Return() -// ]); - -// getattrFunction.Body.StackSize = 3; -// compiler.DefineGlobal( -// desugarer.Context.GetBinaryOperator("."), -// new CGFunction(getattrFunction, LoadSignature(sig)) -// ); -//} - - -//RId globalVoid = new("void"); -//compiler.DefineGlobal(globalVoid, new Class(runtime.TypeSystem.Void)); -//RId globalString = new("string"); -//compiler.DefineGlobal(globalString, new Class(runtime.TypeSystem.String)); - - -//#endregion - - -//#region RAST - -///* -// * The code below represents the RAST of the following Z# code: -// * -// * let stdIO = "std:io"; -// * import { print } from stdIO; -// * -// * fun id(x: string): string { -// * return x; -// * } -// * -// * let message = id("Hello, World!"); -// * print(message); -// * -// * fun foo(x: string): void { -// * print(x); -// * } -// * -// * foo("Hello, foo!"); -// */ - - -//RId stdIO; -//RId print; -//RId id; -//RId id_x; -//RId message; -//RId foo_x; -//RId foo; -//var rastNodes = new RStatement[] -//{ -// // let stdIO = "std:io"; -// new RLetStatement( -// new RNamePattern(stdIO = new("stdIO")), -// null, -// RLiteral.String("std:io") -// ), - -// // import { print } from stdIO; -// new RImport(stdIO) -// { -// Targets = [ -// new("print") -// ] -// }, - -// new RExpressionStatement( -// new RFunction( -// id = new("id"), -// new() -// { -// Args = [ -// new(id_x = new("x"), globalString, null) -// ] -// }) -// { -// ReturnType = globalString, -// Body = new RReturn(id_x) -// } -// ), - -// // let message = "Hello, World!"; -// new RLetStatement( -// new RNamePattern(message = new("message")), -// null, //globals["string"], -// new RCall( -// id, -// [ -// new(RLiteral.String("Hello, World!")) -// ] -// ) -// ), - -// // print(message); -// new RExpressionStatement( -// new RCall(print, -// [ -// new(message) -// ]) -// ), - -// // fun foo(x: string): void { print(x); } -// new RExpressionStatement( -// new RFunction( -// foo = new("foo"), -// new() { -// Args = -// [ -// new(foo_x = new("x"), globalString, null) -// ] -// }) -// { -// ReturnType = globalVoid, -// Body = new RReturn( -// new RCall(print, -// [ -// new(foo_x) -// ]) -// ) -// } -// ), - -// // foo("Hello, foo!"); -// new RExpressionStatement( -// new RCall(foo, -// [ -// new(RLiteral.String("Hello, foo!")) -// ]) -// ) -//}; - -//RModule moduleNode = new(string.Empty) { Content = new(new(rastNodes)) }; - -//#endregion - - -//#region Main - -//// Simplify the RAST -//moduleNode = desugarer.Desugar(moduleNode); - -//// Declare module contents -////var scopes = instantiator.Instantiate(moduleNode); - -//// Document module -//IR.Module module; - -//// Definitions -//using (compiler.UseContext()) // if you want to pre-initialize, pass compiler.Context to the instantiator and use NewScope -// module = compiler.Compile(moduleNode); - - -//var moduleObject = interpreter.LoadIR(module) as ZSModule; - -//Console.WriteLine("Program finished!"); - -//#endregion - - -//#region Utilities - -//Signature LoadSignature(IR.Signature signature) -//{ -// var result = new Signature(signature); - -// foreach (var parameter in signature.Args.Parameters) -// result.Args.Add(new(parameter, interpreter.LoadType(parameter.Type))); - -// return result; -//} - -//#endregion diff --git a/ZSharpTest/Properties/launchSettings.json b/ZSharpTest/Properties/launchSettings.json deleted file mode 100644 index dcafed79..00000000 --- a/ZSharpTest/Properties/launchSettings.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "profiles": { - "tests/": { - "commandName": "Project", - "commandLineArgs": "tests/test-" - }, - "Projects/ToDo": { - "commandName": "Project", - "commandLineArgs": "projects/todo.zs" - }, - "Projects/Guessing Game": { - "commandName": "Project", - "commandLineArgs": "projects/guessing-game.zs" - }, - "Projects/Simple User System": { - "commandName": "Project", - "commandLineArgs": "projects/simple-user-system.zs" - }, - "Tests/Test Class Fields": { - "commandName": "Project", - "commandLineArgs": "tests/test-class-fields.zs" - }, - "Projects/Better User System": { - "commandName": "Project", - "commandLineArgs": "projects/better-user-system.zs" - }, - "Simple Test": { - "commandName": "Project", - "commandLineArgs": "tests/simple.zs" - }, - "Profile 1": { - "commandName": "Project", - "commandLineArgs": "test.zs" - } - } -} \ No newline at end of file diff --git a/ZSharpTest/ZSharpTest.csproj b/ZSharpTest/ZSharpTest.csproj deleted file mode 100644 index 980ea137..00000000 --- a/ZSharpTest/ZSharpTest.csproj +++ /dev/null @@ -1,58 +0,0 @@ - - - - Exe - net8.0 - enable - enable - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - diff --git a/ZSharpTest/projects/better-user-system.zs b/ZSharpTest/projects/better-user-system.zs deleted file mode 100644 index b06299d0..00000000 --- a/ZSharpTest/projects/better-user-system.zs +++ /dev/null @@ -1,95 +0,0 @@ -/* Required Features: - * [-] Primary constructor - * [-] Auto-fields from primary constructor parameters - * [x] Fields - * [x] Anonymous constructor - * [x] Named constructor - * [x] Methods - * [x] Case-Of - * [x] Automatic type inference for first parameter in methods - * [x] Automatic instance binding when accessing instance method/field from instance method - * [x] Instance method as function with `this` first parameter - * [x] Module globals initializers - */ - - -import { input, print } from "std:io"; -import { List } from "net:ZLoad.Test.dll"; - -module Program; - - -class User { - var isAdmin: bool; - - var username: string; - var password: string; - - new(this, username: string, password: string) { - isAdmin = false; - - this.username = username; - this.password = password; - } - - new Admin(this, username: string, password: string) { - User(this: this, username, password); - - isAdmin = true; - } - - fun login(this, username: string, password: string): bool { - if (username != this.username) return false; - if (password != this.password) return false; - - return true; - } -} - - -fun mainMenu(): bool { - print("|== Main Menu ==|"); - print("1. Sign In"); - print("2. Exit Program"); - - let userInput = input("> "); - - case (userInput) { - when ("1") signIn(); - when ("2") return false; - } else print("Invalid input."); - - return true; -} - - -fun signIn(): void { - let username = input("Username: "); - let password = input("Password: "); - - - for (let user in users) { - if (user.login(username, password)) { - print("Successfully logged in to user: " + user.username); - break; - } - } else { - print("Could not log in with provided credentials"); - } - - return; -} - - -fun main(): void { - while (mainMenu()) ; - else print("Thank you for using Better User System!"); - - return; -} - - -let users: List[User] = [ - User("user", "123"), - User.Admin("admin", "321") -]; diff --git a/ZSharpTest/projects/build.zs b/ZSharpTest/projects/build.zs deleted file mode 100644 index ea30fe50..00000000 --- a/ZSharpTest/projects/build.zs +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This file is responsible for building a Z# project. - * - * Requirements: - * [x] FS module - * [x] Directory Class - * [x] Operator / - * [x] Current Directory - * [x] File Class - * [x] Path Class - * [x] Operator / - * [x] `as` keyword for safe conversion - * [ ] Nullable types `T?` - * [x] `is of` operator for type matching - * [ ] custom importer for source of type `File` - * [ ] Project compiler - * [ ] Expose the compiler to Z# (even without members) - * [ ] .NET platform compiler - * [ ] Expose Mono.Cecil ModuleDefinition class (specifically, the `Write(string)` method) -*/ - - -import { - Directory, - File -} from "std:fs"; - - -// The root path of the project. This is usually where this -// script is. -let projectRoot = Directory.cwd(); - -// Source root is the root path of all project source files. -// Only files in this path are considered for discovery. -let sourceRoot = (projectRoot / "src") as Directory? or projectRoot; - -// Custom init file so users don't have to mess with this file. -if ((projectRoot / "init.zs") is initFile of File) - import initFile; - -// Project compiler is a specialized source compiler for compiling -// projects. -import { - Project, - ProjectCompiler -} from "net:ZSharp.ZSProjectCompiler.dll"; - -// The Project object holds the state of compiling the project. -let project = Project( - projectRoot.name, // project name - projectRoot, // project root directory - sourceRoot, // source files root directory -); - -project.discoverZSFiles(); // populates project.sourceFiles - -// Import the current compiler -import { compiler } from "core:compiler"; - -let projectCompiler = ProjectCompiler(compiler); -projectCompiler.compile(project); - -// Create output directory if it doesn't exist -let outDir = projectRoot.createDirectory("dist", existsOk: true); - -// Import the .NET platform compiler -import { - Compiler as NETCompiler -} from "core:platform/.net"; - -let netCompiler = NETCompiler(); - -for (let module in project.modules) { // IR - let netModule = netCompiler.compile(module); - netModule.write(module.name + if (module.entryPoint) ".exe" else ".dll"); -} diff --git a/ZSharpTest/projects/guessing-game.zs b/ZSharpTest/projects/guessing-game.zs deleted file mode 100644 index a150d0ea..00000000 --- a/ZSharpTest/projects/guessing-game.zs +++ /dev/null @@ -1,39 +0,0 @@ -import { input, print } from "std:io"; -import { ceil, log2, random } from "std:math"; - -module Program; - -let minNumber = 1; -let maxNumber = 100; - -let maxTries = ceil(log2(maxNumber - minNumber)); -let number = random(minNumber, maxNumber); - -let inputMessage = "Guess a number between " + string(minNumber) + " and " + string(maxNumber) + ": "; - -fun guessOnce(guess: i32, number: i32, tries: i32): bool { - case (true) { - when (guess < number) print("Too low!"); - when (number < guess) print("Too high!"); - } else return true; - - return false; -} - -fun main(): void { - var tries = 0; - - while (tries < maxTries) { - let guessString = input(inputMessage); - let guess = i32.parse(guessString); - - if (guessOnce(guess, number, tries)) - { - print("You got it in " + string(tries + 1) + " tries!"); - break; - } - else tries = tries + 1; - } else print("You didn't get it in " + string(maxTries) + " tries. The number was " + string(number)); - - return; -} diff --git a/ZSharpTest/projects/simple-user-system.zs b/ZSharpTest/projects/simple-user-system.zs deleted file mode 100644 index bbdea15a..00000000 --- a/ZSharpTest/projects/simple-user-system.zs +++ /dev/null @@ -1,103 +0,0 @@ -/* Required Features: - * [-] Primary constructor - * [-] Auto-fields from primary constructor parameters - * [x] Fields - * [x] Anonymous constructor - * [x] Named constructor - * [x] Methods - * [x] Case-Of - * [x] Automatic type inference for first parameter in methods - * [x] Automatic instance binding when accessing instance method/field from instance method - * [x] Instance method as function with `this` first parameter - * [x] Module globals initializers - */ - - -import { input, print } from "std:io"; - - -module Program; - - -class Authentication { - var username: string; - var password: string; - - new(this, username: string, password: string) { - this.username = username; - this.password = password; - } -} - - -class User { - var isAdmin: bool; - - var username: string; - var password: string; - - new(this, username: string, password: string) { - isAdmin = false; - - this.username = username; - this.password = password; - } - - new Admin(this, username: string, password: string) { - User(this: this, username, password); - - isAdmin = true; - } - - fun login(this, username: string, password: string): bool { - if (username != this.username) return false; - if (password != this.password) return false; - - return true; - } - - fun login(auth: Authentication, this: User): bool { - return this.login(auth.username, auth.password); - } -} - - -fun mainMenu(): bool { - print("|== Main Menu ==|"); - print("1. Sign In"); - print("2. Exit Program"); - - let userInput = input("> "); - - case (userInput) { - when ("1") signIn(); - when ("2") return false; - } else print("Invalid input."); - - return true; -} - - -fun signIn(): void { - let username = input("Username: "); - let password = input("Password: "); - - case (Authentication(username, password)) of (User.login) { - when (user) print("USER"); // userTerminal(); - when (admin) print("ADMIN"); // adminTerminal(); - } else print("Invalid credentials."); - - return; -} - - -fun main(): void { - while (mainMenu()) ; - else print("Thank you for using Simple User System!"); - - return; -} - - -let user = User("user", "123"); -let admin = User.Admin("admin", "321"); diff --git a/ZSharpTest/projects/todo.zs b/ZSharpTest/projects/todo.zs deleted file mode 100644 index a5079f8a..00000000 --- a/ZSharpTest/projects/todo.zs +++ /dev/null @@ -1,71 +0,0 @@ -import { List } from "net:ZLoad.Test.dll"; -import { print, input } from "std:io"; - - -module Program { - let todo: List[string] = [ - "Add list[T] type", - "Add support for generic types in CO", - "Add compiler for `for` statements", - "Fix `for.currentItem` field so that using `let` doesn't force to initialize.", - "Add compiler for `case` statements", - ]; - - fun addTodo(): void { - let item = input("Enter item to add: "); - - todo.append(item); - - return; - } - - fun getTodos(): void { - var i = 1; - for (let item in todo) - { - print(string(i) + ". " + item); - i = i + 1; - } - - return; - } - - fun delTodo(): void { - let index = i32.parse(input("Enter item number to remove: ")); - - todo.removeAt(index - 1); - - getTodos(); - - return; - } - - fun do(): bool { - print("Welcome to The ToDo List App! Please choose what to do:"); - print("-------------------------------------------------------"); - print("\t1. Add an item."); - print("\t2. List all items."); - print("\t3. Remove an item."); - print("\t4. Exit program."); - - - let cmd = input("> "); - - - case (cmd) { - when ("1") addTodo(); - when ("2") getTodos(); - when ("3") delTodo(); - when ("4") return false; - } else print("Unknown command: " + cmd); - - return true; - } - - fun main(): void { - while (do()); - else print("Thank you for using The ToDo List App!"); - - return; - } -} diff --git a/ZSharpTest/test.zs b/ZSharpTest/test.zs deleted file mode 100644 index 341c5317..00000000 --- a/ZSharpTest/test.zs +++ /dev/null @@ -1,10 +0,0 @@ -import { print } from "std:io"; - - -module Program; - -fun main(): void { - print(hello); - - return; -} diff --git a/ZSharpTest/test2.zs b/ZSharpTest/test2.zs deleted file mode 100644 index f467e9cf..00000000 --- a/ZSharpTest/test2.zs +++ /dev/null @@ -1,60 +0,0 @@ -import { input, print } from "std:io"; - - -module Lib { - fun id(x: type): type { return x; } - - fun str(s: string): string { return s; } - - fun printAndGetVoid(x: string): type { print("CT: " + x); return void; } -} - - -module Program; - -var message: string; - -fun main(): Lib.id(void) { - message = input("Please enter a message: "); - let audience = "World!"; - - bar(audience); - - { - print("Hello"); - } - - var v = 10 - 3; - - print(string(v)); - - v = 4; - - print(string(v)); - - while (false) - { - print("TRUE"); - break; - } else { - print("FALSE"); - } - - return; -} - -fun bar(x: string): Lib.printAndGetVoid("This is executed at CT!") { - foo(message + ", " + Lib.str(x)); - return; -} - -fun foo(x: string): void { - print(x); - return; -} - - -// import { compile } from "pkg:dotnet-compiler"; - -// let dotNETModule = compile(infoof(Program)); -// dotNETModule.Write("Program.dll"); diff --git a/ZSharpTest/tests/simple.zs b/ZSharpTest/tests/simple.zs deleted file mode 100644 index 5473346f..00000000 --- a/ZSharpTest/tests/simple.zs +++ /dev/null @@ -1,130 +0,0 @@ -import { input, print } from "std:io"; -import { - BaseClass, - Console, - List, - TestClass, - TestEnum, - TestInterface, - greet, - id -} from "net:ZLoad.Test.dll"; -import { Directory, File } from "net:ZSharp.CT.StandardLibrary.FileSystem.dll"; - -import { Expression, LiteralType } from "net:ZSharp.AST.dll"; - -print("Hello, Document!"); - -module Program; - -class MyClass : TestInterface { - new(this) {} - - fun do(this): void { - print("Hello from MyClass"); - - return; - } - - fun do(this, x: i32): i32 { - return x + 1; - } -} - -class OtherClass : TestInterface { - var x: i32; - - new(this, number: i32) { - this.x = number; - - } - - fun do(this): void { - print("Hello from OtherClass"); - return; - } - - fun do(this, x: i32): i32 { - return x + this.x; - } -} - -class Base { - fun baseMethod(this): void { - print("Base::baseMethod"); - - return; - } -} - -class Derived : Base { - - new() {} - - fun derivedMethod(this): void { - print("Derived::derivedMethod"); - - return; - } -} - -fun testInterface(test: TestInterface): void { - - test.do(); - print(string(test.do(number))); - return; -} - -fun testBaseClass(test: BaseClass): void { - test.doVirtual(); - return; -} - -fun main(): void { - - let c1 = MyClass(); - let c2 = OtherClass(5); - - testInterface(c1); - testInterface(c2); - - let tc = TestClass(); - print(tc.id[string]("Id [T: string] of TestClass")); - - testBaseClass(BaseClass()); - testBaseClass(tc); - - let cwd = Directory.cwd(); - print(cwd.toString()); - let testsDirectory = cwd / "tests" as Directory; - let filePath = testsDirectory / "simple.zs"; - print(filePath.toString()); - //print(filePath.asFile().toString()); - print(id("Id [T: string]")); - - - let base: Base = Derived(); - base.baseMethod(); - - //if (base is derived of Derived) - // derived.derivedMethod(); - - let derived = base as Derived; - derived.derivedMethod(); - - if (filePath is simpleFilePath of File) - print(simpleFilePath.getContent()); - - let testDirectory = testsDirectory.createDirectory("test", existsOk: true); - - //testsDirectory.createDirectory("test", existsOk: false); - - let testEnum = TestEnum.C; - print(string(testEnum)); - - print(string(LiteralType.False)); - - return; -} - -let number = 10; diff --git a/ZSharpTest/tests/test-class-fields.zs b/ZSharpTest/tests/test-class-fields.zs deleted file mode 100644 index 82fff3bb..00000000 --- a/ZSharpTest/tests/test-class-fields.zs +++ /dev/null @@ -1,51 +0,0 @@ -import { print } from "std:io"; - -module Program; - -class MyBase { - var name: string; -} - -class MyClass : MyBase { - let age: i32 = 0; - - var base: MyBase; - - new (this, age: i32) { - base = this; - this.age = age; - } - - new Old(this) { - MyClass(this: this, 80); - } - - fun printAge(this): void { - return MyClass.printAge(this, "this.age = "); - } - - fun printAge(this, message: string): void { - print(message + string(this.age)); - - return; - } -} - - -fun main(): void { - let myClass = MyClass(15); - let old = MyClass.Old(); - - old.printAge(); - - print(string(myClass.age)); - - print(string(myClass.age = 20)); - - print("myClass.age = " + string(myClass.age)); - - myClass.printAge(); - myClass.printAge("Hello!"); - - return; -} diff --git a/ZSharpTest/tests/test-if-statement.zs b/ZSharpTest/tests/test-if-statement.zs deleted file mode 100644 index 84feef93..00000000 --- a/ZSharpTest/tests/test-if-statement.zs +++ /dev/null @@ -1,17 +0,0 @@ -import { print } from "std:io"; - -module Program; - - -fun main(): void { - let value = false; - - if (value) - print("true"); - else if (false) - print("false"); - else - print("else"); - - return; -} diff --git a/ZSharpTest/tests/test-while-expression.zs b/ZSharpTest/tests/test-while-expression.zs deleted file mode 100644 index 111f6b07..00000000 --- a/ZSharpTest/tests/test-while-expression.zs +++ /dev/null @@ -1,16 +0,0 @@ -import { print } from "std:io"; - -module Program; - - -fun main(): void { - let result = - while (false) - break "TRUE"; - else "FALSE"; - - - print(result); - - return; -} diff --git a/ZSharpTokenizerTest/Program.cs b/ZSharpTokenizerTest/Program.cs deleted file mode 100644 index 2b08a92a..00000000 --- a/ZSharpTokenizerTest/Program.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ZSharp.Tokenizer; - - -using (StreamReader stream = File.OpenText("./tokenizerText.txt")) - foreach (var token in Tokenizer.Tokenize(new(stream))) - { - if (token.Is(ZSharp.Text.TokenCategory.WhiteSpace)) - Console.WriteLine($"Token ({token.Type}) @ ({token.Span})"); - else - Console.WriteLine($"Token ({token.Type}) @ ({token.Span}) = {token.Value}"); - } diff --git a/ZSharpTokenizerTest/ZSharpTokenizerTest.csproj b/ZSharpTokenizerTest/ZSharpTokenizerTest.csproj deleted file mode 100644 index 704d2d3c..00000000 --- a/ZSharpTokenizerTest/ZSharpTokenizerTest.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - Exe - net8.0 - enable - enable - - - - - - - - - PreserveNewest - - - - diff --git a/ZSharpTokenizerTest/tokenizerText.txt b/ZSharpTokenizerTest/tokenizerText.txt deleted file mode 100644 index a1956724..00000000 --- a/ZSharpTokenizerTest/tokenizerText.txt +++ /dev/null @@ -1,10 +0,0 @@ -"Hello this is a string" - - "And with escape chars:\n \\ \"" 'H' [] ( - ) , ;: - -_ id this_is_id thisIsAlso _0 __ a0 a0_ - -/ + ++ -- == += -= *= && - -1 2 12 123 1.0 1.2 1.12 1i32 1.111 \ No newline at end of file From 5307cddd6cf0030d4fbd7726c1fa19cfb3e673f6 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 14 Sep 2025 16:29:41 +0300 Subject: [PATCH 211/235] Add test.zs in ZSharp.CLI --- ZSharp.CLI/test.zs | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 ZSharp.CLI/test.zs diff --git a/ZSharp.CLI/test.zs b/ZSharp.CLI/test.zs new file mode 100644 index 00000000..ca1fefc8 --- /dev/null +++ b/ZSharp.CLI/test.zs @@ -0,0 +1,8 @@ +import { Directory } from "std:fs"; +import { print } from "std:io"; + +print("Hello, World!"); + +module A { + print("Inside module A"); +} From 3d00b133f96760fa7708c640445d73b4f0197517 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 14 Sep 2025 21:31:52 +0300 Subject: [PATCH 212/235] Add IR system and organize some stuff --- ZSharp v1.sln | 12 ++++++++ ZSharp.CLI/Program.cs | 8 +++-- ZSharp.CLI/ZSharp.CLI.csproj | 1 + .../dispatcher/Dispatcher.cs | 2 +- .../dispatcher/services/Dispatcher.Call.cs | 2 +- .../dispatcher/services/Dispatcher.Cast.cs | 2 +- .../services/Dispatcher.ImplicitCast.cs | 2 +- .../dispatcher/services/Dispatcher.Index.cs | 2 +- .../dispatcher/services/Dispatcher.Match.cs | 2 +- .../services/Dispatcher.MemberAccess.cs | 2 +- .../services/Dispatcher.ValueAccess.cs | 2 +- .../dispatcher/Dispatcher.cs | 2 +- .../dispatcher/services/Dispatcher.Call.cs | 2 +- .../dispatcher/services/Dispatcher.Cast.cs | 2 +- .../services/Dispatcher.ImplicitCast.cs | 2 +- .../dispatcher/services/Dispatcher.Index.cs | 2 +- .../dispatcher/services/Dispatcher.Match.cs | 2 +- .../services/Dispatcher.MemberAccess.cs | 2 +- .../services/Dispatcher.ValueAccess.cs | 2 +- .../dispatcher/Dispatcher.cs | 2 +- .../dispatcher/services/Dispatcher.Call.cs | 2 +- .../dispatcher/services/Dispatcher.Cast.cs | 2 +- .../services/Dispatcher.ImplicitCast.cs | 2 +- .../dispatcher/services/Dispatcher.Index.cs | 2 +- .../dispatcher/services/Dispatcher.Match.cs | 2 +- .../services/Dispatcher.MemberAccess.cs | 2 +- .../services/Dispatcher.ValueAccess.cs | 2 +- ZSharp.Compiler.IR.Static/GlobalUsings.cs | 2 ++ .../ZSharp.Compiler.IR.Static.csproj | 13 ++++++++ .../dispatcher/Dispatcher.cs | 22 ++++++++++++++ .../dispatcher/services/Dispatcher.Code.cs | 15 ++++++++++ .../services/Dispatcher.Definition.cs | 30 +++++++++++++++++++ .../services/Dispatcher.Reference.cs | 16 ++++++++++ .../dispatcher/services/Dispatcher.Type.cs | 26 ++++++++++++++++ .../objects/RawIRCode.cs | 2 +- .../protocols/ICompileIRCode.cs | 7 +++++ .../protocols/ICompileIRDefinitionAs.cs | 8 +++++ .../protocols/ICompileIRDefinitionIn.cs | 8 +++++ .../protocols/ICompileIRReference.cs | 2 +- .../protocols/ICompileIRType.cs | 19 ++++++++++++ .../common/ICompileIROOPTypeReference.cs | 11 ------- ZSharp.Compiler.IR/core/IRCode.cs | 1 - ZSharp.Compiler.IR/dispatcher/Dispatcher.cs | 7 +++++ .../dispatcher/services/Dispatcher.Code.cs | 10 +++++++ .../services/Dispatcher.Definition.cs | 16 ++++++++++ .../services/Dispatcher.Reference.cs | 11 +++++++ .../dispatcher/services/Dispatcher.Type.cs | 16 ++++++++++ ZSharp.Compiler.IR/ir/IR.cs | 4 +-- ZSharp.Compiler.IR/ir/services/IR.Code.cs | 14 +++------ .../ir/services/IR.Definition.cs | 24 +++++---------- .../ir/services/IR.Reference.cs | 13 +++----- ZSharp.Compiler.IR/ir/services/IR.Type.cs | 20 +++++-------- .../protocols/ICompileIRCode.cs | 7 ----- .../protocols/ICompileIRDefinitionAs.cs | 8 ----- .../protocols/ICompileIRDefinitionIn.cs | 8 ----- .../protocols/ICompileIRType.cs | 17 ----------- .../protocols/IIRDefinitionAsCompiler.cs | 8 +++++ .../protocols/IIRDefinitionInCompiler.cs | 8 +++++ .../protocols/IIRReferenceCompiler.cs | 8 +++++ .../protocols/IIRTypeCompiler.cs | 8 +++++ ZSharp.Compiler.Overloading/GlobalUsings.cs | 4 +++ .../ZSharp.Compiler.Overloading.csproj | 4 +++ .../dispatcher/Dispatcher.T.cs | 8 +++++ .../dispatcher/Dispatcher.cs | 6 ++++ .../overloading/Overloading.cs | 7 +++++ .../overloading/services/Overloading.T.cs | 9 ++++++ ZSharp.Compiler.Reflection/GlobalUsings.cs | 4 +++ .../ZSharp.Compiler.Reflection.csproj | 13 ++++++++ .../dispatcher/Dispatcher.GetCO.cs | 15 ++++++++++ .../dispatcher/Dispatcher.cs | 6 ++++ .../reflection/Reflection.cs | 7 +++++ .../reflection/services/Reflection.GetCO.cs | 9 ++++++ .../dispatcher/Dispatcher.T.cs | 2 +- .../dispatcher/Dispatcher.TypeOf.cs | 2 +- .../dispatcher/Dispatcher.cs | 2 +- ZSharp.Compiler/ZSharp.Compiler.csproj | 2 ++ ZSharp.Compiler/compiler/Compiler.Services.cs | 7 ++++- .../ZSharp.Importer.ILLoader.csproj | 1 + .../il loader/ILLoader.Compiler.cs | 9 ++++++ .../il loader/ILLoader.Expose.cs | 19 ++++++------ .../il loader/ILLoader.IR.cs | 10 ------- .../il loader/ILLoader.cs | 4 +-- .../modular/function/concrete/Function.IR.cs | 6 ++-- .../objects/oop/class/concrete/Class.IR.cs | 4 +-- .../objects/oop/method/concrete/Method.IR.cs | 6 ++-- .../objects/types/boolean/BooleanType.cs | 2 +- .../objects/types/char/CharType.cs | 2 +- .../objects/types/float/Float128Type.cs | 2 +- .../objects/types/float/Float16Type.cs | 2 +- .../objects/types/float/Float32Type.cs | 2 +- .../objects/types/float/Float64Type.cs | 2 +- .../objects/types/int/SInt16Type.cs | 2 +- .../objects/types/int/SInt32Type.cs | 2 +- .../objects/types/int/SInt64Type.cs | 2 +- .../objects/types/int/SInt8Type.cs | 2 +- .../objects/types/int/SIntNativeType.cs | 2 +- .../objects/types/int/UInt16Type.cs | 2 +- .../objects/types/int/UInt32Type.cs | 2 +- .../objects/types/int/UInt64Type.cs | 2 +- .../objects/types/int/UInt8Type.cs | 2 +- .../objects/types/int/UIntNativeType.cs | 2 +- .../objects/types/object/ObjectType.cs | 2 +- .../objects/types/string/StringType.cs | 2 +- .../objects/types/void/VoidType.cs | 2 +- ZSharp.Interpreter/interpreter/Interpreter.cs | 9 +----- .../ZSharp.SourceCompiler.Common.csproj | 1 + .../literals/bool/BooleanLiteral.IR.cs | 4 +-- .../literals/string/StringLiteral.IR.cs | 4 +-- .../ZSharp.SourceCompiler.Module.csproj | 1 + .../objects/modular/global/Global.IR.cs | 8 ++--- 110 files changed, 488 insertions(+), 201 deletions(-) create mode 100644 ZSharp.Compiler.IR.Static/GlobalUsings.cs create mode 100644 ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj create mode 100644 ZSharp.Compiler.IR.Static/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Code.cs create mode 100644 ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Definition.cs create mode 100644 ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Reference.cs create mode 100644 ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Type.cs rename {ZSharp.Compiler.IR => ZSharp.Compiler.IR.Static}/objects/RawIRCode.cs (72%) create mode 100644 ZSharp.Compiler.IR.Static/protocols/ICompileIRCode.cs create mode 100644 ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionAs.cs create mode 100644 ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionIn.cs rename {ZSharp.Compiler.IR => ZSharp.Compiler.IR.Static}/protocols/ICompileIRReference.cs (63%) create mode 100644 ZSharp.Compiler.IR.Static/protocols/ICompileIRType.cs delete mode 100644 ZSharp.Compiler.IR/common/ICompileIROOPTypeReference.cs create mode 100644 ZSharp.Compiler.IR/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Code.cs create mode 100644 ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Definition.cs create mode 100644 ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Reference.cs create mode 100644 ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Type.cs delete mode 100644 ZSharp.Compiler.IR/protocols/ICompileIRCode.cs delete mode 100644 ZSharp.Compiler.IR/protocols/ICompileIRDefinitionAs.cs delete mode 100644 ZSharp.Compiler.IR/protocols/ICompileIRDefinitionIn.cs delete mode 100644 ZSharp.Compiler.IR/protocols/ICompileIRType.cs create mode 100644 ZSharp.Compiler.IR/protocols/IIRDefinitionAsCompiler.cs create mode 100644 ZSharp.Compiler.IR/protocols/IIRDefinitionInCompiler.cs create mode 100644 ZSharp.Compiler.IR/protocols/IIRReferenceCompiler.cs create mode 100644 ZSharp.Compiler.IR/protocols/IIRTypeCompiler.cs create mode 100644 ZSharp.Compiler.Overloading/GlobalUsings.cs create mode 100644 ZSharp.Compiler.Overloading/dispatcher/Dispatcher.T.cs create mode 100644 ZSharp.Compiler.Overloading/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.Overloading/overloading/Overloading.cs create mode 100644 ZSharp.Compiler.Overloading/overloading/services/Overloading.T.cs create mode 100644 ZSharp.Compiler.Reflection/GlobalUsings.cs create mode 100644 ZSharp.Compiler.Reflection/ZSharp.Compiler.Reflection.csproj create mode 100644 ZSharp.Compiler.Reflection/dispatcher/Dispatcher.GetCO.cs create mode 100644 ZSharp.Compiler.Reflection/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.Reflection/reflection/Reflection.cs create mode 100644 ZSharp.Compiler.Reflection/reflection/services/Reflection.GetCO.cs create mode 100644 ZSharp.Importer.ILLoader/il loader/ILLoader.Compiler.cs delete mode 100644 ZSharp.Importer.ILLoader/il loader/ILLoader.IR.cs diff --git a/ZSharp v1.sln b/ZSharp v1.sln index 268753bb..11905c9d 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -75,6 +75,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CG.Proxy", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.CG.Typed", "ZSharp.Compiler.CG.Typed\ZSharp.Compiler.CG.Typed.csproj", "{62E6B22B-2057-8EFC-30D4-B6F497FEF9D8}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Reflection", "ZSharp.Compiler.Reflection\ZSharp.Compiler.Reflection.csproj", "{0B9B763F-D6DA-4D29-B810-7A4CADF152DB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.IR.Static", "ZSharp.Compiler.IR.Static\ZSharp.Compiler.IR.Static.csproj", "{D4B62927-75B2-4147-8B63-1154BA1AB9CE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -225,6 +229,14 @@ Global {62E6B22B-2057-8EFC-30D4-B6F497FEF9D8}.Debug|Any CPU.Build.0 = Debug|Any CPU {62E6B22B-2057-8EFC-30D4-B6F497FEF9D8}.Release|Any CPU.ActiveCfg = Release|Any CPU {62E6B22B-2057-8EFC-30D4-B6F497FEF9D8}.Release|Any CPU.Build.0 = Release|Any CPU + {0B9B763F-D6DA-4D29-B810-7A4CADF152DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0B9B763F-D6DA-4D29-B810-7A4CADF152DB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0B9B763F-D6DA-4D29-B810-7A4CADF152DB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0B9B763F-D6DA-4D29-B810-7A4CADF152DB}.Release|Any CPU.Build.0 = Release|Any CPU + {D4B62927-75B2-4147-8B63-1154BA1AB9CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D4B62927-75B2-4147-8B63-1154BA1AB9CE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D4B62927-75B2-4147-8B63-1154BA1AB9CE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D4B62927-75B2-4147-8B63-1154BA1AB9CE}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZSharp.CLI/Program.cs b/ZSharp.CLI/Program.cs index 48fde44c..e0c398d1 100644 --- a/ZSharp.CLI/Program.cs +++ b/ZSharp.CLI/Program.cs @@ -142,9 +142,11 @@ #region Setup Interpreter - new ZSharp.Compiler.Dispatchers.Direct.Dispatcher(interpreter.Compiler).Apply(); - new ZSharp.Compiler.Dispatchers.Typed.Dispatcher(interpreter.Compiler).Apply(); - new ZSharp.Compiler.Dispatchers.Proxy.Dispatcher(interpreter.Compiler).Apply(); + new ZSharp.Compiler.CGDispatchers.Direct.Dispatcher(interpreter.Compiler).Apply(); + new ZSharp.Compiler.CGDispatchers.Typed.Dispatcher(interpreter.Compiler).Apply(); + new ZSharp.Compiler.CGDispatchers.Proxy.Dispatcher(interpreter.Compiler).Apply(); + + new ZSharp.Compiler.IRDispatchers.Static.Dispatcher(interpreter.Compiler).Apply(); var scriptCompiler = new ScriptCompiler(interpreter, documentNode); diff --git a/ZSharp.CLI/ZSharp.CLI.csproj b/ZSharp.CLI/ZSharp.CLI.csproj index b7d49b25..6ba2582b 100644 --- a/ZSharp.CLI/ZSharp.CLI.csproj +++ b/ZSharp.CLI/ZSharp.CLI.csproj @@ -20,6 +20,7 @@ + diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/Dispatcher.cs b/ZSharp.Compiler.CG.Direct/dispatcher/Dispatcher.cs index 3d5c47a6..4fdc11af 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/Dispatcher.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/Dispatcher.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Direct +namespace ZSharp.Compiler.CGDispatchers.Direct { public partial class Dispatcher(Compiler compiler) { diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Call.cs index adae7770..68633097 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Call.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Call.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Direct +namespace ZSharp.Compiler.CGDispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Cast.cs index 0b55b314..7a417649 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Cast.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Cast.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Direct +namespace ZSharp.Compiler.CGDispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ImplicitCast.cs index b615b953..1ba4a3bc 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ImplicitCast.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Direct +namespace ZSharp.Compiler.CGDispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Index.cs index 8fc1ac29..d056f692 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Index.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Index.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Direct +namespace ZSharp.Compiler.CGDispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Match.cs index 937af126..650f8535 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Match.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Match.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Direct +namespace ZSharp.Compiler.CGDispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.MemberAccess.cs index 43b344fd..926d7aab 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.MemberAccess.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.MemberAccess.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Direct +namespace ZSharp.Compiler.CGDispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ValueAccess.cs index fab43a40..ab671aae 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ValueAccess.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ValueAccess.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Direct +namespace ZSharp.Compiler.CGDispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/Dispatcher.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/Dispatcher.cs index dab3f285..b8e5daab 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/Dispatcher.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/Dispatcher.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Proxy +namespace ZSharp.Compiler.CGDispatchers.Proxy { public partial class Dispatcher(Compiler compiler) { diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Call.cs index 35346f17..6358c41c 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Call.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Call.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Proxy +namespace ZSharp.Compiler.CGDispatchers.Proxy { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Cast.cs index e05d6747..c951e7f9 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Cast.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Cast.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Proxy +namespace ZSharp.Compiler.CGDispatchers.Proxy { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs index 9017f7eb..b670ce6d 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Proxy +namespace ZSharp.Compiler.CGDispatchers.Proxy { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Index.cs index 5bf4775a..283b77e8 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Index.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Index.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Proxy +namespace ZSharp.Compiler.CGDispatchers.Proxy { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Match.cs index a9b88a2a..2b27fdfc 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Match.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Match.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Proxy +namespace ZSharp.Compiler.CGDispatchers.Proxy { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs index 505b8561..54108881 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Proxy +namespace ZSharp.Compiler.CGDispatchers.Proxy { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs index 6422e640..ce7e8e1a 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Proxy +namespace ZSharp.Compiler.CGDispatchers.Proxy { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/Dispatcher.cs b/ZSharp.Compiler.CG.Typed/dispatcher/Dispatcher.cs index 7f66d517..e10ead34 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/Dispatcher.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/Dispatcher.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Typed +namespace ZSharp.Compiler.CGDispatchers.Typed { public partial class Dispatcher(Compiler compiler) { diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Call.cs index 2da827ee..fc9e791a 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Call.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Call.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Typed +namespace ZSharp.Compiler.CGDispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Cast.cs index 7afd8bcc..4a0a703b 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Cast.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Cast.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Typed +namespace ZSharp.Compiler.CGDispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs index 554c5ccf..4239778d 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Typed +namespace ZSharp.Compiler.CGDispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Index.cs index 7a604efd..2962eb7c 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Index.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Index.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Typed +namespace ZSharp.Compiler.CGDispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Match.cs index 3e185238..9b2c3f34 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Match.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Match.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Typed +namespace ZSharp.Compiler.CGDispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.MemberAccess.cs index e74952c6..54b35764 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.MemberAccess.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.MemberAccess.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Typed +namespace ZSharp.Compiler.CGDispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ValueAccess.cs index 587cb748..f933e979 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ValueAccess.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ValueAccess.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Typed +namespace ZSharp.Compiler.CGDispatchers.Typed { partial class Dispatcher { diff --git a/ZSharp.Compiler.IR.Static/GlobalUsings.cs b/ZSharp.Compiler.IR.Static/GlobalUsings.cs new file mode 100644 index 00000000..52ab0744 --- /dev/null +++ b/ZSharp.Compiler.IR.Static/GlobalUsings.cs @@ -0,0 +1,2 @@ +global using Result = ZSharp.Compiler.Result; +global using TargetPlatform = object; diff --git a/ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj b/ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj new file mode 100644 index 00000000..7e575a54 --- /dev/null +++ b/ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/ZSharp.Compiler.IR.Static/dispatcher/Dispatcher.cs b/ZSharp.Compiler.IR.Static/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..c2d84402 --- /dev/null +++ b/ZSharp.Compiler.IR.Static/dispatcher/Dispatcher.cs @@ -0,0 +1,22 @@ +namespace ZSharp.Compiler.IRDispatchers.Static +{ + public partial class Dispatcher(Compiler compiler) + { + private readonly Compiler compiler = compiler; + private IR @base; + + public void Apply() + { + @base = compiler.IR; + + ref var ir = ref compiler.IR; + + ir.CompileCode = CompileCode; + ir.DefinitionInCompiler = this; + ir.DefinitionAsCompiler = this; + ir.ReferenceCompiler = this; + ir.CompileType = CompileType; + ir.TypeCompiler = this; + } + } +} diff --git a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Code.cs b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Code.cs new file mode 100644 index 00000000..fe1e16af --- /dev/null +++ b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Code.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.IRDispatchers.Static +{ + partial class Dispatcher + { + public Result CompileCode(CompilerObject @object, TargetPlatform? target) + { + var result = @base.CompileCode(@object, target); + + if (result.IsError && @object.Is(out var compile)) + result = compile.CompileIRCode(compiler, target); + + return result; + } + } +} diff --git a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Definition.cs b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Definition.cs new file mode 100644 index 00000000..1fea4cae --- /dev/null +++ b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Definition.cs @@ -0,0 +1,30 @@ +namespace ZSharp.Compiler.IRDispatchers.Static +{ + partial class Dispatcher + : IIRDefinitionInCompiler + , IIRDefinitionAsCompiler + { + bool IIRDefinitionInCompiler.CompileDefinition(CompilerObject @object, Owner owner, TargetPlatform? target) + { + var result = @base.CompileDefinition(@object, owner, target); + + if (!result && @object.Is>(out var compile)) + { + compile.CompileIRDefinition(compiler, owner, target); + result = true; + } + + return result; + } + + Result IIRDefinitionAsCompiler.CompileDefinition(CompilerObject @object, object? target) + { + var result = @base.CompileDefinition(@object, target); + + if (result.IsError && @object.Is>(out var compile)) + result = compile.CompileIRDefinition(compiler, target); + + return result; + } + } +} diff --git a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Reference.cs b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Reference.cs new file mode 100644 index 00000000..60ddc103 --- /dev/null +++ b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Reference.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Compiler.IRDispatchers.Static +{ + partial class Dispatcher + : IIRReferenceCompiler + { + Result IIRReferenceCompiler.CompileReference(CompilerObject @object) where T : class + { + var result = @base.CompileReference(@object); + + if (result.IsError && @object.Is>(out var compile)) + result = compile.CompileIRReference(compiler); + + return result; + } + } +} diff --git a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Type.cs b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Type.cs new file mode 100644 index 00000000..585c7d62 --- /dev/null +++ b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Type.cs @@ -0,0 +1,26 @@ +namespace ZSharp.Compiler.IRDispatchers.Static +{ + partial class Dispatcher + : IIRTypeCompiler + { + public Result CompileType(CompilerObject @object) + { + var result = @base.CompileType(@object); + + if (result.IsError && @object.Is(out var compile)) + result = compile.CompileIRType(compiler); + + return result; + } + + Result IIRTypeCompiler.CompileType(CompilerObject @object) + { + var result = @base.CompileTypeAs(@object); + + if (result.IsError && @object.Is>(out var compile)) + result = compile.CompileIRType(compiler); + + return result; + } + } +} diff --git a/ZSharp.Compiler.IR/objects/RawIRCode.cs b/ZSharp.Compiler.IR.Static/objects/RawIRCode.cs similarity index 72% rename from ZSharp.Compiler.IR/objects/RawIRCode.cs rename to ZSharp.Compiler.IR.Static/objects/RawIRCode.cs index 5d3a8f2a..0785cba2 100644 --- a/ZSharp.Compiler.IR/objects/RawIRCode.cs +++ b/ZSharp.Compiler.IR.Static/objects/RawIRCode.cs @@ -8,7 +8,7 @@ public sealed class RawIRCode(IRCode code) { private readonly IRCode code = code; - Result ICompileIRCode.CompileIRCode(Compiler.IR ir, object? target) + Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) => Result.Ok(code); } } diff --git a/ZSharp.Compiler.IR.Static/protocols/ICompileIRCode.cs b/ZSharp.Compiler.IR.Static/protocols/ICompileIRCode.cs new file mode 100644 index 00000000..f261d1f2 --- /dev/null +++ b/ZSharp.Compiler.IR.Static/protocols/ICompileIRCode.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICompileIRCode + { + public Result CompileIRCode(Compiler compiler, TargetPlatform? target); + } +} diff --git a/ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionAs.cs b/ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionAs.cs new file mode 100644 index 00000000..ac95f2d1 --- /dev/null +++ b/ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionAs.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICompileIRDefinitionAs + where T : ZSharp.IR.IRDefinition + { + public Result CompileIRDefinition(Compiler compiler, TargetPlatform? target); + } +} diff --git a/ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionIn.cs b/ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionIn.cs new file mode 100644 index 00000000..e490ff13 --- /dev/null +++ b/ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionIn.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface ICompileIRDefinitionIn + where Owner : ZSharp.IR.IRDefinition + { + public void CompileIRDefinition(Compiler compiler, Owner owner, TargetPlatform? target); + } +} diff --git a/ZSharp.Compiler.IR/protocols/ICompileIRReference.cs b/ZSharp.Compiler.IR.Static/protocols/ICompileIRReference.cs similarity index 63% rename from ZSharp.Compiler.IR/protocols/ICompileIRReference.cs rename to ZSharp.Compiler.IR.Static/protocols/ICompileIRReference.cs index 54501f27..1295b15d 100644 --- a/ZSharp.Compiler.IR/protocols/ICompileIRReference.cs +++ b/ZSharp.Compiler.IR.Static/protocols/ICompileIRReference.cs @@ -3,6 +3,6 @@ public interface ICompileIRReference where T : class { - public Result CompileIRReference(IR ir); + public Result CompileIRReference(Compiler compiler); } } diff --git a/ZSharp.Compiler.IR.Static/protocols/ICompileIRType.cs b/ZSharp.Compiler.IR.Static/protocols/ICompileIRType.cs new file mode 100644 index 00000000..95b33949 --- /dev/null +++ b/ZSharp.Compiler.IR.Static/protocols/ICompileIRType.cs @@ -0,0 +1,19 @@ +using IType = ZSharp.IR.IType; + +namespace ZSharp.Compiler +{ + public interface ICompileIRType + { + public Result CompileIRType(Compiler compiler); + } + + public interface ICompileIRType + : ICompileIRType + where T : class, IType + { + Result ICompileIRType.CompileIRType(Compiler compiler) + => CompileIRType(compiler).When(type => type as IType); + + public new Result CompileIRType(Compiler compiler); + } +} \ No newline at end of file diff --git a/ZSharp.Compiler.IR/common/ICompileIROOPTypeReference.cs b/ZSharp.Compiler.IR/common/ICompileIROOPTypeReference.cs deleted file mode 100644 index ff6a9eb7..00000000 --- a/ZSharp.Compiler.IR/common/ICompileIROOPTypeReference.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICompileIROOPTypeReference - : ICompileIRReference - , ICompileIRReference> - where T : OOPType - { - Result ICompileIRReference.CompileIRReference(IR ir) - => (this as ICompileIRReference < OOPTypeReference < T >>).CompileIRReference(ir).When(v => v as OOPTypeReference); - } -} diff --git a/ZSharp.Compiler.IR/core/IRCode.cs b/ZSharp.Compiler.IR/core/IRCode.cs index 03910cc9..71470257 100644 --- a/ZSharp.Compiler.IR/core/IRCode.cs +++ b/ZSharp.Compiler.IR/core/IRCode.cs @@ -1,5 +1,4 @@ using CommonZ.Utils; -using ZSharp.IR; namespace ZSharp.Compiler { diff --git a/ZSharp.Compiler.IR/dispatcher/Dispatcher.cs b/ZSharp.Compiler.IR/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..6bf6b9e2 --- /dev/null +++ b/ZSharp.Compiler.IR/dispatcher/Dispatcher.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + internal partial class Dispatcher + { + internal static Dispatcher Instance { get; } = new(); + } +} diff --git a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Code.cs b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Code.cs new file mode 100644 index 00000000..7187db51 --- /dev/null +++ b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Code.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public Result CompileCode(CompilerObject @object, TargetPlatform? target) + => Result.Error( + $"Object {@object} does not support compile IR code" + ); + } +} diff --git a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Definition.cs b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Definition.cs new file mode 100644 index 00000000..ef64c9d9 --- /dev/null +++ b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Definition.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + : IIRDefinitionInCompiler + , IIRDefinitionAsCompiler + { + public bool CompileDefinition(CompilerObject @object, Owner owner, TargetPlatform? target) + where Owner : IRDefinition + => false; + + public Result CompileDefinition(CompilerObject @object, object? target) where T : IRDefinition + => Result.Error( + $"Object {@object} does not support compile IR definition of type {typeof(T)}" + ); + } +} diff --git a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Reference.cs b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Reference.cs new file mode 100644 index 00000000..4b613c88 --- /dev/null +++ b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Reference.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + : IIRReferenceCompiler + { + public Result CompileReference(CompilerObject @object) where T : class + => Result.Error( + $"Object {@object} does not support compile IR reference" + ); + } +} diff --git a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Type.cs b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Type.cs new file mode 100644 index 00000000..4796fcb5 --- /dev/null +++ b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Type.cs @@ -0,0 +1,16 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + : IIRTypeCompiler + { + public Result CompileType(CompilerObject @object) + => Result.Error( + $"Object {@object} does not support compile IR type" + ); + + Result IIRTypeCompiler.CompileType(CompilerObject @object) + => Result.Error( + $"Object {@object} does not support compile IR type" + ); + } +} diff --git a/ZSharp.Compiler.IR/ir/IR.cs b/ZSharp.Compiler.IR/ir/IR.cs index c0417d05..f415c6b1 100644 --- a/ZSharp.Compiler.IR/ir/IR.cs +++ b/ZSharp.Compiler.IR/ir/IR.cs @@ -1,7 +1,7 @@ namespace ZSharp.Compiler { - public sealed partial class IR(ZSharp.IR.RuntimeModule runtimeModule) + public partial struct IR(RuntimeModule runtimeModule) { - public ZSharp.IR.RuntimeModule RuntimeModule { get; } = runtimeModule; + public RuntimeModule RuntimeModule { get; } = runtimeModule; } } diff --git a/ZSharp.Compiler.IR/ir/services/IR.Code.cs b/ZSharp.Compiler.IR/ir/services/IR.Code.cs index a81c1f81..b6044d94 100644 --- a/ZSharp.Compiler.IR/ir/services/IR.Code.cs +++ b/ZSharp.Compiler.IR/ir/services/IR.Code.cs @@ -1,15 +1,9 @@ namespace ZSharp.Compiler { - partial class IR - { - public Result CompileCode(CompilerObject @object, TargetPlatform? target) - { - if (@object.Is(out var compile)) - return compile.CompileIRCode(this, target); + public delegate Result CompileIRCode(CompilerObject @object, TargetPlatform? target); - return Result.Error( - $"Object of type { @object.GetType().Name } does not implement ICompileIRCode" - ); - } + partial struct IR + { + public CompileIRCode CompileCode { get; set; } = Dispatcher.Instance.CompileCode; } } diff --git a/ZSharp.Compiler.IR/ir/services/IR.Definition.cs b/ZSharp.Compiler.IR/ir/services/IR.Definition.cs index 46a1914b..3d6f562d 100644 --- a/ZSharp.Compiler.IR/ir/services/IR.Definition.cs +++ b/ZSharp.Compiler.IR/ir/services/IR.Definition.cs @@ -1,27 +1,17 @@ namespace ZSharp.Compiler { - partial class IR + partial struct IR { + public IIRDefinitionAsCompiler DefinitionAsCompiler { get; set; } = Dispatcher.Instance; + + public IIRDefinitionInCompiler DefinitionInCompiler { get; set; } = Dispatcher.Instance; + public Result CompileDefinition(CompilerObject @object, TargetPlatform? target) where T : IRDefinition - { - if (@object.Is>(out var compile)) - return compile.CompileIRDefinition(this, target); - - return Result.Error( - $"Cannot compile definition for object of type {@object}" - ); - } + => DefinitionAsCompiler.CompileDefinition(@object, target); public bool CompileDefinition(CompilerObject @object, Owner owner, TargetPlatform? target) where Owner : IRDefinition - { - if (!@object.Is>(out var compile)) - return false; - - - compile.CompileIRDefinition(this, owner, target); - return true; - } + => DefinitionInCompiler.CompileDefinition(@object, owner, target); } } diff --git a/ZSharp.Compiler.IR/ir/services/IR.Reference.cs b/ZSharp.Compiler.IR/ir/services/IR.Reference.cs index 1e5a97b1..9b0f68d3 100644 --- a/ZSharp.Compiler.IR/ir/services/IR.Reference.cs +++ b/ZSharp.Compiler.IR/ir/services/IR.Reference.cs @@ -1,16 +1,11 @@ namespace ZSharp.Compiler { - partial class IR + partial struct IR { + public IIRReferenceCompiler ReferenceCompiler { get; set; } = Dispatcher.Instance; + public Result CompileReference(CompilerObject @object) where T : class - { - if (@object.Is>(out var compile)) - return compile.CompileIRReference(this); - - return Result.Error( - $"Cannot compile reference for object of type {@object}" - ); - } + => ReferenceCompiler.CompileReference(@object); } } diff --git a/ZSharp.Compiler.IR/ir/services/IR.Type.cs b/ZSharp.Compiler.IR/ir/services/IR.Type.cs index 1f6c3ea9..4a1523a3 100644 --- a/ZSharp.Compiler.IR/ir/services/IR.Type.cs +++ b/ZSharp.Compiler.IR/ir/services/IR.Type.cs @@ -1,21 +1,15 @@ namespace ZSharp.Compiler { - partial class IR + public delegate Result CompileType(CompilerObject @object); + + partial struct IR { - public Result CompileType(CompilerObject @object) - { - if (@object.Is(out var compile)) - return compile.CompileIRType(this); + public CompileType CompileType { get; set; } = Dispatcher.Instance.CompileType; - return Result.Error( - $"Cannot compile type for object of type {@object}" - ); - } + public IIRTypeCompiler TypeCompiler { get; set; } = Dispatcher.Instance; - public Result CompileType(CompilerObject @object) + public Result CompileTypeAs(CompilerObject @object) where T : class, IType - { - throw new NotImplementedException(); - } + => TypeCompiler.CompileType(@object); } } diff --git a/ZSharp.Compiler.IR/protocols/ICompileIRCode.cs b/ZSharp.Compiler.IR/protocols/ICompileIRCode.cs deleted file mode 100644 index 599d6960..00000000 --- a/ZSharp.Compiler.IR/protocols/ICompileIRCode.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICompileIRCode - { - public Result CompileIRCode(IR ir, TargetPlatform? target); - } -} diff --git a/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionAs.cs b/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionAs.cs deleted file mode 100644 index 4c198787..00000000 --- a/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionAs.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICompileIRDefinitionAs - where T : IRDefinition - { - public Result CompileIRDefinition(IR ir, TargetPlatform? target); - } -} diff --git a/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionIn.cs b/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionIn.cs deleted file mode 100644 index 70c7ecb1..00000000 --- a/ZSharp.Compiler.IR/protocols/ICompileIRDefinitionIn.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICompileIRDefinitionIn - where Owner : IRDefinition - { - public void CompileIRDefinition(IR ir, Owner owner, TargetPlatform? target); - } -} diff --git a/ZSharp.Compiler.IR/protocols/ICompileIRType.cs b/ZSharp.Compiler.IR/protocols/ICompileIRType.cs deleted file mode 100644 index e3e0eb29..00000000 --- a/ZSharp.Compiler.IR/protocols/ICompileIRType.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace ZSharp.Compiler -{ - public interface ICompileIRType - { - public Result CompileIRType(IR ir); - } - - public interface ICompileIRType - : ICompileIRType - where T : class, IType - { - Result ICompileIRType.CompileIRType(IR ir) - => CompileIRType(ir).When(type => type as IType); - - public new Result CompileIRType(IR ir); - } -} \ No newline at end of file diff --git a/ZSharp.Compiler.IR/protocols/IIRDefinitionAsCompiler.cs b/ZSharp.Compiler.IR/protocols/IIRDefinitionAsCompiler.cs new file mode 100644 index 00000000..37a0c331 --- /dev/null +++ b/ZSharp.Compiler.IR/protocols/IIRDefinitionAsCompiler.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IIRDefinitionAsCompiler + { + public Result CompileDefinition(CompilerObject @object, TargetPlatform? target) + where T : IRDefinition; + } +} diff --git a/ZSharp.Compiler.IR/protocols/IIRDefinitionInCompiler.cs b/ZSharp.Compiler.IR/protocols/IIRDefinitionInCompiler.cs new file mode 100644 index 00000000..995dc6d2 --- /dev/null +++ b/ZSharp.Compiler.IR/protocols/IIRDefinitionInCompiler.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IIRDefinitionInCompiler + { + public bool CompileDefinition(CompilerObject @object, Owner owner, TargetPlatform? target) + where Owner : IRDefinition; + } +} diff --git a/ZSharp.Compiler.IR/protocols/IIRReferenceCompiler.cs b/ZSharp.Compiler.IR/protocols/IIRReferenceCompiler.cs new file mode 100644 index 00000000..20f03a71 --- /dev/null +++ b/ZSharp.Compiler.IR/protocols/IIRReferenceCompiler.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IIRReferenceCompiler + { + public Result CompileReference(CompilerObject @object) + where T : class; + } +} diff --git a/ZSharp.Compiler.IR/protocols/IIRTypeCompiler.cs b/ZSharp.Compiler.IR/protocols/IIRTypeCompiler.cs new file mode 100644 index 00000000..871a9e7d --- /dev/null +++ b/ZSharp.Compiler.IR/protocols/IIRTypeCompiler.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + public interface IIRTypeCompiler + { + public Result CompileType(CompilerObject @object) + where T : class, IType; + } +} \ No newline at end of file diff --git a/ZSharp.Compiler.Overloading/GlobalUsings.cs b/ZSharp.Compiler.Overloading/GlobalUsings.cs new file mode 100644 index 00000000..c1bcb323 --- /dev/null +++ b/ZSharp.Compiler.Overloading/GlobalUsings.cs @@ -0,0 +1,4 @@ +global using MemberName = string; +global using MemberIndex = int; + +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj b/ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj index fa71b7ae..4e02b16d 100644 --- a/ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj +++ b/ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj @@ -6,4 +6,8 @@ enable + + + + diff --git a/ZSharp.Compiler.Overloading/dispatcher/Dispatcher.T.cs b/ZSharp.Compiler.Overloading/dispatcher/Dispatcher.T.cs new file mode 100644 index 00000000..30d2d580 --- /dev/null +++ b/ZSharp.Compiler.Overloading/dispatcher/Dispatcher.T.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result F(CompilerObject @object) + => Result.Error($"Object '{@object}' does not implement F"); + } +} diff --git a/ZSharp.Compiler.Overloading/dispatcher/Dispatcher.cs b/ZSharp.Compiler.Overloading/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..cd652665 --- /dev/null +++ b/ZSharp.Compiler.Overloading/dispatcher/Dispatcher.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler +{ + internal static partial class Dispatcher + { + } +} diff --git a/ZSharp.Compiler.Overloading/overloading/Overloading.cs b/ZSharp.Compiler.Overloading/overloading/Overloading.cs new file mode 100644 index 00000000..1a4058c4 --- /dev/null +++ b/ZSharp.Compiler.Overloading/overloading/Overloading.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public partial struct Overloading() + { + + } +} diff --git a/ZSharp.Compiler.Overloading/overloading/services/Overloading.T.cs b/ZSharp.Compiler.Overloading/overloading/services/Overloading.T.cs new file mode 100644 index 00000000..c1579bb6 --- /dev/null +++ b/ZSharp.Compiler.Overloading/overloading/services/Overloading.T.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public delegate Result F(CompilerObject callee); + + partial struct Overloading + { + public F CaFll { get; set; } = Dispatcher.F; + } +} diff --git a/ZSharp.Compiler.Reflection/GlobalUsings.cs b/ZSharp.Compiler.Reflection/GlobalUsings.cs new file mode 100644 index 00000000..c1bcb323 --- /dev/null +++ b/ZSharp.Compiler.Reflection/GlobalUsings.cs @@ -0,0 +1,4 @@ +global using MemberName = string; +global using MemberIndex = int; + +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.Reflection/ZSharp.Compiler.Reflection.csproj b/ZSharp.Compiler.Reflection/ZSharp.Compiler.Reflection.csproj new file mode 100644 index 00000000..4e02b16d --- /dev/null +++ b/ZSharp.Compiler.Reflection/ZSharp.Compiler.Reflection.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.GetCO.cs b/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.GetCO.cs new file mode 100644 index 00000000..7b917696 --- /dev/null +++ b/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.GetCO.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result GetCO(object @object) + { + if (@object is CompilerObject co) + return Result.Ok(co); + + return Result.Error( + $"Object [{@object}] does not support static reflection." + ); + } + } +} diff --git a/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.cs b/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..cd652665 --- /dev/null +++ b/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler +{ + internal static partial class Dispatcher + { + } +} diff --git a/ZSharp.Compiler.Reflection/reflection/Reflection.cs b/ZSharp.Compiler.Reflection/reflection/Reflection.cs new file mode 100644 index 00000000..2c128acc --- /dev/null +++ b/ZSharp.Compiler.Reflection/reflection/Reflection.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public partial struct Reflection() + { + + } +} diff --git a/ZSharp.Compiler.Reflection/reflection/services/Reflection.GetCO.cs b/ZSharp.Compiler.Reflection/reflection/services/Reflection.GetCO.cs new file mode 100644 index 00000000..aa6c09e1 --- /dev/null +++ b/ZSharp.Compiler.Reflection/reflection/services/Reflection.GetCO.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public delegate Result GetCO(object @object); + + partial struct Reflection + { + public GetCO GetCO { get; set; } = Dispatcher.GetCO; + } +} diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs index 067bd79c..8424533e 100644 --- a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Direct +namespace ZSharp.Compiler.CGDispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs index cfa3b09e..94eedb49 100644 --- a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Direct +namespace ZSharp.Compiler.CGDispatchers.Direct { partial class Dispatcher { diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs index fa510138..54a54457 100644 --- a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.Dispatchers.Direct +namespace ZSharp.Compiler.CGDispatchers.Direct { internal partial class Dispatcher(Compiler compiler) { diff --git a/ZSharp.Compiler/ZSharp.Compiler.csproj b/ZSharp.Compiler/ZSharp.Compiler.csproj index 28df3c3d..0f26ef2a 100644 --- a/ZSharp.Compiler/ZSharp.Compiler.csproj +++ b/ZSharp.Compiler/ZSharp.Compiler.csproj @@ -17,6 +17,8 @@ + + diff --git a/ZSharp.Compiler/compiler/Compiler.Services.cs b/ZSharp.Compiler/compiler/Compiler.Services.cs index 65c7d986..db0e0200 100644 --- a/ZSharp.Compiler/compiler/Compiler.Services.cs +++ b/ZSharp.Compiler/compiler/Compiler.Services.cs @@ -3,11 +3,16 @@ public sealed partial class Compiler { private CG cg; + private IR ir; + private Overloading overloading; + private Reflection reflection; private TS ts; public ref CG CG => ref cg; - public IR IR { get; } + public ref IR IR => ref ir; + + public ref Reflection Reflection => ref reflection; public ref TS TS => ref ts; diff --git a/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj b/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj index 18eb5ec3..469aa1d5 100644 --- a/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj +++ b/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj @@ -14,6 +14,7 @@ + diff --git a/ZSharp.Importer.ILLoader/il loader/ILLoader.Compiler.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.Compiler.cs new file mode 100644 index 00000000..1cc55c66 --- /dev/null +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.Compiler.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Importer.ILLoader +{ + partial class ILLoader + { + public Compiler.Compiler Compiler { get; } + + public ref Compiler.IR IR => ref Compiler.IR; + } +} diff --git a/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs index bbb63fc5..1f6b0f5f 100644 --- a/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs @@ -6,30 +6,29 @@ namespace ZSharp.Importer.ILLoader public sealed partial class ILLoader { [MaybeNull] - private ZSharp.IR.Function castFunction; + private IR.Function castFunction; - public Collection ExposeAsIR(T? obj) + public Collection ExposeAsIR(T? obj) => ExposeAsIR(obj, typeof(T)); - public Collection ExposeAsIR(object? obj) + public Collection ExposeAsIR(object? obj) => ExposeAsIR(obj, obj?.GetType() ?? typeof(object)); - public Collection ExposeAsIR(object? obj, Type type) + public Collection ExposeAsIR(object? obj, Type type) { var rt = RequireRuntime(); - var ir = RequireIR(); if (obj is null) return rt.Expose(null); var coType = LoadType(type); - var irType = ir.CompileType(coType).Unwrap(); + var irType = IR.CompileType(coType).Unwrap(); var code = rt.Expose(obj); - var function = new ZSharp.IR.GenericFunctionInstance(castFunction!); + var function = new IR.GenericFunctionInstance(castFunction!); function.Arguments.Add(irType); - code.Add(new ZSharp.IR.VM.Call(function)); + code.Add(new IR.VM.Call(function)); return code; } @@ -42,7 +41,7 @@ public CompilerObject Expose(object? obj) public CompilerObject Expose(object? obj, Type type) => new RawIRCode(new([.. ExposeAsIR(obj, type)]) { - Types = [RequireIR().CompileType(LoadType(type)).Unwrap()] + Types = [IR.CompileType(LoadType(type)).Unwrap()] }); public CompilerObject Expose(Delegate @delegate) @@ -63,7 +62,7 @@ private void SetupExposeSystem() { var rt = RequireRuntime(); - var castFunctionReturnType = new ZSharp.IR.GenericParameter("T"); + var castFunctionReturnType = new IR.GenericParameter("T"); castFunction = new(castFunctionReturnType); castFunction.GenericParameters.Add(castFunctionReturnType); castFunction.Signature.Args.Parameters.Add(new("obj", rt.TypeSystem.Object)); diff --git a/ZSharp.Importer.ILLoader/il loader/ILLoader.IR.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.IR.cs deleted file mode 100644 index 10f29d8b..00000000 --- a/ZSharp.Importer.ILLoader/il loader/ILLoader.IR.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Importer.ILLoader -{ - partial class ILLoader - { - public Compiler.IR? IR { get; } - - public Compiler.IR RequireIR() - => IR ?? throw new InvalidOperationException("ILLoader was not initialized with a Runtime"); - } -} diff --git a/ZSharp.Importer.ILLoader/il loader/ILLoader.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.cs index b37d56d0..20e9caa3 100644 --- a/ZSharp.Importer.ILLoader/il loader/ILLoader.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.cs @@ -2,9 +2,9 @@ { public sealed partial class ILLoader { - public ILLoader(Compiler.IR ir, Platform.Runtime.Runtime runtime) + public ILLoader(Compiler.Compiler compiler, Platform.Runtime.Runtime runtime) { - IR = ir; + Compiler = compiler; Runtime = runtime; TypeSystem = new() diff --git a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IR.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IR.cs index fbba7ba8..134ee9cb 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IR.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IR.cs @@ -2,14 +2,14 @@ { partial class Function { - private ZSharp.IR.Function? IR { get; set; } + private IR.Function? IR { get; set; } - private ZSharp.IR.Function GetIR() + private IR.Function GetIR() { if (IR is null) { var returnTypeCO = loader.LoadType(IL.ReturnType); - if (loader.RequireIR().CompileType(returnTypeCO).When(out var returnTypeIR).Error(out var error)) + if (loader.IR.CompileType(returnTypeCO).When(out var returnTypeIR).Error(out var error)) throw new InvalidOperationException($"Failed to load return type for method {IL.Name}: {error}"); IR = new(returnTypeIR!); loader.RequireRuntime().AddFunction(IR, IL); diff --git a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs index 6e808a21..48015685 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs @@ -9,10 +9,10 @@ partial class Class { private IR.Class? IR { get; set; } - Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.IR ir, object? target) + Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) => Result.Ok(GetIR()); - Result> ICompileIRType>.CompileIRType(Compiler.IR ir) + Result> ICompileIRType>.CompileIRType(Compiler.Compiler compiler) => Result>.Ok(new ClassReference(GetIR())); private IR.Class GetIR() diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.IR.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.IR.cs index 0a8ecd1b..63b6ceec 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.IR.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.IR.cs @@ -2,14 +2,14 @@ { partial class Method { - private ZSharp.IR.Method? IR { get; set; } + private IR.Method? IR { get; set; } - private ZSharp.IR.Method GetIR() + private IR.Method GetIR() { if (IR is null) { var returnTypeCO = Loader.LoadType(IL.ReturnType); - if (Loader.RequireIR().CompileType(returnTypeCO).When(out var returnTypeIR).Error(out var error)) + if (Loader.IR.CompileType(returnTypeCO).When(out var returnTypeIR).Error(out var error)) throw new InvalidOperationException($"Failed to load return type for method {IL.Name}: {error}"); IR = new(returnTypeIR!); Loader.RequireRuntime().AddFunction(IR.UnderlyingFunction, IL); diff --git a/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs b/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs index a6f101d7..e91c9c53 100644 --- a/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs @@ -9,7 +9,7 @@ public sealed class BooleanType(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs b/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs index dfb63029..653bd50e 100644 --- a/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs @@ -9,7 +9,7 @@ public sealed class CharType(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs index 55859bc9..63b2137c 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs @@ -9,7 +9,7 @@ public sealed class Float128Type(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs index 909cd240..1463ab51 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs @@ -9,7 +9,7 @@ public sealed class Float16Type(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs index 24c564d7..40ec3fc4 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs @@ -9,7 +9,7 @@ public sealed class Float32Type(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs index 852e3e83..56326fd4 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs @@ -9,7 +9,7 @@ public sealed class Float64Type(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/SInt16Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt16Type.cs index 865e4a74..000fe4fd 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/SInt16Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt16Type.cs @@ -9,7 +9,7 @@ public sealed class SInt16Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/SInt32Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt32Type.cs index cdadcb0e..2ad0aff0 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/SInt32Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt32Type.cs @@ -9,7 +9,7 @@ public sealed class SInt32Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/SInt64Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt64Type.cs index 95ee7852..004274a0 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/SInt64Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt64Type.cs @@ -9,7 +9,7 @@ public sealed class SInt64Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/SInt8Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt8Type.cs index f28dbff8..ed24cef8 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/SInt8Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt8Type.cs @@ -9,7 +9,7 @@ public sealed class SInt8Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/SIntNativeType.cs b/ZSharp.Importer.ILLoader/objects/types/int/SIntNativeType.cs index c79f9ee7..20ebc0f4 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/SIntNativeType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SIntNativeType.cs @@ -9,7 +9,7 @@ public sealed class SIntNativeType(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/UInt16Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt16Type.cs index 0f956987..9c2696e0 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/UInt16Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt16Type.cs @@ -9,7 +9,7 @@ public sealed class UInt16Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/UInt32Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt32Type.cs index 7f7f426c..d93b9e64 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/UInt32Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt32Type.cs @@ -9,7 +9,7 @@ public sealed class UInt32Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/UInt64Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt64Type.cs index 064f6894..a4bbf880 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/UInt64Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt64Type.cs @@ -9,7 +9,7 @@ public sealed class UInt64Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/UInt8Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt8Type.cs index 3945cab7..04add41d 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/UInt8Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt8Type.cs @@ -9,7 +9,7 @@ public sealed class UInt8Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/UIntNativeType.cs b/ZSharp.Importer.ILLoader/objects/types/int/UIntNativeType.cs index 76971f1a..0bdcca81 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/UIntNativeType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UIntNativeType.cs @@ -9,7 +9,7 @@ public sealed class UIntNativeType(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs b/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs index c1400016..c18d78eb 100644 --- a/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs @@ -9,7 +9,7 @@ public sealed class ObjectType(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs index 988a7b62..55eee271 100644 --- a/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs @@ -9,7 +9,7 @@ public sealed class StringType(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs b/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs index 1b0edb62..78f7455e 100644 --- a/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs @@ -9,7 +9,7 @@ public sealed class VoidType(OOPTypeReference type) { private readonly OOPTypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.IR ir) + Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Interpreter/interpreter/Interpreter.cs b/ZSharp.Interpreter/interpreter/Interpreter.cs index 3fe355fc..bce0183c 100644 --- a/ZSharp.Interpreter/interpreter/Interpreter.cs +++ b/ZSharp.Interpreter/interpreter/Interpreter.cs @@ -5,14 +5,10 @@ namespace ZSharp.Interpreter { public sealed partial class Interpreter { - //public Runtime.NET.Runtime Runtime { get; } - public IR.RuntimeModule RuntimeModule { get; } public Compiler.Compiler Compiler { get; } - public Compiler.IR IRCompiler { get; } - public Interpreter(IR.RuntimeModule? runtimeModule = null) { RuntimeModule = runtimeModule ?? IR.RuntimeModule.Standard; @@ -43,10 +39,7 @@ public Interpreter(IR.RuntimeModule? runtimeModule = null) UIntNative = null!, Void = RuntimeModule.TypeSystem.Void }); - IRCompiler = new(RuntimeModule); - ILLoader = new(Compiler.IR, Runtime); - - //new Ops(Compiler); + ILLoader = new(Compiler, Runtime); } public Result Evaluate(CompilerObject @object) diff --git a/ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj b/ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj index 0a663848..a4b30ac3 100644 --- a/ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj +++ b/ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj @@ -7,6 +7,7 @@ + diff --git a/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs b/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs index c09814d0..15144abe 100644 --- a/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs +++ b/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs @@ -3,13 +3,13 @@ partial class BooleanLiteral : ICompileIRCode { - Result ICompileIRCode.CompileIRCode(Compiler.IR ir, object? target) + Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) => Result.Ok( new([ new IR.VM.PutBoolean(value) ]) { - Types = [ir.RuntimeModule.TypeSystem.Boolean] + Types = [compiler.IR.RuntimeModule.TypeSystem.Boolean] } ); } diff --git a/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs b/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs index 1bc51ac4..08640738 100644 --- a/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs +++ b/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs @@ -3,13 +3,13 @@ partial class StringLiteral : ICompileIRCode { - Result ICompileIRCode.CompileIRCode(Compiler.IR ir, object? target) + Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) => Result.Ok( new([ new IR.VM.PutString(value) ]) { - Types = [ir.RuntimeModule.TypeSystem.String] + Types = [compiler.IR.RuntimeModule.TypeSystem.String] } ); } diff --git a/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj b/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj index 968109c9..381fcef5 100644 --- a/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj +++ b/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj @@ -17,6 +17,7 @@ + diff --git a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs index a0bd6b7d..118c05cc 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs @@ -9,11 +9,11 @@ partial class Global { public IR.Global? IR { get; private set; } - Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.IR ir, object? target) + Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) { if (IR is null) { - var typeResult = ir.CompileType(Type); + var typeResult = compiler.IR.CompileType(Type); if ( typeResult @@ -29,9 +29,9 @@ partial class Global return Result.Ok(IR); } - void ICompileIRDefinitionIn.CompileIRDefinition(Compiler.IR ir, IR.Module owner, object? target) + void ICompileIRDefinitionIn.CompileIRDefinition(Compiler.Compiler compiler, IR.Module owner, object? target) { - var result = ir.CompileDefinition(this, target); + var result = compiler.IR.CompileDefinition(this, target); if (result.IsError) return; From c5cf91873faf96c9823139c356be0e3e90545248 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 14 Sep 2025 21:48:34 +0300 Subject: [PATCH 213/235] Upgrade to .NET 9 --- CommonZ/CommonZ.csproj | 2 +- Testing/Testing.csproj | 2 +- ZSharp.AST/ZSharp.AST.csproj | 2 +- ZSharp.CLI/ZSharp.CLI.csproj | 2 +- ZSharp.Compiler.CG.Direct/ZSharp.Compiler.CG.Direct.csproj | 2 +- ZSharp.Compiler.CG.Proxy/ZSharp.Compiler.CG.Proxy.csproj | 2 +- ZSharp.Compiler.CG.Typed/ZSharp.Compiler.CG.Typed.csproj | 2 +- ZSharp.Compiler.CG/ZSharp.Compiler.CG.csproj | 2 +- ZSharp.Compiler.Context/ZSharp.Compiler.Context.csproj | 2 +- ZSharp.Compiler.Core/ZSharp.Compiler.Core.csproj | 2 +- ZSharp.Compiler.Features/ZSharp.Compiler.Features.csproj | 2 +- ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj | 2 +- ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj | 2 +- ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj | 2 +- ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj | 2 +- ZSharp.Compiler.Reflection/ZSharp.Compiler.Reflection.csproj | 2 +- ZSharp.Compiler.TS.Static/ZSharp.Compiler.TS.Static.csproj | 2 +- ZSharp.Compiler.TS/ZSharp.Compiler.TS.csproj | 2 +- ZSharp.Compiler/ZSharp.Compiler.csproj | 2 +- ZSharp.IR/ZSharp.IR.csproj | 2 +- .../ZSharp.Importer.ILLoader.Attributes.csproj | 2 +- ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj | 2 +- ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj | 2 +- ZSharp.Interpreter/ZSharp.Interpreter.csproj | 2 +- .../ZSharp.Library.Standard.FileSystem.csproj | 2 +- ZSharp.Library.Standard.IO/ZSharp.Library.Standard.IO.csproj | 2 +- .../ZSharp.Library.Standard.Math.csproj | 2 +- ZSharp.Logging/ZSharp.Logging.csproj | 2 +- ZSharp.Parser/ZSharp.Parser.csproj | 2 +- ZSharp.Platform.IL/ZSharp.Platform.IL.csproj | 2 +- ZSharp.Platform.Runtime/ZSharp.Platform.Runtime.csproj | 2 +- .../ZSharp.SourceCompiler.Common.csproj | 2 +- ZSharp.SourceCompiler.Core/ZSharp.SourceCompiler.Core.csproj | 2 +- .../ZSharp.SourceCompiler.Module.csproj | 2 +- .../ZSharp.SourceCompiler.Project.csproj | 2 +- .../ZSharp.SourceCompiler.Script.csproj | 2 +- ZSharp.Text/ZSharp.Text.csproj | 2 +- ZSharp.Tokenizer/ZSharp.Tokenizer.csproj | 2 +- 38 files changed, 38 insertions(+), 38 deletions(-) diff --git a/CommonZ/CommonZ.csproj b/CommonZ/CommonZ.csproj index 30402ac0..0d2df0d1 100644 --- a/CommonZ/CommonZ.csproj +++ b/CommonZ/CommonZ.csproj @@ -1,7 +1,7 @@ - net8.0 + net9.0 enable enable diff --git a/Testing/Testing.csproj b/Testing/Testing.csproj index 7a1bad7a..4f8e16a7 100644 --- a/Testing/Testing.csproj +++ b/Testing/Testing.csproj @@ -2,7 +2,7 @@ Exe - net8.0 + net9.0 enable enable diff --git a/ZSharp.AST/ZSharp.AST.csproj b/ZSharp.AST/ZSharp.AST.csproj index 9e4f679a..a11d0188 100644 --- a/ZSharp.AST/ZSharp.AST.csproj +++ b/ZSharp.AST/ZSharp.AST.csproj @@ -1,7 +1,7 @@ - net8.0 + net9.0 enable enable diff --git a/ZSharp.CLI/ZSharp.CLI.csproj b/ZSharp.CLI/ZSharp.CLI.csproj index 6ba2582b..7371fc6a 100644 --- a/ZSharp.CLI/ZSharp.CLI.csproj +++ b/ZSharp.CLI/ZSharp.CLI.csproj @@ -2,7 +2,7 @@ Exe - net8.0 + net9.0 enable enable zs diff --git a/ZSharp.Compiler.CG.Direct/ZSharp.Compiler.CG.Direct.csproj b/ZSharp.Compiler.CG.Direct/ZSharp.Compiler.CG.Direct.csproj index 29b16973..2469cf2f 100644 --- a/ZSharp.Compiler.CG.Direct/ZSharp.Compiler.CG.Direct.csproj +++ b/ZSharp.Compiler.CG.Direct/ZSharp.Compiler.CG.Direct.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Compiler.CG.Proxy/ZSharp.Compiler.CG.Proxy.csproj b/ZSharp.Compiler.CG.Proxy/ZSharp.Compiler.CG.Proxy.csproj index 29b16973..2469cf2f 100644 --- a/ZSharp.Compiler.CG.Proxy/ZSharp.Compiler.CG.Proxy.csproj +++ b/ZSharp.Compiler.CG.Proxy/ZSharp.Compiler.CG.Proxy.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Compiler.CG.Typed/ZSharp.Compiler.CG.Typed.csproj b/ZSharp.Compiler.CG.Typed/ZSharp.Compiler.CG.Typed.csproj index 29b16973..2469cf2f 100644 --- a/ZSharp.Compiler.CG.Typed/ZSharp.Compiler.CG.Typed.csproj +++ b/ZSharp.Compiler.CG.Typed/ZSharp.Compiler.CG.Typed.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Compiler.CG/ZSharp.Compiler.CG.csproj b/ZSharp.Compiler.CG/ZSharp.Compiler.CG.csproj index be4a9954..873c5245 100644 --- a/ZSharp.Compiler.CG/ZSharp.Compiler.CG.csproj +++ b/ZSharp.Compiler.CG/ZSharp.Compiler.CG.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable ZSharp.Compiler diff --git a/ZSharp.Compiler.Context/ZSharp.Compiler.Context.csproj b/ZSharp.Compiler.Context/ZSharp.Compiler.Context.csproj index 4e102195..de110900 100644 --- a/ZSharp.Compiler.Context/ZSharp.Compiler.Context.csproj +++ b/ZSharp.Compiler.Context/ZSharp.Compiler.Context.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable ZSharp.Compiler diff --git a/ZSharp.Compiler.Core/ZSharp.Compiler.Core.csproj b/ZSharp.Compiler.Core/ZSharp.Compiler.Core.csproj index 055aa435..1884a869 100644 --- a/ZSharp.Compiler.Core/ZSharp.Compiler.Core.csproj +++ b/ZSharp.Compiler.Core/ZSharp.Compiler.Core.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Compiler.Features/ZSharp.Compiler.Features.csproj b/ZSharp.Compiler.Features/ZSharp.Compiler.Features.csproj index 7e575a54..01691937 100644 --- a/ZSharp.Compiler.Features/ZSharp.Compiler.Features.csproj +++ b/ZSharp.Compiler.Features/ZSharp.Compiler.Features.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj b/ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj index 7e575a54..01691937 100644 --- a/ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj +++ b/ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj b/ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj index dd8b2233..056a1118 100644 --- a/ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj +++ b/ZSharp.Compiler.IR/ZSharp.Compiler.IR.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable ZSharp.IRCompiler diff --git a/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj b/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj index 9f6c481e..04a2cd82 100644 --- a/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj +++ b/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable ZSharp.Objects diff --git a/ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj b/ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj index 4e02b16d..a46878d7 100644 --- a/ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj +++ b/ZSharp.Compiler.Overloading/ZSharp.Compiler.Overloading.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Compiler.Reflection/ZSharp.Compiler.Reflection.csproj b/ZSharp.Compiler.Reflection/ZSharp.Compiler.Reflection.csproj index 4e02b16d..a46878d7 100644 --- a/ZSharp.Compiler.Reflection/ZSharp.Compiler.Reflection.csproj +++ b/ZSharp.Compiler.Reflection/ZSharp.Compiler.Reflection.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Compiler.TS.Static/ZSharp.Compiler.TS.Static.csproj b/ZSharp.Compiler.TS.Static/ZSharp.Compiler.TS.Static.csproj index 7e575a54..01691937 100644 --- a/ZSharp.Compiler.TS.Static/ZSharp.Compiler.TS.Static.csproj +++ b/ZSharp.Compiler.TS.Static/ZSharp.Compiler.TS.Static.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Compiler.TS/ZSharp.Compiler.TS.csproj b/ZSharp.Compiler.TS/ZSharp.Compiler.TS.csproj index c88af84b..466792ff 100644 --- a/ZSharp.Compiler.TS/ZSharp.Compiler.TS.csproj +++ b/ZSharp.Compiler.TS/ZSharp.Compiler.TS.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Compiler/ZSharp.Compiler.csproj b/ZSharp.Compiler/ZSharp.Compiler.csproj index 0f26ef2a..c1d33bba 100644 --- a/ZSharp.Compiler/ZSharp.Compiler.csproj +++ b/ZSharp.Compiler/ZSharp.Compiler.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.IR/ZSharp.IR.csproj b/ZSharp.IR/ZSharp.IR.csproj index 055aa435..1884a869 100644 --- a/ZSharp.IR/ZSharp.IR.csproj +++ b/ZSharp.IR/ZSharp.IR.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Importer.ILLoader.Attributes/ZSharp.Importer.ILLoader.Attributes.csproj b/ZSharp.Importer.ILLoader.Attributes/ZSharp.Importer.ILLoader.Attributes.csproj index 3bbf45a4..e2374d98 100644 --- a/ZSharp.Importer.ILLoader.Attributes/ZSharp.Importer.ILLoader.Attributes.csproj +++ b/ZSharp.Importer.ILLoader.Attributes/ZSharp.Importer.ILLoader.Attributes.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable ZSharp.Importer.ILLoader diff --git a/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj b/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj index 469aa1d5..5eea8633 100644 --- a/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj +++ b/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj b/ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj index 28901a0d..cdc18594 100644 --- a/ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj +++ b/ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Interpreter/ZSharp.Interpreter.csproj b/ZSharp.Interpreter/ZSharp.Interpreter.csproj index bf462573..353b70e9 100644 --- a/ZSharp.Interpreter/ZSharp.Interpreter.csproj +++ b/ZSharp.Interpreter/ZSharp.Interpreter.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Library.Standard.FileSystem/ZSharp.Library.Standard.FileSystem.csproj b/ZSharp.Library.Standard.FileSystem/ZSharp.Library.Standard.FileSystem.csproj index a7c03949..cb3df907 100644 --- a/ZSharp.Library.Standard.FileSystem/ZSharp.Library.Standard.FileSystem.csproj +++ b/ZSharp.Library.Standard.FileSystem/ZSharp.Library.Standard.FileSystem.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable Standard.FileSystem diff --git a/ZSharp.Library.Standard.IO/ZSharp.Library.Standard.IO.csproj b/ZSharp.Library.Standard.IO/ZSharp.Library.Standard.IO.csproj index a91e61d8..b54aaff8 100644 --- a/ZSharp.Library.Standard.IO/ZSharp.Library.Standard.IO.csproj +++ b/ZSharp.Library.Standard.IO/ZSharp.Library.Standard.IO.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Library.Standard.Math/ZSharp.Library.Standard.Math.csproj b/ZSharp.Library.Standard.Math/ZSharp.Library.Standard.Math.csproj index a91e61d8..b54aaff8 100644 --- a/ZSharp.Library.Standard.Math/ZSharp.Library.Standard.Math.csproj +++ b/ZSharp.Library.Standard.Math/ZSharp.Library.Standard.Math.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Logging/ZSharp.Logging.csproj b/ZSharp.Logging/ZSharp.Logging.csproj index fa71b7ae..125f4c93 100644 --- a/ZSharp.Logging/ZSharp.Logging.csproj +++ b/ZSharp.Logging/ZSharp.Logging.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Parser/ZSharp.Parser.csproj b/ZSharp.Parser/ZSharp.Parser.csproj index 4504d1e5..4ee05270 100644 --- a/ZSharp.Parser/ZSharp.Parser.csproj +++ b/ZSharp.Parser/ZSharp.Parser.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Platform.IL/ZSharp.Platform.IL.csproj b/ZSharp.Platform.IL/ZSharp.Platform.IL.csproj index 215be2da..2cc6cd1f 100644 --- a/ZSharp.Platform.IL/ZSharp.Platform.IL.csproj +++ b/ZSharp.Platform.IL/ZSharp.Platform.IL.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Platform.Runtime/ZSharp.Platform.Runtime.csproj b/ZSharp.Platform.Runtime/ZSharp.Platform.Runtime.csproj index e0c87377..9b9ccdd2 100644 --- a/ZSharp.Platform.Runtime/ZSharp.Platform.Runtime.csproj +++ b/ZSharp.Platform.Runtime/ZSharp.Platform.Runtime.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj b/ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj index a4b30ac3..f7aac97a 100644 --- a/ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj +++ b/ZSharp.SourceCompiler.Common/ZSharp.SourceCompiler.Common.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.SourceCompiler.Core/ZSharp.SourceCompiler.Core.csproj b/ZSharp.SourceCompiler.Core/ZSharp.SourceCompiler.Core.csproj index 13363715..332419c5 100644 --- a/ZSharp.SourceCompiler.Core/ZSharp.SourceCompiler.Core.csproj +++ b/ZSharp.SourceCompiler.Core/ZSharp.SourceCompiler.Core.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable ZSharp.SourceCompiler diff --git a/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj b/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj index 381fcef5..c5684fe8 100644 --- a/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj +++ b/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj b/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj index 0410f51d..7e223a09 100644 --- a/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj +++ b/ZSharp.SourceCompiler.Project/ZSharp.SourceCompiler.Project.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 disable enable diff --git a/ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj b/ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj index 85ac50cf..1fd34d36 100644 --- a/ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj +++ b/ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable diff --git a/ZSharp.Text/ZSharp.Text.csproj b/ZSharp.Text/ZSharp.Text.csproj index 30402ac0..0d2df0d1 100644 --- a/ZSharp.Text/ZSharp.Text.csproj +++ b/ZSharp.Text/ZSharp.Text.csproj @@ -1,7 +1,7 @@ - net8.0 + net9.0 enable enable diff --git a/ZSharp.Tokenizer/ZSharp.Tokenizer.csproj b/ZSharp.Tokenizer/ZSharp.Tokenizer.csproj index e3635754..1c21fabe 100644 --- a/ZSharp.Tokenizer/ZSharp.Tokenizer.csproj +++ b/ZSharp.Tokenizer/ZSharp.Tokenizer.csproj @@ -1,7 +1,7 @@  - net8.0 + net9.0 enable enable From ffebfc4b8f8cf3394b903fd715fe9ba907a6dbf4 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Mon, 15 Sep 2025 02:09:04 +0300 Subject: [PATCH 214/235] This should do it --- ZSharp.AST/nodes/leaf/IdentifierExpression.cs | 10 +- ZSharp.AST/nodes/leaf/IdentifierTokens.cs | 9 + ZSharp.CLI/Program.cs | 349 +++++++++--------- ZSharp.Compiler/compiler/Compiler.Services.cs | 2 +- ZSharp.Compiler/compiler/Compiler.cs | 7 +- .../il loader/ExposedObjectWrapper.cs | 11 + .../il loader/ILLoader.Expose.cs | 7 +- ZSharp.Interpreter/interpreter/Interpreter.cs | 8 +- .../context/DebuggableEvaluationContext.cs | 105 ++++++ .../context/ExecutionEvaluationContext.cs | 30 ++ .../loader/context/IEvaluationContext.cs | 11 + .../DebuggableEvaluationContextFactory.cs | 17 + .../ExecutionEvaluationContextFactory.cs | 24 ++ .../factories/IEvaluationContextFactory.cs | 7 + .../loader/emit/EmitLoader.Standalone.cs | 4 +- .../loader/emit/EmitLoader.cs | 27 +- .../loader/emit/load/EmitLoader.Load.Code.cs | 15 +- .../code/code contexts/UnboundCodeContext.cs | 7 +- .../loader/loaders/code/code/CodeCompiler.cs | 18 +- .../loaders/code/code/core/ICodeContext.cs | 2 +- .../loader/loaders/code/code/core/IContext.cs | 11 + .../code/code/debugging/IDebuggableContext.cs | 10 + .../code/code/debugging/SourceLocation.cs | 13 + .../runtime/Runtime.Evaluate.cs | 13 +- .../runtime/Runtime.Loader.cs | 4 +- ZSharp.Platform.Runtime/runtime/Runtime.cs | 13 +- .../ZSharp.SourceCompiler.Script.csproj | 1 + .../compiler/ScriptCompiler.Debugging.cs | 27 ++ .../compiler/ScriptCompiler.cs | 12 +- .../expr/ScriptCompiler.Compile.Identifier.cs | 2 +- .../stmt/ScriptCompiler.Compile.Expression.cs | 2 +- .../stmt/ScriptCompiler.Compile.Import.cs | 23 +- .../objects/ExpressionWrapper.cs | 48 +++ .../objects/IdentifierBoundObject.cs | 49 +++ .../runtime contexts/DebuggingContext.cs | 19 + 35 files changed, 708 insertions(+), 209 deletions(-) create mode 100644 ZSharp.AST/nodes/leaf/IdentifierTokens.cs create mode 100644 ZSharp.Importer.ILLoader/il loader/ExposedObjectWrapper.cs create mode 100644 ZSharp.Platform.Runtime/loader/context/DebuggableEvaluationContext.cs create mode 100644 ZSharp.Platform.Runtime/loader/context/ExecutionEvaluationContext.cs create mode 100644 ZSharp.Platform.Runtime/loader/context/IEvaluationContext.cs create mode 100644 ZSharp.Platform.Runtime/loader/context/factories/DebuggableEvaluationContextFactory.cs create mode 100644 ZSharp.Platform.Runtime/loader/context/factories/ExecutionEvaluationContextFactory.cs create mode 100644 ZSharp.Platform.Runtime/loader/context/factories/IEvaluationContextFactory.cs create mode 100644 ZSharp.Platform.Runtime/loader/loaders/code/code/core/IContext.cs create mode 100644 ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/IDebuggableContext.cs create mode 100644 ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/SourceLocation.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Debugging.cs create mode 100644 ZSharp.SourceCompiler.Script/objects/ExpressionWrapper.cs create mode 100644 ZSharp.SourceCompiler.Script/objects/IdentifierBoundObject.cs create mode 100644 ZSharp.SourceCompiler.Script/runtime contexts/DebuggingContext.cs diff --git a/ZSharp.AST/nodes/leaf/IdentifierExpression.cs b/ZSharp.AST/nodes/leaf/IdentifierExpression.cs index 4a0af27d..25ad53a8 100644 --- a/ZSharp.AST/nodes/leaf/IdentifierExpression.cs +++ b/ZSharp.AST/nodes/leaf/IdentifierExpression.cs @@ -1,7 +1,13 @@ namespace ZSharp.AST { - public class IdentifierExpression(string name) : Expression + public class IdentifierExpression(IdentifierTokens tokens) : Expression { - public string Name { get; set; } = name; + public new IdentifierTokens TokenInfo + { + get => As(); + init => base.TokenInfo = value; + } + + public string Name { get; set; } = tokens.Identifier.Value; } } diff --git a/ZSharp.AST/nodes/leaf/IdentifierTokens.cs b/ZSharp.AST/nodes/leaf/IdentifierTokens.cs new file mode 100644 index 00000000..a698bfbf --- /dev/null +++ b/ZSharp.AST/nodes/leaf/IdentifierTokens.cs @@ -0,0 +1,9 @@ +using ZSharp.Text; + +namespace ZSharp.AST +{ + public sealed class IdentifierTokens(Token identifier) : TokenInfo + { + public Token Identifier { get; } = identifier; + } +} diff --git a/ZSharp.CLI/Program.cs b/ZSharp.CLI/Program.cs index e0c398d1..8863ba27 100644 --- a/ZSharp.CLI/Program.cs +++ b/ZSharp.CLI/Program.cs @@ -13,201 +13,202 @@ if (filePath is null) { interpreter.Log.Error("Missing input file path argument.", new CLIArgumentLogOrigin("")); + + return; } -else + +#region Parsing + +ZSharp.AST.Document documentNode; +using (StreamReader stream = File.OpenText(filePath)) { - #region Parsing - - ZSharp.AST.Document documentNode; - using (StreamReader stream = File.OpenText(filePath)) - { - var zsharpParser = new ZSharpParser(); - var parser = new Parser(Tokenizer.Tokenize(new(stream))); - - var expressionParser = zsharpParser.Expression; - var statementParser = zsharpParser.Statement; - - expressionParser.Terminal( - TokenType.String, - token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.String) - ); - expressionParser.Terminal( - TokenType.Number, - token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Number) - ); - expressionParser.Terminal( - TokenType.Decimal, - token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Decimal) - ); - expressionParser.Terminal( - TokenType.Identifier, - token => token.Value switch - { - "null" => ZSharp.AST.LiteralExpression.Null(), - "true" => ZSharp.AST.LiteralExpression.True(), - "false" => ZSharp.AST.LiteralExpression.False(), - _ => new ZSharp.AST.IdentifierExpression(token.Value), - } - ); - expressionParser.Nud( - TokenType.LParen, - parser => - { - parser.Eat(TokenType.LParen); - var expression = parser.Parse(); - parser.Eat(TokenType.RParen); - - return expression; - }, - 10000 - ); - expressionParser.Nud( - LangParser.Keywords.Let, - LangParser.ParseLetExpression - ); - expressionParser.Nud( - LangParser.Keywords.Class, - zsharpParser.Class.Parse - ); - - expressionParser.InfixR("=", 10); - expressionParser.InfixL("<", 20); - expressionParser.InfixL("+", 50); - expressionParser.InfixL("-", 50); - expressionParser.InfixL("*", 70); - expressionParser.InfixL("/", 70); - expressionParser.InfixL("**", 80); - - expressionParser.InfixL("==", 30); - expressionParser.InfixL("!=", 30); - - expressionParser.InfixL(LangParser.Keywords.Or, 15); - - expressionParser.Led(TokenType.LParen, LangParser.ParseCallExpression, 100); - expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); - expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); - expressionParser.Led(".", LangParser.ParseMemberAccess, 150); - expressionParser.Led(LangParser.Keywords.As, LangParser.ParseCastExpression, 20); - expressionParser.Led(LangParser.Keywords.Is, LangParser.ParseIsOfExpression, 20); - - expressionParser.Separator(TokenType.Comma); - expressionParser.Separator(TokenType.RParen); - expressionParser.Separator(TokenType.RBracket); - expressionParser.Separator(TokenType.Semicolon); - - expressionParser.Separator(LangParser.Keywords.In); // until it's an operator - - expressionParser.AddKeywordParser( - LangParser.Keywords.While, - LangParser.ParseWhileExpression - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.While, - Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.If, - LangParser.ParseIfStatement - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.For, - LangParser.ParseForStatement - ); - - statementParser.AddKeywordParser( - LangParser.Keywords.Case, - LangParser.ParseCaseStatement - ); - - zsharpParser.Document.AddKeywordParser( - LangParser.Keywords.If, - LangParser.ParseIfStatement - ); - - //zsharpParser.Function.AddKeywordParser( - // LangParser.Keywords.While, - // Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) - //); - - zsharpParser.RegisterParsers(parser); - documentNode = zsharpParser.Parse(parser); - - Console.WriteLine($"Finished parsing document with {documentNode.Statements.Count} statements!"); - } - - #endregion - - #region Setup Interpreter - - new ZSharp.Compiler.CGDispatchers.Direct.Dispatcher(interpreter.Compiler).Apply(); - new ZSharp.Compiler.CGDispatchers.Typed.Dispatcher(interpreter.Compiler).Apply(); - new ZSharp.Compiler.CGDispatchers.Proxy.Dispatcher(interpreter.Compiler).Apply(); - - new ZSharp.Compiler.IRDispatchers.Static.Dispatcher(interpreter.Compiler).Apply(); - - var scriptCompiler = new ScriptCompiler(interpreter, documentNode); - - interpreter.ILLoader.OnLoadOperator = (@operator, method) => - { - interpreter.Log.Warning( - $"Skip loading operator {@operator} ({method.GetParameters().Length} parameters)" + - $"because overloading is not implemented yet", - ZSCScriptLogOrigin.Instance - ); - //scriptCompiler.Context.Operators.Op(@operator.Operator, interpreter.ILLoader.LoadMethod(method)); - }; - - #region Import System - - var stringImporter = new StringImporter(); - - scriptCompiler.Context.ImportSystem.ImportFunction = interpreter.ILLoader.Expose( - (Delegate)( - (string source) => stringImporter.Import(source).Unwrap() as object - ) + var zsharpParser = new ZSharpParser(); + var parser = new Parser(Tokenizer.Tokenize(new(stream))); + + var expressionParser = zsharpParser.Expression; + var statementParser = zsharpParser.Statement; + + expressionParser.Terminal( + TokenType.String, + token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.String) + ); + expressionParser.Terminal( + TokenType.Number, + token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Number) + ); + expressionParser.Terminal( + TokenType.Decimal, + token => new ZSharp.AST.LiteralExpression(token.Value, ZSharp.AST.LiteralType.Decimal) + ); + expressionParser.Terminal( + TokenType.Identifier, + token => token.Value switch + { + "null" => ZSharp.AST.LiteralExpression.Null(), + "true" => ZSharp.AST.LiteralExpression.True(), + "false" => ZSharp.AST.LiteralExpression.False(), + _ => new ZSharp.AST.IdentifierExpression(new(token)), + } + ); + expressionParser.Nud( + TokenType.LParen, + parser => + { + parser.Eat(TokenType.LParen); + var expression = parser.Parse(); + parser.Eat(TokenType.RParen); + + return expression; + }, + 10000 + ); + expressionParser.Nud( + LangParser.Keywords.Let, + LangParser.ParseLetExpression + ); + expressionParser.Nud( + LangParser.Keywords.Class, + zsharpParser.Class.Parse ); - #endregion + expressionParser.InfixR("=", 10); + expressionParser.InfixL("<", 20); + expressionParser.InfixL("+", 50); + expressionParser.InfixL("-", 50); + expressionParser.InfixL("*", 70); + expressionParser.InfixL("/", 70); + expressionParser.InfixL("**", 80); - #region Importers + expressionParser.InfixL("==", 30); + expressionParser.InfixL("!=", 30); - #region Core Library + expressionParser.InfixL(LangParser.Keywords.Or, 15); - var coreImporter = new CoreLibraryImporter(); - stringImporter.RegisterImporter("core", coreImporter); + expressionParser.Led(TokenType.LParen, LangParser.ParseCallExpression, 100); + expressionParser.Led(TokenType.LBracket, LangParser.ParseIndexExpression, 100); + expressionParser.Nud(TokenType.LBracket, LangParser.ParseArrayLiteral); + expressionParser.Led(".", LangParser.ParseMemberAccess, 150); + expressionParser.Led(LangParser.Keywords.As, LangParser.ParseCastExpression, 20); + expressionParser.Led(LangParser.Keywords.Is, LangParser.ParseIsOfExpression, 20); - #endregion + expressionParser.Separator(TokenType.Comma); + expressionParser.Separator(TokenType.RParen); + expressionParser.Separator(TokenType.RBracket); + expressionParser.Separator(TokenType.Semicolon); - #region Standard Library + expressionParser.Separator(LangParser.Keywords.In); // until it's an operator - var stdImporter = new StandardLibraryImporter(); - stringImporter.RegisterImporter("std", stdImporter); + expressionParser.AddKeywordParser( + LangParser.Keywords.While, + LangParser.ParseWhileExpression + ); - stdImporter.Add( - "io", - interpreter.ILLoader.LoadModule(typeof(Standard.IO.ModuleScope).Module) + statementParser.AddKeywordParser( + LangParser.Keywords.While, + Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) ); - stdImporter.Add( - "fs", - interpreter.ILLoader.LoadModule(typeof(Standard.FileSystem.ModuleScope).Module) + + statementParser.AddKeywordParser( + LangParser.Keywords.If, + LangParser.ParseIfStatement ); - #endregion + statementParser.AddKeywordParser( + LangParser.Keywords.For, + LangParser.ParseForStatement + ); - #endregion + statementParser.AddKeywordParser( + LangParser.Keywords.Case, + LangParser.ParseCaseStatement + ); - #endregion + zsharpParser.Document.AddKeywordParser( + LangParser.Keywords.If, + LangParser.ParseIfStatement + ); - #region Compilation + //zsharpParser.Function.AddKeywordParser( + // LangParser.Keywords.While, + // Utils.ExpressionStatement(LangParser.ParseWhileExpression, semicolon: false) + //); - scriptCompiler.Compile(); + zsharpParser.RegisterParsers(parser); + documentNode = zsharpParser.Parse(parser); - #endregion + Console.WriteLine($"Finished parsing document with {documentNode.Statements.Count} statements!"); } +#endregion + +#region Setup Interpreter + +new ZSharp.Compiler.CGDispatchers.Direct.Dispatcher(interpreter.Compiler).Apply(); +new ZSharp.Compiler.CGDispatchers.Typed.Dispatcher(interpreter.Compiler).Apply(); +new ZSharp.Compiler.CGDispatchers.Proxy.Dispatcher(interpreter.Compiler).Apply(); + +new ZSharp.Compiler.IRDispatchers.Static.Dispatcher(interpreter.Compiler).Apply(); + +var scriptCompiler = new ScriptCompiler(interpreter, documentNode, filePath); + +interpreter.ILLoader.OnLoadOperator = (@operator, method) => +{ + interpreter.Log.Warning( + $"Skip loading operator {@operator} ({method.GetParameters().Length} parameters)" + + $"because overloading is not implemented yet", + ZSCScriptLogOrigin.Instance + ); + //scriptCompiler.Context.Operators.Op(@operator.Operator, interpreter.ILLoader.LoadMethod(method)); +}; + +#region Import System + +var stringImporter = new StringImporter(); + +scriptCompiler.Context.ImportSystem.ImportFunction = interpreter.ILLoader.Expose( + (Delegate)( + (string source) => stringImporter.Import(source).Unwrap() as object + ) +); + +#endregion + +#region Importers + +#region Core Library + +var coreImporter = new CoreLibraryImporter(); +stringImporter.RegisterImporter("core", coreImporter); + +#endregion + +#region Standard Library + +var stdImporter = new StandardLibraryImporter(); +stringImporter.RegisterImporter("std", stdImporter); + +stdImporter.Add( + "io", + interpreter.ILLoader.LoadModule(typeof(Standard.IO.ModuleScope).Module) +); +stdImporter.Add( + "fs", + interpreter.ILLoader.LoadModule(typeof(Standard.FileSystem.ModuleScope).Module) +); + +#endregion + +#endregion + +#endregion + +#region Compilation + +scriptCompiler.Compile(); + +#endregion + + Console.WriteLine(); foreach (var log in interpreter.Log.Logs) diff --git a/ZSharp.Compiler/compiler/Compiler.Services.cs b/ZSharp.Compiler/compiler/Compiler.Services.cs index db0e0200..686e48a8 100644 --- a/ZSharp.Compiler/compiler/Compiler.Services.cs +++ b/ZSharp.Compiler/compiler/Compiler.Services.cs @@ -16,6 +16,6 @@ public sealed partial class Compiler public ref TS TS => ref ts; - public TS TypeSystem { init => ts = value; } + //public TS TypeSystem { init => ts = value; } } } diff --git a/ZSharp.Compiler/compiler/Compiler.cs b/ZSharp.Compiler/compiler/Compiler.cs index 0a4eb4fd..287c5a93 100644 --- a/ZSharp.Compiler/compiler/Compiler.cs +++ b/ZSharp.Compiler/compiler/Compiler.cs @@ -11,8 +11,11 @@ public Compiler(ZSharp.IR.RuntimeModule runtimeModule) { RuntimeModule = runtimeModule; - CG = new(); - IR = new(runtimeModule); + cg = new(); + ir = new(runtimeModule); + ts = new(); + overloading = new(); + reflection = new(); } } } diff --git a/ZSharp.Importer.ILLoader/il loader/ExposedObjectWrapper.cs b/ZSharp.Importer.ILLoader/il loader/ExposedObjectWrapper.cs new file mode 100644 index 00000000..4c3f9371 --- /dev/null +++ b/ZSharp.Importer.ILLoader/il loader/ExposedObjectWrapper.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Importer.ILLoader +{ + public sealed class ExposedObjectWrapper(object? target, IL.MethodInfo method) + { + private readonly object? target = target; + private readonly IL.MethodInfo method = method; + + public object? Invoke(object? args) + => method.Invoke(target, [args]); + } +} diff --git a/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs index 1f6b0f5f..0d1d9717 100644 --- a/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs @@ -46,8 +46,11 @@ public CompilerObject Expose(object? obj, Type type) public CompilerObject Expose(Delegate @delegate) { - var methodCO = LoadMethod(@delegate.Method); - var @object = ExposeAsIR(@delegate.Target); + var wrapped = new ExposedObjectWrapper(@delegate.Target, @delegate.Method); + // TODO: Cache this method info + // TODO: Add support for array. Currently not supported because there's no make-array instruction in IR + var methodCO = LoadMethod(typeof(ExposedObjectWrapper).GetMethod("Invoke", [typeof(object)]) ?? throw new()); + var @object = ExposeAsIR(wrapped); var objectCode = new RawIRCode(new(@object)); return new Objects.BoundMethod() diff --git a/ZSharp.Interpreter/interpreter/Interpreter.cs b/ZSharp.Interpreter/interpreter/Interpreter.cs index bce0183c..9fabc01e 100644 --- a/ZSharp.Interpreter/interpreter/Interpreter.cs +++ b/ZSharp.Interpreter/interpreter/Interpreter.cs @@ -42,7 +42,11 @@ public Interpreter(IR.RuntimeModule? runtimeModule = null) ILLoader = new(Compiler, Runtime); } - public Result Evaluate(CompilerObject @object) + public Result Evaluate( + CompilerObject @object, + Platform.Runtime.IEvaluationContext? evaluationContext = null, + Platform.Runtime.Loaders.IContext? codeContext = null + ) { if ( Compiler.IR.CompileCode(@object, Runtime) @@ -53,7 +57,7 @@ public Interpreter(IR.RuntimeModule? runtimeModule = null) var type = irCode!.IsVoid ? RuntimeModule.TypeSystem.Void : irCode.RequireValueType(); - var result = Runtime.Evaluate(irCode.Instructions, type); + var result = Runtime.Evaluate(irCode.Instructions, type, evaluationContext, codeContext); if (irCode.IsVoid) return Result diff --git a/ZSharp.Platform.Runtime/loader/context/DebuggableEvaluationContext.cs b/ZSharp.Platform.Runtime/loader/context/DebuggableEvaluationContext.cs new file mode 100644 index 00000000..9e53d548 --- /dev/null +++ b/ZSharp.Platform.Runtime/loader/context/DebuggableEvaluationContext.cs @@ -0,0 +1,105 @@ +using System.Reflection; +using System.Reflection.Emit; + +namespace ZSharp.Platform.Runtime +{ + internal sealed class DebuggableEvaluationContext + : IEvaluationContext + { + private const string TypeName = ""; + private const string MethodName = ""; + + private readonly PersistedAssemblyBuilder assemblyBuilder; + private readonly ModuleBuilder moduleBuilder; + private readonly TypeBuilder typeBuilder; + private MethodBuilder? methodBuilder; + + public string? OutputPath { get; init; } + + internal DebuggableEvaluationContext(string name) + { + assemblyBuilder = new PersistedAssemblyBuilder( + new AssemblyName(name), + typeof(object).Assembly, + [ + new( + typeof(System.Diagnostics.DebuggableAttribute).GetConstructor([ + typeof(System.Diagnostics.DebuggableAttribute.DebuggingModes) + ]) ?? throw new(), + [ + System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations | + System.Diagnostics.DebuggableAttribute.DebuggingModes.Default | + System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | + System.Diagnostics.DebuggableAttribute.DebuggingModes.EnableEditAndContinue + ] + ) + ] + ); + moduleBuilder = assemblyBuilder.DefineDynamicModule(name); + typeBuilder = moduleBuilder.DefineType( + TypeName, + TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Abstract + ); + } + + ModuleBuilder IEvaluationContext.Module => moduleBuilder; + + ILGenerator IEvaluationContext.DefineCode(Type returnType) + { + if (methodBuilder is not null) + throw new InvalidOperationException("Code method has already been defined."); + + return (methodBuilder = typeBuilder.DefineMethod( + MethodName, + MethodAttributes.Public | MethodAttributes.Static, + returnType, + [] + )).GetILGenerator(); + } + + MethodInfo IEvaluationContext.LoadMethod() + { + typeBuilder.CreateType(); + + var metadataBuilder = assemblyBuilder.GenerateMetadata(out var ilStream, out _, out var pdbBuilder); + var entryPointHandle = IL.Metadata.Ecma335.MetadataTokens.MethodDefinitionHandle(methodBuilder!.MetadataToken); + + var portablePdbBlob = new IL.Metadata.BlobBuilder(); + var portablePdbBuilder = new IL.Metadata.Ecma335.PortablePdbBuilder(pdbBuilder, metadataBuilder.GetRowCounts(), entryPointHandle); + var pdbContentId = portablePdbBuilder.Serialize(portablePdbBlob); + + var debugDirectoryBuilder = new IL.PortableExecutable.DebugDirectoryBuilder(); + debugDirectoryBuilder.AddCodeViewEntry($"{assemblyBuilder.GetName().Name}.pdb", pdbContentId, portablePdbBuilder.FormatVersion); + debugDirectoryBuilder.AddEmbeddedPortablePdbEntry(portablePdbBlob, portablePdbBuilder.FormatVersion); + + IL.PortableExecutable.ManagedPEBuilder peBuilder = new( + header: new( + imageCharacteristics: IL.PortableExecutable.Characteristics.Dll, + subsystem: IL.PortableExecutable.Subsystem.WindowsCui + ), + metadataRootBuilder: new(metadataBuilder), + ilStream: ilStream, + debugDirectoryBuilder: debugDirectoryBuilder + ); + + var peBlob = new IL.Metadata.BlobBuilder(); + peBuilder.Serialize(peBlob); + + using var stream = new MemoryStream(); + peBlob.WriteContentTo(stream); + + if (OutputPath is not null) + { + stream.Seek(0, SeekOrigin.Begin); + using var fileStream = File.Create(Path.Join(OutputPath, $"{assemblyBuilder.GetName().Name}.dll")); + stream.CopyTo(fileStream); + } + + stream.Seek(0, SeekOrigin.Begin); + var loadedAssembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(stream); + var method = loadedAssembly.GetType(TypeName)?.GetMethod(MethodName) + ?? throw new InvalidOperationException("Failed to load generated code method."); + return method; + } + } +} diff --git a/ZSharp.Platform.Runtime/loader/context/ExecutionEvaluationContext.cs b/ZSharp.Platform.Runtime/loader/context/ExecutionEvaluationContext.cs new file mode 100644 index 00000000..851e9fa8 --- /dev/null +++ b/ZSharp.Platform.Runtime/loader/context/ExecutionEvaluationContext.cs @@ -0,0 +1,30 @@ +using System.Reflection; +using System.Reflection.Emit; + +namespace ZSharp.Platform.Runtime +{ + internal sealed class ExecutionEvaluationContext(ModuleBuilder moduleBuilder) + : IEvaluationContext + { + private readonly ModuleBuilder moduleBuilder = moduleBuilder; + private DynamicMethod? dynamicMethod; + + ModuleBuilder IEvaluationContext.Module => throw new NotImplementedException(); + + ILGenerator IEvaluationContext.DefineCode(Type returnType) + { + if (dynamicMethod is not null) + throw new InvalidOperationException("Code has already been defined."); + + return (dynamicMethod = new( + "", + returnType, + [], + moduleBuilder + )).GetILGenerator(); + } + + MethodInfo IEvaluationContext.LoadMethod() + => dynamicMethod ?? throw new InvalidOperationException("Code has not been defined."); + } +} diff --git a/ZSharp.Platform.Runtime/loader/context/IEvaluationContext.cs b/ZSharp.Platform.Runtime/loader/context/IEvaluationContext.cs new file mode 100644 index 00000000..acf77dcb --- /dev/null +++ b/ZSharp.Platform.Runtime/loader/context/IEvaluationContext.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Platform.Runtime +{ + public interface IEvaluationContext + { + public Emit.ModuleBuilder Module { get; } + + public Emit.ILGenerator DefineCode(Type returnType); + + public IL.MethodInfo LoadMethod(); + } +} diff --git a/ZSharp.Platform.Runtime/loader/context/factories/DebuggableEvaluationContextFactory.cs b/ZSharp.Platform.Runtime/loader/context/factories/DebuggableEvaluationContextFactory.cs new file mode 100644 index 00000000..c419ac04 --- /dev/null +++ b/ZSharp.Platform.Runtime/loader/context/factories/DebuggableEvaluationContextFactory.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Platform.Runtime +{ + internal sealed class DebuggableEvaluationContextFactory + : IEvaluationContextFactory + { + private const string AssemblyFormat = "ZSharpPersistedAssembly_{0}"; + private int persistedAssemblyCount = 0; + + public string? OutputPath { get; init; } + + IEvaluationContext IEvaluationContextFactory.CreateEvaluationContext() + => new DebuggableEvaluationContext(string.Format(AssemblyFormat, persistedAssemblyCount++)) + { + OutputPath = OutputPath + }; + } +} diff --git a/ZSharp.Platform.Runtime/loader/context/factories/ExecutionEvaluationContextFactory.cs b/ZSharp.Platform.Runtime/loader/context/factories/ExecutionEvaluationContextFactory.cs new file mode 100644 index 00000000..67438b1c --- /dev/null +++ b/ZSharp.Platform.Runtime/loader/context/factories/ExecutionEvaluationContextFactory.cs @@ -0,0 +1,24 @@ +namespace ZSharp.Platform.Runtime +{ + internal sealed class ExecutionEvaluationContextFactory + : IEvaluationContextFactory + { + public Emit.AssemblyBuilder StandaloneAssembly { get; } + + public Emit.ModuleBuilder StandaloneModule { get; } + + public ExecutionEvaluationContextFactory() + { + StandaloneAssembly = Emit.AssemblyBuilder.DefineDynamicAssembly( + new(""), + Emit.AssemblyBuilderAccess.RunAndCollect + ); + StandaloneModule = StandaloneAssembly.DefineDynamicModule( + "" + ); + } + + IEvaluationContext IEvaluationContextFactory.CreateEvaluationContext() + => new ExecutionEvaluationContext(StandaloneModule); + } +} diff --git a/ZSharp.Platform.Runtime/loader/context/factories/IEvaluationContextFactory.cs b/ZSharp.Platform.Runtime/loader/context/factories/IEvaluationContextFactory.cs new file mode 100644 index 00000000..2b5f2e1b --- /dev/null +++ b/ZSharp.Platform.Runtime/loader/context/factories/IEvaluationContextFactory.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Platform.Runtime +{ + public interface IEvaluationContextFactory + { + public IEvaluationContext CreateEvaluationContext(); + } +} diff --git a/ZSharp.Platform.Runtime/loader/emit/EmitLoader.Standalone.cs b/ZSharp.Platform.Runtime/loader/emit/EmitLoader.Standalone.cs index dd010d78..0bfa89b2 100644 --- a/ZSharp.Platform.Runtime/loader/emit/EmitLoader.Standalone.cs +++ b/ZSharp.Platform.Runtime/loader/emit/EmitLoader.Standalone.cs @@ -2,8 +2,8 @@ { partial class EmitLoader { - private Emit.AssemblyBuilder StandaloneAssembly { get; } + public Emit.AssemblyBuilder StandaloneAssembly { get; } - private Emit.ModuleBuilder StandaloneModule { get; } + public Emit.ModuleBuilder StandaloneModule { get; } } } diff --git a/ZSharp.Platform.Runtime/loader/emit/EmitLoader.cs b/ZSharp.Platform.Runtime/loader/emit/EmitLoader.cs index b4fedea8..4fb3bb3c 100644 --- a/ZSharp.Platform.Runtime/loader/emit/EmitLoader.cs +++ b/ZSharp.Platform.Runtime/loader/emit/EmitLoader.cs @@ -1,17 +1,30 @@ -namespace ZSharp.Platform.Runtime.Loaders +using Debuggable = System.Diagnostics.DebuggableAttribute; + +namespace ZSharp.Platform.Runtime.Loaders { - internal sealed partial class EmitLoader + public sealed partial class EmitLoader { public Runtime Runtime { get; } - public EmitLoader(Runtime runtime) + internal EmitLoader(Runtime runtime) { Runtime = runtime; - - StandaloneAssembly = Emit.AssemblyBuilder.DefineDynamicAssembly( - new IL.AssemblyName(""), - Emit.AssemblyBuilderAccess.RunAndCollect + + StandaloneAssembly = new Emit.PersistedAssemblyBuilder( + new(""), + typeof(void).Assembly, + [ + new( + typeof(Debuggable).GetConstructor([ + typeof(Debuggable.DebuggingModes) + ]) ?? throw new(), + [ + Debuggable.DebuggingModes.Default + ] + ) + ] ); + StandaloneModule = StandaloneAssembly.DefineDynamicModule( "" ); diff --git a/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Code.cs b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Code.cs index 99f8bdf6..b768dd71 100644 --- a/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Code.cs +++ b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Code.cs @@ -1,5 +1,7 @@ using CommonZ.Utils; +using Debuggable = System.Diagnostics.DebuggableAttribute; + namespace ZSharp.Platform.Runtime.Loaders { partial class EmitLoader @@ -7,7 +9,12 @@ partial class EmitLoader private delegate T CodeFunctionType(); private delegate void VoidCodeFunction(); - public Delegate LoadCode(Collection code, IR.IType irReturnType) + public Delegate LoadCode( + Collection code, + IR.IType irReturnType, + IEvaluationContext evaluationContext, + IContext? codeContext = null + ) { if (code.Count == 0) return () => { }; @@ -15,11 +22,13 @@ public Delegate LoadCode(Collection code, IR.IType irReturnTy code.Add(new IR.VM.Return()); var ilReturnType = Runtime.ImportType(irReturnType); - var method = new Emit.DynamicMethod(string.Empty, ilReturnType, null, StandaloneModule); + var ilGenerator = evaluationContext.DefineCode(ilReturnType); - var codeLoader = new CodeCompiler(new UnboundCodeContext(Runtime, method.GetILGenerator())); + var codeLoader = new CodeCompiler(new UnboundCodeContext(Runtime, ilGenerator, codeContext)); codeLoader.CompileCode(code); + var method = evaluationContext.LoadMethod(); + return ilReturnType != typeof(void) ? method.CreateDelegate( diff --git a/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs index 3693269f..38143d87 100644 --- a/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs @@ -1,11 +1,13 @@ using CommonZ.Utils; +using System.Diagnostics.CodeAnalysis; namespace ZSharp.Platform.Runtime.Loaders { - internal sealed class UnboundCodeContext(Runtime runtime, IL.Emit.ILGenerator il) + internal sealed class UnboundCodeContext(Runtime runtime, Emit.ILGenerator il, IContext? inner = null) : ICodeContext , IBranchingCodeContext { + private readonly IContext? inner = inner; private readonly Mapping labels = []; public Emit.ILGenerator IL { get; } = il; @@ -19,5 +21,8 @@ void IBranchingCodeContext.AddBranchTarget(IR.VM.Instruction target) Emit.Label IBranchingCodeContext.GetBranchTarget(IR.VM.Instruction target) => labels[target]; + + bool IContext.Is([NotNullWhen(true)] out T? context) where T : class + => (context = this as T) is not null || (inner?.Is(out context) ?? false); } } diff --git a/ZSharp.Platform.Runtime/loader/loaders/code/code/CodeCompiler.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/CodeCompiler.cs index 31046418..b5a25ef6 100644 --- a/ZSharp.Platform.Runtime/loader/loaders/code/code/CodeCompiler.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/CodeCompiler.cs @@ -8,7 +8,7 @@ public sealed class CodeCompiler(ICodeContext context) public void CompileCode(Collection instructions) { - if (Context is IBranchingCodeContext branchingContext) + if (Context.Is(out var branchingContext)) { foreach (var instruction in instructions) branchingContext.AddBranchTarget(instruction); @@ -26,6 +26,18 @@ public void CompileCode(Collection instructions) private void Compile(IR.VM.Instruction instruction) { + if (Context.Is(out var debuggable)) + { + if (debuggable.TryGetSequencePoint(instruction, out var location)) + Context.IL.MarkSequencePoint( + debuggable.Document, + location.StartLine, + location.StartColumn, + location.EndLine, + location.EndColumn + ); + } + switch (instruction) { case IR.VM.Call call: CodeCompiler_Impl.Compile(RequireContext(), call); break; @@ -64,7 +76,7 @@ private void Compile(IR.VM.Instruction instruction) } private T RequireContext() - where T : ICodeContext - => Context is T required ? required : throw new InvalidOperationException(); + where T : class, ICodeContext + => Context.Is(out var required) ? required : throw new InvalidOperationException(); } } diff --git a/ZSharp.Platform.Runtime/loader/loaders/code/code/core/ICodeContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/core/ICodeContext.cs index 048d13e7..d953c9b1 100644 --- a/ZSharp.Platform.Runtime/loader/loaders/code/code/core/ICodeContext.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/core/ICodeContext.cs @@ -1,6 +1,6 @@ namespace ZSharp.Platform.Runtime.Loaders { - public interface ICodeContext + public interface ICodeContext : IContext { public Emit.ILGenerator IL { get; } diff --git a/ZSharp.Platform.Runtime/loader/loaders/code/code/core/IContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/core/IContext.cs new file mode 100644 index 00000000..e8565445 --- /dev/null +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/core/IContext.cs @@ -0,0 +1,11 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Platform.Runtime.Loaders +{ + public interface IContext + { + public bool Is([NotNullWhen(true)] out T? context) + where T : class, IContext + => (context = this as T) != null; + } +} diff --git a/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/IDebuggableContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/IDebuggableContext.cs new file mode 100644 index 00000000..aa35bed6 --- /dev/null +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/IDebuggableContext.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Platform.Runtime.Loaders +{ + public interface IDebuggableContext + : IContext + { + public System.Diagnostics.SymbolStore.ISymbolDocumentWriter Document { get; } + + public bool TryGetSequencePoint(IR.VM.Instruction instruction, out SourceLocation location); + } +} diff --git a/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/SourceLocation.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/SourceLocation.cs new file mode 100644 index 00000000..aeacf2f9 --- /dev/null +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/SourceLocation.cs @@ -0,0 +1,13 @@ +namespace ZSharp.Platform.Runtime.Loaders +{ + public struct SourceLocation + { + public int StartLine { get; init; } + + public int EndLine { get; init; } + + public int StartColumn { get; init; } + + public int EndColumn { get; init; } + } +} diff --git a/ZSharp.Platform.Runtime/runtime/Runtime.Evaluate.cs b/ZSharp.Platform.Runtime/runtime/Runtime.Evaluate.cs index b271ee58..acede4c3 100644 --- a/ZSharp.Platform.Runtime/runtime/Runtime.Evaluate.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.Evaluate.cs @@ -4,9 +4,18 @@ namespace ZSharp.Platform.Runtime { partial class Runtime { - public object? Evaluate(Collection code, IR.IType type) + public object? Evaluate( + Collection code, + IR.IType type, + IEvaluationContext? evaluationContext = null, + Loaders.IContext? innerContext = null + ) { - return Loader.LoadCode(code, type).DynamicInvoke(null); + return Loader.LoadCode( + code, type, + evaluationContext ?? EvaluationContextFactory.CreateEvaluationContext(), + innerContext + ).DynamicInvoke(null); } } } diff --git a/ZSharp.Platform.Runtime/runtime/Runtime.Loader.cs b/ZSharp.Platform.Runtime/runtime/Runtime.Loader.cs index c11fbd72..afa7f54e 100644 --- a/ZSharp.Platform.Runtime/runtime/Runtime.Loader.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.Loader.cs @@ -2,6 +2,8 @@ { partial class Runtime { - private Loaders.EmitLoader Loader { get; } + public IEvaluationContextFactory EvaluationContextFactory { get; } + + public Loaders.EmitLoader Loader { get; } } } diff --git a/ZSharp.Platform.Runtime/runtime/Runtime.cs b/ZSharp.Platform.Runtime/runtime/Runtime.cs index dc0920ef..4aca18bd 100644 --- a/ZSharp.Platform.Runtime/runtime/Runtime.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.cs @@ -2,12 +2,23 @@ { public sealed partial class Runtime { - public Runtime(TypeSystem typeSystem) + public bool DebugEnabled { get; } + + public Runtime(TypeSystem typeSystem, bool debugging = true) { if (_instance is not null) throw new InvalidOperationException("Runtime instance already exists."); _instance = this; + EvaluationContextFactory = + (DebugEnabled = debugging) + ? new DebuggableEvaluationContextFactory() + { + OutputPath = Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "generated")).FullName + } + : new ExecutionEvaluationContextFactory() + ; + TypeSystem = typeSystem; SetupExposeSystem(); diff --git a/ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj b/ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj index 1fd34d36..eac66889 100644 --- a/ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj +++ b/ZSharp.SourceCompiler.Script/ZSharp.SourceCompiler.Script.csproj @@ -8,6 +8,7 @@ + diff --git a/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Debugging.cs b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Debugging.cs new file mode 100644 index 00000000..15c35615 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Debugging.cs @@ -0,0 +1,27 @@ +using CommonZ.Utils; +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + internal string DocumentPath { get; init; } + + internal DebuggingContext? DebugContext { get; set; } = null!; + + [MemberNotNullWhen(true, nameof(DebugContext), nameof(CurrentEvaluationContext))] + internal bool IsDebuggingEnabled => DebugContext is not null; + + private Platform.Runtime.IEvaluationContext? CurrentEvaluationContext { get; set; } + + private ContextManager EvaluationContext() + { + if (!Interpreter.Runtime.DebugEnabled) return new(() => { }); + CurrentEvaluationContext = Interpreter.Runtime.EvaluationContextFactory.CreateEvaluationContext(); + var document = CurrentEvaluationContext.Module.DefineDocument(DocumentPath); + DebugContext = new(document); + document.SetSource(File.ReadAllBytes(DocumentPath)); + return new(() => DebugContext = null); + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs index 34c10fdc..e3fd2084 100644 --- a/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs +++ b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs @@ -6,7 +6,7 @@ public sealed partial class ScriptCompiler public AST.Document Node { get; } - public ScriptCompiler(Interpreter.Interpreter interpreter, AST.Document document) + public ScriptCompiler(Interpreter.Interpreter interpreter, AST.Document document, string path) { Interpreter = interpreter; Node = document; @@ -18,6 +18,8 @@ public ScriptCompiler(Interpreter.Interpreter interpreter, AST.Document document PostProcess = PostProcess }.Compile }.Compile; + + DocumentPath = path; } public void Compile() @@ -25,7 +27,13 @@ public void Compile() //using var _ = Interpreter.Compiler.ContextScope(new DocumentContext()); using var _ = Interpreter.Compiler.ContextScope(new ScopeContext()); - Node.Statements.ForEach(Compile); + foreach (var statement in Node.Statements) + { + using (EvaluationContext()) + { + Compile(statement); + } + } } } } diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs index b0ae8c18..d104e60f 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs @@ -8,7 +8,7 @@ private Result Compile(AST.IdentifierExpression identifier) { foreach (var scope in Interpreter.Compiler.CurrentContext.FindContext()) if (scope.Get(identifier.Name).Ok(out var result)) - return Result.Ok(result); + return Result.Ok(new Objects.IdentifierBoundObject(this, identifier, result)); return Result.Error( $"Identifier '{identifier.Name}' not found." diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs index 109fc499..9aefbc45 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs @@ -20,7 +20,7 @@ private void Compile(AST.ExpressionStatement expressionStatement) return; } - Interpreter.Evaluate(valueObject!); + Interpreter.Evaluate(valueObject!, CurrentEvaluationContext, DebugContext); } } } diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs index fcd666a1..0f550ab9 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs @@ -54,8 +54,29 @@ [.. argumentsResults.Select(r => r.Unwrap())] return; } + Platform.Runtime.IEvaluationContext? evaluationContext = null; + var codeContext = DebugContext; + if (Interpreter.Runtime.DebugEnabled) + { + evaluationContext = Interpreter.Runtime.EvaluationContextFactory.CreateEvaluationContext(); + + result = new Objects.ExpressionWrapper( + codeContext = new( + evaluationContext.Module.DefineDocument( + DocumentPath, + System.Diagnostics.SymbolStore.SymLanguageType.CSharp, + System.Diagnostics.SymbolStore.SymLanguageVendor.Microsoft, + System.Diagnostics.SymbolStore.SymDocumentType.Text + ) + ), + import.TokenInfo.ImportKeyword.Span, + result! + ); + } + + if ( - Interpreter.Evaluate(result!) + Interpreter.Evaluate(result!, evaluationContext, codeContext) .When(out var importObject) .Error(out error) ) diff --git a/ZSharp.SourceCompiler.Script/objects/ExpressionWrapper.cs b/ZSharp.SourceCompiler.Script/objects/ExpressionWrapper.cs new file mode 100644 index 00000000..bec81097 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/objects/ExpressionWrapper.cs @@ -0,0 +1,48 @@ +using ZSharp.Compiler; + +namespace ZSharp.SourceCompiler.Script.Objects +{ + internal sealed class ExpressionWrapper( + DebuggingContext debugContext, + Text.Span span, + CompilerObject inner + ) + : CompilerObject + , IProxy + , ICompileIRCode + { + private readonly DebuggingContext debugContext = debugContext; + private readonly Text.Span span = span; + private readonly CompilerObject inner = inner; + + R IProxy.Apply(Func fn) + => fn(inner); + + Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) + { + if (target is not Platform.Runtime.Runtime runtime) + return compiler.IR.CompileCode(inner, target); + + var innerCodeResult = compiler.IR.CompileCode(inner, target); + + if ( + innerCodeResult + .When(out var innerCode) + .Error(out var error) + ) return Result.Error(error); + + debugContext.AddSequencePoint( + innerCode!.Instructions[0], + new() + { + StartLine = span.Start.Line, + StartColumn = span.Start.Column, + EndLine = span.End.Line, + EndColumn = span.End.Column + } + ); + + return innerCodeResult; + } + } +} diff --git a/ZSharp.SourceCompiler.Script/objects/IdentifierBoundObject.cs b/ZSharp.SourceCompiler.Script/objects/IdentifierBoundObject.cs new file mode 100644 index 00000000..e0dc00d2 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/objects/IdentifierBoundObject.cs @@ -0,0 +1,49 @@ +using ZSharp.Compiler; + +namespace ZSharp.SourceCompiler.Script.Objects +{ + internal sealed class IdentifierBoundObject( + ScriptCompiler compiler, + AST.IdentifierExpression identifier, + CompilerObject inner + ) + : CompilerObject + , IProxy + , ICompileIRCode + { + private readonly ScriptCompiler compiler = compiler; + private readonly AST.IdentifierExpression identifier = identifier; + private readonly CompilerObject inner = inner; + + R IProxy.Apply(Func fn) + => fn(inner); + + Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) + { + if (target is not Platform.Runtime.Runtime runtime || !this.compiler.IsDebuggingEnabled) + return compiler.IR.CompileCode(inner, target); + + var innerCodeResult = compiler.IR.CompileCode(inner, target); + + if ( + innerCodeResult + .When(out var innerCode) + .Error(out var error) + ) return Result.Error(error); + + var span = identifier.TokenInfo.Identifier.Span; + this.compiler.DebugContext.AddSequencePoint( + innerCode!.Instructions[0], + new() + { + StartLine = span.Start.Line, + StartColumn = span.Start.Column, + EndLine = span.End.Line, + EndColumn = span.End.Column + } + ); + + return innerCodeResult; + } + } +} diff --git a/ZSharp.SourceCompiler.Script/runtime contexts/DebuggingContext.cs b/ZSharp.SourceCompiler.Script/runtime contexts/DebuggingContext.cs new file mode 100644 index 00000000..a4d9c489 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/runtime contexts/DebuggingContext.cs @@ -0,0 +1,19 @@ +using System.Diagnostics.SymbolStore; +using ZSharp.IR.VM; +using ZSharp.Platform.Runtime.Loaders; + +namespace ZSharp.SourceCompiler.Script +{ + internal sealed class DebuggingContext(ISymbolDocumentWriter document) + : IDebuggableContext + { + ISymbolDocumentWriter IDebuggableContext.Document { get; } = document; + private readonly Dictionary sequencePoints = []; + + bool IDebuggableContext.TryGetSequencePoint(Instruction instruction, out SourceLocation location) + => sequencePoints.TryGetValue(instruction, out location); + + public void AddSequencePoint(Instruction instruction, SourceLocation location) + => sequencePoints[instruction] = location; + } +} From cf8ca4f5059dcb4b8e62ae3dc8a5dba6e7905998 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 8 Oct 2025 15:16:23 +0300 Subject: [PATCH 215/235] Rename IR classes to better reflect their purposes --- .../generic/GenericFunctionInstance_Old.cs | 6 +++--- .../instance/GenericFunctionInstance.Call.cs | 2 +- .../instance/GenericFunctionInstance.IR.cs | 4 ++-- ZSharp.Compiler.Objects/oop/class/Class.cs | 16 ++++++++-------- .../oop/class/GenericClass.cs | 2 +- .../oop/class/GenericClassInstance.cs | 8 ++++---- .../oop/constructor/Constructor.cs | 2 +- .../oop/constructor/ConstructorReference.cs | 2 +- ZSharp.Compiler.Objects/oop/enum/EnumValue.cs | 4 ++-- .../oop/interface/Interface.cs | 10 +++++----- .../oop/method/concrete/Method.cs | 12 ++++++------ .../oop/method/concrete/MethodReference.cs | 8 ++++---- .../oop/method/generic/GenericMethod.cs | 4 ++-- .../method/generic/GenericMethodInstance.cs | 6 +++--- .../method/generic/GenericMethodReference.cs | 8 ++++---- .../oop/value type/ValueType.cs | 8 ++++---- ...tionInstance.cs => ConstructedFunction.cs} | 2 +- ZSharp.IR/ir/modular/module/Module.cs | 4 ++-- ZSharp.IR/ir/oop/Dataclass.cs | 6 +++--- ZSharp.IR/ir/oop/Structure.cs | 4 ++-- ZSharp.IR/ir/oop/class/Class.cs | 8 ++++---- ZSharp.IR/ir/oop/class/ClassReference.cs | 4 ++-- ZSharp.IR/ir/oop/class/ConstructedClass.cs | 4 ++-- .../oop/constructor/ConstructorReference.cs | 2 +- ZSharp.IR/ir/oop/enum/EnumClass.cs | 2 +- ZSharp.IR/ir/oop/field/FieldReference.cs | 2 +- .../ir/oop/interface/ConstructedInterface.cs | 4 ++-- ZSharp.IR/ir/oop/interface/Interface.cs | 6 +++--- .../oop/interface/InterfaceImplementation.cs | 4 ++-- .../ir/oop/interface/InterfaceReference.cs | 4 ++-- ZSharp.IR/ir/oop/method/Method.cs | 2 +- ZSharp.IR/ir/oop/method/MethodReference.cs | 2 +- .../ir/oop/value type/ConstructedValueType.cs | 4 ++-- ZSharp.IR/ir/oop/value type/ValueType.cs | 2 +- .../ir/oop/value type/ValueTypeReference.cs | 4 ++-- ZSharp.IR/ir/typeclass/Typeclass.cs | 4 ++-- .../ir/typeclass/TypeclassImplementation.cs | 2 +- ZSharp.IR/ir/types/OOPType.cs | 7 ------- ZSharp.IR/ir/types/TypeDefinition.cs | 7 +++++++ .../type system/types/ConstructedType.cs | 6 +++--- .../type system/types/OOPTypeReference.cs | 19 ------------------- ZSharp.IR/type system/types/TypeReference.cs | 19 +++++++++++++++++++ ZSharp.IR/vm/instructions/misc/GetClass.cs | 8 ++++---- .../vm/instructions/object/CastReference.cs | 4 ++-- .../il loader/ILLoader.Expose.cs | 2 +- .../objects/oop/class/concrete/Class.IR.cs | 6 +++--- .../objects/types/array/ArrayType.cs | 4 ++-- .../objects/types/boolean/BooleanType.cs | 4 ++-- .../objects/types/char/CharType.cs | 4 ++-- .../objects/types/float/Float128Type.cs | 4 ++-- .../objects/types/float/Float16Type.cs | 4 ++-- .../objects/types/float/Float32Type.cs | 4 ++-- .../objects/types/float/Float64Type.cs | 4 ++-- .../objects/types/object/ObjectType.cs | 4 ++-- .../objects/types/pointer/PointerType.cs | 4 ++-- .../objects/types/reference/ReferenceType.cs | 4 ++-- .../objects/types/string/StringType.cs | 4 ++-- .../objects/types/void/VoidType.cs | 4 ++-- .../ir loader/IRLoader.Impl.cs | 2 +- .../loader/emit/load/EmitLoader.Load.Type.cs | 2 +- .../loader/helpers/TypeLoaderBase.cs | 2 +- .../loader/helpers/TypeLoaderHelper.cs | 4 ++-- .../class/load/ClassLoader.Load.Type.cs | 2 +- .../enum/load/EnumClassLoader.Load.Type.cs | 2 +- .../load/InterfaceLoader.Load.Type.cs | 2 +- .../module/load/ModuleLoader.Load.Type.cs | 2 +- .../load/ValueTypeLoader.Load.Type.cs | 2 +- ZSharp.Platform.Runtime/runtime/Runtime.cs | 2 +- .../runtime/cache/Runtime.Cache.Type.cs | 8 ++++---- .../runtime/import/Runtime.Import.Callable.cs | 2 +- .../runtime/import/Runtime.Import.Function.cs | 2 +- .../import/Runtime.Import.Type.Modified.cs | 6 +++--- .../runtime/import/Runtime.Import.Type.cs | 6 +++--- .../runtime/load/Runtime.Load.Type.cs | 2 +- .../type system/TypeSystem.Array.cs | 2 +- .../type system/TypeSystem.Boolean.cs | 2 +- .../type system/TypeSystem.Char.cs | 2 +- .../type system/TypeSystem.Float.cs | 8 ++++---- .../type system/TypeSystem.Object.cs | 2 +- .../type system/TypeSystem.Pointer.cs | 2 +- .../type system/TypeSystem.Reference.cs | 2 +- .../type system/TypeSystem.SInt.cs | 10 +++++----- .../type system/TypeSystem.String.cs | 2 +- .../type system/TypeSystem.UInt.cs | 10 +++++----- .../type system/TypeSystem.Void.cs | 2 +- 85 files changed, 198 insertions(+), 198 deletions(-) rename ZSharp.IR/ir/functional/{GenericFunctionInstance.cs => ConstructedFunction.cs} (87%) delete mode 100644 ZSharp.IR/ir/types/OOPType.cs create mode 100644 ZSharp.IR/ir/types/TypeDefinition.cs delete mode 100644 ZSharp.IR/type system/types/OOPTypeReference.cs create mode 100644 ZSharp.IR/type system/types/TypeReference.cs diff --git a/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs b/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs index 071e0ed6..3125e122 100644 --- a/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs +++ b/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs @@ -6,7 +6,7 @@ namespace ZSharp.Objects public sealed class GenericFunctionInstance_Old(GenericFunction origin) : CompilerObject , ICTCallable_Old - , ICompileIRReference + , ICompileIRReference { public GenericFunction Origin { get; } = origin; @@ -43,7 +43,7 @@ CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] argum code.Append(compiler.CompileIRCode(args[param])); code.Append(new([ - new IR.VM.Call(compiler.CompileIRReference(this)) + new IR.VM.Call(compiler.CompileIRReference(this)) ])); code.Types.Clear(); @@ -53,7 +53,7 @@ CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] argum return new RawCode(code); } - IR.GenericFunctionInstance ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + IR.ConstructedFunction ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) { var arguments = Origin.GenericParameters .Select(genericParameter => Context[genericParameter]) diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs index 94f462f2..f3de373d 100644 --- a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs +++ b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs @@ -37,7 +37,7 @@ CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument_NEW(this)) + new IR.VM.Call(compiler.CompileIRReference(this)) ])); code.Types.Clear(); diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs index 0ebe0e91..4ba9e6b5 100644 --- a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs +++ b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs @@ -3,9 +3,9 @@ namespace ZSharp.Objects { partial class GenericFunctionInstance - : ICompileIRReference + : ICompileIRReference { - IR.GenericFunctionInstance ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + IR.ConstructedFunction ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) { var argumentResults = GenericFunction.GenericParameters .Select(p => GenericArguments[p]) diff --git a/ZSharp.Compiler.Objects/oop/class/Class.cs b/ZSharp.Compiler.Objects/oop/class/Class.cs index 1f60c306..a8a1da4e 100644 --- a/ZSharp.Compiler.Objects/oop/class/Class.cs +++ b/ZSharp.Compiler.Objects/oop/class/Class.cs @@ -8,8 +8,8 @@ public sealed class Class : CompilerObject , IClass , ICompileIRObject - , ICompileIRReference - , ICompileIRType> + , IIRReferenceCompiler + , ICompileIRType> , ICTCallable_Old , IRTCastTo , ICTGetMember_Old @@ -77,7 +77,7 @@ public bool IsDefined { state[BuildState.Base] = true; - IR.Base = compiler.CompileIRReference>(Base); + IR.Base = compiler.CompileIRReference>(Base); } if (Content.Count > 0 && !state[BuildState.Body]) @@ -95,7 +95,7 @@ public bool IsDefined foreach (var @interfaceImplementation in InterfaceImplementations) { IR.InterfaceImplementation implementation = new( - compiler.CompileIRReference>(interfaceImplementation.Abstract) + compiler.CompileIRReference>(interfaceImplementation.Abstract) ); IR.InterfacesImplementations.Add(implementation); @@ -120,12 +120,12 @@ CompilerObject IRTGetMember_Old.Member(Compiler.Compiler compiler, Compi return compiler.Map(Members[member], @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, instance) : @object); } - IR.OOPTypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) + IR.TypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) { return new IR.ClassReference(compiler.CompileIRObject(this, null)); } - IR.ClassReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + IR.ClassReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) { return new IR.ClassReference(compiler.CompileIRObject(this, null)); } @@ -215,9 +215,9 @@ Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObject value if (targetClass.IsSubclassOf(this)) { var targetClassIRResult = - compiler.IR.CompileReference>(targetClass); + compiler.IR.CompileReference>(targetClass); - IR.OOPTypeReference targetClassIR; + IR.TypeReference targetClassIR; if (targetClassIRResult.Error(out error)) return Result.Error(error); diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs index 7006fc82..d17c1bad 100644 --- a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs +++ b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs @@ -115,7 +115,7 @@ CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) { state.Set(BuildState.Base); - @class.Base = compiler.CompileIRType>(Base); + @class.Base = compiler.CompileIRType>(Base); } if (Content.Count > 0 && !state.Get(BuildState.Body)) diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs index ff149af3..31147cf5 100644 --- a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs +++ b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs @@ -11,8 +11,8 @@ public sealed class GenericClassInstance , ICTCallable_Old , IReference , ICompileIRType - , ICompileIRReference> - , ICompileIRReference + , IIRReferenceCompiler> + , IIRReferenceCompiler , IReferencable , IType { @@ -109,7 +109,7 @@ CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] argum return compiler.Call(constructor, arguments); } - IR.OOPTypeReference ICompileIRReference>.CompileIRReference(Compiler.Compiler compiler) + IR.TypeReference IIRReferenceCompiler>.CompileIRReference(Compiler.Compiler compiler) => compiler.CompileIRType(this); GenericClassInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) @@ -144,7 +144,7 @@ bool IType.IsEqualTo(Compiler.Compiler compiler, IType type) return true; } - IR.OOPTypeReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + IR.TypeReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) => compiler.CompileIRType(this); } } diff --git a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs index 6b73906f..2583e529 100644 --- a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs +++ b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs @@ -62,7 +62,7 @@ public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) invocationInstruction = new IR.VM.CreateInstance(new IR.ConstructorReference(IR!) { OwningType = (IR?.Method.Owner is null - ? IR!.Method.Signature.Args.Parameters[0].Type as IR.OOPTypeReference + ? IR!.Method.Signature.Args.Parameters[0].Type as IR.TypeReference : new IR.ClassReference(IR!.Method.Owner as IR.Class ?? throw new())) ?? throw new() }); diff --git a/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs b/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs index 452578df..536dd30d 100644 --- a/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs +++ b/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs @@ -26,7 +26,7 @@ CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] argum var invocationInstruction = rawCode.Code.Instructions.Last(); if (invocationInstruction is IR.VM.CreateInstance createInstance) { - var type = compiler.CompileIRReference>(ownerReference); + var type = compiler.CompileIRReference>(ownerReference); createInstance.Constructor = new IR.ConstructorReference(createInstance.Constructor.Constructor) { diff --git a/ZSharp.Compiler.Objects/oop/enum/EnumValue.cs b/ZSharp.Compiler.Objects/oop/enum/EnumValue.cs index ab4a6c4d..435fc82a 100644 --- a/ZSharp.Compiler.Objects/oop/enum/EnumValue.cs +++ b/ZSharp.Compiler.Objects/oop/enum/EnumValue.cs @@ -6,7 +6,7 @@ public sealed class EnumValue(string name) : CompilerObject , ICTGet , IDynamicallyTyped - , ICompileIRCode + , IIRCodeCompiler , ICompileIRObject { #region Build State @@ -66,7 +66,7 @@ IType IDynamicallyTyped.GetType(Compiler.Compiler compiler) ? type : throw new(); - IRCode ICompileIRCode.CompileIRCode(Compiler.Compiler compiler) + IRCode IIRCodeCompiler.CompileIRCode(Compiler.Compiler compiler) => compiler.CompileIRCode(Value); } } diff --git a/ZSharp.Compiler.Objects/oop/interface/Interface.cs b/ZSharp.Compiler.Objects/oop/interface/Interface.cs index 0e7939d0..3e564bd6 100644 --- a/ZSharp.Compiler.Objects/oop/interface/Interface.cs +++ b/ZSharp.Compiler.Objects/oop/interface/Interface.cs @@ -7,8 +7,8 @@ public sealed class Interface(string? name) : CompilerObject , IAbstraction , ICompileIRObject - , ICompileIRReference> - , ICompileIRType> + , IIRReferenceCompiler> + , ICompileIRType> , ICTGetMember_Old , IRTGetMember_Old , IType @@ -74,7 +74,7 @@ CompilerObject IRTGetMember_Old.Member(Compiler.Compiler compiler, Compi state[BuildState.Bases] = true; foreach (var @base in Bases) - IR.Bases.Add(compiler.CompileIRReference>(@base)); + IR.Bases.Add(compiler.CompileIRReference>(@base)); } if (!state[BuildState.Body]) @@ -88,12 +88,12 @@ CompilerObject IRTGetMember_Old.Member(Compiler.Compiler compiler, Compi return IR; } - IR.OOPTypeReference ICompileIRReference>.CompileIRReference(Compiler.Compiler compiler) + IR.TypeReference IIRReferenceCompiler>.CompileIRReference(Compiler.Compiler compiler) => new IR.InterfaceReference( compiler.CompileIRObject(this, null) ); - IR.OOPTypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) + IR.TypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) => new IR.InterfaceReference( compiler.CompileIRObject(this, null) ); diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs index 213f3d29..fa313d8a 100644 --- a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs +++ b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs @@ -14,8 +14,8 @@ public sealed class Method(string? name) , IMethod , ICTCallable_Old , ICompileIRObject - , ICompileIRObject - , ICompileIRReference + , ICompileIRObject + , IIRReferenceCompiler , IImplementation , IImplementsSpecification , IImplicitCastToType @@ -144,7 +144,7 @@ MethodReference IReferencable.CreateReference(Referencing @ref, }; } - IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.OOPType? owner) + IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.TypeDefinition? owner) { CompileIR(compiler); @@ -169,12 +169,12 @@ CompilerObject IImplicitCastToType.ImplicitCastToType(Compiler.Compiler compiler throw new Compiler.InvalidCastException(this, type); } - IR.MethodReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + IR.MethodReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) => new( - compiler.CompileIRObject(this, null) + compiler.CompileIRObject(this, null) ) { - OwningType = compiler.CompileIRType(Owner) + OwningType = compiler.CompileIRType(Owner) }; void IImplementsSpecification.OnImplementSpecification(Compiler.Compiler compiler, IAbstraction abstraction, CompilerObject specification) diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs b/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs index cfa8ebeb..161ba6d9 100644 --- a/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs +++ b/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs @@ -9,7 +9,7 @@ namespace ZSharp.Objects public sealed class MethodReference(Method origin, ReferenceContext context) : CompilerObject , ICTCallable_Old - , ICompileIRReference + , IIRReferenceCompiler , IRTBoundMember { public Method Origin { get; } = origin; @@ -57,13 +57,13 @@ CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] argum return new RawCode(code); } - IR.MethodReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + IR.MethodReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) { var type = compiler.Feature().CreateReference(Owner, Context); - return new IR.MethodReference(compiler.CompileIRObject(Origin, null!)) + return new IR.MethodReference(compiler.CompileIRObject(Origin, null!)) { - OwningType = compiler.CompileIRReference(type), + OwningType = compiler.CompileIRReference(type), Signature = SignatureIR ?? CompileSignature(compiler) }; } diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs index cec25be0..d00f9607 100644 --- a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs +++ b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs @@ -7,7 +7,7 @@ namespace ZSharp.Objects public sealed class GenericMethod(string? name) : CompilerObject , ICompileIRObject - , ICompileIRObject + , ICompileIRObject , ICTGetIndex , INamedObject , IReferencable @@ -82,7 +82,7 @@ IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) return IR; } - IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.OOPType? owner) + IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.TypeDefinition? owner) { CompileIR(compiler); diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs index 4b244274..1cd18501 100644 --- a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs +++ b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs @@ -4,7 +4,7 @@ namespace ZSharp.Objects public sealed class GenericMethodInstance(GenericMethod origin) : CompilerObject , ICTCallable_Old - , ICompileIRReference + , IIRReferenceCompiler , IRTBoundMember { public GenericMethod Origin { get; } = origin; @@ -53,13 +53,13 @@ CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] argum return new RawCode(code); } - IR.ConstructedMethod ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + IR.ConstructedMethod IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) { var result = new IR.ConstructedMethod( compiler.CompileIRObject(Origin, null) ) { - OwningType = compiler.CompileIRReference(Owner) + OwningType = compiler.CompileIRReference(Owner) }; foreach (var genericParameter in Origin.GenericParameters) diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs index feb4c674..fd21de27 100644 --- a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs +++ b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs @@ -8,7 +8,7 @@ ReferenceContext context ) : CompilerObject , ICTCallable_Old - , ICompileIRReference + , IIRReferenceCompiler , IReferencable , IRTBoundMember { @@ -57,13 +57,13 @@ CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] argum return new RawCode(code); } - IR.MethodReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + IR.MethodReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) { var type = compiler.Feature().CreateReference(Owner, Context); - return new IR.MethodReference(compiler.CompileIRObject(Origin, null!)) + return new IR.MethodReference(compiler.CompileIRObject(Origin, null!)) { - OwningType = compiler.CompileIRReference(type), + OwningType = compiler.CompileIRReference(type), Signature = SignatureIR ?? CompileSignature(compiler) }; } diff --git a/ZSharp.Compiler.Objects/oop/value type/ValueType.cs b/ZSharp.Compiler.Objects/oop/value type/ValueType.cs index aa627b3c..7fe45395 100644 --- a/ZSharp.Compiler.Objects/oop/value type/ValueType.cs +++ b/ZSharp.Compiler.Objects/oop/value type/ValueType.cs @@ -5,8 +5,8 @@ namespace ZSharp.Objects public sealed class ValueType(string? name) : CompilerObject , IType - , ICompileIRReference - , ICompileIRType> + , IIRReferenceCompiler + , ICompileIRType> { #region Build State @@ -45,10 +45,10 @@ private IR.ValueTypeReference CompileIRReference(Compiler.Compiler compiler) return new(CompileIR(compiler)); } - IR.OOPTypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) + IR.TypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) => CompileIRReference(compiler); - IR.ValueTypeReference ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) + IR.ValueTypeReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) => CompileIRReference(compiler); } } diff --git a/ZSharp.IR/ir/functional/GenericFunctionInstance.cs b/ZSharp.IR/ir/functional/ConstructedFunction.cs similarity index 87% rename from ZSharp.IR/ir/functional/GenericFunctionInstance.cs rename to ZSharp.IR/ir/functional/ConstructedFunction.cs index 1c85e8f2..715dff19 100644 --- a/ZSharp.IR/ir/functional/GenericFunctionInstance.cs +++ b/ZSharp.IR/ir/functional/ConstructedFunction.cs @@ -2,7 +2,7 @@ namespace ZSharp.IR { - public sealed class GenericFunctionInstance(Function function) + public sealed class ConstructedFunction(Function function) : ICallable { public Function Function { get; set; } = function; diff --git a/ZSharp.IR/ir/modular/module/Module.cs b/ZSharp.IR/ir/modular/module/Module.cs index 61364ecf..95a00867 100644 --- a/ZSharp.IR/ir/modular/module/Module.cs +++ b/ZSharp.IR/ir/modular/module/Module.cs @@ -10,7 +10,7 @@ public sealed class Module(string? name) : IRDefinition private ModuleCollection? _importedModules; private ModuleCollection? _functions; private GlobalCollection? _globals; - private ModuleCollection? _types; + private ModuleCollection? _types; public string? Name { get; set; } = name; @@ -92,7 +92,7 @@ public Collection Globals public bool HasGlobals => !_globals.IsNullOrEmpty(); - public Collection Types + public Collection Types { get { diff --git a/ZSharp.IR/ir/oop/Dataclass.cs b/ZSharp.IR/ir/oop/Dataclass.cs index f5bfef9d..a3efe174 100644 --- a/ZSharp.IR/ir/oop/Dataclass.cs +++ b/ZSharp.IR/ir/oop/Dataclass.cs @@ -2,15 +2,15 @@ namespace ZSharp.IR { - public sealed class Dataclass : OOPType + public sealed class Dataclass : TypeDefinition { public string? Name { get; set; } public DataclassAttributes Attributes { get; set; } = DataclassAttributes.None; - public OOPTypeReference? Base { get; set; } + public TypeReference? Base { get; set; } - public Collection> TypeClasses { get; } + public Collection> TypeClasses { get; } public Collection Constructors { get; } } diff --git a/ZSharp.IR/ir/oop/Structure.cs b/ZSharp.IR/ir/oop/Structure.cs index 2db409a1..331f20a9 100644 --- a/ZSharp.IR/ir/oop/Structure.cs +++ b/ZSharp.IR/ir/oop/Structure.cs @@ -2,13 +2,13 @@ namespace ZSharp.IR { - public sealed class Structure : OOPType + public sealed class Structure : TypeDefinition { public string? Name { get; set; } public StructureAttributes Attributes { get; set; } = StructureAttributes.None; - public Collection> Bases { get; set; } + public Collection> Bases { get; set; } public Collection Methods { get; } diff --git a/ZSharp.IR/ir/oop/class/Class.cs b/ZSharp.IR/ir/oop/class/Class.cs index 4c0b7e86..7fd4bc33 100644 --- a/ZSharp.IR/ir/oop/class/Class.cs +++ b/ZSharp.IR/ir/oop/class/Class.cs @@ -3,7 +3,7 @@ namespace ZSharp.IR { public sealed class Class(string? name) - : OOPType + : TypeDefinition , ICustomMetadataProvider { private Collection? _customMetadata; @@ -17,9 +17,9 @@ public sealed class Class(string? name) public ClassAttributes Attributes { get; set; } = ClassAttributes.None; - public OOPTypeReference? Base { get; set; } + public TypeReference? Base { get; set; } - public Class(string? name, OOPTypeReference? @base) + public Class(string? name, TypeReference? @base) : this(name) { Base = @base; @@ -101,7 +101,7 @@ public Collection Methods public Collection Properties { get; } = []; - public Collection NestedTypes { get; } = []; + public Collection NestedTypes { get; } = []; //public Collection Events { get; } } diff --git a/ZSharp.IR/ir/oop/class/ClassReference.cs b/ZSharp.IR/ir/oop/class/ClassReference.cs index 9ee0ed93..715a5245 100644 --- a/ZSharp.IR/ir/oop/class/ClassReference.cs +++ b/ZSharp.IR/ir/oop/class/ClassReference.cs @@ -1,10 +1,10 @@ namespace ZSharp.IR { public sealed class ClassReference(Class @class) - : OOPTypeReference + : TypeReference { public Class Definition { get; } = @class; - public OOPTypeReference? OwningType { get; set; } + public TypeReference? OwningType { get; set; } } } diff --git a/ZSharp.IR/ir/oop/class/ConstructedClass.cs b/ZSharp.IR/ir/oop/class/ConstructedClass.cs index bd931ba0..cb7a936b 100644 --- a/ZSharp.IR/ir/oop/class/ConstructedClass.cs +++ b/ZSharp.IR/ir/oop/class/ConstructedClass.cs @@ -7,9 +7,9 @@ public sealed class ConstructedClass(Class @class) { public Class Class { get; set; } = @class; - Class OOPTypeReference.Definition => Class; + Class TypeReference.Definition => Class; - public OOPTypeReference? OwningType { get; set; } + public TypeReference? OwningType { get; set; } public Collection Arguments { get; set; } = @class.HasGenericParameters ? [] : Collection.Empty; } diff --git a/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs b/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs index b640b16c..cde680bb 100644 --- a/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs +++ b/ZSharp.IR/ir/oop/constructor/ConstructorReference.cs @@ -5,7 +5,7 @@ public sealed class ConstructorReference(Constructor constructor) { public Constructor Constructor { get; set; } = constructor; - public required OOPTypeReference OwningType { get; set; } + public required TypeReference OwningType { get; set; } public Signature Signature => Constructor.Method.Signature; diff --git a/ZSharp.IR/ir/oop/enum/EnumClass.cs b/ZSharp.IR/ir/oop/enum/EnumClass.cs index 10516001..03162d15 100644 --- a/ZSharp.IR/ir/oop/enum/EnumClass.cs +++ b/ZSharp.IR/ir/oop/enum/EnumClass.cs @@ -3,7 +3,7 @@ namespace ZSharp.IR { public sealed class EnumClass - : OOPType + : TypeDefinition , IType { public string? Name { get; set; } diff --git a/ZSharp.IR/ir/oop/field/FieldReference.cs b/ZSharp.IR/ir/oop/field/FieldReference.cs index 64a1298b..d8c05ddc 100644 --- a/ZSharp.IR/ir/oop/field/FieldReference.cs +++ b/ZSharp.IR/ir/oop/field/FieldReference.cs @@ -4,6 +4,6 @@ public sealed class FieldReference(Field field) { public Field Field { get; set; } = field; - public required OOPTypeReference OwningType { get; set; } + public required TypeReference OwningType { get; set; } } } diff --git a/ZSharp.IR/ir/oop/interface/ConstructedInterface.cs b/ZSharp.IR/ir/oop/interface/ConstructedInterface.cs index 2323076d..6ca74d81 100644 --- a/ZSharp.IR/ir/oop/interface/ConstructedInterface.cs +++ b/ZSharp.IR/ir/oop/interface/ConstructedInterface.cs @@ -7,9 +7,9 @@ public sealed class ConstructedInterface(Interface @interface) { public Interface Interface { get; set; } = @interface; - Interface OOPTypeReference.Definition => Interface; + Interface TypeReference.Definition => Interface; - public OOPTypeReference? OwningType { get; set; } + public TypeReference? OwningType { get; set; } public Collection Arguments { get; set; } = @interface.HasGenericParameters ? [] : Collection.Empty; } diff --git a/ZSharp.IR/ir/oop/interface/Interface.cs b/ZSharp.IR/ir/oop/interface/Interface.cs index 7939af3a..0de0c4c6 100644 --- a/ZSharp.IR/ir/oop/interface/Interface.cs +++ b/ZSharp.IR/ir/oop/interface/Interface.cs @@ -2,10 +2,10 @@ namespace ZSharp.IR { - public sealed class Interface(string? name) : OOPType + public sealed class Interface(string? name) : TypeDefinition { private Collection? _genericParameters; - private Collection>? _bases; + private Collection>? _bases; private Collection? _methods; public string? Name { get; set; } = name; @@ -26,7 +26,7 @@ public Collection GenericParameters public bool HasGenericParameters => !_genericParameters.IsNullOrEmpty(); - public Collection> Bases + public Collection> Bases { get { diff --git a/ZSharp.IR/ir/oop/interface/InterfaceImplementation.cs b/ZSharp.IR/ir/oop/interface/InterfaceImplementation.cs index 00777ec7..67707302 100644 --- a/ZSharp.IR/ir/oop/interface/InterfaceImplementation.cs +++ b/ZSharp.IR/ir/oop/interface/InterfaceImplementation.cs @@ -2,9 +2,9 @@ namespace ZSharp.IR { - public sealed class InterfaceImplementation(OOPTypeReference @interface) + public sealed class InterfaceImplementation(TypeReference @interface) { - public OOPTypeReference Interface { get; set; } = @interface; + public TypeReference Interface { get; set; } = @interface; /// /// Mapping from interface method to implementation method. diff --git a/ZSharp.IR/ir/oop/interface/InterfaceReference.cs b/ZSharp.IR/ir/oop/interface/InterfaceReference.cs index ad250466..d9273798 100644 --- a/ZSharp.IR/ir/oop/interface/InterfaceReference.cs +++ b/ZSharp.IR/ir/oop/interface/InterfaceReference.cs @@ -1,10 +1,10 @@ namespace ZSharp.IR { public sealed class InterfaceReference(Interface @interface) - : OOPTypeReference + : TypeReference { public Interface Definition { get; } = @interface; - public OOPTypeReference? OwningType { get; set; } + public TypeReference? OwningType { get; set; } } } diff --git a/ZSharp.IR/ir/oop/method/Method.cs b/ZSharp.IR/ir/oop/method/Method.cs index 246c1a5c..01967d5e 100644 --- a/ZSharp.IR/ir/oop/method/Method.cs +++ b/ZSharp.IR/ir/oop/method/Method.cs @@ -38,7 +38,7 @@ public Signature Signature public bool HasBody => UnderlyingFunction.HasBody; - public OOPType? Owner { get; set; } + public TypeDefinition? Owner { get; set; } public Module? Module => Owner?.Module; diff --git a/ZSharp.IR/ir/oop/method/MethodReference.cs b/ZSharp.IR/ir/oop/method/MethodReference.cs index b219a514..204e27b6 100644 --- a/ZSharp.IR/ir/oop/method/MethodReference.cs +++ b/ZSharp.IR/ir/oop/method/MethodReference.cs @@ -5,7 +5,7 @@ public class MethodReference(Method method) { public Method Method { get; set; } = method; - public required OOPTypeReference OwningType { get; set; } + public required TypeReference OwningType { get; set; } public Signature Signature { get; init; } = method.Signature; diff --git a/ZSharp.IR/ir/oop/value type/ConstructedValueType.cs b/ZSharp.IR/ir/oop/value type/ConstructedValueType.cs index 788b940a..1a62a3ca 100644 --- a/ZSharp.IR/ir/oop/value type/ConstructedValueType.cs +++ b/ZSharp.IR/ir/oop/value type/ConstructedValueType.cs @@ -7,9 +7,9 @@ public sealed class ConstructedValueType(ValueType @class) { public ValueType ValueType { get; set; } = @class; - ValueType OOPTypeReference.Definition => ValueType; + ValueType TypeReference.Definition => ValueType; - public OOPTypeReference? OwningType { get; set; } + public TypeReference? OwningType { get; set; } public Collection Arguments { get; set; } = false ? [] : Collection.Empty; } diff --git a/ZSharp.IR/ir/oop/value type/ValueType.cs b/ZSharp.IR/ir/oop/value type/ValueType.cs index 0a52d8ad..f0fc9992 100644 --- a/ZSharp.IR/ir/oop/value type/ValueType.cs +++ b/ZSharp.IR/ir/oop/value type/ValueType.cs @@ -1,6 +1,6 @@ namespace ZSharp.IR { - public sealed class ValueType(string? name) : OOPType + public sealed class ValueType(string? name) : TypeDefinition { public string? Name { get; set; } = name; } diff --git a/ZSharp.IR/ir/oop/value type/ValueTypeReference.cs b/ZSharp.IR/ir/oop/value type/ValueTypeReference.cs index c447146d..679dfc18 100644 --- a/ZSharp.IR/ir/oop/value type/ValueTypeReference.cs +++ b/ZSharp.IR/ir/oop/value type/ValueTypeReference.cs @@ -1,10 +1,10 @@ namespace ZSharp.IR { public sealed class ValueTypeReference(ValueType valueType) - : OOPTypeReference + : TypeReference { public ValueType Definition { get; } = valueType; - public OOPTypeReference? OwningType { get; set; } + public TypeReference? OwningType { get; set; } } } diff --git a/ZSharp.IR/ir/typeclass/Typeclass.cs b/ZSharp.IR/ir/typeclass/Typeclass.cs index 4e595eb2..5660f86c 100644 --- a/ZSharp.IR/ir/typeclass/Typeclass.cs +++ b/ZSharp.IR/ir/typeclass/Typeclass.cs @@ -2,13 +2,13 @@ namespace ZSharp.IR { - public sealed class Typeclass : OOPType + public sealed class Typeclass : TypeDefinition { public string? Name { get; set; } public TypeclassAttributes Attributes { get; set; } = TypeclassAttributes.None; - public Collection> Bases { get; } + public Collection> Bases { get; } public GenericParameter Parameter { get; } diff --git a/ZSharp.IR/ir/typeclass/TypeclassImplementation.cs b/ZSharp.IR/ir/typeclass/TypeclassImplementation.cs index 0960e80f..03c9b45e 100644 --- a/ZSharp.IR/ir/typeclass/TypeclassImplementation.cs +++ b/ZSharp.IR/ir/typeclass/TypeclassImplementation.cs @@ -2,7 +2,7 @@ namespace ZSharp.IR { - public sealed class TypeclassImplementation(Typeclass typeclass) : OOPType + public sealed class TypeclassImplementation(Typeclass typeclass) : TypeDefinition { public Typeclass Typeclass { get; } = typeclass; diff --git a/ZSharp.IR/ir/types/OOPType.cs b/ZSharp.IR/ir/types/OOPType.cs deleted file mode 100644 index a379a235..00000000 --- a/ZSharp.IR/ir/types/OOPType.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.IR -{ - public abstract class OOPType : ModuleMember - { - - } -} diff --git a/ZSharp.IR/ir/types/TypeDefinition.cs b/ZSharp.IR/ir/types/TypeDefinition.cs new file mode 100644 index 00000000..d8de97d7 --- /dev/null +++ b/ZSharp.IR/ir/types/TypeDefinition.cs @@ -0,0 +1,7 @@ +namespace ZSharp.IR +{ + public abstract class TypeDefinition : ModuleMember + { + + } +} diff --git a/ZSharp.IR/type system/types/ConstructedType.cs b/ZSharp.IR/type system/types/ConstructedType.cs index d89687c7..372b7c8d 100644 --- a/ZSharp.IR/type system/types/ConstructedType.cs +++ b/ZSharp.IR/type system/types/ConstructedType.cs @@ -3,15 +3,15 @@ namespace ZSharp.IR { public interface ConstructedType - : OOPTypeReference + : TypeReference { public abstract Collection Arguments { get; } } public interface ConstructedType : ConstructedType - , OOPTypeReference - where T : OOPType + , TypeReference + where T : TypeDefinition { } diff --git a/ZSharp.IR/type system/types/OOPTypeReference.cs b/ZSharp.IR/type system/types/OOPTypeReference.cs deleted file mode 100644 index fa030fe8..00000000 --- a/ZSharp.IR/type system/types/OOPTypeReference.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace ZSharp.IR -{ - public interface OOPTypeReference : IType - { - public OOPTypeReference? OwningType { get; set; } - - public OOPType Definition { get; } - } - - public interface OOPTypeReference : OOPTypeReference - where T : OOPType - { - public new T Definition { get; } - - OOPType OOPTypeReference.Definition { - get => Definition; - } - } -} diff --git a/ZSharp.IR/type system/types/TypeReference.cs b/ZSharp.IR/type system/types/TypeReference.cs new file mode 100644 index 00000000..3e17c65e --- /dev/null +++ b/ZSharp.IR/type system/types/TypeReference.cs @@ -0,0 +1,19 @@ +namespace ZSharp.IR +{ + public interface TypeReference : IType + { + public TypeReference? OwningType { get; set; } + + public TypeDefinition Definition { get; } + } + + public interface TypeReference : TypeReference + where T : TypeDefinition + { + public new T Definition { get; } + + TypeDefinition TypeReference.Definition { + get => Definition; + } + } +} diff --git a/ZSharp.IR/vm/instructions/misc/GetClass.cs b/ZSharp.IR/vm/instructions/misc/GetClass.cs index b684cbfb..c683a627 100644 --- a/ZSharp.IR/vm/instructions/misc/GetClass.cs +++ b/ZSharp.IR/vm/instructions/misc/GetClass.cs @@ -1,11 +1,11 @@ namespace ZSharp.IR.VM { - public sealed class GetClass(OOPTypeReference @class) + public sealed class GetClass(TypeReference @class) : Instruction - , IHasOperand> + , IHasOperand> { - public OOPTypeReference Class { get; set; } = @class; + public TypeReference Class { get; set; } = @class; - OOPTypeReference IHasOperand>.Operand => Class; + TypeReference IHasOperand>.Operand => Class; } } diff --git a/ZSharp.IR/vm/instructions/object/CastReference.cs b/ZSharp.IR/vm/instructions/object/CastReference.cs index fc36d1cb..43a15bb7 100644 --- a/ZSharp.IR/vm/instructions/object/CastReference.cs +++ b/ZSharp.IR/vm/instructions/object/CastReference.cs @@ -1,7 +1,7 @@ namespace ZSharp.IR.VM { - public sealed class CastReference(OOPTypeReference targetType) : Instruction + public sealed class CastReference(TypeReference targetType) : Instruction { - public OOPTypeReference Type { get; set; } = targetType; + public TypeReference Type { get; set; } = targetType; } } diff --git a/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs index 0d1d9717..0aa1d76b 100644 --- a/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs @@ -25,7 +25,7 @@ public sealed partial class ILLoader var code = rt.Expose(obj); - var function = new IR.GenericFunctionInstance(castFunction!); + var function = new IR.ConstructedFunction(castFunction!); function.Arguments.Add(irType); code.Add(new IR.VM.Call(function)); diff --git a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs index 48015685..90862835 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs @@ -5,15 +5,15 @@ namespace ZSharp.Importer.ILLoader.Objects { partial class Class : ICompileIRDefinitionAs - , ICompileIRType> + , ICompileIRType> { private IR.Class? IR { get; set; } Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) => Result.Ok(GetIR()); - Result> ICompileIRType>.CompileIRType(Compiler.Compiler compiler) - => Result>.Ok(new ClassReference(GetIR())); + Result> ICompileIRType>.CompileIRType(Compiler.Compiler compiler) + => Result>.Ok(new ClassReference(GetIR())); private IR.Class GetIR() { diff --git a/ZSharp.Importer.ILLoader/objects/types/array/ArrayType.cs b/ZSharp.Importer.ILLoader/objects/types/array/ArrayType.cs index 3baf6970..4f617c99 100644 --- a/ZSharp.Importer.ILLoader/objects/types/array/ArrayType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/array/ArrayType.cs @@ -2,9 +2,9 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class ArrayType(OOPType type) + public sealed class ArrayType(TypeDefinition type) : CompilerObject { - private readonly OOPType type = type; + private readonly TypeDefinition type = type; } } diff --git a/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs b/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs index e91c9c53..b14ba134 100644 --- a/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs @@ -3,11 +3,11 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class BooleanType(OOPTypeReference type) + public sealed class BooleanType(TypeReference type) : CompilerObject , ICompileIRType { - private readonly OOPTypeReference type = type; + private readonly TypeReference type = type; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); diff --git a/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs b/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs index 653bd50e..9f88e839 100644 --- a/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs @@ -3,11 +3,11 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class CharType(OOPTypeReference type) + public sealed class CharType(TypeReference type) : CompilerObject , ICompileIRType { - private readonly OOPTypeReference type = type; + private readonly TypeReference type = type; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs index 63b2137c..25da461d 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs @@ -3,11 +3,11 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class Float128Type(OOPTypeReference type) + public sealed class Float128Type(TypeReference type) : CompilerObject , ICompileIRType { - private readonly OOPTypeReference type = type; + private readonly TypeReference type = type; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs index 1463ab51..23dc3dbf 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs @@ -3,11 +3,11 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class Float16Type(OOPTypeReference type) + public sealed class Float16Type(TypeReference type) : CompilerObject , ICompileIRType { - private readonly OOPTypeReference type = type; + private readonly TypeReference type = type; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs index 40ec3fc4..5c20dd7b 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs @@ -3,11 +3,11 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class Float32Type(OOPTypeReference type) + public sealed class Float32Type(TypeReference type) : CompilerObject , ICompileIRType { - private readonly OOPTypeReference type = type; + private readonly TypeReference type = type; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs index 56326fd4..f242c7fe 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs @@ -3,11 +3,11 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class Float64Type(OOPTypeReference type) + public sealed class Float64Type(TypeReference type) : CompilerObject , ICompileIRType { - private readonly OOPTypeReference type = type; + private readonly TypeReference type = type; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); diff --git a/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs b/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs index c18d78eb..8e528872 100644 --- a/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs @@ -3,11 +3,11 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class ObjectType(OOPTypeReference type) + public sealed class ObjectType(TypeReference type) : CompilerObject , ICompileIRType { - private readonly OOPTypeReference type = type; + private readonly TypeReference type = type; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); diff --git a/ZSharp.Importer.ILLoader/objects/types/pointer/PointerType.cs b/ZSharp.Importer.ILLoader/objects/types/pointer/PointerType.cs index a308210c..0f645f48 100644 --- a/ZSharp.Importer.ILLoader/objects/types/pointer/PointerType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/pointer/PointerType.cs @@ -2,9 +2,9 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class PointerType(OOPType type) + public sealed class PointerType(TypeDefinition type) : CompilerObject { - private readonly OOPType type = type; + private readonly TypeDefinition type = type; } } diff --git a/ZSharp.Importer.ILLoader/objects/types/reference/ReferenceType.cs b/ZSharp.Importer.ILLoader/objects/types/reference/ReferenceType.cs index ff2a3a61..5080fafb 100644 --- a/ZSharp.Importer.ILLoader/objects/types/reference/ReferenceType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/reference/ReferenceType.cs @@ -2,9 +2,9 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class ReferenceType(OOPType type) + public sealed class ReferenceType(TypeDefinition type) : CompilerObject { - private readonly OOPType type = type; + private readonly TypeDefinition type = type; } } diff --git a/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs index 55eee271..8634292e 100644 --- a/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs @@ -3,11 +3,11 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class StringType(OOPTypeReference type) + public sealed class StringType(TypeReference type) : CompilerObject , ICompileIRType { - private readonly OOPTypeReference type = type; + private readonly TypeReference type = type; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); diff --git a/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs b/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs index 78f7455e..0fb28345 100644 --- a/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs @@ -3,11 +3,11 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class VoidType(OOPTypeReference type) + public sealed class VoidType(TypeReference type) : CompilerObject , ICompileIRType { - private readonly OOPTypeReference type = type; + private readonly TypeReference type = type; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); diff --git a/ZSharp.Importer.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Importer.IRLoader/ir loader/IRLoader.Impl.cs index 461581ea..66d4c180 100644 --- a/ZSharp.Importer.IRLoader/ir loader/IRLoader.Impl.cs +++ b/ZSharp.Importer.IRLoader/ir loader/IRLoader.Impl.cs @@ -114,7 +114,7 @@ private Action Load(ZSharp.IR.Function function, Module owner) }; } - private Action Load(ZSharp.IR.OOPType type, Module owner) + private Action Load(ZSharp.IR.TypeDefinition type, Module owner) => type switch { ZSharp.IR.Class @class => Load(@class, owner), diff --git a/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Type.cs index 3ed2ef8a..86c7b807 100644 --- a/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Type.cs @@ -2,7 +2,7 @@ { partial class EmitLoader { - public Type LoadType(IR.OOPType type) + public Type LoadType(IR.TypeDefinition type) => TypeLoaderHelper.LoadType(this, StandaloneModule, type); } } diff --git a/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderBase.cs b/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderBase.cs index 57d13304..8b7dba5f 100644 --- a/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderBase.cs +++ b/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderBase.cs @@ -2,7 +2,7 @@ { internal abstract class TypeLoaderBase(EmitLoader loader) : LoaderBase(loader) - where T: IR.OOPType + where T: IR.TypeDefinition { public required Emit.TypeBuilder ILType { get; init; } diff --git a/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderHelper.cs b/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderHelper.cs index a353d13c..c3eaea44 100644 --- a/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderHelper.cs +++ b/ZSharp.Platform.Runtime/loader/helpers/TypeLoaderHelper.cs @@ -2,7 +2,7 @@ { internal static class TypeLoaderHelper { - public static Type LoadType(EmitLoader loader, Emit.TypeBuilder parentBuilder, IR.OOPType type) + public static Type LoadType(EmitLoader loader, Emit.TypeBuilder parentBuilder, IR.TypeDefinition type) { var tasks = new TaskManager(() => { }); var result = type switch @@ -42,7 +42,7 @@ public static Type LoadType(EmitLoader loader, Emit.TypeBuilder parentBuilder, I return result; } - public static Type LoadType(EmitLoader loader, Emit.ModuleBuilder parentBuilder, IR.OOPType type) + public static Type LoadType(EmitLoader loader, Emit.ModuleBuilder parentBuilder, IR.TypeDefinition type) { var tasks = new TaskManager(() => { }); var result = type switch diff --git a/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs index eabaa431..52437ddf 100644 --- a/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/class/load/ClassLoader.Load.Type.cs @@ -2,7 +2,7 @@ { partial class ClassLoader { - private void LoadNestedType(IR.OOPType type) + private void LoadNestedType(IR.TypeDefinition type) { TypeLoaderHelper.LoadType(Loader, ILType, type); } diff --git a/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs index b538acc9..1b260c59 100644 --- a/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/enum/load/EnumClassLoader.Load.Type.cs @@ -2,7 +2,7 @@ { partial class EnumClassLoader { - private void LoadNestedType(IR.OOPType type) + private void LoadNestedType(IR.TypeDefinition type) { TypeLoaderHelper.LoadType(Loader, ILType, type); } diff --git a/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs index 0ef79a09..7611fb04 100644 --- a/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/interface/load/InterfaceLoader.Load.Type.cs @@ -2,7 +2,7 @@ { partial class InterfaceLoader { - private void LoadNestedType(IR.OOPType type) + private void LoadNestedType(IR.TypeDefinition type) { TypeLoaderHelper.LoadType(Loader, ILType, type); } diff --git a/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs index 7630ef71..5e164f53 100644 --- a/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/module/load/ModuleLoader.Load.Type.cs @@ -2,7 +2,7 @@ { partial class ModuleLoader { - public void LoadType(IR.OOPType type) + public void LoadType(IR.TypeDefinition type) => TypeLoaderHelper.LoadType(Loader, ILModule, type); } } diff --git a/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs index ea914e6e..6701addf 100644 --- a/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/value type/load/ValueTypeLoader.Load.Type.cs @@ -2,7 +2,7 @@ { partial class ValueTypeLoader { - private void LoadNestedType(IR.OOPType type) + private void LoadNestedType(IR.TypeDefinition type) { TypeLoaderHelper.LoadType(Loader, ILType, type); } diff --git a/ZSharp.Platform.Runtime/runtime/Runtime.cs b/ZSharp.Platform.Runtime/runtime/Runtime.cs index 4aca18bd..ab860664 100644 --- a/ZSharp.Platform.Runtime/runtime/Runtime.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.cs @@ -25,7 +25,7 @@ public Runtime(TypeSystem typeSystem, bool debugging = true) Loader = new(this); - foreach (var (ir, il) in (IEnumerable<(IR.OOPTypeReference, Type)>)[ + foreach (var (ir, il) in (IEnumerable<(IR.TypeReference, Type)>)[ (TypeSystem.Void, typeof(void)), (TypeSystem.Boolean, typeof(bool)), (TypeSystem.Object, typeof(object)), diff --git a/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Type.cs b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Type.cs index 7d43d09c..720369da 100644 --- a/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Type.cs +++ b/ZSharp.Platform.Runtime/runtime/cache/Runtime.Cache.Type.cs @@ -5,7 +5,7 @@ namespace ZSharp.Platform.Runtime partial class Runtime { private Cache _typeCache = []; - private readonly Dictionary _typeDefCache = []; + private readonly Dictionary _typeDefCache = []; public Cache NewTypeContext() => new() { Parent = _typeCache }; @@ -28,13 +28,13 @@ public void DelType(IR.IType ir) public void SetType(IR.IType ir, Type il) => _typeCache.Cache(ir, il); - public void AddTypeDefinition(IR.OOPType ir, Type il) + public void AddTypeDefinition(IR.TypeDefinition ir, Type il) => _typeDefCache.Add(ir, il); - public void DelTypeDefinition(IR.OOPType ir) + public void DelTypeDefinition(IR.TypeDefinition ir) => _typeDefCache.Remove(ir); - public void SetTypeDefinition(IR.OOPType ir, Type il) + public void SetTypeDefinition(IR.TypeDefinition ir, Type il) => _typeDefCache[ir] = il; } } diff --git a/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Callable.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Callable.cs index 1b5b2e1b..777e6913 100644 --- a/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Callable.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Callable.cs @@ -9,7 +9,7 @@ public IL.MethodBase ImportCallable(IR.ICallable callable) IR.Method target => ImportMethod(target), IR.MethodReference target => ImportMethodReference(target), IR.Function target => ImportFunction(target), - IR.GenericFunctionInstance target => ImportConstructedFunction(target), + IR.ConstructedFunction target => ImportConstructedFunction(target), _ => throw new ArgumentException( $"Invalid callable type: {callable.GetType()}", nameof(callable) diff --git a/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Function.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Function.cs index dc321f17..032e9080 100644 --- a/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Function.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Function.cs @@ -12,7 +12,7 @@ public IL.MethodInfo ImportFunction(IR.Function function) return info; } - public IL.MethodInfo ImportConstructedFunction(IR.GenericFunctionInstance constructedFunction) + public IL.MethodInfo ImportConstructedFunction(IR.ConstructedFunction constructedFunction) { var def = ImportFunction(constructedFunction.Function); diff --git a/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.Modified.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.Modified.cs index 266f01c2..cdcd9cd4 100644 --- a/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.Modified.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.Modified.cs @@ -2,7 +2,7 @@ { partial class Runtime { - private Type ImportArrayType(IR.OOPTypeReference @ref) + private Type ImportArrayType(IR.TypeReference @ref) { var con = (IR.ConstructedType)@ref; var elementType = ImportType(con.Arguments[0]); @@ -10,7 +10,7 @@ private Type ImportArrayType(IR.OOPTypeReference @ref) return elementType.MakeArrayType(); } - private Type ImportPointerType(IR.OOPTypeReference @ref) + private Type ImportPointerType(IR.TypeReference @ref) { var con = (IR.ConstructedType)@ref; var elementType = ImportType(con.Arguments[0]); @@ -18,7 +18,7 @@ private Type ImportPointerType(IR.OOPTypeReference @ref) return elementType.MakePointerType(); } - private Type ImportReferenceType(IR.OOPTypeReference @ref) + private Type ImportReferenceType(IR.TypeReference @ref) { var con = (IR.ConstructedType)@ref; var elementType = ImportType(con.Arguments[0]); diff --git a/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.cs index fc704ef6..b59bc175 100644 --- a/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Type.cs @@ -10,12 +10,12 @@ public Type ImportType(IR.IType type) return type switch { - IR.OOPTypeReference reference => ImportTypeReference(reference), + IR.TypeReference reference => ImportTypeReference(reference), _ => throw new NotImplementedException() }; } - public Type ImportTypeDefinition(IR.OOPType def) + public Type ImportTypeDefinition(IR.TypeDefinition def) { if (!_typeDefCache.TryGetValue(def, out var result)) result = _typeDefCache[def] = LoadType(def); @@ -23,7 +23,7 @@ public Type ImportTypeDefinition(IR.OOPType def) return result; } - public Type ImportTypeReference(IR.OOPTypeReference @ref) + public Type ImportTypeReference(IR.TypeReference @ref) { if ( @ref.Definition == TypeSystem.Array diff --git a/ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Type.cs b/ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Type.cs index 8549fbba..7ef706b9 100644 --- a/ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Type.cs +++ b/ZSharp.Platform.Runtime/runtime/load/Runtime.Load.Type.cs @@ -2,7 +2,7 @@ { partial class Runtime { - private Type LoadType(IR.OOPType type) + private Type LoadType(IR.TypeDefinition type) { if (type.Module is not null) throw new InvalidOperationException( diff --git a/ZSharp.Platform.Runtime/type system/TypeSystem.Array.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Array.cs index 7fd3e0e5..5115ebdf 100644 --- a/ZSharp.Platform.Runtime/type system/TypeSystem.Array.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Array.cs @@ -2,6 +2,6 @@ { partial class TypeSystem { - public required IR.OOPType Array { get; init; } + public required IR.TypeDefinition Array { get; init; } } } diff --git a/ZSharp.Platform.Runtime/type system/TypeSystem.Boolean.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Boolean.cs index 44e809c1..77e6b15c 100644 --- a/ZSharp.Platform.Runtime/type system/TypeSystem.Boolean.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Boolean.cs @@ -2,6 +2,6 @@ { partial class TypeSystem { - public required IR.OOPTypeReference Boolean { get; init; } + public required IR.TypeReference Boolean { get; init; } } } diff --git a/ZSharp.Platform.Runtime/type system/TypeSystem.Char.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Char.cs index 0df7d0f4..b434b984 100644 --- a/ZSharp.Platform.Runtime/type system/TypeSystem.Char.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Char.cs @@ -2,6 +2,6 @@ { partial class TypeSystem { - public required IR.OOPTypeReference Char { get; init; } + public required IR.TypeReference Char { get; init; } } } diff --git a/ZSharp.Platform.Runtime/type system/TypeSystem.Float.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Float.cs index 6838cbec..689854ea 100644 --- a/ZSharp.Platform.Runtime/type system/TypeSystem.Float.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Float.cs @@ -2,12 +2,12 @@ { partial class TypeSystem { - public required IR.OOPTypeReference Float16 { get; init; } + public required IR.TypeReference Float16 { get; init; } - public required IR.OOPTypeReference Float32 { get; init; } + public required IR.TypeReference Float32 { get; init; } - public required IR.OOPTypeReference Float64 { get; init; } + public required IR.TypeReference Float64 { get; init; } - public required IR.OOPTypeReference Float128 { get; init; } + public required IR.TypeReference Float128 { get; init; } } } diff --git a/ZSharp.Platform.Runtime/type system/TypeSystem.Object.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Object.cs index 4eb6a5e0..672cec61 100644 --- a/ZSharp.Platform.Runtime/type system/TypeSystem.Object.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Object.cs @@ -2,6 +2,6 @@ { partial class TypeSystem { - public required IR.OOPTypeReference Object { get; init; } + public required IR.TypeReference Object { get; init; } } } diff --git a/ZSharp.Platform.Runtime/type system/TypeSystem.Pointer.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Pointer.cs index 120e5ea2..8411cecd 100644 --- a/ZSharp.Platform.Runtime/type system/TypeSystem.Pointer.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Pointer.cs @@ -2,6 +2,6 @@ { partial class TypeSystem { - public required IR.OOPType Pointer { get; init; } + public required IR.TypeDefinition Pointer { get; init; } } } diff --git a/ZSharp.Platform.Runtime/type system/TypeSystem.Reference.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Reference.cs index 63a2fa79..f534e91b 100644 --- a/ZSharp.Platform.Runtime/type system/TypeSystem.Reference.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Reference.cs @@ -2,6 +2,6 @@ { partial class TypeSystem { - public required IR.OOPType Reference { get; init; } + public required IR.TypeDefinition Reference { get; init; } } } diff --git a/ZSharp.Platform.Runtime/type system/TypeSystem.SInt.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.SInt.cs index cb7b6166..ccdbaa30 100644 --- a/ZSharp.Platform.Runtime/type system/TypeSystem.SInt.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.SInt.cs @@ -2,14 +2,14 @@ { partial class TypeSystem { - public required IR.OOPTypeReference SInt8 { get; init; } + public required IR.TypeReference SInt8 { get; init; } - public required IR.OOPTypeReference SInt16 { get; init; } + public required IR.TypeReference SInt16 { get; init; } - public required IR.OOPTypeReference SInt32 { get; init; } + public required IR.TypeReference SInt32 { get; init; } - public required IR.OOPTypeReference SInt64 { get; init; } + public required IR.TypeReference SInt64 { get; init; } - public required IR.OOPTypeReference SIntNative { get; init; } + public required IR.TypeReference SIntNative { get; init; } } } diff --git a/ZSharp.Platform.Runtime/type system/TypeSystem.String.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.String.cs index f70538bf..e5351c6f 100644 --- a/ZSharp.Platform.Runtime/type system/TypeSystem.String.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.String.cs @@ -2,6 +2,6 @@ { partial class TypeSystem { - public required IR.OOPTypeReference String { get; init; } + public required IR.TypeReference String { get; init; } } } diff --git a/ZSharp.Platform.Runtime/type system/TypeSystem.UInt.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.UInt.cs index 4bcba4f5..6254412e 100644 --- a/ZSharp.Platform.Runtime/type system/TypeSystem.UInt.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.UInt.cs @@ -2,14 +2,14 @@ { partial class TypeSystem { - public required IR.OOPTypeReference UInt8 { get; init; } + public required IR.TypeReference UInt8 { get; init; } - public required IR.OOPTypeReference UInt16 { get; init; } + public required IR.TypeReference UInt16 { get; init; } - public required IR.OOPTypeReference UInt32 { get; init; } + public required IR.TypeReference UInt32 { get; init; } - public required IR.OOPTypeReference UInt64 { get; init; } + public required IR.TypeReference UInt64 { get; init; } - public required IR.OOPTypeReference UIntNative { get; init; } + public required IR.TypeReference UIntNative { get; init; } } } diff --git a/ZSharp.Platform.Runtime/type system/TypeSystem.Void.cs b/ZSharp.Platform.Runtime/type system/TypeSystem.Void.cs index 0b8b3eb6..cf7b41e4 100644 --- a/ZSharp.Platform.Runtime/type system/TypeSystem.Void.cs +++ b/ZSharp.Platform.Runtime/type system/TypeSystem.Void.cs @@ -2,6 +2,6 @@ { partial class TypeSystem { - public required IR.OOPTypeReference Void { get; init; } + public required IR.TypeReference Void { get; init; } } } From 383d529a94a63b44723fc91e95eab353c5bfaced Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 9 Oct 2025 21:53:30 +0300 Subject: [PATCH 216/235] Remove support for debugging --- .../loader/emit/load/EmitLoader.Load.Code.cs | 5 +- .../code/code contexts/UnboundCodeContext.cs | 5 +- .../loader/loaders/code/code/CodeCompiler.cs | 12 ----- .../code/code/debugging/IDebuggableContext.cs | 10 ---- .../code/code/debugging/SourceLocation.cs | 13 ----- .../runtime/Runtime.Evaluate.cs | 6 +-- ZSharp.Platform.Runtime/runtime/Runtime.cs | 4 +- .../compiler/ScriptCompiler.Debugging.cs | 27 ---------- .../compiler/ScriptCompiler.cs | 10 ++-- .../expr/ScriptCompiler.Compile.Identifier.cs | 2 +- .../stmt/ScriptCompiler.Compile.Expression.cs | 2 +- .../stmt/ScriptCompiler.Compile.Import.cs | 36 ++++++-------- .../objects/ExpressionWrapper.cs | 48 ------------------ .../objects/IdentifierBoundObject.cs | 49 ------------------- .../runtime contexts/DebuggingContext.cs | 19 ------- 15 files changed, 27 insertions(+), 221 deletions(-) delete mode 100644 ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/IDebuggableContext.cs delete mode 100644 ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/SourceLocation.cs delete mode 100644 ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Debugging.cs delete mode 100644 ZSharp.SourceCompiler.Script/objects/ExpressionWrapper.cs delete mode 100644 ZSharp.SourceCompiler.Script/objects/IdentifierBoundObject.cs delete mode 100644 ZSharp.SourceCompiler.Script/runtime contexts/DebuggingContext.cs diff --git a/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Code.cs b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Code.cs index b768dd71..a548b5b1 100644 --- a/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Code.cs +++ b/ZSharp.Platform.Runtime/loader/emit/load/EmitLoader.Load.Code.cs @@ -12,8 +12,7 @@ partial class EmitLoader public Delegate LoadCode( Collection code, IR.IType irReturnType, - IEvaluationContext evaluationContext, - IContext? codeContext = null + IEvaluationContext evaluationContext ) { if (code.Count == 0) return () => { }; @@ -24,7 +23,7 @@ public Delegate LoadCode( var ilReturnType = Runtime.ImportType(irReturnType); var ilGenerator = evaluationContext.DefineCode(ilReturnType); - var codeLoader = new CodeCompiler(new UnboundCodeContext(Runtime, ilGenerator, codeContext)); + var codeLoader = new CodeCompiler(new UnboundCodeContext(Runtime, ilGenerator)); codeLoader.CompileCode(code); var method = evaluationContext.LoadMethod(); diff --git a/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs index 38143d87..072d030a 100644 --- a/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code contexts/UnboundCodeContext.cs @@ -3,11 +3,10 @@ namespace ZSharp.Platform.Runtime.Loaders { - internal sealed class UnboundCodeContext(Runtime runtime, Emit.ILGenerator il, IContext? inner = null) + internal sealed class UnboundCodeContext(Runtime runtime, Emit.ILGenerator il) : ICodeContext , IBranchingCodeContext { - private readonly IContext? inner = inner; private readonly Mapping labels = []; public Emit.ILGenerator IL { get; } = il; @@ -23,6 +22,6 @@ Emit.Label IBranchingCodeContext.GetBranchTarget(IR.VM.Instruction target) => labels[target]; bool IContext.Is([NotNullWhen(true)] out T? context) where T : class - => (context = this as T) is not null || (inner?.Is(out context) ?? false); + => (context = this as T) is not null; } } diff --git a/ZSharp.Platform.Runtime/loader/loaders/code/code/CodeCompiler.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/CodeCompiler.cs index b5a25ef6..98baad79 100644 --- a/ZSharp.Platform.Runtime/loader/loaders/code/code/CodeCompiler.cs +++ b/ZSharp.Platform.Runtime/loader/loaders/code/code/CodeCompiler.cs @@ -26,18 +26,6 @@ public void CompileCode(Collection instructions) private void Compile(IR.VM.Instruction instruction) { - if (Context.Is(out var debuggable)) - { - if (debuggable.TryGetSequencePoint(instruction, out var location)) - Context.IL.MarkSequencePoint( - debuggable.Document, - location.StartLine, - location.StartColumn, - location.EndLine, - location.EndColumn - ); - } - switch (instruction) { case IR.VM.Call call: CodeCompiler_Impl.Compile(RequireContext(), call); break; diff --git a/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/IDebuggableContext.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/IDebuggableContext.cs deleted file mode 100644 index aa35bed6..00000000 --- a/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/IDebuggableContext.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Platform.Runtime.Loaders -{ - public interface IDebuggableContext - : IContext - { - public System.Diagnostics.SymbolStore.ISymbolDocumentWriter Document { get; } - - public bool TryGetSequencePoint(IR.VM.Instruction instruction, out SourceLocation location); - } -} diff --git a/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/SourceLocation.cs b/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/SourceLocation.cs deleted file mode 100644 index aeacf2f9..00000000 --- a/ZSharp.Platform.Runtime/loader/loaders/code/code/debugging/SourceLocation.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ZSharp.Platform.Runtime.Loaders -{ - public struct SourceLocation - { - public int StartLine { get; init; } - - public int EndLine { get; init; } - - public int StartColumn { get; init; } - - public int EndColumn { get; init; } - } -} diff --git a/ZSharp.Platform.Runtime/runtime/Runtime.Evaluate.cs b/ZSharp.Platform.Runtime/runtime/Runtime.Evaluate.cs index acede4c3..85b5b3e0 100644 --- a/ZSharp.Platform.Runtime/runtime/Runtime.Evaluate.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.Evaluate.cs @@ -7,14 +7,12 @@ partial class Runtime public object? Evaluate( Collection code, IR.IType type, - IEvaluationContext? evaluationContext = null, - Loaders.IContext? innerContext = null + IEvaluationContext? evaluationContext = null ) { return Loader.LoadCode( code, type, - evaluationContext ?? EvaluationContextFactory.CreateEvaluationContext(), - innerContext + evaluationContext ?? EvaluationContextFactory.CreateEvaluationContext() ).DynamicInvoke(null); } } diff --git a/ZSharp.Platform.Runtime/runtime/Runtime.cs b/ZSharp.Platform.Runtime/runtime/Runtime.cs index ab860664..b5132fb4 100644 --- a/ZSharp.Platform.Runtime/runtime/Runtime.cs +++ b/ZSharp.Platform.Runtime/runtime/Runtime.cs @@ -4,14 +4,14 @@ public sealed partial class Runtime { public bool DebugEnabled { get; } - public Runtime(TypeSystem typeSystem, bool debugging = true) + public Runtime(TypeSystem typeSystem) { if (_instance is not null) throw new InvalidOperationException("Runtime instance already exists."); _instance = this; EvaluationContextFactory = - (DebugEnabled = debugging) + (DebugEnabled = !true) ? new DebuggableEvaluationContextFactory() { OutputPath = Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "generated")).FullName diff --git a/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Debugging.cs b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Debugging.cs deleted file mode 100644 index 15c35615..00000000 --- a/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.Debugging.cs +++ /dev/null @@ -1,27 +0,0 @@ -using CommonZ.Utils; -using System.Diagnostics.CodeAnalysis; - -namespace ZSharp.SourceCompiler.Script -{ - partial class ScriptCompiler - { - internal string DocumentPath { get; init; } - - internal DebuggingContext? DebugContext { get; set; } = null!; - - [MemberNotNullWhen(true, nameof(DebugContext), nameof(CurrentEvaluationContext))] - internal bool IsDebuggingEnabled => DebugContext is not null; - - private Platform.Runtime.IEvaluationContext? CurrentEvaluationContext { get; set; } - - private ContextManager EvaluationContext() - { - if (!Interpreter.Runtime.DebugEnabled) return new(() => { }); - CurrentEvaluationContext = Interpreter.Runtime.EvaluationContextFactory.CreateEvaluationContext(); - var document = CurrentEvaluationContext.Module.DefineDocument(DocumentPath); - DebugContext = new(document); - document.SetSource(File.ReadAllBytes(DocumentPath)); - return new(() => DebugContext = null); - } - } -} diff --git a/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs index e3fd2084..92424ac4 100644 --- a/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs +++ b/ZSharp.SourceCompiler.Script/compiler/ScriptCompiler.cs @@ -6,6 +6,8 @@ public sealed partial class ScriptCompiler public AST.Document Node { get; } + public string DocumentPath { get; } + public ScriptCompiler(Interpreter.Interpreter interpreter, AST.Document document, string path) { Interpreter = interpreter; @@ -27,13 +29,7 @@ public void Compile() //using var _ = Interpreter.Compiler.ContextScope(new DocumentContext()); using var _ = Interpreter.Compiler.ContextScope(new ScopeContext()); - foreach (var statement in Node.Statements) - { - using (EvaluationContext()) - { - Compile(statement); - } - } + Node.Statements.ForEach(Compile); } } } diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs index d104e60f..b0ae8c18 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs @@ -8,7 +8,7 @@ private Result Compile(AST.IdentifierExpression identifier) { foreach (var scope in Interpreter.Compiler.CurrentContext.FindContext()) if (scope.Get(identifier.Name).Ok(out var result)) - return Result.Ok(new Objects.IdentifierBoundObject(this, identifier, result)); + return Result.Ok(result); return Result.Error( $"Identifier '{identifier.Name}' not found." diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs index 9aefbc45..109fc499 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs @@ -20,7 +20,7 @@ private void Compile(AST.ExpressionStatement expressionStatement) return; } - Interpreter.Evaluate(valueObject!, CurrentEvaluationContext, DebugContext); + Interpreter.Evaluate(valueObject!); } } } diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs index 0f550ab9..3f445f33 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs @@ -54,40 +54,32 @@ [.. argumentsResults.Select(r => r.Unwrap())] return; } - Platform.Runtime.IEvaluationContext? evaluationContext = null; - var codeContext = DebugContext; - if (Interpreter.Runtime.DebugEnabled) + if ( + Interpreter.Evaluate(result!) + .When(out var importObject) + .Error(out error) + ) { - evaluationContext = Interpreter.Runtime.EvaluationContextFactory.CreateEvaluationContext(); - - result = new Objects.ExpressionWrapper( - codeContext = new( - evaluationContext.Module.DefineDocument( - DocumentPath, - System.Diagnostics.SymbolStore.SymLanguageType.CSharp, - System.Diagnostics.SymbolStore.SymLanguageVendor.Microsoft, - System.Diagnostics.SymbolStore.SymDocumentType.Text - ) - ), - import.TokenInfo.ImportKeyword.Span, - result! + Interpreter.Log.Error( + $"Failed to evaluate import: {error}", + new NodeLogOrigin(import) ); + return; } - + importResult = Interpreter.RTLoader.Load(importObject!); if ( - Interpreter.Evaluate(result!, evaluationContext, codeContext) - .When(out var importObject) + importResult + .When(out result) .Error(out error) ) { Interpreter.Log.Error( - $"Failed to evaluate import: {error}", + $"Failed to load import: {error}", new NodeLogOrigin(import) ); return; } - result = ZSharp.Interpreter.CTServices.InfoOf(importObject!); if (import.Alias is not null) { @@ -95,7 +87,7 @@ [.. argumentsResults.Select(r => r.Unwrap())] .Compiler .CurrentContext .PerformOperation( - scope => !scope.Add(import.Alias, result).Error(out error) + scope => !scope.Add(import.Alias, result!).Error(out error) ) ) { diff --git a/ZSharp.SourceCompiler.Script/objects/ExpressionWrapper.cs b/ZSharp.SourceCompiler.Script/objects/ExpressionWrapper.cs deleted file mode 100644 index bec81097..00000000 --- a/ZSharp.SourceCompiler.Script/objects/ExpressionWrapper.cs +++ /dev/null @@ -1,48 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.SourceCompiler.Script.Objects -{ - internal sealed class ExpressionWrapper( - DebuggingContext debugContext, - Text.Span span, - CompilerObject inner - ) - : CompilerObject - , IProxy - , ICompileIRCode - { - private readonly DebuggingContext debugContext = debugContext; - private readonly Text.Span span = span; - private readonly CompilerObject inner = inner; - - R IProxy.Apply(Func fn) - => fn(inner); - - Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) - { - if (target is not Platform.Runtime.Runtime runtime) - return compiler.IR.CompileCode(inner, target); - - var innerCodeResult = compiler.IR.CompileCode(inner, target); - - if ( - innerCodeResult - .When(out var innerCode) - .Error(out var error) - ) return Result.Error(error); - - debugContext.AddSequencePoint( - innerCode!.Instructions[0], - new() - { - StartLine = span.Start.Line, - StartColumn = span.Start.Column, - EndLine = span.End.Line, - EndColumn = span.End.Column - } - ); - - return innerCodeResult; - } - } -} diff --git a/ZSharp.SourceCompiler.Script/objects/IdentifierBoundObject.cs b/ZSharp.SourceCompiler.Script/objects/IdentifierBoundObject.cs deleted file mode 100644 index e0dc00d2..00000000 --- a/ZSharp.SourceCompiler.Script/objects/IdentifierBoundObject.cs +++ /dev/null @@ -1,49 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.SourceCompiler.Script.Objects -{ - internal sealed class IdentifierBoundObject( - ScriptCompiler compiler, - AST.IdentifierExpression identifier, - CompilerObject inner - ) - : CompilerObject - , IProxy - , ICompileIRCode - { - private readonly ScriptCompiler compiler = compiler; - private readonly AST.IdentifierExpression identifier = identifier; - private readonly CompilerObject inner = inner; - - R IProxy.Apply(Func fn) - => fn(inner); - - Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) - { - if (target is not Platform.Runtime.Runtime runtime || !this.compiler.IsDebuggingEnabled) - return compiler.IR.CompileCode(inner, target); - - var innerCodeResult = compiler.IR.CompileCode(inner, target); - - if ( - innerCodeResult - .When(out var innerCode) - .Error(out var error) - ) return Result.Error(error); - - var span = identifier.TokenInfo.Identifier.Span; - this.compiler.DebugContext.AddSequencePoint( - innerCode!.Instructions[0], - new() - { - StartLine = span.Start.Line, - StartColumn = span.Start.Column, - EndLine = span.End.Line, - EndColumn = span.End.Column - } - ); - - return innerCodeResult; - } - } -} diff --git a/ZSharp.SourceCompiler.Script/runtime contexts/DebuggingContext.cs b/ZSharp.SourceCompiler.Script/runtime contexts/DebuggingContext.cs deleted file mode 100644 index a4d9c489..00000000 --- a/ZSharp.SourceCompiler.Script/runtime contexts/DebuggingContext.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Diagnostics.SymbolStore; -using ZSharp.IR.VM; -using ZSharp.Platform.Runtime.Loaders; - -namespace ZSharp.SourceCompiler.Script -{ - internal sealed class DebuggingContext(ISymbolDocumentWriter document) - : IDebuggableContext - { - ISymbolDocumentWriter IDebuggableContext.Document { get; } = document; - private readonly Dictionary sequencePoints = []; - - bool IDebuggableContext.TryGetSequencePoint(Instruction instruction, out SourceLocation location) - => sequencePoints.TryGetValue(instruction, out location); - - public void AddSequencePoint(Instruction instruction, SourceLocation location) - => sequencePoints[instruction] = location; - } -} From e7d5a556c36979165a812a12c486218cb70744ac Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 9 Oct 2025 22:49:34 +0300 Subject: [PATCH 217/235] Add stuff --- Examples/test.zs | 9 +-- Testing/Program.cs | 2 +- ZSharp v1.sln | 6 ++ ZSharp.CLI/Program.cs | 28 +++++++- ZSharp.CLI/StandardTypes.cs | 12 ++++ .../services/Dispatcher.ImplicitCast.cs | 3 + ZSharp.Compiler.Core/result/Result.cs | 6 ++ .../dispatcher/Dispatcher.Definition.cs | 8 +++ .../dispatcher/Dispatcher.GetCO.cs | 15 ----- .../services/Reflection.Definition.cs | 9 +++ .../reflection/services/Reflection.GetCO.cs | 9 --- ZSharp.Compiler/compiler/Compiler.Services.cs | 16 +++-- ZSharp.Compiler/compiler/Compiler.cs | 15 +---- ZSharp.Importer.ILLoader/GlobalUsings.cs | 10 ++- .../load/ILLoader.Load.Type.Interface.cs | 2 +- .../objects/GlobalUsings.cs | 9 --- .../function/concrete/Function.Call.cs | 6 +- .../objects/modular/global/Global.CG.Get.cs | 16 +++++ .../objects/modular/global/Global.IR.cs | 30 +++++++++ .../objects/modular/global/Global.cs | 1 + .../objects/modular/module/Module.Member.cs | 6 +- .../type as module/TypeAsModule.Member.cs | 6 +- .../objects/namespace/Namespace.Member.cs | 6 +- .../oop/interface/concrete/Interface.IL.cs | 9 +++ .../oop/interface/concrete/Interface.IR.cs | 37 +++++++++++ .../oop/interface/concrete/Interface.cs | 9 +++ .../oop/method/bound/BoundMethod.Call.cs | 2 +- .../oop/method/concrete/Method.Call.cs | 6 +- ZSharp.Importer.RT/GlobalUsings.cs | 6 ++ ZSharp.Importer.RT/ZSharp.Importer.RT.csproj | 15 +++++ .../objects/string/StringLiteral.IR.cs | 17 +++++ .../objects/string/StringLiteral.cs | 11 ++++ .../rt loader/Loader.Load.Primitives.cs | 8 +++ ZSharp.Importer.RT/rt loader/Loader.Load.cs | 21 ++++++ .../rt loader/Loader.TypeSystem.cs | 7 ++ ZSharp.Importer.RT/rt loader/Loader.cs | 10 +++ ZSharp.Interpreter/CTServices.cs | 19 ------ ZSharp.Interpreter/ZSharp.Interpreter.csproj | 1 + .../interpreter/Interpreter.Evaluate.cs | 37 +++++++++++ .../interpreter/Interpreter.Operators.cs | 19 ++++++ .../interpreter/Interpreter.Runtime.cs | 2 + ZSharp.Interpreter/interpreter/Interpreter.cs | 35 ++-------- .../operator table/OperatorTable.cs | 32 ++++++++++ .../lang/expr/LangParser.MemberAccess.cs | 2 +- .../runtime/import/Runtime.Import.Function.cs | 6 ++ .../ExpressionCompiler.Compile.cs | 1 + .../ExpressionCompiler.Compile.Binary.cs | 31 +++++++++ .../objects/code/block/CodeBlock.IR.cs | 20 +++++- .../objects/code/return/Return.IR.cs | 25 ++++++++ .../objects/code/return/Return.Value.cs | 7 ++ .../objects/code/return/Return.cs | 7 ++ .../TopLevelExpressionCompiler.cs | 2 +- .../context/Context.Operators.cs | 2 +- ZSharp.SourceCompiler.Module/GlobalUsings.cs | 4 ++ .../ZSharp.SourceCompiler.Module.csproj | 2 + .../class compiler/ClassCompiler.Log.cs | 18 ++++++ .../class compiler/ClassCompiler.Tasks.cs | 7 ++ .../class compiler/ClassCompiler.cs | 24 +++++++ .../class compiler/compile/Compile.cs | 43 +++++++++++++ .../class compiler/compile/expr/Call.cs | 45 +++++++++++++ .../class compiler/compile/expr/Expression.cs | 12 ++++ .../compile/expr/Function.cs} | 2 +- .../class compiler/compile/stmt/Definition.cs | 12 ++++ .../class compiler/compile/stmt/Expression.cs | 8 +++ .../stmt/FunctionBodyCompiler.Compile.cs | 3 +- .../stmt/FunctionBodyCompiler.Return.cs | 19 ++++++ .../FunctionCompiler.Compile.cs | 21 ++++++ .../module compiler/ModuleCompiler.cs | 7 +- .../def/ModuleCompiler.Compile.Function.cs | 26 ++++++++ .../forward reference/EmptyReference.cs | 8 +++ .../forward reference/ForwardReference.cs | 17 +++++ .../modular/function/Function.Build.cs | 4 +- .../objects/modular/function/Function.Call.cs | 28 +++++++- .../objects/modular/function/Function.IR.cs | 64 ++++++++++++++++++- .../modular/function/Function.ReturnType.cs | 7 ++ .../objects/modular/global/Global.IR.cs | 7 +- .../objects/modular/module/Module.Build.cs | 4 +- .../objects/modular/module/Module.Content.cs | 9 +++ .../modular/module/Module.EntryPoint.cs | 17 +++++ .../objects/modular/module/Module.IR.cs | 42 ++++++++++++ .../modular/module/Module.Initializer.cs | 17 +++++ .../objects/modular/module/Module.Member.cs | 26 ++++++++ .../objects/modular/module/Module.Name.cs | 2 +- .../def/ScriptCompiler.Compile.Module.cs | 34 ++++++++++ .../expr/ScriptCompiler.Compile.Expression.cs | 2 +- .../expr/ScriptCompiler.Compile.Module.cs | 10 --- 86 files changed, 1033 insertions(+), 154 deletions(-) create mode 100644 ZSharp.CLI/StandardTypes.cs create mode 100644 ZSharp.Compiler.Reflection/dispatcher/Dispatcher.Definition.cs delete mode 100644 ZSharp.Compiler.Reflection/dispatcher/Dispatcher.GetCO.cs create mode 100644 ZSharp.Compiler.Reflection/reflection/services/Reflection.Definition.cs delete mode 100644 ZSharp.Compiler.Reflection/reflection/services/Reflection.GetCO.cs delete mode 100644 ZSharp.Importer.ILLoader/objects/GlobalUsings.cs create mode 100644 ZSharp.Importer.ILLoader/objects/modular/global/Global.CG.Get.cs create mode 100644 ZSharp.Importer.ILLoader/objects/modular/global/Global.IR.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IL.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IR.cs create mode 100644 ZSharp.Importer.RT/GlobalUsings.cs create mode 100644 ZSharp.Importer.RT/ZSharp.Importer.RT.csproj create mode 100644 ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs create mode 100644 ZSharp.Importer.RT/objects/string/StringLiteral.cs create mode 100644 ZSharp.Importer.RT/rt loader/Loader.Load.Primitives.cs create mode 100644 ZSharp.Importer.RT/rt loader/Loader.Load.cs create mode 100644 ZSharp.Importer.RT/rt loader/Loader.TypeSystem.cs create mode 100644 ZSharp.Importer.RT/rt loader/Loader.cs delete mode 100644 ZSharp.Interpreter/CTServices.cs create mode 100644 ZSharp.Interpreter/interpreter/Interpreter.Evaluate.cs create mode 100644 ZSharp.Interpreter/interpreter/Interpreter.Operators.cs create mode 100644 ZSharp.Interpreter/operator table/OperatorTable.cs create mode 100644 ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Binary.cs create mode 100644 ZSharp.SourceCompiler.Common/objects/code/return/Return.IR.cs create mode 100644 ZSharp.SourceCompiler.Common/objects/code/return/Return.Value.cs create mode 100644 ZSharp.SourceCompiler.Common/objects/code/return/Return.cs create mode 100644 ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.Log.cs create mode 100644 ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.Tasks.cs create mode 100644 ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.cs create mode 100644 ZSharp.SourceCompiler.Module/class compiler/compile/Compile.cs create mode 100644 ZSharp.SourceCompiler.Module/class compiler/compile/expr/Call.cs create mode 100644 ZSharp.SourceCompiler.Module/class compiler/compile/expr/Expression.cs rename ZSharp.SourceCompiler.Module/{module compiler/compile/expr/ModuleCompiler.Compile.Function.cs => class compiler/compile/expr/Function.cs} (93%) create mode 100644 ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Definition.cs create mode 100644 ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Expression.cs create mode 100644 ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Return.cs create mode 100644 ZSharp.SourceCompiler.Module/module compiler/compile/def/ModuleCompiler.Compile.Function.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/forward reference/EmptyReference.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/function/Function.ReturnType.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/module/Module.Content.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/module/Module.EntryPoint.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/module/Module.Initializer.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs create mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/def/ScriptCompiler.Compile.Module.cs delete mode 100644 ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Module.cs diff --git a/Examples/test.zs b/Examples/test.zs index b7f072ff..b2c11e37 100644 --- a/Examples/test.zs +++ b/Examples/test.zs @@ -1,15 +1,16 @@ -import { Directory } from "std:fs"; -import { print } from "std:io"; +import { print } from "std:io"; +import { Void } from "std:types"; print("[CT] Hello, World!"); -fun nodeTypeNotImplemented() {} +import { Directory } from "std:fs"; module A { print("[CT] Inside module A"); - fun main() { + fun main(): Void { print("[RT] Hello, World!"); + return; } } diff --git a/Testing/Program.cs b/Testing/Program.cs index b5b49cac..89ce8628 100644 --- a/Testing/Program.cs +++ b/Testing/Program.cs @@ -29,7 +29,7 @@ Void = rtm.TypeSystem.Void }); -var ilLoader = new ILLoader(coc.IR, rt); +var ilLoader = new ILLoader(coc, rt); coc.TS.SInt32 = ilLoader.TypeSystem.SInt32; diff --git a/ZSharp v1.sln b/ZSharp v1.sln index 11905c9d..3ae7003d 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -79,6 +79,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Reflection" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.IR.Static", "ZSharp.Compiler.IR.Static\ZSharp.Compiler.IR.Static.csproj", "{D4B62927-75B2-4147-8B63-1154BA1AB9CE}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Importer.RT", "ZSharp.Importer.RT\ZSharp.Importer.RT.csproj", "{2C743056-A568-443E-B659-5B6731CD9B24}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -237,6 +239,10 @@ Global {D4B62927-75B2-4147-8B63-1154BA1AB9CE}.Debug|Any CPU.Build.0 = Debug|Any CPU {D4B62927-75B2-4147-8B63-1154BA1AB9CE}.Release|Any CPU.ActiveCfg = Release|Any CPU {D4B62927-75B2-4147-8B63-1154BA1AB9CE}.Release|Any CPU.Build.0 = Release|Any CPU + {2C743056-A568-443E-B659-5B6731CD9B24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2C743056-A568-443E-B659-5B6731CD9B24}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2C743056-A568-443E-B659-5B6731CD9B24}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2C743056-A568-443E-B659-5B6731CD9B24}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZSharp.CLI/Program.cs b/ZSharp.CLI/Program.cs index 8863ba27..7a2338f3 100644 --- a/ZSharp.CLI/Program.cs +++ b/ZSharp.CLI/Program.cs @@ -1,4 +1,5 @@ using ZSharp.CLI; +using ZSharp.Importer.ILLoader; using ZSharp.Interpreter; using ZSharp.Parser; using ZSharp.SourceCompiler; @@ -161,6 +162,28 @@ //scriptCompiler.Context.Operators.Op(@operator.Operator, interpreter.ILLoader.LoadMethod(method)); }; +StandardTypes.VoidType = interpreter.ILLoader.TypeSystem.Void; + +#region Standard Operators + +interpreter.Operators.Op(LangParser.Symbols.MemberAccess, interpreter.ILLoader.Expose( + (Delegate)( + (object obj, string memberName) => + { + var type = obj.GetType(); + var property = type.GetProperty(memberName); + if (property is not null) + return property.GetValue(obj); + var field = type.GetField(memberName); + if (field is not null) + return field.GetValue(obj); + throw new Exception($"Member '{memberName}' not found on type '{type.FullName}'"); + } + ) +)); + +#endregion + #region Import System var stringImporter = new StringImporter(); @@ -195,7 +218,10 @@ "fs", interpreter.ILLoader.LoadModule(typeof(Standard.FileSystem.ModuleScope).Module) ); - +stdImporter.Add( + "types", + interpreter.ILLoader.LoadTypeAsModule(typeof(StandardTypes)) +); #endregion #endregion diff --git a/ZSharp.CLI/StandardTypes.cs b/ZSharp.CLI/StandardTypes.cs new file mode 100644 index 00000000..238d2b28 --- /dev/null +++ b/ZSharp.CLI/StandardTypes.cs @@ -0,0 +1,12 @@ +using ZSharp.Compiler; +using ZSharp.Importer.ILLoader; + +namespace ZSharp.CLI +{ + [ModuleScope] + public static class StandardTypes + { + [Alias("Void")] + public static CompilerObject VoidType = null!; + } +} diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs index 4239778d..8b674041 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -15,6 +15,9 @@ public Result ImplicitCast(CompilerObject @object, CompilerObject type) //if (result.IsError && rtd.Is(out var castFrom)) // result = castFrom.ImplicitCast(compiler, @object); + if (result.IsError && compiler.Reflection.IsSameDefinition(type, rtd)) + result = Result.Ok(@object); + return result; } } diff --git a/ZSharp.Compiler.Core/result/Result.cs b/ZSharp.Compiler.Core/result/Result.cs index 812dc96d..7ba589ea 100644 --- a/ZSharp.Compiler.Core/result/Result.cs +++ b/ZSharp.Compiler.Core/result/Result.cs @@ -35,6 +35,12 @@ public static Result Error(string message) ? Result.Ok(map(result)) : Result.Error(error!); + public Result When(Func> map) + where R : class? + => IsOk + ? map(result) + : Result.Error(error!); + public new Result When(out TResult? result) { result = this.result; diff --git a/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.Definition.cs b/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.Definition.cs new file mode 100644 index 00000000..022d25d8 --- /dev/null +++ b/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.Definition.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static bool IsSameDefinition(CompilerObject left, CompilerObject right) + => ReferenceEquals(left, right); + } +} diff --git a/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.GetCO.cs b/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.GetCO.cs deleted file mode 100644 index 7b917696..00000000 --- a/ZSharp.Compiler.Reflection/dispatcher/Dispatcher.GetCO.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace ZSharp.Compiler -{ - partial class Dispatcher - { - public static Result GetCO(object @object) - { - if (@object is CompilerObject co) - return Result.Ok(co); - - return Result.Error( - $"Object [{@object}] does not support static reflection." - ); - } - } -} diff --git a/ZSharp.Compiler.Reflection/reflection/services/Reflection.Definition.cs b/ZSharp.Compiler.Reflection/reflection/services/Reflection.Definition.cs new file mode 100644 index 00000000..420f3288 --- /dev/null +++ b/ZSharp.Compiler.Reflection/reflection/services/Reflection.Definition.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public delegate bool AreSameDefinition(CompilerObject left, CompilerObject right); + + partial struct Reflection + { + public AreSameDefinition IsSameDefinition { get; set; } = Dispatcher.IsSameDefinition; + } +} diff --git a/ZSharp.Compiler.Reflection/reflection/services/Reflection.GetCO.cs b/ZSharp.Compiler.Reflection/reflection/services/Reflection.GetCO.cs deleted file mode 100644 index aa6c09e1..00000000 --- a/ZSharp.Compiler.Reflection/reflection/services/Reflection.GetCO.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Compiler -{ - public delegate Result GetCO(object @object); - - partial struct Reflection - { - public GetCO GetCO { get; set; } = Dispatcher.GetCO; - } -} diff --git a/ZSharp.Compiler/compiler/Compiler.Services.cs b/ZSharp.Compiler/compiler/Compiler.Services.cs index 686e48a8..2023e0c2 100644 --- a/ZSharp.Compiler/compiler/Compiler.Services.cs +++ b/ZSharp.Compiler/compiler/Compiler.Services.cs @@ -2,16 +2,22 @@ { public sealed partial class Compiler { - private CG cg; - private IR ir; - private Overloading overloading; - private Reflection reflection; - private TS ts; + private CG cg = new(); + private Evaluator evaluator = new(); + private IR ir = new(runtimeModule); + private OOP oop = new(); + private Overloading overloading = new(); + private Reflection reflection = new(); + private TS ts = new(); public ref CG CG => ref cg; + public ref Evaluator Evaluator => ref evaluator; + public ref IR IR => ref ir; + public ref OOP OOP => ref oop; + public ref Reflection Reflection => ref reflection; public ref TS TS => ref ts; diff --git a/ZSharp.Compiler/compiler/Compiler.cs b/ZSharp.Compiler/compiler/Compiler.cs index 287c5a93..f81a36ed 100644 --- a/ZSharp.Compiler/compiler/Compiler.cs +++ b/ZSharp.Compiler/compiler/Compiler.cs @@ -1,21 +1,10 @@ namespace ZSharp.Compiler { - public sealed partial class Compiler + public sealed partial class Compiler(ZSharp.IR.RuntimeModule runtimeModule) { - public ZSharp.IR.RuntimeModule RuntimeModule { get; } + public ZSharp.IR.RuntimeModule RuntimeModule { get; } = runtimeModule; public Compiler() : this(ZSharp.IR.RuntimeModule.Standard) { } - - public Compiler(ZSharp.IR.RuntimeModule runtimeModule) - { - RuntimeModule = runtimeModule; - - cg = new(); - ir = new(runtimeModule); - ts = new(); - overloading = new(); - reflection = new(); - } } } diff --git a/ZSharp.Importer.ILLoader/GlobalUsings.cs b/ZSharp.Importer.ILLoader/GlobalUsings.cs index 3511d075..22ada189 100644 --- a/ZSharp.Importer.ILLoader/GlobalUsings.cs +++ b/ZSharp.Importer.ILLoader/GlobalUsings.cs @@ -1 +1,9 @@ -global using CompilerObject = ZSharp.Compiler.CompilerObject; +global using ZSharp.Objects; + +global using IL = System.Reflection; + +global using MemberName = string; +global using MemberIndex = int; + +global using CompilerObject = ZSharp.Compiler.CompilerObject; +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs index c625e366..967efaf0 100644 --- a/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs +++ b/ZSharp.Importer.ILLoader/il loader/load/ILLoader.Load.Type.Interface.cs @@ -7,7 +7,7 @@ public CompilerObject LoadInterface(Type @interface) if (@interface.IsGenericTypeDefinition) return LoadGenericInterface(@interface); - throw new NotImplementedException(); + return new Objects.Interface(@interface, this); } } } diff --git a/ZSharp.Importer.ILLoader/objects/GlobalUsings.cs b/ZSharp.Importer.ILLoader/objects/GlobalUsings.cs deleted file mode 100644 index cee72fe1..00000000 --- a/ZSharp.Importer.ILLoader/objects/GlobalUsings.cs +++ /dev/null @@ -1,9 +0,0 @@ -global using ZSharp.Objects; - -global using IL = System.Reflection; - -global using MemberName = string; -global using MemberIndex = int; - -global using CompilerObjectResult = ZSharp.Compiler.Result; - diff --git a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs index 994e85a0..05b9ba2d 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs @@ -5,7 +5,7 @@ namespace ZSharp.Importer.ILLoader.Objects partial class Function : ICTCallable { - CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { IRCode result = new(); @@ -16,7 +16,7 @@ CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arg .When(out var argumentCode) .Error(out var error) ) - return CompilerObjectResult.Error(error); + return Result.Error(error); result.Instructions.AddRange(argumentCode!.Instructions); } @@ -24,7 +24,7 @@ CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arg result.Instructions.Add(new IR.VM.Call(GetIR())); result.Types.Add(GetIR().ReturnType); - return CompilerObjectResult.Ok(new RawIRCode(result)); + return Result.Ok(new RawIRCode(result)); } } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/global/Global.CG.Get.cs b/ZSharp.Importer.ILLoader/objects/modular/global/Global.CG.Get.cs new file mode 100644 index 00000000..afd5fc7b --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/modular/global/Global.CG.Get.cs @@ -0,0 +1,16 @@ +using ZSharp.Compiler; + +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Global + : ICTGet + { + Result ICTGet.Get(Compiler.Compiler compiler) + => Result.Ok(new RawIRCode(new([ + new IR.VM.GetGlobal(IR) + ]) + { + Types = [ compiler.IR.CompileType(Type).Unwrap() ] + })); + } +} diff --git a/ZSharp.Importer.ILLoader/objects/modular/global/Global.IR.cs b/ZSharp.Importer.ILLoader/objects/modular/global/Global.IR.cs new file mode 100644 index 00000000..b20ee21c --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/modular/global/Global.IR.cs @@ -0,0 +1,30 @@ +using ZSharp.Compiler; + +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Global + : ICompileIRDefinitionAs + { + public IR.Global? IR { get; private set; } + + Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) + { + if (IR is not null) return Result.Ok(IR); + + if (target is not Platform.Runtime.Runtime rt) + return Result.Error("Invalid target platform"); + + if ( + compiler.IR.CompileType(Type) + .When(out var type) + .Error(out var error) + ) return Result.Error(error); + + IR = new(Name, type!); + + rt.AddGlobal(IR, IL); + + return Result.Ok(IR); + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/modular/global/Global.cs b/ZSharp.Importer.ILLoader/objects/modular/global/Global.cs index 0f015c72..427c03da 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/global/Global.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/global/Global.cs @@ -9,6 +9,7 @@ public Global(IL.FieldInfo il, ILLoader loader) { IL = il; Type = loader.LoadType(il.FieldType); + IR = loader.Compiler.IR.CompileDefinition(this, loader.Runtime).Unwrap(); } } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs index c7aaa9ee..a5c92c3c 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs @@ -19,14 +19,14 @@ public void AddMember(string name, CompilerObject member) Members.Add(name, member); } - CompilerObjectResult ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) + Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) { if (!Members.TryGetValue(member, out var result) && (result = LoadMember(member)) is null) - return CompilerObjectResult.Error( + return Result.Error( $"Could not find member {member} in module {IL.Name}" ); - return CompilerObjectResult.Ok(result); + return Result.Ok(result); } } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs index ddcd90f4..1cf60925 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs @@ -19,14 +19,14 @@ public void AddMember(string name, CompilerObject member) Members.Add(name, member); } - CompilerObjectResult ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) + Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) { if (!Members.TryGetValue(member, out var result) && (result = LoadMember(member)) is null) - return CompilerObjectResult.Error( + return Result.Error( $"Could not find member {member} in module {IL.Name}" ); - return CompilerObjectResult.Ok(result); + return Result.Ok(result); } } } diff --git a/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs index 7c93cfa2..b5a215fe 100644 --- a/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs @@ -18,16 +18,16 @@ public void AddMember(string name, CompilerObject member) Members.Add(name, member); } - CompilerObjectResult ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) + Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) { if (!Members.TryGetValue(member, out var result)) if ((result = LoadMember(member)) is not null) AddMember(member, result); - else return CompilerObjectResult.Error( + else return Result.Error( $"Could not find member {member} in namespace {FullName}" ); - return CompilerObjectResult.Ok(result); + return Result.Ok(result); } } } diff --git a/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IL.cs b/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IL.cs new file mode 100644 index 00000000..e5d6a909 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IL.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Interface + { + public Type IL { get; } + + public ILLoader Loader { get; } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IR.cs b/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IR.cs new file mode 100644 index 00000000..4e1e1ee8 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IR.cs @@ -0,0 +1,37 @@ +using ZSharp.Compiler; +using ZSharp.IR; + +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Interface + : ICompileIRDefinitionAs + , ICompileIRType> + { + public IR.Interface? IR { get; private set; } + + Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) + { + if (IR is not null) return Result.Ok(IR); + + if (target is not Platform.Runtime.Runtime rt) + return Result.Error("Invalid target platform"); + + IR = new(Name); + + rt.AddTypeDefinition(IR, IL); + + return Result.Ok(IR); + } + + Result> ICompileIRType>.CompileIRType(Compiler.Compiler compiler) + { + if ( + compiler.IR.CompileDefinition(this, null) + .When(out var definition) + .Error(out var error) + ) return Result>.Error(error); + + return Result>.Ok(new InterfaceReference(definition!)); + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.cs b/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.cs index c4bc234a..d3960904 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.cs @@ -3,5 +3,14 @@ public sealed partial class Interface : CompilerObject { + public string Name => IL.Name; + + public Interface(Type @interface, ILLoader loader) + { + IL = @interface; + Loader = loader; + + IR = loader.Compiler.IR.CompileDefinition(this, loader.Runtime).Unwrap(); + } } } diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs b/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs index e5541b70..0602e102 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs @@ -5,7 +5,7 @@ namespace ZSharp.Importer.ILLoader.Objects partial class BoundMethod : ICTCallable { - CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { if (Object is not null) arguments = [ diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs index 13b74495..9a9007dc 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs @@ -6,7 +6,7 @@ namespace ZSharp.Importer.ILLoader.Objects partial class Method : ICTCallable { - CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { IRCode result = new(); @@ -17,7 +17,7 @@ CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arg .When(out var argumentCode) .Error(out var error) ) - return CompilerObjectResult.Error(error); + return Result.Error(error); result.Instructions.AddRange(argumentCode!.Instructions); } @@ -25,7 +25,7 @@ CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arg result.Instructions.Add(new IR.VM.Call(GetIR())); result.Types.Add(GetIR().ReturnType); - return CompilerObjectResult.Ok(new RawIRCode(result)); + return Result.Ok(new RawIRCode(result)); } } } diff --git a/ZSharp.Importer.RT/GlobalUsings.cs b/ZSharp.Importer.RT/GlobalUsings.cs new file mode 100644 index 00000000..861e2e1e --- /dev/null +++ b/ZSharp.Importer.RT/GlobalUsings.cs @@ -0,0 +1,6 @@ +global using RTObject = object; + +global using CompilerObject = ZSharp.Compiler.CompilerObject; +global using Result = ZSharp.Compiler.Result; + +global using TargetPlatform = object; diff --git a/ZSharp.Importer.RT/ZSharp.Importer.RT.csproj b/ZSharp.Importer.RT/ZSharp.Importer.RT.csproj new file mode 100644 index 00000000..94b2484d --- /dev/null +++ b/ZSharp.Importer.RT/ZSharp.Importer.RT.csproj @@ -0,0 +1,15 @@ + + + + net9.0 + enable + enable + + + + + + + + + diff --git a/ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs b/ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs new file mode 100644 index 00000000..93418086 --- /dev/null +++ b/ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs @@ -0,0 +1,17 @@ +using ZSharp.Compiler; + +namespace ZSharp.Importer.RT.Objects +{ + partial class StringLiteral + : ICompileIRCode + { + Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, TargetPlatform? target) + => Result.Ok(new([ + new IR.VM.PutString(value) + ]) + { + Types = [type], + MaxStackSize = 1 + }); + } +} diff --git a/ZSharp.Importer.RT/objects/string/StringLiteral.cs b/ZSharp.Importer.RT/objects/string/StringLiteral.cs new file mode 100644 index 00000000..ece36bbc --- /dev/null +++ b/ZSharp.Importer.RT/objects/string/StringLiteral.cs @@ -0,0 +1,11 @@ +using Value = string; + +namespace ZSharp.Importer.RT.Objects +{ + internal sealed partial class StringLiteral(Value value, IR.IType type) + : CompilerObject + { + private readonly Value value = value; + private readonly IR.IType type = type; + } +} diff --git a/ZSharp.Importer.RT/rt loader/Loader.Load.Primitives.cs b/ZSharp.Importer.RT/rt loader/Loader.Load.Primitives.cs new file mode 100644 index 00000000..15923e13 --- /dev/null +++ b/ZSharp.Importer.RT/rt loader/Loader.Load.Primitives.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Importer.RT +{ + partial class Loader + { + private Objects.StringLiteral Load(string value) + => new(value, TypeSystem.String); + } +} diff --git a/ZSharp.Importer.RT/rt loader/Loader.Load.cs b/ZSharp.Importer.RT/rt loader/Loader.Load.cs new file mode 100644 index 00000000..7fa4939f --- /dev/null +++ b/ZSharp.Importer.RT/rt loader/Loader.Load.cs @@ -0,0 +1,21 @@ +namespace ZSharp.Importer.RT +{ + public delegate Result LoadObject(RTObject? @object); + + partial class Loader + { + public LoadObject LoadObject; + + public Result Load(RTObject? @object) + => LoadObject(@object); + + private Result DefaultLoader(RTObject? @object) + => @object switch + { + CompilerObject co => Result.Ok(co), + string value => Result.Ok(Load(value)), + null => Result.Error("Cannot directly load null object because it is untyped."), + _ => Result.Error($"Cannot load {@object.GetType().Name} object: {@object}."), + }; + } +} diff --git a/ZSharp.Importer.RT/rt loader/Loader.TypeSystem.cs b/ZSharp.Importer.RT/rt loader/Loader.TypeSystem.cs new file mode 100644 index 00000000..c2e2a9d2 --- /dev/null +++ b/ZSharp.Importer.RT/rt loader/Loader.TypeSystem.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.RT +{ + partial class Loader + { + public required Platform.Runtime.TypeSystem TypeSystem { get; init; } + } +} diff --git a/ZSharp.Importer.RT/rt loader/Loader.cs b/ZSharp.Importer.RT/rt loader/Loader.cs new file mode 100644 index 00000000..67565095 --- /dev/null +++ b/ZSharp.Importer.RT/rt loader/Loader.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Importer.RT +{ + public sealed partial class Loader + { + public Loader() + { + LoadObject = DefaultLoader; + } + } +} diff --git a/ZSharp.Interpreter/CTServices.cs b/ZSharp.Interpreter/CTServices.cs deleted file mode 100644 index fb59b9ef..00000000 --- a/ZSharp.Interpreter/CTServices.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace ZSharp.Interpreter -{ - public static class CTServices - { - public static CompilerObject InfoOf(object @object) - { - if (@object is CompilerObject co) - return co; - - throw new NotImplementedException(); - } - - public static T? InfoOf(object @object) - where T : class, CompilerObject - { - return InfoOf(@object) as T; - } - } -} diff --git a/ZSharp.Interpreter/ZSharp.Interpreter.csproj b/ZSharp.Interpreter/ZSharp.Interpreter.csproj index 353b70e9..20c44119 100644 --- a/ZSharp.Interpreter/ZSharp.Interpreter.csproj +++ b/ZSharp.Interpreter/ZSharp.Interpreter.csproj @@ -11,6 +11,7 @@ + diff --git a/ZSharp.Interpreter/interpreter/Interpreter.Evaluate.cs b/ZSharp.Interpreter/interpreter/Interpreter.Evaluate.cs new file mode 100644 index 00000000..b42cd56e --- /dev/null +++ b/ZSharp.Interpreter/interpreter/Interpreter.Evaluate.cs @@ -0,0 +1,37 @@ +using ZSharp.Compiler; + +namespace ZSharp.Interpreter +{ + partial class Interpreter + { + public Result Evaluate( + CompilerObject @object, + Platform.Runtime.IEvaluationContext? evaluationContext = null + ) + { + if ( + Compiler.IR.CompileCode(@object, Runtime) + .When(out var irCode) + .Error(out var error) + ) + return Result.Ok(@object); + + var type = irCode!.IsVoid ? RuntimeModule.TypeSystem.Void : irCode.RequireValueType(); + + var result = Runtime.Evaluate(irCode.Instructions, type, evaluationContext); + + if (irCode.IsVoid) + return Result + .Ok(new Objects.RawIRCode(new())); + + if (result is null) + return Result + .Ok(@object); + // TODO: should actually be an error! + //return Result + // .Error("Non-void expression evaluated to nothing"); + + return Result.Ok(result); + } + } +} diff --git a/ZSharp.Interpreter/interpreter/Interpreter.Operators.cs b/ZSharp.Interpreter/interpreter/Interpreter.Operators.cs new file mode 100644 index 00000000..6fc9f7b4 --- /dev/null +++ b/ZSharp.Interpreter/interpreter/Interpreter.Operators.cs @@ -0,0 +1,19 @@ +using CommonZ.Utils; + +namespace ZSharp.Interpreter +{ + partial class Interpreter + { + public OperatorTable Operators { get; private set; } = new(); + + public ContextManager OperatorScope(out OperatorTable scopedTable) + { + scopedTable = Operators.CreateChild(); + + var previous = Operators; + Operators = scopedTable; + + return new ContextManager(() => Operators = previous); + } + } +} diff --git a/ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs b/ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs index c03f6290..64080e19 100644 --- a/ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs +++ b/ZSharp.Interpreter/interpreter/Interpreter.Runtime.cs @@ -3,5 +3,7 @@ partial class Interpreter { public Platform.Runtime.Runtime Runtime { get; } + + public Importer.RT.Loader RTLoader { get; } } } diff --git a/ZSharp.Interpreter/interpreter/Interpreter.cs b/ZSharp.Interpreter/interpreter/Interpreter.cs index 9fabc01e..08baeaf8 100644 --- a/ZSharp.Interpreter/interpreter/Interpreter.cs +++ b/ZSharp.Interpreter/interpreter/Interpreter.cs @@ -39,38 +39,11 @@ public Interpreter(IR.RuntimeModule? runtimeModule = null) UIntNative = null!, Void = RuntimeModule.TypeSystem.Void }); + RTLoader = new() + { + TypeSystem = Runtime.TypeSystem + }; ILLoader = new(Compiler, Runtime); } - - public Result Evaluate( - CompilerObject @object, - Platform.Runtime.IEvaluationContext? evaluationContext = null, - Platform.Runtime.Loaders.IContext? codeContext = null - ) - { - if ( - Compiler.IR.CompileCode(@object, Runtime) - .When(out var irCode) - .Error(out var error) - ) - return Result.Ok(@object); - - var type = irCode!.IsVoid ? RuntimeModule.TypeSystem.Void : irCode.RequireValueType(); - - var result = Runtime.Evaluate(irCode.Instructions, type, evaluationContext, codeContext); - - if (irCode.IsVoid) - return Result - .Ok(new Objects.RawIRCode(new())); - - if (result is null) - return Result - .Ok(@object); - // TODO: should actually be an error! - //return Result - // .Error("Non-void expression evaluated to nothing"); - - return Result.Ok(result); - } } } diff --git a/ZSharp.Interpreter/operator table/OperatorTable.cs b/ZSharp.Interpreter/operator table/OperatorTable.cs new file mode 100644 index 00000000..2c86c247 --- /dev/null +++ b/ZSharp.Interpreter/operator table/OperatorTable.cs @@ -0,0 +1,32 @@ +global using Operator = string; + +using CommonZ.Utils; +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Interpreter +{ + public sealed class OperatorTable() + { + private readonly Cache operators = new(); + + internal OperatorTable(OperatorTable? parent = null) + : this() + { + operators = new() + { + Parent = parent?.operators + }; + } + + public void Op(Operator op, CompilerObject obj) + => operators.Cache(op, obj); // TODO: on add + + public CompilerObject? Op(Operator op) + => operators.Cache(op); + + public bool Op(Operator op, [NotNullWhen(true)] out CompilerObject? obj) + => (obj = Op(op)) is not null; + + public OperatorTable CreateChild() => new(this); + } +} diff --git a/ZSharp.Parser/lang/expr/LangParser.MemberAccess.cs b/ZSharp.Parser/lang/expr/LangParser.MemberAccess.cs index 8b28c88e..fd20f567 100644 --- a/ZSharp.Parser/lang/expr/LangParser.MemberAccess.cs +++ b/ZSharp.Parser/lang/expr/LangParser.MemberAccess.cs @@ -14,7 +14,7 @@ public static BinaryExpression ParseMemberAccess(Parser parser, Expression targe { Left = target, Operator = @operator, - Right = LiteralExpression.String(name.Value), + Right = new IdentifierExpression(new(name))//LiteralExpression.String(name.Value), }; else if (parser.Is(TokenType.Number, out var index)) throw new NotImplementedException("Member access by index"); diff --git a/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Function.cs b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Function.cs index 032e9080..fce1ab49 100644 --- a/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Function.cs +++ b/ZSharp.Platform.Runtime/runtime/import/Runtime.Import.Function.cs @@ -9,6 +9,12 @@ public IL.MethodInfo ImportFunction(IR.Function function) if (result is not IL.MethodInfo info) throw new InvalidOperationException(); + if (info.DeclaringType is IL.Emit.TypeBuilder typeBuilder) + info = info.DeclaringType.GetMethod( + info.Name, + [.. info.GetParameters().Select(p => p.ParameterType) ] + ) ?? throw new(); + return info; } diff --git a/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs b/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs index c6d78085..2b9c012a 100644 --- a/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs +++ b/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs @@ -9,6 +9,7 @@ partial class ExpressionCompiler public Result Compile(AST.Expression expression) => PostProcess(expression switch { + AST.BinaryExpression binary => Compile(binary), AST.CallExpression call => Compile(call), AST.IdentifierExpression identifier => Compile(identifier), AST.LiteralExpression literal => Compile(literal), diff --git a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Binary.cs b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Binary.cs new file mode 100644 index 00000000..5b878ed6 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Binary.cs @@ -0,0 +1,31 @@ +namespace ZSharp.SourceCompiler +{ + partial class ExpressionCompiler + { + private Result Compile(AST.BinaryExpression binary) + { + if ( + Compile(binary.Left) + .When(out var left) + .Error(out var error) + ) return Result.Error(error); + + if (binary.Operator == ".") // Special case ??? :( + { + if (binary.Right is AST.IdentifierExpression identifier) + return Interpreter.Compiler.CG.Member(left!, identifier.Name); + } + + if ( + Compile(binary.Right) + .When(out var right) + .Error(out error) + ) return Result.Error(error); + + if (!Interpreter.Operators.Op(binary.Operator, out var @operator)) + return Result.Error($"Unknown operator '{binary.Operator}'"); + + return Interpreter.Compiler.CG.Call(@operator, [ new(left!), new(right!) ]); + } + } +} diff --git a/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs b/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs index fd01e5aa..3a7b69ae 100644 --- a/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs +++ b/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs @@ -1,7 +1,25 @@ -namespace ZSharp.SourceCompiler + +namespace ZSharp.SourceCompiler { partial class CodeBlock + : ICompileIRCode { + Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) + { + var code = new IRCode(); + foreach (var statement in Content) + { + if ( + compiler.IR.CompileCode(statement, target) + .When(out var statementCode) + .Error(out var error) + ) return Result.Error(error); + code.Instructions.AddRange(statementCode!.Instructions); + code.Types.AddRange(statementCode.Types); + } + + return Result.Ok(code); + } } } diff --git a/ZSharp.SourceCompiler.Common/objects/code/return/Return.IR.cs b/ZSharp.SourceCompiler.Common/objects/code/return/Return.IR.cs new file mode 100644 index 00000000..83c77f07 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/objects/code/return/Return.IR.cs @@ -0,0 +1,25 @@ + +namespace ZSharp.SourceCompiler +{ + partial class Return + : ICompileIRCode + { + Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) + { + var code = new IRCode(); + + if (Value is not null) + if ( + compiler.IR.CompileCode(Value, target) + .When(out var valueCode) + .Error(out var error) + ) return Result.Error(error); + else code.Append(valueCode!); + + code.Instructions.Add(new IR.VM.Return()); + code.Types.Clear(); + + return Result.Ok(code); + } + } +} diff --git a/ZSharp.SourceCompiler.Common/objects/code/return/Return.Value.cs b/ZSharp.SourceCompiler.Common/objects/code/return/Return.Value.cs new file mode 100644 index 00000000..859cd2d6 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/objects/code/return/Return.Value.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + partial class Return + { + public CompilerObject? Value { get; set; } + } +} diff --git a/ZSharp.SourceCompiler.Common/objects/code/return/Return.cs b/ZSharp.SourceCompiler.Common/objects/code/return/Return.cs new file mode 100644 index 00000000..ff92a9e4 --- /dev/null +++ b/ZSharp.SourceCompiler.Common/objects/code/return/Return.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler +{ + public sealed partial class Return + : CompilerObject + { + } +} diff --git a/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs b/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs index 4ef0a24c..2063b3e0 100644 --- a/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs +++ b/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs @@ -6,7 +6,7 @@ public sealed class TopLevelExpressionCompiler(Interpreter.Interpreter interpret public Func CompileExpression { get; init; } = new ExpressionCompiler(interpreter).Compile; - public Func LoadCO { get; init; } = @object => Result.Ok(ZSharp.Interpreter.CTServices.InfoOf(@object!)); + public Func LoadCO { get; init; } = interpreter.RTLoader.Load; public Result Compile(AST.Expression expression) { diff --git a/ZSharp.SourceCompiler.Core/context/Context.Operators.cs b/ZSharp.SourceCompiler.Core/context/Context.Operators.cs index 92793869..64aaa8d4 100644 --- a/ZSharp.SourceCompiler.Core/context/Context.Operators.cs +++ b/ZSharp.SourceCompiler.Core/context/Context.Operators.cs @@ -2,6 +2,6 @@ { partial class Context { - public OperatorTable Operators { get; init; } = new(); + } } diff --git a/ZSharp.SourceCompiler.Module/GlobalUsings.cs b/ZSharp.SourceCompiler.Module/GlobalUsings.cs index d78b7439..d9379d54 100644 --- a/ZSharp.SourceCompiler.Module/GlobalUsings.cs +++ b/ZSharp.SourceCompiler.Module/GlobalUsings.cs @@ -1,3 +1,7 @@ global using ZSharp.Compiler; +global using MemberName = string; +global using MemberIndex = int; + + global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj b/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj index c5684fe8..6c620a58 100644 --- a/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj +++ b/ZSharp.SourceCompiler.Module/ZSharp.SourceCompiler.Module.csproj @@ -15,6 +15,7 @@ + @@ -26,6 +27,7 @@ + diff --git a/ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.Log.cs b/ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.Log.cs new file mode 100644 index 00000000..4263f406 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.Log.cs @@ -0,0 +1,18 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ClassCompiler + { + private readonly List> logs = []; + + public void Error(string message, Logging.LogOrigin origin) + => logs.Add(new() + { + Level = Logging.LogLevel.Error, + Message = message, + Origin = origin + }); + + public void Error(string message, AST.Node node) + => Error(message, new NodeLogOrigin(node)); + } +} diff --git a/ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.Tasks.cs b/ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.Tasks.cs new file mode 100644 index 00000000..208118be --- /dev/null +++ b/ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.Tasks.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ClassCompiler + { + private readonly TaskManager tasks; + } +} diff --git a/ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.cs b/ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.cs new file mode 100644 index 00000000..dfb644b7 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/class compiler/ClassCompiler.cs @@ -0,0 +1,24 @@ +namespace ZSharp.SourceCompiler.Module +{ + public sealed partial class ClassCompiler + { + private Objects.Module Object { get; } + + private Interpreter.Interpreter Interpreter { get; } + + private AST.Module Node { get; } + + private CompileExpression CompileExpression { get; } + + public ClassCompiler(Interpreter.Interpreter interpreter, AST.Module module) + { + Interpreter = interpreter; + Node = module; + Object = new(); + + CompileExpression = new TopLevelExpressionCompiler(interpreter).Compile; + + tasks = new(InitCompile); + } + } +} diff --git a/ZSharp.SourceCompiler.Module/class compiler/compile/Compile.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/Compile.cs new file mode 100644 index 00000000..0f790fa2 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/Compile.cs @@ -0,0 +1,43 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ClassCompiler + { + public Result Compile() + { + tasks.RunUntilComplete(); + + if (logs.Count > 0) + { + // TODO: Aggregate errors properly + + var sb = new System.Text.StringBuilder(); + + foreach (var log in logs) + sb.AppendLine(log.ToString()); + + return Result.Error(sb.ToString()); + } + + + return Result.Ok(Object); + } + + private void InitCompile() + { + foreach (var statement in Node.Body) + if (Compile(statement).Error(out var error)) + Error( + $"Failed to compile statement: {error}", + new NodeLogOrigin(statement) + ); + } + + private Result Compile(AST.Statement statement) + => statement switch + { + AST.DefinitionStatement definitionStatement => Compile(definitionStatement), + AST.ExpressionStatement expressionStatement => Compile(expressionStatement), + _ => Result.Error($"Unknown statement type: {statement.GetType().Name}") + }; + } +} diff --git a/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Call.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Call.cs new file mode 100644 index 00000000..bbe9cd70 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Call.cs @@ -0,0 +1,45 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ClassCompiler + { + private Result Compile(AST.CallExpression call) + { + var calleeResult = Compile(call.Callee); + + if ( + calleeResult + .When(out var callee) + .Error(out var errorMessage) + ) return Result.Error( + $"Failed to compile callee: {errorMessage}" + ); + + var argumentResults = call.Arguments + .Select(arg => + { + if ( + Compile(arg.Value) + .When(out var argValue) + .Error(out var error) + ) return Result.Error(error); + + return Result.Ok( + new( + arg.Name, + argValue! + ) + ); + }) + .ToList(); + + if (argumentResults.Any(r => r.IsError)) + return Result.Error( + $"Failed to compile arguments: { + (string.Join(", ", Enumerable.Where>(argumentResults, (Func, bool>)(r => r.IsError)).Select(r => r.Error(out var error) ? error : throw new()))) + }" + ); + + return Interpreter.Compiler.CG.Call(callee!, [.. argumentResults.Select(r => r.Unwrap())]); + } + } +} diff --git a/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Expression.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Expression.cs new file mode 100644 index 00000000..61d5c47a --- /dev/null +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Expression.cs @@ -0,0 +1,12 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ClassCompiler + { + private Result Compile(AST.Expression expression) + => expression switch + { + AST.Function function => Compile(function), + _ => CompileExpression(expression) + }; + } +} diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Function.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Function.cs similarity index 93% rename from ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Function.cs rename to ZSharp.SourceCompiler.Module/class compiler/compile/expr/Function.cs index db4e4152..47a8f651 100644 --- a/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Function.cs +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Function.cs @@ -1,6 +1,6 @@ namespace ZSharp.SourceCompiler.Module { - partial class ModuleCompiler + partial class ClassCompiler { private Result Compile(AST.Function function) { diff --git a/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Definition.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Definition.cs new file mode 100644 index 00000000..90e831d4 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Definition.cs @@ -0,0 +1,12 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ClassCompiler + { + private Result Compile(AST.DefinitionStatement definitionStatement) + => definitionStatement.Definition switch + { + AST.Function function => Compile(function), + _ => Result.Error($"Unknown definition type: {definitionStatement.Definition.GetType().Name}") + }; + } +} diff --git a/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Expression.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Expression.cs new file mode 100644 index 00000000..7eb6bfd8 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Expression.cs @@ -0,0 +1,8 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ClassCompiler + { + private Result Compile(AST.ExpressionStatement expressionStatement) + => CompileExpression(expressionStatement.Expression); + } +} diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs index c022b45d..1775a5c4 100644 --- a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs @@ -6,8 +6,9 @@ private Result Compile(AST.Statement statement) => statement switch { AST.BlockStatement block => Compile(block), - AST.ExpressionStatement expression => Compile(expression), AST.DefinitionStatement definition => Compile(definition), + AST.ExpressionStatement expression => Compile(expression), + AST.Return @return => Compile(@return), _ => Result.Error($"Unknown statement type: {statement.GetType().Name}"), }; } diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Return.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Return.cs new file mode 100644 index 00000000..1c2ed511 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Return.cs @@ -0,0 +1,19 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class FunctionBodyCompiler + { + private Result Compile(AST.Return @return) + { + CompilerObject? value = null; + + if ( + @return.Value is not null && + CompileExpression(@return.Value) + .When(out value) + .Error(out var error) + ) return Result.Error(error); + + return Result.Ok(new Return() { Value = value } ); + } + } +} diff --git a/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs index 64f2b0a9..854be304 100644 --- a/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs +++ b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs @@ -23,6 +23,27 @@ public void CompileSignature() { if (Node.ReturnType is null) Interpreter.Log.Error($"Function {Node.Name} must have a return type.", Node); + else if ( + CompileExpression(Node.ReturnType) + .When(out var returnType) + .Error(out var error) + ) Interpreter.Log.Error($"{error}", Node.ReturnType); + else if ( + Interpreter.Compiler.CG.Get(returnType!) + .When(out returnType) + .Error(out error) + ) Interpreter.Log.Error($"{error}", Node.ReturnType); + else if ( + Interpreter.Evaluate(returnType!) + .When(out var returnTypeObject) + .Error(out error) + ) Interpreter.Log.Error($"{error}", Node.ReturnType); + else if ( + Interpreter.RTLoader.Load(returnTypeObject!) + .When(out returnType) + .Error(out error) + ) Interpreter.Log.Error($"{error}", Node.ReturnType); + else Object.ReturnType = returnType; if (Node.Signature.VarArgs is not null) Interpreter.Log.Error("VarArgs functions are obsolete and should not be used.", Node.Signature.VarArgs); diff --git a/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.cs b/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.cs index e52804cd..b78d3640 100644 --- a/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.cs +++ b/ZSharp.SourceCompiler.Module/module compiler/ModuleCompiler.cs @@ -14,11 +14,16 @@ public ModuleCompiler(Interpreter.Interpreter interpreter, AST.Module module) { Interpreter = interpreter; Node = module; - Object = new(); + Object = new() + { + Name = module.Name + }; CompileExpression = new TopLevelExpressionCompiler(interpreter).Compile; tasks = new(InitCompile); } + + public CompilerObject GetObject() => Object; } } diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/def/ModuleCompiler.Compile.Function.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/def/ModuleCompiler.Compile.Function.cs new file mode 100644 index 00000000..1198030f --- /dev/null +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/def/ModuleCompiler.Compile.Function.cs @@ -0,0 +1,26 @@ +namespace ZSharp.SourceCompiler.Module +{ + partial class ModuleCompiler + { + private Result Compile(AST.Function function) + { + var compiler = new FunctionCompiler(Interpreter, function); + + var result = compiler.Declare(); + + if (result.Ok(out var definition)) + Object.Content.Add(definition); + if ( + function.Name != string.Empty + && (result = Object.AddMember(function.Name, definition!)) + .IsError + ) + return result; + + tasks.AddTask(compiler.CompileSignature); + tasks.AddTask(compiler.CompileBody); + + return result; + } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/forward reference/EmptyReference.cs b/ZSharp.SourceCompiler.Module/objects/forward reference/EmptyReference.cs new file mode 100644 index 00000000..4311e45f --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/forward reference/EmptyReference.cs @@ -0,0 +1,8 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + internal sealed class EmptyReference + : CompilerObject + { + public static CompilerObject Instance { get; } = new EmptyReference(); + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs b/ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs new file mode 100644 index 00000000..4eb3b5f7 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs @@ -0,0 +1,17 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.SourceCompiler.Module.Objects +{ + internal sealed class ForwardReference + : CompilerObject + , IProxy + { + public CompilerObject Inner { get; set; } = EmptyReference.Instance; + + bool CompilerObject.Is([NotNullWhen(true)] out T? result) where T : class + => Inner.Is(out result); + + R IProxy.Apply(Func fn) + => fn(Inner); + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Build.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Build.cs index f99ea667..cd99d2dd 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Build.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Build.cs @@ -7,7 +7,9 @@ partial class Function [Flags] private enum BuildState { - + Owner = 1 << 0, + Signature = 1 << 1, + Body = 1 << 2, } private readonly ObjectBuildState state = new(); diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs index 12e0523b..d4a66179 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs @@ -1,11 +1,35 @@ -namespace ZSharp.SourceCompiler.Module.Objects +using ZSharp.Objects; + +namespace ZSharp.SourceCompiler.Module.Objects { partial class Function : ICTCallable { Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { - throw new NotImplementedException(); + IRCode result = new(); + + foreach (var argument in arguments) + { + if ( + compiler.IR.CompileCode(argument.Object, null) + .When(out var argumentCode) + .Error(out var error) + ) + return Result.Error(error); + + result.Instructions.AddRange(argumentCode!.Instructions); + } + + if (IR is null) + if (CompileIR(compiler, null).When(out var ir).Error(out var error)) + return Result.Error(error); + else IR = ir!; + + result.Instructions.Add(new IR.VM.Call(IR)); + result.Types.Add(IR.ReturnType); + + return Result.Ok(new RawIRCode(result)); } } } diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs index 0b2e91f6..ca6aacb4 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs @@ -1,7 +1,69 @@ -namespace ZSharp.SourceCompiler.Module.Objects + + +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.SourceCompiler.Module.Objects { partial class Function + : ICompileIRDefinitionAs + , ICompileIRDefinitionIn { public IR.Function? IR { get; private set; } + + void ICompileIRDefinitionIn.CompileIRDefinition(Compiler.Compiler compiler, IR.Module owner, object? target) + { + if ( + CompileIR(compiler, target) + .When(out var ir) + .Error(out var error) + ) throw new InvalidOperationException(error.ToString()); + + if (!state[BuildState.Owner]) + { + state[BuildState.Owner] = true; + + owner.Functions.Add(ir!); + } + } + + Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) + => CompileIR(compiler, target); + + private Result CompileIR(Compiler.Compiler compiler, object? target) + { + if (ReturnType is null) + return Result.Error( + $"Function {Name} does not have a return type" + ); + if ( + compiler.IR.CompileType(ReturnType) + .When(out var returnType) + .Error(out var error) + ) return Result.Error(error); + + IR ??= new(returnType!) + { + Name = Name + }; + + if (!state[BuildState.Body]) + { + state[BuildState.Body] = true; + + if (Body is not null) + if ( + compiler.IR.CompileCode(Body, target) + .When(out var body) + .Error(out error) + ) return Result.Error(error); + else + { + IR.Body.Instructions.AddRange(body!.Instructions); + IR.Body.StackSize = body.MaxStackSize; + } + } + + return Result.Ok(IR); + } } } diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.ReturnType.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.ReturnType.cs new file mode 100644 index 00000000..babeca55 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.ReturnType.cs @@ -0,0 +1,7 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Function + { + public CompilerObject? ReturnType { get; set; } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs index 118c05cc..d9566b2e 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs @@ -1,7 +1,4 @@ - -using System.Diagnostics.CodeAnalysis; - -namespace ZSharp.SourceCompiler.Module.Objects +namespace ZSharp.SourceCompiler.Module.Objects { partial class Global : ICompileIRDefinitionAs @@ -19,7 +16,7 @@ partial class Global typeResult .When(out var type) .IsError - ) return typeResult.When(_ => null!); + ) return typeResult.When(_ => (null as IR.Global)!); IR = new(Name, type!); } diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Build.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Build.cs index dec25d8c..50eebb20 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Build.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Build.cs @@ -7,7 +7,9 @@ partial class Module [Flags] private enum BuildState { - + Content = 1 << 0, + EntryPoint = 1 << 1, + Initializer = 1 << 2, } private readonly ObjectBuildState state = new(); diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Content.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Content.cs new file mode 100644 index 00000000..3aba1257 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Content.cs @@ -0,0 +1,9 @@ +using CommonZ.Utils; + +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Module + { + public Collection Content { get; } = []; + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.EntryPoint.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.EntryPoint.cs new file mode 100644 index 00000000..023aa982 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.EntryPoint.cs @@ -0,0 +1,17 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Module + { + private CompilerObject? entryPoint; + + public CompilerObject? EntryPoint + { + get => entryPoint; + set { + if (state[BuildState.EntryPoint]) + throw new InvalidOperationException($"Cannot set entrypoint on an already built module"); + entryPoint = value; + } + } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs index 127159f3..00988013 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs @@ -1,7 +1,49 @@ namespace ZSharp.SourceCompiler.Module.Objects { partial class Module + : ICompileIRDefinitionAs { public IR.Module? IR { get; private set; } + + Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) + { + IR ??= new(Name); + + if (!state[BuildState.Content]) + { + state[BuildState.Content] = true; + + foreach (var item in Content) + compiler.IR.CompileDefinition(item, IR, target); + } + + if (!state[BuildState.EntryPoint]) + { + if (EntryPoint is not null) + if ( + compiler.IR.CompileDefinition(EntryPoint, target) + .When(out var entryPoint) + .Error(out var error) + ) return Result.Error(error); + else IR.EntryPoint = entryPoint; + + state[BuildState.EntryPoint] = true; + } + + if (!state[BuildState.Initializer]) + { + if (Initializer is not null) + if ( + compiler.IR.CompileDefinition(Initializer, target) + .When(out var initializer) + .Error(out var error) + ) return Result.Error(error); + else IR.Initializer = initializer; + + state[BuildState.Initializer] = true; + } + + return Result.Ok(IR); + } } } diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Initializer.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Initializer.cs new file mode 100644 index 00000000..633a5357 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Initializer.cs @@ -0,0 +1,17 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Module + { + private CompilerObject? initializer; + + public CompilerObject? Initializer + { + get => initializer; + set { + if (state[BuildState.Initializer]) + throw new InvalidOperationException($"Cannot set initializer on an already built module"); + initializer = value; + } + } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs new file mode 100644 index 00000000..d98fac2d --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs @@ -0,0 +1,26 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + partial class Module + : ICTGetMember + { + private readonly Dictionary members = []; + + public Result AddMember(string name, CompilerObject member) + { + if (members.ContainsKey(name)) + Result.Error($"Member '{name}' is already defined in module '{Name}'."); + else + members[name] = member; + + return Result.Ok(member); + } + + Result ICTGetMember.Member(Compiler.Compiler compiler, string member) + { + if (members.TryGetValue(member, out var obj)) + return Result.Ok(obj); + + return Result.Error($"Member '{member}' not found in module '{Name}'."); + } + } +} diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Name.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Name.cs index a34d5d21..8aeb06a1 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Name.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Name.cs @@ -2,7 +2,7 @@ { partial class Module { - private string _name; + private string _name = string.Empty; public string Name { get => _name; diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/def/ScriptCompiler.Compile.Module.cs b/ZSharp.SourceCompiler.Script/compiler/compile/def/ScriptCompiler.Compile.Module.cs new file mode 100644 index 00000000..a90fb813 --- /dev/null +++ b/ZSharp.SourceCompiler.Script/compiler/compile/def/ScriptCompiler.Compile.Module.cs @@ -0,0 +1,34 @@ +using ZSharp.Compiler; + +namespace ZSharp.SourceCompiler.Script +{ + partial class ScriptCompiler + { + private Result Compile(AST.Module module) + { + var moduleCompiler = new Module.ModuleCompiler(Interpreter, module); + + var scope = Interpreter.Compiler.CurrentContext.FindFirstContext(); + if (scope is null) + return Result.Error("No scope context found."); + if (scope.Add(module.Name, moduleCompiler.GetObject()).Error(out var error)) + return Result.Error($"Could not add module '{module.Name}' to scope: {error}"); + + var result = moduleCompiler.Compile(); + + if (!result.Ok(out var definition)) + return result; + + + if ( + Interpreter.Compiler.IR.CompileDefinition(definition, Interpreter.Runtime) + .When(out var irModule) + .Error(out error) + ) return Result.Error(error); + + Interpreter.Runtime.ImportModule(irModule!); + + return result; + } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs index df59e704..e35c1d20 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs @@ -23,7 +23,7 @@ private Result PostProcess(Result result) return Interpreter .Evaluate(value) - .When(ZSharp.Interpreter.CTServices.InfoOf); + .When(Interpreter.RTLoader.Load); } } } diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Module.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Module.cs deleted file mode 100644 index 54a10fa9..00000000 --- a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Module.cs +++ /dev/null @@ -1,10 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.SourceCompiler.Script -{ - partial class ScriptCompiler - { - private Result Compile(AST.Module module) - => new Module.ModuleCompiler(Interpreter, module).Compile(); - } -} From 7ad4de81668ec8c4c7054df8bdbae5c76f16bc1e Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Thu, 9 Oct 2025 22:51:21 +0300 Subject: [PATCH 218/235] Add features "playground" It's not a real playground in the sense that you can play with features in it. It's just there so I don't forget about ideas I have --- ZSharp.Compiler.Features/GlobalUsings.cs | 2 +- .../callable/BoundParameter.cs | 9 ++++ .../callable/BoundSignature.cs | 45 +++++++++++++++++++ ZSharp.Compiler.Features/callable/CallSite.cs | 11 +++++ ZSharp.Compiler.Features/callable/Callable.cs | 6 +++ .../callable/IArgumentStream.cs | 11 +++++ .../callable/IParameter.cs | 7 +++ .../callable/ISignature.cs | 7 +++ ZSharp.Compiler.Features/generic/Generic.cs | 5 +-- .../generic/IGenericParameter.cs | 2 +- ZSharp.Compiler.Features/oop/IOOPMember.cs | 13 ------ ZSharp.Compiler.Features/oop/IOOPType.cs | 7 --- ZSharp.Compiler.Features/oop/OOP.cs | 22 --------- ZSharp.Compiler.Features/operators/Ops.cs | 10 ----- .../referencing/IReferencable.cs | 16 ------- .../referencing/IReference.cs | 9 ---- .../referencing/ReferenceContext.cs | 24 ---------- .../referencing/Referencing.cs | 28 ------------ 18 files changed, 100 insertions(+), 134 deletions(-) create mode 100644 ZSharp.Compiler.Features/callable/BoundParameter.cs create mode 100644 ZSharp.Compiler.Features/callable/BoundSignature.cs create mode 100644 ZSharp.Compiler.Features/callable/CallSite.cs create mode 100644 ZSharp.Compiler.Features/callable/Callable.cs create mode 100644 ZSharp.Compiler.Features/callable/IArgumentStream.cs create mode 100644 ZSharp.Compiler.Features/callable/IParameter.cs create mode 100644 ZSharp.Compiler.Features/callable/ISignature.cs delete mode 100644 ZSharp.Compiler.Features/oop/IOOPMember.cs delete mode 100644 ZSharp.Compiler.Features/oop/IOOPType.cs delete mode 100644 ZSharp.Compiler.Features/oop/OOP.cs delete mode 100644 ZSharp.Compiler.Features/operators/Ops.cs delete mode 100644 ZSharp.Compiler.Features/referencing/IReferencable.cs delete mode 100644 ZSharp.Compiler.Features/referencing/IReference.cs delete mode 100644 ZSharp.Compiler.Features/referencing/ReferenceContext.cs delete mode 100644 ZSharp.Compiler.Features/referencing/Referencing.cs diff --git a/ZSharp.Compiler.Features/GlobalUsings.cs b/ZSharp.Compiler.Features/GlobalUsings.cs index 98426100..05db7df2 100644 --- a/ZSharp.Compiler.Features/GlobalUsings.cs +++ b/ZSharp.Compiler.Features/GlobalUsings.cs @@ -1 +1 @@ -global using Error = string; +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.Features/callable/BoundParameter.cs b/ZSharp.Compiler.Features/callable/BoundParameter.cs new file mode 100644 index 00000000..439b8442 --- /dev/null +++ b/ZSharp.Compiler.Features/callable/BoundParameter.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler.Features.Callable +{ + public sealed class BoundParameter + { + public required CompilerObject ParameterObject { get; init; } + + public required CompilerObject ArgumentObject { get; init; } + } +} diff --git a/ZSharp.Compiler.Features/callable/BoundSignature.cs b/ZSharp.Compiler.Features/callable/BoundSignature.cs new file mode 100644 index 00000000..5247aa5a --- /dev/null +++ b/ZSharp.Compiler.Features/callable/BoundSignature.cs @@ -0,0 +1,45 @@ +using CommonZ.Utils; + +namespace ZSharp.Compiler.Features.Callable +{ + public sealed class BoundSignature + { + public required CompilerObject SignatureObject { get; init; } + + public Collection Parameters { get; init; } = []; + + public static Result Create(Compiler compiler, CompilerObject @object, IArgumentStream arguments) + { + if (!@object.Is(out var signature)) + return Result.Error($"Object '{@object}' is not a signature."); + + var boundSignature = new BoundSignature + { + SignatureObject = @object, + }; + foreach (var parameterObject in signature.Parameters(compiler)) + { + if (!parameterObject.Is(out var parameter)) + return Result.Error($"Object '{parameterObject}' is not a parameter."); + + if ( + parameter.Match(compiler, arguments) + .When(out var value) + .Error(out var error) + ) return Result.Error(error); + + boundSignature.Parameters.Add( + new() + { + ParameterObject = (CompilerObject)parameter, + ArgumentObject = value!, + } + ); + } + if (arguments.HasArguments) + return Result.Error($"Too many arguments provided for signature '{@object}'."); + + return Result.Ok(boundSignature); + } + } +} diff --git a/ZSharp.Compiler.Features/callable/CallSite.cs b/ZSharp.Compiler.Features/callable/CallSite.cs new file mode 100644 index 00000000..724f714e --- /dev/null +++ b/ZSharp.Compiler.Features/callable/CallSite.cs @@ -0,0 +1,11 @@ +using CommonZ.Utils; + +namespace ZSharp.Compiler.Features.Callable +{ + public sealed class CallSite + { + public required CompilerObject Callable { get; init; } + + public Collection Arguments { get; init; } = []; + } +} diff --git a/ZSharp.Compiler.Features/callable/Callable.cs b/ZSharp.Compiler.Features/callable/Callable.cs new file mode 100644 index 00000000..519357f0 --- /dev/null +++ b/ZSharp.Compiler.Features/callable/Callable.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler.Features.Callable +{ + public sealed class Callable + { + } +} diff --git a/ZSharp.Compiler.Features/callable/IArgumentStream.cs b/ZSharp.Compiler.Features/callable/IArgumentStream.cs new file mode 100644 index 00000000..a81fb78f --- /dev/null +++ b/ZSharp.Compiler.Features/callable/IArgumentStream.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Compiler.Features.Callable +{ + public interface IArgumentStream + { + public bool HasArguments { get; } + + public CompilerObject? PopArgument(); + + public CompilerObject? PopArgument(string name); + } +} diff --git a/ZSharp.Compiler.Features/callable/IParameter.cs b/ZSharp.Compiler.Features/callable/IParameter.cs new file mode 100644 index 00000000..bba3c9eb --- /dev/null +++ b/ZSharp.Compiler.Features/callable/IParameter.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.Features.Callable +{ + public interface IParameter + { + public Result Match(Compiler compiler, IArgumentStream arguments); + } +} diff --git a/ZSharp.Compiler.Features/callable/ISignature.cs b/ZSharp.Compiler.Features/callable/ISignature.cs new file mode 100644 index 00000000..3745ea31 --- /dev/null +++ b/ZSharp.Compiler.Features/callable/ISignature.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler.Features.Callable +{ + public interface ISignature + { + public IEnumerable Parameters(Compiler compiler); + } +} diff --git a/ZSharp.Compiler.Features/generic/Generic.cs b/ZSharp.Compiler.Features/generic/Generic.cs index 16d9b378..2a394f3a 100644 --- a/ZSharp.Compiler.Features/generic/Generic.cs +++ b/ZSharp.Compiler.Features/generic/Generic.cs @@ -1,9 +1,8 @@ using CommonZ.Utils; -using ZSharp.Objects; -namespace ZSharp.Compiler +namespace ZSharp.Compiler.Features.Generic { - public sealed class Generic(Compiler compiler) : Feature(compiler) + public sealed class Generic { public bool IsGenericDefinition(CompilerObject @object) { diff --git a/ZSharp.Compiler.Features/generic/IGenericParameter.cs b/ZSharp.Compiler.Features/generic/IGenericParameter.cs index 93d56593..3ad68e54 100644 --- a/ZSharp.Compiler.Features/generic/IGenericParameter.cs +++ b/ZSharp.Compiler.Features/generic/IGenericParameter.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Objects +namespace ZSharp.Compiler.Features.Generic { public interface IGenericParameter : CompilerObject { diff --git a/ZSharp.Compiler.Features/oop/IOOPMember.cs b/ZSharp.Compiler.Features/oop/IOOPMember.cs deleted file mode 100644 index acfce5d8..00000000 --- a/ZSharp.Compiler.Features/oop/IOOPMember.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IOOPMember : CompilerObject - { - public IOOPType Owner { get; } - - public bool IsInstance { get; } - - public bool IsClass { get; } - - public bool IsStatic { get; } - } -} diff --git a/ZSharp.Compiler.Features/oop/IOOPType.cs b/ZSharp.Compiler.Features/oop/IOOPType.cs deleted file mode 100644 index 89e2955d..00000000 --- a/ZSharp.Compiler.Features/oop/IOOPType.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IOOPType : CompilerObject - { - - } -} diff --git a/ZSharp.Compiler.Features/oop/OOP.cs b/ZSharp.Compiler.Features/oop/OOP.cs deleted file mode 100644 index 958d5972..00000000 --- a/ZSharp.Compiler.Features/oop/OOP.cs +++ /dev/null @@ -1,22 +0,0 @@ -using ZSharp.Objects; - -namespace ZSharp.Compiler -{ - public sealed class OOP(Compiler compiler) : Feature(compiler) - { - public bool IsClass(CompilerObject @object) - { - throw new NotImplementedException(); - } - - public CompilerObject BaseOf(CompilerObject @object) - { - throw new NotImplementedException(); - } - - public CompilerObject[] InterfacesOf(CompilerObject @object) - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Compiler.Features/operators/Ops.cs b/ZSharp.Compiler.Features/operators/Ops.cs deleted file mode 100644 index bc82de5d..00000000 --- a/ZSharp.Compiler.Features/operators/Ops.cs +++ /dev/null @@ -1,10 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Objects; - -namespace ZSharp.Compiler -{ - public sealed class Ops(Compiler compiler) : Feature(compiler) - { - public Cache Binary = []; - } -} diff --git a/ZSharp.Compiler.Features/referencing/IReferencable.cs b/ZSharp.Compiler.Features/referencing/IReferencable.cs deleted file mode 100644 index 02b74e29..00000000 --- a/ZSharp.Compiler.Features/referencing/IReferencable.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IReferencable : CompilerObject - { - public CompilerObject CreateReference(Compiler.Referencing @ref, ReferenceContext context); - } - - public interface IReferencable : IReferencable - where T : CompilerObject - { - CompilerObject IReferencable.CreateReference(Compiler.Referencing @ref, ReferenceContext context) - => CreateReference(@ref, context); - - public new T CreateReference(Compiler.Referencing @ref, ReferenceContext context); - } -} diff --git a/ZSharp.Compiler.Features/referencing/IReference.cs b/ZSharp.Compiler.Features/referencing/IReference.cs deleted file mode 100644 index 6817cb0c..00000000 --- a/ZSharp.Compiler.Features/referencing/IReference.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IReference - { - public CompilerObject Origin { get; } - - public ReferenceContext? Context { get; set; } - } -} diff --git a/ZSharp.Compiler.Features/referencing/ReferenceContext.cs b/ZSharp.Compiler.Features/referencing/ReferenceContext.cs deleted file mode 100644 index 1762984c..00000000 --- a/ZSharp.Compiler.Features/referencing/ReferenceContext.cs +++ /dev/null @@ -1,24 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Objects -{ - public sealed class ReferenceContext(ReferenceContext? parent = null) - { - public Cache CompileTimeValues { get; init; } = new() - { - Parent = parent?.CompileTimeValues - }; - - public ReferenceContext? Parent { get; } = parent; - - public CompilerObject? Scope { get; init; } = null; - - public CompilerObject this[CompilerObject key] - { - get => CompileTimeValues.Cache(key) ?? throw new KeyNotFoundException( - $"Key {key} was not found in the reference context{(Scope is null ? string.Empty : $" {Scope}")}." - ); - set => CompileTimeValues.Cache(key, value); - } - } -} diff --git a/ZSharp.Compiler.Features/referencing/Referencing.cs b/ZSharp.Compiler.Features/referencing/Referencing.cs deleted file mode 100644 index 4dbb4217..00000000 --- a/ZSharp.Compiler.Features/referencing/Referencing.cs +++ /dev/null @@ -1,28 +0,0 @@ -using ZSharp.Objects; - -namespace ZSharp.Compiler -{ - public sealed class Referencing(Compiler compiler) - : Feature(compiler) - { - public CompilerObject CreateReference(CompilerObject @object, ReferenceContext context) - { - if (@object is IReferencable referencable) - return referencable.CreateReference(this, context); - - return @object; - } - - public T CreateReference(CompilerObject @object, ReferenceContext context) - where T : CompilerObject - { - if (@object is IReferencable referencable) - return referencable.CreateReference(this, context); - - if (@object is T result) - return result; - - throw new NotImplementedException(); - } - } -} From 7e46d6ecb95486305cb2c66e1677c63bceb5b150 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 11 Oct 2025 23:36:41 +0300 Subject: [PATCH 219/235] Fix delegate exposer --- ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs index 0aa1d76b..6bbdbd8b 100644 --- a/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs @@ -46,11 +46,13 @@ public CompilerObject Expose(object? obj, Type type) public CompilerObject Expose(Delegate @delegate) { - var wrapped = new ExposedObjectWrapper(@delegate.Target, @delegate.Method); + //var wrapped = new ExposedObjectWrapper(@delegate.Target, @delegate.Method); // TODO: Cache this method info // TODO: Add support for array. Currently not supported because there's no make-array instruction in IR - var methodCO = LoadMethod(typeof(ExposedObjectWrapper).GetMethod("Invoke", [typeof(object)]) ?? throw new()); - var @object = ExposeAsIR(wrapped); + //var methodCO = LoadMethod(typeof(ExposedObjectWrapper).GetMethod("Invoke", [typeof(object)]) ?? throw new()); + //var @object = ExposeAsIR(wrapped); + var @object = ExposeAsIR(@delegate.Target); + var methodCO = LoadMethod(@delegate.Method); var objectCode = new RawIRCode(new(@object)); return new Objects.BoundMethod() From 425e1820798795a04e8c42bacfa55b7cde9a7492 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen <42520501+binyamin555@users.noreply.github.com> Date: Wed, 15 Oct 2025 14:38:05 +0300 Subject: [PATCH 220/235] Update the discord invite link because I accidentally deleted the existing one --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 14ead123..34b1a6f6 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ > This README file is out-of-date. I will update this once I have enough time and an acceptable working version. -> If you have any questions regarding this project, you can join the discord server ~~[discord server](https://discord.gg/Uc3GN2bfG9)~~ [discord channel on PLTD](https://discord.gg/Zfbzdaks2D). +> If you have any questions regarding this project, you can join the discord server ~~[discord server](https://discord.gg/Uc3GN2bfG9)~~ [discord channel on PLTD](https://discord.gg/jkCSRvpyYA). Welcome to the Z# language repository! This repository holds the first released version of Z#. From 7dfaa00f24fe58c743ecac8dccf17cafd767aece Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 15 Oct 2025 22:57:22 +0300 Subject: [PATCH 221/235] Fix naming/typos --- .../compiler/compile/stmt/ScriptCompiler.Compile.If.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.If.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.If.cs index 9a1a3a84..5e4730f2 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.If.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.If.cs @@ -8,7 +8,7 @@ private void Compile(AST.IfStatement @if) if ( conditionResult - .When(out var confition) + .When(out var condition) .Error(out var error) ) { @@ -21,16 +21,16 @@ private void Compile(AST.IfStatement @if) // TODO: cast to boolean - var conditionValueResult = Interpreter.Evaluate(confition!); + var conditionValueResult = Interpreter.Evaluate(condition!); if ( conditionValueResult .When(out var conditionValue) - .Error(out var error2) + .Error(out error) ) { Interpreter.Log.Error( - $"Failed to evaluate if condition: {error2}", + $"Failed to evaluate if condition: {error}", new NodeLogOrigin(@if.Condition) ); return; From bb7157c567f00449000b64fb4ed36832eb69e065 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 15 Oct 2025 23:02:00 +0300 Subject: [PATCH 222/235] Add evaluation system to compiler --- ZSharp v1.sln | 18 ++++++++++++ ZSharp.CLI/Program.cs | 2 ++ ZSharp.CLI/ZSharp.CLI.csproj | 2 ++ .../GlobalUsings.cs | 4 +++ .../ZSharp.Compiler.Evaluation.Direct.csproj | 15 ++++++++++ .../dispatcher/Dispatcher.cs | 20 +++++++++++++ .../services/Dispatcher.Evaluate.cs | 15 ++++++++++ .../protocols/evaluate/ICTEvaluate.cs | 7 +++++ ZSharp.Compiler.Evaluation.IR/GlobalUsings.cs | 4 +++ .../ZSharp.Compiler.Evaluation.IR.csproj | 17 +++++++++++ .../dispatcher/Dispatcher.cs | 24 ++++++++++++++++ .../services/Dispatcher.Evaluate.cs | 21 ++++++++++++++ ZSharp.Compiler.Evaluation/GlobalUsings.cs | 1 + .../ZSharp.Compiler.Evaluation.csproj | 13 +++++++++ .../dispatcher/Dispatcher.Evaluate.cs | 10 +++++++ .../dispatcher/Dispatcher.cs | 6 ++++ .../evaluator/Evaluator.cs | 7 +++++ .../evaluator/services/Evaluator.Evaluate.cs | 9 ++++++ ZSharp.Compiler/ZSharp.Compiler.csproj | 1 + .../TopLevelExpressionCompiler.cs | 28 ++++++++++--------- .../FunctionCompiler.Compile.cs | 7 +---- .../stmt/ModuleCompiler.Compile.Expression.cs | 17 ++++++++++- .../objects/EmptyObject.cs | 10 +++++++ .../expr/ScriptCompiler.Compile.Expression.cs | 2 +- .../stmt/ScriptCompiler.Compile.Expression.cs | 3 +- .../stmt/ScriptCompiler.Compile.Import.cs | 18 ++---------- 26 files changed, 243 insertions(+), 38 deletions(-) create mode 100644 ZSharp.Compiler.Evaluation.Direct/GlobalUsings.cs create mode 100644 ZSharp.Compiler.Evaluation.Direct/ZSharp.Compiler.Evaluation.Direct.csproj create mode 100644 ZSharp.Compiler.Evaluation.Direct/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.Evaluation.Direct/dispatcher/services/Dispatcher.Evaluate.cs create mode 100644 ZSharp.Compiler.Evaluation.Direct/protocols/evaluate/ICTEvaluate.cs create mode 100644 ZSharp.Compiler.Evaluation.IR/GlobalUsings.cs create mode 100644 ZSharp.Compiler.Evaluation.IR/ZSharp.Compiler.Evaluation.IR.csproj create mode 100644 ZSharp.Compiler.Evaluation.IR/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.Evaluation.IR/dispatcher/services/Dispatcher.Evaluate.cs create mode 100644 ZSharp.Compiler.Evaluation/GlobalUsings.cs create mode 100644 ZSharp.Compiler.Evaluation/ZSharp.Compiler.Evaluation.csproj create mode 100644 ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.Evaluate.cs create mode 100644 ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.cs create mode 100644 ZSharp.Compiler.Evaluation/evaluator/Evaluator.cs create mode 100644 ZSharp.Compiler.Evaluation/evaluator/services/Evaluator.Evaluate.cs create mode 100644 ZSharp.SourceCompiler.Module/objects/EmptyObject.cs diff --git a/ZSharp v1.sln b/ZSharp v1.sln index 3ae7003d..85b0fe79 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -79,8 +79,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Reflection" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.IR.Static", "ZSharp.Compiler.IR.Static\ZSharp.Compiler.IR.Static.csproj", "{D4B62927-75B2-4147-8B63-1154BA1AB9CE}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Evaluation", "ZSharp.Compiler.Evaluation\ZSharp.Compiler.Evaluation.csproj", "{C8474D6A-5A65-4D39-AA23-A9EBF8A405AC}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Importer.RT", "ZSharp.Importer.RT\ZSharp.Importer.RT.csproj", "{2C743056-A568-443E-B659-5B6731CD9B24}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Evaluation.Direct", "ZSharp.Compiler.Evaluation.Direct\ZSharp.Compiler.Evaluation.Direct.csproj", "{12BA2B1B-FC9D-4C8C-8D0B-265248CE992D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Evaluation.IR", "ZSharp.Compiler.Evaluation.IR\ZSharp.Compiler.Evaluation.IR.csproj", "{D409F69A-8459-7B08-E513-7235D92D8EA0}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -239,10 +245,22 @@ Global {D4B62927-75B2-4147-8B63-1154BA1AB9CE}.Debug|Any CPU.Build.0 = Debug|Any CPU {D4B62927-75B2-4147-8B63-1154BA1AB9CE}.Release|Any CPU.ActiveCfg = Release|Any CPU {D4B62927-75B2-4147-8B63-1154BA1AB9CE}.Release|Any CPU.Build.0 = Release|Any CPU + {C8474D6A-5A65-4D39-AA23-A9EBF8A405AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C8474D6A-5A65-4D39-AA23-A9EBF8A405AC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C8474D6A-5A65-4D39-AA23-A9EBF8A405AC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C8474D6A-5A65-4D39-AA23-A9EBF8A405AC}.Release|Any CPU.Build.0 = Release|Any CPU {2C743056-A568-443E-B659-5B6731CD9B24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2C743056-A568-443E-B659-5B6731CD9B24}.Debug|Any CPU.Build.0 = Debug|Any CPU {2C743056-A568-443E-B659-5B6731CD9B24}.Release|Any CPU.ActiveCfg = Release|Any CPU {2C743056-A568-443E-B659-5B6731CD9B24}.Release|Any CPU.Build.0 = Release|Any CPU + {12BA2B1B-FC9D-4C8C-8D0B-265248CE992D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {12BA2B1B-FC9D-4C8C-8D0B-265248CE992D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {12BA2B1B-FC9D-4C8C-8D0B-265248CE992D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {12BA2B1B-FC9D-4C8C-8D0B-265248CE992D}.Release|Any CPU.Build.0 = Release|Any CPU + {D409F69A-8459-7B08-E513-7235D92D8EA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D409F69A-8459-7B08-E513-7235D92D8EA0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D409F69A-8459-7B08-E513-7235D92D8EA0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D409F69A-8459-7B08-E513-7235D92D8EA0}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ZSharp.CLI/Program.cs b/ZSharp.CLI/Program.cs index 7a2338f3..8467bad8 100644 --- a/ZSharp.CLI/Program.cs +++ b/ZSharp.CLI/Program.cs @@ -150,6 +150,8 @@ new ZSharp.Compiler.IRDispatchers.Static.Dispatcher(interpreter.Compiler).Apply(); +new ZSharp.Compiler.EvaluatorDispatchers.Direct.Dispatcher(interpreter.Compiler).Apply(); +new ZSharp.Compiler.EvaluatorDispatchers.IR.Dispatcher(interpreter.Compiler, interpreter.Runtime, interpreter.RTLoader).Apply(); var scriptCompiler = new ScriptCompiler(interpreter, documentNode, filePath); interpreter.ILLoader.OnLoadOperator = (@operator, method) => diff --git a/ZSharp.CLI/ZSharp.CLI.csproj b/ZSharp.CLI/ZSharp.CLI.csproj index 7371fc6a..79956248 100644 --- a/ZSharp.CLI/ZSharp.CLI.csproj +++ b/ZSharp.CLI/ZSharp.CLI.csproj @@ -20,6 +20,8 @@ + + diff --git a/ZSharp.Compiler.Evaluation.Direct/GlobalUsings.cs b/ZSharp.Compiler.Evaluation.Direct/GlobalUsings.cs new file mode 100644 index 00000000..c1bcb323 --- /dev/null +++ b/ZSharp.Compiler.Evaluation.Direct/GlobalUsings.cs @@ -0,0 +1,4 @@ +global using MemberName = string; +global using MemberIndex = int; + +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.Evaluation.Direct/ZSharp.Compiler.Evaluation.Direct.csproj b/ZSharp.Compiler.Evaluation.Direct/ZSharp.Compiler.Evaluation.Direct.csproj new file mode 100644 index 00000000..648e0ee7 --- /dev/null +++ b/ZSharp.Compiler.Evaluation.Direct/ZSharp.Compiler.Evaluation.Direct.csproj @@ -0,0 +1,15 @@ + + + + net9.0 + enable + enable + + + + + + + + + diff --git a/ZSharp.Compiler.Evaluation.Direct/dispatcher/Dispatcher.cs b/ZSharp.Compiler.Evaluation.Direct/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..90b049d9 --- /dev/null +++ b/ZSharp.Compiler.Evaluation.Direct/dispatcher/Dispatcher.cs @@ -0,0 +1,20 @@ +namespace ZSharp.Compiler.EvaluatorDispatchers.Direct +{ + public partial class Dispatcher( + Compiler compiler + ) + { + private readonly Compiler compiler = compiler; + + private Evaluator @base; + + public void Apply() + { + @base = compiler.Evaluator; + + ref var evaluator = ref compiler.Evaluator; + + evaluator.Evaluate = Evaluate; + } + } +} diff --git a/ZSharp.Compiler.Evaluation.Direct/dispatcher/services/Dispatcher.Evaluate.cs b/ZSharp.Compiler.Evaluation.Direct/dispatcher/services/Dispatcher.Evaluate.cs new file mode 100644 index 00000000..14d25ee9 --- /dev/null +++ b/ZSharp.Compiler.Evaluation.Direct/dispatcher/services/Dispatcher.Evaluate.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Compiler.EvaluatorDispatchers.Direct +{ + partial class Dispatcher + { + public Result Evaluate(CompilerObject @object) + { + var result = @base.Evaluate(@object); + + if (result.IsError && @object.Is(out var evaluate)) + result = evaluate.Evaluate(compiler); + + return result; + } + } +} diff --git a/ZSharp.Compiler.Evaluation.Direct/protocols/evaluate/ICTEvaluate.cs b/ZSharp.Compiler.Evaluation.Direct/protocols/evaluate/ICTEvaluate.cs new file mode 100644 index 00000000..3ed21a5d --- /dev/null +++ b/ZSharp.Compiler.Evaluation.Direct/protocols/evaluate/ICTEvaluate.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public interface ICTEvaluate + { + public Result Evaluate(Compiler compiler); + } +} diff --git a/ZSharp.Compiler.Evaluation.IR/GlobalUsings.cs b/ZSharp.Compiler.Evaluation.IR/GlobalUsings.cs new file mode 100644 index 00000000..c1bcb323 --- /dev/null +++ b/ZSharp.Compiler.Evaluation.IR/GlobalUsings.cs @@ -0,0 +1,4 @@ +global using MemberName = string; +global using MemberIndex = int; + +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.Evaluation.IR/ZSharp.Compiler.Evaluation.IR.csproj b/ZSharp.Compiler.Evaluation.IR/ZSharp.Compiler.Evaluation.IR.csproj new file mode 100644 index 00000000..cb67154b --- /dev/null +++ b/ZSharp.Compiler.Evaluation.IR/ZSharp.Compiler.Evaluation.IR.csproj @@ -0,0 +1,17 @@ + + + + net9.0 + enable + enable + + + + + + + + + + + diff --git a/ZSharp.Compiler.Evaluation.IR/dispatcher/Dispatcher.cs b/ZSharp.Compiler.Evaluation.IR/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..2e06a2cb --- /dev/null +++ b/ZSharp.Compiler.Evaluation.IR/dispatcher/Dispatcher.cs @@ -0,0 +1,24 @@ +namespace ZSharp.Compiler.EvaluatorDispatchers.IR +{ + public partial class Dispatcher( + Compiler compiler, + Platform.Runtime.Runtime runtime, + Importer.RT.Loader loader + ) + { + private readonly Compiler compiler = compiler; + private readonly Platform.Runtime.Runtime runtime = runtime; + private readonly Importer.RT.Loader loader = loader; + + private Evaluator @base; + + public void Apply() + { + @base = compiler.Evaluator; + + ref var evaluator = ref compiler.Evaluator; + + evaluator.Evaluate = Evaluate; + } + } +} diff --git a/ZSharp.Compiler.Evaluation.IR/dispatcher/services/Dispatcher.Evaluate.cs b/ZSharp.Compiler.Evaluation.IR/dispatcher/services/Dispatcher.Evaluate.cs new file mode 100644 index 00000000..fd9b0eee --- /dev/null +++ b/ZSharp.Compiler.Evaluation.IR/dispatcher/services/Dispatcher.Evaluate.cs @@ -0,0 +1,21 @@ +namespace ZSharp.Compiler.EvaluatorDispatchers.IR +{ + partial class Dispatcher + { + public Result Evaluate(CompilerObject @object) + { + var result = @base.Evaluate(@object); + + if (result.IsOk) return result; + + var irCodeResult = compiler.IR.CompileCode(@object, runtime); + + if (irCodeResult.When(out var irCode).Error(out var error)) + return Result.Error(error); + + var value = runtime.Evaluate(irCode!.Instructions, irCode.RequireValueType()); + + return loader.Load(value); + } + } +} diff --git a/ZSharp.Compiler.Evaluation/GlobalUsings.cs b/ZSharp.Compiler.Evaluation/GlobalUsings.cs new file mode 100644 index 00000000..05db7df2 --- /dev/null +++ b/ZSharp.Compiler.Evaluation/GlobalUsings.cs @@ -0,0 +1 @@ +global using Result = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.Evaluation/ZSharp.Compiler.Evaluation.csproj b/ZSharp.Compiler.Evaluation/ZSharp.Compiler.Evaluation.csproj new file mode 100644 index 00000000..a46878d7 --- /dev/null +++ b/ZSharp.Compiler.Evaluation/ZSharp.Compiler.Evaluation.csproj @@ -0,0 +1,13 @@ + + + + net9.0 + enable + enable + + + + + + + diff --git a/ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.Evaluate.cs b/ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.Evaluate.cs new file mode 100644 index 00000000..f9d10bd1 --- /dev/null +++ b/ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.Evaluate.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Compiler +{ + partial class Dispatcher + { + public static Result Evaluate(CompilerObject @object) + => Result.Error( + $"Object [{@object}] does not support evaluation." + ); + } +} diff --git a/ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.cs b/ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.cs new file mode 100644 index 00000000..cd652665 --- /dev/null +++ b/ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.cs @@ -0,0 +1,6 @@ +namespace ZSharp.Compiler +{ + internal static partial class Dispatcher + { + } +} diff --git a/ZSharp.Compiler.Evaluation/evaluator/Evaluator.cs b/ZSharp.Compiler.Evaluation/evaluator/Evaluator.cs new file mode 100644 index 00000000..8bcea188 --- /dev/null +++ b/ZSharp.Compiler.Evaluation/evaluator/Evaluator.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Compiler +{ + public partial struct Evaluator() + { + + } +} diff --git a/ZSharp.Compiler.Evaluation/evaluator/services/Evaluator.Evaluate.cs b/ZSharp.Compiler.Evaluation/evaluator/services/Evaluator.Evaluate.cs new file mode 100644 index 00000000..246ee08b --- /dev/null +++ b/ZSharp.Compiler.Evaluation/evaluator/services/Evaluator.Evaluate.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Compiler +{ + public delegate Result Evaluate(CompilerObject @object); + + partial struct Evaluator + { + public Evaluate Evaluate { get; set; } = Dispatcher.Evaluate; + } +} diff --git a/ZSharp.Compiler/ZSharp.Compiler.csproj b/ZSharp.Compiler/ZSharp.Compiler.csproj index c1d33bba..0c467a6d 100644 --- a/ZSharp.Compiler/ZSharp.Compiler.csproj +++ b/ZSharp.Compiler/ZSharp.Compiler.csproj @@ -16,6 +16,7 @@ + diff --git a/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs b/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs index 2063b3e0..1a9cf368 100644 --- a/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs +++ b/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs @@ -10,23 +10,25 @@ public sealed class TopLevelExpressionCompiler(Interpreter.Interpreter interpret public Result Compile(AST.Expression expression) { - var compileResult = CompileExpression(expression); + return CompileExpression(expression); - if ( - compileResult - .When(out var co) - .IsError - ) return compileResult; + //if ( + // compileResult + // .When(out var co) + // .IsError + //) return compileResult; - var evaluateResult = Interpreter.Evaluate(co!); + //return Interpreter.Compiler.Evaluator.Evaluate(co!); - if ( - evaluateResult - .When(out var value) - .Error(out var error) - ) return Result.Error(error); + //var evaluateResult = Interpreter.Evaluate(co!); - return LoadCO(value); + //if ( + // evaluateResult + // .When(out var value) + // .Error(out var error) + //) return Result.Error(error); + + //return LoadCO(value); } } } diff --git a/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs index 854be304..40541fd8 100644 --- a/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs +++ b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs @@ -34,12 +34,7 @@ public void CompileSignature() .Error(out error) ) Interpreter.Log.Error($"{error}", Node.ReturnType); else if ( - Interpreter.Evaluate(returnType!) - .When(out var returnTypeObject) - .Error(out error) - ) Interpreter.Log.Error($"{error}", Node.ReturnType); - else if ( - Interpreter.RTLoader.Load(returnTypeObject!) + Interpreter.Compiler.Evaluator.Evaluate(returnType!) .When(out returnType) .Error(out error) ) Interpreter.Log.Error($"{error}", Node.ReturnType); diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs index eadc1c5c..8d65e937 100644 --- a/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs @@ -3,6 +3,21 @@ partial class ModuleCompiler { private Result Compile(AST.ExpressionStatement expressionStatement) - => CompileExpression(expressionStatement.Expression); + { + var valueObjectResult = Compile(expressionStatement.Expression); + + if ( + valueObjectResult + .When(out var valueObject) + .Error(out var error) + ) + return Result.Error(error); + + Interpreter.Compiler.Evaluator.Evaluate(valueObject!); + return Result.Ok(Objects.EmptyObject.Empty); // it's most likely that the evaluator itself needs + // to return the empty object, although we do need to first cast to void. right now it returns null + // but we can't trust the evaluator saying that null is not valid because it's the only valid value + // for void type. + } } } diff --git a/ZSharp.SourceCompiler.Module/objects/EmptyObject.cs b/ZSharp.SourceCompiler.Module/objects/EmptyObject.cs new file mode 100644 index 00000000..1507a952 --- /dev/null +++ b/ZSharp.SourceCompiler.Module/objects/EmptyObject.cs @@ -0,0 +1,10 @@ +namespace ZSharp.SourceCompiler.Module.Objects +{ + internal sealed class EmptyObject + : CompilerObject + { + public static CompilerObject Empty { get; } = new EmptyObject(); + + private EmptyObject() { } + } +} diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs index e35c1d20..741f382f 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs @@ -21,7 +21,7 @@ private Result PostProcess(Result result) if (Options.EvaluationTarget == EvaluationTarget.Statement) return result; - return Interpreter + return Interpreter // do we realy want to support expression-level evaluation? .Evaluate(value) .When(Interpreter.RTLoader.Load); } diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs index 109fc499..2f8670bf 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Expression.cs @@ -20,7 +20,8 @@ private void Compile(AST.ExpressionStatement expressionStatement) return; } - Interpreter.Evaluate(valueObject!); + Interpreter.Compiler.Evaluator.Evaluate(valueObject!); + // See comment in ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs } } } diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs index 3f445f33..7ad0ceef 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs @@ -55,27 +55,13 @@ [.. argumentsResults.Select(r => r.Unwrap())] } if ( - Interpreter.Evaluate(result!) - .When(out var importObject) - .Error(out error) - ) - { - Interpreter.Log.Error( - $"Failed to evaluate import: {error}", - new NodeLogOrigin(import) - ); - return; - } - importResult = Interpreter.RTLoader.Load(importObject!); - - if ( - importResult + Interpreter.Compiler.Evaluator.Evaluate(result!) .When(out result) .Error(out error) ) { Interpreter.Log.Error( - $"Failed to load import: {error}", + $"Failed to evaluate import: {error}", new NodeLogOrigin(import) ); return; From bf62dd370d031f957869a453ae54fa57d31de737 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 15 Oct 2025 23:05:05 +0300 Subject: [PATCH 223/235] Add support for forwarded types in IL modules exposed to Z# --- .../ImportTypeAttribute.cs | 15 +++++++++++++++ .../extensions/InternalILMemberExtensions.cs | 7 ++++++- .../objects/modular/module/Module.Globals.cs | 13 +++++++++++++ .../type as module/TypeAsModule.Prepare.cs | 13 +++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 ZSharp.Importer.ILLoader.Attributes/ImportTypeAttribute.cs diff --git a/ZSharp.Importer.ILLoader.Attributes/ImportTypeAttribute.cs b/ZSharp.Importer.ILLoader.Attributes/ImportTypeAttribute.cs new file mode 100644 index 00000000..caaee836 --- /dev/null +++ b/ZSharp.Importer.ILLoader.Attributes/ImportTypeAttribute.cs @@ -0,0 +1,15 @@ +namespace ZSharp.Importer.ILLoader +{ + [AttributeUsage( + AttributeTargets.Module | AttributeTargets.Class, + AllowMultiple = true + )] + public sealed class ImportTypeAttribute(Type type) : Attribute + { + public Type Type { get; } = type; + + public string? Alias { get; init; } = null; + + public string? Namespace { get; init; } = null; + } +} diff --git a/ZSharp.Importer.ILLoader/extensions/InternalILMemberExtensions.cs b/ZSharp.Importer.ILLoader/extensions/InternalILMemberExtensions.cs index 80935a92..d7fef64e 100644 --- a/ZSharp.Importer.ILLoader/extensions/InternalILMemberExtensions.cs +++ b/ZSharp.Importer.ILLoader/extensions/InternalILMemberExtensions.cs @@ -1,6 +1,5 @@ using System.Diagnostics.CodeAnalysis; using System.Reflection; -using ZSharp.Importer.ILLoader.Objects; namespace ZSharp.Importer.ILLoader { @@ -37,5 +36,11 @@ public static string GetNamespaceOverride(this MemberInfo member, string rootNam public static bool OverridesNamespace(this MemberInfo member, string rootNamespace, [NotNullWhen(true)] out string? @namespace) => (@namespace = member.GetNamespaceOverride(rootNamespace)) != rootNamespace; + + public static ImportTypeAttribute[] GetImportedTypes(this Module module) + => [.. module.GetCustomAttributes()]; + + public static ImportTypeAttribute[] GetImportedTypes(this Type type) + => [.. type.GetCustomAttributes()]; } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/module/Module.Globals.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Globals.cs index 6423c385..227e406d 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/module/Module.Globals.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Globals.cs @@ -4,6 +4,8 @@ partial class Module { private void PrepareGlobals(IEnumerable scopes) { + foreach (var importedType in IL.GetImportedTypes()) + PrepareImportedType(importedType); foreach (var scope in scopes) PrepareGlobals(scope); } @@ -23,5 +25,16 @@ private void PrepareGlobals(Type scope) BodyLoader.AddMember(member); } } + + private void PrepareImportedType(ImportTypeAttribute importedType) + { + var type = importedType.Type; + if (!type.IsPublic) throw new($"Cannot use {nameof(ImportTypeAttribute)} on non-public type {type.Name}"); + string ns = importedType.Namespace ?? type.Namespace ?? string.Empty; + ILazilyLoadMembers lazyLoader = ns == string.Empty + ? BodyLoader + : Loader.Namespace(ns); + lazyLoader.AddLazyMember(importedType.Alias ?? type.Name, type); + } } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs index 010d241d..ed99f05a 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs @@ -4,6 +4,8 @@ partial class TypeAsModule { private void Prepare() { + foreach (var importedType in IL.GetImportedTypes()) + PrepareImportedType(importedType); foreach (var member in IL.GetMembers()) Prepare(member); } @@ -29,5 +31,16 @@ private void Prepare(IL.MemberInfo member) lazyLoader.AddLazyMember(member.AliasOrName(), member); } + + private void PrepareImportedType(ImportTypeAttribute importedType) + { + var type = importedType.Type; + if (!type.IsPublic) throw new($"Cannot use {nameof(ImportTypeAttribute)} on non-public type {type.Name}"); + string ns = importedType.Namespace ?? type.Namespace ?? string.Empty; + ILazilyLoadMembers lazyLoader = ns == string.Empty + ? BodyLoader + : Loader.Namespace(ns); + lazyLoader.AddLazyMember(importedType.Alias ?? type.Name, type); + } } } From 319999682cbacd95f3a2b40f4a8c35c116eff95d Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 15 Oct 2025 23:06:01 +0300 Subject: [PATCH 224/235] Add core module --- ZSharp v1.sln | 6 ++++++ ZSharp.CLI/Program.cs | 5 +++++ ZSharp.CLI/ZSharp.CLI.csproj | 1 + ZSharp.Library.Core.Compiler/GlobalUsings.cs | 1 + ZSharp.Library.Core.Compiler/ModuleAttributes.cs | 3 +++ .../ZSharp.Library.Core.Compiler.csproj | 15 +++++++++++++++ .../module scope/ModuleScope.cs | 7 +++++++ 7 files changed, 38 insertions(+) create mode 100644 ZSharp.Library.Core.Compiler/GlobalUsings.cs create mode 100644 ZSharp.Library.Core.Compiler/ModuleAttributes.cs create mode 100644 ZSharp.Library.Core.Compiler/ZSharp.Library.Core.Compiler.csproj create mode 100644 ZSharp.Library.Core.Compiler/module scope/ModuleScope.cs diff --git a/ZSharp v1.sln b/ZSharp v1.sln index 85b0fe79..5a7ac4e3 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -83,6 +83,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Evaluation" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Importer.RT", "ZSharp.Importer.RT\ZSharp.Importer.RT.csproj", "{2C743056-A568-443E-B659-5B6731CD9B24}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Library.Core.Compiler", "ZSharp.Library.Core.Compiler\ZSharp.Library.Core.Compiler.csproj", "{820EF0D4-C0F7-468A-A2A5-70A7EF64FF8A}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Evaluation.Direct", "ZSharp.Compiler.Evaluation.Direct\ZSharp.Compiler.Evaluation.Direct.csproj", "{12BA2B1B-FC9D-4C8C-8D0B-265248CE992D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Evaluation.IR", "ZSharp.Compiler.Evaluation.IR\ZSharp.Compiler.Evaluation.IR.csproj", "{D409F69A-8459-7B08-E513-7235D92D8EA0}" @@ -253,6 +255,10 @@ Global {2C743056-A568-443E-B659-5B6731CD9B24}.Debug|Any CPU.Build.0 = Debug|Any CPU {2C743056-A568-443E-B659-5B6731CD9B24}.Release|Any CPU.ActiveCfg = Release|Any CPU {2C743056-A568-443E-B659-5B6731CD9B24}.Release|Any CPU.Build.0 = Release|Any CPU + {820EF0D4-C0F7-468A-A2A5-70A7EF64FF8A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {820EF0D4-C0F7-468A-A2A5-70A7EF64FF8A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {820EF0D4-C0F7-468A-A2A5-70A7EF64FF8A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {820EF0D4-C0F7-468A-A2A5-70A7EF64FF8A}.Release|Any CPU.Build.0 = Release|Any CPU {12BA2B1B-FC9D-4C8C-8D0B-265248CE992D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {12BA2B1B-FC9D-4C8C-8D0B-265248CE992D}.Debug|Any CPU.Build.0 = Debug|Any CPU {12BA2B1B-FC9D-4C8C-8D0B-265248CE992D}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/ZSharp.CLI/Program.cs b/ZSharp.CLI/Program.cs index 8467bad8..b99926ca 100644 --- a/ZSharp.CLI/Program.cs +++ b/ZSharp.CLI/Program.cs @@ -205,6 +205,11 @@ var coreImporter = new CoreLibraryImporter(); stringImporter.RegisterImporter("core", coreImporter); +coreImporter.Add( + "compiler", + interpreter.ILLoader.LoadModule(typeof(Core.Compiler.ModuleScope).Module) +); + #endregion #region Standard Library diff --git a/ZSharp.CLI/ZSharp.CLI.csproj b/ZSharp.CLI/ZSharp.CLI.csproj index 79956248..500bfeaa 100644 --- a/ZSharp.CLI/ZSharp.CLI.csproj +++ b/ZSharp.CLI/ZSharp.CLI.csproj @@ -24,6 +24,7 @@ + diff --git a/ZSharp.Library.Core.Compiler/GlobalUsings.cs b/ZSharp.Library.Core.Compiler/GlobalUsings.cs new file mode 100644 index 00000000..aaaf8106 --- /dev/null +++ b/ZSharp.Library.Core.Compiler/GlobalUsings.cs @@ -0,0 +1 @@ +global using ZSharp.Importer.ILLoader; diff --git a/ZSharp.Library.Core.Compiler/ModuleAttributes.cs b/ZSharp.Library.Core.Compiler/ModuleAttributes.cs new file mode 100644 index 00000000..ab18bbc6 --- /dev/null +++ b/ZSharp.Library.Core.Compiler/ModuleAttributes.cs @@ -0,0 +1,3 @@ +[module: MapNamespace(OldName = "Core.Compiler", NewName = "")] + +[module: ImportType(typeof(ZSharp.Compiler.CompilerObject), Namespace = "")] diff --git a/ZSharp.Library.Core.Compiler/ZSharp.Library.Core.Compiler.csproj b/ZSharp.Library.Core.Compiler/ZSharp.Library.Core.Compiler.csproj new file mode 100644 index 00000000..4a0a6673 --- /dev/null +++ b/ZSharp.Library.Core.Compiler/ZSharp.Library.Core.Compiler.csproj @@ -0,0 +1,15 @@ + + + + net9.0 + enable + enable + + + + + + + + + diff --git a/ZSharp.Library.Core.Compiler/module scope/ModuleScope.cs b/ZSharp.Library.Core.Compiler/module scope/ModuleScope.cs new file mode 100644 index 00000000..031cdbba --- /dev/null +++ b/ZSharp.Library.Core.Compiler/module scope/ModuleScope.cs @@ -0,0 +1,7 @@ +namespace Core.Compiler +{ + [ModuleScope] + public static partial class ModuleScope + { + } +} From 75b05bbab40a5f8d360ce134542c7f372fc783a7 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 15 Oct 2025 23:06:19 +0300 Subject: [PATCH 225/235] Make error messages more clear when object does not support member access --- ZSharp.Compiler.CG/dispatcher/Dispatcher.MemberAccess.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ZSharp.Compiler.CG/dispatcher/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.MemberAccess.cs index 09d91c50..64072057 100644 --- a/ZSharp.Compiler.CG/dispatcher/Dispatcher.MemberAccess.cs +++ b/ZSharp.Compiler.CG/dispatcher/Dispatcher.MemberAccess.cs @@ -4,22 +4,22 @@ partial class Dispatcher { public static Result Member(CompilerObject @object, MemberIndex index) => Result.Error( - "Object does not support member access by index." + $"Object [{@object}] does not support member access by index." ); public static Result Member(CompilerObject @object, MemberIndex index, CompilerObject value) => Result.Error( - "Object does not support member assignment by index." + $"Object [{@object}] does not support member assignment by index." ); public static Result Member(CompilerObject @object, MemberName name) => Result.Error( - "Object does not support member access by name." + $"Object [{@object}] does not support member access by name." ); public static Result Member(CompilerObject @object, MemberName name, CompilerObject value) => Result.Error( - "Object does not support member assignment by name." + $"Object [{@object}] does not support member assignment by name." ); } } From 0868e378f92bb7feb5fa899b0b940778e9f20bd2 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 15 Oct 2025 23:06:45 +0300 Subject: [PATCH 226/235] Update test file --- Examples/test.zs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Examples/test.zs b/Examples/test.zs index b2c11e37..26eb38d7 100644 --- a/Examples/test.zs +++ b/Examples/test.zs @@ -5,6 +5,8 @@ print("[CT] Hello, World!"); import { Directory } from "std:fs"; +import { CompilerObject } from "core:compiler"; + module A { print("[CT] Inside module A"); From ab64fc8f94f3ef55384aa8c10d269b84e368bdb7 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 15 Oct 2025 23:19:34 +0300 Subject: [PATCH 227/235] Fix not returning error result --- .../objects/modular/module/Module.Member.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs index d98fac2d..be80b32c 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs @@ -8,7 +8,7 @@ partial class Module public Result AddMember(string name, CompilerObject member) { if (members.ContainsKey(name)) - Result.Error($"Member '{name}' is already defined in module '{Name}'."); + return Result.Error($"Member '{name}' is already defined in module '{Name}'."); else members[name] = member; From 99b6125b5dd3851785224a38ebea7a46ef0c3920 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Wed, 15 Oct 2025 23:21:15 +0300 Subject: [PATCH 228/235] Remove BALSHOY comment --- .../TopLevelExpressionCompiler.cs | 22 +------------------ 1 file changed, 1 insertion(+), 21 deletions(-) diff --git a/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs b/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs index 1a9cf368..bd70b454 100644 --- a/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs +++ b/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs @@ -9,26 +9,6 @@ public sealed class TopLevelExpressionCompiler(Interpreter.Interpreter interpret public Func LoadCO { get; init; } = interpreter.RTLoader.Load; public Result Compile(AST.Expression expression) - { - return CompileExpression(expression); - - //if ( - // compileResult - // .When(out var co) - // .IsError - //) return compileResult; - - //return Interpreter.Compiler.Evaluator.Evaluate(co!); - - //var evaluateResult = Interpreter.Evaluate(co!); - - //if ( - // evaluateResult - // .When(out var value) - // .Error(out var error) - //) return Result.Error(error); - - //return LoadCO(value); - } + => CompileExpression(expression); } } From 002b2a76ba6e8bf9493e55d90227b344bf043e92 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 17 Oct 2025 15:51:21 +0300 Subject: [PATCH 229/235] Add basic support for type checking and implicit casting --- ZSharp.CLI/Program.cs | 2 ++ ZSharp.CLI/ZSharp.CLI.csproj | 1 + .../callable/IArgumentStream.cs | 10 +++++- .../ZSharp.Compiler.IR.Static.csproj | 1 + .../objects/RawIRCode.cs | 16 ++++++++- .../objects/UntypedIRCode.cs | 29 +++++++++++++++ .../dispatcher/Dispatcher.T.cs | 2 +- .../dispatcher/Dispatcher.TypeOf.cs | 2 +- .../dispatcher/Dispatcher.cs | 4 +-- .../extensions/InternalILMemberExtensions.cs | 5 +++ .../il loader/ILLoader.Expose.cs | 5 ++- .../il loader/ILLoader.cs | 2 +- .../argument stream/ArgumentStream.cs | 35 +++++++++++++++++++ .../callable/parameter/Parameter.IL.cs | 7 ++++ .../objects/callable/parameter/Parameter.cs | 34 ++++++++++++++++++ .../objects/callable/signature/Signature.cs | 15 ++++++++ .../oop/method/concrete/Method.Call.cs | 13 +++++-- .../oop/method/concrete/Method.Signature.cs | 9 +++++ .../objects/oop/method/concrete/Method.cs | 6 ++++ .../method/this parameter/ThisParameter.IL.cs | 7 ++++ .../method/this parameter/ThisParameter.cs | 30 ++++++++++++++++ .../objects/types/string/StringType.cs | 15 +++++++- ZSharp.Importer.RT/ZSharp.Importer.RT.csproj | 1 + .../objects/string/StringLiteral.IR.cs | 6 +++- .../objects/string/StringLiteral.Type.cs | 10 ++++++ .../objects/string/StringLiteral.cs | 4 +-- .../rt loader/Loader.ILLoader.cs | 7 ++++ .../rt loader/Loader.Load.Primitives.cs | 2 +- ZSharp.Importer.RT/rt loader/Loader.cs | 3 +- ZSharp.Interpreter/interpreter/Interpreter.cs | 4 +-- .../module scope/ModuleScope.Functions.cs | 4 +-- .../ExpressionCompiler.Compile.Literal.cs | 2 +- .../LiteralCompiler.Compile.String.cs | 2 +- .../literal compiler/LiteralCompiler.cs | 4 +-- .../expr/ScriptCompiler.Compile.Literal.cs | 2 +- 35 files changed, 275 insertions(+), 26 deletions(-) create mode 100644 ZSharp.Compiler.IR.Static/objects/UntypedIRCode.cs create mode 100644 ZSharp.Importer.ILLoader/objects/callable/argument stream/ArgumentStream.cs create mode 100644 ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.IL.cs create mode 100644 ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.cs create mode 100644 ZSharp.Importer.ILLoader/objects/callable/signature/Signature.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Signature.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.IL.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.cs create mode 100644 ZSharp.Importer.RT/objects/string/StringLiteral.Type.cs create mode 100644 ZSharp.Importer.RT/rt loader/Loader.ILLoader.cs diff --git a/ZSharp.CLI/Program.cs b/ZSharp.CLI/Program.cs index b99926ca..2b6cc6c5 100644 --- a/ZSharp.CLI/Program.cs +++ b/ZSharp.CLI/Program.cs @@ -148,6 +148,8 @@ new ZSharp.Compiler.CGDispatchers.Typed.Dispatcher(interpreter.Compiler).Apply(); new ZSharp.Compiler.CGDispatchers.Proxy.Dispatcher(interpreter.Compiler).Apply(); +new ZSharp.Compiler.TSDispatchers.Static.Dispatcher(interpreter.Compiler).Apply(); + new ZSharp.Compiler.IRDispatchers.Static.Dispatcher(interpreter.Compiler).Apply(); new ZSharp.Compiler.EvaluatorDispatchers.Direct.Dispatcher(interpreter.Compiler).Apply(); diff --git a/ZSharp.CLI/ZSharp.CLI.csproj b/ZSharp.CLI/ZSharp.CLI.csproj index 500bfeaa..966ca74b 100644 --- a/ZSharp.CLI/ZSharp.CLI.csproj +++ b/ZSharp.CLI/ZSharp.CLI.csproj @@ -23,6 +23,7 @@ + diff --git a/ZSharp.Compiler.Features/callable/IArgumentStream.cs b/ZSharp.Compiler.Features/callable/IArgumentStream.cs index a81fb78f..b2665c4e 100644 --- a/ZSharp.Compiler.Features/callable/IArgumentStream.cs +++ b/ZSharp.Compiler.Features/callable/IArgumentStream.cs @@ -1,4 +1,6 @@ -namespace ZSharp.Compiler.Features.Callable +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Compiler.Features.Callable { public interface IArgumentStream { @@ -7,5 +9,11 @@ public interface IArgumentStream public CompilerObject? PopArgument(); public CompilerObject? PopArgument(string name); + + public bool PopArgument([NotNullWhen(true)] out CompilerObject? argument) + => (argument = PopArgument()) is not null; + + public bool PopArgument(string name, [NotNullWhen(true)] out CompilerObject? argument) + => (argument = PopArgument(name)) is not null; } } diff --git a/ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj b/ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj index 01691937..563f4b9d 100644 --- a/ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj +++ b/ZSharp.Compiler.IR.Static/ZSharp.Compiler.IR.Static.csproj @@ -7,6 +7,7 @@ + diff --git a/ZSharp.Compiler.IR.Static/objects/RawIRCode.cs b/ZSharp.Compiler.IR.Static/objects/RawIRCode.cs index 0785cba2..4f66e050 100644 --- a/ZSharp.Compiler.IR.Static/objects/RawIRCode.cs +++ b/ZSharp.Compiler.IR.Static/objects/RawIRCode.cs @@ -1,4 +1,5 @@ -using ZSharp.Compiler; +using CommonZ.Utils; +using ZSharp.Compiler; namespace ZSharp.Objects { @@ -10,5 +11,18 @@ public sealed class RawIRCode(IRCode code) Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) => Result.Ok(code); + + public static CompilerObject From(Collection code, CompilerObject type) + => new UntypedIRCode(code, type); + + public static CompilerObject From(Collection code, IR.IType type) + => From(new() + { + Instructions = code, + Types = [type] + }); + + public static CompilerObject From(IRCode code) + => new RawIRCode(code); } } diff --git a/ZSharp.Compiler.IR.Static/objects/UntypedIRCode.cs b/ZSharp.Compiler.IR.Static/objects/UntypedIRCode.cs new file mode 100644 index 00000000..3eb031b8 --- /dev/null +++ b/ZSharp.Compiler.IR.Static/objects/UntypedIRCode.cs @@ -0,0 +1,29 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Objects +{ + internal sealed class UntypedIRCode(Collection code, CompilerObject type) + : CompilerObject + , ICompileIRCode + , ITyped + { + CompilerObject ITyped.Type => type; + + Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) + { + if ( + compiler.IR.CompileType(type) + .When(out var irType) + .Error(out var error) + ) + return Result.Error(error!); + + return Result.Ok(new() + { + Instructions = code, + Types = [irType!] + }); + } + } +} diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs index 8424533e..2becf8f9 100644 --- a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.T.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.CGDispatchers.Direct +namespace ZSharp.Compiler.TSDispatchers.Static { partial class Dispatcher { diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs index 94eedb49..ca7e92b6 100644 --- a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs @@ -1,4 +1,4 @@ -namespace ZSharp.Compiler.CGDispatchers.Direct +namespace ZSharp.Compiler.TSDispatchers.Static { partial class Dispatcher { diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs index 54a54457..5d326666 100644 --- a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.cs @@ -1,6 +1,6 @@ -namespace ZSharp.Compiler.CGDispatchers.Direct +namespace ZSharp.Compiler.TSDispatchers.Static { - internal partial class Dispatcher(Compiler compiler) + public sealed partial class Dispatcher(Compiler compiler) { private readonly Compiler compiler = compiler; private TS @base; diff --git a/ZSharp.Importer.ILLoader/extensions/InternalILMemberExtensions.cs b/ZSharp.Importer.ILLoader/extensions/InternalILMemberExtensions.cs index d7fef64e..39a01fb0 100644 --- a/ZSharp.Importer.ILLoader/extensions/InternalILMemberExtensions.cs +++ b/ZSharp.Importer.ILLoader/extensions/InternalILMemberExtensions.cs @@ -10,6 +10,11 @@ public static string AliasOrName(this MemberInfo member) ? alias.Name : member.Name; + public static string AliasOrName(this ParameterInfo parameter) + => parameter.GetCustomAttribute() is AliasAttribute alias + ? alias.Name + : parameter.Name ?? throw new InvalidOperationException("Parameter name cannot be null."); + public static bool IsModuleScope(this Type type) => type.GetCustomAttribute() is not null; diff --git a/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs index 6bbdbd8b..fef011a0 100644 --- a/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.Expose.cs @@ -51,9 +51,12 @@ public CompilerObject Expose(Delegate @delegate) // TODO: Add support for array. Currently not supported because there's no make-array instruction in IR //var methodCO = LoadMethod(typeof(ExposedObjectWrapper).GetMethod("Invoke", [typeof(object)]) ?? throw new()); //var @object = ExposeAsIR(wrapped); + if (@delegate.Target is null) + return LoadMethod(@delegate.Method); + var @object = ExposeAsIR(@delegate.Target); var methodCO = LoadMethod(@delegate.Method); - var objectCode = new RawIRCode(new(@object)); + var objectCode = RawIRCode.From(@object, LoadType(@delegate.Target.GetType())); return new Objects.BoundMethod() { diff --git a/ZSharp.Importer.ILLoader/il loader/ILLoader.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.cs index 20e9caa3..c2f28454 100644 --- a/ZSharp.Importer.ILLoader/il loader/ILLoader.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.cs @@ -24,7 +24,7 @@ public ILLoader(Compiler.Compiler compiler, Platform.Runtime.Runtime runtime) SInt32 = new Objects.SInt32Type(Runtime.TypeSystem.SInt32), SInt64 = new Objects.SInt64Type(Runtime.TypeSystem.SInt64), SIntNative = new Objects.SIntNativeType(Runtime.TypeSystem.SIntNative), - String = new Objects.StringType(Runtime.TypeSystem.String), + String = new Objects.StringType(Runtime.TypeSystem.String, this), UInt8 = new Objects.UInt8Type(Runtime.TypeSystem.UInt8), UInt16 = new Objects.UInt16Type(Runtime.TypeSystem.UInt16), UInt32 = new Objects.UInt32Type(Runtime.TypeSystem.UInt32), diff --git a/ZSharp.Importer.ILLoader/objects/callable/argument stream/ArgumentStream.cs b/ZSharp.Importer.ILLoader/objects/callable/argument stream/ArgumentStream.cs new file mode 100644 index 00000000..7f9f8630 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/callable/argument stream/ArgumentStream.cs @@ -0,0 +1,35 @@ +using ZSharp.Compiler; +using ZSharp.Compiler.Features.Callable; + +namespace ZSharp.Importer.ILLoader.Objects +{ + internal sealed class ArgumentStream + : IArgumentStream + { + private readonly List args = []; + private readonly Dictionary kwArgs = []; + + public ArgumentStream(Argument[] arguments) + { + foreach (var argument in arguments) + if (argument.Name is null) args.Add(argument.Object); + else kwArgs[argument.Name] = argument.Object; + } + + bool IArgumentStream.HasArguments => args.Count > 0 || kwArgs.Count > 0; + + CompilerObject? IArgumentStream.PopArgument() + { + if (args.Count == 0) return null; + var arg = args[0]; + args.RemoveAt(0); + return arg; + } + + CompilerObject? IArgumentStream.PopArgument(string name) + { + if (!kwArgs.Remove(name, out var arg)) return null; + return arg; + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.IL.cs b/ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.IL.cs new file mode 100644 index 00000000..b0f86b67 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.IL.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Parameter + { + public IL.ParameterInfo IL { get; } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.cs b/ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.cs new file mode 100644 index 00000000..4e31ce2f --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.cs @@ -0,0 +1,34 @@ +using System.Net.WebSockets; +using ZSharp.Compiler; +using ZSharp.Compiler.Features.Callable; + +namespace ZSharp.Importer.ILLoader.Objects +{ + public sealed partial class Parameter + : CompilerObject + , IParameter + { + public string Name { get; } + + public CompilerObject Type { get; } + + public Parameter(IL.ParameterInfo il, ILLoader loader) + { + IL = il; + + Name = IL.AliasOrName(); + Type = loader.LoadType(IL.ParameterType); + } + + Result IParameter.Match(Compiler.Compiler compiler, IArgumentStream arguments) + { + if (!arguments.PopArgument(Name, out var argument) && + !arguments.PopArgument(out argument) + ) + if (IL.HasDefaultValue) return Result.Error("Default values are not supported yet."); + else return Result.Error($"No argument provided for parameter '{this}'."); + + return compiler.CG.ImplicitCast(argument, Type); + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/callable/signature/Signature.cs b/ZSharp.Importer.ILLoader/objects/callable/signature/Signature.cs new file mode 100644 index 00000000..2c5a261b --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/callable/signature/Signature.cs @@ -0,0 +1,15 @@ +using CommonZ.Utils; +using ZSharp.Compiler.Features.Callable; + +namespace ZSharp.Importer.ILLoader.Objects +{ + internal sealed partial class Signature + : CompilerObject + , ISignature + { + internal readonly Collection parameters = []; + + IEnumerable ISignature.Parameters(Compiler.Compiler compiler) + => parameters.Cast(); + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs index 9a9007dc..42b5cfd0 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs @@ -1,5 +1,6 @@  using ZSharp.Compiler; +using ZSharp.Compiler.Features.Callable; namespace ZSharp.Importer.ILLoader.Objects { @@ -8,14 +9,20 @@ partial class Method { Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { + if ( + BoundSignature.Create(compiler, signature, new ArgumentStream(arguments)) + .When(out var boundSignature) + .Error(out var error) + ) return Result.Error(error); + IRCode result = new(); - foreach (var argument in arguments) + foreach (var boundParameter in boundSignature!.Parameters) { if ( - compiler.IR.CompileCode(argument.Object, null) + compiler.IR.CompileCode(boundParameter.ArgumentObject, null) .When(out var argumentCode) - .Error(out var error) + .Error(out error) ) return Result.Error(error); diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Signature.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Signature.cs new file mode 100644 index 00000000..04e0c2d4 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Signature.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Method + { + private readonly Signature signature = new(); + + public CompilerObject Signature => signature; + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.cs index 5632c90f..f7811256 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.cs @@ -7,6 +7,12 @@ public Method(IL.MethodInfo il, ILLoader loader) { IL = il; Loader = loader; + + if (!IL.IsStatic) + signature.parameters.Add(new ThisParameter(IL, loader)); + + foreach (var parameter in IL.GetParameters()) + signature.parameters.Add(new Parameter(parameter, loader)); } } } diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.IL.cs b/ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.IL.cs new file mode 100644 index 00000000..79d3072d --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.IL.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class ThisParameter + { + public IL.MethodInfo IL { get; } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.cs b/ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.cs new file mode 100644 index 00000000..a3316f21 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.cs @@ -0,0 +1,30 @@ +using ZSharp.Compiler.Features.Callable; + +namespace ZSharp.Importer.ILLoader.Objects +{ + internal sealed partial class ThisParameter + : CompilerObject + , IParameter + { + public string Name => "this"; + + public CompilerObject Type { get; } + + public ThisParameter(IL.MethodInfo il, ILLoader loader) + { + IL = il; + + Type = loader.LoadType(IL.DeclaringType ?? throw new()); + } + + Result IParameter.Match(Compiler.Compiler compiler, IArgumentStream arguments) + { + if (!arguments.PopArgument(Name, out var argument) && + !arguments.PopArgument(out argument) + ) + return Result.Error($"No argument provided for parameter '{Name}'."); + + return compiler.CG.ImplicitCast(argument, Type); + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs index 8634292e..d767141a 100644 --- a/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs @@ -3,13 +3,26 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed class StringType(TypeReference type) + internal sealed class StringType(TypeReference type, ILLoader loader) : CompilerObject , ICompileIRType + , IRTImplicitCastTo { private readonly TypeReference type = type; + private readonly ILLoader loader = loader; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); + + Result IRTImplicitCastTo.ImplicitCast(Compiler.Compiler compiler, CompilerObject @object, CompilerObject type) + { + if (compiler.Reflection.IsSameDefinition(this, type)) + return Result.Ok(@object); + + if (compiler.Reflection.IsSameDefinition(loader.TypeSystem.Object, type)) + return Result.Ok(@object); + + return Result.Error($"Cannot implicitly cast string to {type}."); + } } } diff --git a/ZSharp.Importer.RT/ZSharp.Importer.RT.csproj b/ZSharp.Importer.RT/ZSharp.Importer.RT.csproj index 94b2484d..1295c92b 100644 --- a/ZSharp.Importer.RT/ZSharp.Importer.RT.csproj +++ b/ZSharp.Importer.RT/ZSharp.Importer.RT.csproj @@ -9,6 +9,7 @@ + diff --git a/ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs b/ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs index 93418086..69820d69 100644 --- a/ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs +++ b/ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs @@ -10,7 +10,11 @@ Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, TargetPl new IR.VM.PutString(value) ]) { - Types = [type], + Types = [ + compiler.IR.CompileType(type) + .Else(e => new ErrorMessage($"WTF string can't compile to IR type?? {e}")) + .Unwrap() + ], MaxStackSize = 1 }); } diff --git a/ZSharp.Importer.RT/objects/string/StringLiteral.Type.cs b/ZSharp.Importer.RT/objects/string/StringLiteral.Type.cs new file mode 100644 index 00000000..0f17e734 --- /dev/null +++ b/ZSharp.Importer.RT/objects/string/StringLiteral.Type.cs @@ -0,0 +1,10 @@ +using ZSharp.Compiler; + +namespace ZSharp.Importer.RT.Objects +{ + partial class StringLiteral + : ITyped + { + CompilerObject ITyped.Type => type; + } +} diff --git a/ZSharp.Importer.RT/objects/string/StringLiteral.cs b/ZSharp.Importer.RT/objects/string/StringLiteral.cs index ece36bbc..b5ff0c6e 100644 --- a/ZSharp.Importer.RT/objects/string/StringLiteral.cs +++ b/ZSharp.Importer.RT/objects/string/StringLiteral.cs @@ -2,10 +2,10 @@ namespace ZSharp.Importer.RT.Objects { - internal sealed partial class StringLiteral(Value value, IR.IType type) + internal sealed partial class StringLiteral(Value value, CompilerObject type) : CompilerObject { private readonly Value value = value; - private readonly IR.IType type = type; + private readonly CompilerObject type = type; } } diff --git a/ZSharp.Importer.RT/rt loader/Loader.ILLoader.cs b/ZSharp.Importer.RT/rt loader/Loader.ILLoader.cs new file mode 100644 index 00000000..28fa5d75 --- /dev/null +++ b/ZSharp.Importer.RT/rt loader/Loader.ILLoader.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.RT +{ + partial class Loader + { + public ILLoader.ILLoader ILLoader { get; } + } +} diff --git a/ZSharp.Importer.RT/rt loader/Loader.Load.Primitives.cs b/ZSharp.Importer.RT/rt loader/Loader.Load.Primitives.cs index 15923e13..2e455a30 100644 --- a/ZSharp.Importer.RT/rt loader/Loader.Load.Primitives.cs +++ b/ZSharp.Importer.RT/rt loader/Loader.Load.Primitives.cs @@ -3,6 +3,6 @@ partial class Loader { private Objects.StringLiteral Load(string value) - => new(value, TypeSystem.String); + => new(value, ILLoader.LoadType(typeof(string))); } } diff --git a/ZSharp.Importer.RT/rt loader/Loader.cs b/ZSharp.Importer.RT/rt loader/Loader.cs index 67565095..5d847410 100644 --- a/ZSharp.Importer.RT/rt loader/Loader.cs +++ b/ZSharp.Importer.RT/rt loader/Loader.cs @@ -2,8 +2,9 @@ { public sealed partial class Loader { - public Loader() + public Loader(ILLoader.ILLoader ilLoader) { + ILLoader = ilLoader; LoadObject = DefaultLoader; } } diff --git a/ZSharp.Interpreter/interpreter/Interpreter.cs b/ZSharp.Interpreter/interpreter/Interpreter.cs index 08baeaf8..e4c86548 100644 --- a/ZSharp.Interpreter/interpreter/Interpreter.cs +++ b/ZSharp.Interpreter/interpreter/Interpreter.cs @@ -39,11 +39,11 @@ public Interpreter(IR.RuntimeModule? runtimeModule = null) UIntNative = null!, Void = RuntimeModule.TypeSystem.Void }); - RTLoader = new() + ILLoader = new(Compiler, Runtime); + RTLoader = new(ILLoader) { TypeSystem = Runtime.TypeSystem }; - ILLoader = new(Compiler, Runtime); } } } diff --git a/ZSharp.Library.Standard.IO/module scope/ModuleScope.Functions.cs b/ZSharp.Library.Standard.IO/module scope/ModuleScope.Functions.cs index 34556389..9566ea31 100644 --- a/ZSharp.Library.Standard.IO/module scope/ModuleScope.Functions.cs +++ b/ZSharp.Library.Standard.IO/module scope/ModuleScope.Functions.cs @@ -3,7 +3,7 @@ partial class ModuleScope { [Alias("print")] - public static void Print(string message) - => System.Console.WriteLine(message); + public static void Print(object value) + => System.Console.WriteLine(value); } } diff --git a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs index 8908eec4..61bfadb9 100644 --- a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs +++ b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs @@ -7,7 +7,7 @@ private Result Compile(AST.LiteralExpression literal) if (literal.UnitType is not null) Interpreter.Log.Warning($"Literal has a unit type '{literal.UnitType}' which will be ignored.", new NodeLogOrigin(literal)); - return new LiteralCompiler().Compile(literal); + return new LiteralCompiler(Interpreter).Compile(literal); } } } diff --git a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs index 66d6ddf8..e2da1ba1 100644 --- a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs +++ b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs @@ -4,7 +4,7 @@ partial class LiteralCompiler { private Result CompileString(AST.LiteralExpression expression) { - return Result.Ok(new StringLiteral(expression.Value)); + return Interpreter.RTLoader.Load(expression.Value); } } } diff --git a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.cs b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.cs index dbe7444c..c54aec01 100644 --- a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.cs +++ b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.cs @@ -1,7 +1,7 @@ namespace ZSharp.SourceCompiler { - public sealed partial class LiteralCompiler + public sealed partial class LiteralCompiler(Interpreter.Interpreter interpreter) { - + public Interpreter.Interpreter Interpreter { get; } = interpreter; } } diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs index e376f4cb..d9502693 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs @@ -7,7 +7,7 @@ private Result Compile(AST.LiteralExpression literal) if (literal.UnitType is not null) Interpreter.Log.Warning($"Literal has a unit type '{literal.UnitType}' which will be ignored.", new NodeLogOrigin(literal)); - return new LiteralCompiler().Compile(literal); + return new LiteralCompiler(Interpreter).Compile(literal); } } } From 2531ccccd8f4518d905cd92a2e396a93e9412db5 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 17 Oct 2025 15:52:59 +0300 Subject: [PATCH 230/235] Fix proxy to always expect return type of Result So it can override results if it needs to --- ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs | 2 +- .../objects/forward reference/ForwardReference.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs b/ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs index ef29a7a3..ab3884eb 100644 --- a/ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs +++ b/ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs @@ -2,6 +2,6 @@ { public interface IProxy { - public R Apply(Func fn); + public Result Apply(Func> fn) where R : class; } } diff --git a/ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs b/ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs index 4eb3b5f7..2c691144 100644 --- a/ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs +++ b/ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs @@ -11,7 +11,7 @@ internal sealed class ForwardReference bool CompilerObject.Is([NotNullWhen(true)] out T? result) where T : class => Inner.Is(out result); - R IProxy.Apply(Func fn) + Result IProxy.Apply(Func> fn) => fn(Inner); } } From baa3f24437b282a1dea34e167fb5e3ac50eb761e Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Fri, 17 Oct 2025 15:53:18 +0300 Subject: [PATCH 231/235] Fix annoying warning --- ZSharp.Importer.ILLoader/il loader/ILLoader.Events.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ZSharp.Importer.ILLoader/il loader/ILLoader.Events.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.Events.cs index 900b0b45..83404a8b 100644 --- a/ZSharp.Importer.ILLoader/il loader/ILLoader.Events.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.Events.cs @@ -2,6 +2,6 @@ { partial class ILLoader { - public Action OnLoadOperator; + public Action? OnLoadOperator; } } From 2f8dbba4e77921887ba4b3c632ed8bdacbb1da96 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 18 Oct 2025 21:24:56 +0300 Subject: [PATCH 232/235] Make ILLoader even better Now with (lazy) class member support, code resuse, and proper implicit casting! This commit shows the unlimited ingenuity of humanity. It is really something to behold. --- .../capabilities/internal/IAddMember.cs | 2 +- .../capabilities/internal/IBindable.cs | 7 + .../capabilities/internal/IILType.cs | 7 + .../internal/ILazilyLoadMembers.cs | 7 - .../internal/ILazyMemberLoader.cs | 14 ++ .../capabilities/internal/ILoader.cs | 7 + ZSharp.Importer.ILLoader/helpers/Prepare.cs | 124 ++++++++++++++++++ .../LazyMemberLoader.Container.cs | 7 + .../LazyMemberLoader.LazyLoad.cs | 29 ++++ .../LazyMemberLoader.LazyMembers.cs | 7 + .../LazyMemberLoader.Loader.cs | 7 + .../lazy member loader/LazyMemberLoader.cs | 8 ++ .../module body loader/ModuleBodyLoader.cs | 7 + .../load/ModuleBodyLoader.Load.Field.cs | 0 .../ModuleBodyLoader.Load.Method.Generic.cs | 0 .../load/ModuleBodyLoader.Load.Method.cs | 0 .../load/ModuleBodyLoader.Load.Property.cs | 2 +- .../load/ModuleBodyLoader.Load.cs | 1 + .../type body loader/TypeBodyLoader.cs} | 2 +- .../load/TypeBodyLoader.Load.Field.cs | 10 ++ .../TypeBodyLoader.Load.Method.Generic.cs} | 4 +- .../load/TypeBodyLoader.Load.Method.cs} | 6 +- .../load/TypeBodyLoader.Load.Property.cs} | 4 +- .../load/TypeBodyLoader.Load.cs} | 4 +- .../ModuleBodyLoader.LazyLoad.cs | 30 ----- .../module body loader/ModuleBodyLoader.cs | 9 -- .../load/ModuleLoader.Load.Field.cs | 12 -- .../objects/modular/module/Module.Globals.cs | 40 ------ .../objects/modular/module/Module.LazyLoad.cs | 10 +- .../objects/modular/module/Module.Member.cs | 12 +- .../objects/modular/module/Module.cs | 34 +---- .../modular/property/GlobalProperty.cs | 1 + .../type as module/TypeAsModule.LazyLoad.cs | 8 +- .../type as module/TypeAsModule.Member.cs | 10 +- .../type as module/TypeAsModule.Prepare.cs | 46 ------- .../modular/type as module/TypeAsModule.cs | 8 +- .../objects/namespace/Namespace.LazyLoad.cs | 4 +- .../objects/namespace/Namespace.Member.cs | 2 +- .../oop/class/concrete/Class.LazyLoad.cs | 7 + .../oop/class/concrete/Class.Member.cs | 49 +++++++ .../objects/oop/class/concrete/Class.Type.cs | 10 ++ .../objects/oop/class/concrete/Class.cs | 10 +- .../objects/oop/constructor/Constructor.cs | 4 + .../objects/oop/field/Field.cs | 4 + .../oop/method/concrete/Method.Bind.cs | 22 ++++ .../oop/method/concrete/Method.Call.cs | 2 +- .../oop/method/concrete/Method.Signature.cs | 2 + .../objects/oop/method/concrete/Method.cs | 2 + .../this parameter/ThisParameter.IL.cs | 0 .../this parameter/ThisParameter.cs | 0 .../semantics/IReferenceType.cs | 28 ++++ 51 files changed, 416 insertions(+), 216 deletions(-) create mode 100644 ZSharp.Importer.ILLoader/capabilities/internal/IBindable.cs create mode 100644 ZSharp.Importer.ILLoader/capabilities/internal/IILType.cs delete mode 100644 ZSharp.Importer.ILLoader/capabilities/internal/ILazilyLoadMembers.cs create mode 100644 ZSharp.Importer.ILLoader/capabilities/internal/ILazyMemberLoader.cs create mode 100644 ZSharp.Importer.ILLoader/capabilities/internal/ILoader.cs create mode 100644 ZSharp.Importer.ILLoader/helpers/Prepare.cs create mode 100644 ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.Container.cs create mode 100644 ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.LazyLoad.cs create mode 100644 ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.LazyMembers.cs create mode 100644 ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.Loader.cs create mode 100644 ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.cs create mode 100644 ZSharp.Importer.ILLoader/helpers/module body loader/ModuleBodyLoader.cs rename ZSharp.Importer.ILLoader/{ => helpers}/module body loader/load/ModuleBodyLoader.Load.Field.cs (100%) rename ZSharp.Importer.ILLoader/{ => helpers}/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs (100%) rename ZSharp.Importer.ILLoader/{ => helpers}/module body loader/load/ModuleBodyLoader.Load.Method.cs (100%) rename ZSharp.Importer.ILLoader/{ => helpers}/module body loader/load/ModuleBodyLoader.Load.Property.cs (78%) rename ZSharp.Importer.ILLoader/{ => helpers}/module body loader/load/ModuleBodyLoader.Load.cs (93%) rename ZSharp.Importer.ILLoader/{module loader/ModuleLoader.cs => helpers/type body loader/TypeBodyLoader.cs} (61%) create mode 100644 ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Field.cs rename ZSharp.Importer.ILLoader/{module loader/load/ModuleLoader.Load.Method.Generic.cs => helpers/type body loader/load/TypeBodyLoader.Load.Method.Generic.cs} (64%) rename ZSharp.Importer.ILLoader/{module loader/load/ModuleLoader.Load.Method.cs => helpers/type body loader/load/TypeBodyLoader.Load.Method.cs} (53%) rename ZSharp.Importer.ILLoader/{module loader/load/ModuleLoader.Load.Property.cs => helpers/type body loader/load/TypeBodyLoader.Load.Property.cs} (64%) rename ZSharp.Importer.ILLoader/{module loader/load/ModuleLoader.Load.cs => helpers/type body loader/load/TypeBodyLoader.Load.cs} (77%) delete mode 100644 ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs delete mode 100644 ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.cs delete mode 100644 ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Field.cs delete mode 100644 ZSharp.Importer.ILLoader/objects/modular/module/Module.Globals.cs delete mode 100644 ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.LazyLoad.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Member.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Type.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Bind.cs rename ZSharp.Importer.ILLoader/objects/oop/{method => }/this parameter/ThisParameter.IL.cs (100%) rename ZSharp.Importer.ILLoader/objects/oop/{method => }/this parameter/ThisParameter.cs (100%) create mode 100644 ZSharp.Importer.ILLoader/semantics/IReferenceType.cs diff --git a/ZSharp.Importer.ILLoader/capabilities/internal/IAddMember.cs b/ZSharp.Importer.ILLoader/capabilities/internal/IAddMember.cs index 86e8cc59..62ef9b67 100644 --- a/ZSharp.Importer.ILLoader/capabilities/internal/IAddMember.cs +++ b/ZSharp.Importer.ILLoader/capabilities/internal/IAddMember.cs @@ -2,6 +2,6 @@ { internal interface IAddMember { - public void AddMember(string name, CompilerObject member); + public CompilerObject AddMember(string name, CompilerObject member); } } diff --git a/ZSharp.Importer.ILLoader/capabilities/internal/IBindable.cs b/ZSharp.Importer.ILLoader/capabilities/internal/IBindable.cs new file mode 100644 index 00000000..5dd60137 --- /dev/null +++ b/ZSharp.Importer.ILLoader/capabilities/internal/IBindable.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.ILLoader +{ + internal interface IBindable + { + public Result Bind(Compiler.Compiler compiler, CompilerObject target); + } +} diff --git a/ZSharp.Importer.ILLoader/capabilities/internal/IILType.cs b/ZSharp.Importer.ILLoader/capabilities/internal/IILType.cs new file mode 100644 index 00000000..c3323a6d --- /dev/null +++ b/ZSharp.Importer.ILLoader/capabilities/internal/IILType.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.ILLoader +{ + internal interface IILType + { + public Type GetILType(); + } +} diff --git a/ZSharp.Importer.ILLoader/capabilities/internal/ILazilyLoadMembers.cs b/ZSharp.Importer.ILLoader/capabilities/internal/ILazilyLoadMembers.cs deleted file mode 100644 index 753b8e54..00000000 --- a/ZSharp.Importer.ILLoader/capabilities/internal/ILazilyLoadMembers.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Importer.ILLoader -{ - internal interface ILazilyLoadMembers - { - public void AddLazyMember(MemberName member, IL.MemberInfo lazyLoadedMember); - } -} diff --git a/ZSharp.Importer.ILLoader/capabilities/internal/ILazyMemberLoader.cs b/ZSharp.Importer.ILLoader/capabilities/internal/ILazyMemberLoader.cs new file mode 100644 index 00000000..e9f58a9f --- /dev/null +++ b/ZSharp.Importer.ILLoader/capabilities/internal/ILazyMemberLoader.cs @@ -0,0 +1,14 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ZSharp.Importer.ILLoader +{ + internal interface ILazyMemberLoader + { + public void AddLazyMember(MemberName name, IL.MemberInfo member); + + public CompilerObject? GetLazyMember(MemberName name); + + public bool GetLazyMember(MemberName name, [NotNullWhen(true)] out CompilerObject? member) + => (member = GetLazyMember(name)) is not null; + } +} diff --git a/ZSharp.Importer.ILLoader/capabilities/internal/ILoader.cs b/ZSharp.Importer.ILLoader/capabilities/internal/ILoader.cs new file mode 100644 index 00000000..a009956f --- /dev/null +++ b/ZSharp.Importer.ILLoader/capabilities/internal/ILoader.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.ILLoader +{ + internal interface ILoader + { + public CompilerObject LoadMember(T member); + } +} diff --git a/ZSharp.Importer.ILLoader/helpers/Prepare.cs b/ZSharp.Importer.ILLoader/helpers/Prepare.cs new file mode 100644 index 00000000..d7071051 --- /dev/null +++ b/ZSharp.Importer.ILLoader/helpers/Prepare.cs @@ -0,0 +1,124 @@ +using System.Reflection; + +namespace ZSharp.Importer.ILLoader +{ + internal static class Prepare + { + public static void PrepareModule(Objects.Module module, ILLoader loader) + { + var il = module.IL; + + Dictionary mappedNamespaces = []; + foreach (var mapping in il.GetCustomAttributes()) + mappedNamespaces[mapping.OldName] = mapping.NewName; + + List moduleScopes = []; + + foreach (var type in il.GetTypes()) + if (!type.IsPublic) continue; + else + { + if (type.Namespace is string ns) + ns = mappedNamespaces.GetValueOrDefault(ns, ns); + else ns = string.Empty; + + if (type.IsModuleScope()) + { + moduleScopes.Add(type); + continue; + } + + ILazyMemberLoader lazyLoader = ns == string.Empty + ? module.LazyLoader + : loader.Namespace(ns); + + lazyLoader.AddLazyMember(type.AliasOrName(), type); + } + + foreach (var importedType in il.GetImportedTypes()) + PrepareImportedType(importedType, module.LazyLoader, loader); + foreach (var scope in moduleScopes) + PrepareModuleScope(scope, module.LazyLoader, loader); + } + + public static void PrepareTypeAsModule(Objects.TypeAsModule module, ILLoader loader) + { + var il = module.IL; + + Dictionary mappedNamespaces = []; + foreach (var mapping in il.GetCustomAttributes()) + mappedNamespaces[mapping.OldName] = mapping.NewName; + + List moduleScopes = []; + + foreach (var type in il.GetNestedTypes()) + if (!type.IsPublic) continue; + else + { + if (type.Namespace is string ns) + ns = mappedNamespaces.GetValueOrDefault(ns, ns); + else ns = string.Empty; + + if (type.IsModuleScope()) + { + moduleScopes.Add(type); + continue; + } + + ILazyMemberLoader lazyLoader = ns == string.Empty + ? module.LazyLoader + : loader.Namespace(ns); + + lazyLoader.AddLazyMember(type.AliasOrName(), type); + } + + foreach (var importedType in il.GetImportedTypes()) + PrepareImportedType(importedType, module.LazyLoader, loader); + + PrepareModuleScope(module.IL, module.LazyLoader, loader); + } + + private static void PrepareModuleScope(Type scope, ILazyMemberLoader lazyLoader, ILLoader loader) + { + foreach (var member in scope.GetMembers()) + { + if (member.DeclaringType != scope) continue; + + if (member is MethodInfo method && method.IsOperator(out var op)) + { + loader.OnLoadOperator?.Invoke(op, method); + continue; + } + + lazyLoader.AddLazyMember(member.AliasOrName(), member); + } + } + + private static void PrepareImportedType(ImportTypeAttribute importedType, ILazyMemberLoader lazyLoader, ILLoader loader) + { + var type = importedType.Type; + if (!type.IsPublic) throw new($"Cannot use {nameof(ImportTypeAttribute)} on non-public type {type.Name}"); + string ns = importedType.Namespace ?? type.Namespace ?? string.Empty; + lazyLoader = ns == string.Empty + ? lazyLoader + : loader.Namespace(ns); + lazyLoader.AddLazyMember(importedType.Alias ?? type.Name, type); + } + + public static void PrepareType(Objects.Class @class, ILLoader loader) + { + var il = @class.IL; + + foreach (var member in il.GetMembers()) + { + if (member is MethodInfo method && method.IsOperator(out var op)) + { + loader.OnLoadOperator?.Invoke(op, method); + continue; + } + + @class.LazyLoader.AddLazyMember(member.AliasOrName(), member); + } + } + } +} diff --git a/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.Container.cs b/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.Container.cs new file mode 100644 index 00000000..ac62011e --- /dev/null +++ b/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.Container.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class LazyMemberLoader + { + public required IAddMember Container { get; init; } + } +} diff --git a/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.LazyLoad.cs b/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.LazyLoad.cs new file mode 100644 index 00000000..96725d52 --- /dev/null +++ b/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.LazyLoad.cs @@ -0,0 +1,29 @@ +using System.Reflection; + +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class LazyMemberLoader + : ILazyMemberLoader + { + void ILazyMemberLoader.AddLazyMember(string name, MemberInfo member) + { + if (!lazyMembers.TryGetValue(name, out var members)) + lazyMembers[name] = members = []; + + members.Add(member); + } + + CompilerObject? ILazyMemberLoader.GetLazyMember(string name) + { + if (!lazyMembers.TryGetValue(name, out var members)) + return null; + + CompilerObject? result = null; + + foreach (var member in members) + result = Container.AddMember(name, Loader.LoadMember(member)); + + return result; + } + } +} diff --git a/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.LazyMembers.cs b/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.LazyMembers.cs new file mode 100644 index 00000000..8503705d --- /dev/null +++ b/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.LazyMembers.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class LazyMemberLoader + { + private readonly Dictionary> lazyMembers = []; + } +} diff --git a/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.Loader.cs b/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.Loader.cs new file mode 100644 index 00000000..fa1d9f6e --- /dev/null +++ b/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.Loader.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class LazyMemberLoader + { + public required ILoader Loader { get; init; } + } +} diff --git a/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.cs b/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.cs new file mode 100644 index 00000000..4e8226d7 --- /dev/null +++ b/ZSharp.Importer.ILLoader/helpers/lazy member loader/LazyMemberLoader.cs @@ -0,0 +1,8 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + internal sealed partial class LazyMemberLoader + : CompilerObject + { + + } +} diff --git a/ZSharp.Importer.ILLoader/helpers/module body loader/ModuleBodyLoader.cs b/ZSharp.Importer.ILLoader/helpers/module body loader/ModuleBodyLoader.cs new file mode 100644 index 00000000..ee0f1392 --- /dev/null +++ b/ZSharp.Importer.ILLoader/helpers/module body loader/ModuleBodyLoader.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.ILLoader +{ + internal sealed partial class ModuleBodyLoader(ILLoader loader) + { + public ILLoader Loader { get; } = loader; + } +} diff --git a/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs b/ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.Field.cs similarity index 100% rename from ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Field.cs rename to ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.Field.cs diff --git a/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs b/ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs similarity index 100% rename from ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs rename to ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.Method.Generic.cs diff --git a/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs b/ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.Method.cs similarity index 100% rename from ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Method.cs rename to ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.Method.cs diff --git a/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs b/ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.Property.cs similarity index 78% rename from ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs rename to ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.Property.cs index 61a64f84..489a9aca 100644 --- a/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.Property.cs +++ b/ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.Property.cs @@ -4,7 +4,7 @@ partial class ModuleBodyLoader { private CompilerObject LoadProperty(IL.PropertyInfo property) { - throw new NotImplementedException(); + return new Objects.GlobalProperty(); } } } diff --git a/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs b/ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.cs similarity index 93% rename from ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs rename to ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.cs index 41255873..60c9aa32 100644 --- a/ZSharp.Importer.ILLoader/module body loader/load/ModuleBodyLoader.Load.cs +++ b/ZSharp.Importer.ILLoader/helpers/module body loader/load/ModuleBodyLoader.Load.cs @@ -1,6 +1,7 @@ namespace ZSharp.Importer.ILLoader { partial class ModuleBodyLoader + : ILoader { public CompilerObject LoadMember(IL.MemberInfo member) => member switch diff --git a/ZSharp.Importer.ILLoader/module loader/ModuleLoader.cs b/ZSharp.Importer.ILLoader/helpers/type body loader/TypeBodyLoader.cs similarity index 61% rename from ZSharp.Importer.ILLoader/module loader/ModuleLoader.cs rename to ZSharp.Importer.ILLoader/helpers/type body loader/TypeBodyLoader.cs index bcd5cb3c..42a6714e 100644 --- a/ZSharp.Importer.ILLoader/module loader/ModuleLoader.cs +++ b/ZSharp.Importer.ILLoader/helpers/type body loader/TypeBodyLoader.cs @@ -1,6 +1,6 @@ namespace ZSharp.Importer.ILLoader { - internal sealed partial class ModuleLoader(ILLoader loader) + internal sealed partial class TypeBodyLoader(ILLoader loader) { public ILLoader Loader { get; } = loader; } diff --git a/ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Field.cs b/ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Field.cs new file mode 100644 index 00000000..f662194e --- /dev/null +++ b/ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Field.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Importer.ILLoader +{ + partial class TypeBodyLoader + { + private CompilerObject LoadField(IL.FieldInfo field) + { + return new Objects.Field(field, Loader); + } + } +} diff --git a/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs b/ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Method.Generic.cs similarity index 64% rename from ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs rename to ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Method.Generic.cs index 1414f6e1..ae59e25c 100644 --- a/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.Generic.cs +++ b/ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Method.Generic.cs @@ -1,10 +1,10 @@ namespace ZSharp.Importer.ILLoader { - partial class ModuleLoader + partial class TypeBodyLoader { private CompilerObject LoadGenericMethod(IL.MethodInfo method) { - return new Objects.GenericFunction(); + return new Objects.GenericMethod(); } } } diff --git a/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.cs b/ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Method.cs similarity index 53% rename from ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.cs rename to ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Method.cs index 6bf80511..99848680 100644 --- a/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Method.cs +++ b/ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Method.cs @@ -1,15 +1,13 @@ namespace ZSharp.Importer.ILLoader { - partial class ModuleLoader + partial class TypeBodyLoader { private CompilerObject LoadMethod(IL.MethodInfo method) { - if (!method.IsStatic) throw new ArgumentException("Only static methods are supported.", nameof(method)); - if (method.IsGenericMethodDefinition) return LoadGenericMethod(method); - return new Objects.Function(method, Loader); + return new Objects.Method(method, Loader); } } } diff --git a/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Property.cs b/ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Property.cs similarity index 64% rename from ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Property.cs rename to ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Property.cs index fcb56d01..d867900d 100644 --- a/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Property.cs +++ b/ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.Property.cs @@ -1,10 +1,10 @@ namespace ZSharp.Importer.ILLoader { - partial class ModuleLoader + partial class TypeBodyLoader { private CompilerObject LoadProperty(IL.PropertyInfo property) { - throw new NotImplementedException(); + return new Objects.Property(); } } } diff --git a/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.cs b/ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.cs similarity index 77% rename from ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.cs rename to ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.cs index 279e2561..92690dfb 100644 --- a/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.cs +++ b/ZSharp.Importer.ILLoader/helpers/type body loader/load/TypeBodyLoader.Load.cs @@ -1,6 +1,7 @@ namespace ZSharp.Importer.ILLoader { - partial class ModuleLoader + partial class TypeBodyLoader + : ILoader { public CompilerObject LoadMember(IL.MemberInfo member) => member switch @@ -8,6 +9,7 @@ public CompilerObject LoadMember(IL.MemberInfo member) IL.FieldInfo field => LoadField(field), IL.MethodInfo method => LoadMethod(method), IL.PropertyInfo property => LoadProperty(property), + Type type => Loader.LoadType(type), _ => throw new NotSupportedException(), }; } diff --git a/ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs b/ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs deleted file mode 100644 index 624aa09a..00000000 --- a/ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.LazyLoad.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace ZSharp.Importer.ILLoader -{ - partial class ModuleBodyLoader - : ILazilyLoadMembers - { - private readonly Dictionary> ilMembers = []; - - public void AddLazyMember(string member, IL.MemberInfo lazyLoadedMember) - { - if (!ilMembers.TryGetValue(member, out var list)) - ilMembers[member] = list = []; - - list.Add(lazyLoadedMember); - } - - public void AddMember(IL.MemberInfo member) - => AddLazyMember(member.AliasOrName(), member); - - public bool LoadMember(string member) - { - if (!ilMembers.TryGetValue(member, out var list)) - return false; - - foreach (var item in list) - Container.AddMember(member, LoadMember(item)); - - return true; - } - } -} diff --git a/ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.cs b/ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.cs deleted file mode 100644 index 5dcb481a..00000000 --- a/ZSharp.Importer.ILLoader/module body loader/ModuleBodyLoader.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Importer.ILLoader -{ - internal sealed partial class ModuleBodyLoader(IAddMember container, ILLoader loader) - { - public ILLoader Loader { get; } = loader; - - public IAddMember Container { get; } = container; - } -} diff --git a/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Field.cs b/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Field.cs deleted file mode 100644 index c4594694..00000000 --- a/ZSharp.Importer.ILLoader/module loader/load/ModuleLoader.Load.Field.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ZSharp.Importer.ILLoader -{ - partial class ModuleLoader - { - private CompilerObject LoadField(IL.FieldInfo field) - { - if (!field.IsStatic) throw new ArgumentException("Only static fields are supported.", nameof(field)); - - return new Objects.Global(field, Loader); - } - } -} diff --git a/ZSharp.Importer.ILLoader/objects/modular/module/Module.Globals.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Globals.cs deleted file mode 100644 index 227e406d..00000000 --- a/ZSharp.Importer.ILLoader/objects/modular/module/Module.Globals.cs +++ /dev/null @@ -1,40 +0,0 @@ -namespace ZSharp.Importer.ILLoader.Objects -{ - partial class Module - { - private void PrepareGlobals(IEnumerable scopes) - { - foreach (var importedType in IL.GetImportedTypes()) - PrepareImportedType(importedType); - foreach (var scope in scopes) - PrepareGlobals(scope); - } - - private void PrepareGlobals(Type scope) - { - foreach (var member in scope.GetMembers()) - { - if (member.DeclaringType != scope) continue; - - if (member is IL.MethodInfo method && method.IsOperator(out var op)) - { - Loader.OnLoadOperator?.Invoke(op, method); - continue; - } - - BodyLoader.AddMember(member); - } - } - - private void PrepareImportedType(ImportTypeAttribute importedType) - { - var type = importedType.Type; - if (!type.IsPublic) throw new($"Cannot use {nameof(ImportTypeAttribute)} on non-public type {type.Name}"); - string ns = importedType.Namespace ?? type.Namespace ?? string.Empty; - ILazilyLoadMembers lazyLoader = ns == string.Empty - ? BodyLoader - : Loader.Namespace(ns); - lazyLoader.AddLazyMember(importedType.Alias ?? type.Name, type); - } - } -} diff --git a/ZSharp.Importer.ILLoader/objects/modular/module/Module.LazyLoad.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.LazyLoad.cs index 1bfdcd77..2723e61c 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/module/Module.LazyLoad.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/module/Module.LazyLoad.cs @@ -4,14 +4,6 @@ partial class Module { public ILLoader Loader { get; } - internal ModuleBodyLoader BodyLoader { get; } - - public CompilerObject? LoadMember(string name) - { - if (!BodyLoader.LoadMember(name)) - return null; - - return Members[name]; - } + internal ILazyMemberLoader LazyLoader { get; } } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs index a5c92c3c..52fdb043 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs @@ -9,7 +9,7 @@ partial class Module { public Mapping Members { get; } = []; - public void AddMember(string name, CompilerObject member) + CompilerObject IAddMember.AddMember(string name, CompilerObject member) { var result = OnAddResult.None; if (member is IOnAddTo onAdd) @@ -17,16 +17,18 @@ public void AddMember(string name, CompilerObject member) if (result == OnAddResult.None) Members.Add(name, member); + + return member; } - Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) + Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName name) { - if (!Members.TryGetValue(member, out var result) && (result = LoadMember(member)) is null) + if (!Members.TryGetValue(name, out var member) && !LazyLoader.GetLazyMember(name, out member)) return Result.Error( - $"Could not find member {member} in module {IL.Name}" + $"Could not find member {name} in module {IL.Name}" ); - return Result.Ok(result); + return Result.Ok(member); } } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/module/Module.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.cs index 10061afc..1e45a73a 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/module/Module.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/module/Module.cs @@ -11,36 +11,14 @@ public Module(IL.Module il, ILLoader loader) { IL = il; Loader = loader; - BodyLoader = new(this, loader); - Dictionary mappedNamespaces = []; - foreach (var mapping in il.GetCustomAttributes()) - mappedNamespaces[mapping.OldName] = mapping.NewName; + LazyLoader = new LazyMemberLoader() + { + Container = this, + Loader = new ModuleBodyLoader(loader) + }; - List moduleScopes = []; - - foreach (var type in il.GetTypes()) - if (!type.IsPublic) continue; - else - { - if (type.Namespace is string ns) - ns = mappedNamespaces.GetValueOrDefault(ns, ns); - else ns = string.Empty; - - if (type.IsModuleScope()) - { - moduleScopes.Add(type); - continue; - } - - ILazilyLoadMembers lazyLoader = ns == string.Empty - ? BodyLoader - : Loader.Namespace(ns); - - lazyLoader.AddLazyMember(type.AliasOrName(), type); - } - - PrepareGlobals(moduleScopes); + Prepare.PrepareModule(this, loader); } } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/property/GlobalProperty.cs b/ZSharp.Importer.ILLoader/objects/modular/property/GlobalProperty.cs index 739243c4..84a78379 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/property/GlobalProperty.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/property/GlobalProperty.cs @@ -1,6 +1,7 @@ namespace ZSharp.Importer.ILLoader.Objects { public sealed partial class GlobalProperty + : CompilerObject { } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs index 9eca7ff3..97ea2a80 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.LazyLoad.cs @@ -6,12 +6,6 @@ partial class TypeAsModule internal ModuleBodyLoader BodyLoader { get; } - public CompilerObject? LoadMember(string name) - { - if (!BodyLoader.LoadMember(name)) - return null; - - return Members[name]; - } + internal ILazyMemberLoader LazyLoader { get; } } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs index 1cf60925..21653c4a 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs @@ -9,7 +9,7 @@ partial class TypeAsModule { public Mapping Members { get; } = []; - public void AddMember(string name, CompilerObject member) + CompilerObject IAddMember.AddMember(string name, CompilerObject member) { var result = OnAddResult.None; if (member is IOnAddTo onAdd) @@ -17,13 +17,15 @@ public void AddMember(string name, CompilerObject member) if (result == OnAddResult.None) Members.Add(name, member); + + return member; } - Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) + Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName name) { - if (!Members.TryGetValue(member, out var result) && (result = LoadMember(member)) is null) + if (!Members.TryGetValue(name, out var result) && !LazyLoader.GetLazyMember(name, out result)) return Result.Error( - $"Could not find member {member} in module {IL.Name}" + $"Could not find member {name} in module {IL.Name}" ); return Result.Ok(result); diff --git a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs deleted file mode 100644 index ed99f05a..00000000 --- a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Prepare.cs +++ /dev/null @@ -1,46 +0,0 @@ -namespace ZSharp.Importer.ILLoader.Objects -{ - partial class TypeAsModule - { - private void Prepare() - { - foreach (var importedType in IL.GetImportedTypes()) - PrepareImportedType(importedType); - foreach (var member in IL.GetMembers()) - Prepare(member); - } - - private void Prepare(IL.MemberInfo member) - { - if (member.DeclaringType != IL) - return; - - if (member is Type type && type.IsModuleScope()) - throw new InvalidOperationException($"Module scope types are not allowed: {type.FullName}"); - - if (member is IL.MethodInfo method && method.IsOperator()) - { - Console.WriteLine($"Skipping operator method: {method.Name}"); - return; - } - - var @namespace = member.GetNamespaceOverride(RootNamespace); - ILazilyLoadMembers lazyLoader = @namespace == string.Empty - ? BodyLoader - : Loader.Namespace(@namespace); - - lazyLoader.AddLazyMember(member.AliasOrName(), member); - } - - private void PrepareImportedType(ImportTypeAttribute importedType) - { - var type = importedType.Type; - if (!type.IsPublic) throw new($"Cannot use {nameof(ImportTypeAttribute)} on non-public type {type.Name}"); - string ns = importedType.Namespace ?? type.Namespace ?? string.Empty; - ILazilyLoadMembers lazyLoader = ns == string.Empty - ? BodyLoader - : Loader.Namespace(ns); - lazyLoader.AddLazyMember(importedType.Alias ?? type.Name, type); - } - } -} diff --git a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.cs index 23218d93..654cd678 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.cs @@ -11,13 +11,17 @@ public TypeAsModule(Type il, ILLoader loader) { IL = il; Loader = loader; - BodyLoader = new(this, loader); + LazyLoader = new LazyMemberLoader() + { + Container = this, + Loader = new ModuleBodyLoader(loader) + }; if (il.GetCustomAttribute() is SetNamespaceAttribute setNamespace) RootNamespace = setNamespace.Name; else RootNamespace = string.Empty; - Prepare(); + Prepare.PrepareTypeAsModule(this, loader); } } } diff --git a/ZSharp.Importer.ILLoader/objects/namespace/Namespace.LazyLoad.cs b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.LazyLoad.cs index eaa833c8..04bcc851 100644 --- a/ZSharp.Importer.ILLoader/objects/namespace/Namespace.LazyLoad.cs +++ b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.LazyLoad.cs @@ -1,7 +1,7 @@ namespace ZSharp.Importer.ILLoader.Objects { partial class Namespace - : ILazilyLoadMembers + : ILazyMemberLoader { private readonly Dictionary lazyLoadedMembers = []; @@ -10,7 +10,7 @@ partial class Namespace public void AddLazyMember(MemberName member, IL.MemberInfo lazyLoadedMember) => lazyLoadedMembers.Add(member, lazyLoadedMember); - public CompilerObject? LoadMember(string name) + public CompilerObject? GetLazyMember(string name) { if (!lazyLoadedMembers.TryGetValue(name, out var member)) return null; diff --git a/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs index b5a215fe..aca6d1bf 100644 --- a/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs @@ -21,7 +21,7 @@ public void AddMember(string name, CompilerObject member) Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) { if (!Members.TryGetValue(member, out var result)) - if ((result = LoadMember(member)) is not null) + if ((result = GetLazyMember(member)) is not null) AddMember(member, result); else return Result.Error( $"Could not find member {member} in namespace {FullName}" diff --git a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.LazyLoad.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.LazyLoad.cs new file mode 100644 index 00000000..2283a28e --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.LazyLoad.cs @@ -0,0 +1,7 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Class + { + public ILazyMemberLoader LazyLoader { get; } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Member.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Member.cs new file mode 100644 index 00000000..b14caddc --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Member.cs @@ -0,0 +1,49 @@ +using CommonZ.Utils; +using ZSharp.Compiler; + +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Class + : IAddMember + , ICTGetMember + , IRTGetMember + { + public Mapping Members { get; } = []; + + CompilerObject IAddMember.AddMember(string name, CompilerObject member) + { + var result = OnAddResult.None; + if (member is IOnAddTo onAdd) + result = onAdd.OnAddTo(this); + + if (result == OnAddResult.None) + Members.Add(name, member); + + return member; + } + + Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName name) + { + if (!Members.TryGetValue(name, out var member) && !LazyLoader.GetLazyMember(name, out member)) + return Result.Error( + $"Could not find member {name} in type {IL.Name}" + ); + + return Result.Ok(member); + } + + Result IRTGetMember.Member(Compiler.Compiler compiler, CompilerObject @object, MemberName name) + { + if ( + compiler.CG.Member(this, name) + .When(out var member) + .Error(out var error) + ) return Result.Error(error); + + if (member!.Is(out var bindable)) + return bindable.Bind(compiler, @object); + + return Result.Ok(member); + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Type.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Type.cs new file mode 100644 index 00000000..ce639b17 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Type.cs @@ -0,0 +1,10 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Class + : IReferenceType + , IILType + { + Type IILType.GetILType() + => IL; + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.cs index b3fc5835..920ef3fd 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.cs @@ -1,12 +1,20 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed partial class Class + internal sealed partial class Class : CompilerObject { public Class(Type il, ILLoader loader) { IL = il; Loader = loader; + + LazyLoader = new LazyMemberLoader() + { + Container = this, + Loader = new TypeBodyLoader(loader) + }; + + Prepare.PrepareType(this, loader); } } } diff --git a/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.cs b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.cs index 62e1e48f..9093fe47 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.cs @@ -3,5 +3,9 @@ public sealed partial class Constructor : CompilerObject { + public Constructor(IL.ConstructorInfo il, ILLoader loader) + { + IL = il; + } } } diff --git a/ZSharp.Importer.ILLoader/objects/oop/field/Field.cs b/ZSharp.Importer.ILLoader/objects/oop/field/Field.cs index 8917ea76..8848b892 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/field/Field.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/field/Field.cs @@ -3,5 +3,9 @@ public sealed partial class Field : CompilerObject { + public Field(IL.FieldInfo il, ILLoader loader) + { + + } } } diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Bind.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Bind.cs new file mode 100644 index 00000000..66569cb4 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Bind.cs @@ -0,0 +1,22 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Method + : IBindable + { + Result IBindable.Bind(Compiler.Compiler compiler, CompilerObject target) + { + if (IL.IsStatic) return Result.Ok(this); + + if (!compiler.TS.IsTyped(target, out var targetType)) + return Result.Error( + $"Cannot bind method {IL.Name} to untyped object {target}" + ); + + return Result.Ok(new BoundMethod() + { + Method = this, + Object = target + }); + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs index 42b5cfd0..458d66a1 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs @@ -32,7 +32,7 @@ Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) result.Instructions.Add(new IR.VM.Call(GetIR())); result.Types.Add(GetIR().ReturnType); - return Result.Ok(new RawIRCode(result)); + return Result.Ok(RawIRCode.From(result.Instructions, ReturnType)); } } } diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Signature.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Signature.cs index 04e0c2d4..fb05d4bc 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Signature.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Signature.cs @@ -5,5 +5,7 @@ partial class Method private readonly Signature signature = new(); public CompilerObject Signature => signature; + + public CompilerObject ReturnType { get; } } } diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.cs index f7811256..0c03afbd 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.cs @@ -8,6 +8,8 @@ public Method(IL.MethodInfo il, ILLoader loader) IL = il; Loader = loader; + ReturnType = loader.LoadType(IL.ReturnType); + if (!IL.IsStatic) signature.parameters.Add(new ThisParameter(IL, loader)); diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.IL.cs b/ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.IL.cs similarity index 100% rename from ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.IL.cs rename to ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.IL.cs diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.cs b/ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.cs similarity index 100% rename from ZSharp.Importer.ILLoader/objects/oop/method/this parameter/ThisParameter.cs rename to ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.cs diff --git a/ZSharp.Importer.ILLoader/semantics/IReferenceType.cs b/ZSharp.Importer.ILLoader/semantics/IReferenceType.cs new file mode 100644 index 00000000..81ed3a51 --- /dev/null +++ b/ZSharp.Importer.ILLoader/semantics/IReferenceType.cs @@ -0,0 +1,28 @@ +using ZSharp.Compiler; + +namespace ZSharp.Importer.ILLoader +{ + internal interface IReferenceType + : IILType + , IRTImplicitCastTo + { + Result IRTImplicitCastTo.ImplicitCast(Compiler.Compiler compiler, CompilerObject @object, CompilerObject type) + { + var thisIL = GetILType(); + + if (!type.Is(out var ilTypeProvider)) + return Result.Error( + $"Cannot implicitly cast type {thisIL.Name} to non-IL type {type}" + ); + + var thatIL = ilTypeProvider.GetILType(); + + if (!thisIL.IsAssignableTo(thatIL)) + return Result.Error( + $"Cannot implicitly cast type {thisIL.Name} to incompatible type {thatIL.Name}" + ); + + return Result.Ok(@object); + } + } +} From 4f5e324b1ccdf51ab7fcbd64299f171db4da2b42 Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sat, 18 Oct 2025 21:25:14 +0300 Subject: [PATCH 233/235] Update test file --- Examples/test.zs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Examples/test.zs b/Examples/test.zs index 26eb38d7..603d4e43 100644 --- a/Examples/test.zs +++ b/Examples/test.zs @@ -11,6 +11,8 @@ module A { print("[CT] Inside module A"); fun main(): Void { + print(Directory.cwd().toString()); + print("[RT] Hello, World!"); return; } From ffe60c5a74e11162d0542d3bae43a83d372c6fdb Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 19 Oct 2025 00:07:40 +0300 Subject: [PATCH 234/235] Make string and object wrappers use the proper semantic type Which means that they will behave properly just like non-core classes. --- .../ZSharp.Importer.ILLoader.csproj | 1 + ZSharp.Importer.ILLoader/il loader/ILLoader.cs | 2 +- .../modular/function/concrete/Function.Call.cs | 15 +++++++++++---- .../modular/function/concrete/Function.IL.cs | 4 ++-- .../modular/function/concrete/Function.IR.cs | 6 +++--- .../function/concrete/Function.Signature.cs | 11 +++++++++++ .../modular/function/concrete/Function.cs | 12 +++++++++++- .../objects/types/object/ObjectType.cs | 4 ++++ .../objects/types/string/StringType.cs | 18 +++++------------- 9 files changed, 49 insertions(+), 24 deletions(-) create mode 100644 ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Signature.cs diff --git a/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj b/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj index 5eea8633..64381719 100644 --- a/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj +++ b/ZSharp.Importer.ILLoader/ZSharp.Importer.ILLoader.csproj @@ -14,6 +14,7 @@ + diff --git a/ZSharp.Importer.ILLoader/il loader/ILLoader.cs b/ZSharp.Importer.ILLoader/il loader/ILLoader.cs index c2f28454..20e9caa3 100644 --- a/ZSharp.Importer.ILLoader/il loader/ILLoader.cs +++ b/ZSharp.Importer.ILLoader/il loader/ILLoader.cs @@ -24,7 +24,7 @@ public ILLoader(Compiler.Compiler compiler, Platform.Runtime.Runtime runtime) SInt32 = new Objects.SInt32Type(Runtime.TypeSystem.SInt32), SInt64 = new Objects.SInt64Type(Runtime.TypeSystem.SInt64), SIntNative = new Objects.SIntNativeType(Runtime.TypeSystem.SIntNative), - String = new Objects.StringType(Runtime.TypeSystem.String, this), + String = new Objects.StringType(Runtime.TypeSystem.String), UInt8 = new Objects.UInt8Type(Runtime.TypeSystem.UInt8), UInt16 = new Objects.UInt16Type(Runtime.TypeSystem.UInt16), UInt32 = new Objects.UInt32Type(Runtime.TypeSystem.UInt32), diff --git a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs index 05b9ba2d..0b02242e 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs @@ -1,4 +1,5 @@ using ZSharp.Compiler; +using ZSharp.Compiler.Features.Callable; namespace ZSharp.Importer.ILLoader.Objects { @@ -7,14 +8,20 @@ partial class Function { Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { + if ( + BoundSignature.Create(compiler, signature, new ArgumentStream(arguments)) + .When(out var boundSignature) + .Error(out var error) + ) return Result.Error(error); + IRCode result = new(); - foreach (var argument in arguments) + foreach (var boundParameter in boundSignature!.Parameters) { if ( - compiler.IR.CompileCode(argument.Object, null) + compiler.IR.CompileCode(boundParameter.ArgumentObject, null) .When(out var argumentCode) - .Error(out var error) + .Error(out error) ) return Result.Error(error); @@ -24,7 +31,7 @@ Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) result.Instructions.Add(new IR.VM.Call(GetIR())); result.Types.Add(GetIR().ReturnType); - return Result.Ok(new RawIRCode(result)); + return Result.Ok(RawIRCode.From(result.Instructions, ReturnType)); } } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IL.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IL.cs index 81a95d51..c7437dde 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IL.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IL.cs @@ -2,8 +2,8 @@ { partial class Function { - private readonly ILLoader loader = loader; + public ILLoader Loader { get; } - public IL.MethodInfo IL { get; } = il; + public IL.MethodInfo IL { get; } } } diff --git a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IR.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IR.cs index 134ee9cb..63a203f4 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IR.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.IR.cs @@ -8,11 +8,11 @@ private IR.Function GetIR() { if (IR is null) { - var returnTypeCO = loader.LoadType(IL.ReturnType); - if (loader.IR.CompileType(returnTypeCO).When(out var returnTypeIR).Error(out var error)) + var returnTypeCO = Loader.LoadType(IL.ReturnType); + if (Loader.IR.CompileType(returnTypeCO).When(out var returnTypeIR).Error(out var error)) throw new InvalidOperationException($"Failed to load return type for method {IL.Name}: {error}"); IR = new(returnTypeIR!); - loader.RequireRuntime().AddFunction(IR, IL); + Loader.RequireRuntime().AddFunction(IR, IL); } return IR; diff --git a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Signature.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Signature.cs new file mode 100644 index 00000000..67f29537 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Signature.cs @@ -0,0 +1,11 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Function + { + private readonly Signature signature = new(); + + public CompilerObject Signature => signature; + + public CompilerObject ReturnType { get; } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.cs index ac8ba5e6..ea430d70 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.cs @@ -1,7 +1,17 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed partial class Function(IL.MethodInfo il, ILLoader loader) + public sealed partial class Function : CompilerObject { + public Function(IL.MethodInfo il, ILLoader loader) + { + IL = il; + Loader = loader; + + ReturnType = loader.LoadType(IL.ReturnType); + + foreach (var parameter in IL.GetParameters()) + signature.parameters.Add(new Parameter(parameter, loader)); + } } } diff --git a/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs b/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs index 8e528872..24fde6b1 100644 --- a/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs @@ -6,10 +6,14 @@ namespace ZSharp.Importer.ILLoader.Objects public sealed class ObjectType(TypeReference type) : CompilerObject , ICompileIRType + , IILType { private readonly TypeReference type = type; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); + + Type IILType.GetILType() + => typeof(object); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs index d767141a..b3e5cace 100644 --- a/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs @@ -3,26 +3,18 @@ namespace ZSharp.Importer.ILLoader.Objects { - internal sealed class StringType(TypeReference type, ILLoader loader) + internal sealed class StringType(TypeReference type) : CompilerObject , ICompileIRType - , IRTImplicitCastTo + , IILType + , IReferenceType { private readonly TypeReference type = type; - private readonly ILLoader loader = loader; Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); - Result IRTImplicitCastTo.ImplicitCast(Compiler.Compiler compiler, CompilerObject @object, CompilerObject type) - { - if (compiler.Reflection.IsSameDefinition(this, type)) - return Result.Ok(@object); - - if (compiler.Reflection.IsSameDefinition(loader.TypeSystem.Object, type)) - return Result.Ok(@object); - - return Result.Error($"Cannot implicitly cast string to {type}."); - } + Type IILType.GetILType() + => typeof(string); } } From 5355c0d54b96c35b63bd888f28b74cbedee4b26d Mon Sep 17 00:00:00 2001 From: Binyamin Y Cohen Date: Sun, 19 Oct 2025 12:08:26 +0300 Subject: [PATCH 235/235] Add support for construcings instances from IL types Also add the letter 'I' throughout the entire codebase. Therefore, 'I' exists. That's quite a lot of changes just to be able to call a constructor. In reality, this entire commit allows variant type checking on results. Up until now, objects had to precisely define which capabilities they implement. Now they automatically, implicitly implement all variants of each capability, if they have any. --- CommonZ/IResult.cs | 32 + CommonZ/Result.cs | 52 +- CommonZ/extensions/IResultExtensions.cs | 70 ++ Examples/test.zs | 3 +- ZSharp v1.sln | 12 - ZSharp.CLI/StandardTypes.cs | 8 + ZSharp.Compiler.CG.Direct/GlobalUsings.cs | 1 + .../dispatcher/services/Dispatcher.Call.cs | 2 +- .../dispatcher/services/Dispatcher.Cast.cs | 2 +- .../services/Dispatcher.ImplicitCast.cs | 2 +- .../dispatcher/services/Dispatcher.Index.cs | 4 +- .../dispatcher/services/Dispatcher.Match.cs | 2 +- .../services/Dispatcher.MemberAccess.cs | 8 +- .../services/Dispatcher.ValueAccess.cs | 4 +- .../protocols/callable/ICTCallable.cs | 2 +- .../implicit casting/ICTImplicitCastFrom.cs | 2 +- .../implicit casting/ICTImplicitCastTo.cs | 2 +- .../protocols/index/ICTGetIndex.cs | 2 +- .../protocols/index/ICTSetIndex.cs | 2 +- .../protocols/member access/ICTGetMember.cs | 2 +- .../protocols/member access/ICTSetMember.cs | 2 +- .../protocols/type casting/ICTCastTo.cs | 2 +- .../protocols/type matching/ICTTypeMatch.cs | 2 +- .../protocols/value access/ICTGet.cs | 2 +- .../protocols/value access/ICTSet.cs | 2 +- ZSharp.Compiler.CG.Proxy/GlobalUsings.cs | 1 + .../dispatcher/services/Dispatcher.Call.cs | 2 +- .../dispatcher/services/Dispatcher.Cast.cs | 2 +- .../services/Dispatcher.ImplicitCast.cs | 2 +- .../dispatcher/services/Dispatcher.Index.cs | 4 +- .../dispatcher/services/Dispatcher.Match.cs | 2 +- .../services/Dispatcher.MemberAccess.cs | 8 +- .../services/Dispatcher.ValueAccess.cs | 4 +- ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs | 2 +- ZSharp.Compiler.CG.Typed/GlobalUsings.cs | 1 + .../dispatcher/services/Dispatcher.Call.cs | 2 +- .../dispatcher/services/Dispatcher.Cast.cs | 2 +- .../services/Dispatcher.ImplicitCast.cs | 2 +- .../dispatcher/services/Dispatcher.Index.cs | 4 +- .../dispatcher/services/Dispatcher.Match.cs | 2 +- .../services/Dispatcher.MemberAccess.cs | 8 +- .../services/Dispatcher.ValueAccess.cs | 4 +- .../extensions/CompilerExtensions.cs | 2 +- .../protocols/callable/IRTCallable.cs | 2 +- .../implicit casting/IRTImplicitCastTo.cs | 2 +- .../protocols/index/IRTGetIndex.cs | 2 +- .../protocols/index/IRTSetIndex.cs | 2 +- .../protocols/member access/IRTGetMember.cs | 2 +- .../protocols/member access/IRTSetMember.cs | 2 +- .../runtime/IHasRuntimeDescriptor.cs | 2 +- .../protocols/type casting/IRTCastFrom.cs | 2 +- .../protocols/type casting/IRTCastTo.cs | 2 +- .../protocols/type matching/IRTTypeMatch.cs | 2 +- .../protocols/value access/IRTGet.cs | 2 +- .../protocols/value access/IRTSet.cs | 2 +- ZSharp.Compiler.CG/GlobalUsings.cs | 1 + ZSharp.Compiler.CG/cg/services/CG.Call.cs | 2 +- ZSharp.Compiler.CG/cg/services/CG.Cast.cs | 2 +- .../cg/services/CG.ImplicitCast.cs | 2 +- ZSharp.Compiler.CG/cg/services/CG.Index.cs | 8 +- ZSharp.Compiler.CG/cg/services/CG.Match.cs | 2 +- .../cg/services/CG.MemberAccess.cs | 12 +- .../cg/services/CG.ValueAccess.cs | 4 +- .../dispatcher/Dispatcher.Call.cs | 2 +- .../dispatcher/Dispatcher.Cast.cs | 2 +- .../dispatcher/Dispatcher.ImplicitCast.cs | 2 +- .../dispatcher/Dispatcher.Index.cs | 4 +- .../dispatcher/Dispatcher.Match.cs | 2 +- .../dispatcher/Dispatcher.MemberAccess.cs | 8 +- .../dispatcher/Dispatcher.Runtime.cs | 2 +- .../dispatcher/Dispatcher.ValueAccess.cs | 4 +- ZSharp.Compiler.Context/GlobalUsings.cs | 1 + .../capabilities/scoping/ILookupContext.cs | 2 +- .../capabilities/scoping/IScopeContext.cs | 4 +- .../capabilities/storage/IStorageContext.cs | 2 +- ZSharp.Compiler.Core/result/Result.cs | 64 +- .../GlobalUsings.cs | 1 + .../services/Dispatcher.Evaluate.cs | 2 +- .../protocols/evaluate/ICTEvaluate.cs | 2 +- ZSharp.Compiler.Evaluation.IR/GlobalUsings.cs | 1 + .../services/Dispatcher.Evaluate.cs | 2 +- ZSharp.Compiler.Evaluation/GlobalUsings.cs | 1 + .../dispatcher/Dispatcher.Evaluate.cs | 2 +- .../evaluator/services/Evaluator.Evaluate.cs | 2 +- ZSharp.Compiler.Features/GlobalUsings.cs | 1 + .../callable/BoundSignature.cs | 2 +- .../callable/IParameter.cs | 2 +- ZSharp.Compiler.IR.Static/GlobalUsings.cs | 2 + .../dispatcher/services/Dispatcher.Code.cs | 2 +- .../services/Dispatcher.Definition.cs | 2 +- .../services/Dispatcher.Reference.cs | 2 +- .../dispatcher/services/Dispatcher.Type.cs | 4 +- .../objects/RawIRCode.cs | 2 +- .../objects/UntypedIRCode.cs | 2 +- .../protocols/ICompileIRCode.cs | 2 +- .../protocols/ICompileIRDefinitionAs.cs | 2 +- .../protocols/ICompileIRReference.cs | 4 +- .../protocols/ICompileIRType.cs | 8 +- ZSharp.Compiler.IR/GlobalUsings.cs | 1 + .../dispatcher/services/Dispatcher.Code.cs | 2 +- .../services/Dispatcher.Definition.cs | 2 +- .../services/Dispatcher.Reference.cs | 2 +- .../dispatcher/services/Dispatcher.Type.cs | 4 +- ZSharp.Compiler.IR/ir/services/IR.Code.cs | 2 +- .../ir/services/IR.Definition.cs | 2 +- .../ir/services/IR.Reference.cs | 2 +- ZSharp.Compiler.IR/ir/services/IR.Type.cs | 4 +- .../protocols/IIRDefinitionAsCompiler.cs | 2 +- .../protocols/IIRReferenceCompiler.cs | 2 +- .../protocols/IIRTypeCompiler.cs | 2 +- ZSharp.Compiler.Objects/GlobalUsings.cs | 5 - .../ZSharp.Compiler.Objects.csproj | 15 - .../callables/ArgumentMismatchException.cs | 12 - .../type inference/SimpleInferenceContext.cs | 16 - .../core/IInferredTypeResolver.cs | 9 - .../core/ITypeInferenceContext.cs | 19 - .../type inference/core/InferredType.cs | 43 -- .../resolvers/CommonBaseType.cs | 52 -- .../error messages/Errors.Compilation.cs | 11 - .../error messages/Errors.cs | 7 - .../functional/CTFunction.cs | 7 - .../functional/Function.cs | 22 - .../functional/RTFunction.cs | 140 ---- .../functional/body/Local.cs | 97 --- .../generic/GenericFunctionInstance_Old.cs | 97 --- .../definition/GenericFunction.Generic.cs | 40 -- .../generic/definition/GenericFunction.cs | 167 ----- .../instance/GenericFunctionInstance.Call.cs | 50 -- .../GenericFunctionInstance.Generic.cs | 12 - .../instance/GenericFunctionInstance.IR.cs | 27 - .../GenericFunctionInstance.Signature.cs | 11 - .../instance/GenericFunctionInstance.cs | 7 - .../functional/partial call/PartialCall.cs | 119 ---- .../functional/signature/Parameter.cs | 64 -- .../functional/signature/Signature.cs | 84 --- .../functional/signature/VarParameter.cs | 20 - .../generic/GenericArgument.cs | 17 - .../generic/GenericParameter.cs | 24 - .../literals/ArrayLiteral.cs | 45 -- ZSharp.Compiler.Objects/modular/Global.cs | 113 ---- ZSharp.Compiler.Objects/modular/Module.cs | 69 -- ZSharp.Compiler.Objects/nullable/Nullable.cs | 104 --- ZSharp.Compiler.Objects/oop/Implementation.cs | 16 - .../oop/abstraction/IAbstraction.cs | 10 - ZSharp.Compiler.Objects/oop/class/Class.cs | 268 -------- .../oop/class/GenericClass.cs | 174 ----- .../oop/class/GenericClassInstance.cs | 150 ----- .../oop/constructor/Constructor.cs | 157 ----- .../oop/constructor/ConstructorReference.cs | 43 -- ZSharp.Compiler.Objects/oop/enum/EnumClass.cs | 107 --- ZSharp.Compiler.Objects/oop/enum/EnumValue.cs | 72 -- .../extensibility/IDerivableAbstraction.cs | 9 - .../oop/extensibility/IImplementation.cs | 10 - .../extensibility/IImplementsAbstraction.cs | 33 - .../extensibility/IImplementsSpecification.cs | 8 - .../oop/field/BoundField.cs | 54 -- ZSharp.Compiler.Objects/oop/field/Field.cs | 46 -- .../oop/interface/Interface.cs | 103 --- .../oop/meta/ClassMetaClass.cs | 39 -- ZSharp.Compiler.Objects/oop/meta/ClassSpec.cs | 12 - .../oop/meta/ClassSpecBuilder.cs | 20 - ZSharp.Compiler.Objects/oop/method/IMethod.cs | 8 - .../oop/method/MethodType.cs | 22 - .../oop/method/concrete/BoundMethod.cs | 16 - .../oop/method/concrete/Method.cs | 240 ------- .../oop/method/concrete/MethodReference.cs | 99 --- .../oop/method/generic/BoundGenericMethod.cs | 42 -- .../generic/BoundGenericMethodInstance.cs | 16 - .../generic/BoundGenericMethodReference.cs | 16 - .../oop/method/generic/GenericMethod.cs | 189 ------ .../method/generic/GenericMethodInstance.cs | 73 --- .../generic/GenericMethodInstanceReference.cs | 6 - .../method/generic/GenericMethodReference.cs | 128 ---- .../method/group/BoundMethodOverloadGroup.cs | 19 - .../oop/method/group/MethodOverloadGroup.cs | 30 - .../oop/value type/ValueType.cs | 54 -- .../overloading/OverloadGroup.cs | 54 -- .../exceptions/AmbiguousOverloadException.cs | 14 - .../exceptions/NoOverloadFoundException.cs | 9 - .../exceptions/OverloadException.cs | 10 - .../signature/abstract/ISignature_NEW.cs | 7 - .../signature/abstract_old/ICallableType.cs | 118 ---- .../signature/abstract_old/IParameter.cs | 15 - .../signature/abstract_old/ISignature.cs | 196 ------ .../signature/abstract_old/IVarParameter.cs | 13 - .../ArgumentsCountMismatchException.cs | 11 - .../signature/stub/StubParameter.cs | 46 -- .../signature/stub/StubSignature.cs | 56 -- .../signature/stub/StubVarParameter.cs | 30 - .../typing/TypedUndefined.cs | 11 - .../utils/ObjectBuildState.cs | 28 - .../utils/RuntimeHelpers.cs | 10 - ZSharp.Compiler.Overloading/GlobalUsings.cs | 1 + .../dispatcher/Dispatcher.T.cs | 2 +- .../overloading/services/Overloading.T.cs | 2 +- ZSharp.Compiler.Reflection/GlobalUsings.cs | 1 + ZSharp.Compiler.TS.Static/GlobalUsings.cs | 1 + .../dispatcher/Dispatcher.TypeOf.cs | 2 +- ZSharp.Compiler.TS/GlobalUsings.cs | 1 + ZSharp.Compiler.TS/dispatcher/Dispatcher.T.cs | 2 +- .../dispatcher/services/Dispatcher.TypeOf.cs | 2 +- ZSharp.Compiler.TS/ts/services/TS.TypeOf.cs | 2 +- ZSharp.Compiler/GlobalUsings.cs | 1 + ZSharp.Importer.ILLoader/GlobalUsings.cs | 1 + .../capabilities/internal/IBindable.cs | 2 +- .../capabilities/on add/IOnAddTo.cs | 4 +- ZSharp.Importer.ILLoader/helpers/Prepare.cs | 5 + .../argument stream/ArgumentStream.cs | 5 +- .../objects/callable/parameter/Parameter.cs | 2 +- .../function/concrete/Function.Call.cs | 2 +- .../objects/modular/global/Global.CG.Get.cs | 2 +- .../objects/modular/global/Global.IR.cs | 2 +- .../objects/modular/module/Module.Member.cs | 2 +- .../type as module/TypeAsModule.Member.cs | 2 +- .../objects/namespace/Namespace.Member.cs | 2 +- .../objects/oop/class/concrete/Class.Call.cs | 16 + .../oop/class/concrete/Class.Constructor.cs | 29 + .../objects/oop/class/concrete/Class.IR.cs | 8 +- .../oop/class/concrete/Class.Member.cs | 4 +- .../oop/constructor/Constructor.Call.cs | 66 ++ .../objects/oop/constructor/Constructor.IL.cs | 9 + .../objects/oop/constructor/Constructor.IR.cs | 24 + .../oop/constructor/Constructor.Owner.cs | 17 + .../oop/constructor/Constructor.Signature.cs | 9 + .../objects/oop/constructor/Constructor.cs | 10 +- .../oop/interface/concrete/Interface.IR.cs | 4 +- .../oop/method/bound/BoundMethod.Call.cs | 2 +- .../oop/method/concrete/Method.Bind.cs | 2 +- .../oop/method/concrete/Method.Call.cs | 2 +- .../oop/this parameter/ThisParameter.IL.cs | 2 +- .../oop/this parameter/ThisParameter.cs | 4 +- .../objects/types/boolean/BooleanType.cs | 2 +- .../objects/types/char/CharType.cs | 2 +- .../objects/types/float/Float128Type.cs | 2 +- .../objects/types/float/Float16Type.cs | 2 +- .../objects/types/float/Float32Type.cs | 2 +- .../objects/types/float/Float64Type.cs | 2 +- .../objects/types/int/SInt16Type.cs | 2 +- .../objects/types/int/SInt32Type.cs | 2 +- .../objects/types/int/SInt64Type.cs | 2 +- .../objects/types/int/SInt8Type.cs | 2 +- .../objects/types/int/SIntNativeType.cs | 2 +- .../objects/types/int/UInt16Type.cs | 2 +- .../objects/types/int/UInt32Type.cs | 2 +- .../objects/types/int/UInt64Type.cs | 2 +- .../objects/types/int/UInt8Type.cs | 2 +- .../objects/types/int/UIntNativeType.cs | 2 +- .../objects/types/object/ObjectType.cs | 2 +- .../objects/types/string/StringType.cs | 2 +- .../objects/types/void/VoidType.cs | 2 +- .../semantics/IReferenceType.cs | 2 +- ZSharp.Importer.IRLoader/Context.cs | 11 - ZSharp.Importer.IRLoader/GlobalUsings.cs | 3 - .../ZSharp.Importer.IRLoader.csproj | 14 - .../ir loader/IRLoader.API.cs | 7 - .../ir loader/IRLoader.Impl.cs | 617 ------------------ .../ir loader/IRLoader.cs | 27 - ZSharp.Importer.RT/GlobalUsings.cs | 1 + .../objects/string/StringLiteral.IR.cs | 2 +- ZSharp.Importer.RT/rt loader/Loader.Load.cs | 6 +- .../interpreter/Interpreter.Evaluate.cs | 2 +- .../CompileExpression.cs | 2 +- ZSharp.SourceCompiler.Common/GlobalUsings.cs | 1 + .../ExpressionCompiler.Compile.cs | 4 +- .../ExpressionCompiler.Compile.Binary.cs | 2 +- .../ExpressionCompiler.Compile.Call.cs | 8 +- .../ExpressionCompiler.Compile.Identifier.cs | 2 +- .../ExpressionCompiler.Compile.Literal.cs | 2 +- .../importers/CoreLibraryImporter.cs | 2 +- .../importers/StandardLibraryImporter.cs | 2 +- .../LiteralCompiler.Compile.Boolean.cs | 4 +- .../LiteralCompiler.Compile.String.cs | 2 +- .../LiteralCompiler.Compile.cs | 4 +- .../objects/code/block/CodeBlock.IR.cs | 2 +- .../objects/code/return/Return.IR.cs | 2 +- .../literals/bool/BooleanLiteral.IR.cs | 2 +- .../literals/string/StringLiteral.IR.cs | 2 +- .../TopLevelExpressionCompiler.cs | 6 +- ZSharp.SourceCompiler.Core/GlobalUsings.cs | 3 + .../string importer/IStringImporter.cs | 7 +- .../string importer/StringImporter.cs | 3 +- ZSharp.SourceCompiler.Module/GlobalUsings.cs | 1 + .../class compiler/compile/Compile.cs | 4 +- .../class compiler/compile/expr/Call.cs | 6 +- .../class compiler/compile/expr/Expression.cs | 2 +- .../class compiler/compile/expr/Function.cs | 2 +- .../class compiler/compile/stmt/Definition.cs | 2 +- .../class compiler/compile/stmt/Expression.cs | 2 +- .../compile/FunctionBodyCompiler.Compile.cs | 2 +- .../FunctionBodyCompiler.Compile.Function.cs | 2 +- .../expr/FunctionBodyCompiler.Compile.cs | 2 +- .../FunctionBodyCompiler.Compile.Block.cs | 2 +- ...FunctionBodyCompiler.Compile.Definition.cs | 2 +- ...FunctionBodyCompiler.Compile.Expression.cs | 2 +- .../stmt/FunctionBodyCompiler.Compile.cs | 2 +- .../stmt/FunctionBodyCompiler.Return.cs | 2 +- .../FunctionCompiler.Compile.cs | 4 +- .../compile/ModuleCompiler.Compile.cs | 4 +- .../def/ModuleCompiler.Compile.Function.cs | 2 +- .../expr/ModuleCompiler.Compile.Call.cs | 6 +- .../expr/ModuleCompiler.Compile.Expression.cs | 2 +- .../stmt/ModuleCompiler.Compile.Definition.cs | 2 +- .../stmt/ModuleCompiler.Compile.Expression.cs | 2 +- .../forward reference/ForwardReference.cs | 2 +- .../objects/modular/function/Function.Call.cs | 2 +- .../objects/modular/function/Function.IR.cs | 4 +- .../objects/modular/global/Global.IR.cs | 2 +- .../objects/modular/module/Module.IR.cs | 2 +- .../objects/modular/module/Module.Member.cs | 4 +- ZSharp.SourceCompiler.Script/GlobalUsings.cs | 1 + .../def/ScriptCompiler.Compile.Module.cs | 2 +- .../expr/ScriptCompiler.Compile.Call.cs | 6 +- .../expr/ScriptCompiler.Compile.Expression.cs | 12 +- .../expr/ScriptCompiler.Compile.Identifier.cs | 2 +- .../expr/ScriptCompiler.Compile.Literal.cs | 2 +- .../stmt/ScriptCompiler.Compile.Import.cs | 14 +- .../contexts/ScopeContext.cs | 6 +- 317 files changed, 627 insertions(+), 5492 deletions(-) create mode 100644 CommonZ/IResult.cs create mode 100644 CommonZ/extensions/IResultExtensions.cs delete mode 100644 ZSharp.Compiler.Objects/GlobalUsings.cs delete mode 100644 ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj delete mode 100644 ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs delete mode 100644 ZSharp.Compiler.Objects/contexts/type inference/SimpleInferenceContext.cs delete mode 100644 ZSharp.Compiler.Objects/contexts/type inference/core/IInferredTypeResolver.cs delete mode 100644 ZSharp.Compiler.Objects/contexts/type inference/core/ITypeInferenceContext.cs delete mode 100644 ZSharp.Compiler.Objects/contexts/type inference/core/InferredType.cs delete mode 100644 ZSharp.Compiler.Objects/contexts/type inference/resolvers/CommonBaseType.cs delete mode 100644 ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs delete mode 100644 ZSharp.Compiler.Objects/error messages/Errors.cs delete mode 100644 ZSharp.Compiler.Objects/functional/CTFunction.cs delete mode 100644 ZSharp.Compiler.Objects/functional/Function.cs delete mode 100644 ZSharp.Compiler.Objects/functional/RTFunction.cs delete mode 100644 ZSharp.Compiler.Objects/functional/body/Local.cs delete mode 100644 ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs delete mode 100644 ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs delete mode 100644 ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs delete mode 100644 ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs delete mode 100644 ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Generic.cs delete mode 100644 ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs delete mode 100644 ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Signature.cs delete mode 100644 ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.cs delete mode 100644 ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs delete mode 100644 ZSharp.Compiler.Objects/functional/signature/Parameter.cs delete mode 100644 ZSharp.Compiler.Objects/functional/signature/Signature.cs delete mode 100644 ZSharp.Compiler.Objects/functional/signature/VarParameter.cs delete mode 100644 ZSharp.Compiler.Objects/generic/GenericArgument.cs delete mode 100644 ZSharp.Compiler.Objects/generic/GenericParameter.cs delete mode 100644 ZSharp.Compiler.Objects/literals/ArrayLiteral.cs delete mode 100644 ZSharp.Compiler.Objects/modular/Global.cs delete mode 100644 ZSharp.Compiler.Objects/modular/Module.cs delete mode 100644 ZSharp.Compiler.Objects/nullable/Nullable.cs delete mode 100644 ZSharp.Compiler.Objects/oop/Implementation.cs delete mode 100644 ZSharp.Compiler.Objects/oop/abstraction/IAbstraction.cs delete mode 100644 ZSharp.Compiler.Objects/oop/class/Class.cs delete mode 100644 ZSharp.Compiler.Objects/oop/class/GenericClass.cs delete mode 100644 ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs delete mode 100644 ZSharp.Compiler.Objects/oop/constructor/Constructor.cs delete mode 100644 ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs delete mode 100644 ZSharp.Compiler.Objects/oop/enum/EnumClass.cs delete mode 100644 ZSharp.Compiler.Objects/oop/enum/EnumValue.cs delete mode 100644 ZSharp.Compiler.Objects/oop/extensibility/IDerivableAbstraction.cs delete mode 100644 ZSharp.Compiler.Objects/oop/extensibility/IImplementation.cs delete mode 100644 ZSharp.Compiler.Objects/oop/extensibility/IImplementsAbstraction.cs delete mode 100644 ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs delete mode 100644 ZSharp.Compiler.Objects/oop/field/BoundField.cs delete mode 100644 ZSharp.Compiler.Objects/oop/field/Field.cs delete mode 100644 ZSharp.Compiler.Objects/oop/interface/Interface.cs delete mode 100644 ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs delete mode 100644 ZSharp.Compiler.Objects/oop/meta/ClassSpec.cs delete mode 100644 ZSharp.Compiler.Objects/oop/meta/ClassSpecBuilder.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/IMethod.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/MethodType.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/concrete/BoundMethod.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/concrete/Method.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstanceReference.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs delete mode 100644 ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs delete mode 100644 ZSharp.Compiler.Objects/oop/value type/ValueType.cs delete mode 100644 ZSharp.Compiler.Objects/overloading/OverloadGroup.cs delete mode 100644 ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs delete mode 100644 ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs delete mode 100644 ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs delete mode 100644 ZSharp.Compiler.Objects/signature/abstract/ISignature_NEW.cs delete mode 100644 ZSharp.Compiler.Objects/signature/abstract_old/ICallableType.cs delete mode 100644 ZSharp.Compiler.Objects/signature/abstract_old/IParameter.cs delete mode 100644 ZSharp.Compiler.Objects/signature/abstract_old/ISignature.cs delete mode 100644 ZSharp.Compiler.Objects/signature/abstract_old/IVarParameter.cs delete mode 100644 ZSharp.Compiler.Objects/signature/exceptions/ArgumentsCountMismatchException.cs delete mode 100644 ZSharp.Compiler.Objects/signature/stub/StubParameter.cs delete mode 100644 ZSharp.Compiler.Objects/signature/stub/StubSignature.cs delete mode 100644 ZSharp.Compiler.Objects/signature/stub/StubVarParameter.cs delete mode 100644 ZSharp.Compiler.Objects/typing/TypedUndefined.cs delete mode 100644 ZSharp.Compiler.Objects/utils/ObjectBuildState.cs delete mode 100644 ZSharp.Compiler.Objects/utils/RuntimeHelpers.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Call.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Constructor.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Call.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.IL.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.IR.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Owner.cs create mode 100644 ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Signature.cs delete mode 100644 ZSharp.Importer.IRLoader/Context.cs delete mode 100644 ZSharp.Importer.IRLoader/GlobalUsings.cs delete mode 100644 ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj delete mode 100644 ZSharp.Importer.IRLoader/ir loader/IRLoader.API.cs delete mode 100644 ZSharp.Importer.IRLoader/ir loader/IRLoader.Impl.cs delete mode 100644 ZSharp.Importer.IRLoader/ir loader/IRLoader.cs create mode 100644 ZSharp.SourceCompiler.Core/GlobalUsings.cs diff --git a/CommonZ/IResult.cs b/CommonZ/IResult.cs new file mode 100644 index 00000000..b76bb0e6 --- /dev/null +++ b/CommonZ/IResult.cs @@ -0,0 +1,32 @@ +public interface IResult + where TResult : class? + where TError : class +{ + public bool IsOk { get; } + + public bool IsError { get; } + + public TResult Unwrap(); + + public TError UnwrapError(); + + public IResult When(Action action) + { + if (this.Ok(out var result)) + action(result); + + return this; + } + + public IResult When(Func map) where R : class; + + public IResult Else(Action action) + { + if (this.Error(out var error)) + action(error); + + return this; + } + + public IResult Else(Func map) where E : class; +} \ No newline at end of file diff --git a/CommonZ/Result.cs b/CommonZ/Result.cs index 5abb5651..6bbe56ad 100644 --- a/CommonZ/Result.cs +++ b/CommonZ/Result.cs @@ -2,12 +2,13 @@ namespace CommonZ { - public class Result + public sealed class Result + : IResult where TResult : class? where TError : class { - protected readonly TResult? result; - protected readonly TError? error; + private readonly TResult? result; + private readonly TError? error; [MemberNotNullWhen(true, nameof(result))] public bool IsOk => result is not null; @@ -15,7 +16,7 @@ public class Result [MemberNotNullWhen(true, nameof(error))] public bool IsError => error is not null; - protected Result(TResult? result, TError? error) + private Result(TResult? result, TError? error) { this.result = result; this.error = error; @@ -27,53 +28,20 @@ public static Result Ok(TResult result) public static Result Error(TError error) => new(null, error); - public bool Ok([NotNullWhen(true)] out TResult? result) - => (result = this.result) is not null; - - public bool Error([NotNullWhen(true)] out TError? error) - => (error = this.error) is not null; - - public TResult Unwrap() + TResult IResult.Unwrap() => result ?? throw new InvalidOperationException(error!.ToString()); - public Result When(Action action) - { - if (IsOk) - action(result); - - return this; - } + TError IResult.UnwrapError() + => error ?? throw new InvalidOperationException("Result is Ok"); - public Result When(Func map) - where R : class + IResult IResult.When(Func map) => IsOk ? Result.Ok(map(result)) : Result.Error(error!); - public Result When(out TResult? result) - { - result = this.result; - return this; - } - - public Result Else(Action action) - { - if (IsError) - action(error); - - return this; - } - - public Result Else(Func map) - where E : class + IResult IResult.Else(Func map) => IsOk ? Result.Ok(result) : Result.Error(map(error!)); - - public Result Else(out TError? error) - { - error = this.error; - return this; - } } } diff --git a/CommonZ/extensions/IResultExtensions.cs b/CommonZ/extensions/IResultExtensions.cs new file mode 100644 index 00000000..7e829d1a --- /dev/null +++ b/CommonZ/extensions/IResultExtensions.cs @@ -0,0 +1,70 @@ +using CommonZ; +using System.Diagnostics.CodeAnalysis; +using static System.Runtime.InteropServices.JavaScript.JSType; + +public static class IResultExtensions +{ + public static bool Ok( + this IResult result, + [NotNullWhen(true)] out TResult? output + ) + where TResult : class? + where TError : class + => (output = result.IsOk ? result.Unwrap() : null) is not null; + + public static bool Error( + this IResult result, + [NotNullWhen(true)] out TError? error + ) + where TResult : class? + where TError : class + => (error = result.IsError ? result.UnwrapError() : null) is not null; + + public static IResult When( + this IResult result, + out TResult? output + ) + where TResult : class? + where TError : class + { + output = result.IsOk ? result.Unwrap() : null; + return result; + } + + public static IResult Else( + this IResult result, + out TError? error + ) + where TResult : class? + where TError : class + { + error = result.IsError ? result.UnwrapError() : null; + return result; + } + + public static IResult When( + this IResult result, + Func> map + ) + where TResult : class? + where TError : class + where R : class + { + if (result.IsError) return result.When(_ => (null as R)!); + + return map(result.Unwrap()).Else(e => e); + } + + //public static IResult Else( + // this IResult result, + // Action action + //) + // where TResult : class? + // where TError : class + //{ + // if (result.IsError) + // action(result.UnwrapError()); + + // return result; + //} +} \ No newline at end of file diff --git a/Examples/test.zs b/Examples/test.zs index 603d4e43..76652afa 100644 --- a/Examples/test.zs +++ b/Examples/test.zs @@ -1,5 +1,5 @@ import { print } from "std:io"; -import { Void } from "std:types"; +import { Void, Test } from "std:types"; print("[CT] Hello, World!"); @@ -12,6 +12,7 @@ module A { fun main(): Void { print(Directory.cwd().toString()); + print(Test(Directory.cwd().toString())); print("[RT] Hello, World!"); return; diff --git a/ZSharp v1.sln b/ZSharp v1.sln index 5a7ac4e3..adb6d31b 100644 --- a/ZSharp v1.sln +++ b/ZSharp v1.sln @@ -19,12 +19,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZSharp.Parser", "ZSharp.Par EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Interpreter", "ZSharp.Interpreter\ZSharp.Interpreter.csproj", "{F46A91F5-47BA-468A-81F0-FF6BCEB4112C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Importer.IRLoader", "ZSharp.Importer.IRLoader\ZSharp.Importer.IRLoader.csproj", "{8E9A7EF0-EE8E-4481-BF60-C6BDBD5C7BB8}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Library.Standard.Math", "ZSharp.Library.Standard.Math\ZSharp.Library.Standard.Math.csproj", "{AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Objects", "ZSharp.Compiler.Objects\ZSharp.Compiler.Objects.csproj", "{6B3BEDB2-F3CB-400E-A257-D79F73075AF9}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZSharp.Compiler.Features", "ZSharp.Compiler.Features\ZSharp.Compiler.Features.csproj", "{E3DAA459-48D0-461E-A17E-453816D15090}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Testing", "Testing\Testing.csproj", "{8A5EB8BE-EDF3-444E-AC15-A3E9DEF1FC7F}" @@ -127,18 +123,10 @@ Global {F46A91F5-47BA-468A-81F0-FF6BCEB4112C}.Debug|Any CPU.Build.0 = Debug|Any CPU {F46A91F5-47BA-468A-81F0-FF6BCEB4112C}.Release|Any CPU.ActiveCfg = Release|Any CPU {F46A91F5-47BA-468A-81F0-FF6BCEB4112C}.Release|Any CPU.Build.0 = Release|Any CPU - {8E9A7EF0-EE8E-4481-BF60-C6BDBD5C7BB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8E9A7EF0-EE8E-4481-BF60-C6BDBD5C7BB8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8E9A7EF0-EE8E-4481-BF60-C6BDBD5C7BB8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8E9A7EF0-EE8E-4481-BF60-C6BDBD5C7BB8}.Release|Any CPU.Build.0 = Release|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Debug|Any CPU.Build.0 = Debug|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Release|Any CPU.ActiveCfg = Release|Any CPU {AF9E7F68-2AB3-42F7-AE29-5D7A1CE89DBA}.Release|Any CPU.Build.0 = Release|Any CPU - {6B3BEDB2-F3CB-400E-A257-D79F73075AF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6B3BEDB2-F3CB-400E-A257-D79F73075AF9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6B3BEDB2-F3CB-400E-A257-D79F73075AF9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6B3BEDB2-F3CB-400E-A257-D79F73075AF9}.Release|Any CPU.Build.0 = Release|Any CPU {E3DAA459-48D0-461E-A17E-453816D15090}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E3DAA459-48D0-461E-A17E-453816D15090}.Debug|Any CPU.Build.0 = Debug|Any CPU {E3DAA459-48D0-461E-A17E-453816D15090}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/ZSharp.CLI/StandardTypes.cs b/ZSharp.CLI/StandardTypes.cs index 238d2b28..ddb22eff 100644 --- a/ZSharp.CLI/StandardTypes.cs +++ b/ZSharp.CLI/StandardTypes.cs @@ -4,9 +4,17 @@ namespace ZSharp.CLI { [ModuleScope] + [ImportType(typeof(Test), Namespace = "")] public static class StandardTypes { [Alias("Void")] public static CompilerObject VoidType = null!; + + } + + public class Test(string s) + { + public override string ToString() + => $"Test: {s}"; } } diff --git a/ZSharp.Compiler.CG.Direct/GlobalUsings.cs b/ZSharp.Compiler.CG.Direct/GlobalUsings.cs index c1bcb323..3bfc54ae 100644 --- a/ZSharp.Compiler.CG.Direct/GlobalUsings.cs +++ b/ZSharp.Compiler.CG.Direct/GlobalUsings.cs @@ -2,3 +2,4 @@ global using MemberIndex = int; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Call.cs index 68633097..0f955521 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Call.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Call.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Call(CompilerObject callee, Argument[] arguments) + public IResult Call(CompilerObject callee, Argument[] arguments) { var result = @base.Call(callee, arguments); diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Cast.cs index 7a417649..1378bbd0 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Cast.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Cast.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Cast(CompilerObject @object, CompilerObject type) + public IResult Cast(CompilerObject @object, CompilerObject type) { var result = @base.Cast(@object, type); diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ImplicitCast.cs index 1ba4a3bc..0ee7d1c0 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ImplicitCast.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result ImplicitCast(CompilerObject @object, CompilerObject type) + public IResult ImplicitCast(CompilerObject @object, CompilerObject type) { var result = @base.ImplicitCast(@object, type); diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Index.cs index d056f692..7064c39a 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Index.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Index.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Index(CompilerObject @object, Argument[] arguments) + public IResult Index(CompilerObject @object, Argument[] arguments) { var result = @base.GetIndex(@object, arguments); @@ -12,7 +12,7 @@ public Result Index(CompilerObject @object, Argument[] arguments) return result; } - public Result Index(CompilerObject @object, Argument[] arguments, CompilerObject value) + public IResult Index(CompilerObject @object, Argument[] arguments, CompilerObject value) { var result = @base.GetIndex(@object, arguments); diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Match.cs index 650f8535..3f3d2d6a 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Match.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.Match.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Match(CompilerObject @object, CompilerObject pattern) + public IResult Match(CompilerObject @object, CompilerObject pattern) { var result = @base.Match(@object, pattern); diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.MemberAccess.cs index 926d7aab..f1b143dd 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.MemberAccess.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.MemberAccess.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Member(CompilerObject @object, MemberIndex index) + public IResult Member(CompilerObject @object, MemberIndex index) { var result = @base.GetMemberByIndex(@object, index); @@ -12,7 +12,7 @@ public Result Member(CompilerObject @object, MemberIndex index) return result; } - public Result Member(CompilerObject @object, MemberIndex index, CompilerObject value) + public IResult Member(CompilerObject @object, MemberIndex index, CompilerObject value) { var result = @base.SetMemberByIndex(@object, index, value); @@ -22,7 +22,7 @@ public Result Member(CompilerObject @object, MemberIndex index, CompilerObject v return result; } - public Result Member(CompilerObject @object, MemberName name) + public IResult Member(CompilerObject @object, MemberName name) { var result = @base.GetMemberByName(@object, name); @@ -32,7 +32,7 @@ public Result Member(CompilerObject @object, MemberName name) return result; } - public Result Member(CompilerObject @object, MemberName name, CompilerObject value) + public IResult Member(CompilerObject @object, MemberName name, CompilerObject value) { var result = @base.SetMemberByName(@object, name, value); diff --git a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ValueAccess.cs index ab671aae..90e1c2bd 100644 --- a/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ValueAccess.cs +++ b/ZSharp.Compiler.CG.Direct/dispatcher/services/Dispatcher.ValueAccess.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Get(CompilerObject @object) + public IResult Get(CompilerObject @object) { var result = @base.Get(@object); @@ -12,7 +12,7 @@ public Result Get(CompilerObject @object) return result; } - public Result Set(CompilerObject @object, CompilerObject value) + public IResult Set(CompilerObject @object, CompilerObject value) { var result = @base.Set(@object, value); diff --git a/ZSharp.Compiler.CG.Direct/protocols/callable/ICTCallable.cs b/ZSharp.Compiler.CG.Direct/protocols/callable/ICTCallable.cs index c75cb205..bc8884d7 100644 --- a/ZSharp.Compiler.CG.Direct/protocols/callable/ICTCallable.cs +++ b/ZSharp.Compiler.CG.Direct/protocols/callable/ICTCallable.cs @@ -2,6 +2,6 @@ { public interface ICTCallable { - public Result Call(Compiler compiler, Argument[] arguments); + public IResult Call(Compiler compiler, Argument[] arguments); } } diff --git a/ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastFrom.cs b/ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastFrom.cs index f523cf9b..f3f8a828 100644 --- a/ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastFrom.cs +++ b/ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastFrom.cs @@ -2,6 +2,6 @@ { public interface ICTImplicitCastFrom { - public Result ImplicitCast(Compiler compiler, CompilerObject value); + public IResult ImplicitCast(Compiler compiler, CompilerObject value); } } diff --git a/ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastTo.cs b/ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastTo.cs index 837789de..b66776d5 100644 --- a/ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastTo.cs +++ b/ZSharp.Compiler.CG.Direct/protocols/implicit casting/ICTImplicitCastTo.cs @@ -2,6 +2,6 @@ { public interface ICTImplicitCastTo { - public Result ImplicitCast(Compiler compiler, CompilerObject type); + public IResult ImplicitCast(Compiler compiler, CompilerObject type); } } diff --git a/ZSharp.Compiler.CG.Direct/protocols/index/ICTGetIndex.cs b/ZSharp.Compiler.CG.Direct/protocols/index/ICTGetIndex.cs index 734b43bb..931e80d7 100644 --- a/ZSharp.Compiler.CG.Direct/protocols/index/ICTGetIndex.cs +++ b/ZSharp.Compiler.CG.Direct/protocols/index/ICTGetIndex.cs @@ -2,6 +2,6 @@ { public interface ICTGetIndex { - public Result Index(Compiler compiler, Argument[] arguments); + public IResult Index(Compiler compiler, Argument[] arguments); } } diff --git a/ZSharp.Compiler.CG.Direct/protocols/index/ICTSetIndex.cs b/ZSharp.Compiler.CG.Direct/protocols/index/ICTSetIndex.cs index 90413a34..75a2a017 100644 --- a/ZSharp.Compiler.CG.Direct/protocols/index/ICTSetIndex.cs +++ b/ZSharp.Compiler.CG.Direct/protocols/index/ICTSetIndex.cs @@ -2,6 +2,6 @@ { public interface ICTSetIndex { - public Result Index(Compiler compiler, Argument[] arguments, CompilerObject value); + public IResult Index(Compiler compiler, Argument[] arguments, CompilerObject value); } } diff --git a/ZSharp.Compiler.CG.Direct/protocols/member access/ICTGetMember.cs b/ZSharp.Compiler.CG.Direct/protocols/member access/ICTGetMember.cs index bf4f5b53..4c93538f 100644 --- a/ZSharp.Compiler.CG.Direct/protocols/member access/ICTGetMember.cs +++ b/ZSharp.Compiler.CG.Direct/protocols/member access/ICTGetMember.cs @@ -2,6 +2,6 @@ { public interface ICTGetMember { - public Result Member(Compiler compiler, M member); + public IResult Member(Compiler compiler, M member); } } diff --git a/ZSharp.Compiler.CG.Direct/protocols/member access/ICTSetMember.cs b/ZSharp.Compiler.CG.Direct/protocols/member access/ICTSetMember.cs index b76ad2a9..82680cd7 100644 --- a/ZSharp.Compiler.CG.Direct/protocols/member access/ICTSetMember.cs +++ b/ZSharp.Compiler.CG.Direct/protocols/member access/ICTSetMember.cs @@ -2,6 +2,6 @@ { public interface ICTSetMember { - public Result Member(Compiler compiler, M member, CompilerObject value); + public IResult Member(Compiler compiler, M member, CompilerObject value); } } diff --git a/ZSharp.Compiler.CG.Direct/protocols/type casting/ICTCastTo.cs b/ZSharp.Compiler.CG.Direct/protocols/type casting/ICTCastTo.cs index abb08a74..5dd9046a 100644 --- a/ZSharp.Compiler.CG.Direct/protocols/type casting/ICTCastTo.cs +++ b/ZSharp.Compiler.CG.Direct/protocols/type casting/ICTCastTo.cs @@ -2,6 +2,6 @@ { public interface ICTCastTo { - public Result Cast(Compiler compiler, CompilerObject targetType); + public IResult Cast(Compiler compiler, CompilerObject targetType); } } diff --git a/ZSharp.Compiler.CG.Direct/protocols/type matching/ICTTypeMatch.cs b/ZSharp.Compiler.CG.Direct/protocols/type matching/ICTTypeMatch.cs index 29a124c8..62a88fae 100644 --- a/ZSharp.Compiler.CG.Direct/protocols/type matching/ICTTypeMatch.cs +++ b/ZSharp.Compiler.CG.Direct/protocols/type matching/ICTTypeMatch.cs @@ -2,6 +2,6 @@ { public interface ICTTypeMatch { - public Result Match(Compiler compiler, CompilerObject type); + public IResult Match(Compiler compiler, CompilerObject type); } } diff --git a/ZSharp.Compiler.CG.Direct/protocols/value access/ICTGet.cs b/ZSharp.Compiler.CG.Direct/protocols/value access/ICTGet.cs index e25f7914..83ce7d79 100644 --- a/ZSharp.Compiler.CG.Direct/protocols/value access/ICTGet.cs +++ b/ZSharp.Compiler.CG.Direct/protocols/value access/ICTGet.cs @@ -2,6 +2,6 @@ { public interface ICTGet { - public Result Get(Compiler compiler); + public IResult Get(Compiler compiler); } } diff --git a/ZSharp.Compiler.CG.Direct/protocols/value access/ICTSet.cs b/ZSharp.Compiler.CG.Direct/protocols/value access/ICTSet.cs index 5f571e87..35df8a19 100644 --- a/ZSharp.Compiler.CG.Direct/protocols/value access/ICTSet.cs +++ b/ZSharp.Compiler.CG.Direct/protocols/value access/ICTSet.cs @@ -2,6 +2,6 @@ { public interface ICTSet { - public Result Set(Compiler compiler, CompilerObject value); + public IResult Set(Compiler compiler, CompilerObject value); } } diff --git a/ZSharp.Compiler.CG.Proxy/GlobalUsings.cs b/ZSharp.Compiler.CG.Proxy/GlobalUsings.cs index c1bcb323..3bfc54ae 100644 --- a/ZSharp.Compiler.CG.Proxy/GlobalUsings.cs +++ b/ZSharp.Compiler.CG.Proxy/GlobalUsings.cs @@ -2,3 +2,4 @@ global using MemberIndex = int; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Call.cs index 6358c41c..9ec03475 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Call.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Call.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Call(CompilerObject callee, Argument[] arguments) + public IResult Call(CompilerObject callee, Argument[] arguments) { var result = @base.Call(callee, arguments); diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Cast.cs index c951e7f9..532b2389 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Cast.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Cast.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Cast(CompilerObject @object, CompilerObject type) + public IResult Cast(CompilerObject @object, CompilerObject type) { var result = @base.Cast(@object, type); diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs index b670ce6d..f14f27bd 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result ImplicitCast(CompilerObject @object, CompilerObject type) + public IResult ImplicitCast(CompilerObject @object, CompilerObject type) { var result = @base.ImplicitCast(@object, type); diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Index.cs index 283b77e8..1c1e09f2 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Index.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Index.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Index(CompilerObject @object, Argument[] arguments) + public IResult Index(CompilerObject @object, Argument[] arguments) { var result = @base.GetIndex(@object, arguments); @@ -12,7 +12,7 @@ public Result Index(CompilerObject @object, Argument[] arguments) return result; } - public Result Index(CompilerObject @object, Argument[] arguments, CompilerObject value) + public IResult Index(CompilerObject @object, Argument[] arguments, CompilerObject value) { var result = @base.GetIndex(@object, arguments); diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Match.cs index 2b27fdfc..569a0935 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Match.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.Match.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Match(CompilerObject @object, CompilerObject pattern) + public IResult Match(CompilerObject @object, CompilerObject pattern) { var result = @base.Match(@object, pattern); diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs index 54108881..a3aedf80 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.MemberAccess.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Member(CompilerObject @object, MemberIndex index) + public IResult Member(CompilerObject @object, MemberIndex index) { var result = @base.GetMemberByIndex(@object, index); @@ -12,7 +12,7 @@ public Result Member(CompilerObject @object, MemberIndex index) return result; } - public Result Member(CompilerObject @object, MemberIndex index, CompilerObject value) + public IResult Member(CompilerObject @object, MemberIndex index, CompilerObject value) { var result = @base.SetMemberByIndex(@object, index, value); @@ -22,7 +22,7 @@ public Result Member(CompilerObject @object, MemberIndex index, CompilerObject v return result; } - public Result Member(CompilerObject @object, MemberName name) + public IResult Member(CompilerObject @object, MemberName name) { var result = @base.GetMemberByName(@object, name); @@ -32,7 +32,7 @@ public Result Member(CompilerObject @object, MemberName name) return result; } - public Result Member(CompilerObject @object, MemberName name, CompilerObject value) + public IResult Member(CompilerObject @object, MemberName name, CompilerObject value) { var result = @base.SetMemberByName(@object, name, value); diff --git a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs index ce7e8e1a..99784859 100644 --- a/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs +++ b/ZSharp.Compiler.CG.Proxy/dispatcher/services/Dispatcher.ValueAccess.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Get(CompilerObject @object) + public IResult Get(CompilerObject @object) { var result = @base.Get(@object); @@ -12,7 +12,7 @@ public Result Get(CompilerObject @object) return result; } - public Result Set(CompilerObject @object, CompilerObject value) + public IResult Set(CompilerObject @object, CompilerObject value) { var result = @base.Set(@object, value); diff --git a/ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs b/ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs index ab3884eb..fe4e0a84 100644 --- a/ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs +++ b/ZSharp.Compiler.CG.Proxy/protocols/IProxy.cs @@ -2,6 +2,6 @@ { public interface IProxy { - public Result Apply(Func> fn) where R : class; + public IResult Apply(Func> fn) where R : class; } } diff --git a/ZSharp.Compiler.CG.Typed/GlobalUsings.cs b/ZSharp.Compiler.CG.Typed/GlobalUsings.cs index c1bcb323..3bfc54ae 100644 --- a/ZSharp.Compiler.CG.Typed/GlobalUsings.cs +++ b/ZSharp.Compiler.CG.Typed/GlobalUsings.cs @@ -2,3 +2,4 @@ global using MemberIndex = int; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Call.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Call.cs index fc9e791a..43db0bb7 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Call.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Call.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Call(CompilerObject callee, Argument[] arguments) + public IResult Call(CompilerObject callee, Argument[] arguments) { var result = @base.Call(callee, arguments); diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Cast.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Cast.cs index 4a0a703b..b886c715 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Cast.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Cast.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Cast(CompilerObject @object, CompilerObject type) + public IResult Cast(CompilerObject @object, CompilerObject type) { var result = @base.Cast(@object, type); diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs index 8b674041..0388ce63 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ImplicitCast.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result ImplicitCast(CompilerObject @object, CompilerObject type) + public IResult ImplicitCast(CompilerObject @object, CompilerObject type) { var result = @base.ImplicitCast(@object, type); diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Index.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Index.cs index 2962eb7c..54688b97 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Index.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Index.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Index(CompilerObject @object, Argument[] arguments) + public IResult Index(CompilerObject @object, Argument[] arguments) { var result = @base.GetIndex(@object, arguments); @@ -12,7 +12,7 @@ public Result Index(CompilerObject @object, Argument[] arguments) return result; } - public Result Index(CompilerObject @object, Argument[] arguments, CompilerObject value) + public IResult Index(CompilerObject @object, Argument[] arguments, CompilerObject value) { var result = @base.GetIndex(@object, arguments); diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Match.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Match.cs index 9b2c3f34..9845e765 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Match.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.Match.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Match(CompilerObject @object, CompilerObject pattern) + public IResult Match(CompilerObject @object, CompilerObject pattern) { var result = @base.Match(@object, pattern); diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.MemberAccess.cs index 54b35764..89437ebc 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.MemberAccess.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.MemberAccess.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Member(CompilerObject @object, MemberIndex index) + public IResult Member(CompilerObject @object, MemberIndex index) { var result = @base.GetMemberByIndex(@object, index); @@ -12,7 +12,7 @@ public Result Member(CompilerObject @object, MemberIndex index) return result; } - public Result Member(CompilerObject @object, MemberIndex index, CompilerObject value) + public IResult Member(CompilerObject @object, MemberIndex index, CompilerObject value) { var result = @base.SetMemberByIndex(@object, index, value); @@ -22,7 +22,7 @@ public Result Member(CompilerObject @object, MemberIndex index, CompilerObject v return result; } - public Result Member(CompilerObject @object, MemberName name) + public IResult Member(CompilerObject @object, MemberName name) { var result = @base.GetMemberByName(@object, name); @@ -32,7 +32,7 @@ public Result Member(CompilerObject @object, MemberName name) return result; } - public Result Member(CompilerObject @object, MemberName name, CompilerObject value) + public IResult Member(CompilerObject @object, MemberName name, CompilerObject value) { var result = @base.SetMemberByName(@object, name, value); diff --git a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ValueAccess.cs index f933e979..95c37767 100644 --- a/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ValueAccess.cs +++ b/ZSharp.Compiler.CG.Typed/dispatcher/services/Dispatcher.ValueAccess.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Get(CompilerObject @object) + public IResult Get(CompilerObject @object) { var result = @base.Get(@object); @@ -12,7 +12,7 @@ public Result Get(CompilerObject @object) return result; } - public Result Set(CompilerObject @object, CompilerObject value) + public IResult Set(CompilerObject @object, CompilerObject value) { var result = @base.Set(@object, value); diff --git a/ZSharp.Compiler.CG.Typed/extensions/CompilerExtensions.cs b/ZSharp.Compiler.CG.Typed/extensions/CompilerExtensions.cs index d3c29faa..87a0d69a 100644 --- a/ZSharp.Compiler.CG.Typed/extensions/CompilerExtensions.cs +++ b/ZSharp.Compiler.CG.Typed/extensions/CompilerExtensions.cs @@ -4,7 +4,7 @@ namespace ZSharp.Compiler { public static class CompilerExtensions { - public static Result GetRuntimeDescriptor(this Compiler compiler, CompilerObject @object) + public static IResult GetRuntimeDescriptor(this Compiler compiler, CompilerObject @object) { if (@object.Is(out var hasRuntimeDescriptor)) return hasRuntimeDescriptor.GetRuntimeDescriptor(compiler); diff --git a/ZSharp.Compiler.CG.Typed/protocols/callable/IRTCallable.cs b/ZSharp.Compiler.CG.Typed/protocols/callable/IRTCallable.cs index 966a6877..4e500b03 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/callable/IRTCallable.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/callable/IRTCallable.cs @@ -2,6 +2,6 @@ { public interface IRTCallable { - public Result Call(Compiler compiler, CompilerObject @object, Argument[] arguments); + public IResult Call(Compiler compiler, CompilerObject @object, Argument[] arguments); } } diff --git a/ZSharp.Compiler.CG.Typed/protocols/implicit casting/IRTImplicitCastTo.cs b/ZSharp.Compiler.CG.Typed/protocols/implicit casting/IRTImplicitCastTo.cs index 104be28d..14d4405a 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/implicit casting/IRTImplicitCastTo.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/implicit casting/IRTImplicitCastTo.cs @@ -2,6 +2,6 @@ { public interface IRTImplicitCastTo { - public Result ImplicitCast(Compiler compiler, CompilerObject @object, CompilerObject type); + public IResult ImplicitCast(Compiler compiler, CompilerObject @object, CompilerObject type); } } diff --git a/ZSharp.Compiler.CG.Typed/protocols/index/IRTGetIndex.cs b/ZSharp.Compiler.CG.Typed/protocols/index/IRTGetIndex.cs index 83a153b8..160133c4 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/index/IRTGetIndex.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/index/IRTGetIndex.cs @@ -2,6 +2,6 @@ { public interface IRTGetIndex { - public Result Index(Compiler compiler, CompilerObject @object, Argument[] arguments); + public IResult Index(Compiler compiler, CompilerObject @object, Argument[] arguments); } } diff --git a/ZSharp.Compiler.CG.Typed/protocols/index/IRTSetIndex.cs b/ZSharp.Compiler.CG.Typed/protocols/index/IRTSetIndex.cs index fa44b99a..a780bba6 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/index/IRTSetIndex.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/index/IRTSetIndex.cs @@ -2,6 +2,6 @@ { public interface IRTSetIndex { - public Result Index(Compiler compiler, CompilerObject @object, Argument[] arguments, CompilerObject value); + public IResult Index(Compiler compiler, CompilerObject @object, Argument[] arguments, CompilerObject value); } } diff --git a/ZSharp.Compiler.CG.Typed/protocols/member access/IRTGetMember.cs b/ZSharp.Compiler.CG.Typed/protocols/member access/IRTGetMember.cs index a08d8ac5..b3b83a3b 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/member access/IRTGetMember.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/member access/IRTGetMember.cs @@ -2,6 +2,6 @@ { public interface IRTGetMember { - public Result Member(Compiler compiler, CompilerObject @object, M member); + public IResult Member(Compiler compiler, CompilerObject @object, M member); } } diff --git a/ZSharp.Compiler.CG.Typed/protocols/member access/IRTSetMember.cs b/ZSharp.Compiler.CG.Typed/protocols/member access/IRTSetMember.cs index a082b5d9..36dd69d8 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/member access/IRTSetMember.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/member access/IRTSetMember.cs @@ -2,6 +2,6 @@ { public interface IRTSetMember { - public Result Member(Compiler compiler, CompilerObject @object, M member, CompilerObject value); + public IResult Member(Compiler compiler, CompilerObject @object, M member, CompilerObject value); } } diff --git a/ZSharp.Compiler.CG.Typed/protocols/runtime/IHasRuntimeDescriptor.cs b/ZSharp.Compiler.CG.Typed/protocols/runtime/IHasRuntimeDescriptor.cs index 98a5336e..feb03346 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/runtime/IHasRuntimeDescriptor.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/runtime/IHasRuntimeDescriptor.cs @@ -2,6 +2,6 @@ { public interface IHasRuntimeDescriptor { - public Result GetRuntimeDescriptor(Compiler compiler); + public IResult GetRuntimeDescriptor(Compiler compiler); } } diff --git a/ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastFrom.cs b/ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastFrom.cs index a30af3db..45805fce 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastFrom.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastFrom.cs @@ -2,6 +2,6 @@ { public interface IRTCastFrom { - public Result Cast(Compiler compiler, CompilerObject value); + public IResult Cast(Compiler compiler, CompilerObject value); } } diff --git a/ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastTo.cs b/ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastTo.cs index ca47ab87..454be3c1 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastTo.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/type casting/IRTCastTo.cs @@ -2,6 +2,6 @@ { public interface IRTCastTo { - public Result Cast(Compiler compiler, CompilerObject value, CompilerObject targetType); + public IResult Cast(Compiler compiler, CompilerObject value, CompilerObject targetType); } } diff --git a/ZSharp.Compiler.CG.Typed/protocols/type matching/IRTTypeMatch.cs b/ZSharp.Compiler.CG.Typed/protocols/type matching/IRTTypeMatch.cs index 198c6773..01cb8980 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/type matching/IRTTypeMatch.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/type matching/IRTTypeMatch.cs @@ -2,6 +2,6 @@ { public interface IRTTypeMatch { - public Result Match(Compiler compiler, CompilerObject value, CompilerObject type); + public IResult Match(Compiler compiler, CompilerObject value, CompilerObject type); } } diff --git a/ZSharp.Compiler.CG.Typed/protocols/value access/IRTGet.cs b/ZSharp.Compiler.CG.Typed/protocols/value access/IRTGet.cs index 656d5b58..6d3d7e5c 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/value access/IRTGet.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/value access/IRTGet.cs @@ -2,6 +2,6 @@ { public interface IRTGet { - public Result Get(Compiler compiler, CompilerObject @object); + public IResult Get(Compiler compiler, CompilerObject @object); } } diff --git a/ZSharp.Compiler.CG.Typed/protocols/value access/IRTSet.cs b/ZSharp.Compiler.CG.Typed/protocols/value access/IRTSet.cs index aab7f06f..0b8c295b 100644 --- a/ZSharp.Compiler.CG.Typed/protocols/value access/IRTSet.cs +++ b/ZSharp.Compiler.CG.Typed/protocols/value access/IRTSet.cs @@ -2,6 +2,6 @@ { public interface IRTSet { - public Result Set(Compiler compiler, CompilerObject @object, CompilerObject value); + public IResult Set(Compiler compiler, CompilerObject @object, CompilerObject value); } } diff --git a/ZSharp.Compiler.CG/GlobalUsings.cs b/ZSharp.Compiler.CG/GlobalUsings.cs index c1bcb323..3bfc54ae 100644 --- a/ZSharp.Compiler.CG/GlobalUsings.cs +++ b/ZSharp.Compiler.CG/GlobalUsings.cs @@ -2,3 +2,4 @@ global using MemberIndex = int; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.CG/cg/services/CG.Call.cs b/ZSharp.Compiler.CG/cg/services/CG.Call.cs index 62e34e5d..b30eed0e 100644 --- a/ZSharp.Compiler.CG/cg/services/CG.Call.cs +++ b/ZSharp.Compiler.CG/cg/services/CG.Call.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler { - public delegate Result Call(CompilerObject callee, Argument[] arguments); + public delegate IResult Call(CompilerObject callee, Argument[] arguments); partial struct CG { diff --git a/ZSharp.Compiler.CG/cg/services/CG.Cast.cs b/ZSharp.Compiler.CG/cg/services/CG.Cast.cs index e4529a38..6a936b64 100644 --- a/ZSharp.Compiler.CG/cg/services/CG.Cast.cs +++ b/ZSharp.Compiler.CG/cg/services/CG.Cast.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler { - public delegate Result Cast(CompilerObject @object, CompilerObject type); + public delegate IResult Cast(CompilerObject @object, CompilerObject type); partial struct CG { diff --git a/ZSharp.Compiler.CG/cg/services/CG.ImplicitCast.cs b/ZSharp.Compiler.CG/cg/services/CG.ImplicitCast.cs index 903a2c50..7bea2caa 100644 --- a/ZSharp.Compiler.CG/cg/services/CG.ImplicitCast.cs +++ b/ZSharp.Compiler.CG/cg/services/CG.ImplicitCast.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler { - public delegate Result ImplicitCast(CompilerObject @object, CompilerObject type); + public delegate IResult ImplicitCast(CompilerObject @object, CompilerObject type); partial struct CG { diff --git a/ZSharp.Compiler.CG/cg/services/CG.Index.cs b/ZSharp.Compiler.CG/cg/services/CG.Index.cs index 8e4952b1..d7ce798d 100644 --- a/ZSharp.Compiler.CG/cg/services/CG.Index.cs +++ b/ZSharp.Compiler.CG/cg/services/CG.Index.cs @@ -1,7 +1,7 @@ namespace ZSharp.Compiler { - public delegate Result GetIndex(CompilerObject @object, Argument[] arguments); - public delegate Result SetIndex(CompilerObject @object, Argument[] arguments, CompilerObject value); + public delegate IResult GetIndex(CompilerObject @object, Argument[] arguments); + public delegate IResult SetIndex(CompilerObject @object, Argument[] arguments, CompilerObject value); partial struct CG { @@ -9,10 +9,10 @@ partial struct CG public SetIndex SetIndex { get; set; } = Dispatcher.Index; - public readonly Result Index(CompilerObject @object, Argument[] arguments) + public readonly IResult Index(CompilerObject @object, Argument[] arguments) => GetIndex(@object, arguments); - public readonly Result Index(CompilerObject @object, Argument[] arguments, CompilerObject value) + public readonly IResult Index(CompilerObject @object, Argument[] arguments, CompilerObject value) => SetIndex(@object, arguments, value); } } diff --git a/ZSharp.Compiler.CG/cg/services/CG.Match.cs b/ZSharp.Compiler.CG/cg/services/CG.Match.cs index f8a04517..55c931f8 100644 --- a/ZSharp.Compiler.CG/cg/services/CG.Match.cs +++ b/ZSharp.Compiler.CG/cg/services/CG.Match.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler { - public delegate Result Match(CompilerObject @object, CompilerObject pattern); + public delegate IResult Match(CompilerObject @object, CompilerObject pattern); partial struct CG { diff --git a/ZSharp.Compiler.CG/cg/services/CG.MemberAccess.cs b/ZSharp.Compiler.CG/cg/services/CG.MemberAccess.cs index a000fd1c..4b0e4793 100644 --- a/ZSharp.Compiler.CG/cg/services/CG.MemberAccess.cs +++ b/ZSharp.Compiler.CG/cg/services/CG.MemberAccess.cs @@ -1,8 +1,8 @@ namespace ZSharp.Compiler { - public delegate Result GetMember(CompilerObject @object, T member); + public delegate IResult GetMember(CompilerObject @object, T member); - public delegate Result SetMember(CompilerObject @object, T member, CompilerObject value); + public delegate IResult SetMember(CompilerObject @object, T member, CompilerObject value); partial struct CG { @@ -20,7 +20,7 @@ partial struct CG /// /// /// - public readonly Result Member(CompilerObject @object, MemberIndex index) + public readonly IResult Member(CompilerObject @object, MemberIndex index) => GetMemberByIndex(@object, index); /// @@ -30,7 +30,7 @@ public readonly Result Member(CompilerObject @object, MemberIndex index) /// /// /// - public readonly Result Member(CompilerObject @object, MemberIndex index, CompilerObject value) + public readonly IResult Member(CompilerObject @object, MemberIndex index, CompilerObject value) => SetMemberByIndex(@object, index, value); /// @@ -39,7 +39,7 @@ public readonly Result Member(CompilerObject @object, MemberIndex index, Compile /// /// /// - public readonly Result Member(CompilerObject @object, MemberName name) + public readonly IResult Member(CompilerObject @object, MemberName name) => GetMemberByName(@object, name); /// @@ -49,7 +49,7 @@ public readonly Result Member(CompilerObject @object, MemberName name) /// /// /// - public readonly Result Member(CompilerObject @object, MemberName name, CompilerObject value) + public readonly IResult Member(CompilerObject @object, MemberName name, CompilerObject value) => SetMemberByName(@object, name, value); } } diff --git a/ZSharp.Compiler.CG/cg/services/CG.ValueAccess.cs b/ZSharp.Compiler.CG/cg/services/CG.ValueAccess.cs index 567ae1c0..bed1a4ff 100644 --- a/ZSharp.Compiler.CG/cg/services/CG.ValueAccess.cs +++ b/ZSharp.Compiler.CG/cg/services/CG.ValueAccess.cs @@ -1,8 +1,8 @@ namespace ZSharp.Compiler { - public delegate Result Get(CompilerObject @object); + public delegate IResult Get(CompilerObject @object); - public delegate Result Set(CompilerObject @object, CompilerObject value); + public delegate IResult Set(CompilerObject @object, CompilerObject value); public partial struct CG { diff --git a/ZSharp.Compiler.CG/dispatcher/Dispatcher.Call.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Call.cs index d915c8e5..ec6d5fff 100644 --- a/ZSharp.Compiler.CG/dispatcher/Dispatcher.Call.cs +++ b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Call.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public static Result Call(CompilerObject callee, Argument[] arguments) + public static IResult Call(CompilerObject callee, Argument[] arguments) => Result.Error( $"Object [{callee}] does not support call operation." ); diff --git a/ZSharp.Compiler.CG/dispatcher/Dispatcher.Cast.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Cast.cs index 1bf6b765..77584f8b 100644 --- a/ZSharp.Compiler.CG/dispatcher/Dispatcher.Cast.cs +++ b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Cast.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public static Result Cast(CompilerObject @object, CompilerObject type) + public static IResult Cast(CompilerObject @object, CompilerObject type) => Result.Error( "Cast operation is not supported." ); diff --git a/ZSharp.Compiler.CG/dispatcher/Dispatcher.ImplicitCast.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.ImplicitCast.cs index 63a264e9..30f501a2 100644 --- a/ZSharp.Compiler.CG/dispatcher/Dispatcher.ImplicitCast.cs +++ b/ZSharp.Compiler.CG/dispatcher/Dispatcher.ImplicitCast.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public static Result ImplicitCast(CompilerObject @object, CompilerObject type) + public static IResult ImplicitCast(CompilerObject @object, CompilerObject type) => Result.Error( "Implicit casting is not supported for the given object and type." ); diff --git a/ZSharp.Compiler.CG/dispatcher/Dispatcher.Index.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Index.cs index 752b2669..f8e59ee2 100644 --- a/ZSharp.Compiler.CG/dispatcher/Dispatcher.Index.cs +++ b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Index.cs @@ -2,12 +2,12 @@ { partial class Dispatcher { - public static Result Index(CompilerObject @object, Argument[] arguments) + public static IResult Index(CompilerObject @object, Argument[] arguments) => Result.Error( "Object does not support index operation." ); - public static Result Index(CompilerObject @object, Argument[] arguments, CompilerObject value) + public static IResult Index(CompilerObject @object, Argument[] arguments, CompilerObject value) => Result.Error( "Object does not support index assignment operation." ); diff --git a/ZSharp.Compiler.CG/dispatcher/Dispatcher.Match.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Match.cs index 58f27b28..3a150e39 100644 --- a/ZSharp.Compiler.CG/dispatcher/Dispatcher.Match.cs +++ b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Match.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public static Result Match(CompilerObject @object, CompilerObject pattern) + public static IResult Match(CompilerObject @object, CompilerObject pattern) => Result.Error( "Pattern matching is not supported in the current context." ); diff --git a/ZSharp.Compiler.CG/dispatcher/Dispatcher.MemberAccess.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.MemberAccess.cs index 64072057..05cbfba8 100644 --- a/ZSharp.Compiler.CG/dispatcher/Dispatcher.MemberAccess.cs +++ b/ZSharp.Compiler.CG/dispatcher/Dispatcher.MemberAccess.cs @@ -2,22 +2,22 @@ { partial class Dispatcher { - public static Result Member(CompilerObject @object, MemberIndex index) + public static IResult Member(CompilerObject @object, MemberIndex index) => Result.Error( $"Object [{@object}] does not support member access by index." ); - public static Result Member(CompilerObject @object, MemberIndex index, CompilerObject value) + public static IResult Member(CompilerObject @object, MemberIndex index, CompilerObject value) => Result.Error( $"Object [{@object}] does not support member assignment by index." ); - public static Result Member(CompilerObject @object, MemberName name) + public static IResult Member(CompilerObject @object, MemberName name) => Result.Error( $"Object [{@object}] does not support member access by name." ); - public static Result Member(CompilerObject @object, MemberName name, CompilerObject value) + public static IResult Member(CompilerObject @object, MemberName name, CompilerObject value) => Result.Error( $"Object [{@object}] does not support member assignment by name." ); diff --git a/ZSharp.Compiler.CG/dispatcher/Dispatcher.Runtime.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Runtime.cs index f71a24a5..5c6701cd 100644 --- a/ZSharp.Compiler.CG/dispatcher/Dispatcher.Runtime.cs +++ b/ZSharp.Compiler.CG/dispatcher/Dispatcher.Runtime.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public static Result RuntimeDescriptor(CompilerObject @object) + public static IResult RuntimeDescriptor(CompilerObject @object) => Result.Error( "Object does not support runtime descriptor protocol" ); diff --git a/ZSharp.Compiler.CG/dispatcher/Dispatcher.ValueAccess.cs b/ZSharp.Compiler.CG/dispatcher/Dispatcher.ValueAccess.cs index 0f7a37a9..2551698f 100644 --- a/ZSharp.Compiler.CG/dispatcher/Dispatcher.ValueAccess.cs +++ b/ZSharp.Compiler.CG/dispatcher/Dispatcher.ValueAccess.cs @@ -2,12 +2,12 @@ { partial class Dispatcher { - public static Result Get(CompilerObject @object) + public static IResult Get(CompilerObject @object) => Result.Error( "Object does not support get" ); - public static Result Set(CompilerObject @object, CompilerObject value) + public static IResult Set(CompilerObject @object, CompilerObject value) => Result.Error( "Object does not support set" ); diff --git a/ZSharp.Compiler.Context/GlobalUsings.cs b/ZSharp.Compiler.Context/GlobalUsings.cs index c1bcb323..3bfc54ae 100644 --- a/ZSharp.Compiler.Context/GlobalUsings.cs +++ b/ZSharp.Compiler.Context/GlobalUsings.cs @@ -2,3 +2,4 @@ global using MemberIndex = int; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.Context/capabilities/scoping/ILookupContext.cs b/ZSharp.Compiler.Context/capabilities/scoping/ILookupContext.cs index 731f123c..56d72b00 100644 --- a/ZSharp.Compiler.Context/capabilities/scoping/ILookupContext.cs +++ b/ZSharp.Compiler.Context/capabilities/scoping/ILookupContext.cs @@ -5,7 +5,7 @@ namespace ZSharp.Compiler public interface ILookupContext : IContext { - public Result Get(MemberName name); + public IResult Get(MemberName name); public sealed bool Get(MemberName name, [NotNullWhen(true)] out CompilerObject? value) => Get(name).Ok(out value); diff --git a/ZSharp.Compiler.Context/capabilities/scoping/IScopeContext.cs b/ZSharp.Compiler.Context/capabilities/scoping/IScopeContext.cs index fab4845e..7e52d8ee 100644 --- a/ZSharp.Compiler.Context/capabilities/scoping/IScopeContext.cs +++ b/ZSharp.Compiler.Context/capabilities/scoping/IScopeContext.cs @@ -4,8 +4,8 @@ public interface IScopeContext : IContext , ILookupContext { - public Result Add(MemberName name, CompilerObject value); + public IResult Add(MemberName name, CompilerObject value); - public Result Set(MemberName name, CompilerObject value); + public IResult Set(MemberName name, CompilerObject value); } } diff --git a/ZSharp.Compiler.Context/capabilities/storage/IStorageContext.cs b/ZSharp.Compiler.Context/capabilities/storage/IStorageContext.cs index 5c384eae..a066cf82 100644 --- a/ZSharp.Compiler.Context/capabilities/storage/IStorageContext.cs +++ b/ZSharp.Compiler.Context/capabilities/storage/IStorageContext.cs @@ -4,7 +4,7 @@ namespace ZSharp.Compiler { public interface IStorageContext { - public Result CreateStorage(StorageOptions options); + public IResult CreateStorage(StorageOptions options); public sealed bool CreateStorage(StorageOptions options, [NotNullWhen(true)] out CompilerObject? result) => CreateStorage(options).Ok(out result); diff --git a/ZSharp.Compiler.Core/result/Result.cs b/ZSharp.Compiler.Core/result/Result.cs index 7ba589ea..3aded28d 100644 --- a/ZSharp.Compiler.Core/result/Result.cs +++ b/ZSharp.Compiler.Core/result/Result.cs @@ -1,70 +1,50 @@ using CommonZ; +using System.Diagnostics.CodeAnalysis; namespace ZSharp.Compiler { public class Result - : Result + : IResult where TResult : class? { - protected Result(TResult? result, Error? error) - : base(result, error) - { + private readonly TResult? result; + private readonly Error? error; + + [MemberNotNullWhen(true, nameof(result))] + public bool IsOk => result is not null; + + [MemberNotNullWhen(true, nameof(error))] + public bool IsError => error is not null; + private Result(TResult? result, Error? error) + { + this.result = result; + this.error = error; } - public new static Result Ok(TResult result) + public static Result Ok(TResult result) => new(result, null); - public new static Result Error(Error error) + public static Result Error(Error error) => new(null, error); public static Result Error(string message) => Error(new ErrorMessage(message)); - public new Result When(Action action) - { - if (IsOk) - action(Unwrap()); + TResult IResult.Unwrap() + => result ?? throw new InvalidOperationException(error!.ToString()); - return this; - } + Error IResult.UnwrapError() + => error ?? throw new InvalidOperationException("Result is Ok."); - public new Result When(Func map) - where R : class? + IResult IResult.When(Func map) => IsOk ? Result.Ok(map(result)) : Result.Error(error!); - public Result When(Func> map) - where R : class? - => IsOk - ? map(result) - : Result.Error(error!); - - public new Result When(out TResult? result) - { - result = this.result; - return this; - } - - public new Result Else(Action action) - { - if (IsError) - action(error); - - return this; - } - - public new Result Else(Func map) - where E : class + IResult IResult.Else(Func map) => IsOk ? Result.Ok(result) : Result.Error(map(error!)); - - public new Result Else(out Error? error) - { - error = this.error; - return this; - } } } diff --git a/ZSharp.Compiler.Evaluation.Direct/GlobalUsings.cs b/ZSharp.Compiler.Evaluation.Direct/GlobalUsings.cs index c1bcb323..3bfc54ae 100644 --- a/ZSharp.Compiler.Evaluation.Direct/GlobalUsings.cs +++ b/ZSharp.Compiler.Evaluation.Direct/GlobalUsings.cs @@ -2,3 +2,4 @@ global using MemberIndex = int; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.Evaluation.Direct/dispatcher/services/Dispatcher.Evaluate.cs b/ZSharp.Compiler.Evaluation.Direct/dispatcher/services/Dispatcher.Evaluate.cs index 14d25ee9..811cc0df 100644 --- a/ZSharp.Compiler.Evaluation.Direct/dispatcher/services/Dispatcher.Evaluate.cs +++ b/ZSharp.Compiler.Evaluation.Direct/dispatcher/services/Dispatcher.Evaluate.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Evaluate(CompilerObject @object) + public IResult Evaluate(CompilerObject @object) { var result = @base.Evaluate(@object); diff --git a/ZSharp.Compiler.Evaluation.Direct/protocols/evaluate/ICTEvaluate.cs b/ZSharp.Compiler.Evaluation.Direct/protocols/evaluate/ICTEvaluate.cs index 3ed21a5d..707921d5 100644 --- a/ZSharp.Compiler.Evaluation.Direct/protocols/evaluate/ICTEvaluate.cs +++ b/ZSharp.Compiler.Evaluation.Direct/protocols/evaluate/ICTEvaluate.cs @@ -2,6 +2,6 @@ { public interface ICTEvaluate { - public Result Evaluate(Compiler compiler); + public IResult Evaluate(Compiler compiler); } } diff --git a/ZSharp.Compiler.Evaluation.IR/GlobalUsings.cs b/ZSharp.Compiler.Evaluation.IR/GlobalUsings.cs index c1bcb323..3bfc54ae 100644 --- a/ZSharp.Compiler.Evaluation.IR/GlobalUsings.cs +++ b/ZSharp.Compiler.Evaluation.IR/GlobalUsings.cs @@ -2,3 +2,4 @@ global using MemberIndex = int; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.Evaluation.IR/dispatcher/services/Dispatcher.Evaluate.cs b/ZSharp.Compiler.Evaluation.IR/dispatcher/services/Dispatcher.Evaluate.cs index fd9b0eee..31a85993 100644 --- a/ZSharp.Compiler.Evaluation.IR/dispatcher/services/Dispatcher.Evaluate.cs +++ b/ZSharp.Compiler.Evaluation.IR/dispatcher/services/Dispatcher.Evaluate.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result Evaluate(CompilerObject @object) + public IResult Evaluate(CompilerObject @object) { var result = @base.Evaluate(@object); diff --git a/ZSharp.Compiler.Evaluation/GlobalUsings.cs b/ZSharp.Compiler.Evaluation/GlobalUsings.cs index 05db7df2..501033a9 100644 --- a/ZSharp.Compiler.Evaluation/GlobalUsings.cs +++ b/ZSharp.Compiler.Evaluation/GlobalUsings.cs @@ -1 +1,2 @@ global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.Evaluate.cs b/ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.Evaluate.cs index f9d10bd1..af85fc0e 100644 --- a/ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.Evaluate.cs +++ b/ZSharp.Compiler.Evaluation/dispatcher/Dispatcher.Evaluate.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public static Result Evaluate(CompilerObject @object) + public static IResult Evaluate(CompilerObject @object) => Result.Error( $"Object [{@object}] does not support evaluation." ); diff --git a/ZSharp.Compiler.Evaluation/evaluator/services/Evaluator.Evaluate.cs b/ZSharp.Compiler.Evaluation/evaluator/services/Evaluator.Evaluate.cs index 246ee08b..c077d6b7 100644 --- a/ZSharp.Compiler.Evaluation/evaluator/services/Evaluator.Evaluate.cs +++ b/ZSharp.Compiler.Evaluation/evaluator/services/Evaluator.Evaluate.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler { - public delegate Result Evaluate(CompilerObject @object); + public delegate IResult Evaluate(CompilerObject @object); partial struct Evaluator { diff --git a/ZSharp.Compiler.Features/GlobalUsings.cs b/ZSharp.Compiler.Features/GlobalUsings.cs index 05db7df2..501033a9 100644 --- a/ZSharp.Compiler.Features/GlobalUsings.cs +++ b/ZSharp.Compiler.Features/GlobalUsings.cs @@ -1 +1,2 @@ global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.Features/callable/BoundSignature.cs b/ZSharp.Compiler.Features/callable/BoundSignature.cs index 5247aa5a..845a56af 100644 --- a/ZSharp.Compiler.Features/callable/BoundSignature.cs +++ b/ZSharp.Compiler.Features/callable/BoundSignature.cs @@ -8,7 +8,7 @@ public sealed class BoundSignature public Collection Parameters { get; init; } = []; - public static Result Create(Compiler compiler, CompilerObject @object, IArgumentStream arguments) + public static IResult Create(Compiler compiler, CompilerObject @object, IArgumentStream arguments) { if (!@object.Is(out var signature)) return Result.Error($"Object '{@object}' is not a signature."); diff --git a/ZSharp.Compiler.Features/callable/IParameter.cs b/ZSharp.Compiler.Features/callable/IParameter.cs index bba3c9eb..cc381eb2 100644 --- a/ZSharp.Compiler.Features/callable/IParameter.cs +++ b/ZSharp.Compiler.Features/callable/IParameter.cs @@ -2,6 +2,6 @@ { public interface IParameter { - public Result Match(Compiler compiler, IArgumentStream arguments); + public IResult Match(Compiler compiler, IArgumentStream arguments); } } diff --git a/ZSharp.Compiler.IR.Static/GlobalUsings.cs b/ZSharp.Compiler.IR.Static/GlobalUsings.cs index 52ab0744..2693dd4f 100644 --- a/ZSharp.Compiler.IR.Static/GlobalUsings.cs +++ b/ZSharp.Compiler.IR.Static/GlobalUsings.cs @@ -1,2 +1,4 @@ global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; + global using TargetPlatform = object; diff --git a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Code.cs b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Code.cs index fe1e16af..2d996dc4 100644 --- a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Code.cs +++ b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Code.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result CompileCode(CompilerObject @object, TargetPlatform? target) + public IResult CompileCode(CompilerObject @object, TargetPlatform? target) { var result = @base.CompileCode(@object, target); diff --git a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Definition.cs b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Definition.cs index 1fea4cae..868a9d45 100644 --- a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Definition.cs +++ b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Definition.cs @@ -17,7 +17,7 @@ bool IIRDefinitionInCompiler.CompileDefinition(CompilerObject @object, Ow return result; } - Result IIRDefinitionAsCompiler.CompileDefinition(CompilerObject @object, object? target) + IResult IIRDefinitionAsCompiler.CompileDefinition(CompilerObject @object, object? target) { var result = @base.CompileDefinition(@object, target); diff --git a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Reference.cs b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Reference.cs index 60ddc103..f43db6ad 100644 --- a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Reference.cs +++ b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Reference.cs @@ -3,7 +3,7 @@ partial class Dispatcher : IIRReferenceCompiler { - Result IIRReferenceCompiler.CompileReference(CompilerObject @object) where T : class + IResult IIRReferenceCompiler.CompileReference(CompilerObject @object) where T : class { var result = @base.CompileReference(@object); diff --git a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Type.cs b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Type.cs index 585c7d62..5215586c 100644 --- a/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Type.cs +++ b/ZSharp.Compiler.IR.Static/dispatcher/services/Dispatcher.Type.cs @@ -3,7 +3,7 @@ partial class Dispatcher : IIRTypeCompiler { - public Result CompileType(CompilerObject @object) + public IResult CompileType(CompilerObject @object) { var result = @base.CompileType(@object); @@ -13,7 +13,7 @@ partial class Dispatcher return result; } - Result IIRTypeCompiler.CompileType(CompilerObject @object) + IResult IIRTypeCompiler.CompileType(CompilerObject @object) { var result = @base.CompileTypeAs(@object); diff --git a/ZSharp.Compiler.IR.Static/objects/RawIRCode.cs b/ZSharp.Compiler.IR.Static/objects/RawIRCode.cs index 4f66e050..edff616b 100644 --- a/ZSharp.Compiler.IR.Static/objects/RawIRCode.cs +++ b/ZSharp.Compiler.IR.Static/objects/RawIRCode.cs @@ -9,7 +9,7 @@ public sealed class RawIRCode(IRCode code) { private readonly IRCode code = code; - Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) + IResult ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) => Result.Ok(code); public static CompilerObject From(Collection code, CompilerObject type) diff --git a/ZSharp.Compiler.IR.Static/objects/UntypedIRCode.cs b/ZSharp.Compiler.IR.Static/objects/UntypedIRCode.cs index 3eb031b8..b1351dfb 100644 --- a/ZSharp.Compiler.IR.Static/objects/UntypedIRCode.cs +++ b/ZSharp.Compiler.IR.Static/objects/UntypedIRCode.cs @@ -10,7 +10,7 @@ internal sealed class UntypedIRCode(Collection code, Compiler { CompilerObject ITyped.Type => type; - Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) + IResult ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) { if ( compiler.IR.CompileType(type) diff --git a/ZSharp.Compiler.IR.Static/protocols/ICompileIRCode.cs b/ZSharp.Compiler.IR.Static/protocols/ICompileIRCode.cs index f261d1f2..34366d7f 100644 --- a/ZSharp.Compiler.IR.Static/protocols/ICompileIRCode.cs +++ b/ZSharp.Compiler.IR.Static/protocols/ICompileIRCode.cs @@ -2,6 +2,6 @@ { public interface ICompileIRCode { - public Result CompileIRCode(Compiler compiler, TargetPlatform? target); + public IResult CompileIRCode(Compiler compiler, TargetPlatform? target); } } diff --git a/ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionAs.cs b/ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionAs.cs index ac95f2d1..e0216734 100644 --- a/ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionAs.cs +++ b/ZSharp.Compiler.IR.Static/protocols/ICompileIRDefinitionAs.cs @@ -3,6 +3,6 @@ public interface ICompileIRDefinitionAs where T : ZSharp.IR.IRDefinition { - public Result CompileIRDefinition(Compiler compiler, TargetPlatform? target); + public IResult CompileIRDefinition(Compiler compiler, TargetPlatform? target); } } diff --git a/ZSharp.Compiler.IR.Static/protocols/ICompileIRReference.cs b/ZSharp.Compiler.IR.Static/protocols/ICompileIRReference.cs index 1295b15d..41fb56f3 100644 --- a/ZSharp.Compiler.IR.Static/protocols/ICompileIRReference.cs +++ b/ZSharp.Compiler.IR.Static/protocols/ICompileIRReference.cs @@ -1,8 +1,8 @@ namespace ZSharp.Compiler { - public interface ICompileIRReference + public interface ICompileIRReference where T : class { - public Result CompileIRReference(Compiler compiler); + public IResult CompileIRReference(Compiler compiler); } } diff --git a/ZSharp.Compiler.IR.Static/protocols/ICompileIRType.cs b/ZSharp.Compiler.IR.Static/protocols/ICompileIRType.cs index 95b33949..de509342 100644 --- a/ZSharp.Compiler.IR.Static/protocols/ICompileIRType.cs +++ b/ZSharp.Compiler.IR.Static/protocols/ICompileIRType.cs @@ -4,16 +4,16 @@ namespace ZSharp.Compiler { public interface ICompileIRType { - public Result CompileIRType(Compiler compiler); + public IResult CompileIRType(Compiler compiler); } - public interface ICompileIRType + public interface ICompileIRType : ICompileIRType where T : class, IType { - Result ICompileIRType.CompileIRType(Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler compiler) => CompileIRType(compiler).When(type => type as IType); - public new Result CompileIRType(Compiler compiler); + public new IResult CompileIRType(Compiler compiler); } } \ No newline at end of file diff --git a/ZSharp.Compiler.IR/GlobalUsings.cs b/ZSharp.Compiler.IR/GlobalUsings.cs index 6d3026e3..1a6f1d13 100644 --- a/ZSharp.Compiler.IR/GlobalUsings.cs +++ b/ZSharp.Compiler.IR/GlobalUsings.cs @@ -1,3 +1,4 @@ global using ZSharp.IR; global using TargetPlatform = object; +global using IResult = IResult; diff --git a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Code.cs b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Code.cs index 7187db51..41166394 100644 --- a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Code.cs +++ b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Code.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result CompileCode(CompilerObject @object, TargetPlatform? target) + public IResult CompileCode(CompilerObject @object, TargetPlatform? target) => Result.Error( $"Object {@object} does not support compile IR code" ); diff --git a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Definition.cs b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Definition.cs index ef64c9d9..06d4fe47 100644 --- a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Definition.cs +++ b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Definition.cs @@ -8,7 +8,7 @@ public bool CompileDefinition(CompilerObject @object, Owner owner, Target where Owner : IRDefinition => false; - public Result CompileDefinition(CompilerObject @object, object? target) where T : IRDefinition + public IResult CompileDefinition(CompilerObject @object, object? target) where T : IRDefinition => Result.Error( $"Object {@object} does not support compile IR definition of type {typeof(T)}" ); diff --git a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Reference.cs b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Reference.cs index 4b613c88..308c1bd6 100644 --- a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Reference.cs +++ b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Reference.cs @@ -3,7 +3,7 @@ partial class Dispatcher : IIRReferenceCompiler { - public Result CompileReference(CompilerObject @object) where T : class + public IResult CompileReference(CompilerObject @object) where T : class => Result.Error( $"Object {@object} does not support compile IR reference" ); diff --git a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Type.cs b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Type.cs index 4796fcb5..1fc52436 100644 --- a/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Type.cs +++ b/ZSharp.Compiler.IR/dispatcher/services/Dispatcher.Type.cs @@ -3,12 +3,12 @@ partial class Dispatcher : IIRTypeCompiler { - public Result CompileType(CompilerObject @object) + public IResult CompileType(CompilerObject @object) => Result.Error( $"Object {@object} does not support compile IR type" ); - Result IIRTypeCompiler.CompileType(CompilerObject @object) + IResult IIRTypeCompiler.CompileType(CompilerObject @object) => Result.Error( $"Object {@object} does not support compile IR type" ); diff --git a/ZSharp.Compiler.IR/ir/services/IR.Code.cs b/ZSharp.Compiler.IR/ir/services/IR.Code.cs index b6044d94..3de36578 100644 --- a/ZSharp.Compiler.IR/ir/services/IR.Code.cs +++ b/ZSharp.Compiler.IR/ir/services/IR.Code.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler { - public delegate Result CompileIRCode(CompilerObject @object, TargetPlatform? target); + public delegate IResult CompileIRCode(CompilerObject @object, TargetPlatform? target); partial struct IR { diff --git a/ZSharp.Compiler.IR/ir/services/IR.Definition.cs b/ZSharp.Compiler.IR/ir/services/IR.Definition.cs index 3d6f562d..3457b14f 100644 --- a/ZSharp.Compiler.IR/ir/services/IR.Definition.cs +++ b/ZSharp.Compiler.IR/ir/services/IR.Definition.cs @@ -6,7 +6,7 @@ partial struct IR public IIRDefinitionInCompiler DefinitionInCompiler { get; set; } = Dispatcher.Instance; - public Result CompileDefinition(CompilerObject @object, TargetPlatform? target) + public IResult CompileDefinition(CompilerObject @object, TargetPlatform? target) where T : IRDefinition => DefinitionAsCompiler.CompileDefinition(@object, target); diff --git a/ZSharp.Compiler.IR/ir/services/IR.Reference.cs b/ZSharp.Compiler.IR/ir/services/IR.Reference.cs index 9b0f68d3..77ac1a58 100644 --- a/ZSharp.Compiler.IR/ir/services/IR.Reference.cs +++ b/ZSharp.Compiler.IR/ir/services/IR.Reference.cs @@ -4,7 +4,7 @@ partial struct IR { public IIRReferenceCompiler ReferenceCompiler { get; set; } = Dispatcher.Instance; - public Result CompileReference(CompilerObject @object) + public IResult CompileReference(CompilerObject @object) where T : class => ReferenceCompiler.CompileReference(@object); } diff --git a/ZSharp.Compiler.IR/ir/services/IR.Type.cs b/ZSharp.Compiler.IR/ir/services/IR.Type.cs index 4a1523a3..17fab085 100644 --- a/ZSharp.Compiler.IR/ir/services/IR.Type.cs +++ b/ZSharp.Compiler.IR/ir/services/IR.Type.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler { - public delegate Result CompileType(CompilerObject @object); + public delegate IResult CompileType(CompilerObject @object); partial struct IR { @@ -8,7 +8,7 @@ partial struct IR public IIRTypeCompiler TypeCompiler { get; set; } = Dispatcher.Instance; - public Result CompileTypeAs(CompilerObject @object) + public IResult CompileTypeAs(CompilerObject @object) where T : class, IType => TypeCompiler.CompileType(@object); } diff --git a/ZSharp.Compiler.IR/protocols/IIRDefinitionAsCompiler.cs b/ZSharp.Compiler.IR/protocols/IIRDefinitionAsCompiler.cs index 37a0c331..c0718aee 100644 --- a/ZSharp.Compiler.IR/protocols/IIRDefinitionAsCompiler.cs +++ b/ZSharp.Compiler.IR/protocols/IIRDefinitionAsCompiler.cs @@ -2,7 +2,7 @@ { public interface IIRDefinitionAsCompiler { - public Result CompileDefinition(CompilerObject @object, TargetPlatform? target) + public IResult CompileDefinition(CompilerObject @object, TargetPlatform? target) where T : IRDefinition; } } diff --git a/ZSharp.Compiler.IR/protocols/IIRReferenceCompiler.cs b/ZSharp.Compiler.IR/protocols/IIRReferenceCompiler.cs index 20f03a71..552bed51 100644 --- a/ZSharp.Compiler.IR/protocols/IIRReferenceCompiler.cs +++ b/ZSharp.Compiler.IR/protocols/IIRReferenceCompiler.cs @@ -2,7 +2,7 @@ { public interface IIRReferenceCompiler { - public Result CompileReference(CompilerObject @object) + public IResult CompileReference(CompilerObject @object) where T : class; } } diff --git a/ZSharp.Compiler.IR/protocols/IIRTypeCompiler.cs b/ZSharp.Compiler.IR/protocols/IIRTypeCompiler.cs index 871a9e7d..b0eea7a6 100644 --- a/ZSharp.Compiler.IR/protocols/IIRTypeCompiler.cs +++ b/ZSharp.Compiler.IR/protocols/IIRTypeCompiler.cs @@ -2,7 +2,7 @@ { public interface IIRTypeCompiler { - public Result CompileType(CompilerObject @object) + public IResult CompileType(CompilerObject @object) where T : class, IType; } } \ No newline at end of file diff --git a/ZSharp.Compiler.Objects/GlobalUsings.cs b/ZSharp.Compiler.Objects/GlobalUsings.cs deleted file mode 100644 index cccc780d..00000000 --- a/ZSharp.Compiler.Objects/GlobalUsings.cs +++ /dev/null @@ -1,5 +0,0 @@ -global using MemberName = string; -global using MemberIndex = int; - -global using Error = ZSharp.Compiler.Error; -global using CompilerObjectResult = ZSharp.Compiler.Result; diff --git a/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj b/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj deleted file mode 100644 index 04a2cd82..00000000 --- a/ZSharp.Compiler.Objects/ZSharp.Compiler.Objects.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - net9.0 - enable - enable - ZSharp.Objects - - - - - - - - diff --git a/ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs b/ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs deleted file mode 100644 index aba2b1cd..00000000 --- a/ZSharp.Compiler.Objects/callables/ArgumentMismatchException.cs +++ /dev/null @@ -1,12 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public class ArgumentMismatchException(CompilerObject callable, Argument[] arguments, Exception? innerException = null) - : CompilerObjectException(callable, innerException: innerException) - { - public CompilerObject Callable => Object; - - public Argument[] Arguments { get; } = arguments; - } -} diff --git a/ZSharp.Compiler.Objects/contexts/type inference/SimpleInferenceContext.cs b/ZSharp.Compiler.Objects/contexts/type inference/SimpleInferenceContext.cs deleted file mode 100644 index cfd622b3..00000000 --- a/ZSharp.Compiler.Objects/contexts/type inference/SimpleInferenceContext.cs +++ /dev/null @@ -1,16 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public class SimpleInferenceContext(Compiler.Compiler compiler) - : IContext - , ITypeInferenceContext - { - private readonly Compiler.Compiler compiler = compiler; - - IContext? IContext.Parent { get; set; } - - InferredType ITypeInferenceContext.CreateInferredType(IInferredTypeResolver? resolver) - => (this as ITypeInferenceContext).CreateInferredType(compiler, resolver); - } -} diff --git a/ZSharp.Compiler.Objects/contexts/type inference/core/IInferredTypeResolver.cs b/ZSharp.Compiler.Objects/contexts/type inference/core/IInferredTypeResolver.cs deleted file mode 100644 index 51eecadc..00000000 --- a/ZSharp.Compiler.Objects/contexts/type inference/core/IInferredTypeResolver.cs +++ /dev/null @@ -1,9 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public interface IInferredTypeResolver - { - public IType Resolve(Compiler.Compiler compiler, InferredType inferredType); - } -} diff --git a/ZSharp.Compiler.Objects/contexts/type inference/core/ITypeInferenceContext.cs b/ZSharp.Compiler.Objects/contexts/type inference/core/ITypeInferenceContext.cs deleted file mode 100644 index 436b07a4..00000000 --- a/ZSharp.Compiler.Objects/contexts/type inference/core/ITypeInferenceContext.cs +++ /dev/null @@ -1,19 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public interface ITypeInferenceContext - : IContext - { - public InferredType CreateInferredType(IInferredTypeResolver? resolver = null); - - public InferredType CreateInferredType( - Compiler.Compiler compiler, - IInferredTypeResolver? resolver = null - ) - => new(compiler, this) - { - Resolver = resolver ?? new CommonBaseType() - }; - } -} diff --git a/ZSharp.Compiler.Objects/contexts/type inference/core/InferredType.cs b/ZSharp.Compiler.Objects/contexts/type inference/core/InferredType.cs deleted file mode 100644 index c24d441c..00000000 --- a/ZSharp.Compiler.Objects/contexts/type inference/core/InferredType.cs +++ /dev/null @@ -1,43 +0,0 @@ -using CommonZ.Utils; -using System.Diagnostics.CodeAnalysis; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class InferredType - : CompilerObject - , IType - , IImplicitCastFromValue - { - private readonly Compiler.Compiler compiler; - - public ITypeInferenceContext Context { get; } - - public required IInferredTypeResolver Resolver { get; set; } - - public IType? ResolvedType { get; private set; } - - public bool IsResolved => ResolvedType is not null; - - public Collection CollectedTypes { get; set; } = []; - - internal InferredType(Compiler.Compiler compiler, ITypeInferenceContext context) - { - this.compiler = compiler; - Context = context; - } - - [MemberNotNull(nameof(ResolvedType))] - public IType Resolve() - => ResolvedType = Resolver.Resolve(compiler, this); - - CompilerObject IImplicitCastFromValue.ImplicitCastFromValue(Compiler.Compiler compiler, CompilerObject value) - { - if (!compiler.TypeSystem.IsTyped(value, out var type)) - throw new NotImplementedException(); - - CollectedTypes.Add(type); - return this; - } - } -} diff --git a/ZSharp.Compiler.Objects/contexts/type inference/resolvers/CommonBaseType.cs b/ZSharp.Compiler.Objects/contexts/type inference/resolvers/CommonBaseType.cs deleted file mode 100644 index 7ad57210..00000000 --- a/ZSharp.Compiler.Objects/contexts/type inference/resolvers/CommonBaseType.cs +++ /dev/null @@ -1,52 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class CommonBaseType - : IInferredTypeResolver - { - IType IInferredTypeResolver.Resolve(Compiler.Compiler compiler, InferredType inferredType) - { - List<(IClass, int)> classes = []; - - IType? commonBase = null; - int minDepth = int.MaxValue; - - foreach (var type in inferredType.CollectedTypes) - { - if (type is not IClass @class) - { - if (commonBase is not null && !compiler.TypeSystem.AreEqual(commonBase, type)) - throw new(); - commonBase = type; - - continue; - } - - int depth = 0; - - for (; @class.Base is not null; @class = @class.Base) - depth++; - - if (depth < minDepth) - (commonBase, minDepth) = (@class, depth); - - classes.Add((@class, depth)); - } - - if (commonBase is null) - throw new InvalidOperationException(); - - foreach (var (@class, depth) in classes) - { - var @base = @class; - while (depth > minDepth) @base = @base!.Base; - - if (!compiler.TypeSystem.AreEqual(@base!, commonBase)) - throw new InvalidOperationException(); - } - - return commonBase; - } - } -} diff --git a/ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs b/ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs deleted file mode 100644 index b79f4823..00000000 --- a/ZSharp.Compiler.Objects/error messages/Errors.Compilation.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZSharp.Objects -{ - internal static partial class Errors - { - public static string UndefinedGlobalType(string name) - => $"Type of global {name} is not defined"; - - public static string UndefinedReturnType(string name) - => $"Return type of function {(name == string.Empty ? "" : name)} is not defined."; - } -} diff --git a/ZSharp.Compiler.Objects/error messages/Errors.cs b/ZSharp.Compiler.Objects/error messages/Errors.cs deleted file mode 100644 index 1bd0f453..00000000 --- a/ZSharp.Compiler.Objects/error messages/Errors.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Objects -{ - internal static partial class Errors - { - - } -} diff --git a/ZSharp.Compiler.Objects/functional/CTFunction.cs b/ZSharp.Compiler.Objects/functional/CTFunction.cs deleted file mode 100644 index 182e918f..00000000 --- a/ZSharp.Compiler.Objects/functional/CTFunction.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Objects -{ - public abstract class CTFunction(string? name) : Function(name) - { - - } -} diff --git a/ZSharp.Compiler.Objects/functional/Function.cs b/ZSharp.Compiler.Objects/functional/Function.cs deleted file mode 100644 index 0ac3c5cc..00000000 --- a/ZSharp.Compiler.Objects/functional/Function.cs +++ /dev/null @@ -1,22 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - /// - /// Defines the base structure for a function. - /// - /// A function must have a signature. - /// The signature is used to be able to choose an overload at CG. - /// - /// This is abstract because the behavior for calling a function is - /// different for each type of function. - /// - public abstract class Function(string? name) - : CompilerObject - , ICTCallable_Old - { - - - public abstract CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments); - } -} diff --git a/ZSharp.Compiler.Objects/functional/RTFunction.cs b/ZSharp.Compiler.Objects/functional/RTFunction.cs deleted file mode 100644 index 0b121d2b..00000000 --- a/ZSharp.Compiler.Objects/functional/RTFunction.cs +++ /dev/null @@ -1,140 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public class RTFunction(string? name) - : CompilerObject - , ICTCallable_Old - , ICTReadable - , ICompileIRObject - { - [Flags] - enum BuildState - { - None = 0, - Signature = 0b1, - Body = 0b10, - Owner = 0b100, - } - - private readonly ObjectBuildState state = new(); - - public bool IsDefined - { - init - { - if (value) - foreach (var item in Enum.GetValues()) - state[item] = true; - } - } - - public IR.Function? IR { get; set; } - - public string Name { get; set; } = name ?? string.Empty; - - public CompilerObject? Body { get; set; } - - IType ITyped.Type => throw new NotImplementedException(); - - public Signature Signature { get; set; } = new(); - - public IType? ReturnType - { - get => Signature.ReturnType; - set => Signature.ReturnType = value; - } - - CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) - { - return Call(compiler, arguments); - } - - private RawCode Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (ReturnType is null) - throw new PartiallyCompiledObjectException(this, Errors.UndefinedReturnType(Name)); - - var args = (Signature as ISignature).MatchArguments(compiler, arguments); - - IRCode code = new(); - - List @params = []; - - @params.AddRange(Signature.Args); - - if (Signature.VarArgs is not null) - @params.Add(Signature.VarArgs); - - @params.AddRange(Signature.KwArgs); - - if (Signature.VarKwArgs is not null) - @params.Add(Signature.VarKwArgs); - - foreach (var param in @params) - code.Append(compiler.CompileIRCode(args[param])); - - code.Append(new([ - new IR.VM.Call(compiler.CompileIRObject(this, null)) - ])); - - code.Types.Clear(); - if (ReturnType != compiler.TypeSystem.Void) - code.Types.Add(ReturnType); - - return new RawCode(code); - } - - IRCode ICTReadable.Read(Compiler.Compiler compiler) - => new([ - new IR.VM.GetObject(IR!) - ]) - { - Types = [null!], // TODO: fix type - }; - - [MemberNotNull(nameof(ReturnType))] - public IR.Function CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) - { - IR ??= - new( - compiler.CompileIRType( - ReturnType ?? throw new PartiallyCompiledObjectException( - this, - Errors.UndefinedReturnType(Name) - ) - ) - ) - { - Name = Name - }; - - if (ReturnType is null) - throw new PartiallyCompiledObjectException(this, Errors.UndefinedReturnType(Name)); - - if (owner is not null && !state[BuildState.Owner]) - { - state[BuildState.Owner] = true; - - owner.Functions.Add(IR); - } - - if (!state[BuildState.Signature]) - { - state[BuildState.Signature] = true; - - compiler.CompileIRObject(Signature, IR.Signature); - } - - if (Body is not null && !state[BuildState.Body]) - { - state[BuildState.Body] = true; - - IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); - } - - return IR; - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/body/Local.cs b/ZSharp.Compiler.Objects/functional/body/Local.cs deleted file mode 100644 index c1a9ff18..00000000 --- a/ZSharp.Compiler.Objects/functional/body/Local.cs +++ /dev/null @@ -1,97 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Local - : CompilerObject - , ICTAssignable - , ICTReadable - , ICompileIRObject - { - [Flags] - enum BuildState - { - None = 0, - Owner = 0b1, - Initializer = 0b100, - } - - private readonly ObjectBuildState state = new(); - - public IR.VM.Local? IR { get; set; } - - public required string Name { get; set; } - - public bool IsReadOnly { get; set; } - - public IType? Type { get; set; } - - public CompilerObject? Initializer { get; set; } - - public IR.VM.Local CompileIRObject(Compiler.Compiler compiler, IR.ICallableBody? owner) - { - if (Type is null) - throw new PartiallyCompiledObjectException( - this, $"Local variable {Name} does not have a type" - ); - - IR ??= new(Name, compiler.CompileIRType(Type)); - - if (owner is not null && !state[BuildState.Owner]) - { - state[BuildState.Owner] = true; - - owner.Locals.Add(IR); - } - - if (Initializer is not null && !state[BuildState.Initializer]) - { - state[BuildState.Initializer] = true; - - IR.Initializer = [.. - compiler.IR.CompileCode( - compiler.TypeSystem.ImplicitCast(Initializer, Type).Unwrap() - ).Unwrap().Instructions, - new IR.VM.Dup(), - new IR.VM.SetLocal(IR) - ]; - } - - return IR; - } - - public IRCode Read(Compiler.Compiler compiler) - => new([new IR.VM.GetLocal(IR!)]) - { - MaxStackSize = 1, - Types = [Type] - }; - - public CompilerObject Assign(Compiler.Compiler compiler, CompilerObject value) - { - if (IsReadOnly) - throw new(); - - if (Type is null) - if (compiler.TypeSystem.IsTyped(value, out var valueType)) - Type = valueType; - else throw new PartiallyCompiledObjectException(this, $"Local variable {Name} does not have a type"); - - IR ??= CompileIRObject(compiler, null); - - if (!compiler.TypeSystem.ImplicitCast(value, Type).Ok(out var cast)) - throw new Compiler.InvalidCastException(value, Type); - - var code = compiler.CompileIRCode(cast); - - code.Instructions.AddRange( - [ - new IR.VM.Dup(), - new IR.VM.SetLocal(IR) - ] - ); - - return new RawCode(code); - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs b/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs deleted file mode 100644 index 3125e122..00000000 --- a/ZSharp.Compiler.Objects/functional/generic/GenericFunctionInstance_Old.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class GenericFunctionInstance_Old(GenericFunction origin) - : CompilerObject - , ICTCallable_Old - , ICompileIRReference - { - public GenericFunction Origin { get; } = origin; - - public required ReferenceContext Context { get; init; } - - public Signature? Signature { get; set; } - - public IR.Signature? CompiledSignature { get; private set; } - - CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (Origin.ReturnType is null) - throw new NotImplementedException(); - - CompileSignature(compiler); - - var args = (Signature as ISignature).MatchArguments(compiler, arguments); - - IRCode code = new(); - - List @params = []; - - @params.AddRange(Signature.Args); - - if (Signature.VarArgs is not null) - @params.Add(Signature.VarArgs); - - @params.AddRange(Signature.KwArgs); - - if (Signature.VarKwArgs is not null) - @params.Add(Signature.VarKwArgs); - - foreach (var param in @params) - code.Append(compiler.CompileIRCode(args[param])); - - code.Append(new([ - new IR.VM.Call(compiler.CompileIRReference(this)) - ])); - - code.Types.Clear(); - if (Origin.ReturnType != compiler.TypeSystem.Void) - code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); - - return new RawCode(code); - } - - IR.ConstructedFunction ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) - { - var arguments = Origin.GenericParameters - .Select(genericParameter => Context[genericParameter]) - .Select(compiler.CompileIRType); - - CompileSignature(compiler); - - return new(compiler.CompileIRObject(Origin, null)) - { - Arguments = [.. arguments], - Signature = CompiledSignature, - }; - } - - [MemberNotNull(nameof(Signature), nameof(CompiledSignature))] - private void CompileSignature(Compiler.Compiler compiler) - { - Signature ??= compiler.Feature().CreateReference(Origin.Signature, Context); - - if (CompiledSignature is not null) - return; - - if (Origin.ReturnType is null) - throw new NotImplementedException(); - - CompiledSignature = new(compiler.CompileIRType(compiler.Feature().CreateReference(Origin.ReturnType, Context))); - - foreach (var arg in Signature.Args) - CompiledSignature.Args.Parameters.Add(compiler.CompileIRObject(arg, CompiledSignature)); - - if (Signature.VarArgs is not null) - CompiledSignature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, CompiledSignature); - - foreach (var kwArg in Signature.KwArgs) - CompiledSignature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, CompiledSignature)); - - if (Signature.VarKwArgs is not null) - CompiledSignature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, CompiledSignature); - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs deleted file mode 100644 index 86e5b218..00000000 --- a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.Generic.cs +++ /dev/null @@ -1,40 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public partial class GenericFunction - { - public Result CreateGenericInstance(Compiler.Compiler compiler, IType[] arguments) - { - if (arguments.Length != GenericParameters.Count) - return Result.Error( - $"Invalid generic argument count: Expected {GenericParameters.Count}, got {arguments.Length}" - ); - - Mapping genericArguments = []; - foreach (var (parameter, argument) in GenericParameters.Zip(arguments)) - { - if (!parameter.Match(argument)) - return Result.Error( - $"Type {argument} cannot be assigned to generic parameter {parameter.Name}" - ); - - genericArguments[parameter] = argument; - } - - ReferenceContext context = new(); - foreach (var (p, a) in genericArguments) - context.CompileTimeValues.Cache(p, a); - - return Result.Ok( - new() - { - GenericArguments = genericArguments, - GenericFunction = this, - Signature = compiler.Feature().CreateReference(Signature, context) - } - ); - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs b/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs deleted file mode 100644 index 86aa25aa..00000000 --- a/ZSharp.Compiler.Objects/functional/generic/definition/GenericFunction.cs +++ /dev/null @@ -1,167 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed partial class GenericFunction(string? name = null) - : CompilerObject - , ICompileIRObject - , ICTCallable_Old - , ICTGetIndex - , IReferencable - { - [Flags] - enum BuildState - { - None = 0, - Signature = 0b1, - Body = 0b10, - Owner = 0b100, - Generic = 0b1000, - } - - private readonly ObjectBuildState state = new(); - - public bool Defined - { - init - { - if (value) - foreach (var item in Enum.GetValues()) - state[item] = true; - } - } - - public IR.Function? IR { get; set; } - - public string Name { get; set; } = name ?? string.Empty; - - public Collection GenericParameters { get; set; } = []; - - public IType? ReturnType - { - get => Signature.ReturnType; - set => Signature.ReturnType = value; - } - - public Signature Signature { get; set; } = new(); - - public CompilerObject? Body { get; set; } - - IR.Function ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) - { - IR ??= - new( - compiler.CompileIRType( - ReturnType ?? throw new PartiallyCompiledObjectException( - this, - Errors.UndefinedReturnType(Name) - ) - ) - ) - { - Name = Name - }; - - if (owner is not null && !state[BuildState.Owner]) - { - state[BuildState.Owner] = true; - - owner.Functions.Add(IR); - } - - if (!state[BuildState.Generic]) - { - state[BuildState.Generic] = true; - - foreach (var genericParameter in GenericParameters) - IR.GenericParameters.Add(compiler.CompileIRType(genericParameter)); - } - - if (!state[BuildState.Signature]) - { - state[BuildState.Signature] = true; - - foreach (var arg in Signature.Args) - IR.Signature.Args.Parameters.Add(compiler.CompileIRObject(arg, IR.Signature)); - - if (Signature.VarArgs is not null) - IR.Signature.Args.Var = compiler.CompileIRObject(Signature.VarArgs, IR.Signature); - - foreach (var kwArg in Signature.KwArgs) - IR.Signature.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, IR.Signature)); - - if (Signature.VarKwArgs is not null) - IR.Signature.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, IR.Signature); - } - - if (Body is not null && !state[BuildState.Body]) - { - state[BuildState.Body] = true; - - IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); - } - - return IR; - } - - CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) - { - if (index.Length != GenericParameters.Count) - throw new(); - - ReferenceContext context = new(); - - foreach (var (arg, param) in index.Zip(GenericParameters)) - context[param] = arg.Object; - - return compiler.Feature().CreateReference(this, context); - } - - GenericFunctionInstance_Old IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - { - foreach (var genericParameter in GenericParameters) - if (!context.CompileTimeValues.Contains(genericParameter)) - throw new(); - - return new(this) - { - Context = context, - Signature = @ref.CreateReference(Signature, context) - }; - } - - CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) - { - ITypeInferenceContext infer; - - using var _ = compiler.ContextScope(infer = new SimpleInferenceContext(compiler)); - - List inferredTypes = []; - ReferenceContext context = new(); - - foreach (var genericParameter in GenericParameters) - { - var inferredType = infer.CreateInferredType(); - inferredTypes.Add(inferredType); - context.CompileTimeValues.Cache(genericParameter, inferredType); - } - - var reference = compiler.Feature().CreateReference(this, context); - - var args = (reference.Signature as ISignature)!.MatchArguments(compiler, arguments); - - foreach (var genericParameter in GenericParameters) - context.CompileTimeValues.Cache( - genericParameter, - context.CompileTimeValues.Cache(genericParameter)!.Resolve(), - set: true - ); - - return compiler.Call( - compiler.Feature().CreateReference(this, context), - arguments - ); - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs deleted file mode 100644 index f3de373d..00000000 --- a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Call.cs +++ /dev/null @@ -1,50 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - partial class GenericFunctionInstance - : ICTCallable - { - CompilerObjectResult ICTCallable.Call(Compiler.Compiler compiler, Argument_NEW[] arguments) - { - if (ReturnType is null) - return CompilerObjectResult.Error( - "Return type is not defined" - ); - - var args = Signature.MatchArguments( - compiler, - arguments - .Select(arg => new Argument(arg.Name, arg.Value)) - .ToArray() - ); - - IRCode code = new(); - - List @params = []; - - @params.AddRange(Signature.Args); - - if (Signature.VarArgs is not null) - @params.Add(Signature.VarArgs); - - @params.AddRange(Signature.KwArgs); - - if (Signature.VarKwArgs is not null) - @params.Add(Signature.VarKwArgs); - - foreach (var param in @params) - code.Append(compiler.CompileIRCode(args[param])); - - code.Append(new([ - new IR.VM.Call(compiler.CompileIRReference(this)) - ])); - - code.Types.Clear(); - if (ReturnType != compiler.TypeSystem.Void) - code.Types.Add(ReturnType); - - return CompilerObjectResult.Ok(new RawCode(code)); - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Generic.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Generic.cs deleted file mode 100644 index d204545c..00000000 --- a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Generic.cs +++ /dev/null @@ -1,12 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - partial class GenericFunctionInstance - { - public required Mapping GenericArguments { get; init; } - - public required GenericFunction GenericFunction { get; init; } - } -} diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs deleted file mode 100644 index 4ba9e6b5..00000000 --- a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.IR.cs +++ /dev/null @@ -1,27 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - partial class GenericFunctionInstance - : ICompileIRReference - { - IR.ConstructedFunction ICompileIRReference.CompileIRReference(Compiler.Compiler compiler) - { - var argumentResults = GenericFunction.GenericParameters - .Select(p => GenericArguments[p]) - .Select(compiler.IR.CompileType); - - var arguments = argumentResults - .Select(r => r.Unwrap()); - - var functionIR = compiler.IR.CompileDefinition(GenericFunction, null).Unwrap(); - var signatureIR = compiler.IR.CompileDefinition(Signature, functionIR).Unwrap(); - - return new(functionIR) - { - Arguments = [.. arguments], - Signature = signatureIR, - }; - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Signature.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Signature.cs deleted file mode 100644 index 82d1bb23..00000000 --- a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.Signature.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - partial class GenericFunctionInstance - { - public required ISignature Signature { get; init; } - - public IType? ReturnType => Signature.ReturnType; - } -} diff --git a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.cs b/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.cs deleted file mode 100644 index e8f7815e..00000000 --- a/ZSharp.Compiler.Objects/functional/generic/instance/GenericFunctionInstance.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Objects -{ - public sealed partial class GenericFunctionInstance - : CompilerObject - { - } -} diff --git a/ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs b/ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs deleted file mode 100644 index c323f7c5..00000000 --- a/ZSharp.Compiler.Objects/functional/partial call/PartialCall.cs +++ /dev/null @@ -1,119 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class PartialCall(CompilerObject target) - : CompilerObject - , ICTCallable_Old - { - public CompilerObject Target { get; set; } = target; - - public Argument[] Arguments { get; set; } = []; - - public required ISignature Signature { get; set; } - - CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) - { - return compiler.Call(Target, [ - .. Arguments, - .. arguments - ]); - } - - public static PartialCall CreateFrom(Compiler.Compiler compiler, CompilerObject target, ISignature signature, Argument[] arguments) - => new(target) - { - Signature = ApplyArguments(compiler, signature, arguments), - Arguments = arguments - }; - - private static Signature ApplyArguments(Compiler.Compiler compiler, ISignature origin, Argument[] arguments) - { - var (args, kwArgs) = Utils.SplitArguments(arguments); - - return ApplyArguments(compiler, origin, args, kwArgs); - } - - private static Signature ApplyArguments(Compiler.Compiler compiler, ISignature origin, Collection args, Mapping kwArgs) - { - if (args.Count > origin.Args.Count() && origin.VarArgs is null) - throw new ArgumentsCountMismatchException(); - - if (kwArgs.Count > origin.KwArgs.Count() && origin.VarKwArgs is null) - throw new ArgumentsCountMismatchException(); - - List varArgs = []; - if (args.Count > origin.Args.Count()) - varArgs.AddRange(args.Skip(origin.Args.Count())); - args = [.. args.Take(origin.Args.Count())]; - - Signature result = new() - { - ReturnType = origin.ReturnType, - }; - - foreach (var (arg, param) in args.Zip(origin.Args)) - if (!compiler.TypeSystem.IsTyped(arg, out var argumentType)) - throw new ArgumentException("Argument is not typed."); - else if (!compiler.TypeSystem.IsAssignableTo(argumentType, param.Type ?? throw new())) - throw new Compiler.InvalidCastException(arg, param.Type); - - foreach (var param in origin.Args.Skip(args.Count)) - result.Args.Add(new(param.Name) - { - Default = param.Default, - //Initializer = param.Initializer, - Type = param.Type, - }); - - foreach (var varArg in varArgs) - if ( - !compiler.TypeSystem.IsTyped(varArg, out var argumentType) || - !compiler.TypeSystem.IsAssignableTo(argumentType, origin.VarArgs!.Type ?? throw new()) - ) - throw new Compiler.InvalidCastException(varArg, origin.VarArgs!.Type!); - - if (origin.VarArgs is not null) - result.VarArgs = new(origin.VarArgs.Name) - { - Type = origin.VarArgs.Type, - }; - - foreach (var param in origin.KwArgs) - { - if (!kwArgs.Remove(param.Name, out var arg)) - { - result.KwArgs.Add(new(param.Name) - { - Default = param.Default, - //Initializer = param.Initializer, - Type = param.Type, - }); - continue; - } - - if ( - !compiler.TypeSystem.IsTyped(arg, out var argumentType) || - !compiler.TypeSystem.IsAssignableTo(argumentType, param.Type ?? throw new()) - ) - throw new Compiler.InvalidCastException(arg, param.Type!); - } - - foreach (var varKwArg in kwArgs.Values) - if ( - !compiler.TypeSystem.IsTyped(varKwArg, out var argumentType) || - !compiler.TypeSystem.IsAssignableTo(argumentType, origin.VarKwArgs!.Type ?? throw new()) - ) - throw new Compiler.InvalidCastException(varKwArg, origin.VarKwArgs!.Type!); - - if (origin.VarKwArgs is not null) - result.VarKwArgs = new(origin.VarKwArgs.Name) - { - Type = origin.VarKwArgs.Type, - }; - - return result; - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/signature/Parameter.cs b/ZSharp.Compiler.Objects/functional/signature/Parameter.cs deleted file mode 100644 index 9529a5b5..00000000 --- a/ZSharp.Compiler.Objects/functional/signature/Parameter.cs +++ /dev/null @@ -1,64 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Parameter(string name) - : CompilerObject - , ICTReadable - , ICompileIRObject - , IReferencable - , IParameter - { - public IR.Parameter? IR { get; set; } - - public string Name { get; } = name; - - public IType? Type { get; set; } - - public CompilerObject? Initializer { get; set; } - - public CompilerObject? Default - { - get => Initializer; - set => Initializer = value; - } - - public IR.Parameter CompileIRObject(Compiler.Compiler compiler, IR.Signature? owner) - { - if (Type is null) - throw new("Parameter type not set."); - - IR ??= new(Name, compiler.RuntimeModule.TypeSystem.Void); - if (IR.Type == compiler.RuntimeModule.TypeSystem.Void) - IR.Type = compiler.CompileIRType(Type); - - return IR; - } - - public IRCode Read(Compiler.Compiler compiler) - => new([ - new IR.VM.GetArgument(IR ?? compiler.CompileIRObject(this, null)), - ]) - { - MaxStackSize = 1, - Types = [Type ?? throw new()] - }; - - Parameter IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - { - return new(Name) - { - Initializer = Initializer is null ? null : @ref.CreateReference(Initializer, context), - Type = Type is null ? null : @ref.CreateReference(Type, context), - }; - } - - CompilerObjectResult IParameter.MatchArgument(Compiler.Compiler compiler, CompilerObject argument) - { - if (Type is null) - throw new PartiallyCompiledObjectException(this, $"Parameter's {Name} type is not defined"); - - return compiler.TypeSystem.ImplicitCast(argument, Type); - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/signature/Signature.cs b/ZSharp.Compiler.Objects/functional/signature/Signature.cs deleted file mode 100644 index 8df7ca33..00000000 --- a/ZSharp.Compiler.Objects/functional/signature/Signature.cs +++ /dev/null @@ -1,84 +0,0 @@ -using ZSharp.Compiler; -using Parameters = CommonZ.Utils.Collection; - -namespace ZSharp.Objects -{ - public sealed class Signature - : CompilerObject - , ICompileIRObject - , IReferencable - , ISignature - { - public IR.Signature? IR { get; private set; } - - public Parameters Args { get; init; } = []; - - public VarParameter? VarArgs { get; set; } - - public Parameters KwArgs { get; init; } = []; - - public VarParameter? VarKwArgs { get; set; } - - public IType? ReturnType { get; set; } - - IEnumerable ISignature.Args => Args; - - IVarParameter? ISignature.VarArgs => VarArgs; - - IEnumerable ISignature.KwArgs => KwArgs; - - IVarParameter? ISignature.VarKwArgs => VarKwArgs; - - IType ISignature.ReturnType => ReturnType ?? throw new(); - - IR.Signature ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Signature? owner) - { - if (IR is not null) - return IR; - - if (ReturnType is null) - throw new PartiallyCompiledObjectException(this, "ReturnType is not defined"); - - owner ??= new(compiler.CompileIRType(ReturnType)); - - IR = owner; - - foreach (var arg in Args) - IR.Args.Parameters.Add(compiler.CompileIRObject(arg, IR)); - - if (VarArgs is not null) - IR.Args.Var = compiler.CompileIRObject(VarArgs, IR); - - foreach (var kwArg in KwArgs) - IR.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, IR)); - - if (VarKwArgs is not null) - IR.KwArgs.Var = compiler.CompileIRObject(VarKwArgs, IR); - - return IR; - } - - Signature IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - { - if (ReturnType is null) - throw new PartiallyCompiledObjectException(this, "ReturnType is not defined"); - - Signature result = new() - { - ReturnType = @ref.CreateReference(ReturnType, context) - }; - - result.Args.AddRange(Args.Select(arg => @ref.CreateReference(arg, context))); - - if (VarArgs is not null) - result.VarArgs = @ref.CreateReference(VarArgs, context); - - result.KwArgs.AddRange(KwArgs.Select(arg => @ref.CreateReference(arg, context))); - - if (VarKwArgs is not null) - result.VarKwArgs = @ref.CreateReference(VarKwArgs, context); - - return result; - } - } -} diff --git a/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs b/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs deleted file mode 100644 index af630742..00000000 --- a/ZSharp.Compiler.Objects/functional/signature/VarParameter.cs +++ /dev/null @@ -1,20 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Objects -{ - public sealed class VarParameter(string name) - : CompilerObject - , IVarParameter - { - public string Name { get; set; } = name; - - public IR.Parameter? IR { get; set; } - - public Compiler.IType? Type { get; set; } - - CompilerObject IVarParameter.MatchArguments(Compiler.Compiler compiler, Collection arguments) - { - throw new NotImplementedException(); - } - } -} diff --git a/ZSharp.Compiler.Objects/generic/GenericArgument.cs b/ZSharp.Compiler.Objects/generic/GenericArgument.cs deleted file mode 100644 index 64d86b48..00000000 --- a/ZSharp.Compiler.Objects/generic/GenericArgument.cs +++ /dev/null @@ -1,17 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class GenericArgument(IType type) - { - public IType Type { get; set; } = type; - - public string? Name { get; set; } - - public GenericArgument(string name, IType type) - : this(type) - { - Name = name; - } - } -} diff --git a/ZSharp.Compiler.Objects/generic/GenericParameter.cs b/ZSharp.Compiler.Objects/generic/GenericParameter.cs deleted file mode 100644 index c8b79c2c..00000000 --- a/ZSharp.Compiler.Objects/generic/GenericParameter.cs +++ /dev/null @@ -1,24 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class GenericParameter - : CompilerObject - , ICompileIRType - , IReferencable - , IType - { - public string Name { get; set; } = string.Empty; - - public IR.GenericParameter? IR { get; set; } - - public IR.GenericParameter CompileIRType(Compiler.Compiler compiler) - => IR ??= new(Name); - - IType IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - => context.CompileTimeValues.Cache(this, out var result) ? result : this; - - public bool Match(IType type) - => true; - } -} diff --git a/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs b/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs deleted file mode 100644 index a0fb7c1c..00000000 --- a/ZSharp.Compiler.Objects/literals/ArrayLiteral.cs +++ /dev/null @@ -1,45 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class ArrayLiteral(IEnumerable? items = null) - : CompilerObject - , ICTTypeCast - , IImplicitCastToType - { - public List Items { get; } = new(items ?? []); - - CompilerObject ICTTypeCast.Cast(Compiler.Compiler compiler, IType targetType) - { - var instance = compiler.Call(targetType, []); - - var code = new IRCode(compiler.CompileIRCode(instance).Instructions); - - var append = compiler.Member(targetType, "append"); - - foreach (var item in Items) - code.Instructions.AddRange( - compiler.CompileIRCode( - compiler.Call(append, [ - new(new RawCode(new([ - new IR.VM.Dup() - ]) - { - Types = [targetType] - }) - ), - new(item) - ]) - ).Instructions - ); - - code.Types.Clear(); - code.Types.Add(targetType); - - return new RawCode(code); - } - - CompilerObject IImplicitCastToType.ImplicitCastToType(Compiler.Compiler compiler, IType type) - => compiler.Cast(this, type); - } -} diff --git a/ZSharp.Compiler.Objects/modular/Global.cs b/ZSharp.Compiler.Objects/modular/Global.cs deleted file mode 100644 index 578708a4..00000000 --- a/ZSharp.Compiler.Objects/modular/Global.cs +++ /dev/null @@ -1,113 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Global(string name) - : CompilerObject - , ICTAssignable - , ICTReadable - , ICompileIRObject - { - #region Build State - - [Flags] - enum BuildState - { - None = 0, - Owner = 0b1, - Initializer = 0b10, - } - - private readonly ObjectBuildState state = new(); - - public bool IsDefined - { - init - { - if (value) - foreach (var item in Enum.GetValues()) - state[item] = true; - } - } - - #endregion - - public IR.Global? IR { get; set; } - - public string Name { get; } = name; - - public bool IsReadOnly { get; set; } - - public CompilerObject? Initializer { get; set; } - - public IType? Type { get; set; } - - #region Protocols - - public IR.Global CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) - { - if (Type is null) - throw new PartiallyCompiledObjectException( - this, - Errors.UndefinedGlobalType(Name) - ); - - IR ??= new(Name, compiler.CompileIRType(Type)); - - if (owner is not null && !state[BuildState.Owner]) - { - state[BuildState.Owner] = true; - - owner.Globals.Add(IR!); - } - - if (Initializer is not null && !state[BuildState.Initializer]) - { - state[BuildState.Initializer] = true; - - if (!compiler.TypeSystem.ImplicitCast(Initializer, Type).Ok(out var initializer)) - throw new Compiler.InvalidCastException(Initializer, Type); - - IR.Initializer = [.. compiler.CompileIRCode(initializer).Instructions]; - } - - return IR; - } - - public IRCode Read(Compiler.Compiler compiler) - => new([new IR.VM.GetGlobal(IR!)]) - { - MaxStackSize = 1, - Types = [Type], - }; - - public CompilerObject Assign(Compiler.Compiler compiler, CompilerObject value) - { - if (IsReadOnly) - throw new(); - - if (Type is null) - throw new(); - - IR = compiler.CompileIRObject(this, null); - - if (!compiler.TypeSystem.ImplicitCast(value, Type).Ok(out var cast)) - throw new Compiler.InvalidCastException(value, Type); - - var code = compiler.CompileIRCode(cast); - - code.Instructions.AddRange( - [ - new IR.VM.Dup(), - new IR.VM.SetGlobal(IR), - ] - ); - - code.RequireValueType(); - - return new RawCode(code); - } - - #endregion - } -} diff --git a/ZSharp.Compiler.Objects/modular/Module.cs b/ZSharp.Compiler.Objects/modular/Module.cs deleted file mode 100644 index 9de728d3..00000000 --- a/ZSharp.Compiler.Objects/modular/Module.cs +++ /dev/null @@ -1,69 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Module(string name) - : CompilerObject - , ICompileIRObject - , ICTGetMember_Old - , ICTReadable - { - IType ITyped.Type => throw new NotImplementedException(); - - public Collection Content { get; } = []; - - public Mapping Members { get; } = []; - - public Collection ImportedMembers { get; } = []; - - public IR.Module? IR { get; set; } - - //public RTFunction InitFunction { get; } = new(null); - - public string? Name { get; set; } = name; - - public CompilerObject Member(Compiler.Compiler compiler, string member) - => Members[member]; - - IRCode ICTReadable.Read(Compiler.Compiler compiler) - => new([ - new IR.VM.GetObject(IR!) - ]) - { - Types = [null!], // TODO: fix type - }; - - public IR.Module CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) - { - if (IR is not null) - return IR; - - IR = new(Name); - - foreach (var item in Content) - compiler.CompileIRObject(item, IR); - - if (IR.HasGlobals) - { - // TODO: initialize according to dependency order - - var initializer = IR.Initializer = new(compiler.RuntimeModule.TypeSystem.Void) - { - Name = "" - }; - - foreach (var global in IR.Globals) - if (global.Initializer is not null) - initializer.Body.Instructions.AddRange([ - .. global.Initializer, - new IR.VM.SetGlobal(global), - ]); - - initializer.Body.Instructions.Add(new IR.VM.Return()); - } - - return IR; - } - } -} diff --git a/ZSharp.Compiler.Objects/nullable/Nullable.cs b/ZSharp.Compiler.Objects/nullable/Nullable.cs deleted file mode 100644 index 6ff4a6ac..00000000 --- a/ZSharp.Compiler.Objects/nullable/Nullable.cs +++ /dev/null @@ -1,104 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Nullable(IType underlyingType) - : CompilerObject - , IRTCastFrom - , IRTCastTo - , IType - { - public IType UnderlyingType { get; set; } = underlyingType; - - bool IType.IsEqualTo(Compiler.Compiler compiler, IType other) - { - if (other is not Nullable nullable) return false; - return compiler.TypeSystem.AreEqual(UnderlyingType, nullable.UnderlyingType); - } - - Result IRTCastFrom.Cast(Compiler.Compiler compiler, CompilerObject value) - { - var innerCastResult = compiler.CG.Cast(value, UnderlyingType); - - TypeCast innerCast; - - if (innerCastResult.Error(out var error)) - return Result.Error(error); - else innerCast = innerCastResult.Unwrap(); - - var innerCastCodeResult = compiler.IR.CompileCode(innerCast.Cast); - - IRCode innerCastCode; - - if (innerCastCodeResult.Error(out error)) - return Result.Error(error); - else innerCastCode = innerCastCodeResult.Unwrap(); - - IR.VM.Nop onCast = new(); - - return Result.Ok( - new() - { - Cast = new RawCode(new([ - .. innerCastCode.Instructions, - new IR.VM.Jump(onCast), - .. (IR.VM.Instruction[])(innerCast.CanFail ? [ - innerCast.OnFail, - new IR.VM.PutNull(), - ] : []), - onCast, - ]) - { - Types = [this] - } - ), - } - ); - } - - Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObject value, IType targetType) - { - if (targetType is not Nullable nullable) - return Result.Error( - "Nullable types can only be cast to other nullable types" - ); - - var innerCastResult = compiler.CG.Cast(value, nullable.UnderlyingType); - - TypeCast innerCast; - - if (innerCastResult.Error(out var error)) - return Result.Error(error); - else innerCast = innerCastResult.Unwrap(); - - var innerCastCodeResult = compiler.IR.CompileCode(innerCast.Cast); - - IRCode innerCastCode; - - if (innerCastCodeResult.Error(out error)) - return Result.Error(error); - else innerCastCode = innerCastCodeResult.Unwrap(); - - IR.VM.Nop onCast = new(); - - return Result.Ok( - new() - { - Cast = new RawCode(new([ - .. innerCastCode.Instructions, - new IR.VM.Jump(onCast), - .. (IR.VM.Instruction[])(innerCast.CanFail ? [ - innerCast.OnFail, - new IR.VM.PutNull(), - ] : []), - onCast, - ]) - { - Types = [targetType] - } - ), - } - ); - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/Implementation.cs b/ZSharp.Compiler.Objects/oop/Implementation.cs deleted file mode 100644 index 620eb518..00000000 --- a/ZSharp.Compiler.Objects/oop/Implementation.cs +++ /dev/null @@ -1,16 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Objects -{ - public sealed class Implementation( - IAbstraction @abstract, - CompilerObject concrete - ) - { - public Mapping Mapping { get; } = []; - - public IAbstraction Abstract { get; } = @abstract; - - public CompilerObject Concrete { get; } = concrete; - } -} diff --git a/ZSharp.Compiler.Objects/oop/abstraction/IAbstraction.cs b/ZSharp.Compiler.Objects/oop/abstraction/IAbstraction.cs deleted file mode 100644 index bcd3897f..00000000 --- a/ZSharp.Compiler.Objects/oop/abstraction/IAbstraction.cs +++ /dev/null @@ -1,10 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Objects -{ - public interface IAbstraction - : CompilerObject - { - public Collection Specifications { get; } - } -} diff --git a/ZSharp.Compiler.Objects/oop/class/Class.cs b/ZSharp.Compiler.Objects/oop/class/Class.cs deleted file mode 100644 index a8a1da4e..00000000 --- a/ZSharp.Compiler.Objects/oop/class/Class.cs +++ /dev/null @@ -1,268 +0,0 @@ -using CommonZ; -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Class - : CompilerObject - , IClass - , ICompileIRObject - , IIRReferenceCompiler - , ICompileIRType> - , ICTCallable_Old - , IRTCastTo - , ICTGetMember_Old - , IRTGetMember_Old - , IRTTypeMatch - , IImplementsAbstraction - , IType - , ITypeAssignableToType - { - #region Build State - - [Flags] - enum BuildState - { - None = 0, - Base = 0b1, - Interfaces = 0b10, - Body = 0b100, - Owner = 0b1000, - } - private readonly ObjectBuildState state = new(); - - public bool IsDefined - { - init - { - if (value) - foreach (var item in Enum.GetValues()) - state[item] = true; - } - } - - #endregion - - public IR.Class? IR { get; set; } - - public string? Name { get; set; } - - public IClass? Base { get; set; } - - public CompilerObject? Constructor { get; set; } - - public Collection Interfaces { get; } = []; - - public Collection InterfaceImplementations { get; } = []; - - public Collection Content { get; } = []; - - public Mapping Members { get; } = []; - - #region Protocols - - IR.Class ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) - { - IR ??= new(Name); - - if (owner is not null && !state[BuildState.Owner]) - { - state[BuildState.Owner] = true; - - owner.Types.Add(IR); - } - - if (Base is not null && !state[BuildState.Base]) - { - state[BuildState.Base] = true; - - IR.Base = compiler.CompileIRReference>(Base); - } - - if (Content.Count > 0 && !state[BuildState.Body]) - { - state[BuildState.Body] = true; - - foreach (var item in Content) - compiler.CompileIRObject(item, IR); - } - - if (InterfaceImplementations.Count > 0 && !state[BuildState.Interfaces]) - { - state[BuildState.Interfaces] = true; - - foreach (var @interfaceImplementation in InterfaceImplementations) - { - IR.InterfaceImplementation implementation = new( - compiler.CompileIRReference>(interfaceImplementation.Abstract) - ); - - IR.InterfacesImplementations.Add(implementation); - - foreach (var (@abstract, concrete) in interfaceImplementation.Mapping) - { - var abstractMethod = compiler.CompileIRReference(@abstract); - var concreteMethod = compiler.CompileIRObject(concrete, IR); - implementation.Implementations.Add(abstractMethod, concreteMethod); - } - } - } - - return IR; - } - - CompilerObject ICTGetMember_Old.Member(Compiler.Compiler compiler, string member) - => Members[member]; - - CompilerObject IRTGetMember_Old.Member(Compiler.Compiler compiler, CompilerObject instance, string member) - { - return compiler.Map(Members[member], @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, instance) : @object); - } - - IR.TypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) - { - return new IR.ClassReference(compiler.CompileIRObject(this, null)); - } - - IR.ClassReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) - { - return new IR.ClassReference(compiler.CompileIRObject(this, null)); - } - - - CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (Constructor is null) - throw new InvalidOperationException($"Class {Name} is not constructible"); - - return compiler.Call(Constructor, arguments); - } - - bool? ITypeAssignableToType.IsAssignableTo(Compiler.Compiler compiler, IType target) - { - if (Base is not null && compiler.TypeSystem.IsAssignableTo(Base, target)) - return true; - - foreach (var @interface in Interfaces) - { - if (compiler.TypeSystem.IsAssignableTo(@interface, target)) - return true; - } - - return null; - } - - Result IRTTypeMatch.Match(Compiler.Compiler compiler, CompilerObject value, IType type) - { - var nullableType = new Nullable(type); - var castToTypeResult = compiler.CG.Cast(value, nullableType); - - TypeCast castToType; - - if (castToTypeResult.Error(out var error)) - return Result.Error(error); - else castToType = castToTypeResult.Unwrap(); - - var castToTypeCodeResult = compiler.IR.CompileCode(castToType.Cast); - - IRCode castToTypeCode; - - if (castToTypeCodeResult.Error(out error)) - return Result.Error(error); - else castToTypeCode = castToTypeCodeResult.Unwrap(); - - IR.VM.Nop onMatch = new(); - - return Result.Ok(new() - { - Match = new RawCode(new([ - .. castToTypeCode.Instructions, - new IR.VM.Dup(), - new IR.VM.IsNotNull(), - new IR.VM.JumpIfTrue(onMatch), - ]) - { - Types = [castToTypeCode.RequireValueType()] - }), - OnMatch = onMatch - }); - } - - Result IRTCastTo.Cast(Compiler.Compiler compiler, CompilerObject value, IType targetType) - { - if (targetType is not Class targetClass) - return Result.Error( - "Casting class to non-class object is not supported yet" - ); - - if (IsSubclassOf(targetClass)) - return Result.Ok( - new() - { - Cast = value, - } - ); - - var valueCodeResult = compiler.IR.CompileCode(value); - - IRCode valueCode; - - if (valueCodeResult.Error(out var error)) - return Result.Error(error); - else valueCode = valueCodeResult.Unwrap(); - - if (targetClass.IsSubclassOf(this)) - { - var targetClassIRResult = - compiler.IR.CompileReference>(targetClass); - - IR.TypeReference targetClassIR; - - if (targetClassIRResult.Error(out error)) - return Result.Error(error); - else targetClassIR = targetClassIRResult.Unwrap(); - - IR.VM.Nop onCast = new(); - IR.VM.Nop onFail = new(); - - return Result.Ok( - new() - { - Cast = new RawCode(new([ - .. valueCode.Instructions, - new IR.VM.CastReference(targetClassIR), - new IR.VM.Dup(), - new IR.VM.IsNotNull(), - new IR.VM.JumpIfTrue(onCast), - new IR.VM.Pop(), - new IR.VM.Jump(onFail), - onCast, - ]) - { - Types = [targetType] - }), - OnFail = onFail, - } - ); - } - - return Result.Error( - "Object does not support type cast to the specified type" - ); - } - - #endregion - - public bool IsSubclassOf(Class @base) - { - for ( - IType? current = Base; - current is Class baseClass; - current = baseClass.Base - ) - if (current == @base) return true; - return false; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs b/ZSharp.Compiler.Objects/oop/class/GenericClass.cs deleted file mode 100644 index d17c1bad..00000000 --- a/ZSharp.Compiler.Objects/oop/class/GenericClass.cs +++ /dev/null @@ -1,174 +0,0 @@ -using CommonZ.Utils; -using System; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public class GenericClass - : CompilerObject - , ICTGetIndex - , ICTGetMember_Old - , IRTGetMember_Old - , IReferencable - , ICompileIRObject - , IEvaluable - , IGenericInstantiable - { - [Flags] - enum BuildState - { - None = 0, - Base = 0b1, - Interfaces = 0b10, - Body = 0b100, - Owner = 0b1000, - Generic = 0b10000, - } - private readonly ObjectBuildState state = new(); - - public IR.ConstructedClass? IR { get; set; } - - public string Name { get; set; } = string.Empty; - - public bool Defined { init - { - if (value) - { - foreach (var item in Enum.GetValues()) - state[item] = true; - } - } - } - - public Collection GenericParameters { get; set; } = []; - - public IClass? Base { get; set; } - - public Mapping Implementations { get; set; } = []; - - public CompilerObject Constructor { get; set; } - - public Collection Content { get; } = []; - - public Mapping Members { get; } = []; - - public CompilerObject Member(Compiler.Compiler compiler, MemberName member) - => Members[member]; - - public GenericClassInstance CreateReference(Referencing @ref, ReferenceContext context) - { - int currentErrors = @ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error); - - foreach (var genericParameter in GenericParameters) - if (!context.CompileTimeValues.Contains(genericParameter)) - @ref.Compiler.Log.Error( - $"Missing generic argument for parameter {genericParameter.Name} in type {Name}", - this - ); - - if (@ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error) > currentErrors) - throw new(); // TODO: Huh??? - - return new GenericClassInstance(this, new(context) - { - Scope = this - }); - } - - CompilerObjectResult IGenericInstantiable.Instantiate(Compiler.Compiler compiler, Argument[] arguments) - { - var context = new ReferenceContext(); - - foreach (var (genericParameter, genericArgument) in GenericParameters.Zip(arguments)) - context[genericParameter] = genericArgument.Object; - - return CompilerObjectResult.Ok(new GenericClassInstance(this, new(context) - { - Scope = this - })); - } - - CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) - { - var context = new ReferenceContext(); - - foreach (var (genericParameter, genericArgument) in GenericParameters.Zip(index)) - context[genericParameter] = genericArgument.Object; - - return compiler.Feature().CreateReference(this, context); - } - - IR.Class ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) - { - IR.Class @class = IR?.Class ?? new(Name); - - IR ??= new(@class); - - if (owner is not null && !state.Get(BuildState.Owner)) - { - owner.Types.Add(@class!); - - state.Set(BuildState.Owner); - } - - if (Base is not null && !state.Get(BuildState.Base)) - { - state.Set(BuildState.Base); - - @class.Base = compiler.CompileIRType>(Base); - } - - if (Content.Count > 0 && !state.Get(BuildState.Body)) - { - state.Set(BuildState.Body); - - foreach (var item in Content) - compiler.CompileIRObject(item, @class); - } - - if (GenericParameters.Count > 0 && !state.Get(BuildState.Generic)) - { - state.Set(BuildState.Generic); - foreach (var parameter in GenericParameters) - @class.GenericParameters.Add( - compiler.CompileIRType(parameter) - ); - } - - return @class; - } - - CompilerObject IEvaluable.Evaluate(Compiler.Compiler compiler) - { - if (GenericParameters.Count != 0) - return this; - - return new GenericClassInstance(this, new() - { - Scope = this - }); - } - - CompilerObject IRTGetMember_Old.Member(Compiler.Compiler compiler, CompilerObject value, string member) - { - if (GenericParameters.Count > 0) - throw new InvalidOperationException(); - - var memberObject = compiler.Member(this, member); - - if (memberObject is IRTBoundMember boundMember) - return boundMember.Bind(compiler, value); - - if (memberObject is OverloadGroup group) - return new OverloadGroup(group.Name) - { - Overloads = [.. group.Overloads.Select( - overload => overload is IRTBoundMember boundMember ? - boundMember.Bind(compiler, value) : overload - )], - }; - - return memberObject; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs b/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs deleted file mode 100644 index 31147cf5..00000000 --- a/ZSharp.Compiler.Objects/oop/class/GenericClassInstance.cs +++ /dev/null @@ -1,150 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class GenericClassInstance - : CompilerObject - , IClass - , ICTGetMember_Old - , IRTGetMember_Old - , ICTCallable_Old - , IReference - , ICompileIRType - , IIRReferenceCompiler> - , IIRReferenceCompiler - , IReferencable - , IType - { - CompilerObject IReference.Origin => Origin; - - public ReferenceContext Context { get; set; } - - public GenericClass Origin { get; set; } - - public Mapping GenericArguments { get; } = []; - - public string Name - { - get => Origin.Name; - set => Origin.Name = value; - } - - public IClass? Base - { - get => throw new NotImplementedException(); - set => throw new NotImplementedException(); - } - - public Mapping Members { get; set; } = []; - - #region Constructors - - public GenericClassInstance(GenericClass origin, ReferenceContext context) - { - Context = context; - Origin = origin; - - foreach (var genricParameter in origin.GenericParameters) - GenericArguments[genricParameter] = Context[genricParameter]; - } - - #endregion - - public CompilerObject Member(Compiler.Compiler compiler, string member) - { - if (Members.ContainsKey(member)) return Members[member]; - - var origin = compiler.Member(Origin, member); - - if (Origin.GenericParameters.Count != 0) - origin = compiler.Map(origin, @object => compiler.Feature().CreateReference(@object, Context)); - - return Members[member] = origin; - } - - public CompilerObject Member(Compiler.Compiler compiler, CompilerObject instance, string member) - { - if (Members.ContainsKey(member)) - return compiler.Map(Members[member], @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, instance) : @object); - - var origin = compiler.Member(Origin, member); - - Members[member] = origin = compiler.Map(origin, @object => compiler.Feature().CreateReference(@object, Context)); - - return compiler.Map(origin, @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, instance) : @object); - } - - IR.ConstructedClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) - { - var result = new IR.ConstructedClass( - compiler.CompileIRObject(Origin, null) - ); - - foreach (var parameter in Origin.GenericParameters) - result.Arguments.Add( - compiler.CompileIRType( - Context.CompileTimeValues.Cache(GenericArguments[parameter]) ?? GenericArguments[parameter] - ) - ); - - return result; - } - - CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) - { - CompilerObject? constructor = null; - - //if (Origin.GenericParameters.Count == 0) - constructor = Origin.Constructor; - - if (constructor is null) - throw new NotImplementedException(); - - var @ref = compiler.Feature(); - - if (Context is not null) - constructor = compiler.Map(constructor, @object => @ref.CreateReference(@object, Context)); - - return compiler.Call(constructor, arguments); - } - - IR.TypeReference IIRReferenceCompiler>.CompileIRReference(Compiler.Compiler compiler) - => compiler.CompileIRType(this); - - GenericClassInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - { - context = new(context) - { - Scope = this - }; - - foreach (var (key, value) in GenericArguments) - context.CompileTimeValues.Cache(key, context.CompileTimeValues.Cache(value) ?? value); - - return new(Origin, context); - } - - bool IType.IsEqualTo(Compiler.Compiler compiler, IType type) - { - if (type is not GenericClassInstance other) - return false; - - if (Origin != other.Origin) - return false; - - foreach (var genericParameter in Origin.GenericParameters) - if (GenericArguments[genericParameter] is not IType thisGenericArgument) - throw new Compiler.InvalidCastException(GenericArguments[genericParameter], compiler.TypeSystem.Type); - else if (other.GenericArguments[genericParameter] is not IType otherGenericArgument) - throw new Compiler.InvalidCastException(other.GenericArguments[genericParameter], compiler.TypeSystem.Type); - else if (!compiler.TypeSystem.AreEqual(thisGenericArgument, otherGenericArgument)) - return false; - - return true; - } - - IR.TypeReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) - => compiler.CompileIRType(this); - } -} diff --git a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs b/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs deleted file mode 100644 index 2583e529..00000000 --- a/ZSharp.Compiler.Objects/oop/constructor/Constructor.cs +++ /dev/null @@ -1,157 +0,0 @@ -using ZSharp.Compiler; - -using Args = CommonZ.Utils.Collection; -using KwArgs = CommonZ.Utils.Mapping; - - -namespace ZSharp.Objects -{ - public sealed class Constructor(string? name) - : CompilerObject - , ICTCallable_Old - , ICompileIRObject - , IReferencable - { - [Flags] - enum BuildState - { - None = 0, - Signature = 0b1, - Body = 0b10, - Owner = 0b100, - } - - private readonly ObjectBuildState state = new(); - - public IR.Constructor? IR { get; set; } - - public string? Name { get; set; } = name; - - public Signature Signature { get; set; } = new(); - - public IType? Owner { get; set; } - - public CompilerObject? Body { get; set; } - - public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) - { - var (args, kwArgs) = Utils.SplitArguments(arguments); - - return Call(compiler, args, kwArgs); - } - - public CompilerObject Call(Compiler.Compiler compiler, Args args, KwArgs kwArgs) - { - // TODO: type checking (when type system is implemented) - - IR.VM.Instruction invocationInstruction; - - bool isNewInstance = false; - if (kwArgs.TryGetValue(Signature.Args[0].Name, out var thisArgument)) - { - invocationInstruction = new IR.VM.Call(IR!.Method); - kwArgs.Remove(Signature.Args[0].Name); - args.Insert(0, thisArgument); - } - else - { - var type = Owner ?? Signature.Args[0].Type; - - isNewInstance = true; - - invocationInstruction = new IR.VM.CreateInstance(new IR.ConstructorReference(IR!) - { - OwningType = (IR?.Method.Owner is null - ? IR!.Method.Signature.Args.Parameters[0].Type as IR.TypeReference - : new IR.ClassReference(IR!.Method.Owner as IR.Class ?? throw new())) - ?? throw new() - }); - args.Insert(0, new RawCode(new() - { - Types = [type] - })); - } - - IRCode - argsCode = new(), varArgsCode = new(), - kwArgsCode = new(), varKwArgsCode = new(); - - if (args.Count > Signature.Args.Count) - if (Signature.VarArgs is null) - throw new($"Function {Name} takes {Signature.Args.Count} arguments, but {args.Count} were given."); - else - throw new NotImplementedException("var args"); - else if (args.Count < Signature.Args.Count) - throw new($"Function {Name} takes {Signature.Args.Count} arguments, but {args.Count} were given."); - - for (int i = 0; i < Signature.Args.Count; i++) - argsCode.Append(compiler.CompileIRCode(args[i])); - - if (kwArgs.Count > Signature.KwArgs.Count) - if (Signature.VarKwArgs is null) - throw new($"Function {Name} takes {Signature.KwArgs.Count} keyword arguments, but {kwArgs.Count} were given."); - else - throw new NotImplementedException("var kwargs"); - else if (kwArgs.Count < Signature.KwArgs.Count) - throw new($"Function {Name} takes {Signature.KwArgs.Count} keyword arguments, but {kwArgs.Count} were given."); - - foreach (var kwArgParameter in Signature.KwArgs) - kwArgsCode.Append(compiler.CompileIRCode(kwArgs[kwArgParameter.Name])); - - IRCode result = new(); - result.Append(argsCode); - result.Append(varArgsCode); // should be empty - result.Append(kwArgsCode); - result.Append(varKwArgsCode); // should be empty - - result.Instructions.Add(invocationInstruction); - - result.Types.Clear(); - if (isNewInstance) - result.Types.Add(Owner ?? Signature.Args[0].Type); - - result.MaxStackSize = Math.Max(result.MaxStackSize, result.Types.Count); - - return new RawCode(result); - } - - IR.Constructor ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) - { - IR ??= new(Name) - { - Method = new(compiler.RuntimeModule.TypeSystem.Void) - }; - - Signature.ReturnType ??= compiler.TypeSystem.Void; - - if (owner is not null && !state.Get(BuildState.Owner)) - { - owner.Constructors.Add(IR); - owner.Methods.Add(IR.Method); - - state.Set(BuildState.Owner); - } - - if (!state[BuildState.Signature]) - { - state[BuildState.Signature] = true; - - compiler.CompileIRObject(Signature, IR.Method.Signature); - } - - if (Body is not null && !state.Get(BuildState.Body)) - { - IR.Method.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); - - state.Set(BuildState.Body); - } - - return IR; - } - - ConstructorReference IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - { - return new(this, context); - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs b/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs deleted file mode 100644 index 536dd30d..00000000 --- a/ZSharp.Compiler.Objects/oop/constructor/ConstructorReference.cs +++ /dev/null @@ -1,43 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class ConstructorReference(Constructor origin, ReferenceContext context) - : CompilerObject - , ICTCallable_Old - { - public Constructor Origin { get; } = origin; - - public ReferenceContext Context { get; } = context; - - CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) - { - var result = compiler.Call(Origin, arguments); - - if (result is not RawCode rawCode) - throw new(); - - var owner = Origin.Owner; - if (owner is null) - throw new(); - - var ownerReference = compiler.Feature().CreateReference(owner, Context); - - var invocationInstruction = rawCode.Code.Instructions.Last(); - if (invocationInstruction is IR.VM.CreateInstance createInstance) - { - var type = compiler.CompileIRReference>(ownerReference); - - createInstance.Constructor = new IR.ConstructorReference(createInstance.Constructor.Constructor) - { - OwningType = type - }; - - rawCode.Code.Types.Clear(); - rawCode.Code.Types.Add(ownerReference); - } - - return rawCode; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/enum/EnumClass.cs b/ZSharp.Compiler.Objects/oop/enum/EnumClass.cs deleted file mode 100644 index 7eb024b0..00000000 --- a/ZSharp.Compiler.Objects/oop/enum/EnumClass.cs +++ /dev/null @@ -1,107 +0,0 @@ -using CommonZ; -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class EnumClass(string? name) - : CompilerObject - , IType - , ICTGetMember - , ITypeAssignableToType - , ICompileIRObject - , ICompileIRType - { - #region Build State - - [Flags] - enum BuildState - { - None = 0, - Values = 0b1, - Owner = 0b10, - } - private readonly ObjectBuildState state = new(); - - public bool IsDefined - { - init - { - if (value) - foreach (var item in Enum.GetValues()) - state[item] = true; - } - } - - #endregion - - public IR.EnumClass? IR { get; set; } - - public string? Name { get; set; } = name; - - public IType? MemberType { get; set; } - - public Mapping Values { get; } = []; - - IR.EnumClass ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) - { - if (MemberType is null) - throw new InvalidOperationException(); - - IR ??= new(Name); - - if (IR.Type is null) - { - var underlyingType = compiler.IR.CompileType(MemberType).Unwrap(); - - IR.Type = underlyingType; - } - - if (!state[BuildState.Owner] && owner is not null) - { - state[BuildState.Owner] = true; - - owner.Types.Add(IR); - } - - if (!state[BuildState.Values]) - { - state[BuildState.Values] = true; - - foreach (var value in Values.Values) - compiler.IR.CompileDefinition(value, IR); - } - - return IR; - } - - CompilerObjectResult ICTGetMember.Member(Compiler.Compiler compiler, string member) - { - if (Values.TryGetValue(member, out var value)) - return CompilerObjectResult.Ok(value); - - return CompilerObjectResult.Error( - $"Could not find member {member} in {Name ?? ""}" - ); - } - - IR.EnumClass ICompileIRType.CompileIRType(Compiler.Compiler compiler) - { - return - compiler.IR.CompileDefinition - - (this, null) - .Unwrap(); - } - - bool? ITypeAssignableToType.IsAssignableTo(Compiler.Compiler compiler, IType target) - { - if (compiler.TypeSystem.AreEqual(this, target)) - return true; - if (compiler.TypeSystem.AreEqual(MemberType!, target)) - return true; - - return null; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/enum/EnumValue.cs b/ZSharp.Compiler.Objects/oop/enum/EnumValue.cs deleted file mode 100644 index 435fc82a..00000000 --- a/ZSharp.Compiler.Objects/oop/enum/EnumValue.cs +++ /dev/null @@ -1,72 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class EnumValue(string name) - : CompilerObject - , ICTGet - , IDynamicallyTyped - , IIRCodeCompiler - , ICompileIRObject - { - #region Build State - - [Flags] - enum BuildState - { - None = 0, - Owner = 0b1, - } - private readonly ObjectBuildState state = new(); - - public bool IsDefined - { - init - { - if (value) - foreach (var item in Enum.GetValues()) - state[item] = true; - } - } - - #endregion - - public IR.EnumValue? IR { get; set; } - - public string Name { get; set; } = name; - - public required EnumClass Owner { get; set; } - - public required CompilerObject Value { get; set; } - - IR.EnumValue ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.EnumClass? owner) - { - if (IR is null) - { - var code = compiler.IR.CompileCode(Value).Unwrap(); - - IR = new(Name, code.Instructions); - } - - if (!state[BuildState.Owner] && owner is not null) - { - state[BuildState.Owner] = true; - - owner.Values.Add(IR); - } - - return IR; - } - - CompilerObjectResult ICTGet.Get(Compiler.Compiler compiler) - => compiler.CG.Get(Value); - - IType IDynamicallyTyped.GetType(Compiler.Compiler compiler) - => compiler.TypeSystem.IsTyped(Value, out var type) - ? type - : throw new(); - - IRCode IIRCodeCompiler.CompileIRCode(Compiler.Compiler compiler) - => compiler.CompileIRCode(Value); - } -} diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IDerivableAbstraction.cs b/ZSharp.Compiler.Objects/oop/extensibility/IDerivableAbstraction.cs deleted file mode 100644 index 26c1144a..00000000 --- a/ZSharp.Compiler.Objects/oop/extensibility/IDerivableAbstraction.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IDerivableAbstraction - { - public virtual void OnDerivation(CompilerObject derived) { } - - public virtual void OnImplementation(CompilerObject implementor) { } - } -} diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IImplementation.cs b/ZSharp.Compiler.Objects/oop/extensibility/IImplementation.cs deleted file mode 100644 index 64a2a769..00000000 --- a/ZSharp.Compiler.Objects/oop/extensibility/IImplementation.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace ZSharp.Objects -{ - public interface IImplementation - : CompilerObject - { - public bool Implements(Compiler.Compiler compiler, CompilerObject specification, [NotNullWhen(true)] out IImplementsSpecification? implementation); - } -} diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IImplementsAbstraction.cs b/ZSharp.Compiler.Objects/oop/extensibility/IImplementsAbstraction.cs deleted file mode 100644 index 4f070655..00000000 --- a/ZSharp.Compiler.Objects/oop/extensibility/IImplementsAbstraction.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IImplementsAbstraction - : CompilerObject - { - public Implementation ImplementAbstraction(Compiler.Compiler compiler, IAbstraction abstraction, Implementation? result = null) - { - result ??= new(abstraction, this); - - foreach (var specification in abstraction.Specifications) - { - if (result.Mapping.ContainsKey(specification)) - continue; - - if (!compiler.NameOf(specification, out var specificationName)) - continue; // this is actually invalid but ok - - var member = compiler.Member(this, specificationName); - - if (member is not IImplementation implementationCandidate) - throw new("Not implemented!"); // TODO: on implementation missing - - if (!implementationCandidate.Implements(compiler, specification, out var implementation)) - throw new("Not implemented"); // TODO: on implementation missing - - result.Mapping.Add(specification, implementation); - implementation.OnImplementSpecification(compiler, abstraction, specification); - } - - return result; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs b/ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs deleted file mode 100644 index 82d86d5f..00000000 --- a/ZSharp.Compiler.Objects/oop/extensibility/IImplementsSpecification.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IImplementsSpecification - : CompilerObject - { - public virtual void OnImplementSpecification(Compiler.Compiler compiler, IAbstraction abstraction, CompilerObject specification) { } - } -} diff --git a/ZSharp.Compiler.Objects/oop/field/BoundField.cs b/ZSharp.Compiler.Objects/oop/field/BoundField.cs deleted file mode 100644 index 65d290e4..00000000 --- a/ZSharp.Compiler.Objects/oop/field/BoundField.cs +++ /dev/null @@ -1,54 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class BoundField(Field field, CompilerObject instance) - : CompilerObject - , ICTAssignable - , ICTReadable - { - public Field Field { get; } = field; - - public CompilerObject Instance { get; } = instance; - - public IType? Type => Field.Type; - - public CompilerObject Assign(Compiler.Compiler compiler, CompilerObject value) - { - var instanceCode = compiler.CompileIRCode(Instance); - var valueCode = compiler.CompileIRCode(value); - - return new RawCode(new([ - ..instanceCode.Instructions, - new IR.VM.Dup(), - ..valueCode.Instructions, - new IR.VM.SetField(new IR.FieldReference(Field.IR!) { - OwningType = new IR.ClassReference(Field.IR!.Owner ?? throw new()) - }), - new IR.VM.GetField(new IR.FieldReference(Field.IR!) { - OwningType = new IR.ClassReference(Field.IR!.Owner ?? throw new()) - }), - ]) - { - MaxStackSize = Math.Max(Math.Max(instanceCode.MaxStackSize, valueCode.MaxStackSize), 2), - Types = [Type] - }); - } - - public IRCode Read(Compiler.Compiler compiler) - { - var code = compiler.CompileIRCode(Instance); - - return new([ - ..code.Instructions, - new IR.VM.GetField(new IR.FieldReference(Field.IR!) { - OwningType = new IR.ClassReference(Field.IR!.Owner ?? throw new()) - }) - ]) - { - MaxStackSize = Math.Max(code.MaxStackSize, 1), - Types = [Type] - }; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/field/Field.cs b/ZSharp.Compiler.Objects/oop/field/Field.cs deleted file mode 100644 index 11936a35..00000000 --- a/ZSharp.Compiler.Objects/oop/field/Field.cs +++ /dev/null @@ -1,46 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Field(string name) - : CompilerObject - , ICTReadable - , IRTBoundMember - , ICompileIRObject - { - public IR.Field? IR { get; set; } - - public string Name { get; set; } = name; - - public CompilerObject? Initializer { get; set; } - - public IType? Type { get; set; } - - public bool IsReadOnly { get; set; } - - public CompilerObject Bind(Compiler.Compiler compiler, CompilerObject value) - => new BoundField(this, value); - - public IRCode Read(Compiler.Compiler compiler) - { - throw new NotImplementedException(); - } - - IR.Field ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) - { - if (IR is not null) - { - if (owner is not null && IR.Owner is null) - owner.Fields.Add(IR); - - return IR; - } - - IR = new(Name, compiler.CompileIRType(Type ?? throw new())); - - owner?.Fields.Add(IR); - - return IR; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/interface/Interface.cs b/ZSharp.Compiler.Objects/oop/interface/Interface.cs deleted file mode 100644 index 3e564bd6..00000000 --- a/ZSharp.Compiler.Objects/oop/interface/Interface.cs +++ /dev/null @@ -1,103 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class Interface(string? name) - : CompilerObject - , IAbstraction - , ICompileIRObject - , IIRReferenceCompiler> - , ICompileIRType> - , ICTGetMember_Old - , IRTGetMember_Old - , IType - { - #region Build State - - [Flags] - enum BuildState - { - None = 0b0, - Owner = 0b1, - Bases = 0b10, - Body = 0b100, - } - - private readonly ObjectBuildState state = new(); - - public bool IsDefined - { - init - { - if (value) - foreach (var item in Enum.GetValues()) - state[item] = true; - } - } - - #endregion - - public IR.Interface? IR { get; set; } - - public string Name { get; set; } = name ?? string.Empty; - - public Collection Bases { get; } = []; - - public Collection Content { get; } = []; - - public Mapping Members = []; - - #region Protocols - - Collection IAbstraction.Specifications => Content; - - CompilerObject ICTGetMember_Old.Member(Compiler.Compiler compiler, string member) - => Members[member]; - - CompilerObject IRTGetMember_Old.Member(Compiler.Compiler compiler, CompilerObject value, string member) - => compiler.Map(Members[member], @object => @object is IRTBoundMember bindable ? bindable.Bind(compiler, value) : @object); - - IR.Interface ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Module? owner) - { - IR ??= new(Name); - - if (owner is not null && !state[BuildState.Owner]) - { - state[BuildState.Owner] = true; - - owner.Types.Add(IR); - } - - if (!state[BuildState.Bases]) - { - state[BuildState.Bases] = true; - - foreach (var @base in Bases) - IR.Bases.Add(compiler.CompileIRReference>(@base)); - } - - if (!state[BuildState.Body]) - { - state[BuildState.Body] = true; - - foreach (var item in Content) - compiler.CompileIRObject(item, IR); - } - - return IR; - } - - IR.TypeReference IIRReferenceCompiler>.CompileIRReference(Compiler.Compiler compiler) - => new IR.InterfaceReference( - compiler.CompileIRObject(this, null) - ); - - IR.TypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) - => new IR.InterfaceReference( - compiler.CompileIRObject(this, null) - ); - - #endregion - } -} diff --git a/ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs b/ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs deleted file mode 100644 index 8c579cc5..00000000 --- a/ZSharp.Compiler.Objects/oop/meta/ClassMetaClass.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Xml.Linq; - -namespace ZSharp.Objects -{ - public sealed class ClassMetaClass - : CompilerObject - { - public GenericClass CreateClass(Compiler.Compiler compiler) - { - return new(); - } - - public void ConstructClass( - Compiler.Compiler compiler, - GenericClass @class, - ClassSpec spec - ) - { - @class.Name = spec.Name; - @class.Content.AddRange(spec.Content); - - var bases = spec.Bases; - - if (bases.Length > 0) - { - int interfacesIndex = 0; - if (bases[0] is IClass) - @class.Base = (IClass)bases[interfacesIndex++]; - - //for (; interfacesIndex < bases.Length; interfacesIndex++) - // if (bases[interfacesIndex] is not IAbstraction @abstract) - // throw new(); - // else Implementations[bases[interfacesIndex]] = new(@abstract, this); - } - - - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/meta/ClassSpec.cs b/ZSharp.Compiler.Objects/oop/meta/ClassSpec.cs deleted file mode 100644 index f71c8bbd..00000000 --- a/ZSharp.Compiler.Objects/oop/meta/ClassSpec.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ZSharp.Objects -{ - public sealed class ClassSpec - : CompilerObject - { - public string Name { get; set; } = string.Empty; - - public CompilerObject[] Bases { get; set; } = []; - - public CompilerObject[] Content { get; set; } = []; - } -} diff --git a/ZSharp.Compiler.Objects/oop/meta/ClassSpecBuilder.cs b/ZSharp.Compiler.Objects/oop/meta/ClassSpecBuilder.cs deleted file mode 100644 index 5c72914b..00000000 --- a/ZSharp.Compiler.Objects/oop/meta/ClassSpecBuilder.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace ZSharp.Objects -{ - public sealed class ClassSpecBuilder - : CompilerObject - { - public string Name { get; set; } = string.Empty; - - public List Bases { get; } = []; - - public List Content { get; } = []; - - public ClassSpec CreateSpec() - => new() - { - Name = Name, - Bases = [.. Bases], - Content = [.. Content], - }; - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/IMethod.cs b/ZSharp.Compiler.Objects/oop/method/IMethod.cs deleted file mode 100644 index 508d71e5..00000000 --- a/ZSharp.Compiler.Objects/oop/method/IMethod.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZSharp.Objects -{ - public interface IMethod - : CompilerObject - , Compiler.INamedObject - { - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/MethodType.cs b/ZSharp.Compiler.Objects/oop/method/MethodType.cs deleted file mode 100644 index fd9281c9..00000000 --- a/ZSharp.Compiler.Objects/oop/method/MethodType.cs +++ /dev/null @@ -1,22 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class MethodType(Signature signature, IType returnType) - : CompilerObject - , ISignature - { - public Signature Signature { get; } = signature; - - IEnumerable ISignature.Args => Signature.Args; - - IVarParameter? ISignature.VarArgs => Signature.VarArgs; - - IEnumerable ISignature.KwArgs => Signature.KwArgs; - - IVarParameter? ISignature.VarKwArgs => Signature.VarKwArgs; - - IType ISignature.ReturnType => Signature.ReturnType; - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/BoundMethod.cs b/ZSharp.Compiler.Objects/oop/method/concrete/BoundMethod.cs deleted file mode 100644 index b9492143..00000000 --- a/ZSharp.Compiler.Objects/oop/method/concrete/BoundMethod.cs +++ /dev/null @@ -1,16 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - internal sealed class BoundMethod(Method method, CompilerObject instance) - : CompilerObject - , ICTCallable_Old - { - public Method Method { get; } = method; - - public CompilerObject Instance { get; } = instance; - - public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) - => compiler.Call(Method, [new(Instance), .. arguments]); - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs b/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs deleted file mode 100644 index fa313d8a..00000000 --- a/ZSharp.Compiler.Objects/oop/method/concrete/Method.cs +++ /dev/null @@ -1,240 +0,0 @@ -using CommonZ.Utils; -using System.Diagnostics.CodeAnalysis; -using ZSharp.Compiler; - -using Args = CommonZ.Utils.Collection; -using KwArgs = CommonZ.Utils.Mapping; - - -namespace ZSharp.Objects -{ - public sealed class Method(string? name) - : CompilerObject - , IRTBoundMember - , IMethod - , ICTCallable_Old - , ICompileIRObject - , ICompileIRObject - , IIRReferenceCompiler - , IImplementation - , IImplementsSpecification - , IImplicitCastToType - , IReferencable - , ITyped - { - [Flags] - enum BuildState - { - None = 0, - Signature = 0b1, - Body = 0b10, - Owner = 0b100, - } - - private readonly ObjectBuildState state = new(); - - public bool Defined { init - { - if (value) - foreach (var item in Enum.GetValues()) - state[item] = true; - } - } - - public IR.Method? IR { get; set; } - - public string Name { get; set; } = name ?? string.Empty; - - public CompilerObject Owner { get; set; } - - public Signature Signature { get; set; } = new(); - - public IType? ReturnType - { - get => Signature.ReturnType; - set => Signature.ReturnType = value; - } - - public CompilerObject? Body { get; set; } - - public Collection<(IAbstraction, CompilerObject)> Specifications { get; } = []; - - IType ITyped.Type - { - get - { - if (ReturnType is null) - throw new InvalidOperationException(); - - return new MethodType(Signature, ReturnType); - } - } - - public CompilerObject Bind(Compiler.Compiler compiler, CompilerObject value) - => new BoundMethod(this, value); - - public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (ReturnType is null) - throw new PartiallyCompiledObjectException(this, Errors.UndefinedReturnType(Name)); - - var args = (Signature as ISignature).MatchArguments(compiler, arguments); - - IRCode code = new(); - - List @params = []; - - @params.AddRange(Signature.Args); - - if (Signature.VarArgs is not null) - @params.Add(Signature.VarArgs); - - @params.AddRange(Signature.KwArgs); - - if (Signature.VarKwArgs is not null) - @params.Add(Signature.VarKwArgs); - - foreach (var param in @params) - code.Append(compiler.CompileIRCode(args[param])); - - var ir = compiler.CompileIRReference(this); - - code.Append(new([ - IR.IsVirtual - ? new IR.VM.CallVirtual(ir) - : new IR.VM.Call(ir) - ])); - - code.Types.Clear(); - if (ReturnType != compiler.TypeSystem.Void) - code.Types.Add(ReturnType); - - return new RawCode(code); - } - - [MemberNotNull(nameof(ReturnType))] - public IR.Method CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) - { - CompileIR(compiler); - - if (owner is not null && !state[BuildState.Owner]) - { - state[BuildState.Owner] = true; - - owner.Methods.Add(IR); - } - - CompileDefinition(compiler); - - ReturnType ??= null!; - - return IR; - } - - MethodReference IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - { - if (context.Scope is not GenericClassInstance genericClassInstance) - genericClassInstance = (GenericClassInstance)@ref.CreateReference(context.Scope, context); - - return new(this, context) - { - Owner = genericClassInstance, - //ReturnType = ReturnType is null ? null : @ref.CreateReference(ReturnType, context), - Signature = @ref.CreateReference(Signature, context), - }; - } - - IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.TypeDefinition? owner) - { - CompileIR(compiler); - - CompileDefinition(compiler); - - return IR; - } - - IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) - { - throw new NotImplementedException(); - } - - public override string ToString() - => $""}>"; - - CompilerObject IImplicitCastToType.ImplicitCastToType(Compiler.Compiler compiler, IType type) - { - if (type is not ISignature callableType) - throw new Compiler.InvalidCastException(this, type); - - throw new Compiler.InvalidCastException(this, type); - } - - IR.MethodReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) - => new( - compiler.CompileIRObject(this, null) - ) - { - OwningType = compiler.CompileIRType(Owner) - }; - - void IImplementsSpecification.OnImplementSpecification(Compiler.Compiler compiler, IAbstraction abstraction, CompilerObject specification) - => Specifications.Add((abstraction, specification)); - - [MemberNotNull(nameof(IR))] - private IR.Method CompileIR(Compiler.Compiler compiler) - { - return IR ??= - new( - compiler.CompileIRType( - ReturnType ?? throw new PartiallyCompiledObjectException( - this, - Errors.UndefinedReturnType(Name) - ) - ) - ) - { - Name = Name, - IsInstance = true, - IsVirtual = Specifications.Count > 0, - }; - } - - private void CompileDefinition(Compiler.Compiler compiler) - { - if (IR is null) - throw new InvalidOperationException(); - - if (!state[BuildState.Signature]) - { - state[BuildState.Signature] = true; - - compiler.CompileIRObject(Signature, IR.Signature); - } - - if (Body is not null && !state[BuildState.Body]) - { - state[BuildState.Body] = true; - - IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); - } - } - - bool IImplementation.Implements(Compiler.Compiler compiler, CompilerObject specification, [NotNullWhen(true)] out IImplementsSpecification? implementation) - { - implementation = null; - - if (!compiler.TypeSystem.IsTyped(specification, out var specificationType)) - return (implementation = null) is not null; - - var args = (Argument[])[new Argument(new TypedUndefined(Signature.Args[0].Type ?? throw new()))]; // TODO: owner - var specificationPartial = PartialCall.CreateFrom(compiler, specification, specificationType, args); - var implementationPartial = PartialCall.CreateFrom(compiler, this, Signature, args); - - if (!compiler.TypeSystem.AreEqual(specificationPartial.Signature, implementationPartial.Signature)) - return false; - - implementation = this; - return true; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs b/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs deleted file mode 100644 index 161ba6d9..00000000 --- a/ZSharp.Compiler.Objects/oop/method/concrete/MethodReference.cs +++ /dev/null @@ -1,99 +0,0 @@ -using ZSharp.Compiler; - -using Args = CommonZ.Utils.Collection; -using KwArgs = CommonZ.Utils.Mapping; - - -namespace ZSharp.Objects -{ - public sealed class MethodReference(Method origin, ReferenceContext context) - : CompilerObject - , ICTCallable_Old - , IIRReferenceCompiler - , IRTBoundMember - { - public Method Origin { get; } = origin; - - public ReferenceContext Context { get; } = context; - - public required CompilerObject Owner { get; init; } - - public required Signature Signature { get; init; } - - public IR.Signature? SignatureIR { get; private set; } - - CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (Origin.ReturnType is null) - throw new NotImplementedException(); - - var args = (Signature as ISignature).MatchArguments(compiler, arguments); - - IRCode code = new(); - - List @params = []; - - @params.AddRange(Signature.Args); - - if (Signature.VarArgs is not null) - @params.Add(Signature.VarArgs); - - @params.AddRange(Signature.KwArgs); - - if (Signature.VarKwArgs is not null) - @params.Add(Signature.VarKwArgs); - - foreach (var param in @params) - code.Append(compiler.CompileIRCode(args[param])); - - code.Append(new([ - new IR.VM.Call(compiler.CompileIRReference(this)) - ])); - - code.Types.Clear(); - if (Origin.ReturnType != compiler.TypeSystem.Void) - code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); - - return new RawCode(code); - } - - IR.MethodReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) - { - var type = compiler.Feature().CreateReference(Owner, Context); - - return new IR.MethodReference(compiler.CompileIRObject(Origin, null!)) - { - OwningType = compiler.CompileIRReference(type), - Signature = SignatureIR ?? CompileSignature(compiler) - }; - } - - CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) - => PartialCall.CreateFrom(compiler, this, Signature, [new(value)]); - - private IR.Signature CompileSignature(Compiler.Compiler compiler) - { - if (SignatureIR is not null) - return SignatureIR; - - if (Origin.ReturnType is null) - throw new NotImplementedException(); - - SignatureIR = new(compiler.CompileIRType(compiler.Feature().CreateReference(Origin.ReturnType, Context))); - - foreach (var arg in Signature.Args) - SignatureIR.Args.Parameters.Add(compiler.CompileIRObject(arg, SignatureIR)); - - if (Signature.VarArgs is not null) - SignatureIR.Args.Var = compiler.CompileIRObject(Signature.VarArgs, SignatureIR); - - foreach (var kwArg in Signature.KwArgs) - SignatureIR.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, SignatureIR)); - - if (Signature.VarKwArgs is not null) - SignatureIR.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, SignatureIR); - - return SignatureIR; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs deleted file mode 100644 index c79bcc01..00000000 --- a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethod.cs +++ /dev/null @@ -1,42 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class BoundGenericMethod(GenericMethod method, CompilerObject instance) - : CompilerObject - , ICTCallable_Old - , ICTGetIndex - , IReferencable - { - public GenericMethod Method { get; } = method; - - public CompilerObject Instance { get; } = instance; - - public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) - => compiler.Call(Method, [new(Instance), .. arguments]); - - #region Index - - CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) - { - var context = new ReferenceContext(); - - foreach (var (genericParameter, genericArgument) in Method.GenericParameters.Zip(index)) - context[genericParameter] = genericArgument.Object; - - return compiler.Feature().CreateReference(this, context); - } - - #endregion - - #region Reference - - BoundGenericMethodInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - => new( - @ref.CreateReference(Method, context), - Instance - ); - - #endregion - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs deleted file mode 100644 index 4fd56010..00000000 --- a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodInstance.cs +++ /dev/null @@ -1,16 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class BoundGenericMethodInstance(GenericMethodInstance method, CompilerObject instance) - : CompilerObject - , ICTCallable_Old - { - public GenericMethodInstance Method { get; } = method; - - public CompilerObject Instance { get; } = instance; - - public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) - => compiler.Call(Method, [new(Instance), .. arguments]); - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs b/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs deleted file mode 100644 index c1fc6866..00000000 --- a/ZSharp.Compiler.Objects/oop/method/generic/BoundGenericMethodReference.cs +++ /dev/null @@ -1,16 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class BoundGenericMethodReference(GenericMethodReference method, CompilerObject instance) - : CompilerObject - , ICTCallable_Old - { - public GenericMethodReference Method { get; } = method; - - public CompilerObject Instance { get; } = instance; - - public CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) - => compiler.Call(Method, [new(Instance), .. arguments]); - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs deleted file mode 100644 index d00f9607..00000000 --- a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethod.cs +++ /dev/null @@ -1,189 +0,0 @@ -using CommonZ.Utils; -using System.Diagnostics.CodeAnalysis; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class GenericMethod(string? name) - : CompilerObject - , ICompileIRObject - , ICompileIRObject - , ICTGetIndex - , INamedObject - , IReferencable - , IRTBoundMember - { - #region Build State - - [Flags] - enum BuildState - { - None = 0, - Signature = 0b1, - Body = 0b10, - Owner = 0b100, - Generic = 0b1000, - } - - private readonly ObjectBuildState state = new(); - - public bool Defined - { - init - { - if (value) - foreach (var item in Enum.GetValues()) - state[item] = true; - } - } - - #endregion - - #region Definition - - public string Name { get; set; } = name ?? string.Empty; - - public Collection GenericParameters { get; set; } = []; - - public Signature Signature { get; set; } = new(); - - public CompilerObject? Owner { get; set; } - - public IType? ReturnType - { - get => Signature.ReturnType; - set => Signature.ReturnType = value; - } - - public CompilerObject? Body { get; set; } - - #endregion - - #region IR - - public IR.Method? IR { get; set; } - - IR.IRDefinition ICompileIRObject.CompileIRObject(Compiler.Compiler compiler) - => CompileIR(compiler); - - IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.Class? owner) - { - CompileIR(compiler); - - if (owner is not null && !state[BuildState.Owner]) - { - state[BuildState.Owner] = true; - - owner.Methods.Add(IR); - } - - CompileDefinition(compiler); - - return IR; - } - - IR.Method ICompileIRObject.CompileIRObject(Compiler.Compiler compiler, IR.TypeDefinition? owner) - { - CompileIR(compiler); - - CompileDefinition(compiler); - - return IR; - } - - [MemberNotNull(nameof(IR))] - private IR.Method CompileIR(Compiler.Compiler compiler) - { - return IR ??= - new( - compiler.CompileIRType( - ReturnType ?? throw new PartiallyCompiledObjectException( - this, - Errors.UndefinedReturnType(Name) - ) - ) - ) - { - Name = Name - }; - } - - private void CompileDefinition(Compiler.Compiler compiler) - { - if (IR is null) - throw new InvalidOperationException(); - - if (!state[BuildState.Generic]) - { - state[BuildState.Generic] = true; - - foreach (var genericParameter in GenericParameters) - IR.GenericParameters.Add( - compiler.CompileIRType(genericParameter) - ); - } - - if (!state[BuildState.Signature]) - { - state[BuildState.Signature] = true; - - compiler.CompileIRObject(Signature, IR.Signature); - } - - if (Body is not null && !state[BuildState.Body]) - { - state[BuildState.Body] = true; - - IR.Body.Instructions.AddRange(compiler.CompileIRCode(Body).Instructions); - } - } - - #endregion - - #region Index - - CompilerObject ICTGetIndex.Index(Compiler.Compiler compiler, Argument[] index) - { - var context = new ReferenceContext(); - - foreach (var (genericParameter, genericArgument) in GenericParameters.Zip(index)) - context[genericParameter] = genericArgument.Object; - - return compiler.Feature().CreateReference(this, context); - } - - #endregion - - #region Reference - - GenericMethodInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - { - int currentErrors = @ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error); - - foreach (var genericParameter in GenericParameters) - if (!context.CompileTimeValues.Contains(genericParameter)) - @ref.Compiler.Log.Error( - $"Missing generic argument for parameter {genericParameter.Name} in type {Name}", - this - ); - - if (@ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error) > currentErrors) - throw new(); // TODO: Huh??? - - return new GenericMethodInstance(this) - { - Context = new(context) - { - Scope = this - }, - Signature = @ref.CreateReference(Signature, context), - Owner = Owner ?? Signature.Args.First()?.Type ?? throw new() - }; - } - - CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) - => new BoundGenericMethod(this, value); - - #endregion - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs deleted file mode 100644 index 1cd18501..00000000 --- a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstance.cs +++ /dev/null @@ -1,73 +0,0 @@ -using ZSharp.Compiler; -namespace ZSharp.Objects -{ - public sealed class GenericMethodInstance(GenericMethod origin) - : CompilerObject - , ICTCallable_Old - , IIRReferenceCompiler - , IRTBoundMember - { - public GenericMethod Origin { get; } = origin; - - public required ReferenceContext Context { get; init; } - - public required CompilerObject Owner { get; init; } - - public required Signature Signature { get; init; } - - CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) - => new BoundGenericMethodInstance(this, value); - - CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (Origin.ReturnType is null) - throw new NotImplementedException(); - - var args = (Signature as ISignature).MatchArguments(compiler, arguments); - - IRCode code = new(); - - List @params = []; - - @params.AddRange(Signature.Args); - - if (Signature.VarArgs is not null) - @params.Add(Signature.VarArgs); - - @params.AddRange(Signature.KwArgs); - - if (Signature.VarKwArgs is not null) - @params.Add(Signature.VarKwArgs); - - foreach (var param in @params) - code.Append(compiler.CompileIRCode(args[param])); - - code.Append(new([ - new IR.VM.Call(compiler.CompileIRReference(this)) - ])); - - code.Types.Clear(); - if (Origin.ReturnType != compiler.TypeSystem.Void) - code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); - - return new RawCode(code); - } - - IR.ConstructedMethod IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) - { - var result = new IR.ConstructedMethod( - compiler.CompileIRObject(Origin, null) - ) - { - OwningType = compiler.CompileIRReference(Owner) - }; - - foreach (var genericParameter in Origin.GenericParameters) - result.Arguments.Add( - compiler.CompileIRType(Context.CompileTimeValues.Cache(genericParameter) ?? throw new()) - ); - - return result; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstanceReference.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstanceReference.cs deleted file mode 100644 index 38b3d264..00000000 --- a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodInstanceReference.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace ZSharp.Objects -{ - public sealed class GenericMethodInstanceReference - { - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs b/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs deleted file mode 100644 index fd21de27..00000000 --- a/ZSharp.Compiler.Objects/oop/method/generic/GenericMethodReference.cs +++ /dev/null @@ -1,128 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class GenericMethodReference( - GenericMethod origin, - ReferenceContext context - ) - : CompilerObject - , ICTCallable_Old - , IIRReferenceCompiler - , IReferencable - , IRTBoundMember - { - public GenericMethod Origin { get; } = origin; - - public ReferenceContext Context { get; } = context; - - public required CompilerObject Owner { get; init; } - - public required Signature Signature { get; init; } - - public IR.Signature? SignatureIR { get; private set; } - - CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) - { - if (Origin.ReturnType is null) - throw new NotImplementedException(); - - var args = (Signature as ISignature).MatchArguments(compiler, arguments); - - IRCode code = new(); - - List @params = []; - - @params.AddRange(Signature.Args); - - if (Signature.VarArgs is not null) - @params.Add(Signature.VarArgs); - - @params.AddRange(Signature.KwArgs); - - if (Signature.VarKwArgs is not null) - @params.Add(Signature.VarKwArgs); - - foreach (var param in @params) - code.Append(compiler.CompileIRCode(args[param])); - - code.Append(new([ - new IR.VM.Call(compiler.CompileIRReference(this)) - ])); - - code.Types.Clear(); - if (Origin.ReturnType != compiler.TypeSystem.Void) - code.Types.Add(compiler.Feature().CreateReference(Origin.ReturnType, Context)); - - return new RawCode(code); - } - - IR.MethodReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) - { - var type = compiler.Feature().CreateReference(Owner, Context); - - return new IR.MethodReference(compiler.CompileIRObject(Origin, null!)) - { - OwningType = compiler.CompileIRReference(type), - Signature = SignatureIR ?? CompileSignature(compiler) - }; - } - - CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) - => new BoundGenericMethodReference(this, value); - - private IR.Signature CompileSignature(Compiler.Compiler compiler) - { - if (SignatureIR is not null) - return SignatureIR; - - if (Origin.ReturnType is null) - throw new NotImplementedException(); - - SignatureIR = new(compiler.CompileIRType(compiler.Feature().CreateReference(Origin.ReturnType, Context))); - - foreach (var arg in Signature.Args) - SignatureIR.Args.Parameters.Add(compiler.CompileIRObject(arg, SignatureIR)); - - if (Signature.VarArgs is not null) - SignatureIR.Args.Var = compiler.CompileIRObject(Signature.VarArgs, SignatureIR); - - foreach (var kwArg in Signature.KwArgs) - SignatureIR.KwArgs.Parameters.Add(compiler.CompileIRObject(kwArg, SignatureIR)); - - if (Signature.VarKwArgs is not null) - SignatureIR.KwArgs.Var = compiler.CompileIRObject(Signature.VarKwArgs, SignatureIR); - - return SignatureIR; - } - - #region Reference - - GenericMethodInstance IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - { - int currentErrors = @ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error); - - foreach (var genericParameter in Origin.GenericParameters) - if (!context.CompileTimeValues.Contains(genericParameter)) - @ref.Compiler.Log.Error( - $"Missing generic argument for parameter {genericParameter.Name} in type {Origin.Name}", - this - ); - - if (@ref.Compiler.Log.Logs.Count(l => l.Level == LogLevel.Error) > currentErrors) - throw new(); // TODO: Huh??? - - return new GenericMethodInstance(Origin) - { - Context = new(context) - { - Scope = this - }, - Signature = @ref.CreateReference(Signature, context), - Owner = Owner ?? Signature.Args.First()?.Type ?? throw new() - }; - } - - #endregion - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs b/ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs deleted file mode 100644 index 3bc37182..00000000 --- a/ZSharp.Compiler.Objects/oop/method/group/BoundMethodOverloadGroup.cs +++ /dev/null @@ -1,19 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class BoundMethodOverloadGroup(MethodOverloadGroup group, CompilerObject instance) - : CompilerObject - , ICTCallable_Old - { - public MethodOverloadGroup Group { get; } = group; - - public CompilerObject Instance { get; } = instance; - - CompilerObject ICTCallable_Old.Call(Compiler.Compiler compiler, Argument[] arguments) - => compiler.Call(Group, [ - new(Instance), - .. arguments - ]); - } -} diff --git a/ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs b/ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs deleted file mode 100644 index 33f0133c..00000000 --- a/ZSharp.Compiler.Objects/oop/method/group/MethodOverloadGroup.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class MethodOverloadGroup(string name) - : OverloadGroup(name) - , CompilerObject - , ICTCallable_Old - , IImplementation - , IRTBoundMember - { - CompilerObject IRTBoundMember.Bind(Compiler.Compiler compiler, CompilerObject value) - => new BoundMethodOverloadGroup(this, value); // TODO: check that the value is a valid instance - - bool IImplementation.Implements(Compiler.Compiler compiler, CompilerObject specification, [NotNullWhen(true)] out IImplementsSpecification? implementation) - { - List implementations = []; - - foreach (var method in Overloads) - if (method is IImplementation implements && implements.Implements(compiler, specification, out var methodImplementation)) - implementations.Add(methodImplementation); - - if (implementations.Count == 1) - return (implementation = implementations[0]) is not null; - - return (implementation = null) is not null; - } - } -} diff --git a/ZSharp.Compiler.Objects/oop/value type/ValueType.cs b/ZSharp.Compiler.Objects/oop/value type/ValueType.cs deleted file mode 100644 index 7fe45395..00000000 --- a/ZSharp.Compiler.Objects/oop/value type/ValueType.cs +++ /dev/null @@ -1,54 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class ValueType(string? name) - : CompilerObject - , IType - , IIRReferenceCompiler - , ICompileIRType> - { - #region Build State - - [Flags] - enum BuildState - { - None = 0, - } - private readonly ObjectBuildState state = new(); - - public bool IsDefined - { - init - { - if (value) - foreach (var item in Enum.GetValues()) - state[item] = true; - } - } - - #endregion - - public IR.ValueType? IR { get; set; } - - public string? Name { get; set; } = name; - - private IR.ValueType CompileIR(Compiler.Compiler compiler) - { - IR ??= new(Name); - - return IR; - } - - private IR.ValueTypeReference CompileIRReference(Compiler.Compiler compiler) - { - return new(CompileIR(compiler)); - } - - IR.TypeReference ICompileIRType>.CompileIRType(Compiler.Compiler compiler) - => CompileIRReference(compiler); - - IR.ValueTypeReference IIRReferenceCompiler.CompileIRReference(Compiler.Compiler compiler) - => CompileIRReference(compiler); - } -} diff --git a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs b/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs deleted file mode 100644 index cfdbebe8..00000000 --- a/ZSharp.Compiler.Objects/overloading/OverloadGroup.cs +++ /dev/null @@ -1,54 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public abstract class OverloadGroup(string name) - : CompilerObject - , ICTCallable_Old - , IMappable - - where T : CompilerObject - { - public string Name { get; set; } = name; - - public Collection Overloads { get; init; } = []; - - public virtual CompilerObject Call(Compiler.Compiler compiler, Argument[] arguments) - { - var matchingOverloads = Overloads - .Select(overload => { - try { return compiler.Call(overload, arguments); } - catch (ArgumentMismatchException) { return null!; } - }) - .Where(result => result is not null) - .ToArray(); - - if (matchingOverloads.Length == 0) - throw new NoOverloadFoundException(this, arguments); - - if (matchingOverloads.Length > 1) - throw new AmbiguousOverloadException(this, arguments, matchingOverloads); - - return matchingOverloads[0]; - } - - CompilerObject IMappable.Map(Func func) - { - return new OverloadGroup(Name) - { - Overloads = [.. Overloads.Select(item => func(item)).Where(item => item is not null)] - }; - } - } - - public sealed class OverloadGroup(string name) - : OverloadGroup(name) - , CompilerObject - , ICTCallable_Old - , IMappable - { - - - } -} diff --git a/ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs b/ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs deleted file mode 100644 index b3141ffb..00000000 --- a/ZSharp.Compiler.Objects/overloading/exceptions/AmbiguousOverloadException.cs +++ /dev/null @@ -1,14 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class AmbiguousOverloadException( - CompilerObject group, - Argument[] arguments, - CompilerObject[] overloads - ) - : OverloadException(group, arguments) - { - public CompilerObject[] Overloads { get; } = overloads; - } -} diff --git a/ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs b/ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs deleted file mode 100644 index 9d8c3eff..00000000 --- a/ZSharp.Compiler.Objects/overloading/exceptions/NoOverloadFoundException.cs +++ /dev/null @@ -1,9 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class NoOverloadFoundException(CompilerObject group, Argument[] arguments) - : OverloadException(group, arguments) - { - } -} diff --git a/ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs b/ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs deleted file mode 100644 index 91906ff6..00000000 --- a/ZSharp.Compiler.Objects/overloading/exceptions/OverloadException.cs +++ /dev/null @@ -1,10 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public abstract class OverloadException(CompilerObject group, Argument[] arguments) - : ArgumentMismatchException(group, arguments) - { - //public OverloadGroup Group { get; } = group; - } -} diff --git a/ZSharp.Compiler.Objects/signature/abstract/ISignature_NEW.cs b/ZSharp.Compiler.Objects/signature/abstract/ISignature_NEW.cs deleted file mode 100644 index 8e22dc94..00000000 --- a/ZSharp.Compiler.Objects/signature/abstract/ISignature_NEW.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Objects -{ - public interface ISignature_NEW - { - - } -} diff --git a/ZSharp.Compiler.Objects/signature/abstract_old/ICallableType.cs b/ZSharp.Compiler.Objects/signature/abstract_old/ICallableType.cs deleted file mode 100644 index 6f2daa61..00000000 --- a/ZSharp.Compiler.Objects/signature/abstract_old/ICallableType.cs +++ /dev/null @@ -1,118 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public interface ICallableType - : IType - , ITypeAssignableToType - , ISignature - { - public IType ReturnType { get; } - - #region Protocols - - bool IType.IsEqualTo(Compiler.Compiler compiler, IType type) - { - if (type is not ISignature callableType) - return false; - - if (Args.Count() != callableType.Args.Count()) - return false; - - if ( - VarArgs is null && callableType.VarArgs is not null || - VarArgs is not null && callableType.VarArgs is null - ) - return false; - if ( - !(VarArgs is null && callableType.VarArgs is null) && - !compiler.TypeSystem.AreEqual(VarArgs!.Type, callableType.VarArgs!.Type) - ) - return false; - - if (KwArgs.Count() != callableType.KwArgs.Count()) - return false; - - if ( - VarKwArgs is null && callableType.VarKwArgs is not null || - VarKwArgs is not null && callableType.VarKwArgs is null - ) - return false; - if ( - !(VarKwArgs is null && callableType.VarKwArgs is null) && - !compiler.TypeSystem.AreEqual(VarKwArgs!.Type, callableType.VarKwArgs!.Type) - ) - return false; - - if (!compiler.TypeSystem.AreEqual(ReturnType, callableType.ReturnType)) - return false; - - foreach (var (left, right) in Args.Zip(callableType.Args)) - if (!compiler.TypeSystem.AreEqual(left.Type, right.Type)) - return false; - - var otherKwArgs = callableType.KwArgs.ToDictionary(param => param.Name); - - foreach (var kwArg in KwArgs) - if (!otherKwArgs.TryGetValue(kwArg.Name, out var otherKwArg)) - return false; - else if (!compiler.TypeSystem.AreEqual(kwArg.Type, otherKwArg.Type)) - return false; - - return true; - } - - bool? ITypeAssignableToType.IsAssignableTo(Compiler.Compiler compiler, IType target) - { - if (target is not ISignature callableType) - return false; - - if (Args.Count() != callableType.Args.Count()) - return false; - - if ( - VarArgs is null && callableType.VarArgs is not null || - VarArgs is not null && callableType.VarArgs is null - ) - return false; - if ( - !(VarArgs is null && callableType.VarArgs is null) && - !compiler.TypeSystem.IsAssignableFrom(VarArgs!.Type, callableType.VarArgs!.Type) - ) - return false; - - if (KwArgs.Count() != callableType.KwArgs.Count()) - return false; - - if ( - VarKwArgs is null && callableType.VarKwArgs is not null || - VarKwArgs is not null && callableType.VarKwArgs is null - ) - return false; - if ( - !(VarKwArgs is null && callableType.VarKwArgs is null) && - !compiler.TypeSystem.IsAssignableFrom(VarKwArgs!.Type, callableType.VarKwArgs!.Type) - ) - return false; - - if (!compiler.TypeSystem.IsAssignableTo(ReturnType, callableType.ReturnType)) - return false; - - foreach (var (left, right) in Args.Zip(callableType.Args)) - if (!compiler.TypeSystem.IsAssignableFrom(left.Type, right.Type)) - return false; - - var otherKwArgs = callableType.KwArgs.ToDictionary(param => param.Name); - - foreach (var kwArg in KwArgs) - if (!otherKwArgs.TryGetValue(kwArg.Name, out var otherKwArg)) - return false; - else if (!compiler.TypeSystem.IsAssignableFrom(kwArg.Type, otherKwArg.Type)) - return false; - - return true; - } - - #endregion - } -} diff --git a/ZSharp.Compiler.Objects/signature/abstract_old/IParameter.cs b/ZSharp.Compiler.Objects/signature/abstract_old/IParameter.cs deleted file mode 100644 index 8eb3e3b8..00000000 --- a/ZSharp.Compiler.Objects/signature/abstract_old/IParameter.cs +++ /dev/null @@ -1,15 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public interface IParameter - : CompilerObject - , ITyped - { - public string Name { get; } - - public CompilerObject? Default { get; } - - public CompilerObjectResult MatchArgument(Compiler.Compiler compiler, CompilerObject argument); - } -} diff --git a/ZSharp.Compiler.Objects/signature/abstract_old/ISignature.cs b/ZSharp.Compiler.Objects/signature/abstract_old/ISignature.cs deleted file mode 100644 index 6b0edb5b..00000000 --- a/ZSharp.Compiler.Objects/signature/abstract_old/ISignature.cs +++ /dev/null @@ -1,196 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -using Args = CommonZ.Utils.Collection; -using KwArgs = CommonZ.Utils.Mapping; - - -namespace ZSharp.Objects -{ - public interface ISignature - : CompilerObject - , IType - , ITypeAssignableToType - { - public IEnumerable Args { get; } - - public IVarParameter? VarArgs { get; } - - public IEnumerable KwArgs { get; } - - public IVarParameter? VarKwArgs { get; } - - public IType ReturnType { get; } - - public Mapping MatchArguments(Compiler.Compiler compiler, Compiler.Argument[] arguments) - { - var (args, kwArgs) = Utils.SplitArguments(arguments); - - try - { - return MatchArguments(compiler, args, kwArgs); - } catch (ArgumentsCountMismatchException argumentsCountMismatch) - { - throw new ArgumentMismatchException(this, arguments, innerException: argumentsCountMismatch); - } catch (Compiler.InvalidCastException invalidCast) - { - throw new ArgumentMismatchException(this, arguments, innerException: invalidCast); - } - } - - public Mapping MatchArguments(Compiler.Compiler compiler, Args args, KwArgs kwArgs) - { - var @params = Args.ToList(); - var kwParams = KwArgs.ToList(); - - if (args.Count > @params.Count && VarArgs is null) - throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}."); - - if (kwArgs.Count > kwParams.Count && VarKwArgs is null) - throw new ArgumentsCountMismatchException($"Expected {kwParams.Count} named arguments but got {kwArgs.Count}."); - - Mapping result = []; - - var positionalArgumentsQueue = new Queue(args); - - foreach (var param in @params) - { - if (!positionalArgumentsQueue.TryDequeue(out var arg)) - arg = param.Default ?? throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); - - if (param.MatchArgument(compiler, arg).Ok(out var argumentResult)) - result[param] = argumentResult; - else throw new Compiler.InvalidCastException(arg, null!); - } - - if (VarArgs is not null) - result[VarArgs] = VarArgs.MatchArguments(compiler, [.. positionalArgumentsQueue.Select(arg => new Compiler.Argument(arg))]); - else if (positionalArgumentsQueue.Count > 0) - throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); - - var varKeywordArguments = new Collection(); - - foreach (var kwParam in kwParams) - { - if (!kwArgs.Remove(kwParam.Name, out var kwArg)) - kwArg = kwParam.Default ?? throw new ArgumentsCountMismatchException($"Expected {@params.Count} positional arguments but got {args.Count}"); - else varKeywordArguments.Add(new(kwParam.Name, kwArg)); - - result[kwParam] = kwArg; - } - - if (VarKwArgs is not null) - result[VarKwArgs] = VarKwArgs.MatchArguments(compiler, [.. varKeywordArguments]); - else if (kwArgs.Count > 0) - throw new ArgumentsCountMismatchException($"Expected {@params.Count} named arguments but got {args.Count}"); - - return result; - } - - #region Protocols - - bool IType.IsEqualTo(Compiler.Compiler compiler, IType type) - { - if (type is not ISignature callableType) - return false; - - if (Args.Count() != callableType.Args.Count()) - return false; - - if ( - VarArgs is null && callableType.VarArgs is not null || - VarArgs is not null && callableType.VarArgs is null - ) - return false; - if ( - !(VarArgs is null && callableType.VarArgs is null) && - !compiler.TypeSystem.AreEqual(VarArgs!.Type, callableType.VarArgs!.Type) - ) - return false; - - if (KwArgs.Count() != callableType.KwArgs.Count()) - return false; - - if ( - VarKwArgs is null && callableType.VarKwArgs is not null || - VarKwArgs is not null && callableType.VarKwArgs is null - ) - return false; - if ( - !(VarKwArgs is null && callableType.VarKwArgs is null) && - !compiler.TypeSystem.AreEqual(VarKwArgs!.Type, callableType.VarKwArgs!.Type) - ) - return false; - - if (!compiler.TypeSystem.AreEqual(ReturnType, callableType.ReturnType)) - return false; - - foreach (var (left, right) in Args.Zip(callableType.Args)) - if (!compiler.TypeSystem.AreEqual(left.Type, right.Type)) - return false; - - var otherKwArgs = callableType.KwArgs.ToDictionary(param => param.Name); - - foreach (var kwArg in KwArgs) - if (!otherKwArgs.TryGetValue(kwArg.Name, out var otherKwArg)) - return false; - else if (!compiler.TypeSystem.AreEqual(kwArg.Type, otherKwArg.Type)) - return false; - - return true; - } - - bool? ITypeAssignableToType.IsAssignableTo(Compiler.Compiler compiler, IType target) - { - if (target is not ISignature callableType) - return false; - - if (Args.Count() != callableType.Args.Count()) - return false; - - if ( - VarArgs is null && callableType.VarArgs is not null || - VarArgs is not null && callableType.VarArgs is null - ) - return false; - if ( - !(VarArgs is null && callableType.VarArgs is null) && - !compiler.TypeSystem.IsAssignableFrom(VarArgs!.Type, callableType.VarArgs!.Type) - ) - return false; - - if (KwArgs.Count() != callableType.KwArgs.Count()) - return false; - - if ( - VarKwArgs is null && callableType.VarKwArgs is not null || - VarKwArgs is not null && callableType.VarKwArgs is null - ) - return false; - if ( - !(VarKwArgs is null && callableType.VarKwArgs is null) && - !compiler.TypeSystem.IsAssignableFrom(VarKwArgs!.Type, callableType.VarKwArgs!.Type) - ) - return false; - - if (!compiler.TypeSystem.IsAssignableTo(ReturnType, callableType.ReturnType)) - return false; - - foreach (var (left, right) in Args.Zip(callableType.Args)) - if (!compiler.TypeSystem.IsAssignableFrom(left.Type, right.Type)) - return false; - - var otherKwArgs = callableType.KwArgs.ToDictionary(param => param.Name); - - foreach (var kwArg in KwArgs) - if (!otherKwArgs.TryGetValue(kwArg.Name, out var otherKwArg)) - return false; - else if (!compiler.TypeSystem.IsAssignableFrom(kwArg.Type, otherKwArg.Type)) - return false; - - return true; - } - - #endregion - } -} diff --git a/ZSharp.Compiler.Objects/signature/abstract_old/IVarParameter.cs b/ZSharp.Compiler.Objects/signature/abstract_old/IVarParameter.cs deleted file mode 100644 index 343afed1..00000000 --- a/ZSharp.Compiler.Objects/signature/abstract_old/IVarParameter.cs +++ /dev/null @@ -1,13 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public interface IVarParameter - : CompilerObject - , INamedObject - , ITyped - { - public CompilerObject MatchArguments(Compiler.Compiler compiler, Collection arguments); - } -} diff --git a/ZSharp.Compiler.Objects/signature/exceptions/ArgumentsCountMismatchException.cs b/ZSharp.Compiler.Objects/signature/exceptions/ArgumentsCountMismatchException.cs deleted file mode 100644 index 4f7962e5..00000000 --- a/ZSharp.Compiler.Objects/signature/exceptions/ArgumentsCountMismatchException.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZSharp.Objects -{ - internal sealed class ArgumentsCountMismatchException : Exception - { - public ArgumentsCountMismatchException() : base() { } - - public ArgumentsCountMismatchException(string? message) : base(message) { } - - public ArgumentsCountMismatchException(string? message, Exception? innerException) : base(message, innerException) { } - } -} diff --git a/ZSharp.Compiler.Objects/signature/stub/StubParameter.cs b/ZSharp.Compiler.Objects/signature/stub/StubParameter.cs deleted file mode 100644 index 7e852e70..00000000 --- a/ZSharp.Compiler.Objects/signature/stub/StubParameter.cs +++ /dev/null @@ -1,46 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class StubParameter(string name) - : CompilerObject - , IParameter - , ITyped - , IReferencable - { - public string Name { get; set; } = name; - - public CompilerObject? Default { get; set; } - - public IType? Type { get; set; } - - #region Parameter - - CompilerObjectResult IParameter.MatchArgument(Compiler.Compiler compiler, CompilerObject argument) - { - if (Type is null) - return CompilerObjectResult.Error($"Parameter {Name} does not have a type"); - - return compiler.TypeSystem.ImplicitCast(argument, Type); - } - - #endregion - - #region Typed - - IType ITyped.Type => Type ?? throw new InvalidOperationException($"Parameter {Name} does not define a type"); - - #endregion - - #region Reference - - IParameter IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - => new StubParameter(Name) - { - Default = Default is null ? null : @ref.CreateReference(Default, context), - Type = Type is null ? null : @ref.CreateReference(Type, context), - }; - - #endregion - } -} diff --git a/ZSharp.Compiler.Objects/signature/stub/StubSignature.cs b/ZSharp.Compiler.Objects/signature/stub/StubSignature.cs deleted file mode 100644 index a54a5204..00000000 --- a/ZSharp.Compiler.Objects/signature/stub/StubSignature.cs +++ /dev/null @@ -1,56 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class StubSignature - : CompilerObject - , ISignature - , IReferencable - { - public Collection Args { get; } = []; - - public StubVarParameter? VarArgs { get; set; } - - public Collection KwArgs { get; } = []; - - public StubVarParameter? VarKwArgs { get; set; } - - public IType? ReturnType { get; set; } - - #region Signature - - IEnumerable ISignature.Args => Args; - - IVarParameter? ISignature.VarArgs => VarArgs; - - IEnumerable ISignature.KwArgs => KwArgs; - - IVarParameter? ISignature.VarKwArgs => VarKwArgs; - - IType ISignature.ReturnType => ReturnType ?? throw new(); - - #endregion - - #region Reference - - ISignature IReferencable.CreateReference(Referencing @ref, ReferenceContext context) - { - StubSignature result = new(); - - result.Args.AddRange(Args.Select(arg => @ref.CreateReference(arg, context))); - - if (VarArgs is not null) - result.VarArgs = @ref.CreateReference(VarArgs, context); - - result.KwArgs.AddRange(KwArgs.Select(arg => @ref.CreateReference(arg, context))); - - if (VarKwArgs is not null) - result.VarKwArgs = @ref.CreateReference(VarKwArgs, context); - - return result; - } - - #endregion - } -} diff --git a/ZSharp.Compiler.Objects/signature/stub/StubVarParameter.cs b/ZSharp.Compiler.Objects/signature/stub/StubVarParameter.cs deleted file mode 100644 index f2f1dfcc..00000000 --- a/ZSharp.Compiler.Objects/signature/stub/StubVarParameter.cs +++ /dev/null @@ -1,30 +0,0 @@ -using CommonZ.Utils; -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class StubVarParameter(string name) - : CompilerObject - , IVarParameter - , ITyped - { - public string Name { get; set; } = name; - - public IType? Type { get; set; } - - #region Var Parameter - - CompilerObject IVarParameter.MatchArguments(Compiler.Compiler compiler, Collection arguments) - { - throw new NotImplementedException(); - } - - #endregion - - #region Typed - - IType ITyped.Type => Type ?? throw new InvalidOperationException($"Variadic parameter {Name} does not define a type"); - - #endregion - } -} diff --git a/ZSharp.Compiler.Objects/typing/TypedUndefined.cs b/ZSharp.Compiler.Objects/typing/TypedUndefined.cs deleted file mode 100644 index 5c0256a6..00000000 --- a/ZSharp.Compiler.Objects/typing/TypedUndefined.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ZSharp.Compiler; - -namespace ZSharp.Objects -{ - public sealed class TypedUndefined(IType type) - : CompilerObject - , ITyped - { - public IType Type { get; } = type; - } -} diff --git a/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs b/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs deleted file mode 100644 index be8a8269..00000000 --- a/ZSharp.Compiler.Objects/utils/ObjectBuildState.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace ZSharp.Objects -{ - internal sealed class ObjectBuildState - where T : struct, Enum, IConvertible - { - public T State { get; private set; } - - public bool Get(T state) => State.HasFlag(state); - - public void Set(T state) - { - State = (T)(System.ValueType)(State.ToInt32(null) | state.ToInt32(null)); - } - - public static bool operator &(ObjectBuildState instance, T value) - => instance.Get(value); - - public bool this[T flag] - { - get => Get(flag); - set - { - if (value) - Set(flag); - } - } - } -} diff --git a/ZSharp.Compiler.Objects/utils/RuntimeHelpers.cs b/ZSharp.Compiler.Objects/utils/RuntimeHelpers.cs deleted file mode 100644 index a9d6fced..00000000 --- a/ZSharp.Compiler.Objects/utils/RuntimeHelpers.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ZSharp.Objects -{ - internal static class RuntimeHelpers - { - public static T GetUninitializedObject() - => (T)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject( - typeof(T) - ); - } -} diff --git a/ZSharp.Compiler.Overloading/GlobalUsings.cs b/ZSharp.Compiler.Overloading/GlobalUsings.cs index c1bcb323..3bfc54ae 100644 --- a/ZSharp.Compiler.Overloading/GlobalUsings.cs +++ b/ZSharp.Compiler.Overloading/GlobalUsings.cs @@ -2,3 +2,4 @@ global using MemberIndex = int; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.Overloading/dispatcher/Dispatcher.T.cs b/ZSharp.Compiler.Overloading/dispatcher/Dispatcher.T.cs index 30d2d580..d6c15b5e 100644 --- a/ZSharp.Compiler.Overloading/dispatcher/Dispatcher.T.cs +++ b/ZSharp.Compiler.Overloading/dispatcher/Dispatcher.T.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public static Result F(CompilerObject @object) + public static IResult F(CompilerObject @object) => Result.Error($"Object '{@object}' does not implement F"); } } diff --git a/ZSharp.Compiler.Overloading/overloading/services/Overloading.T.cs b/ZSharp.Compiler.Overloading/overloading/services/Overloading.T.cs index c1579bb6..ff9fb3c8 100644 --- a/ZSharp.Compiler.Overloading/overloading/services/Overloading.T.cs +++ b/ZSharp.Compiler.Overloading/overloading/services/Overloading.T.cs @@ -1,6 +1,6 @@ namespace ZSharp.Compiler { - public delegate Result F(CompilerObject callee); + public delegate IResult F(CompilerObject callee); partial struct Overloading { diff --git a/ZSharp.Compiler.Reflection/GlobalUsings.cs b/ZSharp.Compiler.Reflection/GlobalUsings.cs index c1bcb323..3bfc54ae 100644 --- a/ZSharp.Compiler.Reflection/GlobalUsings.cs +++ b/ZSharp.Compiler.Reflection/GlobalUsings.cs @@ -2,3 +2,4 @@ global using MemberIndex = int; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.TS.Static/GlobalUsings.cs b/ZSharp.Compiler.TS.Static/GlobalUsings.cs index 05db7df2..501033a9 100644 --- a/ZSharp.Compiler.TS.Static/GlobalUsings.cs +++ b/ZSharp.Compiler.TS.Static/GlobalUsings.cs @@ -1 +1,2 @@ global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs index ca7e92b6..d2e55698 100644 --- a/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs +++ b/ZSharp.Compiler.TS.Static/dispatcher/Dispatcher.TypeOf.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public Result TypeOf(CompilerObject @object) + public IResult TypeOf(CompilerObject @object) { var result = @base.TypeOf(@object); diff --git a/ZSharp.Compiler.TS/GlobalUsings.cs b/ZSharp.Compiler.TS/GlobalUsings.cs index 05db7df2..501033a9 100644 --- a/ZSharp.Compiler.TS/GlobalUsings.cs +++ b/ZSharp.Compiler.TS/GlobalUsings.cs @@ -1 +1,2 @@ global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Compiler.TS/dispatcher/Dispatcher.T.cs b/ZSharp.Compiler.TS/dispatcher/Dispatcher.T.cs index 8cb7b400..e648a27e 100644 --- a/ZSharp.Compiler.TS/dispatcher/Dispatcher.T.cs +++ b/ZSharp.Compiler.TS/dispatcher/Dispatcher.T.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public static Result Do(CompilerObject @object) + public static IResult Do(CompilerObject @object) => Result.Error( "Object does not support do" ); diff --git a/ZSharp.Compiler.TS/dispatcher/services/Dispatcher.TypeOf.cs b/ZSharp.Compiler.TS/dispatcher/services/Dispatcher.TypeOf.cs index fed890db..b5071c85 100644 --- a/ZSharp.Compiler.TS/dispatcher/services/Dispatcher.TypeOf.cs +++ b/ZSharp.Compiler.TS/dispatcher/services/Dispatcher.TypeOf.cs @@ -2,7 +2,7 @@ { partial class Dispatcher { - public static Result TypeOf(CompilerObject @object) + public static IResult TypeOf(CompilerObject @object) => Result.Error( "Object does not support typeof" ); diff --git a/ZSharp.Compiler.TS/ts/services/TS.TypeOf.cs b/ZSharp.Compiler.TS/ts/services/TS.TypeOf.cs index 3073b854..3c2b1a46 100644 --- a/ZSharp.Compiler.TS/ts/services/TS.TypeOf.cs +++ b/ZSharp.Compiler.TS/ts/services/TS.TypeOf.cs @@ -2,7 +2,7 @@ namespace ZSharp.Compiler { - public delegate Result TypeOf(CompilerObject @object); + public delegate IResult TypeOf(CompilerObject @object); partial struct TS { diff --git a/ZSharp.Compiler/GlobalUsings.cs b/ZSharp.Compiler/GlobalUsings.cs index c1bcb323..3bfc54ae 100644 --- a/ZSharp.Compiler/GlobalUsings.cs +++ b/ZSharp.Compiler/GlobalUsings.cs @@ -2,3 +2,4 @@ global using MemberIndex = int; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Importer.ILLoader/GlobalUsings.cs b/ZSharp.Importer.ILLoader/GlobalUsings.cs index 22ada189..a24d1fcb 100644 --- a/ZSharp.Importer.ILLoader/GlobalUsings.cs +++ b/ZSharp.Importer.ILLoader/GlobalUsings.cs @@ -7,3 +7,4 @@ global using CompilerObject = ZSharp.Compiler.CompilerObject; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.Importer.ILLoader/capabilities/internal/IBindable.cs b/ZSharp.Importer.ILLoader/capabilities/internal/IBindable.cs index 5dd60137..4d0deca0 100644 --- a/ZSharp.Importer.ILLoader/capabilities/internal/IBindable.cs +++ b/ZSharp.Importer.ILLoader/capabilities/internal/IBindable.cs @@ -2,6 +2,6 @@ { internal interface IBindable { - public Result Bind(Compiler.Compiler compiler, CompilerObject target); + public IResult Bind(Compiler.Compiler compiler, CompilerObject target); } } diff --git a/ZSharp.Importer.ILLoader/capabilities/on add/IOnAddTo.cs b/ZSharp.Importer.ILLoader/capabilities/on add/IOnAddTo.cs index 31d747de..89792d0d 100644 --- a/ZSharp.Importer.ILLoader/capabilities/on add/IOnAddTo.cs +++ b/ZSharp.Importer.ILLoader/capabilities/on add/IOnAddTo.cs @@ -1,7 +1,7 @@ namespace ZSharp.Objects { - public interface IOnAddTo - where T : class, Compiler.CompilerObject + public interface IOnAddTo + where T : class, CompilerObject { public OnAddResult OnAddTo(T @object); } diff --git a/ZSharp.Importer.ILLoader/helpers/Prepare.cs b/ZSharp.Importer.ILLoader/helpers/Prepare.cs index d7071051..a6847f81 100644 --- a/ZSharp.Importer.ILLoader/helpers/Prepare.cs +++ b/ZSharp.Importer.ILLoader/helpers/Prepare.cs @@ -111,6 +111,11 @@ public static void PrepareType(Objects.Class @class, ILLoader loader) foreach (var member in il.GetMembers()) { + if (member is ConstructorInfo constructor) + { + continue; + } + if (member is MethodInfo method && method.IsOperator(out var op)) { loader.OnLoadOperator?.Invoke(op, method); diff --git a/ZSharp.Importer.ILLoader/objects/callable/argument stream/ArgumentStream.cs b/ZSharp.Importer.ILLoader/objects/callable/argument stream/ArgumentStream.cs index 7f9f8630..a221e71f 100644 --- a/ZSharp.Importer.ILLoader/objects/callable/argument stream/ArgumentStream.cs +++ b/ZSharp.Importer.ILLoader/objects/callable/argument stream/ArgumentStream.cs @@ -6,7 +6,7 @@ namespace ZSharp.Importer.ILLoader.Objects internal sealed class ArgumentStream : IArgumentStream { - private readonly List args = []; + internal readonly List args = []; private readonly Dictionary kwArgs = []; public ArgumentStream(Argument[] arguments) @@ -31,5 +31,8 @@ public ArgumentStream(Argument[] arguments) if (!kwArgs.Remove(name, out var arg)) return null; return arg; } + + public bool HasArgument(string name) + => kwArgs.ContainsKey(name); } } diff --git a/ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.cs b/ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.cs index 4e31ce2f..fd473f93 100644 --- a/ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.cs +++ b/ZSharp.Importer.ILLoader/objects/callable/parameter/Parameter.cs @@ -20,7 +20,7 @@ public Parameter(IL.ParameterInfo il, ILLoader loader) Type = loader.LoadType(IL.ParameterType); } - Result IParameter.Match(Compiler.Compiler compiler, IArgumentStream arguments) + IResult IParameter.Match(Compiler.Compiler compiler, IArgumentStream arguments) { if (!arguments.PopArgument(Name, out var argument) && !arguments.PopArgument(out argument) diff --git a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs index 0b02242e..bd894a77 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/function/concrete/Function.Call.cs @@ -6,7 +6,7 @@ namespace ZSharp.Importer.ILLoader.Objects partial class Function : ICTCallable { - Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + IResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { if ( BoundSignature.Create(compiler, signature, new ArgumentStream(arguments)) diff --git a/ZSharp.Importer.ILLoader/objects/modular/global/Global.CG.Get.cs b/ZSharp.Importer.ILLoader/objects/modular/global/Global.CG.Get.cs index afd5fc7b..60c39eed 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/global/Global.CG.Get.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/global/Global.CG.Get.cs @@ -5,7 +5,7 @@ namespace ZSharp.Importer.ILLoader.Objects partial class Global : ICTGet { - Result ICTGet.Get(Compiler.Compiler compiler) + IResult ICTGet.Get(Compiler.Compiler compiler) => Result.Ok(new RawIRCode(new([ new IR.VM.GetGlobal(IR) ]) diff --git a/ZSharp.Importer.ILLoader/objects/modular/global/Global.IR.cs b/ZSharp.Importer.ILLoader/objects/modular/global/Global.IR.cs index b20ee21c..4d822aac 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/global/Global.IR.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/global/Global.IR.cs @@ -7,7 +7,7 @@ partial class Global { public IR.Global? IR { get; private set; } - Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) + IResult ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) { if (IR is not null) return Result.Ok(IR); diff --git a/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs index 52fdb043..da7e6a16 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/module/Module.Member.cs @@ -21,7 +21,7 @@ CompilerObject IAddMember.AddMember(string name, CompilerObject member) return member; } - Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName name) + IResult ICTGetMember.Member(Compiler.Compiler compiler, MemberName name) { if (!Members.TryGetValue(name, out var member) && !LazyLoader.GetLazyMember(name, out member)) return Result.Error( diff --git a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs index 21653c4a..cf372c9d 100644 --- a/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/modular/type as module/TypeAsModule.Member.cs @@ -21,7 +21,7 @@ CompilerObject IAddMember.AddMember(string name, CompilerObject member) return member; } - Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName name) + IResult ICTGetMember.Member(Compiler.Compiler compiler, MemberName name) { if (!Members.TryGetValue(name, out var result) && !LazyLoader.GetLazyMember(name, out result)) return Result.Error( diff --git a/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs index aca6d1bf..cb581917 100644 --- a/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/namespace/Namespace.Member.cs @@ -18,7 +18,7 @@ public void AddMember(string name, CompilerObject member) Members.Add(name, member); } - Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) + IResult ICTGetMember.Member(Compiler.Compiler compiler, MemberName member) { if (!Members.TryGetValue(member, out var result)) if ((result = GetLazyMember(member)) is not null) diff --git a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Call.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Call.cs new file mode 100644 index 00000000..1d73c231 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Call.cs @@ -0,0 +1,16 @@ +using ZSharp.Compiler; + +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Class + : ICTCallable + { + IResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + if (Constructor is null) + return Result.Error("Class doesn't have a constructor and cannot be instantiated."); + + return compiler.CG.Call(Constructor, arguments); + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Constructor.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Constructor.cs new file mode 100644 index 00000000..c217f123 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Constructor.cs @@ -0,0 +1,29 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Class + { + private CompilerObject? constructor; + + public CompilerObject? Constructor + { + get + { + if (constructor is null) + { + var constructors = IL.GetConstructors(); + + if (constructors.Length > 1) + throw new NotImplementedException("Overloaded constructors are not supported."); + + if (constructors.Length == 0) + return null; + + constructor = new Constructor(constructors[0], Loader); + (constructor as IOnAddTo)?.OnAddTo(this); + } + + return constructor; + } + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs index 90862835..9e475017 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.IR.cs @@ -6,13 +6,17 @@ namespace ZSharp.Importer.ILLoader.Objects partial class Class : ICompileIRDefinitionAs , ICompileIRType> + , ICompileIRReference> { private IR.Class? IR { get; set; } - Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) + IResult ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) => Result.Ok(GetIR()); - Result> ICompileIRType>.CompileIRType(Compiler.Compiler compiler) + IResult, Error> ICompileIRReference>.CompileIRReference(Compiler.Compiler compiler) + => Result>.Ok(new ClassReference(GetIR())); + + IResult, Error> ICompileIRType>.CompileIRType(Compiler.Compiler compiler) => Result>.Ok(new ClassReference(GetIR())); private IR.Class GetIR() diff --git a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Member.cs b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Member.cs index b14caddc..f36d65eb 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Member.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/class/concrete/Class.Member.cs @@ -22,7 +22,7 @@ CompilerObject IAddMember.AddMember(string name, CompilerObject member) return member; } - Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName name) + IResult ICTGetMember.Member(Compiler.Compiler compiler, MemberName name) { if (!Members.TryGetValue(name, out var member) && !LazyLoader.GetLazyMember(name, out member)) return Result.Error( @@ -32,7 +32,7 @@ Result ICTGetMember.Member(Compiler.Compiler compiler, MemberName na return Result.Ok(member); } - Result IRTGetMember.Member(Compiler.Compiler compiler, CompilerObject @object, MemberName name) + IResult IRTGetMember.Member(Compiler.Compiler compiler, CompilerObject @object, MemberName name) { if ( compiler.CG.Member(this, name) diff --git a/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Call.cs b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Call.cs new file mode 100644 index 00000000..eaa1875b --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Call.cs @@ -0,0 +1,66 @@ +using ZSharp.Compiler; +using ZSharp.Compiler.Features.Callable; + +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Constructor + : ICTCallable + { + IResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + { + if (Owner is null) + return Result.Error("Constructor doesn't yet have an owner and cannot be used."); + + if ( + compiler.IR.CompileReference(Owner) + .When(out var owner) + .Error(out var error) + ) return Result.Error(error); + + var stream = new ArgumentStream(arguments); + + IR.VM.Instruction callInstruction; + CompilerObject returnType; + + var constructor = new IR.ConstructorReference(GetIR()) + { + OwningType = owner! + }; + + if (stream.HasArgument(thisParameter.Name)) + { + returnType = compiler.TS.Void; + callInstruction = new IR.VM.Call(constructor); + } else + { + stream.args.Insert(0, RawIRCode.From([], Owner)); + returnType = Owner; + callInstruction = new IR.VM.CreateInstance(constructor); + } + + if ( + BoundSignature.Create(compiler, signature, stream) + .When(out var boundSignature) + .Error(out error) + ) return Result.Error(error); + + IRCode result = new(); + + foreach (var boundParameter in boundSignature!.Parameters) + { + if ( + compiler.IR.CompileCode(boundParameter.ArgumentObject, null) + .When(out var argumentCode) + .Error(out error) + ) + return Result.Error(error); + + result.Instructions.AddRange(argumentCode!.Instructions); + } + + result.Instructions.Add(callInstruction); + + return Result.Ok(RawIRCode.From(result.Instructions, returnType)); + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.IL.cs b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.IL.cs new file mode 100644 index 00000000..5f394bc7 --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.IL.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Constructor + { + public IL.ConstructorInfo IL { get; } + + public ILLoader Loader { get; } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.IR.cs b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.IR.cs new file mode 100644 index 00000000..faed2d7f --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.IR.cs @@ -0,0 +1,24 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Constructor + { + private IR.Constructor? IR { get; set; } + + private IR.Constructor GetIR() + { + if (IR is null) + { + var returnTypeCO = Loader.LoadType(typeof(void)); + if (Loader.IR.CompileType(returnTypeCO).When(out var returnTypeIR).Error(out var error)) + throw new InvalidOperationException($"Failed to load return type for method {IL.Name}: {error}"); + IR = new(string.Empty) + { + Method = new(returnTypeIR!) + }; + Loader.RequireRuntime().AddFunction(IR.Method.UnderlyingFunction, IL); + } + + return IR; + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Owner.cs b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Owner.cs new file mode 100644 index 00000000..057b8e6f --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Owner.cs @@ -0,0 +1,17 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Constructor + : IOnAddTo + { + public CompilerObject? Owner { get; private set; } + + OnAddResult IOnAddTo.OnAddTo(CompilerObject @object) + { + if (@object is null || Owner is not null && @object != Owner) + return OnAddResult.Error; + + Owner = @object; + return OnAddResult.None; + } + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Signature.cs b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Signature.cs new file mode 100644 index 00000000..009ef70c --- /dev/null +++ b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.Signature.cs @@ -0,0 +1,9 @@ +namespace ZSharp.Importer.ILLoader.Objects +{ + partial class Constructor + { + public readonly ThisParameter thisParameter; + + public readonly Signature signature = new(); + } +} diff --git a/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.cs b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.cs index 9093fe47..f7e976b0 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/constructor/Constructor.cs @@ -1,11 +1,19 @@ namespace ZSharp.Importer.ILLoader.Objects { - public sealed partial class Constructor + internal sealed partial class Constructor : CompilerObject { public Constructor(IL.ConstructorInfo il, ILLoader loader) { IL = il; + Loader = loader; + + thisParameter = new(il, loader); + + signature.parameters.Add(thisParameter); + + foreach (var parameter in il.GetParameters()) + signature.parameters.Add(new Parameter(parameter, loader)); } } } diff --git a/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IR.cs b/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IR.cs index 4e1e1ee8..66cfaeeb 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IR.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/interface/concrete/Interface.IR.cs @@ -9,7 +9,7 @@ partial class Interface { public IR.Interface? IR { get; private set; } - Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) + IResult ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) { if (IR is not null) return Result.Ok(IR); @@ -23,7 +23,7 @@ partial class Interface return Result.Ok(IR); } - Result> ICompileIRType>.CompileIRType(Compiler.Compiler compiler) + IResult, Error> ICompileIRType>.CompileIRType(Compiler.Compiler compiler) { if ( compiler.IR.CompileDefinition(this, null) diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs b/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs index 0602e102..45f7d4f1 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/bound/BoundMethod.Call.cs @@ -5,7 +5,7 @@ namespace ZSharp.Importer.ILLoader.Objects partial class BoundMethod : ICTCallable { - Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + IResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { if (Object is not null) arguments = [ diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Bind.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Bind.cs index 66569cb4..33333325 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Bind.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Bind.cs @@ -3,7 +3,7 @@ partial class Method : IBindable { - Result IBindable.Bind(Compiler.Compiler compiler, CompilerObject target) + IResult IBindable.Bind(Compiler.Compiler compiler, CompilerObject target) { if (IL.IsStatic) return Result.Ok(this); diff --git a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs index 458d66a1..d1e3fb50 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/method/concrete/Method.Call.cs @@ -7,7 +7,7 @@ namespace ZSharp.Importer.ILLoader.Objects partial class Method : ICTCallable { - Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + IResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { if ( BoundSignature.Create(compiler, signature, new ArgumentStream(arguments)) diff --git a/ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.IL.cs b/ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.IL.cs index 79d3072d..a27872f5 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.IL.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.IL.cs @@ -2,6 +2,6 @@ { partial class ThisParameter { - public IL.MethodInfo IL { get; } + public IL.MethodBase IL { get; } } } diff --git a/ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.cs b/ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.cs index a3316f21..4e800dff 100644 --- a/ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.cs +++ b/ZSharp.Importer.ILLoader/objects/oop/this parameter/ThisParameter.cs @@ -10,14 +10,14 @@ internal sealed partial class ThisParameter public CompilerObject Type { get; } - public ThisParameter(IL.MethodInfo il, ILLoader loader) + public ThisParameter(IL.MethodBase il, ILLoader loader) { IL = il; Type = loader.LoadType(IL.DeclaringType ?? throw new()); } - Result IParameter.Match(Compiler.Compiler compiler, IArgumentStream arguments) + IResult IParameter.Match(Compiler.Compiler compiler, IArgumentStream arguments) { if (!arguments.PopArgument(Name, out var argument) && !arguments.PopArgument(out argument) diff --git a/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs b/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs index b14ba134..956b6f71 100644 --- a/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/boolean/BooleanType.cs @@ -9,7 +9,7 @@ public sealed class BooleanType(TypeReference type) { private readonly TypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs b/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs index 9f88e839..19ab38b9 100644 --- a/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/char/CharType.cs @@ -9,7 +9,7 @@ public sealed class CharType(TypeReference type) { private readonly TypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs index 25da461d..3374276a 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float128Type.cs @@ -9,7 +9,7 @@ public sealed class Float128Type(TypeReference type) { private readonly TypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs index 23dc3dbf..5df97797 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float16Type.cs @@ -9,7 +9,7 @@ public sealed class Float16Type(TypeReference type) { private readonly TypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs index 5c20dd7b..3001cbc6 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float32Type.cs @@ -9,7 +9,7 @@ public sealed class Float32Type(TypeReference type) { private readonly TypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs b/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs index f242c7fe..774d86a1 100644 --- a/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/float/Float64Type.cs @@ -9,7 +9,7 @@ public sealed class Float64Type(TypeReference type) { private readonly TypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/SInt16Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt16Type.cs index 000fe4fd..6354465c 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/SInt16Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt16Type.cs @@ -9,7 +9,7 @@ public sealed class SInt16Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/SInt32Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt32Type.cs index 2ad0aff0..21a7eca4 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/SInt32Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt32Type.cs @@ -9,7 +9,7 @@ public sealed class SInt32Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/SInt64Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt64Type.cs index 004274a0..45422627 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/SInt64Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt64Type.cs @@ -9,7 +9,7 @@ public sealed class SInt64Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/SInt8Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/SInt8Type.cs index ed24cef8..e7754e24 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/SInt8Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SInt8Type.cs @@ -9,7 +9,7 @@ public sealed class SInt8Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/SIntNativeType.cs b/ZSharp.Importer.ILLoader/objects/types/int/SIntNativeType.cs index 20ebc0f4..d24c5304 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/SIntNativeType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/SIntNativeType.cs @@ -9,7 +9,7 @@ public sealed class SIntNativeType(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/UInt16Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt16Type.cs index 9c2696e0..13db4dbd 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/UInt16Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt16Type.cs @@ -9,7 +9,7 @@ public sealed class UInt16Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/UInt32Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt32Type.cs index d93b9e64..cd2ee659 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/UInt32Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt32Type.cs @@ -9,7 +9,7 @@ public sealed class UInt32Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/UInt64Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt64Type.cs index a4bbf880..c2df94b4 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/UInt64Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt64Type.cs @@ -9,7 +9,7 @@ public sealed class UInt64Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/UInt8Type.cs b/ZSharp.Importer.ILLoader/objects/types/int/UInt8Type.cs index 04add41d..f7b4aeab 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/UInt8Type.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UInt8Type.cs @@ -9,7 +9,7 @@ public sealed class UInt8Type(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/int/UIntNativeType.cs b/ZSharp.Importer.ILLoader/objects/types/int/UIntNativeType.cs index 0bdcca81..5cc9f29c 100644 --- a/ZSharp.Importer.ILLoader/objects/types/int/UIntNativeType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/int/UIntNativeType.cs @@ -9,7 +9,7 @@ public sealed class UIntNativeType(IType type) { private readonly IType type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs b/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs index 24fde6b1..ce8b5a0d 100644 --- a/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/object/ObjectType.cs @@ -10,7 +10,7 @@ public sealed class ObjectType(TypeReference type) { private readonly TypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); Type IILType.GetILType() diff --git a/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs index b3e5cace..b6058322 100644 --- a/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/string/StringType.cs @@ -11,7 +11,7 @@ internal sealed class StringType(TypeReference type) { private readonly TypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); Type IILType.GetILType() diff --git a/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs b/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs index 0fb28345..647f13ab 100644 --- a/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs +++ b/ZSharp.Importer.ILLoader/objects/types/void/VoidType.cs @@ -9,7 +9,7 @@ public sealed class VoidType(TypeReference type) { private readonly TypeReference type = type; - Result ICompileIRType.CompileIRType(Compiler.Compiler compiler) + IResult ICompileIRType.CompileIRType(Compiler.Compiler compiler) => Result.Ok(type); } } diff --git a/ZSharp.Importer.ILLoader/semantics/IReferenceType.cs b/ZSharp.Importer.ILLoader/semantics/IReferenceType.cs index 81ed3a51..297e1369 100644 --- a/ZSharp.Importer.ILLoader/semantics/IReferenceType.cs +++ b/ZSharp.Importer.ILLoader/semantics/IReferenceType.cs @@ -6,7 +6,7 @@ internal interface IReferenceType : IILType , IRTImplicitCastTo { - Result IRTImplicitCastTo.ImplicitCast(Compiler.Compiler compiler, CompilerObject @object, CompilerObject type) + IResult IRTImplicitCastTo.ImplicitCast(Compiler.Compiler compiler, CompilerObject @object, CompilerObject type) { var thisIL = GetILType(); diff --git a/ZSharp.Importer.IRLoader/Context.cs b/ZSharp.Importer.IRLoader/Context.cs deleted file mode 100644 index 74681437..00000000 --- a/ZSharp.Importer.IRLoader/Context.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CommonZ.Utils; - -namespace ZSharp.Importer.IRLoader -{ - public sealed class Context - { - public Cache Objects { get; } = []; - - public Cache Types { get; } = []; - } -} diff --git a/ZSharp.Importer.IRLoader/GlobalUsings.cs b/ZSharp.Importer.IRLoader/GlobalUsings.cs deleted file mode 100644 index aeed8fe6..00000000 --- a/ZSharp.Importer.IRLoader/GlobalUsings.cs +++ /dev/null @@ -1,3 +0,0 @@ -global using ZSharp.Objects; - -global using CompilerObject = ZSharp.Compiler.CompilerObject; diff --git a/ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj b/ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj deleted file mode 100644 index cdc18594..00000000 --- a/ZSharp.Importer.IRLoader/ZSharp.Importer.IRLoader.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - net9.0 - enable - enable - - - - - - - - diff --git a/ZSharp.Importer.IRLoader/ir loader/IRLoader.API.cs b/ZSharp.Importer.IRLoader/ir loader/IRLoader.API.cs deleted file mode 100644 index 2e51bfa6..00000000 --- a/ZSharp.Importer.IRLoader/ir loader/IRLoader.API.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZSharp.Importer.IRLoader -{ - public partial class IRLoader - { - public partial Module Import(ZSharp.IR.Module module); - } -} diff --git a/ZSharp.Importer.IRLoader/ir loader/IRLoader.Impl.cs b/ZSharp.Importer.IRLoader/ir loader/IRLoader.Impl.cs deleted file mode 100644 index 66d4c180..00000000 --- a/ZSharp.Importer.IRLoader/ir loader/IRLoader.Impl.cs +++ /dev/null @@ -1,617 +0,0 @@ -using System.Text.RegularExpressions; - -namespace ZSharp.Importer.IRLoader -{ - public partial class IRLoader - { - public Context Context { get; } = new(); - - public partial Module Import(ZSharp.IR.Module module) - => Import(module, new(module.Name!) - { - IR = module, - }); - - public CompilerObject Import(ZSharp.IR.IType type) - => Load(type); - - public CompilerObject Import(ZSharp.IR.Function function) - => Context.Objects.Cache(function)!; - - private Module Import(ZSharp.IR.Module module, Module result) - { - result ??= new(module.Name!) - { - IR = module, - }; - - List actions = []; - - if (module.HasFunctions) - foreach (var function in module.Functions) - actions.Add(Load(function, result)); - - if (module.HasTypes) - foreach (var type in module.Types) - actions.Add(Load(type, result)); - - foreach (var action in actions) - action(); - - var ops = Compiler.Feature(); - - if (module.HasFunctions) - foreach (var function in module.Functions) - { - if (function.Name is null || function.Name == string.Empty) - continue; - - var match = Regex.Match(function.Name, @"^_?(?[+\-*/=?&^%$#@!<>|~]+)_?$"); - if (match.Success) - { - var op = match.Groups["OP"].Value; - if (!ops.Binary.Cache(op, out var group)) - group = ops.Binary.Cache(op, new OverloadGroup(op)); - - if (group is not OverloadGroup overloadGroup) - throw new Exception("Invalid overload group!"); - - overloadGroup.Overloads.Add(Import(function)); - } - } - - return result; - } - - private Action Load(ZSharp.IR.Module module, Module owner) - { - Module result = new(module.Name!) - { - IR = module, - }; - - Context.Objects.Cache(module, result); - - owner.Content.Add(result); - - if (result.Name is not null && result.Name != string.Empty) - owner.Members.Add(result.Name, result); - - return () => Import(module, result); - } - - private Action Load(ZSharp.IR.Function function, Module owner) - { - if (function.HasGenericParameters) - return LoadGenericFunction(function, owner); - - RTFunction result = new(function.Name) - { - IR = function, - IsDefined = true, - }; - - Context.Objects.Cache(function, result); - - owner.Content.Add(result); - - if (result.Name != string.Empty) - { - if (!owner.Members.TryGetValue(result.Name, out var group)) - owner.Members.Add(result.Name, group = new OverloadGroup(result.Name)); - - if (group is not OverloadGroup overloadGroup) - throw new InvalidOperationException(); - - overloadGroup.Overloads.Add(result); - } - - return () => - { - result.Signature = Load(function.Signature); - - result.ReturnType = Load(function.ReturnType); - }; - } - - private Action Load(ZSharp.IR.TypeDefinition type, Module owner) - => type switch - { - ZSharp.IR.Class @class => Load(@class, owner), - ZSharp.IR.Interface @interface => Load(@interface, owner), - ZSharp.IR.EnumClass @enum => Load(@enum, owner), - ZSharp.IR.ValueType valueType => Load(valueType, owner), - _ => throw new NotImplementedException(), - }; - - private Action Load(ZSharp.IR.Class @class, Module owner) - { - if (@class.HasGenericParameters) - return LoadGenericClass(@class, owner); - - Class result = new() - { - Name = @class.Name ?? string.Empty, - IR = @class, - IsDefined = true, - }; - - Context.Objects.Cache(@class, result); - - owner.Content.Add(result); - - if (result.Name is not null && result.Name != string.Empty) - owner.Members.Add(result.Name, result); - - return () => - { - if (@class.Base is not null) - result.Base = (IClass)Load(@class.Base); - - if (@class.HasFields) - foreach (var field in @class.Fields) - { - Field resultField = new(field.Name) - { - IR = field, - Type = Load(field.Type), - }; - if (field.Initializer is not null) - resultField.Initializer = new RawCode(new(field.Initializer) - { - Types = [resultField.Type] - }); - result.Members.Add(resultField.Name, resultField); - }; - - if (@class.Constructors.Count > 0) - foreach (var constructor in @class.Constructors) - { - Constructor resultConstructor = new(constructor.Name) - { - Owner = result, - IR = constructor, - }; - if (resultConstructor.Name is not null && resultConstructor.Name != string.Empty) - { - if (!result.Members.TryGetValue(resultConstructor.Name, out var group)) - result.Members.Add(resultConstructor.Name, group = new OverloadGroup(resultConstructor.Name)); - - if (group is not OverloadGroup overloadGroup) - throw new InvalidOperationException(); - - overloadGroup.Overloads.Add(resultConstructor); - } else - { - if (result.Constructor is not OverloadGroup group) - result.Constructor = group = new OverloadGroup(string.Empty); - - group.Overloads.Add(resultConstructor); - } - resultConstructor.Signature = Load(constructor.Method.Signature); - } - - if (@class.Methods.Count > 0) - foreach (var method in @class.Methods) - { - CompilerObject resultMethod; - if (method.HasGenericParameters) - resultMethod = LoadGenericMethod(method, result); - else - { - resultMethod = new Method(method.Name) - { - IR = method, - Defined = true, - Owner = result, - Signature = Load(method.Signature) - }; - } - if (method.Name is not null && method.Name != string.Empty) - { - if (!result.Members.TryGetValue(method.Name, out var group)) - result.Members.Add(method.Name, group = new OverloadGroup(method.Name)); - - if (group is not OverloadGroup overloadGroup) - throw new InvalidOperationException(); - - overloadGroup.Overloads.Add(resultMethod); - } - } - }; - } - - private GenericMethod LoadGenericMethod(ZSharp.IR.Method method, CompilerObject owner) - { - GenericMethod result = new(method.Name) - { - Defined = true, - IR = method, - Owner = owner - }; - - foreach (var genericParameter in method.GenericParameters) - result.GenericParameters.Add( - Context.Types.Cache(genericParameter, new GenericParameter() - { - IR = genericParameter, - Name = genericParameter.Name - }) - ); - - result.Signature = Load(method.Signature); - - return result; - } - - private Action Load(ZSharp.IR.Interface @interface, Module owner) - { - Interface result = new(@interface.Name) - { - Name = @interface.Name ?? string.Empty, - IR = @interface, - IsDefined = true, - }; - - Context.Objects.Cache(@interface, result); - - owner.Content.Add(result); - - if (result.Name is not null && result.Name != string.Empty) - owner.Members.Add(result.Name, result); - - //if (@interface.HasGenericParameters) - // foreach (var parameter in @interface.GenericParameters) - // { - // var genericParameter = new GenericParameter() - // { - // Name = parameter.Name, - // IR = parameter, - // }; - - // Context.Types.Cache(parameter, genericParameter); - - // result.GenericParameters.Add(genericParameter); - // } - - if (@interface.HasBases) - foreach (var @base in @interface.Bases) - result.Bases.Add(Load(@base)); - - return () => - { - if (@interface.HasMethods) - foreach (var method in @interface.Methods) - { - Method resultMethod = new(method.Name) - { - IR = method, - Defined = true, - Owner = result - }; - - result.Content.Add(resultMethod); - - if (resultMethod.Name is not null && resultMethod.Name != string.Empty) - { - if (!result.Members.TryGetValue(resultMethod.Name, out var group)) - result.Members.Add(resultMethod.Name, group = new OverloadGroup(resultMethod.Name)); - - if (group is not OverloadGroup overloadGroup) - throw new InvalidOperationException(); - - overloadGroup.Overloads.Add(resultMethod); - } - resultMethod.Signature = Load(method.Signature); - resultMethod.ReturnType = Load(method.ReturnType); - } - }; - } - - private Action Load(ZSharp.IR.EnumClass @enum, Module owner) - { - EnumClass result = new(@enum.Name ?? string.Empty) - { - IR = @enum, - IsDefined = true, - }; - - Context.Objects.Cache(@enum, result); - - owner.Content.Add(result); - - if (result.Name is not null && result.Name != string.Empty) - owner.Members.Add(result.Name, result); - - return () => - { - result.MemberType = Load(@enum.Type); - - foreach (var value in @enum.Values) - { - var valueResult = new EnumValue(value.Name) - { - Value = new RawCode(new(value.Value) - { - Types = [result] - }), - Owner = result - }; - result.Values[value.Name] = valueResult; - } - }; - } - - private Action Load(ZSharp.IR.ValueType valueType, Module owner) - { - Objects.ValueType result = new(valueType.Name ?? string.Empty) - { - IR = valueType, - IsDefined = true, - }; - - Context.Objects.Cache(valueType, result); - - owner.Content.Add(result); - - if (result.Name is not null && result.Name != string.Empty) - owner.Members.Add(result.Name, result); - - return () => - { - - }; - } - - private IType Load(ZSharp.IR.IType type) - { - if (Context.Types.Cache(type, out var result)) - return result; - - return type switch - { - ZSharp.IR.ClassReference classReference => Load(classReference), - ZSharp.IR.ConstructedClass constructedClass => Load(constructedClass), - ZSharp.IR.InterfaceReference interfaceReference => Load(interfaceReference), - _ => null! - }; - } - - private IType Load(ZSharp.IR.ClassReference classReference) - => Context.Objects.Cache(classReference.Definition) ?? throw new(); - - private IType Load(ZSharp.IR.ConstructedClass constructed) - { - - if (Context.Objects.Cache(constructed.Class, out var genericInstantiable)) - { - var instance = genericInstantiable.Instantiate( - Compiler, - [.. constructed.Arguments.Select( - arg => new Argument( - Load(arg) - ) - )] - ).Unwrap(); - - if (instance is not IType type) - throw new("Generic instaitation returned a non-type object"); - - return type; - } - - return Context.Types.Cache(constructed) ?? throw new(); - } - - private IType Load(ZSharp.IR.InterfaceReference interfaceReference) - => Context.Objects.Cache(interfaceReference.Definition) ?? throw new(); - - private Action LoadGenericClass(ZSharp.IR.Class @class, Module owner) - { - GenericClass result = new() - { - Name = @class.Name ?? string.Empty, - IR = new(@class), - Defined = true, - }; - - Context.Objects.Cache(@class, result); - - owner.Content.Add(result); - - if (result.Name is not null && result.Name != string.Empty) - owner.Members.Add(result.Name, result); - - if (@class.Base is not null) - result.Base = (IClass)Load(@class.Base); - - var self = new GenericClassInstance(result, new() - { - Scope = result, - CompileTimeValues = new() - }); - - if (@class.HasGenericParameters) - foreach (var parameter in @class.GenericParameters) - { - var genericParameter = new GenericParameter() - { - Name = parameter.Name, - IR = parameter, - }; - - Context.Types.Cache(parameter, genericParameter); - self.Context[genericParameter] = genericParameter; - - result.GenericParameters.Add(genericParameter); - } - - return () => - { - - - if (@class.HasFields) - foreach (var field in @class.Fields) - { - Field resultField = new(field.Name) - { - IR = field, - Type = Load(field.Type), - }; - if (field.Initializer is not null) - resultField.Initializer = new RawCode(new(field.Initializer) - { - Types = [resultField.Type] - }); - result.Members.Add(resultField.Name, resultField); - } - ; - - if (@class.Constructors.Count > 0) - foreach (var constructor in @class.Constructors) - { - Constructor resultConstructor = new(constructor.Name) - { - Owner = self, - IR = constructor, - }; - if (resultConstructor.Name is not null && resultConstructor.Name != string.Empty) - { - if (!result.Members.TryGetValue(resultConstructor.Name, out var group)) - result.Members.Add(resultConstructor.Name, group = new OverloadGroup(resultConstructor.Name)); - - if (group is not OverloadGroup overloadGroup) - throw new InvalidOperationException(); - - overloadGroup.Overloads.Add(resultConstructor); - } - else - { - if (result.Constructor is not OverloadGroup group) - result.Constructor = group = new OverloadGroup(string.Empty); - - group.Overloads.Add(resultConstructor); - } - resultConstructor.Signature = Load(constructor.Method.Signature); - } - - if (@class.Methods.Count > 0) - foreach (var method in @class.Methods) - { - Method resultMethod = new(method.Name) - { - IR = method, - Defined = true, - Owner = result - }; - if (resultMethod.Name is not null && resultMethod.Name != string.Empty) - { - if (!result.Members.TryGetValue(resultMethod.Name, out var group)) - result.Members.Add(resultMethod.Name, group = new OverloadGroup(resultMethod.Name)); - - if (group is not OverloadGroup overloadGroup) - throw new InvalidOperationException(); - - overloadGroup.Overloads.Add(resultMethod); - } - resultMethod.Signature = Load(method.Signature); - } - }; - } - - private Action LoadGenericFunction(ZSharp.IR.Function function, Module owner) - { - GenericFunction result = new(function.Name) - { - IR = function, - Defined = true, - }; - - Context.Objects.Cache(function, result); - - owner.Content.Add(result); - - if (result.Name != string.Empty) - { - if (!owner.Members.TryGetValue(result.Name, out var group)) - owner.Members.Add(result.Name, group = new OverloadGroup(result.Name)); - - if (group is not OverloadGroup overloadGroup) - throw new InvalidOperationException(); - - overloadGroup.Overloads.Add(result); - } - - return () => - { - foreach (var parameter in function.GenericParameters) - { - var genericParameter = new GenericParameter() - { - Name = parameter.Name, - IR = parameter, - }; - - Context.Types.Cache(parameter, genericParameter); - - result.GenericParameters.Add(genericParameter); - } - - result.Signature = Load(function.Signature); - }; - } - - private Signature Load(ZSharp.IR.Signature signature) - { - Signature result = new() - { - ReturnType = Load(signature.ReturnType) - }; - - if (signature.HasArgs) - foreach (var arg in signature.Args.Parameters) - result.Args.Add(LoadParameter(arg)); - - if (signature.IsVarArgs) - result.VarArgs = LoadVarParameter(signature.Args.Var!); - - if (signature.HasKwArgs) - foreach (var arg in signature.KwArgs.Parameters) - result.KwArgs.Add(LoadParameter(arg)); - - if (signature.IsVarKwArgs) - result.VarKwArgs = LoadVarParameter(signature.KwArgs.Var!); - - return result; - } - - private Parameter LoadParameter(ZSharp.IR.Parameter parameter) - { - var type = Load(parameter.Type); - - return new(parameter.Name) - { - IR = parameter, - Initializer = parameter.Initializer is null ? null : new RawCode(new(parameter.Initializer) - { - Types = [type] - }), - Type = type, - }; - } - - private VarParameter LoadVarParameter(ZSharp.IR.Parameter parameter) - { - var type = Load(parameter.Type); - - if (parameter.Initializer is not null) - throw new NotImplementedException(); - - return new(parameter.Name) - { - IR = parameter, - Type = type, - }; - } - } -} diff --git a/ZSharp.Importer.IRLoader/ir loader/IRLoader.cs b/ZSharp.Importer.IRLoader/ir loader/IRLoader.cs deleted file mode 100644 index 4537aa31..00000000 --- a/ZSharp.Importer.IRLoader/ir loader/IRLoader.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace ZSharp.Importer.IRLoader -{ - public sealed partial class IRLoader : Feature - { - public IRLoader(Compiler compiler) : base(compiler) - { - Initialize(); - } - - private void Initialize() - { - foreach (var type in new IType[] { - Compiler.TypeSystem.Type, - Compiler.TypeSystem.Float32, - Compiler.TypeSystem.String, - Compiler.TypeSystem.Int32, - Compiler.TypeSystem.Void, - Compiler.TypeSystem.Boolean, - Compiler.TypeSystem.Object, - }) - Context.Types.Cache(Compiler.CompileIRType(type), type); - - Context.Objects.Cache(Compiler.TypeSystem.ArrayType.IR, Compiler.TypeSystem.ArrayType); - Context.Objects.Cache(Compiler.TypeSystem.ReferenceType.IR, Compiler.TypeSystem.ReferenceType); - } - } -} diff --git a/ZSharp.Importer.RT/GlobalUsings.cs b/ZSharp.Importer.RT/GlobalUsings.cs index 861e2e1e..f45b91d8 100644 --- a/ZSharp.Importer.RT/GlobalUsings.cs +++ b/ZSharp.Importer.RT/GlobalUsings.cs @@ -2,5 +2,6 @@ global using CompilerObject = ZSharp.Compiler.CompilerObject; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; global using TargetPlatform = object; diff --git a/ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs b/ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs index 69820d69..1f82e907 100644 --- a/ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs +++ b/ZSharp.Importer.RT/objects/string/StringLiteral.IR.cs @@ -5,7 +5,7 @@ namespace ZSharp.Importer.RT.Objects partial class StringLiteral : ICompileIRCode { - Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, TargetPlatform? target) + IResult ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, TargetPlatform? target) => Result.Ok(new([ new IR.VM.PutString(value) ]) diff --git a/ZSharp.Importer.RT/rt loader/Loader.Load.cs b/ZSharp.Importer.RT/rt loader/Loader.Load.cs index 7fa4939f..ee6542db 100644 --- a/ZSharp.Importer.RT/rt loader/Loader.Load.cs +++ b/ZSharp.Importer.RT/rt loader/Loader.Load.cs @@ -1,15 +1,15 @@ namespace ZSharp.Importer.RT { - public delegate Result LoadObject(RTObject? @object); + public delegate IResult LoadObject(RTObject? @object); partial class Loader { public LoadObject LoadObject; - public Result Load(RTObject? @object) + public IResult Load(RTObject? @object) => LoadObject(@object); - private Result DefaultLoader(RTObject? @object) + private IResult DefaultLoader(RTObject? @object) => @object switch { CompilerObject co => Result.Ok(co), diff --git a/ZSharp.Interpreter/interpreter/Interpreter.Evaluate.cs b/ZSharp.Interpreter/interpreter/Interpreter.Evaluate.cs index b42cd56e..09872504 100644 --- a/ZSharp.Interpreter/interpreter/Interpreter.Evaluate.cs +++ b/ZSharp.Interpreter/interpreter/Interpreter.Evaluate.cs @@ -4,7 +4,7 @@ namespace ZSharp.Interpreter { partial class Interpreter { - public Result Evaluate( + public IResult Evaluate( CompilerObject @object, Platform.Runtime.IEvaluationContext? evaluationContext = null ) diff --git a/ZSharp.SourceCompiler.Common/CompileExpression.cs b/ZSharp.SourceCompiler.Common/CompileExpression.cs index cbdd8ec8..415f7356 100644 --- a/ZSharp.SourceCompiler.Common/CompileExpression.cs +++ b/ZSharp.SourceCompiler.Common/CompileExpression.cs @@ -1,4 +1,4 @@ namespace ZSharp.SourceCompiler { - public delegate Result CompileExpression(AST.Expression expression); + public delegate IResult CompileExpression(AST.Expression expression); } diff --git a/ZSharp.SourceCompiler.Common/GlobalUsings.cs b/ZSharp.SourceCompiler.Common/GlobalUsings.cs index d78b7439..e7d94052 100644 --- a/ZSharp.SourceCompiler.Common/GlobalUsings.cs +++ b/ZSharp.SourceCompiler.Common/GlobalUsings.cs @@ -1,3 +1,4 @@ global using ZSharp.Compiler; global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs b/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs index 2b9c012a..72d94b1a 100644 --- a/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs +++ b/ZSharp.SourceCompiler.Common/expression compiler/ExpressionCompiler.Compile.cs @@ -1,12 +1,12 @@ namespace ZSharp.SourceCompiler { - public delegate Result PostProcess(Result result); + public delegate IResult PostProcess(IResult result); partial class ExpressionCompiler { public PostProcess PostProcess { get; init; } = r => r; - public Result Compile(AST.Expression expression) + public IResult Compile(AST.Expression expression) => PostProcess(expression switch { AST.BinaryExpression binary => Compile(binary), diff --git a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Binary.cs b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Binary.cs index 5b878ed6..d9a9bf86 100644 --- a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Binary.cs +++ b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Binary.cs @@ -2,7 +2,7 @@ { partial class ExpressionCompiler { - private Result Compile(AST.BinaryExpression binary) + private IResult Compile(AST.BinaryExpression binary) { if ( Compile(binary.Left) diff --git a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Call.cs b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Call.cs index 196a8e03..659163f0 100644 --- a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Call.cs +++ b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Call.cs @@ -2,7 +2,7 @@ { partial class ExpressionCompiler { - private Result Compile(AST.CallExpression call) + private IResult Compile(AST.CallExpression call) { var calleeResult = Compile(call.Callee); @@ -15,14 +15,14 @@ private Result Compile(AST.CallExpression call) ); var argumentResults = call.Arguments - .Select(arg => + .Select>(arg => { if ( Compile(arg.Value) .When(out var argValue) .Error(out var error) ) return Result.Error(error); - + return Result.Ok( new( arg.Name, @@ -35,7 +35,7 @@ private Result Compile(AST.CallExpression call) if (argumentResults.Any(r => r.IsError)) return Result.Error( $"Failed to compile arguments: { - (string.Join(", ", Enumerable.Where>(argumentResults, (Func, bool>)(r => r.IsError)).Select(r => r.Error(out var error) ? error : throw new()))) + (string.Join(", ", Enumerable.Where(argumentResults, (r => r.IsError)).Select(r => r.UnwrapError()))) }" ); diff --git a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Identifier.cs b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Identifier.cs index 29bba233..fd1bac64 100644 --- a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Identifier.cs +++ b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Identifier.cs @@ -2,7 +2,7 @@ { partial class ExpressionCompiler { - private Result Compile(AST.IdentifierExpression identifier) + private IResult Compile(AST.IdentifierExpression identifier) { foreach (var scope in Interpreter.Compiler.CurrentContext.FindContext()) if (scope.Get(identifier.Name).Ok(out var result)) diff --git a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs index 61bfadb9..13d2e017 100644 --- a/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs +++ b/ZSharp.SourceCompiler.Common/expression compiler/compile/ExpressionCompiler.Compile.Literal.cs @@ -2,7 +2,7 @@ { partial class ExpressionCompiler { - private Result Compile(AST.LiteralExpression literal) + private IResult Compile(AST.LiteralExpression literal) { if (literal.UnitType is not null) Interpreter.Log.Warning($"Literal has a unit type '{literal.UnitType}' which will be ignored.", new NodeLogOrigin(literal)); diff --git a/ZSharp.SourceCompiler.Common/importers/CoreLibraryImporter.cs b/ZSharp.SourceCompiler.Common/importers/CoreLibraryImporter.cs index 6380a90a..547e954b 100644 --- a/ZSharp.SourceCompiler.Common/importers/CoreLibraryImporter.cs +++ b/ZSharp.SourceCompiler.Common/importers/CoreLibraryImporter.cs @@ -8,7 +8,7 @@ public sealed class CoreLibraryImporter public void Add(string name, CompilerObject obj) => libraries.Add(name, obj); - Result IStringImporter.Import(string source) + IResult IStringImporter.Import(string source) { if (libraries.TryGetValue(source, out var result)) return Result.Ok(result); diff --git a/ZSharp.SourceCompiler.Common/importers/StandardLibraryImporter.cs b/ZSharp.SourceCompiler.Common/importers/StandardLibraryImporter.cs index efd8f674..3eec364c 100644 --- a/ZSharp.SourceCompiler.Common/importers/StandardLibraryImporter.cs +++ b/ZSharp.SourceCompiler.Common/importers/StandardLibraryImporter.cs @@ -8,7 +8,7 @@ public sealed class StandardLibraryImporter public void Add(string name, CompilerObject obj) => libraries.Add(name, obj); - Result IStringImporter.Import(string source) + IResult IStringImporter.Import(string source) { if (libraries.TryGetValue(source, out var result)) return Result.Ok(result); diff --git a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.Boolean.cs b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.Boolean.cs index ae8344ed..0202c2d6 100644 --- a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.Boolean.cs +++ b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.Boolean.cs @@ -2,10 +2,10 @@ { partial class LiteralCompiler { - private Result CompileFalse(AST.LiteralExpression expression) + private IResult CompileFalse(AST.LiteralExpression expression) => Result.Ok(new BooleanLiteral(false)); - private Result CompileTrue(AST.LiteralExpression expression) + private IResult CompileTrue(AST.LiteralExpression expression) => Result.Ok(new BooleanLiteral(true)); } } diff --git a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs index e2da1ba1..687f184e 100644 --- a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs +++ b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.String.cs @@ -2,7 +2,7 @@ { partial class LiteralCompiler { - private Result CompileString(AST.LiteralExpression expression) + private IResult CompileString(AST.LiteralExpression expression) { return Interpreter.RTLoader.Load(expression.Value); } diff --git a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.cs b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.cs index e17aedd1..6505153f 100644 --- a/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.cs +++ b/ZSharp.SourceCompiler.Common/literal compiler/LiteralCompiler.Compile.cs @@ -2,7 +2,7 @@ { partial class LiteralCompiler { - public Result Compile(AST.LiteralExpression expression) + public IResult Compile(AST.LiteralExpression expression) => expression.Type switch { AST.LiteralType.String => CompileString(expression), @@ -14,7 +14,7 @@ public Result Compile(AST.LiteralExpression expression) _ => Result.Error($"Invalid literal type: {expression.Type}"), }; - private Result NotImplemented(AST.LiteralExpression expression) + private IResult NotImplemented(AST.LiteralExpression expression) => Result.Error($"Literal type not implemented: {expression.Type}"); } } diff --git a/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs b/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs index 3a7b69ae..276db0e0 100644 --- a/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs +++ b/ZSharp.SourceCompiler.Common/objects/code/block/CodeBlock.IR.cs @@ -4,7 +4,7 @@ namespace ZSharp.SourceCompiler partial class CodeBlock : ICompileIRCode { - Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) + IResult ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) { var code = new IRCode(); diff --git a/ZSharp.SourceCompiler.Common/objects/code/return/Return.IR.cs b/ZSharp.SourceCompiler.Common/objects/code/return/Return.IR.cs index 83c77f07..6639e749 100644 --- a/ZSharp.SourceCompiler.Common/objects/code/return/Return.IR.cs +++ b/ZSharp.SourceCompiler.Common/objects/code/return/Return.IR.cs @@ -4,7 +4,7 @@ namespace ZSharp.SourceCompiler partial class Return : ICompileIRCode { - Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) + IResult ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) { var code = new IRCode(); diff --git a/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs b/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs index 15144abe..ffb5c731 100644 --- a/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs +++ b/ZSharp.SourceCompiler.Common/objects/literals/bool/BooleanLiteral.IR.cs @@ -3,7 +3,7 @@ partial class BooleanLiteral : ICompileIRCode { - Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) + IResult ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) => Result.Ok( new([ new IR.VM.PutBoolean(value) diff --git a/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs b/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs index 08640738..8199121b 100644 --- a/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs +++ b/ZSharp.SourceCompiler.Common/objects/literals/string/StringLiteral.IR.cs @@ -3,7 +3,7 @@ partial class StringLiteral : ICompileIRCode { - Result ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) + IResult ICompileIRCode.CompileIRCode(Compiler.Compiler compiler, object? target) => Result.Ok( new([ new IR.VM.PutString(value) diff --git a/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs b/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs index bd70b454..06f660e8 100644 --- a/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs +++ b/ZSharp.SourceCompiler.Common/top-level expression compiler/TopLevelExpressionCompiler.cs @@ -4,11 +4,11 @@ public sealed class TopLevelExpressionCompiler(Interpreter.Interpreter interpret { public Interpreter.Interpreter Interpreter { get; } = interpreter; - public Func CompileExpression { get; init; } = new ExpressionCompiler(interpreter).Compile; + public Func CompileExpression { get; init; } = new ExpressionCompiler(interpreter).Compile; - public Func LoadCO { get; init; } = interpreter.RTLoader.Load; + public Func LoadCO { get; init; } = interpreter.RTLoader.Load; - public Result Compile(AST.Expression expression) + public IResult Compile(AST.Expression expression) => CompileExpression(expression); } } diff --git a/ZSharp.SourceCompiler.Core/GlobalUsings.cs b/ZSharp.SourceCompiler.Core/GlobalUsings.cs new file mode 100644 index 00000000..d2fb58a6 --- /dev/null +++ b/ZSharp.SourceCompiler.Core/GlobalUsings.cs @@ -0,0 +1,3 @@ +global using ZSharp.Compiler; + +global using IResult = IResult; diff --git a/ZSharp.SourceCompiler.Core/custom importer/string importer/IStringImporter.cs b/ZSharp.SourceCompiler.Core/custom importer/string importer/IStringImporter.cs index 00d7ea58..2f5ecea0 100644 --- a/ZSharp.SourceCompiler.Core/custom importer/string importer/IStringImporter.cs +++ b/ZSharp.SourceCompiler.Core/custom importer/string importer/IStringImporter.cs @@ -1,10 +1,7 @@ -using ZSharp.Compiler; -using ZSharp.Objects; - -namespace ZSharp.SourceCompiler +namespace ZSharp.SourceCompiler { public interface IStringImporter { - public Result Import(string source); + public IResult Import(string source); } } diff --git a/ZSharp.SourceCompiler.Core/custom importer/string importer/StringImporter.cs b/ZSharp.SourceCompiler.Core/custom importer/string importer/StringImporter.cs index 9ed17139..6f57ed7b 100644 --- a/ZSharp.SourceCompiler.Core/custom importer/string importer/StringImporter.cs +++ b/ZSharp.SourceCompiler.Core/custom importer/string importer/StringImporter.cs @@ -1,6 +1,5 @@ using CommonZ.Utils; using ZSharp.Compiler; -using ZSharp.Objects; namespace ZSharp.SourceCompiler { @@ -11,7 +10,7 @@ public sealed class StringImporter public IStringImporter? DefaultImporter { get; set; } - public Result Import(string source) + public IResult Import(string source) { var parts = source.Split(':', count: 2, options: StringSplitOptions.TrimEntries); if (parts.Length > 1) diff --git a/ZSharp.SourceCompiler.Module/GlobalUsings.cs b/ZSharp.SourceCompiler.Module/GlobalUsings.cs index d9379d54..f923ef3b 100644 --- a/ZSharp.SourceCompiler.Module/GlobalUsings.cs +++ b/ZSharp.SourceCompiler.Module/GlobalUsings.cs @@ -5,3 +5,4 @@ global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.SourceCompiler.Module/class compiler/compile/Compile.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/Compile.cs index 0f790fa2..2bfc8a8f 100644 --- a/ZSharp.SourceCompiler.Module/class compiler/compile/Compile.cs +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/Compile.cs @@ -2,7 +2,7 @@ { partial class ClassCompiler { - public Result Compile() + public IResult Declare() { tasks.RunUntilComplete(); @@ -32,7 +32,7 @@ private void InitCompile() ); } - private Result Compile(AST.Statement statement) + private IResult Compile(AST.Statement statement) => statement switch { AST.DefinitionStatement definitionStatement => Compile(definitionStatement), diff --git a/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Call.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Call.cs index bbe9cd70..6e1f835e 100644 --- a/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Call.cs +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Call.cs @@ -2,7 +2,7 @@ { partial class ClassCompiler { - private Result Compile(AST.CallExpression call) + private IResult Compile(AST.CallExpression call) { var calleeResult = Compile(call.Callee); @@ -15,7 +15,7 @@ private Result Compile(AST.CallExpression call) ); var argumentResults = call.Arguments - .Select(arg => + .Select>(arg => { if ( Compile(arg.Value) @@ -35,7 +35,7 @@ private Result Compile(AST.CallExpression call) if (argumentResults.Any(r => r.IsError)) return Result.Error( $"Failed to compile arguments: { - (string.Join(", ", Enumerable.Where>(argumentResults, (Func, bool>)(r => r.IsError)).Select(r => r.Error(out var error) ? error : throw new()))) + (string.Join(", ", Enumerable.Where(argumentResults, (r => r.IsError)).Select(r => r.UnwrapError()))) }" ); diff --git a/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Expression.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Expression.cs index 61d5c47a..5837c534 100644 --- a/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Expression.cs +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Expression.cs @@ -2,7 +2,7 @@ { partial class ClassCompiler { - private Result Compile(AST.Expression expression) + private IResult Compile(AST.Expression expression) => expression switch { AST.Function function => Compile(function), diff --git a/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Function.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Function.cs index 47a8f651..1c88924e 100644 --- a/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Function.cs +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/expr/Function.cs @@ -2,7 +2,7 @@ { partial class ClassCompiler { - private Result Compile(AST.Function function) + private IResult Compile(AST.Function function) { var compiler = new FunctionCompiler(Interpreter, function); diff --git a/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Definition.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Definition.cs index 90e831d4..506d6b12 100644 --- a/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Definition.cs +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Definition.cs @@ -2,7 +2,7 @@ { partial class ClassCompiler { - private Result Compile(AST.DefinitionStatement definitionStatement) + private IResult Compile(AST.DefinitionStatement definitionStatement) => definitionStatement.Definition switch { AST.Function function => Compile(function), diff --git a/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Expression.cs b/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Expression.cs index 7eb6bfd8..3bc8d570 100644 --- a/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Expression.cs +++ b/ZSharp.SourceCompiler.Module/class compiler/compile/stmt/Expression.cs @@ -2,7 +2,7 @@ { partial class ClassCompiler { - private Result Compile(AST.ExpressionStatement expressionStatement) + private IResult Compile(AST.ExpressionStatement expressionStatement) => CompileExpression(expressionStatement.Expression); } } diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/FunctionBodyCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/FunctionBodyCompiler.Compile.cs index fd9fe28f..c11455a8 100644 --- a/ZSharp.SourceCompiler.Module/function body compiler/compile/FunctionBodyCompiler.Compile.cs +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/FunctionBodyCompiler.Compile.cs @@ -2,7 +2,7 @@ { partial class FunctionBodyCompiler { - public Result Compile() + public IResult Compile() => Compile(Node); } } diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.Function.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.Function.cs index 197b3665..ec6e7787 100644 --- a/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.Function.cs +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.Function.cs @@ -2,7 +2,7 @@ { partial class FunctionBodyCompiler { - private Result Compile(AST.Function function) + private IResult Compile(AST.Function function) { var compiler = new FunctionCompiler(Interpreter, function); diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.cs index 72c952d0..446b7be6 100644 --- a/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.cs +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/expr/FunctionBodyCompiler.Compile.cs @@ -2,7 +2,7 @@ { partial class FunctionBodyCompiler { - private Result Compile(AST.Expression expression) + private IResult Compile(AST.Expression expression) => expression switch { AST.Function function => Compile(function), diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Block.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Block.cs index 0d977ab6..6ff70b39 100644 --- a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Block.cs +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Block.cs @@ -2,7 +2,7 @@ { partial class FunctionBodyCompiler { - private Result Compile(AST.BlockStatement block) + private IResult Compile(AST.BlockStatement block) { var result = new CodeBlock(); diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Definition.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Definition.cs index 122d6b23..75115bb9 100644 --- a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Definition.cs +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Definition.cs @@ -2,7 +2,7 @@ { partial class FunctionBodyCompiler { - private Result Compile(AST.DefinitionStatement definitionStatement) + private IResult Compile(AST.DefinitionStatement definitionStatement) => Compile(definitionStatement.Definition); } } diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Expression.cs index a52451b7..e022b452 100644 --- a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Expression.cs +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.Expression.cs @@ -2,7 +2,7 @@ { partial class FunctionBodyCompiler { - private Result Compile(AST.ExpressionStatement expressionStatement) + private IResult Compile(AST.ExpressionStatement expressionStatement) => CompileExpression(expressionStatement.Expression); } } diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs index 1775a5c4..417e74a0 100644 --- a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Compile.cs @@ -2,7 +2,7 @@ { partial class FunctionBodyCompiler { - private Result Compile(AST.Statement statement) + private IResult Compile(AST.Statement statement) => statement switch { AST.BlockStatement block => Compile(block), diff --git a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Return.cs b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Return.cs index 1c2ed511..64cf2da3 100644 --- a/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Return.cs +++ b/ZSharp.SourceCompiler.Module/function body compiler/compile/stmt/FunctionBodyCompiler.Return.cs @@ -2,7 +2,7 @@ { partial class FunctionBodyCompiler { - private Result Compile(AST.Return @return) + private IResult Compile(AST.Return @return) { CompilerObject? value = null; diff --git a/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs index 40541fd8..dab4aa9e 100644 --- a/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs +++ b/ZSharp.SourceCompiler.Module/function compiler/FunctionCompiler.Compile.cs @@ -2,7 +2,7 @@ { partial class FunctionCompiler { - public Result Declare() + public IResult Declare() { Error? error = null; @@ -71,7 +71,7 @@ public void CompileBody() Object.Body = body; } - private Result Compile(AST.Parameter parameter) + private IResult Compile(AST.Parameter parameter) { return Result.Error($"Parameter {parameter.Name} did not compile because parameter compilation is not implemented."); } diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/ModuleCompiler.Compile.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/ModuleCompiler.Compile.cs index fc60b1fa..53190771 100644 --- a/ZSharp.SourceCompiler.Module/module compiler/compile/ModuleCompiler.Compile.cs +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/ModuleCompiler.Compile.cs @@ -2,7 +2,7 @@ { partial class ModuleCompiler { - public Result Compile() + public IResult Compile() { tasks.RunUntilComplete(); @@ -32,7 +32,7 @@ private void InitCompile() ); } - private Result Compile(AST.Statement statement) + private IResult Compile(AST.Statement statement) => statement switch { AST.DefinitionStatement definitionStatement => Compile(definitionStatement), diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/def/ModuleCompiler.Compile.Function.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/def/ModuleCompiler.Compile.Function.cs index 1198030f..7231ef7c 100644 --- a/ZSharp.SourceCompiler.Module/module compiler/compile/def/ModuleCompiler.Compile.Function.cs +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/def/ModuleCompiler.Compile.Function.cs @@ -2,7 +2,7 @@ { partial class ModuleCompiler { - private Result Compile(AST.Function function) + private IResult Compile(AST.Function function) { var compiler = new FunctionCompiler(Interpreter, function); diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Call.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Call.cs index c61fedda..74d737bc 100644 --- a/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Call.cs +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Call.cs @@ -2,7 +2,7 @@ { partial class ModuleCompiler { - private Result Compile(AST.CallExpression call) + private IResult Compile(AST.CallExpression call) { var calleeResult = Compile(call.Callee); @@ -15,7 +15,7 @@ private Result Compile(AST.CallExpression call) ); var argumentResults = call.Arguments - .Select(arg => + .Select>(arg => { if ( Compile(arg.Value) @@ -35,7 +35,7 @@ private Result Compile(AST.CallExpression call) if (argumentResults.Any(r => r.IsError)) return Result.Error( $"Failed to compile arguments: { - (string.Join(", ", Enumerable.Where>(argumentResults, (Func, bool>)(r => r.IsError)).Select(r => r.Error(out var error) ? error : throw new()))) + (string.Join(", ", Enumerable.Where(argumentResults, (r => r.IsError)).Select(r => r.UnwrapError()))) }" ); diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Expression.cs index 50c7819f..cf7d4f9b 100644 --- a/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Expression.cs +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/expr/ModuleCompiler.Compile.Expression.cs @@ -2,7 +2,7 @@ { partial class ModuleCompiler { - private Result Compile(AST.Expression expression) + private IResult Compile(AST.Expression expression) => expression switch { AST.Function function => Compile(function), diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Definition.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Definition.cs index bc33688a..0dfb379b 100644 --- a/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Definition.cs +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Definition.cs @@ -2,7 +2,7 @@ { partial class ModuleCompiler { - private Result Compile(AST.DefinitionStatement definitionStatement) + private IResult Compile(AST.DefinitionStatement definitionStatement) => definitionStatement.Definition switch { AST.Function function => Compile(function), diff --git a/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs index 8d65e937..2577fa33 100644 --- a/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs +++ b/ZSharp.SourceCompiler.Module/module compiler/compile/stmt/ModuleCompiler.Compile.Expression.cs @@ -2,7 +2,7 @@ { partial class ModuleCompiler { - private Result Compile(AST.ExpressionStatement expressionStatement) + private IResult Compile(AST.ExpressionStatement expressionStatement) { var valueObjectResult = Compile(expressionStatement.Expression); diff --git a/ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs b/ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs index 2c691144..26a682fa 100644 --- a/ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs +++ b/ZSharp.SourceCompiler.Module/objects/forward reference/ForwardReference.cs @@ -11,7 +11,7 @@ internal sealed class ForwardReference bool CompilerObject.Is([NotNullWhen(true)] out T? result) where T : class => Inner.Is(out result); - Result IProxy.Apply(Func> fn) + IResult IProxy.Apply(Func> fn) => fn(Inner); } } diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs index d4a66179..7f353d9b 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.Call.cs @@ -5,7 +5,7 @@ namespace ZSharp.SourceCompiler.Module.Objects partial class Function : ICTCallable { - Result ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) + IResult ICTCallable.Call(Compiler.Compiler compiler, Argument[] arguments) { IRCode result = new(); diff --git a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs index ca6aacb4..0699e1d3 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/function/Function.IR.cs @@ -26,10 +26,10 @@ partial class Function } } - Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) + IResult ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) => CompileIR(compiler, target); - private Result CompileIR(Compiler.Compiler compiler, object? target) + private IResult CompileIR(Compiler.Compiler compiler, object? target) { if (ReturnType is null) return Result.Error( diff --git a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs index d9566b2e..f40f638c 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/global/Global.IR.cs @@ -6,7 +6,7 @@ partial class Global { public IR.Global? IR { get; private set; } - Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) + IResult ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) { if (IR is null) { diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs index 00988013..04b2d614 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.IR.cs @@ -5,7 +5,7 @@ partial class Module { public IR.Module? IR { get; private set; } - Result ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) + IResult ICompileIRDefinitionAs.CompileIRDefinition(Compiler.Compiler compiler, object? target) { IR ??= new(Name); diff --git a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs index be80b32c..a8aed1bc 100644 --- a/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs +++ b/ZSharp.SourceCompiler.Module/objects/modular/module/Module.Member.cs @@ -5,7 +5,7 @@ partial class Module { private readonly Dictionary members = []; - public Result AddMember(string name, CompilerObject member) + public IResult AddMember(string name, CompilerObject member) { if (members.ContainsKey(name)) return Result.Error($"Member '{name}' is already defined in module '{Name}'."); @@ -15,7 +15,7 @@ public Result AddMember(string name, CompilerObject member) return Result.Ok(member); } - Result ICTGetMember.Member(Compiler.Compiler compiler, string member) + IResult ICTGetMember.Member(Compiler.Compiler compiler, string member) { if (members.TryGetValue(member, out var obj)) return Result.Ok(obj); diff --git a/ZSharp.SourceCompiler.Script/GlobalUsings.cs b/ZSharp.SourceCompiler.Script/GlobalUsings.cs index 05db7df2..501033a9 100644 --- a/ZSharp.SourceCompiler.Script/GlobalUsings.cs +++ b/ZSharp.SourceCompiler.Script/GlobalUsings.cs @@ -1 +1,2 @@ global using Result = ZSharp.Compiler.Result; +global using IResult = IResult; diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/def/ScriptCompiler.Compile.Module.cs b/ZSharp.SourceCompiler.Script/compiler/compile/def/ScriptCompiler.Compile.Module.cs index a90fb813..e50b0e8d 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/def/ScriptCompiler.Compile.Module.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/def/ScriptCompiler.Compile.Module.cs @@ -4,7 +4,7 @@ namespace ZSharp.SourceCompiler.Script { partial class ScriptCompiler { - private Result Compile(AST.Module module) + private IResult Compile(AST.Module module) { var moduleCompiler = new Module.ModuleCompiler(Interpreter, module); diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Call.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Call.cs index ce47020f..e9018de6 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Call.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Call.cs @@ -4,7 +4,7 @@ namespace ZSharp.SourceCompiler.Script { partial class ScriptCompiler { - private Result Compile(AST.CallExpression call) + private IResult Compile(AST.CallExpression call) { var calleeResult = Compile(call.Callee); @@ -17,7 +17,7 @@ private Result Compile(AST.CallExpression call) ); var argumentResults = call.Arguments - .Select(arg => + .Select>(arg => { if ( Compile(arg.Value) @@ -37,7 +37,7 @@ private Result Compile(AST.CallExpression call) if (argumentResults.Any(r => r.IsError)) return Result.Error( $"Failed to compile arguments: { - (string.Join(", ", Enumerable.Where>(argumentResults, (Func, bool>)(r => r.IsError)).Select(r => r.Error(out var error) ? error : throw new()))) + (string.Join(", ", Enumerable.Where(argumentResults, (r => r.IsError)).Select(r => r.UnwrapError()))) }" ); diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs index 741f382f..da544bdc 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Expression.cs @@ -1,8 +1,10 @@ -namespace ZSharp.SourceCompiler.Script +using ZSharp.Compiler; + +namespace ZSharp.SourceCompiler.Script { partial class ScriptCompiler { - private Result Compile(AST.Expression expression) + private IResult Compile(AST.Expression expression) => PostProcess( expression switch { @@ -14,16 +16,14 @@ private Result Compile(AST.Expression expression) } ); - private Result PostProcess(Result result) + private IResult PostProcess(IResult result) { if (!result.Ok(out var value)) return result; if (Options.EvaluationTarget == EvaluationTarget.Statement) return result; - return Interpreter // do we realy want to support expression-level evaluation? - .Evaluate(value) - .When(Interpreter.RTLoader.Load); + return Interpreter.Evaluate(value).When(Interpreter.RTLoader.Load); } } } diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs index b0ae8c18..acf4e1d9 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Identifier.cs @@ -4,7 +4,7 @@ namespace ZSharp.SourceCompiler.Script { partial class ScriptCompiler { - private Result Compile(AST.IdentifierExpression identifier) + private IResult Compile(AST.IdentifierExpression identifier) { foreach (var scope in Interpreter.Compiler.CurrentContext.FindContext()) if (scope.Get(identifier.Name).Ok(out var result)) diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs index d9502693..8c89a4e8 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/expr/ScriptCompiler.Compile.Literal.cs @@ -2,7 +2,7 @@ { partial class ScriptCompiler { - private Result Compile(AST.LiteralExpression literal) + private IResult Compile(AST.LiteralExpression literal) { if (literal.UnitType is not null) Interpreter.Log.Warning($"Literal has a unit type '{literal.UnitType}' which will be ignored.", new NodeLogOrigin(literal)); diff --git a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs index 7ad0ceef..10090bb6 100644 --- a/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs +++ b/ZSharp.SourceCompiler.Script/compiler/compile/stmt/ScriptCompiler.Compile.Import.cs @@ -16,7 +16,7 @@ .. import.Arguments ?? [] ]; var argumentsResults = arguments - .Select((arg, i) => + .Select>((arg, i) => { if ( Compile(arg.Value) @@ -110,14 +110,12 @@ [.. argumentsResults.Select(r => r.Unwrap())] }) .ToArray(); - if (memberResults.Any(vs => vs.result.IsError)) - return; - foreach (var (name, memberResult) in memberResults) - scope.Set( - name.Alias ?? name.Name, - memberResult.Unwrap() - ); + if (memberResult.Ok(out var member)) + scope.Set( + name.Alias ?? name.Name, + member + ); } } } diff --git a/ZSharp.SourceCompiler.Script/contexts/ScopeContext.cs b/ZSharp.SourceCompiler.Script/contexts/ScopeContext.cs index 0e087414..96a4fefa 100644 --- a/ZSharp.SourceCompiler.Script/contexts/ScopeContext.cs +++ b/ZSharp.SourceCompiler.Script/contexts/ScopeContext.cs @@ -11,7 +11,7 @@ public sealed class ScopeContext() public IContext? Parent { get; set; } - public Result Add(string name, CompilerObject value) + public IResult Add(string name, CompilerObject value) { if (scope.ContainsKey(name)) return Result.Error($"Name '{name}' is already defined in this scope."); @@ -19,12 +19,12 @@ public Result Add(string name, CompilerObject value) return Set(name, value); } - public Result Get(string name) + public IResult Get(string name) => scope.TryGetValue(name, out var value) ? Result.Ok(value) : Result.Error($"Name '{name}' is not defined in this scope."); - public Result Set(string name, CompilerObject value) + public IResult Set(string name, CompilerObject value) { scope[name] = value;