From 2ac4afa37995e848d1f767fd35788d5033623af9 Mon Sep 17 00:00:00 2001 From: Chris Anders Date: Sat, 30 Nov 2024 19:14:57 +0100 Subject: [PATCH] refactor: Cleanup --- .Net Core Templates/templatepack.csproj | 37 -- .../class/.template.config/template.json | 12 - .../templates/class/MyClass.back | 0 .../console/.template.config/template.json | 12 - .../templates/console/Program.back | 4 - .../templates/console/TestConsole.backproj | 11 - .../library/.template.config/template.json | 12 - .../templates/library/MyLibrary.backproj | 11 - .../templates/library/test.back | 3 - .github/workflows/release.yml | 2 +- Backlang-npp.xml | 64 ---- Source/.editorconfig | 52 +-- .../Backlang-Compiler.csproj | 58 +-- Source/Backlang-Compiler/Program.cs | 11 +- .../Backlang.Codeanalysis.csproj | 94 +++-- .../Attributes/BinaryOperatorInfoAttribute.cs | 2 +- .../Core/Attributes/KeywordAttribute.cs | 2 +- .../Core/Attributes/LexemeAttribute.cs | 2 +- .../Core/Attributes/OperatorInfoAttribute.cs | 2 +- .../PostUnaryOperatorInfoAttribute.cs | 4 +- .../PreUnaryOperatorInfoAttribute.cs | 4 +- .../Backlang.Codeanalysis/Core/BaseLexer.cs | 5 +- Source/Backlang.Codeanalysis/Core/ErrorID.cs | 4 +- .../Core/LevensteinDistance.cs | 7 +- .../Core/LocalizableString.cs | 9 +- .../Parsing/AST/Annotation.cs | 4 +- .../Parsing/AST/CompilationUnit.cs | 2 +- .../Declarations/BitFieldMemberDeclaration.cs | 5 +- .../AST/Declarations/EnumMemberDeclaration.cs | 2 +- .../Declarations/ImplementationDeclaration.cs | 3 +- .../AST/Declarations/MacroBlockDeclaration.cs | 9 +- .../AST/Declarations/ParameterDeclaration.cs | 8 +- .../AST/Declarations/TypeMemberDeclaration.cs | 8 +- .../Parsing/AST/DocComment.cs | 2 +- .../Expressions/InitializerListExpression.cs | 4 +- .../AST/Expressions/Match/MatchExpression.cs | 16 +- .../AST/Expressions/Match/MatchRule.cs | 13 +- .../Parsing/AST/Expressions/NameExpression.cs | 6 +- .../Parsing/AST/Modifier.cs | 28 +- .../Parsing/AST/Signature.cs | 3 +- .../AST/Statements/MacroBlockStatement.cs | 19 +- .../Parsing/AST/Statements/Statement.cs | 8 +- .../Parsing/AST/Statements/SwitchStatement.cs | 11 +- .../Parsing/AST/Statements/TryStatement.cs | 8 +- .../AST/Statements/VariableStatement.cs | 4 +- .../Parsing/AST/TypeLiteral.cs | 17 +- .../Parsing/Expression.cs | 42 ++- .../Parsing/LNodeExtensions.cs | 7 +- Source/Backlang.Codeanalysis/Parsing/Lexer.cs | 64 ++-- .../Backlang.Codeanalysis/Parsing/Message.cs | 8 +- .../Parsing/OperatorInfo.cs | 5 +- .../Parsing/Parser.Expressions.cs | 49 +-- .../Parsing/Parser.ParsePoints.cs | 11 +- .../Backlang.Codeanalysis/Parsing/Parser.cs | 4 +- .../Precedences/BinaryOpPrecedences.cs | 2 +- .../Parsing/Precedences/UnaryOpPrecedences.cs | 5 +- .../Parsing/SourceDocument.cs | 6 +- .../Parsing/SyntaxTree.cs | 31 +- Source/Backlang.Codeanalysis/Parsing/Token.cs | 2 +- .../Parsing/TokenIterator.cs | 19 +- .../Parsing/TokenType.cs | 308 +++++----------- .../Parsing/TokenUtils.cs | 17 +- .../Properties/Resources.Designer.cs | 94 ++--- .../Properties/Resources.resx | 297 +++++++-------- Source/Backlang.Contracts/Attributes.cs | 3 +- .../Backlang.Contracts.csproj | 62 ++-- Source/Backlang.Contracts/CompilerContext.cs | 7 +- Source/Backlang.Contracts/ConversionUtils.cs | 22 +- .../Datas/CompilerCliOptions.cs | 6 +- .../Backlang.Contracts/Datas/FileScopeData.cs | 4 +- .../DefaultTypeEnvironment.cs | 3 - Source/Backlang.Contracts/ISemanticCheck.cs | 6 +- Source/Backlang.Contracts/IntrinsicHelper.cs | 32 +- .../MethodBodyCompilation.cs | 8 +- Source/Backlang.Contracts/NamespaceImports.cs | 11 +- Source/Backlang.Contracts/Scoping/Scope.cs | 20 +- .../Semantic/ImportCheck.cs | 3 +- .../Semantic/InterfaceNameCheck.cs | 9 +- .../Semantic/ModifierCheck.cs | 9 +- .../Semantic/TypenameCheck.cs | 5 +- .../Semantic/VariableTypeCheck.cs | 2 +- Source/Backlang.Contracts/SemanticChecker.cs | 3 +- Source/Backlang.Contracts/StackHelpers.cs | 25 +- .../TypeSystem/BooleanType.cs | 6 +- .../Backlang.Contracts/TypeSystem/I16Type.cs | 6 +- .../Backlang.Contracts/TypeSystem/I32Type.cs | 6 +- .../Backlang.Contracts/TypeSystem/I64Type.cs | 6 +- .../Backlang.Contracts/TypeSystem/I8Type.cs | 6 +- .../TypeSystem/ObjectType.cs | 6 +- .../TypeSystem/StringType.cs | 6 +- .../Backlang.Contracts/TypeSystem/U16Type.cs | 6 +- .../Backlang.Contracts/TypeSystem/U32Type.cs | 6 +- .../Backlang.Contracts/TypeSystem/U64Type.cs | 6 +- .../Backlang.Contracts/TypeSystem/U8Type.cs | 6 +- .../Backlang.Contracts/TypeSystem/VoidType.cs | 6 +- Source/Backlang.Core/Backlang.Core.csproj | 44 +-- Source/Backlang.Core/Macros/BuiltInMacros.cs | 44 ++- Source/Backlang.Core/Macros/QuoteMacro.cs | 173 ++++++--- Source/Backlang.Core/Result.cs | 35 +- Source/Backlang.Core/Sealed.cs | 3 +- Source/Backlang.Driver/Backlang.Driver.csproj | 102 +++--- Source/Backlang.Driver/BinderExtensions.cs | 11 +- Source/Backlang.Driver/CompilerDriver.cs | 84 +++-- .../Backlang.Driver/Compiling/Attributes.cs | 3 +- .../Backlang.Driver/Compiling/IRGenerator.cs | 60 +-- .../CompilationStages/CompileTargetStage.cs | 14 +- .../ImplementationStage.BodyCompile.cs | 115 +++--- .../ImplementationStage.Helpers.cs | 46 +-- .../CompilationStages/ImplementationStage.cs | 39 +- .../CompilationStages/IntermediateStage.cs | 24 +- .../TypeInheritanceStage.ConvertFunction.cs | 42 ++- .../TypeInheritanceStage.Resolving.cs | 46 +-- .../CompilationStages/TypeInheritanceStage.cs | 113 +++--- .../Compiling/Stages/EmitTreeStage.cs | 3 +- .../ExpandImplementationStage.cs | 18 +- .../ExpandingStages/ExpandMacrosStage.cs | 10 +- .../InitStages/InitEmbeddedResourcesStage.cs | 3 +- .../Stages/InitStages/InitStage.TypeSystem.cs | 26 +- .../Compiling/Stages/InitStages/InitStage.cs | 3 +- .../Compiling/Stages/ParsingStage.cs | 3 +- .../Compiling/Stages/ReportErrorStage.cs | 3 +- .../Compiling/Stages/SemanticCheckStage.cs | 3 +- .../Compiling/Stages/WaitForDebuggerStage.cs | 3 +- .../Targets/Dotnet/CecilExtensions.cs | 11 +- .../Dotnet/ClrTypeEnvironmentBuilder.cs | 27 +- .../Targets/Dotnet/DotNetAssembly.cs | 107 +++--- .../Compiling/Targets/Dotnet/DotNetTarget.cs | 8 +- .../Dotnet/Emitters/ArithmetikEmitter.cs | 14 +- .../Targets/Dotnet/Emitters/CallEmitter.cs | 9 +- .../Targets/Dotnet/Emitters/CopyEmitter.cs | 4 +- .../Dotnet/Emitters/DynamicCastEmitter.cs | 4 +- .../Targets/Dotnet/Emitters/LoadEmitter.cs | 4 +- .../Dotnet/Emitters/LoadIndirectEmitter.cs | 4 +- .../Dotnet/Emitters/NewArrayEmitter.cs | 4 +- .../Dotnet/Emitters/NewObjectEmitter.cs | 4 +- .../Targets/Dotnet/Emitters/TypeofEmitter.cs | 3 +- .../Compiling/Targets/Dotnet/Intrinsics.cs | 68 +++- .../Targets/Dotnet/MethodBodyCompiler.cs | 48 ++- .../RuntimeOptionsModels/FrameworkOptions.cs | 6 +- .../RuntimeOptionsModels/RuntimeConfig.cs | 3 +- .../RuntimeOptionsModels/RuntimeOptions.cs | 6 +- .../Compiling/Targets/Dotnet/TypeUtils.cs | 17 +- .../Core/Implementors/Branches.cs | 2 +- .../AddressExpressionImplementor.cs | 11 +- .../Expressions/ArrayExpressionImplementor.cs | 33 +- .../Expressions/AsExpressionImplementor.cs | 5 +- .../BinaryExpressionImplementor.cs | 19 +- .../Expressions/CallExpressionEmitter.cs | 17 +- .../Expressions/ConstantExpressionEmitter.cs | 5 +- .../Expressions/CtorExpressionImplementor.cs | 5 +- .../DefaultExpressionImplementor.cs | 11 +- .../IdentifierExpressionImplementor.cs | 13 +- .../MemberExpressionImplementor.cs | 11 +- .../PointerExpressionImplementor.cs | 7 +- .../Expressions/TupleExpressionImplementor.cs | 10 +- .../TypeOfExpressionImplementor.cs | 8 +- .../Expressions/UnaryExpressionImplementor.cs | 8 +- .../Implementors/IStatementImplementor.cs | 3 +- .../Statements/AssignmentImplementor.cs | 5 +- .../Statements/BreakStatementImplementor.cs | 3 +- .../Statements/CallImplementor.cs | 31 +- .../ContinueStatementImplementor.cs | 3 +- .../Statements/DoWhileImplementor.cs | 5 +- .../Implementors/Statements/IfImplementor.cs | 22 +- .../Statements/PrintOrPrintlnImplementor.cs | 3 +- .../Statements/ReturnImplementor.cs | 3 +- .../Statements/StaticCallImplementor.cs | 11 +- .../Statements/ThrowImplementor.cs | 7 +- .../Statements/VariableImplementor.cs | 30 +- .../Statements/WhileImplementor.cs | 13 +- .../Core/ImplicitTypeCastTable.cs | 22 +- .../TypeOfInstructionPrototype.cs | 2 +- .../Core/OperatorOverloadingHelpers.cs | 32 +- .../InternalMacros/IntrinsicsMacros.cs | 7 +- .../InternalMacros/SyntacticMacros.cs | 130 ++++--- .../QualifiedNameDeconstructors.cs | 3 +- Source/Backlang.Driver/TypeDeducer.cs | 112 +++--- Source/Backlang.Driver/Utils.cs | 5 +- Source/Backlang.NET.Sdk/AssemblyResolver.cs | 78 ++-- .../Backlang.NET.Sdk/Backlang.NET.Sdk.csproj | 148 ++++---- .../Backlang.NET.Sdk/Backlang.NET.Sdk.nuspec | 50 +-- Source/Backlang.NET.Sdk/BuildTask.cs | 289 ++++++++------- Source/Backlang.NET.Sdk/Sdk/Sdk.props | 26 +- Source/Backlang.NET.Sdk/Sdk/Sdk.targets | 14 +- Source/Backlang.NET.Sdk/Sdk/Version.props | 4 +- .../build/Backlang.DesignTime.targets | 58 +-- .../build/Backlang.NET.Core.Sdk.targets | 346 +++++++++--------- .../build/Backlang.NET.Current.Sdk.targets | 30 +- .../build/Backlang.NET.Sdk.props | 22 +- .../build/Backlang.Version.props | 6 +- .../build/ProjectItemsSchema.xaml | 1 + .../Backlang.NET.Sdk.props | 16 +- .../Backlang.WasmBridge.csproj | 28 +- Source/Backlang.WasmBridge/Bridge.cs | 3 +- Source/Backlang.WasmBridge/main.mjs | 8 +- .../runtimeconfig.template.json | 28 +- .../Backlang.Backends.Bs2k/Addresses.cs | 2 +- .../Backlang.Backends.Bs2k.csproj | 48 +-- .../Backlang.Backends.Bs2k/Bs2kAssembly.cs | 3 +- .../Backlang.Backends.Bs2k/Constants.cs | 2 +- .../Plugins/Backlang.Backends.Bs2k/Emitter.cs | 48 +-- .../Backlang.Backends.Bs2k/Intrinsics.cs | 278 ++++++++++---- .../Backlang.Backends.Bs2k/NameMangler.cs | 2 +- .../Backlang.Backends.Bs2k/Register.cs | 2 +- .../StackLayoutGenerator.cs | 2 +- .../Backlang.ResourcePreprocessor.Mif.csproj | 46 +-- .../MifFormat/MifParser.cs | 18 +- .../MifFormat/Miftokenizer.cs | 18 +- .../MifFormat/TokenType.cs | 2 +- .../MifPreprocessor.cs | 22 +- .../Radix.cs | 2 +- .../AST/Declarations/EnumTests.cs | 3 +- .../AST/Declarations/FunctionTests.cs | 4 +- .../AST/Statements/VariableTests.cs | 103 +++--- Source/TestProject1/LexerTests.cs | 141 ++++--- Source/TestProject1/ParserTestBase.cs | 37 +- Source/TestProject1/TestProject1.csproj | 44 +-- Source/Version.props | 6 +- 218 files changed, 3137 insertions(+), 2779 deletions(-) delete mode 100644 .Net Core Templates/templatepack.csproj delete mode 100644 .Net Core Templates/templates/class/.template.config/template.json delete mode 100644 .Net Core Templates/templates/class/MyClass.back delete mode 100644 .Net Core Templates/templates/console/.template.config/template.json delete mode 100644 .Net Core Templates/templates/console/Program.back delete mode 100644 .Net Core Templates/templates/console/TestConsole.backproj delete mode 100644 .Net Core Templates/templates/library/.template.config/template.json delete mode 100644 .Net Core Templates/templates/library/MyLibrary.backproj delete mode 100644 .Net Core Templates/templates/library/test.back delete mode 100644 Backlang-npp.xml diff --git a/.Net Core Templates/templatepack.csproj b/.Net Core Templates/templatepack.csproj deleted file mode 100644 index 4fb1b50..0000000 --- a/.Net Core Templates/templatepack.csproj +++ /dev/null @@ -1,37 +0,0 @@ - - - - Template - 1.0.61 - Backlang.Templates - Backlang Templates - furesoft - Templates to use when creating an application with Backlang - dotnet-new;templates;backlang - - netstandard2.0 - - true - false - content - $(NoWarn);NU5128 - true - True - https://www.backlang.org - logo.png - https://github.com/Backlang-Org/Backlang - - - - - - - - - - True - \ - - - - \ No newline at end of file diff --git a/.Net Core Templates/templates/class/.template.config/template.json b/.Net Core Templates/templates/class/.template.config/template.json deleted file mode 100644 index 250e706..0000000 --- a/.Net Core Templates/templates/class/.template.config/template.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/template", - "author": "Me", - "classifications": [ "Common", "Code", "Backlang" ], - "identity": "Backlang.Class", - "name": "Backlang Class", - "shortName": "backclass", - "tags": { - "language": "Backlang", - "type": "item" - } -} \ No newline at end of file diff --git a/.Net Core Templates/templates/class/MyClass.back b/.Net Core Templates/templates/class/MyClass.back deleted file mode 100644 index e69de29..0000000 diff --git a/.Net Core Templates/templates/console/.template.config/template.json b/.Net Core Templates/templates/console/.template.config/template.json deleted file mode 100644 index 31a8518..0000000 --- a/.Net Core Templates/templates/console/.template.config/template.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/template", - "author": "Backseat-Comitee", - "classifications": [ "Common", "Console", "Backlang" ], - "identity": "Backlang.ConsoleProject", - "name": "Backlang console project", - "shortName": "backconsole", - "tags": { - "language": "Backlang", - "type": "project" - } -} \ No newline at end of file diff --git a/.Net Core Templates/templates/console/Program.back b/.Net Core Templates/templates/console/Program.back deleted file mode 100644 index 765b79c..0000000 --- a/.Net Core Templates/templates/console/Program.back +++ /dev/null @@ -1,4 +0,0 @@ -func main() -{ - print("Hello World"); -} diff --git a/.Net Core Templates/templates/console/TestConsole.backproj b/.Net Core Templates/templates/console/TestConsole.backproj deleted file mode 100644 index fa4bd1d..0000000 --- a/.Net Core Templates/templates/console/TestConsole.backproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - TestConsole - net7 - TestConsole - true - - - diff --git a/.Net Core Templates/templates/library/.template.config/template.json b/.Net Core Templates/templates/library/.template.config/template.json deleted file mode 100644 index 7b325bb..0000000 --- a/.Net Core Templates/templates/library/.template.config/template.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/template", - "author": "Backseat-Comitee", - "classifications": [ "Common", "Library", "Backlang" ], - "identity": "Backlang.LibraryProject", - "name": "Backlang library project", - "shortName": "backlib", - "tags": { - "language": "Backlang", - "type": "project" - } -} \ No newline at end of file diff --git a/.Net Core Templates/templates/library/MyLibrary.backproj b/.Net Core Templates/templates/library/MyLibrary.backproj deleted file mode 100644 index eb15f27..0000000 --- a/.Net Core Templates/templates/library/MyLibrary.backproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Library - TestConsole - net7 - TestConsole - true - - - \ No newline at end of file diff --git a/.Net Core Templates/templates/library/test.back b/.Net Core Templates/templates/library/test.back deleted file mode 100644 index 978b87f..0000000 --- a/.Net Core Templates/templates/library/test.back +++ /dev/null @@ -1,3 +0,0 @@ -class Test { - -} \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2c6f4b0..7ae08f0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,7 +33,7 @@ jobs: - name: Install .NET Core uses: actions/setup-dotnet@v2 with: - dotnet-version: 7.0.x + dotnet-version: 9.0.x include-prerelease: true - name: Build diff --git a/Backlang-npp.xml b/Backlang-npp.xml deleted file mode 100644 index 0fdafb4..0000000 --- a/Backlang-npp.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - - - 00// 01 02 03/* 04*/ - - - - - - - - - - { - - } - - - - - - - inline this get set prop const global do in unit continue return where type mut import module using as struct class interface let implement of for switch case break if else match with while static abstract override operator private public func enum union bitfield default sizeof and or - true false none error nameof default - # - - obj u8 u16 u32 i32 i8 i16 i32 i64 f32 f64 f16 fraction bool string char SELF - - - - 00" 01\ 02" 03' 04\ 05' 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Source/.editorconfig b/Source/.editorconfig index adb7bcb..e469e51 100644 --- a/Source/.editorconfig +++ b/Source/.editorconfig @@ -104,7 +104,7 @@ dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggest #Style - Modifier preferences #when this rule is set to a list of modifiers, prefer the specified ordering. -csharp_preferred_modifier_order = public,private,protected,internal,static,override,abstract,readonly,async:suggestion +csharp_preferred_modifier_order = public, private, protected, internal, static, override, abstract, readonly, async:suggestion #Style - qualification options @@ -136,31 +136,31 @@ dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case dotnet_naming_symbols.interface.applicable_kinds = interface dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = +dotnet_naming_symbols.interface.required_modifiers = dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = +dotnet_naming_symbols.types.required_modifiers = dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = +dotnet_naming_symbols.non_field_members.required_modifiers = # Benennungsstile dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = dotnet_naming_style.begins_with_i.capitalization = pascal_case -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = dotnet_naming_style.pascal_case.capitalization = pascal_case -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = dotnet_naming_style.pascal_case.capitalization = pascal_case csharp_style_expression_bodied_operators = false:silent csharp_style_expression_bodied_indexers = true:silent @@ -190,31 +190,31 @@ dotnet_naming_rule.nicht_feldmember_should_be_pascal_schreibweise.style = pascal dotnet_naming_symbols.interface.applicable_kinds = interface dotnet_naming_symbols.interface.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected -dotnet_naming_symbols.interface.required_modifiers = +dotnet_naming_symbols.interface.required_modifiers = dotnet_naming_symbols.typen.applicable_kinds = class, struct, interface, enum dotnet_naming_symbols.typen.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected -dotnet_naming_symbols.typen.required_modifiers = +dotnet_naming_symbols.typen.required_modifiers = dotnet_naming_symbols.nicht_feldmember.applicable_kinds = property, event, method dotnet_naming_symbols.nicht_feldmember.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected -dotnet_naming_symbols.nicht_feldmember.required_modifiers = +dotnet_naming_symbols.nicht_feldmember.required_modifiers = # Benennungsstile dotnet_naming_style.beginnt_mit_i.required_prefix = I -dotnet_naming_style.beginnt_mit_i.required_suffix = -dotnet_naming_style.beginnt_mit_i.word_separator = +dotnet_naming_style.beginnt_mit_i.required_suffix = +dotnet_naming_style.beginnt_mit_i.word_separator = dotnet_naming_style.beginnt_mit_i.capitalization = pascal_case -dotnet_naming_style.pascal_schreibweise.required_prefix = -dotnet_naming_style.pascal_schreibweise.required_suffix = -dotnet_naming_style.pascal_schreibweise.word_separator = +dotnet_naming_style.pascal_schreibweise.required_prefix = +dotnet_naming_style.pascal_schreibweise.required_suffix = +dotnet_naming_style.pascal_schreibweise.word_separator = dotnet_naming_style.pascal_schreibweise.capitalization = pascal_case -dotnet_naming_style.pascal_schreibweise.required_prefix = -dotnet_naming_style.pascal_schreibweise.required_suffix = -dotnet_naming_style.pascal_schreibweise.word_separator = +dotnet_naming_style.pascal_schreibweise.required_prefix = +dotnet_naming_style.pascal_schreibweise.required_suffix = +dotnet_naming_style.pascal_schreibweise.word_separator = dotnet_naming_style.pascal_schreibweise.capitalization = pascal_case [*.{cs,vb}] @@ -293,13 +293,13 @@ dotnet_diagnostic.CA1309.severity = suggestion dotnet_diagnostic.CA1507.severity = warning [*.{cs,vb}] -dotnet_naming_rule.private_members_with_underscore.symbols = private_fields +dotnet_naming_rule.private_members_with_underscore.symbols = private_fields dotnet_naming_rule.private_members_with_underscore.style = prefix_underscore dotnet_naming_rule.private_members_with_underscore.severity = suggestion -dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_kinds = field dotnet_naming_symbols.private_fields.applicable_accessibilities = private -dotnet_naming_symbols.private_fields.required_modifiers = readonly +dotnet_naming_symbols.private_fields.required_modifiers = readonly dotnet_naming_style.prefix_underscore.capitalization = camel_case dotnet_naming_style.prefix_underscore.required_prefix = _ diff --git a/Source/Backlang-Compiler/Backlang-Compiler.csproj b/Source/Backlang-Compiler/Backlang-Compiler.csproj index 22563d1..1af673d 100644 --- a/Source/Backlang-Compiler/Backlang-Compiler.csproj +++ b/Source/Backlang-Compiler/Backlang-Compiler.csproj @@ -1,36 +1,36 @@  - - Exe - net9.0 - Backlang_Compiler - enable - enable - preview - True - + + Exe + net9.0 + Backlang_Compiler + enable + enable + preview + True + - - - - - - - - - + + + + + + + + + - - - - + + + + - - - Always - - - + + + Always + - + + + diff --git a/Source/Backlang-Compiler/Program.cs b/Source/Backlang-Compiler/Program.cs index 8498b5d..6d09220 100644 --- a/Source/Backlang-Compiler/Program.cs +++ b/Source/Backlang-Compiler/Program.cs @@ -9,13 +9,10 @@ public static class Program public static void Main(string[] args) { Parser.Default.ParseArguments(args) - .WithParsed(options => { - var context = new CompilerContext - { - Options = options - }; + .WithParsed(options => { + var context = new CompilerContext { Options = options }; - CompilerDriver.Compile(context); - }); + CompilerDriver.Compile(context); + }); } } \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Backlang.Codeanalysis.csproj b/Source/Backlang.Codeanalysis/Backlang.Codeanalysis.csproj index ddca494..5470edc 100644 --- a/Source/Backlang.Codeanalysis/Backlang.Codeanalysis.csproj +++ b/Source/Backlang.Codeanalysis/Backlang.Codeanalysis.csproj @@ -1,51 +1,49 @@  - - net9.0 - enable - preview - True - True - $(Version) - $(Version) - The Parser For Backlang - logo.png - https://www.backlang.org - https://github.com/Backlang-Org/Backlang - backlang,dotnet - True - - - - - - - - True - \ - - - - - - - - - - - - True - True - Resources.resx - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - - - - + + net9.0 + enable + preview + True + True + $(Version) + $(Version) + The Parser For Backlang + logo.png + https://www.backlang.org + https://github.com/Backlang-Org/Backlang + backlang,dotnet + True + + + + + + True + \ + + + + + + + + + + + + True + True + Resources.resx + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + diff --git a/Source/Backlang.Codeanalysis/Core/Attributes/BinaryOperatorInfoAttribute.cs b/Source/Backlang.Codeanalysis/Core/Attributes/BinaryOperatorInfoAttribute.cs index 0e51f25..d5f94dc 100644 --- a/Source/Backlang.Codeanalysis/Core/Attributes/BinaryOperatorInfoAttribute.cs +++ b/Source/Backlang.Codeanalysis/Core/Attributes/BinaryOperatorInfoAttribute.cs @@ -5,7 +5,7 @@ namespace Backlang.Codeanalysis.Core.Attributes; [AttributeUsage(AttributeTargets.Field, AllowMultiple = true)] public sealed class BinaryOperatorInfoAttribute : OperatorInfoAttribute { - public BinaryOperatorInfoAttribute(int precedence) : base(precedence, isUnary: false, isPostUnary: false) + public BinaryOperatorInfoAttribute(int precedence) : base(precedence, false, false) { } diff --git a/Source/Backlang.Codeanalysis/Core/Attributes/KeywordAttribute.cs b/Source/Backlang.Codeanalysis/Core/Attributes/KeywordAttribute.cs index 670b173..e328055 100644 --- a/Source/Backlang.Codeanalysis/Core/Attributes/KeywordAttribute.cs +++ b/Source/Backlang.Codeanalysis/Core/Attributes/KeywordAttribute.cs @@ -9,4 +9,4 @@ public KeywordAttribute(string keyword) } public string Keyword { get; set; } -} +} \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Core/Attributes/LexemeAttribute.cs b/Source/Backlang.Codeanalysis/Core/Attributes/LexemeAttribute.cs index 6e902db..5eccc9d 100644 --- a/Source/Backlang.Codeanalysis/Core/Attributes/LexemeAttribute.cs +++ b/Source/Backlang.Codeanalysis/Core/Attributes/LexemeAttribute.cs @@ -9,4 +9,4 @@ public LexemeAttribute(string lexeleme) } public string Lexeme { get; set; } -} +} \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Core/Attributes/OperatorInfoAttribute.cs b/Source/Backlang.Codeanalysis/Core/Attributes/OperatorInfoAttribute.cs index 518ebc3..6e39a7d 100644 --- a/Source/Backlang.Codeanalysis/Core/Attributes/OperatorInfoAttribute.cs +++ b/Source/Backlang.Codeanalysis/Core/Attributes/OperatorInfoAttribute.cs @@ -13,4 +13,4 @@ public OperatorInfoAttribute(int precedence, bool isUnary, bool isPostUnary) public bool IsPostUnary { get; set; } public bool IsUnary { get; set; } public int Precedence { get; set; } -} +} \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Core/Attributes/PostUnaryOperatorInfoAttribute.cs b/Source/Backlang.Codeanalysis/Core/Attributes/PostUnaryOperatorInfoAttribute.cs index 6157658..9c0c054 100644 --- a/Source/Backlang.Codeanalysis/Core/Attributes/PostUnaryOperatorInfoAttribute.cs +++ b/Source/Backlang.Codeanalysis/Core/Attributes/PostUnaryOperatorInfoAttribute.cs @@ -5,11 +5,11 @@ namespace Backlang.Codeanalysis.Core.Attributes; [AttributeUsage(AttributeTargets.Field, AllowMultiple = true)] public sealed class PostUnaryOperatorInfoAttribute : OperatorInfoAttribute { - public PostUnaryOperatorInfoAttribute(int precedence) : base(precedence, isUnary: true, isPostUnary: true) + public PostUnaryOperatorInfoAttribute(int precedence) : base(precedence, true, true) { } public PostUnaryOperatorInfoAttribute(UnaryOpPrecedences precedence) : this((int)precedence) { } -} +} \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Core/Attributes/PreUnaryOperatorInfoAttribute.cs b/Source/Backlang.Codeanalysis/Core/Attributes/PreUnaryOperatorInfoAttribute.cs index 7878083..26a95cc 100644 --- a/Source/Backlang.Codeanalysis/Core/Attributes/PreUnaryOperatorInfoAttribute.cs +++ b/Source/Backlang.Codeanalysis/Core/Attributes/PreUnaryOperatorInfoAttribute.cs @@ -5,11 +5,11 @@ namespace Backlang.Codeanalysis.Core.Attributes; [AttributeUsage(AttributeTargets.Field, AllowMultiple = true)] public sealed class PreUnaryOperatorInfoAttribute : OperatorInfoAttribute { - public PreUnaryOperatorInfoAttribute(int precedence) : base(precedence, isUnary: true, isPostUnary: false) + public PreUnaryOperatorInfoAttribute(int precedence) : base(precedence, true, false) { } public PreUnaryOperatorInfoAttribute(UnaryOpPrecedences precedence) : this((int)precedence) { } -} +} \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Core/BaseLexer.cs b/Source/Backlang.Codeanalysis/Core/BaseLexer.cs index 9348e31..ad4681b 100644 --- a/Source/Backlang.Codeanalysis/Core/BaseLexer.cs +++ b/Source/Backlang.Codeanalysis/Core/BaseLexer.cs @@ -5,12 +5,11 @@ namespace Backlang.Codeanalysis.Core; public abstract class BaseLexer { - public List Messages = new(); - protected int _column = 1; protected SourceFile _document; protected int _line = 1; - protected int _position = 0; + protected int _position; + public List Messages = new(); public List Tokenize(SourceFile document) { diff --git a/Source/Backlang.Codeanalysis/Core/ErrorID.cs b/Source/Backlang.Codeanalysis/Core/ErrorID.cs index f38e930..1c164e2 100644 --- a/Source/Backlang.Codeanalysis/Core/ErrorID.cs +++ b/Source/Backlang.Codeanalysis/Core/ErrorID.cs @@ -1,6 +1,6 @@ namespace Backlang.Codeanalysis.Core; -public enum ErrorID : int +public enum ErrorID { UnexpecedType = 0001, InvalidModifierCombination = 0002, @@ -33,5 +33,5 @@ public enum ErrorID : int TargetNotFound = 0029, NotDefined = 0030, CannotDeduceType = 31, - DeducingTypeNotPossible = 32, + DeducingTypeNotPossible = 32 } \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Core/LevensteinDistance.cs b/Source/Backlang.Codeanalysis/Core/LevensteinDistance.cs index 6f76647..c0eb191 100644 --- a/Source/Backlang.Codeanalysis/Core/LevensteinDistance.cs +++ b/Source/Backlang.Codeanalysis/Core/LevensteinDistance.cs @@ -38,11 +38,12 @@ public static int Calculate(string source, string target) { var cost = target[j - 1] == source[i - 1] ? 0 : 1; distance[currentRow, j] = Math.Min(Math.Min( - distance[previousRow, j] + 1, - distance[currentRow, j - 1] + 1), - distance[previousRow, j - 1] + cost); + distance[previousRow, j] + 1, + distance[currentRow, j - 1] + 1), + distance[previousRow, j - 1] + cost); } } + return distance[currentRow, m]; } diff --git a/Source/Backlang.Codeanalysis/Core/LocalizableString.cs b/Source/Backlang.Codeanalysis/Core/LocalizableString.cs index 23261e2..3f428a4 100644 --- a/Source/Backlang.Codeanalysis/Core/LocalizableString.cs +++ b/Source/Backlang.Codeanalysis/Core/LocalizableString.cs @@ -9,7 +9,8 @@ public readonly struct LocalizableString public readonly string[] Arguments; public readonly string FallbackValue; - private static readonly ResourceManager _resourceManager = new("Backlang.Codeanalysis.Properties.Resources", typeof(Resources).Assembly); + private static readonly ResourceManager _resourceManager = + new("Backlang.Codeanalysis.Properties.Resources", typeof(Resources).Assembly); public LocalizableString(ErrorID errorID, params string[] arguments) { @@ -38,16 +39,16 @@ public static implicit operator string(LocalizableString lstr) var resourceID = $"BL({(int)lstr.ErrorID:D4})"; - return string.Format(resourceID + ": " + _resourceManager.GetString(resourceID), args: lstr.Arguments); + return string.Format(resourceID + ": " + _resourceManager.GetString(resourceID), lstr.Arguments); } public static implicit operator LocalizableString(ErrorID id) { - return new(id); + return new LocalizableString(id); } public static implicit operator LocalizableString(string message) { - return new(message); + return new LocalizableString(message); } } \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Annotation.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Annotation.cs index 2c5dbd9..9bdf5fa 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Annotation.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Annotation.cs @@ -15,12 +15,14 @@ public static LNode Parse(TokenIterator iterator, Parser parser) public static bool TryParse(Parser parser, out LNodeList node) { var annotations = new LNodeList(); - var isAnnotation = () => parser.Iterator.IsMatch(TokenType.At) && parser.Iterator.Peek(1).Type == TokenType.Identifier; + var isAnnotation = () => + parser.Iterator.IsMatch(TokenType.At) && parser.Iterator.Peek(1).Type == TokenType.Identifier; while (isAnnotation()) { annotations.Add(Parse(parser.Iterator, parser)); } + node = annotations; return annotations.Count > 0; diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/CompilationUnit.cs b/Source/Backlang.Codeanalysis/Parsing/AST/CompilationUnit.cs index 38cadf4..6c4a32d 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/CompilationUnit.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/CompilationUnit.cs @@ -6,7 +6,7 @@ public sealed class CompilationUnit { public LNodeList Body { get; set; } = new(); public SourceFile Document { get; internal set; } - public List Messages { get; set; } = new List(); + public List Messages { get; set; } = new(); public static CompilationUnit FromFile(string filename) { diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/BitFieldMemberDeclaration.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/BitFieldMemberDeclaration.cs index 6a3e77b..7d25448 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/BitFieldMemberDeclaration.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/BitFieldMemberDeclaration.cs @@ -1,4 +1,5 @@ -using Loyc.Syntax; +using Backlang.Codeanalysis.Core; +using Loyc.Syntax; namespace Backlang.Codeanalysis.Parsing.AST.Declarations; @@ -24,7 +25,7 @@ public static LNode Parse(TokenIterator iterator, Parser parser) if (!value[0].HasValue) { - parser.AddError(Core.ErrorID.BitfieldNotLiteral, value.Range); + parser.AddError(ErrorID.BitfieldNotLiteral, value.Range); } return SyntaxTree.Factory.Tuple(SyntaxTree.Factory.Id(nameToken.Text).WithRange(nameToken), value); diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/EnumMemberDeclaration.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/EnumMemberDeclaration.cs index f93ddcb..2a458b7 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/EnumMemberDeclaration.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/EnumMemberDeclaration.cs @@ -18,4 +18,4 @@ public static LNode Parse(TokenIterator iterator, Parser parser) return SyntaxTree.Factory.Var(LNode.Missing, LNode.Id(memberNameToken.Text), value).PlusAttrs(annotations); } -} +} \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/ImplementationDeclaration.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/ImplementationDeclaration.cs index 557f651..8814246 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/ImplementationDeclaration.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/ImplementationDeclaration.cs @@ -45,7 +45,8 @@ public static LNode Parse(TokenIterator iterator, Parser parser) _ = Annotation.TryParse(parser, out var annotations); _ = Modifier.TryParse(parser, out var modifiers); - body.Add(parser.InvokeParsePoint(parser.DeclarationParsePoints).PlusAttrs(annotations).PlusAttrs(modifiers)); + body.Add(parser.InvokeParsePoint(parser.DeclarationParsePoints).PlusAttrs(annotations) + .PlusAttrs(modifiers)); } iterator.Match(TokenType.CloseCurly); diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/MacroBlockDeclaration.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/MacroBlockDeclaration.cs index a0c2d10..dcfb17a 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/MacroBlockDeclaration.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/MacroBlockDeclaration.cs @@ -39,14 +39,13 @@ public static LNode Parse(TokenIterator iterator, Parser parser) return SyntaxTree.Factory.Call(nameExpression, arguments).SetStyle(NodeStyle.StatementBlock) .SetStyle(NodeStyle.Special).WithRange(nameExpression.Range.StartIndex, iterator.Prev.End); } - else - { - parser.Iterator.Match(TokenType.Semicolon); - } + + parser.Iterator.Match(TokenType.Semicolon); return LNode.Call(nameExpression, arguments); } - else if (iterator.Current.Type == TokenType.OpenCurly) + + if (iterator.Current.Type == TokenType.OpenCurly) { iterator.NextToken(); diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/ParameterDeclaration.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/ParameterDeclaration.cs index 4d55cd9..87440f2 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/ParameterDeclaration.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/ParameterDeclaration.cs @@ -13,7 +13,8 @@ public static LNode Parse(TokenIterator iterator, Parser parser) var name = iterator.Match(TokenType.Identifier); var assertNotNull = false; - if(iterator.ConsumeIfMatch(TokenType.Exclamation)) { + if (iterator.ConsumeIfMatch(TokenType.Exclamation)) + { assertNotNull = true; } @@ -30,8 +31,9 @@ public static LNode Parse(TokenIterator iterator, Parser parser) defaultValue = Expression.Parse(parser); } - if(assertNotNull) { - annotations = annotations.Add(LNode.Id(Symbols.AssertNonNull)); + if (assertNotNull) + { + annotations = annotations.Add(LNode.Id(Symbols.AssertNonNull)); } return SyntaxTree.Factory.Var(type, name.Text, defaultValue).PlusAttrs(annotations) diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/TypeMemberDeclaration.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/TypeMemberDeclaration.cs index e20d61f..8976e7a 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/TypeMemberDeclaration.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Declarations/TypeMemberDeclaration.cs @@ -1,4 +1,5 @@ -using Backlang.Codeanalysis.Parsing.AST.Statements; +using Backlang.Codeanalysis.Core; +using Backlang.Codeanalysis.Parsing.AST.Statements; using Loyc.Syntax; namespace Backlang.Codeanalysis.Parsing.AST.Declarations; @@ -28,7 +29,7 @@ public static LNode Parse(TokenIterator iterator, Parser parser) { var range = new SourceRange(parser.Document, iterator.Current.Start, iterator.Current.Text.Length); - parser.AddError(new(Core.ErrorID.UnexpecedTypeMember, iterator.Current.Text), range); + parser.AddError(new LocalizableString(ErrorID.UnexpecedTypeMember, iterator.Current.Text), range); iterator.NextToken(); } @@ -85,6 +86,7 @@ public static LNode ParseProperty(TokenIterator iterator, Parser parser) { args.Add(Statement.ParseBlock(parser)); } + getter = LNode.Call(CodeSymbols.get, args).WithAttrs(modifier); needModifier = true; } @@ -106,6 +108,7 @@ public static LNode ParseProperty(TokenIterator iterator, Parser parser) { args.Add(Statement.ParseBlock(parser)); } + setter = LNode.Call(CodeSymbols.set, args).WithAttrs(modifier); } else if (iterator.IsMatch(TokenType.Init)) @@ -120,6 +123,7 @@ public static LNode ParseProperty(TokenIterator iterator, Parser parser) { args.Add(Statement.ParseBlock(parser)); } + setter = LNode.Call(Symbols.Init, args).WithAttrs(modifier); } diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/DocComment.cs b/Source/Backlang.Codeanalysis/Parsing/AST/DocComment.cs index 3896ed9..0c290c7 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/DocComment.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/DocComment.cs @@ -23,4 +23,4 @@ public static bool TryParse(Parser parser, out LNode node) return result; } -} +} \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/InitializerListExpression.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/InitializerListExpression.cs index 27798f2..72e5f5d 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/InitializerListExpression.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/InitializerListExpression.cs @@ -10,7 +10,7 @@ public static LNode Parse(TokenIterator iterator, Parser parser) do { - if (iterator.Current.Type == (TokenType.CloseSquare)) + if (iterator.Current.Type == TokenType.CloseSquare) { break; } @@ -21,7 +21,7 @@ public static LNode Parse(TokenIterator iterator, Parser parser) { iterator.Match(TokenType.Comma); } - } while (iterator.Current.Type != (TokenType.CloseSquare)); + } while (iterator.Current.Type != TokenType.CloseSquare); iterator.Match(TokenType.CloseSquare); diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/Match/MatchExpression.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/Match/MatchExpression.cs index 2407666..3373de2 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/Match/MatchExpression.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/Match/MatchExpression.cs @@ -5,11 +5,11 @@ namespace Backlang.Codeanalysis.Parsing.AST.Expressions.Match; public sealed class MatchExpression : IParsePoint { /* - * match a with - 12 => 13, - i32 num => num + 2, - _ => 0 + 4; - */ + * match a with + 12 => 13, + i32 num => num + 2, + _ => 0 + 4; + */ public static LNode Parse(TokenIterator iterator, Parser parser) { @@ -27,10 +27,8 @@ public static LNode Parse(TokenIterator iterator, Parser parser) { break; } - else - { - iterator.Match(TokenType.Comma); - } + + iterator.Match(TokenType.Comma); } return SyntaxTree.Factory.Call(LNode.Id(Symbols.Match), matchArgument).WithAttrs(conditions); diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/Match/MatchRule.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/Match/MatchRule.cs index d3aabc4..0333c9d 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/Match/MatchRule.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/Match/MatchRule.cs @@ -17,7 +17,8 @@ public static LNode Parse(TokenIterator iterator, Parser parser) return SyntaxTree.Factory.Tuple(LNode.Literal((Symbol)"_"), result); } - else if (iterator.Peek(1).Type == TokenType.GoesTo) //12 => 13 + + if (iterator.Peek(1).Type == TokenType.GoesTo) //12 => 13 { var matcher = Expression.Parse(parser); @@ -27,7 +28,8 @@ public static LNode Parse(TokenIterator iterator, Parser parser) return SyntaxTree.Factory.Tuple(matcher, result); } - else if (iterator.Current.IsOperator()) // > 12 => false + + if (iterator.Current.IsOperator()) // > 12 => false { var operatorToken = iterator.Current; iterator.NextToken(); @@ -40,7 +42,9 @@ public static LNode Parse(TokenIterator iterator, Parser parser) return SyntaxTree.Factory.Tuple(SyntaxTree.Unary((Symbol)operatorToken.Text, condition), result); } - else if (iterator.Current.Type == TokenType.Identifier && iterator.Peek(1).Type == TokenType.Identifier) //i32 num => num + 2 + + if (iterator.Current.Type == TokenType.Identifier && + iterator.Peek(1).Type == TokenType.Identifier) //i32 num => num + 2 { var type = TypeLiteral.Parse(iterator, parser); var name = iterator.NextToken().Text; @@ -51,7 +55,8 @@ public static LNode Parse(TokenIterator iterator, Parser parser) return SyntaxTree.Factory.Tuple(SyntaxTree.Factory.Var(type, name), result); } - else if (iterator.Current.Type == TokenType.Identifier) //i32 => 32 + + if (iterator.Current.Type == TokenType.Identifier) //i32 => 32 { var type = TypeLiteral.Parse(iterator, parser); diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/NameExpression.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/NameExpression.cs index cb3b9ae..002c0e8 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/NameExpression.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Expressions/NameExpression.cs @@ -13,9 +13,11 @@ public static LNode Parse(TokenIterator iterator, Parser parser) { iterator.NextToken(); - return SyntaxTree.ArrayInstantiation(nameExpression, Expression.ParseList(parser, TokenType.CloseSquare)).WithRange(nameToken, iterator.Prev); + return SyntaxTree.ArrayInstantiation(nameExpression, Expression.ParseList(parser, TokenType.CloseSquare)) + .WithRange(nameToken, iterator.Prev); } - else if (iterator.Current.Type == TokenType.OpenParen) + + if (iterator.Current.Type == TokenType.OpenParen) { iterator.NextToken(); diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Modifier.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Modifier.cs index 57fd4c3..297cecb 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Modifier.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Modifier.cs @@ -7,17 +7,19 @@ namespace Backlang.Codeanalysis.Parsing.AST; public sealed class Modifier { - private static readonly ImmutableDictionary _possibleModifiers = new Dictionary() { - { TokenType.Static, CodeSymbols.Static }, - { TokenType.Public, CodeSymbols.Public }, - { TokenType.Protected, CodeSymbols.Protected }, - { TokenType.Private, CodeSymbols.Private }, - { TokenType.Internal, CodeSymbols.Internal }, - { TokenType.Operator, CodeSymbols.Operator }, - { TokenType.Abstract, CodeSymbols.Abstract }, - { TokenType.Override, CodeSymbols.Override }, - { TokenType.Extern, CodeSymbols.Extern }, - }.ToImmutableDictionary(); + private static readonly ImmutableDictionary _possibleModifiers = + new Dictionary + { + { TokenType.Static, CodeSymbols.Static }, + { TokenType.Public, CodeSymbols.Public }, + { TokenType.Protected, CodeSymbols.Protected }, + { TokenType.Private, CodeSymbols.Private }, + { TokenType.Internal, CodeSymbols.Internal }, + { TokenType.Operator, CodeSymbols.Operator }, + { TokenType.Abstract, CodeSymbols.Abstract }, + { TokenType.Override, CodeSymbols.Override }, + { TokenType.Extern, CodeSymbols.Extern } + }.ToImmutableDictionary(); public static bool TryParse(Parser parser, out LNodeList node) { @@ -28,12 +30,14 @@ public static bool TryParse(Parser parser, out LNodeList node) var modifier = ParseSingle(parser.Iterator); if (modifiers.Contains(modifier)) { - parser.AddError(new(ErrorID.DuplicateModifier, modifier.Name.Name), modifier.Range); + parser.AddError(new LocalizableString(ErrorID.DuplicateModifier, modifier.Name.Name), modifier.Range); continue; } + modifiers.Add(modifier); } + node = modifiers; return modifiers.Count > 0; diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Signature.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Signature.cs index a020ff2..87a03ed 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Signature.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Signature.cs @@ -1,3 +1,4 @@ +using Backlang.Codeanalysis.Core; using Backlang.Codeanalysis.Parsing.AST.Declarations; using Loyc.Syntax; @@ -13,7 +14,7 @@ public static LNode Parse(Parser parser) { var range = new SourceRange(parser.Document, iterator.Current.Start, iterator.Current.Text.Length); - parser.AddError(new(Core.ErrorID.ExpectedTypeLiteral, iterator.Current.Text), range); + parser.AddError(new LocalizableString(ErrorID.ExpectedTypeLiteral, iterator.Current.Text), range); } LNode returnType = LNode.Missing; diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Statements/MacroBlockStatement.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Statements/MacroBlockStatement.cs index 7bd47a5..1c731e8 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Statements/MacroBlockStatement.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Statements/MacroBlockStatement.cs @@ -25,14 +25,13 @@ public static LNode Parse(TokenIterator iterator, Parser parser) return SyntaxTree.Factory.Call(nameExpression, arguments).SetStyle(NodeStyle.StatementBlock) .WithRange(nameToken, iterator.Prev); } - else - { - iterator.Match(TokenType.Semicolon); - return SyntaxTree.Factory.Call(nameExpression, arguments).WithRange(nameToken, iterator.Prev); - } + iterator.Match(TokenType.Semicolon); + + return SyntaxTree.Factory.Call(nameExpression, arguments).WithRange(nameToken, iterator.Prev); } - else if (iterator.Current.Type == TokenType.OpenCurly) + + if (iterator.Current.Type == TokenType.OpenCurly) { //custom code block without arguments var body = Statement.ParseBlock(parser); @@ -41,11 +40,9 @@ public static LNode Parse(TokenIterator iterator, Parser parser) return SyntaxTree.Factory.Call(nameExpression, arguments).SetStyle(NodeStyle.StatementBlock) .WithRange(nameToken, iterator.Prev); } - else - { - iterator.Position = currPos; - return ExpressionStatement.Parse(iterator, parser); - } + iterator.Position = currPos; + + return ExpressionStatement.Parse(iterator, parser); } } \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Statements/Statement.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Statements/Statement.cs index 41f00aa..9ca84a7 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Statements/Statement.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Statements/Statement.cs @@ -26,11 +26,9 @@ public static LNode ParseOneOrBlock(Parser parser) { return ParseBlock(parser); } - else - { - var node = parser.InvokeStatementParsePoint(); - return SyntaxTree.Factory.Braces(node).WithStyle(NodeStyle.StatementBlock).WithRange(node.Range); - } + var node = parser.InvokeStatementParsePoint(); + + return SyntaxTree.Factory.Braces(node).WithStyle(NodeStyle.StatementBlock).WithRange(node.Range); } } \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Statements/SwitchStatement.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Statements/SwitchStatement.cs index 0fbd275..1d61634 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Statements/SwitchStatement.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Statements/SwitchStatement.cs @@ -1,4 +1,5 @@ -using Loyc; +using Backlang.Codeanalysis.Core; +using Loyc; using Loyc.Syntax; namespace Backlang.Codeanalysis.Parsing.AST.Statements; @@ -55,7 +56,7 @@ public static LNode Parse(TokenIterator iterator, Parser parser) { var range = new SourceRange(parser.Document, iterator.Current.Start, iterator.Current.Text.Length); - parser.AddError(new(Core.ErrorID.UnknownSwitchOption), range); + parser.AddError(new LocalizableString(ErrorID.UnknownSwitchOption), range); return LNode.Missing; } } @@ -136,12 +137,14 @@ private static LNode ParseWhen(Parser parser, bool autoBreak) // with element function if (!parser.Iterator.IsMatch(TokenType.Identifier)) { - var range = new SourceRange(parser.Document, parser.Iterator.Current.Start, parser.Iterator.Current.Text.Length); + var range = new SourceRange(parser.Document, parser.Iterator.Current.Start, + parser.Iterator.Current.Text.Length); - parser.AddError(new(Core.ErrorID.ExpectedIdentifier, parser.Iterator.Current.Text), range); + parser.AddError(new LocalizableString(ErrorID.ExpectedIdentifier, parser.Iterator.Current.Text), range); return LNode.Missing; } + var name = LNode.Id(parser.Iterator.Current.Text); parser.Iterator.Match(TokenType.Identifier); parser.Iterator.Match(TokenType.OpenParen); diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Statements/TryStatement.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Statements/TryStatement.cs index 0081b8a..b56f6df 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Statements/TryStatement.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Statements/TryStatement.cs @@ -1,4 +1,5 @@ -using Loyc.Syntax; +using Backlang.Codeanalysis.Core; +using Loyc.Syntax; namespace Backlang.Codeanalysis.Parsing.AST.Statements; @@ -14,7 +15,7 @@ public static LNode Parse(TokenIterator iterator, Parser parser) { var range = new SourceRange(parser.Document, iterator.Current.Start, iterator.Current.Text.Length); - parser.AddError(new(Core.ErrorID.NoCatchBlock), range); + parser.AddError(new LocalizableString(ErrorID.NoCatchBlock), range); } while (iterator.Current.Type == TokenType.Catch) @@ -31,7 +32,8 @@ public static LNode Parse(TokenIterator iterator, Parser parser) finallly = Statement.ParseOneOrBlock(parser); } - return SyntaxTree.Try(body, SyntaxTree.Factory.AltList(catches), finallly).WithRange(keywordToken, iterator.Prev); + return SyntaxTree.Try(body, SyntaxTree.Factory.AltList(catches), finallly) + .WithRange(keywordToken, iterator.Prev); } private static LNode ParseCatch(Parser parser) diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/Statements/VariableStatement.cs b/Source/Backlang.Codeanalysis/Parsing/AST/Statements/VariableStatement.cs index 3cf4775..fbafac4 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/Statements/VariableStatement.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/Statements/VariableStatement.cs @@ -8,8 +8,8 @@ public static LNode Parse(TokenIterator iterator, Parser parser) { var keywordToken = iterator.Prev; - bool isMutable = false; - LNode type = SyntaxTree.Type("", LNode.List()); + var isMutable = false; + var type = SyntaxTree.Type("", LNode.List()); LNode value = LNode.Missing; Token mutableToken = null; diff --git a/Source/Backlang.Codeanalysis/Parsing/AST/TypeLiteral.cs b/Source/Backlang.Codeanalysis/Parsing/AST/TypeLiteral.cs index fa63d02..8c1ba12 100644 --- a/Source/Backlang.Codeanalysis/Parsing/AST/TypeLiteral.cs +++ b/Source/Backlang.Codeanalysis/Parsing/AST/TypeLiteral.cs @@ -15,7 +15,7 @@ public static LNode Parse(TokenIterator iterator, Parser parser) var typename = iterator.Match(TokenType.Identifier).Text; var args = new LNodeList(); - typeNode = SyntaxTree.Type(typename, new()).WithRange(typeToken); + typeNode = SyntaxTree.Type(typename, new LNodeList()).WithRange(typeToken); if (iterator.IsMatch(TokenType.Star)) { @@ -23,13 +23,15 @@ public static LNode Parse(TokenIterator iterator, Parser parser) typeNode = SyntaxTree.Pointer(typeNode).WithRange(typeToken, iterator.Prev); } + if (iterator.IsMatch(TokenType.Ampersand)) { iterator.NextToken(); typeNode = SyntaxTree.RefType(typeNode).WithRange(typeToken, iterator.Prev); } - else if(iterator.IsMatch(TokenType.Questionmark)) { + else if (iterator.IsMatch(TokenType.Questionmark)) + { iterator.NextToken(); typeNode = SyntaxTree.NullableType(typeNode).WithRange(typeToken, iterator.Prev); @@ -54,7 +56,8 @@ public static LNode Parse(TokenIterator iterator, Parser parser) } else { - parser.AddError(new(ErrorID.UnexpecedType, TokenIterator.GetTokenRepresentation(iterator.Current.Type))); //ToDo: Add Range + parser.AddError(new LocalizableString(ErrorID.UnexpecedType, + TokenIterator.GetTokenRepresentation(iterator.Current.Type))); //ToDo: Add Range typeNode = LNode.Missing; iterator.NextToken(); @@ -85,7 +88,7 @@ private static LNode ParseFunctionOrTupleType(TokenIterator iterator, Parser par var parameters = new LNodeList(); while (parser.Iterator.Current.Type != TokenType.CloseParen) { - parameters.Add(TypeLiteral.Parse(iterator, parser)); + parameters.Add(Parse(iterator, parser)); if (parser.Iterator.Current.Type != TokenType.CloseParen) { @@ -102,7 +105,8 @@ private static LNode ParseFunctionOrTupleType(TokenIterator iterator, Parser par var returnType = Parse(iterator, parser); typeNode = SyntaxTree.Factory.Call(CodeSymbols.Fn, - LNode.List(returnType, LNode.Missing, LNode.Call(CodeSymbols.AltList, parameters))).WithRange(typeToken, iterator.Prev); + LNode.List(returnType, LNode.Missing, LNode.Call(CodeSymbols.AltList, parameters))) + .WithRange(typeToken, iterator.Prev); } else { @@ -112,7 +116,8 @@ private static LNode ParseFunctionOrTupleType(TokenIterator iterator, Parser par return typeNode; } - private static LNode ParseGenericType(TokenIterator iterator, Parser parser, Token typeToken, string typename, LNodeList args) + private static LNode ParseGenericType(TokenIterator iterator, Parser parser, Token typeToken, string typename, + LNodeList args) { LNode typeNode; iterator.NextToken(); diff --git a/Source/Backlang.Codeanalysis/Parsing/Expression.cs b/Source/Backlang.Codeanalysis/Parsing/Expression.cs index 3203e11..3be40ef 100644 --- a/Source/Backlang.Codeanalysis/Parsing/Expression.cs +++ b/Source/Backlang.Codeanalysis/Parsing/Expression.cs @@ -44,7 +44,10 @@ static Expression() } } - public static int GetBinaryOperatorPrecedence(TokenType kind) => BinaryOperators.GetValueOrDefault(kind); + public static int GetBinaryOperatorPrecedence(TokenType kind) + { + return BinaryOperators.GetValueOrDefault(kind); + } public static LNode Parse(Parser parser, ParsePoints parsePoints = null, int parentPrecedence = 0) { @@ -59,7 +62,8 @@ public static LNode Parse(Parser parser, ParsePoints parsePoints = null, int par var operand = Parse(parser, parsePoints, preUnaryOperatorPrecedence + 1); - left = SyntaxTree.Unary(GSymbol.Get($"'{operatorToken.Text}"), operand).WithRange(operatorToken.Start, operand.Range.EndIndex).WithStyle(NodeStyle.PrefixNotation); + left = SyntaxTree.Unary(GSymbol.Get($"'{operatorToken.Text}"), operand) + .WithRange(operatorToken.Start, operand.Range.EndIndex).WithStyle(NodeStyle.PrefixNotation); } } else @@ -75,7 +79,8 @@ public static LNode Parse(Parser parser, ParsePoints parsePoints = null, int par { var unaryOperatorToken = parser.Iterator.NextToken(); - left = SyntaxTree.Unary(GSymbol.Get($"'suf{unaryOperatorToken.Text}"), left).WithRange(left.Range.StartIndex, unaryOperatorToken.End).WithStyle(NodeStyle.Operator); + left = SyntaxTree.Unary(GSymbol.Get($"'suf{unaryOperatorToken.Text}"), left) + .WithRange(left.Range.StartIndex, unaryOperatorToken.End).WithStyle(NodeStyle.Operator); } } } @@ -91,7 +96,8 @@ public static LNode Parse(Parser parser, ParsePoints parsePoints = null, int par var operatorToken = parser.Iterator.NextToken(); var right = Parse(parser, parsePoints, precedence); - left = SyntaxTree.Binary(GSymbol.Get($"'{operatorToken.Text}"), left, right).WithRange(left.Range.StartIndex, right.Range.StartIndex); + left = SyntaxTree.Binary(GSymbol.Get($"'{operatorToken.Text}"), left, right) + .WithRange(left.Range.StartIndex, right.Range.StartIndex); // parsing postunary for: Hello::new()? = false; var postUnaryOperatorPrecedence = GetPostUnaryOperatorPrecedence(parser.Iterator.Current.Type); @@ -102,7 +108,8 @@ public static LNode Parse(Parser parser, ParsePoints parsePoints = null, int par { var unaryOperatorToken = parser.Iterator.NextToken(); - left = SyntaxTree.Unary(GSymbol.Get($"'suf{unaryOperatorToken.Text}"), left).WithRange(left.Range.StartIndex, unaryOperatorToken.End).WithStyle(NodeStyle.Operator); + left = SyntaxTree.Unary(GSymbol.Get($"'suf{unaryOperatorToken.Text}"), left) + .WithRange(left.Range.StartIndex, unaryOperatorToken.End).WithStyle(NodeStyle.Operator); } } } @@ -112,14 +119,29 @@ public static LNode Parse(Parser parser, ParsePoints parsePoints = null, int par public static LNodeList ParseList(Parser parser, TokenType terminator, bool consumeTerminator = true) { - return ParsingHelpers.ParseSeperated(parser, terminator, consumeTerminator: consumeTerminator); + return ParsingHelpers.ParseSeperated(parser, terminator, + consumeTerminator: consumeTerminator); + } + + private static int GetPreUnaryOperatorPrecedence(TokenType kind) + { + return PreUnaryOperators.GetValueOrDefault(kind); + } + + private static int GetPostUnaryOperatorPrecedence(TokenType kind) + { + return PostUnaryOperators.GetValueOrDefault(kind); } - private static int GetPreUnaryOperatorPrecedence(TokenType kind) => PreUnaryOperators.GetValueOrDefault(kind); - private static int GetPostUnaryOperatorPrecedence(TokenType kind) => PostUnaryOperators.GetValueOrDefault(kind); + private static bool IsPreUnary(TokenType kind) + { + return PreUnaryOperators.ContainsKey(kind); + } - private static bool IsPreUnary(TokenType kind) => PreUnaryOperators.ContainsKey(kind); - private static bool IsPostUnary(TokenType kind) => PostUnaryOperators.ContainsKey(kind); + private static bool IsPostUnary(TokenType kind) + { + return PostUnaryOperators.ContainsKey(kind); + } private class ExpressionParser : IParsePoint { diff --git a/Source/Backlang.Codeanalysis/Parsing/LNodeExtensions.cs b/Source/Backlang.Codeanalysis/Parsing/LNodeExtensions.cs index cadc13a..12ebacd 100644 --- a/Source/Backlang.Codeanalysis/Parsing/LNodeExtensions.cs +++ b/Source/Backlang.Codeanalysis/Parsing/LNodeExtensions.cs @@ -1,5 +1,5 @@ -using Loyc.Syntax; -using Backlang.Codeanalysis.Parsing.AST; +using Backlang.Codeanalysis.Parsing.AST; +using Loyc.Syntax; namespace Backlang.Codeanalysis.Parsing; @@ -27,6 +27,7 @@ public static LNode FromToken(this LNodeFactory factory, Token token) public static bool IsNoneType(this LNode node) { - return node.Name == Symbols.TypeLiteral && node.Args[0].Args[0].Name.Name == "none" && node.Args[0].Args[0].IsId; + return node.Name == Symbols.TypeLiteral && node.Args[0].Args[0].Name.Name == "none" && + node.Args[0].Args[0].IsId; } } \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/Lexer.cs b/Source/Backlang.Codeanalysis/Parsing/Lexer.cs index 9a3d68a..34ef246 100644 --- a/Source/Backlang.Codeanalysis/Parsing/Lexer.cs +++ b/Source/Backlang.Codeanalysis/Parsing/Lexer.cs @@ -1,10 +1,8 @@ using Backlang.Codeanalysis.Core; using Backlang.Codeanalysis.Core.Attributes; -using Loyc.Collections.Impl; using Loyc.Syntax; using System.Reflection; using System.Text; -using System.Transactions; namespace Backlang.Codeanalysis.Parsing; @@ -19,7 +17,7 @@ static Lexer() foreach (var op in typeValues) { var attributes = op.GetType() - .GetField(Enum.GetName(op)).GetCustomAttributes(true); + .GetField(Enum.GetName(op)).GetCustomAttributes(true); if (attributes != null && attributes.Any()) { @@ -30,7 +28,7 @@ static Lexer() } } - _symbolTokens = new(_symbolTokens.OrderByDescending(_ => _.Key.Length)); + _symbolTokens = new Dictionary(_symbolTokens.OrderByDescending(_ => _.Key.Length)); } protected override Token NextToken() @@ -52,23 +50,28 @@ protected override Token NextToken() { return LexCharLiteral(); } - else if (Current() == '"') + + if (Current() == '"') { return LexDoubleQuoteString(); } - else if (IsMatch("0x")) + + if (IsMatch("0x")) { return LexHexNumber(); } - else if (IsMatch("0b")) + + if (IsMatch("0b")) { return LexBinaryNumber(); } - else if (char.IsDigit(Current())) + + if (char.IsDigit(Current())) { return LexDecimalNumber(); } - else if (IsIdentifierStartDigit()) + + if (IsIdentifierStartDigit()) { var identifier = LexIdentifier(); @@ -79,19 +82,17 @@ protected override Token NextToken() return identifier; } - else + + foreach (var symbol in _symbolTokens) { - foreach (var symbol in _symbolTokens) + if (IsMatch(symbol.Key)) { - if (IsMatch(symbol.Key)) - { - return LexSymbol(symbol); - } + return LexSymbol(symbol); } - - ReportError(); } + ReportError(); + return Token.Invalid; } @@ -118,6 +119,7 @@ private string ReadLine() Advance(); _column++; } + Advance(); _column = 0; _line++; @@ -160,9 +162,9 @@ private bool IsIdentifierStartDigit() private bool IsMatch(string token) { - bool result = Current() == token[0]; + var result = Current() == token[0]; - for (int i = 1; i < token.Length; i++) + for (var i = 1; i < token.Length; i++) { if (result) { @@ -192,7 +194,9 @@ private Token LexBinaryNumber() _column++; } - return new Token(TokenType.BinNumber, _document.Text.Slice(oldpos, _position - oldpos).ToString().Replace("_", string.Empty), oldpos, _position, _line, oldcolumn); + return new Token(TokenType.BinNumber, + _document.Text.Slice(oldpos, _position - oldpos).ToString().Replace("_", string.Empty), oldpos, _position, + _line, oldcolumn); } private Token LexCharLiteral() @@ -216,7 +220,8 @@ private Token LexCharLiteral() _column += 2; - return new Token(TokenType.CharLiteral, _document.Text.Slice(oldpos, _position - oldpos).ToString(), oldpos - 1, ++_position, _line, oldColumn); + return new Token(TokenType.CharLiteral, _document.Text.Slice(oldpos, _position - oldpos).ToString(), oldpos - 1, + ++_position, _line, oldColumn); } private Token LexDecimalNumber() @@ -242,7 +247,8 @@ private Token LexDecimalNumber() } } - return new Token(TokenType.Number, _document.Text.Slice(oldpos, _position - oldpos).ToString(), oldpos, _position, _line, oldcolumn); + return new Token(TokenType.Number, _document.Text.Slice(oldpos, _position - oldpos).ToString(), oldpos, + _position, _line, oldcolumn); } private Token LexDoubleQuoteString() @@ -257,7 +263,9 @@ private Token LexDoubleQuoteString() var range = new SourceRange(_document, _position, 1); Messages.Add(Message.Error(ErrorID.UnterminatedStringLiteral, range)); - return new Token(TokenType.StringLiteral, _document.Text.Slice(oldpos, _position - oldpos - 1).ToString(), oldpos - 1, _position, _line, oldColumn); + return new Token(TokenType.StringLiteral, + _document.Text.Slice(oldpos, _position - oldpos - 1).ToString(), oldpos - 1, _position, _line, + oldColumn); } Advance(); @@ -266,7 +274,8 @@ private Token LexDoubleQuoteString() _column += 2; - return new Token(TokenType.StringLiteral, _document.Text.Slice(oldpos, _position - oldpos).ToString(), oldpos - 1, ++_position, _line, oldColumn); + return new Token(TokenType.StringLiteral, _document.Text.Slice(oldpos, _position - oldpos).ToString(), + oldpos - 1, ++_position, _line, oldColumn); } private Token LexHexNumber() @@ -283,7 +292,9 @@ private Token LexHexNumber() _column++; } - return new Token(TokenType.HexNumber, _document.Text.Slice(oldpos, _position - oldpos).ToString().Replace("_", string.Empty), oldpos, _position, _line, oldcolumn); + return new Token(TokenType.HexNumber, + _document.Text.Slice(oldpos, _position - oldpos).ToString().Replace("_", string.Empty), oldpos, _position, + _line, oldcolumn); } private Token LexIdentifier() @@ -341,7 +352,7 @@ private void SkipComments() } else if (IsMatch("/*")) { - int oldpos = _position; + var oldpos = _position; Advance(); Advance(); @@ -354,6 +365,7 @@ private void SkipComments() { break; } + Advance(); _column++; } diff --git a/Source/Backlang.Codeanalysis/Parsing/Message.cs b/Source/Backlang.Codeanalysis/Parsing/Message.cs index 4d6621d..f145c4e 100644 --- a/Source/Backlang.Codeanalysis/Parsing/Message.cs +++ b/Source/Backlang.Codeanalysis/Parsing/Message.cs @@ -5,7 +5,7 @@ namespace Backlang.Codeanalysis.Parsing; public enum MessageSeverity { - Error, Warning, Info, Hint, + Error, Warning, Info, Hint } public sealed class Message @@ -51,7 +51,11 @@ public static Message Warning(string message, SourceRange range) public override string ToString() { - if (Document == null) return Text; + if (Document == null) + { + return Text; + } + return $"{Document.FileName}:{Range.Start.Line}:{Range.Start.Column} {Text}"; } } \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/OperatorInfo.cs b/Source/Backlang.Codeanalysis/Parsing/OperatorInfo.cs index 664a534..9c74e8b 100644 --- a/Source/Backlang.Codeanalysis/Parsing/OperatorInfo.cs +++ b/Source/Backlang.Codeanalysis/Parsing/OperatorInfo.cs @@ -1,4 +1,3 @@ -using Backlang.Codeanalysis.Parsing; -namespace Backlang.Codeanalysis.Parsing; +namespace Backlang.Codeanalysis.Parsing; -public record struct OperatorInfo(TokenType TokenType, int Precedence, bool IsUnary, bool IsPostUnary); +public record struct OperatorInfo(TokenType TokenType, int Precedence, bool IsUnary, bool IsPostUnary); \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/Parser.Expressions.cs b/Source/Backlang.Codeanalysis/Parsing/Parser.Expressions.cs index dba73ac..f9e0d81 100644 --- a/Source/Backlang.Codeanalysis/Parsing/Parser.Expressions.cs +++ b/Source/Backlang.Codeanalysis/Parsing/Parser.Expressions.cs @@ -2,24 +2,24 @@ using Backlang.Codeanalysis.Parsing.AST; using Loyc; using Loyc.Syntax; -using System.Globalization; namespace Backlang.Codeanalysis.Parsing; public sealed partial class Parser { - private readonly Dictionary _lits = new() { - {"ub", CodeSymbols.UInt8}, - {"us", CodeSymbols.UInt16}, - {"u", CodeSymbols.UInt32}, - {"ui", CodeSymbols.UInt32}, - {"ul", CodeSymbols.UInt64}, - {"b", CodeSymbols.Int8}, - {"s", CodeSymbols.Int16}, - {"l", CodeSymbols.Int64}, - {"h", Symbols.Float16}, - {"f", Symbols.Float32}, - {"d", Symbols.Float64}, + private readonly Dictionary _lits = new() + { + { "ub", CodeSymbols.UInt8 }, + { "us", CodeSymbols.UInt16 }, + { "u", CodeSymbols.UInt32 }, + { "ui", CodeSymbols.UInt32 }, + { "ul", CodeSymbols.UInt64 }, + { "b", CodeSymbols.Int8 }, + { "s", CodeSymbols.Int16 }, + { "l", CodeSymbols.Int64 }, + { "h", Symbols.Float16 }, + { "f", Symbols.Float32 }, + { "d", Symbols.Float64 } }; public void AddError(LocalizableString message, SourceRange range) @@ -29,7 +29,8 @@ public void AddError(LocalizableString message, SourceRange range) public void AddError(LocalizableString message) { - Messages.Add(Message.Error(message, new SourceRange(Document, Iterator.Current.Start, Iterator.Current.Text.Length))); + Messages.Add(Message.Error(message, + new SourceRange(Document, Iterator.Current.Start, Iterator.Current.Text.Length))); } internal LNode ParsePrimary(ParsePoints parsePoints = null) @@ -46,7 +47,7 @@ internal LNode ParsePrimary(ParsePoints parsePoints = null) TokenType.TrueLiteral => ParseBooleanLiteral(true), TokenType.FalseLiteral => ParseBooleanLiteral(false), TokenType.OpenSquare => ParseArrayLiteral(), - _ => InvokeExpressionParsePoint(parsePoints), + _ => InvokeExpressionParsePoint(parsePoints) }; } @@ -78,14 +79,13 @@ private LNode InvokeExpressionParsePoint(ParsePoints parsePoints) return value(Iterator, this).WithRange(token, Iterator.Prev); } - else if (type == Token.Invalid.Type) + + if (type == Token.Invalid.Type) { return LNode.Missing; } - else - { - return Invalid(ErrorID.UnknownExpression); - } + + return Invalid(ErrorID.UnknownExpression); } private LNode ParseBinNumber() @@ -99,7 +99,8 @@ private LNode ParseBinNumber() return LNode.Missing; } - return SyntaxTree.Factory.Call(CodeSymbols.Int32, LNode.List(SyntaxTree.Factory.Literal(result).WithStyle(NodeStyle.BinaryLiteral))) + return SyntaxTree.Factory.Call(CodeSymbols.Int32, + LNode.List(SyntaxTree.Factory.Literal(result).WithStyle(NodeStyle.BinaryLiteral))) .WithRange(Iterator.Prev); } @@ -132,7 +133,7 @@ private LNode ParseHexNumber() } return SyntaxTree.Factory.Call(CodeSymbols.Int32, - LNode.List(SyntaxTree.Factory.Literal(result))) + LNode.List(SyntaxTree.Factory.Literal(result))) .WithRange(Iterator.Prev); } @@ -170,7 +171,7 @@ private LNode ParseNumber() } else { - AddError(new(ErrorID.UnknownLiteral, Iterator.Current.Text)); + AddError(new LocalizableString(ErrorID.UnknownLiteral, Iterator.Current.Text)); result = LNode.Missing; } @@ -204,7 +205,7 @@ private LNode ParseString() { var valueToken = Iterator.NextToken(); - var unescaped = ParseHelpers.UnescapeCStyle(valueToken.Text).ToString(); + var unescaped = ParseHelpers.UnescapeCStyle(valueToken.Text); return SyntaxTree.Factory.Call(CodeSymbols.String, LNode.List(SyntaxTree.Factory.Literal(unescaped))) .WithRange(valueToken); diff --git a/Source/Backlang.Codeanalysis/Parsing/Parser.ParsePoints.cs b/Source/Backlang.Codeanalysis/Parsing/Parser.ParsePoints.cs index 3176612..e03b0e0 100644 --- a/Source/Backlang.Codeanalysis/Parsing/Parser.ParsePoints.cs +++ b/Source/Backlang.Codeanalysis/Parsing/Parser.ParsePoints.cs @@ -59,13 +59,13 @@ public void InitParsePoints() } public void AddDeclarationParsePoint(TokenType type) - where T : IParsePoint + where T : IParsePoint { DeclarationParsePoints.Add(type, T.Parse); } public void AddExpressionParsePoint(TokenType type) - where T : IParsePoint + where T : IParsePoint { ExpressionParsePoints.Add(type, T.Parse); } @@ -78,7 +78,10 @@ public void AddStatementParsePoint(TokenType type) public LNodeList InvokeDeclarationParsePoints(TokenType terminator = TokenType.EOF, ParsePoints parsePoints = null) { - if (parsePoints == null) parsePoints = DeclarationParsePoints; + if (parsePoints == null) + { + parsePoints = DeclarationParsePoints; + } var body = new LNodeList(); while (Iterator.Current.Type != terminator) @@ -111,7 +114,7 @@ public LNode InvokeParsePoint(ParsePoints parsePoints) var range = new SourceRange(Document, Iterator.Current.Start, Iterator.Current.Text.Length); - AddError(new(ErrorID.UnknownExpression, Iterator.Current.Text), range); + AddError(new LocalizableString(ErrorID.UnknownExpression, Iterator.Current.Text), range); Iterator.NextToken(); diff --git a/Source/Backlang.Codeanalysis/Parsing/Parser.cs b/Source/Backlang.Codeanalysis/Parsing/Parser.cs index e9bfbc5..31c438d 100644 --- a/Source/Backlang.Codeanalysis/Parsing/Parser.cs +++ b/Source/Backlang.Codeanalysis/Parsing/Parser.cs @@ -11,7 +11,7 @@ public sealed partial class Parser public Parser(SourceFile document, List tokens, List messages) { Document = document; - Iterator = new(tokens, document); + Iterator = new TokenIterator(tokens, document); Messages = messages; InitParsePoints(); @@ -30,7 +30,7 @@ public static CompilationUnit Parse(SourceDocument src) return new CompilationUnit { Body = LNode.List(LNode.Missing), - Messages = new() { Message.Error(ErrorID.EmptyFile, SourceRange.Synthetic) }, + Messages = new List { Message.Error(ErrorID.EmptyFile, SourceRange.Synthetic) }, Document = document }; } diff --git a/Source/Backlang.Codeanalysis/Parsing/Precedences/BinaryOpPrecedences.cs b/Source/Backlang.Codeanalysis/Parsing/Precedences/BinaryOpPrecedences.cs index 65ecd4c..4658b0e 100644 --- a/Source/Backlang.Codeanalysis/Parsing/Precedences/BinaryOpPrecedences.cs +++ b/Source/Backlang.Codeanalysis/Parsing/Precedences/BinaryOpPrecedences.cs @@ -25,5 +25,5 @@ public enum BinaryOpPrecedences Dot = 8, OperationShortcuts = 2, // += -= *= /= - Equals = OperationShortcuts, + Equals = OperationShortcuts } \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/Precedences/UnaryOpPrecedences.cs b/Source/Backlang.Codeanalysis/Parsing/Precedences/UnaryOpPrecedences.cs index f827dc2..e915509 100644 --- a/Source/Backlang.Codeanalysis/Parsing/Precedences/UnaryOpPrecedences.cs +++ b/Source/Backlang.Codeanalysis/Parsing/Precedences/UnaryOpPrecedences.cs @@ -1,4 +1,5 @@ namespace Backlang.Codeanalysis.Parsing.Precedences; + public enum UnaryOpPrecedences { Literals = 3, // u ui ub us ul b s l @@ -9,5 +10,5 @@ public enum UnaryOpPrecedences Ampersand = 9, Hat = Ampersand, - Dollar = 10, -} + Dollar = 10 +} \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/SourceDocument.cs b/Source/Backlang.Codeanalysis/Parsing/SourceDocument.cs index a199724..8f6f142 100644 --- a/Source/Backlang.Codeanalysis/Parsing/SourceDocument.cs +++ b/Source/Backlang.Codeanalysis/Parsing/SourceDocument.cs @@ -9,19 +9,19 @@ public sealed class SourceDocument public SourceDocument(string filename) { - _document = new SourceFile(new(File.OpenRead(filename)), filename); + _document = new SourceFile(new StreamCharSource(File.OpenRead(filename)), filename); } public SourceDocument(string filename, string content) { var filebody = Encoding.Default.GetBytes(content); - _document = new SourceFile(new(new MemoryStream(filebody)), filename); + _document = new SourceFile(new StreamCharSource(new MemoryStream(filebody)), filename); } public static implicit operator SourceFile(SourceDocument doc) { - SyntaxTree.Factory = new(doc._document); + SyntaxTree.Factory = new LNodeFactory(doc._document); return doc._document; } diff --git a/Source/Backlang.Codeanalysis/Parsing/SyntaxTree.cs b/Source/Backlang.Codeanalysis/Parsing/SyntaxTree.cs index 3bdd80a..ed71155 100644 --- a/Source/Backlang.Codeanalysis/Parsing/SyntaxTree.cs +++ b/Source/Backlang.Codeanalysis/Parsing/SyntaxTree.cs @@ -20,19 +20,22 @@ public static LNode Constructor(LNodeList parameters, LNode code) public static LNode DiscriminatedType(Token nameToken, LNodeList parameters) { - return Factory.Call(Symbols.DiscriminatedType, LNode.List(Factory.FromToken(nameToken), Factory.AltList(parameters))); + return Factory.Call(Symbols.DiscriminatedType, + LNode.List(Factory.FromToken(nameToken), Factory.AltList(parameters))); } public static LNode DiscriminatedUnion(Token nameToken, LNodeList types) { - return Factory.Call(Symbols.DiscriminatedUnion, LNode.List(Factory.FromToken(nameToken), Factory.AltList(types))); + return Factory.Call(Symbols.DiscriminatedUnion, + LNode.List(Factory.FromToken(nameToken), Factory.AltList(types))); } public static LNode Property(LNode type, LNode name, LNode getter, LNode setter, LNode value) { if (value != null) { - return LNode.Call(CodeSymbols.Property, LNode.List(type, getter, setter, LNode.Call(CodeSymbols.Assign, LNode.List(name, value)))); + return LNode.Call(CodeSymbols.Property, + LNode.List(type, getter, setter, LNode.Call(CodeSymbols.Assign, LNode.List(name, value)))); } return LNode.Call(CodeSymbols.Property, LNode.List(type, getter, setter, name)); @@ -106,18 +109,18 @@ public static LNode Enum(LNode name, LNodeList members) { return Factory.Call(CodeSymbols.Enum, Factory.AltList(name, Factory.Call(CodeSymbols.AltList), - Factory.Call(CodeSymbols.Braces, - members))); + Factory.Call(CodeSymbols.Braces, + members))); } public static LNode For(LNode init, LNode arr, LNode body) { return Factory.Call( CodeSymbols.For, - Factory.AltList(Factory.AltList( + Factory.AltList(Factory.AltList( Factory.AltList(LNode.Call(CodeSymbols.In, Factory.AltList(init, arr)).SetStyle(NodeStyle.Operator))), LNode.Missing, - Factory.AltList(), body)); + Factory.AltList(), body)); } public static LNode If(LNode cond, LNode ifBody, LNode elseBody) @@ -130,8 +133,8 @@ public static LNode ImplDecl(LNode target, LNodeList body) var attributes = new LNodeList(); return Factory.Call(Symbols.Implementation, - Factory.AltList(target, LNode.Call(CodeSymbols.Braces, - body).SetStyle(NodeStyle.StatementBlock))).WithAttrs(attributes); + Factory.AltList(target, LNode.Call(CodeSymbols.Braces, + body).SetStyle(NodeStyle.StatementBlock))).WithAttrs(attributes); } public static LNode Import(LNode expr) @@ -196,7 +199,8 @@ public static LNode Struct(Token nameToken, LNodeList inheritances, LNodeList me public static LNode Switch(LNode element, LNodeList cases) { - return Factory.Call(CodeSymbols.SwitchStmt, LNode.List(element, LNode.Call(CodeSymbols.Braces, cases).SetStyle(NodeStyle.StatementBlock))); + return Factory.Call(CodeSymbols.SwitchStmt, + LNode.List(element, LNode.Call(CodeSymbols.Braces, cases).SetStyle(NodeStyle.StatementBlock))); } public static LNode Try(LNode body, LNode catches, LNode finallly) @@ -209,7 +213,8 @@ public static LNode Try(LNode body, LNode catches, LNode finallly) public static LNode Type(string name, LNodeList arguments) { - return Factory.Call(Symbols.TypeLiteral, Factory.AltList(Factory.Id(name), Factory.Call(CodeSymbols.Of, arguments))); + return Factory.Call(Symbols.TypeLiteral, + Factory.AltList(Factory.Id(name), Factory.Call(CodeSymbols.Of, arguments))); } public static LNode Unary(Symbol op, LNode arg) @@ -241,7 +246,7 @@ public static LNode While(LNode cond, LNode body) { return Factory.Call( CodeSymbols.While, - LNode.List(cond, body)); + LNode.List(cond, body)); } public static LNode Unit(LNode result, string unit) @@ -263,6 +268,4 @@ public static LNode DoWhile(LNode body, LNode cond) { return Factory.Call(CodeSymbols.DoWhile, LNode.List(body, cond)); } - - } \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/Token.cs b/Source/Backlang.Codeanalysis/Parsing/Token.cs index 3bdaf2b..0f38815 100644 --- a/Source/Backlang.Codeanalysis/Parsing/Token.cs +++ b/Source/Backlang.Codeanalysis/Parsing/Token.cs @@ -17,7 +17,7 @@ public Token(TokenType type, string text, int start, int end, int line, int colu public Token(TokenType type) { Type = type; - Text = String.Empty; + Text = string.Empty; } public Token(TokenType type, string text) diff --git a/Source/Backlang.Codeanalysis/Parsing/TokenIterator.cs b/Source/Backlang.Codeanalysis/Parsing/TokenIterator.cs index 1d57db4..b17d1c5 100644 --- a/Source/Backlang.Codeanalysis/Parsing/TokenIterator.cs +++ b/Source/Backlang.Codeanalysis/Parsing/TokenIterator.cs @@ -1,4 +1,5 @@ -using Backlang.Codeanalysis.Core.Attributes; +using Backlang.Codeanalysis.Core; +using Backlang.Codeanalysis.Core.Attributes; using Loyc.Syntax; using System.Reflection; @@ -6,9 +7,9 @@ namespace Backlang.Codeanalysis.Parsing; public sealed class TokenIterator { - public readonly List Messages = new(); private readonly SourceFile _document; private readonly List _tokens; + public readonly List Messages = new(); public TokenIterator(List tokens, SourceFile document) { @@ -31,6 +32,7 @@ public static string GetTokenRepresentation(TokenType kind) { return lexeme.Lexeme; } + if (keyword is not null) { return keyword.Keyword; @@ -47,6 +49,7 @@ public bool ConsumeIfMatch(TokenType kind) result = true; NextToken(); } + return result; } @@ -57,7 +60,7 @@ public bool IsMatch(TokenType kind) public bool IsMatch(params TokenType[] kinds) { - bool result = false; + var result = false; foreach (var kind in kinds) { result |= IsMatch(kind); @@ -69,11 +72,15 @@ public bool IsMatch(params TokenType[] kinds) public Token Match(TokenType kind) { if (Current.Type == kind) + { return NextToken(); + } Messages.Add( - Message.Error(new(Core.ErrorID.Expected, GetTokenRepresentation(kind), GetTokenRepresentation(Current.Type)), - new SourceRange(_document, Current.Start, Current.Text.Length))); + Message.Error( + new LocalizableString(ErrorID.Expected, GetTokenRepresentation(kind), + GetTokenRepresentation(Current.Type)), + new SourceRange(_document, Current.Start, Current.Text.Length))); NextToken(); @@ -91,7 +98,9 @@ public Token Peek(int offset) { var index = Position + offset; if (index >= _tokens.Count) + { return _tokens[_tokens.Count - 1]; + } return _tokens[index]; } diff --git a/Source/Backlang.Codeanalysis/Parsing/TokenType.cs b/Source/Backlang.Codeanalysis/Parsing/TokenType.cs index 8cbc83d..707e599 100644 --- a/Source/Backlang.Codeanalysis/Parsing/TokenType.cs +++ b/Source/Backlang.Codeanalysis/Parsing/TokenType.cs @@ -14,25 +14,19 @@ public enum TokenType BinNumber, CharLiteral, - [Lexeme(".")] - [BinaryOperatorInfo(BinaryOpPrecedences.Dot)] + [Lexeme(".")] [BinaryOperatorInfo(BinaryOpPrecedences.Dot)] Dot, - [Lexeme("::")] - [BinaryOperatorInfo(BinaryOpPrecedences.FunctionCalls)] + [Lexeme("::")] [BinaryOperatorInfo(BinaryOpPrecedences.FunctionCalls)] ColonColon, - [BinaryOperatorInfo(BinaryOpPrecedences.DashedOps)] - [Lexeme("+")] + [BinaryOperatorInfo(BinaryOpPrecedences.DashedOps)] [Lexeme("+")] Plus, - [BinaryOperatorInfo(BinaryOpPrecedences.Range)] - [Lexeme("..")] + [BinaryOperatorInfo(BinaryOpPrecedences.Range)] [Lexeme("..")] RangeOperator, - [PreUnaryOperatorInfo(UnaryOpPrecedences.Negate)] - [BinaryOperatorInfo(BinaryOpPrecedences.DashedOps)] - [Lexeme("-")] + [PreUnaryOperatorInfo(UnaryOpPrecedences.Negate)] [BinaryOperatorInfo(BinaryOpPrecedences.DashedOps)] [Lexeme("-")] Minus, [Lexeme("&")] @@ -40,53 +34,37 @@ public enum TokenType [BinaryOperatorInfo(BinaryOpPrecedences.Ampersand)] Ampersand, - [Lexeme("|")] - [BinaryOperatorInfo(BinaryOpPrecedences.Ampersand)] + [Lexeme("|")] [BinaryOperatorInfo(BinaryOpPrecedences.Ampersand)] Pipe, - [Lexeme("~")] - [PreUnaryOperatorInfo(UnaryOpPrecedences.LogicalNot)] + [Lexeme("~")] [PreUnaryOperatorInfo(UnaryOpPrecedences.LogicalNot)] Tilde, - [Lexeme("^")] - [BinaryOperatorInfo(BinaryOpPrecedences.Hat)] - [PreUnaryOperatorInfo(UnaryOpPrecedences.Hat)] + [Lexeme("^")] [BinaryOperatorInfo(BinaryOpPrecedences.Hat)] [PreUnaryOperatorInfo(UnaryOpPrecedences.Hat)] Hat, - [BinaryOperatorInfo(BinaryOpPrecedences.DottedOps)] - [Lexeme("/")] + [BinaryOperatorInfo(BinaryOpPrecedences.DottedOps)] [Lexeme("/")] Slash, - [BinaryOperatorInfo(BinaryOpPrecedences.DottedOps)] - [PreUnaryOperatorInfo(UnaryOpPrecedences.Hat)] - [Lexeme("*")] + [BinaryOperatorInfo(BinaryOpPrecedences.DottedOps)] [PreUnaryOperatorInfo(UnaryOpPrecedences.Hat)] [Lexeme("*")] Star, - [PostUnaryOperatorInfo(UnaryOpPrecedences.Negate)] - [Lexeme(".*")] + [PostUnaryOperatorInfo(UnaryOpPrecedences.Negate)] [Lexeme(".*")] DotAsterisk, // for namespace imports - [BinaryOperatorInfo(BinaryOpPrecedences.Hat)] - [Lexeme("**")] + [BinaryOperatorInfo(BinaryOpPrecedences.Hat)] [Lexeme("**")] StarStar, - [BinaryOperatorInfo(BinaryOpPrecedences.Percent)] - [PostUnaryOperatorInfo(UnaryOpPrecedences.Literals)] - [Lexeme("%")] + [BinaryOperatorInfo(BinaryOpPrecedences.Percent)] [PostUnaryOperatorInfo(UnaryOpPrecedences.Literals)] [Lexeme("%")] Percent, - [BinaryOperatorInfo(BinaryOpPrecedences.And)] - [Lexeme("and")] - [Lexeme("&&")] + [BinaryOperatorInfo(BinaryOpPrecedences.And)] [Lexeme("and")] [Lexeme("&&")] And, - [BinaryOperatorInfo(BinaryOpPrecedences.Or)] - [Lexeme("or")] - [Lexeme("||")] + [BinaryOperatorInfo(BinaryOpPrecedences.Or)] [Lexeme("or")] [Lexeme("||")] Or, - [PreUnaryOperatorInfo(UnaryOpPrecedences.LogicalNot)] - [Lexeme("!")] + [PreUnaryOperatorInfo(UnaryOpPrecedences.LogicalNot)] [Lexeme("!")] Exclamation, [Lexeme("*=")] @@ -99,268 +77,184 @@ public enum TokenType [BinaryOperatorInfo(BinaryOpPrecedences.OperationShortcuts)] EqualsShortcutToken, - [Lexeme("=")] - [BinaryOperatorInfo(BinaryOpPrecedences.Equals)] + [Lexeme("=")] [BinaryOperatorInfo(BinaryOpPrecedences.Equals)] EqualsToken, - [Lexeme("<=")] - [BinaryOperatorInfo(BinaryOpPrecedences.Comparisons)] + [Lexeme("<=")] [BinaryOperatorInfo(BinaryOpPrecedences.Comparisons)] LessThanEqual, - [Lexeme("<")] - [BinaryOperatorInfo(BinaryOpPrecedences.Comparisons)] + [Lexeme("<")] [BinaryOperatorInfo(BinaryOpPrecedences.Comparisons)] LessThan, - [Lexeme(">")] - [BinaryOperatorInfo(BinaryOpPrecedences.Comparisons)] + [Lexeme(">")] [BinaryOperatorInfo(BinaryOpPrecedences.Comparisons)] GreaterThan, - [Lexeme(">=")] - [BinaryOperatorInfo(BinaryOpPrecedences.Comparisons)] + [Lexeme(">=")] [BinaryOperatorInfo(BinaryOpPrecedences.Comparisons)] GreaterThanEqual, - [Lexeme(":")] - Colon, + [Lexeme(":")] Colon, - [Lexeme("(")] - OpenParen, + [Lexeme("(")] OpenParen, - [Lexeme(")")] - CloseParen, + [Lexeme(")")] CloseParen, - [Lexeme("{")] - OpenCurly, + [Lexeme("{")] OpenCurly, - [Lexeme("}")] - CloseCurly, + [Lexeme("}")] CloseCurly, - [Lexeme("->")] - Arrow, + [Lexeme("->")] Arrow, - [Lexeme("=>")] - GoesTo, + [Lexeme("=>")] GoesTo, - [Lexeme("|>")] - [BinaryOperatorInfo(BinaryOpPrecedences.PipeOperator)] + [Lexeme("|>")] [BinaryOperatorInfo(BinaryOpPrecedences.PipeOperator)] PipeOperator, - [Lexeme(",")] - Comma, + [Lexeme(",")] Comma, - [Lexeme("$")] - [PreUnaryOperatorInfo(UnaryOpPrecedences.Dollar)] + [Lexeme("$")] [PreUnaryOperatorInfo(UnaryOpPrecedences.Dollar)] Dollar, - [Lexeme("?")] - [PostUnaryOperatorInfo(UnaryOpPrecedences.Negate)] + [Lexeme("?")] [PostUnaryOperatorInfo(UnaryOpPrecedences.Negate)] Questionmark, - [Lexeme("==")] - [BinaryOperatorInfo(BinaryOpPrecedences.EqualsEquals)] + [Lexeme("==")] [BinaryOperatorInfo(BinaryOpPrecedences.EqualsEquals)] EqualsEquals, - [Lexeme("!=")] - [BinaryOperatorInfo(BinaryOpPrecedences.EqualsEquals)] + [Lexeme("!=")] [BinaryOperatorInfo(BinaryOpPrecedences.EqualsEquals)] NotEquals, - [Lexeme("<->")] - [BinaryOperatorInfo(BinaryOpPrecedences.SwapOperator)] + [Lexeme("<->")] [BinaryOperatorInfo(BinaryOpPrecedences.SwapOperator)] SwapOperator, - [Lexeme("_")] - Underscore, + [Lexeme("_")] Underscore, - [Lexeme(";")] - Semicolon, + [Lexeme(";")] Semicolon, - [Lexeme("[")] - OpenSquare, + [Lexeme("[")] OpenSquare, - [Lexeme("]")] - CloseSquare, + [Lexeme("]")] CloseSquare, - [Lexeme("@")] - At, + [Lexeme("@")] At, - [Lexeme("as")] - [BinaryOperatorInfo(BinaryOpPrecedences.Casting)] + [Lexeme("as")] [BinaryOperatorInfo(BinaryOpPrecedences.Casting)] As, - [Keyword("true")] - TrueLiteral, + [Keyword("true")] TrueLiteral, - [Keyword("false")] - FalseLiteral, + [Keyword("false")] FalseLiteral, - [Keyword("type")] - Type, + [Keyword("type")] Type, - [Keyword("func")] - Function, + [Keyword("func")] Function, - [Keyword("constructor")] - Constructor, + [Keyword("constructor")] Constructor, - [Keyword("destructor")] - Destructor, + [Keyword("destructor")] Destructor, - [Keyword("macro")] - Macro, + [Keyword("macro")] Macro, - [Keyword("let")] - Let, + [Keyword("let")] Let, - [Keyword("prop")] - Property, + [Keyword("prop")] Property, - [Keyword("mut")] - Mutable, + [Keyword("mut")] Mutable, - [Keyword("enum")] - Enum, + [Keyword("enum")] Enum, - [Keyword("try")] - Try, + [Keyword("try")] Try, - [Keyword("catch")] - Catch, + [Keyword("catch")] Catch, - [Keyword("finally")] - Finally, + [Keyword("finally")] Finally, - [Keyword("with")] - With, + [Keyword("with")] With, - [Keyword("match")] - Match, + [Keyword("match")] Match, - [Keyword("struct")] - Struct, + [Keyword("struct")] Struct, - [Keyword("class")] - Class, + [Keyword("class")] Class, - [Keyword("interface")] - Interface, + [Keyword("interface")] Interface, - [Keyword("bitfield")] - Bitfield, + [Keyword("bitfield")] Bitfield, - [Keyword("default")] - Default, + [Keyword("default")] Default, - [Keyword("sizeof")] - SizeOf, + [Keyword("sizeof")] SizeOf, - [Keyword("typeof")] - TypeOf, + [Keyword("typeof")] TypeOf, - [Keyword("none")] - None, + [Keyword("none")] None, - [Keyword("get")] - Get, + [Keyword("get")] Get, - [Keyword("set")] - Set, + [Keyword("set")] Set, - [Keyword("init")] - Init, + [Keyword("init")] Init, - [Keyword("switch")] - Switch, + [Keyword("switch")] Switch, - [Keyword("case")] - Case, + [Keyword("case")] Case, - [Keyword("break")] - Break, + [Keyword("break")] Break, - [Keyword("continue")] - Continue, + [Keyword("continue")] Continue, - [Keyword("return")] - Return, + [Keyword("return")] Return, - [Keyword("when")] - When, + [Keyword("when")] When, - [Keyword("where")] - Where, + [Keyword("where")] Where, - [Keyword("if")] - If, + [Keyword("if")] If, - [Keyword("else")] - Else, + [Keyword("else")] Else, - [Keyword("while")] - While, + [Keyword("while")] While, - [Keyword("do")] - Do, + [Keyword("do")] Do, - [Keyword("in")] - In, + [Keyword("in")] In, - [Keyword("for")] - For, + [Keyword("for")] For, - [Keyword("const")] - Const, + [Keyword("const")] Const, - [Keyword("global")] - Global, + [Keyword("global")] Global, - [Keyword("static")] - Static, + [Keyword("static")] Static, - [Keyword("abstract")] - Abstract, + [Keyword("abstract")] Abstract, - [Keyword("extern")] - Extern, + [Keyword("extern")] Extern, - [Keyword("override")] - Override, + [Keyword("override")] Override, - [Keyword("of")] - Of, + [Keyword("of")] Of, - [Keyword("implement")] - Implement, + [Keyword("implement")] Implement, - [Keyword("operator")] - Operator, + [Keyword("operator")] Operator, - [Keyword("public")] - Public, + [Keyword("public")] Public, - [Keyword("internal")] - Internal, + [Keyword("internal")] Internal, - [Keyword("protected")] - Protected, + [Keyword("protected")] Protected, - [Keyword("private")] - Private, + [Keyword("private")] Private, - [Keyword("import")] - Import, + [Keyword("import")] Import, - [Keyword("module")] - Module, + [Keyword("module")] Module, - [Keyword("using")] - Using, + [Keyword("using")] Using, - [Keyword("union")] - Union, + [Keyword("union")] Union, - [Keyword("throw")] - Throw, + [Keyword("throw")] Throw, - [Keyword("unit")] - Unit, - DocComment, + [Keyword("unit")] Unit, + DocComment } \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Parsing/TokenUtils.cs b/Source/Backlang.Codeanalysis/Parsing/TokenUtils.cs index 37aa8e2..7d382b2 100644 --- a/Source/Backlang.Codeanalysis/Parsing/TokenUtils.cs +++ b/Source/Backlang.Codeanalysis/Parsing/TokenUtils.cs @@ -5,7 +5,7 @@ namespace Backlang.Codeanalysis.Parsing; public static class TokenUtils { - private static readonly Dictionary TokenTypeRepresentations = new Dictionary(StringComparer.Ordinal); + private static readonly Dictionary TokenTypeRepresentations = new(StringComparer.Ordinal); static TokenUtils() { @@ -13,7 +13,8 @@ static TokenUtils() foreach (var keyword in typeValues) { - var attributes = keyword.GetType().GetField(Enum.GetName(keyword)).GetCustomAttributes(inherit: true); + var attributes = keyword.GetType().GetField(Enum.GetName(keyword)) + .GetCustomAttributes(true); if (attributes != null && attributes.Any()) { @@ -40,8 +41,16 @@ public static bool IsOperator(this Token token) //var op = token.Type; //var attributes = op.GetType().GetField(Enum.GetName(op)).GetCustomAttributes(true); //return attributes != null && attributes.Any(); - if(Expression.BinaryOperators.ContainsKey(token.Type)) return true; - if(Expression.PreUnaryOperators.ContainsKey(token.Type)) return true; + if (Expression.BinaryOperators.ContainsKey(token.Type)) + { + return true; + } + + if (Expression.PreUnaryOperators.ContainsKey(token.Type)) + { + return true; + } + return Expression.PostUnaryOperators.ContainsKey(token.Type); } } \ No newline at end of file diff --git a/Source/Backlang.Codeanalysis/Properties/Resources.Designer.cs b/Source/Backlang.Codeanalysis/Properties/Resources.Designer.cs index f11e57e..3d54314 100644 --- a/Source/Backlang.Codeanalysis/Properties/Resources.Designer.cs +++ b/Source/Backlang.Codeanalysis/Properties/Resources.Designer.cs @@ -1,10 +1,9 @@ //------------------------------------------------------------------------------ // -// Dieser Code wurde von einem Tool generiert. -// Laufzeitversion:4.0.30319.42000 +// This code was generated by a tool. // -// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn -// der Code erneut generiert wird. +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. // //------------------------------------------------------------------------------ @@ -13,12 +12,12 @@ namespace Backlang.Codeanalysis.Properties { /// - /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. + /// A strongly-typed resource class, for looking up localized strings, etc. /// - // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert - // -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert. - // Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen - // mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu. + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] @@ -33,7 +32,7 @@ internal Resources() { } /// - /// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird. + /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { @@ -47,8 +46,8 @@ internal Resources() { } /// - /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle - /// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden. + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { @@ -61,7 +60,7 @@ internal Resources() { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Expected Identifier, TupleType or Function-Signature as TypeLiteral, but got {0} ähnelt. + /// Looks up a localized string similar to Expected Identifier, TupleType or Function-Signature as TypeLiteral, but got {0}. /// internal static string BL_0001_ { get { @@ -70,7 +69,7 @@ internal static string BL_0001_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Invalid Modifier Combination ähnelt. + /// Looks up a localized string similar to Invalid Modifier Combination. /// internal static string BL_0002_ { get { @@ -79,7 +78,7 @@ internal static string BL_0002_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Unknown Character '{0}' ähnelt. + /// Looks up a localized string similar to Unknown Character '{0}'. /// internal static string BL_0003_ { get { @@ -88,7 +87,7 @@ internal static string BL_0003_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Unterminated Char-Literal ähnelt. + /// Looks up a localized string similar to Unterminated Char-Literal. /// internal static string BL_0004_ { get { @@ -97,7 +96,7 @@ internal static string BL_0004_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Unexpected Expression {0} ähnelt. + /// Looks up a localized string similar to Unexpected Expression {0}. /// internal static string BL_0005_ { get { @@ -106,7 +105,7 @@ internal static string BL_0005_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Unknown Literal {0} ähnelt. + /// Looks up a localized string similar to Unknown Literal {0}. /// internal static string BL_0006_ { get { @@ -115,7 +114,7 @@ internal static string BL_0006_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Trailing comma is forbidden ähnelt. + /// Looks up a localized string similar to Trailing comma is forbidden. /// internal static string BL_0007_ { get { @@ -124,7 +123,7 @@ internal static string BL_0007_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Bitfield member declaration only allows literals ähnelt. + /// Looks up a localized string similar to Bitfield member declaration only allows literals. /// internal static string BL_0008_ { get { @@ -133,7 +132,7 @@ internal static string BL_0008_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Expected Function, Property or Field-declaration for Type, but got {0} ähnelt. + /// Looks up a localized string similar to Expected Function, Property or Field-declaration for Type, but got {0}. /// internal static string BL_0009_ { get { @@ -142,7 +141,7 @@ internal static string BL_0009_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Expected Type but got {0} ähnelt. + /// Looks up a localized string similar to Expected Type but got {0}. /// internal static string BL_0010_ { get { @@ -151,7 +150,7 @@ internal static string BL_0010_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Unexpected Switch Option ähnelt. + /// Looks up a localized string similar to Unexpected Switch Option. /// internal static string BL_0011_ { get { @@ -160,7 +159,7 @@ internal static string BL_0011_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Expected at least one catch block ähnelt. + /// Looks up a localized string similar to Expected at least one catch block. /// internal static string BL_0012_ { get { @@ -169,7 +168,7 @@ internal static string BL_0012_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die SourceFile is empty ähnelt. + /// Looks up a localized string similar to SourceFile is empty. /// internal static string BL_0013_ { get { @@ -178,7 +177,7 @@ internal static string BL_0013_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Expected Identifier but got {0} ähnelt. + /// Looks up a localized string similar to Expected Identifier but got {0}. /// internal static string BL_0014_ { get { @@ -187,7 +186,7 @@ internal static string BL_0014_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Unterminated String-Literal ähnelt. + /// Looks up a localized string similar to Unterminated String-Literal. /// internal static string BL_0015_ { get { @@ -196,7 +195,7 @@ internal static string BL_0015_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Multiline comment is not closed ähnelt. + /// Looks up a localized string similar to Multiline comment is not closed. /// internal static string BL_0016_ { get { @@ -205,7 +204,7 @@ internal static string BL_0016_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Expected '{0}' but got '{1}' ähnelt. + /// Looks up a localized string similar to Expected '{0}' but got '{1}'. /// internal static string BL_0017_ { get { @@ -214,7 +213,7 @@ internal static string BL_0017_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Duplicate Modifier '{0}' ähnelt. + /// Looks up a localized string similar to Duplicate Modifier '{0}'. /// internal static string BL_0018_ { get { @@ -223,7 +222,7 @@ internal static string BL_0018_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Namespace '{0}' already imported ähnelt. + /// Looks up a localized string similar to Namespace '{0}' already imported. /// internal static string BL_0019_ { get { @@ -232,7 +231,7 @@ internal static string BL_0019_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Got OutputType 'Exe' but couldn't find entry point. ähnelt. + /// Looks up a localized string similar to Got OutputType 'Exe' but couldn't find entry point.. /// internal static string BL_0020_ { get { @@ -241,7 +240,7 @@ internal static string BL_0020_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die {0} cannot be found. Did you mean '{1}'? ähnelt. + /// Looks up a localized string similar to {0} cannot be found. Did you mean '{1}'?. /// internal static string BL_0021_ { get { @@ -250,7 +249,7 @@ internal static string BL_0021_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Cannot implement '{0}', type not found ähnelt. + /// Looks up a localized string similar to Cannot implement '{0}', type not found. /// internal static string BL_0022_ { get { @@ -259,7 +258,7 @@ internal static string BL_0022_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Cannot implement unit type '{0}' ähnelt. + /// Looks up a localized string similar to Cannot implement unit type '{0}'. /// internal static string BL_0023_ { get { @@ -268,7 +267,7 @@ internal static string BL_0023_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die '{0}' already declared ähnelt. + /// Looks up a localized string similar to '{0}' already declared. /// internal static string BL_0024_ { get { @@ -277,7 +276,7 @@ internal static string BL_0024_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Type mismatch {0} {1} ähnelt. + /// Looks up a localized string similar to Type mismatch {0} {1}. /// internal static string BL_0025_ { get { @@ -286,7 +285,7 @@ internal static string BL_0025_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Unit Type mismatch {0} {1} ähnelt. + /// Looks up a localized string similar to Unit Type mismatch {0} {1}. /// internal static string BL_0026_ { get { @@ -295,7 +294,7 @@ internal static string BL_0026_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die {0} cannot be resolved ähnelt. + /// Looks up a localized string similar to {0} cannot be resolved. /// internal static string BL_0027_ { get { @@ -304,7 +303,7 @@ internal static string BL_0027_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Cannot find function '{0}' ähnelt. + /// Looks up a localized string similar to Cannot find function '{0}'. /// internal static string BL_0028_ { get { @@ -313,7 +312,7 @@ internal static string BL_0028_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Target '{0}' cannot be found ähnelt. + /// Looks up a localized string similar to Target '{0}' cannot be found. /// internal static string BL_0029_ { get { @@ -322,7 +321,7 @@ internal static string BL_0029_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Identifier '{0}' is not defined ähnelt. + /// Looks up a localized string similar to Identifier '{0}' is not defined. /// internal static string BL_0030_ { get { @@ -331,12 +330,21 @@ internal static string BL_0030_ { } /// - /// Sucht eine lokalisierte Zeichenfolge, die Cannot set type ähnelt. + /// Looks up a localized string similar to Cannot set type. /// internal static string BL_0031_ { get { return ResourceManager.GetString("BL(0031)", resourceCulture); } } + + /// + /// Looks up a localized string similar to Cannot deduce Type. Declare it manually!. + /// + internal static string BL_0032_ { + get { + return ResourceManager.GetString("BL(0032)", resourceCulture); + } + } } } diff --git a/Source/Backlang.Codeanalysis/Properties/Resources.resx b/Source/Backlang.Codeanalysis/Properties/Resources.resx index 01400d0..e2246f8 100644 --- a/Source/Backlang.Codeanalysis/Properties/Resources.resx +++ b/Source/Backlang.Codeanalysis/Properties/Resources.resx @@ -1,216 +1,221 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, ... + System.Resources.ResXResourceWriter, System.Windows.Forms, ... + this is my long stringthis is a comment + Blue + + [base64 mime encoded serialized .NET Framework object] + + + [base64 mime encoded string representing a byte array form of the .NET Framework object] + This is a comment + + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + + + - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + Expected Identifier, TupleType or Function-Signature as TypeLiteral, but got {0} - + Invalid Modifier Combination - + Unknown Character '{0}' - + Unterminated Char-Literal - + Unexpected Expression {0} - + Unknown Literal {0} - + Trailing comma is forbidden - + Bitfield member declaration only allows literals - + Expected Function, Property or Field-declaration for Type, but got {0} - + Expected Type but got {0} - + Unexpected Switch Option - + Expected at least one catch block - + SourceFile is empty - + Expected Identifier but got {0} - + Unterminated String-Literal - + Multiline comment is not closed - + Expected '{0}' but got '{1}' - + Duplicate Modifier '{0}' - + Namespace '{0}' already imported - + Got OutputType 'Exe' but couldn't find entry point. - + {0} cannot be found. Did you mean '{1}'? - + Cannot implement '{0}', type not found - + Cannot implement unit type '{0}' - + '{0}' already declared - + Type mismatch {0} {1} - + Unit Type mismatch {0} {1} - + {0} cannot be resolved - + Cannot find function '{0}' - + Target '{0}' cannot be found - + Identifier '{0}' is not defined - + Cannot set type - + Cannot deduce Type. Declare it manually! \ No newline at end of file diff --git a/Source/Backlang.Contracts/Attributes.cs b/Source/Backlang.Contracts/Attributes.cs index 50e1066..64305d7 100644 --- a/Source/Backlang.Contracts/Attributes.cs +++ b/Source/Backlang.Contracts/Attributes.cs @@ -1,5 +1,6 @@ namespace Backlang.Contracts; + public static class Attributes { public static readonly IAttribute Mutable = new IntrinsicAttribute("mutable"); -} +} \ No newline at end of file diff --git a/Source/Backlang.Contracts/Backlang.Contracts.csproj b/Source/Backlang.Contracts/Backlang.Contracts.csproj index cc2e809..56bab57 100644 --- a/Source/Backlang.Contracts/Backlang.Contracts.csproj +++ b/Source/Backlang.Contracts/Backlang.Contracts.csproj @@ -1,38 +1,38 @@  - - net9.0 - enable - disable - preview - True - True - A library for writing custom Backlang plugins - https://www.backlang.org - logo.png - https://github.com/Backlang-Org/Backlang - backlang - True - + + net9.0 + enable + disable + preview + True + True + A library for writing custom Backlang plugins + https://www.backlang.org + logo.png + https://github.com/Backlang-Org/Backlang + backlang + True + - - - - - - - + + + + + + + - - - + + + - - - True - \ - - + + + True + \ + + - + diff --git a/Source/Backlang.Contracts/CompilerContext.cs b/Source/Backlang.Contracts/CompilerContext.cs index 4782f99..b67dcfd 100644 --- a/Source/Backlang.Contracts/CompilerContext.cs +++ b/Source/Backlang.Contracts/CompilerContext.cs @@ -2,8 +2,6 @@ namespace Backlang.Contracts; -#nullable disable - public sealed class CompilerContext { public ICompilationTarget CompilationTarget; @@ -42,7 +40,10 @@ public sealed class CompilerContext public void AddError(LNode node, LocalizableString msg) { - if (node.Range.Source is not SourceFile) return; + if (node.Range.Source is not SourceFile) + { + return; + } Messages.Add(Message.Error(msg, node.Range)); } diff --git a/Source/Backlang.Contracts/ConversionUtils.cs b/Source/Backlang.Contracts/ConversionUtils.cs index 6967f16..5d9e53b 100644 --- a/Source/Backlang.Contracts/ConversionUtils.cs +++ b/Source/Backlang.Contracts/ConversionUtils.cs @@ -14,7 +14,8 @@ public static QualifiedName GetModuleName(CompilationUnit tree) return new SimpleName("").Qualify(); } - public static void SetAccessModifier(LNode node, DescribedMember type, AccessModifier defaultChoice = AccessModifier.Private) + public static void SetAccessModifier(LNode node, DescribedMember type, + AccessModifier defaultChoice = AccessModifier.Private) { if (node.Attrs.Contains(LNode.Id(CodeSymbols.Private))) { @@ -61,8 +62,8 @@ public static QualifiedName QualifyNamespace(string @namespace) public static QualifiedName GetQualifiedName(LNode lNode) { - bool isPointer = false; - PointerKind pointerKind = PointerKind.Transient; + var isPointer = false; + var pointerKind = PointerKind.Transient; if (lNode is ("'suf.*", var ns)) @@ -71,6 +72,7 @@ public static QualifiedName GetQualifiedName(LNode lNode) return new SimpleName("*").Qualify(qualifiedNs); } + if (lNode is ("#type*", var arg)) { isPointer = true; @@ -84,21 +86,21 @@ public static QualifiedName GetQualifiedName(LNode lNode) lNode = arg2; } - if (lNode is ("#type", (_, var type))) + if (lNode is ("#type", var (_, type))) { lNode = type; } if (lNode.ArgCount == 3 && lNode is ("#fn", var retType, _, var args)) { - string typename = retType.IsNoneType() ? "Action`" + (args.ArgCount) : "Func`" + (args.ArgCount + 1); + var typename = retType.IsNoneType() ? "Action`" + args.ArgCount : "Func`" + (args.ArgCount + 1); return new SimpleName(typename).Qualify("System"); } if (lNode.Calls(CodeSymbols.Dot)) { - QualifiedName qname = GetQualifiedName(lNode.Args[0]); + var qname = GetQualifiedName(lNode.Args[0]); return GetQualifiedName(lNode.Args[1]).Qualify(qname); } @@ -117,7 +119,7 @@ public static QualifiedName AppendAttributeToName(QualifiedName fullname) { var qualifier = fullname.Slice(0, fullname.PathLength - 1); - return new SimpleName(fullname.FullyUnqualifiedName.ToString() + "Attribute").Qualify(qualifier); + return new SimpleName(fullname.FullyUnqualifiedName + "Attribute").Qualify(qualifier); } private static QualifiedName ShrinkDottedModuleName(LNode lNode) @@ -126,9 +128,7 @@ private static QualifiedName ShrinkDottedModuleName(LNode lNode) { return ShrinkDottedModuleName(lNode.Args[1]).Qualify(ShrinkDottedModuleName(lNode.Args[0])); } - else - { - return new SimpleName(lNode.Name.Name).Qualify(); - } + + return new SimpleName(lNode.Name.Name).Qualify(); } } \ No newline at end of file diff --git a/Source/Backlang.Contracts/Datas/CompilerCliOptions.cs b/Source/Backlang.Contracts/Datas/CompilerCliOptions.cs index 1ce4245..98bdd7e 100644 --- a/Source/Backlang.Contracts/Datas/CompilerCliOptions.cs +++ b/Source/Backlang.Contracts/Datas/CompilerCliOptions.cs @@ -26,13 +26,13 @@ public CompilerCliOptions() [Option("target", Required = false, HelpText = "For which platform to compile to")] public string Target { get; set; } - [Option('e', longName: "embedd", HelpText = "Embedd files into the assembly as resource")] + [Option('e', "embedd", HelpText = "Embedd files into the assembly as resource")] public IEnumerable EmbeddedResource { get; set; } - [Option('v', longName: "version", HelpText = "Set the assembly version")] + [Option('v', "version", HelpText = "Set the assembly version")] public string Version { get; set; } - [Option('f', longName: "framework", HelpText = "On which framework should the assembly be runned on")] + [Option('f', "framework", HelpText = "On which framework should the assembly be runned on")] public string TargetFramework { get; set; } [Option("debug", HelpText = "Wait for debugger been attached for debugging plugins")] diff --git a/Source/Backlang.Contracts/Datas/FileScopeData.cs b/Source/Backlang.Contracts/Datas/FileScopeData.cs index b4fbdcb..7ee5fd0 100644 --- a/Source/Backlang.Contracts/Datas/FileScopeData.cs +++ b/Source/Backlang.Contracts/Datas/FileScopeData.cs @@ -4,8 +4,8 @@ public struct FileScopeData { public FileScopeData() { - ImportetNamespaces = new(); + ImportetNamespaces = new Dictionary(); } public Dictionary ImportetNamespaces { get; set; } -} +} \ No newline at end of file diff --git a/Source/Backlang.Contracts/DefaultTypeEnvironment.cs b/Source/Backlang.Contracts/DefaultTypeEnvironment.cs index 43c0736..d8c4fb9 100644 --- a/Source/Backlang.Contracts/DefaultTypeEnvironment.cs +++ b/Source/Backlang.Contracts/DefaultTypeEnvironment.cs @@ -1,8 +1,5 @@ using Backlang.Contracts.TypeSystem; using Furesoft.Core.CodeDom.Backends.CLR; -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; namespace Backlang.Contracts; diff --git a/Source/Backlang.Contracts/ISemanticCheck.cs b/Source/Backlang.Contracts/ISemanticCheck.cs index 0ad7d56..e38754f 100644 --- a/Source/Backlang.Contracts/ISemanticCheck.cs +++ b/Source/Backlang.Contracts/ISemanticCheck.cs @@ -1,6 +1,8 @@ -namespace Backlang.Codeanalysis.Core; +using Backlang.Contracts; + +namespace Backlang.Codeanalysis.Core; public interface ISemanticCheck { - void Check(CompilationUnit tree, Contracts.CompilerContext context); + void Check(CompilationUnit tree, CompilerContext context); } \ No newline at end of file diff --git a/Source/Backlang.Contracts/IntrinsicHelper.cs b/Source/Backlang.Contracts/IntrinsicHelper.cs index 3ff47f4..4ef95ca 100644 --- a/Source/Backlang.Contracts/IntrinsicHelper.cs +++ b/Source/Backlang.Contracts/IntrinsicHelper.cs @@ -5,8 +5,6 @@ namespace Backlang.Contracts; -#nullable disable - public static class IntrinsicHelper { public static bool IsIntrinsicType(Type intrinsicType, CallPrototype callPrototype) @@ -26,7 +24,8 @@ public static object InvokeIntrinsic(Type intrinsicType, IMethod callee, Instruc if (loadInstruction.Prototype is LoadPrototype) { - var argPrototype = (ConstantPrototype)block.Graph.GetInstruction(loadInstruction.Arguments[0]).Prototype; + var argPrototype = + (ConstantPrototype)block.Graph.GetInstruction(loadInstruction.Arguments[0]).Prototype; arguments.Add(GetValue(argPrototype.Value)); } } @@ -64,43 +63,32 @@ private static object GetValue(Constant value) { return ic.ToInt8(); } - else - { - return ic.ToUInt8(); - } + + return ic.ToUInt8(); case 16: if (ic.Spec.IsSigned) { return ic.ToInt16(); } - else - { - return ic.ToUInt16(); - } + + return ic.ToUInt16(); case 32: if (ic.Spec.IsSigned) { return ic.ToInt32(); } - else - { - return ic.ToUInt32(); - } + + return ic.ToUInt32(); case 64: if (ic.Spec.IsSigned) { return ic.ToInt64(); } - else - { - return ic.ToUInt64(); - } - default: - break; + return ic.ToUInt64(); } return null; @@ -112,7 +100,7 @@ private static object GetValue(Constant value) private static MethodInfo GetMatchingIntrinsicMethod(IMethod callee, Type intrinsicType) { var methods = intrinsicType.GetMethods().Where(_ => _.IsStatic) - .Where(_ => _.Name.Equals(callee.Name.ToString(), StringComparison.OrdinalIgnoreCase)); + .Where(_ => _.Name.Equals(callee.Name.ToString(), StringComparison.OrdinalIgnoreCase)); foreach (var m in methods) { diff --git a/Source/Backlang.Contracts/MethodBodyCompilation.cs b/Source/Backlang.Contracts/MethodBodyCompilation.cs index 80906aa..b71ea22 100644 --- a/Source/Backlang.Contracts/MethodBodyCompilation.cs +++ b/Source/Backlang.Contracts/MethodBodyCompilation.cs @@ -1,4 +1,8 @@ namespace Backlang.Contracts; -public readonly record struct MethodBodyCompilation(LNode Function, CompilerContext Context, - DescribedBodyMethod Method, QualifiedName? Modulename, Scope Scope); \ No newline at end of file +public readonly record struct MethodBodyCompilation( + LNode Function, + CompilerContext Context, + DescribedBodyMethod Method, + QualifiedName? Modulename, + Scope Scope); \ No newline at end of file diff --git a/Source/Backlang.Contracts/NamespaceImports.cs b/Source/Backlang.Contracts/NamespaceImports.cs index 450019a..667a412 100644 --- a/Source/Backlang.Contracts/NamespaceImports.cs +++ b/Source/Backlang.Contracts/NamespaceImports.cs @@ -1,6 +1,5 @@ -using Backlang.Driver; using Backlang.Codeanalysis.Core; -using Backlang.Contracts.Scoping.Items; +using Backlang.Driver; namespace Backlang.Contracts; @@ -16,7 +15,8 @@ public void ImportNamespace(LNode importStatement, CompilerContext context) if (ImportedNamespaces.Contains(qualifiedNs)) { - context.AddError(importStatement, new(ErrorID.NamespaceAlreadyImported, qualifiedNs.ToString())); + context.AddError(importStatement, + new LocalizableString(ErrorID.NamespaceAlreadyImported, qualifiedNs.ToString())); return; } @@ -40,7 +40,8 @@ private void ExpandNamespaceImports(CompilerContext context) var withoutWildcard = imp[..^2]; - context.Binder.TryResolveNamespace(ConversionUtils.QualifyNamespace(withoutWildcard), out var foundNamespaces); + context.Binder.TryResolveNamespace(ConversionUtils.QualifyNamespace(withoutWildcard), + out var foundNamespaces); if (foundNamespaces == null) { @@ -55,4 +56,4 @@ private void ExpandNamespaceImports(CompilerContext context) } } } -} +} \ No newline at end of file diff --git a/Source/Backlang.Contracts/Scoping/Scope.cs b/Source/Backlang.Contracts/Scoping/Scope.cs index bb451de..9eb02f6 100644 --- a/Source/Backlang.Contracts/Scoping/Scope.cs +++ b/Source/Backlang.Contracts/Scoping/Scope.cs @@ -11,7 +11,7 @@ public class Scope public Scope(Scope parent) { Parent = parent; - TypeAliases = new(); + TypeAliases = new Dictionary(); } public Dictionary TypeAliases { get; set; } @@ -25,16 +25,20 @@ public bool Add(ScopeItem item) fsi.Overloads.AddRange(isI.Overloads); return true; } - else - { - if (Contains(item.Name)) return false; - _items.Add(item); - return true; + if (Contains(item.Name)) + { + return false; } + + _items.Add(item); + return true; } - public bool Contains(string name) => _items.Any(_ => _.Name == name); + public bool Contains(string name) + { + return _items.Any(_ => _.Name == name); + } public Scope CreateChildScope() { @@ -43,7 +47,7 @@ public Scope CreateChildScope() public IEnumerable GetAllScopeNames() { - Scope scope = this; + var scope = this; while (scope != null) { foreach (var item in scope._items) diff --git a/Source/Backlang.Contracts/Semantic/ImportCheck.cs b/Source/Backlang.Contracts/Semantic/ImportCheck.cs index 6dfa036..55903c1 100644 --- a/Source/Backlang.Contracts/Semantic/ImportCheck.cs +++ b/Source/Backlang.Contracts/Semantic/ImportCheck.cs @@ -10,7 +10,8 @@ public void Check(CompilationUnit tree, CompilerContext context) { var node = tree.Body[i]; - if (i > 0 && !tree.Body[i - 1].Calls(CodeSymbols.Namespace) && !tree.Body[i - 1].Calls(CodeSymbols.Import) && node.Calls(CodeSymbols.Import)) + if (i > 0 && !tree.Body[i - 1].Calls(CodeSymbols.Namespace) && + !tree.Body[i - 1].Calls(CodeSymbols.Import) && node.Calls(CodeSymbols.Import)) { context.Messages.Add(Message.Warning("Imports should be before module definition", node.Range)); } diff --git a/Source/Backlang.Contracts/Semantic/InterfaceNameCheck.cs b/Source/Backlang.Contracts/Semantic/InterfaceNameCheck.cs index 3659322..7ad0586 100644 --- a/Source/Backlang.Contracts/Semantic/InterfaceNameCheck.cs +++ b/Source/Backlang.Contracts/Semantic/InterfaceNameCheck.cs @@ -13,15 +13,18 @@ public void Check(CompilationUnit tree, CompilerContext context) if (node.Calls(CodeSymbols.Interface)) { - if (node is (_, var typename, _) && typename.Name.Name.Length >= 2) + if (node is var (_, typename, _) && typename.Name.Name.Length >= 2) { if (typename.Name.Name[0] != 'I') { - context.Messages.Add(Message.Warning($"Interface '{typename.Name.Name}' should be start with I", node.Range)); + context.Messages.Add(Message.Warning($"Interface '{typename.Name.Name}' should be start with I", + node.Range)); } + if (char.IsLower(typename.Name.Name[1])) { - context.Messages.Add(Message.Warning($"The second letter of interface '{typename.Name.Name}' should be uppercase", node.Range)); + context.Messages.Add(Message.Warning( + $"The second letter of interface '{typename.Name.Name}' should be uppercase", node.Range)); } } } diff --git a/Source/Backlang.Contracts/Semantic/ModifierCheck.cs b/Source/Backlang.Contracts/Semantic/ModifierCheck.cs index 5f6a0fd..f2fef8f 100644 --- a/Source/Backlang.Contracts/Semantic/ModifierCheck.cs +++ b/Source/Backlang.Contracts/Semantic/ModifierCheck.cs @@ -19,8 +19,10 @@ private void CheckForInvalidModifierCombination(LNode node, CompilerContext cont { var attrs = node.Attrs; var condition = (attrs.Contains(LNode.Id(CodeSymbols.Public)) && attrs.Contains(LNode.Id(CodeSymbols.Private))) - || (attrs.Contains(LNode.Id(CodeSymbols.Public)) && attrs.Contains(LNode.Id(CodeSymbols.Internal))) - || (attrs.Contains(LNode.Id(CodeSymbols.Private)) && attrs.Contains(LNode.Id(CodeSymbols.Internal))); + || (attrs.Contains(LNode.Id(CodeSymbols.Public)) && + attrs.Contains(LNode.Id(CodeSymbols.Internal))) + || (attrs.Contains(LNode.Id(CodeSymbols.Private)) && + attrs.Contains(LNode.Id(CodeSymbols.Internal))); if (condition) { @@ -30,6 +32,7 @@ private void CheckForInvalidModifierCombination(LNode node, CompilerContext cont private bool IsModifiableNode(LNode arg) { - return arg.Calls(CodeSymbols.Class) || arg.Calls(CodeSymbols.Struct) || arg.Calls(CodeSymbols.Fn) || arg.Calls(Symbols.Bitfield); + return arg.Calls(CodeSymbols.Class) || arg.Calls(CodeSymbols.Struct) || arg.Calls(CodeSymbols.Fn) || + arg.Calls(Symbols.Bitfield); } } \ No newline at end of file diff --git a/Source/Backlang.Contracts/Semantic/TypenameCheck.cs b/Source/Backlang.Contracts/Semantic/TypenameCheck.cs index ea3cb20..5610db9 100644 --- a/Source/Backlang.Contracts/Semantic/TypenameCheck.cs +++ b/Source/Backlang.Contracts/Semantic/TypenameCheck.cs @@ -13,9 +13,10 @@ public void Check(CompilationUnit tree, CompilerContext context) if (node.Calls(CodeSymbols.Class) || node.Calls(CodeSymbols.Struct)) { - if (node is (_, var typename, _) && char.IsLower(typename.Name.Name[0])) + if (node is var (_, typename, _) && char.IsLower(typename.Name.Name[0])) { - context.Messages.Add(Message.Warning($"Type '{typename.Name.Name}' should be Uppercase", node.Range)); + context.Messages.Add( + Message.Warning($"Type '{typename.Name.Name}' should be Uppercase", node.Range)); } } } diff --git a/Source/Backlang.Contracts/Semantic/VariableTypeCheck.cs b/Source/Backlang.Contracts/Semantic/VariableTypeCheck.cs index 2d9ac77..302bec5 100644 --- a/Source/Backlang.Contracts/Semantic/VariableTypeCheck.cs +++ b/Source/Backlang.Contracts/Semantic/VariableTypeCheck.cs @@ -11,7 +11,7 @@ public void Check(CompilationUnit tree, CompilerContext context) foreach (var node in letNodes) { - if (node is (_, (_, (_, var type)), (_, _, var value))) + if (node is var (_, (_, (_, type)), (_, _, value))) { if (type.Name.Name == "" && value.Calls(CodeSymbols.Void)) { diff --git a/Source/Backlang.Contracts/SemanticChecker.cs b/Source/Backlang.Contracts/SemanticChecker.cs index e78cce4..781ed0b 100644 --- a/Source/Backlang.Contracts/SemanticChecker.cs +++ b/Source/Backlang.Contracts/SemanticChecker.cs @@ -5,7 +5,8 @@ namespace Backlang.Contracts; public static class SemanticChecker { - private static readonly List _semanticChecks = new() { + private static readonly List _semanticChecks = new() + { new ModuleDefinitionCheck(), new ImportCheck(), new TypenameCheck(), diff --git a/Source/Backlang.Contracts/StackHelpers.cs b/Source/Backlang.Contracts/StackHelpers.cs index 7b08222..3c5bcb2 100644 --- a/Source/Backlang.Contracts/StackHelpers.cs +++ b/Source/Backlang.Contracts/StackHelpers.cs @@ -4,12 +4,27 @@ public static class StackHelpers { public static int SizeOf(IType type, TypeEnvironment environment) { - if (type == environment.Boolean || type == environment.UInt8 || type == environment.Int8) return 1; - else if (type == environment.UInt16 || type == environment.Int16) return 2; - else if (type == environment.UInt32 || type == environment.Int32 || type == environment.Float32) return 4; - else if (type == environment.UInt64 || type == environment.Int64 || type == environment.Float64) return 8; + if (type == environment.Boolean || type == environment.UInt8 || type == environment.Int8) + { + return 1; + } + + if (type == environment.UInt16 || type == environment.Int16) + { + return 2; + } + + if (type == environment.UInt32 || type == environment.Int32 || type == environment.Float32) + { + return 4; + } + + if (type == environment.UInt64 || type == environment.Int64 || type == environment.Float64) + { + return 8; + } - int size = 0; + var size = 0; foreach (var field in type.Fields) { size += SizeOf(field.FieldType, environment); diff --git a/Source/Backlang.Contracts/TypeSystem/BooleanType.cs b/Source/Backlang.Contracts/TypeSystem/BooleanType.cs index a6d5702..2139c8e 100644 --- a/Source/Backlang.Contracts/TypeSystem/BooleanType.cs +++ b/Source/Backlang.Contracts/TypeSystem/BooleanType.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class BooleanType : DescribedType { diff --git a/Source/Backlang.Contracts/TypeSystem/I16Type.cs b/Source/Backlang.Contracts/TypeSystem/I16Type.cs index aac7d39..c00a259 100644 --- a/Source/Backlang.Contracts/TypeSystem/I16Type.cs +++ b/Source/Backlang.Contracts/TypeSystem/I16Type.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class I16Type : DescribedType { diff --git a/Source/Backlang.Contracts/TypeSystem/I32Type.cs b/Source/Backlang.Contracts/TypeSystem/I32Type.cs index 6b71c78..09a0bd1 100644 --- a/Source/Backlang.Contracts/TypeSystem/I32Type.cs +++ b/Source/Backlang.Contracts/TypeSystem/I32Type.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class I32Type : DescribedType { diff --git a/Source/Backlang.Contracts/TypeSystem/I64Type.cs b/Source/Backlang.Contracts/TypeSystem/I64Type.cs index d8f3701..fec0ca2 100644 --- a/Source/Backlang.Contracts/TypeSystem/I64Type.cs +++ b/Source/Backlang.Contracts/TypeSystem/I64Type.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class I64Type : DescribedType { diff --git a/Source/Backlang.Contracts/TypeSystem/I8Type.cs b/Source/Backlang.Contracts/TypeSystem/I8Type.cs index f650b9e..5540025 100644 --- a/Source/Backlang.Contracts/TypeSystem/I8Type.cs +++ b/Source/Backlang.Contracts/TypeSystem/I8Type.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class I8Type : DescribedType { diff --git a/Source/Backlang.Contracts/TypeSystem/ObjectType.cs b/Source/Backlang.Contracts/TypeSystem/ObjectType.cs index eb6442c..4d82939 100644 --- a/Source/Backlang.Contracts/TypeSystem/ObjectType.cs +++ b/Source/Backlang.Contracts/TypeSystem/ObjectType.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class ObjectType : DescribedType { diff --git a/Source/Backlang.Contracts/TypeSystem/StringType.cs b/Source/Backlang.Contracts/TypeSystem/StringType.cs index c418705..7b3d3b0 100644 --- a/Source/Backlang.Contracts/TypeSystem/StringType.cs +++ b/Source/Backlang.Contracts/TypeSystem/StringType.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class StringType : DescribedType { diff --git a/Source/Backlang.Contracts/TypeSystem/U16Type.cs b/Source/Backlang.Contracts/TypeSystem/U16Type.cs index 4a44a43..929bc7f 100644 --- a/Source/Backlang.Contracts/TypeSystem/U16Type.cs +++ b/Source/Backlang.Contracts/TypeSystem/U16Type.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class U16Type : DescribedType { diff --git a/Source/Backlang.Contracts/TypeSystem/U32Type.cs b/Source/Backlang.Contracts/TypeSystem/U32Type.cs index 109e4a5..c17d21e 100644 --- a/Source/Backlang.Contracts/TypeSystem/U32Type.cs +++ b/Source/Backlang.Contracts/TypeSystem/U32Type.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class U32Type : DescribedType { diff --git a/Source/Backlang.Contracts/TypeSystem/U64Type.cs b/Source/Backlang.Contracts/TypeSystem/U64Type.cs index 80caf44..746e448 100644 --- a/Source/Backlang.Contracts/TypeSystem/U64Type.cs +++ b/Source/Backlang.Contracts/TypeSystem/U64Type.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class U64Type : DescribedType { diff --git a/Source/Backlang.Contracts/TypeSystem/U8Type.cs b/Source/Backlang.Contracts/TypeSystem/U8Type.cs index adb222d..51c3ca9 100644 --- a/Source/Backlang.Contracts/TypeSystem/U8Type.cs +++ b/Source/Backlang.Contracts/TypeSystem/U8Type.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class U8Type : DescribedType { diff --git a/Source/Backlang.Contracts/TypeSystem/VoidType.cs b/Source/Backlang.Contracts/TypeSystem/VoidType.cs index 80c703d..f537778 100644 --- a/Source/Backlang.Contracts/TypeSystem/VoidType.cs +++ b/Source/Backlang.Contracts/TypeSystem/VoidType.cs @@ -1,8 +1,4 @@ -using Furesoft.Core.CodeDom.Compiler.Core; -using Furesoft.Core.CodeDom.Compiler.Core.Names; -using Furesoft.Core.CodeDom.Compiler.Core.TypeSystem; - -namespace Backlang.Contracts.TypeSystem; +namespace Backlang.Contracts.TypeSystem; public class VoidType : DescribedType { diff --git a/Source/Backlang.Core/Backlang.Core.csproj b/Source/Backlang.Core/Backlang.Core.csproj index 180995e..f6e4fbc 100644 --- a/Source/Backlang.Core/Backlang.Core.csproj +++ b/Source/Backlang.Core/Backlang.Core.csproj @@ -1,27 +1,27 @@  - - net9.0 - enable - True - Furesoft, Backlang-Org - https://www.backlang-org/ - logo.png - https://github.com/Backlang-Org/Backlang - backlang - True - + + net9.0 + enable + True + Furesoft, Backlang-Org + https://www.backlang-org/ + logo.png + https://github.com/Backlang-Org/Backlang + backlang + True + - - - + + + - - - True - \ - - - - + + + True + \ + + + + diff --git a/Source/Backlang.Core/Macros/BuiltInMacros.cs b/Source/Backlang.Core/Macros/BuiltInMacros.cs index 8245199..03862fb 100644 --- a/Source/Backlang.Core/Macros/BuiltInMacros.cs +++ b/Source/Backlang.Core/Macros/BuiltInMacros.cs @@ -8,7 +8,7 @@ namespace Backlang.Core.Macros; [ContainsMacros] public static partial class BuiltInMacros { - private static LNodeFactory F = new LNodeFactory(EmptySourceFile.Synthetic); + private static readonly LNodeFactory F = new(EmptySourceFile.Synthetic); [LexicalMacro("todo", "Add hint to do something", "todo")] public static LNode Todo(LNode node, IMacroContext context) @@ -39,11 +39,14 @@ public static LNode Refactor(LNode node, IMacroContext context) } [LexicalMacro(@"nameof(id_or_expr)", - @"Converts the 'key' name component of an expression to a string (e.g. nameof(A.B(D)) == ""B"")", "nameof", Mode = MacroMode.MatchIdentifierOrCall)] - public static LNode @Nameof(LNode nameof, IMacroContext context) + @"Converts the 'key' name component of an expression to a string (e.g. nameof(A.B(D)) == ""B"")", "nameof", + Mode = MacroMode.MatchIdentifierOrCall)] + public static LNode Nameof(LNode nameof, IMacroContext context) { if (nameof.ArgCount != 1) + { return null; + } var arg = nameof.Args[0]; if (arg.IsCall) @@ -57,6 +60,7 @@ public static LNode @Nameof(LNode nameof, IMacroContext context) return arg.Args[1]; } + if (arg.Name == (Symbol)"::") { if (arg.Args[1].IsCall) @@ -66,7 +70,8 @@ public static LNode @Nameof(LNode nameof, IMacroContext context) return arg.Args[1]; } - else if (arg.Target.IsId) + + if (arg.Target.IsId) { return arg.Target; } @@ -75,11 +80,14 @@ public static LNode @Nameof(LNode nameof, IMacroContext context) return arg; } - [LexicalMacro("concatId(id, id)", "Concats 2 Ids to a new Id (eg. concatId(a, b) == ab)", "concatId", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro("concatId(id, id)", "Concats 2 Ids to a new Id (eg. concatId(a, b) == ab)", "concatId", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode concatId(LNode concatID, IMacroContext context) { if (concatID.ArgCount < 2) + { return null; + } var sb = new StringBuilder(); @@ -99,8 +107,8 @@ public static LNode concatId(LNode concatID, IMacroContext context) } [LexicalMacro("$variableName", - "Expands a variable (scoped property) assigned by a macro such as `static deconstruct()` or `static tryDeconstruct()`.", - "'$", Mode = MacroMode.Passive)] + "Expands a variable (scoped property) assigned by a macro such as `static deconstruct()` or `static tryDeconstruct()`.", + "'$", Mode = MacroMode.Passive)] public static LNode DollarSignVariable(LNode node, IMacroContext context) { LNode id; @@ -110,20 +118,24 @@ public static LNode DollarSignVariable(LNode node, IMacroContext context) if (context.ScopedProperties.TryGetValue("$" + id.Name.Name, out value)) { if (value is LNode) + { return ((LNode)value).WithRange(id.Range); - else - context.Sink.Warning(id, "The specified scoped property is not a syntax tree. " + - "Use `#getScopedProperty({0})` to insert it as a literal.", id.Name); + } + + context.Sink.Warning(id, "The specified scoped property is not a syntax tree. " + + "Use `#getScopedProperty({0})` to insert it as a literal.", id.Name); } else { context.Sink.Error(id, "There is no macro property in scope named `{0}`", id.Name); } } + return null; } - [LexicalMacro("left <-> right", "Swaps the values of the two variables", "'<->", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro("left <-> right", "Swaps the values of the two variables", "'<->", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode Swap(LNode node, IMacroContext context) { var left = node.Args[0]; @@ -131,13 +143,15 @@ public static LNode Swap(LNode node, IMacroContext context) var temp = GenerateId(null, context); return LNode.Call(CodeSymbols.Braces, LNode.List( - LNode.Call(CodeSymbols.Var, LNode.List(LNode.Missing, LNode.Call(CodeSymbols.Assign, LNode.List(temp, left)))), + LNode.Call(CodeSymbols.Var, + LNode.List(LNode.Missing, LNode.Call(CodeSymbols.Assign, LNode.List(temp, left)))), LNode.Call(CodeSymbols.Assign, LNode.List(left, right)), LNode.Call(CodeSymbols.Assign, LNode.List(right, temp)) - )).SetStyle(NodeStyle.StatementBlock); + )).SetStyle(NodeStyle.StatementBlock); } - [LexicalMacro("generateId()", "Generates a new Id (eg. generateId() == a0)", "generateId", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro("generateId()", "Generates a new Id (eg. generateId() == a0)", "generateId", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode GenerateId(LNode generateID, IMacroContext context) { var alphabet = "abcdefghijklmnopqrstuvwxyz_"; @@ -148,6 +162,6 @@ public static LNode GenerateId(LNode generateID, IMacroContext context) sb.Append(Random.Shared.Next(0, alphabet.Length)); } - return F.Id("_" + sb.ToString() + context.IncrementTempCounter()); + return F.Id("_" + sb + context.IncrementTempCounter()); } } \ No newline at end of file diff --git a/Source/Backlang.Core/Macros/QuoteMacro.cs b/Source/Backlang.Core/Macros/QuoteMacro.cs index 5b0d78f..5e885cc 100644 --- a/Source/Backlang.Core/Macros/QuoteMacro.cs +++ b/Source/Backlang.Core/Macros/QuoteMacro.cs @@ -10,31 +10,38 @@ public partial class BuiltInMacros { private static readonly LNode _CodeSymbols = F.Id("CodeSymbols"); - private static Dictionary CodeSymbolTable = null; + private static Dictionary CodeSymbolTable; [LexicalMacro("quote(code); quote { code(); }", - "Macro-based code quote mechanism, to be used as long as a more complete compiler is not availabe. " + + "Macro-based code quote mechanism, to be used as long as a more complete compiler is not availabe. " + "If there is a single parameter that is braces, the braces are stripped out. " + "If there are multiple parameters, or multiple statements in braces, the result is a call to #splice(). " + "The output refers unqualified to `CodeSymbols` and `LNode` so you must have 'using Loyc.Syntax' at the top of your file. " + "The substitution operator $(expr) causes the specified expression to be inserted unchanged into the output.", "quote", "#quote")] - public static LNode Quote(LNode node, IMessageSink sink) => Quote(node, true, true); - - /// This implements `quote` and related macros. It converts a - /// Loyc tree (e.g. `Foo(this)`) into a piece of .NET code that can - /// construct the essence of the same tree (e.g. - /// `LNode.Call((Symbol) "Foo", LNode.List(LNode.Id(CodeSymbols.This)));`), - /// although this code does not preserve the Range properties. - /// If this flag is true, when a calls to - /// @`'$` is encountered, it is treated as a substitution request, - /// e.g. $node causes node to be included unchanged in the - /// output, and by example, Foo($x, $(..list)) produces this tree: - /// LNode.Call((Symbol) "Foo", LNode.List().Add(x).AddRange(list)). - /// - /// If this flag is true, the output expression - /// does not construct trivia attributes. - /// The quoted form. + public static LNode Quote(LNode node, IMessageSink sink) + { + return Quote(node, true, true); + } + + /// + /// This implements `quote` and related macros. It converts a + /// Loyc tree (e.g. `Foo(this)`) into a piece of .NET code that can + /// construct the essence of the same tree (e.g. + /// `LNode.Call((Symbol) "Foo", LNode.List(LNode.Id(CodeSymbols.This)));`), + /// although this code does not preserve the Range properties. + /// + /// If this flag is true, when a calls to + /// @`'$` is encountered, it is treated as a substitution request, + /// e.g. $node causes node to be included unchanged in the + /// output, and by example, Foo($x, $(..list)) produces this tree: + /// LNode.Call((Symbol) "Foo", LNode.List().Add(x).AddRange(list)). + /// + /// + /// If this flag is true, the output expression + /// does not construct trivia attributes. + /// + /// The quoted form. public static LNode Quote(LNode node, bool allowSubstitutions, bool ignoreTrivia) { LNode code = node, arg; @@ -45,51 +52,75 @@ public static LNode Quote(LNode node, bool allowSubstitutions, bool ignoreTrivia // can still write quote {{...}} to include braces in the output. code = arg; } + return new CodeQuoter(allowSubstitutions, ignoreTrivia).Quote(code.Args.AsLNode(S.Splice)); } - [LexicalMacro(@"e.g. quoteWithTrivia(/* cool! */ $foo) ==> foo.PlusAttrs(LNode.List(LNode.Trivia(CodeSymbols.TriviaMLComment, "" cool! "")))", + [LexicalMacro( + @"e.g. quoteWithTrivia(/* cool! */ $foo) ==> foo.PlusAttrs(LNode.List(LNode.Trivia(CodeSymbols.TriviaMLComment, "" cool! "")))", "Behaves the same as quote(code) except that trivia is included in the output.")] - public static LNode QuoteWithTrivia(LNode node, IMessageSink sink) => Quote(node, true, false); + public static LNode QuoteWithTrivia(LNode node, IMessageSink sink) + { + return Quote(node, true, false); + } [LexicalMacro(@"e.g. rawQuote($foo) ==> F.Call(CodeSymbols.Substitute, F.Id(""foo""));", - "Behaves the same as quote(code) except that the substitution operator $ is not recognized as a request for substitution.", + "Behaves the same as quote(code) except that the substitution operator $ is not recognized as a request for substitution.", "rawQuote", "#rawQuote")] - public static LNode RawQuote(LNode node, IMessageSink sink) => Quote(node, false, true); + public static LNode RawQuote(LNode node, IMessageSink sink) + { + return Quote(node, false, true); + } - [LexicalMacro(@"e.g. rawQuoteWithTrivia(/* cool! */ $foo) ==> LNode.Call(LNode.List(LNode.Trivia(CodeSymbols.TriviaMLComment, "" cool! "")), CodeSymbols.Substitute, LNode.List(LNode.Id((Symbol) ""foo"")))", + [LexicalMacro( + @"e.g. rawQuoteWithTrivia(/* cool! */ $foo) ==> LNode.Call(LNode.List(LNode.Trivia(CodeSymbols.TriviaMLComment, "" cool! "")), CodeSymbols.Substitute, LNode.List(LNode.Id((Symbol) ""foo"")))", "Behaves the same as rawQuote(code) except that trivia is included in the output.")] - public static LNode RawQuoteWithTrivia(LNode node, IMessageSink sink) => Quote(node, false, false); + public static LNode RawQuoteWithTrivia(LNode node, IMessageSink sink) + { + return Quote(node, false, false); + } internal static LNode QuoteSymbol(Symbol name) { if (CodeSymbolTable == null) + { CodeSymbolTable = FindStaticReadOnlies(typeof(CodeSymbols), fInfo => !fInfo.Name.StartsWith("_")); + } + if (CodeSymbolTable.TryGetValue(name, out var field)) + { return F.Dot(_CodeSymbols, F.Id(field)); - else - return F.Call(S.Cast, F.Literal(name.Name), F.Id("Symbol")); + } + + return F.Call(S.Cast, F.Literal(name.Name), F.Id("Symbol")); } - /// Helper function that finds the static readonly fields of a given - /// type in a given class, and creates a table from the _values_ of those - /// fields to the _names_ of those fields. + /// + /// Helper function that finds the static readonly fields of a given + /// type in a given class, and creates a table from the _values_ of those + /// fields to the _names_ of those fields. + /// private static Dictionary FindStaticReadOnlies(Type type, Predicate filter = null) { var dict = new Dictionary(); var list = type.GetFields(BindingFlags.Static | BindingFlags.Public) .Where(field => typeof(T).IsAssignableFrom(field.FieldType) && field.IsInitOnly - && field.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length == 0); + && field.GetCustomAttributes( + typeof(ObsoleteAttribute), true).Length == + 0); foreach (var field in list) + { if (filter == null || filter(field)) + { dict[(T)field.GetValue(null)] = GSymbol.Get(field.Name); + } + } + return dict; } public class CodeQuoter { - public bool _doSubstitutions; - public bool _ignoreTrivia; private static readonly LNode CodeSymbols_Splice = F.Dot(_CodeSymbols, F.Id("Splice")); private static readonly LNode Id_LNode = F.Id("LNode"); @@ -113,9 +144,11 @@ public class CodeQuoter private static readonly LNode LNode_Missing = F.Dot(Id_LNode, F.Id("Missing")); private static readonly LNode LNode_Trivia = F.Dot(Id_LNode, F.Id("Trivia")); + public bool _doSubstitutions; + public bool _ignoreTrivia; public CodeQuoter( - bool doSubstitutions, + bool doSubstitutions, bool ignoreTrivia = true) { _doSubstitutions = doSubstitutions; @@ -125,16 +158,23 @@ public CodeQuoter( public LNode Quote(LNode node) { if (node.Equals(LNode.InParensTrivia)) + { return LNode_InParensTrivia; + } + if (node.Equals(LNode.Missing)) + { return LNode_Missing; + } - LNodeList creationArgs = new LNodeList(); + var creationArgs = new LNodeList(); // Translate attributes (if any) - var attrList = MaybeQuoteList(node.Attrs, isAttributes: true); + var attrList = MaybeQuoteList(node.Attrs, true); if (attrList != null) + { creationArgs.Add(attrList); + } LNode result; switch (node.Kind) @@ -150,7 +190,7 @@ public LNode Quote(LNode node) break; default: // NodeKind.Call => F.Dot(...), F.Of(...), F.Call(...), F.Braces(...) - bool preserveStyle = true; + var preserveStyle = true; if (_doSubstitutions && node.Calls(S.Substitute, 1)) { preserveStyle = false; @@ -158,41 +198,59 @@ public LNode Quote(LNode node) if (attrList != null) { if (result.IsCall) + { result = result.InParens(); + } + result = F.Call(F.Dot(result, Id_PlusAttrs), attrList); } } - else if (!_ignoreTrivia && node.ArgCount == 1 && node.TriviaValue != NoValue.Value && node.Target.IsId) + else if (!_ignoreTrivia && node.ArgCount == 1 && node.TriviaValue != NoValue.Value && + node.Target.IsId) { // LNode.Trivia(Symbol, object) result = F.Call(LNode_Trivia, QuoteSymbol(node.Name), F.Literal(node.TriviaValue)); } /*else if (node.Calls(S.Braces)) // F.Braces(...) - result = F.Call(LNode_Braces, node.Args.SmartSelect(arg => QuoteOne(arg, substitutions))); - else if (node.Calls(S.Dot) && node.ArgCount.IsInRange(1, 2)) - result = F.Call(LNode_Dot, node.Args.SmartSelect(arg => QuoteOne(arg, substitutions))); - else if (node.Calls(S.Of)) - result = F.Call(LNode_Of, node.Args.SmartSelect(arg => QuoteOne(arg, substitutions)));*/ + result = F.Call(LNode_Braces, node.Args.SmartSelect(arg => QuoteOne(arg, substitutions))); + else if (node.Calls(S.Dot) && node.ArgCount.IsInRange(1, 2)) + result = F.Call(LNode_Dot, node.Args.SmartSelect(arg => QuoteOne(arg, substitutions))); + else if (node.Calls(S.Of)) + result = F.Call(LNode_Of, node.Args.SmartSelect(arg => QuoteOne(arg, substitutions)));*/ else { // General case: F.Call(, ) if (node.Target.IsId) + { creationArgs.Add(QuoteSymbol(node.Name)); + } else + { creationArgs.Add(Quote(node.Target)); + } var argList = MaybeQuoteList(node.Args); if (argList != null) + { creationArgs.Add(argList); + } + result = F.Call(LNode_Call, creationArgs); } + // Note: don't preserve prefix notation because if $op is +, // we want $op(x, y) to generate code for x + y (there is no // way to express this with infix notation.) - if (preserveStyle && node.BaseStyle != NodeStyle.Default && node.BaseStyle != NodeStyle.PrefixNotation) - result = F.Call(F.Dot(result, F.Id("SetStyle")), F.Dot(F.Id("NodeStyle"), F.Id(node.BaseStyle.ToString()))); + if (preserveStyle && node.BaseStyle != NodeStyle.Default && + node.BaseStyle != NodeStyle.PrefixNotation) + { + result = F.Call(F.Dot(result, F.Id("SetStyle")), + F.Dot(F.Id("NodeStyle"), F.Id(node.BaseStyle.ToString()))); + } + break; } + return result; } @@ -200,35 +258,52 @@ private static LNode VarArgExpr(LNode arg) { LNode subj; if (arg.Calls(S.Substitute, 1) && ((subj = arg.Args[0]).Calls(S.DotDot, 1) || subj.Calls(S.DotDotDot, 1))) + { return subj.Args[0]; + } + return null; } private LNode MaybeQuoteList(LNodeList list, bool isAttributes = false) { if (isAttributes && _ignoreTrivia) + { list = list.SmartWhere(n => !n.IsTrivia || n.IsIdNamed(S.TriviaInParens)); + } + if (list.IsEmpty) + { return null; - else if (_doSubstitutions && list.Any(a => VarArgExpr(a) != null)) + } + + if (_doSubstitutions && list.Any(a => VarArgExpr(a) != null)) { if (list.Count == 1) + { return F.Call(LNode_List, VarArgExpr(list[0])); + } + // If you write something like quote(Foo($x, $(...y), $z)), a special // output style is used to accommodate the variable argument list. - LNode argList = F.Call(LNode_List); - foreach (LNode arg in list) + var argList = F.Call(LNode_List); + foreach (var arg in list) { var vae = VarArgExpr(arg); if (vae != null) + { argList = F.Call(F.Dot(argList, F.Id("AddRange")), vae); + } else + { argList = F.Call(F.Dot(argList, F.Id("Add")), Quote(arg)); + } } + return argList; } - else - return F.Call(LNode_List, list.SmartSelect(item => Quote(item))); + + return F.Call(LNode_List, list.SmartSelect(item => Quote(item))); } } } \ No newline at end of file diff --git a/Source/Backlang.Core/Result.cs b/Source/Backlang.Core/Result.cs index 3a1f07e..dd073c2 100644 --- a/Source/Backlang.Core/Result.cs +++ b/Source/Backlang.Core/Result.cs @@ -1,26 +1,25 @@ using System.Runtime.CompilerServices; -namespace Backlang.Core +namespace Backlang.Core; + +public class Result { - public class Result - { - private readonly T? _value; + private readonly T? _value; - public Result(T value) - { - _value = value; - } + public Result(T value) + { + _value = value; + } - public static implicit operator T(Result value) - { - return value._value; - } + public static implicit operator T(Result value) + { + return value._value; + } - //Unpacking operator - [SpecialName] - public static bool op_Unpacking(Result value) - { - return value._value != null; - } + //Unpacking operator + [SpecialName] + public static bool op_Unpacking(Result value) + { + return value._value != null; } } \ No newline at end of file diff --git a/Source/Backlang.Core/Sealed.cs b/Source/Backlang.Core/Sealed.cs index 8b88cdc..ecca4c7 100644 --- a/Source/Backlang.Core/Sealed.cs +++ b/Source/Backlang.Core/Sealed.cs @@ -24,6 +24,7 @@ public void Set(T value) { throw new InvalidOperationException("Object is freezed"); } + _value = value; } @@ -43,4 +44,4 @@ public static T op_Unpacking(Sealed value) { return value._value; } -} +} \ No newline at end of file diff --git a/Source/Backlang.Driver/Backlang.Driver.csproj b/Source/Backlang.Driver/Backlang.Driver.csproj index bb33be6..a9c7a57 100644 --- a/Source/Backlang.Driver/Backlang.Driver.csproj +++ b/Source/Backlang.Driver/Backlang.Driver.csproj @@ -1,54 +1,54 @@  - - net9.0 - enable - preview - True - True - Furesoft, Backlang-Org - https://www.backlang-org/ - logo.png - https://github.com/Backlang-Org/Backlang - backlang - True - The Backlang Compiler Chain - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - True - \ - - - + + net9.0 + enable + preview + True + True + Furesoft, Backlang-Org + https://www.backlang-org/ + logo.png + https://github.com/Backlang-Org/Backlang + backlang + True + The Backlang Compiler Chain + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + True + \ + + + diff --git a/Source/Backlang.Driver/BinderExtensions.cs b/Source/Backlang.Driver/BinderExtensions.cs index 2ff9545..2d022cf 100644 --- a/Source/Backlang.Driver/BinderExtensions.cs +++ b/Source/Backlang.Driver/BinderExtensions.cs @@ -7,7 +7,7 @@ public static class BinderExtensions private static readonly ConcurrentDictionary _functionCache = new(); /// - /// Finds a method based on a selector + /// Finds a method based on a selector /// /// /// System.StringBuilder::AppendLine(System.String) @@ -22,18 +22,19 @@ public static IMethod FindFunction(this TypeResolver binder, string selector) var convertedSelector = GetSelector(selector); var type = binder.ResolveTypes(convertedSelector.Typename)?.FirstOrDefault(); - - if(type == null) { + + if (type == null) + { throw new Exception($"Type '{type.FullName}' not found"); } - + var methods = type.Methods .Where(_ => _.Name.ToString() == convertedSelector.FunctionName) .Where(_ => _.Parameters.Count == convertedSelector.ParameterTypes.Length); foreach (var method in methods) { - for (int i = 0; i < method.Parameters.Count; i++) + for (var i = 0; i < method.Parameters.Count; i++) { if (method.Parameters[i].Type.FullName.ToString() == convertedSelector.ParameterTypes[i]) { diff --git a/Source/Backlang.Driver/CompilerDriver.cs b/Source/Backlang.Driver/CompilerDriver.cs index 90526ac..da47cc2 100644 --- a/Source/Backlang.Driver/CompilerDriver.cs +++ b/Source/Backlang.Driver/CompilerDriver.cs @@ -1,64 +1,68 @@ -namespace Backlang.Driver; +using Flo; + +namespace Backlang.Driver; public class CompilerDriver { public static async void Compile(CompilerContext context) { if (string.IsNullOrEmpty(context.TempOutputPath)) + { context.TempOutputPath = Environment.CurrentDirectory; + } var hasError = (List messages) => messages.Any(_ => _.Severity == MessageSeverity.Error); - var pipeline = Flo.Pipeline.Build( - cfg => { - cfg.When(_ => _.Options.WaitForDebugger, _ => { - _.Add(); - }); + var pipeline = Pipeline.Build( + cfg => { + cfg.When(_ => _.Options.WaitForDebugger, _ => { + _.Add(); + }); - cfg.Add(); - cfg.Add(); + cfg.Add(); + cfg.Add(); - cfg.When(_ => !hasError(_.Messages) && _.Options.OutputTree, _ => { - _.Add(); - }); + cfg.When(_ => !hasError(_.Messages) && _.Options.OutputTree, _ => { + _.Add(); + }); - cfg.When(_ => !hasError(_.Messages), _ => { - _.Add(); - }); + cfg.When(_ => !hasError(_.Messages), _ => { + _.Add(); + }); - cfg.When(_ => !hasError(_.Messages), _ => { - _.Add(); - }); + cfg.When(_ => !hasError(_.Messages), _ => { + _.Add(); + }); - cfg.When(_ => !hasError(_.Messages), _ => { - _.Add(); - }); + cfg.When(_ => !hasError(_.Messages), _ => { + _.Add(); + }); - cfg.When(_ => !hasError(_.Messages), _ => { - _.Add(); - }); + cfg.When(_ => !hasError(_.Messages), _ => { + _.Add(); + }); - cfg.When(_ => !hasError(_.Messages), _ => { - _.Add(); - }); + cfg.When(_ => !hasError(_.Messages), _ => { + _.Add(); + }); - cfg.When(_ => !hasError(_.Messages), _ => { - _.Add(); - }); + cfg.When(_ => !hasError(_.Messages), _ => { + _.Add(); + }); - cfg.When(_ => !hasError(_.Messages), _ => { - _.Add(); - }); + cfg.When(_ => !hasError(_.Messages), _ => { + _.Add(); + }); - cfg.When(_ => !hasError(_.Messages), _ => { - _.Add(); - }); + cfg.When(_ => !hasError(_.Messages), _ => { + _.Add(); + }); - cfg.When(_ => _.Messages.Any(), _ => { - _.Add(); - }); - } - ); + cfg.When(_ => _.Messages.Any(), _ => { + _.Add(); + }); + } + ); await pipeline.Invoke(context); } diff --git a/Source/Backlang.Driver/Compiling/Attributes.cs b/Source/Backlang.Driver/Compiling/Attributes.cs index 2723e70..5b677b1 100644 --- a/Source/Backlang.Driver/Compiling/Attributes.cs +++ b/Source/Backlang.Driver/Compiling/Attributes.cs @@ -1,5 +1,6 @@ namespace Backlang.Driver.Compiling; + public static class Attributes { public static readonly IAttribute Mutable = new IntrinsicAttribute("mutable"); -} +} \ No newline at end of file diff --git a/Source/Backlang.Driver/Compiling/IRGenerator.cs b/Source/Backlang.Driver/Compiling/IRGenerator.cs index 84a8c53..4a16816 100644 --- a/Source/Backlang.Driver/Compiling/IRGenerator.cs +++ b/Source/Backlang.Driver/Compiling/IRGenerator.cs @@ -3,13 +3,12 @@ using Furesoft.Core.CodeDom.Compiler.Flow; using Furesoft.Core.CodeDom.Compiler.Instructions; using Furesoft.Core.CodeDom.Compiler.TypeSystem; -using System.Numerics; namespace Backlang.Driver.Compiling; public static class IRGenerator { - private static readonly int[] _primes = new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41}; + private static readonly int[] _primes = new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41 }; public static void GenerateGetHashCode(CompilerContext context, DescribedType type) { @@ -49,20 +48,24 @@ public static void GenerateGetHashCode(CompilerContext context, DescribedType ty ) ); - var multiplication = block.AppendInstruction(Instruction.CreateBinaryArithmeticIntrinsic("*", false, context.Environment.Int32, hash, c)); + var multiplication = block.AppendInstruction( + Instruction.CreateBinaryArithmeticIntrinsic("*", false, context.Environment.Int32, hash, c)); block.AppendInstruction(Instruction.CreateLoadArg(new Parameter(type))); var instruction = Instruction.CreateLoadField(field); - if (field.FieldType.BaseTypes.Count() > 0 && field.FieldType.BaseTypes[0].FullName.ToString() == "System.ValueType") + if (field.FieldType.BaseTypes.Count() > 0 && + field.FieldType.BaseTypes[0].FullName.ToString() == "System.ValueType") { instruction = Instruction.CreateGetFieldPointer(field, null); } var ldField = block.AppendInstruction(instruction); - var call = block.AppendInstruction(Instruction.CreateCall(method, MethodLookup.Virtual, new List() { ldField })); + var call = block.AppendInstruction(Instruction.CreateCall(method, MethodLookup.Virtual, + new List { ldField })); - var addition = block.AppendInstruction(Instruction.CreateBinaryArithmeticIntrinsic("+", false, context.Environment.Int32, ldField, multiplication)); + var addition = block.AppendInstruction(Instruction.CreateBinaryArithmeticIntrinsic("+", false, + context.Environment.Int32, ldField, multiplication)); block.AppendInstruction(Instruction.CreateStore(context.Environment.Int32, hash, addition)); } @@ -71,7 +74,8 @@ public static void GenerateGetHashCode(CompilerContext context, DescribedType ty block.AppendInstruction(Instruction.CreateLoadLocal(new Parameter(context.Environment.Int32, "hash"))); block.Flow = new ReturnFlow(); - gethashcodeMethod.Body = new MethodBody(new Parameter(), new Parameter(type), EmptyArray.Value, graph.ToImmutable()); + gethashcodeMethod.Body = new MethodBody(new Parameter(), new Parameter(type), EmptyArray.Value, + graph.ToImmutable()); type.AddMethod(gethashcodeMethod); } @@ -82,7 +86,8 @@ private static int SelectPrime() public static void GenerateToString(CompilerContext context, DescribedType type) { - var toStringMethod = new DescribedBodyMethod(type, new SimpleName("ToString"), false, Utils.ResolveType(context.Binder, typeof(string))); + var toStringMethod = new DescribedBodyMethod(type, new SimpleName("ToString"), false, + Utils.ResolveType(context.Binder, typeof(string))); toStringMethod.IsPublic = true; toStringMethod.IsOverride = true; @@ -114,29 +119,31 @@ public static void GenerateToString(CompilerContext context, DescribedType type) AppendLine(context, block, appendLineMethod, loadSbf, field.Name + " = "); var value = AppendLoadField(block, field); - var appendMethod = context.Binder.FindFunction($"System.Text.StringBuilder::Append({field.FieldType.FullName})"); + var appendMethod = + context.Binder.FindFunction($"System.Text.StringBuilder::Append({field.FieldType.FullName})"); appendMethod ??= context.Binder.FindFunction("System.Text.StringBuilder::Append(System.Object)"); - block.AppendInstruction(Instruction.CreateCall(appendMethod, MethodLookup.Virtual, new List { loadSbf, value })); + block.AppendInstruction(Instruction.CreateCall(appendMethod, MethodLookup.Virtual, + new List { loadSbf, value })); } - var tsM = context.Binder.FindFunction($"System.Text.StringBuilder::ToString()"); + var tsM = context.Binder.FindFunction("System.Text.StringBuilder::ToString()"); block.AppendInstruction(Instruction.CreateCall(tsM, MethodLookup.Virtual, new List { loadSb })); block.Flow = new ReturnFlow(); - toStringMethod.Body = new MethodBody(new Parameter(), new Parameter(type), EmptyArray.Value, graph.ToImmutable()); + toStringMethod.Body = new MethodBody(new Parameter(), new Parameter(type), EmptyArray.Value, + graph.ToImmutable()); type.AddMethod(toStringMethod); } public static void GenerateEmptyCtor(CompilerContext context, DescribedType type) { - var ctorMethod = new DescribedBodyMethod(type, new SimpleName(".ctor"), false, Utils.ResolveType(context.Binder, typeof(void))) - { - IsConstructor = true - }; + var ctorMethod = + new DescribedBodyMethod(type, new SimpleName(".ctor"), false, + Utils.ResolveType(context.Binder, typeof(void))) { IsConstructor = true }; ctorMethod.IsPublic = true; @@ -146,17 +153,17 @@ public static void GenerateEmptyCtor(CompilerContext context, DescribedType type block.Flow = new ReturnFlow(); - ctorMethod.Body = new MethodBody(new Parameter(), Parameter.CreateThisParameter(type), EmptyArray.Value, graph.ToImmutable()); + ctorMethod.Body = new MethodBody(new Parameter(), Parameter.CreateThisParameter(type), + EmptyArray.Value, graph.ToImmutable()); type.AddMethod(ctorMethod); } public static void GenerateDefaultCtor(CompilerContext context, DescribedType type) { - var ctorMethod = new DescribedBodyMethod(type, new SimpleName(".ctor"), false, Utils.ResolveType(context.Binder, typeof(void))) - { - IsConstructor = true - }; + var ctorMethod = + new DescribedBodyMethod(type, new SimpleName(".ctor"), false, + Utils.ResolveType(context.Binder, typeof(void))) { IsConstructor = true }; ctorMethod.IsPublic = true; @@ -182,7 +189,8 @@ public static void GenerateDefaultCtor(CompilerContext context, DescribedType ty block.Flow = new ReturnFlow(); - ctorMethod.Body = new MethodBody(new Parameter(), Parameter.CreateThisParameter(type), EmptyArray.Value, graph.ToImmutable()); + ctorMethod.Body = new MethodBody(new Parameter(), Parameter.CreateThisParameter(type), + EmptyArray.Value, graph.ToImmutable()); type.AddMethod(ctorMethod); } @@ -199,12 +207,14 @@ private static NamedInstructionBuilder AppendLoadField(BasicBlockBuilder block, return value; } - private static void AppendLine(CompilerContext context, BasicBlockBuilder block, IMethod appendLineMethod, NamedInstructionBuilder argLoad, string valueStr) + private static void AppendLine(CompilerContext context, BasicBlockBuilder block, IMethod appendLineMethod, + NamedInstructionBuilder argLoad, string valueStr) { var va = block.AppendInstruction( - Instruction.CreateConstant(new StringConstant(valueStr), context.Environment.String)); + Instruction.CreateConstant(new StringConstant(valueStr), context.Environment.String)); var value = block.AppendInstruction(Instruction.CreateLoad(context.Environment.String, va)); - block.AppendInstruction(Instruction.CreateCall(appendLineMethod, MethodLookup.Virtual, new List { argLoad, value })); + block.AppendInstruction(Instruction.CreateCall(appendLineMethod, MethodLookup.Virtual, + new List { argLoad, value })); } } \ No newline at end of file diff --git a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/CompileTargetStage.cs b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/CompileTargetStage.cs index 245b042..9397681 100644 --- a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/CompileTargetStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/CompileTargetStage.cs @@ -9,14 +9,17 @@ namespace Backlang.Driver.Compiling.Stages.CompilationStages; public sealed class CompileTargetStage : IHandler { - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { context.Trees = null; var description = GetDescription(context); if (context.Options.Version != null) - context.Assembly.AddAttribute(new VersionAttribute() { Version = Version.Parse(context.Options.Version) }); + { + context.Assembly.AddAttribute(new VersionAttribute { Version = Version.Parse(context.Options.Version) }); + } context.CompilationTarget.BeforeCompiling(context); @@ -25,7 +28,7 @@ public async Task HandleAsync(CompilerContext context, Func _implementations = new Dictionary() - { - [CodeSymbols.Var] = new VariableImplementor(), - [CodeSymbols.Assign] = new AssignmentImplementor(), - [CodeSymbols.If] = new IfImplementor(), - [CodeSymbols.While] = new WhileImplementor(), - [CodeSymbols.DoWhile] = new DoWhileImplementor(), - [CodeSymbols.Return] = new ReturnImplementor(), - [CodeSymbols.Continue] = new ContinueStatementImplementor(), - [CodeSymbols.Break] = new BreakStatementImplementor(), - [CodeSymbols.Throw] = new ThrowImplementor(), - [CodeSymbols.ColonColon] = new StaticCallImplementor(), - [CodeSymbols.Dot] = new CallImplementor(), - [(Symbol)"print"] = new PrintOrPrintlnImplementor(), - [(Symbol)"println"] = new PrintOrPrintlnImplementor(), - }.ToImmutableDictionary(); - - private static readonly ImmutableList _expressions = new List() + private static readonly ImmutableDictionary _implementations = + new Dictionary + { + [CodeSymbols.Var] = new VariableImplementor(), + [CodeSymbols.Assign] = new AssignmentImplementor(), + [CodeSymbols.If] = new IfImplementor(), + [CodeSymbols.While] = new WhileImplementor(), + [CodeSymbols.DoWhile] = new DoWhileImplementor(), + [CodeSymbols.Return] = new ReturnImplementor(), + [CodeSymbols.Continue] = new ContinueStatementImplementor(), + [CodeSymbols.Break] = new BreakStatementImplementor(), + [CodeSymbols.Throw] = new ThrowImplementor(), + [CodeSymbols.ColonColon] = new StaticCallImplementor(), + [CodeSymbols.Dot] = new CallImplementor(), + [(Symbol)"print"] = new PrintOrPrintlnImplementor(), + [(Symbol)"println"] = new PrintOrPrintlnImplementor() + }.ToImmutableDictionary(); + + private static readonly ImmutableList _expressions = new List { new TupleExpressionImplementor(), new ArrayExpressionImplementor(), @@ -45,12 +46,11 @@ public partial class ImplementationStage new PointerExpressionImplementor(), new ConstantExpressionEmitter(), new StaticCallImplementor(), - - new CallExpressionEmitter(), //should be added as last + new CallExpressionEmitter() //should be added as last }.ToImmutableList(); public static MethodBody CompileBody(LNode function, CompilerContext context, IMethod method, - QualifiedName? modulename, Scope scope) + QualifiedName? modulename, Scope scope) { var graph = Utils.CreateGraphBuilder(); var block = graph.EntryPoint; @@ -72,25 +72,34 @@ public static MethodBody CompileBody(LNode function, CompilerContext context, IM graph.ToImmutable()); } - public static BasicBlockBuilder AppendBlock(LNode blkNode, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels) + public static BasicBlockBuilder AppendBlock(LNode blkNode, BasicBlockBuilder block, CompilerContext context, + IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels) { block.Flow = new NothingFlow(); foreach (var node in blkNode.Args) { - if (!node.IsCall) continue; + if (!node.IsCall) + { + continue; + } if (node.Calls(CodeSymbols.Braces)) { - if (node.ArgCount == 0) continue; + if (node.ArgCount == 0) + { + continue; + } - block = AppendBlock(node, block.Graph.AddBasicBlock(), context, method, modulename, scope.CreateChildScope(), branchLabels); + block = AppendBlock(node, block.Graph.AddBasicBlock(), context, method, modulename, + scope.CreateChildScope(), branchLabels); continue; } if (_implementations.ContainsKey(node.Name)) { - block = _implementations[node.Name].Implement(node, block, context, method, modulename, scope, branchLabels); + block = _implementations[node.Name] + .Implement(node, block, context, method, modulename, scope, branchLabels); } else { @@ -113,7 +122,8 @@ public static NamedInstructionBuilder AppendExpression(BasicBlockBuilder block, } public static NamedInstructionBuilder AppendCall(CompilerContext context, BasicBlockBuilder block, - LNode node, IEnumerable methods, Scope scope, QualifiedName? modulename, bool shouldAppendError = true, string methodName = null) + LNode node, IEnumerable methods, Scope scope, QualifiedName? modulename, bool shouldAppendError = true, + string methodName = null) { var argTypes = new List(); @@ -122,7 +132,9 @@ public static NamedInstructionBuilder AppendCall(CompilerContext context, BasicB var type = TypeDeducer.Deduce(arg, scope, context, modulename.Value); if (type != null) + { argTypes.Add(type); + } } if (methodName == null) @@ -135,7 +147,8 @@ public static NamedInstructionBuilder AppendCall(CompilerContext context, BasicB return AppendCall(context, block, node, method, scope, modulename.Value); } - public static NamedInstructionBuilder AppendDtor(CompilerContext context, BasicBlockBuilder block, Scope scope, QualifiedName? modulename, string varname) + public static NamedInstructionBuilder AppendDtor(CompilerContext context, BasicBlockBuilder block, Scope scope, + QualifiedName? modulename, string varname) { if (scope.TryGet(varname, out var scopeItem)) { @@ -146,7 +159,8 @@ public static NamedInstructionBuilder AppendDtor(CompilerContext context, BasicB block.AppendInstruction(Instruction.CreateLoadLocal(scopeItem.Parameter)); - return AppendCall(context, block, LNode.Missing, scopeItem.Type.Methods, scope, modulename, false, "Finalize"); + return AppendCall(context, block, LNode.Missing, scopeItem.Type.Methods, scope, modulename, false, + "Finalize"); } return null; @@ -157,19 +171,24 @@ public static NamedInstructionBuilder AppendCall(CompilerContext context, BasicB { var callTags = AppendCallArguments(context, block, node, scope, modulename); - if (method == null) return null; + if (method == null) + { + return null; + } if (!method.IsStatic) { callTags.Insert(0, block.AppendInstruction(Instruction.CreateLoadArg(new Parameter(method.ParentType)))); } - var call = Instruction.CreateCall(method, method.IsStatic ? MethodLookup.Static : MethodLookup.Virtual, callTags); + var call = Instruction.CreateCall(method, method.IsStatic ? MethodLookup.Static : MethodLookup.Virtual, + callTags); return block.AppendInstruction(call); } - public static List AppendCallArguments(CompilerContext context, BasicBlockBuilder block, LNode node, Scope scope, QualifiedName? modulename) + public static List AppendCallArguments(CompilerContext context, BasicBlockBuilder block, LNode node, + Scope scope, QualifiedName? modulename) { var argTypes = new List(); var callTags = new List(); @@ -209,7 +228,8 @@ public static List AppendCallArguments(CompilerContext context, BasicB { var suggestion = LevensteinDistance.Suggest(arg.Name.Name, scope.GetAllScopeNames()); - context.AddError(arg, new(ErrorID.CannotBeFoundDidYouMean, arg.Name.Name, suggestion)); + context.AddError(arg, + new LocalizableString(ErrorID.CannotBeFoundDidYouMean, arg.Name.Name, suggestion)); } } } @@ -217,7 +237,8 @@ public static List AppendCallArguments(CompilerContext context, BasicB return callTags; } - public static void AppendAllDtors(BasicBlockBuilder block, CompilerContext context, QualifiedName? modulename, Scope scope) + public static void AppendAllDtors(BasicBlockBuilder block, CompilerContext context, QualifiedName? modulename, + Scope scope) { foreach (var v in block.Parameters) { @@ -225,7 +246,8 @@ public static void AppendAllDtors(BasicBlockBuilder block, CompilerContext conte } } - private static void SetReturnType(DescribedBodyMethod method, LNode function, CompilerContext context, Scope scope, QualifiedName modulename) + private static void SetReturnType(DescribedBodyMethod method, LNode function, CompilerContext context, Scope scope, + QualifiedName modulename) { var retType = function.Args[0]; @@ -239,11 +261,14 @@ private static void SetReturnType(DescribedBodyMethod method, LNode function, Co { var deducedReturnType = TypeDeducer.DeduceFunctionReturnType(function, context, scope, modulename); - method.ReturnParameter = deducedReturnType != null ? new Parameter(deducedReturnType) : new Parameter(Utils.ResolveType(context.Binder, typeof(void))); + method.ReturnParameter = deducedReturnType != null + ? new Parameter(deducedReturnType) + : new Parameter(Utils.ResolveType(context.Binder, typeof(void))); } } - private static BasicBlockBuilder EmitFunctionCall(IMethod method, LNode node, BasicBlockBuilder block, CompilerContext context, Scope scope, QualifiedName? moduleName) + private static BasicBlockBuilder EmitFunctionCall(IMethod method, LNode node, BasicBlockBuilder block, + CompilerContext context, Scope scope, QualifiedName? moduleName) { //ToDo: continue implementing static function call in same type var type = (DescribedType)method.ParentType; @@ -252,11 +277,12 @@ private static BasicBlockBuilder EmitFunctionCall(IMethod method, LNode node, Ba if (!methods.Any(_ => _.Name.ToString() == calleeName.ToString())) { - type = (DescribedType)context.Binder.ResolveTypes(new SimpleName(Names.FreeFunctions).Qualify(moduleName.Value)).FirstOrDefault(); + type = (DescribedType)context.Binder + .ResolveTypes(new SimpleName(Names.FreeFunctions).Qualify(moduleName.Value)).FirstOrDefault(); if (type == null) { - context.AddError(node, new(ErrorID.CannotFindFunction, calleeName.ToString())); + context.AddError(node, new LocalizableString(ErrorID.CannotFindFunction, calleeName.ToString())); } } @@ -264,7 +290,8 @@ private static BasicBlockBuilder EmitFunctionCall(IMethod method, LNode node, Ba { if (type.IsStatic && !callee.IsStatic) { - context.AddError(node, $"A non static function '{calleeName.Name.Name}' cannot be called in a static function."); + context.AddError(node, + $"A non static function '{calleeName.Name.Name}' cannot be called in a static function."); return block; } @@ -272,9 +299,11 @@ private static BasicBlockBuilder EmitFunctionCall(IMethod method, LNode node, Ba } else { - var suggestion = LevensteinDistance.Suggest(calleeName.Name.Name, type.Methods.Select(_ => _.Name.ToString())); + var suggestion = + LevensteinDistance.Suggest(calleeName.Name.Name, type.Methods.Select(_ => _.Name.ToString())); - context.AddError(node, new(ErrorID.CannotBeFoundDidYouMean, calleeName.Name.Name, suggestion)); + context.AddError(node, + new LocalizableString(ErrorID.CannotBeFoundDidYouMean, calleeName.Name.Name, suggestion)); } return block; @@ -286,7 +315,7 @@ private static void ConvertMethodBodies(CompilerContext context) { bodyCompilation.Method.Body = CompileBody(bodyCompilation.Function, context, - bodyCompilation.Method, bodyCompilation.Modulename, bodyCompilation.Scope); + bodyCompilation.Method, bodyCompilation.Modulename, bodyCompilation.Scope); } } } \ No newline at end of file diff --git a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/ImplementationStage.Helpers.cs b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/ImplementationStage.Helpers.cs index 32bcd96..3c60eca 100644 --- a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/ImplementationStage.Helpers.cs +++ b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/ImplementationStage.Helpers.cs @@ -5,14 +5,20 @@ namespace Backlang.Driver.Compiling.Stages.CompilationStages; public sealed partial class ImplementationStage : IHandler { + public enum ConditionalJumpKind + { + NotEquals, + Equals, + True, + False + } + public static ImmutableDictionary LiteralTypeMap = new Dictionary { [CodeSymbols.Object] = typeof(object), [CodeSymbols.Bool] = typeof(bool), - [CodeSymbols.String] = typeof(string), [CodeSymbols.Char] = typeof(char), - [CodeSymbols.Int8] = typeof(byte), [CodeSymbols.Int16] = typeof(short), [CodeSymbols.UInt16] = typeof(ushort), @@ -20,29 +26,20 @@ public sealed partial class ImplementationStage : IHandler argTypes) { //ToDo: fix matches parameter (implicit casting is currently not working) - bool matchesAllParameters = method.Parameters.Count == argTypes.Count; - for (int i = 0; i < argTypes.Count; i++) + var matchesAllParameters = method.Parameters.Count == argTypes.Count; + for (var i = 0; i < argTypes.Count; i++) { if (i == 0) { - matchesAllParameters = ImplicitTypeCastTable.IsAssignableTo(argTypes[i], method.Parameters[i].Type); + matchesAllParameters = argTypes[i].IsAssignableTo(method.Parameters[i].Type); continue; } - matchesAllParameters &= ImplicitTypeCastTable.IsAssignableTo(argTypes[i], method.Parameters[i].Type); + matchesAllParameters &= argTypes[i].IsAssignableTo(method.Parameters[i].Type); } return matchesAllParameters; } - public static IMethod GetMatchingMethod(CompilerContext context, List argTypes, IEnumerable methods, string methodname, bool shouldAppendError = true) + public static IMethod GetMatchingMethod(CompilerContext context, List argTypes, IEnumerable methods, + string methodname, bool shouldAppendError = true) { var candiates = new List(); foreach (var m in methods.Where(_ => _.Name.ToString() == methodname)) @@ -154,18 +152,22 @@ public static IMethod GetMatchingMethod(CompilerContext context, List arg if (m.Parameters.Count == argTypes.Count) { if (MatchesParameters(m, argTypes)) + { candiates.Add(m); + } } } if (shouldAppendError && candiates.Count == 0) { - context.Messages.Add(Message.Error($"Cannot find matching function '{methodname}({string.Join(", ", argTypes.Select(_ => _.FullName.ToString()))})'")); + context.Messages.Add(Message.Error( + $"Cannot find matching function '{methodname}({string.Join(", ", argTypes.Select(_ => _.FullName.ToString()))})'")); return null; } //ToDo: refactor getting best candidate - var orderedCandidates = candiates.OrderByDescending(_ => _.Parameters.Select(__ => _.FullName.ToString()).Contains("System.Object")); + var orderedCandidates = candiates.OrderByDescending(_ => + _.Parameters.Select(__ => _.FullName.ToString()).Contains("System.Object")); return orderedCandidates.FirstOrDefault(); } } \ No newline at end of file diff --git a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/ImplementationStage.cs b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/ImplementationStage.cs index 077b839..0f1e7ca 100644 --- a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/ImplementationStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/ImplementationStage.cs @@ -8,7 +8,8 @@ namespace Backlang.Driver.Compiling.Stages.CompilationStages; public sealed partial class ImplementationStage : IHandler { - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { foreach (var tree in context.Trees) { @@ -28,10 +29,14 @@ public async Task HandleAsync(CompilerContext context, Func _.Name.ToString() == "ToString" && _.Parameters.Count == 0)) @@ -55,31 +60,36 @@ private static void ImplementDefaultsForStructs(CompilerContext context, LNode s private static void CollectImplementations(CompilerContext context, LNode st, QualifiedName modulename) { - if (!(st.IsCall && st.Name == Symbols.Implementation)) return; + if (!(st.IsCall && st.Name == Symbols.Implementation)) + { + return; + } var typenode = st.Args[0].Args[0].Args[0].Args[0]; var fullname = ConversionUtils.GetQualifiedName(typenode); DescribedType targetType = null; Scope typeScope = null; - if (context.GlobalScope.TryGet(fullname.FullName.ToString(), out var typeItem)) + if (context.GlobalScope.TryGet(fullname.FullName, out var typeItem)) { targetType = (DescribedType)typeItem.Type; typeItem.Deconstruct(out _, out _, out typeScope, out _); } else { - targetType = (DescribedType)TypeInheritanceStage.ResolveTypeWithModule(typenode, context, modulename, fullname); + targetType = + (DescribedType)TypeInheritanceStage.ResolveTypeWithModule(typenode, context, modulename, fullname); if (targetType == null) { - context.AddError(typenode, new(ErrorID.CannotImplementTypeNotFound, fullname.FullName)); + context.AddError(typenode, + new LocalizableString(ErrorID.CannotImplementTypeNotFound, fullname.FullName)); return; } if (Utils.IsUnitType(context, targetType)) { - context.AddError(typenode, new(ErrorID.CannotImplementUnitType, fullname.FullName)); + context.AddError(typenode, new LocalizableString(ErrorID.CannotImplementUnitType, fullname.FullName)); } typeScope = context.GlobalScope.CreateChildScope(); @@ -98,15 +108,16 @@ private static void CollectImplementations(CompilerContext context, LNode st, Qu } else { - var extensionType = (DescribedType)context.Binder.ResolveTypes(new SimpleName(Names.Extensions).Qualify(modulename)).FirstOrDefault(); + var extensionType = (DescribedType)context.Binder + .ResolveTypes(new SimpleName(Names.Extensions).Qualify(modulename)).FirstOrDefault(); if (extensionType == null) { - extensionType = new DescribedType(new SimpleName(Names.Extensions).Qualify(modulename), context.Assembly) - { - IsStatic = true, - IsPublic = true - }; + extensionType = + new DescribedType(new SimpleName(Names.Extensions).Qualify(modulename), context.Assembly) + { + IsStatic = true, IsPublic = true + }; Utils.AddCompilerGeneratedAttribute(context.Binder, extensionType); diff --git a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/IntermediateStage.cs b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/IntermediateStage.cs index c20aedb..0a6066b 100644 --- a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/IntermediateStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/IntermediateStage.cs @@ -1,4 +1,5 @@ using Backlang.Contracts.Scoping.Items; +using Backlang.Core.CompilerService; using Flo; using Furesoft.Core.CodeDom.Compiler.TypeSystem; using System.Globalization; @@ -7,7 +8,8 @@ namespace Backlang.Driver.Compiling.Stages.CompilationStages; public sealed class IntermediateStage : IHandler { - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { context.Assembly = new DescribedAssembly(new QualifiedName(context.Options.OutputFilename.Replace(".dll", ""))); @@ -56,7 +58,7 @@ public async Task HandleAsync(CompilerContext context, Func _.Name == Symbols.Mutable)) { fieldType.AddAttribute(Attributes.Mutable); } + fieldType.IsPublic = true; discType.AddField(fieldType); } diff --git a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.ConvertFunction.cs b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.ConvertFunction.cs index f15fcfd..96e34bc 100644 --- a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.ConvertFunction.cs +++ b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.ConvertFunction.cs @@ -10,13 +10,17 @@ public sealed partial class TypeInheritanceStage : IHandler { method } }; if (hasBody) { - context.BodyCompilations.Add(new(function, context, method, modulename, scope)); + context.BodyCompilations.Add(new MethodBodyCompilation(function, context, method, modulename, scope)); } if (parentScope.Add(functionItem)) @@ -74,7 +80,8 @@ public static DescribedBodyMethod ConvertFunction(CompilerContext context, Descr return null; } - private static void AddParameters(DescribedBodyMethod method, LNode function, CompilerContext context, QualifiedName modulename, Scope scope) + private static void AddParameters(DescribedBodyMethod method, LNode function, CompilerContext context, + QualifiedName modulename, Scope scope) { var param = function.Args[2]; @@ -97,12 +104,11 @@ private static void ConvertFreeFunction(CompilerContext context, LNode node, Qua DescribedType type; if (!context.Assembly.Types.Any(_ => - _.FullName.ToString() == new SimpleName(Names.FreeFunctions).Qualify(modulename).ToString())) + _.FullName.ToString() == new SimpleName(Names.FreeFunctions).Qualify(modulename).ToString())) { type = new DescribedType(new SimpleName(Names.FreeFunctions).Qualify(modulename), context.Assembly) { - IsStatic = true, - IsPublic = true + IsStatic = true, IsPublic = true }; context.Assembly.AddType(type); @@ -120,12 +126,18 @@ private static void ConvertFreeFunction(CompilerContext context, LNode node, Qua type = (DescribedType)context.Assembly.Types.First(_ => _.Name.ToString() == Names.FreeFunctions); } - string methodName = ConversionUtils.GetMethodName(node); - if (methodName == "main") methodName = "Main"; + var methodName = ConversionUtils.GetMethodName(node); + if (methodName == "main") + { + methodName = "Main"; + } - var method = ConvertFunction(context, type, node, modulename, scope, methodName: methodName); + var method = ConvertFunction(context, type, node, modulename, scope, methodName); - if (method != null) type.AddMethod(method); + if (method != null) + { + type.AddMethod(method); + } } private static Parameter ConvertParameter(LNode p, CompilerContext context, QualifiedName modulename) diff --git a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.Resolving.cs b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.Resolving.cs index da63dc2..5749cdb 100644 --- a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.Resolving.cs +++ b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.Resolving.cs @@ -1,43 +1,40 @@ using Backlang.Contracts.TypeSystem; using Flo; -using Loyc.Geometry; namespace Backlang.Driver.Compiling.Stages; public sealed partial class TypeInheritanceStage : IHandler { - public static readonly ImmutableDictionary TypenameTable = new Dictionary() + public static readonly ImmutableDictionary TypenameTable = new Dictionary { ["obj"] = typeof(object), ["none"] = typeof(void), - ["bool"] = typeof(bool), - ["u8"] = typeof(byte), ["u16"] = typeof(ushort), ["u32"] = typeof(uint), ["u64"] = typeof(ulong), - ["i8"] = typeof(sbyte), ["i16"] = typeof(short), ["i32"] = typeof(int), ["i64"] = typeof(long), - ["f16"] = typeof(Half), ["f32"] = typeof(float), ["f64"] = typeof(double), - ["char"] = typeof(char), - ["string"] = typeof(string), + ["string"] = typeof(string) }.ToImmutableDictionary(); public static IType ResolveTypeWithModule(LNode typeNode, CompilerContext context, QualifiedName modulename) - => ResolveTypeWithModule(typeNode, context, modulename, ConversionUtils.GetQualifiedName(typeNode)); + { + return ResolveTypeWithModule(typeNode, context, modulename, ConversionUtils.GetQualifiedName(typeNode)); + } - public static IType ResolveTypeWithModule(LNode typeNode, CompilerContext context, QualifiedName modulename, QualifiedName fullName) + public static IType ResolveTypeWithModule(LNode typeNode, CompilerContext context, QualifiedName modulename, + QualifiedName fullName) { bool isPointer; - PointerKind pointerKind = PointerKind.Transient; + var pointerKind = PointerKind.Transient; if (fullName.FullyUnqualifiedName is PointerName pName) { @@ -60,7 +57,7 @@ public static IType ResolveTypeWithModule(LNode typeNode, CompilerContext contex { resolvedType = Utils.ResolveType(context.Binder, TypenameTable[fullName.FullName]); - if (typeNode is (_, (_, _, (_, var unit))) && unit != LNode.Missing) + if (typeNode is var (_, (_, _, (_, unit))) && unit != LNode.Missing) { ResolveUnitType(context, modulename, ref resolvedType, unit); } @@ -92,7 +89,8 @@ public static IType ResolveTypeWithModule(LNode typeNode, CompilerContext contex if (resolvedType == null) { - if (context.FileScope.ImportetNamespaces.TryGetValue(typeNode.Range.Source.FileName, out var importedNamespaces)) + if (context.FileScope.ImportetNamespaces.TryGetValue(typeNode.Range.Source.FileName, + out var importedNamespaces)) { ResolveImportedType(typeNode, context, ref fullName, ref resolvedType); } @@ -115,14 +113,15 @@ public static IType ResolveTypeWithModule(LNode typeNode, CompilerContext contex private static IType ResolveNullableType(LNode nullableArg, CompilerContext context, QualifiedName modulename) { - var tupleType = Utils.ResolveType(context.Binder, $"Nullable`1", "System"); + var tupleType = Utils.ResolveType(context.Binder, "Nullable`1", "System"); var innerType = ResolveTypeWithModule(nullableArg, context, modulename); - - return tupleType.MakeGenericType(new List() { innerType }); + + return tupleType.MakeGenericType(new List { innerType }); } - private static void ResolveImportedType(LNode typeNode, CompilerContext context, ref QualifiedName fullName, ref IType resolvedType) + private static void ResolveImportedType(LNode typeNode, CompilerContext context, ref QualifiedName fullName, + ref IType resolvedType) { var namespaceImport = context.FileScope.ImportetNamespaces[typeNode.Range.Source.FileName]; @@ -132,7 +131,10 @@ private static void ResolveImportedType(LNode typeNode, CompilerContext context, resolvedType = context.Binder.ResolveTypes(tmpName).FirstOrDefault(); - if (resolvedType != null) break; + if (resolvedType != null) + { + break; + } } } @@ -159,7 +161,8 @@ private static IType ResolveTupleType(LNode typeNode, CompilerContext context, Q return resolvedType; } - private static IType ResolveFunctionType(LNode typeNode, CompilerContext context, QualifiedName modulename, string func) + private static IType ResolveFunctionType(LNode typeNode, CompilerContext context, QualifiedName modulename, + string func) { IType resolvedType; var fnType = Utils.ResolveType(context.Binder, func, "System"); @@ -179,9 +182,10 @@ private static IType ResolveFunctionType(LNode typeNode, CompilerContext context return resolvedType; } - private static void ResolveUnitType(CompilerContext context, QualifiedName modulename, ref IType resolvedType, LNode unit) + private static void ResolveUnitType(CompilerContext context, QualifiedName modulename, ref IType resolvedType, + LNode unit) { - if (unit is (_, (_, var u))) + if (unit is var (_, (_, u))) { var resolvedUnit = ResolveTypeWithModule(u, context, modulename); diff --git a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.cs b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.cs index e0573b2..3a2689e 100644 --- a/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/CompilationStages/TypeInheritanceStage.cs @@ -8,7 +8,40 @@ namespace Backlang.Driver.Compiling.Stages; public sealed partial class TypeInheritanceStage : IHandler { - public static void ConvertTypeMembers(LNode members, DescribedType type, CompilerContext context, QualifiedName modulename, Scope scope) + public async Task HandleAsync(CompilerContext context, + Func> next) + { + foreach (var tree in context.Trees) + { + var modulename = ConversionUtils.GetModuleName(tree); + + foreach (var node in tree.Body) + { + if (node.Calls(CodeSymbols.Struct) || node.Calls(CodeSymbols.Class) || + node.Calls(CodeSymbols.Interface)) + { + ConvertTypeOrInterface(context, node, modulename, context.GlobalScope); + } + else if (node.Calls(CodeSymbols.Fn)) + { + ConvertFreeFunction(context, node, modulename, context.GlobalScope); + } + else if (node.Calls(CodeSymbols.Enum)) + { + ConvertEnum(context, node, modulename); + } + else if (node.Calls(Symbols.Union)) + { + ConvertUnion(context, node, modulename); + } + } + } + + return await next.Invoke(context); + } + + public static void ConvertTypeMembers(LNode members, DescribedType type, CompilerContext context, + QualifiedName modulename, Scope scope) { foreach (var member in members.Args) { @@ -38,7 +71,10 @@ public static void ConvertAnnotations(LNode st, IMember type, { annotation = annotation.Attrs[0]; - if (annotation.Name == LNode.Missing.Name) continue; + if (annotation.Name == LNode.Missing.Name) + { + continue; + } var fullname = ConversionUtils.GetQualifiedName(annotation.Target); @@ -61,7 +97,8 @@ public static void ConvertAnnotations(LNode st, IMember type, var attrUsage = (DescribedAttribute)resolvedType.Attributes .GetAll() - .FirstOrDefault(_ => _.AttributeType.FullName.ToString() == typeof(AttributeUsageAttribute).FullName); + .FirstOrDefault( + _ => _.AttributeType.FullName.ToString() == typeof(AttributeUsageAttribute).FullName); if (attrUsage != null) { @@ -81,9 +118,11 @@ public static void ConvertAnnotations(LNode st, IMember type, } } - public static DescribedProperty ConvertProperty(CompilerContext context, DescribedType type, LNode member, QualifiedName modulename) + public static DescribedProperty ConvertProperty(CompilerContext context, DescribedType type, LNode member, + QualifiedName modulename) { - var property = new DescribedProperty(new SimpleName(member.Args[3].Args[0].Name.Name), ResolveTypeWithModule(member.Args[0], context, modulename), type); + var property = new DescribedProperty(new SimpleName(member.Args[3].Args[0].Name.Name), + ResolveTypeWithModule(member.Args[0], context, modulename), type); ConversionUtils.SetAccessModifier(member, property); @@ -118,44 +157,15 @@ public static DescribedProperty ConvertProperty(CompilerContext context, Describ return property; } - public async Task HandleAsync(CompilerContext context, Func> next) - { - foreach (var tree in context.Trees) - { - var modulename = ConversionUtils.GetModuleName(tree); - - foreach (var node in tree.Body) - { - if (node.Calls(CodeSymbols.Struct) || node.Calls(CodeSymbols.Class) || node.Calls(CodeSymbols.Interface)) - { - ConvertTypeOrInterface(context, node, modulename, context.GlobalScope); - } - else if (node.Calls(CodeSymbols.Fn)) - { - ConvertFreeFunction(context, node, modulename, context.GlobalScope); - } - else if (node.Calls(CodeSymbols.Enum)) - { - ConvertEnum(context, node, modulename); - } - else if (node.Calls(Symbols.Union)) - { - ConvertUnion(context, node, modulename); - } - } - } - - return await next.Invoke(context); - } - private static void ConvertEnum(CompilerContext context, LNode node, QualifiedName modulename) { - if (node is (_, (_, var nameNode, var typeNode, var membersNode))) + if (node is var (_, (_, nameNode, typeNode, membersNode))) { var name = nameNode.Name; var members = membersNode; - var type = (DescribedType)context.Binder.ResolveTypes(new SimpleName(name.Name).Qualify(modulename)).FirstOrDefault(); + var type = (DescribedType)context.Binder.ResolveTypes(new SimpleName(name.Name).Qualify(modulename)) + .FirstOrDefault(); var i = -1; foreach (var member in members.Args) @@ -172,7 +182,7 @@ private static void ConvertEnum(CompilerContext context, LNode node, QualifiedNa mtype = ResolveTypeWithModule(member.Args[0], context, modulename); } - if (member is (_, var mt, (_, var mname, var mvalue))) + if (member is var (_, mt, (_, mname, mvalue))) { if (mvalue == LNode.Missing) { @@ -192,13 +202,15 @@ private static void ConvertEnum(CompilerContext context, LNode node, QualifiedNa } var valueField = new DescribedField(type, new SimpleName("value__"), false, context.Environment.Int32); - valueField.AddAttribute(new DescribedAttribute(Utils.ResolveType(context.Binder, typeof(SpecialNameAttribute)))); + valueField.AddAttribute( + new DescribedAttribute(Utils.ResolveType(context.Binder, typeof(SpecialNameAttribute)))); type.AddField(valueField); } } - private static void ConvertFields(DescribedType type, CompilerContext context, LNode member, QualifiedName modulename, Scope scope) + private static void ConvertFields(DescribedType type, CompilerContext context, LNode member, + QualifiedName modulename, Scope scope) { var ftype = member.Args[0].Args[0].Args[0]; @@ -214,10 +226,18 @@ private static void ConvertFields(DescribedType type, CompilerContext context, L { field.InitialValue = mvalue.Args[0].Value; } + var isMutable = member.Attrs.Any(_ => _.Name == Symbols.Mutable); - if (isMutable) field.AddAttribute(Attributes.Mutable); + if (isMutable) + { + field.AddAttribute(Attributes.Mutable); + } + var isStatic = member.Attrs.Any(_ => _.Name == CodeSymbols.Static); - if (isStatic) field.IsStatic = true; + if (isStatic) + { + field.IsStatic = true; + } if (scope.Add(new FieldScopeItem { Name = mname.Name, Field = field })) { @@ -229,13 +249,14 @@ private static void ConvertFields(DescribedType type, CompilerContext context, L } } - private static void ConvertTypeOrInterface(CompilerContext context, LNode node, QualifiedName modulename, Scope scope) + private static void ConvertTypeOrInterface(CompilerContext context, LNode node, QualifiedName modulename, + Scope scope) { var name = ConversionUtils.GetQualifiedName(node.Args[0]); var inheritances = node.Args[1]; var members = node.Args[2]; - if (!scope.TryGet(name.FullName.ToString(), out var typeItem)) + if (!scope.TryGet(name.FullName, out var typeItem)) { context.AddError(node, $"Type {typeItem.Name} is not found"); return; @@ -280,7 +301,7 @@ private static void ConvertUnion(CompilerContext context, LNode node, QualifiedN new AttributeArgument( Utils.ResolveType(context.Binder, typeof(LayoutKind)), LayoutKind.Explicit) - ); + ); type.AddAttribute(attribute); @@ -307,7 +328,7 @@ private static void ConvertUnion(CompilerContext context, LNode node, QualifiedN new AttributeArgument( mtype, mvalue.Args[0].Value) - ); + ); field.AddAttribute(attribute); diff --git a/Source/Backlang.Driver/Compiling/Stages/EmitTreeStage.cs b/Source/Backlang.Driver/Compiling/Stages/EmitTreeStage.cs index f331e26..a9545f4 100644 --- a/Source/Backlang.Driver/Compiling/Stages/EmitTreeStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/EmitTreeStage.cs @@ -4,7 +4,8 @@ namespace Backlang.Driver.Compiling.Stages; public sealed class EmitTreeStage : IHandler { - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { var sb = new StringBuilder(); var tree = context.Trees.FirstOrDefault(); diff --git a/Source/Backlang.Driver/Compiling/Stages/ExpandingStages/ExpandImplementationStage.cs b/Source/Backlang.Driver/Compiling/Stages/ExpandingStages/ExpandImplementationStage.cs index 58ea16d..afde8b0 100644 --- a/Source/Backlang.Driver/Compiling/Stages/ExpandingStages/ExpandImplementationStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/ExpandingStages/ExpandImplementationStage.cs @@ -4,24 +4,23 @@ namespace Backlang.Driver.Compiling.Stages.ExpandingStages; public sealed class ExpandImplementationStage : IHandler { - private static readonly ImmutableList _primitiveTypes = new List() + private static readonly ImmutableList _primitiveTypes = new List { (Symbol)"u8", (Symbol)"u16", (Symbol)"u32", (Symbol)"u64", - (Symbol)"i8", (Symbol)"i16", (Symbol)"i32", (Symbol)"i64", - (Symbol)"f16", (Symbol)"f32", - (Symbol)"f64", + (Symbol)"f64" }.ToImmutableList(); - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { foreach (var tree in context.Trees) { @@ -40,7 +39,9 @@ private static LNode GenerateRangeTargets(LNode targets) var maxIndex = _primitiveTypes.IndexOf(max); var difference = maxIndex - minIndex; - return LNode.Call(Symbols.ToExpand, LNode.List(Enumerable.Range(minIndex, difference + 1).Select(i => SyntaxTree.Type(_primitiveTypes[i].Name, LNode.List())).ToArray())); + return LNode.Call(Symbols.ToExpand, + LNode.List(Enumerable.Range(minIndex, difference + 1) + .Select(i => SyntaxTree.Type(_primitiveTypes[i].Name, LNode.List())).ToArray())); } private static LNode GetTargets(LNode targets) @@ -49,7 +50,8 @@ private static LNode GetTargets(LNode targets) { return GenerateRangeTargets(targets); } - else if (targets.Calls(Symbols.ToExpand)) + + if (targets.Calls(Symbols.ToExpand)) { var newTargets = new LNodeList(); foreach (var arg in targets.Args) @@ -99,7 +101,7 @@ private static void ExpandImplementations(CompilerContext context, CompilationUn var impl = node.Clone(); impl = impl.WithArgChanged(0, target); - impl = impl.WithArgs(impl.RecursiveReplace((node) => { + impl = impl.WithArgs(impl.RecursiveReplace(node => { var body = node.Args[1]; if (body.Name != CodeSymbols.Fn) diff --git a/Source/Backlang.Driver/Compiling/Stages/ExpandingStages/ExpandMacrosStage.cs b/Source/Backlang.Driver/Compiling/Stages/ExpandingStages/ExpandMacrosStage.cs index 489fbd0..bb9d7ad 100644 --- a/Source/Backlang.Driver/Compiling/Stages/ExpandingStages/ExpandMacrosStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/ExpandingStages/ExpandMacrosStage.cs @@ -2,6 +2,7 @@ using Backlang.Driver.InternalMacros; using Flo; using LeMP; +using LeMP.Prelude; using Loyc.Collections; using System.Runtime.Loader; @@ -9,11 +10,11 @@ namespace Backlang.Driver.Compiling.Stages.ExpandingStages; public sealed class ExpandMacrosStage : IHandler { - private MacroProcessor _macroProcessor; + private readonly MacroProcessor _macroProcessor; public ExpandMacrosStage() { - _macroProcessor = new MacroProcessor(new MessageHolder(), typeof(LeMP.Prelude.BuiltinMacros)); + _macroProcessor = new MacroProcessor(new MessageHolder(), typeof(BuiltinMacros)); //_macroProcessor.AddMacros(typeof(StandardMacros).Assembly, false); _macroProcessor.AddMacros(typeof(BuiltInMacros).Assembly, false); @@ -22,7 +23,8 @@ public ExpandMacrosStage() _macroProcessor.PreOpenedNamespaces.Add((Symbol)typeof(SyntacticMacros).Namespace); } - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { context.CompilationTarget.BeforeExpandMacros(_macroProcessor); //Only calls once @@ -78,7 +80,7 @@ private MessageSeverity ConvertSeverity(Severity severity) Severity.Info => MessageSeverity.Info, Severity.Warning => MessageSeverity.Warning, Severity.Error => MessageSeverity.Error, - _ => MessageSeverity.Error, + _ => MessageSeverity.Error }; } } \ No newline at end of file diff --git a/Source/Backlang.Driver/Compiling/Stages/InitStages/InitEmbeddedResourcesStage.cs b/Source/Backlang.Driver/Compiling/Stages/InitStages/InitEmbeddedResourcesStage.cs index 7cc6a7d..d4cdeac 100644 --- a/Source/Backlang.Driver/Compiling/Stages/InitStages/InitEmbeddedResourcesStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/InitStages/InitEmbeddedResourcesStage.cs @@ -4,7 +4,8 @@ namespace Backlang.Driver.Compiling.Stages.InitStages; public sealed class InitEmbeddedResourcesStage : IHandler { - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { foreach (var resource in context.Options.EmbeddedResource) { diff --git a/Source/Backlang.Driver/Compiling/Stages/InitStages/InitStage.TypeSystem.cs b/Source/Backlang.Driver/Compiling/Stages/InitStages/InitStage.TypeSystem.cs index 224596d..53821de 100644 --- a/Source/Backlang.Driver/Compiling/Stages/InitStages/InitStage.TypeSystem.cs +++ b/Source/Backlang.Driver/Compiling/Stages/InitStages/InitStage.TypeSystem.cs @@ -50,8 +50,7 @@ public void InitTypeSystem(CompilerContext context) } else { - context.Messages.Add(Message.Error(new(ErrorID.TargetNotFound, context.Options.Target))); - return; + context.Messages.Add(Message.Error(new LocalizableString(ErrorID.TargetNotFound, context.Options.Target))); } } @@ -62,10 +61,7 @@ private static void AddIntrinsicType(CompilerContext context, Type type) var instrinsicsType = new DescribedType( new SimpleName(type.Name).Qualify( - qualifier), intrinsicAssembly) - { - IsStatic = true - }; + qualifier), intrinsicAssembly) { IsStatic = true }; context.Binder.AddAssembly(context.Environment.Void.Parent.Assembly); @@ -83,7 +79,8 @@ private static void AddIntrinsicType(CompilerContext context, Type type) foreach (var method in methods) { - ClrTypeEnvironmentBuilder.AddMethod(instrinsicsType, context.Binder, method, toAdjustParameters, method.Name.ToLower()); + ClrTypeEnvironmentBuilder.AddMethod(instrinsicsType, context.Binder, method, toAdjustParameters, + method.Name.ToLower()); } foreach (var toadjust in toAdjustParameters) @@ -92,9 +89,13 @@ private static void AddIntrinsicType(CompilerContext context, Type type) } } - private static void AddIntrinsicEnum(CompilerContext context, Type fieldType, QualifiedName qualifier, DescribedAssembly intrinsicAssembly) + private static void AddIntrinsicEnum(CompilerContext context, Type fieldType, QualifiedName qualifier, + DescribedAssembly intrinsicAssembly) { - if (!fieldType.IsAssignableTo(typeof(Enum))) return; + if (!fieldType.IsAssignableTo(typeof(Enum))) + { + return; + } var type = new DescribedType(new SimpleName(fieldType.Name).Qualify(qualifier), intrinsicAssembly); @@ -114,7 +115,10 @@ private static void AddIntrinsicEnum(CompilerContext context, Type fieldType, Qu private void InitPluginTargets(PluginContainer plugins) { - if (plugins == null) return; + if (plugins == null) + { + return; + } foreach (var target in plugins?.Targets) { @@ -123,7 +127,7 @@ private void InitPluginTargets(PluginContainer plugins) } private void AddTarget() - where T : ICompilationTarget, new() + where T : ICompilationTarget, new() { var target = new T(); _targets.Add(target.Name, target); diff --git a/Source/Backlang.Driver/Compiling/Stages/InitStages/InitStage.cs b/Source/Backlang.Driver/Compiling/Stages/InitStages/InitStage.cs index 6874240..ea46254 100644 --- a/Source/Backlang.Driver/Compiling/Stages/InitStages/InitStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/InitStages/InitStage.cs @@ -4,7 +4,8 @@ namespace Backlang.Driver.Compiling.Stages.InitStages; public sealed partial class InitStage : IHandler { - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { InitPlugins(context); diff --git a/Source/Backlang.Driver/Compiling/Stages/ParsingStage.cs b/Source/Backlang.Driver/Compiling/Stages/ParsingStage.cs index 2c8da97..5c09bff 100644 --- a/Source/Backlang.Driver/Compiling/Stages/ParsingStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/ParsingStage.cs @@ -4,7 +4,8 @@ namespace Backlang.Driver.Compiling.Stages; public sealed class ParsingStage : IHandler { - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { if (context.Playground.IsPlayground) { diff --git a/Source/Backlang.Driver/Compiling/Stages/ReportErrorStage.cs b/Source/Backlang.Driver/Compiling/Stages/ReportErrorStage.cs index 58611ca..5ae9df0 100644 --- a/Source/Backlang.Driver/Compiling/Stages/ReportErrorStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/ReportErrorStage.cs @@ -4,7 +4,8 @@ namespace Backlang.Driver.Compiling.Stages; public sealed class ReportErrorStage : IHandler { - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { foreach (var msg in context.Messages) { diff --git a/Source/Backlang.Driver/Compiling/Stages/SemanticCheckStage.cs b/Source/Backlang.Driver/Compiling/Stages/SemanticCheckStage.cs index 24caa82..2919187 100644 --- a/Source/Backlang.Driver/Compiling/Stages/SemanticCheckStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/SemanticCheckStage.cs @@ -4,7 +4,8 @@ namespace Backlang.Driver.Compiling.Stages; public sealed class SemanticCheckStage : IHandler { - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { Parallel.ForEachAsync(context.Trees, (tree, ct) => { SemanticChecker.Do(tree, context); diff --git a/Source/Backlang.Driver/Compiling/Stages/WaitForDebuggerStage.cs b/Source/Backlang.Driver/Compiling/Stages/WaitForDebuggerStage.cs index 49a2ff4..83da7b6 100644 --- a/Source/Backlang.Driver/Compiling/Stages/WaitForDebuggerStage.cs +++ b/Source/Backlang.Driver/Compiling/Stages/WaitForDebuggerStage.cs @@ -5,7 +5,8 @@ namespace Backlang.Driver.Compiling.Stages; public sealed class WaitForDebuggerStage : IHandler { - public async Task HandleAsync(CompilerContext context, Func> next) + public async Task HandleAsync(CompilerContext context, + Func> next) { while (!Debugger.IsAttached) { diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/CecilExtensions.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/CecilExtensions.cs index 2a7ee34..a718e5d 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/CecilExtensions.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/CecilExtensions.cs @@ -7,12 +7,11 @@ public static class CecilExtensions { public static MethodReference MakeHostInstanceGeneric(this MethodReference self, params TypeReference[] arguments) { - var reference = new MethodReference(self.Name, self.ReturnType, self.DeclaringType.MakeGenericInstanceType(arguments)) - { - HasThis = self.HasThis, - ExplicitThis = self.ExplicitThis, - CallingConvention = self.CallingConvention - }; + var reference = + new MethodReference(self.Name, self.ReturnType, self.DeclaringType.MakeGenericInstanceType(arguments)) + { + HasThis = self.HasThis, ExplicitThis = self.ExplicitThis, CallingConvention = self.CallingConvention + }; foreach (var generic_parameter in self.GenericParameters) { diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/ClrTypeEnvironmentBuilder.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/ClrTypeEnvironmentBuilder.cs index 67aab8f..dc12ced 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/ClrTypeEnvironmentBuilder.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/ClrTypeEnvironmentBuilder.cs @@ -7,7 +7,7 @@ namespace Backlang.Driver.Compiling.Targets.Dotnet; public class ClrTypeEnvironmentBuilder { - private static ConcurrentBag<(MethodBase, DescribedMethod)> toAdjustParameters = new(); + private static readonly ConcurrentBag<(MethodBase, DescribedMethod)> toAdjustParameters = new(); public static IAssembly CollectTypes(Assembly ass) { @@ -17,7 +17,10 @@ public static IAssembly CollectTypes(Assembly ass) foreach (var type in types) { - if (!type.IsPublic) continue; + if (!type.IsPublic) + { + continue; + } var ns = ConversionUtils.QualifyNamespace(type.Namespace); @@ -33,7 +36,10 @@ public static IAssembly CollectTypes(Assembly ass) public static void FillTypes(Assembly ass, CompilerContext context) { Parallel.ForEach(ass.GetTypes(), type => { - if (!type.IsPublic) return; + if (!type.IsPublic) + { + return; + } var t = Utils.ResolveType(context.Binder, type); @@ -93,7 +99,8 @@ public static void AddMembers(Type type, DescribedType t, TypeResolver resolver) foreach (DescribedGenericParameter gp in t.GenericParameters) { - method.AddGenericParameter(new DescribedGenericParameter(method, new SimpleName(gp.Name.ToString()))); + method.AddGenericParameter( + new DescribedGenericParameter(method, new SimpleName(gp.Name.ToString()))); } t.AddMethod(method); @@ -112,7 +119,7 @@ public static void AddMembers(Type type, DescribedType t, TypeResolver resolver) else if (member is PropertyInfo prop) { var p = new DescribedProperty(new SimpleName(prop.Name), - Utils.ResolveType(resolver, prop.PropertyType), t); + Utils.ResolveType(resolver, prop.PropertyType), t); t.AddProperty(p); } @@ -148,21 +155,25 @@ public static void ConvertParameter(ParameterInfo[] parameterInfos, DescribedMet if (p.ParameterType.IsByRef) { - type = Utils.ResolveType(context.Binder, p.ParameterType.Name.Replace("&", ""), p.ParameterType.Namespace)?.MakePointerType(PointerKind.Reference); + type = Utils + .ResolveType(context.Binder, p.ParameterType.Name.Replace("&", ""), p.ParameterType.Namespace) + ?.MakePointerType(PointerKind.Reference); } else if (p.ParameterType.IsArray) { - type = Utils.ResolveType(context.Binder, p.ParameterType.Name.Replace("&", ""), p.ParameterType.Namespace); + type = Utils.ResolveType(context.Binder, p.ParameterType.Name.Replace("&", ""), + p.ParameterType.Namespace); if (type != null) + { type = context.Environment.MakeArrayType(type, p.ParameterType.GetArrayRank()); + } } if (type != null) { var pa = new Parameter(type, p.Name); method.AddParameter(pa); - continue; } } } diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/DotNetAssembly.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/DotNetAssembly.cs index f141b49..334a189 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/DotNetAssembly.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/DotNetAssembly.cs @@ -6,22 +6,31 @@ using Mono.Cecil.Cil; using System.Collections.Concurrent; using System.ComponentModel; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; +using FieldAttributes = Mono.Cecil.FieldAttributes; +using ManifestResourceAttributes = Mono.Cecil.ManifestResourceAttributes; +using MethodAttributes = Mono.Cecil.MethodAttributes; +using ParameterAttributes = Mono.Cecil.ParameterAttributes; +using PropertyAttributes = Mono.Cecil.PropertyAttributes; +using TypeAttributes = Mono.Cecil.TypeAttributes; namespace Backlang.Driver.Compiling.Targets.Dotnet; -public record struct MethodBodyCompilation(DescribedBodyMethod DescribedMethod, - MethodDefinition ClrMethod, TypeDefinition ClrType); +public record struct MethodBodyCompilation( + DescribedBodyMethod DescribedMethod, + MethodDefinition ClrMethod, + TypeDefinition ClrType); public class DotNetAssembly : ITargetAssembly { private static readonly ConcurrentBag _methodBodyCompilations = new(); private readonly IAssembly _assembly; + private readonly AssemblyDefinition _assemblyDefinition; private readonly AssemblyContentDescription _description; private readonly List<(TypeDefinition definition, QualifiedName name)> _needToAdjust = new(); - private readonly AssemblyDefinition _assemblyDefinition; public DotNetAssembly(AssemblyContentDescription description) { @@ -31,7 +40,8 @@ public DotNetAssembly(AssemblyContentDescription description) var name = new AssemblyNameDefinition(_assembly.FullName.ToString(), va == null ? new Version(1, 0) : va.Version); - _assemblyDefinition = AssemblyDefinition.CreateAssembly(name, description.Assembly.Name.ToString(), ModuleKind.Dll); + _assemblyDefinition = + AssemblyDefinition.CreateAssembly(name, description.Assembly.Name.ToString(), ModuleKind.Dll); _description = description; @@ -49,14 +59,14 @@ public void WriteTo(Stream output) foreach (var type in _assembly.Types.Cast()) { - var clrType = new TypeDefinition(type.FullName.Slice(0, type.FullName.PathLength - 1).FullName.ToString(), - type.Name.ToString(), TypeAttributes.Class); + var clrType = new TypeDefinition(type.FullName.Slice(0, type.FullName.PathLength - 1).FullName, + type.Name.ToString(), TypeAttributes.Class); MakeStructReadonly(type, clrType); _assemblyDefinition.MainModule.Types.Add(clrType); - typeMap.AddOrUpdate(type, (_) => clrType, (_, __) => clrType); + typeMap.AddOrUpdate(type, _ => clrType, (_, __) => clrType); } Parallel.ForEachAsync(typeMap.AsParallel(), (typePair, ct) => { @@ -74,11 +84,13 @@ public void WriteTo(Stream output) CompileBodys(); - Parallel.ForEach(_assembly.Attributes.GetAll().Where(_ => _ is EmbeddedResourceAttribute).Cast(), (er) => { - var err = new EmbeddedResource(er.Name, ManifestResourceAttributes.Public, er.Strm); + Parallel.ForEach( + _assembly.Attributes.GetAll().Where(_ => _ is EmbeddedResourceAttribute).Cast(), + er => { + var err = new EmbeddedResource(er.Name, ManifestResourceAttributes.Public, er.Strm); - _assemblyDefinition.MainModule.Resources.Add(err); - }); + _assemblyDefinition.MainModule.Resources.Add(err); + }); _assemblyDefinition.EntryPoint.IsPublic = true; @@ -101,10 +113,8 @@ private static void ApplyModifiers(DescribedType type, TypeDefinition clrType) { clrType.Attributes |= TypeAttributes.Public; } - else - { - // here also 'internal' is used, because 'internal' doesnt need any attribute. - } + + // here also 'internal' is used, because 'internal' doesnt need any attribute. if (type.IsStatic) { clrType.Attributes |= TypeAttributes.Abstract; @@ -158,9 +168,6 @@ private static void ApplyStructLayout(TypeDefinition clrType, DescribedAttribute case LayoutKind.Explicit: clrType.IsExplicitLayout = true; break; - - default: - break; } } @@ -174,7 +181,8 @@ private void MakeStructReadonly(DescribedType type, TypeDefinition clrType) var ca = new CustomAttribute(_assemblyDefinition.MainModule.ImportReference(readonlyCtor)); - ca.ConstructorArguments.Add(new(_assemblyDefinition.MainModule.ImportReference(typeof(bool)), true)); + ca.ConstructorArguments.Add( + new CustomAttributeArgument(_assemblyDefinition.MainModule.ImportReference(typeof(bool)), true)); clrType.CustomAttributes.Add(ca); } @@ -182,7 +190,8 @@ private void MakeStructReadonly(DescribedType type, TypeDefinition clrType) private FieldDefinition GeneratePropertyField(DescribedProperty property) { - var clrField = new FieldDefinition(@$"<{property.Name}>k__BackingField", FieldAttributes.Private, Resolve(property.PropertyType.FullName)); + var clrField = new FieldDefinition(@$"<{property.Name}>k__BackingField", FieldAttributes.Private, + Resolve(property.PropertyType.FullName)); clrField.CustomAttributes.Add(GetCompilerGeneratedAttribute()); @@ -192,8 +201,8 @@ private FieldDefinition GeneratePropertyField(DescribedProperty property) private MethodDefinition GeneratePropertyGetter(DescribedProperty property, FieldReference reference) { var clrMethod = new MethodDefinition(property.Getter.Name.ToString(), - GetMethodAttributes(property.Getter) | MethodAttributes.HideBySig | MethodAttributes.SpecialName, - Resolve(property.PropertyType.FullName)); + GetMethodAttributes(property.Getter) | MethodAttributes.HideBySig | MethodAttributes.SpecialName, + Resolve(property.PropertyType.FullName)); clrMethod.CustomAttributes.Add(GetCompilerGeneratedAttribute()); @@ -215,17 +224,20 @@ private CustomAttribute GetCompilerGeneratedAttribute() return attr; } - private MethodDefinition GeneratePropertySetter(DescribedProperty property, FieldReference reference, DescribedPropertyMethod propMethod, bool isInitOnly) + private MethodDefinition GeneratePropertySetter(DescribedProperty property, FieldReference reference, + DescribedPropertyMethod propMethod, bool isInitOnly) { var clrMethod = new MethodDefinition(propMethod.Name.ToString(), - GetMethodAttributes(propMethod) | MethodAttributes.HideBySig | MethodAttributes.SpecialName, - Resolve(new SimpleName("Void").Qualify("System"))); + GetMethodAttributes(propMethod) | MethodAttributes.HideBySig | MethodAttributes.SpecialName, + Resolve(new SimpleName("Void").Qualify("System"))); clrMethod.CustomAttributes.Add(GetCompilerGeneratedAttribute()); if (isInitOnly) { - clrMethod.ReturnType = new RequiredModifierType(_assemblyDefinition.MainModule.ImportReference(typeof(System.Runtime.CompilerServices.IsExternalInit)), clrMethod.ReturnType); + clrMethod.ReturnType = + new RequiredModifierType(_assemblyDefinition.MainModule.ImportReference(typeof(IsExternalInit)), + clrMethod.ReturnType); } var param = new ParameterDefinition("value", ParameterAttributes.None, Resolve(property.PropertyType.FullName)); @@ -259,6 +271,7 @@ private void ConvertProperties(DescribedType type, TypeDefinition clrType) clrType.Methods.Add(getter); clrProp.GetMethod = getter; } + if (property.HasSetter) { var setter = GeneratePropertySetter(property, field, property.Setter, false); @@ -326,7 +339,8 @@ private void ConvertMethods(DescribedType type, TypeDefinition clrType) } else if (m.IsDestructor) { - clrMethod.Overrides.Add(_assemblyDefinition.MainModule.ImportReference(typeof(object).GetMethod("Finalize", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))); + clrMethod.Overrides.Add(_assemblyDefinition.MainModule.ImportReference( + typeof(object).GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance))); clrMethod.Name = "Finalize"; clrMethod.IsVirtual = true; clrMethod.IsFamily = true; @@ -335,7 +349,7 @@ private void ConvertMethods(DescribedType type, TypeDefinition clrType) if (m.Body != null) { - _methodBodyCompilations.Add(new(m, clrMethod, clrType)); + _methodBodyCompilations.Add(new MethodBodyCompilation(m, clrMethod, clrType)); } ConvertCustomAttributes(clrType, m, clrMethod); @@ -348,7 +362,8 @@ private void CompileBodys() { foreach (var bodyCompilation in _methodBodyCompilations) { - var variables = MethodBodyCompiler.Compile(bodyCompilation.DescribedMethod, bodyCompilation.ClrMethod, _assemblyDefinition, bodyCompilation.ClrType); + var variables = MethodBodyCompiler.Compile(bodyCompilation.DescribedMethod, bodyCompilation.ClrMethod, + _assemblyDefinition, bodyCompilation.ClrType); bodyCompilation.ClrMethod.DebugInformation.Scope = new ScopeDebugInformation(bodyCompilation.ClrMethod.Body.Instructions[0], @@ -356,7 +371,8 @@ private void CompileBodys() foreach (var variable in variables) { - bodyCompilation.ClrMethod.DebugInformation.Scope.Variables.Add(new VariableDebugInformation(variable.Value, variable.Key)); + bodyCompilation.ClrMethod.DebugInformation.Scope.Variables.Add( + new VariableDebugInformation(variable.Value, variable.Key)); } } } @@ -381,7 +397,8 @@ private void ConvertCustomAttributes(TypeDefinition clrType, DescribedBodyMethod private void ConvertCustomAttribute(TypeDefinition clrType, MethodDefinition clrMethod, DescribedAttribute attr) { var attrType = _assemblyDefinition.ImportType(attr.AttributeType).Resolve(); - var attrCtor = attrType.Methods.FirstOrDefault(_ => _.IsConstructor && attr.ConstructorArguments.Count == _.Parameters.Count); + var attrCtor = attrType.Methods.FirstOrDefault(_ => + _.IsConstructor && attr.ConstructorArguments.Count == _.Parameters.Count); var ca = new CustomAttribute(_assemblyDefinition.MainModule.ImportReference(attrCtor)); clrType.IsBeforeFieldInit = false; @@ -477,9 +494,9 @@ private void ConvertCustomAttribute(TypeDefinition clrType, DescribedAttribute a { var attrType = _assemblyDefinition.ImportType(attr.AttributeType).Resolve(); var attrCtor = attrType.Methods - .FirstOrDefault(_ => - _.IsConstructor - && attr.ConstructorArguments.Count == _.Parameters.Count); + .FirstOrDefault(_ => + _.IsConstructor + && attr.ConstructorArguments.Count == _.Parameters.Count); var ca = new CustomAttribute(_assemblyDefinition.MainModule.ImportReference(attrCtor)); clrType.IsBeforeFieldInit = false; @@ -502,7 +519,8 @@ private void ConvertCustomAttributes(DescribedField field, FieldDefinition clrFi clrField.Offset = (int)attr.ConstructorArguments[0].Value; continue; } - else if (attr.AttributeType.Name.ToString() == "SpecialNameAttribute") + + if (attr.AttributeType.Name.ToString() == "SpecialNameAttribute") { clrField.IsRuntimeSpecialName = true; clrField.IsSpecialName = true; @@ -516,7 +534,8 @@ private void ConvertCustomAttributes(DescribedField field, FieldDefinition clrFi foreach (var arg in attr.ConstructorArguments) { - ca.ConstructorArguments.Add(new CustomAttributeArgument(_assemblyDefinition.ImportType(arg.Type), arg.Value)); + ca.ConstructorArguments.Add(new CustomAttributeArgument(_assemblyDefinition.ImportType(arg.Type), + arg.Value)); } clrField.CustomAttributes.Add(ca); @@ -526,8 +545,8 @@ private void ConvertCustomAttributes(DescribedField field, FieldDefinition clrFi private MethodDefinition GetMethodDefinition(DescribedBodyMethod m, IType returnType) { var clrMethod = new MethodDefinition(m.Name.ToString(), - GetMethodAttributes(m), - Resolve(returnType == null ? new SimpleName("Void").Qualify("System") : returnType.FullName)); + GetMethodAttributes(m), + Resolve(returnType == null ? new SimpleName("Void").Qualify("System") : returnType.FullName)); if (m == _description.EntryPoint) { @@ -542,6 +561,7 @@ private MethodDefinition GetMethodDefinition(DescribedBodyMethod m, IType return param.Constant = p.DefaultValue; param.IsOptional = true; } + clrMethod.Parameters.Add(param); } @@ -553,6 +573,7 @@ private MethodDefinition GetMethodDefinition(DescribedBodyMethod m, IType return clrMethod.Name = ".ctor"; clrMethod.IsStatic = false; } + return clrMethod; } @@ -566,7 +587,10 @@ private TypeReference Resolve(IType dtype) foreach (var gp in dtype.GenericParameters) { if (gp.Name.ToString() == "#" || gp.Name.ToString().StartsWith("T") - || gp.Name.ToString().StartsWith("TResult")) continue; + || gp.Name.ToString().StartsWith("TResult")) + { + continue; + } var resolvedGeneric = Resolve(gp.Name.Qualify("System")); genericType.GenericArguments.Add(resolvedGeneric); @@ -590,12 +614,13 @@ private TypeReference Resolve(QualifiedName name) private void SetTargetFramework(string moniker) { - var tf = _assemblyDefinition.MainModule.ImportReference(typeof(TargetFrameworkAttribute).GetConstructors().First()); + var tf = _assemblyDefinition.MainModule.ImportReference(typeof(TargetFrameworkAttribute).GetConstructors() + .First()); var item = new CustomAttribute(tf); item.ConstructorArguments.Add( new CustomAttributeArgument(_assemblyDefinition.MainModule.ImportReference(typeof(string)), - $".NETCoreApp,Version=v{RuntimeConfig.GetVersion(moniker)}")); + $".NETCoreApp,Version=v{RuntimeConfig.GetVersion(moniker)}")); _assemblyDefinition.CustomAttributes.Add(item); } diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/DotNetTarget.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/DotNetTarget.cs index bfb0ed9..bd003c9 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/DotNetTarget.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/DotNetTarget.cs @@ -1,5 +1,6 @@ using Backlang.Core; using Backlang.Driver.Compiling.Targets.Dotnet.RuntimeOptionsModels; +using Furesoft.Core.CodeDom.Backends.CLR; using Furesoft.Core.CodeDom.Compiler.Pipeline; using LeMP; using System.Collections; @@ -60,7 +61,7 @@ public TypeEnvironment Init(CompilerContext context) ClrTypeEnvironmentBuilder.FillTypes(typeof(Result<>).Assembly, context); ClrTypeEnvironmentBuilder.FillTypes(typeof(ArrayList).Assembly, context); - return new Furesoft.Core.CodeDom.Backends.CLR.CorlibTypeEnvironment(corLib); + return new CorlibTypeEnvironment(corLib); } public void InitReferences(CompilerContext context) @@ -70,7 +71,10 @@ public void InitReferences(CompilerContext context) AddFromAssembly(context, r); } - if (context.CorLib == null) return; + if (context.CorLib == null) + { + return; + } foreach (var r in context.CorLib.Split(';')) { diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/ArithmetikEmitter.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/ArithmetikEmitter.cs index 8b1650c..41ae325 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/ArithmetikEmitter.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/ArithmetikEmitter.cs @@ -1,37 +1,37 @@ using Furesoft.Core.CodeDom.Compiler.Instructions; using Mono.Cecil; using Mono.Cecil.Cil; +using Instruction = Furesoft.Core.CodeDom.Compiler.Instruction; namespace Backlang.Driver.Compiling.Targets.Dotnet.Emitters; internal class ArithmetikEmitter : IEmitter { - private readonly ImmutableDictionary _stringOPMap = new Dictionary() + private readonly ImmutableDictionary _stringOPMap = new Dictionary { ["arith.+"] = OpCodes.Add, ["arith.-"] = OpCodes.Sub, ["arith.*"] = OpCodes.Mul, ["arith./"] = OpCodes.Div, - ["arith.%"] = OpCodes.Div, - ["arith.&"] = OpCodes.And, ["arith.|"] = OpCodes.Or, ["arith.^"] = OpCodes.Xor, - ["arith.<"] = OpCodes.Clt, ["arith.>"] = OpCodes.Cgt, - ["arith.=="] = OpCodes.Ceq, + ["arith.=="] = OpCodes.Ceq }.ToImmutableDictionary(); - public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Furesoft.Core.CodeDom.Compiler.Instruction instruction, BasicBlock block) + public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Instruction instruction, + BasicBlock block) { var arithProtype = (IntrinsicPrototype)instruction.Prototype; if (_stringOPMap.ContainsKey(arithProtype.Name)) { var op = _stringOPMap[arithProtype.Name]; - ilProcessor.Emit(op); return; + ilProcessor.Emit(op); + return; } switch (arithProtype.Name) diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/CallEmitter.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/CallEmitter.cs index 65fe668..7b66f6a 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/CallEmitter.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/CallEmitter.cs @@ -1,13 +1,14 @@ using Furesoft.Core.CodeDom.Compiler.Instructions; using Mono.Cecil; using Mono.Cecil.Cil; +using Instruction = Furesoft.Core.CodeDom.Compiler.Instruction; namespace Backlang.Driver.Compiling.Targets.Dotnet.Emitters; internal class CallEmitter : IEmitter { public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, - Furesoft.Core.CodeDom.Compiler.Instruction instruction, BasicBlock block) + Instruction instruction, BasicBlock block) { var callPrototype = (CallPrototype)instruction.Prototype; @@ -28,7 +29,7 @@ public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, var arg = method.Parameters[i]; //ToDo: move to IR - if (arg.ParameterType.FullName.ToString() == "System.Object") + if (arg.ParameterType.FullName == "System.Object") { ilProcessor.Emit(OpCodes.Box, assemblyDefinition.ImportType(valueType)); } @@ -44,7 +45,7 @@ public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, ilProcessor.Emit(op, assemblyDefinition.MainModule.ImportReference( method - ) - ); + ) + ); } } \ No newline at end of file diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/CopyEmitter.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/CopyEmitter.cs index ec849e5..2901f6e 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/CopyEmitter.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/CopyEmitter.cs @@ -1,11 +1,13 @@ using Mono.Cecil; using Mono.Cecil.Cil; +using Instruction = Furesoft.Core.CodeDom.Compiler.Instruction; namespace Backlang.Driver.Compiling.Targets.Dotnet.Emitters; public class CopyEmitter : IEmitter { - public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Furesoft.Core.CodeDom.Compiler.Instruction instruction, BasicBlock block) + public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Instruction instruction, + BasicBlock block) { ilProcessor.Emit(OpCodes.Dup); } diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/DynamicCastEmitter.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/DynamicCastEmitter.cs index 3402e1a..2671f6e 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/DynamicCastEmitter.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/DynamicCastEmitter.cs @@ -1,12 +1,14 @@ using Furesoft.Core.CodeDom.Compiler.Instructions; using Mono.Cecil; using Mono.Cecil.Cil; +using Instruction = Furesoft.Core.CodeDom.Compiler.Instruction; namespace Backlang.Driver.Compiling.Targets.Dotnet.Emitters; internal class DynamicCastEmitter : IEmitter { - public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Furesoft.Core.CodeDom.Compiler.Instruction instruction, BasicBlock block) + public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Instruction instruction, + BasicBlock block) { var dcp = (DynamicCastPrototype)instruction.Prototype; var checkType = assemblyDefinition.ImportType(dcp.TargetType.ElementType); diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/LoadEmitter.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/LoadEmitter.cs index 41de7fe..1dca18a 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/LoadEmitter.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/LoadEmitter.cs @@ -1,12 +1,14 @@ using Furesoft.Core.CodeDom.Compiler.Instructions; using Mono.Cecil; using Mono.Cecil.Cil; +using Instruction = Furesoft.Core.CodeDom.Compiler.Instruction; namespace Backlang.Driver.Compiling.Targets.Dotnet.Emitters; internal class LoadEmitter : IEmitter { - public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Furesoft.Core.CodeDom.Compiler.Instruction instruction, BasicBlock block) + public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Instruction instruction, + BasicBlock block) { var valueInstruction = block.Graph.GetInstruction(instruction.Arguments[0]); diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/LoadIndirectEmitter.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/LoadIndirectEmitter.cs index ef63113..1d9f385 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/LoadIndirectEmitter.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/LoadIndirectEmitter.cs @@ -1,11 +1,13 @@ using Mono.Cecil; using Mono.Cecil.Cil; +using Instruction = Furesoft.Core.CodeDom.Compiler.Instruction; namespace Backlang.Driver.Compiling.Targets.Dotnet.Emitters; internal class LoadIndirectEmitter : IEmitter { - public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Furesoft.Core.CodeDom.Compiler.Instruction instruction, BasicBlock block) + public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Instruction instruction, + BasicBlock block) { ilProcessor.Emit(OpCodes.Ldind_I4); } diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/NewArrayEmitter.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/NewArrayEmitter.cs index 7a0e0e5..08af5fe 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/NewArrayEmitter.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/NewArrayEmitter.cs @@ -1,12 +1,14 @@ using Furesoft.Core.CodeDom.Compiler.Instructions; using Mono.Cecil; using Mono.Cecil.Cil; +using Instruction = Furesoft.Core.CodeDom.Compiler.Instruction; namespace Backlang.Driver.Compiling.Targets.Dotnet.Emitters; internal class NewArrayEmitter : IEmitter { - public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Furesoft.Core.CodeDom.Compiler.Instruction instruction, BasicBlock block) + public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Instruction instruction, + BasicBlock block) { var prototype = (AllocaArrayPrototype)instruction.Prototype; diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/NewObjectEmitter.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/NewObjectEmitter.cs index 52b4727..ef9837e 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/NewObjectEmitter.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/NewObjectEmitter.cs @@ -1,12 +1,14 @@ using Furesoft.Core.CodeDom.Compiler.Instructions; using Mono.Cecil; using Mono.Cecil.Cil; +using Instruction = Furesoft.Core.CodeDom.Compiler.Instruction; namespace Backlang.Driver.Compiling.Targets.Dotnet.Emitters; internal class NewObjectEmitter : IEmitter { - public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Furesoft.Core.CodeDom.Compiler.Instruction instruction, BasicBlock block) + public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, Instruction instruction, + BasicBlock block) { var newObjectPrototype = (NewObjectPrototype)instruction.Prototype; var method = MethodBodyCompiler.GetMethod(assemblyDefinition, newObjectPrototype.Constructor); diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/TypeofEmitter.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/TypeofEmitter.cs index c220abd..2276fed 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/TypeofEmitter.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Emitters/TypeofEmitter.cs @@ -1,13 +1,14 @@ using Backlang.Driver.Core.Instructions; using Mono.Cecil; using Mono.Cecil.Cil; +using Instruction = Furesoft.Core.CodeDom.Compiler.Instruction; namespace Backlang.Driver.Compiling.Targets.Dotnet.Emitters; internal class TypeofEmitter : IEmitter { public void Emit(AssemblyDefinition assemblyDefinition, ILProcessor ilProcessor, - Furesoft.Core.CodeDom.Compiler.Instruction instruction, BasicBlock block) + Instruction instruction, BasicBlock block) { var toip = (TypeOfInstructionPrototype)instruction.Prototype; diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Intrinsics.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Intrinsics.cs index 8e5850e..14e50f5 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/Intrinsics.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/Intrinsics.cs @@ -6,23 +6,53 @@ public static class Intrinsics { public static ILProcessor iLProcessor; - public static void Ldnull() => iLProcessor.Emit(OpCodes.Ldnull); - - public static void Ldstr(string value) => iLProcessor.Emit(OpCodes.Ldstr, value); - - public static void Ldc_I4(int value) => iLProcessor.Emit(OpCodes.Ldc_I4, value); - - public static void Ldc_I8(long value) => iLProcessor.Emit(OpCodes.Ldc_I8, value); - - public static void Ldc_R4(float value) => iLProcessor.Emit(OpCodes.Ldc_R4, value); - - public static void Ldc_R8(double value) => iLProcessor.Emit(OpCodes.Ldc_R8, value); - - public static void Ldarg(ushort arg) => iLProcessor.Emit(OpCodes.Ldarg, arg); - - public static void Ldarga(ushort arg) => iLProcessor.Emit(OpCodes.Ldarga, arg); - - public static void Ldloc(ushort local) => iLProcessor.Emit(OpCodes.Ldloc, local); - - public static void Ldloca(ushort local) => iLProcessor.Emit(OpCodes.Ldloca, local); + public static void Ldnull() + { + iLProcessor.Emit(OpCodes.Ldnull); + } + + public static void Ldstr(string value) + { + iLProcessor.Emit(OpCodes.Ldstr, value); + } + + public static void Ldc_I4(int value) + { + iLProcessor.Emit(OpCodes.Ldc_I4, value); + } + + public static void Ldc_I8(long value) + { + iLProcessor.Emit(OpCodes.Ldc_I8, value); + } + + public static void Ldc_R4(float value) + { + iLProcessor.Emit(OpCodes.Ldc_R4, value); + } + + public static void Ldc_R8(double value) + { + iLProcessor.Emit(OpCodes.Ldc_R8, value); + } + + public static void Ldarg(ushort arg) + { + iLProcessor.Emit(OpCodes.Ldarg, arg); + } + + public static void Ldarga(ushort arg) + { + iLProcessor.Emit(OpCodes.Ldarga, arg); + } + + public static void Ldloc(ushort local) + { + iLProcessor.Emit(OpCodes.Ldloc, local); + } + + public static void Ldloca(ushort local) + { + iLProcessor.Emit(OpCodes.Ldloca, local); + } } \ No newline at end of file diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/MethodBodyCompiler.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/MethodBodyCompiler.cs index 19d82dc..fad2b6a 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/MethodBodyCompiler.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/MethodBodyCompiler.cs @@ -6,7 +6,7 @@ using Furesoft.Core.CodeDom.Compiler.TypeSystem; using Mono.Cecil; using Mono.Cecil.Cil; - +using Mono.Collections.Generic; using static Backlang.Driver.Compiling.Stages.CompilationStages.ImplementationStage; using Instruction = Mono.Cecil.Cil.Instruction; using LoadFieldPrototype = Furesoft.Core.CodeDom.Compiler.Instructions.LoadFieldPrototype; @@ -26,10 +26,11 @@ public static class MethodBodyCompiler [typeof(IntrinsicPrototype)] = new ArithmetikEmitter(), [typeof(AllocaArrayPrototype)] = new NewArrayEmitter(), [typeof(LoadPrototype)] = new LoadEmitter(), - [typeof(CopyPrototype)] = new CopyEmitter(), + [typeof(CopyPrototype)] = new CopyEmitter() }; - public static Dictionary Compile(DescribedBodyMethod m, MethodDefinition clrMethod, AssemblyDefinition assemblyDefinition, TypeDefinition parentType) + public static Dictionary Compile(DescribedBodyMethod m, MethodDefinition clrMethod, + AssemblyDefinition assemblyDefinition, TypeDefinition parentType) { var ilProcessor = clrMethod.Body.GetILProcessor(); @@ -58,7 +59,7 @@ public static MethodReference GetMethod(AssemblyDefinition assemblyDefinition, I var parentType = assemblyDefinition.ImportType(method.ParentType).Resolve(); foreach (var m in parentType.Methods - .Where(_ => _.Name == method.Name.ToString())) + .Where(_ => _.Name == method.Name.ToString())) { var parameters = m.Parameters; @@ -69,7 +70,8 @@ public static MethodReference GetMethod(AssemblyDefinition assemblyDefinition, I if (method.IsConstructor) { var dts = (DirectTypeSpecialization)GenericTypeMap.Cache[(method.FullName, method)]; - var args = dts.GetRecursiveGenericArguments().Select(_ => assemblyDefinition.ImportType(_)).ToArray(); + var args = dts.GetRecursiveGenericArguments().Select(_ => assemblyDefinition.ImportType(_)) + .ToArray(); var genericType = assemblyDefinition.ImportType(dts); var gctor = genericType.Resolve().Methods.FirstOrDefault(_ => _.Name == method.Name.ToString()); @@ -82,7 +84,9 @@ public static MethodReference GetMethod(AssemblyDefinition assemblyDefinition, I } if (MatchesParameters(parameters, method)) + { return assemblyDefinition.MainModule.ImportReference(m); + } } } @@ -115,7 +119,8 @@ public static void EmitConstant(ILProcessor ilProcessor, ConstantPrototype consP } } - private static void FixJumps(ILProcessor ilProcessor, Dictionary labels, List<(int InstructionIndex, BasicBlockTag Target)> fixups) + private static void FixJumps(ILProcessor ilProcessor, Dictionary labels, + List<(int InstructionIndex, BasicBlockTag Target)> fixups) { foreach (var fixup in fixups) { @@ -129,8 +134,8 @@ private static void FixJumps(ILProcessor ilProcessor, Dictionary variables, - List<(int InstructionIndex, BasicBlockTag Target)> fixups, Dictionary labels) + Dictionary variables, + List<(int InstructionIndex, BasicBlockTag Target)> fixups, Dictionary labels) { labels.Add(block.Tag, ilProcessor.Body.Instructions.Count); @@ -225,7 +230,8 @@ private static void CompileBlock(BasicBlock block, AssemblyDefinition assemblyDe EmitBlockFlow(block, ilProcessor, clrMethod, fixups); } - private static void EmitBlockFlow(BasicBlock block, ILProcessor ilProcessor, MethodDefinition clrMethod, List<(int InstructionIndex, BasicBlockTag Target)> fixups) + private static void EmitBlockFlow(BasicBlock block, ILProcessor ilProcessor, MethodDefinition clrMethod, + List<(int InstructionIndex, BasicBlockTag Target)> fixups) { if (block.Flow is ReturnFlow rf) { @@ -275,13 +281,15 @@ private static void EmitBlockFlow(BasicBlock block, ILProcessor ilProcessor, Met } } - private static void EmitLoadLocal(ILProcessor ilProcessor, LoadLocalPrototype lloc, Dictionary variables) + private static void EmitLoadLocal(ILProcessor ilProcessor, LoadLocalPrototype lloc, + Dictionary variables) { var definition = variables[lloc.Parameter.Name.ToString()]; ilProcessor.Emit(OpCodes.Ldloc, definition); } - private static void EmitStoreField(TypeDefinition parentType, ILProcessor ilProcessor, StoreFieldPointerPrototype fp) + private static void EmitStoreField(TypeDefinition parentType, ILProcessor ilProcessor, + StoreFieldPointerPrototype fp) { var field = parentType.Fields.FirstOrDefault(_ => _.Name == fp.Field.Name.ToString()); @@ -302,7 +310,8 @@ private static void EmitLoadFieldA(TypeDefinition parentType, ILProcessor ilProc ilProcessor.Emit(OpCodes.Ldflda, field); } - private static void EmitLoadArg(MethodDefinition clrMethod, ILProcessor ilProcessor, TypeReference parentType, LoadArgPrototype larg) + private static void EmitLoadArg(MethodDefinition clrMethod, ILProcessor ilProcessor, TypeReference parentType, + LoadArgPrototype larg) { var param = clrMethod.Parameters.FirstOrDefault(_ => _.Name == larg.Parameter.Name.ToString()); @@ -310,7 +319,10 @@ private static void EmitLoadArg(MethodDefinition clrMethod, ILProcessor ilProces { var index = clrMethod.Parameters.IndexOf(param); - if (!clrMethod.IsStatic) index++; + if (!clrMethod.IsStatic) + { + index++; + } ilProcessor.Emit(OpCodes.Ldarg, index); } @@ -340,6 +352,7 @@ private static void EmitIntegerConstant(ILProcessor ilProcessor, dynamic v, Inte { ilProcessor.Emit(OpCodes.Ldc_I4, ic.ToUInt8()); } + break; case 16: @@ -351,6 +364,7 @@ private static void EmitIntegerConstant(ILProcessor ilProcessor, dynamic v, Inte { ilProcessor.Emit(OpCodes.Ldc_I4, ic.ToUInt16()); } + break; case 32: @@ -362,6 +376,7 @@ private static void EmitIntegerConstant(ILProcessor ilProcessor, dynamic v, Inte { ilProcessor.Emit(OpCodes.Ldc_I4, ic.ToUInt32()); } + break; case 64: @@ -373,9 +388,7 @@ private static void EmitIntegerConstant(ILProcessor ilProcessor, dynamic v, Inte { ilProcessor.Emit(OpCodes.Ldc_I4, ic.ToUInt64()); } - break; - default: break; } } @@ -401,10 +414,11 @@ private static VariableDefinition EmitVariableDeclaration(MethodDefinition clrMe return variable; } - private static bool MatchesParameters(Mono.Collections.Generic.Collection parameters, IMethod method) + private static bool MatchesParameters(Collection parameters, IMethod method) { //ToDo: refactor to improve code - var methodParams = string.Join(',', method.Parameters.Select(_ => NormalizeTypename(_.Type?.FullName.ToString()))); + var methodParams = + string.Join(',', method.Parameters.Select(_ => NormalizeTypename(_.Type?.FullName.ToString()))); var monocecilParams = string.Join(',', parameters.Select(_ => _.ParameterType.FullName.ToString())); return methodParams.Equals(monocecilParams, StringComparison.Ordinal); diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/FrameworkOptions.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/FrameworkOptions.cs index 195fdb3..fad4034 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/FrameworkOptions.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/FrameworkOptions.cs @@ -4,9 +4,7 @@ namespace Backlang.Driver.Compiling.Targets.Dotnet.RuntimeOptionsModels; public class FrameworkOptions { - [JsonProperty("name")] - public string Name { get; set; } + [JsonProperty("name")] public string Name { get; set; } - [JsonProperty("version")] - public string Version { get; set; } + [JsonProperty("version")] public string Version { get; set; } } \ No newline at end of file diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/RuntimeConfig.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/RuntimeConfig.cs index b67bf66..2743301 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/RuntimeConfig.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/RuntimeConfig.cs @@ -4,8 +4,7 @@ namespace Backlang.Driver.Compiling.Targets.Dotnet.RuntimeOptionsModels; public class RuntimeConfig { - [JsonProperty("runtimeOptions")] - public RuntimeOptions RuntimeOptions { get; set; } = new(); + [JsonProperty("runtimeOptions")] public RuntimeOptions RuntimeOptions { get; set; } = new(); public static void Save(string path, string name, CompilerCliOptions options) { diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/RuntimeOptions.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/RuntimeOptions.cs index f247847..51106bc 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/RuntimeOptions.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/RuntimeOptionsModels/RuntimeOptions.cs @@ -4,9 +4,7 @@ namespace Backlang.Driver.Compiling.Targets.Dotnet.RuntimeOptionsModels; public class RuntimeOptions { - [JsonProperty("tfm")] - public string Tfm { get; set; } + [JsonProperty("tfm")] public string Tfm { get; set; } - [JsonProperty("framework")] - public FrameworkOptions Framework { get; set; } = new(); + [JsonProperty("framework")] public FrameworkOptions Framework { get; set; } = new(); } \ No newline at end of file diff --git a/Source/Backlang.Driver/Compiling/Targets/Dotnet/TypeUtils.cs b/Source/Backlang.Driver/Compiling/Targets/Dotnet/TypeUtils.cs index 111e4e1..2c64bdc 100644 --- a/Source/Backlang.Driver/Compiling/Targets/Dotnet/TypeUtils.cs +++ b/Source/Backlang.Driver/Compiling/Targets/Dotnet/TypeUtils.cs @@ -21,7 +21,8 @@ public static TypeReference ImportType(this AssemblyDefinition _assemblyDefiniti { return new PointerType(ptrType); } - else if (pn.Kind == PointerKind.Reference) + + if (pn.Kind == PointerKind.Reference) { return new ByReferenceType(ptrType); } @@ -32,20 +33,19 @@ public static TypeReference ImportType(this AssemblyDefinition _assemblyDefiniti { return ImportArrayType(_assemblyDefinition, gn); } - else - { - return ImportGenericType(_assemblyDefinition, gn); - } + + return ImportGenericType(_assemblyDefinition, gn); } - return ImportType(_assemblyDefinition, type.Slice(0, type.PathLength - 1).FullName.ToString(), type.FullyUnqualifiedName.ToString()); + return ImportType(_assemblyDefinition, type.Slice(0, type.PathLength - 1).FullName, + type.FullyUnqualifiedName.ToString()); } public static TypeReference ImportType(this AssemblyDefinition _assemblyDefinition, string ns, string type) { foreach (var ar in _assemblyDefinition.MainModule.AssemblyReferences) { - var ass = _assemblyDefinition.MainModule.AssemblyResolver.Resolve(ar, new ReaderParameters() { }); + var ass = _assemblyDefinition.MainModule.AssemblyResolver.Resolve(ar, new ReaderParameters()); var tr = new TypeReference(ns, type, ass.MainModule, ass.MainModule); @@ -63,7 +63,8 @@ public static TypeReference ImportType(this AssemblyDefinition _assemblyDefiniti private static TypeReference ImportArrayType(AssemblyDefinition _assemblyDefinition, GenericName gn) { var declName = gn.DeclarationName.ToString(); - var rankStr = declName.Substring(declName.IndexOf("!") + 1, declName.IndexOf("`") - (declName.LastIndexOf("!") + 1)); + var rankStr = declName.Substring(declName.IndexOf("!") + 1, + declName.IndexOf("`") - (declName.LastIndexOf("!") + 1)); var rank = int.Parse(rankStr); var elType = _assemblyDefinition.ImportType(gn.TypeArgumentNames[0]); diff --git a/Source/Backlang.Driver/Core/Implementors/Branches.cs b/Source/Backlang.Driver/Core/Implementors/Branches.cs index 08af933..ff7f83a 100644 --- a/Source/Backlang.Driver/Core/Implementors/Branches.cs +++ b/Source/Backlang.Driver/Core/Implementors/Branches.cs @@ -2,6 +2,6 @@ public class BranchLabels { - public BasicBlockTag continueBranch; public BasicBlockTag breakBranch; + public BasicBlockTag continueBranch; } \ No newline at end of file diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/AddressExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/AddressExpressionImplementor.cs index c446f39..a9ec049 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/AddressExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/AddressExpressionImplementor.cs @@ -2,17 +2,22 @@ public class AddressExpressionImplementor : IExpressionImplementor { - public bool CanHandle(LNode node) => node is ("'&", _); + public bool CanHandle(LNode node) + { + return node is ("'&", _); + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) { - if (node is (_, var p)) + if (node is var (_, p)) { var localPrms = block.Parameters.Where(_ => _.Tag.Name.ToString() == p.Name.Name); if (localPrms.Any()) { - return block.AppendInstruction(Instruction.CreateLoadLocalAdress(new Parameter(localPrms.First().Type, localPrms.First().Tag.Name))); + return block.AppendInstruction( + Instruction.CreateLoadLocalAdress(new Parameter(localPrms.First().Type, + localPrms.First().Tag.Name))); } } diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/ArrayExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/ArrayExpressionImplementor.cs index 04d5956..b78f3f8 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/ArrayExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/ArrayExpressionImplementor.cs @@ -1,17 +1,20 @@ using Furesoft.Core.CodeDom.Compiler.Core.Constants; using Furesoft.Core.CodeDom.Compiler.Instructions; -using System.Runtime.CompilerServices; namespace Backlang.Driver.Core.Implementors.Expressions; public class ArrayExpressionImplementor : IExpressionImplementor { - public bool CanHandle(LNode node) => node.Calls(CodeSymbols.Array); + public bool CanHandle(LNode node) + { + return node.Calls(CodeSymbols.Array); + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) { - var value = block.AppendInstruction(Instruction.CreateConstant(new IntegerConstant(node.ArgCount), context.Environment.Int32)); + var value = block.AppendInstruction(Instruction.CreateConstant(new IntegerConstant(node.ArgCount), + context.Environment.Int32)); var counter = block.AppendInstruction(Instruction.CreateLoad(context.Environment.Int32, value)); if (elementType.FullName.Qualifier is GenericName gn) @@ -19,31 +22,35 @@ public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType = context.Binder.ResolveTypes(gn.TypeArgumentNames[0]).FirstOrDefault(); } - var arrayValuesType = GetOrAddArrayValueType(context.Environment.MakeArrayType(elementType, 1), context, out var field); //Todo: replace rank + var arrayValuesType = + GetOrAddArrayValueType(context.Environment.MakeArrayType(elementType, 1), context, + out var field); //Todo: replace rank - field.InitialValue = new byte[] { 1,2,3 }; + field.InitialValue = new byte[] { 1, 2, 3 }; //Todo: only emit this if values are primitive values otherwise emit storeelementref - var args = new List { + var args = new List + { block.AppendInstruction(Instruction.CreateAllocaArray(elementType, counter)), block.AppendInstruction(Instruction.CreateCopy(arrayValuesType, null)) }; - var initArrayMethod = context.Binder.FindFunction("System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(System.Array, System.RuntimeFieldHandle)"); + var initArrayMethod = context.Binder.FindFunction( + "System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(System.Array, System.RuntimeFieldHandle)"); return block.AppendInstruction(Instruction.CreateCall(initArrayMethod, MethodLookup.Static, args)); } - private static DescribedType GetOrAddArrayValueType(IType elementType, CompilerContext context, out DescribedField field) + private static DescribedType GetOrAddArrayValueType(IType elementType, CompilerContext context, + out DescribedField field) { - var arrayValuesType = (DescribedType)context.Binder.ResolveTypes(new SimpleName(Names.ArrayValues).Qualify("")).FirstOrDefault(); + var arrayValuesType = (DescribedType)context.Binder.ResolveTypes(new SimpleName(Names.ArrayValues).Qualify("")) + .FirstOrDefault(); if (arrayValuesType == null) { - arrayValuesType = new DescribedType(new SimpleName(Names.ArrayValues).Qualify(""), context.Assembly) - { - IsStatic = true - }; + arrayValuesType = + new DescribedType(new SimpleName(Names.ArrayValues).Qualify(""), context.Assembly) { IsStatic = true }; Utils.AddCompilerGeneratedAttribute(context.Binder, arrayValuesType); diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/AsExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/AsExpressionImplementor.cs index f3c04a9..3af876a 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/AsExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/AsExpressionImplementor.cs @@ -4,7 +4,10 @@ namespace Backlang.Driver.Core.Implementors.Expressions; public class AsExpressionImplementor : IExpressionImplementor { - public bool CanHandle(LNode node) => node.ArgCount == 2 && node.Calls(CodeSymbols.As); + public bool CanHandle(LNode node) + { + return node.ArgCount == 2 && node.Calls(CodeSymbols.As); + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/BinaryExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/BinaryExpressionImplementor.cs index 0547f90..a21a6f3 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/BinaryExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/BinaryExpressionImplementor.cs @@ -8,9 +8,9 @@ public class BinaryExpressionImplementor : IExpressionImplementor public bool CanHandle(LNode node) { return node.ArgCount == 2 - && !node.Calls(CodeSymbols.ColonColon) - && !node.Calls(CodeSymbols.Tuple) - && node.Name.Name.StartsWith("'"); + && !node.Calls(CodeSymbols.ColonColon) + && !node.Calls(CodeSymbols.Tuple) + && node.Name.Name.StartsWith("'"); } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, @@ -24,14 +24,18 @@ public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, if (leftType.TryGetOperator(node.Name.Name, out var opMethod, leftType, rightType)) { - return block.AppendInstruction(Instruction.CreateCall(opMethod, MethodLookup.Static, new ValueTag[] { lhs, rhs })); + return block.AppendInstruction(Instruction.CreateCall(opMethod, MethodLookup.Static, + new ValueTag[] { lhs, rhs })); } - else if (node.Calls(CodeSymbols.Add) && (leftType == context.Environment.String || rightType == context.Environment.String)) + + if (node.Calls(CodeSymbols.Add) && + (leftType == context.Environment.String || rightType == context.Environment.String)) { var concatMethods = context.Environment.String.Methods .Where(_ => _.Name.ToString() == "Concat" && _.Parameters.Count == 2); - var matchingConcatMethod = concatMethods.FirstOrDefault(_ => _.Parameters[0].Type == leftType && _.Parameters[1].Type == rightType); + var matchingConcatMethod = concatMethods.FirstOrDefault(_ => + _.Parameters[0].Type == leftType && _.Parameters[1].Type == rightType); var call = Instruction.CreateCall(matchingConcatMethod, MethodLookup.Static, new ValueTag[] { lhs, rhs }); @@ -39,6 +43,7 @@ public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, } //ToDo: add check for unittype and no unitype. then unpack unit type - return block.AppendInstruction(Instruction.CreateBinaryArithmeticIntrinsic(node.Name.Name.Substring(1), false, elementType, lhs, rhs)); + return block.AppendInstruction( + Instruction.CreateBinaryArithmeticIntrinsic(node.Name.Name.Substring(1), false, elementType, lhs, rhs)); } } \ No newline at end of file diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/CallExpressionEmitter.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/CallExpressionEmitter.cs index 2691cc9..4b8d53a 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/CallExpressionEmitter.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/CallExpressionEmitter.cs @@ -4,26 +4,32 @@ namespace Backlang.Driver.Core.Implementors.Expressions; public class CallExpressionEmitter : IExpressionImplementor { - public bool CanHandle(LNode node) => node.IsCall && !node.Calls(CodeSymbols.Tuple); + public bool CanHandle(LNode node) + { + return node.IsCall && !node.Calls(CodeSymbols.Tuple); + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) { if (scope.TryGet(node.Name.Name, out var fn)) { - return ImplementationStage.AppendCall(context, block, node, fn.Overloads, scope, modulename, methodName: node.Name.Name); + return ImplementationStage.AppendCall(context, block, node, fn.Overloads, scope, modulename, + methodName: node.Name.Name); } if (TryGetFreeFunctionsFromNamespace(context, node.Range.Source.FileName, out var functions)) { - return ImplementationStage.AppendCall(context, block, node, functions, scope, modulename, methodName: node.Name.Name); + return ImplementationStage.AppendCall(context, block, node, functions, scope, modulename, + methodName: node.Name.Name); } context.AddError(node, $"function {node.Name.Name} not found"); return null; } - private static bool TryGetFreeFunctionsFromNamespace(CompilerContext context, string filename, out IEnumerable functions) + private static bool TryGetFreeFunctionsFromNamespace(CompilerContext context, string filename, + out IEnumerable functions) { var allFreeFunctions = new List(); if (context.FileScope.ImportetNamespaces.TryGetValue(filename, out var importedNamespaces)) @@ -37,7 +43,8 @@ private static bool TryGetFreeFunctionsFromNamespace(CompilerContext context, st continue; } - allFreeFunctions.AddRange(resolvedNs.Types.First(_ => _.Name.ToString() == Names.FreeFunctions).Methods); + allFreeFunctions.AddRange(resolvedNs.Types.First(_ => _.Name.ToString() == Names.FreeFunctions) + .Methods); } } diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/ConstantExpressionEmitter.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/ConstantExpressionEmitter.cs index c669d3d..7d0afa5 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/ConstantExpressionEmitter.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/ConstantExpressionEmitter.cs @@ -4,7 +4,10 @@ namespace Backlang.Driver.Core.Implementors.Expressions; public class ConstantExpressionEmitter : IExpressionImplementor { - public bool CanHandle(LNode node) => node.ArgCount == 1 && node.Args[0].HasValue; + public bool CanHandle(LNode node) + { + return node.ArgCount == 1 && node.Args[0].HasValue; + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/CtorExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/CtorExpressionImplementor.cs index fd13cc9..e29cebf 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/CtorExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/CtorExpressionImplementor.cs @@ -2,7 +2,10 @@ public class CtorExpressionImplementor : IExpressionImplementor { - public bool CanHandle(LNode node) => node.Calls(CodeSymbols.New); + public bool CanHandle(LNode node) + { + return node.Calls(CodeSymbols.New); + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/DefaultExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/DefaultExpressionImplementor.cs index e84372f..7cddbee 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/DefaultExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/DefaultExpressionImplementor.cs @@ -4,29 +4,28 @@ namespace Backlang.Driver.Core.Implementors.Expressions; public class DefaultExpressionImplementor : IExpressionImplementor { - private readonly ImmutableDictionary _defaults = new Dictionary() + private readonly ImmutableDictionary _defaults = new Dictionary { ["Boolean"] = default(bool), ["Char"] = default(char), - ["Byte"] = default(sbyte), ["Short"] = default(short), ["Int32"] = default(int), ["Int64"] = default(long), - ["UByte"] = default(byte), ["UShort"] = default(ushort), ["UInt32"] = default(uint), ["UInt64"] = default(ulong), - ["Float16"] = default(Half), ["Float32"] = default(float), ["Float64"] = default(double), - ["String"] = string.Empty }.ToImmutableDictionary(); - public bool CanHandle(LNode node) => node.ArgCount == 1 && node is ("'default", _); + public bool CanHandle(LNode node) + { + return node.ArgCount == 1 && node is ("'default", _); + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/IdentifierExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/IdentifierExpressionImplementor.cs index de97483..c01361f 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/IdentifierExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/IdentifierExpressionImplementor.cs @@ -1,17 +1,21 @@ -using Backlang.Contracts.Scoping.Items; +using Backlang.Codeanalysis.Core; +using Backlang.Contracts.Scoping.Items; namespace Backlang.Driver.Core.Implementors.Expressions; public class IdentifierExpressionImplementor : IExpressionImplementor { - public bool CanHandle(LNode node) => node.IsId; + public bool CanHandle(LNode node) + { + return node.IsId; + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) { if (!scope.TryGet(node.Name.Name, out var item)) { - context.AddError(node, new(Codeanalysis.Core.ErrorID.NotDefined, node.Name.Name)); + context.AddError(node, new LocalizableString(ErrorID.NotDefined, node.Name.Name)); return null; } @@ -19,7 +23,8 @@ public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, { return block.AppendInstruction(Instruction.CreateLoadArg(psi.Parameter)); } - else if (item is VariableScopeItem vsi) + + if (item is VariableScopeItem vsi) { return block.AppendInstruction(Instruction.CreateLoadLocal(vsi.Parameter)); } diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/MemberExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/MemberExpressionImplementor.cs index ed4116b..32ee947 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/MemberExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/MemberExpressionImplementor.cs @@ -5,10 +5,13 @@ namespace Backlang.Driver.Core.Implementors.Expressions; public class MemberExpressionImplementor : IExpressionImplementor { - public bool CanHandle(LNode node) => node.ArgCount == 2 - && !node.Calls(CodeSymbols.ColonColon) - && !node.Calls(CodeSymbols.Tuple) - && node.Name.Name.StartsWith("'."); + public bool CanHandle(LNode node) + { + return node.ArgCount == 2 + && !node.Calls(CodeSymbols.ColonColon) + && !node.Calls(CodeSymbols.Tuple) + && node.Name.Name.StartsWith("'."); + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/PointerExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/PointerExpressionImplementor.cs index 7b2a0b3..0fb1373 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/PointerExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/PointerExpressionImplementor.cs @@ -4,12 +4,15 @@ namespace Backlang.Driver.Core.Implementors.Expressions; public class PointerExpressionImplementor : IExpressionImplementor { - public bool CanHandle(LNode node) => node is ("'*", _) && node.ArgCount == 1; + public bool CanHandle(LNode node) + { + return node is ("'*", _) && node.ArgCount == 1; + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) { - if (node is (_, var o)) + if (node is var (_, o)) { var localPrms = block.Parameters.Where(_ => _.Tag.Name.ToString() == o.Name.Name); if (localPrms.Any()) diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/TupleExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/TupleExpressionImplementor.cs index ff725ce..8e0988e 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/TupleExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/TupleExpressionImplementor.cs @@ -2,7 +2,10 @@ public class TupleExpressionImplementor : IExpressionImplementor { - public bool CanHandle(LNode node) => node.Calls(CodeSymbols.Tuple); + public bool CanHandle(LNode node) + { + return node.Calls(CodeSymbols.Tuple); + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) @@ -22,13 +25,14 @@ public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, genericTypes.Add(argType); } - var ctor = elementType.Methods.FirstOrDefault(_ => _.IsConstructor && _.Parameters.Count == valueTags.Count); + var ctor = elementType.Methods.FirstOrDefault(_ => + _.IsConstructor && _.Parameters.Count == valueTags.Count); if (ctor != null) { var directMethodSpecialization = ctor.MakeGenericMethod(gargs); - GenericTypeMap.Cache.Add(((QualifiedName, IMember))(elementType.FullName, directMethodSpecialization), elementType); + GenericTypeMap.Cache.Add((elementType.FullName, directMethodSpecialization), elementType); block.AppendInstruction(Instruction.CreateNewObject(directMethodSpecialization, valueTags)); } } diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/TypeOfExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/TypeOfExpressionImplementor.cs index 95f0590..e8dc1c8 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/TypeOfExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/TypeOfExpressionImplementor.cs @@ -5,7 +5,10 @@ namespace Backlang.Driver.Core.Implementors.Expressions; public class TypeOfExpressionImplementor : IExpressionImplementor { - public bool CanHandle(LNode node) => node.ArgCount == 1 && node is ("'typeof", _); + public bool CanHandle(LNode node) + { + return node.ArgCount == 1 && node is ("'typeof", _); + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) @@ -17,6 +20,7 @@ public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, var typeRef = Utils.ResolveType(context.Binder, typeof(Type)); var method = typeRef.Methods.FirstOrDefault(_ => _.Name.ToString() == "GetTypeFromHandle"); - return block.AppendInstruction(Instruction.CreateCall(method, MethodLookup.Static, new List { ldtoken })); + return block.AppendInstruction(Instruction.CreateCall(method, MethodLookup.Static, + new List { ldtoken })); } } \ No newline at end of file diff --git a/Source/Backlang.Driver/Core/Implementors/Expressions/UnaryExpressionImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Expressions/UnaryExpressionImplementor.cs index f1ba20d..da5a9d3 100644 --- a/Source/Backlang.Driver/Core/Implementors/Expressions/UnaryExpressionImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Expressions/UnaryExpressionImplementor.cs @@ -5,7 +5,10 @@ namespace Backlang.Driver.Core.Implementors.Expressions; public class UnaryExpressionImplementor : IExpressionImplementor { - public bool CanHandle(LNode node) => node.ArgCount == 1 && !node.Calls(CodeSymbols.ColonColon) && node.Name.Name.StartsWith("'"); + public bool CanHandle(LNode node) + { + return node.ArgCount == 1 && !node.Calls(CodeSymbols.ColonColon) && node.Name.Name.StartsWith("'"); + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) @@ -25,6 +28,7 @@ public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, return block.AppendInstruction(Instruction.CreateLoadIndirect(leftType)); } - return block.AppendInstruction(Instruction.CreateArithmeticIntrinsic(node.Name.Name.Substring(1), false, elementType, new[] { leftType }, new ValueTag[] { lhs })); + return block.AppendInstruction(Instruction.CreateArithmeticIntrinsic(node.Name.Name.Substring(1), false, + elementType, new[] { leftType }, new ValueTag[] { lhs })); } } \ No newline at end of file diff --git a/Source/Backlang.Driver/Core/Implementors/IStatementImplementor.cs b/Source/Backlang.Driver/Core/Implementors/IStatementImplementor.cs index d1a4d74..438ee47 100644 --- a/Source/Backlang.Driver/Core/Implementors/IStatementImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/IStatementImplementor.cs @@ -2,5 +2,6 @@ public interface IStatementImplementor { - BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null); + BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null); } \ No newline at end of file diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/AssignmentImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/AssignmentImplementor.cs index 071c226..afa21b1 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/AssignmentImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/AssignmentImplementor.cs @@ -5,9 +5,10 @@ namespace Backlang.Driver.Core.Implementors.Statements; public class AssignmentImplementor : IStatementImplementor { - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) { - if (node is (_, var left, var right)) + if (node is var (_, left, right)) { var lt = TypeDeducer.Deduce(left, scope, context, modulename.Value); var rt = TypeDeducer.Deduce(right, scope, context, modulename.Value); diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/BreakStatementImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/BreakStatementImplementor.cs index a3a5459..cce2eff 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/BreakStatementImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/BreakStatementImplementor.cs @@ -4,7 +4,8 @@ namespace Backlang.Driver.Core.Implementors.Statements; public class BreakStatementImplementor : IStatementImplementor { - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) { block.Flow = new JumpFlow(branchLabels.breakBranch); diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/CallImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/CallImplementor.cs index 3a3b186..ae9c1a3 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/CallImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/CallImplementor.cs @@ -1,4 +1,5 @@ -using Backlang.Contracts.Scoping.Items; +using Backlang.Codeanalysis.Core; +using Backlang.Contracts.Scoping.Items; using Backlang.Driver.Core.Instructions; using static Backlang.Driver.Compiling.Stages.CompilationStages.ImplementationStage; @@ -6,16 +7,8 @@ namespace Backlang.Driver.Core.Implementors.Statements; public class CallImplementor : IStatementImplementor { - public static void AppendDiscardReturnValue(BasicBlockBuilder block, IType type) - { - if (type.FullName.ToString() != "System.Void") - { - //Discard value if its not been stored anywhere - block.AppendInstruction(new PopInstructionPrototype().Instantiate(new List())); - } - } - - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) { if (node is ("'.", var target, var callee) && target is ("this", _)) { @@ -34,14 +27,20 @@ public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, Compiler } else { - context.AddError(node, new(Codeanalysis.Core.ErrorID.CannotFindFunction, callee.Name.Name)); + context.AddError(node, new LocalizableString(ErrorID.CannotFindFunction, callee.Name.Name)); } } - else - { - // ToDo: other things and so on... - } + // ToDo: other things and so on... return block; } + + public static void AppendDiscardReturnValue(BasicBlockBuilder block, IType type) + { + if (type.FullName.ToString() != "System.Void") + { + //Discard value if its not been stored anywhere + block.AppendInstruction(new PopInstructionPrototype().Instantiate(new List())); + } + } } \ No newline at end of file diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/ContinueStatementImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/ContinueStatementImplementor.cs index 2828335..7f276eb 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/ContinueStatementImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/ContinueStatementImplementor.cs @@ -4,7 +4,8 @@ namespace Backlang.Driver.Core.Implementors.Statements; public class ContinueStatementImplementor : IStatementImplementor { - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) { block.Flow = new JumpFlow(branchLabels.continueBranch); diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/DoWhileImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/DoWhileImplementor.cs index a9ab085..26920bf 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/DoWhileImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/DoWhileImplementor.cs @@ -5,9 +5,10 @@ namespace Backlang.Driver.Core.Implementors.Statements; public class DoWhileImplementor : IStatementImplementor { - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) { - if (node is (_, var body, var condition)) + if (node is var (_, body, condition)) { TypeDeducer.ExpectType(condition, scope, context, modulename.Value, context.Environment.Boolean); diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/IfImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/IfImplementor.cs index a18785c..92a585f 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/IfImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/IfImplementor.cs @@ -5,9 +5,10 @@ namespace Backlang.Driver.Core.Implementors.Statements; public class IfImplementor : IStatementImplementor { - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) { - if (node is (_, (_, var condition, var body, var elseBody))) + if (node is var (_, (_, condition, body, elseBody))) { TypeDeducer.ExpectType(condition, scope, context, modulename.Value, context.Environment.Boolean); @@ -16,7 +17,8 @@ public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, Compiler if (elseBody.Name != LNode.Missing.Name) { - if_after = ImplementIf(if_after, context, method, modulename, scope, branchLabels, condition, elseBody, true); + if_after = ImplementIf(if_after, context, method, modulename, scope, branchLabels, condition, elseBody, + true); } return if_after; @@ -25,8 +27,9 @@ public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, Compiler return null; } - private static BasicBlockBuilder ImplementIf(BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, - Scope scope, BranchLabels branchLabels, LNode condition, LNode body, bool negate = false) + private static BasicBlockBuilder ImplementIf(BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, + Scope scope, BranchLabels branchLabels, LNode condition, LNode body, bool negate = false) { var if_start = block.Graph.AddBasicBlock(LabelGenerator.NewLabel("if_start")); var if_condition = block.Graph.AddBasicBlock(LabelGenerator.NewLabel("if_condition")); @@ -36,7 +39,8 @@ private static BasicBlockBuilder ImplementIf(BasicBlockBuilder block, CompilerCo AppendExpression(if_condition, condition, context.Environment.Boolean, context, scope, modulename); - if_condition.Flow = new JumpConditionalFlow(if_start, negate ? ConditionalJumpKind.False : ConditionalJumpKind.True); + if_condition.Flow = + new JumpConditionalFlow(if_start, negate ? ConditionalJumpKind.False : ConditionalJumpKind.True); block.Flow = new JumpFlow(if_condition); @@ -48,8 +52,9 @@ private static BasicBlockBuilder ImplementIf(BasicBlockBuilder block, CompilerCo return if_after; } - private static BasicBlockBuilder ImplementIfElse(BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, - Scope scope, BranchLabels branchLabels, LNode condition, LNode body, LNode elseBody) + private static BasicBlockBuilder ImplementIfElse(BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, + Scope scope, BranchLabels branchLabels, LNode condition, LNode body, LNode elseBody) { var if_condition = block.Graph.AddBasicBlock(LabelGenerator.NewLabel("if_condition")); var if_body = block.Graph.AddBasicBlock(LabelGenerator.NewLabel("if_start")); @@ -68,6 +73,7 @@ private static BasicBlockBuilder ImplementIfElse(BasicBlockBuilder block, Compil { if_body.Flow = new JumpFlow(else_end); } + if (else_body.Flow is NothingFlow) { else_body.Flow = new JumpFlow(else_end); diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/PrintOrPrintlnImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/PrintOrPrintlnImplementor.cs index b29c0f4..486c4dd 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/PrintOrPrintlnImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/PrintOrPrintlnImplementor.cs @@ -2,7 +2,8 @@ public class PrintOrPrintlnImplementor : IStatementImplementor { - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) { var deducedArg = TypeDeducer.Deduce(node.Args[0], scope, context, modulename.Value); diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/ReturnImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/ReturnImplementor.cs index 79c4e94..aff3d84 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/ReturnImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/ReturnImplementor.cs @@ -5,7 +5,8 @@ namespace Backlang.Driver.Core.Implementors.Statements; public class ReturnImplementor : IStatementImplementor { - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) { if (node.ArgCount == 1) { diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/StaticCallImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/StaticCallImplementor.cs index 00de84f..05866f2 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/StaticCallImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/StaticCallImplementor.cs @@ -2,7 +2,10 @@ public class StaticCallImplementor : IStatementImplementor, IExpressionImplementor { - public bool CanHandle(LNode node) => node.Calls(CodeSymbols.ColonColon); + public bool CanHandle(LNode node) + { + return node.Calls(CodeSymbols.ColonColon); + } public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, IType elementType, CompilerContext context, Scope scope, QualifiedName? modulename) @@ -11,10 +14,12 @@ public NamedInstructionBuilder Handle(LNode node, BasicBlockBuilder block, var type = TypeDeducer.Deduce(node.Args[0], scope, context, modulename.Value); - return ImplementationStage.AppendCall(context, block, callee, type.Methods, scope, modulename, methodName: callee.Name.Name); + return ImplementationStage.AppendCall(context, block, callee, type.Methods, scope, modulename, + methodName: callee.Name.Name); } - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) { Handle(node, block, TypeDeducer.Deduce(node, scope, context, modulename.Value), diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/ThrowImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/ThrowImplementor.cs index 4738513..ac54963 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/ThrowImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/ThrowImplementor.cs @@ -5,16 +5,17 @@ namespace Backlang.Driver.Core.Implementors.Statements; public class ThrowImplementor : IStatementImplementor { - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) { var valueNode = node.Args[0].Args[0]; var constant = block.AppendInstruction(ConvertConstant( GetLiteralType(valueNode, context, scope, - modulename.Value), valueNode.Value)); + modulename.Value), valueNode.Value)); var msg = block.AppendInstruction( Instruction.CreateLoad(GetLiteralType(valueNode, context, - scope, modulename.Value), constant)); + scope, modulename.Value), constant)); if (node.Args[0].Name.Name == "#string") { diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/VariableImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/VariableImplementor.cs index 8df43f8..050609e 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/VariableImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/VariableImplementor.cs @@ -6,7 +6,8 @@ namespace Backlang.Driver.Core.Implementors.Statements; public class VariableImplementor : IStatementImplementor { - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels = null) { var decl = node.Args[1]; @@ -22,12 +23,12 @@ public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, Compiler { elementType = deducedValueType; - if (elementType == context.Environment.Void && !scope.TryGet(node.Args[0].Name.Name, out var _)) + if (elementType == context.Environment.Void && !scope.TryGet(node.Args[0].Name.Name, out _)) { - if (node.Args[0] is (_, (_, var tp))) //ToDo: Implement Helper function To Get Typename + if (node.Args[0] is var (_, (_, tp))) //ToDo: Implement Helper function To Get Typename { context.AddError(node, - new(ErrorID.CannotBeResolved, tp.Name.ToString())); + new LocalizableString(ErrorID.CannotBeResolved, tp.Name.ToString())); } } } @@ -41,13 +42,15 @@ public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, Compiler if (ut != deducedValueType) { context.AddError(node, - new(ErrorID.UnitTypeMismatch, elementType.ToString(), deducedValueType.ToString())); + new LocalizableString(ErrorID.UnitTypeMismatch, elementType.ToString(), + deducedValueType.ToString())); } + return block; } context.AddError(node, - new(ErrorID.TypeMismatch, elementType.ToString(), deducedValueType.ToString())); + new LocalizableString(ErrorID.TypeMismatch, elementType.ToString(), deducedValueType.ToString())); } } @@ -55,20 +58,21 @@ public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, Compiler var isMutable = node.Attrs.Contains(LNode.Id(Symbols.Mutable)); if (scope.Add(new VariableScopeItem - { - Name = varname, - IsMutable = isMutable, - Parameter = new Parameter(elementType, varname) - })) + { + Name = varname, IsMutable = isMutable, Parameter = new Parameter(elementType, varname) + })) { block.AppendParameter(new BlockParameter(elementType, varname, !isMutable)); } else { - context.AddError(decl.Args[0], new(ErrorID.AlreadyDeclared, varname)); + context.AddError(decl.Args[0], new LocalizableString(ErrorID.AlreadyDeclared, varname)); } - if (deducedValueType == null) return block; + if (deducedValueType == null) + { + return block; + } ImplementationStage.AppendExpression(block, decl.Args[1], elementType, context, scope, modulename); diff --git a/Source/Backlang.Driver/Core/Implementors/Statements/WhileImplementor.cs b/Source/Backlang.Driver/Core/Implementors/Statements/WhileImplementor.cs index 61b5138..3185305 100644 --- a/Source/Backlang.Driver/Core/Implementors/Statements/WhileImplementor.cs +++ b/Source/Backlang.Driver/Core/Implementors/Statements/WhileImplementor.cs @@ -5,9 +5,10 @@ namespace Backlang.Driver.Core.Implementors.Statements; public class WhileImplementor : IStatementImplementor { - public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, QualifiedName? modulename, Scope scope, BranchLabels branchLabels) + public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, CompilerContext context, IMethod method, + QualifiedName? modulename, Scope scope, BranchLabels branchLabels) { - if (node is (_, var condition, var body)) + if (node is var (_, condition, body)) { TypeDeducer.ExpectType(condition, scope, context, modulename.Value, context.Environment.Boolean); @@ -18,16 +19,12 @@ public BasicBlockBuilder Implement(LNode node, BasicBlockBuilder block, Compiler var while_after = block.Graph.AddBasicBlock(LabelGenerator.NewLabel("while_after")); while_after.Flow = new NothingFlow(); - branchLabels = new() - { - breakBranch = while_after, - continueBranch = while_condition - }; + branchLabels = new BranchLabels { breakBranch = while_after, continueBranch = while_condition }; AppendBlock(body, while_start, context, method, modulename, scope.CreateChildScope(), branchLabels); AppendExpression(while_condition, condition, context.Environment.Boolean, context, scope, modulename); - + while_condition.Flow = new JumpConditionalFlow(while_start, ConditionalJumpKind.True); block.Flow = new JumpFlow(while_condition); diff --git a/Source/Backlang.Driver/Core/ImplicitTypeCastTable.cs b/Source/Backlang.Driver/Core/ImplicitTypeCastTable.cs index 122986a..404c2d3 100644 --- a/Source/Backlang.Driver/Core/ImplicitTypeCastTable.cs +++ b/Source/Backlang.Driver/Core/ImplicitTypeCastTable.cs @@ -4,7 +4,7 @@ namespace Backlang.Driver.Core; public static class ImplicitTypeCastTable { - private static Dictionary castMap = new(); + private static readonly Dictionary castMap = new(); public static void InitCastMap(TypeEnvironment environment) { @@ -12,8 +12,10 @@ public static void InitCastMap(TypeEnvironment environment) castMap.Add(environment.UInt16, new[] { environment.UInt32, environment.UInt64 }); castMap.Add(environment.UInt32, new[] { environment.UInt64 }); - castMap.Add(environment.Int8, new[] { environment.Int16, environment.Int32, environment.Int64, environment.Float32 }); - castMap.Add(environment.Int16, new[] { environment.Int32, environment.Int64, environment.Float32, environment.Float64 }); + castMap.Add(environment.Int8, + new[] { environment.Int16, environment.Int32, environment.Int64, environment.Float32 }); + castMap.Add(environment.Int16, + new[] { environment.Int32, environment.Int64, environment.Float32, environment.Float64 }); castMap.Add(environment.Int32, new[] { environment.Int64, environment.Float64 }); } @@ -23,19 +25,23 @@ public static bool IsAssignableTo(this IType type, IType toCast) { return true; } - else if (toCast is UnitType ut) + + if (toCast is UnitType ut) { return IsAssignableTo(type, ut.BaseTypes[0]); } - else if (HasImplicitCastOperator(type, toCast)) + + if (HasImplicitCastOperator(type, toCast)) { return true; } - else if (castMap.ContainsKey(toCast)) + + if (castMap.ContainsKey(toCast)) { return castMap[toCast].Contains(type); } - else if (toCast.FullName.ToString() == "System.Object") + + if (toCast.FullName.ToString() == "System.Object") { return true; } @@ -45,7 +51,7 @@ public static bool IsAssignableTo(this IType type, IType toCast) private static bool HasImplicitCastOperator(IType type, IType toCast) { - var result = OperatorOverloadingHelpers.TryGetOperator(type, "implicit", out var method, type); + var result = type.TryGetOperator("implicit", out var method, type); return result && method.ReturnParameter.Type == toCast; } diff --git a/Source/Backlang.Driver/Core/Instructions/TypeOfInstructionPrototype.cs b/Source/Backlang.Driver/Core/Instructions/TypeOfInstructionPrototype.cs index 8f18019..1ad8160 100644 --- a/Source/Backlang.Driver/Core/Instructions/TypeOfInstructionPrototype.cs +++ b/Source/Backlang.Driver/Core/Instructions/TypeOfInstructionPrototype.cs @@ -21,4 +21,4 @@ public override InstructionPrototype Map(MemberMapping mapping) { return null; } -} +} \ No newline at end of file diff --git a/Source/Backlang.Driver/Core/OperatorOverloadingHelpers.cs b/Source/Backlang.Driver/Core/OperatorOverloadingHelpers.cs index 182a864..2c109c5 100644 --- a/Source/Backlang.Driver/Core/OperatorOverloadingHelpers.cs +++ b/Source/Backlang.Driver/Core/OperatorOverloadingHelpers.cs @@ -2,43 +2,40 @@ public static class OperatorOverloadingHelpers { - private static readonly ImmutableDictionary binMap = new Dictionary() + private static readonly ImmutableDictionary binMap = new Dictionary { ["'+"] = "op_Addition", ["'/"] = "op_Division", ["'-"] = "op_Subtraction", ["'*"] = "op_Multiply", ["'%"] = "op_Modulus", - ["'&"] = "op_BitwiseAnd", ["'|"] = "op_BitwiseOr", ["'^"] = "op_ExclusiveOr", ["'=="] = "op_Equality", - ["'!="] = "op_Inequality", + ["'!="] = "op_Inequality" }.ToImmutableDictionary(); - private static readonly ImmutableDictionary unMap = new Dictionary() + private static readonly ImmutableDictionary unMap = new Dictionary { ["'!"] = "op_LogicalNot", ["'-"] = "op_UnaryNegation", ["'~"] = "op_OnesComplement", - ["'*"] = "op_Deref", ["'&"] = "op_AddressOf", - ["'%"] = "op_Percentage", ["'suf?"] = "op_Unpacking", - ["implicit"] = "op_Implicit", - ["explicit"] = "op_Explicit", + ["explicit"] = "op_Explicit" }.ToImmutableDictionary(); public static bool TryGetOperator(this IType type, string op, out IMethod opMethod, params IType[] args) { var possibleMethods = type.Methods.Where(_ => _.IsStatic - && !_.IsConstructor && !_.IsDestructor - && _.Attributes.GetAll().Any(__ => __?.AttributeType?.Name.ToString() == "SpecialNameAttribute") - && _.Parameters.Count == args.Length + && !_.IsConstructor && !_.IsDestructor + && _.Attributes.GetAll().Any(__ => + __?.AttributeType?.Name.ToString() == "SpecialNameAttribute") + && _.Parameters.Count == args.Length ); ImmutableDictionary nameMap = null; @@ -51,21 +48,26 @@ public static bool TryGetOperator(this IType type, string op, out IMethod opMeth nameMap = binMap; } - possibleMethods = possibleMethods.Where(_ => nameMap.ContainsValue(_.Name.ToString()) && nameMap[op] == _.Name.ToString()); + possibleMethods = + possibleMethods.Where(_ => nameMap.ContainsValue(_.Name.ToString()) && nameMap[op] == _.Name.ToString()); foreach (var method in possibleMethods) { - for (int i = 0; i < args.Length; i++) + for (var i = 0; i < args.Length; i++) { var arg = args[i]; var param = method.Parameters[i].Type; - if (arg != param) goto nextMethod; + if (arg != param) + { + goto nextMethod; + } } + opMethod = method; return true; - nextMethod: continue; + nextMethod: ; } opMethod = null; diff --git a/Source/Backlang.Driver/InternalMacros/IntrinsicsMacros.cs b/Source/Backlang.Driver/InternalMacros/IntrinsicsMacros.cs index 299e8de..f2f69aa 100644 --- a/Source/Backlang.Driver/InternalMacros/IntrinsicsMacros.cs +++ b/Source/Backlang.Driver/InternalMacros/IntrinsicsMacros.cs @@ -1,5 +1,4 @@ using LeMP; -using Loyc.Syntax; using System.Reflection; namespace Backlang.Driver.InternalMacros; @@ -61,7 +60,8 @@ public static LNode InlineBlock(LNode node, IMacroContext context) return LNode.Call((Symbol)"'{}", newBodyArgs).WithStyle(NodeStyle.Operator); } - private static LNode ConvertCall(LNode calls, CompilerContext context, Dictionary availableConstants) + private static LNode ConvertCall(LNode calls, CompilerContext context, + Dictionary availableConstants) { var newArgs = new LNodeList(); @@ -86,7 +86,8 @@ private static LNode ConvertCall(LNode calls, CompilerContext context, Dictionar } else { - newArgs.Add(LNode.Call((Symbol)$"#{constantValue.GetType().Name}", LNode.List(LNode.Literal(constantValue)))); + newArgs.Add(LNode.Call((Symbol)$"#{constantValue.GetType().Name}", + LNode.List(LNode.Literal(constantValue)))); } } else diff --git a/Source/Backlang.Driver/InternalMacros/SyntacticMacros.cs b/Source/Backlang.Driver/InternalMacros/SyntacticMacros.cs index 88f9537..6c1236b 100644 --- a/Source/Backlang.Driver/InternalMacros/SyntacticMacros.cs +++ b/Source/Backlang.Driver/InternalMacros/SyntacticMacros.cs @@ -13,52 +13,48 @@ public static class SyntacticMacros ["mul"] = ("Multiply", 2), ["div"] = ("Division", 2), ["mod"] = ("Modulus", 2), - ["logical_not"] = ("LogicalNot", 1), - ["neg"] = ("UnaryNegation", 1), - ["bitwise_and"] = ("BitwiseAnd", 2), ["bitwise_or"] = ("BitwiseOr", 2), ["exclusive_or"] = ("ExclusiveOr", 2), - ["equality"] = ("Equality", 2), ["inequality"] = ("Inequality", 2), - ["bitwise_not"] = ("OnesComplement", 1), ["unpacking"] = ("Unpacking", 1), - ["deref"] = ("Deref", 1), ["addrof"] = ("AddressOf", 2), - - ["percent"] = ("Percentage", 1), + ["percent"] = ("Percentage", 1) }; - private static readonly LNodeFactory F = new LNodeFactory(EmptySourceFile.Synthetic); + private static readonly LNodeFactory F = new(EmptySourceFile.Synthetic); - [LexicalMacro("constructor()", "Convert constructor() to .ctor() function", "#constructor", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro("constructor()", "Convert constructor() to .ctor() function", "#constructor", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode Constructor(LNode node, IMacroContext context) { var factory = new LNodeFactory(node.Source); SyntaxTree.Factory = factory; - return SyntaxTree.Signature(SyntaxTree.Type(".ctor", new()), + return SyntaxTree.Signature(SyntaxTree.Type(".ctor", new LNodeList()), SyntaxTree.Type("none", LNode.List()), node.Args[0].Args, - new()).PlusArg(node.Args[1]).WithAttrs(node.Attrs).WithRange(node.Range); + new LNodeList()).PlusArg(node.Args[1]).WithAttrs(node.Attrs).WithRange(node.Range); } - [LexicalMacro("destructor()", "Convert destructor() to .dtor() function", "#destructor", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro("destructor()", "Convert destructor() to .dtor() function", "#destructor", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode Destructor(LNode node, IMacroContext context) { var factory = new LNodeFactory(node.Source); SyntaxTree.Factory = factory; - return SyntaxTree.Signature(SyntaxTree.Type(".dtor", new()), - SyntaxTree.Type("none", LNode.List()), node.Args[0].Args, new()) + return SyntaxTree.Signature(SyntaxTree.Type(".dtor", new LNodeList()), + SyntaxTree.Type("none", LNode.List()), node.Args[0].Args, new LNodeList()) .PlusArg(node.Args[1]).WithAttrs(node.Attrs).WithRange(node.Range); } - [LexicalMacro(".dtor()", "Convert destructor() or .dtor() to Finalize", ".dtor", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro(".dtor()", "Convert destructor() or .dtor() to Finalize", ".dtor", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode DestructorNormalisation(LNode @operator, IMacroContext context) { return @operator.WithTarget(LNode.Id("Finalize")); @@ -71,7 +67,7 @@ public static LNode DivEquals(LNode @operator, IMacroContext context) } [LexicalMacro("#fn", "Transform function", "#fn", - Mode = MacroMode.MatchIdentifierOrCall | MacroMode.ProcessChildrenBefore)] + Mode = MacroMode.MatchIdentifierOrCall | MacroMode.ProcessChildrenBefore)] public static LNode TransformFunction(LNode node, IMacroContext context) { node = ExpandOperator(node, context); @@ -86,7 +82,10 @@ private static LNode ExpandNotnullAssertionPostfix(LNode node, IMacroContext con var newBody = new LNodeList(); var newParameters = new LNodeList(); - if(node.ArgCount == 0) return node; + if (node.ArgCount == 0) + { + return node; + } foreach (var parameter in node[2].Args) { @@ -96,10 +95,13 @@ private static LNode ExpandNotnullAssertionPostfix(LNode node, IMacroContext con { var name = parameter[1][0]; - var throwNode = LNode.Call(CodeSymbols.Throw, LNode.List(LNode.Call(CodeSymbols.String, LNode.List(LNode.Literal($"Parameter '{name.Name}' is none"))))); + var throwNode = LNode.Call(CodeSymbols.Throw, + LNode.List(LNode.Call(CodeSymbols.String, + LNode.List(LNode.Literal($"Parameter '{name.Name}' is none"))))); var ifBody = LNode.Call(CodeSymbols.Braces, LNode.List(throwNode)); - newBody = newBody.Add(SyntaxTree.If(LNode.Call(CodeSymbols.Eq, LNode.List(name, SyntaxTree.None())), ifBody, LNode.Missing)); + newBody = newBody.Add(SyntaxTree.If(LNode.Call(CodeSymbols.Eq, LNode.List(name, SyntaxTree.None())), + ifBody, LNode.Missing)); } newParameters.Add(parameter.WithoutAttrNamed(nonNullAttribute.Name)); @@ -118,18 +120,22 @@ private static LNode ExpandOperator(LNode @operator, IMacroContext context) var operatorAttribute = SyntaxTree.Factory.Id((Symbol)"#operator"); if (@operator.Attrs.Contains(operatorAttribute)) { - var newAttrs = new LNodeList() { LNode.Id(CodeSymbols.Public), LNode.Id(CodeSymbols.Static), LNode.Id(CodeSymbols.Operator) }; + var newAttrs = new LNodeList + { + LNode.Id(CodeSymbols.Public), LNode.Id(CodeSymbols.Static), LNode.Id(CodeSymbols.Operator) + }; var modChanged = @operator.WithAttrs(newAttrs); var fnName = @operator.Args[1]; var compContext = (CompilerContext)context.ScopedProperties["Context"]; - if (fnName is (_, (_, var name)) && OpMap.ContainsKey(name.Name.Name)) + if (fnName is var (_, (_, name)) && OpMap.ContainsKey(name.Name.Name)) { var op = OpMap[name.Name.Name]; if (@operator[2].ArgCount != op.ArgumentCount) { - compContext.AddError(@operator, $"Cannot overload operator, parameter count mismatch. {op.ArgumentCount} parameters expected"); + compContext.AddError(@operator, + $"Cannot overload operator, parameter count mismatch. {op.ArgumentCount} parameters expected"); } var newTarget = SyntaxTree.Type("op_" + op.OperatorName, LNode.List()).WithRange(fnName.Range); @@ -143,17 +149,18 @@ private static LNode ExpandOperator(LNode @operator, IMacroContext context) [LexicalMacro("12%", "divide by 100 (percent)", "'%", Mode = MacroMode.MatchIdentifierOrCall)] public static LNode Percentage(LNode @operator, IMacroContext context) { - if (@operator is (_, var inner)) + if (@operator is var (_, inner)) { if (inner.ArgCount == 1 && inner.Args[0] is LiteralNode ln) { - dynamic percentValue = ((dynamic)ln.Value) / 100; + var percentValue = (dynamic)ln.Value / 100; if (percentValue is int pi) { return LNode.Call(CodeSymbols.Int32, LNode.List(LNode.Literal(pi))); } - else if (percentValue is double di) + + if (percentValue is double di) { return LNode.Call(Symbols.Float32, LNode.List(LNode.Literal(di))); } @@ -169,9 +176,15 @@ public static LNode Percentage(LNode @operator, IMacroContext context) [LexicalMacro("^hat", "Gets a handle for the variable", "'^", Mode = MacroMode.MatchIdentifierOrCall)] public static LNode HandleOperator(LNode @operator, IMacroContext context) { - if (@operator.Args.Count != 1) return @operator; + if (@operator.Args.Count != 1) + { + return @operator; + } - if (!@operator.Args[0].IsId) context.Error("Expected Identifier for HandleOperator"); + if (!@operator.Args[0].IsId) + { + context.Error("Expected Identifier for HandleOperator"); + } return LNode.Call( LNode.Call(LNode.Id("::"), LNode.List( @@ -207,7 +220,8 @@ public static LNode Instantiation(LNode node, IMacroContext context) return node; } - [LexicalMacro("target(dotnet) {}", "Only Compile Code If CompilationTarget Is Selected", "target", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro("target(dotnet) {}", "Only Compile Code If CompilationTarget Is Selected", "target", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode TargetMacro(LNode node, IMacroContext context) { var target = (string)context.ScopedProperties["Target"]; @@ -223,7 +237,8 @@ public static LNode TargetMacro(LNode node, IMacroContext context) return LNode.Call((Symbol)"'{}"); } - [LexicalMacro("left -= right;", "Convert to left = left - something", "'-=", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro("left -= right;", "Convert to left = left - something", "'-=", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode MinusEquals(LNode @operator, IMacroContext context) { return ConvertToAssignment(@operator, CodeSymbols.Sub); @@ -240,25 +255,29 @@ public static LNode NoneCheckShortcut(LNode node, IMacroContext context) return SyntaxTree.If(condition, LNode.Call(CodeSymbols.Braces, body), LNode.Missing); } - [LexicalMacro("left *= right;", "Convert to left = left * something", "'*=", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro("left *= right;", "Convert to left = left * something", "'*=", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode MulEquals(LNode @operator, IMacroContext context) { return ConvertToAssignment(@operator, CodeSymbols.Mul); } - [LexicalMacro("left += right;", "Convert to left = left + something", "'+=", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro("left += right;", "Convert to left = left + something", "'+=", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode PlusEquals(LNode @operator, IMacroContext context) { return ConvertToAssignment(@operator, CodeSymbols.Add); } - [LexicalMacro("left |= right;", "Convert to left = left | something", "'|=", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro("left |= right;", "Convert to left = left | something", "'|=", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode OrEquals(LNode @operator, IMacroContext context) { return ConvertToAssignment(@operator, CodeSymbols.Or); } - [LexicalMacro("left &= right;", "Convert to left = left & something", "'&=", Mode = MacroMode.MatchIdentifierOrCall)] + [LexicalMacro("left &= right;", "Convert to left = left & something", "'&=", + Mode = MacroMode.MatchIdentifierOrCall)] public static LNode AndEquals(LNode @operator, IMacroContext context) { return ConvertToAssignment(@operator, CodeSymbols.And); @@ -271,7 +290,8 @@ public static LNode PowerOperator(LNode node, IMacroContext context) var right = node.Args[1]; var powCall = F.Call(F.Call(CodeSymbols.Dot, LNode.List( - LNode.Call(CodeSymbols.Dot, LNode.List(LNode.Id((Symbol)"System"), LNode.Id((Symbol)"Math"))).SetStyle(NodeStyle.Operator), + LNode.Call(CodeSymbols.Dot, LNode.List(LNode.Id((Symbol)"System"), LNode.Id((Symbol)"Math"))) + .SetStyle(NodeStyle.Operator), LNode.Id((Symbol)"Pow"))).SetStyle(NodeStyle.Operator), LNode.List(left, right)); return powCall.WithRange(node.Range); @@ -280,39 +300,41 @@ public static LNode PowerOperator(LNode node, IMacroContext context) [LexicalMacro("\"hello $name\"", "Interpolate a string", "#string")] public static LNode InterpolateString(LNode node, IMacroContext context) { - if (node is (_, var valueNode)) + if (node is var (_, valueNode)) { - string formatString = valueNode.Value.ToString(); + var formatString = valueNode.Value.ToString(); if (formatString.Contains('$')) { var formatArgs = new List(); - int counter = 0; + var counter = 0; - formatString = Regex.Replace(formatString, "\\$(?\\w[0-9a-zA-Z_]*)(:(\\{(?[0-9a-zA-Z_]*)\\}))?", _ => { - var sb = new StringBuilder(); - sb.Append('{').Append(counter++); + formatString = Regex.Replace(formatString, + "\\$(?\\w[0-9a-zA-Z_]*)(:(\\{(?[0-9a-zA-Z_]*)\\}))?", _ => { + var sb = new StringBuilder(); + sb.Append('{').Append(counter++); - var options = _.Groups["options"].Value; + var options = _.Groups["options"].Value; - if (!string.IsNullOrEmpty(options)) - { - sb.Append(':').Append(options); - } + if (!string.IsNullOrEmpty(options)) + { + sb.Append(':').Append(options); + } - sb.Append('}'); + sb.Append('}'); - var varRange = new SourceRange(valueNode.Range.Source, - _.Index + node.Range.StartIndex + 1, _.Length); + var varRange = new SourceRange(valueNode.Range.Source, + _.Index + node.Range.StartIndex + 1, _.Length); - formatArgs.Add(SyntaxTree.Factory.Id(_.Groups["name"].Value).WithRange(varRange)); + formatArgs.Add(SyntaxTree.Factory.Id(_.Groups["name"].Value).WithRange(varRange)); - return sb.ToString(); - }); + return sb.ToString(); + }); - formatArgs.Insert(0, SyntaxTree.Factory.Call(CodeSymbols.String, LNode.List(SyntaxTree.Factory.Literal(formatString)))); + formatArgs.Insert(0, + SyntaxTree.Factory.Call(CodeSymbols.String, LNode.List(SyntaxTree.Factory.Literal(formatString)))); - node = ExtensionUtils.coloncolon("string", LNode.Call((Symbol)"Format").WithArgs(formatArgs)); + node = "string".coloncolon(LNode.Call((Symbol)"Format").WithArgs(formatArgs)); } } diff --git a/Source/Backlang.Driver/QualifiedNameDeconstructors.cs b/Source/Backlang.Driver/QualifiedNameDeconstructors.cs index 879d267..50ff66f 100644 --- a/Source/Backlang.Driver/QualifiedNameDeconstructors.cs +++ b/Source/Backlang.Driver/QualifiedNameDeconstructors.cs @@ -1,4 +1,5 @@ namespace Backlang.Driver; + public static class QualifiedNameDeconstructors { public static void Deconstruct(this QualifiedName qualified, out string qualifier, out string unqualified) @@ -6,4 +7,4 @@ public static void Deconstruct(this QualifiedName qualified, out string qualifie qualifier = qualified.Qualifier.ToString(); unqualified = qualified.FullyUnqualifiedName.ToString(); } -} +} \ No newline at end of file diff --git a/Source/Backlang.Driver/TypeDeducer.cs b/Source/Backlang.Driver/TypeDeducer.cs index ca72c1e..e1c36de 100644 --- a/Source/Backlang.Driver/TypeDeducer.cs +++ b/Source/Backlang.Driver/TypeDeducer.cs @@ -1,34 +1,28 @@ using Backlang.Codeanalysis.Core; using Backlang.Contracts.TypeSystem; -using System.Linq.Expressions; namespace Backlang.Driver; public static class TypeDeducer { - public static readonly ImmutableDictionary TypenameTable = new Dictionary() + public static readonly ImmutableDictionary TypenameTable = new Dictionary { ["obj"] = CodeSymbols.Object, ["none"] = CodeSymbols.Void, - ["bool"] = CodeSymbols.Bool, - ["u8"] = CodeSymbols.UInt8, ["u16"] = CodeSymbols.UInt16, ["u32"] = CodeSymbols.UInt32, ["u64"] = CodeSymbols.UInt64, - ["i8"] = CodeSymbols.Int8, ["i16"] = CodeSymbols.Int16, ["i32"] = CodeSymbols.Int32, ["i64"] = CodeSymbols.Int64, - ["f16"] = Symbols.Float16, ["f32"] = Symbols.Float32, ["f64"] = Symbols.Float64, - ["char"] = CodeSymbols.Char, - ["string"] = CodeSymbols.String, + ["string"] = CodeSymbols.String }.ToImmutableDictionary(); //ToDo: check for implicit cast @@ -38,32 +32,37 @@ public static IType Deduce(LNode node, Scope scope, CompilerContext context, Qua { return ImplementationStage.GetLiteralType(node, context, scope, modulename); } + if (TypenameTable.ContainsKey(node.Name.Name)) { return Deduce(LNode.Id(TypenameTable[node.Name.Name]), scope, context, modulename); } - else if (node.Calls(CodeSymbols.Typeof)) + + if (node.Calls(CodeSymbols.Typeof)) { return Utils.ResolveType(context.Binder, typeof(Type)); } - else if (node.Calls(Symbols.Unit) && node is (_, var value, var unit)) + + if (node.Calls(Symbols.Unit) && node is var (_, value, unit)) { return DeduceUnitType(scope, context, modulename, value, unit); } - else if (node.Calls(CodeSymbols.As) && node is (_, var expr, var castType)) + + if (node.Calls(CodeSymbols.As) && node is var (_, expr, castType)) { return Deduce(castType, scope, context, modulename); } - else if (node.ArgCount == 1 && node.Calls(CodeSymbols.Default)) + + if (node.ArgCount == 1 && node.Calls(CodeSymbols.Default)) { - if (node is (_, (_, (_, var type)))) + if (node is var (_, (_, (_, type)))) { return Deduce(type, scope, context, modulename); } } else if (node.Calls(CodeSymbols.New)) { - if (node is (_, var call)) + if (node is var (_, call)) { return Deduce(call.Target, scope, context, modulename); } @@ -90,25 +89,24 @@ public static IType Deduce(LNode node, Scope scope, CompilerContext context, Qua { return item?.Type; } - else - { - var type = TypeInheritanceStage.ResolveTypeWithModule(node, context, modulename); - - if (type != null) - { - return type; - } - var suggestion = LevensteinDistance.Suggest(node.Name.Name, scope.GetAllScopeNames()); + var type = TypeInheritanceStage.ResolveTypeWithModule(node, context, modulename); - context.AddError(node, $"{node.Name} cannot be resolved. Did you mean '{suggestion}'?"); + if (type != null) + { + return type; } + + var suggestion = LevensteinDistance.Suggest(node.Name.Name, scope.GetAllScopeNames()); + + context.AddError(node, $"{node.Name} cannot be resolved. Did you mean '{suggestion}'?"); } return null; } - public static IType DeduceFunctionReturnType(LNode funcDefinition, CompilerContext context, Scope scope, QualifiedName modulename) + public static IType DeduceFunctionReturnType(LNode funcDefinition, CompilerContext context, Scope scope, + QualifiedName modulename) { var returnNodes = funcDefinition.Descendants().Where(_ => _.Calls(CodeSymbols.Return)).ToArray(); @@ -147,11 +145,12 @@ private static IType FindCommonType(IType first, IType second) return first; } - if (ImplicitTypeCastTable.IsAssignableTo(first, second)) + if (first.IsAssignableTo(second)) { return first; } - if (ImplicitTypeCastTable.IsAssignableTo(second, first)) + + if (second.IsAssignableTo(first)) { return second; } @@ -168,12 +167,14 @@ private static IType FindCommonType(IType first, IType second) if (first.BaseTypes.Count > 0 && second.BaseTypes.Count > 0) { - if (first.BaseTypes[0].FullName.ToString() == "System.ValueType" || second.BaseTypes[0].FullName.ToString() == "System.ValueType") + if (first.BaseTypes[0].FullName.ToString() == "System.ValueType" || + second.BaseTypes[0].FullName.ToString() == "System.ValueType") { return null; } - if (first.BaseTypes[0].FullName.ToString() == "System.Object" || second.BaseTypes[0].FullName.ToString() == "System.Object") + if (first.BaseTypes[0].FullName.ToString() == "System.Object" || + second.BaseTypes[0].FullName.ToString() == "System.Object") { return null; } @@ -189,7 +190,8 @@ private static IType FindCommonType(IType first, IType second) return null; } - public static void ExpectType(LNode node, Scope scope, CompilerContext context, QualifiedName modulename, IType expectedType) + public static void ExpectType(LNode node, Scope scope, CompilerContext context, QualifiedName modulename, + IType expectedType) { var deducedType = Deduce(node, scope, context, modulename); @@ -199,7 +201,8 @@ public static void ExpectType(LNode node, Scope scope, CompilerContext context, } } - public static IType NotExpectType(LNode node, Scope scope, CompilerContext context, QualifiedName modulename, IType expectedType) + public static IType NotExpectType(LNode node, Scope scope, CompilerContext context, QualifiedName modulename, + IType expectedType) { var deducedType = Deduce(node, scope, context, modulename); @@ -211,7 +214,8 @@ public static IType NotExpectType(LNode node, Scope scope, CompilerContext conte return deducedType; } - private static IType DeduceUnitType(Scope scope, CompilerContext context, QualifiedName modulename, LNode value, LNode unit) + private static IType DeduceUnitType(Scope scope, CompilerContext context, QualifiedName modulename, LNode value, + LNode unit) { var resolvedUnit = TypeInheritanceStage.ResolveTypeWithModule(unit, context, modulename); @@ -226,7 +230,7 @@ private static IType DeduceUnitType(Scope scope, CompilerContext context, Qualif private static IType DeduceArray(LNode node, Scope scope, CompilerContext context, QualifiedName modulename) { //ToDo: Make deducing array type better - int rank = GetArrayRank(node); + var rank = GetArrayRank(node); while (node.ArgCount > 0 && node[0].Calls(CodeSymbols.Array)) { @@ -238,14 +242,16 @@ private static IType DeduceArray(LNode node, Scope scope, CompilerContext contex private static int GetArrayRank(LNode node) { - int rank = 0; + var rank = 0; while (node.Calls(CodeSymbols.Array)) { rank++; if (node.ArgCount > 0) + { node = node[0]; + } } return rank; @@ -253,7 +259,8 @@ private static int GetArrayRank(LNode node) private static IType DeduceTuple(LNode node, Scope scope, CompilerContext context, QualifiedName modulename) { - var tupleType = context.Binder.ResolveTypes(new SimpleName("Tuple`" + node.ArgCount).Qualify("System")).FirstOrDefault(); + var tupleType = context.Binder.ResolveTypes(new SimpleName("Tuple`" + node.ArgCount).Qualify("System")) + .FirstOrDefault(); if (tupleType == null) { @@ -273,12 +280,15 @@ private static IType DeduceTuple(LNode node, Scope scope, CompilerContext contex private static IType DeduceBinary(LNode node, Scope scope, CompilerContext context, QualifiedName moduleName) { if (node.Calls(CodeSymbols.Add) || node.Calls(CodeSymbols.Mul) - || node.Calls(CodeSymbols.Div) || node.Calls(CodeSymbols.Sub) || node.Calls(CodeSymbols.AndBits) - || node.Calls(CodeSymbols.OrBits) || node.Calls((Symbol)"'^") || node.Calls(CodeSymbols.Mod)) + || node.Calls(CodeSymbols.Div) || node.Calls(CodeSymbols.Sub) || + node.Calls(CodeSymbols.AndBits) + || node.Calls(CodeSymbols.OrBits) || node.Calls((Symbol)"'^") || + node.Calls(CodeSymbols.Mod)) { return DeduceBinaryHelper(node, scope, context, moduleName); } - else if (node.Calls(CodeSymbols.LT) + + if (node.Calls(CodeSymbols.LT) || node.Calls(CodeSymbols.GT) || node.Calls(CodeSymbols.LE) || node.Calls(CodeSymbols.GE)) { @@ -287,19 +297,23 @@ private static IType DeduceBinary(LNode node, Scope scope, CompilerContext conte return context.Environment.Boolean; } - else if (node.Calls(CodeSymbols.Eq) || node.Calls(CodeSymbols.NotEq)) + + if (node.Calls(CodeSymbols.Eq) || node.Calls(CodeSymbols.NotEq)) { return context.Environment.Boolean; } - else if (node.Calls(CodeSymbols.As)) + + if (node.Calls(CodeSymbols.As)) { return DeduceExplicitCast(node, scope, context, moduleName); } - else if (node.Calls(CodeSymbols.Dot)) + + if (node.Calls(CodeSymbols.Dot)) { return DeduceMember(node, scope, context, moduleName); } - else if (node.Calls(CodeSymbols.ColonColon)) + + if (node.Calls(CodeSymbols.ColonColon)) { return DeduceStaticMethod(node, scope, context, moduleName); } @@ -336,7 +350,7 @@ private static IType DeduceStaticMethod(LNode node, Scope scope, CompilerContext } else { - context.AddError(node, $"Mismatching Parameter count: {type.FullName.ToString() + "::" + fnName}()"); + context.AddError(node, $"Mismatching Parameter count: {type.FullName + "::" + fnName}()"); } return null; @@ -358,7 +372,8 @@ private static IType DeduceMember(LNode node, Scope scope, CompilerContext conte } var funcArgs = node[1].Args.Select(_ => Deduce(_, scope, context, modulename)); - var func = context.Binder.FindFunction(left.ToString() + "::" + qualified.Name + "(" + string.Join(',', funcArgs) + ")"); + var func = context.Binder.FindFunction( + left + "::" + qualified.Name + "(" + string.Join(',', funcArgs) + ")"); return func.ReturnParameter.Type; } @@ -390,7 +405,8 @@ private static IType DeduceUnary(LNode node, Scope scope, CompilerContext contex { return left.MakePointerType(PointerKind.Transient); } - else if (node.Calls(CodeSymbols._Dereference)) + + if (node.Calls(CodeSymbols._Dereference)) { if (left is PointerType pt) { @@ -433,7 +449,8 @@ private static IType DeduceBinaryHelper(LNode node, Scope scope, CompilerContext { return left; } - else if (right is UnitType && left is not UnitType) + + if (right is UnitType && left is not UnitType) { return right; } @@ -444,7 +461,8 @@ private static IType DeduceBinaryHelper(LNode node, Scope scope, CompilerContext return left; } - else if (right.IsPointerType()) + + if (right.IsPointerType()) { ExpectType(node.Args[0], scope, context, modulename, context.Environment.Int32); diff --git a/Source/Backlang.Driver/Utils.cs b/Source/Backlang.Driver/Utils.cs index 7731185..e5d8ce6 100644 --- a/Source/Backlang.Driver/Utils.cs +++ b/Source/Backlang.Driver/Utils.cs @@ -43,12 +43,13 @@ public static string GenerateIdentifier() public static bool IsUnitType(CompilerContext context, IType resolvedUnit) { var attr = resolvedUnit.Attributes.GetAll(); - var attrType = Utils.ResolveType(context.Binder, typeof(UnitTypeAttribute)); + var attrType = ResolveType(context.Binder, typeof(UnitTypeAttribute)); return attr.Select(_ => _.AttributeType).Contains(attrType); } - public static void AddCompilerGeneratedAttribute(TypeResolver binder, DescribedType type) { + public static void AddCompilerGeneratedAttribute(TypeResolver binder, DescribedType type) + { var attributeType = ResolveType(binder, typeof(CompilerGeneratedAttribute)); type.AddAttribute(new DescribedAttribute(attributeType)); diff --git a/Source/Backlang.NET.Sdk/AssemblyResolver.cs b/Source/Backlang.NET.Sdk/AssemblyResolver.cs index 9dc37ef..9a1215e 100644 --- a/Source/Backlang.NET.Sdk/AssemblyResolver.cs +++ b/Source/Backlang.NET.Sdk/AssemblyResolver.cs @@ -2,56 +2,56 @@ using System.IO; using System.Reflection; -namespace Backlang.NET.Sdk +namespace Backlang.NET.Sdk; + +internal sealed class AssemblyResolver { - internal sealed class AssemblyResolver + /// + /// Build task directory containing our assemblies. + /// + private static readonly string s_path = + Path.GetDirectoryName(Path.GetFullPath(typeof(AssemblyResolver).Assembly.Location)); + + /// + /// Resolve assembly. + /// + private static readonly ResolveEventHandler assemblyresolver = AssemblyResolve; + + public static void InitializeSafe() { - /// - /// Build task directory containing our assemblies. - /// - private static readonly string s_path = Path.GetDirectoryName(Path.GetFullPath(typeof(AssemblyResolver).Assembly.Location)); + try + { + var domain = AppDomain.CurrentDomain; - /// - /// Resolve assembly. - /// - private static ResolveEventHandler assemblyresolver = new ResolveEventHandler(AssemblyResolve); + // re-add the event handler - public static void InitializeSafe() + domain.AssemblyResolve -= assemblyresolver; + domain.AssemblyResolve += assemblyresolver; + } + catch { - try - { - var domain = AppDomain.CurrentDomain; + } + } - // re-add the event handler + private static Assembly AssemblyResolve(object sender, ResolveEventArgs args) + { + // try to resolve assemblies within our task directory + // we'll ignore the minor version of the requested assembly + var assname = new AssemblyName(args.Name); - domain.AssemblyResolve -= assemblyresolver; - domain.AssemblyResolve += assemblyresolver; - } - catch + try + { + var hintpath = Path.Combine(s_path, assname.Name + ".dll"); + if (File.Exists(hintpath)) { + // try to load the assembly: + return Assembly.LoadFile(hintpath); } } - - private static Assembly AssemblyResolve(object sender, ResolveEventArgs args) + catch { - // try to resolve assemblies within our task directory - // we'll ignore the minor version of the requested assembly - var assname = new AssemblyName(args.Name); - - try - { - var hintpath = Path.Combine(s_path, assname.Name + ".dll"); - if (File.Exists(hintpath)) - { - // try to load the assembly: - return Assembly.LoadFile(hintpath); - } - } - catch - { - } - - return null; } + + return null; } } \ No newline at end of file diff --git a/Source/Backlang.NET.Sdk/Backlang.NET.Sdk.csproj b/Source/Backlang.NET.Sdk/Backlang.NET.Sdk.csproj index 10bf06a..fde921a 100644 --- a/Source/Backlang.NET.Sdk/Backlang.NET.Sdk.csproj +++ b/Source/Backlang.NET.Sdk/Backlang.NET.Sdk.csproj @@ -1,88 +1,88 @@  - - net9.0 - Backlang.NET.Sdk - preview - True - - true - false - false - - Backlang.NET.Sdk - backlang;sdk;back;msbuild - True - The MSBuild SDK containing build targets and runtime. - $(Version) - $(Version) - logo.png - https://github.com/Backlang-Org/Backlang - https://www.backlang.org - - - - true - false - true - $(MSBuildThisFileDirectory)bin\$(Configuration)\$(TargetFramework)\publish - $(MSBuildThisFileDirectory)$(MSbuildProjectName).nuspec - - - - - - + + net9.0 + Backlang.NET.Sdk + preview + True - - - - InitializeSourceControlInformation; - BuildOnlySettings; - PrepareForBuild; - PreBuildEvent; - ResolveProjectReferences; - GetTargetPath; - PrepareForRun; - IncrementalClean; - PostBuildEvent - - + true + false + false - - - - - + Backlang.NET.Sdk + backlang;sdk;back;msbuild + True + The MSBuild SDK containing build targets and runtime. + $(Version) + $(Version) + logo.png + https://github.com/Backlang-Org/Backlang + https://www.backlang.org + - - - - + + true + false + true + $(MSBuildThisFileDirectory)bin\$(Configuration)\$(TargetFramework)\publish + $(MSBuildThisFileDirectory)$(MSbuildProjectName).nuspec + - - - + + + + - - - $(NuspecProperties);id=$(PackageId) - $(NuspecProperties);packToolsDir=$(PackToolsDir) - $(NuspecProperties);description=$(Description) - $(NuspecProperties);version=$(PackageVersion) + + + + InitializeSourceControlInformation; + BuildOnlySettings; + PrepareForBuild; + PreBuildEvent; + ResolveProjectReferences; + GetTargetPath; + PrepareForRun; + IncrementalClean; + PostBuildEvent + - - - <_PropsLine Include="<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">" /> - <_PropsLine Include="<PropertyGroup>" /> - <_PropsLine Include=" <BacklangVersion Condition=" '%24(BacklangVersion)'=='' ">$(PackageVersion)</BacklangVersion>" /> - <_PropsLine Include="</PropertyGroup>" /> - <_PropsLine Include="</Project>" /> + + + + + + + + - - + + + + + + + + $(NuspecProperties);id=$(PackageId) + $(NuspecProperties);packToolsDir=$(PackToolsDir) + $(NuspecProperties);description=$(Description) + $(NuspecProperties);version=$(PackageVersion) + + + + + + <_PropsLine Include="<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">"/> + <_PropsLine Include="<PropertyGroup>"/> + <_PropsLine Include=" <BacklangVersion Condition=" '%24(BacklangVersion)'=='' ">$(PackageVersion)</BacklangVersion>"/> + <_PropsLine Include="</PropertyGroup>"/> + <_PropsLine Include="</Project>"/> + + + diff --git a/Source/Backlang.NET.Sdk/Backlang.NET.Sdk.nuspec b/Source/Backlang.NET.Sdk/Backlang.NET.Sdk.nuspec index c5b5109..1d921d2 100644 --- a/Source/Backlang.NET.Sdk/Backlang.NET.Sdk.nuspec +++ b/Source/Backlang.NET.Sdk/Backlang.NET.Sdk.nuspec @@ -1,28 +1,28 @@ - - $id$ - $version$ - Backlang.NET.Sdk - furesoft - furesoft,Backlang - https://github.com/Backseating-Committee-2k/Backlang - false - $description$ - - Backlang,compile-Backlang,sdk - - - - - - - - + + $id$ + $version$ + Backlang.NET.Sdk + furesoft + furesoft,Backlang + https://github.com/Backseating-Committee-2k/Backlang + false + $description$ + + Backlang,compile-Backlang,sdk + + + + + + + + \ No newline at end of file diff --git a/Source/Backlang.NET.Sdk/BuildTask.cs b/Source/Backlang.NET.Sdk/BuildTask.cs index 7d3c36b..a8c0320 100644 --- a/Source/Backlang.NET.Sdk/BuildTask.cs +++ b/Source/Backlang.NET.Sdk/BuildTask.cs @@ -1,4 +1,5 @@ -using Backlang.Contracts; +using Backlang.Codeanalysis.Parsing; +using Backlang.Contracts; using Backlang.Driver; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; @@ -9,205 +10,201 @@ using System.Text; using System.Threading; -namespace Backlang.NET.Sdk +namespace Backlang.NET.Sdk; + +public class BuildTask : Task, ICancelableTask { - public class BuildTask : Task, ICancelableTask - { - private CancellationTokenSource _cancellation = new CancellationTokenSource(); + private CancellationTokenSource _cancellation = new(); - [Required] - public string[] Compile { get; set; } + [Required] public string[] Compile { get; set; } - public string DebugType { get; set; } + public string DebugType { get; set; } - public string EntryPoint { get; set; } - public bool GenerateFullPaths { get; set; } - public string[] MacroReferences { get; set; } - public string NetFrameworkPath { get; set; } - public string NoWarn { get; set; } + public string EntryPoint { get; set; } + public bool GenerateFullPaths { get; set; } + public string[] MacroReferences { get; set; } + public string NetFrameworkPath { get; set; } + public string NoWarn { get; set; } - /// - /// Optimization level. - /// Can be a boolean value (true/false), an integer specifying the level(0-9), or an optimization name (debug, release). - public string Optimization { get; set; } = bool.TrueString; + /// + /// Optimization level. + /// Can be a boolean value (true/false), an integer specifying the level(0-9), or an optimization name (debug, + /// release). + /// + public string Optimization { get; set; } = bool.TrueString; - [Required] - public string OutputName { get; set; } + [Required] public string OutputName { get; set; } - [Required] - public string OutputPath { get; set; } + [Required] public string OutputPath { get; set; } - public string OutputTree { get; set; } - public string OutputType { get; set; } - public string Path { get; set; } - public string ProjectFile { get; set; } - public string CorLib { get; set; } - public string[] Resources { get; set; } - public string ResultingOutputPath { get; set; } - public string Target { get; set; } + public string OutputTree { get; set; } + public string OutputType { get; set; } + public string Path { get; set; } + public string ProjectFile { get; set; } + public string CorLib { get; set; } + public string[] Resources { get; set; } + public string ResultingOutputPath { get; set; } + public string Target { get; set; } - [Required] - public string TargetFramework { get; set; } + [Required] public string TargetFramework { get; set; } - [Required] - public string TempOutputPath { get; set; } + [Required] public string TempOutputPath { get; set; } - public string Version { get; set; } + public string Version { get; set; } - public void Cancel() - { - _cancellation.Cancel(); - } + public void Cancel() + { + _cancellation.Cancel(); + } - public override bool Execute() - { - _cancellation = new CancellationTokenSource(); + public override bool Execute() + { + _cancellation = new CancellationTokenSource(); - // initiate our assembly resolver within MSBuild process: - AssemblyResolver.InitializeSafe(); + // initiate our assembly resolver within MSBuild process: + AssemblyResolver.InitializeSafe(); - var filename = System.IO.Path.GetFileName(Path); - Path = Path.Substring(0, Path.Length - filename.Length); + var filename = System.IO.Path.GetFileName(Path); + Path = Path.Substring(0, Path.Length - filename.Length); - Compile = Compile.Select(_ => Path + _).ToArray(); - Resources = Resources == null ? Array.Empty() : Resources.Select(_ => Path + _).ToArray(); + Compile = Compile.Select(_ => Path + _).ToArray(); + Resources = Resources == null ? Array.Empty() : Resources.Select(_ => Path + _).ToArray(); - try + try + { + if (Compile == null) { - if (Compile == null) - { - Log.LogError("No Source Files specified."); - return false; - } + Log.LogError("No Source Files specified."); + return false; + } - var context = new CompilerContext(); - context.Options.InputFiles = Compile; - context.Options.OutputFilename = OutputName; - context.Options.OutputType = OutputType; - context.Options.Version = Version; - context.Options.EmbeddedResource = Resources; - context.Options.TargetFramework = TargetFramework; - - context.TempOutputPath = TempOutputPath; - context.OutputPath = OutputPath; - context.MacroReferences = MacroReferences; - context.ResultingOutputPath = ResultingOutputPath; - context.ProjectFile = ProjectFile; - context.CorLib = CorLib; - - if (!string.IsNullOrEmpty(OutputTree)) - { - context.Options.OutputTree = bool.Parse(OutputTree); - } + var context = new CompilerContext(); + context.Options.InputFiles = Compile; + context.Options.OutputFilename = OutputName; + context.Options.OutputType = OutputType; + context.Options.Version = Version; + context.Options.EmbeddedResource = Resources; + context.Options.TargetFramework = TargetFramework; + + context.TempOutputPath = TempOutputPath; + context.OutputPath = OutputPath; + context.MacroReferences = MacroReferences; + context.ResultingOutputPath = ResultingOutputPath; + context.ProjectFile = ProjectFile; + context.CorLib = CorLib; + + if (!string.IsNullOrEmpty(OutputTree)) + { + context.Options.OutputTree = bool.Parse(OutputTree); + } - CompilerDriver.Compile(context); + CompilerDriver.Compile(context); - foreach (var msg in context.Messages) + foreach (var msg in context.Messages) + { + if (msg.Severity == MessageSeverity.Error) { - if (msg.Severity == Codeanalysis.Parsing.MessageSeverity.Error) - { - Log.LogError(msg.ToString()); - } - else - { - Log.LogWarning(msg.ToString()); - } + Log.LogError(msg.ToString()); + } + else + { + Log.LogWarning(msg.ToString()); } - - return !context.Messages.Any(); - } - catch (Exception ex) - { - LogException(ex); - return false; } - } - public bool IsCanceled() + return !context.Messages.Any(); + } + catch (Exception ex) { - return _cancellation != null && _cancellation.IsCancellationRequested; + LogException(ex); + return false; } + } + + public bool IsCanceled() + { + return _cancellation != null && _cancellation.IsCancellationRequested; + } - private void LogException(Exception ex) + private void LogException(Exception ex) + { + if (ex is AggregateException aex && aex.InnerExceptions != null) { - if (ex is AggregateException aex && aex.InnerExceptions != null) - { - foreach (var innerEx in aex.InnerExceptions) - { - LogException(innerEx); - } - } - else + foreach (var innerEx in aex.InnerExceptions) { - Log.LogErrorFromException(ex, true); + LogException(innerEx); } } + else + { + Log.LogErrorFromException(ex, true); + } + } - // honestly I don't know why msbuild in VS does not handle Console.Output, - // so we have our custom TextWriter that we pass to Log - private sealed class LogWriter : TextWriter + // honestly I don't know why msbuild in VS does not handle Console.Output, + // so we have our custom TextWriter that we pass to Log + private sealed class LogWriter : TextWriter + { + public LogWriter(TaskLoggingHelper log) { - public LogWriter(TaskLoggingHelper log) - { - Debug.Assert(log != null); + Debug.Assert(log != null); - Log = log; - NewLine = "\n"; - } + Log = log; + NewLine = "\n"; + } - public override Encoding Encoding => Encoding.UTF8; - private StringBuilder Buffer { get; } = new StringBuilder(); - private TaskLoggingHelper Log { get; } + public override Encoding Encoding => Encoding.UTF8; + private StringBuilder Buffer { get; } = new(); + private TaskLoggingHelper Log { get; } - public override void Write(char value) + public override void Write(char value) + { + lock (Buffer) // accessed in parallel { - lock (Buffer) // accessed in parallel - { - Buffer.Append(value); - } - - if (value == '\n') - { - TryLogCompleteMessage(); - } + Buffer.Append(value); } - public override void Write(string value) + if (value == '\n') { - lock (Buffer) - { - Buffer.Append(value); - } - TryLogCompleteMessage(); } + } - private bool LogCompleteMessage(string line) + public override void Write(string value) + { + lock (Buffer) { - return Log.LogMessageFromText(line.Trim(), MessageImportance.High); + Buffer.Append(value); } - private bool TryLogCompleteMessage() - { - string line = null; + TryLogCompleteMessage(); + } - lock (Buffer) // accessed in parallel + private bool LogCompleteMessage(string line) + { + return Log.LogMessageFromText(line.Trim(), MessageImportance.High); + } + + private bool TryLogCompleteMessage() + { + string line = null; + + lock (Buffer) // accessed in parallel + { + // get line from the buffer: + for (var i = 0; i < Buffer.Length; i++) { - // get line from the buffer: - for (var i = 0; i < Buffer.Length; i++) + if (Buffer[i] == '\n') { - if (Buffer[i] == '\n') - { - line = Buffer.ToString(0, i); + line = Buffer.ToString(0, i); - Buffer.Remove(0, i + 1); - } + Buffer.Remove(0, i + 1); } } - - // - return line != null && LogCompleteMessage(line); } + + // + return line != null && LogCompleteMessage(line); } } } \ No newline at end of file diff --git a/Source/Backlang.NET.Sdk/Sdk/Sdk.props b/Source/Backlang.NET.Sdk/Sdk/Sdk.props index 8359ff2..7e56d8b 100644 --- a/Source/Backlang.NET.Sdk/Sdk/Sdk.props +++ b/Source/Backlang.NET.Sdk/Sdk/Sdk.props @@ -1,20 +1,20 @@  - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + - - .back - false + + .back + false - - true - true - false - + + true + true + false + - + - + \ No newline at end of file diff --git a/Source/Backlang.NET.Sdk/Sdk/Sdk.targets b/Source/Backlang.NET.Sdk/Sdk/Sdk.targets index db27f0a..3157d30 100644 --- a/Source/Backlang.NET.Sdk/Sdk/Sdk.targets +++ b/Source/Backlang.NET.Sdk/Sdk/Sdk.targets @@ -1,12 +1,12 @@  - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + - + - - - + + + \ No newline at end of file diff --git a/Source/Backlang.NET.Sdk/Sdk/Version.props b/Source/Backlang.NET.Sdk/Sdk/Version.props index 70aec1f..2dfb15a 100644 --- a/Source/Backlang.NET.Sdk/Sdk/Version.props +++ b/Source/Backlang.NET.Sdk/Sdk/Version.props @@ -1,4 +1,4 @@  - - + + \ No newline at end of file diff --git a/Source/Backlang.NET.Sdk/build/Backlang.DesignTime.targets b/Source/Backlang.NET.Sdk/build/Backlang.DesignTime.targets index dc9850d..946ae1e 100644 --- a/Source/Backlang.NET.Sdk/build/Backlang.DesignTime.targets +++ b/Source/Backlang.NET.Sdk/build/Backlang.DesignTime.targets @@ -1,36 +1,36 @@  - - - $(MSBuildExtensionsPath)\Microsoft\VisualStudio\Managed\Microsoft.Managed.DesignTime.targets - - + + + $(MSBuildExtensionsPath)\Microsoft\VisualStudio\Managed\Microsoft.Managed.DesignTime.targets + + - - - Backlang - + + + Backlang + - - - - - File - - - BrowseObject - - + + + + + File + + + BrowseObject + + - - - - + + + + - - - - <_CompilerCommandLineArgs Include="@(BacklangCommandLineArgs)" /> - - + + + + <_CompilerCommandLineArgs Include="@(BacklangCommandLineArgs)"/> + + \ No newline at end of file diff --git a/Source/Backlang.NET.Sdk/build/Backlang.NET.Core.Sdk.targets b/Source/Backlang.NET.Sdk/build/Backlang.NET.Core.Sdk.targets index 8c4b40e..3451395 100644 --- a/Source/Backlang.NET.Sdk/build/Backlang.NET.Core.Sdk.targets +++ b/Source/Backlang.NET.Sdk/build/Backlang.NET.Core.Sdk.targets @@ -1,38 +1,38 @@  - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - Backlang - Managed - true - true - true - true - - - - - - - - - - - <_DebugSymbolsIntermediatePathTemporary Include="$(PdbFile)" /> - - <_DebugSymbolsIntermediatePath Include="@(_DebugSymbolsIntermediatePathTemporary->'%(RootDir)%(Directory)%(Filename).pdb')" /> - - - - _ComputeNonExistentFileProperty - - - - - <_ExplicitReference Include="$(FrameworkPathOverride)\mscorlib.dll" /> - - - + + + + + <_DebugSymbolsIntermediatePathTemporary Include="$(PdbFile)"/> + + <_DebugSymbolsIntermediatePath Include="@(_DebugSymbolsIntermediatePathTemporary->'%(RootDir)%(Directory)%(Filename).pdb')"/> + + + + _ComputeNonExistentFileProperty + + + + + <_ExplicitReference Include="$(FrameworkPathOverride)\mscorlib.dll"/> + + + - - - - - - - - <_Temporary Remove="@(_Temporary)" /> - - - - - - - - - - - - - - - - - - <_Temporary Remove="@(_Temporary)" /> - - - - - + + + <_Temporary Remove="@(_Temporary)"/> + + + + + + + + + + + + + + + + + + <_Temporary Remove="@(_Temporary)"/> + + + + + + Returns="@(BacklangCommandLineArgs)" + DependsOnTargets="$(CoreCompileDependsOn)"> - - mscorlib - netcore + + mscorlib + netcore - - <_DotNetHostExecutableName>dotnet - <_DotNetHostExecutableName Condition=" '$(OS)' == 'Windows_NT' ">$(_DotNetHostExecutableName).exe - <_DotNetHostExecutableDirectory>$(MSBuildSDKsPath)/../../.. - <_DotNetHostExecutablePath>$(_DotNetHostExecutableDirectory)/$(_DotNetHostExecutableName) - - - - - <_FscTask_FscToolExe>$(_DotNetHostExecutableName) - <_FscTask_FscToolPath>$(_DotNetHostExecutableDirectory) - <_FscTask_DotnetFscCompilerPath> "$(FscToolPath)/$(FscToolExe)" - - - - <_FscTask_FscToolExe>$(FscToolExe) - <_FscTask_FscToolPath>$(FscToolPath) - <_FscTask_DotnetFscCompilerPath> - - - - %(IntermediateAssembly.RelativeDir) - library - - - - - - - - - - - - - - - $(_DotNetHostExecutableName).exe + <_DotNetHostExecutableDirectory>$(MSBuildSDKsPath)/../../.. + <_DotNetHostExecutablePath>$(_DotNetHostExecutableDirectory)/$(_DotNetHostExecutableName) + + + + + <_FscTask_FscToolExe>$(_DotNetHostExecutableName) + <_FscTask_FscToolPath>$(_DotNetHostExecutableDirectory) + <_FscTask_DotnetFscCompilerPath>"$(FscToolPath)/$(FscToolExe)" + + + + <_FscTask_FscToolExe>$(FscToolExe) + <_FscTask_FscToolPath>$(FscToolPath) + <_FscTask_DotnetFscCompilerPath> + + + + %(IntermediateAssembly.RelativeDir) + library + + + + + + + + + + + + + + + - - - - - @(CoreLibReference)@(StandardReference) - - - - - - - - - - - - - - - - - - $(TargetFramework) - - - - - - $(MSBuildProjectFullPath) - + '%(Filename)' == 'mscorlib' "/> + + + + + @(CoreLibReference)@(StandardReference) + + + + + + + + + + + + + + + + + + $(TargetFramework) + + + + + + $(MSBuildProjectFullPath) + \ No newline at end of file diff --git a/Source/Backlang.NET.Sdk/build/Backlang.NET.Current.Sdk.targets b/Source/Backlang.NET.Sdk/build/Backlang.NET.Current.Sdk.targets index b6cfed7..5194c5a 100644 --- a/Source/Backlang.NET.Sdk/build/Backlang.NET.Current.Sdk.targets +++ b/Source/Backlang.NET.Sdk/build/Backlang.NET.Current.Sdk.targets @@ -1,26 +1,26 @@  - - - true - + + true + - - + + - + - - - + + + - + \ No newline at end of file diff --git a/Source/Backlang.NET.Sdk/build/Backlang.NET.Sdk.props b/Source/Backlang.NET.Sdk/build/Backlang.NET.Sdk.props index ca0d89d..19432a2 100644 --- a/Source/Backlang.NET.Sdk/build/Backlang.NET.Sdk.props +++ b/Source/Backlang.NET.Sdk/build/Backlang.NET.Sdk.props @@ -1,18 +1,18 @@  - - 4 + + 4 - - $(MSBuildThisFileDirectory)/../tools/Backlang.NET.Sdk.dll + + $(MSBuildThisFileDirectory)/../tools/Backlang.NET.Sdk.dll - - {F2A71F9B-5D33-465A-A702-920D77279786} + + {F2A71F9B-5D33-465A-A702-920D77279786} - - $(MSBuildThisFileDirectory)Backlang.NET.Current.Sdk.targets - + + $(MSBuildThisFileDirectory)Backlang.NET.Current.Sdk.targets + - - + + \ No newline at end of file diff --git a/Source/Backlang.NET.Sdk/build/Backlang.Version.props b/Source/Backlang.NET.Sdk/build/Backlang.Version.props index 8a26967..49a208c 100644 --- a/Source/Backlang.NET.Sdk/build/Backlang.Version.props +++ b/Source/Backlang.NET.Sdk/build/Backlang.Version.props @@ -1,5 +1,5 @@ - -1.0.0 - + + 1.0.0 + diff --git a/Source/Backlang.NET.Sdk/build/ProjectItemsSchema.xaml b/Source/Backlang.NET.Sdk/build/ProjectItemsSchema.xaml index 0128611..d79d3a9 100644 --- a/Source/Backlang.NET.Sdk/build/ProjectItemsSchema.xaml +++ b/Source/Backlang.NET.Sdk/build/ProjectItemsSchema.xaml @@ -1,4 +1,5 @@  + - - - $(MSBuildToolsPath)\Microsoft.Common.CrossTargeting.targets - + + + $(MSBuildToolsPath)\Microsoft.Common.CrossTargeting.targets + - - $(MSBuildProjectFullPath) - + + $(MSBuildProjectFullPath) + diff --git a/Source/Backlang.WasmBridge/Backlang.WasmBridge.csproj b/Source/Backlang.WasmBridge/Backlang.WasmBridge.csproj index d8074a4..30d9e55 100644 --- a/Source/Backlang.WasmBridge/Backlang.WasmBridge.csproj +++ b/Source/Backlang.WasmBridge/Backlang.WasmBridge.csproj @@ -1,16 +1,16 @@  - - net9.0 - browser-wasm - main.mjs - Exe - true - true - preview - True - - - - - + + net9.0 + browser-wasm + main.mjs + Exe + true + true + preview + True + + + + + diff --git a/Source/Backlang.WasmBridge/Bridge.cs b/Source/Backlang.WasmBridge/Bridge.cs index d04f0f4..acfcc03 100644 --- a/Source/Backlang.WasmBridge/Bridge.cs +++ b/Source/Backlang.WasmBridge/Bridge.cs @@ -2,7 +2,6 @@ using Backlang.Driver; using System; using System.IO; -using System.Reflection; using System.Runtime.InteropServices.JavaScript; using System.Text; @@ -12,7 +11,7 @@ public partial class Bridge public static string CompileAndRun(string src) { var context = new CompilerContext(); - context.Playground = new() { IsPlayground = true, Source = src }; + context.Playground = new PlaygroundData { IsPlayground = true, Source = src }; var assemblyStream = new MemoryStream(); diff --git a/Source/Backlang.WasmBridge/main.mjs b/Source/Backlang.WasmBridge/main.mjs index 409a9d6..8a67f13 100644 --- a/Source/Backlang.WasmBridge/main.mjs +++ b/Source/Backlang.WasmBridge/main.mjs @@ -1,15 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { dotnet } from './dotnet.js' +import {dotnet} from './dotnet.js' -const { setModuleImports, getAssemblyExports, getConfig } = await dotnet +const {setModuleImports, getAssemblyExports, getConfig} = await dotnet .withDiagnosticTracing(false) .create(); -setModuleImports('main.mjs', { - -}); +setModuleImports('main.mjs', {}); const config = getConfig(); const exports = await getAssemblyExports(config.mainAssemblyName); diff --git a/Source/Backlang.WasmBridge/runtimeconfig.template.json b/Source/Backlang.WasmBridge/runtimeconfig.template.json index 4fac149..b7093f7 100644 --- a/Source/Backlang.WasmBridge/runtimeconfig.template.json +++ b/Source/Backlang.WasmBridge/runtimeconfig.template.json @@ -1,16 +1,16 @@ { - "wasmHostProperties": { - "perHostConfig": [ - { - "name": "node", - "js-path": "main.mjs", - "Host": "nodejs" - }, - { - "name": "v8", - "js-path": "main.mjs", - "Host": "v8" - } - ] - } + "wasmHostProperties": { + "perHostConfig": [ + { + "name": "node", + "js-path": "main.mjs", + "Host": "nodejs" + }, + { + "name": "v8", + "js-path": "main.mjs", + "Host": "v8" + } + ] + } } diff --git a/Source/Plugins/Backlang.Backends.Bs2k/Addresses.cs b/Source/Plugins/Backlang.Backends.Bs2k/Addresses.cs index 67dd8db..14db0f5 100644 --- a/Source/Plugins/Backlang.Backends.Bs2k/Addresses.cs +++ b/Source/Plugins/Backlang.Backends.Bs2k/Addresses.cs @@ -14,5 +14,5 @@ public enum Addresses TERMINAL_CURSOR_POINTER = 8000, TERMINAL_BUFFER_START = 0, - TERMINAL_BUFFER_END = 8000, + TERMINAL_BUFFER_END = 8000 } \ No newline at end of file diff --git a/Source/Plugins/Backlang.Backends.Bs2k/Backlang.Backends.Bs2k.csproj b/Source/Plugins/Backlang.Backends.Bs2k/Backlang.Backends.Bs2k.csproj index 36e8e2b..ae891de 100644 --- a/Source/Plugins/Backlang.Backends.Bs2k/Backlang.Backends.Bs2k.csproj +++ b/Source/Plugins/Backlang.Backends.Bs2k/Backlang.Backends.Bs2k.csproj @@ -1,30 +1,30 @@ - - net9.0 - enable - enable - preview - True - True - A backend for backlang for the bs2k emulation system - https://www.backlang.org - logo.png - https://github.com/Backlang-Org/Backlang - backlang, plugin, backend, bs2k - + + net9.0 + enable + enable + preview + True + True + A backend for backlang for the bs2k emulation system + https://www.backlang.org + logo.png + https://github.com/Backlang-Org/Backlang + backlang, plugin, backend, bs2k + - - - - + + + + - - - True - \ - - + + + True + \ + + - + diff --git a/Source/Plugins/Backlang.Backends.Bs2k/Bs2kAssembly.cs b/Source/Plugins/Backlang.Backends.Bs2k/Bs2kAssembly.cs index 0197274..d3646bb 100644 --- a/Source/Plugins/Backlang.Backends.Bs2k/Bs2kAssembly.cs +++ b/Source/Plugins/Backlang.Backends.Bs2k/Bs2kAssembly.cs @@ -19,7 +19,8 @@ public void WriteTo(Stream output) var types = Contents.Assembly.Types; - foreach (var er in Contents.Assembly.Attributes.GetAll().Where(_ => _ is EmbeddedResourceAttribute).Cast()) + foreach (var er in Contents.Assembly.Attributes.GetAll().Where(_ => _ is EmbeddedResourceAttribute) + .Cast()) { var rawStrm = new MemoryStream(); er.Strm.CopyTo(rawStrm); diff --git a/Source/Plugins/Backlang.Backends.Bs2k/Constants.cs b/Source/Plugins/Backlang.Backends.Bs2k/Constants.cs index b58ce87..1f2e7ec 100644 --- a/Source/Plugins/Backlang.Backends.Bs2k/Constants.cs +++ b/Source/Plugins/Backlang.Backends.Bs2k/Constants.cs @@ -18,5 +18,5 @@ public enum Constants TERMINAL_BUFFER_SIZE = 8000, FRAMEBUFFER_SIZE = 691200, - STACK_SIZE = 524288, + STACK_SIZE = 524288 } \ No newline at end of file diff --git a/Source/Plugins/Backlang.Backends.Bs2k/Emitter.cs b/Source/Plugins/Backlang.Backends.Bs2k/Emitter.cs index 59f87bc..b881cf0 100644 --- a/Source/Plugins/Backlang.Backends.Bs2k/Emitter.cs +++ b/Source/Plugins/Backlang.Backends.Bs2k/Emitter.cs @@ -12,10 +12,10 @@ namespace Backlang.Backends.Bs2k; public class Emitter { - private readonly IMethod _mainMethod; private readonly StringBuilder _builder = new(); + private readonly IMethod _mainMethod; - private Dictionary _stringConstants = new(); + private readonly Dictionary _stringConstants = new(); public Emitter(IMethod mainMethod) { @@ -75,7 +75,10 @@ public void EmitStringConstants(IType program) Emit("\n", null, 0); } - public override string ToString() => _builder.ToString(); + public override string ToString() + { + return _builder.ToString(); + } public void Emit(string instruction, string? comment = null, int indentlevel = 1) { @@ -108,8 +111,6 @@ private void EmitBinary(IntrinsicPrototype arith, int indentlevel) case "arith.<=": Emit("comp_le R1, R2, R3", null, indentlevel); break; case "arith.>": Emit("comp_gt R1, R2, R3", null, indentlevel); break; case "arith.>=": Emit("comp_ge R1, R2, R3", null, indentlevel); break; - default: - break; } Emit("push R3", "push result onto stack", indentlevel); @@ -181,30 +182,31 @@ private void EmitInstruction(BasicBlock block, Instruction instruction, int inde switch (instruction.Prototype) { case CallPrototype callPrototype: + { + if (IntrinsicHelper.IsIntrinsicType(typeof(Intrinsics), callPrototype)) { - if (IntrinsicHelper.IsIntrinsicType(typeof(Intrinsics), callPrototype)) - { - var intrinsic = IntrinsicHelper.InvokeIntrinsic(typeof(Intrinsics), - callPrototype.Callee, instruction, block).ToString(); + var intrinsic = IntrinsicHelper.InvokeIntrinsic(typeof(Intrinsics), + callPrototype.Callee, instruction, block).ToString(); - Emit("//emited from intrinsic", null, indentlevel); - foreach (var intr in intrinsic.Split("\n")) - { - Emit(intr, null, indentlevel); - } - - return; + Emit("//emited from intrinsic", null, indentlevel); + foreach (var intr in intrinsic.Split("\n")) + { + Emit(intr, null, indentlevel); } - var callee = callPrototype.Callee - .ParentType.FullName.FullyUnqualifiedName.ToString() == Names.FreeFunctions - ? callPrototype.Callee.Name.ToString() : callPrototype.Callee.FullName.ToString(); - - Emit($"// Calling '{callee}'", null, indentlevel); - EmitCall(instruction, block.Graph, indentlevel); - break; + return; } + var callee = callPrototype.Callee + .ParentType.FullName.FullyUnqualifiedName.ToString() == Names.FreeFunctions + ? callPrototype.Callee.Name.ToString() + : callPrototype.Callee.FullName.ToString(); + + Emit($"// Calling '{callee}'", null, indentlevel); + EmitCall(instruction, block.Graph, indentlevel); + break; + } + case NewObjectPrototype newObjectPrototype: break; diff --git a/Source/Plugins/Backlang.Backends.Bs2k/Intrinsics.cs b/Source/Plugins/Backlang.Backends.Bs2k/Intrinsics.cs index e5fa35c..4e2156e 100644 --- a/Source/Plugins/Backlang.Backends.Bs2k/Intrinsics.cs +++ b/Source/Plugins/Backlang.Backends.Bs2k/Intrinsics.cs @@ -8,83 +8,203 @@ public static class Intrinsics public static Constants constants; - public static string Label(string label) => $"{label}:\n"; - - public static string Copy(char value, string target) => Copy((int)value, target); - - public static string Copy(char value, Register target) => Copy((int)value, target); - - public static string Copy(int value, string target) => $"copy {value}, {target}"; - - public static string Copy(int value, Register target) => $"copy {value}, {target}"; - - public static string Jump(string label) => $"jump {label}"; - - public static string Jump(Register register) => $"jump {register}"; - - public static string Jump_Eq(Register register, Register addr) => $"jump_eq {register}, {addr}"; - - public static string Jump_Eq(Register register, string addr) => $"jump_eq {register}, {addr}"; - - public static string Jump_Neq(Register register, string addr) => $"jump_neq {register}, {addr}"; - - public static string Jump_Neq(Register register, Register addr) => $"jump_neq {register}, {addr}"; - - public static string Jump_Gt(Register register, string addr) => $"jump_gt {register}, {addr}"; - - public static string Jump_Gt(Register register, Register addr) => $"jump_gt {register}, {addr}"; - - public static string Jump_Ge(Register register, string addr) => $"jump_ge {register}, {addr}"; - - public static string Jump_Ge(Register register, Register addr) => $"jump_ge {register}, {addr}"; - - public static string Jump_Lt(Register register, string addr) => $"jump_lt {register}, {addr}"; - - public static string Jump_Lt(Register register, Register addr) => $"jump_lt {register}, {addr}"; - - public static string Jump_Le(Register register, string addr) => $"jump_le {register}, {addr}"; - - public static string Jump_Le(Register register, Register addr) => $"jump_le {register}, {addr}"; - - public static string Push(Register register) => $"push {register}"; - - public static string Push(int value) => $"copy {value}, R0\npush R0"; - - public static string Push(char value) => Push((int)value); - - public static string Pop(Register register) => $"pop {register}"; - - public static string Pop() => $"pop"; - - public static string Ret() => "return"; - - public static string NoOp() => "noop"; - - public static string Halt() => "halt"; - - public static string Add(Register lhs, Register rhs, Register target) => $"add {lhs}, {rhs}, {target}"; - - public static string Sub(Register lhs, Register rhs, Register target) => $"sub {lhs}, {rhs}, {target}"; - - public static string Mult(Register lhs, Register rhs, Register high, Register low) => $"add {lhs}, {rhs}, {high}, {low}"; - - public static string Divmod(Register lhs, Register rhs, Register result, Register remainder) => $"divmod {lhs}, {rhs}, {result}, {remainder}"; - - public static string And(Register lhs, Register rhs, Register target) => $"and {lhs}, {rhs}, {target}"; - - public static string Or(Register lhs, Register rhs, Register target) => $"or {lhs}, {rhs}, {target}"; - - public static string Comp(Register lhs, Register rhs, Register target) => $"comp {lhs}, {rhs}, {target}"; - - public static string Comp_Eq(Register lhs, Register rhs, Register target) => $"comp_eq {lhs}, {rhs}, {target}"; - - public static string Comp_Neq(Register lhs, Register rhs, Register target) => $"comp_neq {lhs}, {rhs}, {target}"; - - public static string Comp_Gt(Register lhs, Register rhs, Register target) => $"comp_gt {lhs} {rhs}, {target}"; - - public static string Comp_Ge(Register lhs, Register rhs, Register target) => $"comp_ge {lhs}, {rhs}, {target}"; - - public static string Comp_Lt(Register lhs, Register rhs, Register target) => $"comp_lt {lhs}, {rhs}, {target}"; - - public static string Comp_Le(Register lhs, Register rhs, Register target) => $"comp_le {lhs}, {rhs}, {target}"; + public static string Label(string label) + { + return $"{label}:\n"; + } + + public static string Copy(char value, string target) + { + return Copy((int)value, target); + } + + public static string Copy(char value, Register target) + { + return Copy((int)value, target); + } + + public static string Copy(int value, string target) + { + return $"copy {value}, {target}"; + } + + public static string Copy(int value, Register target) + { + return $"copy {value}, {target}"; + } + + public static string Jump(string label) + { + return $"jump {label}"; + } + + public static string Jump(Register register) + { + return $"jump {register}"; + } + + public static string Jump_Eq(Register register, Register addr) + { + return $"jump_eq {register}, {addr}"; + } + + public static string Jump_Eq(Register register, string addr) + { + return $"jump_eq {register}, {addr}"; + } + + public static string Jump_Neq(Register register, string addr) + { + return $"jump_neq {register}, {addr}"; + } + + public static string Jump_Neq(Register register, Register addr) + { + return $"jump_neq {register}, {addr}"; + } + + public static string Jump_Gt(Register register, string addr) + { + return $"jump_gt {register}, {addr}"; + } + + public static string Jump_Gt(Register register, Register addr) + { + return $"jump_gt {register}, {addr}"; + } + + public static string Jump_Ge(Register register, string addr) + { + return $"jump_ge {register}, {addr}"; + } + + public static string Jump_Ge(Register register, Register addr) + { + return $"jump_ge {register}, {addr}"; + } + + public static string Jump_Lt(Register register, string addr) + { + return $"jump_lt {register}, {addr}"; + } + + public static string Jump_Lt(Register register, Register addr) + { + return $"jump_lt {register}, {addr}"; + } + + public static string Jump_Le(Register register, string addr) + { + return $"jump_le {register}, {addr}"; + } + + public static string Jump_Le(Register register, Register addr) + { + return $"jump_le {register}, {addr}"; + } + + public static string Push(Register register) + { + return $"push {register}"; + } + + public static string Push(int value) + { + return $"copy {value}, R0\npush R0"; + } + + public static string Push(char value) + { + return Push((int)value); + } + + public static string Pop(Register register) + { + return $"pop {register}"; + } + + public static string Pop() + { + return "pop"; + } + + public static string Ret() + { + return "return"; + } + + public static string NoOp() + { + return "noop"; + } + + public static string Halt() + { + return "halt"; + } + + public static string Add(Register lhs, Register rhs, Register target) + { + return $"add {lhs}, {rhs}, {target}"; + } + + public static string Sub(Register lhs, Register rhs, Register target) + { + return $"sub {lhs}, {rhs}, {target}"; + } + + public static string Mult(Register lhs, Register rhs, Register high, Register low) + { + return $"add {lhs}, {rhs}, {high}, {low}"; + } + + public static string Divmod(Register lhs, Register rhs, Register result, Register remainder) + { + return $"divmod {lhs}, {rhs}, {result}, {remainder}"; + } + + public static string And(Register lhs, Register rhs, Register target) + { + return $"and {lhs}, {rhs}, {target}"; + } + + public static string Or(Register lhs, Register rhs, Register target) + { + return $"or {lhs}, {rhs}, {target}"; + } + + public static string Comp(Register lhs, Register rhs, Register target) + { + return $"comp {lhs}, {rhs}, {target}"; + } + + public static string Comp_Eq(Register lhs, Register rhs, Register target) + { + return $"comp_eq {lhs}, {rhs}, {target}"; + } + + public static string Comp_Neq(Register lhs, Register rhs, Register target) + { + return $"comp_neq {lhs}, {rhs}, {target}"; + } + + public static string Comp_Gt(Register lhs, Register rhs, Register target) + { + return $"comp_gt {lhs} {rhs}, {target}"; + } + + public static string Comp_Ge(Register lhs, Register rhs, Register target) + { + return $"comp_ge {lhs}, {rhs}, {target}"; + } + + public static string Comp_Lt(Register lhs, Register rhs, Register target) + { + return $"comp_lt {lhs}, {rhs}, {target}"; + } + + public static string Comp_Le(Register lhs, Register rhs, Register target) + { + return $"comp_le {lhs}, {rhs}, {target}"; + } } \ No newline at end of file diff --git a/Source/Plugins/Backlang.Backends.Bs2k/NameMangler.cs b/Source/Plugins/Backlang.Backends.Bs2k/NameMangler.cs index fbfea3f..ed0dd79 100644 --- a/Source/Plugins/Backlang.Backends.Bs2k/NameMangler.cs +++ b/Source/Plugins/Backlang.Backends.Bs2k/NameMangler.cs @@ -19,7 +19,7 @@ public static string Mangle(IMethod method) sb.Append(ns); } - sb.Append(method.FullName.FullyUnqualifiedName.ToString()); + sb.Append(method.FullName.FullyUnqualifiedName); foreach (var param in method.Parameters) { diff --git a/Source/Plugins/Backlang.Backends.Bs2k/Register.cs b/Source/Plugins/Backlang.Backends.Bs2k/Register.cs index 0f04872..0b19766 100644 --- a/Source/Plugins/Backlang.Backends.Bs2k/Register.cs +++ b/Source/Plugins/Backlang.Backends.Bs2k/Register.cs @@ -261,5 +261,5 @@ public enum Register Flags = R253, IP = R254, - SP = R255, + SP = R255 } \ No newline at end of file diff --git a/Source/Plugins/Backlang.Backends.Bs2k/StackLayoutGenerator.cs b/Source/Plugins/Backlang.Backends.Bs2k/StackLayoutGenerator.cs index 8d1c6c4..66d7a8c 100644 --- a/Source/Plugins/Backlang.Backends.Bs2k/StackLayoutGenerator.cs +++ b/Source/Plugins/Backlang.Backends.Bs2k/StackLayoutGenerator.cs @@ -36,4 +36,4 @@ private int RoundUp(int num_to_round, int multiple) return remainder == 0 ? num_to_round : num_to_round + multiple - remainder; } -} +} \ No newline at end of file diff --git a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/Backlang.ResourcePreprocessor.Mif.csproj b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/Backlang.ResourcePreprocessor.Mif.csproj index eae90a4..53d01d0 100644 --- a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/Backlang.ResourcePreprocessor.Mif.csproj +++ b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/Backlang.ResourcePreprocessor.Mif.csproj @@ -1,30 +1,30 @@  - - net9.0 - enable - enable - preview - True - True - A resource preprocessor for mif files - https://www.backlang.org - logo.png - https://github.com/Backlang-Org/Backlang - backlang, plugin, preprocessor - + + net9.0 + enable + enable + preview + True + True + A resource preprocessor for mif files + https://www.backlang.org + logo.png + https://github.com/Backlang-Org/Backlang + backlang, plugin, preprocessor + - - - + + + - - - True - \ - - + + + True + \ + + - + diff --git a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/MifParser.cs b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/MifParser.cs index b31879f..8fe7f4b 100644 --- a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/MifParser.cs +++ b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/MifParser.cs @@ -5,7 +5,7 @@ namespace Backlang.ResourcePreprocessor.Mif.MifFormat; public class MifParser { - private static Tokenizer tokenizer; + private static readonly Tokenizer tokenizer; private int _position; @@ -20,7 +20,6 @@ static MifParser() .Token(TokenType.ADDRESS_RADIX, @"ADDRESS_RADIX") .Token(TokenType.DATA_RADIX, @"DATA_RADIX") .Token(TokenType.Radix, string.Join('|', Enum.GetNames())) - .Token(TokenType.Number, @"[-]?[0-9A-F]+") .Token(TokenType.Colon, @":") .Ignore(TokenType.Comment, @"--.+") @@ -125,7 +124,7 @@ private long ParseNumber(Radix radix) Radix.HEX => Convert.ToInt64(token.Value, 16), Radix.DEC => Convert.ToInt64(token.Value, 10), Radix.UNS => (long)Convert.ToUInt64(token.Value, 10), - _ => 0, + _ => 0 }; } @@ -155,7 +154,9 @@ private void ParserOption(MifFile file) } if (value != null) + { file.Options.Add(key, value); + } Match(TokenType.Semicolon); } @@ -176,9 +177,11 @@ private int ParseNumber() if (int.TryParse(token.Value, out var iR)) + { return iR; - else - return Convert.ToInt32(token.Value, 16); + } + + return Convert.ToInt32(token.Value, 16); } private Radix ParseRadix() @@ -224,7 +227,10 @@ private bool IsMatch(params TokenType[] types) foreach (var t in types) { - if (token.Type == t) return true; + if (token.Type == t) + { + return true; + } } return false; diff --git a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/Miftokenizer.cs b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/Miftokenizer.cs index d91e22b..2006f35 100644 --- a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/Miftokenizer.cs +++ b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/Miftokenizer.cs @@ -17,15 +17,20 @@ public Token(TType type, string value) public class Tokenizer { - private readonly IList tokenTypes = new List(); private readonly TType defaultTokenType; + private readonly IList tokenTypes = new List(); - public Tokenizer(TType defaultTokenType) => this.defaultTokenType = defaultTokenType; + public Tokenizer(TType defaultTokenType) + { + this.defaultTokenType = defaultTokenType; + } public Tokenizer Token(TType type, params string[] matchingRegexs) { foreach (var matchingRegex in matchingRegexs) + { tokenTypes.Add(new TokenType(type, matchingRegex, false)); + } return this; } @@ -33,7 +38,9 @@ public Tokenizer Token(TType type, params string[] matchingRegexs) public Tokenizer Ignore(TType type, params string[] matchingRegexs) { foreach (var matchingRegex in matchingRegexs) + { tokenTypes.Add(new TokenType(type, matchingRegex, true)); + } return this; } @@ -42,7 +49,9 @@ public IList> Tokenize(string input) { IEnumerable> tokens = new[] { new Token(defaultTokenType, input) }; foreach (var type in tokenTypes) + { tokens = ExtractTokenType(tokens, type); + } return tokens.ToList(); } @@ -71,7 +80,10 @@ private IEnumerable> ExtractTokenType( var currentIndex = 0; foreach (Match match in matches) { - if (toExtract.Ignore) continue; + if (toExtract.Ignore) + { + continue; + } if (currentIndex < match.Index) { diff --git a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/TokenType.cs b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/TokenType.cs index 74dbc5e..95afa31 100644 --- a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/TokenType.cs +++ b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifFormat/TokenType.cs @@ -17,5 +17,5 @@ public enum TokenType Width, DEPTH, ADDRESS_RADIX, - DATA_RADIX, + DATA_RADIX } \ No newline at end of file diff --git a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifPreprocessor.cs b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifPreprocessor.cs index a0c09ac..2509fd2 100644 --- a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifPreprocessor.cs +++ b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/MifPreprocessor.cs @@ -1,19 +1,19 @@ using Backlang.Contracts; +using Backlang.ResourcePreprocessor.Mif.MifFormat; using System.ComponentModel.Composition; -namespace Backlang.ResourcePreprocessor.Mif +namespace Backlang.ResourcePreprocessor.Mif; + +[Export(typeof(IResourcePreprocessor))] +public class MifPreprocessor : IResourcePreprocessor { - [Export(typeof(IResourcePreprocessor))] - public class MifPreprocessor : IResourcePreprocessor - { - public string Extension => ".mif"; + public string Extension => ".mif"; - public Stream Preprocess(Stream strm) - { - var file = MifFormat.MifParser.Parse(new StreamReader(strm).ReadToEnd()); - var raw = MifFormat.MifTranslator.Translate(file); + public Stream Preprocess(Stream strm) + { + var file = MifParser.Parse(new StreamReader(strm).ReadToEnd()); + var raw = MifTranslator.Translate(file); - return new MemoryStream(raw); - } + return new MemoryStream(raw); } } \ No newline at end of file diff --git a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/Radix.cs b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/Radix.cs index f6c57c8..5772167 100644 --- a/Source/Plugins/Backlang.ResourcePreprocessor.Mif/Radix.cs +++ b/Source/Plugins/Backlang.ResourcePreprocessor.Mif/Radix.cs @@ -6,5 +6,5 @@ public enum Radix OCT, HEX, DEC, - UNS, + UNS } \ No newline at end of file diff --git a/Source/TestProject1/AST/Declarations/EnumTests.cs b/Source/TestProject1/AST/Declarations/EnumTests.cs index 4808660..d8e6b12 100644 --- a/Source/TestProject1/AST/Declarations/EnumTests.cs +++ b/Source/TestProject1/AST/Declarations/EnumTests.cs @@ -35,7 +35,8 @@ public void Enum_With_Int_Values_Should_Pass() [TestMethod] public void Enum_With_Strings_Should_Pass() { - var src = "enum Colors { White = \"white\", Red = \"red\", Green = \"green\", Blue = \"blue\", Black = \"black\" }"; + var src = + "enum Colors { White = \"white\", Red = \"red\", Green = \"green\", Blue = \"blue\", Black = \"black\" }"; var result = ParseAndGetNodes(src); Assert.AreEqual(0, result.errors.Count); diff --git a/Source/TestProject1/AST/Declarations/FunctionTests.cs b/Source/TestProject1/AST/Declarations/FunctionTests.cs index bd81573..11042c8 100644 --- a/Source/TestProject1/AST/Declarations/FunctionTests.cs +++ b/Source/TestProject1/AST/Declarations/FunctionTests.cs @@ -167,8 +167,8 @@ public void FunctionDeclaration_With_Modifiers_Should_Pass() Assert.AreEqual(0, result.errors.Count); var array = statement.Attrs.ToVList().ToArray(); - Assert.IsTrue(array.Any(_ => _.IsId && (_.Name == CodeSymbols.Public))); - Assert.IsTrue(array.Any(_ => _.IsId && (_.Name == CodeSymbols.Static))); + Assert.IsTrue(array.Any(_ => _.IsId && _.Name == CodeSymbols.Public)); + Assert.IsTrue(array.Any(_ => _.IsId && _.Name == CodeSymbols.Static)); Assert.AreEqual("i32", retType.Args[0].Args[0].Name.Name); Assert.AreEqual("test", name.Args[0].Args[0].Name.Name); diff --git a/Source/TestProject1/AST/Statements/VariableTests.cs b/Source/TestProject1/AST/Statements/VariableTests.cs index 286c051..c306076 100644 --- a/Source/TestProject1/AST/Statements/VariableTests.cs +++ b/Source/TestProject1/AST/Statements/VariableTests.cs @@ -3,75 +3,74 @@ using Loyc.Syntax; using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace TestProject1.AST.Statements +namespace TestProject1.AST.Statements; + +[TestClass] +public class VariableTests : ParserTestBase { - [TestClass] - public class VariableTests : ParserTestBase + [TestMethod] + public void VariableDeclaration_Full_MissMatch_Types_Should_Pass() { - [TestMethod] - public void VariableDeclaration_Full_MissMatch_Types_Should_Pass() - { - var src = "let hello : bool = \"true\";"; + var src = "let hello : bool = \"true\";"; - var result = ParseAndGetNodesInFunction(src); - var statement = result.nodes[0]; - var right = statement.Args[1]; + var result = ParseAndGetNodesInFunction(src); + var statement = result.nodes[0]; + var right = statement.Args[1]; - Assert.AreEqual(0, result.errors.Count); + Assert.AreEqual(0, result.errors.Count); - Assert.IsTrue(statement.Calls(CodeSymbols.Var)); - Assert.AreEqual((Symbol)"hello", right.Args[0].Name); - Assert.AreEqual("true", right.Args[1].Args[0].Value); - } + Assert.IsTrue(statement.Calls(CodeSymbols.Var)); + Assert.AreEqual((Symbol)"hello", right.Args[0].Name); + Assert.AreEqual("true", right.Args[1].Args[0].Value); + } - [TestMethod] - public void VariableDeclaration_Mutable_Full_BoolValue_Should_Pass() - { - var src = "let mut hello : bool = true;"; + [TestMethod] + public void VariableDeclaration_Mutable_Full_BoolValue_Should_Pass() + { + var src = "let mut hello : bool = true;"; - var result = ParseAndGetNodesInFunction(src); - var statement = result.nodes[0]; - var right = statement.Args[1]; + var result = ParseAndGetNodesInFunction(src); + var statement = result.nodes[0]; + var right = statement.Args[1]; - Assert.AreEqual(0, result.errors.Count); + Assert.AreEqual(0, result.errors.Count); - Assert.IsTrue(statement.Calls(CodeSymbols.Var)); - Assert.AreEqual((Symbol)"hello", right.Args[0].Name); - Assert.AreEqual(LNode.Id(Symbols.Mutable), statement.Attrs[0]); - Assert.AreEqual(true, right.Args[1].Args[0].Value); - } + Assert.IsTrue(statement.Calls(CodeSymbols.Var)); + Assert.AreEqual((Symbol)"hello", right.Args[0].Name); + Assert.AreEqual(LNode.Id(Symbols.Mutable), statement.Attrs[0]); + Assert.AreEqual(true, right.Args[1].Args[0].Value); + } - [TestMethod] - public void VariableDeclaration_Without_Type_Should_Pass() - { - var src = "let hello = 42;"; + [TestMethod] + public void VariableDeclaration_Without_Type_Should_Pass() + { + var src = "let hello = 42;"; - var result = ParseAndGetNodesInFunction(src); - var statement = result.nodes[0]; + var result = ParseAndGetNodesInFunction(src); + var statement = result.nodes[0]; - var right = statement.Args[1]; + var right = statement.Args[1]; - Assert.AreEqual(0, result.errors.Count); + Assert.AreEqual(0, result.errors.Count); - Assert.IsTrue(statement.Calls(CodeSymbols.Var)); - Assert.AreEqual((Symbol)"hello", right.Args[0].Name); - Assert.AreEqual(42, right.Args[1].Args[0].Value); - } + Assert.IsTrue(statement.Calls(CodeSymbols.Var)); + Assert.AreEqual((Symbol)"hello", right.Args[0].Name); + Assert.AreEqual(42, right.Args[1].Args[0].Value); + } - [TestMethod] - public void VariableDeclarationWithHex_Should_Pass() - { - var src = "let hello = 0xc0ffee;"; - var result = ParseAndGetNodesInFunction(src); - var statement = result.nodes[0]; + [TestMethod] + public void VariableDeclarationWithHex_Should_Pass() + { + var src = "let hello = 0xc0ffee;"; + var result = ParseAndGetNodesInFunction(src); + var statement = result.nodes[0]; - var right = statement.Args[1]; + var right = statement.Args[1]; - Assert.AreEqual(0, result.errors.Count); + Assert.AreEqual(0, result.errors.Count); - Assert.IsTrue(statement.Calls(CodeSymbols.Var)); - Assert.AreEqual((Symbol)"hello", right.Args[0].Name); - Assert.AreEqual(0xC0ffee, right.Args[1].Args[0].Value); - } + Assert.IsTrue(statement.Calls(CodeSymbols.Var)); + Assert.AreEqual((Symbol)"hello", right.Args[0].Name); + Assert.AreEqual(0xC0ffee, right.Args[1].Args[0].Value); } } \ No newline at end of file diff --git a/Source/TestProject1/LexerTests.cs b/Source/TestProject1/LexerTests.cs index 0304283..be43365 100644 --- a/Source/TestProject1/LexerTests.cs +++ b/Source/TestProject1/LexerTests.cs @@ -1,91 +1,90 @@ using Backlang.Codeanalysis.Parsing; using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace TestProject1 +namespace TestProject1; + +[TestClass] +public class LexerTests { - [TestClass] - public class LexerTests + [TestMethod] + public void Lexer_Arrow_Should_Pass() { - [TestMethod] - public void Lexer_Arrow_Should_Pass() - { - var src = "a -> b"; - var lexer = new Lexer(); - var tokens = lexer.Tokenize(new SourceDocument("test", src)); + var src = "a -> b"; + var lexer = new Lexer(); + var tokens = lexer.Tokenize(new SourceDocument("test", src)); - Assert.AreEqual(4, tokens.Count); - Assert.AreEqual(tokens[1].Type, TokenType.Arrow); - } + Assert.AreEqual(4, tokens.Count); + Assert.AreEqual(tokens[1].Type, TokenType.Arrow); + } - [TestMethod] - public void Lexer_BinNumber_Should_Pass() - { - var src = "0x1011011110110110"; - var lexer = new Lexer(); - var tokens = lexer.Tokenize(new SourceDocument("test", src)); + [TestMethod] + public void Lexer_BinNumber_Should_Pass() + { + var src = "0x1011011110110110"; + var lexer = new Lexer(); + var tokens = lexer.Tokenize(new SourceDocument("test", src)); - Assert.AreEqual(tokens.Count, 2); - Assert.AreEqual(tokens[0].Type, TokenType.HexNumber); - Assert.AreEqual(tokens[0].Text, "1011011110110110"); - } + Assert.AreEqual(tokens.Count, 2); + Assert.AreEqual(tokens[0].Type, TokenType.HexNumber); + Assert.AreEqual(tokens[0].Text, "1011011110110110"); + } - [TestMethod] - public void Lexer_BinNumber_With_Seperator_Should_Pass() - { - var src = "0x1011_0111_1011_0110"; - var lexer = new Lexer(); - var tokens = lexer.Tokenize(new SourceDocument("test", src)); + [TestMethod] + public void Lexer_BinNumber_With_Seperator_Should_Pass() + { + var src = "0x1011_0111_1011_0110"; + var lexer = new Lexer(); + var tokens = lexer.Tokenize(new SourceDocument("test", src)); - Assert.AreEqual(tokens.Count, 2); - Assert.AreEqual(tokens[0].Type, TokenType.HexNumber); - Assert.AreEqual(tokens[0].Text, "1011011110110110"); - } + Assert.AreEqual(tokens.Count, 2); + Assert.AreEqual(tokens[0].Type, TokenType.HexNumber); + Assert.AreEqual(tokens[0].Text, "1011011110110110"); + } - [TestMethod] - public void Lexer_HexNumber_Should_Pass() - { - var src = "0xc0ffee"; - var lexer = new Lexer(); - var tokens = lexer.Tokenize(new SourceDocument("test", src)); + [TestMethod] + public void Lexer_HexNumber_Should_Pass() + { + var src = "0xc0ffee"; + var lexer = new Lexer(); + var tokens = lexer.Tokenize(new SourceDocument("test", src)); - Assert.AreEqual(tokens.Count, 2); - Assert.AreEqual(tokens[0].Type, TokenType.HexNumber); - Assert.AreEqual(tokens[0].Text, "c0ffee"); - } + Assert.AreEqual(tokens.Count, 2); + Assert.AreEqual(tokens[0].Type, TokenType.HexNumber); + Assert.AreEqual(tokens[0].Text, "c0ffee"); + } - [TestMethod] - public void Lexer_HexNumber_With_Seperator_Should_Pass() - { - var src = "0xc0_ff_ee"; - var lexer = new Lexer(); - var tokens = lexer.Tokenize(new SourceDocument("test", src)); + [TestMethod] + public void Lexer_HexNumber_With_Seperator_Should_Pass() + { + var src = "0xc0_ff_ee"; + var lexer = new Lexer(); + var tokens = lexer.Tokenize(new SourceDocument("test", src)); - Assert.AreEqual(tokens.Count, 2); - Assert.AreEqual(tokens[0].Type, TokenType.HexNumber); - Assert.AreEqual(tokens[0].Text, "c0ffee"); - } + Assert.AreEqual(tokens.Count, 2); + Assert.AreEqual(tokens[0].Type, TokenType.HexNumber); + Assert.AreEqual(tokens[0].Text, "c0ffee"); + } - [TestMethod] - public void Lexer_IdentifierWithUnderscore_Should_Pass() - { - var src = "hello_world"; - var lexer = new Lexer(); - var tokens = lexer.Tokenize(new SourceDocument("test", src)); + [TestMethod] + public void Lexer_IdentifierWithUnderscore_Should_Pass() + { + var src = "hello_world"; + var lexer = new Lexer(); + var tokens = lexer.Tokenize(new SourceDocument("test", src)); - Assert.AreEqual(tokens.Count, 2); - Assert.AreEqual(tokens[0].Type, TokenType.Identifier); - Assert.AreEqual(tokens[0].Text, "hello_world"); - } + Assert.AreEqual(tokens.Count, 2); + Assert.AreEqual(tokens[0].Type, TokenType.Identifier); + Assert.AreEqual(tokens[0].Text, "hello_world"); + } - [TestMethod] - public void Lexer_Multiple_Char_Symbol_Should_Pass() - { - var src = "a <-> b"; - var lexer = new Lexer(); - var tokens = lexer.Tokenize(new SourceDocument("test", src)); + [TestMethod] + public void Lexer_Multiple_Char_Symbol_Should_Pass() + { + var src = "a <-> b"; + var lexer = new Lexer(); + var tokens = lexer.Tokenize(new SourceDocument("test", src)); - Assert.AreEqual(4, tokens.Count); - Assert.AreEqual(tokens[1].Type, TokenType.SwapOperator); - } + Assert.AreEqual(4, tokens.Count); + Assert.AreEqual(tokens[1].Type, TokenType.SwapOperator); } } \ No newline at end of file diff --git a/Source/TestProject1/ParserTestBase.cs b/Source/TestProject1/ParserTestBase.cs index 08fdb04..e1ad5bd 100644 --- a/Source/TestProject1/ParserTestBase.cs +++ b/Source/TestProject1/ParserTestBase.cs @@ -5,33 +5,32 @@ using System.Collections.Generic; using System.Linq; -namespace TestProject1 +namespace TestProject1; + +public class ParserTestBase { - public class ParserTestBase + protected static (LNodeList nodes, List errors) ParseAndGetNodes(string source) { - protected static (LNodeList nodes, List errors) ParseAndGetNodes(string source) - { - var ast = CompilationUnit.FromText(source); + var ast = CompilationUnit.FromText(source); - var node = ast.Body; + var node = ast.Body; - Assert.IsNotNull(node); + Assert.IsNotNull(node); - return (node, ast.Messages); - } + return (node, ast.Messages); + } - protected static (LNode nodes, List errors) ParseAndGetNode(string source) - { - var result = ParseAndGetNodes(source); + protected static (LNode nodes, List errors) ParseAndGetNode(string source) + { + var result = ParseAndGetNodes(source); - return (result.nodes.First(), result.errors); - } + return (result.nodes.First(), result.errors); + } - protected static (LNodeList nodes, List errors) ParseAndGetNodesInFunction(string source) - { - var tree = ParseAndGetNodes("func main() {" + source + "}"); + protected static (LNodeList nodes, List errors) ParseAndGetNodesInFunction(string source) + { + var tree = ParseAndGetNodes("func main() {" + source + "}"); - return (tree.Item1.First().Args[3].Args, tree.Item2); - } + return (tree.Item1.First().Args[3].Args, tree.Item2); } } \ No newline at end of file diff --git a/Source/TestProject1/TestProject1.csproj b/Source/TestProject1/TestProject1.csproj index ee288fa..72cd539 100644 --- a/Source/TestProject1/TestProject1.csproj +++ b/Source/TestProject1/TestProject1.csproj @@ -1,30 +1,30 @@  - - net9.0 - enable + + net9.0 + enable - false - latest - True - + false + latest + True + - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + - - - + + + - - - + + + diff --git a/Source/Version.props b/Source/Version.props index ef52452..0c40773 100644 --- a/Source/Version.props +++ b/Source/Version.props @@ -1,5 +1,5 @@  - - 1.0.83 - + + 1.0.83 + \ No newline at end of file