From 524be8a9b77a1f66b2b9f2e7cfd0a28d20d24f93 Mon Sep 17 00:00:00 2001 From: "J. Ritchie Carroll" Date: Mon, 16 Sep 2024 03:04:24 -0400 Subject: [PATCH] Added initial source code generator for attribute Converted projects to .NET 8.0 --- src/Tests/ASTTests/ASTTests.csproj | 2 +- .../ArrayPassByValue/ArrayPassByValue.csproj | 2 +- .../BehavioralTests/BehavioralTests.csproj | 2 +- .../Behavioral/ExprSwitch/ExprSwitch.csproj | 2 +- .../Behavioral/ForVariants/ForVariants.csproj | 2 +- .../InterfaceCasting/InterfaceCasting.csproj | 2 +- .../InterfaceImplementation.csproj | 2 +- .../InterfaceInheritance.csproj | 2 +- .../LambdaFunctions/LambdaFunctions.csproj | 2 +- .../PointerToPointer/PointerToPointer.csproj | 2 +- .../Behavioral/SortArrayType/SortArrayType.cs | 181 +++++++++--------- .../SortArrayType/SortArrayType.cs.target | 8 +- .../SortArrayType/SortArrayType.csproj | 23 ++- .../SortArrayType_PersonStruct.cs | 7 +- .../Behavioral/TypeSwitch/TypeSwitch.csproj | 2 +- src/Tests/ChannelTests/ChannelTests.csproj | 2 +- src/Tests/CommonTests/CommonTests.csproj | 2 +- src/Tests/GenericTests/GenericTests.csproj | 2 +- .../GrammarTests/GrammarTests.csproj | 2 +- .../Antlr4.Runtime/Antlr4.Runtime.csproj | 2 +- src/Utilities/CommandLine/CommandLine.csproj | 2 +- .../CommandLine/Core/ArgumentsExtensions.cs | 2 +- .../CommandLine/Core/InstanceBuilder.cs | 2 +- .../CommandLine/Core/OptionSpecification.cs | 2 +- .../CommandLine/Core/ReflectionExtensions.cs | 4 +- src/Utilities/CommandLine/Core/Scalar.cs | 4 +- .../Core/SpecificationPropertyRules.cs | 4 +- src/Utilities/CommandLine/ErrorHandling.cs | 8 +- .../Infrastructure/ResultExtensions.cs | 2 +- src/Utilities/CommandLine/Maybe.cs | 2 +- src/Utilities/CommandLine/Parser.cs | 2 +- src/Utilities/CommandLine/ParserResult.cs | 2 +- src/Utilities/CommandLine/Text/Example.cs | 2 +- src/Utilities/CommandLine/Text/HelpText.cs | 2 +- .../GenGoFuncRefInstances.csproj | 2 +- src/Utilities/QuickTest/QuickTest.csproj | 2 +- src/go2cs.CodeGenerators/AttributeFinder.cs | 137 +++++++++++++ src/go2cs.CodeGenerators/Internal/Index.cs | 85 ++++++++ src/go2cs.CodeGenerators/Internal/Range.cs | 70 +++++++ .../Internal/RuntimeHelpers.cs | 29 +++ src/go2cs.CodeGenerators/TypeGenerator.cs | 153 +++++++++++++++ .../go2cs.CodeGenerators.csproj | 25 +++ src/go2cs.Common/Internal/Index.cs | 85 ++++++++ src/go2cs.Common/Internal/IsExternalInit.cs | 7 + src/go2cs.Common/Internal/Range.cs | 70 +++++++ src/go2cs.Common/Internal/RuntimeHelpers.cs | 29 +++ .../Metadata/FunctionSignature.cs | 2 +- src/go2cs.Common/Metadata/InterfaceInfo.cs | 2 +- src/go2cs.Common/go2cs.Common.csproj | 4 +- src/go2cs.Templates/InheritedTypeTemplate.cs | 68 +++---- src/go2cs.Templates/InheritedTypeTemplate.tt | 2 +- src/go2cs.Templates/Internal/Index.cs | 85 ++++++++ .../Internal/IsExternalInit.cs | 7 + src/go2cs.Templates/Internal/Range.cs | 70 +++++++ .../Internal/RuntimeHelpers.cs | 29 +++ src/go2cs.Templates/LibraryProjectTemplate.cs | 26 +-- src/go2cs.Templates/LibraryProjectTemplate.tt | 8 +- src/go2cs.Templates/MainProjectTemplate.cs | 26 +-- src/go2cs.Templates/MainProjectTemplate.tt | 8 +- src/go2cs.Templates/TemplateBase.cs | 8 +- src/go2cs.Templates/TemplateBase.tt | 2 +- src/go2cs.Templates/go2cs.Templates.csproj | 6 +- src/go2cs.sln | 7 + src/go2cs/Converter/Converter_ForStmt.cs | 2 +- src/go2cs/Converter/Converter_MethodDecl.cs | 2 +- src/go2cs/PreScanner/PreScanner_Type.cs | 6 +- .../PublishProfiles/linux-arm.pubxml | 4 +- .../PublishProfiles/linux-x64.pubxml | 4 +- .../Properties/PublishProfiles/osx-x64.pubxml | 4 +- .../Properties/PublishProfiles/win-64.pubxml | 4 +- .../ScannerBase/ScannerBase_Signature.cs | 4 +- src/go2cs/go2cs.csproj | 2 +- src/gocore/errors/errors.csproj | 2 +- src/gocore/fmt/fmt.csproj | 2 +- src/gocore/golib/TypeExtensions.cs | 3 +- src/gocore/golib/array.cs | 5 +- src/gocore/golib/golib.csproj | 2 +- src/gocore/golib/slice.cs | 2 +- src/gocore/golib/sstring.cs | 8 +- src/gocore/golib/string.cs | 56 +++--- src/gocore/golib/typeAttribute.cs | 36 ++++ src/gocore/io/io.csproj | 2 +- src/gocore/sort/sort.csproj | 2 +- src/gocore/strings/strings.csproj | 2 +- src/gocore/sync/sync.csproj | 2 +- src/gocore/time/time.csproj | 2 +- 86 files changed, 1220 insertions(+), 283 deletions(-) create mode 100644 src/go2cs.CodeGenerators/AttributeFinder.cs create mode 100644 src/go2cs.CodeGenerators/Internal/Index.cs create mode 100644 src/go2cs.CodeGenerators/Internal/Range.cs create mode 100644 src/go2cs.CodeGenerators/Internal/RuntimeHelpers.cs create mode 100644 src/go2cs.CodeGenerators/TypeGenerator.cs create mode 100644 src/go2cs.CodeGenerators/go2cs.CodeGenerators.csproj create mode 100644 src/go2cs.Common/Internal/Index.cs create mode 100644 src/go2cs.Common/Internal/IsExternalInit.cs create mode 100644 src/go2cs.Common/Internal/Range.cs create mode 100644 src/go2cs.Common/Internal/RuntimeHelpers.cs create mode 100644 src/go2cs.Templates/Internal/Index.cs create mode 100644 src/go2cs.Templates/Internal/IsExternalInit.cs create mode 100644 src/go2cs.Templates/Internal/Range.cs create mode 100644 src/go2cs.Templates/Internal/RuntimeHelpers.cs create mode 100644 src/gocore/golib/typeAttribute.cs diff --git a/src/Tests/ASTTests/ASTTests.csproj b/src/Tests/ASTTests/ASTTests.csproj index 15e646d6e..c207ad042 100644 --- a/src/Tests/ASTTests/ASTTests.csproj +++ b/src/Tests/ASTTests/ASTTests.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 false latest diff --git a/src/Tests/Behavioral/ArrayPassByValue/ArrayPassByValue.csproj b/src/Tests/Behavioral/ArrayPassByValue/ArrayPassByValue.csproj index 11cffbc6f..f7dcb6239 100644 --- a/src/Tests/Behavioral/ArrayPassByValue/ArrayPassByValue.csproj +++ b/src/Tests/Behavioral/ArrayPassByValue/ArrayPassByValue.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true go ArrayPassByValue diff --git a/src/Tests/Behavioral/BehavioralTests/BehavioralTests.csproj b/src/Tests/Behavioral/BehavioralTests/BehavioralTests.csproj index a9a0a326d..ec4338cfc 100644 --- a/src/Tests/Behavioral/BehavioralTests/BehavioralTests.csproj +++ b/src/Tests/Behavioral/BehavioralTests/BehavioralTests.csproj @@ -1,7 +1,7 @@  - net7.0 + net8.0 false latest diff --git a/src/Tests/Behavioral/ExprSwitch/ExprSwitch.csproj b/src/Tests/Behavioral/ExprSwitch/ExprSwitch.csproj index 6b623d6c5..787f05dde 100644 --- a/src/Tests/Behavioral/ExprSwitch/ExprSwitch.csproj +++ b/src/Tests/Behavioral/ExprSwitch/ExprSwitch.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true go ExprSwitch diff --git a/src/Tests/Behavioral/ForVariants/ForVariants.csproj b/src/Tests/Behavioral/ForVariants/ForVariants.csproj index 5306ca61b..d48fb982c 100644 --- a/src/Tests/Behavioral/ForVariants/ForVariants.csproj +++ b/src/Tests/Behavioral/ForVariants/ForVariants.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true go ForVariants diff --git a/src/Tests/Behavioral/InterfaceCasting/InterfaceCasting.csproj b/src/Tests/Behavioral/InterfaceCasting/InterfaceCasting.csproj index 1faa4399a..43243ffbf 100644 --- a/src/Tests/Behavioral/InterfaceCasting/InterfaceCasting.csproj +++ b/src/Tests/Behavioral/InterfaceCasting/InterfaceCasting.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true go InterfaceCasting diff --git a/src/Tests/Behavioral/InterfaceImplementation/InterfaceImplementation.csproj b/src/Tests/Behavioral/InterfaceImplementation/InterfaceImplementation.csproj index 445520634..ca1a9a25d 100644 --- a/src/Tests/Behavioral/InterfaceImplementation/InterfaceImplementation.csproj +++ b/src/Tests/Behavioral/InterfaceImplementation/InterfaceImplementation.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true go InterfaceImplementation diff --git a/src/Tests/Behavioral/InterfaceInheritance/InterfaceInheritance.csproj b/src/Tests/Behavioral/InterfaceInheritance/InterfaceInheritance.csproj index 9dbadf6dc..6d9290a29 100644 --- a/src/Tests/Behavioral/InterfaceInheritance/InterfaceInheritance.csproj +++ b/src/Tests/Behavioral/InterfaceInheritance/InterfaceInheritance.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true go InterfaceInheritance diff --git a/src/Tests/Behavioral/LambdaFunctions/LambdaFunctions.csproj b/src/Tests/Behavioral/LambdaFunctions/LambdaFunctions.csproj index ea864ef0d..295efb0f3 100644 --- a/src/Tests/Behavioral/LambdaFunctions/LambdaFunctions.csproj +++ b/src/Tests/Behavioral/LambdaFunctions/LambdaFunctions.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true go LambdaFunctions diff --git a/src/Tests/Behavioral/PointerToPointer/PointerToPointer.csproj b/src/Tests/Behavioral/PointerToPointer/PointerToPointer.csproj index 53ced45d4..11308207a 100644 --- a/src/Tests/Behavioral/PointerToPointer/PointerToPointer.csproj +++ b/src/Tests/Behavioral/PointerToPointer/PointerToPointer.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true go PointerToPointer diff --git a/src/Tests/Behavioral/SortArrayType/SortArrayType.cs b/src/Tests/Behavioral/SortArrayType/SortArrayType.cs index 37e51016c..d0b5d4c40 100644 --- a/src/Tests/Behavioral/SortArrayType/SortArrayType.cs +++ b/src/Tests/Behavioral/SortArrayType/SortArrayType.cs @@ -1,95 +1,104 @@ -using static go.main_package; +namespace go; -namespace go -{ using fmt = fmt_package; using sort = sort_package; using static builtin; public static partial class main_package { -public partial struct Person -{ - public @string Name; - public nint Age; - public float ShoeSize; -} - -public partial struct PeopleByShoeSize : ISlice -{ -} - -public partial struct PeopleByAge : ISlice -{ -} - -public static nint Len(this PeopleByShoeSize p) -{ - return len(p); -} - -public static void Swap(this PeopleByShoeSize p, nint i, nint j) -{ - (p[i], p[j]) = (p[j], p[i]); -} - -public static bool Less(this PeopleByShoeSize p, nint i, nint j) -{ - return (p[i].ShoeSize < p[j].ShoeSize); -} - -public static nint Len(this PeopleByAge p) -{ - return len(p); -} - -public static void Swap(this PeopleByAge p, nint i, nint j) -{ - (p[i], p[j]) = (p[j], p[i]); -} - -public static bool Less(this PeopleByAge p, nint i, nint j) -{ - return (p[i].Age < p[j].Age); -} - -private static void Main() -{ - var people = new Person[] { - new() { - Name = "Person1"u8, - Age = 26, - ShoeSize = 8, - }, - new() { - Name = "Person2"u8, - Age = 21, - ShoeSize = 4, - }, - new() { - Name = "Person3"u8, - Age = 15, - ShoeSize = 9, - }, - new() { - Name = "Person4"u8, - Age = 45, - ShoeSize = 15, - }, - new() { - Name = "Person5"u8, - Age = 25, - ShoeSize = 8.50F, - }}.slice(); - - fmt.Println(people); - - sort.Sort(new PeopleByShoeSize(people)); - fmt.Println(people); - - sort.Sort(new PeopleByAge(people)); - fmt.Println(people); -} + [type("struct")] + public partial struct Person + { + public @string Name; + public nint Age; + public float32 ShoeSize; + } + + [type("[]Person")] + public partial struct PeopleByShoeSize : ISlice + { + } + + public partial struct PeopleByAge : ISlice + { + } + + public static nint Len(this PeopleByShoeSize p) + { + return len(p); + } + + public static void Swap(this PeopleByShoeSize p, nint i, nint j) + { + (p[i], p[j]) = (p[j], p[i]); + } + + public static bool Less(this PeopleByShoeSize p, nint i, nint j) + { + return (p[i].ShoeSize < p[j].ShoeSize); + } + + public static nint Len(this PeopleByAge p) + { + return len(p); + } + + public static void Swap(this PeopleByAge p, nint i, nint j) + { + (p[i], p[j]) = (p[j], p[i]); + } + + public static bool Less(this PeopleByAge p, nint i, nint j) + { + return (p[i].Age < p[j].Age); + } + + private static void Main() + { + var people = new Person[] { + //new( + // Name: "Person1"u8, + // Age: 26, + // ShoeSize: 8 + //), + //new( + // Name: "Person2"u8, + // Age: 21, + // ShoeSize: 4 + //), + //new( + // Name: "Person3"u8, + // Age: 15, + // ShoeSize: 9 + //), + //new( + // Name: "Person4"u8, + // Age: 45, + // ShoeSize: 15 + //), + //new( + // Name: "Person5"u8, + // Age: 25, + // ShoeSize: 8.50F + //) + }.slice(); + + var test = new Person[] + { + new() { Name = "Person1"u8, Age = 26, ShoeSize = 8 }, + new() { Name = "Person2"u8, Age = 21, ShoeSize = 4 }, + new() { Name = "Person3"u8, Age = 15, ShoeSize = 9 }, + new() { Name = "Person4"u8, Age = 45, ShoeSize = 15 }, + new() { Name = "Person5"u8, Age = 25, ShoeSize = 8.50F } + }; + + fmt.Println(people); + + sort.Sort(new PeopleByShoeSize(people)); + fmt.Println(people); + + sort.Sort(new PeopleByAge(people)); + fmt.Println(people); + } } // end main_package -} diff --git a/src/Tests/Behavioral/SortArrayType/SortArrayType.cs.target b/src/Tests/Behavioral/SortArrayType/SortArrayType.cs.target index 2d720e080..6b0594f12 100644 --- a/src/Tests/Behavioral/SortArrayType/SortArrayType.cs.target +++ b/src/Tests/Behavioral/SortArrayType/SortArrayType.cs.target @@ -1,15 +1,14 @@ using static go.main_package; -namespace go -{ +namespace go; + using fmt = fmt_package; using sort = sort_package; using static builtin; public static partial class main_package { -public partial struct Person -{ +public partial struct Person { public @string Name; public nint Age; public float ShoeSize; @@ -92,4 +91,3 @@ private static void Main() } } // end main_package -} diff --git a/src/Tests/Behavioral/SortArrayType/SortArrayType.csproj b/src/Tests/Behavioral/SortArrayType/SortArrayType.csproj index f4280c88d..1cb052c06 100644 --- a/src/Tests/Behavioral/SortArrayType/SortArrayType.csproj +++ b/src/Tests/Behavioral/SortArrayType/SortArrayType.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true go SortArrayType @@ -11,16 +11,20 @@ https://github.com/GridProtectionAlliance/go2cs https://github.com/GridProtectionAlliance/go2cs MIT - $(GOPATH)\src\go2cs\go2cs.ico enable 660;661;IDE1006 0.1.0 + latest bin\$(Configuration)\$(TargetFramework)\ + + + + @@ -37,15 +41,24 @@ - + + $(GOPATH)\src\go2cs\golib\$(OutDir)golib.dll - + + + $(GOPATH)\src\go2cs\fmt\$(OutDir)fmt_package.dll - + + + $(GOPATH)\src\go2cs\sort\$(OutDir)sort_package.dll + + + + diff --git a/src/Tests/Behavioral/SortArrayType/SortArrayType_PersonStruct.cs b/src/Tests/Behavioral/SortArrayType/SortArrayType_PersonStruct.cs index 73d28b032..c8c472099 100644 --- a/src/Tests/Behavioral/SortArrayType/SortArrayType_PersonStruct.cs +++ b/src/Tests/Behavioral/SortArrayType/SortArrayType_PersonStruct.cs @@ -26,11 +26,8 @@ public static partial class main_package public partial struct Person { // Constructors - public Person(NilType _) + public Person(NilType _) : this(default, default, default) { - this.Name = default; - this.Age = default; - this.ShoeSize = default; } public Person(@string Name = default, nint Age = default, float ShoeSize = default) @@ -70,4 +67,4 @@ public static Person Person_cast(dynamic value) return new Person(value.Name, value.Age, value.ShoeSize); } } -} \ No newline at end of file +} diff --git a/src/Tests/Behavioral/TypeSwitch/TypeSwitch.csproj b/src/Tests/Behavioral/TypeSwitch/TypeSwitch.csproj index 9dadeefa4..b5629c8cc 100644 --- a/src/Tests/Behavioral/TypeSwitch/TypeSwitch.csproj +++ b/src/Tests/Behavioral/TypeSwitch/TypeSwitch.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true go TypeSwitch diff --git a/src/Tests/ChannelTests/ChannelTests.csproj b/src/Tests/ChannelTests/ChannelTests.csproj index cddd45ba8..c8574b3d1 100644 --- a/src/Tests/ChannelTests/ChannelTests.csproj +++ b/src/Tests/ChannelTests/ChannelTests.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 false latest diff --git a/src/Tests/CommonTests/CommonTests.csproj b/src/Tests/CommonTests/CommonTests.csproj index 58c095098..2b30068b2 100644 --- a/src/Tests/CommonTests/CommonTests.csproj +++ b/src/Tests/CommonTests/CommonTests.csproj @@ -1,7 +1,7 @@  - net7.0 + net8.0 false latest diff --git a/src/Tests/GenericTests/GenericTests.csproj b/src/Tests/GenericTests/GenericTests.csproj index 3512d3eb0..237aa5680 100644 --- a/src/Tests/GenericTests/GenericTests.csproj +++ b/src/Tests/GenericTests/GenericTests.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 latest diff --git a/src/Tests/GrammarTests/GrammarTests/GrammarTests.csproj b/src/Tests/GrammarTests/GrammarTests/GrammarTests.csproj index 7a805ffff..2cc7f52ab 100644 --- a/src/Tests/GrammarTests/GrammarTests/GrammarTests.csproj +++ b/src/Tests/GrammarTests/GrammarTests/GrammarTests.csproj @@ -1,7 +1,7 @@  - net7.0 + net8.0 enable false diff --git a/src/Utilities/Antlr4.Runtime/Antlr4.Runtime.csproj b/src/Utilities/Antlr4.Runtime/Antlr4.Runtime.csproj index 50c16f5e7..dac1a0b95 100644 --- a/src/Utilities/Antlr4.Runtime/Antlr4.Runtime.csproj +++ b/src/Utilities/Antlr4.Runtime/Antlr4.Runtime.csproj @@ -3,7 +3,7 @@ The ANTLR Organization 4.9.3 en-US - net7.0 + net8.0 $(NoWarn);CS1591;CS1574;CS1580;IDE0090 true Antlr4.Runtime.Standard diff --git a/src/Utilities/CommandLine/CommandLine.csproj b/src/Utilities/CommandLine/CommandLine.csproj index 2be2d1c5b..84593ed90 100644 --- a/src/Utilities/CommandLine/CommandLine.csproj +++ b/src/Utilities/CommandLine/CommandLine.csproj @@ -2,7 +2,7 @@ Library - net7.0 + net8.0 latest diff --git a/src/Utilities/CommandLine/Core/ArgumentsExtensions.cs b/src/Utilities/CommandLine/Core/ArgumentsExtensions.cs index e1a0aa5fc..f24052aff 100644 --- a/src/Utilities/CommandLine/Core/ArgumentsExtensions.cs +++ b/src/Utilities/CommandLine/Core/ArgumentsExtensions.cs @@ -23,7 +23,7 @@ public static IEnumerable Preprocess( ? errors : arguments.Preprocess(preprocessorLookup.TailNoFail()); }, - Enumerable.Empty()); + []); } } } diff --git a/src/Utilities/CommandLine/Core/InstanceBuilder.cs b/src/Utilities/CommandLine/Core/InstanceBuilder.cs index aa811e4b4..d4061c2e0 100644 --- a/src/Utilities/CommandLine/Core/InstanceBuilder.cs +++ b/src/Utilities/CommandLine/Core/InstanceBuilder.cs @@ -133,7 +133,7 @@ join sp in specPropsWithValue on prms.Name.ToLower() equals sp.Property.Name.ToL var preprocessorErrors = arguments.Any() ? arguments.Preprocess(PreprocessorGuards.Lookup(nameComparer)) - : Enumerable.Empty(); + : []; var result = arguments.Any() ? preprocessorErrors.Any() diff --git a/src/Utilities/CommandLine/Core/OptionSpecification.cs b/src/Utilities/CommandLine/Core/OptionSpecification.cs index d74b1d311..6762dc2ce 100644 --- a/src/Utilities/CommandLine/Core/OptionSpecification.cs +++ b/src/Utilities/CommandLine/Core/OptionSpecification.cs @@ -47,7 +47,7 @@ public static OptionSpecification FromAttribute(OptionAttribute attribute, Type public static OptionSpecification NewSwitch(string shortName, string longName, bool required, string helpText, string metaValue, bool hidden = false) { return new OptionSpecification(shortName, longName, required, string.Empty, Maybe.Nothing(), Maybe.Nothing(), - '\0', Maybe.Nothing(), helpText, metaValue, Enumerable.Empty(), typeof(bool), TargetType.Switch, hidden); + '\0', Maybe.Nothing(), helpText, metaValue, [], typeof(bool), TargetType.Switch, hidden); } public string ShortName diff --git a/src/Utilities/CommandLine/Core/ReflectionExtensions.cs b/src/Utilities/CommandLine/Core/ReflectionExtensions.cs index 4d5424e2b..ad9a105da 100644 --- a/src/Utilities/CommandLine/Core/ReflectionExtensions.cs +++ b/src/Utilities/CommandLine/Core/ReflectionExtensions.cs @@ -197,7 +197,7 @@ public static object StaticProperty(this Type type, string name) BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Static, null, null, - Array.Empty()); + []); #endif } @@ -212,7 +212,7 @@ public static object InstanceProperty(this Type type, string name, object target BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, target, - Array.Empty()); + []); #endif } diff --git a/src/Utilities/CommandLine/Core/Scalar.cs b/src/Utilities/CommandLine/Core/Scalar.cs index fe6bb4d47..55c156542 100644 --- a/src/Utilities/CommandLine/Core/Scalar.cs +++ b/src/Utilities/CommandLine/Core/Scalar.cs @@ -18,8 +18,8 @@ public static IEnumerable Partition( (f, s) => f.IsName() && s.IsValue() ? typeLookup(f.Text).MapValueOrDefault(info => - info.TargetType == TargetType.Scalar ? new[] { f, s } : Array.Empty(), Array.Empty()) - : Array.Empty()) + info.TargetType == TargetType.Scalar ? new[] { f, s } : [], []) + : []) from t in tseq select t; } diff --git a/src/Utilities/CommandLine/Core/SpecificationPropertyRules.cs b/src/Utilities/CommandLine/Core/SpecificationPropertyRules.cs index 7f8cbd0bb..e60a86c9e 100644 --- a/src/Utilities/CommandLine/Core/SpecificationPropertyRules.cs +++ b/src/Utilities/CommandLine/Core/SpecificationPropertyRules.cs @@ -42,7 +42,7 @@ group o by o.SetName into g from o in options select new MutuallyExclusiveSetError(o.FromOptionSpecification(), o.SetName); } - return Enumerable.Empty(); + return []; }; } @@ -111,7 +111,7 @@ private static Func, IEnumerable> Enfo from s in options select new SequenceOutOfRangeError(s.Specification.FromSpecification()); } - return Enumerable.Empty(); + return []; }; } diff --git a/src/Utilities/CommandLine/ErrorHandling.cs b/src/Utilities/CommandLine/ErrorHandling.cs index c5c49d577..4eb170938 100644 --- a/src/Utilities/CommandLine/ErrorHandling.cs +++ b/src/Utilities/CommandLine/ErrorHandling.cs @@ -186,7 +186,7 @@ public static Result FailWith(TMessage m /// public static Result Succeed(TSuccess value) { - return new Ok(value, Enumerable.Empty()); + return new Ok(value, []); } /// @@ -213,7 +213,7 @@ public static Result Try(Func func) try { return new Ok( - func(), Enumerable.Empty()); + func(), []); } catch (Exception ex) { @@ -236,7 +236,7 @@ static class Trial #endif public static Result Ok(TSuccess value) { - return new Ok(value, Enumerable.Empty()); + return new Ok(value, []); } /// @@ -247,7 +247,7 @@ public static Result Ok(TSuccess value) #endif public static Result Pass(TSuccess value) { - return new Ok(value, Enumerable.Empty()); + return new Ok(value, []); } /// diff --git a/src/Utilities/CommandLine/Infrastructure/ResultExtensions.cs b/src/Utilities/CommandLine/Infrastructure/ResultExtensions.cs index 88b8bf124..b671979b3 100644 --- a/src/Utilities/CommandLine/Infrastructure/ResultExtensions.cs +++ b/src/Utilities/CommandLine/Infrastructure/ResultExtensions.cs @@ -20,7 +20,7 @@ public static IEnumerable SuccessfulMessages(this var ok = (Ok)result; return ok.Messages; } - return Enumerable.Empty(); + return []; } public static Maybe ToMaybe(this Result result) diff --git a/src/Utilities/CommandLine/Maybe.cs b/src/Utilities/CommandLine/Maybe.cs index e4592e247..6d0fbb9f8 100644 --- a/src/Utilities/CommandLine/Maybe.cs +++ b/src/Utilities/CommandLine/Maybe.cs @@ -391,7 +391,7 @@ public static IEnumerable ToEnumerable(this Maybe maybe) { return Enumerable.Empty().Concat(new[] { value }); } - return Enumerable.Empty(); + return []; } } } \ No newline at end of file diff --git a/src/Utilities/CommandLine/Parser.cs b/src/Utilities/CommandLine/Parser.cs index be57b9e27..52679d0c0 100644 --- a/src/Utilities/CommandLine/Parser.cs +++ b/src/Utilities/CommandLine/Parser.cs @@ -206,7 +206,7 @@ private static IEnumerable HandleUnknownArguments(bool ignoreUnknownA { return ignoreUnknownArguments ? Enumerable.Empty().Concat(ErrorType.UnknownOptionError) - : Enumerable.Empty(); + : []; } private void Dispose(bool disposing) diff --git a/src/Utilities/CommandLine/ParserResult.cs b/src/Utilities/CommandLine/ParserResult.cs index 554f1d6eb..1ad7ecadc 100644 --- a/src/Utilities/CommandLine/ParserResult.cs +++ b/src/Utilities/CommandLine/ParserResult.cs @@ -29,7 +29,7 @@ public IEnumerable Choices public static TypeInfo Create(Type current) { - return new TypeInfo(current, Enumerable.Empty()); + return new TypeInfo(current, []); } public static TypeInfo Create(Type current, IEnumerable choices) diff --git a/src/Utilities/CommandLine/Text/Example.cs b/src/Utilities/CommandLine/Text/Example.cs index 861476e4b..de7715bfc 100644 --- a/src/Utilities/CommandLine/Text/Example.cs +++ b/src/Utilities/CommandLine/Text/Example.cs @@ -49,7 +49,7 @@ public Example(string helpText, UnParserSettings formatStyle, object sample) /// Example description. /// A sample instance. public Example(string helpText, object sample) - : this(helpText, Enumerable.Empty(), sample) + : this(helpText, [], sample) { } diff --git a/src/Utilities/CommandLine/Text/HelpText.cs b/src/Utilities/CommandLine/Text/HelpText.cs index 60b277730..c869ef6b5 100644 --- a/src/Utilities/CommandLine/Text/HelpText.cs +++ b/src/Utilities/CommandLine/Text/HelpText.cs @@ -295,7 +295,7 @@ public static HelpText AutoBuild(ParserResult parserResult, int maxDisplay return AutoBuild(parserResult, current => DefaultParsingErrorsHandler(parserResult, current), e => e, maxDisplayWidth: maxDisplayWidth); var err = errors.OfType().Single(); - var pr = new NotParsed(TypeInfo.Create(err.Type), Enumerable.Empty()); + var pr = new NotParsed(TypeInfo.Create(err.Type), []); return err.Matched ? AutoBuild(pr, current => DefaultParsingErrorsHandler(pr, current), e => e, maxDisplayWidth: maxDisplayWidth) : AutoBuild(parserResult, current => DefaultParsingErrorsHandler(parserResult, current), e => e, true, maxDisplayWidth); diff --git a/src/Utilities/GenGoFuncRefInstances/GenGoFuncRefInstances.csproj b/src/Utilities/GenGoFuncRefInstances/GenGoFuncRefInstances.csproj index 0fcde2638..6a71af2db 100644 --- a/src/Utilities/GenGoFuncRefInstances/GenGoFuncRefInstances.csproj +++ b/src/Utilities/GenGoFuncRefInstances/GenGoFuncRefInstances.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 latest diff --git a/src/Utilities/QuickTest/QuickTest.csproj b/src/Utilities/QuickTest/QuickTest.csproj index 0fc3fa94c..8e669c2e9 100644 --- a/src/Utilities/QuickTest/QuickTest.csproj +++ b/src/Utilities/QuickTest/QuickTest.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true latest diff --git a/src/go2cs.CodeGenerators/AttributeFinder.cs b/src/go2cs.CodeGenerators/AttributeFinder.cs new file mode 100644 index 000000000..f9443a798 --- /dev/null +++ b/src/go2cs.CodeGenerators/AttributeFinder.cs @@ -0,0 +1,137 @@ +//****************************************************************************************************** +// AttributeFinder.cs - Gbtc +// +// Copyright © 2024, Grid Protection Alliance. All Rights Reserved. +// +// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See +// the NOTICE file distributed with this work for additional information regarding copyright ownership. +// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this +// file except in compliance with the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/MIT +// +// Unless agreed to in writing, the subject software distributed under the License is distributed on an +// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the +// License for the specific language governing permissions and limitations. +// +// Code Modification History: +// ---------------------------------------------------------------------------------------------------- +// 07/08/2024 - J. Ritchie Carroll +// Generated original version of source code. +// +//****************************************************************************************************** + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace go2cs.CodeGenerators; + +public sealed class AttributeFinder(string attributeFullName) : ISyntaxContextReceiver where TDeclarationSyntax : BaseTypeDeclarationSyntax +{ + public List<(TDeclarationSyntax targetSyntax, List attributes)> TargetAttributes = []; + + public bool HasAttributes => TargetAttributes.Count > 0; + + public void OnVisitSyntaxNode(GeneratorSyntaxContext context) + { + if (DeclarationHasAttributes(context.Node)) + TargetAttributes.Add(GetSemanticTargetForGeneration(context)); + } + + private static bool DeclarationHasAttributes(SyntaxNode node) + { + return node is TDeclarationSyntax { AttributeLists.Count: > 0 }; + } + + private (TDeclarationSyntax, List) GetSemanticTargetForGeneration(GeneratorSyntaxContext context) + { + List attributes = []; + TDeclarationSyntax targetSyntax = (TDeclarationSyntax)context.Node; + + foreach (AttributeSyntax attributeSyntax in targetSyntax.AttributeLists.SelectMany(attributeListSyntax => attributeListSyntax.Attributes)) + { + if (context.SemanticModel.GetSymbolInfo(attributeSyntax).Symbol is not IMethodSymbol attributeSymbol) + continue; + + INamedTypeSymbol attributeContainingTypeSymbol = attributeSymbol.ContainingType; + + if (string.Equals(attributeFullName, attributeContainingTypeSymbol.ToDisplayString(), StringComparison.Ordinal)) + attributes.Add(attributeSyntax); + } + + return (targetSyntax, attributes); + } +} + +public static class AttributeSyntaxExtensions +{ + public static string[] GetArgumentValues(this AttributeSyntax attribute) + { + SeparatedSyntaxList arguments = attribute.ArgumentList?.Arguments ?? default; + return arguments.Select(argument => argument.Expression.NormalizeWhitespace().ToFullString()).ToArray(); + } +} + +public static class StructDeclarationSyntaxExtensions +{ + public static List<(string typeName, string fieldName)> GetStructFields(this StructDeclarationSyntax structDeclaration, GeneratorExecutionContext context) + { + // Obtain the SemanticModel from the context + SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree); + + List<(string typeName, string fieldName)> fields = []; + + foreach (FieldDeclarationSyntax? fieldDeclaration in structDeclaration.Members.OfType()) + { + TypeSyntax variableTypeSyntax = fieldDeclaration.Declaration.Type; + + TypeInfo typeInfo = semanticModel.GetTypeInfo(variableTypeSyntax); + ITypeSymbol? typeSymbol = typeInfo.Type; + + if (typeSymbol == null) + continue; // Type couldn't be resolved + + string fullyQualifiedTypeName = typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + + foreach (VariableDeclaratorSyntax variableDeclarator in fieldDeclaration.Declaration.Variables) + { + string fieldName = variableDeclarator.Identifier.Text; + fields.Add((fullyQualifiedTypeName, fieldName)); + } + } + + return fields; + } +} + +public static class SyntaxNodeExtensions +{ + public static string GetNamespaceName(this SyntaxNode syntaxNode) + { + BaseNamespaceDeclarationSyntax[] namespaceDeclarations = syntaxNode.Ancestors() + .OfType() + .ToArray(); + + if (!namespaceDeclarations.Any()) + return string.Empty; + + // Build the full namespace by joining nested namespaces + string namespaceName = string.Join(".", namespaceDeclarations + .Select(ns => ns.Name.ToString()) + .Reverse()); + + return namespaceName; + } + + public static string GetParentClassName(this SyntaxNode syntaxNode) + { + ClassDeclarationSyntax? classDeclaration = syntaxNode.Ancestors() + .OfType() + .FirstOrDefault(); + + return classDeclaration?.Identifier.Text ?? string.Empty; + } +} diff --git a/src/go2cs.CodeGenerators/Internal/Index.cs b/src/go2cs.CodeGenerators/Internal/Index.cs new file mode 100644 index 000000000..2dd6fbdd9 --- /dev/null +++ b/src/go2cs.CodeGenerators/Internal/Index.cs @@ -0,0 +1,85 @@ +using System.Runtime.CompilerServices; + +// ReSharper disable once CheckNamespace +namespace System; + +internal readonly struct Index : IEquatable +{ + private readonly int m_value; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Index(int value, bool fromEnd = false) + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); + + if (fromEnd) + m_value = ~value; + else + m_value = value; + } + + private Index(int value) + { + m_value = value; + } + + public static Index Start => new Index(0); + + public static Index End => new Index(~0); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromStart(int value) + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); + + return new Index(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromEnd(int value) + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); + + return new Index(~value); + } + + public int Value => m_value < 0 ? ~m_value : m_value; + + public bool IsFromEnd => m_value < 0; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetOffset(int length) + { + int offset = m_value; + + if (IsFromEnd) + offset += length + 1; + + return offset; + } + + public override bool Equals(object? value) + { + return value is Index index && m_value == index.m_value; + } + + public bool Equals(Index other) => m_value == other.m_value; + + public override int GetHashCode() + { + return m_value; + } + + public static implicit operator Index(int value) + { + return FromStart(value); + } + + public override string ToString() + { + return IsFromEnd ? $"^{(uint)Value}" : ((uint)Value).ToString(); + } +} \ No newline at end of file diff --git a/src/go2cs.CodeGenerators/Internal/Range.cs b/src/go2cs.CodeGenerators/Internal/Range.cs new file mode 100644 index 000000000..9c0593c6f --- /dev/null +++ b/src/go2cs.CodeGenerators/Internal/Range.cs @@ -0,0 +1,70 @@ +// Proxy implementations of System.Range and System.Index for .NET Standard 2.0 + +using System.Runtime.CompilerServices; + +// ReSharper disable once CheckNamespace +namespace System; + +internal readonly struct Range(Index start, Index end) : IEquatable +{ + public Index Start { get; } = start; + + public Index End { get; } = end; + + public override bool Equals(object? value) + { + return value is Range r && r.Start.Equals(Start) && r.End.Equals(End); + } + + public bool Equals(Range other) + { + return other.Start.Equals(Start) && other.End.Equals(End); + } + + public override int GetHashCode() + { + return Start.GetHashCode() * 31 + End.GetHashCode(); + } + + public override string ToString() + { + return $"{Start}..{End}"; + } + + public static Range StartAt(Index start) + { + return new Range(start, Index.End); + } + + public static Range EndAt(Index end) + { + return new Range(Index.Start, end); + } + + public static Range All => new(Index.Start, Index.End); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public (int Offset, int Length) GetOffsetAndLength(int length) + { + int start; + Index startIndex = Start; + + if (startIndex.IsFromEnd) + start = length - startIndex.Value; + else + start = startIndex.Value; + + int end; + Index endIndex = End; + + if (endIndex.IsFromEnd) + end = length - endIndex.Value; + else + end = endIndex.Value; + + if ((uint)end > (uint)length || (uint)start > (uint)end) + throw new ArgumentOutOfRangeException(nameof(length)); + + return (start, end - start); + } +} \ No newline at end of file diff --git a/src/go2cs.CodeGenerators/Internal/RuntimeHelpers.cs b/src/go2cs.CodeGenerators/Internal/RuntimeHelpers.cs new file mode 100644 index 000000000..8c3b663b2 --- /dev/null +++ b/src/go2cs.CodeGenerators/Internal/RuntimeHelpers.cs @@ -0,0 +1,29 @@ +// ReSharper disable once CheckNamespace +namespace System.Runtime.CompilerServices; + +internal static class RuntimeHelpers +{ + public static T[] GetSubArray(T[] array, Range range) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + + (int offset, int length) = range.GetOffsetAndLength(array.Length); + + if (default(T) != null || typeof(T[]) == array.GetType()) + { + if (length == 0) + return []; + + T[] dest = new T[length]; + Array.Copy(array, offset, dest, 0, length); + return dest; + } + else + { + T[] dest = (T[])Array.CreateInstance(array.GetType().GetElementType()!, length); + Array.Copy(array, offset, dest, 0, length); + return dest; + } + } +} \ No newline at end of file diff --git a/src/go2cs.CodeGenerators/TypeGenerator.cs b/src/go2cs.CodeGenerators/TypeGenerator.cs new file mode 100644 index 000000000..68e8b1e66 --- /dev/null +++ b/src/go2cs.CodeGenerators/TypeGenerator.cs @@ -0,0 +1,153 @@ +//****************************************************************************************************** +// TypeGenerator.cs - Gbtc +// +// Copyright © 2024, Grid Protection Alliance. All Rights Reserved. +// +// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See +// the NOTICE file distributed with this work for additional information regarding copyright ownership. +// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this +// file except in compliance with the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/MIT +// +// Unless agreed to in writing, the subject software distributed under the License is distributed on an +// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the +// License for the specific language governing permissions and limitations. +// +// Code Modification History: +// ---------------------------------------------------------------------------------------------------- +// 09/15/2024 - J. Ritchie Carroll +// Generated original version of source code. +// +//****************************************************************************************************** + +//#define DEBUG_GENERATOR + +using System.Collections.Generic; +using System.Linq; +using go2cs.Metadata; +using go2cs.Templates; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using TypeInfo = go2cs.Metadata.TypeInfo; + +#if DEBUG_GENERATOR +using System.Diagnostics; +#endif + +namespace go2cs.CodeGenerators; + +[Generator] +public class TypeGenerator : ISourceGenerator +{ + private const string Namespace = "go"; + private const string AttributeName = $"{Namespace}.typeAttribute"; + + public void Initialize(GeneratorInitializationContext context) + { + #if DEBUG_GENERATOR + if (!Debugger.IsAttached) + Debugger.Launch(); + #endif + + // Find specified attribute type on class declarations + context.RegisterForSyntaxNotifications(() => new AttributeFinder(AttributeName)); + } + + public void Execute(GeneratorExecutionContext context) + { + if (context.SyntaxContextReceiver is not AttributeFinder { HasAttributes: true } attributeFinder) + return; + + foreach ((StructDeclarationSyntax targetSyntax, List attributes) in attributeFinder.TargetAttributes) + { + string packageNamespace = targetSyntax.GetNamespaceName(); + string namespaceHeader = $"namespace {packageNamespace}\r\n{{\r\n"; + string namespaceFooter = $"\r\n}}\r\n"; + string packageClassName = targetSyntax.GetParentClassName(); + string packageName = packageClassName.EndsWith("_package") ? packageClassName[..^8] : packageClassName; + string identifier = targetSyntax.Identifier.Text; + string scope = char.IsUpper(identifier[0]) ? "public" : "private"; + + CompilationUnitSyntax root = (CompilationUnitSyntax)targetSyntax.SyntaxTree.GetRoot(); + + IEnumerable usingStatements = targetSyntax.SyntaxTree + .GetRoot() // Get the root node of the syntax tree + .DescendantNodesAndSelf() // Include the root node itself in the traversal + .OfType() // Get the CompilationUnitSyntax (root of the file) + .SelectMany(cu => cu.Usings) // Select all using directives at the root level + .Select(u => u.GetText().ToString().Trim()); // Get the text of each using directive + + foreach (AttributeSyntax attribute in attributes) + { + // Get the attribute's argument values + string[] arguments = attribute.GetArgumentValues(); + + if (arguments.Length < 1) + continue; + + // Get the attribute's first constructor argument value, type definition + string typeDefinition = arguments[0][1..^1]; + + string generatedSource; + + if (typeDefinition.Equals("struct")) + { + generatedSource = new StructTypeTemplate + { + NamespacePrefix = packageNamespace, + NamespaceHeader = namespaceHeader, + NamespaceFooter = namespaceFooter, + PackageName = packageName, + StructName = identifier, + Scope = scope, + StructFields = GetStructFields(targetSyntax, context), + PromotedStructs = [], // TODO: Fix this + PromotedFunctions = [], // TODO: Fix this + PromotedFields = [], // TODO: Fix this + UsingStatements = usingStatements + }.TransformText(); + + } + else if (typeDefinition.StartsWith("[]")) + { + generatedSource = string.Empty; + } + else + { + generatedSource = string.Empty; + } + + // Add the source code to the compilation + context.AddSource($"{packageNamespace}.{packageClassName}.{identifier}.g.cs", generatedSource); + } + } + } + + // TODO: Change the way template operates / fix field infos + private FieldInfo[] GetStructFields(StructDeclarationSyntax structDeclaration, GeneratorExecutionContext context) + { + List<(string typeName, string fieldName)> fields = structDeclaration.GetStructFields(context); + List fieldInfos = []; + + foreach ((string typeName, string fieldName) in fields) + { + fieldInfos.Add(new FieldInfo + { + Name = fieldName, + Type = new TypeInfo + { + Name = typeName, + TypeName = typeName, + FullTypeName = typeName, + TypeClass = TypeClass.Simple + }, + Description = string.Empty, + Comments = string.Empty, + IsPromoted = false + }); + } + + return fieldInfos.ToArray(); + } +} diff --git a/src/go2cs.CodeGenerators/go2cs.CodeGenerators.csproj b/src/go2cs.CodeGenerators/go2cs.CodeGenerators.csproj new file mode 100644 index 000000000..e4667f5d9 --- /dev/null +++ b/src/go2cs.CodeGenerators/go2cs.CodeGenerators.csproj @@ -0,0 +1,25 @@ + + + + netstandard2.0 + enable + true + latest + go2cs.CodeGenerators + true + + + + + + + + + + + True + True + + + + diff --git a/src/go2cs.Common/Internal/Index.cs b/src/go2cs.Common/Internal/Index.cs new file mode 100644 index 000000000..2dd6fbdd9 --- /dev/null +++ b/src/go2cs.Common/Internal/Index.cs @@ -0,0 +1,85 @@ +using System.Runtime.CompilerServices; + +// ReSharper disable once CheckNamespace +namespace System; + +internal readonly struct Index : IEquatable +{ + private readonly int m_value; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Index(int value, bool fromEnd = false) + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); + + if (fromEnd) + m_value = ~value; + else + m_value = value; + } + + private Index(int value) + { + m_value = value; + } + + public static Index Start => new Index(0); + + public static Index End => new Index(~0); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromStart(int value) + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); + + return new Index(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromEnd(int value) + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); + + return new Index(~value); + } + + public int Value => m_value < 0 ? ~m_value : m_value; + + public bool IsFromEnd => m_value < 0; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetOffset(int length) + { + int offset = m_value; + + if (IsFromEnd) + offset += length + 1; + + return offset; + } + + public override bool Equals(object? value) + { + return value is Index index && m_value == index.m_value; + } + + public bool Equals(Index other) => m_value == other.m_value; + + public override int GetHashCode() + { + return m_value; + } + + public static implicit operator Index(int value) + { + return FromStart(value); + } + + public override string ToString() + { + return IsFromEnd ? $"^{(uint)Value}" : ((uint)Value).ToString(); + } +} \ No newline at end of file diff --git a/src/go2cs.Common/Internal/IsExternalInit.cs b/src/go2cs.Common/Internal/IsExternalInit.cs new file mode 100644 index 000000000..31ef86486 --- /dev/null +++ b/src/go2cs.Common/Internal/IsExternalInit.cs @@ -0,0 +1,7 @@ +using System.ComponentModel; + +// ReSharper disable once CheckNamespace +namespace System.Runtime.CompilerServices; + +[EditorBrowsable(EditorBrowsableState.Never)] +internal class IsExternalInit { } diff --git a/src/go2cs.Common/Internal/Range.cs b/src/go2cs.Common/Internal/Range.cs new file mode 100644 index 000000000..9c0593c6f --- /dev/null +++ b/src/go2cs.Common/Internal/Range.cs @@ -0,0 +1,70 @@ +// Proxy implementations of System.Range and System.Index for .NET Standard 2.0 + +using System.Runtime.CompilerServices; + +// ReSharper disable once CheckNamespace +namespace System; + +internal readonly struct Range(Index start, Index end) : IEquatable +{ + public Index Start { get; } = start; + + public Index End { get; } = end; + + public override bool Equals(object? value) + { + return value is Range r && r.Start.Equals(Start) && r.End.Equals(End); + } + + public bool Equals(Range other) + { + return other.Start.Equals(Start) && other.End.Equals(End); + } + + public override int GetHashCode() + { + return Start.GetHashCode() * 31 + End.GetHashCode(); + } + + public override string ToString() + { + return $"{Start}..{End}"; + } + + public static Range StartAt(Index start) + { + return new Range(start, Index.End); + } + + public static Range EndAt(Index end) + { + return new Range(Index.Start, end); + } + + public static Range All => new(Index.Start, Index.End); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public (int Offset, int Length) GetOffsetAndLength(int length) + { + int start; + Index startIndex = Start; + + if (startIndex.IsFromEnd) + start = length - startIndex.Value; + else + start = startIndex.Value; + + int end; + Index endIndex = End; + + if (endIndex.IsFromEnd) + end = length - endIndex.Value; + else + end = endIndex.Value; + + if ((uint)end > (uint)length || (uint)start > (uint)end) + throw new ArgumentOutOfRangeException(nameof(length)); + + return (start, end - start); + } +} \ No newline at end of file diff --git a/src/go2cs.Common/Internal/RuntimeHelpers.cs b/src/go2cs.Common/Internal/RuntimeHelpers.cs new file mode 100644 index 000000000..8c3b663b2 --- /dev/null +++ b/src/go2cs.Common/Internal/RuntimeHelpers.cs @@ -0,0 +1,29 @@ +// ReSharper disable once CheckNamespace +namespace System.Runtime.CompilerServices; + +internal static class RuntimeHelpers +{ + public static T[] GetSubArray(T[] array, Range range) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + + (int offset, int length) = range.GetOffsetAndLength(array.Length); + + if (default(T) != null || typeof(T[]) == array.GetType()) + { + if (length == 0) + return []; + + T[] dest = new T[length]; + Array.Copy(array, offset, dest, 0, length); + return dest; + } + else + { + T[] dest = (T[])Array.CreateInstance(array.GetType().GetElementType()!, length); + Array.Copy(array, offset, dest, 0, length); + return dest; + } + } +} \ No newline at end of file diff --git a/src/go2cs.Common/Metadata/FunctionSignature.cs b/src/go2cs.Common/Metadata/FunctionSignature.cs index 92824f2f4..170d3ec2e 100644 --- a/src/go2cs.Common/Metadata/FunctionSignature.cs +++ b/src/go2cs.Common/Metadata/FunctionSignature.cs @@ -55,7 +55,7 @@ public string GetParameterTypeNames() => public static string Generate(string functionName, IEnumerable parameterTypeNames = null) { if (parameterTypeNames is null) - parameterTypeNames = Enumerable.Empty(); + parameterTypeNames = []; return $"{functionName}({string.Join(", ", parameterTypeNames)})"; } diff --git a/src/go2cs.Common/Metadata/InterfaceInfo.cs b/src/go2cs.Common/Metadata/InterfaceInfo.cs index c7d416811..2969659d1 100644 --- a/src/go2cs.Common/Metadata/InterfaceInfo.cs +++ b/src/go2cs.Common/Metadata/InterfaceInfo.cs @@ -58,7 +58,7 @@ public static InterfaceInfo error() => Name = "Error", Signature = new() { - Parameters = Array.Empty(), + Parameters = [], Result = new[] { new ParameterInfo diff --git a/src/go2cs.Common/go2cs.Common.csproj b/src/go2cs.Common/go2cs.Common.csproj index 0755a9c36..f8975b346 100644 --- a/src/go2cs.Common/go2cs.Common.csproj +++ b/src/go2cs.Common/go2cs.Common.csproj @@ -1,7 +1,7 @@ - + - net7.0 + netstandard2.0 go2cs latest diff --git a/src/go2cs.Templates/InheritedTypeTemplate.cs b/src/go2cs.Templates/InheritedTypeTemplate.cs index 246deca0f..55f6ed5f4 100644 --- a/src/go2cs.Templates/InheritedTypeTemplate.cs +++ b/src/go2cs.Templates/InheritedTypeTemplate.cs @@ -16,7 +16,7 @@ namespace go2cs.Templates /// Class to produce the template output /// - #line 1 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 1 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] public partial class InheritedTypeTemplate : TemplateBase { @@ -27,7 +27,7 @@ public partial class InheritedTypeTemplate : TemplateBase public override string TransformText() { - #line 1 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 1 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" // This template creates an inherited type, e.g., type MyFloat float64 in a _StructOf().cs file #line default @@ -40,7 +40,7 @@ public override string TransformText() // // Generated on "); - #line 11 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 11 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(GeneratedTime)); #line default @@ -49,90 +49,90 @@ public override string TransformText() "--\r\nusing System;\r\nusing System.CodeDom.Compiler;\r\nusing System.Collections;\r\nus" + "ing System.Runtime.CompilerServices;\r\n"); - #line 18 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 18 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" if (!NamespacePrefix.Equals("go")) { #line default #line hidden this.Write("using go;\r\n"); - #line 20 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 20 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" } #line default #line hidden this.Write("\r\n#nullable enable\r\n\r\n"); - #line 24 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 24 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(NamespaceHeader)); #line default #line hidden this.Write("\r\n public static partial class "); - #line 25 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 25 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(PackageName)); #line default #line hidden this.Write("_package\r\n {\r\n ["); - #line 27 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 27 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(GeneratedCodeAttribute)); #line default #line hidden this.Write("]\r\n "); - #line 28 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 28 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Scope)); #line default #line hidden this.Write(" partial struct "); - #line 28 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 28 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default #line hidden - #line 28 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 28 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(ImplementedInterface)); #line default #line hidden this.Write("\r\n {\r\n // Value of the "); - #line 30 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 30 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default #line hidden this.Write(" struct\r\n private readonly "); - #line 31 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 31 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(TypeName)); #line default #line hidden this.Write(" m_value;\r\n "); - #line 32 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 32 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(InterfaceImplementation)); #line default #line hidden this.Write("\r\n public "); - #line 33 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 33 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default #line hidden this.Write("("); - #line 33 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 33 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(TypeName)); #line default @@ -140,14 +140,14 @@ public override string TransformText() this.Write(" value) => m_value = value;\r\n\r\n // Enable implicit conversions between" + " "); - #line 35 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 35 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(TypeName)); #line default #line hidden this.Write(" and "); - #line 35 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 35 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default @@ -155,21 +155,21 @@ public override string TransformText() this.Write(" struct\r\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\r\n " + " public static implicit operator "); - #line 37 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 37 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default #line hidden this.Write("("); - #line 37 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 37 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(TypeName)); #line default #line hidden this.Write(" value) => new "); - #line 37 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 37 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default @@ -177,14 +177,14 @@ public override string TransformText() this.Write("(value);\r\n \r\n [MethodImpl(MethodImplOptions.AggressiveInlin" + "ing)]\r\n public static implicit operator "); - #line 40 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 40 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(TypeName)); #line default #line hidden this.Write("("); - #line 40 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 40 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default @@ -192,7 +192,7 @@ public override string TransformText() this.Write(" value) => value.m_value;\r\n \r\n // Enable comparisons betwee" + "n nil and "); - #line 42 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 42 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default @@ -200,14 +200,14 @@ public override string TransformText() this.Write(" struct\r\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\r\n " + " public static bool operator ==("); - #line 44 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 44 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default #line hidden this.Write(" value, NilType nil) => value.Equals(default("); - #line 44 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 44 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default @@ -215,7 +215,7 @@ public override string TransformText() this.Write("));\r\n\r\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\r\n " + " public static bool operator !=("); - #line 47 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 47 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default @@ -224,7 +224,7 @@ public override string TransformText() "ions.AggressiveInlining)]\r\n public static bool operator ==(NilType ni" + "l, "); - #line 50 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 50 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default @@ -232,7 +232,7 @@ public override string TransformText() this.Write(" value) => value == nil;\r\n\r\n [MethodImpl(MethodImplOptions.AggressiveI" + "nlining)]\r\n public static bool operator !=(NilType nil, "); - #line 53 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 53 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default @@ -240,21 +240,21 @@ public override string TransformText() this.Write(" value) => value != nil;\r\n\r\n [MethodImpl(MethodImplOptions.AggressiveI" + "nlining)]\r\n public static implicit operator "); - #line 56 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 56 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default #line hidden this.Write("(NilType nil) => default("); - #line 56 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 56 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(StructName)); #line default #line hidden this.Write(");\r\n }\r\n }\r\n"); - #line 59 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 59 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(NamespaceFooter)); #line default @@ -263,7 +263,7 @@ public override string TransformText() return this.GenerationEnvironment.ToString(); } - #line 60 "D:\Projects\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" + #line 60 "C:\Projects\gpa\go2cs\src\go2cs.Templates\InheritedTypeTemplate.tt" // Template Parameters public string NamespacePrefix; @@ -307,7 +307,7 @@ public string InterfaceImplementation case TypeClass.Slice: return new ISliceImplementation { TypeName = Common.RemoveSurrounding(TypeName, "slice<", ">") }.TransformText(); case TypeClass.Map: - string[] mapType = Common.RemoveSurrounding(TypeName, "map<", ">").Split(","); + string[] mapType = Common.RemoveSurrounding(TypeName, "map<", ">").Split(','); return new IMapImplementation { KeyName = mapType[0].Trim(), TypeName = mapType[1].Trim() }.TransformText(); case TypeClass.Channel: return ""; diff --git a/src/go2cs.Templates/InheritedTypeTemplate.tt b/src/go2cs.Templates/InheritedTypeTemplate.tt index ae11e0364..99bfad731 100644 --- a/src/go2cs.Templates/InheritedTypeTemplate.tt +++ b/src/go2cs.Templates/InheritedTypeTemplate.tt @@ -100,7 +100,7 @@ public string InterfaceImplementation case TypeClass.Slice: return new ISliceImplementation { TypeName = Common.RemoveSurrounding(TypeName, "slice<", ">") }.TransformText(); case TypeClass.Map: - string[] mapType = Common.RemoveSurrounding(TypeName, "map<", ">").Split(","); + string[] mapType = Common.RemoveSurrounding(TypeName, "map<", ">").Split(','); return new IMapImplementation { KeyName = mapType[0].Trim(), TypeName = mapType[1].Trim() }.TransformText(); case TypeClass.Channel: return ""; diff --git a/src/go2cs.Templates/Internal/Index.cs b/src/go2cs.Templates/Internal/Index.cs new file mode 100644 index 000000000..2dd6fbdd9 --- /dev/null +++ b/src/go2cs.Templates/Internal/Index.cs @@ -0,0 +1,85 @@ +using System.Runtime.CompilerServices; + +// ReSharper disable once CheckNamespace +namespace System; + +internal readonly struct Index : IEquatable +{ + private readonly int m_value; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Index(int value, bool fromEnd = false) + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); + + if (fromEnd) + m_value = ~value; + else + m_value = value; + } + + private Index(int value) + { + m_value = value; + } + + public static Index Start => new Index(0); + + public static Index End => new Index(~0); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromStart(int value) + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); + + return new Index(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromEnd(int value) + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); + + return new Index(~value); + } + + public int Value => m_value < 0 ? ~m_value : m_value; + + public bool IsFromEnd => m_value < 0; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetOffset(int length) + { + int offset = m_value; + + if (IsFromEnd) + offset += length + 1; + + return offset; + } + + public override bool Equals(object? value) + { + return value is Index index && m_value == index.m_value; + } + + public bool Equals(Index other) => m_value == other.m_value; + + public override int GetHashCode() + { + return m_value; + } + + public static implicit operator Index(int value) + { + return FromStart(value); + } + + public override string ToString() + { + return IsFromEnd ? $"^{(uint)Value}" : ((uint)Value).ToString(); + } +} \ No newline at end of file diff --git a/src/go2cs.Templates/Internal/IsExternalInit.cs b/src/go2cs.Templates/Internal/IsExternalInit.cs new file mode 100644 index 000000000..31ef86486 --- /dev/null +++ b/src/go2cs.Templates/Internal/IsExternalInit.cs @@ -0,0 +1,7 @@ +using System.ComponentModel; + +// ReSharper disable once CheckNamespace +namespace System.Runtime.CompilerServices; + +[EditorBrowsable(EditorBrowsableState.Never)] +internal class IsExternalInit { } diff --git a/src/go2cs.Templates/Internal/Range.cs b/src/go2cs.Templates/Internal/Range.cs new file mode 100644 index 000000000..9c0593c6f --- /dev/null +++ b/src/go2cs.Templates/Internal/Range.cs @@ -0,0 +1,70 @@ +// Proxy implementations of System.Range and System.Index for .NET Standard 2.0 + +using System.Runtime.CompilerServices; + +// ReSharper disable once CheckNamespace +namespace System; + +internal readonly struct Range(Index start, Index end) : IEquatable +{ + public Index Start { get; } = start; + + public Index End { get; } = end; + + public override bool Equals(object? value) + { + return value is Range r && r.Start.Equals(Start) && r.End.Equals(End); + } + + public bool Equals(Range other) + { + return other.Start.Equals(Start) && other.End.Equals(End); + } + + public override int GetHashCode() + { + return Start.GetHashCode() * 31 + End.GetHashCode(); + } + + public override string ToString() + { + return $"{Start}..{End}"; + } + + public static Range StartAt(Index start) + { + return new Range(start, Index.End); + } + + public static Range EndAt(Index end) + { + return new Range(Index.Start, end); + } + + public static Range All => new(Index.Start, Index.End); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public (int Offset, int Length) GetOffsetAndLength(int length) + { + int start; + Index startIndex = Start; + + if (startIndex.IsFromEnd) + start = length - startIndex.Value; + else + start = startIndex.Value; + + int end; + Index endIndex = End; + + if (endIndex.IsFromEnd) + end = length - endIndex.Value; + else + end = endIndex.Value; + + if ((uint)end > (uint)length || (uint)start > (uint)end) + throw new ArgumentOutOfRangeException(nameof(length)); + + return (start, end - start); + } +} \ No newline at end of file diff --git a/src/go2cs.Templates/Internal/RuntimeHelpers.cs b/src/go2cs.Templates/Internal/RuntimeHelpers.cs new file mode 100644 index 000000000..8c3b663b2 --- /dev/null +++ b/src/go2cs.Templates/Internal/RuntimeHelpers.cs @@ -0,0 +1,29 @@ +// ReSharper disable once CheckNamespace +namespace System.Runtime.CompilerServices; + +internal static class RuntimeHelpers +{ + public static T[] GetSubArray(T[] array, Range range) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + + (int offset, int length) = range.GetOffsetAndLength(array.Length); + + if (default(T) != null || typeof(T[]) == array.GetType()) + { + if (length == 0) + return []; + + T[] dest = new T[length]; + Array.Copy(array, offset, dest, 0, length); + return dest; + } + else + { + T[] dest = (T[])Array.CreateInstance(array.GetType().GetElementType()!, length); + Array.Copy(array, offset, dest, 0, length); + return dest; + } + } +} \ No newline at end of file diff --git a/src/go2cs.Templates/LibraryProjectTemplate.cs b/src/go2cs.Templates/LibraryProjectTemplate.cs index 4870fc3df..28f5d8aa7 100644 --- a/src/go2cs.Templates/LibraryProjectTemplate.cs +++ b/src/go2cs.Templates/LibraryProjectTemplate.cs @@ -17,7 +17,7 @@ namespace go2cs.Templates /// Class to produce the template output /// - #line 1 "D:\Projects\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" + #line 1 "C:\Projects\gpa\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] public partial class LibraryProjectTemplate : TemplateBase { @@ -28,23 +28,23 @@ public partial class LibraryProjectTemplate : TemplateBase public override string TransformText() { - #line 1 "D:\Projects\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" + #line 1 "C:\Projects\gpa\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" // This template creates a .csproj file #line default #line hidden this.Write("\r\n\r\n \r\n Library\r\n net7.0\r\n \r\n net8.0\r\n go\r\n "); - #line 15 "D:\Projects\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" + #line 15 "C:\Projects\gpa\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(AssemblyName)); #line default #line hidden this.Write("\r\n go2cs\r\n Copyright © "); - #line 17 "D:\Projects\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" + #line 17 "C:\Projects\gpa\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(DateTime.Now.ToString("yyyy"))); #line default @@ -82,7 +82,7 @@ public override string TransformText() $(GOPATH)\src\go2cs\golib\$(OutDir)golib.dll "); - #line 48 "D:\Projects\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" + #line 48 "C:\Projects\gpa\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" if (Imports is not null) @@ -95,12 +95,12 @@ public override string TransformText() importPath = value; string package; - if (importPath.Contains('/')) + if (importPath.Contains("/")) { string[] parts = importPath.Split('/'); package = parts[^1]; parts[0] = $"go2cs.{parts[0]}"; - importPath = string.Join('/', parts); + importPath = string.Join("/", parts); } else { @@ -108,27 +108,27 @@ public override string TransformText() importPath = $"go2cs/{importPath}"; } - importPath = $"$(GOPATH)\\src\\{importPath.Replace('/', '\\')}\\$(OutDir){package}_package.dll"; + importPath = $"$(GOPATH)\\src\\{importPath.Replace("/", "\\")}\\$(OutDir){package}_package.dll"; #line default #line hidden this.Write("\r\n "); - #line 77 "D:\Projects\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" + #line 77 "C:\Projects\gpa\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" } } @@ -141,7 +141,7 @@ public override string TransformText() return this.GenerationEnvironment.ToString(); } - #line 86 "D:\Projects\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" + #line 86 "C:\Projects\gpa\go2cs\src\go2cs.Templates\LibraryProjectTemplate.tt" // Template Parameters public string AssemblyName; // File name without extension diff --git a/src/go2cs.Templates/LibraryProjectTemplate.tt b/src/go2cs.Templates/LibraryProjectTemplate.tt index 02e4b0298..2af661e84 100644 --- a/src/go2cs.Templates/LibraryProjectTemplate.tt +++ b/src/go2cs.Templates/LibraryProjectTemplate.tt @@ -10,7 +10,7 @@ Library - net7.0 + net8.0 go <#=AssemblyName#> go2cs @@ -57,12 +57,12 @@ importPath = value; string package; - if (importPath.Contains('/')) + if (importPath.Contains("/")) { string[] parts = importPath.Split('/'); package = parts[^1]; parts[0] = $"go2cs.{parts[0]}"; - importPath = string.Join('/', parts); + importPath = string.Join("/", parts); } else { @@ -70,7 +70,7 @@ importPath = $"go2cs/{importPath}"; } - importPath = $"$(GOPATH)\\src\\{importPath.Replace('/', '\\')}\\$(OutDir){package}_package.dll";#> + importPath = $"$(GOPATH)\\src\\{importPath.Replace("/", "\\")}\\$(OutDir){package}_package.dll";#> <#=importPath#> diff --git a/src/go2cs.Templates/MainProjectTemplate.cs b/src/go2cs.Templates/MainProjectTemplate.cs index 4438961b2..9094eb54a 100644 --- a/src/go2cs.Templates/MainProjectTemplate.cs +++ b/src/go2cs.Templates/MainProjectTemplate.cs @@ -17,7 +17,7 @@ namespace go2cs.Templates /// Class to produce the template output /// - #line 1 "D:\Projects\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" + #line 1 "C:\Projects\gpa\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] public partial class MainProjectTemplate : TemplateBase { @@ -28,24 +28,24 @@ public partial class MainProjectTemplate : TemplateBase public override string TransformText() { - #line 1 "D:\Projects\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" + #line 1 "C:\Projects\gpa\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" // This template creates a .csproj file #line default #line hidden this.Write("\r\n\r\n \r\n Exe\r\n net7.0\r\n \r\n net8.0\r\n true\r\n go\r\n "); - #line 16 "D:\Projects\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" + #line 16 "C:\Projects\gpa\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(AssemblyName)); #line default #line hidden this.Write("\r\n go2cs\r\n Copyright © "); - #line 18 "D:\Projects\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" + #line 18 "C:\Projects\gpa\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(DateTime.Now.ToString("yyyy"))); #line default @@ -84,7 +84,7 @@ public override string TransformText() $(GOPATH)\src\go2cs\golib\$(OutDir)golib.dll "); - #line 50 "D:\Projects\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" + #line 50 "C:\Projects\gpa\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" if (Imports is not null) @@ -97,12 +97,12 @@ public override string TransformText() importPath = value; string package; - if (importPath.Contains('/')) + if (importPath.Contains("/")) { string[] parts = importPath.Split('/'); package = parts[^1]; parts[0] = $"go2cs.{parts[0]}"; - importPath = string.Join('/', parts); + importPath = string.Join("/", parts); } else { @@ -110,27 +110,27 @@ public override string TransformText() importPath = $"go2cs/{importPath}"; } - importPath = $"$(GOPATH)\\src\\{importPath.Replace('/', '\\')}\\$(OutDir){package}_package.dll"; + importPath = $"$(GOPATH)\\src\\{importPath.Replace("/", "\\")}\\$(OutDir){package}_package.dll"; #line default #line hidden this.Write("\r\n "); - #line 79 "D:\Projects\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" + #line 79 "C:\Projects\gpa\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" } } @@ -143,7 +143,7 @@ public override string TransformText() return this.GenerationEnvironment.ToString(); } - #line 88 "D:\Projects\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" + #line 88 "C:\Projects\gpa\go2cs\src\go2cs.Templates\MainProjectTemplate.tt" // Template Parameters public string AssemblyName; // File name without extension diff --git a/src/go2cs.Templates/MainProjectTemplate.tt b/src/go2cs.Templates/MainProjectTemplate.tt index f8fc6692d..bd3876427 100644 --- a/src/go2cs.Templates/MainProjectTemplate.tt +++ b/src/go2cs.Templates/MainProjectTemplate.tt @@ -10,7 +10,7 @@ Exe - net7.0 + net8.0 true go <#=AssemblyName#> @@ -59,12 +59,12 @@ importPath = value; string package; - if (importPath.Contains('/')) + if (importPath.Contains("/")) { string[] parts = importPath.Split('/'); package = parts[^1]; parts[0] = $"go2cs.{parts[0]}"; - importPath = string.Join('/', parts); + importPath = string.Join("/", parts); } else { @@ -72,7 +72,7 @@ importPath = $"go2cs/{importPath}"; } - importPath = $"$(GOPATH)\\src\\{importPath.Replace('/', '\\')}\\$(OutDir){package}_package.dll";#> + importPath = $"$(GOPATH)\\src\\{importPath.Replace("/", "\\")}\\$(OutDir){package}_package.dll";#> <#=importPath#> diff --git a/src/go2cs.Templates/TemplateBase.cs b/src/go2cs.Templates/TemplateBase.cs index d73ba8932..53a8f4b81 100644 --- a/src/go2cs.Templates/TemplateBase.cs +++ b/src/go2cs.Templates/TemplateBase.cs @@ -18,7 +18,7 @@ namespace go2cs.Templates /// Class to produce the template output /// - #line 1 "D:\Projects\go2cs\src\go2cs.Templates\TemplateBase.tt" + #line 1 "C:\Projects\gpa\go2cs\src\go2cs.Templates\TemplateBase.tt" [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] public partial class TemplateBase : TemplateBaseBase { @@ -31,14 +31,14 @@ public virtual string TransformText() return this.GenerationEnvironment.ToString(); } - #line 9 "D:\Projects\go2cs\src\go2cs.Templates\TemplateBase.tt" + #line 9 "C:\Projects\gpa\go2cs\src\go2cs.Templates\TemplateBase.tt" /* It's important to note that these templates are designed for use at runtime, as a result the project file should be set to use the file preprocessor for each T4 template, e.g.: TextTemplatingFilePreprocessor */ -public string Version => Common.EntryAssembly.GetName().Version.ToString(); +public string Version => "0.1.0"; //Common.EntryAssembly.GetName().Version.ToString(); public string GeneratedCodeAttribute => $"GeneratedCode(\"go2cs\", \"{Version}\")"; @@ -70,7 +70,7 @@ public class TemplateBaseBase /// /// The string builder that generation-time code is using to assemble generated output /// - protected System.Text.StringBuilder GenerationEnvironment + public System.Text.StringBuilder GenerationEnvironment { get { diff --git a/src/go2cs.Templates/TemplateBase.tt b/src/go2cs.Templates/TemplateBase.tt index d01565c9e..fc6d64faa 100644 --- a/src/go2cs.Templates/TemplateBase.tt +++ b/src/go2cs.Templates/TemplateBase.tt @@ -12,7 +12,7 @@ the project file should be set to use the file preprocessor for each T4 template, e.g.: TextTemplatingFilePreprocessor */ -public string Version => Common.EntryAssembly.GetName().Version.ToString(); +public string Version => "0.1.0"; //Common.EntryAssembly.GetName().Version.ToString(); public string GeneratedCodeAttribute => $"GeneratedCode(\"go2cs\", \"{Version}\")"; diff --git a/src/go2cs.Templates/go2cs.Templates.csproj b/src/go2cs.Templates/go2cs.Templates.csproj index f2e94a6db..fb4df2d53 100644 --- a/src/go2cs.Templates/go2cs.Templates.csproj +++ b/src/go2cs.Templates/go2cs.Templates.csproj @@ -1,15 +1,11 @@  - net7.0 + netstandard2.0 go2cs.Templates latest - - bin\$(Configuration)\$(TargetFramework)\ - - diff --git a/src/go2cs.sln b/src/go2cs.sln index 914dfa54f..46db11d11 100644 --- a/src/go2cs.sln +++ b/src/go2cs.sln @@ -92,6 +92,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GrammarTests", "Tests\Gramm EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASTTests", "Tests\ASTTests\ASTTests.csproj", "{3914E6ED-7859-4C5E-8A2B-1D8C4A934F0A}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "go2cs.CodeGenerators", "go2cs.CodeGenerators\go2cs.CodeGenerators.csproj", "{BF939235-2F28-4B8E-A34C-CBE30DA45415}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -222,6 +224,10 @@ Global {3914E6ED-7859-4C5E-8A2B-1D8C4A934F0A}.Debug|Any CPU.Build.0 = Debug|Any CPU {3914E6ED-7859-4C5E-8A2B-1D8C4A934F0A}.Release|Any CPU.ActiveCfg = Release|Any CPU {3914E6ED-7859-4C5E-8A2B-1D8C4A934F0A}.Release|Any CPU.Build.0 = Release|Any CPU + {BF939235-2F28-4B8E-A34C-CBE30DA45415}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BF939235-2F28-4B8E-A34C-CBE30DA45415}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BF939235-2F28-4B8E-A34C-CBE30DA45415}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BF939235-2F28-4B8E-A34C-CBE30DA45415}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -261,6 +267,7 @@ Global {FAADAA70-3DE3-411F-A679-39D1757B84D9} = {6F09E8D8-D54E-46B1-875C-987A40094FF5} {D0DB5C35-CE9D-49F5-99B6-D31A187DEEA0} = {65A671E4-4025-48B4-8FD0-9C57FECA553A} {3914E6ED-7859-4C5E-8A2B-1D8C4A934F0A} = {6F09E8D8-D54E-46B1-875C-987A40094FF5} + {BF939235-2F28-4B8E-A34C-CBE30DA45415} = {78E6A8DC-83D6-4536-BE17-211B1B1D0D97} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {96A9E85F-A473-4202-B41E-F0E5F3B9AF22} diff --git a/src/go2cs/Converter/Converter_ForStmt.cs b/src/go2cs/Converter/Converter_ForStmt.cs index b50406f10..674cb7b7e 100644 --- a/src/go2cs/Converter/Converter_ForStmt.cs +++ b/src/go2cs/Converter/Converter_ForStmt.cs @@ -63,7 +63,7 @@ private bool ForHasInitStatement(GoParser.ForClauseContext forClause, out GoPars if (!Identifiers.TryGetValue(identifierList, out identifiers)) { AddWarning(shortVarDecl, $"Failed to find identifier lists for short var declaration statements: {shortVarDecl.GetText()}"); - identifiers = Array.Empty(); + identifiers = []; } } diff --git a/src/go2cs/Converter/Converter_MethodDecl.cs b/src/go2cs/Converter/Converter_MethodDecl.cs index c9e11d6b3..b1901a3b9 100644 --- a/src/go2cs/Converter/Converter_MethodDecl.cs +++ b/src/go2cs/Converter/Converter_MethodDecl.cs @@ -69,7 +69,7 @@ public override void ExitMethodDecl(GoParser.MethodDeclContext context) string receiverParametersSignature = method.GenerateReceiverParametersSignature(); string parametersSignature = signature.GenerateParametersSignature(); string resultSignature = signature.GenerateResultSignature(); - ParameterInfo[] receiverParameters = method.ReceiverParameters ?? Array.Empty(); + ParameterInfo[] receiverParameters = method.ReceiverParameters ?? []; if (signature.Parameters.Length == 0) parametersSignature = $"({receiverParametersSignature})"; diff --git a/src/go2cs/PreScanner/PreScanner_Type.cs b/src/go2cs/PreScanner/PreScanner_Type.cs index a4bcb5d18..74c2132f1 100644 --- a/src/go2cs/PreScanner/PreScanner_Type.cs +++ b/src/go2cs/PreScanner/PreScanner_Type.cs @@ -120,7 +120,7 @@ public override void ExitInterfaceType(GoParser.InterfaceTypeContext context) Name = GetValidIdentifierName(typeInfo.TypeName), Signature = new Signature { - Parameters = System.Array.Empty(), + Parameters = [], Result = new[] { new ParameterInfo @@ -151,8 +151,8 @@ public override void ExitInterfaceType(GoParser.InterfaceTypeContext context) Name = identifier, Signature = Signatures[context] = new Signature { - Parameters = parameters?.ToArray() ?? System.Array.Empty(), - Result = Result?.ToArray() ?? System.Array.Empty() + Parameters = parameters?.ToArray() ?? [], + Result = Result?.ToArray() ?? [] }, Comments = CheckForCommentsRight(methodSpec), IsPromoted = false diff --git a/src/go2cs/Properties/PublishProfiles/linux-arm.pubxml b/src/go2cs/Properties/PublishProfiles/linux-arm.pubxml index 52b49d785..b8f572e5d 100644 --- a/src/go2cs/Properties/PublishProfiles/linux-arm.pubxml +++ b/src/go2cs/Properties/PublishProfiles/linux-arm.pubxml @@ -6,9 +6,9 @@ https://go.microsoft.com/fwlink/?LinkID=208121. Release Any CPU - bin\Release\net7.0\publish\linux-arm\ + bin\Release\net8.0\publish\linux-arm\ FileSystem - net7.0 + net8.0 linux-arm true True diff --git a/src/go2cs/Properties/PublishProfiles/linux-x64.pubxml b/src/go2cs/Properties/PublishProfiles/linux-x64.pubxml index 7f3e5f9b1..d7d9f8da0 100644 --- a/src/go2cs/Properties/PublishProfiles/linux-x64.pubxml +++ b/src/go2cs/Properties/PublishProfiles/linux-x64.pubxml @@ -6,9 +6,9 @@ https://go.microsoft.com/fwlink/?LinkID=208121. Release Any CPU - bin\Release\net7.0\publish\linux-x64\ + bin\Release\net8.0\publish\linux-x64\ FileSystem - net7.0 + net8.0 linux-x64 true True diff --git a/src/go2cs/Properties/PublishProfiles/osx-x64.pubxml b/src/go2cs/Properties/PublishProfiles/osx-x64.pubxml index 66363f65e..4b54dfe94 100644 --- a/src/go2cs/Properties/PublishProfiles/osx-x64.pubxml +++ b/src/go2cs/Properties/PublishProfiles/osx-x64.pubxml @@ -6,9 +6,9 @@ https://go.microsoft.com/fwlink/?LinkID=208121. Release Any CPU - bin\Release\net7.0\publish\osx-x64\ + bin\Release\net8.0\publish\osx-x64\ FileSystem - net7.0 + net8.0 osx-x64 true True diff --git a/src/go2cs/Properties/PublishProfiles/win-64.pubxml b/src/go2cs/Properties/PublishProfiles/win-64.pubxml index 82931b3fb..eea4a16eb 100644 --- a/src/go2cs/Properties/PublishProfiles/win-64.pubxml +++ b/src/go2cs/Properties/PublishProfiles/win-64.pubxml @@ -6,9 +6,9 @@ https://go.microsoft.com/fwlink/?LinkID=208121. Release Any CPU - bin\Release\net7.0\publish\win-x64\ + bin\Release\net8.0\publish\win-x64\ FileSystem - net7.0 + net8.0 win-x64 true True diff --git a/src/go2cs/ScannerBase/ScannerBase_Signature.cs b/src/go2cs/ScannerBase/ScannerBase_Signature.cs index 95884fed5..40782ef00 100644 --- a/src/go2cs/ScannerBase/ScannerBase_Signature.cs +++ b/src/go2cs/ScannerBase/ScannerBase_Signature.cs @@ -55,8 +55,8 @@ public override void ExitSignature(GoParser.SignatureContext context) Parameters.TryGetValue(context.parameters(), out List parameters); Signatures[context] = new Signature { - Parameters = parameters?.ToArray() ?? System.Array.Empty(), - Result = Result?.ToArray() ?? System.Array.Empty() + Parameters = parameters?.ToArray() ?? [], + Result = Result?.ToArray() ?? [] }; } diff --git a/src/go2cs/go2cs.csproj b/src/go2cs/go2cs.csproj index 5ffb38758..c6b9d90cc 100644 --- a/src/go2cs/go2cs.csproj +++ b/src/go2cs/go2cs.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 true go2cs go2cs diff --git a/src/gocore/errors/errors.csproj b/src/gocore/errors/errors.csproj index 34656839d..12a639ca7 100644 --- a/src/gocore/errors/errors.csproj +++ b/src/gocore/errors/errors.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 go errors_package ..\go2cs.ico diff --git a/src/gocore/fmt/fmt.csproj b/src/gocore/fmt/fmt.csproj index c2c039aa2..5fecedbe6 100644 --- a/src/gocore/fmt/fmt.csproj +++ b/src/gocore/fmt/fmt.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 go fmt_package ..\go2cs.ico diff --git a/src/gocore/golib/TypeExtensions.cs b/src/gocore/golib/TypeExtensions.cs index 3e2acfd65..9d3c115ec 100644 --- a/src/gocore/golib/TypeExtensions.cs +++ b/src/gocore/golib/TypeExtensions.cs @@ -22,6 +22,7 @@ //****************************************************************************************************** // ReSharper disable CheckNamespace // ReSharper disable UnusedMember.Global +// ReSharper disable InconsistentNaming using System; using System.Collections.Generic; @@ -358,7 +359,7 @@ public static MethodInfo GetExplicitGenericConversionOperator(this Type genericT } /// - /// Create a interface handler for interface from + /// Create an interface handler for interface from /// an object-based target. /// /// Generic handler type. diff --git a/src/gocore/golib/array.cs b/src/gocore/golib/array.cs index 7e29b0f52..e8c256a39 100644 --- a/src/gocore/golib/array.cs +++ b/src/gocore/golib/array.cs @@ -29,7 +29,6 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; -using static System.Runtime.InteropServices.JavaScript.JSType; namespace go; @@ -55,7 +54,7 @@ public interface IArray : IArray internal readonly T[] m_array; [MethodImpl(MethodImplOptions.AggressiveInlining)] - public array() => m_array = Array.Empty(); + public array() => m_array = []; [MethodImpl(MethodImplOptions.AggressiveInlining)] public array(int length) => m_array = new T[length]; @@ -67,7 +66,7 @@ public interface IArray : IArray public array(ulong length) => m_array = new T[length]; [MethodImpl(MethodImplOptions.AggressiveInlining)] - public array(T[]? array) => m_array = array ?? Array.Empty(); + public array(T[]? array) => m_array = array ?? []; [MethodImpl(MethodImplOptions.AggressiveInlining)] public array(Span source) => m_array = source.ToArray(); diff --git a/src/gocore/golib/golib.csproj b/src/gocore/golib/golib.csproj index d80627d5b..f1a301840 100644 --- a/src/gocore/golib/golib.csproj +++ b/src/gocore/golib/golib.csproj @@ -1,7 +1,7 @@  - net7.0 + net8.0 true go ..\go2cs.ico diff --git a/src/gocore/golib/slice.cs b/src/gocore/golib/slice.cs index 4bab147c2..143323782 100644 --- a/src/gocore/golib/slice.cs +++ b/src/gocore/golib/slice.cs @@ -62,7 +62,7 @@ public interface ISlice : ISlice public slice() { - m_array = Array.Empty(); + m_array = []; m_low = m_length = 0; } diff --git a/src/gocore/golib/sstring.cs b/src/gocore/golib/sstring.cs index 86f25681d..f9294bba7 100644 --- a/src/gocore/golib/sstring.cs +++ b/src/gocore/golib/sstring.cs @@ -76,11 +76,11 @@ namespace go; internal readonly ReadOnlySpan m_value; [MethodImpl(MethodImplOptions.AggressiveInlining)] - public sstring() => m_value = ReadOnlySpan.Empty; + public sstring() => m_value = []; [MethodImpl(MethodImplOptions.AggressiveInlining)] public sstring(byte[]? bytes) => - m_value = bytes is null ? ReadOnlySpan.Empty : new ReadOnlySpan(bytes); + m_value = bytes is null ? [] : new ReadOnlySpan(bytes); [MethodImpl(MethodImplOptions.AggressiveInlining)] public sstring(ReadOnlySpan bytes) => @@ -255,7 +255,7 @@ private static unsafe bool Decode(Decoder decoder, byte[] value, int index, int #endif [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator sstring(slice value) => new(value.ToArray()); + public static implicit operator sstring(in slice value) => new(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator slice(sstring value) => new(value.m_value); @@ -267,7 +267,7 @@ private static unsafe bool Decode(Decoder decoder, byte[] value, int index, int public static implicit operator slice(sstring value) => new(GetRuneEnumerator(value.ToString()).ToArray()); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator sstring(slice value) => new(value.ToArray()); + public static implicit operator sstring(in slice value) => new(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator slice(sstring value) => new(value.ToString().ToCharArray()); diff --git a/src/gocore/golib/string.cs b/src/gocore/golib/string.cs index 4eee73927..5fee38f55 100644 --- a/src/gocore/golib/string.cs +++ b/src/gocore/golib/string.cs @@ -39,31 +39,31 @@ namespace go; /// /// Represents a structure with heap allocated data that behaves like a Go string. /// -public readonly struct @string : IConvertible, IEquatable<@string>, IComparable<@string>, IReadOnlyList, IEnumerable, IEnumerable<(nint, rune)>, IEnumerable, ICloneable +public readonly struct @string : IConvertible, IEquatable<@string>, IComparable<@string>, IReadOnlyList, IEnumerable, IEnumerable<(nint, rune)>, IEnumerable, ICloneable { - internal readonly byte[] m_value; + internal readonly uint8[] m_value; [MethodImpl(MethodImplOptions.AggressiveInlining)] - public @string() => m_value = Array.Empty(); + public @string() => m_value = []; [MethodImpl(MethodImplOptions.AggressiveInlining)] - public @string(byte[]? bytes) + public @string(uint8[]? bytes) { if (bytes is null) { - m_value = Array.Empty(); + m_value = []; } else { - m_value = new byte[bytes.Length]; + m_value = new uint8[bytes.Length]; Array.Copy(bytes, m_value, bytes.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public @string(ReadOnlySpan bytes) + public @string(ReadOnlySpan bytes) { - m_value = new byte[bytes.Length]; + m_value = new uint8[bytes.Length]; bytes.CopyTo(m_value); } @@ -74,7 +74,7 @@ public @string(char[] value) : this(new string(value)) { } public @string(rune[] value) : this(new string(value.Select(item => (char)item).ToArray())) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public @string(in slice value) : this(value.ToArray()) { } + public @string(in slice value) : this(value.ToArray()) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public @string(in slice value) : this(value.ToArray()) { } @@ -94,7 +94,7 @@ public int Length get => m_value.Length; } - public byte this[int index] + public uint8 this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get @@ -106,7 +106,7 @@ public byte this[int index] } } - public byte this[nint index] + public uint8 this[nint index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get @@ -118,7 +118,7 @@ public byte this[nint index] } } - public byte this[ulong index] + public uint8 this[ulong index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => this[(nint)index]; @@ -126,11 +126,11 @@ public byte this[ulong index] // Allows for implicit range support: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges#implicit-range-support [MethodImpl(MethodImplOptions.AggressiveInlining)] - public slice Slice(int start, int length) => + public slice Slice(int start, int length) => new(m_value, start, start + length); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public slice Slice(nint start, nint length) => + public slice Slice(nint start, nint length) => new(m_value, (int)start, (int)(start + length)); [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -176,7 +176,7 @@ public override bool Equals(object? obj) yield break; Decoder decoder = Encoding.UTF8.GetDecoder(); - byte[] value = m_value; + uint8[] value = m_value; char[] rune = new char[1]; int byteCount; @@ -199,11 +199,11 @@ public override bool Equals(object? obj) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe bool Decode(Decoder decoder, byte[] value, nint index, int byteCount, char[] rune) + private static unsafe bool Decode(Decoder decoder, uint8[] value, nint index, int byteCount, char[] rune) { bool completed; - fixed (byte* bytes = &value[index]) + fixed (uint8* bytes = &value[index]) fixed (char* chars = rune) { decoder.Convert(bytes, byteCount, chars, 1, true, out _, out _, out completed); @@ -234,15 +234,15 @@ public static @string Default { #else [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator @string(ReadOnlySpan value) => new(value); + public static implicit operator @string(ReadOnlySpan value) => new(value); #endif [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator @string(slice value) => new(value); + public static implicit operator @string(slice value) => new(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator slice(@string value) => new(value.m_value); + public static implicit operator slice(@string value) => new(value.m_value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator @string(slice value) => new(value); @@ -257,10 +257,10 @@ public static @string Default { public static implicit operator slice(@string value) => new(((IEnumerable)value).ToArray()); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static explicit operator byte[](@string value) => value.m_value; + public static explicit operator uint8[](@string value) => value.m_value; [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator @string(byte[] value) => new(value); + public static implicit operator @string(uint8[] value) => new(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator rune[](@string value) => ((IEnumerable)value).ToArray(); @@ -315,7 +315,7 @@ public static @string Default { object ICloneable.Clone() => Clone(); - int IReadOnlyCollection.Count => Length; + int IReadOnlyCollection.Count => Length; bool IConvertible.ToBoolean(IFormatProvider? provider) => ((IConvertible)ToString()).ToBoolean(provider); @@ -323,7 +323,7 @@ public static @string Default { sbyte IConvertible.ToSByte(IFormatProvider? provider) => ((IConvertible)ToString()).ToSByte(provider); - byte IConvertible.ToByte(IFormatProvider? provider) => ((IConvertible)ToString()).ToByte(provider); + uint8 IConvertible.ToByte(IFormatProvider? provider) => ((IConvertible)ToString()).ToByte(provider); short IConvertible.ToInt16(IFormatProvider? provider) => ((IConvertible)ToString()).ToInt16(provider); @@ -351,9 +351,9 @@ public static @string Default { IEnumerator IEnumerable.GetEnumerator() => m_value.GetEnumerator(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - IEnumerator IEnumerable.GetEnumerator() + IEnumerator IEnumerable.GetEnumerator() { - foreach (byte item in m_value) + foreach (uint8 item in m_value) yield return item; } @@ -369,7 +369,7 @@ IEnumerator IEnumerable.GetEnumerator() [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe bool BytesAreEqual(byte[] data1, byte[] data2) + private static unsafe bool BytesAreEqual(uint8[] data1, uint8[] data2) { if (data1 == data2) return true; @@ -380,7 +380,7 @@ private static unsafe bool BytesAreEqual(byte[] data1, byte[] data2) if (data1.Length == 0) return true; - fixed (byte* bytes1 = data1, bytes2 = data2) + fixed (uint8* bytes1 = data1, bytes2 = data2) { int len = data1.Length; int rem = len % (sizeof(long) * 16); diff --git a/src/gocore/golib/typeAttribute.cs b/src/gocore/golib/typeAttribute.cs new file mode 100644 index 000000000..512074336 --- /dev/null +++ b/src/gocore/golib/typeAttribute.cs @@ -0,0 +1,36 @@ +//****************************************************************************************************** +// typeAttribute.cs - Gbtc +// +// Copyright © 2024, Grid Protection Alliance. All Rights Reserved. +// +// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See +// the NOTICE file distributed with this work for additional information regarding copyright ownership. +// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this +// file except in compliance with the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/MIT +// +// Unless agreed to in writing, the subject software distributed under the License is distributed on an +// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the +// License for the specific language governing permissions and limitations. +// +// Code Modification History: +// ---------------------------------------------------------------------------------------------------- +// 09/15/2024 - J. Ritchie Carroll +// Generated original version of source code. +// +//****************************************************************************************************** +// ReSharper disable InconsistentNaming + +using System; + +namespace go; + +/// +/// Represents a type definition attribute. +/// +/// Type definition string. +public class typeAttribute(string definition) : Attribute +{ + public string Definition { get; } = definition; +} diff --git a/src/gocore/io/io.csproj b/src/gocore/io/io.csproj index 6d2d8d0ea..59d21d402 100644 --- a/src/gocore/io/io.csproj +++ b/src/gocore/io/io.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 go io_package ..\go2cs.ico diff --git a/src/gocore/sort/sort.csproj b/src/gocore/sort/sort.csproj index 4e6745b69..545d6a1b9 100644 --- a/src/gocore/sort/sort.csproj +++ b/src/gocore/sort/sort.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 go sort_package ..\go2cs.ico diff --git a/src/gocore/strings/strings.csproj b/src/gocore/strings/strings.csproj index 27e2104a3..3d8565044 100644 --- a/src/gocore/strings/strings.csproj +++ b/src/gocore/strings/strings.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 go strings_package ..\go2cs.ico diff --git a/src/gocore/sync/sync.csproj b/src/gocore/sync/sync.csproj index 62049ba80..f221987a9 100644 --- a/src/gocore/sync/sync.csproj +++ b/src/gocore/sync/sync.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 go sync_package ..\go2cs.ico diff --git a/src/gocore/time/time.csproj b/src/gocore/time/time.csproj index 44bb1c3dc..cc622f5c5 100644 --- a/src/gocore/time/time.csproj +++ b/src/gocore/time/time.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 go time_package ..\go2cs.ico