diff --git a/.editorconfig b/.editorconfig
index 1a2db97..ffd8205 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -1,74 +1,32 @@
-root = true
-
-[*]
-charset = utf-8
-indent_size = 4
-indent_style = space
-insert_final_newline = true
-trim_trailing_whitespace = true
-
-[*.{yml,props,targets,csproj}]
-indent_size = 2
-
-# IDE0079: Remove unnecessary suppression
-dotnet_remove_unnecessary_suppression_exclusions = category:ReSharper
-
-# IDE0079: Remove unnecessary suppression
-# dotnet_diagnostic.IDE0079.severity = none
-
-# CA2255: The 'ModuleInitializer' attribute should not be used in libraries
-dotnet_diagnostic.CA2255.severity = none
-
-# CS8600: Converting null literal or possible null value to non-nullable type.
-dotnet_diagnostic.CS8600.severity = error
-
-# CS8601: Possible null reference assignment.
-dotnet_diagnostic.CS8601.severity = error
-
-# CS8602: Dereference of a possibly null reference.
-dotnet_diagnostic.CS8602.severity = error
-
-# CS8603: Possible null reference return.
-dotnet_diagnostic.CS8603.severity = error
-
-# CS8604: Possible null reference argument.
-dotnet_diagnostic.CS8604.severity = error
-
-# CS8610: Nullability of reference types in type of parameter doesn't match overridden member.
-dotnet_diagnostic.CS8610.severity = error
-
-# CS8613: Nullability of reference types in return type doesn't match implicitly implemented member.
-dotnet_diagnostic.CS8613.severity = error
-
-# CS8614: Nullability of reference types in type of parameter doesn't match implicitly implemented member.
-dotnet_diagnostic.CS8614.severity = error
-
-# CS8618: Non-nullable field is uninitialized. Consider declaring as nullable.
-dotnet_diagnostic.CS8618.severity = error
-
-# CS8619: Nullability of reference types in value doesn't match target type.
-dotnet_diagnostic.CS8619.severity = error
-
-# CS8620: Argument cannot be used for parameter due to differences in the nullability of reference types.
-dotnet_diagnostic.CS8620.severity = error
-
-# CS8625: Cannot convert null literal to non-nullable reference type.
-dotnet_diagnostic.CS8625.severity = error
-
-# CS8634: The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint.
-dotnet_diagnostic.CS8634.severity = error
-
-# CS8643: Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type.
-dotnet_diagnostic.CS8643.severity = error
-
-# CS8653: A default expression introduces a null value for a type parameter.
-dotnet_diagnostic.CS8653.severity = error
-
-# CS8714: The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'notnull' constraint.
-dotnet_diagnostic.CS8714.severity = error
-
-# IDE0059: Unnecessary assigment of a value
-dotnet_diagnostic.IDE0059.severity = none
-
-# IDE0060: Remove unused parameter
-dotnet_diagnostic.IDE0060.severity = none
+root = true
+
+[*]
+charset = utf-8
+indent_size = 4
+indent_style = space
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+[*.{yml,yaml}]
+indent_size = 2
+
+[*.{slnx,csproj,proj,props,targets}]
+indent_size = 2
+
+[*.cs]
+resharper_csharp_max_line_length = 160
+
+# Using directive options
+dotnet_sort_system_directives_first = true
+dotnet_separate_import_directive_groups = true
+
+# Prefer var whenever possible
+csharp_style_var_for_built_in_types = true:suggestion
+csharp_style_var_when_type_is_apparent = true:suggestion
+csharp_style_var_elsewhere = true:suggestion
+
+# Indentation preferences
+csharp_indent_labels = no_change
+
+# IDE0079: Remove unnecessary suppression
+dotnet_remove_unnecessary_suppression_exclusions = category:ReSharper
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..176a458
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+* text=auto
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 631a3e1..974569a 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -1,40 +1,40 @@
-name: Publish
-
-on:
- push:
- tags:
- - "[0-9]+.[0-9]+.[0-9]+"
- - "[0-9]+.[0-9]+.[0-9]+-[a-z]+.[0-9]+"
-
-permissions:
- contents: write
-
-jobs:
- publish:
- if: github.repository == 'rameel/ramstack.expressionparser'
- name: Publish packages
- runs-on: ubuntu-latest
-
- steps:
- - name: Install .NET
- uses: actions/setup-dotnet@v4
- with:
- dotnet-version: 10.0.x
-
- - name: Checkout
- uses: actions/checkout@v4
-
- - name: Build Solution
- run: dotnet build -c Release
-
- - name: Create NuGet Packages
- run: dotnet pack -c Release -o ./nuget --no-build
-
- - name: Publish NuGet Packages
- run: dotnet nuget push ./nuget/*.nupkg --api-key ${{secrets.NUGET_API_KEY}} --skip-duplicate -s https://api.nuget.org/v3/index.json
-
- - name: Create GitHub Release
- uses: softprops/action-gh-release@v2
- with:
- draft: true
- files: nuget/*
+name: Publish
+
+on:
+ push:
+ tags:
+ - "[0-9]+.[0-9]+.[0-9]+"
+ - "[0-9]+.[0-9]+.[0-9]+-[a-z]+.[0-9]+"
+
+permissions:
+ contents: write
+
+jobs:
+ publish:
+ if: github.repository == 'rameel/ramstack.expressionparser'
+ name: Publish packages
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Install .NET
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 10.0.x
+
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Build Solution
+ run: dotnet build -c Release
+
+ - name: Create NuGet Packages
+ run: dotnet pack -c Release -o ./nuget --no-build
+
+ - name: Publish NuGet Packages
+ run: dotnet nuget push ./nuget/*.nupkg --api-key ${{secrets.NUGET_API_KEY}} --skip-duplicate -s https://api.nuget.org/v3/index.json
+
+ - name: Create GitHub Release
+ uses: softprops/action-gh-release@v2
+ with:
+ draft: true
+ files: nuget/*
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index bdf51bf..de27f9b 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -1,29 +1,29 @@
-name: Build & Test
-
-on:
- pull_request:
- branches: [main]
-
-jobs:
- build-and-test:
- name: "Test projects"
- runs-on: ubuntu-latest
- steps:
- - name: Install .NET
- uses: actions/setup-dotnet@v4
- with:
- dotnet-version: |
- 6.x
- 7.x
- 8.x
- 9.x
- 10.x
-
- - name: Checkout
- uses: actions/checkout@v4
-
- - name: Test Projects (Debug)
- run: dotnet test -c Debug
-
- - name: Test Projects (Release)
- run: dotnet test -c Release
+name: Build & Test
+
+on:
+ pull_request:
+ branches: [main]
+
+jobs:
+ build-and-test:
+ name: "Test projects"
+ runs-on: ubuntu-latest
+ steps:
+ - name: Install .NET
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: |
+ 6.x
+ 7.x
+ 8.x
+ 9.x
+ 10.x
+
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Test Projects (Debug)
+ run: dotnet test -c Debug
+
+ - name: Test Projects (Release)
+ run: dotnet test -c Release
diff --git a/.gitignore b/.gitignore
index 4f81b1b..bd6adb1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,37 +1,37 @@
-#Ignore thumbnails created by windows
-[Tt]humbs.db
-
-#Ignore files build by Visual Studio
-*.obj
-*.exe
-*.pdb
-*.user
-*.patch
-*.aps
-*.pch
-*.vspscc
-*_i.c
-*_p.c
-*.ncb
-*.suo
-*.tlb
-*.tlh
-*.bak
-*.cache
-*.ilk
-*.log
-*.lib
-*.sbr
-*.cs.ide
-[Dd]ebug*/
-[Rr]elease*/
-bin/
-obj/
-.vs/
-.vscode/
-*.ReSharper
-*.ReSharper.user
-[Tt]est[Rr]esult*
-
-#Ignore Rider/Idea files
-.idea/
+#Ignore thumbnails created by windows
+[Tt]humbs.db
+
+#Ignore files build by Visual Studio
+*.obj
+*.exe
+*.pdb
+*.user
+*.patch
+*.aps
+*.pch
+*.vspscc
+*_i.c
+*_p.c
+*.ncb
+*.suo
+*.tlb
+*.tlh
+*.bak
+*.cache
+*.ilk
+*.log
+*.lib
+*.sbr
+*.cs.ide
+[Dd]ebug*/
+[Rr]elease*/
+bin/
+obj/
+.vs/
+.vscode/
+*.ReSharper
+*.ReSharper.user
+[Tt]est[Rr]esult*
+
+#Ignore Rider/Idea files
+.idea/
diff --git a/Directory.Build.props b/Directory.Build.props
index bf61882..9e6caca 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -1,5 +1,19 @@
-
-
- true
-
-
+
+
+ true
+
+
+
+ $(NoWarn);CS0649
+ true
+
+
+
+ true
+ latest
+ Recommended
+ Default
+ true
+ true
+
+
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 6834dcb..e56b9af 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -1,14 +1,14 @@
-
-
-
- true
-
-
-
-
-
-
-
-
-
+
+
+
+ true
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
index 6666765..92e3431 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,9 +1,9 @@
-MIT License
-
-Copyright 2024 Rameel (https://github.com/rameel)
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+MIT License
+
+Copyright 2024 Rameel (https://github.com/rameel)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
index cfc1920..218b8d9 100644
--- a/README.md
+++ b/README.md
@@ -1,70 +1,70 @@
-# Ramstack.ExpressionParser
-[](https://nuget.org/packages/Ramstack.ExpressionParser)
-[](https://github.com/rameel/ramstack.expressionparser/blob/main/LICENSE)
-
-**Ramstack.ExpressionParser** is a flexible expression parser library for .NET,
-allowing dynamic evaluation and binding of expressions with context-aware support.
-
-## Getting Started
-
-To install the `Ramstack.ExpressionParser` [NuGet package](https://www.nuget.org/packages/Ramstack.ExpressionParser) to your project, run the following command:
-
-```shell
-dotnet add package Ramstack.ExpressionParser
-```
-
-## Usage
-
-```csharp
-var result = ExpressionParser.Parse("math.min(2 + 3, 2 * 3)");
-if (result.Success)
-{
- var lambda = Expression.Lambda>(result.Value);
- var fn = lambda.Compile();
-
- Console.WriteLine(fn());
-}
-```
-
-### Using `ContextAwareBinder`
-
-`ContextAwareBinder` allows binding expressions to a specific context,
-making it possible to reference its properties, fields, and methods directly within expressions.
-
-- The provided context acts as an implicit **this**, meaning you can access its members without prefixes.
-- Case-insensitive binding: identifiers in expressions are resolved in case-insensitive manner (e.g., level, Level, and LEVEL are treated the same).
-
-```csharp
-var parameter = Expression.Parameter(typeof(LogEvent), "logEvent");
-var binder = new ContextAwareBinder(parameter);
-
-var result = ExpressionParser.Parse("level == LogLevel.Error && string.IsNullOrEmpty(source)", binder);
-var predicate = Expression
- .Lambda>(result.Value, parameter)
- .Compile();
-```
-
-Here, `IsEnabled` evaluates the parsed expression against a `LogEvent` instance:
-```csharp
-public bool IsEnabled(LogEvent logEvent)
-{
- return _predicate(logEvent);
-}
-```
-
-This makes it easy to create dynamic, human-readable expressions for filtering or evaluating objects at runtime.
-
-## Supported Versions
-
-| | Version |
-|------|------------|
-| .NET | 6, 7, 8, 9 |
-
-## Contributions
-
-Bug reports and contributions are welcome.
-
-## License
-
-This package is released under the **MIT License**.
-See the [LICENSE](https://github.com/rameel/ramstack.expressionparser/blob/main/LICENSE) file for details.
+# Ramstack.ExpressionParser
+[](https://nuget.org/packages/Ramstack.ExpressionParser)
+[](https://github.com/rameel/ramstack.expressionparser/blob/main/LICENSE)
+
+**Ramstack.ExpressionParser** is a flexible expression parser library for .NET,
+allowing dynamic evaluation and binding of expressions with context-aware support.
+
+## Getting Started
+
+To install the `Ramstack.ExpressionParser` [NuGet package](https://www.nuget.org/packages/Ramstack.ExpressionParser) to your project, run the following command:
+
+```shell
+dotnet add package Ramstack.ExpressionParser
+```
+
+## Usage
+
+```csharp
+var result = ExpressionParser.Parse("math.min(2 + 3, 2 * 3)");
+if (result.Success)
+{
+ var lambda = Expression.Lambda>(result.Value);
+ var fn = lambda.Compile();
+
+ Console.WriteLine(fn());
+}
+```
+
+### Using `ContextAwareBinder`
+
+`ContextAwareBinder` allows binding expressions to a specific context,
+making it possible to reference its properties, fields, and methods directly within expressions.
+
+- The provided context acts as an implicit **this**, meaning you can access its members without prefixes.
+- Case-insensitive binding: identifiers in expressions are resolved in case-insensitive manner (e.g., level, Level, and LEVEL are treated the same).
+
+```csharp
+var parameter = Expression.Parameter(typeof(LogEvent), "logEvent");
+var binder = new ContextAwareBinder(parameter);
+
+var result = ExpressionParser.Parse("level == LogLevel.Error && string.IsNullOrEmpty(source)", binder);
+var predicate = Expression
+ .Lambda>(result.Value, parameter)
+ .Compile();
+```
+
+Here, `IsEnabled` evaluates the parsed expression against a `LogEvent` instance:
+```csharp
+public bool IsEnabled(LogEvent logEvent)
+{
+ return _predicate(logEvent);
+}
+```
+
+This makes it easy to create dynamic, human-readable expressions for filtering or evaluating objects at runtime.
+
+## Supported Versions
+
+| | Version |
+|------|------------|
+| .NET | 6, 7, 8, 9 |
+
+## Contributions
+
+Bug reports and contributions are welcome.
+
+## License
+
+This package is released under the **MIT License**.
+See the [LICENSE](https://github.com/rameel/ramstack.expressionparser/blob/main/LICENSE) file for details.
diff --git a/src/Ramstack.ExpressionParser/Binder.cs b/src/Ramstack.ExpressionParser/Binder.cs
index 21fc014..4e455bc 100644
--- a/src/Ramstack.ExpressionParser/Binder.cs
+++ b/src/Ramstack.ExpressionParser/Binder.cs
@@ -1,53 +1,53 @@
-using System.Linq.Expressions;
-using System.Reflection;
-
-namespace Ramstack.Parsing;
-
-///
-/// Provides an abstract base class for binding expressions.
-///
-public abstract class Binder
-{
- ///
- /// Gets the expression context associated with this binder instance.
- ///
- public virtual Expression? Context => null;
-
- ///
- /// Resolves the type associated with the specified name.
- ///
- /// The representing the name of the requested type.
- ///
- /// The instance corresponding to the specified
- /// if resolved successfully; otherwise, .
- ///
- public abstract Type? BindToType(Identifier name);
-
- ///
- /// Attempts to bind to a method based on the specified type, method name, and parameter types.
- ///
- /// The from which to select the method.
- /// The representing the name of the method to bind.
- /// An array of objects representing
- /// the types of arguments passed to the method.
- /// A indicating whether to match only static methods
- /// () or instance methods ().
- ///
- /// A representing the matching method if found; otherwise,
- /// if no suitable method is identified.
- ///
- public abstract MethodInfo? BindToMethod(Type? type, Identifier methodName, Type[] parameterTypes, bool isStatic);
-
- ///
- /// Attempts to bind to a member (field, property, or method) based on the specified type and member name.
- ///
- /// The from which to select the member.
- /// The representing the name of the member to bind.
- /// A indicating whether to match only static members
- /// () or instance members ().
- ///
- /// A representing the matching member if found; otherwise,
- /// if no suitable member is identified.
- ///
- public abstract MemberInfo? BindToMember(Type? type, Identifier memberName, bool isStatic);
-}
+using System.Linq.Expressions;
+using System.Reflection;
+
+namespace Ramstack.Parsing;
+
+///
+/// Provides an abstract base class for binding expressions.
+///
+public abstract class Binder
+{
+ ///
+ /// Gets the expression context associated with this binder instance.
+ ///
+ public virtual Expression? Context => null;
+
+ ///
+ /// Resolves the type associated with the specified name.
+ ///
+ /// The representing the name of the requested type.
+ ///
+ /// The instance corresponding to the specified
+ /// if resolved successfully; otherwise, .
+ ///
+ public abstract Type? BindToType(Identifier name);
+
+ ///
+ /// Attempts to bind to a method based on the specified type, method name, and parameter types.
+ ///
+ /// The from which to select the method.
+ /// The representing the name of the method to bind.
+ /// An array of objects representing
+ /// the types of arguments passed to the method.
+ /// A indicating whether to match only static methods
+ /// () or instance methods ().
+ ///
+ /// A representing the matching method if found; otherwise,
+ /// if no suitable method is identified.
+ ///
+ public abstract MethodInfo? BindToMethod(Type? type, Identifier methodName, Type[] parameterTypes, bool isStatic);
+
+ ///
+ /// Attempts to bind to a member (field, property, or method) based on the specified type and member name.
+ ///
+ /// The from which to select the member.
+ /// The representing the name of the member to bind.
+ /// A indicating whether to match only static members
+ /// () or instance members ().
+ ///
+ /// A representing the matching member if found; otherwise,
+ /// if no suitable member is identified.
+ ///
+ public abstract MemberInfo? BindToMember(Type? type, Identifier memberName, bool isStatic);
+}
diff --git a/src/Ramstack.ExpressionParser/ContextAwareBinder.cs b/src/Ramstack.ExpressionParser/ContextAwareBinder.cs
index a567a51..6edc1f6 100644
--- a/src/Ramstack.ExpressionParser/ContextAwareBinder.cs
+++ b/src/Ramstack.ExpressionParser/ContextAwareBinder.cs
@@ -1,55 +1,55 @@
-using System.Linq.Expressions;
-using System.Reflection;
-
-namespace Ramstack.Parsing;
-
-///
-/// Represents a binder that is aware of a specific context expression,
-/// allows resolution of members and methods based on the provided context.
-///
-public class ContextAwareBinder : DefaultBinder
-{
- private readonly Expression _context;
-
- ///
- [SuppressMessage("ReSharper", "ConvertToAutoProperty")]
- public override Expression Context => _context;
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The context expression used for binding operations.
- public ContextAwareBinder(Expression context)
- {
- _context = context ?? throw new ArgumentNullException(nameof(context));
-
- if (context.Type != typeof(object))
- RegisterType(context.Type, true);
- }
-
- ///
- public override MemberInfo? BindToMember(Type? type, Identifier memberName, bool isStatic)
- {
- if (type is null && isStatic)
- {
- var member = base.BindToMember(_context.Type, memberName, false);
- if (member is not null)
- return member;
- }
-
- return base.BindToMember(type, memberName, isStatic);
- }
-
- ///
- public override MethodInfo? BindToMethod(Type? type, Identifier methodName, Type[] parameterTypes, bool isStatic)
- {
- if (type is null && isStatic)
- {
- var method = base.BindToMethod(_context.Type, methodName, parameterTypes, false);
- if (method is not null)
- return method;
- }
-
- return base.BindToMethod(type, methodName, parameterTypes, isStatic);
- }
-}
+using System.Linq.Expressions;
+using System.Reflection;
+
+namespace Ramstack.Parsing;
+
+///
+/// Represents a binder that is aware of a specific context expression,
+/// allows resolution of members and methods based on the provided context.
+///
+public class ContextAwareBinder : DefaultBinder
+{
+ private readonly Expression _context;
+
+ ///
+ [SuppressMessage("ReSharper", "ConvertToAutoProperty")]
+ public override Expression Context => _context;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The context expression used for binding operations.
+ public ContextAwareBinder(Expression context)
+ {
+ _context = context ?? throw new ArgumentNullException(nameof(context));
+
+ if (context.Type != typeof(object))
+ RegisterType(context.Type, true);
+ }
+
+ ///
+ public override MemberInfo? BindToMember(Type? type, Identifier memberName, bool isStatic)
+ {
+ if (type is null && isStatic)
+ {
+ var member = base.BindToMember(_context.Type, memberName, false);
+ if (member is not null)
+ return member;
+ }
+
+ return base.BindToMember(type, memberName, isStatic);
+ }
+
+ ///
+ public override MethodInfo? BindToMethod(Type? type, Identifier methodName, Type[] parameterTypes, bool isStatic)
+ {
+ if (type is null && isStatic)
+ {
+ var method = base.BindToMethod(_context.Type, methodName, parameterTypes, false);
+ if (method is not null)
+ return method;
+ }
+
+ return base.BindToMethod(type, methodName, parameterTypes, isStatic);
+ }
+}
diff --git a/src/Ramstack.ExpressionParser/DefaultBinder.cs b/src/Ramstack.ExpressionParser/DefaultBinder.cs
index 0374e59..3508f54 100644
--- a/src/Ramstack.ExpressionParser/DefaultBinder.cs
+++ b/src/Ramstack.ExpressionParser/DefaultBinder.cs
@@ -1,168 +1,168 @@
-using System.Numerics;
-using System.Reflection;
-using System.Text.RegularExpressions;
-
-using Ramstack.Parsing.Internal;
-
-namespace Ramstack.Parsing;
-
-///
-/// Represents a default implementation of the class.
-///
-public class DefaultBinder : Binder
-{
- private static readonly Dictionary Empty = new();
-
- ///
- /// A predefined dictionary of safe common .NET types.
- ///
- private static readonly Dictionary PredefinedType = new(StringComparer.OrdinalIgnoreCase)
- {
- { "bool", (typeof(bool), false) },
- { "boolean", (typeof(bool), false) },
- { "byte", (typeof(byte), false) },
- { "sbyte", (typeof(sbyte), false) },
- { "short", (typeof(short), false) },
- { "ushort", (typeof(ushort), false) },
- { "int", (typeof(int), false) },
- { "uint", (typeof(uint), false) },
- { "long", (typeof(long), false) },
- { "ulong", (typeof(ulong), false) },
- { "int8", (typeof(sbyte), false) },
- { "uint8", (typeof(byte), false) },
- { "int16", (typeof(short), false) },
- { "uint16", (typeof(ushort), false) },
- { "int32", (typeof(int), false) },
- { "uint32", (typeof(uint), false) },
- { "int64", (typeof(long), false) },
- { "uint64", (typeof(ulong), false) },
- #if NET7_0_OR_GREATER
- { "int128", (typeof(Int128), false) },
- { "uint128", (typeof(UInt128), false) },
- #endif
- { "nint", (typeof(nint), false) },
- { "nuint", (typeof(nuint), false) },
- { "half", (typeof(Half), false) },
- { "float", (typeof(float), false) },
- { "single", (typeof(float), false) },
- { "double", (typeof(double), false) },
- { "decimal", (typeof(decimal), false) },
- { "bigint", (typeof(BigInteger), false) },
- { "biginteger", (typeof(BigInteger), false) },
- { "string", (typeof(string), true) },
- { "char", (typeof(char), false) },
- { "object", (typeof(object), true) },
- { nameof(Convert), (typeof(Convert), false) },
- { nameof(CultureInfo), (typeof(CultureInfo), true) },
- { nameof(DateTime), (typeof(DateTime), false) },
- { nameof(DateTimeOffset), (typeof(DateTimeOffset), false) },
- { nameof(DateOnly), (typeof(DateOnly), false) },
- { nameof(TimeOnly), (typeof(TimeOnly), false) },
- { nameof(DateTimeKind), (typeof(DateTimeKind), false) },
- { nameof(DayOfWeek), (typeof(DayOfWeek), false) },
- { nameof(Guid), (typeof(Guid), false) },
- { nameof(Math), (typeof(Math), true) },
- { nameof(MathF), (typeof(MathF), true) },
- { nameof(Regex), (typeof(Regex), false) },
- { nameof(RegexOptions), (typeof(RegexOptions), false) },
- { nameof(StringComparer), (typeof(StringComparer), false) },
- { nameof(StringComparison), (typeof(StringComparison), false) },
- { nameof(StringSplitOptions), (typeof(StringSplitOptions), true) },
- { nameof(TimeSpan), (typeof(TimeSpan), false) },
- { nameof(TimeZoneInfo), (typeof(TimeZoneInfo), false) },
- { nameof(Version), (typeof(Version), true) }
- };
-
- ///
- /// A dictionary of user-registered types.
- ///
- private Dictionary _types = Empty;
-
- ///
- /// Registers a custom type for use in binding operations, allowing it to be resolved by name.
- ///
- /// The to register for binding.
- /// A indicating whether the type's members
- /// should be imported directly into scope as static members (default is ).
- public void RegisterType(Type type, bool importAsStatic = false)
- {
- if (!PredefinedType.ContainsKey(type.Name))
- {
- if (ReferenceEquals(_types, Empty))
- _types = new Dictionary(StringComparer.OrdinalIgnoreCase);
-
- _types[type.Name] = (type, importAsStatic);
- }
- }
-
- ///
- public override Type? BindToType(Identifier typeName)
- {
- if (!PredefinedType.TryGetValue(typeName.Name, out var value))
- _types.TryGetValue(typeName.Name, out value);
-
- return value.type;
- }
-
- ///
- public override MethodInfo? BindToMethod(Type? type, Identifier methodName, Type[] parameterTypes, bool isStatic)
- {
- var q = type is not null
- ? GetMethods(type, methodName.Name, isStatic)
- : PredefinedType
- .Concat(_types)
- .Where(t => t.Value.isStatic)
- .SelectMany(t => GetMethods(t.Value.type, methodName.Name, isStatic));
-
- var methods = q.ToArray();
- if (methods.Length == 0)
- return null;
-
- var method = (MethodInfo?)MethodResolver.ResolveMethod(methods, parameterTypes);
- if (method is null)
- Error.AmbiguousMatch(methods);
-
- return method;
- }
-
- ///
- public override MemberInfo? BindToMember(Type? type, Identifier memberName, bool isStatic)
- {
- var bindingFlags = isStatic
- ? BindingFlags.Public | BindingFlags.Static
- : BindingFlags.Public | BindingFlags.Instance;
-
- var q = type?.GetMembers(bindingFlags)
- ?? PredefinedType
- .Concat(_types)
- .Where(t => t.Value.isStatic)
- .SelectMany(t => t.Value.type.GetMembers(bindingFlags));
-
- var candidates = q
- .Where(m =>
- m.Name.Equals(memberName.Name, StringComparison.OrdinalIgnoreCase)
- && m.MemberType is MemberTypes.Field or MemberTypes.Property)
- .ToArray();
-
- switch (candidates.Length)
- {
- case 0: return null;
- case 1: return candidates[0];
- }
-
- Error.AmbiguousMatch(candidates);
- return null;
- }
-
- private static IEnumerable GetMethods(Type type, string methodName, bool isStatic)
- {
- var bindingFlags = isStatic
- ? BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static
- : BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance;
-
- return type
- .GetMethods(bindingFlags)
- .Where(m => string.Equals(m.Name, methodName, StringComparison.OrdinalIgnoreCase))
- .Distinct();
- }
-}
+using System.Numerics;
+using System.Reflection;
+using System.Text.RegularExpressions;
+
+using Ramstack.Parsing.Internal;
+
+namespace Ramstack.Parsing;
+
+///
+/// Represents a default implementation of the class.
+///
+public class DefaultBinder : Binder
+{
+ private static readonly Dictionary Empty = new();
+
+ ///
+ /// A predefined dictionary of safe common .NET types.
+ ///
+ private static readonly Dictionary PredefinedType = new(StringComparer.OrdinalIgnoreCase)
+ {
+ { "bool", (typeof(bool), false) },
+ { "boolean", (typeof(bool), false) },
+ { "byte", (typeof(byte), false) },
+ { "sbyte", (typeof(sbyte), false) },
+ { "short", (typeof(short), false) },
+ { "ushort", (typeof(ushort), false) },
+ { "int", (typeof(int), false) },
+ { "uint", (typeof(uint), false) },
+ { "long", (typeof(long), false) },
+ { "ulong", (typeof(ulong), false) },
+ { "int8", (typeof(sbyte), false) },
+ { "uint8", (typeof(byte), false) },
+ { "int16", (typeof(short), false) },
+ { "uint16", (typeof(ushort), false) },
+ { "int32", (typeof(int), false) },
+ { "uint32", (typeof(uint), false) },
+ { "int64", (typeof(long), false) },
+ { "uint64", (typeof(ulong), false) },
+ #if NET7_0_OR_GREATER
+ { "int128", (typeof(Int128), false) },
+ { "uint128", (typeof(UInt128), false) },
+ #endif
+ { "nint", (typeof(nint), false) },
+ { "nuint", (typeof(nuint), false) },
+ { "half", (typeof(Half), false) },
+ { "float", (typeof(float), false) },
+ { "single", (typeof(float), false) },
+ { "double", (typeof(double), false) },
+ { "decimal", (typeof(decimal), false) },
+ { "bigint", (typeof(BigInteger), false) },
+ { "biginteger", (typeof(BigInteger), false) },
+ { "string", (typeof(string), true) },
+ { "char", (typeof(char), false) },
+ { "object", (typeof(object), true) },
+ { nameof(Convert), (typeof(Convert), false) },
+ { nameof(CultureInfo), (typeof(CultureInfo), true) },
+ { nameof(DateTime), (typeof(DateTime), false) },
+ { nameof(DateTimeOffset), (typeof(DateTimeOffset), false) },
+ { nameof(DateOnly), (typeof(DateOnly), false) },
+ { nameof(TimeOnly), (typeof(TimeOnly), false) },
+ { nameof(DateTimeKind), (typeof(DateTimeKind), false) },
+ { nameof(DayOfWeek), (typeof(DayOfWeek), false) },
+ { nameof(Guid), (typeof(Guid), false) },
+ { nameof(Math), (typeof(Math), true) },
+ { nameof(MathF), (typeof(MathF), true) },
+ { nameof(Regex), (typeof(Regex), false) },
+ { nameof(RegexOptions), (typeof(RegexOptions), false) },
+ { nameof(StringComparer), (typeof(StringComparer), false) },
+ { nameof(StringComparison), (typeof(StringComparison), false) },
+ { nameof(StringSplitOptions), (typeof(StringSplitOptions), true) },
+ { nameof(TimeSpan), (typeof(TimeSpan), false) },
+ { nameof(TimeZoneInfo), (typeof(TimeZoneInfo), false) },
+ { nameof(Version), (typeof(Version), true) }
+ };
+
+ ///
+ /// A dictionary of user-registered types.
+ ///
+ private Dictionary _types = Empty;
+
+ ///
+ /// Registers a custom type for use in binding operations, allowing it to be resolved by name.
+ ///
+ /// The to register for binding.
+ /// A indicating whether the type's members
+ /// should be imported directly into scope as static members (default is ).
+ public void RegisterType(Type type, bool importAsStatic = false)
+ {
+ if (!PredefinedType.ContainsKey(type.Name))
+ {
+ if (ReferenceEquals(_types, Empty))
+ _types = new Dictionary(StringComparer.OrdinalIgnoreCase);
+
+ _types[type.Name] = (type, importAsStatic);
+ }
+ }
+
+ ///
+ public override Type? BindToType(Identifier name)
+ {
+ if (!PredefinedType.TryGetValue(name.Name, out var value))
+ _types.TryGetValue(name.Name, out value);
+
+ return value.type;
+ }
+
+ ///
+ public override MethodInfo? BindToMethod(Type? type, Identifier methodName, Type[] parameterTypes, bool isStatic)
+ {
+ var q = type is not null
+ ? GetMethods(type, methodName.Name, isStatic)
+ : PredefinedType
+ .Concat(_types)
+ .Where(t => t.Value.isStatic)
+ .SelectMany(t => GetMethods(t.Value.type, methodName.Name, isStatic));
+
+ var methods = q.ToArray();
+ if (methods.Length == 0)
+ return null;
+
+ var method = (MethodInfo?)MethodResolver.ResolveMethod(methods, parameterTypes);
+ if (method is null)
+ Error.AmbiguousMatch(methods);
+
+ return method;
+ }
+
+ ///
+ public override MemberInfo? BindToMember(Type? type, Identifier memberName, bool isStatic)
+ {
+ var bindingFlags = isStatic
+ ? BindingFlags.Public | BindingFlags.Static
+ : BindingFlags.Public | BindingFlags.Instance;
+
+ var q = type?.GetMembers(bindingFlags)
+ ?? PredefinedType
+ .Concat(_types)
+ .Where(t => t.Value.isStatic)
+ .SelectMany(t => t.Value.type.GetMembers(bindingFlags));
+
+ var candidates = q
+ .Where(m =>
+ m.Name.Equals(memberName.Name, StringComparison.OrdinalIgnoreCase)
+ && m.MemberType is MemberTypes.Field or MemberTypes.Property)
+ .ToArray();
+
+ switch (candidates.Length)
+ {
+ case 0: return null;
+ case 1: return candidates[0];
+ }
+
+ Error.AmbiguousMatch(candidates);
+ return null;
+ }
+
+ private static IEnumerable GetMethods(Type type, string methodName, bool isStatic)
+ {
+ var bindingFlags = isStatic
+ ? BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static
+ : BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance;
+
+ return type
+ .GetMethods(bindingFlags)
+ .Where(m => string.Equals(m.Name, methodName, StringComparison.OrdinalIgnoreCase))
+ .Distinct();
+ }
+}
diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs
index aee65b2..d14d93b 100644
--- a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs
+++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs
@@ -1,318 +1,318 @@
-using System.Linq.Expressions;
-using System.Reflection;
-
-using Ramstack.Parsing.Internal;
-
-namespace Ramstack.Parsing;
-
-partial class ExpressionBuilder
-{
- private object ResolveSymbol(Expr.Reference expr)
- {
- var expression = TryResolveSymbol(expr);
- if (expression is null)
- Error.CannotResolveSymbol(expr.Value);
-
- return expression;
- }
-
- private object? TryResolveSymbol(Expr.Reference expr)
- {
- var name = expr.Value;
- var type = Binder.BindToType(name);
-
- if (type is not null)
- return type;
-
- var member = Binder.BindToMember(type: null, memberName: name, isStatic: true);
- if (member is null)
- return null;
-
- var context = member.IsStatic() ? null : Binder.Context;
-
- Debug.Assert(context is not null || member.IsStatic());
- Debug.Assert(context is null || !member.IsStatic());
-
- return Expression.MakeMemberAccess(context, member);
- }
-
- private static Expression? ApplyImplicitConversion(Expression expression, Type conversionType)
- {
- if (expression.Type == conversionType
- || expression.Type.IsClass && conversionType.IsAssignableFrom(expression.Type))
- return expression;
-
- if (TypeUtils.CanConvertPrimitive(expression.Type, conversionType))
- return Expression.Convert(expression, conversionType);
-
- var conversion = TypeUtils.FindConversionOperator(expression.Type, typeof(bool));
- if (conversion is not null)
- return Expression.Convert(expression, conversionType, conversion);
-
- return null;
- }
-
- private static List CreateInjectingArguments(MethodInfo method, IReadOnlyList args)
- {
- var parameters = method.GetParameters();
- var list = new List();
-
- for (var i = 0; i < args.Count; i++)
- {
- var arg = args[i];
- var parameter = parameters[i];
-
- if (parameter.GetCustomAttribute() is not null)
- {
- Debug.Assert(parameter.ParameterType.IsSZArray);
- Debug.Assert(parameter.ParameterType.GetElementType() is not null);
-
- var paramArray = new List();
- var paramArrayType = parameter.ParameterType.GetElementType()!;
-
- for (; i < args.Count; i++)
- paramArray.Add(
- Convert(args[i], paramArrayType));
-
- list.Add(
- Expression.NewArrayInit(
- paramArrayType,
- paramArray));
-
- break;
- }
-
- list.Add(Convert(arg, parameter.ParameterType));
- }
-
- return list;
-
- static Expression Convert(Expression argument, Type conversionType)
- {
- if (argument.Type == conversionType)
- return argument;
-
- if (argument.Type.IsClass)
- if (conversionType.IsAssignableFrom(argument.Type))
- return argument;
-
- return Expression.Convert(argument, conversionType);
- }
- }
-
- private static Expression ApplyBinaryExpression(Identifier op, Func apply, Expression lhs, Expression rhs)
- {
- var enumUnderlyingType = lhs.Type.IsEnum
- ? lhs.Type.GetEnumUnderlyingType()
- : rhs.Type.IsEnum
- ? rhs.Type.GetEnumUnderlyingType()
- : null;
-
- var enumType = lhs.Type.IsEnum
- ? lhs.Type
- : rhs.Type.IsEnum
- ? rhs.Type
- : null;
-
- if (enumUnderlyingType is not null)
- {
- if (lhs.Type != rhs.Type)
- if (lhs.Type.IsEnum ? enumUnderlyingType != rhs.Type : enumUnderlyingType != lhs.Type)
- Error.NonApplicableBinaryOperator(op, lhs.Type, rhs.Type);
-
- if (lhs.Type.IsEnum)
- lhs = Expression.Convert(lhs, enumUnderlyingType);
-
- if (rhs.Type.IsEnum)
- rhs = Expression.Convert(rhs, enumUnderlyingType);
- }
-
- if (enumType is null && op.Name is ">>" or ">>>" or "<<")
- {
- if (!TypeUtils.IsInteger(lhs.Type) && TypeUtils.IsInteger(rhs.Type))
- Error.NonApplicableBinaryOperator(op, lhs.Type, rhs.Type);
-
- if (rhs.Type == typeof(sbyte)
- || rhs.Type == typeof(byte)
- || rhs.Type == typeof(short)
- || rhs.Type == typeof(ushort))
- rhs = Expression.Convert(rhs, typeof(int));
-
- if (rhs.Type != typeof(int))
- Error.NonApplicableBinaryOperator(op, lhs.Type, rhs.Type);
-
- if (lhs.Type == typeof(sbyte)
- || lhs.Type == typeof(byte)
- || lhs.Type == typeof(short)
- || lhs.Type == typeof(ushort))
- lhs = Expression.Convert(lhs, typeof(int));
-
- if (op.Name == ">>>")
- {
- if (lhs.Type == typeof(int))
- return Expression.Convert(
- apply(Expression.Convert(lhs, typeof(uint)), rhs),
- typeof(int));
-
- if (lhs.Type == typeof(long))
- return Expression.Convert(
- apply(Expression.Convert(lhs, typeof(ulong)), rhs),
- typeof(long));
- }
-
- return apply(lhs, rhs);
- }
-
- ApplyBinaryNumericPromotions(op, ref lhs, ref rhs);
- var result = apply(lhs, rhs);
-
- if (enumType is not null)
- {
- switch (op.Name)
- {
- case "==":
- case "!=":
- case ">":
- case "<":
- case ">=":
- case "<=":
- return result;
-
- default:
- return Expression.Convert(result, enumType);
- }
- }
-
- return result;
- }
-
- private static void ApplyBinaryNumericPromotions(Identifier op, ref Expression lhs, ref Expression rhs)
- {
- //
- // 12.4.7.3 Binary numeric promotions
- // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#12473-binary-numeric-promotions
- //
- // Binary numeric promotion implicitly converts both operands to a common type which,
- // in case of the non-relational operators, also becomes the result type of the operation.
- // Binary numeric promotion consists of applying the following rules, in the order they appear here:
- //
- // * If either operand is of type decimal, the other operand is converted to type decimal,
- // or a binding-time error occurs if the other operand is of type float or double.
- // * Otherwise, if either operand is of type double, the other operand is converted to type double.
- // * Otherwise, if either operand is of type float, the other operand is converted to type float.
- // * Otherwise, if either operand is of type ulong, the other operand is converted to type ulong,
- // or a binding-time error occurs if the other operand is of type sbyte, short, int, or long.
- // * Otherwise, if either operand is of type long, the other operand is converted to type long.
- // * Otherwise, if either operand is of type uint and the other operand is of type sbyte, short, or int,
- // both operands are converted to type long.
- // * Otherwise, if either operand is of type uint, the other operand is converted to type uint.
- // * Otherwise, both operands are converted to type int.
-
- var lhsType = lhs.Type;
- var rhsType = rhs.Type;
-
- if (!TypeUtils.IsNumeric(lhsType)
- || !TypeUtils.IsNumeric(rhsType))
- return;
-
- var conversionTypes = new[]
- {
- typeof(decimal),
- typeof(double),
- typeof(float),
- typeof(ulong),
- typeof(long),
- typeof(uint),
- typeof(int)
- };
-
- // ReSharper disable once ForCanBeConvertedToForeach
- for (var i = 0; i < conversionTypes.Length; i++)
- {
- var conversionType = conversionTypes[i];
-
- if (conversionType != typeof(int))
- if (lhsType != conversionType && rhsType != conversionType)
- continue;
-
- if (conversionType == typeof(decimal))
- {
- //
- // If either operand is of type decimal, the other operand is converted to type decimal,
- // or a compile-time error occurs if the other operand is of type float or double.
- //
- if (lhsType == typeof(double)
- || lhsType == typeof(float)
- || rhsType == typeof(double)
- || rhsType == typeof(float))
- Error.NonApplicableBinaryOperator(op, lhsType, rhsType);
- }
- else if (conversionType == typeof(ulong))
- {
- //
- // If either operand is of type ulong, the other operand is converted to type ulong,
- // or a compile-time error occurs if the other operand is of type sbyte, short, int, or long.
- //
- if (lhsType == typeof(sbyte)
- || lhsType == typeof(short)
- || lhsType == typeof(int)
- || lhsType == typeof(long)
- || rhsType == typeof(sbyte)
- || rhsType == typeof(short)
- || rhsType == typeof(int)
- || rhsType == typeof(long))
- Error.NonApplicableBinaryOperator(op, lhsType, rhsType);
- }
- else if (conversionType == typeof(uint))
- {
- //
- // If either operand is of type uint and the other operand is of type sbyte, short, or int,
- // both operands are converted to type long.
- //
- if (lhsType == typeof(sbyte)
- || lhsType == typeof(short)
- || lhsType == typeof(int)
- || rhsType == typeof(sbyte)
- || rhsType == typeof(short)
- || rhsType == typeof(int))
- conversionType = typeof(long);
- }
-
- if (lhsType != conversionType)
- lhs = Expression.Convert(lhs, conversionType);
-
- if (rhsType != conversionType)
- rhs = Expression.Convert(rhs, conversionType);
-
- return;
- }
- }
-
- private static Func ResolveBinaryOperatorFactory(string @operator)
- {
- return @operator switch
- {
- "??" => Expression.Coalesce,
- "&&" => Expression.AndAlso,
- "||" => Expression.OrElse,
- "==" => Expression.Equal,
- "!=" => Expression.NotEqual,
- "<=" => Expression.LessThanOrEqual,
- ">=" => Expression.GreaterThanOrEqual,
- ">>" => Expression.RightShift,
- "<<" => Expression.LeftShift,
- ">>>" => Expression.RightShift,
- "<" => Expression.LessThan,
- ">" => Expression.GreaterThan,
- "&" => Expression.And,
- "|" => Expression.Or,
- "^" => Expression.ExclusiveOr,
- "+" => Expression.Add,
- "-" => Expression.Subtract,
- "*" => Expression.Multiply,
- "/" => Expression.Divide,
- "%" => Expression.Modulo,
- _ => throw new NotSupportedException($"Operator '{@operator}' is not supported.")
- };
- }
-}
+using System.Linq.Expressions;
+using System.Reflection;
+
+using Ramstack.Parsing.Internal;
+
+namespace Ramstack.Parsing;
+
+partial class ExpressionBuilder
+{
+ private object ResolveSymbol(Expr.Reference expr)
+ {
+ var expression = TryResolveSymbol(expr);
+ if (expression is null)
+ Error.CannotResolveSymbol(expr.Value);
+
+ return expression;
+ }
+
+ private object? TryResolveSymbol(Expr.Reference expr)
+ {
+ var name = expr.Value;
+ var type = Binder.BindToType(name);
+
+ if (type is not null)
+ return type;
+
+ var member = Binder.BindToMember(type: null, memberName: name, isStatic: true);
+ if (member is null)
+ return null;
+
+ var context = member.IsStatic() ? null : Binder.Context;
+
+ Debug.Assert(context is not null || member.IsStatic());
+ Debug.Assert(context is null || !member.IsStatic());
+
+ return Expression.MakeMemberAccess(context, member);
+ }
+
+ private static Expression? ApplyImplicitConversion(Expression expression, Type conversionType)
+ {
+ if (expression.Type == conversionType
+ || expression.Type.IsClass && conversionType.IsAssignableFrom(expression.Type))
+ return expression;
+
+ if (TypeUtils.CanConvertPrimitive(expression.Type, conversionType))
+ return Expression.Convert(expression, conversionType);
+
+ var conversion = TypeUtils.FindConversionOperator(expression.Type, typeof(bool));
+ if (conversion is not null)
+ return Expression.Convert(expression, conversionType, conversion);
+
+ return null;
+ }
+
+ private static List CreateInjectingArguments(MethodInfo method, IReadOnlyList args)
+ {
+ var parameters = method.GetParameters();
+ var list = new List();
+
+ for (var i = 0; i < args.Count; i++)
+ {
+ var arg = args[i];
+ var parameter = parameters[i];
+
+ if (parameter.GetCustomAttribute() is not null)
+ {
+ Debug.Assert(parameter.ParameterType.IsSZArray);
+ Debug.Assert(parameter.ParameterType.GetElementType() is not null);
+
+ var paramArray = new List();
+ var paramArrayType = parameter.ParameterType.GetElementType()!;
+
+ for (; i < args.Count; i++)
+ paramArray.Add(
+ Convert(args[i], paramArrayType));
+
+ list.Add(
+ Expression.NewArrayInit(
+ paramArrayType,
+ paramArray));
+
+ break;
+ }
+
+ list.Add(Convert(arg, parameter.ParameterType));
+ }
+
+ return list;
+
+ static Expression Convert(Expression argument, Type conversionType)
+ {
+ if (argument.Type == conversionType)
+ return argument;
+
+ if (argument.Type.IsClass)
+ if (conversionType.IsAssignableFrom(argument.Type))
+ return argument;
+
+ return Expression.Convert(argument, conversionType);
+ }
+ }
+
+ private static Expression ApplyBinaryExpression(Identifier op, Func apply, Expression lhs, Expression rhs)
+ {
+ var enumUnderlyingType = lhs.Type.IsEnum
+ ? lhs.Type.GetEnumUnderlyingType()
+ : rhs.Type.IsEnum
+ ? rhs.Type.GetEnumUnderlyingType()
+ : null;
+
+ var enumType = lhs.Type.IsEnum
+ ? lhs.Type
+ : rhs.Type.IsEnum
+ ? rhs.Type
+ : null;
+
+ if (enumUnderlyingType is not null)
+ {
+ if (lhs.Type != rhs.Type)
+ if (lhs.Type.IsEnum ? enumUnderlyingType != rhs.Type : enumUnderlyingType != lhs.Type)
+ Error.NonApplicableBinaryOperator(op, lhs.Type, rhs.Type);
+
+ if (lhs.Type.IsEnum)
+ lhs = Expression.Convert(lhs, enumUnderlyingType);
+
+ if (rhs.Type.IsEnum)
+ rhs = Expression.Convert(rhs, enumUnderlyingType);
+ }
+
+ if (enumType is null && op.Name is ">>" or ">>>" or "<<")
+ {
+ if (!TypeUtils.IsInteger(lhs.Type) && TypeUtils.IsInteger(rhs.Type))
+ Error.NonApplicableBinaryOperator(op, lhs.Type, rhs.Type);
+
+ if (rhs.Type == typeof(sbyte)
+ || rhs.Type == typeof(byte)
+ || rhs.Type == typeof(short)
+ || rhs.Type == typeof(ushort))
+ rhs = Expression.Convert(rhs, typeof(int));
+
+ if (rhs.Type != typeof(int))
+ Error.NonApplicableBinaryOperator(op, lhs.Type, rhs.Type);
+
+ if (lhs.Type == typeof(sbyte)
+ || lhs.Type == typeof(byte)
+ || lhs.Type == typeof(short)
+ || lhs.Type == typeof(ushort))
+ lhs = Expression.Convert(lhs, typeof(int));
+
+ if (op.Name == ">>>")
+ {
+ if (lhs.Type == typeof(int))
+ return Expression.Convert(
+ apply(Expression.Convert(lhs, typeof(uint)), rhs),
+ typeof(int));
+
+ if (lhs.Type == typeof(long))
+ return Expression.Convert(
+ apply(Expression.Convert(lhs, typeof(ulong)), rhs),
+ typeof(long));
+ }
+
+ return apply(lhs, rhs);
+ }
+
+ ApplyBinaryNumericPromotions(op, ref lhs, ref rhs);
+ var result = apply(lhs, rhs);
+
+ if (enumType is not null)
+ {
+ switch (op.Name)
+ {
+ case "==":
+ case "!=":
+ case ">":
+ case "<":
+ case ">=":
+ case "<=":
+ return result;
+
+ default:
+ return Expression.Convert(result, enumType);
+ }
+ }
+
+ return result;
+ }
+
+ private static void ApplyBinaryNumericPromotions(Identifier op, ref Expression lhs, ref Expression rhs)
+ {
+ //
+ // 12.4.7.3 Binary numeric promotions
+ // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#12473-binary-numeric-promotions
+ //
+ // Binary numeric promotion implicitly converts both operands to a common type which,
+ // in case of the non-relational operators, also becomes the result type of the operation.
+ // Binary numeric promotion consists of applying the following rules, in the order they appear here:
+ //
+ // * If either operand is of type decimal, the other operand is converted to type decimal,
+ // or a binding-time error occurs if the other operand is of type float or double.
+ // * Otherwise, if either operand is of type double, the other operand is converted to type double.
+ // * Otherwise, if either operand is of type float, the other operand is converted to type float.
+ // * Otherwise, if either operand is of type ulong, the other operand is converted to type ulong,
+ // or a binding-time error occurs if the other operand is of type sbyte, short, int, or long.
+ // * Otherwise, if either operand is of type long, the other operand is converted to type long.
+ // * Otherwise, if either operand is of type uint and the other operand is of type sbyte, short, or int,
+ // both operands are converted to type long.
+ // * Otherwise, if either operand is of type uint, the other operand is converted to type uint.
+ // * Otherwise, both operands are converted to type int.
+
+ var lhsType = lhs.Type;
+ var rhsType = rhs.Type;
+
+ if (!TypeUtils.IsNumeric(lhsType)
+ || !TypeUtils.IsNumeric(rhsType))
+ return;
+
+ var conversionTypes = new[]
+ {
+ typeof(decimal),
+ typeof(double),
+ typeof(float),
+ typeof(ulong),
+ typeof(long),
+ typeof(uint),
+ typeof(int)
+ };
+
+ // ReSharper disable once ForCanBeConvertedToForeach
+ for (var i = 0; i < conversionTypes.Length; i++)
+ {
+ var conversionType = conversionTypes[i];
+
+ if (conversionType != typeof(int))
+ if (lhsType != conversionType && rhsType != conversionType)
+ continue;
+
+ if (conversionType == typeof(decimal))
+ {
+ //
+ // If either operand is of type decimal, the other operand is converted to type decimal,
+ // or a compile-time error occurs if the other operand is of type float or double.
+ //
+ if (lhsType == typeof(double)
+ || lhsType == typeof(float)
+ || rhsType == typeof(double)
+ || rhsType == typeof(float))
+ Error.NonApplicableBinaryOperator(op, lhsType, rhsType);
+ }
+ else if (conversionType == typeof(ulong))
+ {
+ //
+ // If either operand is of type ulong, the other operand is converted to type ulong,
+ // or a compile-time error occurs if the other operand is of type sbyte, short, int, or long.
+ //
+ if (lhsType == typeof(sbyte)
+ || lhsType == typeof(short)
+ || lhsType == typeof(int)
+ || lhsType == typeof(long)
+ || rhsType == typeof(sbyte)
+ || rhsType == typeof(short)
+ || rhsType == typeof(int)
+ || rhsType == typeof(long))
+ Error.NonApplicableBinaryOperator(op, lhsType, rhsType);
+ }
+ else if (conversionType == typeof(uint))
+ {
+ //
+ // If either operand is of type uint and the other operand is of type sbyte, short, or int,
+ // both operands are converted to type long.
+ //
+ if (lhsType == typeof(sbyte)
+ || lhsType == typeof(short)
+ || lhsType == typeof(int)
+ || rhsType == typeof(sbyte)
+ || rhsType == typeof(short)
+ || rhsType == typeof(int))
+ conversionType = typeof(long);
+ }
+
+ if (lhsType != conversionType)
+ lhs = Expression.Convert(lhs, conversionType);
+
+ if (rhsType != conversionType)
+ rhs = Expression.Convert(rhs, conversionType);
+
+ return;
+ }
+ }
+
+ private static Func ResolveBinaryOperatorFactory(string @operator)
+ {
+ return @operator switch
+ {
+ "??" => Expression.Coalesce,
+ "&&" => Expression.AndAlso,
+ "||" => Expression.OrElse,
+ "==" => Expression.Equal,
+ "!=" => Expression.NotEqual,
+ "<=" => Expression.LessThanOrEqual,
+ ">=" => Expression.GreaterThanOrEqual,
+ ">>" => Expression.RightShift,
+ "<<" => Expression.LeftShift,
+ ">>>" => Expression.RightShift,
+ "<" => Expression.LessThan,
+ ">" => Expression.GreaterThan,
+ "&" => Expression.And,
+ "|" => Expression.Or,
+ "^" => Expression.ExclusiveOr,
+ "+" => Expression.Add,
+ "-" => Expression.Subtract,
+ "*" => Expression.Multiply,
+ "/" => Expression.Divide,
+ "%" => Expression.Modulo,
+ _ => throw new NotSupportedException($"Operator '{@operator}' is not supported.")
+ };
+ }
+}
diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs
index d099604..16760db 100644
--- a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs
+++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs
@@ -1,461 +1,461 @@
-using System.Linq.Expressions;
-using System.Reflection;
-
-using Ramstack.Parsing.Internal;
-
-namespace Ramstack.Parsing;
-
-///
-/// Builds the from the .
-///
-/// The binder instance.
-public partial class ExpressionBuilder(Binder binder) : ExprVisitor
-{
- ///
- /// Gets the binder instance.
- ///
- public Binder Binder { get; } = binder;
-
- ///
- protected internal override Expression VisitReference(Expr.Reference expr)
- {
- var symbol = ResolveSymbol(expr);
- if (symbol is Expression expression)
- return expression;
-
- Error.Throw($"'{expr}' is a type, which is not valid in the given context.");
- return null;
- }
-
- ///
- protected internal override Expression VisitLiteral(Expr.Literal expr) =>
- Expression.Constant(expr.Value);
-
- ///
- protected internal override Expression VisitBinary(Expr.Binary expr)
- {
- var lhs = Visit(expr.Left);
- var rhs = Visit(expr.Right);
-
- var lhsType = lhs.Type;
- var rhsType = rhs.Type;
-
- var factory = ResolveBinaryOperatorFactory(expr.Operator.Name);
-
- switch (expr.Operator.Name)
- {
- case "&&":
- case "||":
- lhs = ApplyImplicitConversion(lhs, typeof(bool));
- rhs = ApplyImplicitConversion(rhs, typeof(bool));
-
- if (lhs is null)
- Error.MissingImplicitConversion(lhsType, typeof(bool));
-
- if (rhs is null)
- Error.MissingImplicitConversion(rhsType, typeof(bool));
-
- break;
-
- case "??":
- if (lhsType.IsValueType && !lhsType.IsNullable())
- Error.NonApplicableBinaryOperator(expr.Operator, lhsType, rhsType);
-
- rhs = ApplyImplicitConversion(rhs, lhsType);
- if (rhs is null)
- Error.NonApplicableBinaryOperator(expr.Operator, lhsType, rhsType);
-
- break;
-
- case "+":
- if (lhsType != typeof(string) && rhsType != typeof(string))
- break;
-
- var arguments = new List();
- var argumentTypes = new List();
-
- Flatten(lhs);
- Flatten(rhs);
-
- var methods = typeof(string)
- .GetMethods(
- BindingFlags.Public | BindingFlags.Static)
- .Where(m =>
- m.Name == nameof(string.Concat)
- && (m.CallingConvention & CallingConventions.VarArgs) == 0)
- .Cast()
- .ToArray();
-
- if (argumentTypes.Any(t => t != typeof(string)))
- {
- for (var i = 0; i < arguments.Count; i++)
- {
- argumentTypes[i] = typeof(object);
- if (arguments[i].Type.IsValueType)
- arguments[i] = Expression.Convert(arguments[i], typeof(object));
- }
- }
-
- var cmi = (MethodInfo?)MethodResolver.ResolveMethod(methods, argumentTypes.ToArray())!;
- Debug.Assert(cmi is not null);
-
- var args = CreateInjectingArguments(cmi, arguments);
- return Expression.Call(null, cmi, args);
-
- void Flatten(Expression e)
- {
- if (e is MethodCallExpression call
- && call.Method.Name == nameof(string.Concat)
- && call.Method.DeclaringType == typeof(string))
- {
- var list = call.Arguments;
- if (list.Count != 1)
- {
- foreach (var item in list)
- {
- arguments.Add(item);
- argumentTypes.Add(item.Type);
- }
- }
- else
- {
- var array = (NewArrayExpression)list[0];
- foreach (var item in array.Expressions)
- {
- arguments.Add(item);
- argumentTypes.Add(item.Type);
- }
- }
- }
- else
- {
- arguments.Add(e);
- argumentTypes.Add(e.Type);
- }
- }
- }
-
- try
- {
- return ApplyBinaryExpression(expr.Operator, factory, lhs, rhs);
- }
- catch (Exception e) when (e is not ParseErrorException)
- {
- Error.NonApplicableBinaryOperator(expr.Operator, lhsType, rhsType);
- }
-
- return null!;
- }
-
- ///
- protected internal override Expression VisitIndex(Expr.Indexer expr)
- {
- var self = Visit(expr.Expression);
- var parameters = Visit(expr.Parameters).ToArray();
- var parameterTypes = parameters.Length != 0
- ? new Type[parameters.Length]
- : [];
-
- for (var i = 0; i < parameterTypes.Length; i++)
- parameterTypes[i] = parameters[i].Type;
-
- try
- {
- return self.Type.IsArray ? ProcessArray() : ProcessIndex();
- }
- catch (Exception e) when (e is not ParseErrorException)
- {
- Error.Throw(e.Message);
- }
-
- return null;
-
- Expression ProcessArray()
- {
- for (var i = 0; i < parameterTypes.Length; i++)
- {
- var argumentType = parameterTypes[i];
- if (argumentType != typeof(int))
- {
- if (!TypeUtils.CanConvertPrimitive(argumentType, typeof(int)) && TypeUtils.FindConversionOperator(argumentType, typeof(int)) is null)
- Error.MissingImplicitConversion(argumentType, typeof(int));
-
- parameters[i] = Expression.Convert(parameters[i], typeof(int));
- }
- }
-
- return Expression.ArrayAccess(self, parameters);
- }
-
- Expression ProcessIndex()
- {
- var methods = new List();
-
- foreach (var pi in self.Type.GetProperties())
- {
- var mi = pi.GetMethod;
- if (mi?.GetParameters().Length != 0)
- methods.Add(mi!);
- }
-
- if (methods.Count == 0)
- Error.NonIndexingType(self.Type);
-
- var method = (MethodInfo?)MethodResolver.ResolveMethod(methods.ToArray(), parameterTypes);
- if (method is null)
- {
- var list = self.Type.GetProperties().Where(p => p.GetMethod?.GetParameters().Length != 0);
- Error.AmbiguousMatch(list);
- }
-
- var injectingArguments = CreateInjectingArguments(method, parameters);
- return Expression.Call(self, method, injectingArguments);
- }
- }
-
- ///
- protected internal override Expression VisitCall(Expr.Call expr)
- {
- var arguments = Visit(expr.Parameters);
- var argumentTypes = arguments.Count != 0
- ? new Type[arguments.Count]
- : [];
-
- for (var i = 0; i < argumentTypes.Length; i++)
- argumentTypes[i] = arguments[i].Type;
-
- if (expr.Expression.Kind == ExprKind.MemberAccess)
- return ProcessMemberAccess((Expr.MemberAccess)expr.Expression);
-
- if (expr.Expression.Kind == ExprKind.Reference)
- return ProcessReference((Expr.Reference)expr.Expression);
-
- Error.MethodNameExpected(expr.Expression);
- return null;
-
- Expression Invoke(Expression? instance, MethodInfo? method)
- {
- Debug.Assert(instance is not null || method is not null);
-
- if (instance is not null)
- {
- Debug.Assert(method is null && typeof(Delegate).IsAssignableFrom(instance.Type)
- || method is not null && !typeof(Delegate).IsAssignableFrom(instance.Type));
-
- if (method is null)
- {
- const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
- method = instance.Type.GetMethod(nameof(Action.Invoke), bindingFlags);
- }
- }
-
- if (method is null)
- throw new InvalidOperationException(
- $"Unable to resolve a method: {expr}.");
-
- var injectingArguments = CreateInjectingArguments(method, arguments);
- return Expression.Call(instance, method, injectingArguments);
- }
-
- Expression ProcessMemberAccess(Expr.MemberAccess e)
- {
- var instance = e.Expression is Expr.Reference r
- ? ResolveSymbol(r)
- : Visit(e.Expression);
-
- if (e.Member is Expr.Reference m)
- {
- Debug.Assert(instance is Type or Expression);
-
- var type = instance as Type;
- var expression = instance as Expression;
-
- var memberInfo = Binder.BindToMember(type ?? expression?.Type, m.Value, expression is null);
- if (memberInfo is not null)
- {
- if (!typeof(Delegate).IsAssignableFrom(memberInfo.GetMemberType()))
- Error.NonInvocableMember(m);
-
- //
- // This shouldn't happen, but we'll crash if it does
- //
- if (expression is null)
- throw new InvalidOperationException(
- "Cannot access a member on a null reference.");
-
- expression = Expression.MakeMemberAccess(expression, memberInfo);
- return Invoke(expression, null);
- }
-
- var methodInfo = Binder.BindToMethod(type ?? expression?.Type, m.Value, argumentTypes, expression is null);
- if (methodInfo is null)
- Error.CannotResolveSymbol(m.Value);
-
- return Invoke(expression, methodInfo);
- }
-
- Error.MethodNameExpected(e.Member);
- return null;
- }
-
- Expression ProcessReference(Expr.Reference e)
- {
- var symbol = TryResolveSymbol(e);
- var type = symbol as Type;
-
- Debug.Assert(symbol is null or Type or Expression);
-
- if (symbol is Expression expression)
- {
- if (!typeof(Delegate).IsAssignableFrom(expression.Type))
- Error.NonInvocableMember(e);
-
- return Invoke(expression, null);
- }
-
- if (type is not null)
- Error.NonInvocableMember(e);
-
- var methodInfo = Binder.BindToMethod(null, e.Value, argumentTypes, true);
- if (methodInfo is null)
- Error.CannotResolveSymbol(e.Value);
-
- var instance = methodInfo.IsStatic ? null : Binder.Context;
- return Invoke(instance, methodInfo);
- }
- }
-
- ///
- protected internal override Expression VisitMemberAccess(Expr.MemberAccess expr)
- {
- var instance = expr.Expression is Expr.Reference r
- ? ResolveSymbol(r)
- : Visit(expr.Expression);
-
- if (expr.Member is Expr.Reference m)
- {
- var type = instance as Type;
- var expression = instance as Expression;
-
- Debug.Assert(type is not null || expression is not null);
-
- var memberInfo = Binder.BindToMember(type ?? expression!.Type, m.Value, expression is null);
-
- if (memberInfo is null)
- Error.CannotResolveSymbol(m.Value);
-
- if (memberInfo.DeclaringType == typeof(Array) && memberInfo.Name == nameof(Array.Length))
- {
- Debug.Assert(expression is not null);
- return Expression.ArrayLength(expression);
- }
-
- return Expression.MakeMemberAccess(expression, memberInfo);
- }
-
- Error.IdentifierExpected(expr.Member);
- return null;
- }
-
- ///
- protected internal override Expression VisitUnary(Expr.Unary expr)
- {
- var operand = Visit(expr.Operand);
-
- var operandType = operand.Type;
- var underlyingType = operandType.IsEnum
- ? operandType.GetEnumUnderlyingType()
- : operandType;
-
- if (operandType.IsEnum)
- operand = Expression.Convert(operand, underlyingType);
-
- switch (expr.UnaryType, operand)
- {
- case (UnaryType.Negate, ConstantExpression { Value: 0x80000000u }):
- return Expression.Constant(int.MinValue);
-
- case (UnaryType.Negate, ConstantExpression { Value: 0x8000000000000000ul }):
- return Expression.Constant(long.MinValue);
-
- case (UnaryType.Negate, _) when operand.Type == typeof(uint):
- return Expression.Convert(operand, typeof(long));
-
- case (not UnaryType.Convert, _) when underlyingType == typeof(byte):
- case (not UnaryType.Convert, _) when underlyingType == typeof(sbyte):
- case (not UnaryType.Convert, _) when underlyingType == typeof(short):
- case (not UnaryType.Convert, _) when underlyingType == typeof(ushort):
- operand = Expression.Convert(operand, typeof(int));
- break;
- }
-
- try
- {
- switch (expr.UnaryType)
- {
- case UnaryType.Not:
- return Expression.Not(operand);
-
- case UnaryType.Negate:
- return Expression.Negate(operand);
-
- case UnaryType.UnaryPlus:
- return Expression.UnaryPlus(operand);
-
- case UnaryType.OnesComplement:
- operand = Expression.OnesComplement(operand);
- return operandType.IsEnum
- ? Expression.Convert(operand, operandType)
- : operand;
-
- case UnaryType.Convert:
- var type = Binder.BindToType(expr.Operator);
- if (type is null)
- Error.CannotResolveSymbol(expr.Operator);
-
- if (operand.Type == type
- || operand.Type.IsClass && type.IsAssignableFrom(operand.Type))
- return operand;
-
- return Expression.Convert(operand, type);
-
- default:
- var message = $"The unary expression type '{expr.UnaryType}' is not supported.";
- throw new ArgumentOutOfRangeException(nameof(expr), message);
- }
- }
- catch (Exception e) when (e is not ParseErrorException)
- {
- Error.NonApplicableUnaryOperator(expr, operand.Type);
- }
-
- return null;
- }
-
- ///
- protected internal override Expression VisitConditional(Expr.Conditional expr)
- {
- var test = Visit(expr.Test);
- var ifTrue = Visit(expr.IfTrue);
- var ifFalse = Visit(expr.IfFalse);
-
- try
- {
- var condition = ApplyImplicitConversion(test, typeof(bool));
- if (condition is null)
- Error.MissingImplicitConversion(test.Type, typeof(bool));
-
- return Expression.Condition(condition, ifTrue, ifFalse);
- }
- catch (Exception e) when (e is not ParseErrorException)
- {
- Error.Throw(e.Message);
- }
-
- return null;
- }
-
- ///
- protected internal override Expression VisitParenthesized(Expr.Parenthesized expr) =>
- Visit(expr.Expression);
-}
+using System.Linq.Expressions;
+using System.Reflection;
+
+using Ramstack.Parsing.Internal;
+
+namespace Ramstack.Parsing;
+
+///
+/// Builds the from the .
+///
+/// The binder instance.
+public partial class ExpressionBuilder(Binder binder) : ExprVisitor
+{
+ ///
+ /// Gets the binder instance.
+ ///
+ public Binder Binder { get; } = binder;
+
+ ///
+ protected internal override Expression VisitReference(Expr.Reference expr)
+ {
+ var symbol = ResolveSymbol(expr);
+ if (symbol is Expression expression)
+ return expression;
+
+ Error.Throw($"'{expr}' is a type, which is not valid in the given context.");
+ return null;
+ }
+
+ ///
+ protected internal override Expression VisitLiteral(Expr.Literal expr) =>
+ Expression.Constant(expr.Value);
+
+ ///
+ protected internal override Expression VisitBinary(Expr.Binary expr)
+ {
+ var lhs = Visit(expr.Left);
+ var rhs = Visit(expr.Right);
+
+ var lhsType = lhs.Type;
+ var rhsType = rhs.Type;
+
+ var factory = ResolveBinaryOperatorFactory(expr.Operator.Name);
+
+ switch (expr.Operator.Name)
+ {
+ case "&&":
+ case "||":
+ lhs = ApplyImplicitConversion(lhs, typeof(bool));
+ rhs = ApplyImplicitConversion(rhs, typeof(bool));
+
+ if (lhs is null)
+ Error.MissingImplicitConversion(lhsType, typeof(bool));
+
+ if (rhs is null)
+ Error.MissingImplicitConversion(rhsType, typeof(bool));
+
+ break;
+
+ case "??":
+ if (lhsType.IsValueType && !lhsType.IsNullable())
+ Error.NonApplicableBinaryOperator(expr.Operator, lhsType, rhsType);
+
+ rhs = ApplyImplicitConversion(rhs, lhsType);
+ if (rhs is null)
+ Error.NonApplicableBinaryOperator(expr.Operator, lhsType, rhsType);
+
+ break;
+
+ case "+":
+ if (lhsType != typeof(string) && rhsType != typeof(string))
+ break;
+
+ var arguments = new List();
+ var argumentTypes = new List();
+
+ Flatten(lhs);
+ Flatten(rhs);
+
+ var methods = typeof(string)
+ .GetMethods(
+ BindingFlags.Public | BindingFlags.Static)
+ .Where(m =>
+ m.Name == nameof(string.Concat)
+ && (m.CallingConvention & CallingConventions.VarArgs) == 0)
+ .Cast()
+ .ToArray();
+
+ if (argumentTypes.Any(t => t != typeof(string)))
+ {
+ for (var i = 0; i < arguments.Count; i++)
+ {
+ argumentTypes[i] = typeof(object);
+ if (arguments[i].Type.IsValueType)
+ arguments[i] = Expression.Convert(arguments[i], typeof(object));
+ }
+ }
+
+ var cmi = (MethodInfo?)MethodResolver.ResolveMethod(methods, argumentTypes.ToArray())!;
+ Debug.Assert(cmi is not null);
+
+ var args = CreateInjectingArguments(cmi, arguments);
+ return Expression.Call(null, cmi, args);
+
+ void Flatten(Expression e)
+ {
+ if (e is MethodCallExpression call
+ && call.Method.Name == nameof(string.Concat)
+ && call.Method.DeclaringType == typeof(string))
+ {
+ var list = call.Arguments;
+ if (list.Count != 1)
+ {
+ foreach (var item in list)
+ {
+ arguments.Add(item);
+ argumentTypes.Add(item.Type);
+ }
+ }
+ else
+ {
+ var array = (NewArrayExpression)list[0];
+ foreach (var item in array.Expressions)
+ {
+ arguments.Add(item);
+ argumentTypes.Add(item.Type);
+ }
+ }
+ }
+ else
+ {
+ arguments.Add(e);
+ argumentTypes.Add(e.Type);
+ }
+ }
+ }
+
+ try
+ {
+ return ApplyBinaryExpression(expr.Operator, factory, lhs, rhs);
+ }
+ catch (Exception e) when (e is not ParseErrorException)
+ {
+ Error.NonApplicableBinaryOperator(expr.Operator, lhsType, rhsType);
+ }
+
+ return null!;
+ }
+
+ ///
+ protected internal override Expression VisitIndex(Expr.Indexer expr)
+ {
+ var self = Visit(expr.Expression);
+ var parameters = Visit(expr.Parameters).ToArray();
+ var parameterTypes = parameters.Length != 0
+ ? new Type[parameters.Length]
+ : [];
+
+ for (var i = 0; i < parameterTypes.Length; i++)
+ parameterTypes[i] = parameters[i].Type;
+
+ try
+ {
+ return self.Type.IsArray ? ProcessArray() : ProcessIndex();
+ }
+ catch (Exception e) when (e is not ParseErrorException)
+ {
+ Error.Throw(e.Message);
+ }
+
+ return null;
+
+ Expression ProcessArray()
+ {
+ for (var i = 0; i < parameterTypes.Length; i++)
+ {
+ var argumentType = parameterTypes[i];
+ if (argumentType != typeof(int))
+ {
+ if (!TypeUtils.CanConvertPrimitive(argumentType, typeof(int)) && TypeUtils.FindConversionOperator(argumentType, typeof(int)) is null)
+ Error.MissingImplicitConversion(argumentType, typeof(int));
+
+ parameters[i] = Expression.Convert(parameters[i], typeof(int));
+ }
+ }
+
+ return Expression.ArrayAccess(self, parameters);
+ }
+
+ Expression ProcessIndex()
+ {
+ var methods = new List();
+
+ foreach (var pi in self.Type.GetProperties())
+ {
+ var mi = pi.GetMethod;
+ if (mi?.GetParameters().Length != 0)
+ methods.Add(mi!);
+ }
+
+ if (methods.Count == 0)
+ Error.NonIndexingType(self.Type);
+
+ var method = (MethodInfo?)MethodResolver.ResolveMethod(methods.ToArray(), parameterTypes);
+ if (method is null)
+ {
+ var list = self.Type.GetProperties().Where(p => p.GetMethod?.GetParameters().Length != 0);
+ Error.AmbiguousMatch(list);
+ }
+
+ var injectingArguments = CreateInjectingArguments(method, parameters);
+ return Expression.Call(self, method, injectingArguments);
+ }
+ }
+
+ ///
+ protected internal override Expression VisitCall(Expr.Call expr)
+ {
+ var arguments = Visit(expr.Parameters);
+ var argumentTypes = arguments.Count != 0
+ ? new Type[arguments.Count]
+ : [];
+
+ for (var i = 0; i < argumentTypes.Length; i++)
+ argumentTypes[i] = arguments[i].Type;
+
+ if (expr.Expression.Kind == ExprKind.MemberAccess)
+ return ProcessMemberAccess((Expr.MemberAccess)expr.Expression);
+
+ if (expr.Expression.Kind == ExprKind.Reference)
+ return ProcessReference((Expr.Reference)expr.Expression);
+
+ Error.MethodNameExpected(expr.Expression);
+ return null;
+
+ Expression Invoke(Expression? instance, MethodInfo? method)
+ {
+ Debug.Assert(instance is not null || method is not null);
+
+ if (instance is not null)
+ {
+ Debug.Assert(method is null && typeof(Delegate).IsAssignableFrom(instance.Type)
+ || method is not null && !typeof(Delegate).IsAssignableFrom(instance.Type));
+
+ if (method is null)
+ {
+ const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
+ method = instance.Type.GetMethod(nameof(Action.Invoke), bindingFlags);
+ }
+ }
+
+ if (method is null)
+ throw new InvalidOperationException(
+ $"Unable to resolve a method: {expr}.");
+
+ var injectingArguments = CreateInjectingArguments(method, arguments);
+ return Expression.Call(instance, method, injectingArguments);
+ }
+
+ Expression ProcessMemberAccess(Expr.MemberAccess e)
+ {
+ var instance = e.Expression is Expr.Reference r
+ ? ResolveSymbol(r)
+ : Visit(e.Expression);
+
+ if (e.Member is Expr.Reference m)
+ {
+ Debug.Assert(instance is Type or Expression);
+
+ var type = instance as Type;
+ var expression = instance as Expression;
+
+ var memberInfo = Binder.BindToMember(type ?? expression?.Type, m.Value, expression is null);
+ if (memberInfo is not null)
+ {
+ if (!typeof(Delegate).IsAssignableFrom(memberInfo.GetMemberType()))
+ Error.NonInvocableMember(m);
+
+ //
+ // This shouldn't happen, but we'll crash if it does
+ //
+ if (expression is null)
+ throw new InvalidOperationException(
+ "Cannot access a member on a null reference.");
+
+ expression = Expression.MakeMemberAccess(expression, memberInfo);
+ return Invoke(expression, null);
+ }
+
+ var methodInfo = Binder.BindToMethod(type ?? expression?.Type, m.Value, argumentTypes, expression is null);
+ if (methodInfo is null)
+ Error.CannotResolveSymbol(m.Value);
+
+ return Invoke(expression, methodInfo);
+ }
+
+ Error.MethodNameExpected(e.Member);
+ return null;
+ }
+
+ Expression ProcessReference(Expr.Reference e)
+ {
+ var symbol = TryResolveSymbol(e);
+ var type = symbol as Type;
+
+ Debug.Assert(symbol is null or Type or Expression);
+
+ if (symbol is Expression expression)
+ {
+ if (!typeof(Delegate).IsAssignableFrom(expression.Type))
+ Error.NonInvocableMember(e);
+
+ return Invoke(expression, null);
+ }
+
+ if (type is not null)
+ Error.NonInvocableMember(e);
+
+ var methodInfo = Binder.BindToMethod(null, e.Value, argumentTypes, true);
+ if (methodInfo is null)
+ Error.CannotResolveSymbol(e.Value);
+
+ var instance = methodInfo.IsStatic ? null : Binder.Context;
+ return Invoke(instance, methodInfo);
+ }
+ }
+
+ ///
+ protected internal override Expression VisitMemberAccess(Expr.MemberAccess expr)
+ {
+ var instance = expr.Expression is Expr.Reference r
+ ? ResolveSymbol(r)
+ : Visit(expr.Expression);
+
+ if (expr.Member is Expr.Reference m)
+ {
+ var type = instance as Type;
+ var expression = instance as Expression;
+
+ Debug.Assert(type is not null || expression is not null);
+
+ var memberInfo = Binder.BindToMember(type ?? expression!.Type, m.Value, expression is null);
+
+ if (memberInfo is null)
+ Error.CannotResolveSymbol(m.Value);
+
+ if (memberInfo.DeclaringType == typeof(Array) && memberInfo.Name == nameof(Array.Length))
+ {
+ Debug.Assert(expression is not null);
+ return Expression.ArrayLength(expression);
+ }
+
+ return Expression.MakeMemberAccess(expression, memberInfo);
+ }
+
+ Error.IdentifierExpected(expr.Member);
+ return null;
+ }
+
+ ///
+ protected internal override Expression VisitUnary(Expr.Unary expr)
+ {
+ var operand = Visit(expr.Operand);
+
+ var operandType = operand.Type;
+ var underlyingType = operandType.IsEnum
+ ? operandType.GetEnumUnderlyingType()
+ : operandType;
+
+ if (operandType.IsEnum)
+ operand = Expression.Convert(operand, underlyingType);
+
+ switch (expr.UnaryType, operand)
+ {
+ case (UnaryType.Negate, ConstantExpression { Value: 0x80000000u }):
+ return Expression.Constant(int.MinValue);
+
+ case (UnaryType.Negate, ConstantExpression { Value: 0x8000000000000000ul }):
+ return Expression.Constant(long.MinValue);
+
+ case (UnaryType.Negate, _) when operand.Type == typeof(uint):
+ return Expression.Convert(operand, typeof(long));
+
+ case (not UnaryType.Convert, _) when underlyingType == typeof(byte):
+ case (not UnaryType.Convert, _) when underlyingType == typeof(sbyte):
+ case (not UnaryType.Convert, _) when underlyingType == typeof(short):
+ case (not UnaryType.Convert, _) when underlyingType == typeof(ushort):
+ operand = Expression.Convert(operand, typeof(int));
+ break;
+ }
+
+ try
+ {
+ switch (expr.UnaryType)
+ {
+ case UnaryType.Not:
+ return Expression.Not(operand);
+
+ case UnaryType.Negate:
+ return Expression.Negate(operand);
+
+ case UnaryType.UnaryPlus:
+ return Expression.UnaryPlus(operand);
+
+ case UnaryType.OnesComplement:
+ operand = Expression.OnesComplement(operand);
+ return operandType.IsEnum
+ ? Expression.Convert(operand, operandType)
+ : operand;
+
+ case UnaryType.Convert:
+ var type = Binder.BindToType(expr.Operator);
+ if (type is null)
+ Error.CannotResolveSymbol(expr.Operator);
+
+ if (operand.Type == type
+ || operand.Type.IsClass && type.IsAssignableFrom(operand.Type))
+ return operand;
+
+ return Expression.Convert(operand, type);
+
+ default:
+ var message = $"The unary expression type '{expr.UnaryType}' is not supported.";
+ throw new ArgumentOutOfRangeException(nameof(expr), message);
+ }
+ }
+ catch (Exception e) when (e is not ParseErrorException)
+ {
+ Error.NonApplicableUnaryOperator(expr, operand.Type);
+ }
+
+ return null;
+ }
+
+ ///
+ protected internal override Expression VisitConditional(Expr.Conditional expr)
+ {
+ var test = Visit(expr.Test);
+ var ifTrue = Visit(expr.IfTrue);
+ var ifFalse = Visit(expr.IfFalse);
+
+ try
+ {
+ var condition = ApplyImplicitConversion(test, typeof(bool));
+ if (condition is null)
+ Error.MissingImplicitConversion(test.Type, typeof(bool));
+
+ return Expression.Condition(condition, ifTrue, ifFalse);
+ }
+ catch (Exception e) when (e is not ParseErrorException)
+ {
+ Error.Throw(e.Message);
+ }
+
+ return null;
+ }
+
+ ///
+ protected internal override Expression VisitParenthesized(Expr.Parenthesized expr) =>
+ Visit(expr.Expression);
+}
diff --git a/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs b/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs
index 2376107..9c71eee 100644
--- a/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs
+++ b/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs
@@ -1,270 +1,270 @@
-using Ramstack.Parsing.Parsers;
-
-using static Ramstack.Parsing.Parser;
-
-namespace Ramstack.Parsing;
-
-partial class ExpressionParser
-{
- ///
- /// Gets the sub-expression parser, which serves as the base parser for expressions.
- ///
- public static Parser Subparser { get; } = CreateParser();
-
- ///
- /// Gets the main expression parser, which ensures that the entire input is consumed.
- ///
- public static Parser Parser { get; } = Subparser.ThenIgnore(Eof);
-
- [SuppressMessage("ReSharper", "InconsistentNaming")]
- private static Parser CreateParser()
- {
- var identifier_start =
- Choice(
- Character.Letter,
- L('_')).Void();
-
- var identifier_body =
- Choice(
- Character.LetterOrDigit,
- L('_')).Void();
-
- var identifier =
- Seq(
- identifier_start,
- identifier_body.Many()
- ).Map(m => new Identifier(m.ToString())).As("identifier");
-
- var keyword =
- Seq(
- OneOf("true", "false", "null"),
- Not(identifier_body)
- ).Void();
-
- var number_literal =
- ConstantNumberParser
- .NumericLiteral
- .Do(Expr (v) => new Expr.Literal(v));
-
- var string_literal =
- Literal
- .DoubleQuotedString
- .Do(Expr (v) => new Expr.Literal(v));
-
- var char_literal =
- Literal
- .QuotedCharacter
- .Do(Expr (v) => new Expr.Literal(v));
-
- var boolean_literal =
- OneOf("true", "false")
- .ThenIgnore(Not(identifier_body))
- .Do(Expr (v) => new Expr.Literal(v == "true"));
-
- var null_literal =
- L("null")
- .ThenIgnore(Not(identifier_body))
- .Do(Expr (_) => new Expr.Literal(null));
-
- var prefix_operator =
- OneOf("+-!~")
- .ThenIgnore(S)
- .Do(v => new Identifier(v.ToString()));
-
- var expression =
- Deferred();
-
- var literal_expression =
- Choice(
- number_literal,
- string_literal,
- char_literal,
- boolean_literal,
- null_literal
- ).ThenIgnore(S);
-
- var identifier_expression =
- identifier
- .Between(Not(keyword), S)
- .Do(Expr (v) => new Expr.Reference(v));
-
- var parenthesis_expression =
- expression
- .Between(
- Seq(L('('), S),
- Seq(L(')'), S))
- .Do(Expr (e) => new Expr.Parenthesized(e));
-
- var primary_expression =
- Choice(
- literal_expression,
- identifier_expression,
- parenthesis_expression);
-
- var expression_list =
- expression
- .Separated(
- Seq(L(','), S)).As("expression_list");
-
- var call_expression =
- expression_list
- .Between(
- Seq(L('('), S),
- Seq(L(')'), S)).Do(list => (list, indexer: false));
-
- var indexer_expression =
- expression_list
- .Between(
- Seq(L('['), S),
- Seq(L(']'), S)).Do(list => (list, indexer: true));
-
- var call_or_indexer_expression =
- Seq(
- primary_expression,
- Choice(
- call_expression,
- indexer_expression
- ).Many()
- ).Do((expr, list) =>
- {
- foreach (var (parameters, indexer) in list)
- expr = indexer
- ? new Expr.Indexer(expr, parameters)
- : new Expr.Call(expr, parameters);
- return expr;
- });
-
- var member_expression =
- call_or_indexer_expression.Fold(Seq(L('.'), S, Not(keyword)), (lhs, rhs, _) =>
- {
- return HijackMemberExpression(lhs, rhs);
-
- static Expr HijackMemberExpression(Expr result, Expr value)
- {
- return value switch
- {
- Expr.Call call => new Expr.Call(HijackMemberExpression(result, call.Expression), call.Parameters),
- Expr.Indexer indexer => new Expr.Indexer(HijackMemberExpression(result, indexer.Expression), indexer.Parameters),
- _ => new Expr.MemberAccess(result, value)
- };
- }
- });
-
- var cast_expression =
- Seq(
- member_expression,
- identifier.Between(
- Seq(L(':'), S),
- S).Many()
- ).Do((expr, ids) =>
- {
- foreach (var id in ids)
- expr = new Expr.Unary(id, UnaryType.Convert, expr);
-
- return expr;
- });
-
- var prefix_expression =
- Seq(
- prefix_operator.Many(),
- cast_expression
- ).Do((operators, expr) =>
- {
- for (var i = operators.Count - 1; i >= 0; i--)
- {
- var type = operators[i].Name[0] switch
- {
- '+' => UnaryType.UnaryPlus,
- '!' => UnaryType.Not,
- '~' => UnaryType.OnesComplement,
- _ => UnaryType.Negate
- };
-
- expr = new Expr.Unary(operators[i], type, expr);
- }
-
- return expr;
- });
-
- var mul_expression =
- prefix_expression.Fold(
- OneOf("*/%").ThenIgnore(S).Do(CreateIdentifier),
- (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
-
- var add_expression =
- mul_expression.Fold(
- OneOf("+-").ThenIgnore(S).Do(CreateIdentifier),
- (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
-
- var shift_expression =
- add_expression.Fold(
- OneOf(["<<", ">>", ">>>"]).ThenIgnore(S).Do(CreateIdentifier),
- (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
-
- var relational_expression =
- shift_expression.Fold(
- OneOf(["<", ">", "<=", ">="]).ThenIgnore(S).Do(CreateIdentifier),
- (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
-
- var equality_expression =
- relational_expression.Fold(
- OneOf("==", "!=").ThenIgnore(S).Do(CreateIdentifier),
- (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
-
- var bitwise_and_expression =
- equality_expression.Fold(
- L('&').ThenIgnore(S).Do(CreateIdentifier),
- (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
-
- var bitwise_xor_expression =
- bitwise_and_expression.Fold(
- L('^').ThenIgnore(S).Do(CreateIdentifier),
- (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
-
- var bitwise_or_expression =
- bitwise_xor_expression.Fold(
- L('|').ThenIgnore(S).Do(CreateIdentifier),
- (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
-
- var logical_and_expression =
- bitwise_or_expression.Fold(
- L("&&").ThenIgnore(S).Do(CreateIdentifier),
- (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
-
- var logical_or_expression =
- logical_and_expression.Fold(
- L("||").ThenIgnore(S).Do(CreateIdentifier),
- (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
-
- var null_coalesce_expression =
- logical_or_expression.FoldR(
- L("??").ThenIgnore(S).Do(CreateIdentifier),
- (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
-
- var conditional_expression = Deferred();
- conditional_expression.Parser =
- Seq(
- null_coalesce_expression,
- Seq(
- L('?'), S,
- expression,
- L(':').Or(Fail("Expected ':'")), S,
- conditional_expression.Or(Fail("Expected expression"))
- ).Optional()
- ).Do(Expr (Expr condition, OptionalValue<(char, Unit, Expr @true, char, Unit, Expr @false)> optional) =>
- optional.HasValue
- ? new Expr.Conditional(condition, optional.Value.@true, optional.Value.@false)
- : condition);
-
- expression.Parser =
- conditional_expression;
-
- return S.Then(expression);
- }
-
- private static Identifier CreateIdentifier(string v) =>
- new Identifier(v);
-
- private static Identifier CreateIdentifier(char v) =>
- new Identifier(v.ToString());
-}
+using Ramstack.Parsing.Parsers;
+
+using static Ramstack.Parsing.Parser;
+
+namespace Ramstack.Parsing;
+
+partial class ExpressionParser
+{
+ ///
+ /// Gets the sub-expression parser, which serves as the base parser for expressions.
+ ///
+ public static Parser Subparser { get; } = CreateParser();
+
+ ///
+ /// Gets the main expression parser, which ensures that the entire input is consumed.
+ ///
+ public static Parser Parser { get; } = Subparser.ThenIgnore(Eof);
+
+ [SuppressMessage("ReSharper", "InconsistentNaming")]
+ private static Parser CreateParser()
+ {
+ var identifier_start =
+ Choice(
+ Character.Letter,
+ L('_')).Void();
+
+ var identifier_body =
+ Choice(
+ Character.LetterOrDigit,
+ L('_')).Void();
+
+ var identifier =
+ Seq(
+ identifier_start,
+ identifier_body.Many()
+ ).Map(m => new Identifier(m.ToString())).As("identifier");
+
+ var keyword =
+ Seq(
+ OneOf("true", "false", "null"),
+ Not(identifier_body)
+ ).Void();
+
+ var number_literal =
+ ConstantNumberParser
+ .NumericLiteral
+ .Do(Expr (v) => new Expr.Literal(v));
+
+ var string_literal =
+ Literal
+ .DoubleQuotedString
+ .Do(Expr (v) => new Expr.Literal(v));
+
+ var char_literal =
+ Literal
+ .QuotedCharacter
+ .Do(Expr (v) => new Expr.Literal(v));
+
+ var boolean_literal =
+ OneOf("true", "false")
+ .ThenIgnore(Not(identifier_body))
+ .Do(Expr (v) => new Expr.Literal(v == "true"));
+
+ var null_literal =
+ L("null")
+ .ThenIgnore(Not(identifier_body))
+ .Do(Expr (_) => new Expr.Literal(null));
+
+ var prefix_operator =
+ OneOf("+-!~")
+ .ThenIgnore(S)
+ .Do(v => new Identifier(v.ToString()));
+
+ var expression =
+ Deferred();
+
+ var literal_expression =
+ Choice(
+ number_literal,
+ string_literal,
+ char_literal,
+ boolean_literal,
+ null_literal
+ ).ThenIgnore(S);
+
+ var identifier_expression =
+ identifier
+ .Between(Not(keyword), S)
+ .Do(Expr (v) => new Expr.Reference(v));
+
+ var parenthesis_expression =
+ expression
+ .Between(
+ Seq(L('('), S),
+ Seq(L(')'), S))
+ .Do(Expr (e) => new Expr.Parenthesized(e));
+
+ var primary_expression =
+ Choice(
+ literal_expression,
+ identifier_expression,
+ parenthesis_expression);
+
+ var expression_list =
+ expression
+ .Separated(
+ Seq(L(','), S)).As("expression_list");
+
+ var call_expression =
+ expression_list
+ .Between(
+ Seq(L('('), S),
+ Seq(L(')'), S)).Do(list => (list, indexer: false));
+
+ var indexer_expression =
+ expression_list
+ .Between(
+ Seq(L('['), S),
+ Seq(L(']'), S)).Do(list => (list, indexer: true));
+
+ var call_or_indexer_expression =
+ Seq(
+ primary_expression,
+ Choice(
+ call_expression,
+ indexer_expression
+ ).Many()
+ ).Do((expr, list) =>
+ {
+ foreach (var (parameters, indexer) in list)
+ expr = indexer
+ ? new Expr.Indexer(expr, parameters)
+ : new Expr.Call(expr, parameters);
+ return expr;
+ });
+
+ var member_expression =
+ call_or_indexer_expression.Fold(Seq(L('.'), S, Not(keyword)), (lhs, rhs, _) =>
+ {
+ return HijackMemberExpression(lhs, rhs);
+
+ static Expr HijackMemberExpression(Expr result, Expr value)
+ {
+ return value switch
+ {
+ Expr.Call call => new Expr.Call(HijackMemberExpression(result, call.Expression), call.Parameters),
+ Expr.Indexer indexer => new Expr.Indexer(HijackMemberExpression(result, indexer.Expression), indexer.Parameters),
+ _ => new Expr.MemberAccess(result, value)
+ };
+ }
+ });
+
+ var cast_expression =
+ Seq(
+ member_expression,
+ identifier.Between(
+ Seq(L(':'), S),
+ S).Many()
+ ).Do((expr, ids) =>
+ {
+ foreach (var id in ids)
+ expr = new Expr.Unary(id, UnaryType.Convert, expr);
+
+ return expr;
+ });
+
+ var prefix_expression =
+ Seq(
+ prefix_operator.Many(),
+ cast_expression
+ ).Do((operators, expr) =>
+ {
+ for (var i = operators.Count - 1; i >= 0; i--)
+ {
+ var type = operators[i].Name[0] switch
+ {
+ '+' => UnaryType.UnaryPlus,
+ '!' => UnaryType.Not,
+ '~' => UnaryType.OnesComplement,
+ _ => UnaryType.Negate
+ };
+
+ expr = new Expr.Unary(operators[i], type, expr);
+ }
+
+ return expr;
+ });
+
+ var mul_expression =
+ prefix_expression.Fold(
+ OneOf("*/%").ThenIgnore(S).Do(CreateIdentifier),
+ (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
+
+ var add_expression =
+ mul_expression.Fold(
+ OneOf("+-").ThenIgnore(S).Do(CreateIdentifier),
+ (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
+
+ var shift_expression =
+ add_expression.Fold(
+ OneOf(["<<", ">>", ">>>"]).ThenIgnore(S).Do(CreateIdentifier),
+ (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
+
+ var relational_expression =
+ shift_expression.Fold(
+ OneOf(["<", ">", "<=", ">="]).ThenIgnore(S).Do(CreateIdentifier),
+ (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
+
+ var equality_expression =
+ relational_expression.Fold(
+ OneOf("==", "!=").ThenIgnore(S).Do(CreateIdentifier),
+ (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
+
+ var bitwise_and_expression =
+ equality_expression.Fold(
+ L('&').ThenIgnore(S).Do(CreateIdentifier),
+ (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
+
+ var bitwise_xor_expression =
+ bitwise_and_expression.Fold(
+ L('^').ThenIgnore(S).Do(CreateIdentifier),
+ (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
+
+ var bitwise_or_expression =
+ bitwise_xor_expression.Fold(
+ L('|').ThenIgnore(S).Do(CreateIdentifier),
+ (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
+
+ var logical_and_expression =
+ bitwise_or_expression.Fold(
+ L("&&").ThenIgnore(S).Do(CreateIdentifier),
+ (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
+
+ var logical_or_expression =
+ logical_and_expression.Fold(
+ L("||").ThenIgnore(S).Do(CreateIdentifier),
+ (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
+
+ var null_coalesce_expression =
+ logical_or_expression.FoldR(
+ L("??").ThenIgnore(S).Do(CreateIdentifier),
+ (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));
+
+ var conditional_expression = Deferred();
+ conditional_expression.Parser =
+ Seq(
+ null_coalesce_expression,
+ Seq(
+ L('?'), S,
+ expression,
+ L(':').Or(Fail("Expected ':'")), S,
+ conditional_expression.Or(Fail("Expected expression"))
+ ).Optional()
+ ).Do(Expr (Expr condition, OptionalValue<(char, Unit, Expr @true, char, Unit, Expr @false)> optional) =>
+ optional.HasValue
+ ? new Expr.Conditional(condition, optional.Value.@true, optional.Value.@false)
+ : condition);
+
+ expression.Parser =
+ conditional_expression;
+
+ return S.Then(expression);
+ }
+
+ private static Identifier CreateIdentifier(string v) =>
+ new Identifier(v);
+
+ private static Identifier CreateIdentifier(char v) =>
+ new Identifier(v.ToString());
+}
diff --git a/src/Ramstack.ExpressionParser/ExpressionParser.cs b/src/Ramstack.ExpressionParser/ExpressionParser.cs
index ae1d458..7e25115 100644
--- a/src/Ramstack.ExpressionParser/ExpressionParser.cs
+++ b/src/Ramstack.ExpressionParser/ExpressionParser.cs
@@ -1,178 +1,178 @@
-using System.Linq.Expressions;
-
-namespace Ramstack.Parsing;
-
-///
-/// Provides methods for parsing and evaluating expressions.
-///
-public static partial class ExpressionParser
-{
- ///
- /// Parses the specified expression into an .
- ///
- /// The expression string to parse.
- ///
- /// The result of the parsing operation.
- ///
- public static ParseResult Parse(ReadOnlySpan source) =>
- Parse(source, new ExpressionBuilder(new DefaultBinder()));
-
- ///
- /// Parses the specified expression into an using the specified .
- ///
- /// The expression string to parse.
- /// The binder instance used for resolving members and methods.
- ///
- /// The result of the parsing operation.
- ///
- public static ParseResult Parse(ReadOnlySpan source, Binder binder) =>
- Parse(source, new ExpressionBuilder(binder));
-
- ///
- /// Parses the specified expression into an using the specified .
- ///
- /// The expression string to parse.
- /// The expression builder responsible for constructing the expression tree.
- ///
- /// The result of the parsing operation.
- ///
- public static ParseResult Parse(ReadOnlySpan source, ExpressionBuilder builder)
- {
- try
- {
- var result = Parser.Parse(source);
- if (!result.Success)
- {
- return new ParseResult
- {
- Length = result.Length,
- ErrorMessage = result.ErrorMessage
- };
- }
-
- var expression = builder.Visit(result.Value!);
- return new ParseResult
- {
- Length = result.Length,
- Value = expression
- };
- }
- catch (ParseErrorException e)
- {
- return new ParseResult
- {
- Length = 0,
- ErrorMessage = e.Message,
- Exception = e.InnerException
- };
- }
- catch (Exception e)
- {
- return new ParseResult
- {
- Length = 0,
- ErrorMessage = e.Message,
- Exception = e
- };
- }
- }
-
- ///
- /// Evaluates the specified expression and returns the result as an object.
- ///
- /// The expression string to evaluate.
- ///
- /// The evaluated result.
- ///
- public static object? Evaluate(ReadOnlySpan source) =>
- Evaluate