From 0e47475b0a62b37dc2856817ad58b685d47f411e Mon Sep 17 00:00:00 2001 From: GMIKE Date: Sun, 17 Apr 2022 04:31:00 +0300 Subject: [PATCH 01/11] Input abstraction --- .../Examples/TernaryOperator.cs | 54 +++++++++++++++++++ .../FindTemplateTests.cs | 5 +- .../Mock/EmptyParsingContext.cs | 2 +- .../PlaceholderParserTests.cs | 10 ++-- .../ReplaceTemplateTests.cs | 2 +- ...StateMachine.StructuralSearch.Tests.csproj | 3 ++ .../StructurSearchParserTests.cs | 18 ++++--- .../EmptyInput.cs | 12 +++++ .../FileInput.cs | 20 +++++++ .../FindParser.cs | 10 ++-- .../IFindParser.cs | 3 +- .../IParsingContext.cs | 3 +- .../ISource.cs | 9 ++++ .../Input.cs | 13 +++++ .../ParsingContext.cs | 6 +++ .../Placeholder/FileProperty.cs | 25 +++++++-- .../Placeholder/Placeholder.cs | 1 - .../Parameters/PlaceholderFileParameter.cs | 23 ++++---- .../StringInput.cs | 19 +++++++ .../StructuralSearchParser.cs | 3 +- 20 files changed, 205 insertions(+), 36 deletions(-) create mode 100644 src/SimpleStateMachine.StructuralSearch.Tests/Examples/TernaryOperator.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/EmptyInput.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/FileInput.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/ISource.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/Input.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/StringInput.cs diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/Examples/TernaryOperator.cs b/src/SimpleStateMachine.StructuralSearch.Tests/Examples/TernaryOperator.cs new file mode 100644 index 0000000..f45b96f --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch.Tests/Examples/TernaryOperator.cs @@ -0,0 +1,54 @@ +using System; + +namespace SimpleStateMachine.StructuralSearch.Tests.Examples +{ + public class TernaryOperator + { + public int Test1() + { + var temp = 150; + + if(temp == 125) + return 12; + else + return 15; + } + + public int Test2() + { + var temp = 150; + + if(temp == 125) + return 12; + else + return 15; + } + + public int Test3() + { + var temp2 = 150; + + if(temp2 == 125) + return 12; + else + return 15; + } + + public int Test4() + { + var temp3 = 150; + + if(temp3 == 125) + return 12; + else if (temp3 == 135) + return 15; + else + return 0; + } + + public void Test5() + { + + } + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateTests.cs index d028e05..39cb231 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateTests.cs @@ -28,9 +28,10 @@ public void SourceParsingBeFindTemplateShouldBeSuccess(string templatePath, stri { var findTemplate = File.ReadAllText(templatePath); var source = File.ReadAllText(sourcePath); + var input = Input.String(source); var findParser = StructuralSearch.ParseFindTemplate(findTemplate); - IParsingContext parsingContext = new ParsingContext(); - var result = findParser.Parse(ref parsingContext, source); + IParsingContext parsingContext = new ParsingContext(input); + var result = findParser.Parse(ref parsingContext, input); Assert.NotNull(findParser); Assert.NotNull(result.Value); diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs b/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs index 33bee37..4512e4b 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs @@ -2,7 +2,7 @@ { public class EmptyParsingContext : IParsingContext { - public FileProperty File { get; } = new FileProperty(); + public IInput Input { get; } public bool TryGetPlaceholder(string name, out Placeholder value) { diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs index e44eb05..362f23e 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs @@ -18,9 +18,10 @@ public void FindTemplateShouldBeNotEmpty() [InlineData("($test$)", "(value (test) )", "value (test) ")] public void TemplateParsingShouldBeSuccess(string template, string source, string result) { - IParsingContext parsingContext = new ParsingContext(); + var input = Input.String(source); + IParsingContext parsingContext = new ParsingContext(input); var templateParser = StructuralSearch.ParseFindTemplate(template); - var res = templateParser.Parse(ref parsingContext, source); + var res = templateParser.Parse(ref parsingContext, input); var placeholder = parsingContext.GetPlaceholder("test"); Assert.Equal(placeholder.Value, result); @@ -30,9 +31,10 @@ public void TemplateParsingShouldBeSuccess(string template, string source, strin [InlineData("$var$;$var2$;", "test;;;test;;;", "value ")] public void TemplateParsingShouldBeSuccess2(string template, string source, string result) { - IParsingContext parsingContext = new ParsingContext(); + var input = Input.String(source); + IParsingContext parsingContext = new ParsingContext(input); var templateParser = StructuralSearch.ParseFindTemplate(template); - templateParser.Parse(ref parsingContext, source); + templateParser.Parse(ref parsingContext, input); // var templateStr = File.ReadAllText(templatePath); diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceTemplateTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceTemplateTests.cs index d3a1662..db25cb1 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceTemplateTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceTemplateTests.cs @@ -38,7 +38,7 @@ public void ReplaceBuildShouldBeSuccess(string templatePath, string resultPath, var replaceResult = File.ReadAllText(resultPath); var replaceBuilder = StructuralSearch.ParseReplaceTemplate(replaceTemplate); - var parsingContext = new ParsingContext(); + var parsingContext = new ParsingContext(Input.Empty); for (int i = 0; i < keys.Length; i++) { parsingContext.AddPlaceholder(Placeholder.CreateEmpty(parsingContext, keys[i], values[i])); diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj b/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj index b90e87b..8f8652b 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj +++ b/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj @@ -25,6 +25,9 @@ + + Always + Always diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs index 547f66f..1bce6f0 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs @@ -1,4 +1,5 @@ -using SimpleStateMachine.StructuralSearch.Tests.Mock; +using System.IO; +using SimpleStateMachine.StructuralSearch.Tests.Mock; using Xunit; namespace SimpleStateMachine.StructuralSearch.Tests @@ -6,14 +7,19 @@ namespace SimpleStateMachine.StructuralSearch.Tests public class StructuralSearchParserTests { [Theory] - [InlineData("AssignmentNullUnionOperator")] - [InlineData("NullUnionOperator")] - [InlineData("TernaryOperator")] - public static void StructuralSearchShouldBeSuccess(string exampleName) + // [InlineData("AssignmentNullUnionOperator")] + // [InlineData("NullUnionOperator")] + [InlineData("TernaryOperator", "Examples/TernaryOperator.cs")] + public static void StructuralSearchShouldBeSuccess(string exampleName, string exampleFilePath) { var config = ConfigurationMock.GetConfigurationFromFiles(exampleName); var parser = new StructuralSearchParser(config); - + + var fileInfo = new FileInfo(exampleFilePath); + var input = Input.File(fileInfo); + IParsingContext context = new ParsingContext(input); + + parser.Parse(ref context); } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs b/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs new file mode 100644 index 0000000..a987059 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs @@ -0,0 +1,12 @@ +using Pidgin; + +namespace SimpleStateMachine.StructuralSearch +{ + public class EmptyInput : IInput + { + public Result Parse(Parser parser) + { + throw new System.NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/FileInput.cs b/src/SimpleStateMachine.StructuralSearch/FileInput.cs new file mode 100644 index 0000000..4e10de7 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/FileInput.cs @@ -0,0 +1,20 @@ +using System.IO; +using Pidgin; + +namespace SimpleStateMachine.StructuralSearch +{ + public class FileInput : IInput + { + public FileInput(FileInfo fileInfo) + { + FileInfo = fileInfo; + } + + public readonly FileInfo FileInfo; + + public Result Parse(Parser parser) + { + return parser.Parse(FileInfo.OpenText()); + } + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/FindParser.cs b/src/SimpleStateMachine.StructuralSearch/FindParser.cs index ec1b7e7..3d68f72 100644 --- a/src/SimpleStateMachine.StructuralSearch/FindParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/FindParser.cs @@ -1,6 +1,8 @@ using System.Collections.Generic; +using System.IO; using Pidgin; using SimpleStateMachine.StructuralSearch.Extensions; +using YamlDotNet.Core.Events; namespace SimpleStateMachine.StructuralSearch { @@ -12,13 +14,13 @@ public FindParser(SeriesParser parser) Parser = parser; } - public SourceMatch Parse(ref IParsingContext context, string input) + public SourceMatch Parse(ref IParsingContext context, IInput input) { Parser.SetContext(ref context); - var result = Parser.Select(x => string.Join(string.Empty, x)) - .AsMatch() - .Parse(input); + var result = input.Parse(Parser.Select(x => string.Join(string.Empty, x)) + .AsMatch()); + return result.Success ? result.Value : SourceMatch.Empty; } } diff --git a/src/SimpleStateMachine.StructuralSearch/IFindParser.cs b/src/SimpleStateMachine.StructuralSearch/IFindParser.cs index ce74042..95db213 100644 --- a/src/SimpleStateMachine.StructuralSearch/IFindParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/IFindParser.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.IO; using Pidgin; using SimpleStateMachine.StructuralSearch.ReplaceTemplate; @@ -6,6 +7,6 @@ namespace SimpleStateMachine.StructuralSearch { public interface IFindParser { - SourceMatch Parse(ref IParsingContext context, string input); + SourceMatch Parse(ref IParsingContext context, IInput input); } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs b/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs index 497a16f..f71dc4f 100644 --- a/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs +++ b/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs @@ -2,7 +2,8 @@ { public interface IParsingContext { - FileProperty File { get; } + IInput Input { get; } + bool TryGetPlaceholder(string name, out Placeholder value); void AddPlaceholder(Placeholder placeholder); diff --git a/src/SimpleStateMachine.StructuralSearch/ISource.cs b/src/SimpleStateMachine.StructuralSearch/ISource.cs new file mode 100644 index 0000000..2c4ac60 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/ISource.cs @@ -0,0 +1,9 @@ +using Pidgin; + +namespace SimpleStateMachine.StructuralSearch +{ + public interface IInput + { + Result Parse(Parser parser); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Input.cs b/src/SimpleStateMachine.StructuralSearch/Input.cs new file mode 100644 index 0000000..bd5e47f --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Input.cs @@ -0,0 +1,13 @@ +using System.IO; + +namespace SimpleStateMachine.StructuralSearch +{ + public static class Input + { + public static readonly IInput Empty = new EmptyInput(); + + public static IInput String(string input) => new StringInput(input); + + public static IInput File(FileInfo fileInfo) => new FileInput(fileInfo); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs b/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs index 4624fb9..a739845 100644 --- a/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs +++ b/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs @@ -4,10 +4,16 @@ namespace SimpleStateMachine.StructuralSearch { public class ParsingContext : IParsingContext { + public ParsingContext(IInput input) + { + Input = input; + } public Dictionary Placeholders { get; } = new(); public FileProperty File { get; } + public IInput Input { get; } + public bool TryGetPlaceholder(string name, out Placeholder value) { return Placeholders.TryGetValue(name, out value); diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/FileProperty.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/FileProperty.cs index 1ef474e..1dbd1f9 100644 --- a/src/SimpleStateMachine.StructuralSearch/Placeholder/FileProperty.cs +++ b/src/SimpleStateMachine.StructuralSearch/Placeholder/FileProperty.cs @@ -1,11 +1,28 @@ -namespace SimpleStateMachine.StructuralSearch +using System.IO; + +namespace SimpleStateMachine.StructuralSearch { public class FileProperty { + public FileProperty(FileInfo fileInfo) + { + FileInfo = fileInfo; + StreamReader = new StreamReader(fileInfo.OpenRead()); + } + + public readonly FileInfo FileInfo; public readonly string Path; public readonly string Data; - public readonly string Name; - public readonly string Directory; - public readonly int Lenght; + public readonly StreamReader StreamReader; + public string Name => FileInfo.Name; + public string Directory => FileInfo.FullName; + public long Lenght => FileInfo.Length; + + public static FileProperty FromFile(string path) + { + return new FileProperty(new FileInfo(path)); + } + + public static readonly FileProperty Empty = new FileProperty(null); } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs index 76e2146..35d6230 100644 --- a/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs +++ b/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs @@ -17,7 +17,6 @@ public Placeholder(IParsingContext context, string name, string value, LinePrope public readonly string Name; public readonly string Value; public readonly int Lenght; - public FileProperty File => _context.File; public readonly LineProperty Line; public readonly ColumnProperty Column; public readonly OffsetProperty Offset; diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs index f49b03c..c6be479 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs @@ -15,16 +15,19 @@ public PlaceholderFileParameter(PlaceholderParameter parameter, FileProperty pro public string GetValue() { - var file = PlaceholderParameter.GetPlaceholder().File; - return Property switch - { - FileProperty.Path => file.Path, - FileProperty.Data => file.Data, - FileProperty.Name => file.Name, - FileProperty.Directory => file.Directory, - FileProperty.Lenght => file.Lenght.ToString(), - _ => throw new ArgumentOutOfRangeException() - }; + // TODO + // var file = PlaceholderParameter.GetPlaceholder().File; + // return Property switch + // { + // FileProperty.Path => file.Path, + // FileProperty.Data => file.Data, + // FileProperty.Name => file.Name, + // FileProperty.Directory => file.Directory, + // FileProperty.Lenght => file.Lenght.ToString(), + // _ => throw new ArgumentOutOfRangeException() + // }; + + return null; } public override string ToString() diff --git a/src/SimpleStateMachine.StructuralSearch/StringInput.cs b/src/SimpleStateMachine.StructuralSearch/StringInput.cs new file mode 100644 index 0000000..f55b02a --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/StringInput.cs @@ -0,0 +1,19 @@ +using Pidgin; + +namespace SimpleStateMachine.StructuralSearch +{ + public class StringInput : IInput + { + public StringInput(string input) + { + Input = input; + } + + public readonly string Input; + + public Result Parse(Parser parser) + { + return parser.Parse(Input); + } + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs index 6c21071..54a772a 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs @@ -1,5 +1,6 @@  using System.Collections.Generic; +using System.IO; using System.Linq; using SimpleStateMachine.StructuralSearch.Configurations; using SimpleStateMachine.StructuralSearch.Extensions; @@ -37,7 +38,7 @@ public StructuralSearchParser(Configuration configuration) public void Parse(ref IParsingContext context) { - FindParser.Parse(ref context, context.File.Data); + var result = FindParser.Parse(ref context, context.Input); } public void Replace(ref IParsingContext context) From 3418f69ff59e18103a505179b137b4b8f5f859f0 Mon Sep 17 00:00:00 2001 From: GMIKE Date: Sun, 17 Apr 2022 13:27:21 +0300 Subject: [PATCH 02/11] input property --- .../Program.cs | 1 + .../EmptyInput.cs | 6 ++++ .../FileInput.cs | 6 ++++ .../IInput.cs | 15 ++++++++++ .../ISource.cs | 9 ------ .../ParsingContext.cs | 2 -- .../Placeholder/FileProperty.cs | 28 ------------------- .../Placeholder/Placeholder.cs | 2 +- .../Rules/Parameters/FileProperty.cs | 2 +- .../Parameters/PlaceholderFileParameter.cs | 21 +++++++------- .../StringInput.cs | 6 ++++ 11 files changed, 46 insertions(+), 52 deletions(-) create mode 100644 src/SimpleStateMachine.StructuralSearch/IInput.cs delete mode 100644 src/SimpleStateMachine.StructuralSearch/ISource.cs delete mode 100644 src/SimpleStateMachine.StructuralSearch/Placeholder/FileProperty.cs diff --git a/src/SimpleStateMachine.StructuralSearch.Sandbox/Program.cs b/src/SimpleStateMachine.StructuralSearch.Sandbox/Program.cs index 56b4bf0..aa83d93 100644 --- a/src/SimpleStateMachine.StructuralSearch.Sandbox/Program.cs +++ b/src/SimpleStateMachine.StructuralSearch.Sandbox/Program.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text.Json; using System.Text.RegularExpressions; diff --git a/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs b/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs index a987059..d46d109 100644 --- a/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs +++ b/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs @@ -8,5 +8,11 @@ public Result Parse(Parser parser) { throw new System.NotImplementedException(); } + + public string Extension => string.Empty; + public string Path => string.Empty; + public string Name => string.Empty; + public string Data => string.Empty; + public long Lenght => 0; } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/FileInput.cs b/src/SimpleStateMachine.StructuralSearch/FileInput.cs index 4e10de7..a386c39 100644 --- a/src/SimpleStateMachine.StructuralSearch/FileInput.cs +++ b/src/SimpleStateMachine.StructuralSearch/FileInput.cs @@ -16,5 +16,11 @@ public Result Parse(Parser parser) { return parser.Parse(FileInfo.OpenText()); } + + public string Extension => FileInfo.Extension; + public string Path => System.IO.Path.GetFullPath(FileInfo.FullName); + public string Name => System.IO.Path.GetFileNameWithoutExtension(FileInfo.Name); + public string Data => FileInfo.OpenText().ReadToEnd(); + public long Lenght => FileInfo.Length; } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/IInput.cs b/src/SimpleStateMachine.StructuralSearch/IInput.cs new file mode 100644 index 0000000..fbb012f --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/IInput.cs @@ -0,0 +1,15 @@ +using Pidgin; + +namespace SimpleStateMachine.StructuralSearch +{ + public interface IInput + { + Result Parse(Parser parser); + + string Extension { get; } + string Path { get; } + string Name { get; } + string Data { get; } + public long Lenght { get; } + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/ISource.cs b/src/SimpleStateMachine.StructuralSearch/ISource.cs deleted file mode 100644 index 2c4ac60..0000000 --- a/src/SimpleStateMachine.StructuralSearch/ISource.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Pidgin; - -namespace SimpleStateMachine.StructuralSearch -{ - public interface IInput - { - Result Parse(Parser parser); - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs b/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs index a739845..62b416b 100644 --- a/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs +++ b/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs @@ -10,8 +10,6 @@ public ParsingContext(IInput input) } public Dictionary Placeholders { get; } = new(); - public FileProperty File { get; } - public IInput Input { get; } public bool TryGetPlaceholder(string name, out Placeholder value) diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/FileProperty.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/FileProperty.cs deleted file mode 100644 index 1dbd1f9..0000000 --- a/src/SimpleStateMachine.StructuralSearch/Placeholder/FileProperty.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.IO; - -namespace SimpleStateMachine.StructuralSearch -{ - public class FileProperty - { - public FileProperty(FileInfo fileInfo) - { - FileInfo = fileInfo; - StreamReader = new StreamReader(fileInfo.OpenRead()); - } - - public readonly FileInfo FileInfo; - public readonly string Path; - public readonly string Data; - public readonly StreamReader StreamReader; - public string Name => FileInfo.Name; - public string Directory => FileInfo.FullName; - public long Lenght => FileInfo.Length; - - public static FileProperty FromFile(string path) - { - return new FileProperty(new FileInfo(path)); - } - - public static readonly FileProperty Empty = new FileProperty(null); - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs index 35d6230..32311c4 100644 --- a/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs +++ b/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs @@ -20,7 +20,7 @@ public Placeholder(IParsingContext context, string name, string value, LinePrope public readonly LineProperty Line; public readonly ColumnProperty Column; public readonly OffsetProperty Offset; - + public IInput Input => _context.Input; public static Placeholder CreateEmpty(IParsingContext context, string name, string value) { diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/FileProperty.cs b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/FileProperty.cs index 3f039e1..78cef0d 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/FileProperty.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/FileProperty.cs @@ -4,8 +4,8 @@ public enum FileProperty { Path = 0, Data, + Extension, Name, - Directory, Lenght } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs index c6be479..fbda8e5 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs @@ -15,17 +15,16 @@ public PlaceholderFileParameter(PlaceholderParameter parameter, FileProperty pro public string GetValue() { - // TODO - // var file = PlaceholderParameter.GetPlaceholder().File; - // return Property switch - // { - // FileProperty.Path => file.Path, - // FileProperty.Data => file.Data, - // FileProperty.Name => file.Name, - // FileProperty.Directory => file.Directory, - // FileProperty.Lenght => file.Lenght.ToString(), - // _ => throw new ArgumentOutOfRangeException() - // }; + var input = PlaceholderParameter.GetPlaceholder().Input; + return Property switch + { + FileProperty.Path => input.Path, + FileProperty.Data => input.Data, + FileProperty.Extension => input.Extension, + FileProperty.Name => input.Name, + FileProperty.Lenght => input.Lenght.ToString(), + _ => throw new ArgumentOutOfRangeException() + }; return null; } diff --git a/src/SimpleStateMachine.StructuralSearch/StringInput.cs b/src/SimpleStateMachine.StructuralSearch/StringInput.cs index f55b02a..ea8c245 100644 --- a/src/SimpleStateMachine.StructuralSearch/StringInput.cs +++ b/src/SimpleStateMachine.StructuralSearch/StringInput.cs @@ -15,5 +15,11 @@ public Result Parse(Parser parser) { return parser.Parse(Input); } + + public string Extension => string.Empty; + public string Path => string.Empty; + public string Name => string.Empty; + public string Data => string.Empty; + public long Lenght => Input.Length; } } \ No newline at end of file From e47385d9d6817edb7fcc1ab57f3c969cab4eafe1 Mon Sep 17 00:00:00 2001 From: GMIKE Date: Sun, 17 Apr 2022 16:40:28 +0300 Subject: [PATCH 03/11] fix parsing whitespaces --- .../Parsers/PlaceholderParser.cs | 2 +- .../Rules/Parameters/PlaceholderFileParameter.cs | 2 -- src/SimpleStateMachine.StructuralSearch/SeriesParser.cs | 2 +- .../StructuralSearch/CommonParser.cs | 3 ++- .../StructuralSearch/FindTemplateParser.cs | 2 +- .../Templates/FindTemplate/ParserToParser.cs | 5 +++++ 6 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs b/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs index 7b2a78a..5d6b263 100644 --- a/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs @@ -20,7 +20,7 @@ public override Parser BuildParser(Func?> nex Func?> nextNext) { var _next = next(); - var _nextNext = nextNext() ?? Parser.End.ThenReturn(string.Empty); + var _nextNext = nextNext() ?? Parser.OneOf(CommonParser.WhiteSpaces, Parser.End.ThenReturn(string.Empty)); var lookahead = Parsers.Lookahead(_next.Then(_nextNext, (s1, s2) => { OnLookahead = () => new List> diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs index fbda8e5..c1a6746 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/PlaceholderFileParameter.cs @@ -25,8 +25,6 @@ public string GetValue() FileProperty.Lenght => input.Lenght.ToString(), _ => throw new ArgumentOutOfRangeException() }; - - return null; } public override string ToString() diff --git a/src/SimpleStateMachine.StructuralSearch/SeriesParser.cs b/src/SimpleStateMachine.StructuralSearch/SeriesParser.cs index 4b68b35..85bf00a 100644 --- a/src/SimpleStateMachine.StructuralSearch/SeriesParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/SeriesParser.cs @@ -27,7 +27,7 @@ public override bool TryParse(ref ParseState state, ref PooledList(); + result = results; return false; } diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/CommonParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/CommonParser.cs index 7ea026f..be5fdb0 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/CommonParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/CommonParser.cs @@ -25,7 +25,8 @@ internal static readonly Parser LineEnds = EndOfLine.AtLeastOnceString(); internal static readonly Parser WhiteSpaces - = OneOf(Spaces, LineEnds); + = OneOf(Spaces, LineEnds, LineEnds) + .AtLeastOnceString(); internal static readonly Parser Identifier = Letter.Then(AnyString, (h, t) => h + t); diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindTemplateParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindTemplateParser.cs index 59f767c..d8f6bbb 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindTemplateParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindTemplateParser.cs @@ -32,7 +32,7 @@ static FindTemplateParser() .Try(); internal static readonly Parser> WhiteSpaces = - ParserToParser.ResultAsParser(CommonParser.WhiteSpaces) + ParserToParser.ParserAsParser(CommonParser.WhiteSpaces) .Try(); internal static readonly Parser> Placeholder = diff --git a/src/SimpleStateMachine.StructuralSearch/Templates/FindTemplate/ParserToParser.cs b/src/SimpleStateMachine.StructuralSearch/Templates/FindTemplate/ParserToParser.cs index f505059..fa80992 100644 --- a/src/SimpleStateMachine.StructuralSearch/Templates/FindTemplate/ParserToParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/Templates/FindTemplate/ParserToParser.cs @@ -27,6 +27,11 @@ public static Parser> ResultAsParser(Parser Parsers.String(value, ignoreCase)); } + public static Parser> ParserAsParser(Parser parser) + { + return parser.Select(value => parser); + } + public static Parser> ResultAsMatch(Parser parser, bool ignoreCase = false) { return parser.Select(x=> Parsers.String(x, ignoreCase).AsMatch()); From 5b775431dd13ab48f984c0ca071307e14bb59465 Mon Sep 17 00:00:00 2001 From: GMIKE Date: Sat, 23 Apr 2022 04:23:00 +0300 Subject: [PATCH 04/11] readonly record struct, update .Net version --- global.json | 2 +- ...ateMachine.StructuralSearch.Sandbox.csproj | 4 +- .../Examples/TernaryOperator.cs | 36 ++++++++--------- .../FindTemplateTests.cs | 4 +- ...StateMachine.StructuralSearch.Tests.csproj | 6 +-- .../Extensions/MatchExtensions.cs | 9 +++++ .../Extensions/ParserExtensions.cs | 38 ++++++++++++++++++ .../FindParser.cs | 26 +++++++++---- .../IFindParser.cs | 2 +- .../Parsers/ParserWithLookahead.cs | 8 ++-- .../Parsers/Parsers.cs | 39 +++++++++++++++++++ .../Parsers/PlaceholderParser.cs | 16 ++------ .../Placeholder/Column.cs | 14 ------- .../Placeholder/ColumnPosition.cs | 10 +++++ .../Placeholder/LinePosition.cs | 10 +++++ .../Placeholder/LineProperty.cs | 14 ------- .../Placeholder/MatchPosition.cs | 20 ++++++++++ .../Placeholder/OffsetPosition.cs | 10 +++++ .../Placeholder/OffsetProperty.cs | 14 ------- .../Placeholder/Placeholder.cs | 33 ++++++++-------- ...SimpleStateMachine.StructuralSearch.csproj | 2 +- 21 files changed, 208 insertions(+), 109 deletions(-) create mode 100644 src/SimpleStateMachine.StructuralSearch/Extensions/MatchExtensions.cs delete mode 100644 src/SimpleStateMachine.StructuralSearch/Placeholder/Column.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/Placeholder/ColumnPosition.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/Placeholder/LinePosition.cs delete mode 100644 src/SimpleStateMachine.StructuralSearch/Placeholder/LineProperty.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/Placeholder/MatchPosition.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/Placeholder/OffsetPosition.cs delete mode 100644 src/SimpleStateMachine.StructuralSearch/Placeholder/OffsetProperty.cs diff --git a/global.json b/global.json index e5674e1..1bcf6c0 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "5.0.0", + "version": "6.0.0", "rollForward": "latestMinor", "allowPrerelease": false } diff --git a/src/SimpleStateMachine.StructuralSearch.Sandbox/SimpleStateMachine.StructuralSearch.Sandbox.csproj b/src/SimpleStateMachine.StructuralSearch.Sandbox/SimpleStateMachine.StructuralSearch.Sandbox.csproj index 5ae1b76..72e7851 100644 --- a/src/SimpleStateMachine.StructuralSearch.Sandbox/SimpleStateMachine.StructuralSearch.Sandbox.csproj +++ b/src/SimpleStateMachine.StructuralSearch.Sandbox/SimpleStateMachine.StructuralSearch.Sandbox.csproj @@ -5,11 +5,11 @@ net5.0 enable enable - 9 + 10 - + diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/Examples/TernaryOperator.cs b/src/SimpleStateMachine.StructuralSearch.Tests/Examples/TernaryOperator.cs index f45b96f..8cd797b 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/Examples/TernaryOperator.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/Examples/TernaryOperator.cs @@ -6,44 +6,44 @@ public class TernaryOperator { public int Test1() { - var temp = 150; + var temp = 1; - if(temp == 125) - return 12; + if(temp == 2) + return 3; else - return 15; + return 4; } public int Test2() { - var temp = 150; + var temp = 5; - if(temp == 125) - return 12; + if(temp == 6) + return 7; else - return 15; + return 8; } public int Test3() { - var temp2 = 150; + var temp2 = 1; - if(temp2 == 125) - return 12; + if(temp2 == 2) + return 3; else - return 15; + return 4; } public int Test4() { - var temp3 = 150; + var temp3 = 5; - if(temp3 == 125) - return 12; - else if (temp3 == 135) - return 15; + if(temp3 == 6) + return 7; + else if (temp3 == 8) + return 9; else - return 0; + return 10; } public void Test5() diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateTests.cs index 39cb231..90749de 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateTests.cs @@ -34,8 +34,8 @@ public void SourceParsingBeFindTemplateShouldBeSuccess(string templatePath, stri var result = findParser.Parse(ref parsingContext, input); Assert.NotNull(findParser); - Assert.NotNull(result.Value); - Assert.Equal(result.Lenght, source.Length); + // Assert.NotNull(result.Value); + Assert.Equal(result.Length, source.Length); } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj b/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj index 8f8652b..abbde51 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj +++ b/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj @@ -4,17 +4,17 @@ net5.0 enable false - 9 + 10 - + runtime; build; native; contentfiles; analyzers; buildtransitive all - + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/src/SimpleStateMachine.StructuralSearch/Extensions/MatchExtensions.cs b/src/SimpleStateMachine.StructuralSearch/Extensions/MatchExtensions.cs new file mode 100644 index 0000000..6efb91b --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Extensions/MatchExtensions.cs @@ -0,0 +1,9 @@ +namespace SimpleStateMachine.StructuralSearch.Extensions; + +public static class MatchExtensions +{ + public static bool IsEmpty(this Match match) + { + return string.IsNullOrEmpty(match.Value); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Extensions/ParserExtensions.cs b/src/SimpleStateMachine.StructuralSearch/Extensions/ParserExtensions.cs index 9edcdcc..750e0f1 100644 --- a/src/SimpleStateMachine.StructuralSearch/Extensions/ParserExtensions.cs +++ b/src/SimpleStateMachine.StructuralSearch/Extensions/ParserExtensions.cs @@ -49,6 +49,44 @@ public static Parser Contains(this Parser pa : throw new ArgumentNullException(nameof(parser)); } + // public static Parser Match(this Parser parser, ref ParseState state, + // ref PooledList> expected, out T result) + // { + // Parser.CurrentPos.TryParse(ref state, ref expected, out var oldPos); + // Parser.CurrentOffset.TryParse(ref state, ref expected, out var oldOffset); + // var res = parser.TryParse(ref state, ref expected, out result); + // + // if (res) + // { + // Parser.CurrentPos.TryParse(ref state, ref expected, out var newPos); + // Parser.CurrentOffset.TryParse(ref state, ref expected, out var newOffset); + // + // var line = new LinePosition(oldPos.Line, newPos.Line); + // var column = new ColumnPosition(oldPos.Col, newPos.Col); + // var offset = new OffsetPosition(oldOffset, newOffset); + // + // return null; + // } + // } + + public static Parser> Match(this Parser parser) + { + return Map((oldPos, oldOffset, result, newPos, newOffset) => + { + var line = new LinePosition(oldPos.Line, newPos.Line); + var column = new ColumnPosition(oldPos.Col, newPos.Col); + var offset = new OffsetPosition(oldOffset, newOffset); + var lenght = newOffset - oldOffset; + return new Match(result, lenght, column, line, offset); + }, + Parser.CurrentPos, Parser.CurrentOffset, + parser, + Parser.CurrentPos, Parser.CurrentOffset); + } + + + + // public static Parser WithResult(this Parser parser, Func transformResult) // { // = Parser.CurrentSourcePosDelta.Select((Func) (d => new SourcePos(1, 1) + d)); diff --git a/src/SimpleStateMachine.StructuralSearch/FindParser.cs b/src/SimpleStateMachine.StructuralSearch/FindParser.cs index 3d68f72..85660f0 100644 --- a/src/SimpleStateMachine.StructuralSearch/FindParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/FindParser.cs @@ -1,5 +1,8 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.IO; +using System.Linq; +using System.Text; using Pidgin; using SimpleStateMachine.StructuralSearch.Extensions; using YamlDotNet.Core.Events; @@ -14,14 +17,23 @@ public FindParser(SeriesParser parser) Parser = parser; } - public SourceMatch Parse(ref IParsingContext context, IInput input) + public string Parse(ref IParsingContext context, IInput input) { + StringBuilder res = new StringBuilder(); Parser.SetContext(ref context); - - var result = input.Parse(Parser.Select(x => string.Join(string.Empty, x)) - .AsMatch()); - - return result.Success ? result.Value : SourceMatch.Empty; + var parser = Parser.Select(x => string.Join(string.Empty, x)).Match().Try(); + var empty = Pidgin.Parser.Any.Select(x=> + { + res.Append(x); + return string.Empty; + }).ThenReturn(Match.EmptyMatchString); + var parse = Pidgin.Parser.OneOf(parser, empty) + .Many(); + + var result = input.Parse(parse); + var t = result.Value.Where(x => !x.IsEmpty()); + // return result.Success ? result.Value.JoinToString() : string.Empty; + return string.Empty; } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/IFindParser.cs b/src/SimpleStateMachine.StructuralSearch/IFindParser.cs index 95db213..3b4b90a 100644 --- a/src/SimpleStateMachine.StructuralSearch/IFindParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/IFindParser.cs @@ -7,6 +7,6 @@ namespace SimpleStateMachine.StructuralSearch { public interface IFindParser { - SourceMatch Parse(ref IParsingContext context, IInput input); + string Parse(ref IParsingContext context, IInput input); } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Parsers/ParserWithLookahead.cs b/src/SimpleStateMachine.StructuralSearch/Parsers/ParserWithLookahead.cs index 187e6e9..7c67a9b 100644 --- a/src/SimpleStateMachine.StructuralSearch/Parsers/ParserWithLookahead.cs +++ b/src/SimpleStateMachine.StructuralSearch/Parsers/ParserWithLookahead.cs @@ -1,12 +1,14 @@ using System; using System.Collections.Generic; +using System.Runtime.CompilerServices; using Pidgin; +using SimpleStateMachine.StructuralSearch.Extensions; namespace SimpleStateMachine.StructuralSearch { public abstract class ParserWithLookahead : Parser { - private Func> _parser { get; set; } + protected Lazy> parser; public Func>> OnLookahead { get; set; } @@ -16,13 +18,13 @@ public abstract Parser BuildParser(Func?> next, public void Lookahead(Func?> next, Func?> nextNext) { // lazy initialization - _parser = () => BuildParser(next, nextNext); + parser = new Lazy>(() => BuildParser(next, nextNext)); } public override bool TryParse(ref ParseState state, ref PooledList> expected, out T result) { - var res = _parser().TryParse(ref state, ref expected, out result); + var res = parser.Value.TryParse(ref state, ref expected, out result); return res; } } diff --git a/src/SimpleStateMachine.StructuralSearch/Parsers/Parsers.cs b/src/SimpleStateMachine.StructuralSearch/Parsers/Parsers.cs index 42d3fc9..e64b0d9 100644 --- a/src/SimpleStateMachine.StructuralSearch/Parsers/Parsers.cs +++ b/src/SimpleStateMachine.StructuralSearch/Parsers/Parsers.cs @@ -121,5 +121,44 @@ public static Parser Lookahead(Parser parser) = parser != null ? (Parser) new LookaheadParser(parser) : throw new ArgumentNullException(nameof (parser)); + + public static Parser> Match(Parser parser) + { + return Map((oldPos, oldOffset, result, newPos, newOffset) => + { + var line = new LinePosition(oldPos.Line, newPos.Line); + var column = new ColumnPosition(oldPos.Col, newPos.Col); + var offset = new OffsetPosition(oldOffset, newOffset); + var lenght = newOffset - oldOffset; + return new Match(result, lenght, column, line, offset); + }, + Parser.CurrentPos, Parser.CurrentOffset, + parser, + Parser.CurrentPos, Parser.CurrentOffset); + } + + + // public static string Match(Parser parser, ref ParseState state, + // ref PooledList> expected, out string result) + // { + // Parser.CurrentPos.Then(Parser.CurrentOffset, (pos, i) => (oldPos, oldOffset)) + // .Then() + // .TryParse(ref state, ref expected, out var oldPos); + // .TryParse(ref state, ref expected, out var oldOffset); + // var res = parser.TryParse(ref state, ref expected, out result); + // + // if (res) + // { + // Parser.CurrentPos.TryParse(ref state, ref expected, out var newPos); + // Parser.CurrentOffset.TryParse(ref state, ref expected, out var newOffset); + // + // var line = new LinePosition(oldPos.Line, newPos.Line); + // var column = new ColumnPosition(oldPos.Col, newPos.Col); + // var offset = new OffsetPosition(oldOffset, newOffset); + // + // } + // + // return null; + // } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs b/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs index 5d6b263..8bd3e55 100644 --- a/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs @@ -20,7 +20,7 @@ public override Parser BuildParser(Func?> nex Func?> nextNext) { var _next = next(); - var _nextNext = nextNext() ?? Parser.OneOf(CommonParser.WhiteSpaces, Parser.End.ThenReturn(string.Empty)); + var _nextNext = nextNext() ?? Parser.OneOf(Parser.Any.AsString(), Parser.End.ThenReturn(string.Empty)); var lookahead = Parsers.Lookahead(_next.Then(_nextNext, (s1, s2) => { OnLookahead = () => new List> @@ -66,22 +66,14 @@ public override bool TryParse(ref ParseState state, ref PooledList.CurrentPos.TryParse(ref state, ref expected, out var oldPos); - Parser.CurrentOffset.TryParse(ref state, ref expected, out var oldOffset); - res = base.TryParse(ref state, ref expected, out result); - + res = parser.Value.Match().TryParse(ref state, ref expected, out var match); + result = match.Value; if (res) { - Parser.CurrentSourcePosDelta.TryParse(ref state, ref expected, out var posDelta); - Parser.CurrentOffset.TryParse(ref state, ref expected, out var newOffset); - _context.AddPlaceholder(new Placeholder( context: _context, name: Name, - value: result, - line: new LineProperty(oldPos.Line, oldPos.Line + posDelta.Lines), - column: new ColumnProperty(oldPos.Col, oldPos.Col + posDelta.Cols), - offset: new OffsetProperty(oldOffset, newOffset))); + match: match)); } } diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/Column.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/Column.cs deleted file mode 100644 index 25c4480..0000000 --- a/src/SimpleStateMachine.StructuralSearch/Placeholder/Column.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace SimpleStateMachine.StructuralSearch -{ - public class ColumnProperty - { - public ColumnProperty(int start, int end) - { - Start = start; - End = end; - } - - public readonly int Start; - public readonly int End; - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/ColumnPosition.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/ColumnPosition.cs new file mode 100644 index 0000000..6776195 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Placeholder/ColumnPosition.cs @@ -0,0 +1,10 @@ +namespace SimpleStateMachine.StructuralSearch +{ + public readonly record struct ColumnPosition(int Start, int End) + { + public readonly int Start = Start; + public readonly int End = End; + + public static readonly ColumnPosition Empty = new(0, 0); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/LinePosition.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/LinePosition.cs new file mode 100644 index 0000000..1ed42d1 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Placeholder/LinePosition.cs @@ -0,0 +1,10 @@ +namespace SimpleStateMachine.StructuralSearch +{ + public readonly record struct LinePosition(int Start, int End) + { + public readonly int Start = Start; + public readonly int End = End; + + public static readonly LinePosition Empty = new(0, 0); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/LineProperty.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/LineProperty.cs deleted file mode 100644 index 30aa306..0000000 --- a/src/SimpleStateMachine.StructuralSearch/Placeholder/LineProperty.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace SimpleStateMachine.StructuralSearch -{ - public class LineProperty - { - public LineProperty(int start, int end) - { - Start = start; - End = end; - } - - public readonly int Start; - public readonly int End; - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/MatchPosition.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/MatchPosition.cs new file mode 100644 index 0000000..4e02ece --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Placeholder/MatchPosition.cs @@ -0,0 +1,20 @@ +using System; + +namespace SimpleStateMachine.StructuralSearch +{ + public readonly record struct Match(T Value, int Lenght, ColumnPosition Column, LinePosition Line, + OffsetPosition Offset) + { + + } + + public static class Match + { + public static readonly Match EmptyMatchString = new( + string.Empty, + 0, + ColumnPosition.Empty, + LinePosition.Empty, + OffsetPosition.Empty); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/OffsetPosition.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/OffsetPosition.cs new file mode 100644 index 0000000..7cd526b --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Placeholder/OffsetPosition.cs @@ -0,0 +1,10 @@ +namespace SimpleStateMachine.StructuralSearch +{ + public readonly record struct OffsetPosition(int Start, int End) + { + public readonly int Start = Start; + public readonly int End = End; + + public static readonly OffsetPosition Empty = new(0, 0); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/OffsetProperty.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/OffsetProperty.cs deleted file mode 100644 index 4454d5f..0000000 --- a/src/SimpleStateMachine.StructuralSearch/Placeholder/OffsetProperty.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace SimpleStateMachine.StructuralSearch -{ - public class OffsetProperty - { - public OffsetProperty(int start, int end) - { - Start = start; - End = end; - } - - public readonly int Start; - public readonly int End; - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs index 32311c4..367631a 100644 --- a/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs +++ b/src/SimpleStateMachine.StructuralSearch/Placeholder/Placeholder.cs @@ -1,25 +1,22 @@ namespace SimpleStateMachine.StructuralSearch { - public class Placeholder + public readonly struct Placeholder { - private IParsingContext _context; - public Placeholder(IParsingContext context, string name, string value, LineProperty line, ColumnProperty column, OffsetProperty offset) + private readonly Match _match; + private readonly IParsingContext _context; + public Placeholder(IParsingContext context, string name, Match match) { _context = context; Name = name; - Lenght = value.Length; - Value = value; - Line = line; - Column = column; - Offset = offset; + _match = match; } public readonly string Name; - public readonly string Value; - public readonly int Lenght; - public readonly LineProperty Line; - public readonly ColumnProperty Column; - public readonly OffsetProperty Offset; + public string Value => _match.Value; + public int Lenght => _match.Lenght; + public LinePosition Line => _match.Line; + public ColumnPosition Column => _match.Column; + public OffsetPosition Offset => _match.Offset; public IInput Input => _context.Input; public static Placeholder CreateEmpty(IParsingContext context, string name, string value) @@ -27,10 +24,12 @@ public static Placeholder CreateEmpty(IParsingContext context, string name, stri return new Placeholder( context: context, name: name, - value: value, - line: null, - column: null, - offset: null); + new Match( + value, + value.Length, + ColumnPosition.Empty, + LinePosition.Empty, + OffsetPosition.Empty)); } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/SimpleStateMachine.StructuralSearch.csproj b/src/SimpleStateMachine.StructuralSearch/SimpleStateMachine.StructuralSearch.csproj index 1e35bc2..e501e18 100644 --- a/src/SimpleStateMachine.StructuralSearch/SimpleStateMachine.StructuralSearch.csproj +++ b/src/SimpleStateMachine.StructuralSearch/SimpleStateMachine.StructuralSearch.csproj @@ -2,7 +2,7 @@ net5.0 - 9 + 10 enable From f43c0f52ec16a8391525699a184c527015331fa2 Mon Sep 17 00:00:00 2001 From: GMIKE Date: Sun, 24 Apr 2022 04:07:38 +0300 Subject: [PATCH 05/11] FindParserMatch --- ...ateTests.cs => FindTemplateParserTests.cs} | 9 +- .../Mock/EmptyParsingContext.cs | 9 +- .../PlaceholderParserTests.cs | 29 ++++-- .../EmptyInput.cs | 2 +- .../Extensions/ParserExtensions.cs | 88 +++---------------- .../FileInput.cs | 2 +- .../FindParser.cs | 43 +++++---- .../FindParserResult.cs | 5 ++ .../IFindParser.cs | 2 +- .../IInput.cs | 2 +- .../IParsingContext.cs | 6 +- .../Parsers/LookaheadParser.cs | 5 +- .../Parsers/ParserWithLookahead.cs | 1 - .../Parsers/PlaceholderParser.cs | 5 +- .../ParsingContext.cs | 12 ++- .../Placeholder/MatchPosition.cs | 7 +- .../StringInput.cs | 2 +- .../StructuralSearchParser.cs | 2 +- 18 files changed, 109 insertions(+), 122 deletions(-) rename src/SimpleStateMachine.StructuralSearch.Tests/{FindTemplateTests.cs => FindTemplateParserTests.cs} (87%) create mode 100644 src/SimpleStateMachine.StructuralSearch/FindParserResult.cs diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateParserTests.cs similarity index 87% rename from src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateTests.cs rename to src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateParserTests.cs index 90749de..4abc086 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplateParserTests.cs @@ -1,4 +1,5 @@ using System.IO; +using System.Linq; using Pidgin; using Xunit; @@ -31,11 +32,13 @@ public void SourceParsingBeFindTemplateShouldBeSuccess(string templatePath, stri var input = Input.String(source); var findParser = StructuralSearch.ParseFindTemplate(findTemplate); IParsingContext parsingContext = new ParsingContext(input); - var result = findParser.Parse(ref parsingContext, input); + var matches = findParser.Parse(ref parsingContext); + Assert.Single(matches); + + var match = matches.First(); Assert.NotNull(findParser); - // Assert.NotNull(result.Value); - Assert.Equal(result.Length, source.Length); + Assert.Equal(match.Match.Lenght, source.Length); } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs b/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs index 4512e4b..282c5c0 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs @@ -1,4 +1,6 @@ -namespace SimpleStateMachine.StructuralSearch.Tests.Mock +using System.Collections.Generic; + +namespace SimpleStateMachine.StructuralSearch.Tests.Mock { public class EmptyParsingContext : IParsingContext { @@ -18,5 +20,10 @@ public Placeholder GetPlaceholder(string name) { return Placeholder.CreateEmpty(this, name, string.Empty); } + + public IReadOnlyDictionary Switch() + { + throw new System.NotImplementedException(); + } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs index 362f23e..52fcad6 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs @@ -1,4 +1,7 @@ -using Pidgin; +using System.Collections.Generic; +using System.Linq; +using Microsoft.VisualBasic; +using Pidgin; using Xunit; namespace SimpleStateMachine.StructuralSearch.Tests @@ -21,22 +24,32 @@ public void TemplateParsingShouldBeSuccess(string template, string source, strin var input = Input.String(source); IParsingContext parsingContext = new ParsingContext(input); var templateParser = StructuralSearch.ParseFindTemplate(template); - var res = templateParser.Parse(ref parsingContext, input); - var placeholder = parsingContext.GetPlaceholder("test"); + var matches = templateParser.Parse(ref parsingContext); + + Assert.Single(matches); + var match = matches.First(); + Assert.Single(match.Placeholders); + var placeholder = match.Placeholders.First(); - Assert.Equal(placeholder.Value, result); + Assert.Equal(placeholder.Value.Value, result); } [Theory] - [InlineData("$var$;$var2$;", "test;;;test;;;", "value ")] - public void TemplateParsingShouldBeSuccess2(string template, string source, string result) + [InlineData("$var$;", "test;;;", "test;;")] + [InlineData("$var$;.", "test;;;.", "test;;")] + [InlineData("$var$;$var2$;", "test;;;test;;;", "test",";;test;;")] + public void TemplateParsingShouldBeSuccess2(string template, string source, params string[] values) { var input = Input.String(source); IParsingContext parsingContext = new ParsingContext(input); var templateParser = StructuralSearch.ParseFindTemplate(template); - templateParser.Parse(ref parsingContext, input); - + var matches = templateParser.Parse(ref parsingContext); + Assert.Single(matches); + var match = matches.First(); + Assert.Equal(match.Placeholders.Count, values.Length); + Assert.Equal(match.Placeholders.Select(x=> x.Value.Value), values); + // var templateStr = File.ReadAllText(templatePath); // var template = StructuralSearch.ParseTemplate(templateStr); // diff --git a/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs b/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs index d46d109..ff366dd 100644 --- a/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs +++ b/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs @@ -4,7 +4,7 @@ namespace SimpleStateMachine.StructuralSearch { public class EmptyInput : IInput { - public Result Parse(Parser parser) + public Result ParseBy(Parser parser) { throw new System.NotImplementedException(); } diff --git a/src/SimpleStateMachine.StructuralSearch/Extensions/ParserExtensions.cs b/src/SimpleStateMachine.StructuralSearch/Extensions/ParserExtensions.cs index 750e0f1..4a46019 100644 --- a/src/SimpleStateMachine.StructuralSearch/Extensions/ParserExtensions.cs +++ b/src/SimpleStateMachine.StructuralSearch/Extensions/ParserExtensions.cs @@ -42,32 +42,22 @@ public static bool TryParse(this Parser parser, string value, out result = res.Success ? res.Value : default; return res.Success; } + + public static Parser ThenInvoke(this Parser parser, Action action) + { + return parser.Select(x => + { + action.Invoke(x); + return x; + }); + } + public static Parser Contains(this Parser parser) { return parser != null ? parser.Optional().Select(x => x.HasValue) : throw new ArgumentNullException(nameof(parser)); } - - // public static Parser Match(this Parser parser, ref ParseState state, - // ref PooledList> expected, out T result) - // { - // Parser.CurrentPos.TryParse(ref state, ref expected, out var oldPos); - // Parser.CurrentOffset.TryParse(ref state, ref expected, out var oldOffset); - // var res = parser.TryParse(ref state, ref expected, out result); - // - // if (res) - // { - // Parser.CurrentPos.TryParse(ref state, ref expected, out var newPos); - // Parser.CurrentOffset.TryParse(ref state, ref expected, out var newOffset); - // - // var line = new LinePosition(oldPos.Line, newPos.Line); - // var column = new ColumnPosition(oldPos.Col, newPos.Col); - // var offset = new OffsetPosition(oldOffset, newOffset); - // - // return null; - // } - // } public static Parser> Match(this Parser parser) { @@ -83,37 +73,7 @@ public static Parser> Match(this Parser parser) parser, Parser.CurrentPos, Parser.CurrentOffset); } - - - - - // public static Parser WithResult(this Parser parser, Func transformResult) - // { - // = Parser.CurrentSourcePosDelta.Select((Func) (d => new SourcePos(1, 1) + d)); - // parser.Select() - // return this.Select((Func)(_ => result)); - // } - - // public static Parser BetweenWithLookahead(this Parser parser, Parser parser1, Parser parser2) - // { - // if (parser1 == null) - // throw new ArgumentNullException(nameof (parser1)); - // if (parser2 == null) - // throw new ArgumentNullException(nameof (parser2)); - // - // return Parser.Map((Func) ((_, t, _) => t), parser1, parser, parser2); - // } - // public Parser Between( - // Parser parser1, - // Parser parser2) - // { - // if (parser1 == null) - // throw new ArgumentNullException(nameof (parser1)); - // if (parser2 == null) - // throw new ArgumentNullException(nameof (parser2)); - // return Parser.Map((Func) ((u, t, v) => t), parser1, this, parser2); - // } public static Parser WithDebug(this Parser parser, string label) { return Map((u, t, v) => @@ -153,33 +113,5 @@ public static Parser After(this Parser parse { return parserAfter.Then(parser, (u, t) => t); } - - // public static Parser BetweenAsThen(this Parser parser, Parser parser1, Parser parser2, Func func) - // { - // if (parser1 == null) - // throw new ArgumentNullException(nameof (parser1)); - // if (parser2 == null) - // throw new ArgumentNullException(nameof (parser2)); - // - // return Parser.Map(func, parser1, this, parser2); - // } - - // public static Parser Between(this Parser parser, - // Parser parser1, - // Parser parser2) - // { - // if (parser1 == null) - // throw new ArgumentNullException(nameof (parser1)); - // if (parser2 == null) - // throw new ArgumentNullException(nameof (parser2)); - // return Parser.Map((Func) ((u, t, v) => t), parser1, this, parser2); - // } - - // public static T ParseOrThrow(this Parser parser, - // string input, - // IConfiguration? configuration = null) - // { - // return ParserExtensions.GetValueOrThrow(parser.Parse(input, configuration)); - // } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/FileInput.cs b/src/SimpleStateMachine.StructuralSearch/FileInput.cs index a386c39..1c46fbe 100644 --- a/src/SimpleStateMachine.StructuralSearch/FileInput.cs +++ b/src/SimpleStateMachine.StructuralSearch/FileInput.cs @@ -12,7 +12,7 @@ public FileInput(FileInfo fileInfo) public readonly FileInfo FileInfo; - public Result Parse(Parser parser) + public Result ParseBy(Parser parser) { return parser.Parse(FileInfo.OpenText()); } diff --git a/src/SimpleStateMachine.StructuralSearch/FindParser.cs b/src/SimpleStateMachine.StructuralSearch/FindParser.cs index 85660f0..e07aafc 100644 --- a/src/SimpleStateMachine.StructuralSearch/FindParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/FindParser.cs @@ -12,28 +12,39 @@ namespace SimpleStateMachine.StructuralSearch public class FindParser : IFindParser { private SeriesParser Parser { get; } - public FindParser(SeriesParser parser) + public FindParser(SeriesParser parser) { Parser = parser; } - public string Parse(ref IParsingContext context, IInput input) + public IEnumerable Parse(ref IParsingContext context) { - StringBuilder res = new StringBuilder(); + List matches = new(); + StringBuilder res = new(); Parser.SetContext(ref context); - var parser = Parser.Select(x => string.Join(string.Empty, x)).Match().Try(); - var empty = Pidgin.Parser.Any.Select(x=> - { - res.Append(x); - return string.Empty; - }).ThenReturn(Match.EmptyMatchString); - var parse = Pidgin.Parser.OneOf(parser, empty) - .Many(); - - var result = input.Parse(parse); - var t = result.Value.Where(x => !x.IsEmpty()); - // return result.Success ? result.Value.JoinToString() : string.Empty; - return string.Empty; + + var parsingContext = context; + var parser = Parser.Select(x => string.Join(string.Empty, x)) + .Match() + .ThenInvoke(match => + { + var placeholders= parsingContext.Switch(); + matches.Add(new FindParserMatch(match, placeholders)); + }) + .ThenReturn(Unit.Value) + .Try(); + + var empty = Parser.Any + .ThenInvoke(x => + { + res.Append(x); + parsingContext.Switch(); + }) + .ThenReturn(Unit.Value); + + context.Input.ParseBy(Pidgin.Parser.OneOf(parser, empty).Many()); + + return matches.OrderBy(x=> x.Match.Offset.Start); } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/FindParserResult.cs b/src/SimpleStateMachine.StructuralSearch/FindParserResult.cs new file mode 100644 index 0000000..39ce87c --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/FindParserResult.cs @@ -0,0 +1,5 @@ +using System.Collections.Generic; + +namespace SimpleStateMachine.StructuralSearch; + +public readonly record struct FindParserMatch(Match Match, IReadOnlyDictionary Placeholders); \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/IFindParser.cs b/src/SimpleStateMachine.StructuralSearch/IFindParser.cs index 3b4b90a..04ce8a2 100644 --- a/src/SimpleStateMachine.StructuralSearch/IFindParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/IFindParser.cs @@ -7,6 +7,6 @@ namespace SimpleStateMachine.StructuralSearch { public interface IFindParser { - string Parse(ref IParsingContext context, IInput input); + IEnumerable Parse(ref IParsingContext context); } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/IInput.cs b/src/SimpleStateMachine.StructuralSearch/IInput.cs index fbb012f..852da05 100644 --- a/src/SimpleStateMachine.StructuralSearch/IInput.cs +++ b/src/SimpleStateMachine.StructuralSearch/IInput.cs @@ -4,7 +4,7 @@ namespace SimpleStateMachine.StructuralSearch { public interface IInput { - Result Parse(Parser parser); + Result ParseBy(Parser parser); string Extension { get; } string Path { get; } diff --git a/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs b/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs index f71dc4f..0760575 100644 --- a/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs +++ b/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs @@ -1,4 +1,6 @@ -namespace SimpleStateMachine.StructuralSearch +using System.Collections.Generic; + +namespace SimpleStateMachine.StructuralSearch { public interface IParsingContext { @@ -9,5 +11,7 @@ public interface IParsingContext void AddPlaceholder(Placeholder placeholder); Placeholder GetPlaceholder(string name); + + IReadOnlyDictionary Switch(); } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Parsers/LookaheadParser.cs b/src/SimpleStateMachine.StructuralSearch/Parsers/LookaheadParser.cs index de0854d..14df294 100644 --- a/src/SimpleStateMachine.StructuralSearch/Parsers/LookaheadParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/Parsers/LookaheadParser.cs @@ -7,7 +7,10 @@ internal sealed class LookaheadParser : Parser { private readonly Parser _parser; - public LookaheadParser(Parser parser) => this._parser = parser; + public LookaheadParser(Parser parser) + { + this._parser = parser; + } public override bool TryParse(ref ParseState state, ref PooledList> expecteds, out T result) { diff --git a/src/SimpleStateMachine.StructuralSearch/Parsers/ParserWithLookahead.cs b/src/SimpleStateMachine.StructuralSearch/Parsers/ParserWithLookahead.cs index 7c67a9b..df34438 100644 --- a/src/SimpleStateMachine.StructuralSearch/Parsers/ParserWithLookahead.cs +++ b/src/SimpleStateMachine.StructuralSearch/Parsers/ParserWithLookahead.cs @@ -17,7 +17,6 @@ public abstract Parser BuildParser(Func?> next, public void Lookahead(Func?> next, Func?> nextNext) { - // lazy initialization parser = new Lazy>(() => BuildParser(next, nextNext)); } diff --git a/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs b/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs index 8bd3e55..f9ce818 100644 --- a/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs @@ -20,7 +20,10 @@ public override Parser BuildParser(Func?> nex Func?> nextNext) { var _next = next(); - var _nextNext = nextNext() ?? Parser.OneOf(Parser.Any.AsString(), Parser.End.ThenReturn(string.Empty)); + var _nextNext = nextNext() ?? Parser.End.ThenReturn(string.Empty); + + // Parser.OneOf(Parser.End.ThenReturn(string.Empty), Parser.Any.ThenReturn(string.Empty)); + var lookahead = Parsers.Lookahead(_next.Then(_nextNext, (s1, s2) => { OnLookahead = () => new List> diff --git a/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs b/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs index 62b416b..12dd791 100644 --- a/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs +++ b/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; namespace SimpleStateMachine.StructuralSearch { @@ -8,7 +9,7 @@ public ParsingContext(IInput input) { Input = input; } - public Dictionary Placeholders { get; } = new(); + public readonly Dictionary Placeholders = new(); public IInput Input { get; } @@ -26,5 +27,14 @@ public Placeholder GetPlaceholder(string name) { return Placeholders[name]; } + + public IReadOnlyDictionary Switch() + { + var placeholders = Placeholders + .OrderBy(x=> x.Value.Offset.Start) + .ToDictionary(x=> x.Key, x=> x.Value); + Placeholders.Clear(); + return placeholders; + } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Placeholder/MatchPosition.cs b/src/SimpleStateMachine.StructuralSearch/Placeholder/MatchPosition.cs index 4e02ece..d80ed3a 100644 --- a/src/SimpleStateMachine.StructuralSearch/Placeholder/MatchPosition.cs +++ b/src/SimpleStateMachine.StructuralSearch/Placeholder/MatchPosition.cs @@ -3,11 +3,8 @@ namespace SimpleStateMachine.StructuralSearch { public readonly record struct Match(T Value, int Lenght, ColumnPosition Column, LinePosition Line, - OffsetPosition Offset) - { - - } - + OffsetPosition Offset); + public static class Match { public static readonly Match EmptyMatchString = new( diff --git a/src/SimpleStateMachine.StructuralSearch/StringInput.cs b/src/SimpleStateMachine.StructuralSearch/StringInput.cs index ea8c245..c7c437b 100644 --- a/src/SimpleStateMachine.StructuralSearch/StringInput.cs +++ b/src/SimpleStateMachine.StructuralSearch/StringInput.cs @@ -11,7 +11,7 @@ public StringInput(string input) public readonly string Input; - public Result Parse(Parser parser) + public Result ParseBy(Parser parser) { return parser.Parse(Input); } diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs index 54a772a..e64bb6b 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs @@ -38,7 +38,7 @@ public StructuralSearchParser(Configuration configuration) public void Parse(ref IParsingContext context) { - var result = FindParser.Parse(ref context, context.Input); + var result = FindParser.Parse(ref context); } public void Replace(ref IParsingContext context) From bff4e31f3eecb7278c373af227805134cce051a7 Mon Sep 17 00:00:00 2001 From: GMIKE Date: Sun, 8 May 2022 15:39:43 +0300 Subject: [PATCH 06/11] Some for StructuralSearchParser --- .../Program.cs | 19 +++++++ .../Mock/EmptyParsingContext.cs | 12 ++++- .../PlaceholderParserTests.cs | 3 +- .../StructurSearchParserTests.cs | 13 +++-- .../Configurations/Configuration.cs | 8 +-- .../Custom/StreamReplacer.cs | 53 +++++++++++++++++++ .../EmptyInput.cs | 5 ++ .../Extensions/StringExtensions.cs | 12 +++++ .../FileInput.cs | 19 +++++-- .../FindParser.cs | 4 +- .../Helper/StreamExtensions.cs | 46 ++++++++++++++++ .../Helper/TextReaderExtensions.cs | 46 ++++++++++++++++ .../IInput.cs | 1 + .../IParsingContext.cs | 4 +- .../Parsers/PlaceholderParser.cs | 38 +++++++++---- .../ParsingContext.cs | 19 ++++++- .../Rules/FindRule/FindRule.cs | 8 ++- .../StringInput.cs | 5 ++ .../StructuralSearchParser.cs | 26 +++++++-- 19 files changed, 307 insertions(+), 34 deletions(-) create mode 100644 src/SimpleStateMachine.StructuralSearch/Custom/StreamReplacer.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/Extensions/StringExtensions.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/Helper/StreamExtensions.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/Helper/TextReaderExtensions.cs diff --git a/src/SimpleStateMachine.StructuralSearch.Sandbox/Program.cs b/src/SimpleStateMachine.StructuralSearch.Sandbox/Program.cs index aa83d93..f291002 100644 --- a/src/SimpleStateMachine.StructuralSearch.Sandbox/Program.cs +++ b/src/SimpleStateMachine.StructuralSearch.Sandbox/Program.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using Pidgin; @@ -20,6 +21,24 @@ internal static class Program { static void Main(string[] args) { + + var source = "test;;;test;;;."; + var parser = Parser.OneOf(Parser.Any.ThenReturn(Unit.Value), Parser.End); + + + var t = Parser.Any.AtLeastOnceAsStringUntil(Lookahead(String(";").Then(Not(String(";"))).Try())).ParseOrThrow(source); + + + var path = "Test.txt"; + var oldText = "0123456789"; + var text = "test"; + File.WriteAllText(path, oldText); + + using var stringReader = text.AsStream(); + using var streamWriter = File.OpenWrite(path); + + stringReader.CopyPartTo(streamWriter, 0, 7); + // var config = YmlHelper.Parse( // @"C:\Users\roman\GitHub\SimpleStateMachine.StructuralSearch\src\SimpleStateMachine.StructuralSearch.Tests\ConfigurationFile\FullConfig.yml"); // diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs b/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs index 282c5c0..2077175 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/Mock/EmptyParsingContext.cs @@ -21,7 +21,17 @@ public Placeholder GetPlaceholder(string name) return Placeholder.CreateEmpty(this, name, string.Empty); } - public IReadOnlyDictionary Switch() + public IReadOnlyDictionary SwitchOnNew() + { + throw new System.NotImplementedException(); + } + + public void Set(IReadOnlyDictionary placeholders) + { + throw new System.NotImplementedException(); + } + + public void Clear() { throw new System.NotImplementedException(); } diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs index 52fcad6..1ce567c 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/PlaceholderParserTests.cs @@ -35,9 +35,8 @@ public void TemplateParsingShouldBeSuccess(string template, string source, strin } [Theory] - [InlineData("$var$;", "test;;;", "test;;")] + [InlineData("$var$;", "test;;", "test")] [InlineData("$var$;.", "test;;;.", "test;;")] - [InlineData("$var$;$var2$;", "test;;;test;;;", "test",";;test;;")] public void TemplateParsingShouldBeSuccess2(string template, string source, params string[] values) { var input = Input.String(source); diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs index 1bce6f0..c029380 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs @@ -1,4 +1,5 @@ using System.IO; +using System.Linq; using SimpleStateMachine.StructuralSearch.Tests.Mock; using Xunit; @@ -9,8 +10,8 @@ public class StructuralSearchParserTests [Theory] // [InlineData("AssignmentNullUnionOperator")] // [InlineData("NullUnionOperator")] - [InlineData("TernaryOperator", "Examples/TernaryOperator.cs")] - public static void StructuralSearchShouldBeSuccess(string exampleName, string exampleFilePath) + [InlineData("TernaryOperator", "Examples/TernaryOperator.cs", 3)] + public static void StructuralSearchShouldBeSuccess(string exampleName, string exampleFilePath, int matchesCount) { var config = ConfigurationMock.GetConfigurationFromFiles(exampleName); var parser = new StructuralSearchParser(config); @@ -19,7 +20,13 @@ public static void StructuralSearchShouldBeSuccess(string exampleName, string ex var input = Input.File(fileInfo); IParsingContext context = new ParsingContext(input); - parser.Parse(ref context); + var matches = parser.Parse(ref context); + Assert.Equal(matches.Count(), matchesCount); + // foreach (var match in matches) + // { + // input.Replace(match.Match); + // } + } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Configurations/Configuration.cs b/src/SimpleStateMachine.StructuralSearch/Configurations/Configuration.cs index 6dba871..4cdf031 100644 --- a/src/SimpleStateMachine.StructuralSearch/Configurations/Configuration.cs +++ b/src/SimpleStateMachine.StructuralSearch/Configurations/Configuration.cs @@ -7,13 +7,13 @@ namespace SimpleStateMachine.StructuralSearch.Configurations { public class Configuration : IEquatable { - public string FindTemplate { get; set; } + public string FindTemplate { get; init; } - public List? FindRules { get; set; } + public List? FindRules { get; init; } - public string ReplaceTemplate { get; set; } + public string ReplaceTemplate { get; init; } - public List? ReplaceRules { get; set; } + public List? ReplaceRules { get; init; } public bool Equals(Configuration? other) { diff --git a/src/SimpleStateMachine.StructuralSearch/Custom/StreamReplacer.cs b/src/SimpleStateMachine.StructuralSearch/Custom/StreamReplacer.cs new file mode 100644 index 0000000..474e309 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Custom/StreamReplacer.cs @@ -0,0 +1,53 @@ +using System.IO; +using System.Threading.Tasks; + +namespace SimpleStateMachine.StructuralSearch.Custom; + +// public class StreamReplacer : Stream +// { +// +// private readonly Stream _baseStream; +// +// public StreamReplacer(Stream baseStream) +// { +// _baseStream = baseStream; +// } +// +// public Task Replace(Stream stream, int fromStart, int fromEnd, int toStart, int toEnd) +// { +// stream.SetLength(); +// stream.Position = fromStart; +// stream. +// } +// +// public override void Flush() +// { +// throw new System.NotImplementedException(); +// } +// +// public override int Read(byte[] buffer, int offset, int count) +// { +// throw new System.NotImplementedException(); +// } +// +// public override long Seek(long offset, SeekOrigin origin) +// { +// throw new System.NotImplementedException(); +// } +// +// public override void SetLength(long value) +// { +// throw new System.NotImplementedException(); +// } +// +// public override void Write(byte[] buffer, int offset, int count) +// { +// throw new System.NotImplementedException(); +// } +// +// public override bool CanRead { get; } +// public override bool CanSeek { get; } +// public override bool CanWrite { get; } +// public override long Length { get; } +// public override long Position { get; set; } +// } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs b/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs index ff366dd..1649fb4 100644 --- a/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs +++ b/src/SimpleStateMachine.StructuralSearch/EmptyInput.cs @@ -9,6 +9,11 @@ public Result ParseBy(Parser parser) throw new System.NotImplementedException(); } + public void Replace(Match match, string value) + { + throw new System.NotImplementedException(); + } + public string Extension => string.Empty; public string Path => string.Empty; public string Name => string.Empty; diff --git a/src/SimpleStateMachine.StructuralSearch/Extensions/StringExtensions.cs b/src/SimpleStateMachine.StructuralSearch/Extensions/StringExtensions.cs new file mode 100644 index 0000000..0fcdc92 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Extensions/StringExtensions.cs @@ -0,0 +1,12 @@ +using System.IO; +using System.Text; + +namespace SimpleStateMachine.StructuralSearch.Extensions; + +public static class StringExtensions +{ + public static MemoryStream AsStream(this string str) + { + return new MemoryStream(Encoding.UTF8.GetBytes(str)); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/FileInput.cs b/src/SimpleStateMachine.StructuralSearch/FileInput.cs index 1c46fbe..d6d66c7 100644 --- a/src/SimpleStateMachine.StructuralSearch/FileInput.cs +++ b/src/SimpleStateMachine.StructuralSearch/FileInput.cs @@ -1,22 +1,35 @@ using System.IO; +using System.Threading; using Pidgin; +using SimpleStateMachine.StructuralSearch.Helper; namespace SimpleStateMachine.StructuralSearch { public class FileInput : IInput { + public readonly FileInfo FileInfo; + public FileInput(FileInfo fileInfo) { FileInfo = fileInfo; } - - public readonly FileInfo FileInfo; - + public Result ParseBy(Parser parser) { return parser.Parse(FileInfo.OpenText()); } + public void Replace(Match match, string value) + { + using var valueReader = new StringReader(value); + using var streamWriter = new StreamWriter(FileInfo.FullName); + var emptyStart = match.Offset.Start + match.Lenght; + var emptyEnd = match.Offset.End; + valueReader.CopyPartTo(streamWriter, match.Offset.Start, match.Lenght); + + //return (emptyStart, emptyEnd); + } + public string Extension => FileInfo.Extension; public string Path => System.IO.Path.GetFullPath(FileInfo.FullName); public string Name => System.IO.Path.GetFileNameWithoutExtension(FileInfo.Name); diff --git a/src/SimpleStateMachine.StructuralSearch/FindParser.cs b/src/SimpleStateMachine.StructuralSearch/FindParser.cs index e07aafc..106aa6a 100644 --- a/src/SimpleStateMachine.StructuralSearch/FindParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/FindParser.cs @@ -28,7 +28,7 @@ public IEnumerable Parse(ref IParsingContext context) .Match() .ThenInvoke(match => { - var placeholders= parsingContext.Switch(); + var placeholders= parsingContext.SwitchOnNew(); matches.Add(new FindParserMatch(match, placeholders)); }) .ThenReturn(Unit.Value) @@ -38,7 +38,7 @@ public IEnumerable Parse(ref IParsingContext context) .ThenInvoke(x => { res.Append(x); - parsingContext.Switch(); + parsingContext.SwitchOnNew(); }) .ThenReturn(Unit.Value); diff --git a/src/SimpleStateMachine.StructuralSearch/Helper/StreamExtensions.cs b/src/SimpleStateMachine.StructuralSearch/Helper/StreamExtensions.cs new file mode 100644 index 0000000..4d9015b --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Helper/StreamExtensions.cs @@ -0,0 +1,46 @@ +using System; +using System.Diagnostics.Contracts; +using System.IO; + +namespace SimpleStateMachine.StructuralSearch.Helper; + +public static class StreamExtensions + { + /// + /// Copies a specific number of bytes from the current position of the + /// source stream to the current position of the destination stream. + /// + /// The source stream. + /// The destination stream. + /// The number of bytes to copy. + /// The size of the buffer to use. + /// The default is 4096. + public static void CopyPartTo(this Stream source, Stream destination, int offset, int count, int bufferSize) + { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (destination == null) throw new ArgumentNullException(nameof(destination)); + + byte[] buffer = new byte[bufferSize]; + int read; + while (count > 0 && (read = source.Read(buffer, 0, Math.Min(buffer.Length, count))) > 0) + { + count -= read; + destination.Write(buffer, offset, read); + } + } + + /// + /// Copies a specific number of bytes from the current position of the + /// source stream to the current position of the destination stream. + /// + /// The source stream. + /// The destination stream. + /// The number of bytes to copy. + public static void CopyPartTo(this Stream source, Stream destination, int offset, int count) + { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (destination == null) throw new ArgumentNullException(nameof(destination)); + + CopyPartTo(source, destination, offset, count, 0x1000); + } + } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Helper/TextReaderExtensions.cs b/src/SimpleStateMachine.StructuralSearch/Helper/TextReaderExtensions.cs new file mode 100644 index 0000000..2577172 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Helper/TextReaderExtensions.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; + +namespace SimpleStateMachine.StructuralSearch.Helper; + +public static class TextReaderExtensions +{ + /// + /// Copies a specific number of bytes from the current position of the + /// source stream to the current position of the destination stream. + /// + /// The source stream. + /// The destination stream. + /// The number of bytes to copy. + /// The size of the buffer to use. + /// The default is 4096. + public static void CopyPartTo(this TextReader source, TextWriter destination, int offset, int count, int bufferSize) + { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (destination == null) throw new ArgumentNullException(nameof(destination)); + + char[] buffer = new char[bufferSize]; + int read; + + while (count > 0 && (read = source.ReadBlock(buffer)) > 0) + { + count -= read; + destination.Write(buffer, offset, read); + } + } + + /// + /// Copies a specific number of bytes from the current position of the + /// source stream to the current position of the destination stream. + /// + /// The source stream. + /// The destination stream. + /// The number of bytes to copy. + public static void CopyPartTo(this TextReader source, TextWriter destination, int offset, int count) + { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (destination == null) throw new ArgumentNullException(nameof(destination)); + + CopyPartTo(source, destination, offset, count, 4096); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/IInput.cs b/src/SimpleStateMachine.StructuralSearch/IInput.cs index 852da05..7350a93 100644 --- a/src/SimpleStateMachine.StructuralSearch/IInput.cs +++ b/src/SimpleStateMachine.StructuralSearch/IInput.cs @@ -5,6 +5,7 @@ namespace SimpleStateMachine.StructuralSearch public interface IInput { Result ParseBy(Parser parser); + void Replace(Match match, string value); string Extension { get; } string Path { get; } diff --git a/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs b/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs index 0760575..7cce05c 100644 --- a/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs +++ b/src/SimpleStateMachine.StructuralSearch/IParsingContext.cs @@ -12,6 +12,8 @@ public interface IParsingContext Placeholder GetPlaceholder(string name); - IReadOnlyDictionary Switch(); + IReadOnlyDictionary SwitchOnNew(); + void Set(IReadOnlyDictionaryplaceholders); + void Clear(); } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs b/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs index f9ce818..2d29dc9 100644 --- a/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/Parsers/PlaceholderParser.cs @@ -20,19 +20,35 @@ public override Parser BuildParser(Func?> nex Func?> nextNext) { var _next = next(); - var _nextNext = nextNext() ?? Parser.End.ThenReturn(string.Empty); - - // Parser.OneOf(Parser.End.ThenReturn(string.Empty), Parser.Any.ThenReturn(string.Empty)); + var _nextNext = nextNext(); + // ?? Parser.OneOf(Parser.End.ThenReturn(string.Empty), Parser.Any.ThenReturn(string.Empty)); + // Parser.End.ThenReturn(string.Empty) - var lookahead = Parsers.Lookahead(_next.Then(_nextNext, (s1, s2) => + Parser lookahead; + if (_nextNext is not null) { - OnLookahead = () => new List> + lookahead = Parsers.Lookahead(_next.Then(_nextNext, (s1, s2) => { - new(_next, s1, s1.Length), - new(_nextNext, s2, s2.Length), - }; - return Unit.Value; - }).Try()); + OnLookahead = () => new List> + { + new(_next, s1, s1.Length), + new(_nextNext, s2, s2.Length), + }; + return Unit.Value; + }).Try()); + } + else + { + lookahead = Parsers.Lookahead(_next.Select(s => + { + OnLookahead = () => new List> + { + new(_next, s, s.Length) + }; + return Unit.Value; + }).Try()); + } + var anyString = CommonTemplateParser.AnyCharWithPlshd .AtLeastOnceAsStringUntil(lookahead); @@ -49,7 +65,7 @@ public override Parser BuildParser(Func?> nex //parenthesised and tokens and whiteSpaces var prdsAndTokens = Parser.OneOf(parenthesised, token) - .Until(lookahead) + .AtLeastOnceUntil(lookahead) .JoinToString() .Try(); diff --git a/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs b/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs index 12dd791..7ed89af 100644 --- a/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs +++ b/src/SimpleStateMachine.StructuralSearch/ParsingContext.cs @@ -28,13 +28,28 @@ public Placeholder GetPlaceholder(string name) return Placeholders[name]; } - public IReadOnlyDictionary Switch() + public IReadOnlyDictionary SwitchOnNew() { var placeholders = Placeholders .OrderBy(x=> x.Value.Offset.Start) .ToDictionary(x=> x.Key, x=> x.Value); - Placeholders.Clear(); + Clear(); return placeholders; } + + public void Set(IReadOnlyDictionary placeholders) + { + Clear(); + + foreach (var placeholder in placeholders) + { + Placeholders.Add(placeholder.Key, placeholder.Value); + } + } + + public void Clear() + { + Placeholders.Clear(); + } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/FindRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/FindRule.cs index 1760b14..5e884d1 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/FindRule.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/FindRule.cs @@ -15,6 +15,12 @@ public FindRule(PlaceholderParameter placeholder, IRule rule) public override string ToString() { return $"{Placeholder}{Constant.Space}{_rule}"; - } + } + + public bool Execute() + { + var value = Placeholder.GetValue(); + return _rule.Execute(value); + } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/StringInput.cs b/src/SimpleStateMachine.StructuralSearch/StringInput.cs index c7c437b..7f30966 100644 --- a/src/SimpleStateMachine.StructuralSearch/StringInput.cs +++ b/src/SimpleStateMachine.StructuralSearch/StringInput.cs @@ -16,6 +16,11 @@ public Result ParseBy(Parser parser) return parser.Parse(Input); } + public void Replace(Match match, string value) + { + throw new System.NotImplementedException(); + } + public string Extension => string.Empty; public string Path => string.Empty; public string Name => string.Empty; diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs index e64bb6b..c7eb5f5 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs @@ -36,15 +36,33 @@ public StructuralSearchParser(Configuration configuration) .ToDictionary(x => x.FindRule.Placeholder.Name, x => x); } - public void Parse(ref IParsingContext context) + public IEnumerable Parse(ref IParsingContext context) { - var result = FindParser.Parse(ref context); + var matches = FindParser.Parse(ref context); + var result = new List(); + + foreach (var match in matches) + { + context.Set(match.Placeholders); + if (AllRulesCompleted(ref context)) + { + result.Add(match); + } + } + + return result; } - public void Replace(ref IParsingContext context) + public void Replace(FindParserMatch context) { - ReplaceBuilder.Build(context); + //ReplaceBuilder.Build(context); + // context. //FindParser.Parse(context, context.File.Data); } + + public bool AllRulesCompleted(ref IParsingContext context) + { + return FindRules.Values.All(x => x.Execute()); + } } } \ No newline at end of file From a9670f9da8240862ddc6fb3c128674c0d2e31d15 Mon Sep 17 00:00:00 2001 From: GMIKE Date: Sun, 8 May 2022 17:39:25 +0300 Subject: [PATCH 07/11] some before check --- .../Examples/NullUnionOperator.cs | 51 ++++++++++++ .../FindRuleParserTests.cs | 4 +- .../ReplaceRule/NullUnionOperator.txt | 1 + ...StateMachine.StructuralSearch.Tests.csproj | 4 - .../StructurSearchParserTests.cs | 5 -- .../Rules/FindRule/ILogicalRule.cs | 6 ++ .../FindRule/LogicalRule/BinaryLogicalRule.cs | 32 ++++++++ .../PlaceholderLogicalRule.cs} | 6 +- .../FindRule/LogicalRule/UnaryLogicalRule.cs | 32 ++++++++ .../Rules/ReplaceRule/ReplaceRule.cs | 4 +- .../StructuralSearch/FindRulesParser.cs | 14 ++-- .../StructuralSearch/LogicalRuleParser.cs | 81 +++++++++++++++++++ .../StructuralSearch/ReplaceRuleParser.cs | 2 +- .../StructuralSearch/StructuralSearch.cs | 4 +- .../StructuralSearchParser.cs | 2 +- 15 files changed, 219 insertions(+), 29 deletions(-) create mode 100644 src/SimpleStateMachine.StructuralSearch.Tests/Examples/NullUnionOperator.cs create mode 100644 src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRule/NullUnionOperator.txt create mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/FindRule/ILogicalRule.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/BinaryLogicalRule.cs rename src/SimpleStateMachine.StructuralSearch/Rules/FindRule/{FindRule.cs => LogicalRule/PlaceholderLogicalRule.cs} (78%) create mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/UnaryLogicalRule.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/StructuralSearch/LogicalRuleParser.cs diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/Examples/NullUnionOperator.cs b/src/SimpleStateMachine.StructuralSearch.Tests/Examples/NullUnionOperator.cs new file mode 100644 index 0000000..69c874e --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch.Tests/Examples/NullUnionOperator.cs @@ -0,0 +1,51 @@ +namespace SimpleStateMachine.StructuralSearch.Tests.Examples; + +public class NullUnionOperator +{ + public int Test1() + { + int? temp = 1; + + if(temp is null) + return 3; + else + return 4; + } + + public int Test2() + { + int? temp = 5; + + if(temp is null) + return 7; + else + return 8; + } + + public int Test3() + { + int? temp2 = 1; + + if(temp2 is null) + return 3; + else + return 4; + } + + public int Test4() + { + int? temp3 = 5; + + if(temp3 is null) + return 7; + else if (temp3 == 8) + return 9; + else + return 10; + } + + public void Test5() + { + + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/FindRuleParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/FindRuleParserTests.cs index 8c98cfc..9dda22b 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/FindRuleParserTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/FindRuleParserTests.cs @@ -28,7 +28,7 @@ public class FindRuleParserTests public void FindRuleExprParsingShouldBeSuccess(string ruleStr) { - var rule = FindRuleParser.Expr.ParseOrThrow(ruleStr); + var rule = RuleParser.Expr.ParseOrThrow(ruleStr); var _ruleStr = rule.ToString()?.ToLower(); Assert.NotNull(rule); Assert.Equal(_ruleStr, ruleStr.ToLower()); @@ -39,7 +39,7 @@ public void FindRuleExprParsingShouldBeSuccess(string ruleStr) [InlineData("In (\"Is\", \"==\", \"!=\", \"is not\")", "In \"Is\",\"==\",\"!=\",\"is not\"")] public void FindRuleExprParsingShouldBeEqualsCustomResult(string ruleStr, string customResult) { - var rule = FindRuleParser.Expr.ParseOrThrow(ruleStr); + var rule = RuleParser.Expr.ParseOrThrow(ruleStr); var _ruleStr = rule.ToString()?.ToLower(); Assert.NotNull(rule); Assert.Equal(_ruleStr, customResult.ToLower()); diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRule/NullUnionOperator.txt b/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRule/NullUnionOperator.txt new file mode 100644 index 0000000..7dc05eb --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRule/NullUnionOperator.txt @@ -0,0 +1 @@ +$sign$ Is ("Is", "==", "!=", "is not") \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj b/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj index abbde51..667de2e 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj +++ b/src/SimpleStateMachine.StructuralSearch.Tests/SimpleStateMachine.StructuralSearch.Tests.csproj @@ -50,9 +50,5 @@ Always - - - - diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs index c029380..6d07eb8 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs @@ -22,11 +22,6 @@ public static void StructuralSearchShouldBeSuccess(string exampleName, string ex var matches = parser.Parse(ref context); Assert.Equal(matches.Count(), matchesCount); - // foreach (var match in matches) - // { - // input.Replace(match.Match); - // } - } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/ILogicalRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/ILogicalRule.cs new file mode 100644 index 0000000..fc95673 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/ILogicalRule.cs @@ -0,0 +1,6 @@ +namespace SimpleStateMachine.StructuralSearch.Rules; + +public interface ILogicalRule +{ + bool Execute(); +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/BinaryLogicalRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/BinaryLogicalRule.cs new file mode 100644 index 0000000..1d8afe2 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/BinaryLogicalRule.cs @@ -0,0 +1,32 @@ +using SimpleStateMachine.StructuralSearch.Helper; + +namespace SimpleStateMachine.StructuralSearch.Rules; + +public class BinaryLogicalRule : ILogicalRule +{ + public BinaryRuleType Type { get; } + + public ILogicalRule Left { get; } + + public ILogicalRule Right { get; } + + public BinaryLogicalRule(BinaryRuleType type, ILogicalRule left, ILogicalRule right) + { + Type = type; + Left = left; + Right = right; + } + + public bool Execute() + { + var left = Left.Execute(); + var right = Right.Execute(); + + return LogicalHelper.Calculate(Type, left, right); + } + + public override string ToString() + { + return $"{Left}{Constant.Space}{Type}{Constant.Space}{Right}"; + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/FindRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/PlaceholderLogicalRule.cs similarity index 78% rename from src/SimpleStateMachine.StructuralSearch/Rules/FindRule/FindRule.cs rename to src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/PlaceholderLogicalRule.cs index 5e884d1..4c8a59b 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/FindRule.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/PlaceholderLogicalRule.cs @@ -1,12 +1,12 @@ namespace SimpleStateMachine.StructuralSearch.Rules { - public class FindRule + public class PlaceholderLogicalRule : ILogicalRule { public PlaceholderParameter Placeholder { get; } private IRule _rule { get; } - public FindRule(PlaceholderParameter placeholder, IRule rule) + public PlaceholderLogicalRule(PlaceholderParameter placeholder, IRule rule) { Placeholder = placeholder; _rule = rule; @@ -16,7 +16,7 @@ public override string ToString() { return $"{Placeholder}{Constant.Space}{_rule}"; } - + public bool Execute() { var value = Placeholder.GetValue(); diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/UnaryLogicalRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/UnaryLogicalRule.cs new file mode 100644 index 0000000..b28c41d --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/UnaryLogicalRule.cs @@ -0,0 +1,32 @@ +using System; + +namespace SimpleStateMachine.StructuralSearch.Rules; + +public class UnaryLogicalRule : ILogicalRule +{ + public UnaryRuleType Type { get; } + + public ILogicalRule Parameter { get; } + + public UnaryLogicalRule(UnaryRuleType type, ILogicalRule parameter) + { + Type = type; + Parameter = parameter; + } + + public bool Execute() + { + var result = Parameter.Execute(); + + return Type switch + { + UnaryRuleType.Not => !result, + _ => throw new ArgumentOutOfRangeException() + }; + } + + public override string ToString() + { + return $"{Type}{Constant.Space}{Parameter}"; + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs index ee49fbe..18c380f 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs @@ -6,11 +6,11 @@ namespace SimpleStateMachine.StructuralSearch { public class ReplaceRule { - public FindRule FindRule { get; } + public PlaceholderLogicalRule FindRule { get; } public IRuleParameter Parameter { get; } - public ReplaceRule(FindRule findRule, IRuleParameter parameter) + public ReplaceRule(PlaceholderLogicalRule findRule, IRuleParameter parameter) { FindRule = findRule; Parameter = parameter; diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindRulesParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindRulesParser.cs index 7d6b8af..9002978 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindRulesParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindRulesParser.cs @@ -7,7 +7,7 @@ namespace SimpleStateMachine.StructuralSearch { - public static class FindRuleParser + public static class RuleParser { internal static Parser> Binary(Parser op) => op.Select>(type => (l, r) => new BinaryRule(type, l, r)); @@ -71,14 +71,10 @@ internal static readonly Parser> Not ) ); - internal static readonly Parser Rule = - Parser.Map((parameter, rule) => new FindRule(parameter, rule), + internal static readonly Parser PlaceholderLogicalRule = + Parser.Map((parameter, rule) => new PlaceholderLogicalRule(parameter, rule), ParametersParser.PlaceholderParameter, - Expr.TrimStart()); - - internal static FindRule ParseTemplate(string str) - { - return Rule.ParseOrThrow(str); - } + Expr.TrimStart()) + .As(); } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/LogicalRuleParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/LogicalRuleParser.cs new file mode 100644 index 0000000..94a5e7f --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/LogicalRuleParser.cs @@ -0,0 +1,81 @@ +using System; +using Pidgin; +using Pidgin.Expression; +using SimpleStateMachine.StructuralSearch.Extensions; +using SimpleStateMachine.StructuralSearch.Rules; + +namespace SimpleStateMachine.StructuralSearch; + +public static class LogicalRuleParser +{ + internal static Parser> BinaryLogical(Parser op) + => op.Select>(type => (l, r) => new BinaryLogicalRule(type, l, r)); + + internal static Parser> UnaryLogical(Parser op) + => op.Select>(type => param => new UnaryLogicalRule(type, param)); + + internal static readonly Parser> And + = BinaryLogical(Parsers.EnumValue(BinaryRuleType.And, true) + .TrimStart() + .Try()); + + internal static readonly Parser> Or + = BinaryLogical(Parsers.EnumValue(BinaryRuleType.Or, true) + .TrimStart() + .Try()); + + internal static readonly Parser> NOR + = BinaryLogical(Parsers.EnumValue(BinaryRuleType.NOR, true) + .TrimStart() + .Try()); + + internal static readonly Parser> XOR + = BinaryLogical(Parsers.EnumValue(BinaryRuleType.XOR, true) + .TrimStart() + .Try()); + + internal static readonly Parser> NAND + = BinaryLogical(Parsers.EnumValue(BinaryRuleType.NAND, true) + .TrimStart() + .Try()); + + internal static readonly Parser> XNOR + = BinaryLogical(Parsers.EnumValue(BinaryRuleType.XNOR, true) + .TrimStart() + .Try()); + + internal static readonly Parser> Not + = UnaryLogical(Parsers.EnumValue(UnaryRuleType.Not, true) + .TrimStart() + .Try()); + + public static readonly Parser Expr = ExpressionParser.Build( + rule => ( + Parser.OneOf( + RuleParser.PlaceholderLogicalRule, + CommonParser.Parenthesised(rule, x => x.TrimStart()) + ), + new[] + { + Operator.Prefix(Not), + Operator.InfixL(And), + Operator.InfixL(NOR), + Operator.InfixL(XOR), + Operator.InfixL(NAND), + Operator.InfixL(XNOR), + Operator.InfixL(Or), + } + ) + ); + + internal static readonly Parser Rule = + Parser.Map((parameter, rule) => new PlaceholderLogicalRule(parameter, rule), + ParametersParser.PlaceholderParameter, + Expr.TrimStart()) + .As(); + + internal static ILogicalRule ParseTemplate(string str) + { + return Rule.ParseOrThrow(str); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs index 2292245..eef6f61 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs @@ -16,7 +16,7 @@ public static class ReplaceRuleParser internal static readonly Parser ReplaceRule = Parser.Map((rule, parameter) => new ReplaceRule(rule, parameter), - FindRuleParser.Rule.Before(CommonTemplateParser.Should.TrimStart()), + RuleParser.PlaceholderLogicalRule.Before(CommonTemplateParser.Should.TrimStart()), Parser.OneOf(ChangeParameter.Try(), ParametersParser.Parameter.Try())) .Try() .TrimStart(); diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/StructuralSearch.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/StructuralSearch.cs index 3e2acd7..34d8017 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/StructuralSearch.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/StructuralSearch.cs @@ -12,8 +12,8 @@ public static IFindParser ParseFindTemplate(string template) public static IReplaceBuilder ParseReplaceTemplate(string template) => ReplaceTemplateParser.ParseTemplate(template); - public static FindRule ParseFindRule(string template) - => FindRuleParser.ParseTemplate(template); + public static PlaceholderLogicalRule ParseFindRule(string template) + => RuleParser.ParseTemplate(template); public static ReplaceRule ParseReplaceRule(string template) => ReplaceRuleParser.ParseTemplate(template); diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs index c7eb5f5..17f417c 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs @@ -13,7 +13,7 @@ public class StructuralSearchParser { public IFindParser FindParser { get; set; } - public Dictionary FindRules { get; set; } + public Dictionary FindRules { get; set; } public IReplaceBuilder ReplaceBuilder { get; set; } From e9304f61e74606a8abce8a2e68b62c2182e885b0 Mon Sep 17 00:00:00 2001 From: GMIKE Date: Sun, 8 May 2022 19:46:15 +0300 Subject: [PATCH 08/11] new find rules --- .../FindRuleParserTests.cs | 43 +++++----- .../Rules/FindRule/BinaryRule.cs | 6 +- .../Rules/FindRule/ILogicalRule.cs | 6 -- .../Rules/FindRule/IRule.cs | 2 +- .../Rules/FindRule/InRule.cs | 29 ------- .../Rules/FindRule/InSubRule.cs | 30 +++++++ .../FindRule/{IsRule.cs => IsSubRule.cs} | 20 ++--- .../FindRule/LogicalRule/BinaryLogicalRule.cs | 32 -------- .../LogicalRule/PlaceholderLogicalRule.cs | 26 ------ .../FindRule/LogicalRule/UnaryLogicalRule.cs | 32 -------- .../Rules/FindRule/SubRule.cs | 42 ++++++++++ .../FindRule/{ => Types}/BinaryRuleType.cs | 0 .../FindRule/{ => Types}/LineProperty.cs | 0 .../FindRule/{ => Types}/OffsetProperty.cs | 0 .../FindRule/{ => Types}/PlaceholderType.cs | 0 .../Rules/FindRule/{ => Types}/SubRuleType.cs | 0 .../FindRule/{ => Types}/UnaryRuleType.cs | 0 .../Rules/FindRule/UnaryRule.cs | 4 +- .../Rules/FindRule/UnarySubRule.cs | 38 --------- .../Rules/ReplaceRule/ReplaceRule.cs | 9 ++- .../StructuralSearch/FindRulesParser.cs | 15 ++-- .../StructuralSearch/LogicalRuleParser.cs | 81 ------------------- .../StructuralSearch/ReplaceRuleParser.cs | 2 +- .../StructuralSearch/StructuralSearch.cs | 4 +- .../StructuralSearch/SubFindRuleParser.cs | 40 --------- .../StructuralSearch/SubRuleParser.cs | 45 +++++++++++ .../StructuralSearchParser.cs | 17 ++-- 27 files changed, 181 insertions(+), 342 deletions(-) delete mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/FindRule/ILogicalRule.cs delete mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/FindRule/InRule.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/FindRule/InSubRule.cs rename src/SimpleStateMachine.StructuralSearch/Rules/FindRule/{IsRule.cs => IsSubRule.cs} (59%) delete mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/BinaryLogicalRule.cs delete mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/PlaceholderLogicalRule.cs delete mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/UnaryLogicalRule.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/FindRule/SubRule.cs rename src/SimpleStateMachine.StructuralSearch/Rules/FindRule/{ => Types}/BinaryRuleType.cs (100%) rename src/SimpleStateMachine.StructuralSearch/Rules/FindRule/{ => Types}/LineProperty.cs (100%) rename src/SimpleStateMachine.StructuralSearch/Rules/FindRule/{ => Types}/OffsetProperty.cs (100%) rename src/SimpleStateMachine.StructuralSearch/Rules/FindRule/{ => Types}/PlaceholderType.cs (100%) rename src/SimpleStateMachine.StructuralSearch/Rules/FindRule/{ => Types}/SubRuleType.cs (100%) rename src/SimpleStateMachine.StructuralSearch/Rules/FindRule/{ => Types}/UnaryRuleType.cs (100%) delete mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/FindRule/UnarySubRule.cs delete mode 100644 src/SimpleStateMachine.StructuralSearch/StructuralSearch/LogicalRuleParser.cs delete mode 100644 src/SimpleStateMachine.StructuralSearch/StructuralSearch/SubFindRuleParser.cs create mode 100644 src/SimpleStateMachine.StructuralSearch/StructuralSearch/SubRuleParser.cs diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/FindRuleParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/FindRuleParserTests.cs index 9dda22b..64987c9 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/FindRuleParserTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/FindRuleParserTests.cs @@ -10,36 +10,41 @@ namespace SimpleStateMachine.StructuralSearch.Tests public class FindRuleParserTests { [Theory] - [InlineData("equals $var$")] - [InlineData("equals \"\\$\"")] - [InlineData("Not equals $var$.Lenght")] - [InlineData("Not equals $var$.offset.Start")] - [InlineData("equals $var$.Lenght and Not StartsWith \"123\"")] - [InlineData("equals $var$.Lenght and Not StartsWith \"\\\"Test\"")] - [InlineData("Contains $var$.Lenght")] - [InlineData("Contains \"123\"")] - [InlineData("StartsWith $var$.Lenght")] - [InlineData("StartsWith \"123\"")] - [InlineData("EndsWith $var$.Lenght")] - [InlineData("EndsWith \"123\"")] - [InlineData("Match $var$.Lenght")] - [InlineData("Is Int")] - [InlineData("Is DateTime")] + [InlineData("$var$ equals $var$")] + [InlineData("$var$ equals \"\\$\"")] + [InlineData("Not $var$ equals $var$.Lenght")] + [InlineData("Not $var$ equals $var$.offset.Start")] + [InlineData("$var$ equals $var$.Lenght and Not $var$ StartsWith \"123\"")] + [InlineData("Not $var$ equals $var$.Lenght and $var$ StartsWith \"123\"")] + [InlineData("$var$ equals $var$.Lenght and Not $var$ StartsWith \"\\\"Test\"")] + [InlineData("$var$ Contains $var$.Lenght")] + [InlineData("$var1$.Lenght Contains $var2$.Lenght")] + [InlineData("$var$ Contains \"123\"")] + [InlineData("$var$ StartsWith $var$.Lenght")] + [InlineData("$var$.Lenght Equals $var$.Lenght")] + [InlineData("$var$ StartsWith \"123\"")] + [InlineData("$var$ EndsWith $var$.Lenght")] + [InlineData("$var$ EndsWith \"123\"")] + [InlineData("$var$ Match $var$.Lenght")] + [InlineData("$var$ Is Int")] + [InlineData("$var$ Is DateTime")] public void FindRuleExprParsingShouldBeSuccess(string ruleStr) { - var rule = RuleParser.Expr.ParseOrThrow(ruleStr); + var rule = FindRuleParser.Expr.ParseOrThrow(ruleStr); var _ruleStr = rule.ToString()?.ToLower(); Assert.NotNull(rule); Assert.Equal(_ruleStr, ruleStr.ToLower()); } [Theory] - [InlineData("In \"Is\", \"==\", \"!=\", \"is not\"", "In \"Is\",\"==\",\"!=\",\"is not\"")] - [InlineData("In (\"Is\", \"==\", \"!=\", \"is not\")", "In \"Is\",\"==\",\"!=\",\"is not\"")] + [InlineData("$var$ In \"Is\", \"==\", \"!=\", \"is not\"", "$var$ In \"Is\",\"==\",\"!=\",\"is not\"")] + [InlineData("$var$ In (\"Is\", \"==\", \"!=\", \"is not\")", "$var$ In \"Is\",\"==\",\"!=\",\"is not\"")] + [InlineData("Not ($var$ equals $var$.Lenght and $var$ StartsWith \"123\")", "Not $var$ equals $var$.Lenght and $var$ StartsWith \"123\"")] + [InlineData("Not ($var$ equals $var$.Lenght)", "Not $var$ equals $var$.Lenght")] public void FindRuleExprParsingShouldBeEqualsCustomResult(string ruleStr, string customResult) { - var rule = RuleParser.Expr.ParseOrThrow(ruleStr); + var rule = FindRuleParser.Expr.ParseOrThrow(ruleStr); var _ruleStr = rule.ToString()?.ToLower(); Assert.NotNull(rule); Assert.Equal(_ruleStr, customResult.ToLower()); diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/BinaryRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/BinaryRule.cs index 3003b1a..925df7f 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/BinaryRule.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/BinaryRule.cs @@ -17,10 +17,10 @@ public BinaryRule(BinaryRuleType type, IRule left, IRule right) Right = right; } - public bool Execute(string value) + public bool Execute() { - var left = Left.Execute(value); - var right = Right.Execute(value); + var left = Left.Execute(); + var right = Right.Execute(); return LogicalHelper.Calculate(Type, left, right); } diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/ILogicalRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/ILogicalRule.cs deleted file mode 100644 index fc95673..0000000 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/ILogicalRule.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace SimpleStateMachine.StructuralSearch.Rules; - -public interface ILogicalRule -{ - bool Execute(); -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/IRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/IRule.cs index df0ad49..1ef83c1 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/IRule.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/IRule.cs @@ -2,6 +2,6 @@ { public interface IRule { - bool Execute(string value); + bool Execute(); } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/InRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/InRule.cs deleted file mode 100644 index fb7a8d6..0000000 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/InRule.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace SimpleStateMachine.StructuralSearch.Rules -{ - public class InRule : IRule - { - public SubRuleType Type { get; } - - public IEnumerable Parameters { get; } - - public InRule(SubRuleType type, IEnumerable parameters) - { - Type = type; - - Parameters = parameters; - } - - public bool Execute(string value) - { - return Parameters.Any(parameter => Equals(value, parameter.GetValue())); - } - - public override string ToString() - { - return $"{Type}{Constant.Space}{string.Join(Constant.Comma, Parameters.Select(x=>x.ToString()))}"; - } - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/InSubRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/InSubRule.cs new file mode 100644 index 0000000..1b74255 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/InSubRule.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; +using System.Linq; + +namespace SimpleStateMachine.StructuralSearch.Rules +{ + public class InSubRule : IRule + { + public IRuleParameter Parameter { get; } + + public IEnumerable Arguments { get; } + + public InSubRule(IRuleParameter parameter, IEnumerable arguments) + { + Parameter = parameter; + + Arguments = arguments; + } + + public bool Execute() + { + var value = Parameter.GetValue(); + return Arguments.Any(parameter => Equals(value, parameter.GetValue())); + } + + public override string ToString() + { + return $"{Parameter}{Constant.Space}{SubRuleType.In}{Constant.Space}{string.Join(Constant.Comma, Arguments.Select(x=>x.ToString()))}"; + } + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/IsRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/IsSubRule.cs similarity index 59% rename from src/SimpleStateMachine.StructuralSearch/Rules/FindRule/IsRule.cs rename to src/SimpleStateMachine.StructuralSearch/Rules/FindRule/IsSubRule.cs index f5f3eb1..e076ac1 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/IsRule.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/IsSubRule.cs @@ -3,21 +3,23 @@ namespace SimpleStateMachine.StructuralSearch.Rules { - public class IsRule : IRule + public class IsSubRule : IRule { - public SubRuleType Type { get; } + public PlaceholderType Argument { get; } - public PlaceholderType PlaceholderType { get; } + public IRuleParameter Parameter { get; } - public IsRule(SubRuleType type, PlaceholderType placeholderType) + public IsSubRule(IRuleParameter parameter, PlaceholderType argument) { - Type = type; - PlaceholderType = placeholderType; + Parameter = parameter; + Argument = argument; } - public bool Execute(string value) + public bool Execute() { - return PlaceholderType switch + var value = Parameter.GetValue(); + + return Argument switch { PlaceholderType.Var => CommonParser.Identifier.TryParse(value, out _), PlaceholderType.Int => int.TryParse(value, out _), @@ -30,7 +32,7 @@ public bool Execute(string value) public override string ToString() { - return $"{Type}{Constant.Space}{PlaceholderType}"; + return $"{Parameter}{Constant.Space}{SubRuleType.Is}{Constant.Space}{Argument}"; } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/BinaryLogicalRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/BinaryLogicalRule.cs deleted file mode 100644 index 1d8afe2..0000000 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/BinaryLogicalRule.cs +++ /dev/null @@ -1,32 +0,0 @@ -using SimpleStateMachine.StructuralSearch.Helper; - -namespace SimpleStateMachine.StructuralSearch.Rules; - -public class BinaryLogicalRule : ILogicalRule -{ - public BinaryRuleType Type { get; } - - public ILogicalRule Left { get; } - - public ILogicalRule Right { get; } - - public BinaryLogicalRule(BinaryRuleType type, ILogicalRule left, ILogicalRule right) - { - Type = type; - Left = left; - Right = right; - } - - public bool Execute() - { - var left = Left.Execute(); - var right = Right.Execute(); - - return LogicalHelper.Calculate(Type, left, right); - } - - public override string ToString() - { - return $"{Left}{Constant.Space}{Type}{Constant.Space}{Right}"; - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/PlaceholderLogicalRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/PlaceholderLogicalRule.cs deleted file mode 100644 index 4c8a59b..0000000 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/PlaceholderLogicalRule.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace SimpleStateMachine.StructuralSearch.Rules -{ - public class PlaceholderLogicalRule : ILogicalRule - { - public PlaceholderParameter Placeholder { get; } - - private IRule _rule { get; } - - public PlaceholderLogicalRule(PlaceholderParameter placeholder, IRule rule) - { - Placeholder = placeholder; - _rule = rule; - } - - public override string ToString() - { - return $"{Placeholder}{Constant.Space}{_rule}"; - } - - public bool Execute() - { - var value = Placeholder.GetValue(); - return _rule.Execute(value); - } - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/UnaryLogicalRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/UnaryLogicalRule.cs deleted file mode 100644 index b28c41d..0000000 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LogicalRule/UnaryLogicalRule.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; - -namespace SimpleStateMachine.StructuralSearch.Rules; - -public class UnaryLogicalRule : ILogicalRule -{ - public UnaryRuleType Type { get; } - - public ILogicalRule Parameter { get; } - - public UnaryLogicalRule(UnaryRuleType type, ILogicalRule parameter) - { - Type = type; - Parameter = parameter; - } - - public bool Execute() - { - var result = Parameter.Execute(); - - return Type switch - { - UnaryRuleType.Not => !result, - _ => throw new ArgumentOutOfRangeException() - }; - } - - public override string ToString() - { - return $"{Type}{Constant.Space}{Parameter}"; - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/SubRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/SubRule.cs new file mode 100644 index 0000000..f670c7d --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/SubRule.cs @@ -0,0 +1,42 @@ +using System; +using System.Text.RegularExpressions; + +namespace SimpleStateMachine.StructuralSearch.Rules +{ + public class SubRule : IRule + { + public SubRuleType Type { get; } + + public IRuleParameter Left { get; } + + public IRuleParameter Right { get; } + + public SubRule(SubRuleType type, IRuleParameter left, IRuleParameter right) + { + Type = type; + Left = left; + Right = right; + } + + public bool Execute() + { + var left = Right.GetValue(); + var right = Left.GetValue(); + + return Type switch + { + SubRuleType.Equals => left.Equals(right), + SubRuleType.Contains => left.Contains(right), + SubRuleType.StartsWith => left.StartsWith(right), + SubRuleType.EndsWith => left.EndsWith(right), + SubRuleType.Match => Regex.IsMatch(left, right), + _ => throw new ArgumentOutOfRangeException() + }; + } + + public override string ToString() + { + return $"{Left}{Constant.Space}{Type}{Constant.Space}{Right}"; + } + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/BinaryRuleType.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/BinaryRuleType.cs similarity index 100% rename from src/SimpleStateMachine.StructuralSearch/Rules/FindRule/BinaryRuleType.cs rename to src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/BinaryRuleType.cs diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LineProperty.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/LineProperty.cs similarity index 100% rename from src/SimpleStateMachine.StructuralSearch/Rules/FindRule/LineProperty.cs rename to src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/LineProperty.cs diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/OffsetProperty.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/OffsetProperty.cs similarity index 100% rename from src/SimpleStateMachine.StructuralSearch/Rules/FindRule/OffsetProperty.cs rename to src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/OffsetProperty.cs diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/PlaceholderType.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/PlaceholderType.cs similarity index 100% rename from src/SimpleStateMachine.StructuralSearch/Rules/FindRule/PlaceholderType.cs rename to src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/PlaceholderType.cs diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/SubRuleType.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/SubRuleType.cs similarity index 100% rename from src/SimpleStateMachine.StructuralSearch/Rules/FindRule/SubRuleType.cs rename to src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/SubRuleType.cs diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/UnaryRuleType.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/UnaryRuleType.cs similarity index 100% rename from src/SimpleStateMachine.StructuralSearch/Rules/FindRule/UnaryRuleType.cs rename to src/SimpleStateMachine.StructuralSearch/Rules/FindRule/Types/UnaryRuleType.cs diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/UnaryRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/UnaryRule.cs index a0c8649..d7af616 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/UnaryRule.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/UnaryRule.cs @@ -14,9 +14,9 @@ public UnaryRule(UnaryRuleType type, IRule parameter) Parameter = parameter; } - public bool Execute(string value) + public bool Execute() { - var result = Parameter.Execute(value); + var result = Parameter.Execute(); return Type switch { diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/UnarySubRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/UnarySubRule.cs deleted file mode 100644 index d86f6b6..0000000 --- a/src/SimpleStateMachine.StructuralSearch/Rules/FindRule/UnarySubRule.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Text.RegularExpressions; - -namespace SimpleStateMachine.StructuralSearch.Rules -{ - public class UnarySubRule : IRule - { - public SubRuleType Type { get; } - - public IRuleParameter Parameter { get; } - - public UnarySubRule(SubRuleType type, IRuleParameter parameter) - { - Type = type; - Parameter = parameter; - } - - public bool Execute(string value) - { - var param = Parameter.GetValue(); - - return Type switch - { - SubRuleType.Equals => value.Equals(param), - SubRuleType.Contains => value.Contains(param), - SubRuleType.StartsWith => value.StartsWith(param), - SubRuleType.EndsWith => value.EndsWith(param), - SubRuleType.Match => Regex.IsMatch(value, param), - _ => throw new ArgumentOutOfRangeException() - }; - } - - public override string ToString() - { - return $"{Type}{Constant.Space}{Parameter}"; - } - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs index 18c380f..258b8cf 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs @@ -6,13 +6,14 @@ namespace SimpleStateMachine.StructuralSearch { public class ReplaceRule { - public PlaceholderLogicalRule FindRule { get; } - + public IRule FindRule { get; } + public PlaceholderParameter Placeholder { get; } public IRuleParameter Parameter { get; } - - public ReplaceRule(PlaceholderLogicalRule findRule, IRuleParameter parameter) + + public ReplaceRule(IRule findRule, PlaceholderParameter placeholder, IRuleParameter parameter) { FindRule = findRule; + Placeholder = placeholder; Parameter = parameter; } diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindRulesParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindRulesParser.cs index 9002978..bce825c 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindRulesParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/FindRulesParser.cs @@ -7,7 +7,7 @@ namespace SimpleStateMachine.StructuralSearch { - public static class RuleParser + public static class FindRuleParser { internal static Parser> Binary(Parser op) => op.Select>(type => (l, r) => new BinaryRule(type, l, r)); @@ -53,9 +53,7 @@ internal static readonly Parser> Not public static readonly Parser Expr = ExpressionParser.Build( rule => ( Parser.OneOf( - SubRuleParser.UnarySubRule, - SubRuleParser.IsSubRule, - SubRuleParser.InSubRule, + SubRuleParser.OneOfSubRule, CommonParser.Parenthesised(rule, x => x.TrimStart()) ), new[] @@ -71,10 +69,9 @@ internal static readonly Parser> Not ) ); - internal static readonly Parser PlaceholderLogicalRule = - Parser.Map((parameter, rule) => new PlaceholderLogicalRule(parameter, rule), - ParametersParser.PlaceholderParameter, - Expr.TrimStart()) - .As(); + internal static IRule ParseTemplate(string str) + { + return Expr.ParseOrThrow(str); + } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/LogicalRuleParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/LogicalRuleParser.cs deleted file mode 100644 index 94a5e7f..0000000 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/LogicalRuleParser.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using Pidgin; -using Pidgin.Expression; -using SimpleStateMachine.StructuralSearch.Extensions; -using SimpleStateMachine.StructuralSearch.Rules; - -namespace SimpleStateMachine.StructuralSearch; - -public static class LogicalRuleParser -{ - internal static Parser> BinaryLogical(Parser op) - => op.Select>(type => (l, r) => new BinaryLogicalRule(type, l, r)); - - internal static Parser> UnaryLogical(Parser op) - => op.Select>(type => param => new UnaryLogicalRule(type, param)); - - internal static readonly Parser> And - = BinaryLogical(Parsers.EnumValue(BinaryRuleType.And, true) - .TrimStart() - .Try()); - - internal static readonly Parser> Or - = BinaryLogical(Parsers.EnumValue(BinaryRuleType.Or, true) - .TrimStart() - .Try()); - - internal static readonly Parser> NOR - = BinaryLogical(Parsers.EnumValue(BinaryRuleType.NOR, true) - .TrimStart() - .Try()); - - internal static readonly Parser> XOR - = BinaryLogical(Parsers.EnumValue(BinaryRuleType.XOR, true) - .TrimStart() - .Try()); - - internal static readonly Parser> NAND - = BinaryLogical(Parsers.EnumValue(BinaryRuleType.NAND, true) - .TrimStart() - .Try()); - - internal static readonly Parser> XNOR - = BinaryLogical(Parsers.EnumValue(BinaryRuleType.XNOR, true) - .TrimStart() - .Try()); - - internal static readonly Parser> Not - = UnaryLogical(Parsers.EnumValue(UnaryRuleType.Not, true) - .TrimStart() - .Try()); - - public static readonly Parser Expr = ExpressionParser.Build( - rule => ( - Parser.OneOf( - RuleParser.PlaceholderLogicalRule, - CommonParser.Parenthesised(rule, x => x.TrimStart()) - ), - new[] - { - Operator.Prefix(Not), - Operator.InfixL(And), - Operator.InfixL(NOR), - Operator.InfixL(XOR), - Operator.InfixL(NAND), - Operator.InfixL(XNOR), - Operator.InfixL(Or), - } - ) - ); - - internal static readonly Parser Rule = - Parser.Map((parameter, rule) => new PlaceholderLogicalRule(parameter, rule), - ParametersParser.PlaceholderParameter, - Expr.TrimStart()) - .As(); - - internal static ILogicalRule ParseTemplate(string str) - { - return Rule.ParseOrThrow(str); - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs index eef6f61..61d55fa 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs @@ -16,7 +16,7 @@ public static class ReplaceRuleParser internal static readonly Parser ReplaceRule = Parser.Map((rule, parameter) => new ReplaceRule(rule, parameter), - RuleParser.PlaceholderLogicalRule.Before(CommonTemplateParser.Should.TrimStart()), + FindRuleParser.Expr.Before(CommonTemplateParser.Should.TrimStart()), Parser.OneOf(ChangeParameter.Try(), ParametersParser.Parameter.Try())) .Try() .TrimStart(); diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/StructuralSearch.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/StructuralSearch.cs index 34d8017..f2904e8 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/StructuralSearch.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/StructuralSearch.cs @@ -12,8 +12,8 @@ public static IFindParser ParseFindTemplate(string template) public static IReplaceBuilder ParseReplaceTemplate(string template) => ReplaceTemplateParser.ParseTemplate(template); - public static PlaceholderLogicalRule ParseFindRule(string template) - => RuleParser.ParseTemplate(template); + public static IRule ParseFindRule(string template) + => FindRuleParser.ParseTemplate(template); public static ReplaceRule ParseReplaceRule(string template) => ReplaceRuleParser.ParseTemplate(template); diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/SubFindRuleParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/SubFindRuleParser.cs deleted file mode 100644 index 1d5b3b7..0000000 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/SubFindRuleParser.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Collections.Generic; -using Pidgin; -using SimpleStateMachine.StructuralSearch.Extensions; - -namespace SimpleStateMachine.StructuralSearch.Rules -{ - public static class SubRuleParser - { - public static readonly Parser SubRuleType = - Parsers.EnumExcept(true, Rules.SubRuleType.Is, Rules.SubRuleType.In) - .TrimStart(); - - public static readonly Parser UnarySubRule = - Parser.Map((type, param) => new UnarySubRule(type, param), - SubRuleType, ParametersParser.Parameter) - .As() - .Try(); - - public static readonly Parser PlaceholderType = - Parser.CIEnum() - .TrimStart(); - - public static readonly Parser IsSubRule = - Parser.Map((type, param) => new IsRule(type, param), - Parsers.EnumValue(Rules.SubRuleType.Is, true) - .TrimStart(), - PlaceholderType) - .As() - .Try(); - - public static readonly Parser InSubRule = - Parser.Map((type, param) => new InRule(type, param), - Parsers.EnumValue(Rules.SubRuleType.In, true) - .TrimStart(), Parser.OneOf(ParametersParser.Parameters, - CommonParser.Parenthesised(ParametersParser.Parameters, x=> x.Trim()))) - .As() - .Try(); - } -} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/SubRuleParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/SubRuleParser.cs new file mode 100644 index 0000000..1d24283 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/SubRuleParser.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using Pidgin; +using SimpleStateMachine.StructuralSearch.Extensions; + +namespace SimpleStateMachine.StructuralSearch.Rules +{ + public static class SubRuleParser + { + public static readonly Parser SubRuleType = + Parser.CIEnum().TrimStart(); + + public static Parser SubRule(IRuleParameter left, SubRuleType ruleType) => + ParametersParser.Parameter.Select(right => new SubRule(ruleType, left, right)) + .As() + .Try(); + + public static readonly Parser PlaceholderType = + Parser.CIEnum() + .TrimStart(); + + public static Parser IsSubRule(IRuleParameter left, SubRuleType ruleType) => + PlaceholderType.Select(arg => new IsSubRule(left, arg)) + .As() + .Try(); + + public static Parser InSubRule(IRuleParameter left, SubRuleType ruleType) => + Parser.OneOf(ParametersParser.Parameters, + CommonParser.Parenthesised(ParametersParser.Parameters, x => x.Trim())) + .Select(args => new InSubRule(left, args)) + .As() + .Try(); + + + public static readonly Parser OneOfSubRule = + Parser.Map((left, ruleType) => (left, ruleType), + ParametersParser.Parameter, SubRuleType) + .Then(x => x.ruleType switch + { + Rules.SubRuleType.In => InSubRule(x.left, x.ruleType), + Rules.SubRuleType.Is => IsSubRule(x.left, x.ruleType), + _ => SubRule(x.left, x.ruleType) + }); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs index 17f417c..660c25f 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs @@ -13,7 +13,7 @@ public class StructuralSearchParser { public IFindParser FindParser { get; set; } - public Dictionary FindRules { get; set; } + public IEnumerable FindRules { get; set; } public IReplaceBuilder ReplaceBuilder { get; set; } @@ -25,15 +25,14 @@ public StructuralSearchParser(Configuration configuration) FindRules = configuration.FindRules .EmptyIfNull() - .Select(StructuralSearch.ParseFindRule) - .ToDictionary(x => x.Placeholder.Name, x => x); + .Select(StructuralSearch.ParseFindRule); ReplaceBuilder = StructuralSearch.ParseReplaceTemplate(configuration.ReplaceTemplate); - ReplaceRules = configuration.ReplaceRules - .EmptyIfNull() - .Select(StructuralSearch.ParseReplaceRule) - .ToDictionary(x => x.FindRule.Placeholder.Name, x => x); + // ReplaceRules = configuration.ReplaceRules + // .EmptyIfNull() + // .Select(StructuralSearch.ParseReplaceRule) + // .ToDictionary(x => x.FindRule.Placeholder.Name, x => x); } public IEnumerable Parse(ref IParsingContext context) @@ -62,7 +61,9 @@ public void Replace(FindParserMatch context) public bool AllRulesCompleted(ref IParsingContext context) { - return FindRules.Values.All(x => x.Execute()); + //return FindRules.Values.All(x => x.Execute()); + + return true; } } } \ No newline at end of file From 5c1262f62c97d5a5cbc9fe20516a9d3fbf85c293 Mon Sep 17 00:00:00 2001 From: GMIKE Date: Mon, 9 May 2022 03:29:06 +0300 Subject: [PATCH 09/11] new replace rule with new find rule, replace sub rules --- .../ConfigurationFile/FullConfig.yml | 1 + .../ConfigurationFile/ShortConfig.yml | 3 +- .../Mock/Configuration.cs | 5 ++-- .../ReplaceRule/NullUnionOperator.txt | 2 +- .../ReplaceRuleParserTests.cs | 29 +++++-------------- .../Constant.cs | 10 +++++++ .../Rules/ReplaceRule/ReplaceRule.cs | 15 +++++----- .../Rules/ReplaceRule/ReplaceSubRule.cs | 20 +++++++++++++ .../StructuralSearch/CommonParser.cs | 3 ++ .../StructuralSearch/ReplaceRuleParser.cs | 18 ++++++++++-- 10 files changed, 69 insertions(+), 37 deletions(-) create mode 100644 src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceSubRule.cs diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/FullConfig.yml b/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/FullConfig.yml index d1bafe5..2a99664 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/FullConfig.yml +++ b/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/FullConfig.yml @@ -27,6 +27,7 @@ ReplaceTemplate: |- $var$ = $value1$ ?? $value2$; ReplaceRules: + - $sign$ In ("!=", "is not") then $var2$ => $var1$, $var1$ => $var2$ # TernaryOperator diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/ShortConfig.yml b/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/ShortConfig.yml index 04115a6..2393371 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/ShortConfig.yml +++ b/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/ShortConfig.yml @@ -25,7 +25,8 @@ - $sign$ In ("Is", "==", "!=", "is not") ReplaceTemplate: |- $var$ = $value1$ ?? $value2$; - + ReplaceRules: + - $sign$ In ("!=", "is not") then $var2$ => $var1$, $var1$ => $var2$ # TernaryOperator - FindTemplate: |- diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/Mock/Configuration.cs b/src/SimpleStateMachine.StructuralSearch.Tests/Mock/Configuration.cs index 9242fdd..ab529ff 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/Mock/Configuration.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/Mock/Configuration.cs @@ -13,9 +13,8 @@ public static Configuration GetConfigurationFromFiles(string name) var fileRule = FileOrNull("FindRule", fileName) ; var replaceTemplate = FileOrNull("ReplaceTemplate", fileName); var replaceRule = FileOrNull("ReplaceRule", fileName); - - var fileRules = fileRule is null ? null : new List{ fileRule }; - var replaceRules = replaceRule is null ? null : new List{ replaceRule }; + var fileRules = fileRule is null ? null : new List(fileRule.Split(Constant.LineFeed.ToString())); + var replaceRules = replaceRule is null ? null : new List(replaceRule.Split(Constant.LineFeed.ToString())); var config = new Configuration { FindTemplate = findTemplate, diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRule/NullUnionOperator.txt b/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRule/NullUnionOperator.txt index 7dc05eb..082363d 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRule/NullUnionOperator.txt +++ b/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRule/NullUnionOperator.txt @@ -1 +1 @@ -$sign$ Is ("Is", "==", "!=", "is not") \ No newline at end of file +$sign$ In ("!=", "is not") then $var2$ => $var1$, $var1$ => $var2$ \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRuleParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRuleParserTests.cs index ba61dc1..5d267e8 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRuleParserTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRuleParserTests.cs @@ -7,28 +7,13 @@ namespace SimpleStateMachine.StructuralSearch.Tests public class ReplaceRuleParserTests { [Theory] - [InlineData("$var$", "equals $var$", "$var$")] - [InlineData("$var$", "equals \"\\$\"", "\"\\$\"")] - [InlineData("$var$", "Not equals $var$.Lenght", "$var$.Lenght")] - [InlineData("$var$", "Not equals $var$.offset.Start", "$var$.offset.Start")] - [InlineData("$var$", "equals $var$.Lenght and Not StartsWith \"123\"", "$var$.offset.Start.Trim")] - [InlineData("$var$", "equals $var$.Lenght and Not StartsWith \"\\\"Test\"", "$var$.offset.Start.ToUpper")] - public void ReplaceRulePartsParsingShouldBeSuccess(string placeholder, string findRule, string replaceRule) - { - var replaceRuleStr = $"{placeholder} {findRule} => {replaceRule}"; - var rule = StructuralSearch.ParseReplaceRule(replaceRuleStr); - var ruleStr = rule.ToString().ToLower(); - Assert.NotNull(rule); - Assert.Equal(ruleStr, replaceRuleStr.ToLower()); - } - - [Theory] - [InlineData("$var1$ equals $var$ => $var2$")] - [InlineData("$var1$ equals \"\\$\" => \"\\$\"")] - [InlineData("$var1$ Not equals $var$.Lenght => $var$.Lenght")] - [InlineData("$var1$ Not equals $var$.offset.Start => $var$.offset.Start")] - [InlineData("$var1$ equals $var$.Lenght and Not StartsWith \"123\" => $var$.offset.Start.Trim")] - [InlineData("$var1$ equals $var$.Lenght and Not StartsWith \"\\\"Test\" => $var$.offset.Start.ToUpper")] + [InlineData("$var1$ equals $var2$ then $var1$ => $var3$")] + [InlineData("$var1$ equals \"\\$\" then $var1$ => \"\\$\",$var2$ => \"132\"")] + [InlineData("Not $var1$ equals $var$.Lenght then $var1$ => $var$.Lenght")] + [InlineData("Not $var1$ equals $var$.offset.Start then $var1$ => $var$.offset.Start")] + [InlineData("$var1$ equals $var$.Lenght and Not $var1$ StartsWith \"123\" then $var1$ => $var$.offset.Start.Trim")] + [InlineData("$var1$ equals $var$.Lenght and Not $var1$ StartsWith \"123\" then $var1$ => $var$.offset.Start.Trim,$var2$ => $var$.offset.Start.Trim")] + [InlineData("$var1$ equals $var$.Lenght and Not $var1$ StartsWith \"\\\"Test\" then $var1$ => $var$.offset.Start.ToUpper")] public void ReplaceRuleParsingShouldBeSuccess(string replaceRule) { var rule = StructuralSearch.ParseReplaceRule(replaceRule); diff --git a/src/SimpleStateMachine.StructuralSearch/Constant.cs b/src/SimpleStateMachine.StructuralSearch/Constant.cs index 5a3ead5..4466a87 100644 --- a/src/SimpleStateMachine.StructuralSearch/Constant.cs +++ b/src/SimpleStateMachine.StructuralSearch/Constant.cs @@ -12,6 +12,11 @@ public static partial class Constant /// public static readonly string Not ="Not"; + /// + /// String: "Then" + /// + public static readonly string Then ="Then"; + /// /// Parenthesis char: '(' /// @@ -97,6 +102,11 @@ public static partial class Constant /// public static readonly char More = '>'; + /// + /// Char: ':' + /// + public static readonly char Colon = ':'; + /// /// String: "=>" /// diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs index 258b8cf..88de028 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceRule.cs @@ -1,4 +1,6 @@ -using Pidgin; +using System.Collections.Generic; +using System.Reflection.Metadata; +using Pidgin; using SimpleStateMachine.StructuralSearch.Extensions; using SimpleStateMachine.StructuralSearch.Rules; @@ -7,19 +9,18 @@ namespace SimpleStateMachine.StructuralSearch public class ReplaceRule { public IRule FindRule { get; } - public PlaceholderParameter Placeholder { get; } - public IRuleParameter Parameter { get; } - public ReplaceRule(IRule findRule, PlaceholderParameter placeholder, IRuleParameter parameter) + public IEnumerable Rules { get; } + + public ReplaceRule(IRule findRule, IEnumerable rules) { FindRule = findRule; - Placeholder = placeholder; - Parameter = parameter; + Rules = rules; } public override string ToString() { - return $"{FindRule}{Constant.Space}{Constant.Should}{Constant.Space}{Parameter}"; + return $"{FindRule}{Constant.Space}{Constant.Then}{Constant.Space}{string.Join(Constant.Comma, Rules)}"; } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceSubRule.cs b/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceSubRule.cs new file mode 100644 index 0000000..ef09293 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch/Rules/ReplaceRule/ReplaceSubRule.cs @@ -0,0 +1,20 @@ +using SimpleStateMachine.StructuralSearch.Rules; + +namespace SimpleStateMachine.StructuralSearch; + +public class ReplaceSubRule +{ + public PlaceholderParameter Placeholder { get; } + public IRuleParameter Parameter { get; } + + public ReplaceSubRule(PlaceholderParameter placeholder, IRuleParameter parameter) + { + Placeholder = placeholder; + Parameter = parameter; + } + + public override string ToString() + { + return $"{Placeholder}{Constant.Space}{Constant.Should}{Constant.Space}{Parameter}"; + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/CommonParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/CommonParser.cs index be5fdb0..b809955 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/CommonParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/CommonParser.cs @@ -34,6 +34,9 @@ internal static readonly Parser Identifier internal static readonly Parser Comma = Char(Constant.Comma); + internal static readonly Parser Colon + = Char(Constant.Colon); + internal static readonly Parser DoubleQuotes = Char(Constant.DoubleQuotes); diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs index 61d55fa..1c8bf34 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearch/ReplaceRuleParser.cs @@ -13,14 +13,26 @@ public static class ReplaceRuleParser .As() .Try() .TrimStart(); + + internal static readonly Parser Then = + Parser.CIString(Constant.Then) + .Try() + .TrimStart(); - internal static readonly Parser ReplaceRule = - Parser.Map((rule, parameter) => new ReplaceRule(rule, parameter), - FindRuleParser.Expr.Before(CommonTemplateParser.Should.TrimStart()), + internal static readonly Parser ReplaceSubRule = + Parser.Map((placeholder, parameter) => new ReplaceSubRule(placeholder, parameter), + ParametersParser.PlaceholderParameter.Before(CommonTemplateParser.Should.TrimStart()), Parser.OneOf(ChangeParameter.Try(), ParametersParser.Parameter.Try())) .Try() .TrimStart(); + internal static readonly Parser ReplaceRule = + Parser.Map((rule, subRules) => new ReplaceRule(rule, subRules), + FindRuleParser.Expr, + Then.Then(ReplaceSubRule.SeparatedAtLeastOnce(CommonParser.Comma))) + .Try() + .TrimStart(); + internal static ReplaceRule ParseTemplate(string str) { return ReplaceRule.ParseOrThrow(str); From d3ae8ce2159c0a5e3b562477506a682cef6cb2d4 Mon Sep 17 00:00:00 2001 From: GMIKE Date: Tue, 10 May 2022 20:05:02 +0300 Subject: [PATCH 10/11] fix config parser --- .../ConfigurationFile/FullConfig.yml | 7 +-- .../ConfigurationFile/ShortConfig.yml | 7 +-- .../Examples/NullUnionOperator.cs | 26 ++++----- .../FindRule/NullUnionOperator.txt | 3 +- .../FindTemplate/NullUnionOperator.txt | 8 +-- .../Source/NullUnionOperator.txt | 6 +-- .../StructurSearchParserTests.cs | 2 +- .../StructuralSearchParser.cs | 53 +++++++++++++------ 8 files changed, 60 insertions(+), 52 deletions(-) diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/FullConfig.yml b/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/FullConfig.yml index 2a99664..4c6daaa 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/FullConfig.yml +++ b/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/FullConfig.yml @@ -14,16 +14,13 @@ # NullUnionOperator - FindTemplate: |- - if($value1$ $sign$ null) - { + if($value$ $sign$ null) $var$ = $value2$; - } else - { $var$ = $value1$; - } FindRules: - $sign$ In ("Is", "==", "!=", "is not") + - $value$ In ($value1$, "$value1$.Value", $value2$, "$value2$.Value") ReplaceTemplate: |- $var$ = $value1$ ?? $value2$; ReplaceRules: diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/ShortConfig.yml b/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/ShortConfig.yml index 2393371..c673f23 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/ShortConfig.yml +++ b/src/SimpleStateMachine.StructuralSearch.Tests/ConfigurationFile/ShortConfig.yml @@ -13,16 +13,13 @@ # NullUnionOperator - FindTemplate: |- - if($value1$ $sign$ null) - { + if($value$ $sign$ null) $var$ = $value2$; - } else - { $var$ = $value1$; - } FindRules: - $sign$ In ("Is", "==", "!=", "is not") + - $value$ In ($value1$, "$value1$.Value", $value2$, "$value2$.Value") ReplaceTemplate: |- $var$ = $value1$ ?? $value2$; ReplaceRules: diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/Examples/NullUnionOperator.cs b/src/SimpleStateMachine.StructuralSearch.Tests/Examples/NullUnionOperator.cs index 69c874e..41be29b 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/Examples/NullUnionOperator.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/Examples/NullUnionOperator.cs @@ -12,24 +12,26 @@ public int Test1() return 4; } - public int Test2() + public void Test2() { - int? temp = 5; - - if(temp is null) - return 7; + int? result; + int? temp1 = 5; + int? temp2 = 5; + if(temp1 is null) + result = temp2; else - return 8; + result = temp1; } - public int Test3() + public void Test3() { - int? temp2 = 1; - - if(temp2 is null) - return 3; + int result; + int? temp1 = 5; + int? temp2 = 5; + if(temp1 is null) + result = temp2.Value; else - return 4; + result = temp1.Value; } public int Test4() diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/FindRule/NullUnionOperator.txt b/src/SimpleStateMachine.StructuralSearch.Tests/FindRule/NullUnionOperator.txt index 3afde7b..ca18854 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/FindRule/NullUnionOperator.txt +++ b/src/SimpleStateMachine.StructuralSearch.Tests/FindRule/NullUnionOperator.txt @@ -1 +1,2 @@ -$sign$ In ("Is", "==", "!=", "is not") \ No newline at end of file +$sign$ In ("Is", "==", "!=", "is not") +$value$ In ($value1$, "$value1$.Value", $value2$, "$value2$.Value") \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplate/NullUnionOperator.txt b/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplate/NullUnionOperator.txt index 24e5979..38d96cb 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplate/NullUnionOperator.txt +++ b/src/SimpleStateMachine.StructuralSearch.Tests/FindTemplate/NullUnionOperator.txt @@ -1,8 +1,4 @@ -if($value1$ $sign$ null) -{ +if($value$ $sign$ null) $var$ = $value2$; -} else -{ - $var$ = $value1$; -} \ No newline at end of file + $var$ = $value1$; \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/Source/NullUnionOperator.txt b/src/SimpleStateMachine.StructuralSearch.Tests/Source/NullUnionOperator.txt index 0e7e960..df34cb0 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/Source/NullUnionOperator.txt +++ b/src/SimpleStateMachine.StructuralSearch.Tests/Source/NullUnionOperator.txt @@ -1,8 +1,4 @@ if(var1 is null) -{ temp = var2; -} else -{ - temp = var1; -} \ No newline at end of file + temp = var1; \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs index 6d07eb8..0a341b0 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/StructurSearchParserTests.cs @@ -9,7 +9,7 @@ public class StructuralSearchParserTests { [Theory] // [InlineData("AssignmentNullUnionOperator")] - // [InlineData("NullUnionOperator")] + [InlineData("NullUnionOperator", "Examples/NullUnionOperator.cs", 2)] [InlineData("TernaryOperator", "Examples/TernaryOperator.cs", 3)] public static void StructuralSearchShouldBeSuccess(string exampleName, string exampleFilePath, int matchesCount) { diff --git a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs index 660c25f..86b0f96 100644 --- a/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/StructuralSearchParser.cs @@ -17,7 +17,7 @@ public class StructuralSearchParser public IReplaceBuilder ReplaceBuilder { get; set; } - public Dictionary ReplaceRules { get; set; } + public IEnumerable ReplaceRules { get; set; } public StructuralSearchParser(Configuration configuration) { @@ -29,29 +29,54 @@ public StructuralSearchParser(Configuration configuration) ReplaceBuilder = StructuralSearch.ParseReplaceTemplate(configuration.ReplaceTemplate); - // ReplaceRules = configuration.ReplaceRules - // .EmptyIfNull() - // .Select(StructuralSearch.ParseReplaceRule) - // .ToDictionary(x => x.FindRule.Placeholder.Name, x => x); + ReplaceRules = configuration.ReplaceRules + .EmptyIfNull() + .Select(StructuralSearch.ParseReplaceRule); } public IEnumerable Parse(ref IParsingContext context) { var matches = FindParser.Parse(ref context); + return matches; + } + + public IEnumerable ApplyFindRule(ref IParsingContext context, IEnumerable matches) + { var result = new List(); - foreach (var match in matches) { - context.Set(match.Placeholders); - if (AllRulesCompleted(ref context)) - { + context.Set(match.Placeholders); + var all = FindRules.All(x => x.Execute()); + if (all) + { result.Add(match); - } + } } return result; } - + public void ApplyReplaceRule(ref IParsingContext context, IEnumerable matches) + { + // var result = new List(); + // foreach (var match in matches) + // { + // context.Set(match.Placeholders); + // + // var rules = ReplaceRules + // .Where(x => x.FindRule.Execute()) + // .SelectMany(x => x.Rules); + // + // var placeHolder = match.Placeholders + // .ToDictionary(x=> x.Key, x=> x.Value); + // + // foreach (var rule in rules) + // { + // placeHolder[rule.Placeholder.Name].Value + // } + // } + // + // return result; + } public void Replace(FindParserMatch context) { //ReplaceBuilder.Build(context); @@ -59,11 +84,5 @@ public void Replace(FindParserMatch context) //FindParser.Parse(context, context.File.Data); } - public bool AllRulesCompleted(ref IParsingContext context) - { - //return FindRules.Values.All(x => x.Execute()); - - return true; - } } } \ No newline at end of file From ca43648928a20e370ccee22f9f2446b614853467 Mon Sep 17 00:00:00 2001 From: GMIKE Date: Tue, 10 May 2022 20:05:17 +0300 Subject: [PATCH 11/11] fix parameters parser, tests --- .../ParameterParserTests.cs | 44 +++++++++++++++++++ .../ReplaceRuleParserTests.cs | 3 +- .../Rules/Parameters/ParametersParser.cs | 1 - .../Rules/Parameters/StringFormatParameter.cs | 2 +- .../Rules/Parameters/StringParameter.cs | 2 +- 5 files changed, 48 insertions(+), 4 deletions(-) create mode 100644 src/SimpleStateMachine.StructuralSearch.Tests/ParameterParserTests.cs diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/ParameterParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/ParameterParserTests.cs new file mode 100644 index 0000000..0115369 --- /dev/null +++ b/src/SimpleStateMachine.StructuralSearch.Tests/ParameterParserTests.cs @@ -0,0 +1,44 @@ +using Pidgin; +using Xunit; + +namespace SimpleStateMachine.StructuralSearch.Tests; + +public class ParameterParserTests +{ + [Theory] + [InlineData("\\\"132\\\"")] + public void StringParameterParsingShouldBeSuccess(string str) + { + var parameter = ParametersParser.StringParameter.ParseOrThrow(str); + var parameterStr = parameter.ToString().ToLower(); + Assert.Equal(parameterStr.ToLower(), str.ToLower()); + } + + [Theory] + [InlineData("\"132\"")] + public void StringParameterParsingShouldBeFail(string str) + { + Assert.Throws(() => ParametersParser.StringParameter.ParseOrThrow(str)); + } + + [Theory] + [InlineData("\"132\"")] + [InlineData("\"132$var1$\"")] + [InlineData("\"132 $var1$\"")] + [InlineData("\"132 $var1$ \"")] + [InlineData("\"123$var1$.Lenght456\"")] + [InlineData("\" \\\"132\\\" \"")] + public void StringFormatParameterParsingShouldBeSuccess(string str) + { + var parameter = ParametersParser.StringFormatParameter.ParseOrThrow(str); + var parameterStr = parameter.ToString().ToLower(); + Assert.Equal(parameterStr.ToLower(), str.ToLower()); + } + + [Theory] + [InlineData("\\\"132\\\"")] + public void StringFormatParameterParsingShouldBeFail(string str) + { + Assert.Throws(() => ParametersParser.StringFormatParameter.ParseOrThrow(str)); + } +} \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRuleParserTests.cs b/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRuleParserTests.cs index 5d267e8..577c23b 100644 --- a/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRuleParserTests.cs +++ b/src/SimpleStateMachine.StructuralSearch.Tests/ReplaceRuleParserTests.cs @@ -7,7 +7,7 @@ namespace SimpleStateMachine.StructuralSearch.Tests public class ReplaceRuleParserTests { [Theory] - [InlineData("$var1$ equals $var2$ then $var1$ => $var3$")] + [InlineData("$var1$ equals $var2$ then $var1$ => \"test $var3$\"")] [InlineData("$var1$ equals \"\\$\" then $var1$ => \"\\$\",$var2$ => \"132\"")] [InlineData("Not $var1$ equals $var$.Lenght then $var1$ => $var$.Lenght")] [InlineData("Not $var1$ equals $var$.offset.Start then $var1$ => $var$.offset.Start")] @@ -21,5 +21,6 @@ public void ReplaceRuleParsingShouldBeSuccess(string replaceRule) Assert.NotNull(rule); Assert.Equal(ruleStr, replaceRule.ToLower()); } + } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/ParametersParser.cs b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/ParametersParser.cs index f027bea..82ca401 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/ParametersParser.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/ParametersParser.cs @@ -23,7 +23,6 @@ public static class ParametersParser .AtLeastOnceString() .Select(x => new StringParameter(x)) .As() - .TrimStart() .Try(); public static readonly Parser StringFormatParameter = diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/StringFormatParameter.cs b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/StringFormatParameter.cs index 4bd1363..d2dd438 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/StringFormatParameter.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/StringFormatParameter.cs @@ -19,7 +19,7 @@ public string GetValue() public override string ToString() { - return $"{string.Join(Constant.Space, Parameters.Select(x=> x.ToString()))}"; + return $"{Constant.DoubleQuotes}{string.Join(string.Empty, Parameters.Select(x=> x.ToString()))}{Constant.DoubleQuotes}"; } } } \ No newline at end of file diff --git a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/StringParameter.cs b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/StringParameter.cs index f4b12c8..40f7bbb 100644 --- a/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/StringParameter.cs +++ b/src/SimpleStateMachine.StructuralSearch/Rules/Parameters/StringParameter.cs @@ -19,7 +19,7 @@ public override string ToString() var value = EscapeHelper.EscapeChars(Value, c => $"{Constant.BackSlash}{c}", Constant.PlaceholderSeparator, Constant.DoubleQuotes); - return $"{Constant.DoubleQuotes}{value}{Constant.DoubleQuotes}"; + return $"{value}"; } } } \ No newline at end of file