From f85c82f487dd7d6ec01441ec806d3a81d7a32920 Mon Sep 17 00:00:00 2001 From: Jan Date: Mon, 1 Mar 2021 14:30:10 +0100 Subject: [PATCH] Remove old ZoneCodeGenerator implementation in c# --- premake5.lua | 4 - src/ZoneCodeGenerator.lua | 50 -- src/ZoneCodeGenerator/Domain/CustomAction.cs | 17 - src/ZoneCodeGenerator/Domain/DataException.cs | 9 - src/ZoneCodeGenerator/Domain/DataType.cs | 21 - .../Domain/DataTypeBaseType.cs | 46 -- src/ZoneCodeGenerator/Domain/DataTypeEnum.cs | 26 - .../Domain/DataTypeStruct.cs | 51 -- src/ZoneCodeGenerator/Domain/DataTypeType.cs | 11 - .../Domain/DataTypeTypedef.cs | 22 - src/ZoneCodeGenerator/Domain/DataTypeUnion.cs | 25 - .../Domain/DataTypeWithMembers.cs | 72 --- src/ZoneCodeGenerator/Domain/EnumMember.cs | 14 - .../Domain/Evaluation/IEvaluation.cs | 15 - .../Domain/Evaluation/OperandDynamic.cs | 33 -- .../Domain/Evaluation/OperandStatic.cs | 37 -- .../Domain/Evaluation/Operation.cs | 63 --- .../Domain/Evaluation/OperationType.cs | 159 ------ .../Domain/FastFileStructure/FastFileBlock.cs | 30 - .../Domain/ForwardDeclaration.cs | 49 -- .../Domain/Information/MemberInformation.cs | 41 -- .../Information/StructureInformation.cs | 60 -- src/ZoneCodeGenerator/Domain/Namespace.cs | 59 -- src/ZoneCodeGenerator/Domain/ReferenceType.cs | 7 - .../Domain/ReferenceTypeArray.cs | 19 - .../Domain/ReferenceTypePointer.cs | 29 - .../Domain/TypeDeclaration.cs | 55 -- src/ZoneCodeGenerator/Domain/Variable.cs | 20 - .../Generating/CodeGenerator.cs | 113 ---- .../Generating/CodeTemplate.cs | 56 -- .../Computations/MemberComputations.cs | 108 ---- .../MemberReferenceComputations.cs | 105 ---- .../Computations/StructureComputations.cs | 23 - .../Generating/DataTypeAttributeRenderer.cs | 29 - .../Generating/RenderingContext.cs | 162 ------ .../Generating/TemplateGroupResources.cs | 126 ----- .../Generating/Templates/AssetStructTests.stg | 41 -- .../Generating/Templates/Common.stg | 69 --- .../Templates/Loading/ArrayPointer.stg | 165 ------ .../Generating/Templates/Loading/Common.stg | 8 - .../Templates/Loading/DynamicArray.stg | 20 - .../Generating/Templates/Loading/Embedded.stg | 69 --- .../Templates/Loading/PointerArray.stg | 101 ---- .../Templates/Loading/SinglePointer.stg | 115 ---- .../Generating/Templates/ZoneLoad.stg | 382 ------------- .../Generating/Templates/ZoneWrite.stg | 38 -- .../Interface/Arguments/ArgumentParser.cs | 113 ---- .../Interface/Arguments/CommandLineOption.cs | 83 --- .../Interface/Arguments/UsageInformation.cs | 108 ---- src/ZoneCodeGenerator/Interface/CUI.cs | 112 ---- src/ZoneCodeGenerator/Interface/CUISession.cs | 20 - .../Interface/CommandLineOptions.cs | 98 ---- .../Interface/PrettyPrinter.cs | 315 ----------- src/ZoneCodeGenerator/LoadingException.cs | 11 - .../Parsing/C_Header/BlockType.cs | 11 - .../Parsing/C_Header/Blocks/Block.cs | 25 - .../Parsing/C_Header/Blocks/BlockEnum.cs | 114 ---- .../Parsing/C_Header/Blocks/BlockNamespace.cs | 51 -- .../Parsing/C_Header/Blocks/BlockNone.cs | 44 -- .../Parsing/C_Header/Blocks/BlockStruct.cs | 134 ----- .../Parsing/C_Header/Blocks/BlockUnion.cs | 134 ----- .../C_Header/Blocks/INameAssignable.cs | 7 - .../Parsing/C_Header/Blocks/IVariableBlock.cs | 9 - .../C_Header/Blocks/IVariableHolder.cs | 9 - .../Parsing/C_Header/HeaderReader.cs | 80 --- .../Parsing/C_Header/IHeaderParserState.cs | 28 - .../C_Header/Impl/HeaderParserState.cs | 216 -------- .../Parsing/C_Header/Impl/Preprocessor.cs | 182 ------- .../Parsing/C_Header/Tests/TestCloseBlock.cs | 48 -- .../Parsing/C_Header/Tests/TestEnum.cs | 57 -- .../Parsing/C_Header/Tests/TestEnumMember.cs | 66 --- .../Parsing/C_Header/Tests/TestForwardDecl.cs | 52 -- .../Parsing/C_Header/Tests/TestNamespace.cs | 29 - .../Parsing/C_Header/Tests/TestStruct.cs | 69 --- .../Parsing/C_Header/Tests/TestTypedef.cs | 133 ----- .../Parsing/C_Header/Tests/TestUnion.cs | 69 --- .../Parsing/C_Header/Tests/TestVariable.cs | 119 ---- .../Parsing/CommandFile/CommandFileReader.cs | 70 --- .../CommandFile/ICommandParserState.cs | 20 - .../Impl/CommandFilePreprocessor.cs | 56 -- .../CommandFile/Impl/CommandParserState.cs | 138 ----- .../PostProcessor/PostProcessorLeafs.cs | 62 --- .../PostProcessor/PostProcessorMemberLeafs.cs | 59 -- .../PostProcessor/PostProcessorUnions.cs | 41 -- .../PostProcessor/PostProcessorUsages.cs | 63 --- .../Parsing/CommandFile/Tests/TestAction.cs | 114 ---- .../CommandFile/Tests/TestArrayCount.cs | 82 --- .../CommandFile/Tests/TestArraySize.cs | 89 --- .../Parsing/CommandFile/Tests/TestAsset.cs | 59 -- .../Parsing/CommandFile/Tests/TestBlock.cs | 56 -- .../CommandFile/Tests/TestCondition.cs | 98 ---- .../Parsing/CommandFile/Tests/TestCount.cs | 137 ----- .../Parsing/CommandFile/Tests/TestGame.cs | 37 -- .../Parsing/CommandFile/Tests/TestName.cs | 67 --- .../Parsing/CommandFile/Tests/TestReorder.cs | 127 ----- .../Parsing/CommandFile/Tests/TestReusable.cs | 63 --- .../CommandFile/Tests/TestScriptString.cs | 61 --- .../Parsing/CommandFile/Tests/TestSetBlock.cs | 83 --- .../Parsing/CommandFile/Tests/TestString.cs | 67 --- .../Parsing/CommandFile/Tests/TestUse.cs | 49 -- .../CommandFile/Tests/TestWithEvaluation.cs | 251 --------- .../Parsing/ICommentProcessor.cs | 7 - .../Parsing/IDataPostProcessor.cs | 9 - .../Parsing/IIncludingParsingStream.cs | 12 - src/ZoneCodeGenerator/Parsing/ILexer.cs | 14 - src/ZoneCodeGenerator/Parsing/IParserState.cs | 10 - .../Parsing/IParsingFileStream.cs | 33 -- .../Parsing/Impl/CommentProcessor.cs | 57 -- .../Parsing/Impl/IncludingStreamFileSystem.cs | 107 ---- src/ZoneCodeGenerator/Parsing/Impl/Lexer.cs | 162 ------ .../Parsing/Matching/BaseMatcher.cs | 66 --- .../Parsing/Matching/GroupMatcher.cs | 17 - .../Parsing/Matching/Matchers/MatcherArray.cs | 47 -- .../Matching/Matchers/MatcherGroupAnd.cs | 40 -- .../Matching/Matchers/MatcherGroupLoop.cs | 69 --- .../Matching/Matchers/MatcherGroupOptional.cs | 30 - .../Matching/Matchers/MatcherGroupOr.cs | 37 -- .../Matching/Matchers/MatcherLiteral.cs | 37 -- .../Parsing/Matching/Matchers/MatcherName.cs | 98 ---- .../Matching/Matchers/MatcherNumber.cs | 36 -- .../Matching/Matchers/MatcherTypename.cs | 74 --- .../Matching/Matchers/MatcherWithTag.cs | 33 -- .../Parsing/Matching/MatchingContext.cs | 28 - .../Parsing/Matching/TokenMatcher.cs | 66 --- .../Parsing/Matching/TokenMatchingResult.cs | 70 --- src/ZoneCodeGenerator/Parsing/Parser.cs | 85 --- .../Parsing/ParserException.cs | 9 - .../Parsing/Testing/AbstractTokenTest.cs | 158 ------ .../Parsing/Testing/ITokenTest.cs | 9 - .../Parsing/Testing/TestFailedException.cs | 9 - .../Parsing/Testing/TokenTestResult.cs | 8 - .../Persistence/IDataRepository.cs | 14 - .../Persistence/IReadOnlyDataRepository.cs | 20 - .../Persistence/InMemoryDataRepository.cs | 134 ----- src/ZoneCodeGenerator/Program.cs | 37 -- .../Properties/AssemblyInfo.cs | 39 -- .../Utils/AlignmentExtension.cs | 15 - .../Utils/KeyValueExtension.cs | 20 - src/ZoneCodeGenerator/Utils/RandomName.cs | 23 - test/ZoneCodeGeneratorTests.lua | 47 -- .../AssertionExtensions.cs | 25 - .../Domain/NamespaceTest.cs | 95 ---- test/ZoneCodeGeneratorTests/FieldInjector.cs | 27 - .../Parsing/C_Header/Impl/PreprocessorTest.cs | 186 ------- .../C_Header/Tests/TestCloseBlockTest.cs | 161 ------ .../C_Header/Tests/TestEnumMemberTest.cs | 318 ----------- .../Parsing/C_Header/Tests/TestEnumTest.cs | 394 -------------- .../C_Header/Tests/TestForwardDeclTest.cs | 121 ----- .../C_Header/Tests/TestNamespaceTest.cs | 140 ----- .../Parsing/C_Header/Tests/TestStructTest.cs | 181 ------ .../Parsing/C_Header/Tests/TestTypedefTest.cs | 291 ---------- .../Parsing/C_Header/Tests/TestUnionTest.cs | 181 ------ .../C_Header/Tests/TestVariableTest.cs | 443 --------------- .../Impl/CommandFilePreprocessorTest.cs | 76 --- .../CommandFile/Tests/TestAssetTest.cs | 176 ------ .../CommandFile/Tests/TestBlockTest.cs | 279 ---------- .../CommandFile/Tests/TestCountTest.cs | 514 ------------------ .../Parsing/CommandFile/Tests/TestGameTest.cs | 83 --- .../Parsing/CommandFile/Tests/TestUseTest.cs | 118 ---- .../Parsing/Impl/CommentProcessorTest.cs | 93 ---- .../Parsing/Impl/LexerTest.cs | 357 ------------ .../Matching/Matchers/MatcherArrayTest.cs | 253 --------- .../Matching/Matchers/MatcherGroupAndTest.cs | 177 ------ .../Matching/Matchers/MatcherGroupLoopTest.cs | 232 -------- .../Matchers/MatcherGroupOptionalTest.cs | 85 --- .../Matching/Matchers/MatcherGroupOrTest.cs | 192 ------- .../Matching/Matchers/MatcherLiteralTest.cs | 192 ------- .../Matching/Matchers/MatcherNameTest.cs | 208 ------- .../Matching/Matchers/MatcherNumberTest.cs | 208 ------- .../Matching/Matchers/MatcherTypenameTest.cs | 310 ----------- .../Parsing/Matching/Matchers/TestMatcher.cs | 44 -- .../Mock/IncludingParsingStreamTest.cs | 45 -- .../Persistence/InMemoryDataRepositoryTest.cs | 142 ----- .../Properties/AssemblyInfo.cs | 19 - 174 files changed, 15421 deletions(-) delete mode 100644 src/ZoneCodeGenerator.lua delete mode 100644 src/ZoneCodeGenerator/Domain/CustomAction.cs delete mode 100644 src/ZoneCodeGenerator/Domain/DataException.cs delete mode 100644 src/ZoneCodeGenerator/Domain/DataType.cs delete mode 100644 src/ZoneCodeGenerator/Domain/DataTypeBaseType.cs delete mode 100644 src/ZoneCodeGenerator/Domain/DataTypeEnum.cs delete mode 100644 src/ZoneCodeGenerator/Domain/DataTypeStruct.cs delete mode 100644 src/ZoneCodeGenerator/Domain/DataTypeType.cs delete mode 100644 src/ZoneCodeGenerator/Domain/DataTypeTypedef.cs delete mode 100644 src/ZoneCodeGenerator/Domain/DataTypeUnion.cs delete mode 100644 src/ZoneCodeGenerator/Domain/DataTypeWithMembers.cs delete mode 100644 src/ZoneCodeGenerator/Domain/EnumMember.cs delete mode 100644 src/ZoneCodeGenerator/Domain/Evaluation/IEvaluation.cs delete mode 100644 src/ZoneCodeGenerator/Domain/Evaluation/OperandDynamic.cs delete mode 100644 src/ZoneCodeGenerator/Domain/Evaluation/OperandStatic.cs delete mode 100644 src/ZoneCodeGenerator/Domain/Evaluation/Operation.cs delete mode 100644 src/ZoneCodeGenerator/Domain/Evaluation/OperationType.cs delete mode 100644 src/ZoneCodeGenerator/Domain/FastFileStructure/FastFileBlock.cs delete mode 100644 src/ZoneCodeGenerator/Domain/ForwardDeclaration.cs delete mode 100644 src/ZoneCodeGenerator/Domain/Information/MemberInformation.cs delete mode 100644 src/ZoneCodeGenerator/Domain/Information/StructureInformation.cs delete mode 100644 src/ZoneCodeGenerator/Domain/Namespace.cs delete mode 100644 src/ZoneCodeGenerator/Domain/ReferenceType.cs delete mode 100644 src/ZoneCodeGenerator/Domain/ReferenceTypeArray.cs delete mode 100644 src/ZoneCodeGenerator/Domain/ReferenceTypePointer.cs delete mode 100644 src/ZoneCodeGenerator/Domain/TypeDeclaration.cs delete mode 100644 src/ZoneCodeGenerator/Domain/Variable.cs delete mode 100644 src/ZoneCodeGenerator/Generating/CodeGenerator.cs delete mode 100644 src/ZoneCodeGenerator/Generating/CodeTemplate.cs delete mode 100644 src/ZoneCodeGenerator/Generating/Computations/MemberComputations.cs delete mode 100644 src/ZoneCodeGenerator/Generating/Computations/MemberReferenceComputations.cs delete mode 100644 src/ZoneCodeGenerator/Generating/Computations/StructureComputations.cs delete mode 100644 src/ZoneCodeGenerator/Generating/DataTypeAttributeRenderer.cs delete mode 100644 src/ZoneCodeGenerator/Generating/RenderingContext.cs delete mode 100644 src/ZoneCodeGenerator/Generating/TemplateGroupResources.cs delete mode 100644 src/ZoneCodeGenerator/Generating/Templates/AssetStructTests.stg delete mode 100644 src/ZoneCodeGenerator/Generating/Templates/Common.stg delete mode 100644 src/ZoneCodeGenerator/Generating/Templates/Loading/ArrayPointer.stg delete mode 100644 src/ZoneCodeGenerator/Generating/Templates/Loading/Common.stg delete mode 100644 src/ZoneCodeGenerator/Generating/Templates/Loading/DynamicArray.stg delete mode 100644 src/ZoneCodeGenerator/Generating/Templates/Loading/Embedded.stg delete mode 100644 src/ZoneCodeGenerator/Generating/Templates/Loading/PointerArray.stg delete mode 100644 src/ZoneCodeGenerator/Generating/Templates/Loading/SinglePointer.stg delete mode 100644 src/ZoneCodeGenerator/Generating/Templates/ZoneLoad.stg delete mode 100644 src/ZoneCodeGenerator/Generating/Templates/ZoneWrite.stg delete mode 100644 src/ZoneCodeGenerator/Interface/Arguments/ArgumentParser.cs delete mode 100644 src/ZoneCodeGenerator/Interface/Arguments/CommandLineOption.cs delete mode 100644 src/ZoneCodeGenerator/Interface/Arguments/UsageInformation.cs delete mode 100644 src/ZoneCodeGenerator/Interface/CUI.cs delete mode 100644 src/ZoneCodeGenerator/Interface/CUISession.cs delete mode 100644 src/ZoneCodeGenerator/Interface/CommandLineOptions.cs delete mode 100644 src/ZoneCodeGenerator/Interface/PrettyPrinter.cs delete mode 100644 src/ZoneCodeGenerator/LoadingException.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/BlockType.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Blocks/Block.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockEnum.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockNamespace.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockNone.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockStruct.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockUnion.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Blocks/INameAssignable.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Blocks/IVariableBlock.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Blocks/IVariableHolder.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/HeaderReader.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/IHeaderParserState.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Impl/HeaderParserState.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Impl/Preprocessor.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestCloseBlock.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestEnum.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestEnumMember.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestForwardDecl.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestNamespace.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestStruct.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestTypedef.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestUnion.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestVariable.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/CommandFileReader.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/ICommandParserState.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Impl/CommandFilePreprocessor.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Impl/CommandParserState.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorLeafs.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorMemberLeafs.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorUnions.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorUsages.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestAction.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestArrayCount.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestArraySize.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestAsset.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestBlock.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestCondition.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestCount.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestGame.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestName.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestReorder.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestReusable.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestScriptString.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestSetBlock.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestString.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestUse.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestWithEvaluation.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/ICommentProcessor.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/IDataPostProcessor.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/IIncludingParsingStream.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/ILexer.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/IParserState.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/IParsingFileStream.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Impl/CommentProcessor.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Impl/IncludingStreamFileSystem.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Impl/Lexer.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/BaseMatcher.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/GroupMatcher.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherArray.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupAnd.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupLoop.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupOptional.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupOr.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherLiteral.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherName.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherNumber.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherTypename.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherWithTag.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/MatchingContext.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/TokenMatcher.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Matching/TokenMatchingResult.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Parser.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/ParserException.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Testing/AbstractTokenTest.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Testing/ITokenTest.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Testing/TestFailedException.cs delete mode 100644 src/ZoneCodeGenerator/Parsing/Testing/TokenTestResult.cs delete mode 100644 src/ZoneCodeGenerator/Persistence/IDataRepository.cs delete mode 100644 src/ZoneCodeGenerator/Persistence/IReadOnlyDataRepository.cs delete mode 100644 src/ZoneCodeGenerator/Persistence/InMemoryDataRepository.cs delete mode 100644 src/ZoneCodeGenerator/Program.cs delete mode 100644 src/ZoneCodeGenerator/Properties/AssemblyInfo.cs delete mode 100644 src/ZoneCodeGenerator/Utils/AlignmentExtension.cs delete mode 100644 src/ZoneCodeGenerator/Utils/KeyValueExtension.cs delete mode 100644 src/ZoneCodeGenerator/Utils/RandomName.cs delete mode 100644 test/ZoneCodeGeneratorTests.lua delete mode 100644 test/ZoneCodeGeneratorTests/AssertionExtensions.cs delete mode 100644 test/ZoneCodeGeneratorTests/Domain/NamespaceTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/FieldInjector.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/C_Header/Impl/PreprocessorTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestCloseBlockTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestEnumMemberTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestEnumTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestForwardDeclTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestNamespaceTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestStructTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestTypedefTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestUnionTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestVariableTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/CommandFile/Impl/CommandFilePreprocessorTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestAssetTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestBlockTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestCountTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestGameTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestUseTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Impl/CommentProcessorTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Impl/LexerTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherArrayTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupAndTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupLoopTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupOptionalTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupOrTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherLiteralTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherNameTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherNumberTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherTypenameTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/TestMatcher.cs delete mode 100644 test/ZoneCodeGeneratorTests/Parsing/Mock/IncludingParsingStreamTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Persistence/InMemoryDataRepositoryTest.cs delete mode 100644 test/ZoneCodeGeneratorTests/Properties/AssemblyInfo.cs diff --git a/premake5.lua b/premake5.lua index ff7ac955..fa003fba 100644 --- a/premake5.lua +++ b/premake5.lua @@ -133,7 +133,6 @@ include "src/Linker.lua" include "src/Unlinker.lua" include "src/Utils.lua" include "src/ZoneCode.lua" -include "src/ZoneCodeGenerator.lua" include "src/ZoneCodeGeneratorLib.lua" include "src/ZoneCodeGeneratorNew.lua" include "src/ZoneCommon.lua" @@ -149,7 +148,6 @@ group "Components" Crypto:project() Utils:project() ZoneCode:project() - ZoneCodeGenerator:project() ZoneCodeGeneratorLib:project() ZoneCommon:project() ZoneLoading:project() @@ -170,14 +168,12 @@ group "" -- Tests -- ======================== include "test/ObjCommonTests.lua" -include "test/ZoneCodeGeneratorTests.lua" include "test/ZoneCodeGeneratorLibTests.lua" include "test/ZoneCommonTests.lua" -- Tests group: Unit test and other tests projects group "Tests" ObjCommonTests:project() - ZoneCodeGeneratorTests:project() ZoneCodeGeneratorLibTests:project() ZoneCommonTests:project() group "" \ No newline at end of file diff --git a/src/ZoneCodeGenerator.lua b/src/ZoneCodeGenerator.lua deleted file mode 100644 index baf5cc3c..00000000 --- a/src/ZoneCodeGenerator.lua +++ /dev/null @@ -1,50 +0,0 @@ -ZoneCodeGenerator = {} - -function ZoneCodeGenerator:include() - -end - -function ZoneCodeGenerator:link() - if References:link("ZoneCodeGenerator") then - links "ZoneCodeGenerator" - end -end - -function ZoneCodeGenerator:use() - dependson "ZoneCodeGenerator" -end - -function ZoneCodeGenerator:project() - References:reset() - local folder = ProjectFolder(); - - project "ZoneCodeGenerator" - targetdir(TargetDirectoryLib) - location "%{wks.location}/src/%{prj.name}" - kind "ConsoleApp" - language "C#" - dotnetframework "4.5" - namespace "ZoneCodeGenerator" - - files { - path.join(folder, "ZoneCodeGenerator/**.cs"), - path.join(folder, "ZoneCodeGenerator/**.stg") - } - - filter "files:**.stg" - buildaction "Embed" - filter {} - - vpaths { ["*"] = "src/ZoneCodeGenerator" } - - nuget { - "Antlr3.Runtime:3.5.1", - "StringTemplate4:4.0.8" - } - - links { - "System", - "System.Core", - "System.Data" - } -end diff --git a/src/ZoneCodeGenerator/Domain/CustomAction.cs b/src/ZoneCodeGenerator/Domain/CustomAction.cs deleted file mode 100644 index c6bed7f7..00000000 --- a/src/ZoneCodeGenerator/Domain/CustomAction.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace ZoneCodeGenerator.Domain -{ - class CustomAction - { - public string ActionName { get; } - public IList ParameterTypes { get; } - - public CustomAction(string actionName, IEnumerable parameterTypes) - { - ActionName = actionName; - ParameterTypes = new List(parameterTypes); - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Domain/DataException.cs b/src/ZoneCodeGenerator/Domain/DataException.cs deleted file mode 100644 index 3ca526d8..00000000 --- a/src/ZoneCodeGenerator/Domain/DataException.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZoneCodeGenerator.Domain -{ - class DataException : LoadingException - { - public DataException(string message) : base(message) - { - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/DataType.cs b/src/ZoneCodeGenerator/Domain/DataType.cs deleted file mode 100644 index 385169fd..00000000 --- a/src/ZoneCodeGenerator/Domain/DataType.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace ZoneCodeGenerator.Domain -{ - abstract class DataType - { - public string Namespace { get; } - public string Name { get; } - public DataTypeType Type { get; } - public string FullName => string.IsNullOrEmpty(Namespace) ? Name : $"{Namespace}::{Name}"; - - public abstract int Alignment { get; } - public abstract bool ForceAlignment { get; } - public abstract int Size { get; } - - protected DataType(string _namespace, string name, DataTypeType type) - { - Namespace = _namespace; - Name = name; - Type = type; - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/DataTypeBaseType.cs b/src/ZoneCodeGenerator/Domain/DataTypeBaseType.cs deleted file mode 100644 index bd229530..00000000 --- a/src/ZoneCodeGenerator/Domain/DataTypeBaseType.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -namespace ZoneCodeGenerator.Domain -{ - class DataTypeBaseType : DataType - { - public static readonly DataTypeBaseType FLOAT = new DataTypeBaseType("float", 4); - public static readonly DataTypeBaseType DOUBLE = new DataTypeBaseType("double", 8); - public static readonly DataTypeBaseType BOOL = new DataTypeBaseType("bool", 1); - public static readonly DataTypeBaseType CHAR = new DataTypeBaseType("char", 1); - public static readonly DataTypeBaseType UNSIGNED_CHAR = new DataTypeBaseType("unsigned char", 1); - public static readonly DataTypeBaseType SHORT = new DataTypeBaseType("short", 2); - public static readonly DataTypeBaseType UNSIGNED_SHORT = new DataTypeBaseType("unsigned short", 2); - public static readonly DataTypeBaseType INT = new DataTypeBaseType("int", 4); - public static readonly DataTypeBaseType UNSIGNED_INT = new DataTypeBaseType("unsigned int", 4); - public static readonly DataTypeBaseType LONG = new DataTypeBaseType("long", 4); - public static readonly DataTypeBaseType UNSIGNED_LONG = new DataTypeBaseType("unsigned long", 4); - public static readonly DataTypeBaseType LONG_LONG = new DataTypeBaseType("long long", 8); - public static readonly DataTypeBaseType UNSIGNED_LONG_LONG = new DataTypeBaseType("unsigned long long", 8); - public static readonly DataTypeBaseType VOID = new DataTypeBaseType("void", 0); - - public static readonly IEnumerable BASE_TYPES = typeof(DataTypeBaseType) - .GetFields(BindingFlags.Public | BindingFlags.Static) - .Where(info => info.FieldType == typeof(DataTypeBaseType)) - .Select(info => info.GetValue(null)) - .Cast() - .ToList(); - - public override bool ForceAlignment => false; - public override int Size { get; } - public override int Alignment => Size; - - private DataTypeBaseType(string name, int size) : base("", name, DataTypeType.BaseType) - { - Size = size; - } - - public override string ToString() - { - return $"BaseType {FullName}"; - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/DataTypeEnum.cs b/src/ZoneCodeGenerator/Domain/DataTypeEnum.cs deleted file mode 100644 index 5729e456..00000000 --- a/src/ZoneCodeGenerator/Domain/DataTypeEnum.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Collections.Generic; - -namespace ZoneCodeGenerator.Domain -{ - class DataTypeEnum : DataType - { - public DataTypeBaseType ParentType { get; } - public List Members { get; } - - public override bool ForceAlignment => ParentType.ForceAlignment; - public override int Size => ParentType.Size; - public override int Alignment => ParentType.Alignment; - - - public DataTypeEnum(string _namespace, string name, DataTypeBaseType parentType) : base(_namespace, name, DataTypeType.Enum) - { - Members = new List(); - ParentType = parentType; - } - - public override string ToString() - { - return $"enum {FullName}"; - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/DataTypeStruct.cs b/src/ZoneCodeGenerator/Domain/DataTypeStruct.cs deleted file mode 100644 index 60b0329f..00000000 --- a/src/ZoneCodeGenerator/Domain/DataTypeStruct.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using ZoneCodeGenerator.Utils; - -namespace ZoneCodeGenerator.Domain -{ - class DataTypeStruct : DataTypeWithMembers - { - public DataTypeStruct(string _namespace, string name, int pack) : base(_namespace, name, pack, DataTypeType.Struct) - { - } - - protected override int CalculateSize() - { - var currentSize = 0; - var currentBitOffset = 0; - - foreach (var member in Members) - { - if (member.VariableType.HasCustomBitSize) - { - currentBitOffset += member.VariableType.CustomBitSize.GetValueOrDefault(0); - } - else - { - if (currentBitOffset > 0) - { - currentBitOffset = currentBitOffset.Align(8); - currentSize += currentBitOffset / 8; - currentBitOffset = 0; - } - - currentSize = currentSize.Align(member.ForceAlignment ? member.Alignment : Math.Min(member.Alignment, Pack)); - currentSize += member.VariableType.Size; - } - } - - if (currentBitOffset > 0) - { - currentBitOffset = currentBitOffset.Align(8); - currentSize += currentBitOffset / 8; - } - - return currentSize.Align(Alignment); - } - - public override string ToString() - { - return $"struct {FullName}"; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Domain/DataTypeType.cs b/src/ZoneCodeGenerator/Domain/DataTypeType.cs deleted file mode 100644 index fd4632e2..00000000 --- a/src/ZoneCodeGenerator/Domain/DataTypeType.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZoneCodeGenerator.Domain -{ - enum DataTypeType - { - Struct, - Union, - Enum, - Typedef, - BaseType - } -} diff --git a/src/ZoneCodeGenerator/Domain/DataTypeTypedef.cs b/src/ZoneCodeGenerator/Domain/DataTypeTypedef.cs deleted file mode 100644 index 410a13f4..00000000 --- a/src/ZoneCodeGenerator/Domain/DataTypeTypedef.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace ZoneCodeGenerator.Domain -{ - class DataTypeTypedef : DataType - { - public TypeDeclaration TypeDefinition { get; } - - public DataTypeTypedef(string _namespace, string name, TypeDeclaration typeDefinitionDeclaration) : base(_namespace, name, DataTypeType.Typedef) - { - TypeDefinition = typeDefinitionDeclaration; - } - - public int? AlignmentOverride { get; set; } - public override int Alignment => AlignmentOverride ?? TypeDefinition.Alignment; - public override bool ForceAlignment => AlignmentOverride != null || TypeDefinition.ForceAlignment; - public override int Size => TypeDefinition.Size; - - public override string ToString() - { - return $"typedef {FullName}"; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Domain/DataTypeUnion.cs b/src/ZoneCodeGenerator/Domain/DataTypeUnion.cs deleted file mode 100644 index 99a815b6..00000000 --- a/src/ZoneCodeGenerator/Domain/DataTypeUnion.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Linq; -using ZoneCodeGenerator.Utils; - -namespace ZoneCodeGenerator.Domain -{ - class DataTypeUnion : DataTypeWithMembers - { - public DataTypeUnion(string _namespace, string name, int pack) : base(_namespace, name, pack, DataTypeType.Union) - { - } - - protected override int CalculateSize() - { - return Members - .Select(variable => variable.VariableType.Size) - .Max() - .Align(Alignment); - } - - public override string ToString() - { - return $"union {FullName}"; - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/DataTypeWithMembers.cs b/src/ZoneCodeGenerator/Domain/DataTypeWithMembers.cs deleted file mode 100644 index f1bde70c..00000000 --- a/src/ZoneCodeGenerator/Domain/DataTypeWithMembers.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace ZoneCodeGenerator.Domain -{ - abstract class DataTypeWithMembers : DataType - { - public int? AlignmentOverride { get; set; } - private int alignment; - public override int Alignment => AlignmentOverride ?? alignment; - public override bool ForceAlignment => AlignmentOverride != null; - - private int size; - public override int Size => size; - - public int Pack { get; } - - public List Members { get; } - - public bool IsAnonymous { get; set; } - - private bool finalized; - public void FinalizeDataType() - { - if (finalized) return; - - finalized = true; - CalculateProperties(); - } - - protected DataTypeWithMembers(string _namespace, string name, int pack, DataTypeType type) : base(_namespace, name, type) - { - Members = new List(); - Pack = pack; - finalized = false; - IsAnonymous = false; - } - - private void CalculateProperties() - { - foreach (var member in Members - .Select(variable => variable.VariableType.Type)) - { - switch (member) - { - case DataTypeWithMembers dataTypeWithMembers: - dataTypeWithMembers.FinalizeDataType(); - break; - - case DataTypeTypedef typeDef: - { - while (typeDef.TypeDefinition.Type is DataTypeTypedef typeDef2) - { - typeDef = typeDef2; - } - - if(typeDef.TypeDefinition.Type is DataTypeWithMembers dataTypeWithMembers) - { - dataTypeWithMembers.FinalizeDataType(); - } - break; - } - } - } - - alignment = Members.Select(variable => variable.Alignment).Max(); - size = CalculateSize(); - } - - protected abstract int CalculateSize(); - } -} diff --git a/src/ZoneCodeGenerator/Domain/EnumMember.cs b/src/ZoneCodeGenerator/Domain/EnumMember.cs deleted file mode 100644 index ff2bb3ae..00000000 --- a/src/ZoneCodeGenerator/Domain/EnumMember.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace ZoneCodeGenerator.Domain -{ - class EnumMember - { - public string Name { get; } - public long Value { get; } - - public EnumMember(string name, long value) - { - Name = name; - Value = value; - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/Evaluation/IEvaluation.cs b/src/ZoneCodeGenerator/Domain/Evaluation/IEvaluation.cs deleted file mode 100644 index ae186a38..00000000 --- a/src/ZoneCodeGenerator/Domain/Evaluation/IEvaluation.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ZoneCodeGenerator.Domain.Evaluation -{ - interface IEvaluation - { - bool IsStatic { get; } - - int EvaluateNumeric(); - } -} diff --git a/src/ZoneCodeGenerator/Domain/Evaluation/OperandDynamic.cs b/src/ZoneCodeGenerator/Domain/Evaluation/OperandDynamic.cs deleted file mode 100644 index 3b1a20aa..00000000 --- a/src/ZoneCodeGenerator/Domain/Evaluation/OperandDynamic.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain.Information; - -namespace ZoneCodeGenerator.Domain.Evaluation -{ - class OperandDynamic : IEvaluation - { - public StructureInformation Structure { get; } - public IList ReferencedMemberChain { get; } - public IList ArrayIndices { get; } - - public bool IsStatic => false; - - public OperandDynamic(StructureInformation structure, IEnumerable memberChain) - { - Structure = structure; - ReferencedMemberChain = new List(memberChain); - ArrayIndices = new List(); - } - - public int EvaluateNumeric() - { - throw new Exception("A dynamic operand cannot be evaluated."); - } - - public override string ToString() - { - return $"{Structure.Type.FullName}::{string.Join("::", ReferencedMemberChain.Select(information => information.Member.Name))}{string.Concat(ArrayIndices.Select(i => $"[{i}]"))}"; - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/Evaluation/OperandStatic.cs b/src/ZoneCodeGenerator/Domain/Evaluation/OperandStatic.cs deleted file mode 100644 index 1649fcbb..00000000 --- a/src/ZoneCodeGenerator/Domain/Evaluation/OperandStatic.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ZoneCodeGenerator.Domain.Evaluation -{ - class OperandStatic : IEvaluation - { - public int Value { get; } - public EnumMember EnumMemberValue { get; } - - public bool IsStatic => true; - public int EvaluateNumeric() - { - return Value; - } - - public OperandStatic(int value) - { - Value = value; - EnumMemberValue = null; - } - - public OperandStatic(EnumMember enumMember) - { - Value = (int) enumMember.Value; - EnumMemberValue = enumMember; - } - - public override string ToString() - { - return Value.ToString(); - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/Evaluation/Operation.cs b/src/ZoneCodeGenerator/Domain/Evaluation/Operation.cs deleted file mode 100644 index 61f46743..00000000 --- a/src/ZoneCodeGenerator/Domain/Evaluation/Operation.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ZoneCodeGenerator.Domain.Evaluation -{ - class Operation : IEvaluation - { - public IEvaluation Operand1 { get; } - public bool Operand1NeedsParenthesis => Operand1 is Operation operation1 && - operation1.OperationType.Precedence > OperationType.Precedence; - - public IEvaluation Operand2 { get; } - public bool Operand2NeedsParenthesis => Operand2 is Operation operation2 && - operation2.OperationType.Precedence >= OperationType.Precedence; - - public OperationType OperationType { get; } - - public bool IsStatic => Operand1.IsStatic && Operand2.IsStatic; - - public int EvaluateNumeric() - { - return OperationType.Function(Operand1.EvaluateNumeric(), Operand2.EvaluateNumeric()); - } - - public Operation(IEvaluation operand1, IEvaluation operand2, OperationType type) - { - Operand1 = operand1; - Operand2 = operand2; - OperationType = type; - } - - public override string ToString() - { - string operand1String; - string operand2String; - - if (Operand1 is Operation operation1 - && operation1.OperationType.Precedence > OperationType.Precedence) - { - operand1String = $"({Operand1})"; - } - else - { - operand1String = Operand1.ToString(); - } - - if (Operand2 is Operation operation2 - && operation2.OperationType.Precedence > OperationType.Precedence) - { - operand2String = $"({Operand2})"; - } - else - { - operand2String = Operand2.ToString(); - } - - return $"{operand1String} {OperationType} {operand2String}"; - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/Evaluation/OperationType.cs b/src/ZoneCodeGenerator/Domain/Evaluation/OperationType.cs deleted file mode 100644 index 854b04b2..00000000 --- a/src/ZoneCodeGenerator/Domain/Evaluation/OperationType.cs +++ /dev/null @@ -1,159 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; - -namespace ZoneCodeGenerator.Domain.Evaluation -{ - sealed class OperationType - { - // https://en.cppreference.com/w/cpp/language/operator_precedence - public enum OperationPrecedence - { - MultiplicationDivisionRemainder = 1, - AdditionSubtraction = 2, - BitwiseShift = 3, - RelationalGreaterLessThan = 4, - RelationalEquals = 5, - BitwiseAnd = 6, - BitwiseXor = 7, - BitwiseOr = 8, - LogicalAnd = 9, - LogicalOr = 10 - } - - public delegate int EvaluationFunction(int operand1, int operand2); - - public string Syntax { get; } - public OperationPrecedence Precedence { get; } - public EvaluationFunction Function { get; } - - public override string ToString() - { - return Syntax; - } - - private OperationType(string syntax, OperationPrecedence precedence, EvaluationFunction function) - { - Syntax = syntax; - Precedence = precedence; - Function = function; - } - - public static OperationType OperationAdd = new OperationType( - "+", - OperationPrecedence.AdditionSubtraction, - (operand1, operand2) => operand1 + operand2 - ); - - public static OperationType OperationSubtract = new OperationType( - "-", - OperationPrecedence.AdditionSubtraction, - (operand1, operand2) => operand1 - operand2 - ); - - public static OperationType OperationMultiply = new OperationType( - "*", - OperationPrecedence.MultiplicationDivisionRemainder, - (operand1, operand2) => operand1 * operand2 - ); - - public static OperationType OperationDivide = new OperationType( - "/", - OperationPrecedence.MultiplicationDivisionRemainder, - (operand1, operand2) => operand1 / operand2 - ); - - public static OperationType OperationRemainder = new OperationType( - "%", - OperationPrecedence.MultiplicationDivisionRemainder, - (operand1, operand2) => operand1 % operand2 - ); - - public static OperationType OperationBitwiseAnd = new OperationType( - "&", - OperationPrecedence.BitwiseAnd, - (operand1, operand2) => operand1 & operand2 - ); - - public static OperationType OperationBitwiseXor = new OperationType( - "^", - OperationPrecedence.BitwiseXor, - (operand1, operand2) => operand1 ^ operand2 - ); - - public static OperationType OperationBitwiseOr = new OperationType( - "|", - OperationPrecedence.BitwiseOr, - (operand1, operand2) => operand1 | operand2 - ); - - public static OperationType OperationShiftLeft = new OperationType( - "<<", - OperationPrecedence.BitwiseShift, - (operand1, operand2) => operand1 << operand2 - ); - - public static OperationType OperationShiftRight = new OperationType( - ">>", - OperationPrecedence.BitwiseShift, - (operand1, operand2) => operand1 >> operand2 - ); - - public static OperationType OperationGreaterThan = new OperationType( - ">", - OperationPrecedence.RelationalGreaterLessThan, - (operand1, operand2) => operand1 > operand2 ? 1 : 0 - ); - - public static OperationType OperationGreaterEqualsThan = new OperationType( - ">=", - OperationPrecedence.RelationalGreaterLessThan, - (operand1, operand2) => operand1 >= operand2 ? 1 : 0 - ); - - public static OperationType OperationLessThan = new OperationType( - "<", - OperationPrecedence.RelationalGreaterLessThan, - (operand1, operand2) => operand1 < operand2 ? 1 : 0 - ); - - public static OperationType OperationLessEqualsThan = new OperationType( - "<=", - OperationPrecedence.RelationalGreaterLessThan, - (operand1, operand2) => operand1 <= operand2 ? 1 : 0 - ); - - public static OperationType OperationEquals = new OperationType( - "==", - OperationPrecedence.RelationalEquals, - (operand1, operand2) => operand1 == operand2 ? 1 : 0 - ); - - public static OperationType OperationNotEquals = new OperationType( - "!=", - OperationPrecedence.RelationalEquals, - (operand1, operand2) => operand1 != operand2 ? 1 : 0 - ); - - public static OperationType OperationAnd = new OperationType( - "&&", - OperationPrecedence.LogicalAnd, - (operand1, operand2) => operand1 > 0 && operand2 > 0 ? 1 : 0 - ); - - public static OperationType OperationOr = new OperationType( - "||", - OperationPrecedence.LogicalOr, - (operand1, operand2) => operand1 > 0 || operand2 > 0 ? 1 : 0 - ); - - public static List Types => typeof(OperationType) - .GetFields(BindingFlags.Static | BindingFlags.Public) - .Select(info => info.GetValue(null)) - .OfType() - .ToList(); - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Domain/FastFileStructure/FastFileBlock.cs b/src/ZoneCodeGenerator/Domain/FastFileStructure/FastFileBlock.cs deleted file mode 100644 index 558a409c..00000000 --- a/src/ZoneCodeGenerator/Domain/FastFileStructure/FastFileBlock.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace ZoneCodeGenerator.Domain.FastFileStructure -{ - class FastFileBlock - { - public enum Type - { - Temp, - Runtime, - Delay, - Normal - } - - public string Name { get; } - public long Index { get; } - public Type BlockType { get; } - public bool IsDefault { get; } - public bool IsTemp => BlockType == Type.Temp; - public bool IsRuntime => BlockType == Type.Runtime; - public bool IsDelay => BlockType == Type.Delay; - public bool IsNormal => BlockType == Type.Normal; - - public FastFileBlock(string name, long index, Type blockType, bool isDefault) - { - Name = name; - Index = index; - BlockType = blockType; - IsDefault = isDefault; - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/ForwardDeclaration.cs b/src/ZoneCodeGenerator/Domain/ForwardDeclaration.cs deleted file mode 100644 index 57711cde..00000000 --- a/src/ZoneCodeGenerator/Domain/ForwardDeclaration.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; - -namespace ZoneCodeGenerator.Domain -{ - class ForwardDeclaration : DataType - { - private DataType forwardedType; - - public DataType ForwardedType - { - get => forwardedType; - - set - { - if (forwardedType == null) - { - if(value.Type != Type) - throw new DataException($"Type of forwarded type '{Name}' does not match previous declaration"); - - forwardedType = value; - } - else if(forwardedType != value) - { - throw new DataException($"Tried to set forwarded type '{Name}' multiple times with different types"); - } - } - } - - public ForwardDeclaration(string _namespace, string name, DataTypeType dataTypeType) : base(_namespace, name, dataTypeType) - { - switch (dataTypeType) - { - case DataTypeType.Enum: - case DataTypeType.Struct: - case DataTypeType.Union: - break; - - default: - throw new ArgumentException($"Cannot create forward declaration for type '{dataTypeType}'"); - } - forwardedType = null; - } - - public override int Alignment => 0; - public override bool ForceAlignment => false; - - public override int Size => 0; - } -} diff --git a/src/ZoneCodeGenerator/Domain/Information/MemberInformation.cs b/src/ZoneCodeGenerator/Domain/Information/MemberInformation.cs deleted file mode 100644 index 7d9cf3b1..00000000 --- a/src/ZoneCodeGenerator/Domain/Information/MemberInformation.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain.Evaluation; -using ZoneCodeGenerator.Domain.FastFileStructure; -using ZoneCodeGenerator.Generating.Computations; - -namespace ZoneCodeGenerator.Domain.Information -{ - class MemberInformation - { - public StructureInformation Parent { get; } - public StructureInformation StructureType { get; } - public Variable Member { get; set; } - public bool IsString { get; set; } - public bool IsScriptString { get; set; } - public bool IsReusable { get; set; } - public bool IsLeaf { get; set; } - public IEvaluation Condition { get; set; } - public FastFileBlock Block { get; set; } - - public MemberComputations Computations => new MemberComputations(this); - - public MemberInformation(StructureInformation parent, Variable member, StructureInformation structureType) - { - Parent = parent; - Member = member; - StructureType = structureType; - IsString = false; - IsScriptString = false; - IsReusable = false; - IsLeaf = false; - Condition = null; - Block = null; - } - - public override string ToString() - { - return $"info for {Member.Name}"; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Domain/Information/StructureInformation.cs b/src/ZoneCodeGenerator/Domain/Information/StructureInformation.cs deleted file mode 100644 index 015dda6c..00000000 --- a/src/ZoneCodeGenerator/Domain/Information/StructureInformation.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System.Collections.Generic; -using ZoneCodeGenerator.Domain.FastFileStructure; -using ZoneCodeGenerator.Generating.Computations; - -namespace ZoneCodeGenerator.Domain.Information -{ - class StructureInformation - { - public DataTypeWithMembers Type { get; } - public bool IsUnion => Type is DataTypeUnion; - - public EnumMember AssetEnumEntry { get; set; } - public bool IsAsset => AssetEnumEntry != null; - - private int? fastFileAlign; - public bool HasNonDefaultAlign => fastFileAlign != null; - public int FastFileAlign - { - get => fastFileAlign ?? Type.Alignment; - set => fastFileAlign = value; - } - - public List Usages { get; } - public List OrderedMembers { get; set; } - public bool NonEmbeddedReferenceExists { get; set; } - public bool SinglePointerReferenceExists { get; set; } - public bool ArrayPointerReferenceExists { get; set; } - public bool ArrayReferenceExists { get; set; } - public bool ReferenceFromNonDefaultNormalBlockExists { get; set; } - - public CustomAction PostLoadAction { get; set; } - public FastFileBlock Block { get; set; } - - public bool IsLeaf { get; set; } - - public List NameChain { get; set; } - public StructureComputations Computations => new StructureComputations(this); - - public StructureInformation(DataTypeWithMembers type) - { - AssetEnumEntry = null; - fastFileAlign = null; - Type = type; - NonEmbeddedReferenceExists = false; - SinglePointerReferenceExists = false; - ArrayReferenceExists = false; - ReferenceFromNonDefaultNormalBlockExists = false; - Usages = new List(); - OrderedMembers = new List(); - PostLoadAction = null; - IsLeaf = true; - NameChain = null; - } - - public override string ToString() - { - return $"info for {Type}"; - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/Namespace.cs b/src/ZoneCodeGenerator/Domain/Namespace.cs deleted file mode 100644 index a9aecd84..00000000 --- a/src/ZoneCodeGenerator/Domain/Namespace.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; - -namespace ZoneCodeGenerator.Domain -{ - class Namespace - { - private static readonly Regex nameRegex = new Regex(@"^[a-zA-Z_$][a-zA-Z0-9_$]*$"); - private readonly Stack namespaceStack; - - public Namespace() - { - namespaceStack = new Stack(); - } - - public void Push(string _namespace) - { - if(!nameRegex.IsMatch(_namespace)) - throw new ArgumentException("Namespace name invalid"); - - namespaceStack.Push(_namespace); - } - - public string Pop() - { - return namespaceStack.Pop(); - } - - public string GetName() - { - if (namespaceStack.Count == 0) - return ""; - - var result = ""; - var stackSnapshot = namespaceStack.ToArray(); - - // The stack is read from top to bottom. Therefore we need to access it in reverse order here. - for(var i = stackSnapshot.Length - 1; i >= 0; i--) - { - if (!string.IsNullOrEmpty(result)) - result += "::"; - result += stackSnapshot[i]; - } - - return result; - } - - public override string ToString() - { - return GetName(); - } - - public static string Combine(Namespace _namespace, string typename) - { - return $"{_namespace}::{typename}"; - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/ReferenceType.cs b/src/ZoneCodeGenerator/Domain/ReferenceType.cs deleted file mode 100644 index 22369ce9..00000000 --- a/src/ZoneCodeGenerator/Domain/ReferenceType.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZoneCodeGenerator.Domain -{ - abstract class ReferenceType - { - - } -} diff --git a/src/ZoneCodeGenerator/Domain/ReferenceTypeArray.cs b/src/ZoneCodeGenerator/Domain/ReferenceTypeArray.cs deleted file mode 100644 index 70399de3..00000000 --- a/src/ZoneCodeGenerator/Domain/ReferenceTypeArray.cs +++ /dev/null @@ -1,19 +0,0 @@ -using ZoneCodeGenerator.Domain.Evaluation; - -namespace ZoneCodeGenerator.Domain -{ - class ReferenceTypeArray : ReferenceType - { - public int ArraySize { get; } - - public IEvaluation DynamicSize { get; set; } - public IEvaluation DynamicCount { get; set; } - - public ReferenceTypeArray(int arraySize) - { - ArraySize = arraySize; - DynamicSize = null; - DynamicCount = null; - } - } -} diff --git a/src/ZoneCodeGenerator/Domain/ReferenceTypePointer.cs b/src/ZoneCodeGenerator/Domain/ReferenceTypePointer.cs deleted file mode 100644 index b9d59abc..00000000 --- a/src/ZoneCodeGenerator/Domain/ReferenceTypePointer.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain.Evaluation; - -namespace ZoneCodeGenerator.Domain -{ - class ReferenceTypePointer : ReferenceType - { - public static IEvaluation DefaultCount = new OperandStatic(1); - - public IEvaluation Count { get; set; } = DefaultCount; - public IEvaluation[] CountByArrayIndex { get; set; } - public bool HasCountByArrayIndex => CountByArrayIndex != null; - - private static bool EvaluationIsArray(IEvaluation eval) - { - return !eval.IsStatic || eval.EvaluateNumeric() > 1; - } - - public bool IsArray(int index) - { - return EvaluationIsArray(HasCountByArrayIndex ? CountByArrayIndex[index] : Count); - } - - public bool AnyIsArray => - HasCountByArrayIndex ? CountByArrayIndex.Any(EvaluationIsArray) : EvaluationIsArray(Count); - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Domain/TypeDeclaration.cs b/src/ZoneCodeGenerator/Domain/TypeDeclaration.cs deleted file mode 100644 index 1832ec04..00000000 --- a/src/ZoneCodeGenerator/Domain/TypeDeclaration.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace ZoneCodeGenerator.Domain -{ - class TypeDeclaration - { - private const int PointerSize = 4; - - public DataType Type { get; set; } - - - public int? CustomBitSize { get; set; } - - public bool IsConst { get; set; } - - public bool HasCustomBitSize => CustomBitSize != null; - - private readonly List references; - public IReadOnlyList References => references.AsReadOnly(); - - public int Alignment => references.OfType().Any() ? PointerSize : Type.Alignment; - public bool ForceAlignment => !references.OfType().Any() && Type.ForceAlignment; - - public int Size - { - get - { - var currentSize = Type.Size; - - foreach (var reference in References.Reverse()) - { - switch (reference) - { - case ReferenceTypePointer _: - currentSize = PointerSize; - break; - case ReferenceTypeArray array: - currentSize *= array.ArraySize; - break; - } - } - - return currentSize; - } - } - - public TypeDeclaration(DataType type, List references) - { - Type = type; - this.references = references ?? new List(); - CustomBitSize = null; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Domain/Variable.cs b/src/ZoneCodeGenerator/Domain/Variable.cs deleted file mode 100644 index 30cb2038..00000000 --- a/src/ZoneCodeGenerator/Domain/Variable.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace ZoneCodeGenerator.Domain -{ - class Variable - { - public string Name { get; } - - public int? AlignmentOverride { get; set; } - - public int Alignment => AlignmentOverride ?? VariableType.Alignment; - public bool ForceAlignment => AlignmentOverride != null || VariableType.ForceAlignment; - - public TypeDeclaration VariableType { get; } - - public Variable(string name, TypeDeclaration type) - { - Name = name; - VariableType = type; - } - } -} diff --git a/src/ZoneCodeGenerator/Generating/CodeGenerator.cs b/src/ZoneCodeGenerator/Generating/CodeGenerator.cs deleted file mode 100644 index 30534e9e..00000000 --- a/src/ZoneCodeGenerator/Generating/CodeGenerator.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Interface; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Generating -{ - static class CodeGenerator - { - private class GeneratorPreset - { - public string FileName { get; } - public string TemplateName { get; } - - public GeneratorPreset(string fileName, string templateName) - { - FileName = fileName; - TemplateName = templateName; - } - } - - private static readonly Dictionary presets = - new Dictionary(StringComparer.CurrentCultureIgnoreCase) - { - { - "ZoneLoad", new GeneratorPreset("$asset/$asset_load_db", "ZoneLoad.stg") - }, - { - "ZoneWrite", new GeneratorPreset("$asset/$asset_write_db", "ZoneWrite.stg") - }, - { - "AssetStructTests", new GeneratorPreset("$asset/$asset_struct_test", "AssetStructTests.stg") - } - }; - - public static IEnumerable Presets => presets.Keys; - - public static bool GenerateCodeForPreset(string presetName, StructureInformation asset, CUISession session) - { - if (!presets.ContainsKey(presetName)) - { - Console.WriteLine($"Unknown preset '{presetName}'"); - return false; - } - - var preset = presets[presetName]; - - try - { - if (!Directory.Exists(session.GeneratorOutputPath)) - Directory.CreateDirectory(session.GeneratorOutputPath); - - var codeTemplate = CodeTemplate.FromResources(preset.TemplateName); - - if (codeTemplate == null) - { - Console.WriteLine($"Could not find template '{preset.TemplateName}'"); - return false; - } - - var resolvedFileName = preset.FileName.Replace("$asset", asset.Type.Name.ToLower()); - var fullPath = Path.Combine(session.GeneratorOutputPath, resolvedFileName); - var folderOfFile = Path.GetDirectoryName(fullPath); - - if (!Directory.Exists(folderOfFile)) - Directory.CreateDirectory(folderOfFile); - - var renderingContext = RenderingContext.BuildContext(session, asset); - - if (renderingContext == null) - { - Console.WriteLine("Building rendering context failed"); - return false; - } - - if (!codeTemplate.HasHeaderTemplate && !codeTemplate.HasSourceTemplate) - { - Console.WriteLine($"Preset '{presetName}' does not have a header or a source! This is weird."); - return false; - } - - if (codeTemplate.HasHeaderTemplate) - { - using (var fileStream = new FileStream(fullPath + ".h", FileMode.Create)) - { - codeTemplate.RenderHeaderFile(fileStream, renderingContext); - fileStream.Close(); - } - } - - if (codeTemplate.HasSourceTemplate) - { - using (var fileStream = new FileStream(fullPath + ".cpp", FileMode.Create)) - { - codeTemplate.RenderSourceFile(fileStream, renderingContext); - fileStream.Close(); - } - } - - return true; - } - catch (Exception e) - { - Console.WriteLine("An exception occured while trying to generate code"); - Console.WriteLine(e.GetType().Name); - Console.WriteLine(e.Message); - return false; - } - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/CodeTemplate.cs b/src/ZoneCodeGenerator/Generating/CodeTemplate.cs deleted file mode 100644 index eeed1884..00000000 --- a/src/ZoneCodeGenerator/Generating/CodeTemplate.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.IO; -using Antlr4.StringTemplate; -using ZoneCodeGenerator.Domain; - -namespace ZoneCodeGenerator.Generating -{ - class CodeTemplate - { - private const string SourceTemplateName = "source"; - private const string HeaderTemplateName = "header"; - - private readonly TemplateGroup templateGroup; - - public bool HasSourceTemplate => templateGroup.IsDefined(SourceTemplateName); - public bool HasHeaderTemplate => templateGroup.IsDefined(HeaderTemplateName); - - private CodeTemplate(TemplateGroup templateGroup) - { - this.templateGroup = templateGroup; - templateGroup.RegisterRenderer(typeof(string), new StringRenderer()); - templateGroup.RegisterRenderer(typeof(DataType), new DataTypeAttributeRenderer()); - } - - public static CodeTemplate FromResources(string fileName) - { - var templateGroup = new TemplateGroupResources(fileName); - - templateGroup.Load(); - - return new CodeTemplate(templateGroup); - } - - public void RenderSourceFile(Stream stream, RenderingContext context) - { - RenderTemplate(stream, templateGroup.GetInstanceOf(SourceTemplateName), context); - } - - public void RenderHeaderFile(Stream stream, RenderingContext context) - { - RenderTemplate(stream, templateGroup.GetInstanceOf(HeaderTemplateName), context); - } - - private static void RenderTemplate(Stream stream, Template template, RenderingContext context) - { - if (template == null) - return; - - template.Add("context", context); - - using (var writer = new StreamWriter(stream)) - { - template.Write(new AutoIndentWriter(writer)); - } - } - } -} diff --git a/src/ZoneCodeGenerator/Generating/Computations/MemberComputations.cs b/src/ZoneCodeGenerator/Generating/Computations/MemberComputations.cs deleted file mode 100644 index 9064c681..00000000 --- a/src/ZoneCodeGenerator/Generating/Computations/MemberComputations.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Evaluation; -using ZoneCodeGenerator.Domain.Information; - -namespace ZoneCodeGenerator.Generating.Computations -{ - class MemberComputations - { - private readonly MemberInformation information; - - public bool ShouldIgnore => information.Condition != null - && information.Condition.IsStatic - && information.Condition.EvaluateNumeric() == 0; - - public bool ContainsNonEmbeddedReference => - information.Member.VariableType.References.OfType().Any(); - - public bool ContainsSinglePointerReference => information.Member.VariableType.References.Any() - && information.Member.VariableType.References.Last() is - ReferenceTypePointer pointerReference - && !pointerReference.AnyIsArray; - - public bool ContainsArrayPointerReference => information.Member.VariableType.References.Any() - && information.Member.VariableType.References.Last() is - ReferenceTypePointer pointerReference - && pointerReference.AnyIsArray; - - public bool ContainsPointerArrayReference => ContainsSinglePointerReference - && (IsArray && PointerDepthIsOne || !IsArray && PointerDepthIsTwo); - - public bool ContainsArrayReference => information.Member.VariableType.References.Any() - && information.Member.VariableType.References - .Last() is ReferenceTypeArray; - - - public IEvaluation ArrayPointerCountEvaluation => - information.Member.VariableType.References.Last() is ReferenceTypePointer pointerReference - ? pointerReference.Count - : null; - - public bool IsArray => information.Member.VariableType.References - .TakeWhile(type => type is ReferenceTypeArray) - .Any(); - - public IEnumerable ArraySizes => information.Member.VariableType.References - .TakeWhile(type => type is ReferenceTypeArray) - .OfType() - .Select(array => array.ArraySize); - - public int ArrayDimension => information.Member.VariableType.References - .TakeWhile(type => type is ReferenceTypeArray) - .Count(); - - public bool IsPointerToArray => information.Member.VariableType.References.OfType().Any() - && information.Member.VariableType.References.Last() is ReferenceTypeArray; - - public IEnumerable PointerToArraySizes => information.Member.VariableType.References - .Reverse() - .TakeWhile(type => type is ReferenceTypeArray) - .OfType() - .Reverse() - .Select(array => array.ArraySize); - - public int PointerDepth => information.Member.VariableType.References - .OfType() - .Count(); - - public bool PointerDepthIsOne => PointerDepth == 1; - public bool PointerDepthIsTwo => PointerDepth == 2; - - public bool IsNotDefaultNormalBlock => - information.Block != null && !(information.Block.IsNormal && information.Block.IsDefault); - - public bool IsTempBlock => information.Block != null && information.Block.IsTemp; - public bool IsRuntimeBlock => information.Block != null && information.Block.IsRuntime; - - private IEnumerable ParentUsedMembers => - information.Parent.IsUnion && information.Parent.Computations.DynamicMember != null - ? information.Parent.OrderedMembers.Where(member => !member.Computations.ShouldIgnore) - : information.Parent.OrderedMembers.Where(member => - !member.IsLeaf && !member.Computations.ShouldIgnore); - - public bool IsFirstMember => ParentUsedMembers.FirstOrDefault() == information; - - public bool IsLastMember => ParentUsedMembers.LastOrDefault() == information; - - public bool HasDynamicArraySize => information.Member.VariableType.References - .OfType() - .Any(array => array.DynamicSize != null); - - public bool IsDynamicMember => HasDynamicArraySize || - !ContainsNonEmbeddedReference && - information.StructureType?.Computations.DynamicMember != null; - - public bool IsAfterPartialLoad => IsDynamicMember || - information.Parent.IsUnion && - information.Parent.Computations.DynamicMember != null; - - public MemberReferenceComputations References => new MemberReferenceComputations(information); - - public MemberComputations(MemberInformation information) - { - this.information = information; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/Computations/MemberReferenceComputations.cs b/src/ZoneCodeGenerator/Generating/Computations/MemberReferenceComputations.cs deleted file mode 100644 index c41c8c22..00000000 --- a/src/ZoneCodeGenerator/Generating/Computations/MemberReferenceComputations.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Evaluation; -using ZoneCodeGenerator.Domain.Information; - -namespace ZoneCodeGenerator.Generating.Computations -{ - class MemberReferenceComputations - { - private readonly MemberInformation information; - private readonly List referenceIndices; - private readonly int combinedIndex; - - public ReferenceType Reference => referenceIndices.Count < information.Member.VariableType.References.Count - ? information.Member.VariableType.References[referenceIndices.Count] - : null; - - public ReferenceType NextReference => - referenceIndices.Count + 1 < information.Member.VariableType.References.Count - ? information.Member.VariableType.References[referenceIndices.Count + 1] - : null; - - public IEnumerable FollowingReferences => - information.Member.VariableType.References.Skip(referenceIndices.Count + 1); - - public IEnumerable ArrayIndices => referenceIndices; - - public bool IsArray => Reference is ReferenceTypeArray; - public int ArraySize => Reference is ReferenceTypeArray array ? array.ArraySize : 0; - - public bool HasDynamicArrayCount => Reference is ReferenceTypeArray array && array.DynamicCount != null; - - public IEvaluation DynamicArrayCountEvaluation => - Reference is ReferenceTypeArray array ? array.DynamicCount : null; - - public IEnumerable ArrayEntries => Enumerable.Range(0, ArraySize) - .Select(i => new MemberReferenceComputations(information, referenceIndices.Concat(new[] {i}))); - - public bool IsSinglePointer => Reference is ReferenceTypePointer referenceTypePointer - && !referenceTypePointer.IsArray(combinedIndex) - && !FollowingReferences.OfType().Any(); - - public bool IsArrayPointer => Reference is ReferenceTypePointer referenceTypePointer - && referenceTypePointer.IsArray(combinedIndex) - && !FollowingReferences.OfType().Any(); - - public IEvaluation ArrayPointerCountEvaluation - { - get - { - if (!(Reference is ReferenceTypePointer pointer)) - return null; - - return pointer.HasCountByArrayIndex ? pointer.CountByArrayIndex[combinedIndex] : pointer.Count; - } - } - - public bool IsPointerArray => - (Reference is ReferenceTypePointer referenceTypePointer && referenceTypePointer.IsArray(combinedIndex) || - Reference is ReferenceTypeArray) - && NextReference is ReferenceTypePointer nextReferencePointer && - !nextReferencePointer.IsArray(combinedIndex); - - public IEvaluation PointerArrayCountEvaluation => NextReference is ReferenceTypePointer referenceTypePointer - ? referenceTypePointer.Count - : null; - - public bool IsDynamicArray => - Reference is ReferenceTypeArray referenceTypeArray && referenceTypeArray.DynamicSize != null; - - public IEvaluation DynamicArraySizeEvaluation => Reference is ReferenceTypeArray referenceTypeArray - ? referenceTypeArray.DynamicSize - : null; - - public MemberReferenceComputations(MemberInformation information) - { - this.information = information; - referenceIndices = new List(); - combinedIndex = 0; - } - - private MemberReferenceComputations(MemberInformation information, IEnumerable referenceIndices) - { - this.information = information; - this.referenceIndices = new List(referenceIndices); - - var arraySizes = information.Member.VariableType.References - .OfType() - .Select(array => array.ArraySize) - .ToList(); - var indexDepth = 0; - combinedIndex = 0; - foreach (var referenceIndex in this.referenceIndices) - { - var sizePerIndexInCurrentDepth = arraySizes.Count <= indexDepth + 1 - ? 1 - : arraySizes.Skip(indexDepth + 1).Aggregate((i1, i2) => i1 * i2); - - combinedIndex += referenceIndex * sizePerIndexInCurrentDepth; - indexDepth++; - } - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/Computations/StructureComputations.cs b/src/ZoneCodeGenerator/Generating/Computations/StructureComputations.cs deleted file mode 100644 index 204551dd..00000000 --- a/src/ZoneCodeGenerator/Generating/Computations/StructureComputations.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Evaluation; -using ZoneCodeGenerator.Domain.Information; - -namespace ZoneCodeGenerator.Generating.Computations -{ - class StructureComputations - { - private readonly StructureInformation information; - - public bool IsUsed => information.Usages.Any(); - - public MemberInformation DynamicMember => - information.OrderedMembers.FirstOrDefault(memberInformation => memberInformation.Computations.IsDynamicMember); - - public StructureComputations(StructureInformation information) - { - this.information = information; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/DataTypeAttributeRenderer.cs b/src/ZoneCodeGenerator/Generating/DataTypeAttributeRenderer.cs deleted file mode 100644 index 3feb739e..00000000 --- a/src/ZoneCodeGenerator/Generating/DataTypeAttributeRenderer.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Globalization; -using Antlr4.StringTemplate; -using ZoneCodeGenerator.Domain; - -namespace ZoneCodeGenerator.Generating -{ - class DataTypeAttributeRenderer : IAttributeRenderer - { - public string ToString(object obj, string formatString, CultureInfo culture) - { - if (formatString == null) - return obj.ToString(); - - if (!(obj is DataType dataType)) - { - return obj.ToString(); - } - - switch (formatString) - { - case "safe_name": - return dataType.Name.Replace(" ", "_"); - - default: - return obj.ToString(); - } - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/RenderingContext.cs b/src/ZoneCodeGenerator/Generating/RenderingContext.cs deleted file mode 100644 index 5e7d897e..00000000 --- a/src/ZoneCodeGenerator/Generating/RenderingContext.cs +++ /dev/null @@ -1,162 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.FastFileStructure; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Interface; - -namespace ZoneCodeGenerator.Generating -{ - class RenderingContext - { - public class UsedType - { - public bool MembersLoaded { get; set; } - public DataType Type { get; } - public StructureInformation Information { get; } - public bool IsContextAsset { get; set; } - - public bool NonRuntimeReferenceExists { get; set; } - public bool NonEmbeddedReferenceExists { get; set; } - public bool ArrayReferenceExists { get; set; } - public bool PointerArrayReferenceExists { get; set; } - public bool PointerArrayReferenceIsReusable { get; set; } - - public UsedType(DataType type, StructureInformation information) - { - MembersLoaded = false; - Type = type; - Information = information; - IsContextAsset = false; - NonRuntimeReferenceExists = false; - NonEmbeddedReferenceExists = false; - ArrayReferenceExists = false; - PointerArrayReferenceExists = false; - PointerArrayReferenceIsReusable = false; - } - } - - public string Game { get; set; } - public StructureInformation Asset { get; private set; } - - private readonly IDictionary usedTypes; - public IEnumerable UsedTypes => usedTypes.Values; - - public IEnumerable UsedStructures => UsedTypes - .Where(usedType => usedType.Information != null && usedType.Information.Type == usedType.Type); - - public IEnumerable ReferencedAssets => UsedTypes.Where(type => - type.Information != null && type.Information.IsAsset && type.Information != Asset); - - public IList Blocks { get; private set; } - - public FastFileBlock DefaultNormalBlock => Blocks.FirstOrDefault(block => block.IsDefault && block.IsNormal) ?? - Blocks.FirstOrDefault(block => block.IsNormal); - - public FastFileBlock DefaultTempBlock => Blocks.FirstOrDefault(block => block.IsDefault && block.IsTemp) ?? - Blocks.FirstOrDefault(block => block.IsTemp); - - public bool HasActions => UsedTypes.Any(type => - (type.Information == null || !type.Information.IsAsset || type.IsContextAsset) && type.NonRuntimeReferenceExists && - type.Information?.PostLoadAction != null); - - private RenderingContext() - { - usedTypes = new Dictionary(); - } - - private UsedType GetBaseType(UsedType usedType) - { - if (usedType.Type is DataTypeTypedef typeDef) - { - while (typeDef.TypeDefinition.Type is DataTypeTypedef anotherTypeDef) - { - typeDef = anotherTypeDef; - } - - if (!usedTypes.ContainsKey(typeDef.TypeDefinition.Type)) - { - var result = new UsedType(typeDef.TypeDefinition.Type, usedType.Information); - usedTypes.Add(typeDef.TypeDefinition.Type, result); - - return result; - } - - return usedTypes[typeDef.TypeDefinition.Type]; - } - - return null; - } - - private void AddMembersToContext(StructureInformation structureInformation) - { - foreach (var member in structureInformation.OrderedMembers - .Where(member => !member.Computations.ShouldIgnore)) - { - UsedType usedType; - if (!usedTypes.ContainsKey(member.Member.VariableType.Type)) - { - usedType = new UsedType(member.Member.VariableType.Type, member.StructureType); - usedTypes.Add(usedType.Type, usedType); - } - else - { - usedType = usedTypes[member.Member.VariableType.Type]; - } - - var baseUsedType = GetBaseType(usedType); - - if (!member.Computations.IsRuntimeBlock) - { - usedType.NonRuntimeReferenceExists = true; - - if (baseUsedType != null) - baseUsedType.NonRuntimeReferenceExists = true; - } - - if (member.Computations.ContainsNonEmbeddedReference) - usedType.NonEmbeddedReferenceExists = true; - - if (member.Computations.ContainsArrayPointerReference || member.Computations.ContainsArrayReference) - usedType.ArrayReferenceExists = true; - - if (member.Computations.ContainsPointerArrayReference && !member.IsString) - { - usedType.PointerArrayReferenceExists = true; - - if (member.IsReusable) - usedType.PointerArrayReferenceIsReusable = true; - } - - if (usedType.Information != null && !usedType.Information.IsAsset && !member.Computations.IsRuntimeBlock && - !usedType.MembersLoaded) - { - usedType.MembersLoaded = true; - AddMembersToContext(usedType.Information); - } - } - } - - private void MakeAsset(StructureInformation asset) - { - Asset = asset; - var usage = new UsedType(asset.Type, asset) {IsContextAsset = true}; - usedTypes.Add(usage.Type, usage); - - AddMembersToContext(asset); - } - - public static RenderingContext BuildContext(CUISession session, StructureInformation asset) - { - var context = new RenderingContext - { - Game = session.Game, - Blocks = session.Repository.GetAllFastFileBlocks().ToList() - }; - - context.MakeAsset(asset); - - return context; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/TemplateGroupResources.cs b/src/ZoneCodeGenerator/Generating/TemplateGroupResources.cs deleted file mode 100644 index 035abfb3..00000000 --- a/src/ZoneCodeGenerator/Generating/TemplateGroupResources.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using System.IO; -using System.Reflection; -using Antlr.Runtime; -using Antlr4.StringTemplate; -using Antlr4.StringTemplate.Compiler; -using Antlr4.StringTemplate.Misc; - -namespace ZoneCodeGenerator.Generating -{ - public class TemplateGroupResources : TemplateGroup - { - private const string ResourceBasePath = "ZoneCodeGenerator.Generating.Templates"; - private const char DefaultDelimiterStart = '<'; - private const char DefaultDelimiterStop = '>'; - - private bool alreadyLoaded; - private readonly string fileName; - - public TemplateGroupResources(string fileName, char delimiterStartChar, char delimiterStopChar) : base(delimiterStartChar, delimiterStopChar) - { - this.fileName = fileName; - alreadyLoaded = false; - } - - public TemplateGroupResources(string fileName) : this(fileName, DefaultDelimiterStart, DefaultDelimiterStop) - { - - } - - public override void ImportTemplates(IToken fileNameToken) - { - var text = Utility.Strip(fileNameToken.Text, 1); - - TemplateGroup importingGroup = null; - if (text.EndsWith(GroupFileExtension)) - { - importingGroup = new TemplateGroupResources(text, DelimiterStartChar, DelimiterStopChar); - } - else if (text.EndsWith(TemplateFileExtension)) - { - importingGroup = new TemplateGroup(DelimiterStartChar, DelimiterStopChar); - - using (var resourceStream = StreamFromResources(text)) - { - if (resourceStream != null) - { - using (var textStream = new StreamReader(resourceStream)) - { - var inputStream = new ANTLRReaderStream(textStream) - { - name = fileName - }; - - importingGroup.LoadTemplateFile("/", fileName, inputStream); - } - } - } - } - - if (importingGroup != null) - { - importingGroup.Load(); - ImportTemplates(importingGroup); - } - else - { - ErrorManager.CompiletimeError(ErrorType.CANT_IMPORT, null, fileNameToken, text); - } - } - - public override void Load() - { - if (alreadyLoaded) - return; - alreadyLoaded = true; - - if (Verbose) - Console.WriteLine($"loading group file '{fileName}'"); - - using (var resourceStream = StreamFromResources(fileName)) - { - if (resourceStream == null) - { - Console.WriteLine($"Resource '{fileName}' doesn't exist"); - Console.WriteLine("The following files do exist: " + string.Join(", ", Assembly.GetExecutingAssembly().GetManifestResourceNames())); - - return; - } - - using (var textStream = new StreamReader(resourceStream)) - { - var inputStream = new ANTLRReaderStream(textStream) - { - name = fileName - }; - - try - { - var lexer = new GroupLexer(inputStream); - var tokenStream = new CommonTokenStream(lexer); - var parser = new GroupParser(tokenStream); - - parser.group(this, "/"); - } - catch (Exception ex) - { - ErrorManager.IOError(null, ErrorType.CANT_LOAD_GROUP_FILE, ex, FileName); - } - } - } - } - - private static Stream StreamFromResources(string fileName) - { - var resourceName = $"{ResourceBasePath}.{fileName.Replace('\\', '.').Replace('/', '.')}"; - var assembly = Assembly.GetExecutingAssembly(); - - return assembly.GetManifestResourceStream(resourceName); - } - - public override string Name => "TemplateGroupResources"; - - public override string FileName => Name; - } -} diff --git a/src/ZoneCodeGenerator/Generating/Templates/AssetStructTests.stg b/src/ZoneCodeGenerator/Generating/Templates/AssetStructTests.stg deleted file mode 100644 index 31429fac..00000000 --- a/src/ZoneCodeGenerator/Generating/Templates/AssetStructTests.stg +++ /dev/null @@ -1,41 +0,0 @@ -delimiters "$", "$" - -import "Common.stg" - -TestMethod(structure) ::= << -$if(structure.NonEmbeddedReferenceExists)$ -TEST_METHOD(Test_$structure.Type.Name$) -{ - Assert::AreEqual($structure.Type.Size$u, sizeof($structure.Type.FullName$)); - Assert::AreEqual($structure.Type.Alignment$u, alignof($structure.Type.FullName$)); -} -$endif$ ->> - -// ======================= -// Source file entry point -// ======================= -source(context) ::= << -// ==================================================================== -// This file has been generated by ZoneCodeGenerator. -// Do not modify. -// Any changes will be discarded when regenerating. -// ==================================================================== - -#include "CppUnitTest.h" -#include "Game/$context.Game$/$context.Game$.h" - -using namespace Microsoft::VisualStudio::CppUnitTestFramework; -using namespace $context.Game$; - -namespace ZoneCommonTests -{ - TEST_CLASS(AssetStructTest_$context.Asset.Type.Name$) - { - public: - $TestMethod(context.Asset)$ - $context.UsedStructures:{structure | $if(!structure.Information.Type.IsAnonymous && !structure.Information.IsAsset)$$TestMethod(structure)$ - $endif$}$ - }; -} ->> \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/Templates/Common.stg b/src/ZoneCodeGenerator/Generating/Templates/Common.stg deleted file mode 100644 index 64f39a8e..00000000 --- a/src/ZoneCodeGenerator/Generating/Templates/Common.stg +++ /dev/null @@ -1,69 +0,0 @@ -delimiters "$", "$" - -Capital(name) ::= "$name; format=\"cap\"$" -Lower(name) ::= "$name; format=\"lower\"$" - -TypeDeclaration(typeDecl) ::= "$if(typeDecl.IsConst)$const $endif$$typeDecl.Type.FullName$" - -TypeVarName(type) ::= "var$SafeTypeName(type)$" -TypePtrVarName(type) ::= "var$SafeTypeName(type)$Ptr" - -SafeTypeName(type) ::= "$type; format=\"safe_name\"$" - -PrintFollowingReferences(references) ::= <% -$references:{ reference | - -$if(reference.ArraySize)$ -[$reference.ArraySize$] -$else$ -* -$endif$ - -}$ -%> - -PrintArrayIndices(reference) ::= "$reference.ArrayIndices:{ index | [$index$]}$" - -PrintOperandStatic(op) ::= <% -$if(op.EnumMemberValue)$ -$op.EnumMemberValue.Name$ -$else$ -$op.Value$ -$endif$ -%> - -PrintOperandDynamic(op) ::= <% -$TypeVarName(op.Structure.Type)$ -$if(first(op.ReferencedMemberChain))$ -->$trunc(op.ReferencedMemberChain):{member | $member.Member.Name$$if(member.Computations.ContainsNonEmbeddedReference)$->$else$.$endif$}$ -$last(op.ReferencedMemberChain):{member | $member.Member.Name$}$ -$op.ArrayIndices:{ arrayIndex | [$PrintEvaluation(arrayIndex)$]}$ -$endif$ -%> - -PrintOperation(operation) ::= <% -$if(operation.Operand1NeedsParenthesis)$ -($PrintEvaluation(operation.Operand1)$) -$else$ -$PrintEvaluation(operation.Operand1)$ -$endif$ - -$operation.OperationType.Syntax$ - -$if(operation.Operand2NeedsParenthesis)$ -($PrintEvaluation(operation.Operand2)$) -$else$ -$PrintEvaluation(operation.Operand2)$ -$endif$ - -%> - -PrintEvaluation(eval) ::= <% -$if(eval.OperationType)$ -$PrintOperation(eval)$ -$elseif(eval.IsStatic)$ -$PrintOperandStatic(eval)$ -$else$ -$PrintOperandDynamic(eval)$ -$endif$ -%> \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/Templates/Loading/ArrayPointer.stg b/src/ZoneCodeGenerator/Generating/Templates/Loading/ArrayPointer.stg deleted file mode 100644 index c5abc87b..00000000 --- a/src/ZoneCodeGenerator/Generating/Templates/Loading/ArrayPointer.stg +++ /dev/null @@ -1,165 +0,0 @@ -delimiters "$", "$" - -// Everything related to loading a pointer with a count that can be larger than 1 - -LoadArrayPointer_Loading(context, structure, member, reference) ::= << -$if(member.Computations.IsTempBlock)$ -$member.Member.VariableType.Type.FullName$* ptr = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$; -$endif$$\\$ - -$TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = m_stream->Alloc<$TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$>(alignof($TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$)); $\\$ -// $member.Member.VariableType.Type.Alignment$$\\$ -$\\$ -$\\$ -$if(member.Computations.IsTempBlock)$ - -$member.Member.VariableType.Type.FullName$** toInsert = nullptr; -if(ptr == PTR_INSERT) - toInsert = m_stream->InsertPointer<$member.Member.VariableType.Type.FullName$>(); - -$endif$$\\$ -$\\$ -$\\$ -$if(member.StructureType && !member.StructureType.IsLeaf && !member.Computations.IsRuntimeBlock)$ -$TypeVarName(member.Member.VariableType.Type)$ = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$; -LoadArray_$member.Member.VariableType.Type.Name$(true, $PrintEvaluation(reference.ArrayPointerCountEvaluation)$);$\\$ -$else$ -m_stream->Load<$TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$>($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$, $PrintEvaluation(reference.ArrayPointerCountEvaluation)$);$\\$ -$endif$$\\$ -$\\$ -$if(member.Computations.IsTempBlock)$ - -if(toInsert != nullptr) - *toInsert = $TypeVarName(structure.Type)$->$member.Member.Name$;$\\$ -$endif$ ->> - -LoadArrayPointer_ScriptString(context, structure, member, reference) ::= <% -$TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = m_stream->Alloc<$TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$>(alignof($TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$)); -// $member.Member.VariableType.Type.Alignment$ -$\n$ - -varScriptString = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$;$\n$ -LoadScriptStringArray(true, $PrintEvaluation(reference.ArrayPointerCountEvaluation)$); - -%> - -LoadArrayPointer_TypeCheck(context, structure, member, reference) ::= <% -$if(member.IsScriptString)$ -$LoadArrayPointer_ScriptString(context, structure, member, reference)$ -$else$ -$LoadArrayPointer_Loading(context, structure, member, reference)$ -$endif$ -%> - -LoadArrayPointer_Reuse(context, structure, member, reference) ::= << -$if(member.Computations.IsTempBlock)$ -if($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ == PTR_FOLLOWING || $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ == PTR_INSERT) -{ - $LoadArrayPointer_TypeCheck(context, structure, member, reference)$ -} -else -{ - $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = m_stream->ConvertOffsetToAlias($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$); -}$\\$ -$else$ -if($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ == PTR_FOLLOWING) -{ - $LoadArrayPointer_TypeCheck(context, structure, member, reference)$ -} -else -{ - $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = m_stream->ConvertOffsetToPointer($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$); -}$\\$ -$endif$ ->> - -LoadArrayPointer_PointerCheck(context, structure, member, reference) ::= << -if ($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$) -{ - $if(member.IsReusable)$ - $LoadArrayPointer_Reuse(context, structure, member, reference)$ - $else$ - $LoadArrayPointer_TypeCheck(context, structure, member, reference)$ - $endif$ -} ->> - -LoadArrayPointer_Block(context, structure, member, reference) ::= <% -$if(member.Computations.IsNotDefaultNormalBlock)$ -m_stream->PushBlock($member.Block.Name$);$\n$ -$endif$ - -$LoadArrayPointer_PointerCheck(context, structure, member, reference)$ - -$if(member.Computations.IsNotDefaultNormalBlock)$ -$\n$m_stream->PopBlock(); -$endif$ -%> - -LoadArrayPointer(context, structure, member, reference) ::= <% -$LoadArrayPointer_Block(context, structure, member, reference)$ -%> - -LoadPointerArrayMethod_Loading(context, type, structure) ::= <% -*$TypePtrVarName(type)$ = m_stream->Alloc<$type.FullName$>(alignof($type.FullName$)); -// $type.Alignment$ -$\n$ - -$if(structure && !structure.IsLeaf)$ - -$TypeVarName(structure.Type)$ = *$TypePtrVarName(type)$;$\n$ -Load_$type.Name$(true); - -$else$ - -m_stream->Load<$type.FullName$>(*$TypePtrVarName(type)$); - -$endif$ -%> - -LoadPointerArrayMethod_Asset(context, type, structure) ::= << -$LoaderClassName(structure)$ loader(m_zone, m_stream); -AddDependency(loader.Load($TypePtrVarName(type)$)); ->> - -LoadPointerArrayMethod_PointerCheck(context, type, structure, reusable) ::= << -if (*$TypePtrVarName(type)$) -{ - $if(structure && structure.IsAsset)$ - $LoadPointerArrayMethod_Asset(context, type, structure)$ - $else$ - $if(reusable)$ - if(*$TypePtrVarName(type)$ == PTR_FOLLOWING) - { - $LoadPointerArrayMethod_Loading(context, type, structure)$ - } - else - { - *$TypePtrVarName(type)$ = m_stream->ConvertOffsetToPointer(*$TypePtrVarName(type)$); - } - $else$ - $LoadPointerArrayMethod_Loading(context, type, structure)$ - $endif$ - $endif$ -} ->> - -LoadPointerArrayMethod(context, type, structure, reusable) ::= << -void $LoaderClassName(context.Asset)$::LoadPtrArray_$SafeTypeName(type)$(const bool atStreamStart, const size_t count) -{ - assert($TypePtrVarName(type)$ != nullptr); - - if(atStreamStart) - m_stream->Load<$type.FullName$*>($TypePtrVarName(type)$, count); - - $type.FullName$** var = $TypePtrVarName(type)$; - for(size_t index = 0; index < count; index++) - { - $TypePtrVarName(type)$ = var; - $LoadPointerArrayMethod_PointerCheck(context, type, structure, reusable)$ - - var++; - } -} ->> \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/Templates/Loading/Common.stg b/src/ZoneCodeGenerator/Generating/Templates/Loading/Common.stg deleted file mode 100644 index 0b353249..00000000 --- a/src/ZoneCodeGenerator/Generating/Templates/Loading/Common.stg +++ /dev/null @@ -1,8 +0,0 @@ -delimiters "$", "$" - -// Loading common -LoaderClassName(asset) ::= "Loader_$asset.Type.Name$" - -CustomAction(action) ::= << -m_actions.$action.ActionName$($first(action.ParameterTypes):{ param | $TypeVarName(param)$}$$rest(action.ParameterTypes):{ param | , $TypeVarName(param)$}$); ->> \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/Templates/Loading/DynamicArray.stg b/src/ZoneCodeGenerator/Generating/Templates/Loading/DynamicArray.stg deleted file mode 100644 index 51bb61ba..00000000 --- a/src/ZoneCodeGenerator/Generating/Templates/Loading/DynamicArray.stg +++ /dev/null @@ -1,20 +0,0 @@ -delimiters "$", "$" - -// Everything related to loading a dynamic array - -LoadDynamicArray_Load(context, structure, member, reference) ::= <% -$if(member.StructureType && !member.StructureType.IsLeaf)$ - -$TypeVarName(member.Member.VariableType.Type)$ = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$;$\n$ -LoadArray_$member.Member.VariableType.Type.Name$(true, $PrintEvaluation(reference.DynamicArraySizeEvaluation)$); - -$else$ - -m_stream->Load<$TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$>($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$, $PrintEvaluation(reference.DynamicArraySizeEvaluation)$); - -$endif$ -%> - -LoadDynamicArray(context, structure, member, reference) ::= <% -$LoadDynamicArray_Load(context, structure, member, reference)$ -%> \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/Templates/Loading/Embedded.stg b/src/ZoneCodeGenerator/Generating/Templates/Loading/Embedded.stg deleted file mode 100644 index c3032eb2..00000000 --- a/src/ZoneCodeGenerator/Generating/Templates/Loading/Embedded.stg +++ /dev/null @@ -1,69 +0,0 @@ -delimiters "$", "$" - -// Everything related to loading an embedded reference - -ArrayCount(reference) ::= <% -$if(reference.HasDynamicArrayCount)$ -$PrintEvaluation(reference.DynamicArrayCountEvaluation)$ -$else$ -$reference.ArraySize$ -$endif$ -%> - -LoadEmbedded_Load(context, structure, member, reference) ::= << -$if(!member.IsLeaf)$ -$TypeVarName(member.Member.VariableType.Type)$ = &$TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$; -Load_$member.Member.VariableType.Type.Name$($if(member.Computations.IsAfterPartialLoad)$true$else$false$endif$);$\\$ -$if(member.StructureType.PostLoadAction)$ -$CustomAction(member.StructureType.PostLoadAction)$ -$endif$ -$elseif(member.Computations.IsAfterPartialLoad)$ -m_stream->Load<$TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$>(&$TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$);$\\$ -$endif$ ->> - -LoadEmbedded_TypeCheck(context, structure, member, reference) ::= <% -$if(member.IsScriptString)$ -$TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = UseScriptString($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$); -$else$ -$LoadEmbedded_Load(context, structure, member, reference)$ -$endif$ -%> - -LoadEmbedded_Block(context, structure, member, reference) ::= <% -$if(member.Computations.IsNotDefaultNormalBlock)$ -m_stream->PushBlock($member.Block.Name$);$\n$ -$endif$ - -$LoadEmbedded_TypeCheck(context, structure, member, reference)$ - -$if(member.Computations.IsNotDefaultNormalBlock)$ -$\n$m_stream->PopBlock(); -$endif$ -%> - -LoadEmbedded(context, structure, member, reference) ::= <% -$LoadEmbedded_Block(context, structure, member, reference)$ -%> - -LoadEmbeddedArray_Load(context, structure, member, reference) ::= << -$if(!member.IsLeaf)$ -$TypeVarName(member.Member.VariableType.Type)$ = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$; -LoadArray_$member.Member.VariableType.Type.Name$($if(member.Computations.IsAfterPartialLoad)$true$else$false$endif$, $ArrayCount(reference)$);$\\$ -$elseif(member.Computations.IsAfterPartialLoad)$ -m_stream->Load<$TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$>($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$, $ArrayCount(reference)$);$\\$ -$endif$ ->> - -LoadEmbeddedArray_TypeCheck(context, structure, member, reference) ::= <% -$if(member.IsScriptString)$ -varScriptString = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$;$\n$ -LoadScriptStringArray(false, $ArrayCount(reference)$); -$else$ -$LoadEmbeddedArray_Load(context, structure, member, reference)$ -$endif$ -%> - -LoadEmbeddedArray(context, structure, member, reference) ::= << -$LoadEmbeddedArray_TypeCheck(context, structure, member, reference)$ ->> \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/Templates/Loading/PointerArray.stg b/src/ZoneCodeGenerator/Generating/Templates/Loading/PointerArray.stg deleted file mode 100644 index 273f021b..00000000 --- a/src/ZoneCodeGenerator/Generating/Templates/Loading/PointerArray.stg +++ /dev/null @@ -1,101 +0,0 @@ -delimiters "$", "$" - -LoadPointerArray_Loading_Array(context, structure, member, reference) ::= <% -$TypePtrVarName(member.Member.VariableType.Type)$ = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$;$\n$ -LoadPtrArray_$SafeTypeName(member.Member.VariableType.Type)$(false, $reference.ArraySize$); -%> - -LoadPointerArray_Loading_Pointer_Inner(context, structure, member, reference) ::= <% -$TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = m_stream->Alloc<$TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$>(alignof($TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$)); -// $member.Member.VariableType.Alignment$$\n$ -$TypePtrVarName(member.Member.VariableType.Type)$ = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$;$\n$ -LoadPtrArray_$SafeTypeName(member.Member.VariableType.Type)$(true, $PrintEvaluation(reference.ArrayPointerCountEvaluation)$); -%> - -LoadPointerArray_Loading_Pointer(context, structure, member, reference) ::= << -if($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$) -{ - $if(member.IsReusable)$ - if($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ == PTR_FOLLOWING) - { - $LoadPointerArray_Loading_Pointer_Inner(context, structure, member, reference)$ - } - else - { - $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = m_stream->ConvertOffsetToPointer($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$); - } - $else$ - $LoadPointerArray_Loading_Pointer_Inner(context, structure, member, reference)$ - $endif$ -} ->> - -LoadPointerArray_Loading(context, structure, member, reference) ::= <% -$if(member.Computations.IsArray)$ -$LoadPointerArray_Loading_Array(context, structure, member, reference)$ -$else$ -$LoadPointerArray_Loading_Pointer(context, structure, member, reference)$ -$endif$ -%> - -LoadPointerArray_String_Array(context, structure, member, reference) ::= << -varXString = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$; -LoadXStringArray(false, $reference.ArraySize$); ->> - -LoadPointerArray_String_Pointer_Inner(context, structure, member, reference) ::= <% -$TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = m_stream->Alloc<$TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$>(alignof($TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$)); -// $member.Member.VariableType.Alignment$$\n$ -varXString = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$;$\n$ -LoadXStringArray(true, $PrintEvaluation(reference.ArrayPointerCountEvaluation)$); -%> - -LoadPointerArray_String_Pointer(context, structure, member, reference) ::= << -if($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$) -{ - $if(member.IsReusable)$ - if($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ == PTR_FOLLOWING) - { - $LoadPointerArray_String_Pointer_Inner(context, structure, member, reference)$ - } - else - { - $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = m_stream->ConvertOffsetToPointer($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$); - } - $else$ - $LoadPointerArray_String_Pointer_Inner(context, structure, member, reference)$ - $endif$ -} ->> - -LoadPointerArray_String(context, structure, member, reference) ::= <% -$if(reference.IsArray)$ -$LoadPointerArray_String_Array(context, structure, member, reference)$ -$else$ -$LoadPointerArray_String_Pointer(context, structure, member, reference)$ -$endif$ -%> - -LoadPointerArray_TypeCheck(context, structure, member, reference) ::= <% -$if(member.IsString)$ -$LoadPointerArray_String(context, structure, member, reference)$ -$else$ -$LoadPointerArray_Loading(context, structure, member, reference)$ -$endif$ -%> - -LoadPointerArray_Block(context, structure, member, reference) ::= <% -$if(member.Computations.IsNotDefaultNormalBlock)$ -m_stream->PushBlock($member.Block.Name$);$\n$ -$endif$ - -$LoadPointerArray_TypeCheck(context, structure, member, reference)$ - -$if(member.Computations.IsNotDefaultNormalBlock)$ -$\n$m_stream->PopBlock(); -$endif$ -%> - -LoadPointerArray(context, structure, member, reference) ::= <% -$LoadPointerArray_Block(context, structure, member, reference)$ -%> \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/Templates/Loading/SinglePointer.stg b/src/ZoneCodeGenerator/Generating/Templates/Loading/SinglePointer.stg deleted file mode 100644 index ba28e9c3..00000000 --- a/src/ZoneCodeGenerator/Generating/Templates/Loading/SinglePointer.stg +++ /dev/null @@ -1,115 +0,0 @@ -delimiters "$", "$" - -// Everything related to loading a pointer with a count that is statically 1 - -LoadSinglePointerInner(context, structure, member, reference) ::= << -$if(member.Computations.IsTempBlock)$ -$member.Member.VariableType.Type.FullName$* ptr = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$; -$endif$$\\$ - -$TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = m_stream->Alloc<$TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$>(alignof($TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$)); // $member.Member.VariableType.Type.Alignment$$\\$ -$\\$ -$\\$ -$if(member.Computations.IsTempBlock)$ - -$member.Member.VariableType.Type.FullName$** toInsert = nullptr; -if(ptr == PTR_INSERT) - toInsert = m_stream->InsertPointer<$member.Member.VariableType.Type.FullName$>(); - -$endif$$\\$ -$\\$ -$\\$ -$if(member.StructureType && !member.StructureType.IsLeaf && !member.Computations.IsRuntimeBlock)$ -$TypeVarName(member.Member.VariableType.Type)$ = $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$; -Load_$member.Member.VariableType.Type.Name$(true);$\\$ -$if(member.StructureType.PostLoadAction)$ - -$CustomAction(member.StructureType.PostLoadAction)$ -$endif$ -$else$ -m_stream->Load<$TypeDeclaration(member.Member.VariableType)$$PrintFollowingReferences(reference.FollowingReferences)$>($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$);$\\$ -$endif$$\\$ -$\\$ -$if(member.Computations.IsTempBlock)$ - -if(toInsert != nullptr) - *toInsert = $TypeVarName(structure.Type)$->$member.Member.Name$;$\\$ -$endif$ ->> - -LoadSinglePointerAsset(context, structure, member, reference) ::= << -$LoaderClassName(member.StructureType)$ loader(m_zone, m_stream); -AddDependency(loader.Load(&$TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$)); ->> - -LoadSinglePointer_Reuse(context, structure, member, reference) ::= << -$if(member.Computations.IsTempBlock)$ -if($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ == PTR_FOLLOWING || $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ == PTR_INSERT) -{ - $LoadSinglePointerInner(context, structure, member, reference)$ -} -else -{ - $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = m_stream->ConvertOffsetToAlias($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$); -}$\\$ -$else$ -if($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ == PTR_FOLLOWING) -{ - $LoadSinglePointerInner(context, structure, member, reference)$ -} -else -{ - $TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$ = m_stream->ConvertOffsetToPointer($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$); -}$\\$ -$endif$ ->> - -LoadSinglePointer_PointerCheck(context, structure, member, reference) ::= << -if ($TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$) -{ - $if(member.StructureType && member.StructureType.IsAsset)$ - $LoadSinglePointerAsset(context, structure, member, reference)$ - $else$ - $if(member.IsReusable)$ - $LoadSinglePointer_Reuse(context, structure, member, reference)$ - $else$ - $LoadSinglePointerInner(context, structure, member, reference)$ - $endif$ - $endif$ -} ->> - -LoadSinglePointer_String(context, structure, member, reference) ::= <% -$if(member.Member.VariableType.IsConst)$ -varXString = &$TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$;$\n$ -$else$ -varXString = const_cast(&$TypeVarName(structure.Type)$->$member.Member.Name$$PrintArrayIndices(reference)$);$\n$ -$endif$ -LoadXString(false); -%> - -LoadSinglePointer_TypeCheck(context, structure, member, reference) ::= <% -$if(member.IsString)$ -$LoadSinglePointer_String(context, structure, member, reference)$ -$elseif(member.IsScriptString)$ -// ScriptString $member.Member.Name$ -$else$ -$LoadSinglePointer_PointerCheck(context, structure, member, reference)$ -$endif$ -%> - -LoadSinglePointer_Block(context, structure, member, reference) ::= <% -$if(member.Computations.IsNotDefaultNormalBlock)$ -m_stream->PushBlock($member.Block.Name$);$\n$ -$endif$ - -$LoadSinglePointer_TypeCheck(context, structure, member, reference)$ - -$if(member.Computations.IsNotDefaultNormalBlock)$ -$\n$m_stream->PopBlock(); -$endif$ -%> - -LoadSinglePointer(context, structure, member, reference) ::= <% -$LoadSinglePointer_Block(context, structure, member, reference)$ -%> \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/Templates/ZoneLoad.stg b/src/ZoneCodeGenerator/Generating/Templates/ZoneLoad.stg deleted file mode 100644 index 7e48c99b..00000000 --- a/src/ZoneCodeGenerator/Generating/Templates/ZoneLoad.stg +++ /dev/null @@ -1,382 +0,0 @@ -delimiters "$", "$" - -import "Common.stg" - -import "Loading/Common.stg" -import "Loading/ArrayPointer.stg" -import "Loading/DynamicArray.stg" -import "Loading/Embedded.stg" -import "Loading/SinglePointer.stg" -import "Loading/PointerArray.stg" - -// Loading common -LoaderClassName(asset) ::= "Loader_$asset.Type.Name$" - -HeaderConstructor(context) ::= "$LoaderClassName(context.Asset)$(Zone* zone, IZoneInputStream* stream);" - -HeaderTempPtrLoadMethodDeclaration(structure) ::= "void LoadPtr_$structure.Type.Name$(bool atStreamStart);" -HeaderArrayLoadMethodDeclaration(type) ::= "void LoadArray_$SafeTypeName(type)$(bool atStreamStart, size_t count);" -HeaderPtrArrayLoadMethodDeclaration(type) ::= "void LoadPtrArray_$SafeTypeName(type)$(bool atStreamStart, size_t count);" -HeaderLoadMethodDeclaration(structure) ::= "void Load_$structure.Type.Name$(bool atStreamStart);" - -HeaderGetNameMethodDeclaration(asset) ::= "static std::string GetAssetName($asset.Type.FullName$* pAsset);" -HeaderAssetLoadMethodDeclaration(asset) ::= "void LoadAsset_$asset.Type.Name$($asset.Type.FullName$** pAsset);" -HeaderMainLoadMethodDeclaration(asset) ::= "XAssetInfo<$asset.Type.FullName$>* Load($asset.Type.FullName$** pAsset);" - -VariableDeclaration(type) ::= << -$type.FullName$* var$SafeTypeName(type)$; ->> - -PointerVariableDeclaration(type) ::= << -$type.FullName$** var$SafeTypeName(type)$Ptr; ->> - -// ======================= -// Header file entry point -// ======================= -header(context) ::= << -// ==================================================================== -// This file has been generated by ZoneCodeGenerator. -// Do not modify. -// Any changes will be discarded when regenerating. -// ==================================================================== - -#pragma once - -#include "Loading/AssetLoader.h" -#include "Game/$context.Game$/$context.Game$.h" -$if(context.HasActions)$ -#include "Game/$context.Game$/XAssets/$Lower(context.Asset.Type.Name)$/$Lower(context.Asset.Type.Name)$_actions.h" -$endif$ -#include - -namespace $context.Game$ -{ - class $LoaderClassName(context.Asset)$ final : public AssetLoader - { - XAssetInfo<$context.Asset.Type.FullName$>* m_asset_info; - $if(context.HasActions)$ - Actions_$context.Asset.Type.Name$ m_actions; - $endif$ - $VariableDeclaration(context.Asset.Type)$ - $PointerVariableDeclaration(context.Asset.Type)$ - - $context.UsedTypes:{type | $if(type.Information && !type.Information.Type.IsAnonymous && !type.Information.IsLeaf && !type.Information.IsAsset)$$VariableDeclaration(type.Type)$ - $endif$}$ - $context.UsedTypes:{type | $if(type.PointerArrayReferenceExists && !type.IsContextAsset)$$PointerVariableDeclaration(type.Type)$ - $endif$}$$\\$ - - $context.UsedTypes:{usedType | $if(usedType.PointerArrayReferenceExists)$$HeaderPtrArrayLoadMethodDeclaration(usedType.Type)$$\n$$endif$}$ - $context.UsedTypes:{usedType | $if(usedType.ArrayReferenceExists && usedType.Information && !usedType.Information.IsLeaf && usedType.NonRuntimeReferenceExists)$$HeaderArrayLoadMethodDeclaration(usedType.Type)$$\n$$endif$}$ - $context.UsedStructures:{usedStructure | $if(usedStructure.NonRuntimeReferenceExists && !usedStructure.Information.IsLeaf && !usedStructure.Information.IsAsset)$$HeaderLoadMethodDeclaration(usedStructure.Information)$$\n$$endif$}$ - $HeaderLoadMethodDeclaration(context.Asset)$ - $HeaderTempPtrLoadMethodDeclaration(context.Asset)$ - $HeaderAssetLoadMethodDeclaration(context.Asset)$ - - public: - $HeaderConstructor(context)$ - $HeaderMainLoadMethodDeclaration(context.Asset)$ - $HeaderGetNameMethodDeclaration(context.Asset)$ - }; -} ->> - -LoadMemberReference_Array(context, structure, member, reference) ::= << -$first(reference.ArrayEntries):{entry | $LoadMemberReference(context, structure, member, entry)$}$ -$rest(reference.ArrayEntries):{entry | - -$LoadMemberReference(context, structure, member, entry)$}$ ->> - -LoadMemberReference(context, structure, member, reference) ::= <% -$if(reference.IsDynamicArray)$ -$LoadDynamicArray(context, structure, member, reference)$ -$elseif(reference.IsSinglePointer)$ -$LoadSinglePointer(context, structure, member, reference)$ -$elseif(reference.IsArrayPointer)$ -$LoadArrayPointer(context, structure, member, reference)$ -$elseif(reference.IsPointerArray)$ -$LoadPointerArray(context, structure, member, reference)$ -$elseif(reference.IsArray && !reference.NextReference)$ -$LoadEmbeddedArray(context, structure, member, reference)$ -$elseif(!reference.Reference)$ -$LoadEmbedded(context, structure, member, reference)$ -$elseif(reference.IsArray)$ -$LoadMemberReference_Array(context, structure, member, reference)$ -$else$ -// LoadMemberReference failed @ $member.Member.Name$ -$endif$ -%> - -LoadMemberCondition_Struct(context, structure, member) ::= << - - -$if(member.Condition)$ -if($PrintEvaluation(member.Condition)$) -{ - $LoadMemberReference(context, structure, member, member.Computations.References)$ -}$\\$ -$else$ -$LoadMemberReference(context, structure, member, member.Computations.References)$$\\$ -$endif$ ->> - -LoadMemberCondition_Union(context, structure, member) ::= << -$if(member.Computations.IsFirstMember)$$\\$ -$if(member.Condition)$ - -if($PrintEvaluation(member.Condition)$) -{ - $LoadMemberReference(context, structure, member, member.Computations.References)$ -}$\\$ -$else$ - -$LoadMemberReference(context, structure, member, member.Computations.References)$$\\$ -$endif$$\\$ -$elseif(member.Computations.IsLastMember)$$\\$ -$if(member.Condition)$ -else if($PrintEvaluation(member.Condition)$) -{ - $LoadMemberReference(context, structure, member, member.Computations.References)$ -}$\\$ -$else$ -else -{ - $LoadMemberReference(context, structure, member, member.Computations.References)$ -}$\\$ -$endif$$\\$ -$else$$\\$ -$if(member.Condition)$ -else if($PrintEvaluation(member.Condition)$) -{ - $LoadMemberReference(context, structure, member, member.Computations.References)$ -}$\\$ -$else$$\\$ -#error Middle member of union must have condition ($member.Member.Name$) -$endif$$\\$ -$endif$ ->> - -LoadMemberCondition(context, structure, member) ::= <% -$if(structure.IsUnion)$ -$LoadMemberCondition_Union(context, structure, member)$ -$else$ -$LoadMemberCondition_Struct(context, structure, member)$ -$endif$ -%> - -LoadMemberIfNeedsTreatment(context, structure, member) ::= <% -$if(!member.Computations.ShouldIgnore)$ - -$if(member.IsString || member.IsScriptString)$ -$LoadMemberCondition(context, structure, member)$ -$elseif(member.Computations.ContainsNonEmbeddedReference)$ -$LoadMemberCondition(context, structure, member)$ -$elseif(member.StructureType && !member.StructureType.IsLeaf)$ -$LoadMemberCondition(context, structure, member)$ -$elseif(member.Computations.IsAfterPartialLoad)$ -$LoadMemberCondition(context, structure, member)$ -$endif$ - -$endif$ -%> - -LoadTempPtrMethod(context, structure) ::= << -void $LoaderClassName(context.Asset)$::LoadPtr_$structure.Type.Name$(const bool atStreamStart) -{ - assert($TypePtrVarName(structure.Type)$ != nullptr); - - if(atStreamStart) - m_stream->Load<$structure.Type.FullName$*>($TypePtrVarName(structure.Type)$); - - m_stream->PushBlock($context.DefaultTempBlock.Name$); - - if(*$TypePtrVarName(structure.Type)$ != nullptr) - { - if(*$TypePtrVarName(structure.Type)$ == PTR_FOLLOWING || *$TypePtrVarName(structure.Type)$ == PTR_INSERT) - { - $structure.Type.FullName$* ptr = *$TypePtrVarName(structure.Type)$; - *$TypePtrVarName(structure.Type)$ = m_stream->Alloc<$structure.Type.FullName$>(alignof($structure.Type.FullName$)); - - $structure.Type.FullName$** toInsert = nullptr; - if(ptr == PTR_INSERT) - toInsert = m_stream->InsertPointer<$structure.Type.FullName$>(); - - $if(!structure.IsLeaf)$ - $TypeVarName(structure.Type)$ = *$TypePtrVarName(structure.Type)$; - Load_$structure.Type.Name$(true); - $endif$ - - $if(structure.PostLoadAction)$ - $CustomAction(structure.PostLoadAction)$ - $endif$ - - $if(structure.IsAsset)$ - LoadAsset_$structure.Type.Name$($TypePtrVarName(structure.Type)$); - $endif$ - - if(toInsert != nullptr) - *toInsert = *$TypePtrVarName(structure.Type)$; - } - else - { - *$TypePtrVarName(structure.Type)$ = m_stream->ConvertOffsetToAlias(*$TypePtrVarName(structure.Type)$); - } - } - - m_stream->PopBlock(); -} ->> - -LoadArrayMethod(context, type, structure) ::= << -void $LoaderClassName(context.Asset)$::LoadArray_$type.Name$(const bool atStreamStart, const size_t count) -{ - assert($TypeVarName(type)$ != nullptr); - - if(atStreamStart) - m_stream->Load<$type.FullName$>($TypeVarName(type)$, count); - - $type.FullName$* var = $TypeVarName(type)$; - for(size_t index = 0; index < count; index++) - { - $if(!type.Members)$ - $TypeVarName(structure.Type)$ = var; - $else$ - $TypeVarName(type)$ = var; - $endif$ - Load_$structure.Type.Name$(false); - var++; - } -} ->> - -LoadMethod(context, structure) ::= << -void $LoaderClassName(context.Asset)$::Load_$structure.Type.Name$(const bool atStreamStart) -{ - assert($TypeVarName(structure.Type)$ != nullptr);$\\$ - - $if(!(structure.IsUnion && structure.Computations.DynamicMember))$ - - if(atStreamStart) - $if(!structure.Computations.DynamicMember)$ - m_stream->Load<$structure.Type.FullName$>($TypeVarName(structure.Type)$); // Size: $structure.Type.Size$$\\$ - $else$ - m_stream->LoadPartial<$structure.Type.FullName$>($TypeVarName(structure.Type)$, offsetof($structure.Type.FullName$, $structure.Computations.DynamicMember.Member.Name$));$\\$ - $endif$ - $else$ - assert(atStreamStart);$\\$ - $endif$ - $if(structure.Block)$ - - m_stream->PushBlock($structure.Block.Name$);$\\$ - $elseif(structure.IsAsset)$ - - m_stream->PushBlock($context.DefaultNormalBlock.Name$);$\\$ - $endif$ - $structure.OrderedMembers:{member | $LoadMemberIfNeedsTreatment(context, structure, member)$}$ - $if(structure.Block || structure.IsAsset)$ - - m_stream->PopBlock(); - $endif$ -} ->> - -VariableInitialization(type) ::= << -var$type.Name$ = nullptr; ->> - -PointerVariableInitialization(type) ::= << -var$type.Name$Ptr = nullptr; ->> - -ConstructorMethod(context) ::= << -$LoaderClassName(context.Asset)$::$LoaderClassName(context.Asset)$(Zone* zone, IZoneInputStream* stream) - : AssetLoader($context.Asset.AssetEnumEntry.Name$, zone, stream)$\\$ - $if(context.HasActions)$, m_actions(zone)$endif$ -{ - m_asset_info = nullptr; - $VariableInitialization(context.Asset.Type)$ - $PointerVariableInitialization(context.Asset.Type)$ - - $context.UsedTypes:{type | $if(type.Information && !type.Information.Type.IsAnonymous && !type.Information.IsLeaf && !type.Information.IsAsset)$$VariableInitialization(type.Type)$ - $endif$}$ - $context.UsedTypes:{type | $if(type.Information && type.PointerArrayReferenceExists && !type.IsContextAsset)$$PointerVariableInitialization(type.Type)$ - $endif$}$$\\$ -} ->> - -LoadAssetMethod(context, structure) ::= << -void $LoaderClassName(context.Asset)$::LoadAsset_$structure.Type.Name$($structure.Type.FullName$** pAsset) -{ - assert(pAsset != nullptr); - m_asset_info = reinterpret_cast*>(LinkAsset(GetAssetName(*pAsset), *pAsset)); - *pAsset = m_asset_info->Asset(); -} ->> - -MainLoadMethod(context) ::= << -XAssetInfo<$context.Asset.Type.FullName$>* $LoaderClassName(context.Asset)$::Load($context.Asset.Type.FullName$** pAsset) -{ - assert(pAsset != nullptr); - - m_asset_info = nullptr; - - $TypePtrVarName(context.Asset.Type)$ = pAsset; - LoadPtr_$context.Asset.Type.Name$(false); - - if(m_asset_info == nullptr && *pAsset != nullptr) - m_asset_info = reinterpret_cast*>(GetAssetInfo(GetAssetName(*pAsset))); - - return m_asset_info; -} ->> - -GetNameMethod(context) ::= << -std::string $LoaderClassName(context.Asset)$::GetAssetName($context.Asset.Type.FullName$* pAsset) -{ -$if(context.Asset.NameChain)$ - return pAsset->$first(context.Asset.NameChain):{member | $member.Member.Name$}$$rest(context.Asset.NameChain):{member | .$member.Member.Name$}$; -$else$ - return "$context.Asset.Type.Name$"; -$endif$ -} ->> - -IncludeHeaderOfOtherAsset(asset) ::= << -#include "../$Lower(asset.Type.Name)$/$Lower(asset.Type.Name)$_load_db.h" - ->> - -// ======================= -// Source file entry point -// ======================= -source(context) ::= << -// ==================================================================== -// This file has been generated by ZoneCodeGenerator. -// Do not modify. -// Any changes will be discarded when regenerating. -// ==================================================================== - -#include "$Lower(context.Asset.Type.Name)$_load_db.h" -#include - -// Referenced Assets: -$context.ReferencedAssets:IncludeHeaderOfOtherAsset()$ - -using namespace $context.Game$; - -$ConstructorMethod(context)$ - -$context.UsedTypes:{usedType | $if(usedType.PointerArrayReferenceExists)$$LoadPointerArrayMethod(context, usedType.Type, usedType.Information, usedType.PointerArrayReferenceIsReusable)$$\n$$\n$$endif$}$ -$context.UsedTypes:{usedType | $if(usedType.ArrayReferenceExists && usedType.Information && !usedType.Information.IsLeaf && usedType.NonRuntimeReferenceExists)$$LoadArrayMethod(context, usedType.Type, usedType.Information)$$\n$$\n$$endif$}$ -$context.UsedStructures:{usedStructure | $if(usedStructure.NonRuntimeReferenceExists && !usedStructure.Information.IsLeaf && !usedStructure.Information.IsAsset)$$LoadMethod(context, usedStructure.Information)$$\n$$\n$$endif$}$ -$LoadMethod(context, context.Asset)$ - -$LoadTempPtrMethod(context, context.Asset)$ - -$LoadAssetMethod(context, context.Asset)$ - -$MainLoadMethod(context)$ - -$GetNameMethod(context)$ ->> \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Generating/Templates/ZoneWrite.stg b/src/ZoneCodeGenerator/Generating/Templates/ZoneWrite.stg deleted file mode 100644 index f6dd71b2..00000000 --- a/src/ZoneCodeGenerator/Generating/Templates/ZoneWrite.stg +++ /dev/null @@ -1,38 +0,0 @@ -delimiters "$", "$" - -import "Common.stg" - -WriterClassName(asset) ::= "$asset.Type.Name; format=\"cap\"$ZoneWriter" - -// ======================= -// Header file entry point -// ======================= -header(context) ::= << -#pragma once - -namespace ZoneLoader -{ - class $WriterClassName(context.Asset)$ - { - public: - // TODO - } -} ->> - -IncludeHeaderOfOtherAsset(asset) ::= << -#include "../$asset.Type.Name$/$asset.Type.Name; format="lower"$_write_db.h" - ->> - -// ======================= -// Source file entry point -// ======================= -source(context) ::= << -#include "$context.Asset.Type.Name; format="lower"$_write_db.h" - -// Referenced Assets: -$context.ReferencedAssets:IncludeHeaderOfOtherAsset()$ - -// TODO ->> \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Interface/Arguments/ArgumentParser.cs b/src/ZoneCodeGenerator/Interface/Arguments/ArgumentParser.cs deleted file mode 100644 index bfa621d0..00000000 --- a/src/ZoneCodeGenerator/Interface/Arguments/ArgumentParser.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace ZoneCodeGenerator.Interface.Arguments -{ - class ArgumentParser - { - private readonly CommandLineOption[] options; - - private readonly List noOptionArgs; - private readonly Dictionary> optionArgs; - - public IReadOnlyList Arguments => noOptionArgs.AsReadOnly(); - - public ArgumentParser(CommandLineOption[] options) - { - this.options = options; - noOptionArgs = new List(); - optionArgs = new Dictionary>(); - } - - public bool ParseArguments(string[] args) - { - noOptionArgs.Clear(); - optionArgs.Clear(); - - for (var i = 0; i < args.Length; i++) - { - var arg = args[i]; - - if (arg.StartsWith("-")) - { - CommandLineOption matchedOption; - - if (arg.StartsWith("--")) - { - var longNameToFind = arg.Substring(2); - matchedOption = options.FirstOrDefault(option => longNameToFind.Equals(option.LongName)); - } - else - { - var shortNameToFind = arg.Substring(1); - matchedOption = options.FirstOrDefault(option => shortNameToFind.Equals(option.ShortName)); - } - - if (matchedOption == null) - { - Console.WriteLine($"Unknown option '{arg}'."); - return false; - } - - List parameters; - if (optionArgs.ContainsKey(matchedOption)) - { - if (!matchedOption.MultiUse) - { - Console.WriteLine($"Option '{arg}' already specified."); - return false; - } - - parameters = optionArgs[matchedOption]; - } - else - { - parameters = new List(); - optionArgs.Add(matchedOption, parameters); - } - - if (i + matchedOption.ParameterCount >= args.Length) - { - Console.WriteLine($"Not enough parameters for option '{arg}'."); - return false; - } - - for (var parameter = 0; parameter < matchedOption.ParameterCount; parameter++) - { - if (args[i + parameter + 1].StartsWith("-")) - { - Console.WriteLine($"Not enough parameters for option '{arg}'."); - return false; - } - - parameters.Add(args[i + parameter + 1]); - } - - i += matchedOption.ParameterCount; - } - else - { - noOptionArgs.Add(arg); - } - } - - return true; - } - - public bool IsOptionSpecified(CommandLineOption option) - { - return optionArgs.ContainsKey(option); - } - - public string GetValueForOption(CommandLineOption option) - { - return IsOptionSpecified(option) ? string.Join(" ", optionArgs[option]) : null; - } - - public IReadOnlyList GetParametersForOption(CommandLineOption option) - { - return IsOptionSpecified(option) ? optionArgs[option].AsReadOnly() : null; - } - } -} diff --git a/src/ZoneCodeGenerator/Interface/Arguments/CommandLineOption.cs b/src/ZoneCodeGenerator/Interface/Arguments/CommandLineOption.cs deleted file mode 100644 index 53a04be4..00000000 --- a/src/ZoneCodeGenerator/Interface/Arguments/CommandLineOption.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Collections.Generic; - -namespace ZoneCodeGenerator.Interface.Arguments -{ - class CommandLineOption - { - public string ShortName { get; private set; } - public string LongName { get; private set; } - public string Description { get; private set; } - public string Category { get; private set; } - public bool MultiUse { get; private set; } - - private readonly List parameters; - public IReadOnlyList Parameters => parameters.AsReadOnly(); - public int ParameterCount => parameters.Count; - - private CommandLineOption() - { - ShortName = null; - LongName = null; - Description = ""; - Category = ""; - MultiUse = false; - parameters = new List(); - } - - public class CommandLineOptionBuilder - { - private readonly CommandLineOption option; - - private CommandLineOptionBuilder() - { - option = new CommandLineOption(); - } - - public static CommandLineOptionBuilder Create() - { - return new CommandLineOptionBuilder(); - } - - public CommandLineOptionBuilder WithShortName(string shortName) - { - option.ShortName = shortName; - return this; - } - - public CommandLineOptionBuilder WithLongName(string longName) - { - option.LongName = longName; - return this; - } - - public CommandLineOptionBuilder WithDescription(string description) - { - option.Description = description; - return this; - } - - public CommandLineOptionBuilder WithCategory(string category) - { - option.Category = category; - return this; - } - - public CommandLineOptionBuilder WithParameter(string argumentName) - { - option.parameters.Add(argumentName); - return this; - } - - public CommandLineOptionBuilder Reusable() - { - option.MultiUse = true; - return this; - } - - public CommandLineOption Build() - { - return option; - } - } - } -} diff --git a/src/ZoneCodeGenerator/Interface/Arguments/UsageInformation.cs b/src/ZoneCodeGenerator/Interface/Arguments/UsageInformation.cs deleted file mode 100644 index 8cacb0e8..00000000 --- a/src/ZoneCodeGenerator/Interface/Arguments/UsageInformation.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System; -using System.Linq; -using System.Text; - -namespace ZoneCodeGenerator.Interface.Arguments -{ - static class UsageInformation - { - public static string FromCommandlineOptions(CommandLineOption[] options) - { - var usageInformation = new StringBuilder(); - usageInformation.AppendLine("Usage:"); - usageInformation.AppendLine(); - - var longestShortName = 0; - var longestLongName = 0; - var longestArgumentLength = 0; - - foreach (var option in CommandLineOptions.ALL_OPTIONS) - { - if (option.ShortName != null && longestShortName < option.ShortName.Length) - longestShortName = option.ShortName.Length; - - if (option.LongName != null && longestLongName < option.LongName.Length) - longestLongName = option.LongName.Length; - - var argumentLength = GetOptionArgumentLength(option); - if (longestArgumentLength < argumentLength) - longestArgumentLength = argumentLength; - } - - var categories = CommandLineOptions.ALL_OPTIONS - .Select(option => option.Category) - .Distinct(); - - var firstCategory = true; - foreach (var category in categories) - { - var optionsOfCategory = CommandLineOptions.ALL_OPTIONS - .Where(option => category.Equals(option.Category)); - - if(!firstCategory) - usageInformation.AppendLine(); - - if (!string.IsNullOrEmpty(category)) - { - usageInformation.AppendLine($"== {category} =="); - } - - foreach (var option in optionsOfCategory) - { - if (option.ShortName != null) - { - usageInformation.Append($"-{option.ShortName}"); - usageInformation.Append(' ', longestShortName - option.ShortName.Length); - - if (option.LongName != null) - usageInformation.Append(", "); - else - usageInformation.Append(' ', 2); - } - else - { - usageInformation.Append(' ', longestShortName + 1 + 2); - } - - if (option.LongName != null) - { - usageInformation.Append($"--{option.LongName}"); - usageInformation.Append(' ', longestLongName - option.LongName.Length); - } - else - { - usageInformation.Append(' ', longestLongName + 2); - } - - usageInformation.Append(' '); - - var argumentLength = GetOptionArgumentLength(option); - for(var i = 0; i < option.ParameterCount; i++) - { - if (i != 0) - usageInformation.Append(' '); - - usageInformation.Append($"<{option.Parameters[i]}>"); - } - - usageInformation.Append(' ', longestArgumentLength - argumentLength + 1); - - usageInformation.Append(option.Description); - - usageInformation.AppendLine(); - } - - firstCategory = false; - } - - return usageInformation.ToString(); - } - - private static int GetOptionArgumentLength(CommandLineOption option) - { - return option.ParameterCount * 2 // < and > - + option.Parameters.Select(s => s.Length).Sum() // Length of the argument name - + Math.Max(0, option.ParameterCount - 1); // One space between each argument - } - } -} diff --git a/src/ZoneCodeGenerator/Interface/CUI.cs b/src/ZoneCodeGenerator/Interface/CUI.cs deleted file mode 100644 index 286ddb44..00000000 --- a/src/ZoneCodeGenerator/Interface/CUI.cs +++ /dev/null @@ -1,112 +0,0 @@ -using System; -using System.Linq; -using ZoneCodeGenerator.Generating; -using ZoneCodeGenerator.Interface.Arguments; -using ZoneCodeGenerator.Parsing.C_Header; -using ZoneCodeGenerator.Parsing.CommandFile; - -namespace ZoneCodeGenerator.Interface -{ - class CUI - { - public bool Start(string[] args) - { - var argumentParser = new ArgumentParser(CommandLineOptions.ALL_OPTIONS); - - if (args.Length == 0 || !argumentParser.ParseArguments(args)) - { - PrintUsage(); - return false; - } - - if (argumentParser.IsOptionSpecified(CommandLineOptions.OPTION_HELP)) - { - PrintUsage(); - return true; - } - - var session = new CUISession - { - Verbose = argumentParser.IsOptionSpecified(CommandLineOptions.OPTION_VERBOSE) - }; - - if (argumentParser.IsOptionSpecified(CommandLineOptions.OPTION_OUTPUT_FOLDER)) - { - session.GeneratorOutputPath = argumentParser.GetValueForOption(CommandLineOptions.OPTION_OUTPUT_FOLDER); - } - - if (argumentParser.IsOptionSpecified(CommandLineOptions.OPTION_CREATE)) - { - session.SourceFilePath = argumentParser.GetValueForOption(CommandLineOptions.OPTION_CREATE); - session.Repository = HeaderReader.ReadFile(session.SourceFilePath, session.Verbose); - - if (session.Repository == null) - { - Console.WriteLine($"Creating a database from header file '{argumentParser.GetValueForOption(CommandLineOptions.OPTION_CREATE)}' failed."); - return false; - } - } - else - { - Console.WriteLine("Parsing a c header is needed to perform any other action."); - return false; - } - - if (argumentParser.IsOptionSpecified(CommandLineOptions.OPTION_EDITING_COMMANDS)) - { - if (!CommandFileReader.ReadFile(argumentParser.GetValueForOption(CommandLineOptions.OPTION_EDITING_COMMANDS), session, session.Verbose)) - { - return false; - } - } - - if (argumentParser.IsOptionSpecified(CommandLineOptions.OPTION_PRINT)) - { - var printer = new PrettyPrinter(session.Repository); - printer.PrintAll(); - } - - if (argumentParser.IsOptionSpecified(CommandLineOptions.OPTION_GENERATE)) - { - var generationArgs = argumentParser.GetParametersForOption(CommandLineOptions.OPTION_GENERATE); - for (var i = 0; i < generationArgs.Count; i += CommandLineOptions.OPTION_GENERATE.ParameterCount) - { - var assetName = generationArgs[i]; - var preset = generationArgs[i + 1]; - - var assets = session.Repository.GetAllStructureInformation() - .Where(inf => inf.IsAsset); - - if (!assetName.Equals("*")) - assets = assets.Where(inf => - inf.Type.FullName.Equals(assetName, StringComparison.CurrentCultureIgnoreCase)); - - if (!assets.Any()) - { - Console.WriteLine($"Could not find asset '{assetName}'."); - continue; - } - - foreach (var asset in assets) - { - if (CodeGenerator.GenerateCodeForPreset(preset, asset, session)) - { - Console.WriteLine($"Successfully generated code for asset '{asset.Type.FullName}' with preset '{preset}'"); - } - else - { - Console.WriteLine($"Could not generate code for asset '{asset.Type.FullName}' with preset '{preset}'"); - } - } - } - } - - return true; - } - - private static void PrintUsage() - { - Console.WriteLine(UsageInformation.FromCommandlineOptions(CommandLineOptions.ALL_OPTIONS)); - } - } -} diff --git a/src/ZoneCodeGenerator/Interface/CUISession.cs b/src/ZoneCodeGenerator/Interface/CUISession.cs deleted file mode 100644 index 3addefbd..00000000 --- a/src/ZoneCodeGenerator/Interface/CUISession.cs +++ /dev/null @@ -1,20 +0,0 @@ -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Interface -{ - class CUISession - { - public string Game { get; set; } - public IDataRepository Repository { get; set; } - public string GeneratorOutputPath { get; set; } - public string SourceFilePath { get; set; } - public bool Verbose { get; set; } - - public CUISession() - { - Repository = null; - GeneratorOutputPath = "."; - Verbose = false; - } - } -} diff --git a/src/ZoneCodeGenerator/Interface/CommandLineOptions.cs b/src/ZoneCodeGenerator/Interface/CommandLineOptions.cs deleted file mode 100644 index 44d5b09b..00000000 --- a/src/ZoneCodeGenerator/Interface/CommandLineOptions.cs +++ /dev/null @@ -1,98 +0,0 @@ -using ZoneCodeGenerator.Generating; -using ZoneCodeGenerator.Interface.Arguments; - -namespace ZoneCodeGenerator.Interface -{ - static class CommandLineOptions - { - // ------ - // GENERAL - // ------ - - public static readonly CommandLineOption OPTION_HELP = CommandLineOption.CommandLineOptionBuilder.Create() - .WithShortName("?") - .WithLongName("help") - .WithDescription("Show usage.") - .Build(); - - public static readonly CommandLineOption OPTION_VERBOSE = CommandLineOption.CommandLineOptionBuilder.Create() - .WithShortName("v") - .WithLongName("verbose") - .WithDescription("Gives a lot and detailed output.") - .Build(); - - // ------ - // INPUT - // ------ - private const string CategoryInput = "Input"; - - public static readonly CommandLineOption OPTION_CREATE = CommandLineOption.CommandLineOptionBuilder.Create() - .WithShortName("h") - .WithLongName("header") - .WithDescription("Create a new database from the specified header file.") - .WithCategory(CategoryInput) - .WithParameter("headerFile") - .Build(); - - // ------ - // EDITING - // ------ - private const string CategoryEditing = "Editing"; - - public static readonly CommandLineOption OPTION_EDITING_COMMANDS = CommandLineOption.CommandLineOptionBuilder.Create() - .WithShortName("e") - .WithLongName("editing-commands") - .WithDescription("Specifies the editing command file. Defaults to stdin.") - .WithCategory(CategoryEditing) - .WithParameter("commandFile") - .Build(); - - // ------ - // OUTPUT - // ------ - private const string CategoryOutput = "Output"; - - public static readonly CommandLineOption OPTION_OUTPUT_FOLDER = CommandLineOption.CommandLineOptionBuilder.Create() - .WithShortName("o") - .WithLongName("output") - .WithDescription("Specify the folder to save the generate code files to. Defaults to the current directory.") - .WithCategory(CategoryOutput) - .WithParameter("outputPath") - .Build(); - - public static readonly CommandLineOption OPTION_PRINT = CommandLineOption.CommandLineOptionBuilder.Create() - .WithShortName("p") - .WithLongName("print") - .WithDescription("Print the loaded data.") - .WithCategory(CategoryOutput) - .Build(); - - public static readonly CommandLineOption OPTION_GENERATE = CommandLineOption.CommandLineOptionBuilder.Create() - .WithShortName("g") - .WithLongName("generate") - .WithDescription($"Generates a specified asset/preset combination. Can be used multiple times. Available presets: {string.Join(", ", CodeGenerator.Presets)}") - .WithCategory(CategoryOutput) - .WithParameter("assetName") - .WithParameter("preset") - .Reusable() - .Build(); - - public static readonly CommandLineOption[] ALL_OPTIONS = - { - // GENERAL - OPTION_HELP, - OPTION_VERBOSE, - - // INPUT - OPTION_CREATE, - - // EDITING - OPTION_EDITING_COMMANDS, - - // OUTPUT - OPTION_OUTPUT_FOLDER, - OPTION_PRINT, - OPTION_GENERATE, - }; - } -} diff --git a/src/ZoneCodeGenerator/Interface/PrettyPrinter.cs b/src/ZoneCodeGenerator/Interface/PrettyPrinter.cs deleted file mode 100644 index f18a4ba9..00000000 --- a/src/ZoneCodeGenerator/Interface/PrettyPrinter.cs +++ /dev/null @@ -1,315 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Interface -{ - class PrettyPrinter - { - private readonly IDataRepository dataRepository; - - public PrettyPrinter(IDataRepository dataRepository) - { - this.dataRepository = dataRepository; - } - - public void PrintEnums() - { - var allEnums = dataRepository.GetAllEnums(); - var dataTypeEnums = allEnums.ToList(); - - Console.WriteLine($"{dataTypeEnums.Count} enums:"); - - foreach(var _enum in dataTypeEnums) - { - Console.WriteLine($" Name: {_enum.FullName}"); - Console.WriteLine($" Alignment: {_enum.Alignment}"); - Console.WriteLine($" Size: {_enum.Size}"); - - foreach(var member in _enum.Members) - { - Console.WriteLine($" {member.Name} = {member.Value}"); - } - - Console.WriteLine(); - } - } - - private static void PrintVariablePointerToArray(Variable variable) - { - var arraySize = new List(); - var pointerDepth = 0; - var referenceOffset = 0; - - for (; referenceOffset < variable.VariableType.References.Count; referenceOffset++) - { - if (!(variable.VariableType.References[referenceOffset] is ReferenceTypePointer)) - break; - - pointerDepth++; - } - - for (; referenceOffset < variable.VariableType.References.Count; referenceOffset++) - { - if (!(variable.VariableType.References[referenceOffset] is ReferenceTypeArray array)) - throw new Exception("Expected the rest of the references to be array references"); - - arraySize.Add(array.ArraySize); - } - - var memberBuilder = new StringBuilder(); - memberBuilder.Append(" "); - memberBuilder.Append(variable.VariableType.Type.FullName); - memberBuilder.Append('('); - memberBuilder.Append('*', pointerDepth); - memberBuilder.Append(variable.Name); - memberBuilder.Append(')'); - - foreach (var array in arraySize) - { - memberBuilder.Append('['); - memberBuilder.Append(array); - memberBuilder.Append(']'); - } - - Console.WriteLine(memberBuilder.ToString()); - } - - private static void PrintVariableArrayOfPointers(Variable variable) - { - var arraySize = new List(); - var pointerDepth = 0; - var referenceOffset = 0; - - for (; referenceOffset < variable.VariableType.References.Count; referenceOffset++) - { - if (!(variable.VariableType.References[referenceOffset] is ReferenceTypeArray array)) - break; - - arraySize.Add(array.ArraySize); - } - - for (; referenceOffset < variable.VariableType.References.Count; referenceOffset++) - { - if (!(variable.VariableType.References[referenceOffset] is ReferenceTypePointer)) - throw new Exception("Expected the rest of the references to be pointer references"); - - pointerDepth++; - } - - var memberBuilder = new StringBuilder(); - memberBuilder.Append(" "); - memberBuilder.Append(variable.VariableType.Type.FullName); - memberBuilder.Append('*', pointerDepth); - memberBuilder.Append(" "); - memberBuilder.Append(variable.Name); - - foreach (var array in arraySize) - { - memberBuilder.Append('['); - memberBuilder.Append(array); - memberBuilder.Append(']'); - } - - Console.WriteLine(memberBuilder.ToString()); - } - - private static void PrintVariable(Variable variable) - { - if (variable.VariableType.References.Count == 0) - { - Console.WriteLine($" {variable.VariableType.Type.FullName} {variable.Name}"); - } - else - { - if (variable.VariableType.References[0] is ReferenceTypePointer && - variable.VariableType.References.OfType().Any()) - { - PrintVariablePointerToArray(variable); - } - else - { - PrintVariableArrayOfPointers(variable); - } - } - } - - public void PrintStructs() - { - var allStructs = dataRepository.GetAllStructs(); - var dataTypeStructs = allStructs.ToList(); - - Console.WriteLine($"{dataTypeStructs.Count} structs:"); - - foreach(var _struct in dataTypeStructs) - { - Console.WriteLine($" Name: {_struct.FullName}"); - Console.WriteLine($" Alignment: {_struct.Alignment}"); - Console.WriteLine($" Size: {_struct.Size}"); - - foreach(var member in _struct.Members) - PrintVariable(member); - - Console.WriteLine(); - } - - } - - public void PrintUnions() - { - var allUnions = dataRepository.GetAllUnions(); - var dataTypeUnions = allUnions.ToList(); - - Console.WriteLine($"{dataTypeUnions.Count} unions:"); - - foreach(var union in dataTypeUnions) - { - Console.WriteLine($" Name: {union.FullName}"); - Console.WriteLine($" Alignment: {union.Alignment}"); - Console.WriteLine($" Size: {union.Size}"); - - foreach(var member in union.Members) - PrintVariable(member); - - Console.WriteLine(); - } - } - - private static void PrintTypedefPointerToArray(DataTypeTypedef typedef) - { - var arraySize = new List(); - var pointerDepth = 0; - var referenceOffset = 0; - - for (; referenceOffset < typedef.TypeDefinition.References.Count; referenceOffset++) - { - if (!(typedef.TypeDefinition.References[referenceOffset] is ReferenceTypePointer)) - break; - - pointerDepth++; - } - - for (; referenceOffset < typedef.TypeDefinition.References.Count; referenceOffset++) - { - if (!(typedef.TypeDefinition.References[referenceOffset] is ReferenceTypeArray array)) - throw new Exception("Expected the rest of the references to be array references"); - - arraySize.Add(array.ArraySize); - } - - var memberBuilder = new StringBuilder(); - memberBuilder.Append(" "); - memberBuilder.Append(typedef.TypeDefinition.Type.FullName); - memberBuilder.Append('('); - memberBuilder.Append('*', pointerDepth); - memberBuilder.Append(')'); - - foreach (var array in arraySize) - { - memberBuilder.Append('['); - memberBuilder.Append(array); - memberBuilder.Append(']'); - } - - Console.WriteLine(memberBuilder.ToString()); - } - - private static void PrintTypedefArrayOfPointers(DataTypeTypedef typedef) - { - var arraySize = new List(); - var pointerDepth = 0; - var referenceOffset = 0; - - for (; referenceOffset < typedef.TypeDefinition.References.Count; referenceOffset++) - { - if (!(typedef.TypeDefinition.References[referenceOffset] is ReferenceTypeArray array)) - break; - - arraySize.Add(array.ArraySize); - } - - for (; referenceOffset < typedef.TypeDefinition.References.Count; referenceOffset++) - { - if (!(typedef.TypeDefinition.References[referenceOffset] is ReferenceTypePointer)) - throw new Exception("Expected the rest of the references to be pointer references"); - - pointerDepth++; - } - - var memberBuilder = new StringBuilder(); - memberBuilder.Append(" "); - memberBuilder.Append(typedef.TypeDefinition.Type.FullName); - memberBuilder.Append('*', pointerDepth); - - foreach (var array in arraySize) - { - memberBuilder.Append('['); - memberBuilder.Append(array); - memberBuilder.Append(']'); - } - - Console.WriteLine(memberBuilder.ToString()); - } - - public void PrintTypedefs() - { - var allTypedefs = dataRepository.GetAllTypedefs(); - var dataTypeTypedefs = allTypedefs.ToList(); - - Console.WriteLine($"{dataTypeTypedefs.Count} typedefs:"); - - foreach (var typeDef in dataTypeTypedefs) - { - Console.WriteLine($" Name: {typeDef.FullName}"); - Console.WriteLine($" Alignment: {typeDef.Alignment}"); - Console.WriteLine($" Size: {typeDef.Size}"); - - if (typeDef.TypeDefinition.References.Count == 0) - { - Console.WriteLine($" {typeDef.TypeDefinition.Type.FullName}"); - } - else - { - if (typeDef.TypeDefinition.References[0] is ReferenceTypePointer && - typeDef.TypeDefinition.References.OfType().Any()) - { - PrintTypedefPointerToArray(typeDef); - } - else - { - PrintTypedefArrayOfPointers(typeDef); - } - } - - Console.WriteLine(); - } - - } - - public void PrintAll() - { - PrintEnums(); - - Console.WriteLine(); - Console.WriteLine("=========================================================================================================="); - Console.WriteLine(); - - PrintStructs(); - - Console.WriteLine(); - Console.WriteLine("=========================================================================================================="); - Console.WriteLine(); - - PrintUnions(); - - Console.WriteLine(); - Console.WriteLine("=========================================================================================================="); - Console.WriteLine(); - - PrintTypedefs(); - } - } -} diff --git a/src/ZoneCodeGenerator/LoadingException.cs b/src/ZoneCodeGenerator/LoadingException.cs deleted file mode 100644 index 67ffa365..00000000 --- a/src/ZoneCodeGenerator/LoadingException.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace ZoneCodeGenerator -{ - class LoadingException : Exception - { - public LoadingException(string message) : base(message) - { - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/BlockType.cs b/src/ZoneCodeGenerator/Parsing/C_Header/BlockType.cs deleted file mode 100644 index 5dfcf4de..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/BlockType.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ZoneCodeGenerator.Parsing.C_Header -{ - enum BlockType - { - None, - Enum, - Namespace, - Struct, - Union - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/Block.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/Block.cs deleted file mode 100644 index 29a9fbfa..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/Block.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.C_Header.Blocks -{ - abstract class Block - { - protected readonly IHeaderParserState State; - public BlockType Type { get; } - - protected Block(IHeaderParserState headerParserState, BlockType type) - { - State = headerParserState; - Type = type; - } - - public abstract IEnumerable> GetAvailableTests(); - - public abstract void OnOpen(); - - public abstract void OnClose(); - - public abstract void OnChildBlockClose(Block childBlock); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockEnum.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockEnum.cs deleted file mode 100644 index f1cca5d8..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockEnum.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System; -using System.Collections.Generic; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.C_Header.Blocks -{ - class BlockEnum : Block, INameAssignable, IVariableBlock - { - private readonly ITokenTest[] tests = - { - new TestEnumMember(), - new TestCloseBlock(true) - }; - - public string Name { get; } - public string AssignedName { get; private set; } - public string Namespace { get; private set; } - public DataTypeBaseType ParentType { get; } - public bool IsTypedef { get; } - public List Members { get; } - - private DataTypeEnum _enum; - - public BlockEnum(IHeaderParserState headerParserState, string name, DataTypeBaseType parentType, bool isTypedef) : base(headerParserState, BlockType.Enum) - { - Name = name; - ParentType = parentType; - IsTypedef = isTypedef; - Members = new List(); - } - - public override IEnumerable> GetAvailableTests() - { - return tests; - } - - public override void OnOpen() - { - Namespace = State.CurrentNamespace.ToString(); - - State.CurrentNamespace.Push(Name); - } - - public override void OnClose() - { - var poppedNamespaceName = State.CurrentNamespace.Pop(); - - if (!Name.Equals(poppedNamespaceName)) - throw new Exception($"Popped namespace '{poppedNamespaceName}' does not equal name of union block '{Name}'"); - - _enum = new DataTypeEnum(Namespace, Name, ParentType); - - _enum.Members.AddRange(Members); - - State.AddDataType(_enum); - - if (IsTypedef) - { - var typeDeclaration = new TypeDeclaration(_enum, new List()); - var typedef = new DataTypeTypedef(Namespace, AssignedName, typeDeclaration); - - State.AddDataType(typedef); - } - } - - public override void OnChildBlockClose(Block childBlock) - { - - } - - public void AssignName(string nameAssignment) - { - AssignedName = nameAssignment; - } - - public virtual void AddMember(EnumMember enumMember) - { - Members.Add(enumMember); - } - - public virtual EnumMember FindMember(string enumMemberName) - { - return Members.Find(member => member.Name.Equals(enumMemberName)); - } - - public virtual long GetNextEnumValue() - { - var nextValue = 0L; - - if (Members.Count > 0) - { - nextValue = Members[Members.Count - 1].Value + 1; - } - - return nextValue; - } - - public bool DefinesVariable() - { - return !IsTypedef && !string.IsNullOrEmpty(AssignedName) && _enum != null; - } - - public Variable GetDefinedVariable() - { - if (!DefinesVariable()) - return null; - - var typeDeclaration = new TypeDeclaration(_enum, new List()); - return new Variable(AssignedName, typeDeclaration); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockNamespace.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockNamespace.cs deleted file mode 100644 index a4b81527..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockNamespace.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.C_Header.Blocks -{ - class BlockNamespace : Block - { - private readonly ITokenTest[] tests = - { - new TestNamespace(), - new TestEnum(), - new TestStruct(), - new TestUnion(), - new TestTypedef(), - new TestForwardDecl(), - new TestCloseBlock() - }; - - public string Name { get; } - - public BlockNamespace(IHeaderParserState headerParserState, string namespaceName) : base(headerParserState, BlockType.Namespace) - { - Name = namespaceName; - } - - public override IEnumerable> GetAvailableTests() - { - return tests; - } - - public override void OnOpen() - { - State.CurrentNamespace.Push(Name); - } - - public override void OnClose() - { - var poppedNamespaceName = State.CurrentNamespace.Pop(); - - if (!Name.Equals(poppedNamespaceName)) - throw new Exception($"Popped namespace '{poppedNamespaceName}' does not equal name of namespace block '{Name}'"); - } - - public override void OnChildBlockClose(Block childBlock) - { - // Do nothing - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockNone.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockNone.cs deleted file mode 100644 index 89274588..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockNone.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Collections.Generic; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.C_Header.Blocks -{ - class BlockNone : Block - { - private readonly ITokenTest[] tests = - { - new TestNamespace(), - new TestEnum(), - new TestStruct(), - new TestUnion(), - new TestTypedef(), - new TestForwardDecl() - }; - - public BlockNone(IHeaderParserState headerParserState) : base(headerParserState, BlockType.None) - { - - } - - public override IEnumerable> GetAvailableTests() - { - return tests; - } - - public override void OnOpen() - { - // Do nothing - } - - public override void OnClose() - { - // Do nothing - } - - public override void OnChildBlockClose(Block childBlock) - { - // Do nothing - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockStruct.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockStruct.cs deleted file mode 100644 index 112a61db..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockStruct.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.Collections.Generic; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Utils; - -namespace ZoneCodeGenerator.Parsing.C_Header.Blocks -{ - class BlockStruct : Block, INameAssignable, IVariableHolder, IVariableBlock - { - private readonly ITokenTest[] tests = - { - new TestStruct(), - new TestEnum(), - new TestUnion(), - new TestVariable(), - new TestCloseBlock(true) - }; - - public string Name { get; } - public bool IsAnonymous { get; } - - public string AssignedName { get; private set; } - public string Namespace { get; private set; } - public bool IsTypedef { get; } - public int? CustomAlignment { get; set; } - public int Pack { get; private set; } - public List Variables { get; } - - private DataTypeStruct _struct; - private DataTypeTypedef typedef; - - public BlockStruct(IHeaderParserState headerParserState, string name, bool isTypedef) : base(headerParserState, BlockType.Struct) - { - if (!string.IsNullOrEmpty(name)) - { - Name = name; - IsAnonymous = false; - } - else - { - Name = RandomName.GenerateName(); - IsAnonymous = true; - } - - IsTypedef = isTypedef; - Variables = new List(); - AssignedName = ""; - _struct = null; - typedef = null; - } - - public override IEnumerable> GetAvailableTests() - { - return tests; - } - - public override void OnOpen() - { - Pack = State.CurrentPack; - - Namespace = State.CurrentNamespace.ToString(); - - State.CurrentNamespace.Push(Name); - - State.AddForwardDeclaration(new ForwardDeclaration(Namespace, Name, DataTypeType.Struct)); - } - - public override void OnClose() - { - var poppedNamespaceName = State.CurrentNamespace.Pop(); - - if (!Name.Equals(poppedNamespaceName)) - throw new Exception($"Popped namespace '{poppedNamespaceName}' does not equal name of struct block '{Name}'"); - - _struct = new DataTypeStruct(Namespace, Name, Pack) - { - AlignmentOverride = CustomAlignment, - IsAnonymous = IsAnonymous - }; - - _struct.Members.AddRange(Variables); - - State.AddDataType(_struct); - - if (IsTypedef) - { - var typeDeclaration = new TypeDeclaration(_struct, new List()); - typedef = new DataTypeTypedef(Namespace, AssignedName, typeDeclaration); - - State.AddDataType(typedef); - } - } - - public override void OnChildBlockClose(Block childBlock) - { - if (childBlock is IVariableBlock variableBlock) - { - AddVariable(variableBlock.GetDefinedVariable()); - } - } - - public void AssignName(string nameAssignment) - { - AssignedName = nameAssignment; - } - - public void AddVariable(Variable variable) - { - Variables.Add(variable); - } - - public Variable GetDefinedVariable() - { - var name = ""; - DataType dataType = _struct; - - if (!IsTypedef) - name = AssignedName; - else - dataType = typedef; - - var typeDeclaration = new TypeDeclaration(dataType, new List()); - return new Variable(name, typeDeclaration); - } - - public void Inherit(DataTypeStruct parent) - { - foreach(var variable in parent.Members) - AddVariable(variable); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockUnion.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockUnion.cs deleted file mode 100644 index 1b60ff10..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/BlockUnion.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.Collections.Generic; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Utils; - -namespace ZoneCodeGenerator.Parsing.C_Header.Blocks -{ - class BlockUnion : Block, INameAssignable, IVariableHolder, IVariableBlock - { - private readonly ITokenTest[] tests = - { - new TestStruct(), - new TestEnum(), - new TestUnion(), - new TestVariable(), - new TestCloseBlock(true) - }; - - public string Name { get; } - public bool IsAnonymous { get; } - - public string AssignedName { get; private set; } - public string Namespace { get; private set; } - public bool IsTypedef { get; } - public int? CustomAlignment { get; set; } - public int Pack { get; private set; } - public List Variables { get; } - - private DataTypeUnion union; - private DataTypeTypedef typedef; - - public BlockUnion(IHeaderParserState headerParserState, string name, bool isTypedef) : base(headerParserState, BlockType.Union) - { - if (!string.IsNullOrEmpty(name)) - { - Name = name; - IsAnonymous = false; - } - else - { - Name = RandomName.GenerateName(); - IsAnonymous = true; - } - - IsTypedef = isTypedef; - Variables = new List(); - CustomAlignment = null; - AssignedName = ""; - union = null; - typedef = null; - } - - public override IEnumerable> GetAvailableTests() - { - return tests; - } - - public override void OnOpen() - { - Namespace = State.CurrentNamespace.ToString(); - Pack = State.CurrentPack; - - State.CurrentNamespace.Push(Name); - - State.AddForwardDeclaration(new ForwardDeclaration(Namespace, Name, DataTypeType.Union)); - } - - public override void OnClose() - { - var poppedNamespaceName = State.CurrentNamespace.Pop(); - - if (!Name.Equals(poppedNamespaceName)) - throw new Exception($"Popped namespace '{poppedNamespaceName}' does not equal name of union block '{Name}'"); - - union = new DataTypeUnion(Namespace, Name, Pack) - { - AlignmentOverride = CustomAlignment, - IsAnonymous = IsAnonymous - }; - - union.Members.AddRange(Variables); - - State.AddDataType(union); - - if (IsTypedef) - { - var typeDeclaration = new TypeDeclaration(union, new List()); - typedef = new DataTypeTypedef(Namespace, AssignedName, typeDeclaration); - - State.AddDataType(typedef); - } - } - - public override void OnChildBlockClose(Block childBlock) - { - if (childBlock is IVariableBlock variableBlock) - { - AddVariable(variableBlock.GetDefinedVariable()); - } - } - - public void AssignName(string nameAssignment) - { - AssignedName = nameAssignment; - } - - public void AddVariable(Variable variable) - { - Variables.Add(variable); - } - - public Variable GetDefinedVariable() - { - var name = ""; - DataType dataType = union; - - if (!IsTypedef) - name = AssignedName; - else - dataType = typedef; - - var typeDeclaration = new TypeDeclaration(dataType, new List()); - return new Variable(name, typeDeclaration); - } - - public void Inherit(DataTypeUnion parent) - { - foreach(var variable in parent.Members) - AddVariable(variable); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/INameAssignable.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/INameAssignable.cs deleted file mode 100644 index 81b329c5..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/INameAssignable.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZoneCodeGenerator.Parsing.C_Header.Blocks -{ - interface INameAssignable - { - void AssignName(string nameAssignment); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/IVariableBlock.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/IVariableBlock.cs deleted file mode 100644 index 1ec216e0..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/IVariableBlock.cs +++ /dev/null @@ -1,9 +0,0 @@ -using ZoneCodeGenerator.Domain; - -namespace ZoneCodeGenerator.Parsing.C_Header.Blocks -{ - interface IVariableBlock - { - Variable GetDefinedVariable(); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/IVariableHolder.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/IVariableHolder.cs deleted file mode 100644 index ec58b894..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Blocks/IVariableHolder.cs +++ /dev/null @@ -1,9 +0,0 @@ -using ZoneCodeGenerator.Domain; - -namespace ZoneCodeGenerator.Parsing.C_Header.Blocks -{ - interface IVariableHolder - { - void AddVariable(Variable variable); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/HeaderReader.cs b/src/ZoneCodeGenerator/Parsing/C_Header/HeaderReader.cs deleted file mode 100644 index 23f035f0..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/HeaderReader.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using ZoneCodeGenerator.Parsing.C_Header.Impl; -using ZoneCodeGenerator.Parsing.Impl; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Parsing.C_Header -{ - static class HeaderReader - { - private static readonly IDataPostProcessor[] postProcessors = - { - - }; - - public static IDataRepository ReadFile(string path, bool verbose = false) - { - try - { - using (IIncludingParsingStream streamFileSystem = new IncludingStreamFileSystem(path)) - { - var state = new HeaderParserState(); - IDataRepository dataRepository; - - using (IParsingFileStream preprocessorStream = new Preprocessor(streamFileSystem, state)) - { - var lexer = new Lexer(preprocessorStream); - var parser = new Parser(state, lexer); - - if (!parser.Parse(verbose)) - return null; - - dataRepository = new InMemoryDataRepository(); - try - { - state.FinishAndSaveTo(dataRepository); - } - catch (LoadingException e) - { - PrintFinishingError(e); - return null; - } - - preprocessorStream.Close(); - streamFileSystem.Close(); - - } - - if (!PostProcessRepository(dataRepository)) - { - Console.WriteLine("Postprocessing data failed."); - return null; - } - - return dataRepository; - } - } - catch (IOException e) - { - Console.WriteLine("An exception occured while trying to read header file"); - Console.WriteLine(e.Message); - return null; - } - } - - private static bool PostProcessRepository(IDataRepository repository) - { - return postProcessors.All(postProcessor => postProcessor.PostProcess(repository)); - } - - private static void PrintFinishingError(LoadingException e) - { - Console.WriteLine("Parsing failed."); - - Console.WriteLine(e.Message); - Console.WriteLine(); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/IHeaderParserState.cs b/src/ZoneCodeGenerator/Parsing/C_Header/IHeaderParserState.cs deleted file mode 100644 index c8fede13..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/IHeaderParserState.cs +++ /dev/null @@ -1,28 +0,0 @@ -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Parsing.C_Header -{ - interface IHeaderParserState : IParserState - { - Namespace CurrentNamespace { get; } - int CurrentPack { get; } - Block CurrentBlock { get; } - Block PreviousBlock { get; } - - void PushPack(int pack); - int PopPack(); - - void PushBlock(Block block); - Block PopBlock(); - - void AddDataType(DataType dataType); - void AddForwardDeclaration(ForwardDeclaration forwardDeclaration); - - DataType FindType(string typename); - EnumMember FindEnumMember(string enumMemberName); - - void FinishAndSaveTo(IDataRepository dataRepository); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Impl/HeaderParserState.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Impl/HeaderParserState.cs deleted file mode 100644 index 9cfecacd..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Impl/HeaderParserState.cs +++ /dev/null @@ -1,216 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Parsing.C_Header.Impl -{ - class HeaderParserState : IHeaderParserState - { - private const int DefaultPack = 8; - - private readonly Block defaultBlock; - private readonly Stack packStack; - private readonly Stack blockStack; - - private readonly Dictionary dataTypes; - private readonly Dictionary forwardDeclarations; - - public Namespace CurrentNamespace { get; } - - public HeaderParserState() - { - defaultBlock = new BlockNone(this); - packStack = new Stack(); - blockStack = new Stack(); - - dataTypes = new Dictionary(); - forwardDeclarations = new Dictionary(); - CurrentNamespace = new Namespace(); - } - - public int CurrentPack => packStack.Count == 0 ? DefaultPack : packStack.Peek(); - - public Block CurrentBlock => blockStack.Count == 0 ? defaultBlock : blockStack.Peek(); - - public Block PreviousBlock => blockStack.Count < 2 ? defaultBlock : blockStack.ElementAt(1); - - public void PushPack(int pack) - { - packStack.Push(pack); - } - - public int PopPack() - { - return packStack.Pop(); - } - - public void PushBlock(Block block) - { - block.OnOpen(); - blockStack.Push(block); - } - - public Block PopBlock() - { - var block = blockStack.Pop(); - - block.OnClose(); - CurrentBlock.OnChildBlockClose(block); - - return block; - } - - public void AddDataType(DataType dataType) - { - if (dataTypes.ContainsKey(dataType.FullName)) - throw new ParserException($"Type '{dataType.FullName}' is already defined."); - - dataTypes.Add(dataType.FullName, dataType); - } - - public void AddForwardDeclaration(ForwardDeclaration forwardDeclaration) - { - if (forwardDeclarations.ContainsKey(forwardDeclaration.FullName)) - { - var existingForwardDeclaration = forwardDeclarations[forwardDeclaration.FullName]; - - if (existingForwardDeclaration.Type != forwardDeclaration.Type) - throw new ParserException( - $"Forward declaration of type '{forwardDeclaration.FullName}' already done with different type."); - } - else - { - forwardDeclarations.Add(forwardDeclaration.FullName, forwardDeclaration); - } - } - - public DataType FindType(string typename) - { - var currentNamespaceTypename = Namespace.Combine(CurrentNamespace, typename); - - var baseType = - DataTypeBaseType.BASE_TYPES.FirstOrDefault(databaseBaseType => databaseBaseType.Name.Equals(typename)); - - if (baseType != null) - return baseType; - - if (dataTypes.ContainsKey(typename)) - { - return dataTypes[typename]; - } - - if (dataTypes.ContainsKey(currentNamespaceTypename)) - { - return dataTypes[currentNamespaceTypename]; - } - - if (forwardDeclarations.ContainsKey(typename)) - { - return forwardDeclarations[typename]; - } - - if (forwardDeclarations.ContainsKey(currentNamespaceTypename)) - { - return forwardDeclarations[currentNamespaceTypename]; - } - - return null; - } - - public EnumMember FindEnumMember(string enumMemberName) - { - foreach (var block in blockStack) - { - if (!(block is BlockEnum blockEnum)) continue; - - var foundMember = blockEnum.FindMember(enumMemberName); - - if (foundMember != null) - return foundMember; - } - - foreach (var dataType in dataTypes) - { - if (!(dataType.Value is DataTypeEnum _enum)) - continue; - - var foundMember = _enum.Members.Find(member => member.Name.Equals(enumMemberName)); - - if (foundMember != null) - return foundMember; - } - - return null; - } - - private void ResolveForwardDeclarations() - { - foreach (var forwardDeclaration in forwardDeclarations.Values) - { - var foundType = FindType(forwardDeclaration.FullName); - - if (foundType == null || foundType is ForwardDeclaration) - throw new ParserException($"Type {forwardDeclaration.FullName} was declared but not defined."); - - forwardDeclaration.ForwardedType = foundType; - } - - foreach (var dataType in dataTypes.Values) - { - if (dataType is DataTypeWithMembers dataTypeWithMembers) - { - foreach (var variable in dataTypeWithMembers.Members) - { - if (variable.VariableType.Type is ForwardDeclaration forwardDeclaration) - variable.VariableType.Type = forwardDeclaration.ForwardedType; - } - } - else if (dataType is DataTypeTypedef typeDef) - { - if (typeDef.TypeDefinition.Type is ForwardDeclaration forwardDeclaration) - typeDef.TypeDefinition.Type = forwardDeclaration.ForwardedType; - } - } - } - - public void FinishAndSaveTo(IDataRepository dataRepository) - { - if (blockStack.Count > 0) - throw new ParserException($"Parsing finished but {blockStack.Count} blocks were not closed."); - - ResolveForwardDeclarations(); - - foreach (var dataType in dataTypes.Values) - { - switch (dataType) - { - case DataTypeEnum _enum: - dataRepository.Add(_enum); - break; - case DataTypeStruct _struct: - _struct.FinalizeDataType(); - dataRepository.Add(_struct); - break; - case DataTypeTypedef typedef: - dataRepository.Add(typedef); - break; - case DataTypeUnion union: - union.FinalizeDataType(); - dataRepository.Add(union); - break; - default: - throw new ArgumentOutOfRangeException(nameof(dataType)); - } - } - } - - public IEnumerable> GetTests() - { - return CurrentBlock.GetAvailableTests(); - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Impl/Preprocessor.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Impl/Preprocessor.cs deleted file mode 100644 index 658043bc..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Impl/Preprocessor.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System.Collections.Generic; -using System.Text.RegularExpressions; -using ZoneCodeGenerator.Parsing.Impl; -using ZoneCodeGenerator.Utils; - -namespace ZoneCodeGenerator.Parsing.C_Header.Impl -{ - class Preprocessor : IParsingFileStream - { - private static readonly Regex packPushRegex = new Regex(@"^\s*#pragma\s+pack\s*\(\s*push\s*,\s*(\d+)\s*\)\s*$"); - private static readonly Regex packPopRegex = new Regex(@"^\s*#pragma\s+pack\s*\(\s*pop\s*\)\s*$"); - private static readonly Regex defineRegex = new Regex(@"^\s*#define\s+(\w+)(?:\s+(.*))?$"); - private static readonly Regex undefRegex = new Regex(@"^\s*#undef\s+(\w+)\s*$"); - private static readonly Regex includeRegex = new Regex(@"^\s*#include\s+(?:\""(.*)\""|\<(.*)\>)\s*$"); - private static readonly Regex ifdefRegex = new Regex(@"^\s*#ifdef\s+(\w+)\s*$"); - private static readonly Regex ifndefRegex = new Regex(@"^\s*#ifndef\s+(\w+)\s*$"); - private static readonly Regex elseRegex = new Regex(@"^\s*#else\s*$"); - private static readonly Regex endifRegex = new Regex(@"^\s*#endif\s*$"); - - private readonly IIncludingParsingStream streamFileSystem; - private readonly IHeaderParserState state; - private readonly ICommentProcessor commentProcessor; - - private readonly Dictionary defines; - private readonly Stack conditions; - - public bool EndOfStream => streamFileSystem.EndOfStream; - public string Filename => streamFileSystem.Filename; - public int Line => streamFileSystem.Line; - - public Preprocessor(IIncludingParsingStream includingParsingStream, IHeaderParserState state) - { - streamFileSystem = includingParsingStream; - this.state = state; - commentProcessor = new CommentProcessor(); - - defines = new Dictionary - { - {"__zonecodegenerator", "1"} - }; - - conditions = new Stack(); - } - - private void ParseCompilerExpression(string line) - { - var packPush = packPushRegex.Match(line.ToLower()); - if(packPush.Success) - { - state.PushPack(int.Parse(packPush.Groups[1].Value)); - return; - } - - var packPop = packPopRegex.Match(line.ToLower()); - if(packPop.Success) - { - state.PopPack(); - return; - } - - var define = defineRegex.Match(line); - if (define.Success) - { - var key = define.Groups[1].Value; - var value = define.Groups[2].Value.Trim(); - - if (defines.ContainsKey(key)) - defines[key] = value; - else - defines.Add(key, value); - return; - } - - var undef = undefRegex.Match(line); - if (undef.Success) - { - var key = undef.Groups[1].Value; - - if(defines.ContainsKey(key)) - defines.Remove(key); - return; - } - - var include = includeRegex.Match(line); - if (include.Success) - { - var filename = include.Groups[1].Success ? include.Groups[1].Value : include.Groups[2].Value; - - streamFileSystem.IncludeFile(filename); - return; - } - - var ifdef = ifdefRegex.Match(line); - if (ifdef.Success) - { - var key = ifdef.Groups[1].Value; - - conditions.Push(defines.ContainsKey(key)); - return; - } - - var ifndef = ifndefRegex.Match(line); - if (ifndef.Success) - { - var key = ifndef.Groups[1].Value; - - conditions.Push(!defines.ContainsKey(key)); - return; - } - - var _else = elseRegex.Match(line); - if (_else.Success) - { - if (conditions.Count > 0) - { - conditions.Push(!conditions.Pop()); - } - return; - } - - var endif = endifRegex.Match(line); - if (endif.Success) - { - if (conditions.Count > 0) - { - conditions.Pop(); - } - return; - } - } - - private string Preprocess(string line) - { - bool defineMatched; - line = commentProcessor.RemoveComments(line); - - if (line.StartsWith("#")) - { - ParseCompilerExpression(line); - return ""; - } - - if (conditions.Count > 0 && !conditions.Peek()) - { - return ""; - } - - do - { - defineMatched = false; - foreach (var (defineKey, defineValue) in defines) - { - var match = Regex.Match(line, $@"^(.*\W)?{defineKey}(\W.*)?$"); - - if (!match.Success) continue; - - line = match.Groups[1].Value + defineValue + match.Groups[2].Value; - defineMatched = true; - break; - } - - } while (defineMatched); - - return line; - } - - public string ReadLine() - { - return Preprocess(streamFileSystem.ReadLine()); - } - - public void Dispose() - { - Close(); - } - - public void Close() - { - streamFileSystem.Close(); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestCloseBlock.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestCloseBlock.cs deleted file mode 100644 index 99a81e6c..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestCloseBlock.cs +++ /dev/null @@ -1,48 +0,0 @@ -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.C_Header.Tests -{ - class TestCloseBlock : AbstractTokenTest - { - private const string NameToken = "close_with_name"; - private const string SemicolonToken = "close_with_semi_colon"; - - private readonly bool semicolonRequired; - - private static readonly TokenMatcher[] matchers = { - new MatcherLiteral("}"), - new MatcherGroupOptional( new MatcherGroupAnd( - new MatcherGroupOptional(new MatcherName().WithName(NameToken)), - new MatcherLiteral(";").WithName(SemicolonToken) - )) - }; - - public TestCloseBlock(bool semicolonRequired = false) : base(matchers) - { - this.semicolonRequired = semicolonRequired; - } - - protected override void ProcessMatch(IHeaderParserState state) - { - if (HasMatcherTokens(NameToken)) - { - if (state.CurrentBlock is INameAssignable nameAssignableBlock) - { - nameAssignableBlock.AssignName(NextMatch(NameToken)); - } - else - { - throw new TestFailedException($"Cannot give block '{state.CurrentBlock.Type}' a name when closing"); - } - } - - if (!HasMatcherTokens(SemicolonToken) && semicolonRequired) - throw new TestFailedException($"Block '{state.CurrentBlock.Type}' needs to be closed with a '{'}'};'"); - - state.PopBlock(); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestEnum.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestEnum.cs deleted file mode 100644 index 9e1e7d17..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestEnum.cs +++ /dev/null @@ -1,57 +0,0 @@ -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Utils; - -namespace ZoneCodeGenerator.Parsing.C_Header.Tests -{ - class TestEnum : AbstractTokenTest - { - private const string TypedefToken = "typedef"; - private const string NameToken = "name"; - private const string TypenameToken = "typename"; - - private static readonly TokenMatcher[] matchers = { - new MatcherGroupOptional(new MatcherLiteral("typedef").WithName(TypedefToken)), - new MatcherLiteral("enum"), - new MatcherGroupOptional(new MatcherName().WithName(NameToken)), - new MatcherGroupOptional(new MatcherGroupAnd(new MatcherLiteral(":"), new MatcherTypename().WithName(TypenameToken))), - new MatcherLiteral("{") - }; - - public TestEnum() : base(matchers) - { - - } - - protected override void ProcessMatch(IHeaderParserState state) - { - var isTypedef = HasMatcherTokens(TypedefToken); - var name = NextMatch(NameToken) ?? RandomName.GenerateName(); - var parentType = DataTypeBaseType.INT; - - if (HasMatcherTokens(TypenameToken)) - { - var typeName = NextMatch(TypenameToken); - var type = state.FindType(typeName); - - if (type == null) - throw new TestFailedException($"Parent type '{typeName}' of enum '{name}' not found."); - - while (type is DataTypeTypedef typedef) - { - if (typedef.TypeDefinition.References.Count > 0) - throw new TestFailedException($"Parent type of enum '{name}' cannot be a typedef that is an array or a pointer."); - - type = typedef.TypeDefinition.Type; - } - - parentType = type as DataTypeBaseType ?? throw new TestFailedException($"Parent type of enum '{name}' must be a base type."); - } - - state.PushBlock(new BlockEnum(state, name, parentType, isTypedef)); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestEnumMember.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestEnumMember.cs deleted file mode 100644 index 388b2b7e..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestEnumMember.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.C_Header.Tests -{ - class TestEnumMember : AbstractTokenTest - { - private const string NameToken = "name"; - private const string NumberValueToken = "value_number"; - private const string EnumMemberValueToken = "value_string"; - - private static readonly TokenMatcher[] matchers = { - new MatcherName().WithName(NameToken), - new MatcherGroupOptional(new MatcherGroupAnd( - new MatcherLiteral("="), - new MatcherGroupOr( - new MatcherNumber().WithName(NumberValueToken), - new MatcherName().WithName(EnumMemberValueToken) - ))), - new MatcherGroupOr( - new MatcherLiteral(","), - new MatcherLiteral("}").NonConsuming() - ) - }; - - public TestEnumMember() : base(matchers) - { - - } - - protected override void ProcessMatch(IHeaderParserState state) - { - var name = NextMatch(NameToken); - long value; - - if (!(state.CurrentBlock is BlockEnum _enum)) - throw new Exception("Excepted enum to be top block when parsing an enum member."); - - if (HasMatcherTokens(NumberValueToken)) - { - value = long.Parse(NextMatch(NumberValueToken)); - } - else if(HasMatcherTokens(EnumMemberValueToken)) - { - var stringValue = NextMatch(EnumMemberValueToken); - var memberWithFittingName = state.FindEnumMember(stringValue); - - if(memberWithFittingName == null) - throw new TestFailedException($"Could not find value for '{stringValue}'."); - - value = memberWithFittingName.Value; - } - else - { - value = _enum.GetNextEnumValue(); - } - - var enumMember = new EnumMember(name, value); - _enum.AddMember(enumMember); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestForwardDecl.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestForwardDecl.cs deleted file mode 100644 index 06b132fe..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestForwardDecl.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.C_Header.Tests -{ - class TestForwardDecl : AbstractTokenTest - { - private const string EnumToken = "enum"; - private const string StructToken = "struct"; - private const string UnionToken = "union"; - private const string NameToken = "name"; - - private static readonly TokenMatcher[] matchers = { - new MatcherGroupOr( - new MatcherLiteral("enum").WithName(EnumToken), - new MatcherLiteral("struct").WithName(StructToken), - new MatcherLiteral("union").WithName(UnionToken) - ), - new MatcherName().WithName(NameToken), - new MatcherLiteral(";") - }; - - public TestForwardDecl() : base(matchers) - { - - } - - protected override void ProcessMatch(IHeaderParserState state) - { - var name = NextMatch(NameToken); - var _namespace = state.CurrentNamespace.ToString(); - - if (HasMatcherTokens(EnumToken)) - { - state.AddForwardDeclaration(new ForwardDeclaration(_namespace, name, DataTypeType.Enum)); - } - else if (HasMatcherTokens(StructToken)) - { - state.AddForwardDeclaration(new ForwardDeclaration(_namespace, name, DataTypeType.Struct)); - } - else if (HasMatcherTokens(UnionToken)) - { - state.AddForwardDeclaration(new ForwardDeclaration(_namespace, name, DataTypeType.Union)); - } - else - throw new Exception("Unknown type for forward declaration."); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestNamespace.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestNamespace.cs deleted file mode 100644 index e51f07ae..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestNamespace.cs +++ /dev/null @@ -1,29 +0,0 @@ -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.C_Header.Tests -{ - class TestNamespace : AbstractTokenTest - { - private const string NamespaceNameToken = "namespace_name"; - - private static readonly TokenMatcher[] matchers = - { - new MatcherLiteral("namespace"), - new MatcherName().WithName(NamespaceNameToken), - new MatcherLiteral("{") - }; - - public TestNamespace() : base(matchers) - { - - } - - protected override void ProcessMatch(IHeaderParserState state) - { - state.PushBlock(new BlockNamespace(state, NextMatch(NamespaceNameToken))); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestStruct.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestStruct.cs deleted file mode 100644 index 98834338..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestStruct.cs +++ /dev/null @@ -1,69 +0,0 @@ -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Utils; - -namespace ZoneCodeGenerator.Parsing.C_Header.Tests -{ - class TestStruct : AbstractTokenTest - { - private const string TypedefToken = "typedef"; - private const string NameToken = "name"; - private const string AlignToken = "align"; - private const string ParentToken = "parent"; - - private static readonly TokenMatcher[] matchers = { - new MatcherGroupOptional(new MatcherLiteral("typedef").WithName(TypedefToken)), - new MatcherGroupOptional(new MatcherLiteral("const")), - new MatcherLiteral("struct"), - new MatcherGroupOptional(new MatcherGroupAnd( - new MatcherLiteral("__declspec"), - new MatcherLiteral("("), - new MatcherLiteral("align"), - new MatcherLiteral("("), - new MatcherNumber().WithName(AlignToken), - new MatcherLiteral(")"), - new MatcherLiteral(")") - )), - new MatcherGroupOptional(new MatcherName().WithName(NameToken)), - new MatcherGroupOptional(new MatcherGroupAnd( - new MatcherLiteral(":"), - new MatcherTypename().WithName(ParentToken) - )), - new MatcherLiteral("{") - }; - - public TestStruct() : base(matchers) - { - - } - - protected override void ProcessMatch(IHeaderParserState state) - { - var isTypedef = HasMatcherTokens(TypedefToken); - var name = NextMatch(NameToken) ?? ""; - - var block = new BlockStruct(state, name, isTypedef); - - if (HasMatcherTokens(AlignToken)) - block.CustomAlignment = int.Parse(NextMatch(AlignToken)); - - if (HasMatcherTokens(ParentToken)) - { - var parentDataTypeName = NextMatch(ParentToken); - var parentDataType = state.FindType(parentDataTypeName); - - if(parentDataType == null) - throw new TestFailedException($"Could not find parent data type '{parentDataTypeName}' for struct '{name}'"); - if(!(parentDataType is DataTypeStruct parentStruct)) - throw new TestFailedException($"Parent data type '{parentDataTypeName}' for struct '{name}' must be a struct as well."); - - block.Inherit(parentStruct); - } - - state.PushBlock(block); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestTypedef.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestTypedef.cs deleted file mode 100644 index b7861398..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestTypedef.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System.Collections.Generic; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.C_Header.Tests -{ - class TestTypedef : AbstractTokenTest - { - private const string TypeNameTokens = "typename"; - private const string PointerTokens = "pointer"; - private const string NameToken = "name"; - private const string ArrayTokens = "array"; - private const string AlignValueToken = "alignValue"; - private const string TokenConst = "constToken"; - - private const string TagAlign = "alignTag"; - private const string TagArrayOfPointers = "arrayOfPointersTag"; - private const string TagPointerToArray = "pointerToArrayTag"; - - private static readonly TokenMatcher align = new MatcherGroupAnd( - new MatcherLiteral("__declspec", "("), - new MatcherLiteral("align", "("), - new MatcherNumber().WithName(AlignValueToken), - new MatcherLiteral(")"), - new MatcherLiteral(")") - ).WithTag(TagAlign); - - private static readonly TokenMatcher arrayOfPointers = new MatcherGroupAnd( - new MatcherGroupOptional(new MatcherLiteral("const").WithName(TokenConst)), - new MatcherTypename().WithName(TypeNameTokens), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.ZeroOneMultiple, - new MatcherLiteral("*").WithName(PointerTokens)), - new MatcherName().WithName(NameToken), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.ZeroOneMultiple, new MatcherArray().WithName(ArrayTokens)), - new MatcherLiteral(";") - ).WithTag(TagArrayOfPointers); - - private static readonly TokenMatcher pointerToArray = new MatcherGroupAnd( - new MatcherGroupOptional(new MatcherLiteral("const").WithName(TokenConst)), - new MatcherTypename().WithName(TypeNameTokens), - new MatcherLiteral("("), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.OneMultiple, - new MatcherLiteral("*").WithName(PointerTokens)), - new MatcherName().WithName(NameToken), - new MatcherLiteral(")"), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.OneMultiple, new MatcherArray().WithName(ArrayTokens)), - new MatcherLiteral(";") - ).WithTag(TagPointerToArray); - - private static readonly TokenMatcher[] matchers = - { - new MatcherLiteral("typedef"), - new MatcherGroupOptional(new MatcherWithTag(TagAlign)), - new MatcherGroupOr( - new MatcherWithTag(TagArrayOfPointers), - new MatcherWithTag(TagPointerToArray) - ) - }; - - public TestTypedef() : base(matchers) - { - AddTaggedMatcher(align); - AddTaggedMatcher(arrayOfPointers); - AddTaggedMatcher(pointerToArray); - } - - protected override void ProcessMatch(IHeaderParserState state) - { - // Check if a custom alignment has been defined - int? alignmentOverride = null; - if (PeekTag().Equals(TagAlign)) - { - NextTag(); - alignmentOverride = int.Parse(NextMatch(AlignValueToken)); - } - - // See which variant has been used - var isArrayOfPointersVariant = NextTag().Equals(TagArrayOfPointers); - - // Get name of typedef and the amount of pointer depth it has - var name = NextMatch(NameToken); - var pointerDepth = GetMatcherTokenCount(PointerTokens); - - // Find referenced type - var typeName = NextMatch(TypeNameTokens); - var type = state.FindType(typeName); - if (type == null) - throw new TestFailedException($"Could not find type '{typeName}' of typedef '{name}'."); - - // Collect all array sizes that have been specified - var arraySize = new int[GetMatcherTokenCount(ArrayTokens)]; - string arrayToken; - var index = 0; - while ((arrayToken = NextMatch(ArrayTokens)) != null) - { - if (!int.TryParse(arrayToken, out arraySize[index++])) - throw new TestFailedException($"Array size '{arrayToken}' is not numeric."); - } - - var references = new List(); - if (isArrayOfPointersVariant) - { - foreach (var array in arraySize) - references.Add(new ReferenceTypeArray(array)); - - for (var i = 0; i < pointerDepth; i++) - references.Add(new ReferenceTypePointer()); - } - else - { - for (var i = 0; i < pointerDepth; i++) - references.Add(new ReferenceTypePointer()); - - foreach (var array in arraySize) - references.Add(new ReferenceTypeArray(array)); - } - - var typeDeclaration = new TypeDeclaration(type, references) - { - IsConst = HasMatcherTokens(TokenConst) - }; - var typedef = new DataTypeTypedef(state.CurrentNamespace.ToString(), name, typeDeclaration) - { - - AlignmentOverride = alignmentOverride - }; - - state.AddDataType(typedef); - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestUnion.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestUnion.cs deleted file mode 100644 index 5e698aff..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestUnion.cs +++ /dev/null @@ -1,69 +0,0 @@ -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Utils; - -namespace ZoneCodeGenerator.Parsing.C_Header.Tests -{ - class TestUnion : AbstractTokenTest - { - private const string TypedefToken = "typedef"; - private const string NameToken = "name"; - private const string AlignToken = "align"; - private const string ParentToken = "parent"; - - private static readonly TokenMatcher[] matchers = { - new MatcherGroupOptional(new MatcherLiteral("typedef").WithName(TypedefToken)), - new MatcherGroupOptional(new MatcherLiteral("const")), - new MatcherLiteral("union"), - new MatcherGroupOptional(new MatcherGroupAnd( - new MatcherLiteral("__declspec"), - new MatcherLiteral("("), - new MatcherLiteral("align"), - new MatcherLiteral("("), - new MatcherNumber().WithName(AlignToken), - new MatcherLiteral(")"), - new MatcherLiteral(")") - )), - new MatcherGroupOptional(new MatcherName().WithName(NameToken)), - new MatcherGroupOptional(new MatcherGroupAnd( - new MatcherLiteral(":"), - new MatcherTypename().WithName(ParentToken) - )), - new MatcherLiteral("{") - }; - - public TestUnion() : base(matchers) - { - - } - - protected override void ProcessMatch(IHeaderParserState state) - { - var isTypedef = HasMatcherTokens(TypedefToken); - var name = NextMatch(NameToken) ?? ""; - - var block = new BlockUnion(state, name, isTypedef); - - if (HasMatcherTokens(AlignToken)) - block.CustomAlignment = int.Parse(NextMatch(AlignToken)); - - if (HasMatcherTokens(ParentToken)) - { - var parentDataTypeName = NextMatch(ParentToken); - var parentDataType = state.FindType(parentDataTypeName); - - if(parentDataType == null) - throw new TestFailedException($"Could not find parent data type '{parentDataTypeName}' for union '{name}'"); - if(!(parentDataType is DataTypeUnion parentUnion)) - throw new TestFailedException($"Parent data type '{parentDataTypeName}' for union '{name}' must be a union as well."); - - block.Inherit(parentUnion); - } - - state.PushBlock(block); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestVariable.cs b/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestVariable.cs deleted file mode 100644 index 20be331f..00000000 --- a/src/ZoneCodeGenerator/Parsing/C_Header/Tests/TestVariable.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Collections.Generic; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.C_Header.Tests -{ - class TestVariable : AbstractTokenTest - { - private const string PointerToArrayVariant = "pointertoarray"; - private const string ArrayOfPointersVariant = "arrayofpointers"; - private const string TypeNameToken = "typename"; - private const string PointerTokens = "pointer"; - private const string NameToken = "name"; - private const string ArrayTokens = "array"; - private const string BitSizeToken = "bitsize"; - private const string TokenConst = "constToken"; - - private static readonly TokenMatcher[] arrayOfPointersMatchers = { - new MatcherGroupOptional(new MatcherLiteral("const").WithName(TokenConst)), - new MatcherTypename().WithName(TypeNameToken), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.ZeroOneMultiple, new MatcherLiteral("*").WithName(PointerTokens)), - new MatcherName().WithName(NameToken), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.ZeroOneMultiple, new MatcherArray().WithName(ArrayTokens)), - new MatcherGroupOptional(new MatcherGroupAnd( - new MatcherLiteral(":"), - new MatcherNumber().WithName(BitSizeToken) - )), - new MatcherLiteral(";").WithName(ArrayOfPointersVariant) - }; - - private static readonly TokenMatcher[] pointerToArrayMatchers = { - new MatcherGroupOptional(new MatcherLiteral("const").WithName(TokenConst)), - new MatcherTypename().WithName(TypeNameToken), - new MatcherLiteral("("), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.OneMultiple, new MatcherLiteral("*").WithName(PointerTokens)), - new MatcherName().WithName(NameToken), - new MatcherLiteral(")"), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.OneMultiple, new MatcherArray().WithName(ArrayTokens)), - new MatcherLiteral(";").WithName(PointerToArrayVariant) - }; - - private static readonly TokenMatcher[] matchers = - { - new MatcherGroupOr( - new MatcherGroupAnd(arrayOfPointersMatchers), - new MatcherGroupAnd(pointerToArrayMatchers) - ) - }; - - public TestVariable() : base(matchers) - { - - } - - protected override void ProcessMatch(IHeaderParserState state) - { - var name = NextMatch(NameToken); - var typeName = NextMatch(TypeNameToken); - var type = state.FindType(typeName); - - if (type == null) - throw new TestFailedException($"Type '{typeName}' not found."); - - var pointerDepth = GetMatcherTokenCount(PointerTokens); - - int? bitSize = null; - if (HasMatcherTokens(BitSizeToken)) - bitSize = int.Parse(NextMatch(BitSizeToken)); - - string arrayToken; - var index = 0; - var arraySize = new int[GetMatcherTokenCount(ArrayTokens)]; - while ((arrayToken = NextMatch(ArrayTokens)) != null) - { - if (!int.TryParse(arrayToken, out arraySize[index++])) - throw new TestFailedException($"Array size '{arrayToken}' is not numeric."); - } - - if (state.CurrentBlock is IVariableHolder variableHolder) - { - var references = new List(); - - if (HasMatcherTokens(PointerToArrayVariant)) - { - for (var i = 0; i < pointerDepth; i++) - references.Add(new ReferenceTypePointer()); - foreach(var array in arraySize) - references.Add(new ReferenceTypeArray(array)); - } - else - { - foreach(var array in arraySize) - references.Add(new ReferenceTypeArray(array)); - - for (var i = 0; i < pointerDepth; i++) - references.Add(new ReferenceTypePointer()); - } - - var typeDeclaration = new TypeDeclaration(type, references) - { - CustomBitSize = bitSize, - IsConst = HasMatcherTokens(TokenConst) - }; - - var variable = new Variable(name, typeDeclaration); - - variableHolder.AddVariable(variable); - } - else - { - throw new Exception("Expected current block to be a variable holder when parsing variables."); - } - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/CommandFileReader.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/CommandFileReader.cs deleted file mode 100644 index aa457105..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/CommandFileReader.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using ZoneCodeGenerator.Interface; -using ZoneCodeGenerator.Parsing.CommandFile.Impl; -using ZoneCodeGenerator.Parsing.CommandFile.PostProcessor; -using ZoneCodeGenerator.Parsing.Impl; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Parsing.CommandFile -{ - static class CommandFileReader - { - private static readonly IDataPostProcessor[] postProcessors = - { - new PostProcessorUsages(), - new PostProcessorLeafs(), - new PostProcessorMemberLeafs(), - new PostProcessorUnions(), - }; - - public static bool ReadFile(string path, CUISession session, bool verbose = false) - { - try - { - using (IIncludingParsingStream streamFileSystem = new IncludingStreamFileSystem(path)) - { - var state = new CommandParserState(session.Repository); - - using (IParsingFileStream preprocessorStream = new CommandFilePreprocessor(streamFileSystem)) - { - var lexer = new Lexer(preprocessorStream); - var parser = new Parser(state, lexer); - - if (!parser.Parse(verbose)) - return false; - - preprocessorStream.Close(); - streamFileSystem.Close(); - - if (!state.Apply(session)) - { - Console.WriteLine("Finalizing from command file failed"); - return false; - } - - if (!PostProcessRepository(session.Repository)) - { - Console.WriteLine("Postprocessing commands failed."); - return false; - } - } - - return true; - } - } - catch (IOException) - { - - } - - return false; - } - - private static bool PostProcessRepository(IDataRepository repository) - { - return postProcessors.All(postProcessor => postProcessor.PostProcess(repository)); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/ICommandParserState.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/ICommandParserState.cs deleted file mode 100644 index 7d00d613..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/ICommandParserState.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Collections.Generic; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.FastFileStructure; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Parsing.CommandFile -{ - interface ICommandParserState : IParserState - { - string Game { get; set; } - IReadOnlyDataRepository Repository { get; } - List FastFileBlocks { get; } - StructureInformation DataTypeInUse { get; set; } - - bool GetMembersFromParts(string[] parts, StructureInformation baseType, out List members); - bool GetTypenameAndMembersFromParts(string[] parts, out StructureInformation typeInformation, - out List members); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Impl/CommandFilePreprocessor.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Impl/CommandFilePreprocessor.cs deleted file mode 100644 index 2f1b021b..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Impl/CommandFilePreprocessor.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Text.RegularExpressions; -using ZoneCodeGenerator.Parsing.Impl; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Impl -{ - class CommandFilePreprocessor : IParsingFileStream - { - private static readonly Regex includeRegex = new Regex(@"^\s*include\s*(?:\""(.*)\""|\<(.*)\>)\s*$"); - - private readonly IIncludingParsingStream parsingStream; - private readonly ICommentProcessor commentProcessor; - - public CommandFilePreprocessor(IIncludingParsingStream parsingStream) - { - this.parsingStream = parsingStream; - commentProcessor = new CommentProcessor(); - } - - public void Dispose() - { - parsingStream.Close(); - } - - public bool EndOfStream => parsingStream.EndOfStream; - public string Filename => parsingStream.Filename; - public int Line => parsingStream.Line; - - public string ReadLine() - { - return Preprocess(parsingStream.ReadLine()); - } - - public void Close() - { - parsingStream.Close(); - } - - private string Preprocess(string line) - { - line = commentProcessor.RemoveComments(line); - - var includeMatch = includeRegex.Match(line); - - if (includeMatch.Success) - { - var filename = includeMatch.Groups[1].Success ? includeMatch.Groups[1].Value : includeMatch.Groups[2].Value; - - parsingStream.IncludeFile(filename); - - return ""; - } - - return line; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Impl/CommandParserState.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Impl/CommandParserState.cs deleted file mode 100644 index 91567e83..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Impl/CommandParserState.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.FastFileStructure; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Interface; -using ZoneCodeGenerator.Parsing.CommandFile.Tests; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Impl -{ - class CommandParserState : ICommandParserState - { - private static readonly ITokenTest[] tests = - { - new TestAction(), - new TestArrayCount(), - new TestArraySize(), - new TestAsset(), - new TestBlock(), - new TestCondition(), - new TestCount(), - new TestGame(), - new TestName(), - new TestReorder(), - new TestReusable(), - new TestScriptString(), - new TestSetBlock(), - new TestString(), - new TestUse() - }; - - public string Game { get; set; } - public IReadOnlyDataRepository Repository { get; } - public List FastFileBlocks { get; } - public StructureInformation DataTypeInUse { get; set; } - - public CommandParserState(IReadOnlyDataRepository repository) - { - Repository = repository; - FastFileBlocks = new List(); - DataTypeInUse = null; - } - - public IEnumerable> GetTests() - { - return tests; - } - - public bool Apply(CUISession session) - { - session.Game = Game; - - foreach (var block in FastFileBlocks) - { - session.Repository.Add(block); - } - - return true; - } - - private bool FindTypenameParts(string[] parts, out DataTypeWithMembers dataTypeWithMembers, - out int typeNamePartCount) - { - typeNamePartCount = 1; - while (typeNamePartCount <= parts.Length) - { - var currentTypeName = string.Join("::", parts, 0, typeNamePartCount); - var foundDataType = Repository.GetDataTypeByName(currentTypeName); - - if (foundDataType != null) - { - if (!(foundDataType is DataTypeWithMembers foundDataTypeWithMembers)) - { - throw new TestFailedException( - $"Referenced type '{currentTypeName}' needs to be a data type with members to be used in an evaluation."); - } - - dataTypeWithMembers = foundDataTypeWithMembers; - return true; - } - - typeNamePartCount++; - } - - dataTypeWithMembers = null; - return false; - } - - public bool GetMembersFromParts(string[] parts, StructureInformation baseType, - out List members) - { - members = new List(); - var currentStructure = baseType; - foreach (var part in parts) - { - var member = currentStructure.OrderedMembers.FirstOrDefault(information => - information.Member.Name.Equals(part)); - - if (member == null) - { - members = null; - return false; - } - - members.Add(member); - currentStructure = member.StructureType; - } - - return true; - } - - public bool GetTypenameAndMembersFromParts(string[] parts, out StructureInformation typeInformation, - out List members) - { - if (!FindTypenameParts(parts, out var type, out var typeNamePartCount)) - { - typeInformation = null; - members = null; - return false; - } - - typeInformation = Repository.GetInformationFor(type); - if (typeInformation == null) - { - members = null; - return false; - } - - var memberParts = new string[parts.Length - typeNamePartCount]; - Array.Copy(parts, typeNamePartCount, memberParts, 0, memberParts.Length); - - return GetMembersFromParts(memberParts, typeInformation, out members); - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorLeafs.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorLeafs.cs deleted file mode 100644 index 5fb868a2..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorLeafs.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Parsing.CommandFile.PostProcessor -{ - class PostProcessorLeafs : IDataPostProcessor - { - public static bool IsLeaf(StructureInformation structureInformation) - { - foreach (var member in structureInformation.OrderedMembers) - { - // If there is a condition to this member and it always evaluates to false: Skip this member - if (member.Condition != null && member.Condition.IsStatic && member.Condition.EvaluateNumeric() == 0) - continue; - - // Any ScriptStrings or Strings need to be processed. - if (member.IsScriptString - || member.IsString) - return false; - - // If there are any Pointer members that are not always count 0 it needs to be processed. - var hasNoPointerMembers = member.Member.VariableType.References.OfType().All(pointer => - { - if (!pointer.Count.IsStatic) - return false; - - return pointer.Count.EvaluateNumeric() == 0; - }); - - if (!hasNoPointerMembers) - return false; - - // If the member has an embedded type with dynamic size - if (member.Computations.HasDynamicArraySize) - return false; - - if (member.StructureType != null - && member.StructureType != structureInformation - && !IsLeaf(member.StructureType)) - return false; - } - - return true; - } - - public bool PostProcess(IDataRepository repository) - { - foreach (var dataTypeWithMembers in repository.GetAllStructs() - .AsEnumerable() - .Concat(repository.GetAllUnions())) - { - var information = repository.GetInformationFor(dataTypeWithMembers); - - information.IsLeaf = IsLeaf(information); - } - - return true; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorMemberLeafs.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorMemberLeafs.cs deleted file mode 100644 index 755ac7a3..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorMemberLeafs.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Parsing.CommandFile.PostProcessor -{ - class PostProcessorMemberLeafs : IDataPostProcessor - { - private static bool MemberIsLeaf(MemberInformation member) - { - if (member.IsString || member.IsScriptString) - return false; - - if (member.StructureType != null && !member.StructureType.IsLeaf) - return false; - - // If there are any Pointer members that are not always count 0 it needs to be processed. - var hasNoPointerMembers = member.Member.VariableType.References.OfType().All(pointer => - { - if (!pointer.Count.IsStatic) - return false; - - return pointer.Count.EvaluateNumeric() == 0; - }); - - if (!hasNoPointerMembers) - return false; - - if (member.Computations.HasDynamicArraySize) - return false; - - return true; - } - - private static void ProcessStructureInformation(StructureInformation structure) - { - foreach (var member in structure.OrderedMembers) - { - member.IsLeaf = MemberIsLeaf(member); - } - } - - public bool PostProcess(IDataRepository repository) - { - foreach (var structure in repository.GetAllStructs() - .Cast() - .Concat(repository.GetAllUnions()) - .Select(repository.GetInformationFor)) - { - ProcessStructureInformation(structure); - } - - return true; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorUnions.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorUnions.cs deleted file mode 100644 index 5d56d4cc..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorUnions.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Parsing.CommandFile.PostProcessor -{ - class PostProcessorUnions : IDataPostProcessor - { - private static bool ProcessUnion(StructureInformation unionInformation) - { - var entriesWithoutConditionCount = - unionInformation.OrderedMembers.Count(member => member.Condition == null && !member.IsLeaf); - - if (entriesWithoutConditionCount > 1 && unionInformation.Usages.Any() && !unionInformation.IsLeaf) - { - Console.WriteLine($"Union '{unionInformation.Type.FullName}' has more than one entry without a condition!"); - return false; - } - else if (entriesWithoutConditionCount == 1) - { - // If there is only one entry without condition make it the last of the ordered members - var entryWithoutCondition = unionInformation.OrderedMembers.First(information => information.Condition == null); - - unionInformation.OrderedMembers.Remove(entryWithoutCondition); - unionInformation.OrderedMembers.Insert(unionInformation.OrderedMembers.Count, entryWithoutCondition); - } - - return true; - } - - public bool PostProcess(IDataRepository repository) - { - return repository.GetAllUnions() - .Select(repository.GetInformationFor) - .All(ProcessUnion); - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorUsages.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorUsages.cs deleted file mode 100644 index 5886a141..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/PostProcessor/PostProcessorUsages.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Parsing.CommandFile.PostProcessor -{ - class PostProcessorUsages : IDataPostProcessor - { - private static bool ProcessAsset(StructureInformation assetStructure) - { - var processedAssets = new HashSet(); - var processingQueue = new Queue(); - processingQueue.Enqueue(assetStructure); - - while (processingQueue.Count != 0) - { - var currentStructure = processingQueue.Dequeue(); - - if (!processedAssets.Add(currentStructure)) - { - continue; - } - - foreach (var member in currentStructure.OrderedMembers - .Where(member => member.StructureType != null) - .Where(member => !member.Computations.ShouldIgnore)) - { - if (member.Computations.ContainsNonEmbeddedReference) - member.StructureType.NonEmbeddedReferenceExists = true; - - if (member.Computations.ContainsSinglePointerReference) - member.StructureType.SinglePointerReferenceExists = true; - - if (member.Computations.ContainsArrayPointerReference) - member.StructureType.ArrayPointerReferenceExists = true; - - if (member.Computations.ContainsArrayReference) - member.StructureType.ArrayReferenceExists = true; - - if (member.Computations.IsNotDefaultNormalBlock) - member.StructureType.ReferenceFromNonDefaultNormalBlockExists = true; - - member.StructureType.Usages.Add(currentStructure); - processingQueue.Enqueue(member.StructureType); - } - } - - return true; - } - - public bool PostProcess(IDataRepository repository) - { - return repository.GetAllStructs() - .AsEnumerable() - .Concat(repository.GetAllUnions()) - .Select(repository.GetInformationFor) - .Where(information => information.IsAsset) - .All(ProcessAsset); - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestAction.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestAction.cs deleted file mode 100644 index 19cc8a54..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestAction.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestAction : AbstractTokenTest - { - private const string TokenTypename = "typeName"; - private const string TagTypename = "typeName"; - - private const string TokenActionName = "actionName"; - - private const string TokenActionArgument = "actionArgument"; - private const string TagActionArguments = "actionArguments"; - - private static readonly TokenMatcher actionArguments = new MatcherGroupAnd( - new MatcherLiteral("("), - new MatcherGroupOptional(new MatcherGroupAnd( - new MatcherTypename().WithName(TokenActionArgument), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.ZeroOneMultiple, new MatcherGroupAnd( - new MatcherLiteral(","), - new MatcherTypename().WithName(TokenActionArgument) - )) - )), - new MatcherLiteral(")") - ).WithTag(TagActionArguments); - - private static readonly TokenMatcher[] matchers = - { - new MatcherLiteral("set"), - new MatcherLiteral("action"), - new MatcherGroupOr( - new MatcherGroupAnd( - new MatcherName().WithName(TokenActionName), - new MatcherWithTag(TagActionArguments) - ), - new MatcherGroupAnd( - new MatcherTypename().WithName(TokenTypename).WithTag(TagTypename), - new MatcherName().WithName(TokenActionName), - new MatcherWithTag(TagActionArguments) - ) - ), - new MatcherLiteral(";") - }; - - public TestAction() : base(matchers) - { - AddTaggedMatcher(actionArguments); - } - - protected override void ProcessMatch(ICommandParserState state) - { - StructureInformation selectedStructure; - if (PeekTag().Equals(TagTypename)) - { - NextTag(); - var typeName = NextMatch(TokenTypename); - var typeNameParts = typeName.Split(new[] {"::"}, StringSplitOptions.None); - - if (state.DataTypeInUse != null && - state.GetMembersFromParts(typeNameParts, state.DataTypeInUse, out var selectedMembers)) - { - selectedStructure = state.DataTypeInUse; - } - else if (state.GetTypenameAndMembersFromParts(typeNameParts, out selectedStructure, out selectedMembers)) - { - // Do nothing - } - else - { - throw new TestFailedException($"Could not find type '{typeName}'."); - } - - if (selectedMembers.Any()) - { - selectedStructure = selectedMembers.Last().StructureType ?? - throw new TestFailedException("Member is not a data type with members."); - } - } - else - { - selectedStructure = state.DataTypeInUse ?? throw new TestFailedException("No type found for action."); - } - - var actionName = NextMatch(TokenActionName); - if (string.IsNullOrEmpty(actionName)) - { - throw new TestFailedException("Action needs a valid name!"); - } - - var parameterTypes = new List(); - string parameter; - while ((parameter = NextMatch(TokenActionArgument)) != null) - { - var parameterDataType = state.Repository.GetDataTypeByName(parameter); - - if (parameterDataType == null) - { - throw new TestFailedException($"Could not find type '{parameter}'."); - } - - parameterTypes.Add(parameterDataType); - } - - selectedStructure.PostLoadAction = new CustomAction(actionName, parameterTypes); - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestArrayCount.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestArrayCount.cs deleted file mode 100644 index 59a23c64..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestArrayCount.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestArrayCount : TestWithEvaluation - { - private StructureInformation referencedType; - private const string TypeNameToken = "typeName"; - - // set count ; - private static readonly TokenMatcher[] matchers = - { - new MatcherLiteral("set"), - new MatcherLiteral("arraycount"), - new MatcherTypename().WithName(TypeNameToken), - new MatcherWithTag(TagEvaluation), - new MatcherLiteral(";") - }; - - public TestArrayCount() : base(matchers) - { - } - - protected override void ProcessMatch(ICommandParserState state) - { - var typeName = NextMatch(TypeNameToken); - var typeNameParts = typeName.Split(new[] { "::" }, StringSplitOptions.None); - if (state.DataTypeInUse != null - && state.GetMembersFromParts(typeNameParts, state.DataTypeInUse, out var typeMembers)) - { - referencedType = state.DataTypeInUse; - } - else if (state.GetTypenameAndMembersFromParts(typeNameParts, out referencedType, out typeMembers)) - { - // Do nothing - } - else - { - throw new TestFailedException($"Could not find type/members '{typeName}'"); - } - - if (typeMembers == null - || !typeMembers.Any()) - { - throw new TestFailedException("Can only set array size for members and not for types."); - } - - if (!NextTag().Equals(TagEvaluation)) - throw new Exception("Expected first array size tag to be a calculation statement"); - - var evaluation = ProcessEvaluation(state); - - var referencedMember = typeMembers.Last(); - var reference = referencedMember.Member.VariableType.References.OfType() - .FirstOrDefault(); - - if (reference != null) - reference.DynamicCount = evaluation; - else - throw new TestFailedException( - $"Member '{referencedMember.Member.Name}' of type '{referencedMember.Member.VariableType.Type.FullName}' cannot have its array count set due to it not having an array reference"); - } - - protected override IEnumerable GetUsedTypes(ICommandParserState state) - { - if (state.DataTypeInUse != null - && state.DataTypeInUse != referencedType) - { - return new[] { state.DataTypeInUse, referencedType }; - } - - return new[] { referencedType }; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestArraySize.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestArraySize.cs deleted file mode 100644 index dd5f677e..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestArraySize.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestArraySize : TestWithEvaluation - { - private StructureInformation referencedType; - private const string TypeNameToken = "typeName"; - - // set count ; - private static readonly TokenMatcher[] matchers = - { - new MatcherLiteral("set"), - new MatcherLiteral("arraysize"), - new MatcherTypename().WithName(TypeNameToken), - new MatcherWithTag(TagEvaluation), - new MatcherLiteral(";") - }; - - public TestArraySize() : base(matchers) - { - } - - protected override void ProcessMatch(ICommandParserState state) - { - var typeName = NextMatch(TypeNameToken); - var typeNameParts = typeName.Split(new[] {"::"}, StringSplitOptions.None); - if (state.DataTypeInUse != null - && state.GetMembersFromParts(typeNameParts, state.DataTypeInUse, out var typeMembers)) - { - referencedType = state.DataTypeInUse; - } - else if (state.GetTypenameAndMembersFromParts(typeNameParts, out referencedType, out typeMembers)) - { - // Do nothing - } - else - { - throw new TestFailedException($"Could not find type/members '{typeName}'"); - } - - if (typeMembers == null - || !typeMembers.Any()) - { - throw new TestFailedException("Can only set array size for members and not for types."); - } - - if (!NextTag().Equals(TagEvaluation)) - throw new Exception("Expected first array size tag to be a calculation statement"); - - var evaluation = ProcessEvaluation(state); - - var referencedMember = typeMembers.Last(); - var reference = referencedMember.Member.VariableType.References.OfType() - .FirstOrDefault(); - - if (!referencedMember.Parent.IsUnion && - referencedMember.Parent.Type.Members.Last() != referencedMember.Member) - { - throw new TestFailedException( - "Cannot change the array size of a member that is not the last member of its structure."); - } - - if (reference != null) - reference.DynamicSize = evaluation; - else - throw new TestFailedException( - $"Member '{referencedMember.Member.Name}' of type '{referencedMember.Member.VariableType.Type.FullName}' cannot have its array size set due to it not having an array reference"); - } - - protected override IEnumerable GetUsedTypes(ICommandParserState state) - { - if (state.DataTypeInUse != null - && state.DataTypeInUse != referencedType) - { - return new[] {state.DataTypeInUse, referencedType}; - } - - return new[] {referencedType}; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestAsset.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestAsset.cs deleted file mode 100644 index f35d67a4..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestAsset.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestAsset : AbstractTokenTest - { - private const string AssetTypeNameToken = "name"; - private const string AssetEnumEntryToken = "enumEntry"; - - private static readonly TokenMatcher[] matchers = { - new MatcherLiteral("asset"), - new MatcherTypename().WithName(AssetTypeNameToken), - new MatcherName().WithName(AssetEnumEntryToken), - new MatcherLiteral(";") - }; - - public TestAsset() : base(matchers) - { - - } - - protected override void ProcessMatch(ICommandParserState state) - { - var assetTypeName = NextMatch(AssetTypeNameToken); - - var assetType = state.Repository.GetDataTypeByName(assetTypeName); - if (assetType == null) - { - throw new TestFailedException($"Could not find type '{assetTypeName}' to mark it as an asset."); - } - - if (!(assetType is DataTypeWithMembers assetTypeWithMembers)) - { - throw new TestFailedException($"Type of asset '{assetTypeName}' needs to be struct or union."); - } - - var assetInfo = state.Repository.GetInformationFor(assetTypeWithMembers); - if (assetInfo == null) - { - throw new TestFailedException($"Could not find information for type '{assetTypeName}' to mark it as an asset."); - } - - var enumEntryName = NextMatch(AssetEnumEntryToken); - var enumEntry = state.Repository.GetAllEnums() - .SelectMany(_enum => _enum.Members) - .FirstOrDefault(member => member.Name.Equals(enumEntryName, StringComparison.CurrentCultureIgnoreCase)); - - assetInfo.AssetEnumEntry = enumEntry ?? throw new TestFailedException( - $"Could not find enum entry '{enumEntryName}' as an asset type index for asset type '{assetTypeName}'."); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestBlock.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestBlock.cs deleted file mode 100644 index ee72cb86..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestBlock.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Linq; -using ZoneCodeGenerator.Domain.FastFileStructure; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestBlock : AbstractTokenTest - { - private const string BlockTypeToken = "type"; - private const string BlockEnumMemberToken = "enumEntry"; - private const string DefaultToken = "default"; - - private static readonly TokenMatcher[] matchers = { - new MatcherLiteral("block"), - new MatcherName().WithName(BlockTypeToken), - new MatcherName().WithName(BlockEnumMemberToken), - new MatcherGroupOptional( - new MatcherLiteral("default").WithName(DefaultToken) - ), - new MatcherLiteral(";") - }; - - public TestBlock() : base(matchers) - { - - } - - protected override void ProcessMatch(ICommandParserState state) - { - var blockEnumEntryName = NextMatch(BlockEnumMemberToken); - var blockEnumEntry = state.Repository.GetAllEnums() - .SelectMany(_enum => _enum.Members) - .FirstOrDefault(member => member.Name.Equals(blockEnumEntryName)); - if (blockEnumEntry == null) - { - throw new TestFailedException($"Could not find enum entry '{blockEnumEntryName}' for block."); - } - - var blockTypeInput = NextMatch(BlockTypeToken); - if (!Enum.TryParse(blockTypeInput, true, out FastFileBlock.Type blockType)) - { - var blockTypeValues = Enum.GetValues(typeof(FastFileBlock.Type)).OfType() - .Select(type => type.ToString()); - - throw new TestFailedException($"Unknown fastfile block type '{blockTypeInput}'. Must be one of the following: {string.Join(", ", blockTypeValues)}"); - } - - var block = new FastFileBlock(blockEnumEntry.Name, blockEnumEntry.Value, blockType, HasMatcherTokens(DefaultToken)); - - state.FastFileBlocks.Add(block); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestCondition.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestCondition.cs deleted file mode 100644 index 91f646a2..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestCondition.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Evaluation; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestCondition : TestWithEvaluation - { - private StructureInformation referencedType; - - private const string TagAlways = "always"; - private const string TagNever = "never"; - private const string TypeNameToken = "typeName"; - - // set condition (always | never | ); - private static readonly TokenMatcher[] matchers = - { - new MatcherLiteral("set"), - new MatcherLiteral("condition"), - new MatcherTypename().WithName(TypeNameToken), - new MatcherGroupOr( - new MatcherLiteral("always").WithTag(TagAlways), - new MatcherLiteral("never").WithTag(TagNever), - new MatcherWithTag(TagEvaluation) - ), - new MatcherLiteral(";") - }; - - public TestCondition() : base(matchers) - { - } - - protected override void ProcessMatch(ICommandParserState state) - { - var typeName = NextMatch(TypeNameToken); - var typeNameParts = typeName.Split(new[] {"::"}, StringSplitOptions.None); - - if (state.DataTypeInUse != null - && state.GetMembersFromParts(typeNameParts, state.DataTypeInUse, out var typeMembers)) - { - referencedType = state.DataTypeInUse; - } - else if (state.GetTypenameAndMembersFromParts(typeNameParts, out referencedType, out typeMembers)) - { - // Do nothing - } - else - { - throw new TestFailedException($"Could not find type/members '{typeName}'"); - } - - if (typeMembers == null - || !typeMembers.Any()) - { - throw new TestFailedException("Can only set conditions for members and not for types."); - } - - IEvaluation evaluation; - switch (NextTag()) - { - case TagAlways: - evaluation = new OperandStatic(1); - break; - - case TagNever: - evaluation = new OperandStatic(0); - break; - - case TagEvaluation: - evaluation = ProcessEvaluation(state); - break; - - default: - throw new Exception("Unexpected Tag in TestCondition"); - } - - var referencedMember = typeMembers.Last(); - referencedMember.Condition = evaluation; - } - - protected override IEnumerable GetUsedTypes(ICommandParserState state) - { - if (state.DataTypeInUse != null - && state.DataTypeInUse != referencedType) - { - return new[] {state.DataTypeInUse, referencedType}; - } - - return new[] {referencedType}; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestCount.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestCount.cs deleted file mode 100644 index f67f6798..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestCount.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Evaluation; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestCount : TestWithEvaluation - { - private StructureInformation referencedType; - private const string TokenTypeName = "typeName"; - private const string TokenPointerResolve = "pointerResolve"; - private const string TokenArrayIndex = "arrayIndex"; - - // set count ; - private static readonly TokenMatcher[] matchers = - { - new MatcherLiteral("set"), - new MatcherLiteral("count"), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.ZeroOneMultiple, - new MatcherLiteral("*").WithName(TokenPointerResolve)), - new MatcherTypename().WithName(TokenTypeName), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.ZeroOneMultiple, - new MatcherArray().WithName(TokenArrayIndex)), - new MatcherWithTag(TagEvaluation), - new MatcherLiteral(";") - }; - - public TestCount() : base(matchers) - { - } - - private void SetCountByArrayIndex(MemberInformation referencedMember, ReferenceTypePointer pointer, - IEvaluation evaluation) - { - if (pointer.CountByArrayIndex == null) - { - pointer.CountByArrayIndex = new IEvaluation[referencedMember.Member.VariableType.References - .OfType().Select(array => array.ArraySize).Aggregate((i1, i2) => i1 * i2)]; - } - - var arraySizes = referencedMember.Member.VariableType.References - .OfType() - .Select(array => array.ArraySize) - .ToList(); - var index = 0; - var indexDepth = 0; - string s; - while ((s = NextMatch(TokenArrayIndex)) != null) - { - var specifiedIndex = int.Parse(s); - - if (specifiedIndex >= arraySizes[indexDepth]) - { - throw new TestFailedException($"Specified index '{specifiedIndex}' is out of bounds at type '{referencedMember.Parent.Type.FullName}::{referencedMember.Member.Name}'"); - } - - var sizePerIndexInCurrentDepth = arraySizes.Count <= indexDepth + 1 ? - 1 : arraySizes.Skip(indexDepth + 1).Aggregate((i1, i2) => i1 * i2); - - index += specifiedIndex * sizePerIndexInCurrentDepth; - indexDepth++; - } - - pointer.CountByArrayIndex[index] = evaluation; - } - - protected override void ProcessMatch(ICommandParserState state) - { - var typeName = NextMatch(TokenTypeName); - var typeNameParts = typeName.Split(new[] {"::"}, StringSplitOptions.None); - if (state.DataTypeInUse != null - && state.GetMembersFromParts(typeNameParts, state.DataTypeInUse, out var typeMembers)) - { - referencedType = state.DataTypeInUse; - } - else if (state.GetTypenameAndMembersFromParts(typeNameParts, out referencedType, out typeMembers)) - { - // Do nothing - } - else - { - throw new TestFailedException($"Could not find type/members '{typeName}'"); - } - - if (typeMembers == null - || !typeMembers.Any()) - { - throw new TestFailedException("Can only set count for members and not for types."); - } - - if (!NextTag().Equals(TagEvaluation)) - throw new Exception("Expected first count tag to be a calculation statement"); - - var evaluation = ProcessEvaluation(state); - - var referencedMember = typeMembers.Last(); - var reference = referencedMember.Member.VariableType.References - .OfType() - .Skip(GetMatcherTokenCount(TokenPointerResolve)) - .FirstOrDefault(); - - if (reference != null) - { - if (HasMatcherTokens(TokenArrayIndex)) - { - SetCountByArrayIndex(referencedMember, reference, evaluation); - } - else - { - reference.Count = evaluation; - } - } - else - { - throw new TestFailedException( - $"Member '{referencedMember.Member.Name}' of type '{referencedMember.Member.VariableType.Type.FullName}' cannot have its count set due to it not having a pointer reference"); - } - } - - protected override IEnumerable GetUsedTypes(ICommandParserState state) - { - if (state.DataTypeInUse != null - && state.DataTypeInUse != referencedType) - { - return new[] {state.DataTypeInUse, referencedType}; - } - - return new[] {referencedType}; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestGame.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestGame.cs deleted file mode 100644 index 38b2a6ab..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestGame.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using ZoneCodeGenerator.Domain.FastFileStructure; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestGame : AbstractTokenTest - { - private const string GameNameToken = "name"; - - private static readonly TokenMatcher[] matchers = { - new MatcherLiteral("game"), - new MatcherName().WithName(GameNameToken), - new MatcherLiteral(";") - }; - - public TestGame() : base(matchers) - { - - } - - protected override void ProcessMatch(ICommandParserState state) - { - if (!string.IsNullOrEmpty(state.Game)) - { - throw new TestFailedException($"Game has already been set with value '{state.Game}'"); - } - - state.Game = NextMatch(GameNameToken); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestName.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestName.cs deleted file mode 100644 index ec541347..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestName.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Linq; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestName : AbstractTokenTest - { - private const string MemberTypeNameToken = "name"; - - private static readonly TokenMatcher[] matchers = { - new MatcherLiteral("set"), - new MatcherLiteral("name"), - new MatcherTypename().WithName(MemberTypeNameToken), - new MatcherLiteral(";") - }; - - public TestName() : base(matchers) - { - - } - - protected override void ProcessMatch(ICommandParserState state) - { - var typeName = NextMatch(MemberTypeNameToken); - var typeNameParts = typeName.Split(new[] { "::" }, StringSplitOptions.None); - StructureInformation structure; - - if (state.DataTypeInUse != null && - state.GetMembersFromParts(typeNameParts, state.DataTypeInUse, out var memberList)) - { - structure = state.DataTypeInUse; - } - else if (state.GetTypenameAndMembersFromParts(typeNameParts, out structure, out memberList)) - { - // Do nothing - } - else - { - throw new TestFailedException($"Could not find type '{typeName}'."); - } - - if (memberList == null || !memberList.Any()) - { - throw new TestFailedException("Need to specify a member when trying to set to a structure name."); - } - - for (var i = 0; i < memberList.Count - 1; i++) - { - if (memberList[i].Computations.ContainsNonEmbeddedReference) - { - throw new TestFailedException("Can only add embedded members to name chain."); - } - } - - if (!memberList[memberList.Count - 1].IsString) - { - throw new TestFailedException("Final name member must be a string."); - } - - structure.NameChain = memberList; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestReorder.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestReorder.cs deleted file mode 100644 index 317d1dfc..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestReorder.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestReorder : AbstractTokenTest - { - private const string TypeNameToken = "typeName"; - private const string ReorderMemberNameToken = "member"; - private const string TokenFindFirst = "findFirst"; - - private static readonly TokenMatcher[] matchers = - { - new MatcherLiteral("reorder"), - new MatcherGroupOptional(new MatcherTypename().WithName(TypeNameToken)), - new MatcherLiteral(":"), - new MatcherGroupOptional(new MatcherLiteral(".", ".", ".").WithName(TokenFindFirst)), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.OneMultiple, - new MatcherName().WithName(ReorderMemberNameToken)), - new MatcherLiteral(";") - }; - - public TestReorder() : base(matchers) - { - } - - protected override void ProcessMatch(ICommandParserState state) - { - StructureInformation typeToReorder; - - if (HasMatcherTokens(TypeNameToken)) - { - // If there was a type specified then use it to reorder. - var typeName = NextMatch(TypeNameToken); - var typeNameParts = typeName.Split(new[] {"::"}, StringSplitOptions.None); - - if (!state.GetTypenameAndMembersFromParts(typeNameParts, out typeToReorder, out var memberList)) - { - throw new TestFailedException($"Could not parse type with name '{typeName}'."); - } - - // If there were members specified, use the type of the member. - if (memberList.Any()) - { - var lastMember = memberList.Last(); - - typeToReorder = lastMember.StructureType - ?? throw new TestFailedException( - $"Cannot reorder type of '{lastMember.Member.Name}'. Type is not a data type with members."); - } - } - else if (state.DataTypeInUse != null) - { - // If there was no type specified try to use the one currently in use. - typeToReorder = state.DataTypeInUse; - } - else - { - // No type specified and no type in use. We don't know what to reorder. - throw new TestFailedException("A type to reorder needs to be specified."); - } - - // Create a pool of all members that have not been sorted yet. - var memberPool = new List(typeToReorder.OrderedMembers); - - // Create a list that will be the sorted list at the end. - var sortedMembers = new List(memberPool.Count); - - if (HasMatcherTokens(TokenFindFirst)) - { - var firstMemberName = NextMatch(ReorderMemberNameToken); - var firstMember = - memberPool.FirstOrDefault(information => information.Member.Name.Equals(firstMemberName)); - - if (firstMember == null) - { - throw new TestFailedException( - $"Cannot find member with name '{firstMemberName}' in type '{typeToReorder.Type.FullName}'."); - } - - var firstMemberIndex = memberPool.IndexOf(firstMember); - sortedMembers.AddRange(memberPool.GetRange(0, firstMemberIndex + 1)); - memberPool.RemoveRange(0, firstMemberIndex + 1); - } - - string nextMemberName; - while ((nextMemberName = NextMatch(ReorderMemberNameToken)) != null) - { - var nextMember = - memberPool.FirstOrDefault(information => information.Member.Name.Equals(nextMemberName)); - - if (nextMember != null) - { - sortedMembers.Add(nextMember); - memberPool.Remove(nextMember); - } - else - { - nextMember = - sortedMembers.FirstOrDefault(information => information.Member.Name.Equals(nextMemberName)); - - if (nextMember == null) - { - throw new TestFailedException( - $"Cannot find member with name '{nextMemberName}' in type '{typeToReorder.Type.FullName}'."); - } - - sortedMembers.Remove(nextMember); - sortedMembers.Add(nextMember); - } - } - - // Insert members that have not been mentioned at the end. - sortedMembers.AddRange(memberPool); - - // Apply new members to the StructureInformation - typeToReorder.OrderedMembers = sortedMembers; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestReusable.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestReusable.cs deleted file mode 100644 index bdb6872e..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestReusable.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestReusable : AbstractTokenTest - { - private const string MemberTypeNameToken = "name"; - - private static readonly TokenMatcher[] matchers = { - new MatcherLiteral("set"), - new MatcherLiteral("reusable"), - new MatcherTypename().WithName(MemberTypeNameToken), - new MatcherLiteral(";") - }; - - public TestReusable() : base(matchers) - { - - } - - protected override void ProcessMatch(ICommandParserState state) - { - var typeName = NextMatch(MemberTypeNameToken); - var typeNameParts = typeName.Split(new[] { "::" }, StringSplitOptions.None); - - if (state.DataTypeInUse != null && - state.GetMembersFromParts(typeNameParts, state.DataTypeInUse, out var memberList)) - { - // Do nothing - } - else if (state.GetTypenameAndMembersFromParts(typeNameParts, out _, out memberList)) - { - // Do nothing - } - else - { - throw new TestFailedException($"Could not find type '{typeName}'."); - } - - if (memberList == null || !memberList.Any()) - { - throw new TestFailedException("Need to specify a member when trying to set to a string."); - } - - var lastMember = memberList.Last(); - - if (!lastMember.Computations.ContainsNonEmbeddedReference) - { - throw new TestFailedException($"Specified member '{lastMember.Member.Name}' is not a pointer reference and therefore cannot be reusable."); - } - - lastMember.IsReusable = true; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestScriptString.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestScriptString.cs deleted file mode 100644 index 797a7049..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestScriptString.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestScriptString : AbstractTokenTest - { - private const string MemberTypeNameToken = "name"; - - private static readonly TokenMatcher[] matchers = { - new MatcherLiteral("set"), - new MatcherLiteral("scriptstring"), - new MatcherTypename().WithName(MemberTypeNameToken), - new MatcherLiteral(";") - }; - - public TestScriptString() : base(matchers) - { - - } - - protected override void ProcessMatch(ICommandParserState state) - { - var typeName = NextMatch(MemberTypeNameToken); - var typeNameParts = typeName.Split(new[] { "::" }, StringSplitOptions.None); - - if (state.DataTypeInUse != null && - state.GetMembersFromParts(typeNameParts, state.DataTypeInUse, out var memberList)) - { - // Do nothing - } - else if (state.GetTypenameAndMembersFromParts(typeNameParts, out _, out memberList)) - { - // Do nothing - } - else - { - throw new TestFailedException($"Could not find type '{typeName}'."); - } - - if (memberList == null || !memberList.Any()) - { - throw new TestFailedException("Need to specify a member when trying to set to a script string."); - } - - var lastMember = memberList.Last(); - if (!(lastMember.Member.VariableType.Type is DataTypeBaseType)) - { - throw new TestFailedException($"Specified member '{lastMember.Member.Name}' is not a base type and therefore cannot be a script string."); - } - - lastMember.IsScriptString = true; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestSetBlock.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestSetBlock.cs deleted file mode 100644 index 74288e35..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestSetBlock.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestSetBlock : AbstractTokenTest - { - private const string TokenTypeName = "name"; - private const string TokenBlockEnumEntry = "block"; - - private static readonly TokenMatcher[] matchers = - { - new MatcherLiteral("set"), - new MatcherLiteral("block"), - new MatcherGroupOr(new MatcherGroupAnd( - new MatcherTypename().WithName(TokenTypeName), - new MatcherName().WithName(TokenBlockEnumEntry) - ), - new MatcherName().WithName(TokenBlockEnumEntry)), - new MatcherLiteral(";") - }; - - public TestSetBlock() : base(matchers) - { - } - - protected override void ProcessMatch(ICommandParserState state) - { - var typeName = NextMatch(TokenTypeName); - - StructureInformation typeInfo; - List memberList; - - if (typeName != null) - { - var typeNameParts = typeName.Split(new[] { "::" }, StringSplitOptions.None); - if (state.DataTypeInUse != null && - state.GetMembersFromParts(typeNameParts, state.DataTypeInUse, out memberList)) - { - typeInfo = state.DataTypeInUse; - } - else if (state.GetTypenameAndMembersFromParts(typeNameParts, out typeInfo, out memberList)) - { - // Do nothing - } - else - { - throw new TestFailedException($"Could not find type '{typeName}'."); - } - } - else - { - typeInfo = state.DataTypeInUse; - memberList = new List(); - - if(typeInfo == null) - throw new TestFailedException("Must specify a type or member."); - } - - var blockName = NextMatch(TokenBlockEnumEntry); - var block = state.FastFileBlocks - .FirstOrDefault(fastFileBlock => fastFileBlock.Name.Equals(blockName)); - - if (block == null) - throw new TestFailedException($"Could not find fastfile block with name '{blockName}'"); - - if (memberList.Any()) - { - var member = memberList.Last(); - member.Block = block; - } - else - { - typeInfo.Block = block; - } - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestString.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestString.cs deleted file mode 100644 index 1bd4bb76..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestString.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestString : AbstractTokenTest - { - private const string MemberTypeNameToken = "name"; - - private static readonly TokenMatcher[] matchers = { - new MatcherLiteral("set"), - new MatcherLiteral("string"), - new MatcherTypename().WithName(MemberTypeNameToken), - new MatcherLiteral(";") - }; - - public TestString() : base(matchers) - { - - } - - protected override void ProcessMatch(ICommandParserState state) - { - var typeName = NextMatch(MemberTypeNameToken); - var typeNameParts = typeName.Split(new[] { "::" }, StringSplitOptions.None); - - if (state.DataTypeInUse != null && - state.GetMembersFromParts(typeNameParts, state.DataTypeInUse, out var memberList)) - { - // Do nothing - } - else if (state.GetTypenameAndMembersFromParts(typeNameParts, out _, out memberList)) - { - // Do nothing - } - else - { - throw new TestFailedException($"Could not find type '{typeName}'."); - } - - if (memberList == null || !memberList.Any()) - { - throw new TestFailedException("Need to specify a member when trying to set to a string."); - } - - var lastMember = memberList.Last(); - if (lastMember.Member.VariableType.Type != DataTypeBaseType.CHAR) - { - throw new TestFailedException($"Specified member '{lastMember.Member.Name}' is not char type and therefore cannot be a string."); - } - - if (!lastMember.Computations.ContainsSinglePointerReference) - { - throw new TestFailedException($"Specified member '{lastMember.Member.Name}' is a single pointer reference and therefore cannot be a string."); - } - - lastMember.IsString = true; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestUse.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestUse.cs deleted file mode 100644 index a990ed0f..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestUse.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - class TestUse : AbstractTokenTest - { - private const string TypeNameToken = "typeName"; - - private static readonly TokenMatcher[] matchers = { - new MatcherLiteral("use"), - new MatcherTypename().WithName(TypeNameToken), - new MatcherLiteral(";") - }; - - public TestUse() : base(matchers) - { - - } - - protected override void ProcessMatch(ICommandParserState state) - { - var typeName = NextMatch(TypeNameToken); - var dataTypeToUse = state.Repository.GetDataTypeByName(typeName); - - if (dataTypeToUse == null) - { - throw new TestFailedException($"Could not find data type '{typeName}'"); - } - - if (!(dataTypeToUse is DataTypeWithMembers dataTypeWithMembersToUse)) - { - throw new TestFailedException($"To use data type '{typeName}' it must either be a struct or a union."); - } - - var dataTypeToUseInformation = state.Repository.GetInformationFor(dataTypeWithMembersToUse); - - if (dataTypeToUseInformation == null) - { - throw new Exception($"Could not find information for type '{dataTypeWithMembersToUse.FullName}'"); - } - - state.DataTypeInUse = dataTypeToUseInformation; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestWithEvaluation.cs b/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestWithEvaluation.cs deleted file mode 100644 index fd90c7f5..00000000 --- a/src/ZoneCodeGenerator/Parsing/CommandFile/Tests/TestWithEvaluation.cs +++ /dev/null @@ -1,251 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Evaluation; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing.CommandFile.Tests -{ - abstract class TestWithEvaluation : AbstractTokenTest - { - private const string TagOperand = "operand"; - private const string TagOperationType = "operationType"; - private const string TokenOperationType = "operationTypeToken"; - - // Evaluation Sub-Tags - private const string TagEvaluationParenthesis = "evaluationParenthesis"; - private const string TagEvaluationParenthesisEnd = "evaluationParenthesisEnd"; - private const string TagEvaluationNot = "evaluationNot"; - private const string TagEvaluationOperation = "evaluationOperation"; - - // Operand Sub-Tags - private const string TagOperandNumber = "operandNumber"; - private const string TagOperandTypename = "operandTypename"; - private const string TokenOperandNumber = "operandNumberToken"; - private const string TokenOperandTypename = "operandTypenameToken"; - private const string TokenOperandArray = "operandArrayToken"; - - // OperandArray Sub-Tags - private const string TagOperandArray = "operandArray"; - private const string TagOperandArrayEnd = "operandArrayEnd"; - - // Visible to children - protected const string TagEvaluation = "evaluation"; - - private static readonly TokenMatcher operandArray = new MatcherGroupAnd( - new MatcherLiteral("["), - new MatcherWithTag(TagEvaluation), - new MatcherLiteral("]").WithTag(TagOperandArrayEnd) - ).WithTag(TagOperandArray); - - // operand ::= * | - private static readonly TokenMatcher operand = new MatcherGroupOr( - new MatcherGroupAnd( - new MatcherTypename().WithName(TokenOperandTypename), - new MatcherGroupLoop(MatcherGroupLoop.LoopMode.ZeroOneMultiple, new MatcherWithTag(TagOperandArray)) - ).WithTag(TagOperandTypename), - new MatcherNumber().WithName(TokenOperandNumber).WithTag(TagOperandNumber) - ).WithTag(TagOperand); - - // operationType ::= + | - | * | / | << | >> | ... - private static readonly TokenMatcher operationType = new MatcherGroupOr( - OperationType.Types - .OrderByDescending(type => type.Syntax.Length) - .Select(type => new MatcherLiteral(type.Syntax.ToCharArray().Select(c => c.ToString()).ToArray()).WithName(TokenOperationType)) - .Cast().ToArray() - ).WithTag(TagOperationType); - - // evaluation ::= ( ) | [ ] - private static readonly TokenMatcher evaluation = new MatcherGroupAnd( - new MatcherGroupOr( - new MatcherGroupAnd( - new MatcherGroupOptional(new MatcherLiteral("!").WithTag(TagEvaluationNot)), - new MatcherLiteral("("), - new MatcherWithTag(TagEvaluation), - new MatcherLiteral(")").WithTag(TagEvaluationParenthesisEnd) - ).WithTag(TagEvaluationParenthesis), - new MatcherWithTag(TagOperand) - ), - new MatcherGroupOptional(new MatcherGroupAnd( - new MatcherWithTag(TagOperationType), - new MatcherWithTag(TagEvaluation) - ).WithTag(TagEvaluationOperation)) - - ).WithTag(TagEvaluation); - - protected TestWithEvaluation(TokenMatcher[] matchers) : base(matchers) - { - AddTaggedMatcher(operandArray); - AddTaggedMatcher(operand); - AddTaggedMatcher(operationType); - AddTaggedMatcher(evaluation); - } - - private IEvaluation ProcessOperandNumber(ICommandParserState state) - { - var numberString = NextMatch(TokenOperandNumber); - return new OperandStatic(int.Parse(numberString)); - } - - protected abstract IEnumerable GetUsedTypes(ICommandParserState state); - - private IEvaluation ProcessOperandTypename(ICommandParserState state) - { - var typenameString = NextMatch(TokenOperandTypename); - var arrayIndexEvaluations = new List(); - - while (PeekTag().Equals(TagOperandArray)) - { - NextTag(); - - if (NextTag() != TagEvaluation) - throw new Exception("Expected evaluation tag @ Operand"); - - arrayIndexEvaluations.Add(ProcessEvaluation(state)); - - if (NextTag() != TagOperandArrayEnd) - throw new Exception("Expected operand array end tag @ Operand"); - } - - var nameParts = typenameString.Split(new[] { "::" }, StringSplitOptions.None); - - if (nameParts.Length == 1 && arrayIndexEvaluations.Count == 0) - { - var enumMember = state.Repository.GetAllEnums().SelectMany(_enum => _enum.Members) - .FirstOrDefault(member => member.Name.Equals(nameParts[0])); - - if(enumMember != null) - { - return new OperandStatic(enumMember); - } - } - - List referencedMemberChain = null; - - var referencedType = GetUsedTypes(state) - .FirstOrDefault(usedType => state.GetMembersFromParts(nameParts, usedType, out referencedMemberChain)); - - if (referencedType == null) - { - if (!state.GetTypenameAndMembersFromParts(nameParts, out referencedType, - out referencedMemberChain)) - { - throw new TestFailedException($"Could not evaluate '{typenameString}'."); - } - } - - var operandDynamic = new OperandDynamic(referencedType, referencedMemberChain); - foreach (var indexEvaluation in arrayIndexEvaluations) - { - operandDynamic.ArrayIndices.Add(indexEvaluation); - } - - return operandDynamic; - } - - private IEvaluation ProcessOperand(ICommandParserState state) - { - var operandTypeTag = NextTag(); - - if (operandTypeTag.Equals(TagOperandNumber)) - { - return ProcessOperandNumber(state); - } - - if(operandTypeTag.Equals(TagOperandTypename)) - { - return ProcessOperandTypename(state); - } - - throw new Exception("Unknown Operand Type"); - } - - private OperationType ProcessOperationType(ICommandParserState state) - { - var operationMatch = NextMatch(TokenOperationType); - - return OperationType.Types.First(type => type.Syntax.Equals(operationMatch)); - } - - private IEvaluation ProcessEvaluationInParenthesis(ICommandParserState state) - { - var isNegated = false; - if (NextTag().Equals(TagEvaluationNot)) - { - NextTag(); - isNegated = true; - } - - var processedEvaluation = ProcessEvaluation(state); - - if (NextTag() != TagEvaluationParenthesisEnd) - throw new Exception("Expected parenthesis end tag @ EvaluationInParenthesis"); - - return !isNegated - ? processedEvaluation - : new Operation(processedEvaluation, new OperandStatic(0), OperationType.OperationEquals); - } - - protected IEvaluation ProcessEvaluation(ICommandParserState state) - { - var operands = new List(); - var operators = new List(); - - while (true) - { - IEvaluation firstStatementPart; - var tag = NextTag(); - switch (tag) - { - case TagEvaluationParenthesis: - firstStatementPart = ProcessEvaluationInParenthesis(state); - break; - - case TagOperand: - firstStatementPart = ProcessOperand(state); - break; - - default: - throw new Exception($"Invalid followup tag '{tag}' @ Evaluation"); - } - operands.Add(firstStatementPart); - - if (PeekTag() == TagEvaluationOperation) - { - NextTag(); - - if (NextTag() != TagOperationType) - throw new Exception("Expected operationType tag @ Evaluation"); - - operators.Add(ProcessOperationType(state)); - - if (NextTag() != TagEvaluation) - throw new Exception("Expected EvaluationTag @ Evaluation"); - } - else - { - break; - } - } - - while (operators.Any()) - { - var nextOperator = operators - .OrderBy(type => type.Precedence) - .First(); - var operatorIndex = operators.IndexOf(nextOperator); - - var operation = new Operation(operands[operatorIndex], operands[operatorIndex + 1], nextOperator); - operands.RemoveRange(operatorIndex, 2); - operands.Insert(operatorIndex, operation); - operators.RemoveAt(operatorIndex); - } - - return operands[0]; - } - } -} \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Parsing/ICommentProcessor.cs b/src/ZoneCodeGenerator/Parsing/ICommentProcessor.cs deleted file mode 100644 index d10f992e..00000000 --- a/src/ZoneCodeGenerator/Parsing/ICommentProcessor.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ZoneCodeGenerator.Parsing -{ - interface ICommentProcessor - { - string RemoveComments(string line); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/IDataPostProcessor.cs b/src/ZoneCodeGenerator/Parsing/IDataPostProcessor.cs deleted file mode 100644 index cba70750..00000000 --- a/src/ZoneCodeGenerator/Parsing/IDataPostProcessor.cs +++ /dev/null @@ -1,9 +0,0 @@ -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGenerator.Parsing -{ - interface IDataPostProcessor - { - bool PostProcess(IDataRepository repository); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/IIncludingParsingStream.cs b/src/ZoneCodeGenerator/Parsing/IIncludingParsingStream.cs deleted file mode 100644 index b53b8f17..00000000 --- a/src/ZoneCodeGenerator/Parsing/IIncludingParsingStream.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ZoneCodeGenerator.Parsing -{ - interface IIncludingParsingStream : IParsingFileStream - { - /// - /// Pushes back current file and the position in it to read from another file now instead. - /// After completion returns back to the previous file. - /// - /// - void IncludeFile(string filename); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/ILexer.cs b/src/ZoneCodeGenerator/Parsing/ILexer.cs deleted file mode 100644 index bf722c68..00000000 --- a/src/ZoneCodeGenerator/Parsing/ILexer.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace ZoneCodeGenerator.Parsing -{ - interface ILexer - { - int CurrentLine { get; } - string CurrentFile { get; } - bool IsEndOfStream { get; } - int CachedTokenCount { get; } - - string NextToken(); - string PeekToken(int index = 0); - void SkipTokens(int count); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/IParserState.cs b/src/ZoneCodeGenerator/Parsing/IParserState.cs deleted file mode 100644 index 1a439bfe..00000000 --- a/src/ZoneCodeGenerator/Parsing/IParserState.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing -{ - interface IParserState where TState : IParserState - { - IEnumerable> GetTests(); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/IParsingFileStream.cs b/src/ZoneCodeGenerator/Parsing/IParsingFileStream.cs deleted file mode 100644 index 32679b0a..00000000 --- a/src/ZoneCodeGenerator/Parsing/IParsingFileStream.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; - -namespace ZoneCodeGenerator.Parsing -{ - interface IParsingFileStream : IDisposable - { - /// - /// Whether the end of the stream has been reached. - /// - bool EndOfStream { get; } - - /// - /// The current filename. - /// - string Filename { get; } - - /// - /// The current line in the current file. - /// - int Line { get; } - - /// - /// Reads a line from the current header and returns it. - /// - /// - string ReadLine(); - - /// - /// Closes this and all underlying streams. - /// - void Close(); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Impl/CommentProcessor.cs b/src/ZoneCodeGenerator/Parsing/Impl/CommentProcessor.cs deleted file mode 100644 index fb6b5668..00000000 --- a/src/ZoneCodeGenerator/Parsing/Impl/CommentProcessor.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; - -namespace ZoneCodeGenerator.Parsing.Impl -{ - class CommentProcessor : ICommentProcessor - { - private const string LineCommentStart = "//"; - private const string BlockCommentStart = "/*"; - private const string BlockCommentEnd = "*/"; - - private bool inComment; - - public CommentProcessor() - { - inComment = false; - } - - public string RemoveComments(string line) - { - if (inComment) - { - var idx = line.IndexOf(BlockCommentEnd, StringComparison.Ordinal); - - if(idx == -1) - return ""; - - line = line.Substring(idx + BlockCommentEnd.Length); - inComment = false; - } - - var commentIndex = line.IndexOf(LineCommentStart, StringComparison.Ordinal); - if (commentIndex != -1) - line = line.Remove(commentIndex).Trim(); - - while (true) - { - var indexBlockCommentBegin = line.IndexOf(BlockCommentStart, StringComparison.Ordinal); - - if (indexBlockCommentBegin == -1) - break; - - var indexBlockCommentEnd = line.IndexOf(BlockCommentEnd, indexBlockCommentBegin, StringComparison.Ordinal); - - if(indexBlockCommentEnd == -1) - { - line = line.Remove(indexBlockCommentBegin).Trim(); - inComment = true; - break; - } - - line = line.Remove(indexBlockCommentBegin, indexBlockCommentEnd + BlockCommentEnd.Length - indexBlockCommentBegin).Trim(); - } - - return line; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Impl/IncludingStreamFileSystem.cs b/src/ZoneCodeGenerator/Parsing/Impl/IncludingStreamFileSystem.cs deleted file mode 100644 index 392262b2..00000000 --- a/src/ZoneCodeGenerator/Parsing/Impl/IncludingStreamFileSystem.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System.Collections.Generic; -using System.IO; - -namespace ZoneCodeGenerator.Parsing.Impl -{ - class IncludingStreamFileSystem : IIncludingParsingStream - { - private class HeaderStreamState - { - private readonly StreamReader reader; - private readonly Stream stream; - - public string Cwd { get; } - public string Filename { get; } - public int Line { get; private set; } - - public HeaderStreamState(FileStream stream, string filepath) - { - this.stream = stream; - reader = new StreamReader(stream); - - Cwd = Path.GetDirectoryName(filepath); - Filename = Path.GetFileName(filepath); - Line = 1; - } - - public bool EndOfStream => reader.EndOfStream; - - public string ReadLine() - { - Line++; - return reader.ReadLine() ?? ""; - } - - public void Close() - { - reader.Close(); - stream.Close(); - } - } - - private readonly Stack states; - - public IncludingStreamFileSystem(string path) - { - states = new Stack(); - var initialState = new HeaderStreamState(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read), path); - - states.Push(initialState); - } - - public bool EndOfStream => states.Count == 0; - - public string Filename => states.Count == 0 ? "" : State.Filename; - - public int Line => states.Count == 0 ? -1 : State.Line; - - private HeaderStreamState State => states.Count == 0 ? null : states.Peek(); - - public string ReadLine() - { - var state = State; - - if (state == null) - return ""; - - var line = state.ReadLine(); - - if (state.EndOfStream) - { - state.Close(); - states.Pop(); - } - - return line; - } - - public void IncludeFile(string filename) - { - var state = State; - - if (state == null) - return; - - var path = Path.Combine(state.Cwd, filename); - - if (!File.Exists(path)) return; - - var newState = new HeaderStreamState(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read), path); - - states.Push(newState); - } - - public void Close() - { - while (states.Count > 0) - { - states.Pop().Close(); - } - } - - public void Dispose() - { - Close(); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Impl/Lexer.cs b/src/ZoneCodeGenerator/Parsing/Impl/Lexer.cs deleted file mode 100644 index 20bf79c6..00000000 --- a/src/ZoneCodeGenerator/Parsing/Impl/Lexer.cs +++ /dev/null @@ -1,162 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace ZoneCodeGenerator.Parsing.Impl -{ - class Lexer : ILexer - { - private class LexerToken - { - public string Token { get; set; } - public int Row { get; set; } - public string Filename { get; set; } - } - - private static readonly char[] charTokens = { - ';', - ':', - '{', - '}', - ',', - '.', - '=', - '(', - ')', - '*', - '[', - ']', - '<', - '>', - '#', - '&', - '%', - '\"', - '?', - '!', - '+', - '-', - '/', - '\\', - '|' - }; - - private readonly IParsingFileStream fileStream; - - private readonly List tokenCache; - - public bool IsEndOfStream => fileStream.EndOfStream && tokenCache.Count == 0; - public int CachedTokenCount => tokenCache.Count; - - public Lexer(IParsingFileStream fileStream) - { - this.fileStream = fileStream; - tokenCache = new List(); - } - - public int CurrentLine => tokenCache.Count == 0 ? fileStream.Line : tokenCache[0].Row; - - public string CurrentFile => tokenCache.Count == 0 ? fileStream.Filename : tokenCache[0].Filename; - - private static bool IsCharToken(char c) - { - return charTokens.Contains(c); - } - - private void TokenizeLine(string filename, int lineNr, string line) - { - line = line.Trim(); - - while(line.Length > 0) - { - var token = ""; - - while (line.Length > 0) - { - var c = line[0]; - line = line.Substring(1); - - if (char.IsWhiteSpace(c)) - break; - - if (IsCharToken(c)) - { - if(token == "") - { - token += c; - break; - } - else - { - line = c + line; - break; - } - } - - token += c; - } - - tokenCache.Add(new LexerToken() - { - Token = token, - Row = lineNr, - Filename = filename - }); - line = line.TrimStart(); - } - } - - public string NextToken() - { - while(tokenCache.Count == 0) - { - if (fileStream.EndOfStream) - { - return ""; - } - - TokenizeLine(fileStream.Filename, fileStream.Line, fileStream.ReadLine()); - } - - var token = tokenCache[0].Token; - tokenCache.RemoveAt(0); - return token; - } - - public string PeekToken(int index = 0) - { - if (index < 0) - return ""; - - while (tokenCache.Count <= index) - { - if (fileStream.EndOfStream) - { - return ""; - } - - TokenizeLine(fileStream.Filename, fileStream.Line, fileStream.ReadLine()); - } - - return tokenCache[index].Token; - } - - public void SkipTokens(int count) - { - if (count < 0) - return; - - while (tokenCache.Count < count) - { - if (fileStream.EndOfStream) - { - tokenCache.Clear(); - return; - } - - TokenizeLine(fileStream.Filename, fileStream.Line, fileStream.ReadLine()); - } - - tokenCache.RemoveRange(0, count); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/BaseMatcher.cs b/src/ZoneCodeGenerator/Parsing/Matching/BaseMatcher.cs deleted file mode 100644 index ea926cb5..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/BaseMatcher.cs +++ /dev/null @@ -1,66 +0,0 @@ -namespace ZoneCodeGenerator.Parsing.Matching -{ - abstract class BaseMatcher : TokenMatcher - { - protected class MatchingResult - { - public bool Successful { get; } - public int TokensConsumed { get; } - - public MatchingResult(bool successful, int tokensConsumed) - { - Successful = successful; - TokensConsumed = tokensConsumed; - } - } - - private string name; - private string output; - private bool consuming; - - protected BaseMatcher() - { - name = null; - consuming = true; - output = ""; - } - - protected abstract MatchingResult Matches(MatchingContext context, int tokenOffset); - - protected void SetMatcherOutput(string text) - { - output = text; - } - - public BaseMatcher WithName(string tokenName) - { - name = tokenName; - return this; - } - - public BaseMatcher NonConsuming() - { - consuming = false; - return this; - } - - protected override TokenMatchingResult PerformTest(MatchingContext context, int tokenOffset) - { - var match = Matches(context, tokenOffset); - - var success = match.Successful; - var consumedTokens = success && consuming ? match.TokensConsumed : 0; - - var result = new TokenMatchingResult(success, consumedTokens); - - if (success) - { - if (name != null) - result.AddNamedMatch(name, output); - result.AppendTag(Tag); - } - - return result; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/GroupMatcher.cs b/src/ZoneCodeGenerator/Parsing/Matching/GroupMatcher.cs deleted file mode 100644 index a02a4c59..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/GroupMatcher.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ZoneCodeGenerator.Parsing.Matching -{ - abstract class GroupMatcher : TokenMatcher - { - public TokenMatcher[] Matchers { get; } - protected GroupMatcher(TokenMatcher[] matchers) - { - Matchers = matchers; - } - - protected abstract override TokenMatchingResult PerformTest(MatchingContext context, int tokenOffset); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherArray.cs b/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherArray.cs deleted file mode 100644 index 67f26dbc..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherArray.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Globalization; -using System.Text.RegularExpressions; - -namespace ZoneCodeGenerator.Parsing.Matching.Matchers -{ - class MatcherArray : BaseMatcher - { - private static readonly Regex decimalNumberRegex = new Regex(@"^[0-9]+$"); - private static readonly Regex hexNumberRegex = new Regex(@"^0x([0-9a-fA-F]+)$"); - private static readonly Regex nameRegex = new Regex(@"^[a-zA-Z_$][a-zA-Z0-9_$]*$"); - - protected override MatchingResult Matches(MatchingContext context, int tokenOffset) - { - var lexer = context.Lexer; - - if (lexer.PeekToken(tokenOffset++) != "[") - return new MatchingResult(false, 0); - - var token = lexer.PeekToken(tokenOffset++); - - if (decimalNumberRegex.IsMatch(token)) - { - SetMatcherOutput(token); - } - else if (hexNumberRegex.IsMatch(token)) - { - SetMatcherOutput(int.Parse(hexNumberRegex.Match(token).Groups[1].Value, NumberStyles.HexNumber).ToString()); - } - else if (nameRegex.IsMatch(token)) - { - SetMatcherOutput(token); - } - else - { - return new MatchingResult(false, 0); - } - - return lexer.PeekToken(tokenOffset) != "]" ? new MatchingResult(false, 0) - : new MatchingResult(true, 3); - } - - protected override string GetIdentifier() - { - return "Array"; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupAnd.cs b/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupAnd.cs deleted file mode 100644 index 61de793a..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupAnd.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; - -namespace ZoneCodeGenerator.Parsing.Matching.Matchers -{ - class MatcherGroupAnd : GroupMatcher - { - public MatcherGroupAnd(params TokenMatcher[] matchers) : base(matchers) - { - if(matchers.Length == 0) - throw new ArgumentException("A matcher group is supposed to have matchers."); - } - - protected override TokenMatchingResult PerformTest(MatchingContext context, int tokenOffset) - { - var result = new TokenMatchingResult(true, 0); - result.AppendTag(Tag); - - foreach(var matcher in Matchers) - { - var matcherResult = matcher.Test(context, tokenOffset + result.ConsumedTokenCount); - - if (matcherResult.Successful) - { - matcherResult.CopyTo(result); - } - else - { - return new TokenMatchingResult(false, 0); - } - } - - return result; - } - - protected override string GetIdentifier() - { - return "GroupAnd"; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupLoop.cs b/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupLoop.cs deleted file mode 100644 index 5f3cfd66..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupLoop.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; - -namespace ZoneCodeGenerator.Parsing.Matching.Matchers -{ - class MatcherGroupLoop : GroupMatcher - { - public enum LoopMode - { - ZeroOneMultiple, - OneMultiple, - Multiple - } - - private readonly TokenMatcher matcher; - private readonly LoopMode mode; - - public MatcherGroupLoop(LoopMode mode, TokenMatcher matcher) : base(new []{matcher}) - { - this.mode = mode; - this.matcher = matcher; - } - - protected override TokenMatchingResult PerformTest(MatchingContext context, int tokenOffset) - { - var successfulResult = new TokenMatchingResult(true, 0); - successfulResult.AppendTag(Tag); - - var matchedTimes = 0; - - while (true) - { - var matcherResult = matcher.Test(context, tokenOffset + successfulResult.ConsumedTokenCount); - - if (!matcherResult.Successful) - break; - - matcherResult.CopyTo(successfulResult); - matchedTimes++; - } - - int minAmountOfMatches; - switch (mode) - { - case LoopMode.ZeroOneMultiple: - minAmountOfMatches = 0; - break; - - case LoopMode.OneMultiple: - minAmountOfMatches = 1; - break; - - case LoopMode.Multiple: - minAmountOfMatches = 2; - break; - default: - throw new ArgumentOutOfRangeException(); - } - - return matchedTimes < minAmountOfMatches - ? new TokenMatchingResult(false, 0) - : successfulResult; - } - - protected override string GetIdentifier() - { - return "GroupLoop"; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupOptional.cs b/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupOptional.cs deleted file mode 100644 index 7e88f5d8..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupOptional.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace ZoneCodeGenerator.Parsing.Matching.Matchers -{ - class MatcherGroupOptional : GroupMatcher - { - private readonly TokenMatcher matcher; - - public MatcherGroupOptional(TokenMatcher matcher) : base(new []{matcher}) - { - this.matcher = matcher; - } - - protected override TokenMatchingResult PerformTest(MatchingContext context, int tokenOffset) - { - var result = matcher.Test(context, tokenOffset); - - if (!result.Successful) - { - result = new TokenMatchingResult(true, 0); - } - - result.PrependTag(Tag); - return result; - } - - protected override string GetIdentifier() - { - return "GroupOptional"; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupOr.cs b/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupOr.cs deleted file mode 100644 index d2e9e9e3..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherGroupOr.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; - -namespace ZoneCodeGenerator.Parsing.Matching.Matchers -{ - class MatcherGroupOr : GroupMatcher - { - private readonly TokenMatcher[] matchers; - - public MatcherGroupOr(params TokenMatcher[] matchers) : base(matchers) - { - if(matchers.Length == 0) - throw new ArgumentException("A matcher group is supposed to have matchers."); - - this.matchers = matchers; - } - - protected override TokenMatchingResult PerformTest(MatchingContext context, int tokenOffset) - { - foreach(var matcher in matchers) - { - var matcherResult = matcher.Test(context, tokenOffset); - - if (!matcherResult.Successful) continue; - - matcherResult.PrependTag(Tag); - return matcherResult; - } - - return new TokenMatchingResult(false, 0); - } - - protected override string GetIdentifier() - { - return "GroupOr"; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherLiteral.cs b/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherLiteral.cs deleted file mode 100644 index 16702133..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherLiteral.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Text; - -namespace ZoneCodeGenerator.Parsing.Matching.Matchers -{ - class MatcherLiteral : BaseMatcher - { - private readonly string[] literals; - - public MatcherLiteral(params string[] literals) - { - this.literals = literals; - } - - protected override MatchingResult Matches(MatchingContext context, int tokenOffset) - { - var matcherOutputBuilder = new StringBuilder(); - - foreach (var literal in literals) - { - var token = context.Lexer.PeekToken(tokenOffset++); - var isMatch = string.Equals(token, literal); - - if (!isMatch) return new MatchingResult(false, 0); - - matcherOutputBuilder.Append(literal); - } - - SetMatcherOutput(matcherOutputBuilder.ToString()); - return new MatchingResult(true, literals.Length); - } - - protected override string GetIdentifier() - { - return $"Literal(\"{string.Join("", literals)}\")"; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherName.cs b/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherName.cs deleted file mode 100644 index e444820f..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherName.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System.Linq; -using System.Text.RegularExpressions; - -namespace ZoneCodeGenerator.Parsing.Matching.Matchers -{ - class MatcherName : BaseMatcher - { - private static readonly Regex nameRegex = new Regex(@"^[a-zA-Z_$][a-zA-Z0-9_$]*$"); - - private static readonly string[] reservedWords = { - "const", - "int", - "char", - "short", - "long", - "unsigned", - "typedef", - "void", - "static", - "class", - "struct", - "enum", - "union", - "namespace", - "using", - "public", - "protected", - "private", - "alignas", - "and", - "auto", - "bool", - "catch", - "concept", - "default", - "double", - "float", - "extern", - "for", - "if", - "mutable", - "noexcept", - "nullptr", - "switch", - "this", - "true", - "false", - "typeid", - "while", - "alignof", - "break", - "continue", - "dynamic_cast", - "static_cast", - "explicit", - "friend", - "not", - "operator", - "return", - "sizeof", - "thread_local", - "try", - "typename", - "volatile", - "asm", - "case", - "constexpr", - "decltype", - "do", - "else", - "export", - "goto", - "inline", - "new", - "reinterpret_cast", - "static", - "template", - "throw", - "virtual" - }; - - protected override MatchingResult Matches(MatchingContext context, int tokenOffset) - { - var token = context.Lexer.PeekToken(tokenOffset); - var isMatch = nameRegex.IsMatch(token) && !reservedWords.Contains(token); - - if (!isMatch) return new MatchingResult(false, 0); - - SetMatcherOutput(token); - return new MatchingResult(true, 1); - } - - protected override string GetIdentifier() - { - return "Name"; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherNumber.cs b/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherNumber.cs deleted file mode 100644 index 2ffc6c48..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherNumber.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Globalization; -using System.Text.RegularExpressions; - -namespace ZoneCodeGenerator.Parsing.Matching.Matchers -{ - class MatcherNumber : BaseMatcher - { - private static readonly Regex decimalNumber = new Regex(@"^\d+$"); - private static readonly Regex hexNumber = new Regex(@"^0x([0-9a-fA-F]+)$"); - - protected override MatchingResult Matches(MatchingContext context, int tokenOffset) - { - var token = context.Lexer.PeekToken(tokenOffset); - - var currentMatch = decimalNumber.Match(token); - - if (currentMatch.Success) - { - SetMatcherOutput(token); - return new MatchingResult(true, 1); - } - - currentMatch = hexNumber.Match(token); - - if (!currentMatch.Success) return new MatchingResult(false, 0); - - SetMatcherOutput(int.Parse( currentMatch.Groups[1].Value, NumberStyles.HexNumber).ToString()); - return new MatchingResult(true, 1); - } - - protected override string GetIdentifier() - { - return "Number"; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherTypename.cs b/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherTypename.cs deleted file mode 100644 index 524eae16..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherTypename.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; - -namespace ZoneCodeGenerator.Parsing.Matching.Matchers -{ - class MatcherTypename : BaseMatcher - { - private static readonly Regex nameRegex = new Regex(@"^[a-zA-Z_$][a-zA-Z0-9_$]*$"); - - private int MatchTypenameExtension(MatchingContext context, int tokenOffset) - { - if (!":".Equals(context.Lexer.PeekToken(tokenOffset++))) - return 0; - if (!":".Equals(context.Lexer.PeekToken(tokenOffset++))) - return 0; - - return nameRegex.IsMatch(context.Lexer.PeekToken(tokenOffset)) ? 3 : 0; - } - - protected override MatchingResult Matches(MatchingContext context, int tokenOffset) - { - var lexer = context.Lexer; - var typename = new StringBuilder(); - var startTokenOffset = tokenOffset; - - var currentPart = lexer.PeekToken(tokenOffset++); - if ("unsigned".Equals(currentPart) - || "signed".Equals(currentPart)) - { - typename.Append(currentPart); - typename.Append(' '); - currentPart = lexer.PeekToken(tokenOffset++); - } - - if (!nameRegex.IsMatch(currentPart)) - return new MatchingResult(false, 0); - typename.Append(currentPart); - - if ("long".Equals(currentPart)) - { - currentPart = lexer.PeekToken(tokenOffset); - if (currentPart.Equals("long")) - { - tokenOffset++; - typename.Append(' '); - typename.Append(currentPart); - } - } - else - { - var extensionLength = MatchTypenameExtension(context, tokenOffset); - while (extensionLength > 0) - { - for (var i = 0; i < extensionLength; i++) - { - typename.Append(lexer.PeekToken(tokenOffset + i)); - } - - tokenOffset += extensionLength; - extensionLength = MatchTypenameExtension(context, tokenOffset); - } - } - - SetMatcherOutput(typename.ToString()); - return new MatchingResult(true, tokenOffset - startTokenOffset); - } - - protected override string GetIdentifier() - { - return "Typename"; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherWithTag.cs b/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherWithTag.cs deleted file mode 100644 index a5a934cc..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/Matchers/MatcherWithTag.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ZoneCodeGenerator.Parsing.Matching.Matchers -{ - class MatcherWithTag : TokenMatcher - { - private readonly string tag; - - public MatcherWithTag(string tag) - { - this.tag = tag; - } - - protected override TokenMatchingResult PerformTest(MatchingContext context, int tokenOffset) - { - var matcherWithTag = context.GetMatcherByTag(tag); - - if (matcherWithTag == null) - { - throw new Exception($"Could not find matcher with tag '{tag}'"); - } - - return matcherWithTag.Test(context, tokenOffset); - } - - protected override string GetIdentifier() - { - return $"WithTag(\"{tag}\")"; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/MatchingContext.cs b/src/ZoneCodeGenerator/Parsing/Matching/MatchingContext.cs deleted file mode 100644 index 8d7c788c..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/MatchingContext.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace ZoneCodeGenerator.Parsing.Matching -{ - class MatchingContext - { - public ILexer Lexer { get; } - - public bool Verbose { get; set; } - - private readonly Dictionary taggedMatchers; - - public MatchingContext(ILexer lexer, Dictionary taggedMatchers) - { - Lexer = lexer; - this.taggedMatchers = taggedMatchers; - Verbose = false; - } - - public TokenMatcher GetMatcherByTag(string tag) - { - return taggedMatchers.ContainsKey(tag) ? taggedMatchers[tag] : null; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/TokenMatcher.cs b/src/ZoneCodeGenerator/Parsing/Matching/TokenMatcher.cs deleted file mode 100644 index d4244a23..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/TokenMatcher.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace ZoneCodeGenerator.Parsing.Matching -{ - abstract class TokenMatcher - { - private const int DebugPeekMin = 3; - - public string Tag { get; private set; } - - protected TokenMatcher() - { - Tag = ""; - } - - public TokenMatcher WithTag(string tag) - { - Tag = tag; - return this; - } - - protected abstract string GetIdentifier(); - - public override string ToString() - { - return string.IsNullOrEmpty(Tag) ? GetIdentifier() : Tag; - } - - protected abstract TokenMatchingResult PerformTest(MatchingContext context, int tokenOffset); - - public virtual TokenMatchingResult Test(MatchingContext context, int tokenOffset) - { - var result = PerformTest(context, tokenOffset); - - if (context.Verbose) - { - if (result.Successful) - { - var matchedTokens = new List(); - - for (var i = 0; i < result.ConsumedTokenCount; i++) - { - matchedTokens.Add(context.Lexer.PeekToken(tokenOffset + i)); - } - - Console.WriteLine($"Matcher {ToString()} matched: {string.Join(" ", matchedTokens)}"); - } - else - { - var debugPeekCount = Math.Max(context.Lexer.CachedTokenCount - tokenOffset, DebugPeekMin); - var nextTokens = new List(); - - for (var i = 0; i < debugPeekCount; i++) - { - nextTokens.Add(context.Lexer.PeekToken(tokenOffset + i)); - } - - Console.WriteLine($"Matcher {ToString()} failed @ {string.Join(" ", nextTokens)}"); - } - } - - return result; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Matching/TokenMatchingResult.cs b/src/ZoneCodeGenerator/Parsing/Matching/TokenMatchingResult.cs deleted file mode 100644 index 1bf328a1..00000000 --- a/src/ZoneCodeGenerator/Parsing/Matching/TokenMatchingResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Utils; - -namespace ZoneCodeGenerator.Parsing.Matching -{ - class TokenMatchingResult - { - public bool Successful { get; set; } - public int ConsumedTokenCount { get; set; } - - private readonly Dictionary> namedMatches; - public IReadOnlyDictionary> NamedMatches => namedMatches; - - private readonly List matchedTags; - public IReadOnlyList MatchedTags => matchedTags; - - public TokenMatchingResult(bool success, int consumedTokenCount) - { - if(!success && consumedTokenCount > 0) - throw new ArgumentException("Token Match cannot be unsuccessful and consume tokens"); - - if(consumedTokenCount < 0) - throw new ArgumentException("Consumed token count cannot be negative"); - - Successful = success; - ConsumedTokenCount = consumedTokenCount; - - namedMatches = new Dictionary>(); - matchedTags = new List(); - } - - public void AddNamedMatch(string name, string value) - { - if(!namedMatches.ContainsKey(name)) - namedMatches.Add(name, new List()); - - namedMatches[name].Add(value); - } - - public void PrependTag(string tag) - { - if (!string.IsNullOrEmpty(tag)) - matchedTags.Insert(0, tag); - } - - public void AppendTag(string tag) - { - if(!string.IsNullOrEmpty(tag)) - matchedTags.Add(tag); - } - - public void CopyTo(TokenMatchingResult target) - { - foreach(var (matchKey, matchValue) in namedMatches) - { - foreach (var namedMatch in matchValue) - { - target.AddNamedMatch(matchKey, namedMatch); - } - } - - target.matchedTags.AddRange(matchedTags); - - target.ConsumedTokenCount += ConsumedTokenCount; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Parser.cs b/src/ZoneCodeGenerator/Parsing/Parser.cs deleted file mode 100644 index aa7b937d..00000000 --- a/src/ZoneCodeGenerator/Parsing/Parser.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGenerator.Parsing -{ - class Parser where TState : IParserState - { - // Amount of consecutive tokens that are output after a parser error to show the region where the error happened. - private const int ParserErrorTokenPeekCount = 3; - - private readonly ILexer lexer; - private readonly TState state; - - public Parser(TState state, ILexer lexer) - { - this.state = state; - this.lexer = lexer; - } - - public bool Parse(bool verbose = false) - { - while (!lexer.IsEndOfStream) - { - var testSuccessful = false; - - try - { - foreach (var test in state.GetTests()) - { - switch (test.PerformTest(state, lexer, verbose)) - { - case TokenTestResult.Match: - lexer.SkipTokens(test.ConsumedTokenCount); - testSuccessful = true; - break; - case TokenTestResult.NoMatch: - break; - default: - throw new ArgumentOutOfRangeException(); - } - - if (testSuccessful) - break; - } - } - catch (LoadingException e) - { - PrintParserError(e); - return false; - } - - if (!testSuccessful) - { - PrintParserError(new LoadingException("Could not parse expression")); - return false; - } - - // Peek for the next token here to be able to determine if the stream is at its end or not - lexer.PeekToken(); - } - - return true; - } - - private void PrintParserError(LoadingException e) - { - Console.WriteLine($"Parsing failed in file '{lexer.CurrentFile}' at line {lexer.CurrentLine}:"); - - Console.WriteLine(e.Message); - - Console.Write(" "); - - var tokenCountToShow = Math.Max(ParserErrorTokenPeekCount, lexer.CachedTokenCount); - for (var i = 0; i < tokenCountToShow; i++) - { - var token = lexer.PeekToken(i); - if (string.IsNullOrEmpty(token)) - break; - Console.Write($"{token} "); - } - Console.WriteLine(); - Console.WriteLine(); - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/ParserException.cs b/src/ZoneCodeGenerator/Parsing/ParserException.cs deleted file mode 100644 index a1b1e9ff..00000000 --- a/src/ZoneCodeGenerator/Parsing/ParserException.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZoneCodeGenerator.Parsing -{ - class ParserException : LoadingException - { - public ParserException(string message) : base(message) - { - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Testing/AbstractTokenTest.cs b/src/ZoneCodeGenerator/Parsing/Testing/AbstractTokenTest.cs deleted file mode 100644 index ae3da312..00000000 --- a/src/ZoneCodeGenerator/Parsing/Testing/AbstractTokenTest.cs +++ /dev/null @@ -1,158 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; -using ZoneCodeGenerator.Utils; - -namespace ZoneCodeGenerator.Parsing.Testing -{ - abstract class AbstractTokenTest : ITokenTest where TState : IParserState - { - private TokenMatchingResult lastResult; - private int tagOffset; - private readonly Dictionary matchOffset; - - public int ConsumedTokenCount => lastResult?.ConsumedTokenCount ?? 0; - - private readonly TokenMatcher matcherEntryPoint; - private readonly Dictionary taggedMatchers; - - protected AbstractTokenTest(TokenMatcher[] matcherEntryPoint) - { - this.matcherEntryPoint = new MatcherGroupAnd(matcherEntryPoint); - taggedMatchers = new Dictionary(); - - lastResult = null; - tagOffset = 0; - matchOffset = new Dictionary(); - - BuildTaggedMatcherList(matcherEntryPoint); - } - - private void BuildTaggedMatcherList(IEnumerable matchersWithTags) - { - foreach (var tokenMatcher in matchersWithTags) - { - if (!string.IsNullOrEmpty(tokenMatcher.Tag)) - { - taggedMatchers[tokenMatcher.Tag] = tokenMatcher; - } - - if (tokenMatcher is GroupMatcher groupMatcher) - { - BuildTaggedMatcherList(groupMatcher.Matchers); - } - } - } - - private void Reset() - { - lastResult = null; - tagOffset = 0; - matchOffset.Clear(); - } - - protected void AddTaggedMatcher(params TokenMatcher[] taggedMatcher) - { - BuildTaggedMatcherList(taggedMatcher); - } - - protected string PeekTag() - { - return lastResult?.MatchedTags.ElementAtOrDefault(tagOffset) ?? ""; - } - - protected string NextTag() - { - return lastResult?.MatchedTags.ElementAtOrDefault(tagOffset++) ?? ""; - } - - protected bool HasMatcherTokens(string matcherName) - { - return GetMatcherTokenCount(matcherName) > 0; - } - - protected int GetMatcherTokenCount(string matcherName) - { - if (lastResult == null || !lastResult.NamedMatches.TryGetValue(matcherName, out var matches)) - { - return 0; - } - - return matches.Count; - } - - protected string PeekMatch(string matcherName) - { - if (!lastResult.NamedMatches.TryGetValue(matcherName, out var matches)) - { - return null; - } - - if (!matchOffset.TryGetValue(matcherName, out var offset)) - { - offset = 0; - } - - return matches.ElementAtOrDefault(offset); - } - - protected string NextMatch(string matcherName) - { - if (!lastResult.NamedMatches.TryGetValue(matcherName, out var matches)) - { - return null; - } - - if (!matchOffset.TryGetValue(matcherName, out var offset)) - { - offset = 0; - } - - var result = matches.ElementAtOrDefault(offset++); - - matchOffset[matcherName] = offset; - - return result; - } - - protected abstract void ProcessMatch(TState state); - - public TokenTestResult PerformTest(TState state, ILexer lexer, bool verbose = false) - { - var context = new MatchingContext(lexer, taggedMatchers) - { - Verbose = verbose - }; - - if (context.Verbose) - { - Console.WriteLine($"Test {GetType().Name} start"); - } - - Reset(); - lastResult = matcherEntryPoint.Test(context, 0); - - if (!lastResult.Successful) - { - if (context.Verbose) - { - Console.WriteLine($"Test {GetType().Name} failed"); - } - - return TokenTestResult.NoMatch; - } - - ProcessMatch(state); - - if (context.Verbose) - { - Console.WriteLine($"Test {GetType().Name} successful"); - } - - return TokenTestResult.Match; - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Testing/ITokenTest.cs b/src/ZoneCodeGenerator/Parsing/Testing/ITokenTest.cs deleted file mode 100644 index 5a0fa110..00000000 --- a/src/ZoneCodeGenerator/Parsing/Testing/ITokenTest.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZoneCodeGenerator.Parsing.Testing -{ - interface ITokenTest where TState : IParserState - { - int ConsumedTokenCount { get; } - - TokenTestResult PerformTest(TState state, ILexer lexer, bool verbose = false); - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Testing/TestFailedException.cs b/src/ZoneCodeGenerator/Parsing/Testing/TestFailedException.cs deleted file mode 100644 index edf61ca7..00000000 --- a/src/ZoneCodeGenerator/Parsing/Testing/TestFailedException.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ZoneCodeGenerator.Parsing.Testing -{ - class TestFailedException : LoadingException - { - public TestFailedException(string message) : base(message) - { - } - } -} diff --git a/src/ZoneCodeGenerator/Parsing/Testing/TokenTestResult.cs b/src/ZoneCodeGenerator/Parsing/Testing/TokenTestResult.cs deleted file mode 100644 index 47d7e654..00000000 --- a/src/ZoneCodeGenerator/Parsing/Testing/TokenTestResult.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZoneCodeGenerator.Parsing.Testing -{ - enum TokenTestResult - { - Match, - NoMatch - } -} diff --git a/src/ZoneCodeGenerator/Persistence/IDataRepository.cs b/src/ZoneCodeGenerator/Persistence/IDataRepository.cs deleted file mode 100644 index 98ada481..00000000 --- a/src/ZoneCodeGenerator/Persistence/IDataRepository.cs +++ /dev/null @@ -1,14 +0,0 @@ -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.FastFileStructure; - -namespace ZoneCodeGenerator.Persistence -{ - interface IDataRepository : IReadOnlyDataRepository - { - void Add(DataTypeEnum data); - void Add(DataTypeStruct data); - void Add(DataTypeUnion data); - void Add(DataTypeTypedef data); - void Add(FastFileBlock block); - } -} diff --git a/src/ZoneCodeGenerator/Persistence/IReadOnlyDataRepository.cs b/src/ZoneCodeGenerator/Persistence/IReadOnlyDataRepository.cs deleted file mode 100644 index c48759ac..00000000 --- a/src/ZoneCodeGenerator/Persistence/IReadOnlyDataRepository.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Collections.Generic; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.FastFileStructure; -using ZoneCodeGenerator.Domain.Information; - -namespace ZoneCodeGenerator.Persistence -{ - interface IReadOnlyDataRepository - { - IEnumerable GetAllEnums(); - IEnumerable GetAllStructs(); - IEnumerable GetAllUnions(); - IEnumerable GetAllTypedefs(); - IEnumerable GetAllStructureInformation(); - IEnumerable GetAllFastFileBlocks(); - - DataType GetDataTypeByName(string name); - StructureInformation GetInformationFor(DataTypeWithMembers dataTypeWithMembers); - } -} diff --git a/src/ZoneCodeGenerator/Persistence/InMemoryDataRepository.cs b/src/ZoneCodeGenerator/Persistence/InMemoryDataRepository.cs deleted file mode 100644 index 3e13a3a8..00000000 --- a/src/ZoneCodeGenerator/Persistence/InMemoryDataRepository.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.FastFileStructure; -using ZoneCodeGenerator.Domain.Information; - -namespace ZoneCodeGenerator.Persistence -{ - class InMemoryDataRepository : IDataRepository - { - private readonly List typedefs; - private readonly List enums; - private readonly List structs; - private readonly List unions; - private readonly List structureInformationList; - private readonly List blocks; - - public InMemoryDataRepository() - { - typedefs = new List(); - enums = new List(); - structs = new List(); - unions = new List(); - structureInformationList = new List(); - blocks = new List(); - } - - public void Add(DataTypeEnum data) - { - enums.Add(data); - } - - public void Add(DataTypeTypedef data) - { - typedefs.Add(data); - } - - public void Add(FastFileBlock block) - { - blocks.Add(block); - } - - public void Add(DataTypeStruct data) - { - structs.Add(data); - } - - public void Add(DataTypeUnion data) - { - unions.Add(data); - } - - public IEnumerable GetAllEnums() - { - return enums.AsEnumerable(); - } - - public IEnumerable GetAllStructs() - { - return structs.AsEnumerable(); - } - - public IEnumerable GetAllTypedefs() - { - return typedefs.AsEnumerable(); - } - - public IEnumerable GetAllStructureInformation() - { - return structureInformationList.AsEnumerable(); - } - - public IEnumerable GetAllFastFileBlocks() - { - return blocks.AsEnumerable(); - } - - public IEnumerable GetAllUnions() - { - return unions.AsEnumerable(); - } - - public DataType GetDataTypeByName(string name) - { - DataType data = enums.Find(_enum => _enum.FullName.Equals(name)); - if (data != null) - return data; - - data = structs.Find(_struct => _struct.FullName.Equals(name)); - if (data != null) - return data; - - data = unions.Find(_struct => _struct.FullName.Equals(name)); - if (data != null) - return data; - - data = typedefs.Find(typeDef => typeDef.FullName.Equals(name)); - - return data; - } - - public StructureInformation GetInformationFor(DataTypeWithMembers dataTypeWithMembers) - { - var information = structureInformationList.Find(listEntry => listEntry.Type == dataTypeWithMembers); - - if (information == null) - { - information = new StructureInformation(dataTypeWithMembers); - structureInformationList.Add(information); - - foreach (var member in dataTypeWithMembers.Members) - { - StructureInformation memberStructureInformation = null; - - var memberDataType = member.VariableType.Type; - - while (memberDataType is DataTypeTypedef typedef) - { - memberDataType = typedef.TypeDefinition.Type; - } - - if (memberDataType is DataTypeWithMembers memberType) - { - memberStructureInformation = GetInformationFor(memberType); - } - - information.OrderedMembers.Add(new MemberInformation(information, member, memberStructureInformation)); - } - } - - return information; - } - } -} diff --git a/src/ZoneCodeGenerator/Program.cs b/src/ZoneCodeGenerator/Program.cs deleted file mode 100644 index eb75603d..00000000 --- a/src/ZoneCodeGenerator/Program.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using ZoneCodeGenerator.Interface; -using ZoneCodeGenerator.Parsing.C_Header; - -namespace ZoneCodeGenerator -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [STAThread] - static int Main(string[] args) - { - var cui = new CUI(); - - return cui.Start(args) ? 0 : 1; - } - - private static bool CreateDatabase(string[] args) - { - var storage = HeaderReader.ReadFile(args[0]); - - var prettyPrinter = new PrettyPrinter(storage); - - prettyPrinter.PrintAll(); - - return true; - } - - private static bool PrintDatabase(string[] args) - { - Console.WriteLine("Printing"); - return true; - } - } -} diff --git a/src/ZoneCodeGenerator/Properties/AssemblyInfo.cs b/src/ZoneCodeGenerator/Properties/AssemblyInfo.cs deleted file mode 100644 index c41f146b..00000000 --- a/src/ZoneCodeGenerator/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ZoneCodeGenerator")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ZoneCodeGenerator")] -[assembly: AssemblyCopyright("Copyright © 2019")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("d1c20c32-9cb8-44b8-9df7-f0cf8fb304d3")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] - -[assembly: InternalsVisibleTo("ZoneCodeGeneratorTests")] -[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] \ No newline at end of file diff --git a/src/ZoneCodeGenerator/Utils/AlignmentExtension.cs b/src/ZoneCodeGenerator/Utils/AlignmentExtension.cs deleted file mode 100644 index 05d0bfa0..00000000 --- a/src/ZoneCodeGenerator/Utils/AlignmentExtension.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace ZoneCodeGenerator.Utils -{ - static class AlignmentExtension - { - public static int Align(this int valueToAlign, int alignment) - { - return (valueToAlign + alignment - 1) / alignment * alignment; - } - - public static long Align(this long valueToAlign, long alignment) - { - return (valueToAlign + alignment - 1) / alignment * alignment; - } - } -} diff --git a/src/ZoneCodeGenerator/Utils/KeyValueExtension.cs b/src/ZoneCodeGenerator/Utils/KeyValueExtension.cs deleted file mode 100644 index 7d875de1..00000000 --- a/src/ZoneCodeGenerator/Utils/KeyValueExtension.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace ZoneCodeGenerator.Utils -{ - public static class KeyValueExtension - { - public static void Deconstruct(this KeyValuePair keyValuePair, out T1 m1, out T2 m2) - { - m1 = keyValuePair.Key; - m2 = keyValuePair.Value; - } - - public static void Deconstruct(this Tuple keyValuePair, out T1 m1, out T2 m2) - { - m1 = keyValuePair.Item1; - m2 = keyValuePair.Item2; - } - } -} diff --git a/src/ZoneCodeGenerator/Utils/RandomName.cs b/src/ZoneCodeGenerator/Utils/RandomName.cs deleted file mode 100644 index 428c91a1..00000000 --- a/src/ZoneCodeGenerator/Utils/RandomName.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; - -namespace ZoneCodeGenerator.Utils -{ - static class RandomName - { - private const int NameLen = 32; - - private static readonly Random random = new Random(); - private static readonly char[] generatorChars = { - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' - }; - - public static string GenerateName() - { - var name = ""; - for (var i = 0; i < NameLen; i++) - name += generatorChars[random.Next(generatorChars.Length)]; - - return name; - } - } -} diff --git a/test/ZoneCodeGeneratorTests.lua b/test/ZoneCodeGeneratorTests.lua deleted file mode 100644 index 676b25ab..00000000 --- a/test/ZoneCodeGeneratorTests.lua +++ /dev/null @@ -1,47 +0,0 @@ -ZoneCodeGeneratorTests = {} - -function ZoneCodeGeneratorTests:include() - -end - -function ZoneCodeGeneratorTests:link() - if References:link("ZoneCodeGeneratorTests") then - links "ZoneCodeGeneratorTests" - end -end - -function ZoneCodeGeneratorTests:use() - -end - -function ZoneCodeGeneratorTests:project() - References:reset() - local folder = TestFolder(); - - project "ZoneCodeGeneratorTests" - targetdir(TargetDirectoryTest) - location "%{wks.location}/test/%{prj.name}" - kind "SharedLib" - language "C#" - dotnetframework "4.5" - - files { - path.join(folder, "ZoneCodeGeneratorTests/**.cs") - } - - vpaths { ["*"] = "test/ZoneCodeGeneratorTests" } - - nuget { - "Moq:4.13.1", - "MSTest.TestFramework:2.0.0", - "MSTest.TestAdapter:2.0.0" - } - - links { - "System", - "System.Core", - "System.Data" - } - - ZoneCodeGenerator:link() -end diff --git a/test/ZoneCodeGeneratorTests/AssertionExtensions.cs b/test/ZoneCodeGeneratorTests/AssertionExtensions.cs deleted file mode 100644 index 6bee7a42..00000000 --- a/test/ZoneCodeGeneratorTests/AssertionExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace ZoneCodeGeneratorTests -{ - public static class AssertionExtensions - { - public static void Contains(this Assert assert, object expected, ICollection collection) - { - if (collection.Cast().Any(item => item == expected)) - { - return; - } - - throw new AssertFailedException(); - } - - public static void IsZero(this Assert assert, int number) - { - if(number != 0) - throw new AssertFailedException(); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Domain/NamespaceTest.cs b/test/ZoneCodeGeneratorTests/Domain/NamespaceTest.cs deleted file mode 100644 index c963b5c2..00000000 --- a/test/ZoneCodeGeneratorTests/Domain/NamespaceTest.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using ZoneCodeGenerator.Domain; - -namespace ZoneCodeGeneratorTests.Domain -{ - [TestClass] - public class NamespaceTest - { - [TestMethod] - public void EnsureEmptyNamespaceResultIsCorrect() - { - var nameSpace = new Namespace(); - - Assert.AreEqual("", nameSpace.GetName()); - } - - [TestMethod] - public void EnsureSingleNamespaceElementResultIsCorrect() - { - var nameSpace = new Namespace(); - - nameSpace.Push("NameTheSpace"); - - Assert.AreEqual("NameTheSpace", nameSpace.GetName()); - } - - [TestMethod] - public void EnsureDoubleNamespaceElementResultIsCorrect() - { - var nameSpace = new Namespace(); - - nameSpace.Push("NameTheSpace"); - nameSpace.Push("Please"); - - Assert.AreEqual("NameTheSpace::Please", nameSpace.GetName()); - } - - [TestMethod] - public void EnsurePopRemovesNamespace() - { - var nameSpace = new Namespace(); - - nameSpace.Push("NameTheSpace"); - nameSpace.Push("Please"); - nameSpace.Push("Not"); - - Assert.AreEqual("Not", nameSpace.Pop()); - Assert.AreEqual("NameTheSpace::Please", nameSpace.GetName()); - } - - [TestMethod] - public void EnsureMultipleNamespaceElementsResultIsCorrect() - { - var nameSpace = new Namespace(); - - nameSpace.Push("NameTheSpace"); - nameSpace.Push("Please"); - nameSpace.Push("Just"); - nameSpace.Push("Not"); - nameSpace.Push("MySpace"); - - Assert.AreEqual("NameTheSpace::Please::Just::Not::MySpace", nameSpace.GetName()); - } - - [TestMethod] - public void EnsureNamespaceCanBePoppedToEmpty() - { - var nameSpace = new Namespace(); - - nameSpace.Push("NameTheSpace"); - nameSpace.Push("Please"); - - Assert.AreEqual("Please", nameSpace.Pop()); - Assert.AreEqual("NameTheSpace", nameSpace.Pop()); - - Assert.AreEqual("", nameSpace.GetName()); - } - - [TestMethod] - public void EnsureUsingPopTooOftenResultsInAnError() - { - var nameSpace = new Namespace(); - - nameSpace.Push("NameTheSpace"); - nameSpace.Push("Please"); - - Assert.AreEqual("Please", nameSpace.Pop()); - Assert.AreEqual("NameTheSpace", nameSpace.Pop()); - Assert.ThrowsException(() => nameSpace.Pop()); - - Assert.AreEqual("", nameSpace.GetName()); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/FieldInjector.cs b/test/ZoneCodeGeneratorTests/FieldInjector.cs deleted file mode 100644 index 3d5e5a87..00000000 --- a/test/ZoneCodeGeneratorTests/FieldInjector.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Reflection; - -namespace ZoneCodeGeneratorTests -{ - internal static class FieldInjector - { - public static bool InjectToField(object target, object toInject) - { - if(target == null || toInject == null) - throw new ArgumentException("Params must not be null"); - - var injectType = toInject.GetType(); - var fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance); - - foreach(var field in fields) - { - if (!field.FieldType.IsAssignableFrom(injectType)) continue; - - field.SetValue(target, toInject); - return true; - } - - return false; - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Impl/PreprocessorTest.cs b/test/ZoneCodeGeneratorTests/Parsing/C_Header/Impl/PreprocessorTest.cs deleted file mode 100644 index 7dbf642f..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Impl/PreprocessorTest.cs +++ /dev/null @@ -1,186 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using ZoneCodeGenerator.Parsing.C_Header; -using ZoneCodeGenerator.Parsing.C_Header.Impl; -using ZoneCodeGenerator.Utils; -using ZoneCodeGeneratorTests.Parsing.Mock; - -namespace ZoneCodeGeneratorTests.Parsing.C_Header.Impl -{ - [TestClass] - public class PreprocessorTest - { - private IncludingParsingStreamTest headerStreamTest; - private IHeaderParserState headerParserState; - - private Preprocessor preprocessor; - - [TestInitialize] - public void Setup() - { - headerStreamTest = new IncludingParsingStreamTest("file.h"); - headerParserState = new HeaderParserState(); - preprocessor = new Preprocessor(headerStreamTest, headerParserState); - } - - [TestMethod] - public void EnsureReturnsUnmodifiedText() - { - string[] stringsThatShouldNotBeModified = - { - "This is a normal string", - "There is nothing to be preprocessed!", - "0124124124 # 124124124", - "...", - "asdf", - "" - }; - - headerStreamTest.Lines.AddRange(stringsThatShouldNotBeModified); - - foreach (var stringThatShouldNotBeModified in stringsThatShouldNotBeModified) - { - Assert.AreEqual(stringThatShouldNotBeModified, preprocessor.ReadLine()); - } - } - - [TestMethod] - public void EnsureDefinesArePlacedCorrectly() - { - var defineStrings = new Dictionary() - { - {"#define World Hell", ""}, - {"Hello World!", "Hello Hell!"}, - {"World-wide Teamwork", "Hell-wide Teamwork"}, - {"#define great pretty bad", ""}, - {"Defines are great, right?", "Defines are pretty bad, right?"}, - {"Great world", "Great world"}, // Capitalization should matter - }; - headerStreamTest.Lines.AddRange(defineStrings.Keys); - - foreach (var (_, expectedResult) in defineStrings) - { - Assert.AreEqual(expectedResult, preprocessor.ReadLine().Trim()); - } - } - - [TestMethod] - public void EnsureDefinesCanBeOverwritten() - { - var defineStrings = new Dictionary() - { - {"#define World Hell", ""}, - {"#define World Mars", ""}, - {"Hello World!", "Hello Mars!"} - }; - headerStreamTest.Lines.AddRange(defineStrings.Keys); - - foreach (var (_, expectedResult) in defineStrings) - { - Assert.AreEqual(expectedResult, preprocessor.ReadLine().Trim()); - } - } - - [TestMethod] - public void EnsureEmptyDefinesResolveToEmpty() - { - var defineStrings = new Dictionary - { - {"#define World", ""}, - {"Hello World!", "Hello !"} - }; - headerStreamTest.Lines.AddRange(defineStrings.Keys); - - foreach (var (_, expectedResult) in defineStrings) - { - Assert.AreEqual(expectedResult, preprocessor.ReadLine().Trim()); - } - } - - [TestMethod] - public void EnsureUndefRemovesDefines() - { - var defineStrings = new Dictionary() - { - {"#define World Hell", ""}, - {"Hello World!", "Hello Hell!"}, - {"#undef World", ""}, - {"Hello World 2!", "Hello World 2!"}, - {"#define Hell Jupiter", ""}, - {"#define Hell Mars", ""}, - {"#undef Hell", ""}, - {"Hell no", "Hell no"}, - }; - headerStreamTest.Lines.AddRange(defineStrings.Keys); - - foreach (var (_, expectedResult) in defineStrings) - { - Assert.AreEqual(expectedResult, preprocessor.ReadLine().Trim()); - } - } - - [TestMethod] - public void EnsurePackIsParsedCorrectly() - { - var defaultPack = headerParserState.CurrentPack; - - var packs = new List> - { - new Tuple("Test", defaultPack), - new Tuple("#pragma pack(push, 16)", 16), - new Tuple("Test2", 16), - new Tuple("#pragma pack(push, 64)", 64), - new Tuple("Test3", 64), - new Tuple("Test4", 64), - new Tuple("#pragma pack(pop)", 16), - new Tuple("Test5", 16), - new Tuple("#pragma pack(pop)", defaultPack), - new Tuple("Test6", defaultPack) - }; - headerStreamTest.Lines.AddRange(packs.Select(tuple => tuple.Item1)); - - foreach (var (_, expectedPack) in packs) - { - preprocessor.ReadLine(); - - Assert.AreEqual(expectedPack, headerParserState.CurrentPack); - } - } - - [TestMethod] - public void EnsureIncludeChangesFileWhenUsingQuotationMarks() - { - headerStreamTest.Lines.AddRange(new [] - { - "#include \"asdf.h\"", - "#include \"file/path/to/header.h\"" - }); - preprocessor.ReadLine(); - Assert.AreEqual(1, headerStreamTest.IncludeCount); - Assert.AreEqual("asdf.h", headerStreamTest.LastInclude); - - preprocessor.ReadLine(); - Assert.AreEqual(2, headerStreamTest.IncludeCount); - Assert.AreEqual("file/path/to/header.h", headerStreamTest.LastInclude); - } - - [TestMethod] - public void EnsureIncludeChangesFileWhenUsingCarets() - { - headerStreamTest.Lines.AddRange(new [] - { - "#include ", - "#include " - }); - preprocessor.ReadLine(); - Assert.AreEqual(1, headerStreamTest.IncludeCount); - Assert.AreEqual("asdf.h", headerStreamTest.LastInclude); - - preprocessor.ReadLine(); - Assert.AreEqual(2, headerStreamTest.IncludeCount); - Assert.AreEqual("file/path/to/header.h", headerStreamTest.LastInclude); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestCloseBlockTest.cs b/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestCloseBlockTest.cs deleted file mode 100644 index 8d822e6b..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestCloseBlockTest.cs +++ /dev/null @@ -1,161 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.C_Header; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGeneratorTests.Parsing.C_Header.Tests -{ - [TestClass] - public class TestCloseBlockTest - { - private Mock parserStateMock; - private Mock topBlock; - private Mock topBlockNameAssignable; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - parserStateMock = new Mock(); - topBlock = new Mock(parserStateMock.Object, BlockType.None); - topBlockNameAssignable = topBlock.As(); - - parserStateMock.SetupGet(state => state.CurrentBlock).Returns(() => topBlock.Object); - - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - } - - [TestMethod] - public void EnsureRecognizesSimpleCurlyBrackets() - { - tokens.AddRange(new List - { - "}", "struct", "test", "{" - }); - - var test = new TestCloseBlock(false); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object, true)); - - // Be sure there was no name assigned - topBlockNameAssignable.Verify(assignable => assignable.AssignName(It.IsAny()), Times.Never()); - - // Be sure the top block was popped - parserStateMock.Verify(state => state.PopBlock()); - - Assert.AreEqual(1, test.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureRecognizesCurlyBracketsWithSemicolon() - { - tokens.AddRange(new List - { - "}", ";", "struct", "test", "{" - }); - - var test = new TestCloseBlock(true); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - // Be sure there was no name assigned - topBlockNameAssignable.Verify(assignable => assignable.AssignName(It.IsAny()), Times.Never()); - - // Be sure the top block was popped - parserStateMock.Verify(state => state.PopBlock()); - - Assert.AreEqual(2, test.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureFailsWithoutSemicolonIfRequired() - { - tokens.AddRange(new List - { - "}", "struct", "test", "{" - }); - - var test = new TestCloseBlock(true); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - // Be sure there was no name assigned - topBlockNameAssignable.Verify(assignable => assignable.AssignName(It.IsAny()), Times.Never()); - - parserStateMock.Verify(state => state.PopBlock(), Times.Never()); - } - - [TestMethod] - public void EnsureAssignsName() - { - tokens.AddRange(new List - { - "}", "closing_name", ";", "struct", "test", "{" - }); - - var test = new TestCloseBlock(true); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - topBlockNameAssignable.Verify(assignable => assignable.AssignName("closing_name")); - topBlockNameAssignable.VerifyNoOtherCalls(); - - // Be sure the top block was popped - parserStateMock.Verify(state => state.PopBlock()); - - Assert.AreEqual(3, test.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureFailsIfCannotAssignName() - { - tokens.AddRange(new List - { - "}", "closing_name", ";", "struct", "test", "{" - }); - - // No INameAssignable interface implemented - topBlock = new Mock(parserStateMock.Object, BlockType.None); - - var test = new TestCloseBlock(true); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - parserStateMock.Verify(state => state.PopBlock(), Times.Never()); - } - - [TestMethod] - public void EnsureDoesNotMatchIfNoCurlyBracket() - { - tokens.AddRange(new List - { - "{", "}", "struct", "test", "{" - }); - - var test = new TestCloseBlock(false); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - parserStateMock.Verify(state => state.PopBlock(), Times.Never()); - - Assert.AreEqual(0, test.ConsumedTokenCount); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestEnumMemberTest.cs b/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestEnumMemberTest.cs deleted file mode 100644 index 91300e07..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestEnumMemberTest.cs +++ /dev/null @@ -1,318 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.C_Header; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGeneratorTests.Parsing.C_Header.Tests -{ - [TestClass] - public class TestEnumMemberTest - { - private Mock parserStateMock; - private Mock enumMock; - private EnumMember addedEnumMember; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - parserStateMock = new Mock(); - enumMock = new Mock(parserStateMock.Object, "testenum", DataTypeBaseType.INT, false); - addedEnumMember = null; - - parserStateMock.SetupGet(state => state.CurrentBlock).Returns(() => enumMock.Object); - enumMock.Setup(_enum => _enum.AddMember(It.IsAny())) - .Callback((EnumMember member) => addedEnumMember = member); - - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - } - - [TestMethod] - public void EnsureAcceptsSimpleEnumEntry() - { - tokens.AddRange(new List - { - "asdf", "," - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(2, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Once()); - - Assert.AreEqual("asdf", addedEnumMember.Name); - Assert.AreEqual(0L, addedEnumMember.Value); - } - - [TestMethod] - public void EnsureAcceptsEntryWithSpecialCharacters() - { - tokens.AddRange(new List - { - "$ASgF123__", "," - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(2, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Once()); - - Assert.AreEqual("$ASgF123__", addedEnumMember.Name); - Assert.AreEqual(0L, addedEnumMember.Value); - } - - [TestMethod] - public void EnsureRejectsWithDigitInTheBeginning() - { - tokens.AddRange(new List - { - "123var", "," - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Never()); - } - - [TestMethod] - public void EnsureAcceptsEntryWithDecimalNumber() - { - tokens.AddRange(new List - { - "leet", "=", "1337", "," - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Once()); - - Assert.AreEqual("leet", addedEnumMember.Name); - Assert.AreEqual(1337L, addedEnumMember.Value); - } - - [TestMethod] - public void EnsureAcceptsEntryWithHexadecimalNumber() - { - tokens.AddRange(new List - { - "smoke", "=", "0x1a4", "," - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Once()); - - Assert.AreEqual("smoke", addedEnumMember.Name); - Assert.AreEqual(420L, addedEnumMember.Value); - } - - [TestMethod] - public void EnsureRejectsEntryWithoutName() - { - tokens.AddRange(new List - { - "," - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Never()); - } - - [TestMethod] - public void EnsureRejectsEntryWithoutNameButWithNumber() - { - tokens.AddRange(new List - { - "=", "0", "," - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Never()); - } - - [TestMethod] - public void EnsurePicksNextNumberWhenNoneSpecified() - { - enumMock.Setup(_enum => _enum.GetNextEnumValue()).Returns(1337L); - tokens.AddRange(new List - { - "asdf", "," - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(2, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Once()); - - Assert.AreEqual("asdf", addedEnumMember.Name); - Assert.AreEqual(1337L, addedEnumMember.Value); - } - - [TestMethod] - public void EnsureNeedsTerminator() - { - tokens.AddRange(new List - { - "asdf", "nextentry" - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Never()); - } - - [TestMethod] - public void EnsureNeedsTerminatorEvenWithValueSpecified() - { - tokens.AddRange(new List - { - "asdf", "=", "0", "nextentry" - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Never()); - } - - [TestMethod] - public void EnsureAcceptsLastEntryWithoutComma() - { - tokens.AddRange(new List - { - "asdf", "}" - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(1, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Once()); - - Assert.AreEqual("asdf", addedEnumMember.Name); - Assert.AreEqual(0L, addedEnumMember.Value); - } - - [TestMethod] - public void EnsureAcceptsLastEntryWithoutCommaWithValueSpecified() - { - tokens.AddRange(new List - { - "asdf", "=", "1336", "}" - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(3, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Once()); - - Assert.AreEqual("asdf", addedEnumMember.Name); - Assert.AreEqual(1336L, addedEnumMember.Value); - } - - [TestMethod] - public void EnsureAcceptsOtherEnumValues() - { - var previousMember = new EnumMember("prev", 1335); - - parserStateMock.Setup(state => state.FindEnumMember("prev")).Returns(previousMember); - - tokens.AddRange(new List - { - "asdf", "=", "prev", "," - }); - - var test = new TestEnumMember(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Once()); - - Assert.AreEqual("asdf", addedEnumMember.Name); - Assert.AreEqual(1335L, addedEnumMember.Value); - } - - [TestMethod] - public void EnsureThrowsErrorIfPreviousEnumValueNotDeclared() - { - tokens.AddRange(new List - { - "asdf", "=", "prev", "," - }); - - var test = new TestEnumMember(); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Never()); - } - - [TestMethod] - public void EnsureThrowsErrorIfTopBlockIsNotEnum() - { - var blockMock = new Mock(parserStateMock.Object, BlockType.None); - parserStateMock.SetupGet(state => state.CurrentBlock).Returns(blockMock.Object); - tokens.AddRange(new List - { - "asdf", "=", "0", "," - }); - - var test = new TestEnumMember(); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - enumMock.Verify(_enum => _enum.AddMember(It.IsAny()), Times.Never()); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestEnumTest.cs b/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestEnumTest.cs deleted file mode 100644 index 0fc60abb..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestEnumTest.cs +++ /dev/null @@ -1,394 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.C_Header; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGeneratorTests.Parsing.C_Header.Tests -{ - [TestClass] - public class TestEnumTest - { - private Mock parserStateMock; - private Block pushedBlock; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - parserStateMock = new Mock(); - - parserStateMock.Setup(state => state.PushBlock(It.IsAny())) - .Callback((Block block) => pushedBlock = block); - - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - } - - [TestMethod] - public void EnsureAcceptsSimpleEnumOpening() - { - tokens.AddRange(new List - { - "enum", "test_enum", "{", "test" - }); - - var test = new TestEnum(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(3, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Once()); - parserStateMock.VerifyNoOtherCalls(); - - if (pushedBlock is BlockEnum blockEnum) - { - Assert.AreEqual("test_enum", blockEnum.Name); - Assert.IsFalse(blockEnum.IsTypedef); - Assert.AreEqual(DataTypeBaseType.INT, blockEnum.ParentType); - } - else - Assert.Fail("Pushed block is supposed to be an enum"); - } - - [TestMethod] - public void EnsureAcceptsEnumAsTypedef() - { - tokens.AddRange(new List - { - "typedef", "enum", "test_enum", "{", "test" - }); - - var test = new TestEnum(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Once()); - parserStateMock.VerifyNoOtherCalls(); - - if (pushedBlock is BlockEnum blockEnum) - { - Assert.AreEqual("test_enum", blockEnum.Name); - Assert.IsTrue(blockEnum.IsTypedef); - Assert.AreEqual(DataTypeBaseType.INT, blockEnum.ParentType); - } - else - Assert.Fail("Pushed block is supposed to be an enum"); - } - - [TestMethod] - public void EnsureAcceptsEnumWithParentTypeSpecified() - { - parserStateMock.Setup(state => state.FindType("unsigned char")).Returns(DataTypeBaseType.UNSIGNED_CHAR); - - tokens.AddRange(new List - { - "enum", "test_enum", ":", "unsigned", "char", "{", "test" - }); - - var test = new TestEnum(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(6, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Once()); - - if (pushedBlock is BlockEnum blockEnum) - { - Assert.AreEqual("test_enum", blockEnum.Name); - Assert.IsFalse(blockEnum.IsTypedef); - Assert.AreEqual(DataTypeBaseType.UNSIGNED_CHAR, blockEnum.ParentType); - } - else - Assert.Fail("Pushed block is supposed to be an enum"); - } - - [TestMethod] - public void EnsureAcceptsEnumWithParentTypeAsTypedef() - { - var typeDeclaration = new TypeDeclaration(DataTypeBaseType.SHORT, new List()); - var typedef = new DataTypeTypedef("", "bla_blub", typeDeclaration); - parserStateMock.Setup(state => state.FindType("bla_blub")).Returns(typedef); - - tokens.AddRange(new List - { - "enum", "test_enum", ":", "bla_blub", "{", "test" - }); - - var test = new TestEnum(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(5, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Once()); - - if (pushedBlock is BlockEnum blockEnum) - { - Assert.AreEqual("test_enum", blockEnum.Name); - Assert.IsFalse(blockEnum.IsTypedef); - Assert.AreEqual(DataTypeBaseType.SHORT, blockEnum.ParentType); - } - else - Assert.Fail("Pushed block is supposed to be an enum"); - } - - [TestMethod] - public void EnsureAcceptsEnumWithParentTypeAsTypedefWithNamespace() - { - var typeDeclaration = new TypeDeclaration(DataTypeBaseType.SHORT, new List()); - var typedef = new DataTypeTypedef("std", "bla_blub", typeDeclaration); - parserStateMock.Setup(state => state.FindType("std::bla_blub")).Returns(typedef); - - tokens.AddRange(new List - { - "enum", "test_enum", ":", "std", ":", ":", "bla_blub", "{", "test" - }); - - var test = new TestEnum(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(8, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Once()); - - if (pushedBlock is BlockEnum blockEnum) - { - Assert.AreEqual("test_enum", blockEnum.Name); - Assert.IsFalse(blockEnum.IsTypedef); - Assert.AreEqual(DataTypeBaseType.SHORT, blockEnum.ParentType); - } - else - Assert.Fail("Pushed block is supposed to be an enum"); - } - - [TestMethod] - public void EnsureRejectsEnumWithInvalidParentType() - { - tokens.AddRange(new List - { - "enum", "test_enum", ":", "non_existant", "{", "test" - }); - - var test = new TestEnum(); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Never()); - parserStateMock.Verify(state => state.FindType("non_existant"), Times.Once()); - } - - [TestMethod] - public void EnsureRejectsEnumWithParentTypeAsTypedefWithArray() - { - var typeDeclaration = new TypeDeclaration(DataTypeBaseType.SHORT, new List - { - new ReferenceTypeArray(3) - }); - var typedef = new DataTypeTypedef("", "bla_blub", typeDeclaration); - parserStateMock.Setup(state => state.FindType("bla_blub")).Returns(typedef); - - tokens.AddRange(new List - { - "enum", "test_enum", ":", "bla_blub", "{", "test" - }); - - var test = new TestEnum(); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Never()); - parserStateMock.Verify(state => state.FindType("bla_blub"), Times.Once()); - } - - [TestMethod] - public void EnsureRejectsEnumWithParentTypeAsTypedefWithPointerDepth() - { - var typeDeclaration = new TypeDeclaration(DataTypeBaseType.SHORT, new List - { - new ReferenceTypePointer() - }); - var typedef = new DataTypeTypedef("", "bla_blub", typeDeclaration); - parserStateMock.Setup(state => state.FindType("bla_blub")).Returns(typedef); - - tokens.AddRange(new List - { - "enum", "test_enum", ":", "bla_blub", "{", "test" - }); - - var test = new TestEnum(); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Never()); - parserStateMock.Verify(state => state.FindType("bla_blub"), Times.Once()); - } - - [TestMethod] - public void EnsureRejectsEnumWithParentTypeNotBaseType() - { - var _struct = new DataTypeStruct("", "bla_blub", 4); - parserStateMock.Setup(state => state.FindType("bla_blub")).Returns(_struct); - - tokens.AddRange(new List - { - "enum", "test_enum", ":", "bla_blub", "{", "test" - }); - - var test = new TestEnum(); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Never()); - parserStateMock.Verify(state => state.FindType("bla_blub"), Times.Once()); - } - - [TestMethod] - public void EnsureRejectsEnumWithParentTypeTypedefNotBaseType() - { - var _struct = new DataTypeStruct("", "bla_blub", 4); - var typeDeclaration = new TypeDeclaration(_struct, new List()); - var typedef = new DataTypeTypedef("", "bla_blub", typeDeclaration); - parserStateMock.Setup(state => state.FindType("bla_blub")).Returns(typedef); - - tokens.AddRange(new List - { - "enum", "test_enum", ":", "bla_blub", "{", "test" - }); - - var test = new TestEnum(); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Never()); - parserStateMock.Verify(state => state.FindType("bla_blub"), Times.Once()); - } - - [TestMethod] - public void EnsureRejectsWhenKeywordIsWrong() - { - tokens.AddRange(new List - { - "notenum", "test_enum", "{", "test" - }); - - var test = new TestEnum(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Never()); - parserStateMock.VerifyNoOtherCalls(); - } - - [TestMethod] - public void EnsureRejectsWhenNameIsWrong() - { - tokens.AddRange(new List - { - "enum", "3name", "{", "test" - }); - - var test = new TestEnum(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Never()); - parserStateMock.VerifyNoOtherCalls(); - } - - [TestMethod] - public void EnsureRejectsWhenNoCurlyBrackets() - { - tokens.AddRange(new List - { - "enum", "test_enum", "test", "test2" - }); - - var test = new TestEnum(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Never()); - parserStateMock.VerifyNoOtherCalls(); - } - - [TestMethod] - public void EnsureRejectsWhenDoubleColonButNoType() - { - tokens.AddRange(new List - { - "enum", "test_enum", ":", "{", "test" - }); - - var test = new TestEnum(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Never()); - parserStateMock.VerifyNoOtherCalls(); - } - - [TestMethod] - public void EnsureRejectsWhenDoubleColonAndTypeButNoBracket() - { - tokens.AddRange(new List - { - "enum", "test_enum", ":", "short", "test" - }); - - var test = new TestEnum(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Never()); - parserStateMock.VerifyNoOtherCalls(); - } - - [TestMethod] - public void EnsureNameIsGeneratedIfNoneExisting() - { - tokens.AddRange(new List - { - "enum", "{", "test" - }); - - var test = new TestEnum(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(2, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny()), Times.Once()); - parserStateMock.VerifyNoOtherCalls(); - - if (pushedBlock is BlockEnum blockEnum) - { - Assert.IsFalse(string.IsNullOrEmpty(blockEnum.Name)); - Assert.IsFalse(blockEnum.IsTypedef); - Assert.AreEqual(DataTypeBaseType.INT, blockEnum.ParentType); - } - else - Assert.Fail("Pushed block is supposed to be an enum"); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestForwardDeclTest.cs b/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestForwardDeclTest.cs deleted file mode 100644 index f100a1d7..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestForwardDeclTest.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.C_Header; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGeneratorTests.Parsing.C_Header.Tests -{ - [TestClass] - public class TestForwardDeclTest - { - private Mock parserStateMock; - private ForwardDeclaration addedForwardDeclaration; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - private Namespace currentNamespace; - - [TestInitialize] - public void Setup() - { - currentNamespace = new Namespace(); - parserStateMock = new Mock(); - - parserStateMock.SetupGet(state => state.CurrentNamespace).Returns(() => currentNamespace); - parserStateMock.Setup(state => state.AddForwardDeclaration(It.IsAny())) - .Callback((ForwardDeclaration forwardDeclaration) => addedForwardDeclaration = forwardDeclaration); - - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - } - - [TestMethod] - public void EnsureAcceptsForwardDeclarationForEnums() - { - tokens.AddRange(new List - { - "enum", "test_enum", ";" - }); - - var test = new TestForwardDecl(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(3, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddForwardDeclaration(It.IsAny()), Times.Once()); - - Assert.AreEqual("", addedForwardDeclaration.Namespace); - Assert.AreEqual("test_enum", addedForwardDeclaration.Name); - Assert.AreEqual(DataTypeType.Enum, addedForwardDeclaration.Type); - } - - [TestMethod] - public void EnsureAcceptsForwardDeclarationForStructs() - { - tokens.AddRange(new List - { - "struct", "test_struct", ";" - }); - - var test = new TestForwardDecl(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(3, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddForwardDeclaration(It.IsAny()), Times.Once()); - - Assert.AreEqual("", addedForwardDeclaration.Namespace); - Assert.AreEqual("test_struct", addedForwardDeclaration.Name); - Assert.AreEqual(DataTypeType.Struct, addedForwardDeclaration.Type); - } - - [TestMethod] - public void EnsureAcceptsForwardDeclarationForUnions() - { - tokens.AddRange(new List - { - "union", "test_union", ";" - }); - - var test = new TestForwardDecl(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(3, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddForwardDeclaration(It.IsAny()), Times.Once()); - - Assert.AreEqual("", addedForwardDeclaration.Namespace); - Assert.AreEqual("test_union", addedForwardDeclaration.Name); - Assert.AreEqual(DataTypeType.Union, addedForwardDeclaration.Type); - } - - [TestMethod] - public void EnsureRejectsForwardDeclarationForNamespaces() - { - tokens.AddRange(new List - { - "namespace", "test_union", ";" - }); - - var test = new TestForwardDecl(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestNamespaceTest.cs b/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestNamespaceTest.cs deleted file mode 100644 index 165e4bbf..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestNamespaceTest.cs +++ /dev/null @@ -1,140 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.C_Header; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGeneratorTests.Parsing.C_Header.Tests -{ - [TestClass] - public class TestNamespaceTest - { - private Mock parserStateMock; - private Block pushedBlock; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - parserStateMock = new Mock(); - pushedBlock = null; - - parserStateMock.Setup(state => state.PushBlock(It.IsAny())) - .Callback((Block block) => pushedBlock = block); - - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - } - - [TestMethod] - public void EnsureAcceptsNamespaceDeclaration() - { - tokens.AddRange(new List - { - "namespace", "some_namespace", "{" - }); - - var test = new TestNamespace(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(3, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny())); - parserStateMock.VerifyNoOtherCalls(); - - if (pushedBlock is BlockNamespace namespaceBlock) - { - Assert.AreEqual("some_namespace", namespaceBlock.Name); - } - else - Assert.Fail("Pushed block is supposed to be a namespace"); - } - - [TestMethod] - public void EnsureAcceptsNamespacesWithSpecialCharacters() - { - tokens.AddRange(new List - { - "namespace", "$omeW3irdN4m3sp4c3", "{" - }); - - var test = new TestNamespace(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(3, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.PushBlock(It.IsAny())); - parserStateMock.VerifyNoOtherCalls(); - - if (pushedBlock is BlockNamespace namespaceBlock) - { - Assert.AreEqual("$omeW3irdN4m3sp4c3", namespaceBlock.Name); - } - else - Assert.Fail("Pushed block is supposed to be a namespace"); - } - - [TestMethod] - public void EnsureCanOnlyHaveOneNamespaceName() - { - tokens.AddRange(new List - { - "namespace", "namespace_name", "another_namespace_name", "{" - }); - - var test = new TestNamespace(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - parserStateMock.VerifyNoOtherCalls(); - } - - [TestMethod] - public void EnsureNeedsOpeningCurlyBrackets() - { - tokens.AddRange(new List - { - "namespace", "namespace_name", "" - }); - - var test = new TestNamespace(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - parserStateMock.VerifyNoOtherCalls(); - } - - [TestMethod] - public void EnsureRejectsNameWithDigitAsFirstCharacter() - { - tokens.AddRange(new List - { - "namespace", "1ns", "{" - }); - - var test = new TestNamespace(); - - Assert.AreEqual(TokenTestResult.NoMatch, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(0, test.ConsumedTokenCount); - - parserStateMock.VerifyNoOtherCalls(); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestStructTest.cs b/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestStructTest.cs deleted file mode 100644 index 85964ff5..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestStructTest.cs +++ /dev/null @@ -1,181 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.C_Header; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGeneratorTests.Parsing.C_Header.Tests -{ - [TestClass] - public class TestStructTest - { - private Mock parserStateMock; - private List typesOfState; - private Namespace currentNamespace; - private BlockStruct pushedStruct; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - currentNamespace = new Namespace(); - - parserStateMock = new Mock(); - typesOfState = new List(); - parserStateMock.SetupGet(state => state.CurrentNamespace) - .Returns(() => currentNamespace); - parserStateMock.Setup(state => state.PushBlock(It.IsAny())) - .Callback((Block block) => pushedStruct = block as BlockStruct); - parserStateMock.Setup(state => state.FindType(It.IsAny())) - .Returns((string query) => typesOfState.FirstOrDefault(type => type.FullName.Equals(query))); - - pushedStruct = null; - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - } - - [TestMethod] - public void EnsureAcceptsSimpleStructStatement() - { - tokens.AddRange(new List - { - "struct", "{" - }); - - var test = new TestStruct(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(2, test.ConsumedTokenCount); - - Assert.IsNotNull(pushedStruct); - Assert.IsFalse(pushedStruct.IsTypedef); - } - - [TestMethod] - public void EnsureAcceptsNamedStructStatement() - { - tokens.AddRange(new List - { - "struct", "test_struct", "{" - }); - - var test = new TestStruct(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(3, test.ConsumedTokenCount); - - Assert.IsNotNull(pushedStruct); - Assert.IsFalse(pushedStruct.IsTypedef); - Assert.AreEqual("test_struct", pushedStruct.Name); - } - - [TestMethod] - public void EnsureCanBeTypedef() - { - tokens.AddRange(new List - { - "typedef", "struct", "test_struct", "{" - }); - - var test = new TestStruct(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - Assert.IsNotNull(pushedStruct); - Assert.IsTrue(pushedStruct.IsTypedef); - Assert.AreEqual("test_struct", pushedStruct.Name); - } - - [TestMethod] - public void EnsureAcceptsCustomSpecifiedAlignment() - { - tokens.AddRange(new List - { - "struct", "__declspec", "(", "align", "(", "64", ")", ")", "test_struct", "{" - }); - - var test = new TestStruct(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(10, test.ConsumedTokenCount); - - Assert.IsNotNull(pushedStruct); - Assert.IsFalse(pushedStruct.IsTypedef); - Assert.AreEqual("test_struct", pushedStruct.Name); - Assert.AreEqual(64, pushedStruct.CustomAlignment); - } - - [TestMethod] - public void EnsureCanSpecifyParent() - { - tokens.AddRange(new List - { - "struct", "test_struct", ":", "test", ":", ":", "parent", "{" - }); - - var test = new TestStruct(); - - var parent = new DataTypeStruct("test", "parent", 4); - var parentEntry = new Variable("test_int", new TypeDeclaration(DataTypeBaseType.INT, new List())); - parent.Members.Add(parentEntry); - typesOfState.Add(parent); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(8, test.ConsumedTokenCount); - - Assert.IsNotNull(pushedStruct); - Assert.IsFalse(pushedStruct.IsTypedef); - Assert.AreEqual("test_struct", pushedStruct.Name); - Assert.AreEqual(1, pushedStruct.Variables.Count); - Assert.AreEqual(parentEntry, pushedStruct.Variables[0]); - } - - [TestMethod] - public void EnsureFailsWhenParentTypeCannotBeFound() - { - tokens.AddRange(new List - { - "struct", "test_struct", ":", "test", ":", ":", "parent", "{" - }); - - var test = new TestStruct(); - - Assert.ThrowsException( - () => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - - [TestMethod] - public void EnsureFailsWhenParentTypeIsNotDataTypeWithMembers() - { - tokens.AddRange(new List - { - "struct", "test_struct", ":", "test", ":", ":", "parent", "{" - }); - - var test = new TestStruct(); - - var testEnum = new DataTypeEnum("test", "parent", DataTypeBaseType.INT); - typesOfState.Add(testEnum); - - Assert.ThrowsException( - () => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestTypedefTest.cs b/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestTypedefTest.cs deleted file mode 100644 index 0d58939d..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestTypedefTest.cs +++ /dev/null @@ -1,291 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.C_Header; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGeneratorTests.Parsing.C_Header.Tests -{ - [TestClass] - public class TestTypedefTest - { - private Mock parserStateMock; - private List typesOfState; - private Namespace currentNamespace; - private DataTypeTypedef addedTypedef; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - currentNamespace = new Namespace(); - - parserStateMock = new Mock(); - typesOfState = new List(); - parserStateMock.SetupGet(state => state.CurrentNamespace) - .Returns(() => currentNamespace); - parserStateMock.Setup(state => state.AddDataType(It.IsAny())) - .Callback((DataType dataType) => addedTypedef = (DataTypeTypedef)dataType); - parserStateMock.Setup(state => state.FindType(It.IsAny())) - .Returns((string typename) => - { - return typesOfState.Concat(DataTypeBaseType.BASE_TYPES) - .FirstOrDefault(type => type.FullName.Equals(typename)); - }); - - addedTypedef = null; - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - } - - [TestMethod] - public void EnsureAcceptsSimpleTypedef() - { - tokens.AddRange(new List - { - "typedef", "char", "new_typedef", ";" - }); - - var test = new TestTypedef(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddDataType(It.IsAny())); - - Assert.AreEqual("new_typedef", addedTypedef.FullName); - Assert.AreEqual(DataTypeBaseType.CHAR, addedTypedef.TypeDefinition.Type); - Assert.IsFalse(addedTypedef.TypeDefinition.IsConst); - } - - [TestMethod] - public void EnsureMakesUseOfCurrentNamespace() - { - currentNamespace.Push("test_namespace"); - - tokens.AddRange(new List - { - "typedef", "char", "new_typedef", ";" - }); - - var test = new TestTypedef(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddDataType(It.IsAny())); - - Assert.AreEqual("test_namespace::new_typedef", addedTypedef.FullName); - } - - [TestMethod] - public void EnsureCorrectlyHandlesTypesWithMoreThanOneToken() - { - tokens.AddRange(new List - { - "typedef", "const", "unsigned", "int", "new_typedef", ";" - }); - - var test = new TestTypedef(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(6, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddDataType(It.IsAny())); - - Assert.AreEqual("new_typedef", addedTypedef.FullName); - Assert.AreEqual(DataTypeBaseType.UNSIGNED_INT, addedTypedef.TypeDefinition.Type); - Assert.IsTrue(addedTypedef.TypeDefinition.IsConst); - } - - [TestMethod] - public void EnsureHandlesPointers() - { - tokens.AddRange(new List - { - "typedef", "int", "*", "*", "*", "asdf", ";" - }); - - var test = new TestTypedef(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(7, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddDataType(It.IsAny())); - - Assert.AreEqual("asdf", addedTypedef.FullName); - Assert.AreEqual(DataTypeBaseType.INT, addedTypedef.TypeDefinition.Type); - Assert.IsFalse(addedTypedef.TypeDefinition.IsConst); - - Assert.AreEqual(3, addedTypedef.TypeDefinition.References.Count); - foreach (var typeDefinitionReference in addedTypedef.TypeDefinition.References) - { - Assert.IsInstanceOfType(typeDefinitionReference, typeof(ReferenceTypePointer)); - } - } - - [TestMethod] - public void EnsureHandlesArrays() - { - tokens.AddRange(new List - { - "typedef", "int", "asdf", "[", "3", "]", "[", "5", "]", ";" - }); - - var test = new TestTypedef(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(10, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddDataType(It.IsAny())); - - Assert.AreEqual("asdf", addedTypedef.FullName); - Assert.AreEqual(DataTypeBaseType.INT, addedTypedef.TypeDefinition.Type); - Assert.IsFalse(addedTypedef.TypeDefinition.IsConst); - - Assert.AreEqual(2, addedTypedef.TypeDefinition.References.Count); - foreach (var typeDefinitionReference in addedTypedef.TypeDefinition.References) - { - Assert.IsInstanceOfType(typeDefinitionReference, typeof(ReferenceTypeArray)); - } - - Assert.AreEqual(3, ((ReferenceTypeArray) addedTypedef.TypeDefinition.References[0]).ArraySize); - Assert.AreEqual(5, ((ReferenceTypeArray) addedTypedef.TypeDefinition.References[1]).ArraySize); - } - - [TestMethod] - public void EnsureCorrectlyHandlesArrayOfPointers() - { - tokens.AddRange(new List - { - "typedef", "int", "*", "*", "asdf", "[", "1337", "]", "[", "0x1A4", "]", ";" - }); - - var test = new TestTypedef(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(12, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddDataType(It.IsAny())); - - Assert.AreEqual("asdf", addedTypedef.FullName); - Assert.AreEqual(DataTypeBaseType.INT, addedTypedef.TypeDefinition.Type); - Assert.IsFalse(addedTypedef.TypeDefinition.IsConst); - - Assert.AreEqual(4, addedTypedef.TypeDefinition.References.Count); - Assert.IsInstanceOfType(addedTypedef.TypeDefinition.References[0], typeof(ReferenceTypeArray)); - Assert.IsInstanceOfType(addedTypedef.TypeDefinition.References[1], typeof(ReferenceTypeArray)); - Assert.IsInstanceOfType(addedTypedef.TypeDefinition.References[2], typeof(ReferenceTypePointer)); - Assert.IsInstanceOfType(addedTypedef.TypeDefinition.References[3], typeof(ReferenceTypePointer)); - - Assert.AreEqual(1337, ((ReferenceTypeArray) addedTypedef.TypeDefinition.References[0]).ArraySize); - Assert.AreEqual(0x1A4, ((ReferenceTypeArray) addedTypedef.TypeDefinition.References[1]).ArraySize); - } - - [TestMethod] - public void EnsureCorrectlyHandlesPointerToArray() - { - tokens.AddRange(new List - { - "typedef", "int", "(", "*", "*", "asdf", ")", "[", "1337", "]", "[", "0x1A4", "]", ";" - }); - - var test = new TestTypedef(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(14, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddDataType(It.IsAny())); - - Assert.AreEqual("asdf", addedTypedef.FullName); - Assert.AreEqual(DataTypeBaseType.INT, addedTypedef.TypeDefinition.Type); - Assert.IsFalse(addedTypedef.TypeDefinition.IsConst); - - Assert.AreEqual(4, addedTypedef.TypeDefinition.References.Count); - Assert.IsInstanceOfType(addedTypedef.TypeDefinition.References[0], typeof(ReferenceTypePointer)); - Assert.IsInstanceOfType(addedTypedef.TypeDefinition.References[1], typeof(ReferenceTypePointer)); - Assert.IsInstanceOfType(addedTypedef.TypeDefinition.References[2], typeof(ReferenceTypeArray)); - Assert.IsInstanceOfType(addedTypedef.TypeDefinition.References[3], typeof(ReferenceTypeArray)); - - Assert.AreEqual(1337, ((ReferenceTypeArray) addedTypedef.TypeDefinition.References[2]).ArraySize); - Assert.AreEqual(0x1A4, ((ReferenceTypeArray) addedTypedef.TypeDefinition.References[3]).ArraySize); - } - - [TestMethod] - public void EnsureHandlesCustomSpecifiedAlignment() - { - tokens.AddRange(new List - { - "typedef", "__declspec", "(", "align", "(", "16", ")", ")", "int", "*", "my_type_align_16", ";" - }); - - var test = new TestTypedef(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(12, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddDataType(It.IsAny())); - - Assert.AreEqual("my_type_align_16", addedTypedef.FullName); - Assert.AreEqual(DataTypeBaseType.INT, addedTypedef.TypeDefinition.Type); - Assert.IsFalse(addedTypedef.TypeDefinition.IsConst); - Assert.AreEqual(16, addedTypedef.AlignmentOverride); - - Assert.AreEqual(1, addedTypedef.TypeDefinition.References.Count); - Assert.IsInstanceOfType(addedTypedef.TypeDefinition.References[0], typeof(ReferenceTypePointer)); - } - - [TestMethod] - public void EnsureTestFailsWhenTypeCannotBeFound() - { - tokens.AddRange(new List - { - "typedef", "some_type", "invalid_typedef", ";" - }); - - var test = new TestTypedef(); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - - [TestMethod] - public void EnsureCanUseCustomTypes() - { - tokens.AddRange(new List - { - "typedef", "some_type", "custom_typedef", ";" - }); - - var test = new TestTypedef(); - - var someType = new DataTypeStruct("", "some_type", 4); - typesOfState.Add(someType); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - parserStateMock.Verify(state => state.AddDataType(It.IsAny())); - - Assert.AreEqual("custom_typedef", addedTypedef.FullName); - Assert.AreEqual(someType, addedTypedef.TypeDefinition.Type); - Assert.IsFalse(addedTypedef.TypeDefinition.IsConst); - - Assert.AreEqual(0, addedTypedef.TypeDefinition.References.Count); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestUnionTest.cs b/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestUnionTest.cs deleted file mode 100644 index 9e397d1f..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestUnionTest.cs +++ /dev/null @@ -1,181 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.C_Header; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGeneratorTests.Parsing.C_Header.Tests -{ - [TestClass] - public class TestUnionTest - { - private Mock parserStateMock; - private List typesOfState; - private Namespace currentNamespace; - private BlockUnion pushedUnion; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - currentNamespace = new Namespace(); - - parserStateMock = new Mock(); - typesOfState = new List(); - parserStateMock.SetupGet(state => state.CurrentNamespace) - .Returns(() => currentNamespace); - parserStateMock.Setup(state => state.PushBlock(It.IsAny())) - .Callback((Block block) => pushedUnion = block as BlockUnion); - parserStateMock.Setup(state => state.FindType(It.IsAny())) - .Returns((string query) => typesOfState.FirstOrDefault(type => type.FullName.Equals(query))); - - pushedUnion = null; - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - } - - [TestMethod] - public void EnsureAcceptsSimpleUnionStatement() - { - tokens.AddRange(new List - { - "union", "{" - }); - - var test = new TestUnion(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(2, test.ConsumedTokenCount); - - Assert.IsNotNull(pushedUnion); - Assert.IsFalse(pushedUnion.IsTypedef); - } - - [TestMethod] - public void EnsureAcceptsNamedUnionStatement() - { - tokens.AddRange(new List - { - "union", "test_union", "{" - }); - - var test = new TestUnion(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(3, test.ConsumedTokenCount); - - Assert.IsNotNull(pushedUnion); - Assert.IsFalse(pushedUnion.IsTypedef); - Assert.AreEqual("test_union", pushedUnion.Name); - } - - [TestMethod] - public void EnsureCanBeTypedef() - { - tokens.AddRange(new List - { - "typedef", "union", "test_union", "{" - }); - - var test = new TestUnion(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - Assert.IsNotNull(pushedUnion); - Assert.IsTrue(pushedUnion.IsTypedef); - Assert.AreEqual("test_union", pushedUnion.Name); - } - - [TestMethod] - public void EnsureAcceptsCustomSpecifiedAlignment() - { - tokens.AddRange(new List - { - "union", "__declspec", "(", "align", "(", "64", ")", ")", "test_union", "{" - }); - - var test = new TestUnion(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(10, test.ConsumedTokenCount); - - Assert.IsNotNull(pushedUnion); - Assert.IsFalse(pushedUnion.IsTypedef); - Assert.AreEqual("test_union", pushedUnion.Name); - Assert.AreEqual(64, pushedUnion.CustomAlignment); - } - - [TestMethod] - public void EnsureCanSpecifyParent() - { - tokens.AddRange(new List - { - "union", "test_union", ":", "test", ":", ":", "parent", "{" - }); - - var test = new TestUnion(); - - var parent = new DataTypeUnion("test", "parent", 4); - var parentEntry = new Variable("test_int", new TypeDeclaration(DataTypeBaseType.INT, new List())); - parent.Members.Add(parentEntry); - typesOfState.Add(parent); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(8, test.ConsumedTokenCount); - - Assert.IsNotNull(pushedUnion); - Assert.IsFalse(pushedUnion.IsTypedef); - Assert.AreEqual("test_union", pushedUnion.Name); - Assert.AreEqual(1, pushedUnion.Variables.Count); - Assert.AreEqual(parentEntry, pushedUnion.Variables[0]); - } - - [TestMethod] - public void EnsureFailsWhenParentTypeCannotBeFound() - { - tokens.AddRange(new List - { - "union", "test_union", ":", "test", ":", ":", "parent", "{" - }); - - var test = new TestUnion(); - - Assert.ThrowsException( - () => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - - [TestMethod] - public void EnsureFailsWhenParentTypeIsNotDataTypeWithMembers() - { - tokens.AddRange(new List - { - "union", "test_union", ":", "test", ":", ":", "parent", "{" - }); - - var test = new TestUnion(); - - var testEnum = new DataTypeEnum("test", "parent", DataTypeBaseType.INT); - typesOfState.Add(testEnum); - - Assert.ThrowsException( - () => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestVariableTest.cs b/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestVariableTest.cs deleted file mode 100644 index c8610339..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/C_Header/Tests/TestVariableTest.cs +++ /dev/null @@ -1,443 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.C_Header; -using ZoneCodeGenerator.Parsing.C_Header.Blocks; -using ZoneCodeGenerator.Parsing.C_Header.Tests; -using ZoneCodeGenerator.Parsing.Testing; - -namespace ZoneCodeGeneratorTests.Parsing.C_Header.Tests -{ - [TestClass] - public class TestVariableTest - { - private Mock parserStateMock; - private List typesOfState; - private Namespace currentNamespace; - private Stack blocks; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - currentNamespace = new Namespace(); - blocks = new Stack(); - - parserStateMock = new Mock(); - typesOfState = new List(); - parserStateMock.SetupGet(state => state.CurrentNamespace) - .Returns(() => currentNamespace); - parserStateMock.SetupGet(state => state.CurrentBlock) - .Returns(() => blocks.Peek()); - parserStateMock.Setup(state => state.FindType(It.IsAny())) - .Returns((string query) => typesOfState.Concat(DataTypeBaseType.BASE_TYPES).FirstOrDefault(type => type.FullName.Equals(query))); - - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - } - - [TestMethod] - public void EnsureAcceptsSimpleVariableStatement() - { - tokens.AddRange(new List - { - "int", "test", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(3, test.ConsumedTokenCount); - - Assert.AreEqual(1, block.Variables.Count); - - var variable = block.Variables[0]; - - Assert.AreEqual("test", variable.Name); - Assert.IsNull(variable.AlignmentOverride); - Assert.IsFalse(variable.VariableType.IsConst); - Assert.IsFalse(variable.VariableType.HasCustomBitSize); - - Assert.AreEqual(0, variable.VariableType.References.Count); - Assert.AreEqual(DataTypeBaseType.INT, variable.VariableType.Type); - } - - [TestMethod] - public void EnsureAcceptsCustomStructures() - { - tokens.AddRange(new List - { - "test_namespace", ":", ":", "customStruct", "hey_ho", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var customStruct = new DataTypeStruct("test_namespace", "customStruct", 4); - typesOfState.Add(customStruct); - - var test = new TestVariable(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(6, test.ConsumedTokenCount); - - Assert.AreEqual(1, block.Variables.Count); - - var variable = block.Variables[0]; - - Assert.AreEqual("hey_ho", variable.Name); - Assert.IsNull(variable.AlignmentOverride); - Assert.IsFalse(variable.VariableType.IsConst); - Assert.IsFalse(variable.VariableType.HasCustomBitSize); - - Assert.AreEqual(0, variable.VariableType.References.Count); - Assert.AreEqual(customStruct, variable.VariableType.Type); - } - - [TestMethod] - public void EnsureFailsWhenTypeCannotBeFound() - { - tokens.AddRange(new List - { - "test_namespace", ":", ":", "customStruct", "hey_ho", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.ThrowsException( - () => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - - [TestMethod] - public void EnsureCanHandlePointers() - { - tokens.AddRange(new List - { - "float", "*", "santa_claus", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - Assert.AreEqual(1, block.Variables.Count); - - var variable = block.Variables[0]; - - Assert.AreEqual("santa_claus", variable.Name); - Assert.IsNull(variable.AlignmentOverride); - Assert.IsFalse(variable.VariableType.IsConst); - Assert.IsFalse(variable.VariableType.HasCustomBitSize); - - Assert.AreEqual(1, variable.VariableType.References.Count); - Assert.IsInstanceOfType(variable.VariableType.References[0], typeof(ReferenceTypePointer)); - - Assert.AreEqual(DataTypeBaseType.FLOAT, variable.VariableType.Type); - } - - [TestMethod] - public void EnsureCanHandleMultiPointers() - { - tokens.AddRange(new List - { - "float", "*", "*", "*", "*", "santa_claus", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(7, test.ConsumedTokenCount); - - Assert.AreEqual(1, block.Variables.Count); - - var variable = block.Variables[0]; - - Assert.AreEqual("santa_claus", variable.Name); - Assert.IsNull(variable.AlignmentOverride); - Assert.IsFalse(variable.VariableType.IsConst); - Assert.IsFalse(variable.VariableType.HasCustomBitSize); - - Assert.AreEqual(4, variable.VariableType.References.Count); - Assert.IsInstanceOfType(variable.VariableType.References[0], typeof(ReferenceTypePointer)); - Assert.IsInstanceOfType(variable.VariableType.References[1], typeof(ReferenceTypePointer)); - Assert.IsInstanceOfType(variable.VariableType.References[2], typeof(ReferenceTypePointer)); - Assert.IsInstanceOfType(variable.VariableType.References[3], typeof(ReferenceTypePointer)); - - Assert.AreEqual(DataTypeBaseType.FLOAT, variable.VariableType.Type); - } - - [TestMethod] - public void EnsureCanHandleArrays() - { - tokens.AddRange(new List - { - "double", "pepper", "[", "9", "]", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(6, test.ConsumedTokenCount); - - Assert.AreEqual(1, block.Variables.Count); - - var variable = block.Variables[0]; - - Assert.AreEqual("pepper", variable.Name); - Assert.IsNull(variable.AlignmentOverride); - Assert.IsFalse(variable.VariableType.IsConst); - Assert.IsFalse(variable.VariableType.HasCustomBitSize); - - Assert.AreEqual(1, variable.VariableType.References.Count); - Assert.IsInstanceOfType(variable.VariableType.References[0], typeof(ReferenceTypeArray)); - Assert.AreEqual(9, ((ReferenceTypeArray) variable.VariableType.References[0]).ArraySize); - - Assert.AreEqual(DataTypeBaseType.DOUBLE, variable.VariableType.Type); - } - - [TestMethod] - public void EnsureCanHandleMultipleArrays() - { - tokens.AddRange(new List - { - "long", "long", "salt", "[", "4", "]", "[", "2", "]", "[", "1", "]", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(13, test.ConsumedTokenCount); - - Assert.AreEqual(1, block.Variables.Count); - - var variable = block.Variables[0]; - - Assert.AreEqual("salt", variable.Name); - Assert.IsNull(variable.AlignmentOverride); - Assert.IsFalse(variable.VariableType.IsConst); - Assert.IsFalse(variable.VariableType.HasCustomBitSize); - - Assert.AreEqual(3, variable.VariableType.References.Count); - Assert.IsInstanceOfType(variable.VariableType.References[0], typeof(ReferenceTypeArray)); - Assert.AreEqual(4, ((ReferenceTypeArray) variable.VariableType.References[0]).ArraySize); - Assert.IsInstanceOfType(variable.VariableType.References[1], typeof(ReferenceTypeArray)); - Assert.AreEqual(2, ((ReferenceTypeArray) variable.VariableType.References[1]).ArraySize); - Assert.IsInstanceOfType(variable.VariableType.References[2], typeof(ReferenceTypeArray)); - Assert.AreEqual(1, ((ReferenceTypeArray) variable.VariableType.References[2]).ArraySize); - - Assert.AreEqual(DataTypeBaseType.LONG_LONG, variable.VariableType.Type); - } - - [TestMethod] - public void EnsureCanHandleArrayOfPointers() - { - tokens.AddRange(new List - { - "unsigned", "long", "long", "*", "*", "what_a_var", "[", "6", "]", "[", "9", "]", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(13, test.ConsumedTokenCount); - - Assert.AreEqual(1, block.Variables.Count); - - var variable = block.Variables[0]; - - Assert.AreEqual("what_a_var", variable.Name); - Assert.IsNull(variable.AlignmentOverride); - Assert.IsFalse(variable.VariableType.IsConst); - Assert.IsFalse(variable.VariableType.HasCustomBitSize); - - Assert.AreEqual(4, variable.VariableType.References.Count); - Assert.IsInstanceOfType(variable.VariableType.References[0], typeof(ReferenceTypeArray)); - Assert.AreEqual(6, ((ReferenceTypeArray) variable.VariableType.References[0]).ArraySize); - Assert.IsInstanceOfType(variable.VariableType.References[1], typeof(ReferenceTypeArray)); - Assert.AreEqual(9, ((ReferenceTypeArray) variable.VariableType.References[1]).ArraySize); - Assert.IsInstanceOfType(variable.VariableType.References[2], typeof(ReferenceTypePointer)); - Assert.IsInstanceOfType(variable.VariableType.References[3], typeof(ReferenceTypePointer)); - - Assert.AreEqual(DataTypeBaseType.UNSIGNED_LONG_LONG, variable.VariableType.Type); - } - - [TestMethod] - public void EnsureCanHandlePointerToArray() - { - tokens.AddRange(new List - { - "unsigned", "char", "(", "*", "*", "send_halp", ")", "[", "1", "]", "[", "3", "]", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(14, test.ConsumedTokenCount); - - Assert.AreEqual(1, block.Variables.Count); - - var variable = block.Variables[0]; - - Assert.AreEqual("send_halp", variable.Name); - Assert.IsNull(variable.AlignmentOverride); - Assert.IsFalse(variable.VariableType.IsConst); - Assert.IsFalse(variable.VariableType.HasCustomBitSize); - - Assert.AreEqual(4, variable.VariableType.References.Count); - Assert.IsInstanceOfType(variable.VariableType.References[0], typeof(ReferenceTypePointer)); - Assert.IsInstanceOfType(variable.VariableType.References[1], typeof(ReferenceTypePointer)); - Assert.IsInstanceOfType(variable.VariableType.References[2], typeof(ReferenceTypeArray)); - Assert.AreEqual(1, ((ReferenceTypeArray) variable.VariableType.References[2]).ArraySize); - Assert.IsInstanceOfType(variable.VariableType.References[3], typeof(ReferenceTypeArray)); - Assert.AreEqual(3, ((ReferenceTypeArray) variable.VariableType.References[3]).ArraySize); - - Assert.AreEqual(DataTypeBaseType.UNSIGNED_CHAR, variable.VariableType.Type); - } - - [TestMethod] - public void EnsureAcceptsConstVariables() - { - tokens.AddRange(new List - { - "const", "int", "test", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - Assert.AreEqual(1, block.Variables.Count); - - var variable = block.Variables[0]; - - Assert.AreEqual("test", variable.Name); - Assert.IsNull(variable.AlignmentOverride); - Assert.IsTrue(variable.VariableType.IsConst); - Assert.IsFalse(variable.VariableType.HasCustomBitSize); - - Assert.AreEqual(0, variable.VariableType.References.Count); - Assert.AreEqual(DataTypeBaseType.INT, variable.VariableType.Type); - } - - [TestMethod] - public void EnsureAcceptsConstPointerVariables() - { - tokens.AddRange(new List - { - "const", "char", "*", "str", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(5, test.ConsumedTokenCount); - - Assert.AreEqual(1, block.Variables.Count); - - var variable = block.Variables[0]; - - Assert.AreEqual("str", variable.Name); - Assert.IsNull(variable.AlignmentOverride); - Assert.IsTrue(variable.VariableType.IsConst); - Assert.IsFalse(variable.VariableType.HasCustomBitSize); - - Assert.AreEqual(1, variable.VariableType.References.Count); - Assert.IsInstanceOfType(variable.VariableType.References[0], typeof(ReferenceTypePointer)); - Assert.AreEqual(DataTypeBaseType.CHAR, variable.VariableType.Type); - } - - [TestMethod] - public void EnsureAcceptsCustomBitSizes() - { - tokens.AddRange(new List - { - "int", "test", ":", "3", ";" - }); - - var block = new BlockStruct(parserStateMock.Object, "test_struct", false); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(5, test.ConsumedTokenCount); - - Assert.AreEqual(1, block.Variables.Count); - - var variable = block.Variables[0]; - - Assert.AreEqual("test", variable.Name); - Assert.IsNull(variable.AlignmentOverride); - Assert.IsFalse(variable.VariableType.IsConst); - - Assert.IsTrue(variable.VariableType.HasCustomBitSize); - Assert.AreEqual(3, variable.VariableType.CustomBitSize); - - Assert.AreEqual(0, variable.VariableType.References.Count); - Assert.AreEqual(DataTypeBaseType.INT, variable.VariableType.Type); - } - - [TestMethod] - public void EnsureThrowsExceptionWhenNotInBlockThatCanHoldVariables() - { - tokens.AddRange(new List - { - "int", "test", ";" - }); - - var block = new BlockNamespace(parserStateMock.Object, "asdf"); - blocks.Push(block); - - var test = new TestVariable(); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Impl/CommandFilePreprocessorTest.cs b/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Impl/CommandFilePreprocessorTest.cs deleted file mode 100644 index 7a36faf8..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Impl/CommandFilePreprocessorTest.cs +++ /dev/null @@ -1,76 +0,0 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using ZoneCodeGenerator.Parsing.CommandFile.Impl; -using ZoneCodeGeneratorTests.Parsing.Mock; - -namespace ZoneCodeGeneratorTests.Parsing.CommandFile.Impl -{ - [TestClass] - public class PreprocessorTest - { - private IncludingParsingStreamTest headerStreamTest; - - private CommandFilePreprocessor preprocessor; - - [TestInitialize] - public void Setup() - { - headerStreamTest = new IncludingParsingStreamTest("file.h"); - preprocessor = new CommandFilePreprocessor(headerStreamTest); - } - - [TestMethod] - public void EnsureReturnsUnmodifiedText() - { - string[] stringsThatShouldNotBeModified = - { - "This is a normal string", - "There is nothing to be preprocessed!", - "0124124124 # 124124124", - "...", - "asdf", - "" - }; - - headerStreamTest.Lines.AddRange(stringsThatShouldNotBeModified); - - foreach (var stringThatShouldNotBeModified in stringsThatShouldNotBeModified) - { - Assert.AreEqual(stringThatShouldNotBeModified, preprocessor.ReadLine()); - } - } - - [TestMethod] - public void EnsureIncludeChangesFileWhenUsingQuotationMarks() - { - headerStreamTest.Lines.AddRange(new[] - { - "include \"asdf.h\"", - "include \"file/path/to/header.h\"" - }); - preprocessor.ReadLine(); - Assert.AreEqual(1, headerStreamTest.IncludeCount); - Assert.AreEqual("asdf.h", headerStreamTest.LastInclude); - - preprocessor.ReadLine(); - Assert.AreEqual(2, headerStreamTest.IncludeCount); - Assert.AreEqual("file/path/to/header.h", headerStreamTest.LastInclude); - } - - [TestMethod] - public void EnsureIncludeChangesFileWhenUsingCarets() - { - headerStreamTest.Lines.AddRange(new[] - { - "include ", - "include " - }); - preprocessor.ReadLine(); - Assert.AreEqual(1, headerStreamTest.IncludeCount); - Assert.AreEqual("asdf.h", headerStreamTest.LastInclude); - - preprocessor.ReadLine(); - Assert.AreEqual(2, headerStreamTest.IncludeCount); - Assert.AreEqual("file/path/to/header.h", headerStreamTest.LastInclude); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestAssetTest.cs b/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestAssetTest.cs deleted file mode 100644 index 274258e1..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestAssetTest.cs +++ /dev/null @@ -1,176 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.CommandFile; -using ZoneCodeGenerator.Parsing.CommandFile.Tests; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGeneratorTests.Parsing.CommandFile.Tests -{ - [TestClass] - public class TestAssetTest - { - private Mock repositoryMock; - private Mock parserStateMock; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - parserStateMock = new Mock(); - - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - repositoryMock = new Mock(); - - parserStateMock.SetupGet(state => state.Repository) - .Returns(() => repositoryMock.Object); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - } - - [TestMethod] - public void EnsureAcceptsSimpleAssetStatement() - { - tokens.AddRange(new List - { - "asset", "test", ":", ":", "type", "TEST_TYPE_NUMBER", ";" - }); - - var test = new TestAsset(); - var assetStruct = new DataTypeStruct("test", "type", 4); - var assetInformation = new StructureInformation(assetStruct); - - var assetEnum = new DataTypeEnum("", "testEnum", DataTypeBaseType.INT); - var assetEnumEntry = new EnumMember("TEST_TYPE_NUMBER", 1337); - assetEnum.Members.Add(assetEnumEntry); - - repositoryMock.Setup(repository => repository.GetDataTypeByName("test::type")) - .Returns(assetStruct); - repositoryMock.Setup(repository => repository.GetInformationFor(assetStruct)) - .Returns(() => assetInformation); - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[]{assetEnum}); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(7, test.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureThrowsExceptionWhenTypeCannotBeFound() - { - tokens.AddRange(new List - { - "asset", "test", ":", ":", "type", "TEST_TYPE_NUMBER", ";" - }); - - var test = new TestAsset(); - var assetStruct = new DataTypeStruct("test", "type", 4); - var assetInformation = new StructureInformation(assetStruct); - - var assetEnum = new DataTypeEnum("", "testEnum", DataTypeBaseType.INT); - var assetEnumEntry = new EnumMember("TEST_TYPE_NUMBER", 1337); - assetEnum.Members.Add(assetEnumEntry); - - repositoryMock.Setup(repository => repository.GetInformationFor(It.IsAny())) - .Returns(() => assetInformation); - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[]{assetEnum}); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - - [TestMethod] - public void EnsureThrowsExceptionWhenNoInformationForAssetCanBeFound() - { - tokens.AddRange(new List - { - "asset", "test", ":", ":", "type", "TEST_TYPE_NUMBER", ";" - }); - - var test = new TestAsset(); - var assetStruct = new DataTypeStruct("test", "type", 4); - - var assetEnum = new DataTypeEnum("", "testEnum", DataTypeBaseType.INT); - var assetEnumEntry = new EnumMember("TEST_TYPE_NUMBER", 1337); - assetEnum.Members.Add(assetEnumEntry); - - repositoryMock.Setup(repository => repository.GetDataTypeByName("test::type")) - .Returns(assetStruct); - repositoryMock.Setup(repository => repository.GetInformationFor(assetStruct)) - .Returns(() => null); - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[] { assetEnum }); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - - [TestMethod] - public void EnsureThrowsExceptionWhenEnumEntryCannotBeFound() - { - tokens.AddRange(new List - { - "asset", "test", ":", ":", "type", "TEST_TYPE_NUMBER", ";" - }); - - var test = new TestAsset(); - var assetStruct = new DataTypeStruct("test", "type", 4); - var assetInformation = new StructureInformation(assetStruct); - - var assetEnum = new DataTypeEnum("", "testEnum", DataTypeBaseType.INT); - var assetEnumEntry = new EnumMember("NOT_THE_RIGHT_ENTRY", 420); - assetEnum.Members.Add(assetEnumEntry); - - repositoryMock.Setup(repository => repository.GetDataTypeByName("test::type")) - .Returns(assetStruct); - repositoryMock.Setup(repository => repository.GetInformationFor(assetStruct)) - .Returns(() => assetInformation); - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[]{assetEnum}); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - - [TestMethod] - public void EnsureThrowsExceptionWhenAssetIsNotADataTypeWithMembers() - { - tokens.AddRange(new List - { - "asset", "test", ":", ":", "type", "TEST_TYPE_NUMBER", ";" - }); - - var test = new TestAsset(); - var asset = new DataTypeEnum("test", "type", DataTypeBaseType.INT); - var assetStruct = new DataTypeStruct("test", "type", 4); - var assetInformation = new StructureInformation(assetStruct); - - var assetEnum = new DataTypeEnum("", "testEnum", DataTypeBaseType.INT); - var assetEnumEntry = new EnumMember("TEST_TYPE_NUMBER", 1337); - assetEnum.Members.Add(assetEnumEntry); - - repositoryMock.Setup(repository => repository.GetDataTypeByName("test::type")) - .Returns(asset); - repositoryMock.Setup(repository => repository.GetInformationFor(It.IsAny())) - .Returns(() => assetInformation); - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[] { assetEnum }); - - Assert.ThrowsException(() => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - } -} \ No newline at end of file diff --git a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestBlockTest.cs b/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestBlockTest.cs deleted file mode 100644 index 8ddc6944..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestBlockTest.cs +++ /dev/null @@ -1,279 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.FastFileStructure; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.CommandFile; -using ZoneCodeGenerator.Parsing.CommandFile.Tests; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGeneratorTests.Parsing.CommandFile.Tests -{ - [TestClass] - public class TestBlockTest - { - private Mock repositoryMock; - private Mock parserStateMock; - - private List fastFileBlocks; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - parserStateMock = new Mock(); - - fastFileBlocks = new List(); - - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - repositoryMock = new Mock(); - - parserStateMock.SetupGet(state => state.Repository) - .Returns(() => repositoryMock.Object); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - - parserStateMock.SetupGet(state => state.FastFileBlocks) - .Returns(() => fastFileBlocks); - } - - [TestMethod] - public void EnsureAcceptsSimpleTempBlockStatement() - { - tokens.AddRange(new List - { - "block", "temp", "SomeThing", ";" - }); - - var test = new TestBlock(); - - var assetTypeEnum = new DataTypeEnum("", "AssetTypeEnum", DataTypeBaseType.INT); - var enumEntry1 = new EnumMember("whatever", 1); - var enumEntry2 = new EnumMember("SomeThing", 513); - assetTypeEnum.Members.Add(enumEntry1); - assetTypeEnum.Members.Add(enumEntry2); - - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[] { assetTypeEnum }); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - Assert.AreEqual(1, fastFileBlocks.Count); - - var block = fastFileBlocks[0]; - - Assert.AreEqual("SomeThing", block.Name); - Assert.AreEqual(513, block.Index); - Assert.AreEqual(FastFileBlock.Type.Temp, block.BlockType); - Assert.IsTrue(block.IsTemp); - } - - [TestMethod] - public void EnsureAcceptsSimpleRuntimeBlockStatement() - { - tokens.AddRange(new List - { - "block", "runtime", "ASSET_TYPE_RUNTIME", ";" - }); - - var test = new TestBlock(); - - var assetTypeEnum = new DataTypeEnum("", "AssetTypeEnum", DataTypeBaseType.INT); - var enumEntry1 = new EnumMember("whatever", 1); - var enumEntry2 = new EnumMember("ASSET_TYPE_RUNTIME", 11); - assetTypeEnum.Members.Add(enumEntry1); - assetTypeEnum.Members.Add(enumEntry2); - - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[] { assetTypeEnum }); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - Assert.AreEqual(1, fastFileBlocks.Count); - - var block = fastFileBlocks[0]; - - Assert.AreEqual("ASSET_TYPE_RUNTIME", block.Name); - Assert.AreEqual(11, block.Index); - Assert.AreEqual(FastFileBlock.Type.Runtime, block.BlockType); - Assert.IsTrue(block.IsRuntime); - } - - [TestMethod] - public void EnsureAcceptsSimpleDelayBlockStatement() - { - tokens.AddRange(new List - { - "block", "delay", "ASSET_TYPE_DELAY", ";" - }); - - var test = new TestBlock(); - - var assetTypeEnum = new DataTypeEnum("", "AssetTypeEnum", DataTypeBaseType.INT); - var enumEntry1 = new EnumMember("whatever", 1); - var enumEntry2 = new EnumMember("ASSET_TYPE_DELAY", 133); - assetTypeEnum.Members.Add(enumEntry1); - assetTypeEnum.Members.Add(enumEntry2); - - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[] { assetTypeEnum }); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - Assert.AreEqual(1, fastFileBlocks.Count); - - var block = fastFileBlocks[0]; - - Assert.AreEqual("ASSET_TYPE_DELAY", block.Name); - Assert.AreEqual(133, block.Index); - Assert.AreEqual(FastFileBlock.Type.Delay, block.BlockType); - Assert.IsTrue(block.IsDelay); - } - - [TestMethod] - public void EnsureAcceptsSimpleNormalBlockStatement() - { - tokens.AddRange(new List - { - "block", "normal", "BLOCK_TYPE_LEET", ";" - }); - - var test = new TestBlock(); - - var assetTypeEnum = new DataTypeEnum("", "AssetTypeEnum", DataTypeBaseType.INT); - var enumEntryBlaze = new EnumMember("BLOCK_TYPE_BLAZE", 420); - var enumEntryLeet = new EnumMember("BLOCK_TYPE_LEET", 1337); - assetTypeEnum.Members.Add(enumEntryBlaze); - assetTypeEnum.Members.Add(enumEntryLeet); - - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[] { assetTypeEnum }); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - Assert.AreEqual(1, fastFileBlocks.Count); - - var block = fastFileBlocks[0]; - - Assert.AreEqual("BLOCK_TYPE_LEET", block.Name); - Assert.AreEqual(1337, block.Index); - Assert.AreEqual(FastFileBlock.Type.Normal, block.BlockType); - Assert.IsTrue(block.IsNormal); - } - - [TestMethod] - public void EnsureDoesNotExceptUnknownTypes() - { - tokens.AddRange(new List - { - "block", "unknowntype", "ASSET_TYPE_WHATEVER", ";" - }); - - var test = new TestBlock(); - - var assetTypeEnum = new DataTypeEnum("", "AssetTypeEnum", DataTypeBaseType.INT); - var enumEntry1 = new EnumMember("whatever", 1); - var enumEntry2 = new EnumMember("ASSET_TYPE_WHATEVER", 2); - assetTypeEnum.Members.Add(enumEntry1); - assetTypeEnum.Members.Add(enumEntry2); - - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[] { assetTypeEnum }); - - Assert.ThrowsException( - () => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - - [TestMethod] - public void EnsureDoesNotSetDefaultBlockWhenNotSpecified() - { - tokens.AddRange(new List - { - "block", "normal", "ASSET_TYPE_BLOCK", ";" - }); - - var test = new TestBlock(); - - var assetTypeEnum = new DataTypeEnum("", "AssetTypeEnum", DataTypeBaseType.INT); - var enumEntry = new EnumMember("ASSET_TYPE_BLOCK", 5); - assetTypeEnum.Members.Add(enumEntry); - - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[] { assetTypeEnum }); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(4, test.ConsumedTokenCount); - - Assert.AreEqual(1, fastFileBlocks.Count); - - var block = fastFileBlocks[0]; - Assert.IsFalse(block.IsDefault); - } - - [TestMethod] - public void EnsureDoesSetDefaultBlockWhenSpecified() - { - tokens.AddRange(new List - { - "block", "normal", "ASSET_TYPE_BLOCK", "default", ";" - }); - - var test = new TestBlock(); - - var assetTypeEnum = new DataTypeEnum("", "AssetTypeEnum", DataTypeBaseType.INT); - var enumEntry = new EnumMember("ASSET_TYPE_BLOCK", 5); - assetTypeEnum.Members.Add(enumEntry); - - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[] { assetTypeEnum }); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(5, test.ConsumedTokenCount); - - Assert.AreEqual(1, fastFileBlocks.Count); - - var block = fastFileBlocks[0]; - Assert.IsTrue(block.IsDefault); - } - - [TestMethod] - public void EnsureThrowsExceptionWhenEnumEntryCannotBeFound() - { - tokens.AddRange(new List - { - "block", "normal", "ASSET_TYPE_BLOCK", ";" - }); - - var test = new TestBlock(); - - var assetTypeEnum = new DataTypeEnum("", "AssetTypeEnum", DataTypeBaseType.INT); - var enumEntry1 = new EnumMember("whatever", 1); - var enumEntry2 = new EnumMember("ASSET_TYPE_SOMETHING_ELSE", 6); - assetTypeEnum.Members.Add(enumEntry1); - assetTypeEnum.Members.Add(enumEntry2); - - repositoryMock.Setup(repository => repository.GetAllEnums()) - .Returns(() => new[] { assetTypeEnum }); - - Assert.ThrowsException( - () => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - } -} \ No newline at end of file diff --git a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestCountTest.cs b/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestCountTest.cs deleted file mode 100644 index f7ee4f23..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestCountTest.cs +++ /dev/null @@ -1,514 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.Evaluation; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.CommandFile.Impl; -using ZoneCodeGenerator.Parsing.CommandFile.Tests; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGeneratorTests.Parsing.CommandFile.Tests -{ - [TestClass] - public class TestCountTest - { - private IDataRepository repository; - private CommandParserState parserState; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - - repository = new InMemoryDataRepository(); - parserState = new CommandParserState(repository); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - } - - [TestMethod] - public void EnsureCanHandleSimpleCountStatement() - { - tokens.AddRange(new List - { - "set", "count", "test_struct", ":", ":", "ptrEntry", "5", ";" - }); - - var test = new TestCount(); - - var testStruct = new DataTypeStruct("", "test_struct", 4); - - var pointerReference = new ReferenceTypePointer(); - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List(new[] {pointerReference}))); - testStruct.Members.Add(ptrEntry); - - repository.Add(testStruct); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserState, lexerMock.Object)); - Assert.AreEqual(8, test.ConsumedTokenCount); - - Assert.AreNotEqual(ReferenceTypePointer.DefaultCount, pointerReference.Count); - Assert.IsTrue(pointerReference.Count.IsStatic); - - Assert.IsInstanceOfType(pointerReference.Count, typeof(OperandStatic)); - Assert.AreEqual(5, ((OperandStatic) pointerReference.Count).Value); - } - - [TestMethod] - public void EnsureCanHandleReferenceToSubStruct() - { - tokens.AddRange(new List - { - "set", "count", "papaStruct", ":", ":", "kiddo", ":", ":", "ptrEntry", "5", ";" - }); - - var test = new TestCount(); - - var parentStruct = new DataTypeStruct("", "papaStruct", 4); - var testStruct = new DataTypeStruct("", "test_struct", 4); - - var childEntry = new Variable("kiddo", new TypeDeclaration(testStruct, new List())); - parentStruct.Members.Add(childEntry); - - var pointerReference = new ReferenceTypePointer(); - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List(new[] {pointerReference}))); - testStruct.Members.Add(ptrEntry); - - repository.Add(testStruct); - repository.Add(parentStruct); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserState, lexerMock.Object)); - Assert.AreEqual(11, test.ConsumedTokenCount); - - Assert.AreNotEqual(ReferenceTypePointer.DefaultCount, pointerReference.Count); - Assert.IsTrue(pointerReference.Count.IsStatic); - - Assert.IsInstanceOfType(pointerReference.Count, typeof(OperandStatic)); - Assert.AreEqual(5, ((OperandStatic) pointerReference.Count).Value); - } - - [TestMethod] - public void EnsureFailsWhenStructureCannotBeFound() - { - tokens.AddRange(new List - { - "set", "count", "test_struct", ":", ":", "ptrEntry", "5", ";" - }); - - var test = new TestCount(); - - Assert.ThrowsException(() => test.PerformTest(parserState, lexerMock.Object)); - } - - [TestMethod] - public void EnsureFailsWhenReferencingStructAndNotMembers() - { - tokens.AddRange(new List - { - "set", "count", "test_struct", "5", ";" - }); - - var test = new TestCount(); - - var testStruct = new DataTypeStruct("", "test_struct", 4); - - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List())); - testStruct.Members.Add(ptrEntry); - - repository.Add(testStruct); - - Assert.ThrowsException(() => test.PerformTest(parserState, lexerMock.Object)); - } - - [TestMethod] - public void EnsureFailsWhenReferencedMemberHasNoPointerReference() - { - tokens.AddRange(new List - { - "set", "count", "test_struct", ":", ":", "ptrEntry", "5", ";" - }); - - var test = new TestCount(); - - var testStruct = new DataTypeStruct("", "test_struct", 4); - - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List())); - testStruct.Members.Add(ptrEntry); - - repository.Add(testStruct); - - Assert.ThrowsException(() => test.PerformTest(parserState, lexerMock.Object)); - } - - [TestMethod] - public void EnsureCanHandleMultipleOperations() - { - tokens.AddRange(new List - { - "set", "count", "test_struct", ":", ":", "ptrEntry", "1", "+", "countEntry", "*", "2", ";" - }); - - var test = new TestCount(); - - var testStruct = new DataTypeStruct("", "test_struct", 4); - - var pointerReference = new ReferenceTypePointer(); - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List(new[] {pointerReference}))); - testStruct.Members.Add(ptrEntry); - - var countEntry = new Variable("countEntry", - new TypeDeclaration(DataTypeBaseType.UNSIGNED_INT, new List())); - testStruct.Members.Add(countEntry); - - repository.Add(testStruct); - var testStructInfo = repository.GetInformationFor(testStruct); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserState, lexerMock.Object)); - Assert.AreEqual(12, test.ConsumedTokenCount); - - Assert.AreNotEqual(ReferenceTypePointer.DefaultCount, pointerReference.Count); - Assert.IsFalse(pointerReference.Count.IsStatic); - - Assert.IsInstanceOfType(pointerReference.Count, typeof(Operation)); - - var countOperation = (Operation) pointerReference.Count; - Assert.AreEqual(OperationType.OperationAdd, countOperation.OperationType); - - Assert.IsInstanceOfType(countOperation.Operand1, typeof(OperandStatic)); - Assert.AreEqual(1, ((OperandStatic) countOperation.Operand1).Value); - - Assert.IsInstanceOfType(countOperation.Operand2, typeof(Operation)); - var multiplicationOperation = (Operation) countOperation.Operand2; - Assert.AreEqual(OperationType.OperationMultiply, multiplicationOperation.OperationType); - - Assert.IsInstanceOfType(multiplicationOperation.Operand2, typeof(OperandStatic)); - Assert.AreEqual(2, ((OperandStatic) multiplicationOperation.Operand2).Value); - - Assert.IsInstanceOfType(multiplicationOperation.Operand1, typeof(OperandDynamic)); - var ptrEntryDynamicOperand = (OperandDynamic) multiplicationOperation.Operand1; - Assert.AreEqual(testStructInfo, ptrEntryDynamicOperand.Structure); - Assert.AreEqual(1, ptrEntryDynamicOperand.ReferencedMemberChain.Count); - Assert.AreEqual(countEntry, ptrEntryDynamicOperand.ReferencedMemberChain[0].Member); - Assert.AreEqual(0, ptrEntryDynamicOperand.ArrayIndices.Count); - } - - [TestMethod] - public void EnsureCanHandleParenthesis() - { - tokens.AddRange(new List - { - "set", "count", "test_struct", ":", ":", "ptrEntry", "(", "1", "+", "countEntry", ")", "*", "2", ";" - }); - - var test = new TestCount(); - - var testStruct = new DataTypeStruct("", "test_struct", 4); - - var pointerReference = new ReferenceTypePointer(); - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List(new[] {pointerReference}))); - testStruct.Members.Add(ptrEntry); - - var countEntry = new Variable("countEntry", - new TypeDeclaration(DataTypeBaseType.UNSIGNED_INT, new List())); - testStruct.Members.Add(countEntry); - - repository.Add(testStruct); - var testStructInfo = repository.GetInformationFor(testStruct); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserState, lexerMock.Object)); - Assert.AreEqual(14, test.ConsumedTokenCount); - - Assert.AreNotEqual(ReferenceTypePointer.DefaultCount, pointerReference.Count); - Assert.IsFalse(pointerReference.Count.IsStatic); - - Assert.IsInstanceOfType(pointerReference.Count, typeof(Operation)); - - var countOperation = (Operation) pointerReference.Count; - Assert.AreEqual(OperationType.OperationMultiply, countOperation.OperationType); - - Assert.IsInstanceOfType(countOperation.Operand2, typeof(OperandStatic)); - Assert.AreEqual(2, ((OperandStatic) countOperation.Operand2).Value); - - Assert.IsInstanceOfType(countOperation.Operand1, typeof(Operation)); - var additionOperation = (Operation) countOperation.Operand1; - Assert.AreEqual(OperationType.OperationAdd, additionOperation.OperationType); - - Assert.IsInstanceOfType(additionOperation.Operand1, typeof(OperandStatic)); - Assert.AreEqual(1, ((OperandStatic) additionOperation.Operand1).Value); - - Assert.IsInstanceOfType(additionOperation.Operand2, typeof(OperandDynamic)); - var ptrEntryDynamicOperand = (OperandDynamic) additionOperation.Operand2; - Assert.AreEqual(testStructInfo, ptrEntryDynamicOperand.Structure); - Assert.AreEqual(1, ptrEntryDynamicOperand.ReferencedMemberChain.Count); - Assert.AreEqual(countEntry, ptrEntryDynamicOperand.ReferencedMemberChain[0].Member); - Assert.AreEqual(0, ptrEntryDynamicOperand.ArrayIndices.Count); - } - - [TestMethod] - public void EnsureCanHandleReferencesToDifferentStructs() - { - tokens.AddRange(new List - { - "set", "count", "test_struct", ":", ":", "ptrEntry", "1", "+", "someOtherStruct", ":", ":", - "countEntry", ";" - }); - - var test = new TestCount(); - - var testStruct = new DataTypeStruct("", "test_struct", 4); - var someOtherStruct = new DataTypeStruct("", "someOtherStruct", 4); - - var pointerReference = new ReferenceTypePointer(); - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List(new[] {pointerReference}))); - testStruct.Members.Add(ptrEntry); - - var countEntry = new Variable("countEntry", - new TypeDeclaration(DataTypeBaseType.UNSIGNED_INT, new List())); - someOtherStruct.Members.Add(countEntry); - - repository.Add(testStruct); - repository.Add(someOtherStruct); - - var someOtherStructInfo = repository.GetInformationFor(someOtherStruct); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserState, lexerMock.Object)); - Assert.AreEqual(13, test.ConsumedTokenCount); - - Assert.AreNotEqual(ReferenceTypePointer.DefaultCount, pointerReference.Count); - Assert.IsFalse(pointerReference.Count.IsStatic); - - Assert.IsInstanceOfType(pointerReference.Count, typeof(Operation)); - - var countOperation = (Operation) pointerReference.Count; - Assert.AreEqual(OperationType.OperationAdd, countOperation.OperationType); - - Assert.IsInstanceOfType(countOperation.Operand1, typeof(OperandStatic)); - Assert.AreEqual(1, ((OperandStatic) countOperation.Operand1).Value); - - Assert.IsInstanceOfType(countOperation.Operand2, typeof(OperandDynamic)); - var dynamicOperand = (OperandDynamic) countOperation.Operand2; - Assert.AreEqual(someOtherStructInfo, dynamicOperand.Structure); - Assert.AreEqual(1, dynamicOperand.ReferencedMemberChain.Count); - Assert.AreEqual(countEntry, dynamicOperand.ReferencedMemberChain[0].Member); - Assert.AreEqual(0, dynamicOperand.ArrayIndices.Count); - } - - [TestMethod] - public void EnsureCanHandleArrayIndices() - { - tokens.AddRange(new List - { - "set", "count", "test_struct", ":", ":", "ptrEntry", "1", "+", "countEntry", "[", "7", "]", "[", "4", - "]", ";" - }); - - var test = new TestCount(); - - var testStruct = new DataTypeStruct("", "test_struct", 4); - - var pointerReference = new ReferenceTypePointer(); - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List(new[] {pointerReference}))); - testStruct.Members.Add(ptrEntry); - - var countEntry = new Variable("countEntry", - new TypeDeclaration(DataTypeBaseType.UNSIGNED_INT, - new List(new[] {new ReferenceTypeArray(9), new ReferenceTypeArray(9)}))); - testStruct.Members.Add(countEntry); - - repository.Add(testStruct); - var testStructInfo = repository.GetInformationFor(testStruct); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserState, lexerMock.Object)); - Assert.AreEqual(16, test.ConsumedTokenCount); - - Assert.AreNotEqual(ReferenceTypePointer.DefaultCount, pointerReference.Count); - Assert.IsFalse(pointerReference.Count.IsStatic); - - Assert.IsInstanceOfType(pointerReference.Count, typeof(Operation)); - - var countOperation = (Operation) pointerReference.Count; - Assert.AreEqual(OperationType.OperationAdd, countOperation.OperationType); - - Assert.IsInstanceOfType(countOperation.Operand1, typeof(OperandStatic)); - Assert.AreEqual(1, ((OperandStatic) countOperation.Operand1).Value); - - Assert.IsInstanceOfType(countOperation.Operand2, typeof(OperandDynamic)); - var dynamicOperand = (OperandDynamic) countOperation.Operand2; - Assert.AreEqual(testStructInfo, dynamicOperand.Structure); - Assert.AreEqual(1, dynamicOperand.ReferencedMemberChain.Count); - Assert.AreEqual(countEntry, dynamicOperand.ReferencedMemberChain[0].Member); - - Assert.AreEqual(2, dynamicOperand.ArrayIndices.Count); - Assert.IsTrue(dynamicOperand.ArrayIndices[0].IsStatic); - Assert.AreEqual(7, dynamicOperand.ArrayIndices[0].EvaluateNumeric()); - Assert.IsTrue(dynamicOperand.ArrayIndices[1].IsStatic); - Assert.AreEqual(4, dynamicOperand.ArrayIndices[1].EvaluateNumeric()); - } - - [TestMethod] - public void EnsureFailsWhenReferencingInvalidStructInDynamicOperand() - { - tokens.AddRange(new List - { - "set", "count", "test_struct", ":", ":", "ptrEntry", "1", "+", "someOtherStruct", ":", ":", - "countEntry", ";" - }); - - var test = new TestCount(); - - var testStruct = new DataTypeStruct("", "test_struct", 4); - - var pointerReference = new ReferenceTypePointer(); - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List(new[] {pointerReference}))); - testStruct.Members.Add(ptrEntry); - - var countEntry = new Variable("countEntry", - new TypeDeclaration(DataTypeBaseType.UNSIGNED_INT, - new List(new[] {new ReferenceTypeArray(9), new ReferenceTypeArray(9)}))); - testStruct.Members.Add(countEntry); - - repository.Add(testStruct); - - Assert.ThrowsException(() => test.PerformTest(parserState, lexerMock.Object)); - } - - [TestMethod] - public void EnsureCanReferenceNoMembersAsDynamicOperands() - { - tokens.AddRange(new List - { - "set", "count", "test_struct", ":", ":", "ptrEntry", "test_struct", ";" - }); - - var test = new TestCount(); - - var testStruct = new DataTypeStruct("", "test_struct", 4); - - var pointerReference = new ReferenceTypePointer(); - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List(new[] {pointerReference}))); - testStruct.Members.Add(ptrEntry); - - var countEntry = new Variable("countEntry", - new TypeDeclaration(DataTypeBaseType.UNSIGNED_INT, - new List(new[] {new ReferenceTypeArray(9), new ReferenceTypeArray(9)}))); - testStruct.Members.Add(countEntry); - - repository.Add(testStruct); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserState, lexerMock.Object)); - Assert.AreEqual(8, test.ConsumedTokenCount); - - Assert.AreNotEqual(ReferenceTypePointer.DefaultCount, pointerReference.Count); - Assert.IsFalse(pointerReference.Count.IsStatic); - - Assert.IsInstanceOfType(pointerReference.Count, typeof(OperandDynamic)); - Assert.AreEqual("test_struct", ((OperandDynamic)pointerReference.Count).Structure.Type.Name); - } - - [TestMethod] - public void EnsureCanReferenceUsingUsedStructure() - { - tokens.AddRange(new List - { - "set", "count", "ptrEntry", "5", ";" - }); - - var test = new TestCount(); - - var testStruct = new DataTypeStruct("", "test_struct", 4); - - var pointerReference = new ReferenceTypePointer(); - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List(new[] {pointerReference}))); - testStruct.Members.Add(ptrEntry); - - repository.Add(testStruct); - var testStructInfo = repository.GetInformationFor(testStruct); - parserState.DataTypeInUse = testStructInfo; - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserState, lexerMock.Object)); - Assert.AreEqual(5, test.ConsumedTokenCount); - - Assert.AreNotEqual(ReferenceTypePointer.DefaultCount, pointerReference.Count); - Assert.IsTrue(pointerReference.Count.IsStatic); - - Assert.IsInstanceOfType(pointerReference.Count, typeof(OperandStatic)); - Assert.AreEqual(5, ((OperandStatic) pointerReference.Count).Value); - } - - [TestMethod] - public void EnsureCanHandleReferencesToUsedStructure() - { - tokens.AddRange(new List - { - "set", "count", "test_struct", ":", ":", "ptrEntry", "1", "+", "countEntry", ";" - }); - - var test = new TestCount(); - - var testStruct = new DataTypeStruct("", "test_struct", 4); - var someOtherStruct = new DataTypeStruct("", "someOtherStruct", 4); - - var pointerReference = new ReferenceTypePointer(); - var ptrEntry = new Variable("ptrEntry", - new TypeDeclaration(DataTypeBaseType.INT, new List(new[] {pointerReference}))); - testStruct.Members.Add(ptrEntry); - - var countEntry = new Variable("countEntry", - new TypeDeclaration(DataTypeBaseType.UNSIGNED_INT, new List())); - someOtherStruct.Members.Add(countEntry); - - repository.Add(testStruct); - - repository.Add(someOtherStruct); - var someOtherStructInfo = repository.GetInformationFor(someOtherStruct); - parserState.DataTypeInUse = someOtherStructInfo; - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserState, lexerMock.Object)); - Assert.AreEqual(10, test.ConsumedTokenCount); - - Assert.AreNotEqual(ReferenceTypePointer.DefaultCount, pointerReference.Count); - Assert.IsFalse(pointerReference.Count.IsStatic); - - Assert.IsInstanceOfType(pointerReference.Count, typeof(Operation)); - - var countOperation = (Operation) pointerReference.Count; - Assert.AreEqual(OperationType.OperationAdd, countOperation.OperationType); - - Assert.IsInstanceOfType(countOperation.Operand1, typeof(OperandStatic)); - Assert.AreEqual(1, ((OperandStatic) countOperation.Operand1).Value); - - Assert.IsInstanceOfType(countOperation.Operand2, typeof(OperandDynamic)); - var dynamicOperand = (OperandDynamic) countOperation.Operand2; - Assert.AreEqual(someOtherStructInfo, dynamicOperand.Structure); - Assert.AreEqual(1, dynamicOperand.ReferencedMemberChain.Count); - Assert.AreEqual(countEntry, dynamicOperand.ReferencedMemberChain[0].Member); - Assert.AreEqual(0, dynamicOperand.ArrayIndices.Count); - } - } -} \ No newline at end of file diff --git a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestGameTest.cs b/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestGameTest.cs deleted file mode 100644 index e8a9121e..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestGameTest.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.CommandFile; -using ZoneCodeGenerator.Parsing.CommandFile.Tests; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGeneratorTests.Parsing.CommandFile.Tests -{ - [TestClass] - public class TestGameTest - { - private Mock repositoryMock; - private Mock parserStateMock; - - private string game; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - parserStateMock = new Mock(); - - game = ""; - - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - repositoryMock = new Mock(); - - parserStateMock.SetupGet(state => state.Repository) - .Returns(() => repositoryMock.Object); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - - parserStateMock.SetupGet(state => state.Game) - .Returns(() => game); - parserStateMock.SetupSet(state => state.Game = It.IsAny()) - .Callback((string s) => game = s); - } - - [TestMethod] - public void EnsureAcceptsSimpleGameStatement() - { - tokens.AddRange(new List - { - "game", "asdf", ";" - }); - - var test = new TestGame(); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(3, test.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureDoesNotAcceptMultipleGameStatements() - { - tokens.AddRange(new List - { - "game", "asdf", ";" - }); - - game = "alreadyAssignment"; - - var test = new TestGame(); - - Assert.ThrowsException( - () => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - } -} \ No newline at end of file diff --git a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestUseTest.cs b/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestUseTest.cs deleted file mode 100644 index a7cfbb41..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/CommandFile/Tests/TestUseTest.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Domain.FastFileStructure; -using ZoneCodeGenerator.Domain.Information; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.CommandFile; -using ZoneCodeGenerator.Parsing.CommandFile.Tests; -using ZoneCodeGenerator.Parsing.Testing; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGeneratorTests.Parsing.CommandFile.Tests -{ - [TestClass] - public class TestUseTest - { - private Mock repositoryMock; - private Mock parserStateMock; - - private StructureInformation usedType; - - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - [TestInitialize] - public void Setup() - { - parserStateMock = new Mock(); - - usedType = null; - - tokenOffset = 0; - tokens = new List(); - lexerMock = new Mock(); - repositoryMock = new Mock(); - - parserStateMock.SetupGet(state => state.Repository) - .Returns(() => repositoryMock.Object); - - repositoryMock.Setup(repository => repository.GetInformationFor(It.IsAny())) - .Returns((DataTypeWithMembers type) => new StructureInformation(type)); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - - parserStateMock.SetupGet(state => state.DataTypeInUse) - .Returns(() => usedType); - parserStateMock.SetupSet(state => state.DataTypeInUse = It.IsAny()) - .Callback((StructureInformation type) => usedType = type); - } - - [TestMethod] - public void EnsureAcceptsSimpleUseStatement() - { - tokens.AddRange(new List - { - "use", "test", ":", ":", "type", ";" - }); - - var test = new TestUse(); - - var assetTypeToUse = new DataTypeStruct("test", "type", 4); - - repositoryMock.Setup(repository => repository.GetDataTypeByName("test::type")) - .Returns(() => assetTypeToUse); - - Assert.AreEqual(TokenTestResult.Match, test.PerformTest(parserStateMock.Object, lexerMock.Object)); - Assert.AreEqual(6, test.ConsumedTokenCount); - - Assert.IsNotNull(assetTypeToUse); - Assert.AreEqual(usedType.Type, assetTypeToUse); - } - - [TestMethod] - public void EnsureThrowsExceptionWhenTypeIsNotFound() - { - tokens.AddRange(new List - { - "use", "test", ":", ":", "type", ";" - }); - - var test = new TestUse(); - - Assert.ThrowsException( - () => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - - [TestMethod] - public void EnsureThrowsExceptionWhenTypeIsNotDataTypeWithMembers() - { - tokens.AddRange(new List - { - "use", "test", ":", ":", "type", ";" - }); - - var test = new TestUse(); - - var _enum = new DataTypeEnum("test", "type", DataTypeBaseType.INT); - var enumEntry1 = new EnumMember("ENTRY_ONE", 1); - var enumEntry2 = new EnumMember("ENTRY_TWO", 2); - _enum.Members.Add(enumEntry1); - _enum.Members.Add(enumEntry2); - - repositoryMock.Setup(repository => repository.GetDataTypeByName("test::type")) - .Returns(() => _enum); - - Assert.ThrowsException( - () => test.PerformTest(parserStateMock.Object, lexerMock.Object)); - } - } -} \ No newline at end of file diff --git a/test/ZoneCodeGeneratorTests/Parsing/Impl/CommentProcessorTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Impl/CommentProcessorTest.cs deleted file mode 100644 index cac4ce75..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Impl/CommentProcessorTest.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System.Collections.Generic; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.Impl; -using ZoneCodeGenerator.Utils; - -namespace ZoneCodeGeneratorTests.Parsing.Impl -{ - [TestClass] - public class CommentPreprocessorTest - { - private ICommentProcessor commentProcessor; - - [TestInitialize] - public void Setup() - { - commentProcessor = new CommentProcessor(); - } - - [TestMethod] - public void EnsureReturnsUnmodifiedText() - { - string[] stringsThatShouldNotBeModified = - { - "This is a normal string", - "There is nothing to be preprocessed!", - "0124124124 # 124124124", - "...", - "asdf", - "" - }; - - foreach (var stringThatShouldNotBeModified in stringsThatShouldNotBeModified) - { - Assert.AreEqual(stringThatShouldNotBeModified, commentProcessor.RemoveComments(stringThatShouldNotBeModified)); - } - } - - [TestMethod] - public void EnsureDoesRemoveLineComments() - { - var commentStrings = new Dictionary() - { - {"// This is a comment at the beginning of the line", ""}, - {"Text in front of a comment // Comment", "Text in front of a comment"}, - {"/ / Not a comment", "/ / Not a comment"}, - {"asdf /// Triple slash is a comment", "asdf"}, - {"b2h3 /////////////// In fact after the first two slashes it should always be considered a comment", "b2h3"}, - }; - - foreach (var (input, expectedResult) in commentStrings) - { - Assert.AreEqual(expectedResult, commentProcessor.RemoveComments(input)); - } - } - - [TestMethod] - public void EnsureDoesRemoveBlockComments() - { - var commentStrings = new Dictionary() - { - {"/* This is a block comment */", ""}, - {"Text in front of a comment /** Comment ***/", "Text in front of a comment"}, - {"/ * Not a comment */", "/ * Not a comment */"}, - {"Text in front of comment /* Comment */ Text after the comment", "Text in front of comment Text after the comment"}, - {"Hello/*Hell*/World", "HelloWorld"}, - }; - - foreach (var (input, expectedResult) in commentStrings) - { - Assert.AreEqual(expectedResult, commentProcessor.RemoveComments(input)); - } - } - - [TestMethod] - public void EnsureBlockCommentsWorkOverMultipleLines() - { - var commentStrings = new Dictionary() - { - {"The start of the comment /* Is now", "The start of the comment"}, - {"Nothing to be seen here", ""}, - {"* / /* Still nothing", ""}, - {"The comment ends */ now", " now"}, - {"This line should not cause any issues", "This line should not cause any issues"}, - }; - - foreach (var (input, expectedResult) in commentStrings) - { - Assert.AreEqual(expectedResult, commentProcessor.RemoveComments(input)); - } - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Impl/LexerTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Impl/LexerTest.cs deleted file mode 100644 index 7c014b9d..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Impl/LexerTest.cs +++ /dev/null @@ -1,357 +0,0 @@ -using System.Collections.Generic; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using ZoneCodeGenerator.Parsing.Impl; -using ZoneCodeGeneratorTests.Parsing.Mock; - -namespace ZoneCodeGeneratorTests.Parsing.Impl -{ - [TestClass] - public class LexerTest - { - private IncludingParsingStreamTest headerStream; - private Lexer lexer; - - [TestInitialize] - public void Setup() - { - headerStream = new IncludingParsingStreamTest("file.h"); - lexer = new Lexer(headerStream); - } - - private void AssertTokenOutput(params string[] expectedTokens) - { - foreach (var token in expectedTokens) - Assert.AreEqual(token, lexer.NextToken()); - } - - [TestMethod] - public void EnsureCanSplitWords() - { - headerStream.Lines.AddRange(new List - { - "Some random tokens", - "right here" - }); - - AssertTokenOutput("Some", "random", "tokens", "right", "here"); - Assert.IsTrue(lexer.IsEndOfStream); - } - - [TestMethod] - public void EnsureCanSplitSpecialCharactersFromWords() - { - headerStream.Lines.AddRange(new List - { - "word1;word2; word3 ; word4 ;word5", - "word1:word2: word3 : word4 :word5", - "word1{word2{ word3 { word4 {word5", - "word1}word2} word3 } word4 }word5", - "word1,word2, word3 , word4 ,word5", - "word1.word2. word3 . word4 .word5", - "word1=word2= word3 = word4 =word5", - "word1(word2( word3 ( word4 (word5", - "word1)word2) word3 ) word4 )word5", - "word1*word2* word3 * word4 *word5", - "word1[word2[ word3 [ word4 [word5", - "word1]word2] word3 ] word4 ]word5", - "word1word2> word3 > word4 >word5", - "word1#word2# word3 # word4 #word5", - "word1&word2& word3 & word4 &word5", - "word1%word2% word3 % word4 %word5", - "word1\"word2\" word3 \" word4 \"word5", - "word1?word2? word3 ? word4 ?word5", - "word1!word2! word3 ! word4 !word5", - "word1+word2+ word3 + word4 +word5", - "word1-word2- word3 - word4 -word5", - "word1/word2/ word3 / word4 /word5", - "word1\\word2\\ word3 \\ word4 \\word5", - "word1|word2| word3 | word4 |word5", - }); - - AssertTokenOutput("word1", ";", "word2", ";", "word3", ";", "word4", ";", "word5"); - AssertTokenOutput("word1", ":", "word2", ":", "word3", ":", "word4", ":", "word5"); - AssertTokenOutput("word1", "{", "word2", "{", "word3", "{", "word4", "{", "word5"); - AssertTokenOutput("word1", "}", "word2", "}", "word3", "}", "word4", "}", "word5"); - AssertTokenOutput("word1", ",", "word2", ",", "word3", ",", "word4", ",", "word5"); - AssertTokenOutput("word1", ".", "word2", ".", "word3", ".", "word4", ".", "word5"); - AssertTokenOutput("word1", "=", "word2", "=", "word3", "=", "word4", "=", "word5"); - AssertTokenOutput("word1", "(", "word2", "(", "word3", "(", "word4", "(", "word5"); - AssertTokenOutput("word1", ")", "word2", ")", "word3", ")", "word4", ")", "word5"); - AssertTokenOutput("word1", "*", "word2", "*", "word3", "*", "word4", "*", "word5"); - AssertTokenOutput("word1", "[", "word2", "[", "word3", "[", "word4", "[", "word5"); - AssertTokenOutput("word1", "]", "word2", "]", "word3", "]", "word4", "]", "word5"); - AssertTokenOutput("word1", "<", "word2", "<", "word3", "<", "word4", "<", "word5"); - AssertTokenOutput("word1", ">", "word2", ">", "word3", ">", "word4", ">", "word5"); - AssertTokenOutput("word1", "#", "word2", "#", "word3", "#", "word4", "#", "word5"); - AssertTokenOutput("word1", "&", "word2", "&", "word3", "&", "word4", "&", "word5"); - AssertTokenOutput("word1", "%", "word2", "%", "word3", "%", "word4", "%", "word5"); - AssertTokenOutput("word1", "\"", "word2", "\"", "word3", "\"", "word4", "\"", "word5"); - AssertTokenOutput("word1", "?", "word2", "?", "word3", "?", "word4", "?", "word5"); - AssertTokenOutput("word1", "!", "word2", "!", "word3", "!", "word4", "!", "word5"); - AssertTokenOutput("word1", "+", "word2", "+", "word3", "+", "word4", "+", "word5"); - AssertTokenOutput("word1", "-", "word2", "-", "word3", "-", "word4", "-", "word5"); - AssertTokenOutput("word1", "/", "word2", "/", "word3", "/", "word4", "/", "word5"); - AssertTokenOutput("word1", "\\", "word2", "\\", "word3", "\\", "word4", "\\", "word5"); - AssertTokenOutput("word1", "|", "word2", "|", "word3", "|", "word4", "|", "word5"); - - Assert.IsTrue(lexer.IsEndOfStream); - } - - [TestMethod] - public void EnsurePeekingDoesNotConsumeTokens() - { - headerStream.Lines.AddRange(new List - { - "Some random tokens", - "right here" - }); - - Assert.AreEqual("Some", lexer.PeekToken()); - Assert.AreEqual("tokens", lexer.PeekToken(2)); - Assert.AreEqual("here", lexer.PeekToken(4)); - Assert.AreEqual("right", lexer.PeekToken(3)); - - - Assert.AreEqual("Some", lexer.NextToken()); - Assert.AreEqual("right", lexer.PeekToken(2)); - - AssertTokenOutput("random", "tokens", "right"); - - Assert.AreEqual("here", lexer.PeekToken()); - Assert.AreEqual("here", lexer.PeekToken()); - Assert.AreEqual("here", lexer.PeekToken()); - - Assert.AreEqual("here", lexer.NextToken()); - - Assert.IsTrue(lexer.IsEndOfStream); - } - - [TestMethod] - public void EnsurePeekingOutOfBoundsDoesNotCauseIssues() - { - headerStream.Lines.AddRange(new List - { - "Some random tokens", - "right here" - }); - - Assert.AreEqual("", lexer.PeekToken(1337)); - Assert.AreEqual("", lexer.PeekToken(5)); - Assert.AreEqual("", lexer.PeekToken(-2)); - - AssertTokenOutput("Some", "random", "tokens", "right", "here"); - Assert.IsTrue(lexer.IsEndOfStream); - - Assert.AreEqual("", lexer.PeekToken()); - Assert.AreEqual("", lexer.PeekToken(2)); - } - - [TestMethod] - public void EnsureGettingNextTokenAfterStreamEndDoesNotCauseIssues() - { - headerStream.Lines.AddRange(new List - { - "Some random tokens", - "right here" - }); - - AssertTokenOutput("Some", "random", "tokens", "right", "here"); - Assert.IsTrue(lexer.IsEndOfStream); - - Assert.AreEqual("", lexer.NextToken()); - Assert.AreEqual("", lexer.NextToken()); - } - - [TestMethod] - public void EnsureSkippingTokensWorksCorrectly() - { - headerStream.Lines.AddRange(new List - { - "Some random tokens", - "right here" - }); - - AssertTokenOutput("Some", "random"); - Assert.IsFalse(lexer.IsEndOfStream); - - lexer.SkipTokens(2); - - AssertTokenOutput("here"); - Assert.IsTrue(lexer.IsEndOfStream); - } - - [TestMethod] - public void EnsureSkippingNoTokensWorksCorrectly() - { - headerStream.Lines.AddRange(new List - { - "Some random tokens", - "right here" - }); - - AssertTokenOutput("Some", "random"); - Assert.IsFalse(lexer.IsEndOfStream); - - lexer.SkipTokens(0); - - AssertTokenOutput("tokens", "right", "here"); - Assert.IsTrue(lexer.IsEndOfStream); - } - - [TestMethod] - public void EnsureSkippingOutOfBoundsDoesNotCauseIssues() - { - headerStream.Lines.AddRange(new List - { - "Some random tokens", - "right here" - }); - - AssertTokenOutput("Some", "random"); - Assert.IsFalse(lexer.IsEndOfStream); - - lexer.SkipTokens(-5); - - AssertTokenOutput("tokens", "right"); - - lexer.SkipTokens(1337); - Assert.IsTrue(lexer.IsEndOfStream); - AssertTokenOutput(""); - } - - [TestMethod] - public void EnsureSkippingAfterStreamEndDoesNotCauseIssues() - { - headerStream.Lines.AddRange(new List - { - "Some random tokens", - "right here" - }); - - AssertTokenOutput("Some", "random", "tokens", "right", "here"); - Assert.IsTrue(lexer.IsEndOfStream); - - lexer.SkipTokens(1); - lexer.SkipTokens(2); - - Assert.IsTrue(lexer.IsEndOfStream); - } - - [TestMethod] - public void EnsureTheFilenameOfTheTokenIsCorrect() - { - headerStream.Lines.AddRange(new List - { - "Some", - "random", - "tokens", - "right", - "here" - }); - - Assert.AreEqual("file.h", lexer.CurrentFile); - AssertTokenOutput("Some"); - Assert.AreEqual("file.h", lexer.CurrentFile); - headerStream.Filename = "file2.h"; - AssertTokenOutput("random"); - headerStream.Filename = "file3.h"; - Assert.AreEqual("file3.h", lexer.CurrentFile); - } - - [TestMethod] - public void EnsureFilenameOfTokenStaysConsistent() - { - headerStream.Lines.AddRange(new List - { - "Some", - "random", - "tokens", - "right", - "here" - }); - - Assert.AreEqual("file.h", lexer.CurrentFile); - Assert.AreEqual("Some", lexer.PeekToken()); - - headerStream.Filename = "file2.h"; - - Assert.AreEqual("file.h", lexer.CurrentFile); - Assert.AreEqual("Some", lexer.PeekToken()); - Assert.AreEqual("file.h", lexer.CurrentFile); - - Assert.AreEqual("Some", lexer.NextToken()); - - Assert.AreEqual("file2.h", lexer.CurrentFile); - - AssertTokenOutput("random", "tokens", "right", "here"); - Assert.IsTrue(lexer.IsEndOfStream); - } - - [TestMethod] - public void EnsureTheLineOfTheTokenIsCorrect() - { - headerStream.Lines.AddRange(new List - { - "Some", - "random", - "tokens", - "right", - "here" - }); - - Assert.AreEqual(0, lexer.CurrentLine); - AssertTokenOutput("Some"); - Assert.AreEqual(1, lexer.CurrentLine); - AssertTokenOutput("random"); - Assert.AreEqual(2, lexer.CurrentLine); - - lexer.SkipTokens(1); - Assert.AreEqual(3, lexer.CurrentLine); - } - - [TestMethod] - public void EnsureLineOfTokenStaysConsistent() - { - headerStream.Lines.AddRange(new List - { - "Some", - "random", - "tokens", - "right", - "here" - }); - - Assert.AreEqual(0, lexer.CurrentLine); - Assert.AreEqual("Some", lexer.PeekToken()); - Assert.AreEqual("random", lexer.PeekToken(1)); - - headerStream.Line = 3; - - Assert.AreEqual(0, lexer.CurrentLine); - Assert.AreEqual("Some", lexer.PeekToken()); - Assert.AreEqual("Some", lexer.NextToken()); - - Assert.AreEqual(1, lexer.CurrentLine); - Assert.AreEqual("random", lexer.PeekToken()); - Assert.AreEqual("random", lexer.NextToken()); - - Assert.AreEqual(3, lexer.CurrentLine); - Assert.AreEqual("right", lexer.PeekToken()); - Assert.AreEqual("right", lexer.NextToken()); - } - - [TestMethod] - public void EnsureTreatsUnusedSpecialCharactersAsWordCharacters() - { - headerStream.Lines.AddRange(new List - { - "$ome _random token$", - "right here" - }); - - AssertTokenOutput("$ome", "_random", "token$", "right", "here"); - Assert.IsTrue(lexer.IsEndOfStream); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherArrayTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherArrayTest.cs deleted file mode 100644 index bed8b3a7..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherArrayTest.cs +++ /dev/null @@ -1,253 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; - -namespace ZoneCodeGeneratorTests.Parsing.Matching.Matchers -{ - [TestClass] - public class MatcherArrayTest - { - private Mock lexerMock; - private int tokenOffset; - private List tokens; - private MatchingContext matchingContext; - - [TestInitialize] - public void Setup() - { - tokenOffset = 0; - tokens = new List(); - - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - - matchingContext = new MatchingContext(lexerMock.Object, new Dictionary()); - } - - [TestMethod] - public void EnsureDecimalArraysAreRecognized() - { - tokens.AddRange(new List - { - "[", "15", "]" - }); - - var matcher = new MatcherArray(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureHexArraysAreRecognized() - { - tokens.AddRange(new List - { - "[", "0x20", "]" - }); - - var matcher = new MatcherArray(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureEnumValueArraysAreRecognized() - { - tokens.AddRange(new List - { - "[", "ENUM_VALUE", "]" - }); - - var matcher = new MatcherArray(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureInvalidEnumValueNameIsNotRecognized() - { - tokens.AddRange(new List - { - "[", "09INVALID", "]" - }); - - var matcher = new MatcherArray(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureFirstSquareBracketIsRequiredToBeRecognized() - { - tokens.AddRange(new List - { - "13", "]" - }); - - var matcher = new MatcherArray(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureSecondSquareBracketIsRequiredToBeRecognized() - { - tokens.AddRange(new List - { - "[", "13" - }); - - var matcher = new MatcherArray(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureSquareBracketsAreRequiredToBeRecognized() - { - tokens.AddRange(new List - { - "13" - }); - - var matcher = new MatcherArray(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureSquareBracketsNeedToBeInTheCorrectOrder() - { - tokens.AddRange(new List - { - "]", "13", "[" - }); - - var matcher = new MatcherArray(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureNamedOutputIsDecimalNumberForDecimalInput() - { - tokens.AddRange(new List - { - "[", "13", "]" - }); - - var matcher = new MatcherArray().WithName("array_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.ConsumedTokenCount); - Assert.AreEqual("13", result.NamedMatches["array_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureNamedOutputIsDecimalNumberForHexInput() - { - tokens.AddRange(new List - { - "[", "0x133", "]" - }); - - var matcher = new MatcherArray().WithName("array_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.ConsumedTokenCount); - Assert.AreEqual("307", result.NamedMatches["array_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureNamedOutputIsStringForEnumValueInput() - { - tokens.AddRange(new List - { - "[", "HELLO_WORLD", "]" - }); - - var matcher = new MatcherArray().WithName("array_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.ConsumedTokenCount); - Assert.AreEqual("HELLO_WORLD", result.NamedMatches["array_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureMakesCorrectUseOfTokenOffset() - { - tokens.AddRange(new List - { - "random", "string", "[", "5", "]", ";" - }); - - var matcher = new MatcherArray(); - var result = matcher.Test(matchingContext, 2); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureAddsTagWhenMatched() - { - tokens.AddRange(new List - { - "[", "42", "]", "randomString" - }); - - var matcher = new MatcherArray().WithTag("asdf"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.ConsumedTokenCount); - Assert.AreEqual(1, result.MatchedTags.Count); - Assert.AreEqual("asdf", result.MatchedTags[0]); - } - - [TestMethod] - public void EnsureDoesNotAddTagWhenNotMatched() - { - tokens.AddRange(new List - { - "nope", "[", "42", "]", "randomString" - }); - - var matcher = new MatcherArray().WithTag("asdf"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.AreEqual(0, result.MatchedTags.Count); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupAndTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupAndTest.cs deleted file mode 100644 index fa84b960..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupAndTest.cs +++ /dev/null @@ -1,177 +0,0 @@ -using System; -using System.Collections.Generic; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; - -namespace ZoneCodeGeneratorTests.Parsing.Matching.Matchers -{ - [TestClass] - public class MatcherGroupAndTest - { - private Mock lexerMock; - private MatchingContext matchingContext; - - [TestInitialize] - public void Setup() - { - lexerMock = new Mock(); - matchingContext = new MatchingContext(lexerMock.Object, new Dictionary()); - } - - [TestMethod] - public void EnsureAllTestsSuccessfulMakesGroupSuccessful() - { - var groupAnd = new MatcherGroupAnd - ( - new TestMatcher(true, 1), - new TestMatcher(true, 1), - new TestMatcher(true, 1), - new TestMatcher(true, 1) - ); - - var result = groupAnd.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(4, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureLastTestFailingLetsGroupFail() - { - var groupAnd = new MatcherGroupAnd - ( - new TestMatcher(true, 4), - new TestMatcher(true, 2), - new TestMatcher(true, 1), - new TestMatcher(false, 0) - ); - - var result = groupAnd.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureFirstTestFailingLetsGroupFail() - { - var groupAnd = new MatcherGroupAnd - ( - new TestMatcher(false, 0), - new TestMatcher(true, 1), - new TestMatcher(true, 1), - new TestMatcher(true, 1) - ); - - var result = groupAnd.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureTestsAreCalledWithCorrectTokenOffsets() - { - var testMatchers = new[] - { - new TestMatcher(true, 4), - new TestMatcher(true, 2), - new TestMatcher(true, 1), - new TestMatcher(false, 0), - new TestMatcher(true, 1) - }; - var iTokenMatcherArray = (TokenMatcher[])testMatchers.Clone(); - var groupAnd = new MatcherGroupAnd(iTokenMatcherArray); - - var result = groupAnd.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - - Assert.IsTrue(testMatchers[0].WasTested); - Assert.AreEqual(0, testMatchers[0].TestTokenOffset); - - Assert.IsTrue(testMatchers[1].WasTested); - Assert.AreEqual(4, testMatchers[1].TestTokenOffset); - - Assert.IsTrue(testMatchers[2].WasTested); - Assert.AreEqual(6, testMatchers[2].TestTokenOffset); - - Assert.IsTrue(testMatchers[3].WasTested); - Assert.AreEqual(7, testMatchers[3].TestTokenOffset); - - Assert.IsFalse(testMatchers[4].WasTested); - } - - [TestMethod] - public void EnsureGroupWithNoTestsThrowsException() - { - MatcherGroupAnd matcherGroup = null; - - Assert.ThrowsException( - () => matcherGroup = new MatcherGroupAnd() - ); - - Assert.IsNull(matcherGroup); - } - - [TestMethod] - public void EnsureMakesCorrectUseOfTokenOffset() - { - var testMatchers = new[] - { - new TestMatcher(true, 3), - new TestMatcher(true, 1) - }; - var iTokenMatcherArray = (TokenMatcher[])testMatchers.Clone(); - var groupAnd = new MatcherGroupAnd(iTokenMatcherArray); - - var result = groupAnd.Test(matchingContext, 5); - - Assert.IsTrue(result.Successful); - - Assert.AreEqual(5, testMatchers[0].TestTokenOffset); - Assert.AreEqual(8, testMatchers[1].TestTokenOffset); - } - - [TestMethod] - public void EnsureAddsTagWhenMatched() - { - var testMatchers = new[] - { - new TestMatcher(true, 3).WithTag("testTagTheSecond"), - new TestMatcher(true, 1).WithTag("testTagTheThird") - }; - var iTokenMatcherArray = (TokenMatcher[])testMatchers.Clone(); - var groupAnd = new MatcherGroupAnd(iTokenMatcherArray).WithTag("testTagTheFirst"); - - var result = groupAnd.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.MatchedTags.Count); - Assert.AreEqual("testTagTheFirst", result.MatchedTags[0]); - Assert.AreEqual("testTagTheSecond", result.MatchedTags[1]); - Assert.AreEqual("testTagTheThird", result.MatchedTags[2]); - } - - [TestMethod] - public void EnsureDoesNotAddTagWhenNotMatched() - { - var testMatchers = new[] - { - new TestMatcher(true, 3).WithTag("testTagTheSecond"), - new TestMatcher(false, 1).WithTag("testTagTheThird") - }; - var iTokenMatcherArray = (TokenMatcher[])testMatchers.Clone(); - var groupAnd = new MatcherGroupAnd(iTokenMatcherArray).WithTag("testTagTheFirst"); - - var result = groupAnd.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.MatchedTags.Count); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupLoopTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupLoopTest.cs deleted file mode 100644 index 82f95931..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupLoopTest.cs +++ /dev/null @@ -1,232 +0,0 @@ -using System.Collections.Generic; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; - -namespace ZoneCodeGeneratorTests.Parsing.Matching.Matchers -{ - [TestClass] - public class MatcherGroupLoopTest - { - private const string LoopToken = "loop_token"; - - private int testsUntilUnsuccessful; - private int timesTested; - private Mock lexerMock; - private Mock tokenMatcherMock; - private MatchingContext matchingContext; - - [TestInitialize] - public void Setup() - { - timesTested = 0; - testsUntilUnsuccessful = 0; - lexerMock = new Mock(); - tokenMatcherMock = new Mock(); - - tokenMatcherMock.Setup(matcher => matcher.Test(It.IsAny(), It.IsAny())) - .Returns(() => - { - timesTested++; - - if(testsUntilUnsuccessful == 0) - return new TokenMatchingResult(false, 0); - - testsUntilUnsuccessful--; - - var matchResult = new TokenMatchingResult(true, 1); - - matchResult.AddNamedMatch(LoopToken, "test"); - matchResult.AppendTag("testTag"); - - return matchResult; - }); - - matchingContext = new MatchingContext(lexerMock.Object, new Dictionary()); - } - - [TestMethod] - public void EnsureZeroOneMultipleAcceptsNoSuccessfulTests() - { - testsUntilUnsuccessful = 0; - var matcherGroup = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.ZeroOneMultiple, tokenMatcherMock.Object); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.AreEqual(1, timesTested); - } - - [TestMethod] - public void EnsureZeroOneMultipleAcceptsOneSuccessfulTest() - { - testsUntilUnsuccessful = 1; - var matcherGroup = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.ZeroOneMultiple, tokenMatcherMock.Object); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual(2, timesTested); - } - - [TestMethod] - public void EnsureZeroOneMultipleAcceptsMultipleSuccessfulTest() - { - testsUntilUnsuccessful = 5; - var matcherGroup = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.ZeroOneMultiple, tokenMatcherMock.Object); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(5, result.ConsumedTokenCount); - Assert.AreEqual(6, timesTested); - } - - [TestMethod] - public void EnsureOneMultipleRejectsNoSuccessfulTests() - { - testsUntilUnsuccessful = 0; - var matcherGroup = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.OneMultiple, tokenMatcherMock.Object); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.AreEqual(1, timesTested); - } - - [TestMethod] - public void EnsureOneMultipleAcceptsOneSuccessfulTest() - { - testsUntilUnsuccessful = 1; - var matcherGroup = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.OneMultiple, tokenMatcherMock.Object); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual(2, timesTested); - } - - [TestMethod] - public void EnsureOneMultipleAcceptsMultipleSuccessfulTests() - { - testsUntilUnsuccessful = 3; - var matcherGroup = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.OneMultiple, tokenMatcherMock.Object); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.ConsumedTokenCount); - Assert.AreEqual(4, timesTested); - } - - [TestMethod] - public void EnsureMultipleRejectsNoSuccessfulTests() - { - testsUntilUnsuccessful = 0; - var matcherGroup = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.Multiple, tokenMatcherMock.Object); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.AreEqual(1, timesTested); - } - - [TestMethod] - public void EnsureMultipleRejectsOneSuccessfulTest() - { - testsUntilUnsuccessful = 1; - var matcherGroup = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.Multiple, tokenMatcherMock.Object); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.AreEqual(2, timesTested); - } - - [TestMethod] - public void EnsureMultipleAcceptsMultipleSuccessfulTests() - { - testsUntilUnsuccessful = 2; - var matcherGroup = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.Multiple, tokenMatcherMock.Object); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(2, result.ConsumedTokenCount); - Assert.AreEqual(3, timesTested); - } - - [TestMethod] - public void EnsureAllNamedMatchesAreIncluded() - { - testsUntilUnsuccessful = 10; - var matcherGroup = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.Multiple, tokenMatcherMock.Object); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(10, result.ConsumedTokenCount); - Assert.AreEqual(11, timesTested); - - var namedMatches = result.NamedMatches[LoopToken]; - - Assert.AreEqual(10, namedMatches.Count); - - foreach(var namedMatch in namedMatches) - Assert.AreEqual("test", namedMatch); - } - - [TestMethod] - public void EnsureMakesCorrectUseOfTokenOffset() - { - testsUntilUnsuccessful = 2; - var groupLoop = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.OneMultiple, tokenMatcherMock.Object); - - var result = groupLoop.Test(matchingContext, 4); - - tokenMatcherMock.Verify(matcher => matcher.Test(It.IsAny(), 4)); - tokenMatcherMock.Verify(matcher => matcher.Test(It.IsAny(), 5)); - tokenMatcherMock.Verify(matcher => matcher.Test(It.IsAny(), 6)); - tokenMatcherMock.VerifyNoOtherCalls(); - - Assert.IsTrue(result.Successful); - } - - [TestMethod] - public void EnsureAddsTagWhenMatched() - { - testsUntilUnsuccessful = 4; - var groupLoop = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.OneMultiple, tokenMatcherMock.Object).WithTag("loopTag"); - - var result = groupLoop.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(5, result.MatchedTags.Count); - Assert.AreEqual("loopTag", result.MatchedTags[0]); - Assert.AreEqual("testTag", result.MatchedTags[1]); - Assert.AreEqual("testTag", result.MatchedTags[2]); - Assert.AreEqual("testTag", result.MatchedTags[3]); - Assert.AreEqual("testTag", result.MatchedTags[4]); - } - - [TestMethod] - public void EnsureDoesNotAddTagWhenNotMatched() - { - testsUntilUnsuccessful = 1; - var groupLoop = new MatcherGroupLoop(MatcherGroupLoop.LoopMode.Multiple, tokenMatcherMock.Object).WithTag("loopTag"); - - var result = groupLoop.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.MatchedTags.Count); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupOptionalTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupOptionalTest.cs deleted file mode 100644 index 01e452d5..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupOptionalTest.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System.Collections.Generic; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; - -namespace ZoneCodeGeneratorTests.Parsing.Matching.Matchers -{ - [TestClass] - public class MatcherGroupOptionalTest - { - private Mock lexerMock; - private MatchingContext matchingContext; - - [TestInitialize] - public void Setup() - { - lexerMock = new Mock(); - matchingContext = new MatchingContext(lexerMock.Object, new Dictionary()); - } - - [TestMethod] - public void EnsureIsSuccessfulWhenMatcherIsSuccessful() - { - var matcherGroup = new MatcherGroupOptional(new TestMatcher(true, 5)); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(5, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureIsSuccessfulWhenMatcherIsUnsuccessful() - { - var matcherGroup = new MatcherGroupOptional(new TestMatcher(false, 0)); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureMakesCorrectUseOfTokenOffset() - { - var testMatcher = new TestMatcher(true, 1); - var groupOptional = new MatcherGroupOptional(testMatcher); - - var result = groupOptional.Test(matchingContext, 7); - - Assert.IsTrue(result.Successful); - - Assert.AreEqual(7, testMatcher.TestTokenOffset); - } - - [TestMethod] - public void EnsureAddsTagWhenMatched() - { - var testMatcher = new TestMatcher(true, 1).WithTag("testTag"); - var groupOptional = new MatcherGroupOptional(testMatcher).WithTag("optionalTag"); - - var result = groupOptional.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(2, result.MatchedTags.Count); - Assert.AreEqual("optionalTag", result.MatchedTags[0]); - Assert.AreEqual("testTag", result.MatchedTags[1]); - } - - [TestMethod] - public void EnsureDoesStillAddItsOwnTagWhenMatcherDoesNotMatch() - { - var testMatcher = new TestMatcher(false, 0).WithTag("testTag"); - var groupOptional = new MatcherGroupOptional(testMatcher).WithTag("optionalTag"); - - var result = groupOptional.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.MatchedTags.Count); - Assert.AreEqual("optionalTag", result.MatchedTags[0]); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupOrTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupOrTest.cs deleted file mode 100644 index 5c18b8b5..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherGroupOrTest.cs +++ /dev/null @@ -1,192 +0,0 @@ -using System; -using System.Collections.Generic; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; - -namespace ZoneCodeGeneratorTests.Parsing.Matching.Matchers -{ - [TestClass] - public class MatcherGroupOrTest - { - private Mock lexerMock; - private MatchingContext matchingContext; - - [TestInitialize] - public void Setup() - { - lexerMock = new Mock(); - matchingContext = new MatchingContext(lexerMock.Object, new Dictionary()); - } - - [TestMethod] - public void EnsureAnyTestSuccessfulMakesGroupSuccessful() - { - var matcherGroup = new MatcherGroupOr - ( - new TestMatcher(false, 0), - new TestMatcher(false, 0), - new TestMatcher(true, 3), - new TestMatcher(false, 0) - ); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureLastTestSuccessfulMakesGroupSuccessful() - { - var matcherGroup = new MatcherGroupOr - ( - new TestMatcher(false, 0), - new TestMatcher(false, 0), - new TestMatcher(false, 0), - new TestMatcher(true, 4) - ); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(4, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureAllTestsSuccessfulMakesGroupSuccessful() - { - var matcherGroup = new MatcherGroupOr - ( - new TestMatcher(true, 1), - new TestMatcher(true, 2), - new TestMatcher(true, 3), - new TestMatcher(true, 4) - ); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureNoTestsSuccessfulMakesGroupUnsuccessful() - { - var matcherGroup = new MatcherGroupOr - ( - new TestMatcher(false, 0), - new TestMatcher(false, 0), - new TestMatcher(false, 0) - ); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureTestsAreCalledWithCorrectTokenOffsets() - { - var testMatchers = new[] - { - new TestMatcher(false, 0), - new TestMatcher(false, 0), - new TestMatcher(false, 0), - new TestMatcher(true, 4), - new TestMatcher(false, 0), - }; - var iTokenMatcherArray = (TokenMatcher[])testMatchers.Clone(); - var matcherGroup = new MatcherGroupOr(iTokenMatcherArray); - - var result = matcherGroup.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(4, result.ConsumedTokenCount); - - Assert.IsTrue(testMatchers[0].WasTested); - Assert.AreEqual(0, testMatchers[0].TestTokenOffset); - - Assert.IsTrue(testMatchers[1].WasTested); - Assert.AreEqual(0, testMatchers[1].TestTokenOffset); - - Assert.IsTrue(testMatchers[2].WasTested); - Assert.AreEqual(0, testMatchers[2].TestTokenOffset); - - Assert.IsTrue(testMatchers[3].WasTested); - Assert.AreEqual(0, testMatchers[3].TestTokenOffset); - - Assert.IsFalse(testMatchers[4].WasTested); - } - - [TestMethod] - public void EnsureGroupWithNoTestsThrowsException() - { - MatcherGroupOr matcherGroup = null; - - Assert.ThrowsException( - () => matcherGroup = new MatcherGroupOr() - ); - - Assert.IsNull(matcherGroup); - } - - [TestMethod] - public void EnsureMakesCorrectUseOfTokenOffset() - { - var testMatchers = new[] - { - new TestMatcher(true, 3), - new TestMatcher(false, 1) - }; - var iTokenMatcherArray = (TokenMatcher[])testMatchers.Clone(); - var groupOr = new MatcherGroupOr(iTokenMatcherArray); - - var result = groupOr.Test(matchingContext, 5); - - Assert.IsTrue(result.Successful); - - Assert.AreEqual(5, testMatchers[0].TestTokenOffset); - Assert.IsFalse(testMatchers[1].WasTested); - } - - [TestMethod] - public void EnsureAddsTagWhenMatched() - { - var testMatchers = new[] - { - new TestMatcher(false, 3).WithTag("testTagTheSecond"), - new TestMatcher(true, 1).WithTag("testTagTheThird") - }; - var iTokenMatcherArray = (TokenMatcher[])testMatchers.Clone(); - var groupOr = new MatcherGroupOr(iTokenMatcherArray).WithTag("testTagTheFirst"); - - var result = groupOr.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(2, result.MatchedTags.Count); - Assert.AreEqual("testTagTheFirst", result.MatchedTags[0]); - Assert.AreEqual("testTagTheThird", result.MatchedTags[1]); - } - - [TestMethod] - public void EnsureDoesNotAddTagWhenNotMatched() - { - var testMatchers = new[] - { - new TestMatcher(false, 3).WithTag("testTagTheSecond"), - new TestMatcher(false, 1).WithTag("testTagTheThird") - }; - var iTokenMatcherArray = (TokenMatcher[])testMatchers.Clone(); - var groupOr = new MatcherGroupOr(iTokenMatcherArray).WithTag("testTagTheFirst"); - - var result = groupOr.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.MatchedTags.Count); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherLiteralTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherLiteralTest.cs deleted file mode 100644 index 767ef110..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherLiteralTest.cs +++ /dev/null @@ -1,192 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; - -namespace ZoneCodeGeneratorTests.Parsing.Matching.Matchers -{ - [TestClass] - public class MatcherLiteralTest - { - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - private MatchingContext matchingContext; - - [TestInitialize] - public void Setup() - { - tokenOffset = 0; - tokens = new List(); - - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - - matchingContext = new MatchingContext(lexerMock.Object, new Dictionary()); - } - - [TestMethod] - public void EnsureMatchingSameStringReturnsSuccessful() - { - tokens.AddRange(new List - { - "const" - }); - - var matcher = new MatcherLiteral("const"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureMatchingDifferentStringReturnsUnsuccessful() - { - tokens.AddRange(new List - { - "long" - }); - - var matcher = new MatcherLiteral("const"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureMatchingIsCaseSensitive() - { - tokens.AddRange(new List - { - "CONST" - }); - - var matcher = new MatcherLiteral("const"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureNamedMatchIsLiteralItself() - { - tokens.AddRange(new List - { - "const" - }); - - var matcher = new MatcherLiteral("const").WithName("test_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual("const", result.NamedMatches["test_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureMatcherWithMultipleLiteralTokensMatchesWhenAllAreFound() - { - tokens.AddRange(new List - { - "const", "range", "of", "turtles" - }); - - var matcher = new MatcherLiteral("const", "range"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(2, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureMatcherWithMultipleLiteralTokensDoesNotMatchWhenFirstTokenIsDifferent() - { - tokens.AddRange(new List - { - "static", "range", "of", "turtles" - }); - - var matcher = new MatcherLiteral("const", "range"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureMatcherWithMultipleLiteralTokensDoesNotMatchWhenSecondTokenIsDifferent() - { - tokens.AddRange(new List - { - "const", "element", "of", "turtles" - }); - - var matcher = new MatcherLiteral("const", "const"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureMakesCorrectUseOfTokenOffset() - { - tokens.AddRange(new List - { - "strawberry", "cake", "is", "yummy" - }); - - var matcher = new MatcherLiteral("cake"); - var result = matcher.Test(matchingContext, 1); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureAddsTagWhenMatched() - { - tokens.AddRange(new List - { - "strawberry" - }); - - var matcher = new MatcherLiteral("strawberry").WithTag("strawberryMatcher"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual(1, result.MatchedTags.Count); - Assert.AreEqual("strawberryMatcher", result.MatchedTags[0]); - } - - [TestMethod] - public void EnsureDoesNotAddTagWhenNotMatched() - { - tokens.AddRange(new List - { - "apple" - }); - - var matcher = new MatcherLiteral("strawberry").WithTag("strawberryMatcher"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.AreEqual(0, result.MatchedTags.Count); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherNameTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherNameTest.cs deleted file mode 100644 index 37f77e4f..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherNameTest.cs +++ /dev/null @@ -1,208 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; - -namespace ZoneCodeGeneratorTests.Parsing.Matching.Matchers -{ - [TestClass] - public class MatcherNameTest - { - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - private MatchingContext matchingContext; - - [TestInitialize] - public void Setup() - { - tokenOffset = 0; - tokens = new List(); - - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - - matchingContext = new MatchingContext(lexerMock.Object, new Dictionary()); - } - - [TestMethod] - public void EnsureRecognizesNormalName() - { - tokens.AddRange(new List - { - "variable_name" - }); - - var matcher = new MatcherName(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureRecognizesUnderscoreAtTheBeginning() - { - tokens.AddRange(new List - { - "_variable_name" - }); - - var matcher = new MatcherName(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureAcceptsDigit() - { - tokens.AddRange(new List - { - "v4ri4bl3_n4m3" - }); - - var matcher = new MatcherName(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureDoesNotAcceptDigitAtTheBeginning() - { - tokens.AddRange(new List - { - "5variable_name" - }); - - var matcher = new MatcherName(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureDoesNotAcceptCKeyword() - { - tokens.AddRange(new List - { - "float" - }); - - var matcher = new MatcherName(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureDoesNotAcceptSymbols() - { - tokens.AddRange(new List - { - "%$§" - }); - - var matcher = new MatcherName(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureDoesNotAcceptEmptyString() - { - tokens.AddRange(new List - { - "" - }); - - var matcher = new MatcherName(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureNamedOutputIsMatchedName() - { - tokens.AddRange(new List - { - "variable_n4me" - }); - - var matcher = new MatcherName().WithName("name_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual("variable_n4me", result.NamedMatches["name_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureMakesCorrectUseOfTokenOffset() - { - tokens.AddRange(new List - { - "static", "int", "variable_n4me", "=", "5", ";" - }); - - var matcher = new MatcherName().WithName("name_token"); - var result = matcher.Test(matchingContext, 2); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual("variable_n4me", result.NamedMatches["name_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureAddsTagWhenMatched() - { - tokens.AddRange(new List - { - "variable_n4me" - }); - - var matcher = new MatcherName().WithTag("very_cool_matcher"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual(1, result.MatchedTags.Count); - Assert.AreEqual("very_cool_matcher", result.MatchedTags[0]); - } - - [TestMethod] - public void EnsureDoesNotAddTagWhenNotMatched() - { - tokens.AddRange(new List - { - "1337" - }); - - var matcher = new MatcherName().WithTag("very_cool_matcher"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.AreEqual(0, result.MatchedTags.Count); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherNumberTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherNumberTest.cs deleted file mode 100644 index 5326eab1..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherNumberTest.cs +++ /dev/null @@ -1,208 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; - -namespace ZoneCodeGeneratorTests.Parsing.Matching.Matchers -{ - [TestClass] - public class MatcherNumberTest - { - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - private MatchingContext matchingContext; - - [TestInitialize] - public void Setup() - { - tokenOffset = 0; - tokens = new List(); - - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - - matchingContext = new MatchingContext(lexerMock.Object, new Dictionary()); - } - - [TestMethod] - public void EnsureDecimalNumbersAreRecognized() - { - tokens.AddRange(new List - { - "1337" - }); - - var matcher = new MatcherNumber(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureHexNumbersAreRecognized() - { - tokens.AddRange(new List - { - "0x1A4" - }); - - var matcher = new MatcherNumber(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureHexNumbersWithInvalidLettersAreInvalid() - { - tokens.AddRange(new List - { - "0xAFZF" - }); - - var matcher = new MatcherNumber(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureWordsAreInvalid() - { - tokens.AddRange(new List - { - "Hello" - }); - - var matcher = new MatcherNumber(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureSymbolsAreInvalid() - { - tokens.AddRange(new List - { - "%" - }); - - var matcher = new MatcherNumber(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureJustHexPrefixIsInvalid() - { - tokens.AddRange(new List - { - "0x" - }); - - var matcher = new MatcherNumber(); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureNamedOutputIsDecimalNumberForDecimalInput() - { - tokens.AddRange(new List - { - "420" - }); - - var matcher = new MatcherNumber().WithName("number_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual("420", result.NamedMatches["number_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureNamedOutputIsDecimalNumberForHexInput() - { - tokens.AddRange(new List - { - "0x1a5" - }); - - var matcher = new MatcherNumber().WithName("number_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual("421", result.NamedMatches["number_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureMakesCorrectUseOfTokenOffset() - { - tokens.AddRange(new List - { - "int", "kek", "=", "1337", ";" - }); - - var matcher = new MatcherNumber(); - var result = matcher.Test(matchingContext, 3); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureAddsTagWhenMatched() - { - tokens.AddRange(new List - { - "1337" - }); - - var matcher = new MatcherNumber().WithTag("Taggerino"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual(1, result.MatchedTags.Count); - Assert.AreEqual("Taggerino", result.MatchedTags[0]); - } - - [TestMethod] - public void EnsureDoesNotAddTagWhenNotMatched() - { - tokens.AddRange(new List - { - "not_a_number_yo" - }); - - var matcher = new MatcherNumber().WithTag("Taggerino"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.AreEqual(0, result.MatchedTags.Count); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherTypenameTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherTypenameTest.cs deleted file mode 100644 index 8b59899c..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/MatcherTypenameTest.cs +++ /dev/null @@ -1,310 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using ZoneCodeGenerator.Parsing; -using ZoneCodeGenerator.Parsing.Matching; -using ZoneCodeGenerator.Parsing.Matching.Matchers; - -namespace ZoneCodeGeneratorTests.Parsing.Matching.Matchers -{ - [TestClass] - public class MatcherTypenameTest - { - private Mock lexerMock; - private int tokenOffset; - private List tokens; - - private MatchingContext matchingContext; - - [TestInitialize] - public void Setup() - { - tokenOffset = 0; - tokens = new List(); - - lexerMock = new Mock(); - - lexerMock.Setup(lexer => lexer.PeekToken(It.IsAny())) - .Returns((int index) => tokens.ElementAtOrDefault(index + tokenOffset)); - lexerMock.Setup(lexer => lexer.NextToken()) - .Returns(() => tokens.ElementAtOrDefault(tokenOffset++)); - lexerMock.Setup(lexer => lexer.SkipTokens(It.IsAny())) - .Callback((int count) => tokenOffset += count); - - matchingContext = new MatchingContext(lexerMock.Object, new Dictionary()); - } - - [TestMethod] - public void EnsureBaseTypeNamesAreRecognized() - { - tokens.AddRange(new List - { - "int" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual("int", result.NamedMatches["type_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureNormalTypeNamesAreRecognized() - { - tokens.AddRange(new List - { - "GfxWorld" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual("GfxWorld", result.NamedMatches["type_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureUnsignedTypeNamesAreRecognized() - { - tokens.AddRange(new List - { - "unsigned", "int" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(2, result.ConsumedTokenCount); - Assert.AreEqual("unsigned int", result.NamedMatches["type_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureSignedTypeNamesAreRecognized() - { - tokens.AddRange(new List - { - "signed", "int" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(2, result.ConsumedTokenCount); - Assert.AreEqual("signed int", result.NamedMatches["type_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureDoubleLongIsRecognized() - { - tokens.AddRange(new List - { - "long", "long" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(2, result.ConsumedTokenCount); - Assert.AreEqual("long long", result.NamedMatches["type_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureDoubleLongWithPrefixesIsRecognized() - { - tokens.AddRange(new List - { - "unsigned", "long", "long" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(3, result.ConsumedTokenCount); - Assert.AreEqual("unsigned long long", result.NamedMatches["type_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureDoubleIntIsNotRecognized() - { - tokens.AddRange(new List - { - "int", "int" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual("int", result.NamedMatches["type_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureNamespacesAreAllowed() - { - tokens.AddRange(new List - { - "std", ":", ":", "string" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(4, result.ConsumedTokenCount); - Assert.AreEqual("std::string", result.NamedMatches["type_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureAcceptsTypeNamesWithNumbersAndUnderscores() - { - tokens.AddRange(new List - { - "std", ":", ":", "int32_t" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(4, result.ConsumedTokenCount); - Assert.AreEqual("std::int32_t", result.NamedMatches["type_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureShortNamespacesAreAllowed() - { - tokens.AddRange(new List - { - "a", ":", ":", "b" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(4, result.ConsumedTokenCount); - Assert.AreEqual("a::b", result.NamedMatches["type_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureDoubleColonPrefixIsNotAllowed() - { - tokens.AddRange(new List - { - ":", ":", "string" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.IsFalse(result.NamedMatches.ContainsKey("type_token")); - } - - [TestMethod] - public void EnsureSingleDoubleColonNamespacesDoNotMatch() - { - tokens.AddRange(new List - { - "std", ":", "string" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(1, result.ConsumedTokenCount); - Assert.AreEqual("std", result.NamedMatches["type_token"].ElementAtOrDefault(0)); - } - - [TestMethod] - public void EnsureSymbolsAreNotAllowed() - { - tokens.AddRange(new List - { - "%" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.IsFalse(result.NamedMatches.ContainsKey("type_token")); - } - - [TestMethod] - public void EnsureSymbolsWithUnsignedAreNotAllowed() - { - tokens.AddRange(new List - { - "unsigned", "%" - }); - - var matcher = new MatcherTypename().WithName("type_token"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.IsFalse(result.NamedMatches.ContainsKey("type_token")); - } - - [TestMethod] - public void EnsureMakesCorrectUseOfTokenOffset() - { - tokens.AddRange(new List - { - "5", "4", "3", "2", "std", ":", ":", "string", "randomString", ";" - }); - - var matcher = new MatcherTypename(); - var result = matcher.Test(matchingContext, 4); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(4, result.ConsumedTokenCount); - } - - [TestMethod] - public void EnsureAddsTagWhenMatched() - { - tokens.AddRange(new List - { - "std", ":", ":", "something", "test" - }); - - var matcher = new MatcherTypename().WithTag("naisu"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsTrue(result.Successful); - Assert.AreEqual(4, result.ConsumedTokenCount); - Assert.AreEqual(1, result.MatchedTags.Count); - Assert.AreEqual("naisu", result.MatchedTags[0]); - } - - [TestMethod] - public void EnsureDoesNotAddTagWhenNotMatched() - { - tokens.AddRange(new List - { - "1337", "asdf", ":", ":", "something", "test" - }); - - var matcher = new MatcherTypename().WithTag("naisu"); - var result = matcher.Test(matchingContext, 0); - - Assert.IsFalse(result.Successful); - Assert.AreEqual(0, result.ConsumedTokenCount); - Assert.AreEqual(0, result.MatchedTags.Count); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/TestMatcher.cs b/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/TestMatcher.cs deleted file mode 100644 index a121d60c..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Matching/Matchers/TestMatcher.cs +++ /dev/null @@ -1,44 +0,0 @@ -using ZoneCodeGenerator.Parsing.Matching; - -namespace ZoneCodeGeneratorTests.Parsing.Matching.Matchers -{ - class TestMatcher : TokenMatcher - { - private readonly int tokenCount; - private readonly string tokenName; - - public bool Successful { get; set; } - public int TestTokenOffset { get; private set; } - public bool WasTested { get; private set; } - - public TestMatcher(bool successful, int tokenCount, string tokenName = "") - { - Successful = successful; - this.tokenCount = tokenCount; - this.tokenName = tokenName; - TestTokenOffset = 0; - WasTested = false; - } - - protected override string GetIdentifier() - { - return "TestMatcher"; - } - - protected override TokenMatchingResult PerformTest(MatchingContext context, int tokenOffset) - { - var result = new TokenMatchingResult(Successful, Successful ? tokenCount : 0); - - if(result.Successful) - result.AppendTag(Tag); - - if(!string.IsNullOrEmpty(tokenName)) - result.AddNamedMatch(tokenName, "test"); - - TestTokenOffset = tokenOffset; - WasTested = true; - - return result; - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Parsing/Mock/IncludingParsingStreamTest.cs b/test/ZoneCodeGeneratorTests/Parsing/Mock/IncludingParsingStreamTest.cs deleted file mode 100644 index 2bce5d05..00000000 --- a/test/ZoneCodeGeneratorTests/Parsing/Mock/IncludingParsingStreamTest.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Collections.Generic; -using ZoneCodeGenerator.Parsing; - -namespace ZoneCodeGeneratorTests.Parsing.Mock -{ - class IncludingParsingStreamTest : IIncludingParsingStream - { - public string Filename { get; set; } - public int Line { get; set; } - public List Lines { get; } - public bool EndOfStream => Line >= Lines.Count; - public string LastInclude { get; private set; } - public int IncludeCount { get; private set; } - - public IncludingParsingStreamTest(string filename) - { - Line = 0; - Filename = filename; - Lines = new List(); - LastInclude = ""; - IncludeCount = 0; - } - - public string ReadLine() - { - return EndOfStream ? "" : Lines[Line++]; - } - - public void IncludeFile(string filename) - { - LastInclude = filename; - IncludeCount++; - } - - public void Close() - { - - } - - public void Dispose() - { - Close(); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Persistence/InMemoryDataRepositoryTest.cs b/test/ZoneCodeGeneratorTests/Persistence/InMemoryDataRepositoryTest.cs deleted file mode 100644 index 1d94d567..00000000 --- a/test/ZoneCodeGeneratorTests/Persistence/InMemoryDataRepositoryTest.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System.Collections.Generic; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using ZoneCodeGenerator.Domain; -using ZoneCodeGenerator.Persistence; - -namespace ZoneCodeGeneratorTests.Persistence -{ - [TestClass] - public class InMemoryDataRepositoryTest - { - private IDataRepository dataRepository; - - private DataTypeEnum enum1; - private DataTypeEnum enum2; - - private DataTypeStruct struct1; - private DataTypeStruct struct2; - - private DataTypeUnion union1; - private DataTypeUnion union2; - - private DataTypeTypedef typedef1; - private DataTypeTypedef typedef2; - - [TestInitialize] - public void PrepareSampleStorage() - { - dataRepository = new InMemoryDataRepository(); - - enum1 = new DataTypeEnum("namespace1", "enum1", DataTypeBaseType.INT); - enum2 = new DataTypeEnum("other_namespace", "enum2", DataTypeBaseType.SHORT); - - struct1 = new DataTypeStruct("", "test_struct1", 4); - struct2 = new DataTypeStruct("space", "aBeautifulStruct", 2); - - union1 = new DataTypeUnion("", "u", 4); - union2 = new DataTypeUnion("namespacesareaverynice", "averylongunionnamewhowouldevercreateanamethislong", 16); - - var typeDeclaration1 = new TypeDeclaration(DataTypeBaseType.BOOL, new List - { - new ReferenceTypeArray(4), - new ReferenceTypeArray(6) - }); - typedef1 = new DataTypeTypedef("namespace1", "mytypedef", typeDeclaration1); - var typeDeclaration2 = new TypeDeclaration(struct1, new List - { - new ReferenceTypePointer() - }); - typedef2 = new DataTypeTypedef("", "struct1_p", typeDeclaration2); - - dataRepository.Add(enum1); - dataRepository.Add(enum2); - dataRepository.Add(struct1); - dataRepository.Add(struct2); - dataRepository.Add(union1); - dataRepository.Add(union2); - dataRepository.Add(typedef1); - dataRepository.Add(typedef2); - } - - [TestMethod] - public void EnsureEnumsCanBeSavedAndRestored() - { - var allEnums = new List(dataRepository.GetAllEnums()); - - Assert.AreEqual(2, allEnums.Count); - - Assert.That.Contains(enum1, allEnums); - Assert.That.Contains(enum2, allEnums); - } - - [TestMethod] - public void EnsureStructsCanBeSavedAndRestored() - { - var allEnums = new List(dataRepository.GetAllStructs()); - - Assert.AreEqual(2, allEnums.Count); - Assert.That.Contains(struct1, allEnums); - Assert.That.Contains(struct2, allEnums); - } - - [TestMethod] - public void EnsureUnionsCanBeSavedAndRestored() - { - var allUnions = new List(dataRepository.GetAllUnions()); - - Assert.AreEqual(2, allUnions.Count); - Assert.That.Contains(union1, allUnions); - Assert.That.Contains(union2, allUnions); - } - - [TestMethod] - public void EnsureTypedefsCanBeSavedAndRestored() - { - var allTypedefs = new List(dataRepository.GetAllTypedefs()); - - Assert.AreEqual(2, allTypedefs.Count); - Assert.That.Contains(typedef1, allTypedefs); - Assert.That.Contains(typedef2, allTypedefs); - } - - [TestMethod] - public void EnsureEnumsCanBeFoundByName() - { - var foundDataType1 = dataRepository.GetDataTypeByName("namespace1::enum1"); - Assert.AreEqual(enum1, foundDataType1); - - var foundDataType2 = dataRepository.GetDataTypeByName("other_namespace::enum2"); - Assert.AreEqual(enum2, foundDataType2); - } - - [TestMethod] - public void EnsureStructsCanBeFoundByName() - { - var foundDataType1 = dataRepository.GetDataTypeByName("test_struct1"); - Assert.AreEqual(struct1, foundDataType1); - - var foundDataType2 = dataRepository.GetDataTypeByName("space::aBeautifulStruct"); - Assert.AreEqual(struct2, foundDataType2); - } - - [TestMethod] - public void EnsureUnionsCanBeFoundByName() - { - var foundDataType1 = dataRepository.GetDataTypeByName("u"); - Assert.AreEqual(union1, foundDataType1); - - var foundDataType2 = dataRepository.GetDataTypeByName("namespacesareaverynice::averylongunionnamewhowouldevercreateanamethislong"); - Assert.AreEqual(union2, foundDataType2); - } - - [TestMethod] - public void EnsureTypedefsCanBeFoundByName() - { - var foundDataType1 = dataRepository.GetDataTypeByName("namespace1::mytypedef"); - Assert.AreEqual(typedef1, foundDataType1); - - var foundDataType2 = dataRepository.GetDataTypeByName("struct1_p"); - Assert.AreEqual(typedef2, foundDataType2); - } - } -} diff --git a/test/ZoneCodeGeneratorTests/Properties/AssemblyInfo.cs b/test/ZoneCodeGeneratorTests/Properties/AssemblyInfo.cs deleted file mode 100644 index 245f86ce..00000000 --- a/test/ZoneCodeGeneratorTests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -[assembly: AssemblyTitle("ZoneCodeGeneratorTests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ZoneCodeGeneratorTests")] -[assembly: AssemblyCopyright("Copyright © 2019")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -[assembly: ComVisible(false)] - -[assembly: Guid("c29242db-84d0-4a37-ad3f-19b72b23c7e0")] - -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")]