From 349fa0387a49093523e9f6a994629f2e8c0bb818 Mon Sep 17 00:00:00 2001 From: rameel Date: Mon, 16 Nov 2026 22:02:58 +0500 Subject: [PATCH 1/2] repo: normalize formatting rules and line endings --- .editorconfig | 106 +- .gitattributes | 1 + .github/workflows/publish.yml | 80 +- .github/workflows/test.yml | 58 +- .gitignore | 74 +- Directory.Build.props | 10 +- Directory.Packages.props | 26 +- LICENSE | 18 +- README.md | 140 +-- src/Ramstack.ExpressionParser/Binder.cs | 106 +- .../ContextAwareBinder.cs | 110 +-- .../DefaultBinder.cs | 336 +++---- .../ExpressionBuilder.Helpers.cs | 636 ++++++------ .../ExpressionBuilder.cs | 922 ++++++++--------- .../ExpressionParser.Parser.cs | 540 +++++----- .../ExpressionParser.cs | 356 +++---- .../Expressions/Expr.Binary.cs | 90 +- .../Expressions/Expr.Call.cs | 84 +- .../Expressions/Expr.Conditional.cs | 90 +- .../Expressions/Expr.Index.cs | 72 +- .../Expressions/Expr.Literal.cs | 72 +- .../Expressions/Expr.MemberAccess.cs | 74 +- .../Expressions/Expr.Parenthesized.cs | 62 +- .../Expressions/Expr.Reference.cs | 60 +- .../Expressions/Expr.Unary.cs | 170 ++-- .../Expressions/Expr.cs | 64 +- .../Expressions/ExprKind.cs | 158 +-- .../Expressions/ExprVisitor.cs | 244 ++--- .../Expressions/Identifier.cs | 46 +- .../Expressions/UnaryType.cs | 94 +- .../Internal/Error.cs | 218 ++-- .../Internal/MethodResolver.cs | 848 ++++++++-------- .../Internal/ReflectionExtensions.cs | 246 ++--- .../Internal/TypeUtils.cs | 360 +++---- .../ParseErrorException.cs | 54 +- .../Parsers/ConstantNumberParser.cs | 876 ++++++++-------- .../Properties/AssemblyInfo.cs | 2 +- .../Ramstack.ExpressionParser.csproj | 144 +-- .../Data/Expressions.txt | 934 +++++++++--------- .../Data/StringConcat.txt | 64 +- .../ExpressionParserTest.cs | 240 ++--- .../Ramstack.ExpressionParser.Tests.csproj | 80 +- 42 files changed, 4462 insertions(+), 4503 deletions(-) create mode 100644 .gitattributes 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..ed14ea7 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,5 +1,5 @@ - - - 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 -[![NuGet](https://img.shields.io/nuget/v/Ramstack.ExpressionParser.svg)](https://nuget.org/packages/Ramstack.ExpressionParser) -[![MIT](https://img.shields.io/github/license/rameel/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 +[![NuGet](https://img.shields.io/nuget/v/Ramstack.ExpressionParser.svg)](https://nuget.org/packages/Ramstack.ExpressionParser) +[![MIT](https://img.shields.io/github/license/rameel/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..4556f34 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 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(); + } +} 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(source); - - /// - /// Evaluates the specified expression within the provided context. - /// - /// The expression string to evaluate. - /// The evaluation context. - /// - /// The evaluated result. - /// - public static object? Evaluate(ReadOnlySpan source, object context) - { - var p = Expression.Parameter(typeof(object), "p"); - var c = Expression.Variable(context.GetType(), "context"); - var r = Parse(source, new ContextAwareBinder(c)); - - if (!r.Success) - throw new ArgumentException(r.ErrorMessage); - - if (r.Value is null) - return null; - - var block = Expression.Block( - variables: [c], - expressions: - [ - Expression.Assign(c, Expression.Convert(p, context.GetType())), - r.Value.Type.IsClass ? r.Value : Expression.Convert(r.Value, typeof(object)) - ]); - - return Expression - .Lambda>(block, p) - .Compile()(context); - } - - /// - /// Evaluates the specified expression. - /// - /// The expected result type. - /// The expression string to evaluate. - /// - /// The evaluated result of type . - /// - public static TResult? Evaluate(ReadOnlySpan source) - { - var r = Parse(source, new DefaultBinder()); - if (!r.Success) - throw new ArgumentException(r.ErrorMessage); - - if (r.Value is null) - return default; - - var e = r.Value; - if (e.Type != typeof(TResult) && (!e.Type.IsClass || !typeof(TResult).IsAssignableFrom(e.Type))) - e = Expression.Convert(e, typeof(TResult)); - - return Expression - .Lambda>(e) - .Compile()(); - } - - /// - /// Evaluates the specified expression within the given context and returns the result as the specified type. - /// - /// The type of the evaluation context. - /// The expected result type. - /// The expression string to evaluate. - /// The evaluation context. - /// - /// The evaluated result of type . - /// - public static TResult? Evaluate(ReadOnlySpan source, TContext context) where TContext : notnull - { - var c = Expression.Parameter(context.GetType(), "context"); - var r = Parse(source, new ContextAwareBinder(c)); - - if (!r.Success) - throw new ArgumentException(r.ErrorMessage); - - if (r.Value is null) - return default; - - var e = r.Value; - if (e.Type != typeof(TResult) && (!e.Type.IsClass || !typeof(TResult).IsAssignableFrom(e.Type))) - e = Expression.Convert(e, typeof(TResult)); - - return Expression - .Lambda>(e, c) - .Compile()(context); - } -} +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(source); + + /// + /// Evaluates the specified expression within the provided context. + /// + /// The expression string to evaluate. + /// The evaluation context. + /// + /// The evaluated result. + /// + public static object? Evaluate(ReadOnlySpan source, object context) + { + var p = Expression.Parameter(typeof(object), "p"); + var c = Expression.Variable(context.GetType(), "context"); + var r = Parse(source, new ContextAwareBinder(c)); + + if (!r.Success) + throw new ArgumentException(r.ErrorMessage); + + if (r.Value is null) + return null; + + var block = Expression.Block( + variables: [c], + expressions: + [ + Expression.Assign(c, Expression.Convert(p, context.GetType())), + r.Value.Type.IsClass ? r.Value : Expression.Convert(r.Value, typeof(object)) + ]); + + return Expression + .Lambda>(block, p) + .Compile()(context); + } + + /// + /// Evaluates the specified expression. + /// + /// The expected result type. + /// The expression string to evaluate. + /// + /// The evaluated result of type . + /// + public static TResult? Evaluate(ReadOnlySpan source) + { + var r = Parse(source, new DefaultBinder()); + if (!r.Success) + throw new ArgumentException(r.ErrorMessage); + + if (r.Value is null) + return default; + + var e = r.Value; + if (e.Type != typeof(TResult) && (!e.Type.IsClass || !typeof(TResult).IsAssignableFrom(e.Type))) + e = Expression.Convert(e, typeof(TResult)); + + return Expression + .Lambda>(e) + .Compile()(); + } + + /// + /// Evaluates the specified expression within the given context and returns the result as the specified type. + /// + /// The type of the evaluation context. + /// The expected result type. + /// The expression string to evaluate. + /// The evaluation context. + /// + /// The evaluated result of type . + /// + public static TResult? Evaluate(ReadOnlySpan source, TContext context) where TContext : notnull + { + var c = Expression.Parameter(context.GetType(), "context"); + var r = Parse(source, new ContextAwareBinder(c)); + + if (!r.Success) + throw new ArgumentException(r.ErrorMessage); + + if (r.Value is null) + return default; + + var e = r.Value; + if (e.Type != typeof(TResult) && (!e.Type.IsClass || !typeof(TResult).IsAssignableFrom(e.Type))) + e = Expression.Convert(e, typeof(TResult)); + + return Expression + .Lambda>(e, c) + .Compile()(context); + } +} diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs index 6abcef5..c2f1561 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs @@ -1,45 +1,45 @@ -namespace Ramstack.Parsing.Expressions; - -partial class Expr -{ - /// - /// Represents a binary operation expression in an expression tree, consisting of an operator and two operands. - /// - public sealed class Binary(Identifier @operator, Expr lhs, Expr rhs) : Expr(ExprKind.Binary) - { - /// - /// Gets the operator of the binary expression. - /// - /// - /// An representing the operator, such as "+" or "-". - /// - public Identifier Operator { get; } = @operator; - - /// - /// Gets the left-hand side operand of the binary expression. - /// - public Expr Left { get; } = lhs; - - /// - /// Gets the right-hand side operand of the binary expression. - /// - public Expr Right { get; } = rhs; - - /// - /// Deconstructs the binary expression into its operator and operands. - /// - /// The representing the operator of the binary expression. - /// The representing the left-hand side operand. - /// The representing the right-hand side operand. - public void Deconstruct(out Identifier @operator, out Expr lhs, out Expr rhs) => - (@operator, lhs, rhs) = (Operator, Left, Right); - - /// - public override T Accept(ExprVisitor visitor) => - visitor.VisitBinary(this); - - /// - public override string ToString() => - $"({Left} {Operator} {Right})"; - } -} +namespace Ramstack.Parsing.Expressions; + +partial class Expr +{ + /// + /// Represents a binary operation expression in an expression tree, consisting of an operator and two operands. + /// + public sealed class Binary(Identifier @operator, Expr lhs, Expr rhs) : Expr(ExprKind.Binary) + { + /// + /// Gets the operator of the binary expression. + /// + /// + /// An representing the operator, such as "+" or "-". + /// + public Identifier Operator { get; } = @operator; + + /// + /// Gets the left-hand side operand of the binary expression. + /// + public Expr Left { get; } = lhs; + + /// + /// Gets the right-hand side operand of the binary expression. + /// + public Expr Right { get; } = rhs; + + /// + /// Deconstructs the binary expression into its operator and operands. + /// + /// The representing the operator of the binary expression. + /// The representing the left-hand side operand. + /// The representing the right-hand side operand. + public void Deconstruct(out Identifier @operator, out Expr lhs, out Expr rhs) => + (@operator, lhs, rhs) = (Operator, Left, Right); + + /// + public override T Accept(ExprVisitor visitor) => + visitor.VisitBinary(this); + + /// + public override string ToString() => + $"({Left} {Operator} {Right})"; + } +} diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs index b1df3f0..0c1754f 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs @@ -1,42 +1,42 @@ -namespace Ramstack.Parsing.Expressions; - -partial class Expr -{ - /// - /// Represents a method call expression in an expression tree, consisting of a target expression and its parameters. - /// - public sealed class Call(Expr expression, IReadOnlyList parameters) : Expr(ExprKind.Call) - { - /// - /// Gets the expression being called, such as a method or function reference. - /// - /// - /// An representing the target of the call, e.g., Math.Abs. - /// - public Expr Expression { get; } = expression; - - /// - /// Gets the list of parameters passed to the call. - /// - /// - /// An of instances representing the arguments, e.g., -5. - /// - public IReadOnlyList Parameters { get; } = parameters; - - /// - /// Deconstructs the call expression into its target expression and parameters. - /// - /// The representing the target of the call. - /// The of instances representing the call’s arguments. - public void Deconstruct(out Expr expression, out IReadOnlyList parameters) => - (expression, parameters) = (Expression, Parameters); - - /// - public override T Accept(ExprVisitor visitor) => - visitor.VisitCall(this); - - /// - public override string ToString() => - $"{Expression}({string.Join(", ", Parameters)})"; - } -} +namespace Ramstack.Parsing.Expressions; + +partial class Expr +{ + /// + /// Represents a method call expression in an expression tree, consisting of a target expression and its parameters. + /// + public sealed class Call(Expr expression, IReadOnlyList parameters) : Expr(ExprKind.Call) + { + /// + /// Gets the expression being called, such as a method or function reference. + /// + /// + /// An representing the target of the call, e.g., Math.Abs. + /// + public Expr Expression { get; } = expression; + + /// + /// Gets the list of parameters passed to the call. + /// + /// + /// An of instances representing the arguments, e.g., -5. + /// + public IReadOnlyList Parameters { get; } = parameters; + + /// + /// Deconstructs the call expression into its target expression and parameters. + /// + /// The representing the target of the call. + /// The of instances representing the call’s arguments. + public void Deconstruct(out Expr expression, out IReadOnlyList parameters) => + (expression, parameters) = (Expression, Parameters); + + /// + public override T Accept(ExprVisitor visitor) => + visitor.VisitCall(this); + + /// + public override string ToString() => + $"{Expression}({string.Join(", ", Parameters)})"; + } +} diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs index a9eb9da..077b210 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs @@ -1,45 +1,45 @@ -namespace Ramstack.Parsing.Expressions; - -partial class Expr -{ - /// - /// Represents a conditional (ternary) expression in an expression tree. - /// - public sealed class Conditional(Expr test, Expr ifTrue, Expr ifFalse) : Expr(ExprKind.Conditional) - { - /// - /// Gets the condition expression evaluated to determine the outcome. - /// - /// - /// An representing the test condition, e.g., a > b. - /// - public Expr Test { get; } = test; - - /// - /// Gets the expression evaluated if the condition is . - /// - public Expr IfTrue { get; } = ifTrue; - - /// - /// Gets the expression evaluated if the condition is . - /// - public Expr IfFalse { get; } = ifFalse; - - /// - /// Deconstructs the conditional expression into its test condition and branch expressions. - /// - /// The representing the condition to evaluate. - /// The representing the branch. - /// The representing the branch. - public void Deconstruct(out Expr test, out Expr ifTrue, out Expr ifFalse) => - (test, ifTrue, ifFalse) = (Test, IfTrue, IfFalse); - - /// - public override T Accept(ExprVisitor visitor) => - visitor.VisitConditional(this); - - /// - public override string ToString() => - $"{Test} ? {IfTrue} : {IfFalse}"; - } -} +namespace Ramstack.Parsing.Expressions; + +partial class Expr +{ + /// + /// Represents a conditional (ternary) expression in an expression tree. + /// + public sealed class Conditional(Expr test, Expr ifTrue, Expr ifFalse) : Expr(ExprKind.Conditional) + { + /// + /// Gets the condition expression evaluated to determine the outcome. + /// + /// + /// An representing the test condition, e.g., a > b. + /// + public Expr Test { get; } = test; + + /// + /// Gets the expression evaluated if the condition is . + /// + public Expr IfTrue { get; } = ifTrue; + + /// + /// Gets the expression evaluated if the condition is . + /// + public Expr IfFalse { get; } = ifFalse; + + /// + /// Deconstructs the conditional expression into its test condition and branch expressions. + /// + /// The representing the condition to evaluate. + /// The representing the branch. + /// The representing the branch. + public void Deconstruct(out Expr test, out Expr ifTrue, out Expr ifFalse) => + (test, ifTrue, ifFalse) = (Test, IfTrue, IfFalse); + + /// + public override T Accept(ExprVisitor visitor) => + visitor.VisitConditional(this); + + /// + public override string ToString() => + $"{Test} ? {IfTrue} : {IfFalse}"; + } +} diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs index 45106f6..42df46c 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs @@ -1,36 +1,36 @@ -namespace Ramstack.Parsing.Expressions; - -partial class Expr -{ - /// - /// Represents an indexing operation in an expression tree, such as accessing an array or a parameterized property. - /// - public sealed class Indexer(Expr expression, IReadOnlyList parameters) : Expr(ExprKind.Index) - { - /// - /// Gets the expression being indexed, such as an array or object with an indexer. - /// - public Expr Expression { get; } = expression; - - /// - /// Gets the list of parameters used as indices or arguments for the indexing operation. - /// - public IReadOnlyList Parameters { get; } = parameters; - - /// - /// Deconstructs the indexer expression into its target expression and index parameters. - /// - /// The representing the target being indexed. - /// The of instances representing the indices. - public void Deconstruct(out Expr expression, out IReadOnlyList parameters) => - (expression, parameters) = (Expression, Parameters); - - /// - public override T Accept(ExprVisitor visitor) => - visitor.VisitIndex(this); - - /// - public override string ToString() => - $"{Expression}[{string.Join(", ", Parameters)}]"; - } -} +namespace Ramstack.Parsing.Expressions; + +partial class Expr +{ + /// + /// Represents an indexing operation in an expression tree, such as accessing an array or a parameterized property. + /// + public sealed class Indexer(Expr expression, IReadOnlyList parameters) : Expr(ExprKind.Index) + { + /// + /// Gets the expression being indexed, such as an array or object with an indexer. + /// + public Expr Expression { get; } = expression; + + /// + /// Gets the list of parameters used as indices or arguments for the indexing operation. + /// + public IReadOnlyList Parameters { get; } = parameters; + + /// + /// Deconstructs the indexer expression into its target expression and index parameters. + /// + /// The representing the target being indexed. + /// The of instances representing the indices. + public void Deconstruct(out Expr expression, out IReadOnlyList parameters) => + (expression, parameters) = (Expression, Parameters); + + /// + public override T Accept(ExprVisitor visitor) => + visitor.VisitIndex(this); + + /// + public override string ToString() => + $"{Expression}[{string.Join(", ", Parameters)}]"; + } +} diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Literal.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Literal.cs index 4b404fd..6d37e87 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Literal.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Literal.cs @@ -1,36 +1,36 @@ -namespace Ramstack.Parsing.Expressions; - -partial class Expr -{ - /// - /// Represents a literal value in an expression tree, such as a number, string, or boolean. - /// - public sealed class Literal(object? value) : Expr(ExprKind.Literal) - { - /// - /// Gets the constant value of the literal expression. - /// - public object? Value { get; } = value; - - /// - /// Deconstructs the literal expression into its value. - /// - /// The constant value of the literal, which may be null. - public void Deconstruct(out object? value) => - value = Value; - - /// - public override T Accept(ExprVisitor visitor) => - visitor.VisitLiteral(this); - - /// - public override string ToString() => Value switch - { - null => "null", - bool b => b ? "true" : "false", - string s => $"\"{s}\"", - char c => $"'{c}'", - _ => Value.ToString()! - }; - } -} +namespace Ramstack.Parsing.Expressions; + +partial class Expr +{ + /// + /// Represents a literal value in an expression tree, such as a number, string, or boolean. + /// + public sealed class Literal(object? value) : Expr(ExprKind.Literal) + { + /// + /// Gets the constant value of the literal expression. + /// + public object? Value { get; } = value; + + /// + /// Deconstructs the literal expression into its value. + /// + /// The constant value of the literal, which may be null. + public void Deconstruct(out object? value) => + value = Value; + + /// + public override T Accept(ExprVisitor visitor) => + visitor.VisitLiteral(this); + + /// + public override string ToString() => Value switch + { + null => "null", + bool b => b ? "true" : "false", + string s => $"\"{s}\"", + char c => $"'{c}'", + _ => Value.ToString()! + }; + } +} diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs index d921395..4017429 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs @@ -1,37 +1,37 @@ -namespace Ramstack.Parsing.Expressions; - -partial class Expr -{ - /// - /// Represents a member access operation in an expression tree, - /// such as accessing a field or property like obj.Property. - /// - public sealed class MemberAccess(Expr expression, Expr member) : Expr(ExprKind.MemberAccess) - { - /// - /// Gets the expression whose member is being accessed. - /// - public Expr Expression { get; } = expression; - - /// - /// Gets the expression representing the member being accessed. - /// - public Expr Member { get; } = member; - - /// - /// Deconstructs the member access expression into its target expression and member. - /// - /// The representing the target object. - /// The representing the accessed member. - public void Deconstruct(out Expr expression, out Expr member) => - (expression, member) = (Expression, Member); - - /// - public override T Accept(ExprVisitor visitor) => - visitor.VisitMemberAccess(this); - - /// - public override string ToString() => - $"{Expression}.{Member}"; - } -} +namespace Ramstack.Parsing.Expressions; + +partial class Expr +{ + /// + /// Represents a member access operation in an expression tree, + /// such as accessing a field or property like obj.Property. + /// + public sealed class MemberAccess(Expr expression, Expr member) : Expr(ExprKind.MemberAccess) + { + /// + /// Gets the expression whose member is being accessed. + /// + public Expr Expression { get; } = expression; + + /// + /// Gets the expression representing the member being accessed. + /// + public Expr Member { get; } = member; + + /// + /// Deconstructs the member access expression into its target expression and member. + /// + /// The representing the target object. + /// The representing the accessed member. + public void Deconstruct(out Expr expression, out Expr member) => + (expression, member) = (Expression, Member); + + /// + public override T Accept(ExprVisitor visitor) => + visitor.VisitMemberAccess(this); + + /// + public override string ToString() => + $"{Expression}.{Member}"; + } +} diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs index 9ebfd53..36ad1c2 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs @@ -1,31 +1,31 @@ -namespace Ramstack.Parsing.Expressions; - -partial class Expr -{ - /// - /// Represents a parenthesized expression in an expression tree, used to enforce precedence or grouping. - /// - /// The enclosed within parentheses. - public sealed class Parenthesized(Expr expression) : Expr(ExprKind.Parenthesized) - { - /// - /// Gets the expression enclosed within parentheses. - /// - public Expr Expression { get; } = expression; - - /// - /// Deconstructs the parenthesized expression into its inner expression. - /// - /// The enclosed within parentheses. - public void Deconstruct(out Expr expression) => - expression = Expression; - - /// - public override T Accept(ExprVisitor visitor) => - visitor.VisitParenthesized(this); - - /// - public override string ToString() => - $"({Expression})"; - } -} +namespace Ramstack.Parsing.Expressions; + +partial class Expr +{ + /// + /// Represents a parenthesized expression in an expression tree, used to enforce precedence or grouping. + /// + /// The enclosed within parentheses. + public sealed class Parenthesized(Expr expression) : Expr(ExprKind.Parenthesized) + { + /// + /// Gets the expression enclosed within parentheses. + /// + public Expr Expression { get; } = expression; + + /// + /// Deconstructs the parenthesized expression into its inner expression. + /// + /// The enclosed within parentheses. + public void Deconstruct(out Expr expression) => + expression = Expression; + + /// + public override T Accept(ExprVisitor visitor) => + visitor.VisitParenthesized(this); + + /// + public override string ToString() => + $"({Expression})"; + } +} diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Reference.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Reference.cs index e6f8188..675145b 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Reference.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Reference.cs @@ -1,30 +1,30 @@ -namespace Ramstack.Parsing.Expressions; - -partial class Expr -{ - /// - /// Represents a reference to a variable, parameter, or member in an expression tree. - /// - public sealed class Reference(Identifier value) : Expr(ExprKind.Reference) - { - /// - /// Gets the identifier representing the referenced entity. - /// - public Identifier Value { get; } = value; - - /// - /// Deconstructs the reference expression into its identifier. - /// - /// The representing the referenced entity. - public void Deconstruct(out Identifier value) => - value = Value; - - /// - public override T Accept(ExprVisitor visitor) => - visitor.VisitReference(this); - - /// - public override string ToString() => - Value.ToString(); - } -} +namespace Ramstack.Parsing.Expressions; + +partial class Expr +{ + /// + /// Represents a reference to a variable, parameter, or member in an expression tree. + /// + public sealed class Reference(Identifier value) : Expr(ExprKind.Reference) + { + /// + /// Gets the identifier representing the referenced entity. + /// + public Identifier Value { get; } = value; + + /// + /// Deconstructs the reference expression into its identifier. + /// + /// The representing the referenced entity. + public void Deconstruct(out Identifier value) => + value = Value; + + /// + public override T Accept(ExprVisitor visitor) => + visitor.VisitReference(this); + + /// + public override string ToString() => + Value.ToString(); + } +} diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs index cfc3060..37cf3e3 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs @@ -1,85 +1,85 @@ -namespace Ramstack.Parsing.Expressions; - -partial class Expr -{ - /// - /// Represents a unary operation expression in an expression tree, consisting of an operator and a single operand. - /// - /// The representing the unary operator, e.g., "-" or "int". - /// The specifying the kind of unary operation (e.g., arithmetic or conversion). - /// The on which the unary operation is applied. - public sealed class Unary(Identifier @operator, UnaryType unaryType, Expr operand) : Expr(ExprKind.Unary) - { - /// - /// Gets the operator of the unary expression. - /// - /// - /// An representing the unary operator, such as "-" or a type name like "int". - /// - public Identifier Operator { get; } = @operator; - - /// - /// Gets the type of the unary operation. - /// - /// - /// A value indicating the nature of the operation, e.g., arithmetic or conversion. - /// - public UnaryType UnaryType { get; } = unaryType; - - /// - /// Gets the operand of the unary expression. - /// - /// - /// An representing the expression the operator is applied to, e.g., x. - /// - public Expr Operand { get; } = operand; - - /// - /// Deconstructs the unary expression into its type and operand. - /// - /// The of the unary operation. - /// The on which the operation is applied. - /// - /// - /// var unary = new Unary(new Identifier("-"), UnaryType.Arithmetic, new Identifier("x")); - /// unary.Deconstruct(out UnaryType type, out Expr op); - /// // type is UnaryType.Arithmetic, op is Identifier("x") - /// - /// - public void Deconstruct(out UnaryType unaryType, out Expr operand) => - (unaryType, operand) = (UnaryType, Operand); - - /// - /// Deconstructs the unary expression into its operator, type, and operand. - /// - /// The representing the unary operator. - /// The of the unary operation. - /// The on which the operation is applied. - /// - /// - /// var unary = new Unary(new Identifier("-"), UnaryType.Arithmetic, new Identifier("x")); - /// unary.Deconstruct(out Identifier op, out UnaryType type, out Expr operand); - /// // op.Name is "-", type is UnaryType.Arithmetic, operand is Identifier("x") - /// - /// - public void Deconstruct(out Identifier @operator, out UnaryType unaryType, out Expr operand) => - (@operator, unaryType, operand) = (Operator, UnaryType, Operand); - - /// - /// - /// The result of type produced by the visitor's method. - /// - public override T Accept(ExprVisitor visitor) => - visitor.VisitUnary(this); - - /// - /// - /// A string representation of the unary expression, e.g., -x for operators or x:int for conversions. - /// - public override string ToString() => UnaryType switch - { - UnaryType.Convert => $"{Operand}:{Operator}", - _ => $"{Operator}({Operand})" - }; - } -} +namespace Ramstack.Parsing.Expressions; + +partial class Expr +{ + /// + /// Represents a unary operation expression in an expression tree, consisting of an operator and a single operand. + /// + /// The representing the unary operator, e.g., "-" or "int". + /// The specifying the kind of unary operation (e.g., arithmetic or conversion). + /// The on which the unary operation is applied. + public sealed class Unary(Identifier @operator, UnaryType unaryType, Expr operand) : Expr(ExprKind.Unary) + { + /// + /// Gets the operator of the unary expression. + /// + /// + /// An representing the unary operator, such as "-" or a type name like "int". + /// + public Identifier Operator { get; } = @operator; + + /// + /// Gets the type of the unary operation. + /// + /// + /// A value indicating the nature of the operation, e.g., arithmetic or conversion. + /// + public UnaryType UnaryType { get; } = unaryType; + + /// + /// Gets the operand of the unary expression. + /// + /// + /// An representing the expression the operator is applied to, e.g., x. + /// + public Expr Operand { get; } = operand; + + /// + /// Deconstructs the unary expression into its type and operand. + /// + /// The of the unary operation. + /// The on which the operation is applied. + /// + /// + /// var unary = new Unary(new Identifier("-"), UnaryType.Arithmetic, new Identifier("x")); + /// unary.Deconstruct(out UnaryType type, out Expr op); + /// // type is UnaryType.Arithmetic, op is Identifier("x") + /// + /// + public void Deconstruct(out UnaryType unaryType, out Expr operand) => + (unaryType, operand) = (UnaryType, Operand); + + /// + /// Deconstructs the unary expression into its operator, type, and operand. + /// + /// The representing the unary operator. + /// The of the unary operation. + /// The on which the operation is applied. + /// + /// + /// var unary = new Unary(new Identifier("-"), UnaryType.Arithmetic, new Identifier("x")); + /// unary.Deconstruct(out Identifier op, out UnaryType type, out Expr operand); + /// // op.Name is "-", type is UnaryType.Arithmetic, operand is Identifier("x") + /// + /// + public void Deconstruct(out Identifier @operator, out UnaryType unaryType, out Expr operand) => + (@operator, unaryType, operand) = (Operator, UnaryType, Operand); + + /// + /// + /// The result of type produced by the visitor's method. + /// + public override T Accept(ExprVisitor visitor) => + visitor.VisitUnary(this); + + /// + /// + /// A string representation of the unary expression, e.g., -x for operators or x:int for conversions. + /// + public override string ToString() => UnaryType switch + { + UnaryType.Convert => $"{Operand}:{Operator}", + _ => $"{Operator}({Operand})" + }; + } +} diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.cs index 26b189b..59ad12a 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.cs @@ -1,32 +1,32 @@ -namespace Ramstack.Parsing.Expressions; - -/// -/// Represents a node in an expression tree, serving as the base class for all expression types. -/// -public abstract partial class Expr(ExprKind kind) -{ - /// - /// Gets the kind of this expression node. - /// - /// - /// An value indicating the type of expression, such as a literal, binary operation, or reference. - /// - public ExprKind Kind { get; init; } = kind; - - /// - /// Deconstructs the expression into its kind. - /// - /// The of this expression node, output as an enumeration value. - public void Deconstruct(out ExprKind kind) => - kind = Kind; - - /// - /// Accepts a visitor to process this expression node and return a result of type . - /// - /// The type of the result produced by the visitor. - /// The instance that processes this expression. - /// - /// A result of type as determined by the visitor's implementation. - /// - public abstract T Accept(ExprVisitor visitor); -} +namespace Ramstack.Parsing.Expressions; + +/// +/// Represents a node in an expression tree, serving as the base class for all expression types. +/// +public abstract partial class Expr(ExprKind kind) +{ + /// + /// Gets the kind of this expression node. + /// + /// + /// An value indicating the type of expression, such as a literal, binary operation, or reference. + /// + public ExprKind Kind { get; init; } = kind; + + /// + /// Deconstructs the expression into its kind. + /// + /// The of this expression node, output as an enumeration value. + public void Deconstruct(out ExprKind kind) => + kind = Kind; + + /// + /// Accepts a visitor to process this expression node and return a result of type . + /// + /// The type of the result produced by the visitor. + /// The instance that processes this expression. + /// + /// A result of type as determined by the visitor's implementation. + /// + public abstract T Accept(ExprVisitor visitor); +} diff --git a/src/Ramstack.ExpressionParser/Expressions/ExprKind.cs b/src/Ramstack.ExpressionParser/Expressions/ExprKind.cs index 1ec4735..04791ca 100644 --- a/src/Ramstack.ExpressionParser/Expressions/ExprKind.cs +++ b/src/Ramstack.ExpressionParser/Expressions/ExprKind.cs @@ -1,79 +1,79 @@ -namespace Ramstack.Parsing.Expressions; - -/// -/// Defines the possible types of nodes in an expression tree used by the expression parser. -/// -public enum ExprKind -{ - /// - /// Represents a reference to a variable, parameter, or member in the expression. - /// - /// - /// In the expression x, this would indicate a reference to the variable "x". - /// - Reference, - - /// - /// Represents a constant value, such as a number or string literal. - /// - /// - /// In the expression 42 or "hello", this denotes a literal value. - /// - Literal, - - /// - /// Represents a binary operation, such as addition or subtraction, involving two operands. - /// - /// - /// In the expression a + b, this indicates the addition operation. - /// - Binary, - - /// - /// Represents a method invocation within the expression. - /// - /// - /// In the expression Math.Abs(-5), this denotes the method call to "Abs". - /// - Call, - - /// - /// Represents an indexing operation or access to a parameterized property. - /// - /// - /// In the expression array[0], this indicates an index operation. - /// - Index, - - /// - /// Represents a read operation on a field or property of an object. - /// - /// - /// In the expression obj.Property, this denotes accessing the "Property" member. - /// - MemberAccess, - - /// - /// Represents a unary operation, such as negation or logical NOT, involving a single operand. - /// - /// - /// In the expression -x, this indicates the negation operation. - /// - Unary, - - /// - /// Represents a conditional (ternary) operation with a condition, true branch, and false branch. - /// - /// - /// In the expression a > b ? a : b, this denotes a conditional operation. - /// - Conditional, - - /// - /// Represents an expression enclosed in parentheses to enforce precedence or grouping. - /// - /// - /// In the expression (a + b), this indicates a parenthesized sub-expression. - /// - Parenthesized -} +namespace Ramstack.Parsing.Expressions; + +/// +/// Defines the possible types of nodes in an expression tree used by the expression parser. +/// +public enum ExprKind +{ + /// + /// Represents a reference to a variable, parameter, or member in the expression. + /// + /// + /// In the expression x, this would indicate a reference to the variable "x". + /// + Reference, + + /// + /// Represents a constant value, such as a number or string literal. + /// + /// + /// In the expression 42 or "hello", this denotes a literal value. + /// + Literal, + + /// + /// Represents a binary operation, such as addition or subtraction, involving two operands. + /// + /// + /// In the expression a + b, this indicates the addition operation. + /// + Binary, + + /// + /// Represents a method invocation within the expression. + /// + /// + /// In the expression Math.Abs(-5), this denotes the method call to "Abs". + /// + Call, + + /// + /// Represents an indexing operation or access to a parameterized property. + /// + /// + /// In the expression array[0], this indicates an index operation. + /// + Index, + + /// + /// Represents a read operation on a field or property of an object. + /// + /// + /// In the expression obj.Property, this denotes accessing the "Property" member. + /// + MemberAccess, + + /// + /// Represents a unary operation, such as negation or logical NOT, involving a single operand. + /// + /// + /// In the expression -x, this indicates the negation operation. + /// + Unary, + + /// + /// Represents a conditional (ternary) operation with a condition, true branch, and false branch. + /// + /// + /// In the expression a > b ? a : b, this denotes a conditional operation. + /// + Conditional, + + /// + /// Represents an expression enclosed in parentheses to enforce precedence or grouping. + /// + /// + /// In the expression (a + b), this indicates a parenthesized sub-expression. + /// + Parenthesized +} diff --git a/src/Ramstack.ExpressionParser/Expressions/ExprVisitor.cs b/src/Ramstack.ExpressionParser/Expressions/ExprVisitor.cs index 9e1c315..fe857f5 100644 --- a/src/Ramstack.ExpressionParser/Expressions/ExprVisitor.cs +++ b/src/Ramstack.ExpressionParser/Expressions/ExprVisitor.cs @@ -1,122 +1,122 @@ -namespace Ramstack.Parsing.Expressions; - -/// -/// Provides an abstract base class for visiting or rewriting expression trees, -/// producing a result of type . -/// -/// The type of the result produced by visiting the expression tree nodes. -public abstract class ExprVisitor -{ - /// - /// Dispatches an expression to the appropriate specialized visit method based on its . - /// - /// The to visit. - /// - /// A result of type produced by the corresponding visit method. - /// - public virtual T Visit(Expr expr) => - expr.Accept(this); - - /// - /// Visits a list of expressions and returns a collection of results. - /// - /// The of instances to visit. - /// - /// An containing the results of type for each visited expression. - /// - /// - /// Returns an empty list if is empty; otherwise, visits each expression in sequence. - /// - public virtual IReadOnlyList Visit(IReadOnlyList nodes) - { - if (nodes.Count == 0) - return []; - - var result = new T[nodes.Count]; - for (var i = 0; i < result.Length; i++) - result[i] = Visit(nodes[i]); - - return result; - } - - /// - /// Visits a reference expression node. - /// - /// The to visit. - /// - /// A result of type produced by processing the reference expression. - /// - protected internal abstract T VisitReference(Expr.Reference expr); - - /// - /// Visits a literal expression node. - /// - /// The to visit. - /// - /// A result of type produced by processing the literal expression. - /// - protected internal abstract T VisitLiteral(Expr.Literal expr); - - /// - /// Visits a binary operation expression node. - /// - /// The to visit. - /// - /// A result of type produced by processing the binary expression. - /// - protected internal abstract T VisitBinary(Expr.Binary expr); - - /// - /// Visits a method call expression node. - /// - /// The to visit. - /// - /// A result of type produced by processing the call expression. - /// - protected internal abstract T VisitCall(Expr.Call expr); - - /// - /// Visits an indexer expression node. - /// - /// The to visit. - /// - /// A result of type produced by processing the indexer expression. - /// - protected internal abstract T VisitIndex(Expr.Indexer expr); - - /// - /// Visits a member access expression node. - /// - /// The to visit. - /// - /// A result of type produced by processing the member access expression. - /// - protected internal abstract T VisitMemberAccess(Expr.MemberAccess expr); - - /// - /// Visits a unary operation expression node. - /// - /// The to visit. - /// - /// A result of type produced by processing the unary expression. - /// - protected internal abstract T VisitUnary(Expr.Unary expr); - - /// - /// Visits a conditional (ternary) expression node. - /// - /// The to visit. - /// - /// A result of type produced by processing the conditional expression. - /// - protected internal abstract T VisitConditional(Expr.Conditional expr); - - /// - /// Visits a parenthesized expression node. - /// - /// The to visit. - /// - /// A result of type produced by processing the parenthesized expression. - /// - protected internal abstract T VisitParenthesized(Expr.Parenthesized expr); -} +namespace Ramstack.Parsing.Expressions; + +/// +/// Provides an abstract base class for visiting or rewriting expression trees, +/// producing a result of type . +/// +/// The type of the result produced by visiting the expression tree nodes. +public abstract class ExprVisitor +{ + /// + /// Dispatches an expression to the appropriate specialized visit method based on its . + /// + /// The to visit. + /// + /// A result of type produced by the corresponding visit method. + /// + public virtual T Visit(Expr expr) => + expr.Accept(this); + + /// + /// Visits a list of expressions and returns a collection of results. + /// + /// The of instances to visit. + /// + /// An containing the results of type for each visited expression. + /// + /// + /// Returns an empty list if is empty; otherwise, visits each expression in sequence. + /// + public virtual IReadOnlyList Visit(IReadOnlyList nodes) + { + if (nodes.Count == 0) + return []; + + var result = new T[nodes.Count]; + for (var i = 0; i < result.Length; i++) + result[i] = Visit(nodes[i]); + + return result; + } + + /// + /// Visits a reference expression node. + /// + /// The to visit. + /// + /// A result of type produced by processing the reference expression. + /// + protected internal abstract T VisitReference(Expr.Reference expr); + + /// + /// Visits a literal expression node. + /// + /// The to visit. + /// + /// A result of type produced by processing the literal expression. + /// + protected internal abstract T VisitLiteral(Expr.Literal expr); + + /// + /// Visits a binary operation expression node. + /// + /// The to visit. + /// + /// A result of type produced by processing the binary expression. + /// + protected internal abstract T VisitBinary(Expr.Binary expr); + + /// + /// Visits a method call expression node. + /// + /// The to visit. + /// + /// A result of type produced by processing the call expression. + /// + protected internal abstract T VisitCall(Expr.Call expr); + + /// + /// Visits an indexer expression node. + /// + /// The to visit. + /// + /// A result of type produced by processing the indexer expression. + /// + protected internal abstract T VisitIndex(Expr.Indexer expr); + + /// + /// Visits a member access expression node. + /// + /// The to visit. + /// + /// A result of type produced by processing the member access expression. + /// + protected internal abstract T VisitMemberAccess(Expr.MemberAccess expr); + + /// + /// Visits a unary operation expression node. + /// + /// The to visit. + /// + /// A result of type produced by processing the unary expression. + /// + protected internal abstract T VisitUnary(Expr.Unary expr); + + /// + /// Visits a conditional (ternary) expression node. + /// + /// The to visit. + /// + /// A result of type produced by processing the conditional expression. + /// + protected internal abstract T VisitConditional(Expr.Conditional expr); + + /// + /// Visits a parenthesized expression node. + /// + /// The to visit. + /// + /// A result of type produced by processing the parenthesized expression. + /// + protected internal abstract T VisitParenthesized(Expr.Parenthesized expr); +} diff --git a/src/Ramstack.ExpressionParser/Expressions/Identifier.cs b/src/Ramstack.ExpressionParser/Expressions/Identifier.cs index 99d5f82..d930c19 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Identifier.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Identifier.cs @@ -1,23 +1,23 @@ -namespace Ramstack.Parsing.Expressions; - -/// -/// Represents an identifier in an expression, encapsulating its name as a string. -/// -public sealed class Identifier(string name) -{ - /// - /// Gets the name of the identifier. - /// - public string Name { get; } = name; - - /// - /// Deconstructs the identifier into its constituent name. - /// - /// The name of the identifier, output as a string. - public void Deconstruct(out string name) => - name = Name; - - /// - public override string ToString() => - Name; -} +namespace Ramstack.Parsing.Expressions; + +/// +/// Represents an identifier in an expression, encapsulating its name as a string. +/// +public sealed class Identifier(string name) +{ + /// + /// Gets the name of the identifier. + /// + public string Name { get; } = name; + + /// + /// Deconstructs the identifier into its constituent name. + /// + /// The name of the identifier, output as a string. + public void Deconstruct(out string name) => + name = Name; + + /// + public override string ToString() => + Name; +} diff --git a/src/Ramstack.ExpressionParser/Expressions/UnaryType.cs b/src/Ramstack.ExpressionParser/Expressions/UnaryType.cs index ef344e8..4da0230 100644 --- a/src/Ramstack.ExpressionParser/Expressions/UnaryType.cs +++ b/src/Ramstack.ExpressionParser/Expressions/UnaryType.cs @@ -1,47 +1,47 @@ -namespace Ramstack.Parsing.Expressions; - -/// -/// Defines the types of unary operations supported in an expression tree. -/// -public enum UnaryType -{ - /// - /// Represents a type cast or conversion operation, such as converting a value to a specific type. - /// - /// - /// In the expression x:int, this indicates a conversion of x to an integer. - /// - Convert, - - /// - /// Represents an arithmetic negation operation. - /// - /// - /// In the expression -x, this indicates the arithmetic negation of x. - /// - Negate, - - /// - /// Represents a logical negation operation. - /// - /// - /// In the expression !x, this indicates a logical NOT operation on x. - /// - Not, - - /// - /// Represents a bitwise ones complement operation, flipping all bits of a value. - /// - /// - /// In the expression ~x, this indicates a ones complement operation on x. - /// - OnesComplement, - - /// - /// Represents a unary plus operation. - /// - /// - /// In the expression +x, this indicates a unary plus operation on x. - /// - UnaryPlus -} +namespace Ramstack.Parsing.Expressions; + +/// +/// Defines the types of unary operations supported in an expression tree. +/// +public enum UnaryType +{ + /// + /// Represents a type cast or conversion operation, such as converting a value to a specific type. + /// + /// + /// In the expression x:int, this indicates a conversion of x to an integer. + /// + Convert, + + /// + /// Represents an arithmetic negation operation. + /// + /// + /// In the expression -x, this indicates the arithmetic negation of x. + /// + Negate, + + /// + /// Represents a logical negation operation. + /// + /// + /// In the expression !x, this indicates a logical NOT operation on x. + /// + Not, + + /// + /// Represents a bitwise ones complement operation, flipping all bits of a value. + /// + /// + /// In the expression ~x, this indicates a ones complement operation on x. + /// + OnesComplement, + + /// + /// Represents a unary plus operation. + /// + /// + /// In the expression +x, this indicates a unary plus operation on x. + /// + UnaryPlus +} diff --git a/src/Ramstack.ExpressionParser/Internal/Error.cs b/src/Ramstack.ExpressionParser/Internal/Error.cs index 40cc9e2..91ed1b7 100644 --- a/src/Ramstack.ExpressionParser/Internal/Error.cs +++ b/src/Ramstack.ExpressionParser/Internal/Error.cs @@ -1,109 +1,109 @@ -using System.Reflection; - -namespace Ramstack.Parsing.Internal; - -/// -/// Provides helper methods for throwing exceptions during expression parsing to simplify error handling. -/// -internal static class Error -{ - /// - /// Throws a indicating an unresolved symbol. - /// - /// The that could not be resolved. - [DoesNotReturn] - public static void CannotResolveSymbol(Identifier identifier) => - throw new ParseErrorException($"Cannot resolve symbol '{identifier}'."); - - /// - /// Throws a indicating an identifier was expected. - /// - /// The encountered where an identifier was expected. - [DoesNotReturn] - public static void IdentifierExpected(Expr expr) => - throw new ParseErrorException($"Identifier expected (expression: {expr})."); - - /// - /// Throws a indicating a method name was expected. - /// - /// The encountered where a method name was expected. - [DoesNotReturn] - public static void MethodNameExpected(Expr expr) => - throw new ParseErrorException($"Method name expected (expression: {expr})."); - - /// - /// Throws a indicating a non-invocable member was used like a method. - /// - /// The representing the non-invocable member. - [DoesNotReturn] - public static void NonInvocableMember(Expr expr) => - throw new ParseErrorException($"Non-invocable member '{expr}' cannot be used like a method."); - - /// - /// Throws a indicating a unary operator cannot be applied to an operand. - /// - /// The containing the operator. - /// The of the operand. - [DoesNotReturn] - public static void NonApplicableUnaryOperator(Expr.Unary expr, Type operandType) - { - var message = $"Unary operator '{expr.Operator}' cannot be applied to operand of type '{operandType}'."; - throw new ParseErrorException(message); - } - - /// - /// Throws a indicating a binary operator cannot be applied to its operands. - /// - /// The representing the binary operator. - /// The of the left operand. - /// The of the right operand. - [DoesNotReturn] - public static void NonApplicableBinaryOperator(Identifier op, Type left, Type right) - { - var message = $"Operator '{op}' cannot be applied to operands of type '{left}' and '{right}'."; - throw new ParseErrorException(message); - } - - /// - /// Throws a indicating an implicit type conversion is not possible. - /// - /// The source of the operand. - /// The target for the conversion. - [DoesNotReturn] - public static void MissingImplicitConversion(Type operandType, Type conversionType) - { - var message = $"Cannot implicitly convert type '{operandType}' to '{conversionType}'."; - throw new ParseErrorException(message); - } - - /// - /// Throws a indicating indexing cannot be applied to a type. - /// - /// The that does not support indexing. - [DoesNotReturn] - public static void NonIndexingType(Type type) - { - var message = $"Cannot apply indexing with [] to an expression of type '{type}'."; - throw new ParseErrorException(message); - } - - /// - /// Throws a indicating an ambiguous match among multiple candidates. - /// - /// The collection of objects representing ambiguous matches. - [DoesNotReturn] - public static void AmbiguousMatch(IEnumerable candidates) - { - var names = string.Join("\r\n ", candidates.Select(c => $"{c} (in {c.DeclaringType})")); - throw new ParseErrorException($"Ambiguous match found:\r\n {names}"); - } - - /// - /// Throws a with a custom error message. - /// - /// The custom error message, or null for a default message. - /// Always thrown with the specified . - [DoesNotReturn] - public static void Throw(string? message) => - throw new ParseErrorException(message); -} +using System.Reflection; + +namespace Ramstack.Parsing.Internal; + +/// +/// Provides helper methods for throwing exceptions during expression parsing to simplify error handling. +/// +internal static class Error +{ + /// + /// Throws a indicating an unresolved symbol. + /// + /// The that could not be resolved. + [DoesNotReturn] + public static void CannotResolveSymbol(Identifier identifier) => + throw new ParseErrorException($"Cannot resolve symbol '{identifier}'."); + + /// + /// Throws a indicating an identifier was expected. + /// + /// The encountered where an identifier was expected. + [DoesNotReturn] + public static void IdentifierExpected(Expr expr) => + throw new ParseErrorException($"Identifier expected (expression: {expr})."); + + /// + /// Throws a indicating a method name was expected. + /// + /// The encountered where a method name was expected. + [DoesNotReturn] + public static void MethodNameExpected(Expr expr) => + throw new ParseErrorException($"Method name expected (expression: {expr})."); + + /// + /// Throws a indicating a non-invocable member was used like a method. + /// + /// The representing the non-invocable member. + [DoesNotReturn] + public static void NonInvocableMember(Expr expr) => + throw new ParseErrorException($"Non-invocable member '{expr}' cannot be used like a method."); + + /// + /// Throws a indicating a unary operator cannot be applied to an operand. + /// + /// The containing the operator. + /// The of the operand. + [DoesNotReturn] + public static void NonApplicableUnaryOperator(Expr.Unary expr, Type operandType) + { + var message = $"Unary operator '{expr.Operator}' cannot be applied to operand of type '{operandType}'."; + throw new ParseErrorException(message); + } + + /// + /// Throws a indicating a binary operator cannot be applied to its operands. + /// + /// The representing the binary operator. + /// The of the left operand. + /// The of the right operand. + [DoesNotReturn] + public static void NonApplicableBinaryOperator(Identifier op, Type left, Type right) + { + var message = $"Operator '{op}' cannot be applied to operands of type '{left}' and '{right}'."; + throw new ParseErrorException(message); + } + + /// + /// Throws a indicating an implicit type conversion is not possible. + /// + /// The source of the operand. + /// The target for the conversion. + [DoesNotReturn] + public static void MissingImplicitConversion(Type operandType, Type conversionType) + { + var message = $"Cannot implicitly convert type '{operandType}' to '{conversionType}'."; + throw new ParseErrorException(message); + } + + /// + /// Throws a indicating indexing cannot be applied to a type. + /// + /// The that does not support indexing. + [DoesNotReturn] + public static void NonIndexingType(Type type) + { + var message = $"Cannot apply indexing with [] to an expression of type '{type}'."; + throw new ParseErrorException(message); + } + + /// + /// Throws a indicating an ambiguous match among multiple candidates. + /// + /// The collection of objects representing ambiguous matches. + [DoesNotReturn] + public static void AmbiguousMatch(IEnumerable candidates) + { + var names = string.Join("\r\n ", candidates.Select(c => $"{c} (in {c.DeclaringType})")); + throw new ParseErrorException($"Ambiguous match found:\r\n {names}"); + } + + /// + /// Throws a with a custom error message. + /// + /// The custom error message, or null for a default message. + /// Always thrown with the specified . + [DoesNotReturn] + public static void Throw(string? message) => + throw new ParseErrorException(message); +} diff --git a/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs b/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs index 7aed137..23f69f4 100644 --- a/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs +++ b/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs @@ -1,424 +1,424 @@ -// -// This file is based on the System.DefaultBinder class from the .NET Foundation. -// The original implementation is licensed under the MIT license. -// -// Source: https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs -// - -using System.Reflection; - -namespace Ramstack.Parsing.Internal; - -/// -/// Represents a helper class that provides functionality to resolve a method -/// from a set of candidate methods based on specified parameter types. -/// -internal static class MethodResolver -{ - /// - /// Resolves the most appropriate method from the provided array of methods - /// that matches the specified parameter types. - /// - /// An array of methods representing the candidates for matching. - /// The argument types used to locate a matching method. - /// - /// The resolved if a matching method is found; otherwise, null. - /// - public static MethodBase? ResolveMethod(IReadOnlyList match, Type[] argumentTypes) - { - if (match.Count == 0) - throw new ArgumentException("Value cannot be an empty collection."); - - var candidates = match.ToArray(); - var parameterArrayTypes = new Type?[candidates.Length]; - - // Find the method that matches... - var currentIndex = 0; - - // Filter methods by parameter count and type - for (var i = 0; i < candidates.Length; i++) - { - var paramArrayType = default(Type?); - - // Validate the parameters. - var parameters = candidates[i].GetParameters(); - - // Match method by parameter count - if (parameters.Length == 0) - { - // No formal parameters - if (argumentTypes.Length != 0) - if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0) - continue; - - // This is a valid routine so we move it up the candidates list. - candidates[currentIndex++] = candidates[i]; - continue; - } - - int j; - if (parameters.Length > argumentTypes.Length) - { - // Shortage of provided parameters - // - // If the number of parameters is greater than the number of argumentTypes then - // we are in the situation were we may be using default values. - for (j = argumentTypes.Length; j < parameters.Length - 1; j++) - { - if (parameters[j].DefaultValue == DBNull.Value) - break; - } - - if (j != parameters.Length - 1) - continue; - - if (parameters[j].DefaultValue == DBNull.Value) - { - if (!parameters[j].ParameterType.IsArray) - continue; - - if (!parameters[j].IsDefined(typeof(ParamArrayAttribute), true)) - continue; - - paramArrayType = parameters[j].ParameterType.GetElementType(); - } - } - else if (parameters.Length < argumentTypes.Length) - { - // Excess provided parameters - - // Test for the ParamArray case - var lastParameterIndex = parameters.Length - 1; - - if (!parameters[lastParameterIndex].ParameterType.IsArray) - continue; - - if (!parameters[lastParameterIndex].IsDefined(typeof(ParamArrayAttribute), true)) - continue; - - paramArrayType = parameters[lastParameterIndex].ParameterType.GetElementType(); - } - else - { - // Test for paramArray, save paramArray type - var lastParameterIndex = parameters.Length - 1; - var lastParameterType = parameters[lastParameterIndex].ParameterType; - - if (lastParameterType.IsArray) - if (parameters[lastParameterIndex].IsDefined(typeof(ParamArrayAttribute), true)) - if (!lastParameterType.IsAssignableFrom(argumentTypes[lastParameterIndex])) - paramArrayType = lastParameterType.GetElementType(); - } - - var argumentsToCheck = paramArrayType is null ? argumentTypes.Length : parameters.Length - 1; - - // Match method by parameter type - for (j = 0; j < argumentsToCheck && j < argumentTypes.Length; j++) - { - // Classic argument coercion checks - - // get the formal type - var parameterType = parameters[j].ParameterType; - - if (parameterType.IsByRef) - { - Debug.Assert(parameterType.GetElementType() is not null); - parameterType = parameterType.GetElementType()!; - } - - // the type is the same - if (parameterType == argumentTypes[j]) - continue; - - // the type is Object, so it will match everything - if (parameterType == typeof(object)) - continue; - - // now do a "classic" type check - if (parameterType.IsPrimitive) - { - if (!TypeUtils.CanConvertPrimitive(argumentTypes[j], parameterType)) - break; - } - else - { - //if (argumentTypes[j] == typeof(object)) - // continue; - - if (!parameterType.IsAssignableFrom(argumentTypes[j])) - { - if (argumentTypes[j].IsCOMObject) - // ReSharper disable once PossibleMistakenSystemTypeArgument - if (parameterType.IsInstanceOfType(argumentTypes[j])) - continue; - - break; - } - } - } - - if (paramArrayType is not null && j == parameters.Length - 1) - { - // Check that excess arguments can be placed in the param array - for (; j < argumentTypes.Length; j++) - { - if (paramArrayType.IsPrimitive) - { - if (!TypeUtils.CanConvertPrimitive(argumentTypes[j], paramArrayType)) - break; - } - else - { - //if (argumentTypes[j] == typeof(object)) - // continue; - - if (!paramArrayType.IsAssignableFrom(argumentTypes[j])) - { - if (argumentTypes[j].IsCOMObject) - // ReSharper disable once PossibleMistakenSystemTypeArgument - if (paramArrayType.IsInstanceOfType(argumentTypes[j])) - continue; - - break; - } - } - } - } - - if (j == argumentTypes.Length) - { - // This is a valid routine so we move it up the candidates list - parameterArrayTypes[currentIndex] = paramArrayType; - candidates[currentIndex++] = candidates[i]; - } - } - - // If we didn't find a method - if (currentIndex == 0) - return null; - - if (currentIndex == 1) - return candidates[0]; - - var min = 0; - for (var i = 1; i < currentIndex; i++) - { - // Walk all of the methods looking the most specific method to invoke - var newMin = FindMostSpecificMethod( - candidates[min], - parameterArrayTypes[min], - candidates[i], - parameterArrayTypes[i], - argumentTypes); - - // Ambiguous match found - if (newMin == 0) - return null; - - if (newMin == 2) - min = i; - } - - return candidates[min]; - } - - private static int FindMostSpecific( - ParameterInfo[] p1, Type? paramArrayType1, - ParameterInfo[] p2, Type? paramArrayType2, - Type[] types) - { - // A method using params is always less specific than one not using params - if (paramArrayType1 is not null && paramArrayType2 is null) - return 2; - - if (paramArrayType1 is null && paramArrayType2 is not null) - return 1; - - // now either p1 and p2 both use params or neither does. - - var p1Less = false; - var p2Less = false; - - for (var i = 0; i < types.Length; i++) - { - // If a param array is present, then either - // the user re-ordered the parameters in which case - // the argument to the param array is either an array - // in which case the params is conceptually ignored and so paramArrayType1 is null - // or the argument to the param array is a single element - // in which case paramOrder[i] == p1.Length - 1 for that element - // or the user did not re-order the parameters in which case - // the paramOrder array could contain indexes larger than p.Length - 1 (see VSW 577286) - // so any index >= p.Length - 1 is being put in the param array - - var c1 = paramArrayType1 is not null && i >= p1.Length - 1 - ? paramArrayType1 - : p1[i].ParameterType; - - var c2 = paramArrayType2 is not null && i >= p2.Length - 1 - ? paramArrayType2 - : p2[i].ParameterType; - - if (c1 == c2) - continue; - - switch (FindMostSpecificType(c1, c2, types[i])) - { - case 0: return 0; - case 1: p1Less = true; break; - case 2: p2Less = true; break; - } - } - - // Two way p1Less and p2Less can be equal. All the arguments are the - // same they both equal false, otherwise there were things that both - // were the most specific type on.... - if (p1Less == p2Less) - { - // if we cannot tell which is a better match based on parameter types (p1Less == p2Less), - // let's see which one has the most matches without using the params array (the longer one wins). - if (!p1Less) - { - if (p1.Length > p2.Length) - return 1; - - if (p2.Length > p1.Length) - return 2; - } - - return 0; - } - - return p1Less ? 1 : 2; - } - - private static int FindMostSpecificType(Type c1, Type c2, Type t) - { - // If the two types are exact move on... - if (c1 == c2) - return 0; - - if (c1 == t) - return 1; - - if (c2 == t) - return 2; - - if (c1.IsByRef || c2.IsByRef) - { - if (c1.IsByRef && c2.IsByRef) - { - c1 = c1.GetElementType()!; - c2 = c2.GetElementType()!; - } - else if (c1.IsByRef) - { - if (c1.GetElementType() == c2) - return 2; - - c1 = c1.GetElementType()!; - } - else - { - if (c2.GetElementType() == c1) - return 1; - - c2 = c2.GetElementType()!; - } - } - - bool c1FromC2; - bool c2FromC1; - - // ReSharper disable once ConditionIsAlwaysTrueOrFalse - Debug.Assert(c1 is not null); - - // ReSharper disable once ConditionIsAlwaysTrueOrFalse - Debug.Assert(c2 is not null); - - if (c1.IsPrimitive && c2.IsPrimitive) - { - c1FromC2 = TypeUtils.CanConvertPrimitive(c2, c1); - c2FromC1 = TypeUtils.CanConvertPrimitive(c1, c2); - } - else - { - c1FromC2 = c1.IsAssignableFrom(c2); - c2FromC1 = c2.IsAssignableFrom(c1); - } - - if (c1FromC2 == c2FromC1) - return 0; - - if (c1FromC2) - return 2; - - return 1; - } - - private static int FindMostSpecificMethod( - MethodBase m1, Type? paramArrayType1, - MethodBase m2, Type? paramArrayType2, - Type[] types) - { - // Find the most specific method based on the parameters. - var res = FindMostSpecific( - m1.GetParameters(), paramArrayType1, - m2.GetParameters(), paramArrayType2, types); - - // If the match was not ambiguous then return the result. - if (res != 0) - return res; - - // Check to see if the methods have the exact same name and signature. - if (CompareSignature(m1, m2)) - { - Debug.Assert(m1.DeclaringType is not null); - Debug.Assert(m2.DeclaringType is not null); - - // Determine the depth of the declaring types for both methods. - var hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType); - var hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType); - - // The most derived method is the most specific one. - if (hierarchyDepth1 == hierarchyDepth2) - return 0; - - if (hierarchyDepth1 < hierarchyDepth2) - return 2; - - return 1; - } - - // The match is ambiguous. - return 0; - } - - private static bool CompareSignature(MethodBase m1, MethodBase m2) - { - var params1 = m1.GetParameters(); - var params2 = m2.GetParameters(); - - if (params1.Length != params2.Length) - return false; - - for (var i = 0; i < params1.Length; i++) - if (params1[i].ParameterType != params2[i].ParameterType) - return false; - - return true; - } - - private static int GetHierarchyDepth(Type? type) - { - var depth = 0; - do - { - depth++; - type = type!.BaseType; - } - while (type is not null); - - return depth; - } -} +// +// This file is based on the System.DefaultBinder class from the .NET Foundation. +// The original implementation is licensed under the MIT license. +// +// Source: https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs +// + +using System.Reflection; + +namespace Ramstack.Parsing.Internal; + +/// +/// Represents a helper class that provides functionality to resolve a method +/// from a set of candidate methods based on specified parameter types. +/// +internal static class MethodResolver +{ + /// + /// Resolves the most appropriate method from the provided array of methods + /// that matches the specified parameter types. + /// + /// An array of methods representing the candidates for matching. + /// The argument types used to locate a matching method. + /// + /// The resolved if a matching method is found; otherwise, null. + /// + public static MethodBase? ResolveMethod(IReadOnlyList match, Type[] argumentTypes) + { + if (match.Count == 0) + throw new ArgumentException("Value cannot be an empty collection."); + + var candidates = match.ToArray(); + var parameterArrayTypes = new Type?[candidates.Length]; + + // Find the method that matches... + var currentIndex = 0; + + // Filter methods by parameter count and type + for (var i = 0; i < candidates.Length; i++) + { + var paramArrayType = default(Type?); + + // Validate the parameters. + var parameters = candidates[i].GetParameters(); + + // Match method by parameter count + if (parameters.Length == 0) + { + // No formal parameters + if (argumentTypes.Length != 0) + if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0) + continue; + + // This is a valid routine so we move it up the candidates list. + candidates[currentIndex++] = candidates[i]; + continue; + } + + int j; + if (parameters.Length > argumentTypes.Length) + { + // Shortage of provided parameters + // + // If the number of parameters is greater than the number of argumentTypes then + // we are in the situation were we may be using default values. + for (j = argumentTypes.Length; j < parameters.Length - 1; j++) + { + if (parameters[j].DefaultValue == DBNull.Value) + break; + } + + if (j != parameters.Length - 1) + continue; + + if (parameters[j].DefaultValue == DBNull.Value) + { + if (!parameters[j].ParameterType.IsArray) + continue; + + if (!parameters[j].IsDefined(typeof(ParamArrayAttribute), true)) + continue; + + paramArrayType = parameters[j].ParameterType.GetElementType(); + } + } + else if (parameters.Length < argumentTypes.Length) + { + // Excess provided parameters + + // Test for the ParamArray case + var lastParameterIndex = parameters.Length - 1; + + if (!parameters[lastParameterIndex].ParameterType.IsArray) + continue; + + if (!parameters[lastParameterIndex].IsDefined(typeof(ParamArrayAttribute), true)) + continue; + + paramArrayType = parameters[lastParameterIndex].ParameterType.GetElementType(); + } + else + { + // Test for paramArray, save paramArray type + var lastParameterIndex = parameters.Length - 1; + var lastParameterType = parameters[lastParameterIndex].ParameterType; + + if (lastParameterType.IsArray) + if (parameters[lastParameterIndex].IsDefined(typeof(ParamArrayAttribute), true)) + if (!lastParameterType.IsAssignableFrom(argumentTypes[lastParameterIndex])) + paramArrayType = lastParameterType.GetElementType(); + } + + var argumentsToCheck = paramArrayType is null ? argumentTypes.Length : parameters.Length - 1; + + // Match method by parameter type + for (j = 0; j < argumentsToCheck && j < argumentTypes.Length; j++) + { + // Classic argument coercion checks + + // get the formal type + var parameterType = parameters[j].ParameterType; + + if (parameterType.IsByRef) + { + Debug.Assert(parameterType.GetElementType() is not null); + parameterType = parameterType.GetElementType()!; + } + + // the type is the same + if (parameterType == argumentTypes[j]) + continue; + + // the type is Object, so it will match everything + if (parameterType == typeof(object)) + continue; + + // now do a "classic" type check + if (parameterType.IsPrimitive) + { + if (!TypeUtils.CanConvertPrimitive(argumentTypes[j], parameterType)) + break; + } + else + { + //if (argumentTypes[j] == typeof(object)) + // continue; + + if (!parameterType.IsAssignableFrom(argumentTypes[j])) + { + if (argumentTypes[j].IsCOMObject) + // ReSharper disable once PossibleMistakenSystemTypeArgument + if (parameterType.IsInstanceOfType(argumentTypes[j])) + continue; + + break; + } + } + } + + if (paramArrayType is not null && j == parameters.Length - 1) + { + // Check that excess arguments can be placed in the param array + for (; j < argumentTypes.Length; j++) + { + if (paramArrayType.IsPrimitive) + { + if (!TypeUtils.CanConvertPrimitive(argumentTypes[j], paramArrayType)) + break; + } + else + { + //if (argumentTypes[j] == typeof(object)) + // continue; + + if (!paramArrayType.IsAssignableFrom(argumentTypes[j])) + { + if (argumentTypes[j].IsCOMObject) + // ReSharper disable once PossibleMistakenSystemTypeArgument + if (paramArrayType.IsInstanceOfType(argumentTypes[j])) + continue; + + break; + } + } + } + } + + if (j == argumentTypes.Length) + { + // This is a valid routine so we move it up the candidates list + parameterArrayTypes[currentIndex] = paramArrayType; + candidates[currentIndex++] = candidates[i]; + } + } + + // If we didn't find a method + if (currentIndex == 0) + return null; + + if (currentIndex == 1) + return candidates[0]; + + var min = 0; + for (var i = 1; i < currentIndex; i++) + { + // Walk all of the methods looking the most specific method to invoke + var newMin = FindMostSpecificMethod( + candidates[min], + parameterArrayTypes[min], + candidates[i], + parameterArrayTypes[i], + argumentTypes); + + // Ambiguous match found + if (newMin == 0) + return null; + + if (newMin == 2) + min = i; + } + + return candidates[min]; + } + + private static int FindMostSpecific( + ParameterInfo[] p1, Type? paramArrayType1, + ParameterInfo[] p2, Type? paramArrayType2, + Type[] types) + { + // A method using params is always less specific than one not using params + if (paramArrayType1 is not null && paramArrayType2 is null) + return 2; + + if (paramArrayType1 is null && paramArrayType2 is not null) + return 1; + + // now either p1 and p2 both use params or neither does. + + var p1Less = false; + var p2Less = false; + + for (var i = 0; i < types.Length; i++) + { + // If a param array is present, then either + // the user re-ordered the parameters in which case + // the argument to the param array is either an array + // in which case the params is conceptually ignored and so paramArrayType1 is null + // or the argument to the param array is a single element + // in which case paramOrder[i] == p1.Length - 1 for that element + // or the user did not re-order the parameters in which case + // the paramOrder array could contain indexes larger than p.Length - 1 (see VSW 577286) + // so any index >= p.Length - 1 is being put in the param array + + var c1 = paramArrayType1 is not null && i >= p1.Length - 1 + ? paramArrayType1 + : p1[i].ParameterType; + + var c2 = paramArrayType2 is not null && i >= p2.Length - 1 + ? paramArrayType2 + : p2[i].ParameterType; + + if (c1 == c2) + continue; + + switch (FindMostSpecificType(c1, c2, types[i])) + { + case 0: return 0; + case 1: p1Less = true; break; + case 2: p2Less = true; break; + } + } + + // Two way p1Less and p2Less can be equal. All the arguments are the + // same they both equal false, otherwise there were things that both + // were the most specific type on.... + if (p1Less == p2Less) + { + // if we cannot tell which is a better match based on parameter types (p1Less == p2Less), + // let's see which one has the most matches without using the params array (the longer one wins). + if (!p1Less) + { + if (p1.Length > p2.Length) + return 1; + + if (p2.Length > p1.Length) + return 2; + } + + return 0; + } + + return p1Less ? 1 : 2; + } + + private static int FindMostSpecificType(Type c1, Type c2, Type t) + { + // If the two types are exact move on... + if (c1 == c2) + return 0; + + if (c1 == t) + return 1; + + if (c2 == t) + return 2; + + if (c1.IsByRef || c2.IsByRef) + { + if (c1.IsByRef && c2.IsByRef) + { + c1 = c1.GetElementType()!; + c2 = c2.GetElementType()!; + } + else if (c1.IsByRef) + { + if (c1.GetElementType() == c2) + return 2; + + c1 = c1.GetElementType()!; + } + else + { + if (c2.GetElementType() == c1) + return 1; + + c2 = c2.GetElementType()!; + } + } + + bool c1FromC2; + bool c2FromC1; + + // ReSharper disable once ConditionIsAlwaysTrueOrFalse + Debug.Assert(c1 is not null); + + // ReSharper disable once ConditionIsAlwaysTrueOrFalse + Debug.Assert(c2 is not null); + + if (c1.IsPrimitive && c2.IsPrimitive) + { + c1FromC2 = TypeUtils.CanConvertPrimitive(c2, c1); + c2FromC1 = TypeUtils.CanConvertPrimitive(c1, c2); + } + else + { + c1FromC2 = c1.IsAssignableFrom(c2); + c2FromC1 = c2.IsAssignableFrom(c1); + } + + if (c1FromC2 == c2FromC1) + return 0; + + if (c1FromC2) + return 2; + + return 1; + } + + private static int FindMostSpecificMethod( + MethodBase m1, Type? paramArrayType1, + MethodBase m2, Type? paramArrayType2, + Type[] types) + { + // Find the most specific method based on the parameters. + var res = FindMostSpecific( + m1.GetParameters(), paramArrayType1, + m2.GetParameters(), paramArrayType2, types); + + // If the match was not ambiguous then return the result. + if (res != 0) + return res; + + // Check to see if the methods have the exact same name and signature. + if (CompareSignature(m1, m2)) + { + Debug.Assert(m1.DeclaringType is not null); + Debug.Assert(m2.DeclaringType is not null); + + // Determine the depth of the declaring types for both methods. + var hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType); + var hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType); + + // The most derived method is the most specific one. + if (hierarchyDepth1 == hierarchyDepth2) + return 0; + + if (hierarchyDepth1 < hierarchyDepth2) + return 2; + + return 1; + } + + // The match is ambiguous. + return 0; + } + + private static bool CompareSignature(MethodBase m1, MethodBase m2) + { + var params1 = m1.GetParameters(); + var params2 = m2.GetParameters(); + + if (params1.Length != params2.Length) + return false; + + for (var i = 0; i < params1.Length; i++) + if (params1[i].ParameterType != params2[i].ParameterType) + return false; + + return true; + } + + private static int GetHierarchyDepth(Type? type) + { + var depth = 0; + do + { + depth++; + type = type!.BaseType; + } + while (type is not null); + + return depth; + } +} diff --git a/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs b/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs index 62d99ef..71d4eb6 100644 --- a/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs +++ b/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs @@ -1,123 +1,123 @@ -using System.Reflection; - -namespace Ramstack.Parsing.Internal; - -/// -/// Provides reflection based extension methods. -/// -internal static class ReflectionExtensions -{ - /// - /// Determines whether the specified type is a type. - /// - /// The to evaluate. - /// - /// true if the type is a type; otherwise, false. - /// - public static bool IsNullable(this Type type) => - type.IsGenericType && !type.IsGenericTypeDefinition && type.GetGenericTypeDefinition() == typeof(Nullable<>); - - /// - /// Determines whether the specified type is declared as static. - /// - /// The to evaluate. - /// - /// true if the type is declared as static; otherwise, false. - /// - public static bool IsStatic(this Type type) => - type.IsClass && type.IsAbstract && type.IsSealed; - - /// - /// Determines whether the specified member is declared as static. - /// - /// The instance representing the member to evaluate. - /// - /// true if the member is declared as static; otherwise, false. - /// The determination is made as follows: - /// - /// For constructors, checks . - /// For events, checks whether the event's AddMethod is static. - /// For fields, checks . - /// For methods, checks . - /// For properties, checks whether the property's GetMethod or SetMethod is static. - /// For types (including nested types), checks whether the type is static using . - /// - /// - /// - /// Thrown when the member type is unsupported or cannot be evaluated for static declaration. - /// - public static bool IsStatic(this MemberInfo memberInfo) - { - bool result; - - switch (memberInfo.MemberType) - { - case MemberTypes.Constructor: - result = ((ConstructorInfo)memberInfo).IsStatic; - break; - - case MemberTypes.Event: - result = ((EventInfo)memberInfo).AddMethod!.IsStatic; - break; - - case MemberTypes.Field: - result = ((FieldInfo)memberInfo).IsStatic; - break; - - case MemberTypes.Method: - result = ((MethodBase)memberInfo).IsStatic; - break; - - case MemberTypes.Property: - var pi = (PropertyInfo)memberInfo; - result = (pi.GetMethod ?? pi.SetMethod)!.IsStatic; - break; - - case MemberTypes.TypeInfo: - case MemberTypes.NestedType: - result = ((Type)memberInfo).IsStatic(); - break; - - default: - throw new ArgumentException( - $"The member type '{memberInfo.MemberType}' is not supported.", - nameof(memberInfo)); - } - - return result; - } - - /// - /// Determines the runtime type associated with the specified member. - /// - /// The instance representing the member to evaluate. - /// - /// The associated with the member, determined as follows: - /// - /// If the member is a field, returns . - /// If the member is a property, returns . - /// If the member is an event, returns . - /// If the member is a method, returns . - /// If the member is a constructor, returns of the constructor. - /// If the member is a type, returns the itself. - /// - /// - /// - /// Thrown when the member type is unsupported or the runtime type cannot be determined. - /// - public static Type GetMemberType(this MemberInfo memberInfo) - { - return memberInfo.MemberType switch - { - MemberTypes.Field => ((FieldInfo)memberInfo).FieldType, - MemberTypes.Property => ((PropertyInfo)memberInfo).PropertyType, - MemberTypes.Event => ((EventInfo)memberInfo).EventHandlerType, - MemberTypes.Method => ((MethodInfo)memberInfo).ReturnType, - MemberTypes.Constructor => memberInfo.DeclaringType, - MemberTypes.TypeInfo => (Type)memberInfo, - _ => null - } ?? throw new ArgumentException( - $"The member type '{memberInfo.MemberType}' is not supported or its runtime type cannot be determined.", - nameof(memberInfo)); - } -} +using System.Reflection; + +namespace Ramstack.Parsing.Internal; + +/// +/// Provides reflection based extension methods. +/// +internal static class ReflectionExtensions +{ + /// + /// Determines whether the specified type is a type. + /// + /// The to evaluate. + /// + /// true if the type is a type; otherwise, false. + /// + public static bool IsNullable(this Type type) => + type.IsGenericType && !type.IsGenericTypeDefinition && type.GetGenericTypeDefinition() == typeof(Nullable<>); + + /// + /// Determines whether the specified type is declared as static. + /// + /// The to evaluate. + /// + /// true if the type is declared as static; otherwise, false. + /// + public static bool IsStatic(this Type type) => + type.IsClass && type.IsAbstract && type.IsSealed; + + /// + /// Determines whether the specified member is declared as static. + /// + /// The instance representing the member to evaluate. + /// + /// true if the member is declared as static; otherwise, false. + /// The determination is made as follows: + /// + /// For constructors, checks . + /// For events, checks whether the event's AddMethod is static. + /// For fields, checks . + /// For methods, checks . + /// For properties, checks whether the property's GetMethod or SetMethod is static. + /// For types (including nested types), checks whether the type is static using . + /// + /// + /// + /// Thrown when the member type is unsupported or cannot be evaluated for static declaration. + /// + public static bool IsStatic(this MemberInfo memberInfo) + { + bool result; + + switch (memberInfo.MemberType) + { + case MemberTypes.Constructor: + result = ((ConstructorInfo)memberInfo).IsStatic; + break; + + case MemberTypes.Event: + result = ((EventInfo)memberInfo).AddMethod!.IsStatic; + break; + + case MemberTypes.Field: + result = ((FieldInfo)memberInfo).IsStatic; + break; + + case MemberTypes.Method: + result = ((MethodBase)memberInfo).IsStatic; + break; + + case MemberTypes.Property: + var pi = (PropertyInfo)memberInfo; + result = (pi.GetMethod ?? pi.SetMethod)!.IsStatic; + break; + + case MemberTypes.TypeInfo: + case MemberTypes.NestedType: + result = ((Type)memberInfo).IsStatic(); + break; + + default: + throw new ArgumentException( + $"The member type '{memberInfo.MemberType}' is not supported.", + nameof(memberInfo)); + } + + return result; + } + + /// + /// Determines the runtime type associated with the specified member. + /// + /// The instance representing the member to evaluate. + /// + /// The associated with the member, determined as follows: + /// + /// If the member is a field, returns . + /// If the member is a property, returns . + /// If the member is an event, returns . + /// If the member is a method, returns . + /// If the member is a constructor, returns of the constructor. + /// If the member is a type, returns the itself. + /// + /// + /// + /// Thrown when the member type is unsupported or the runtime type cannot be determined. + /// + public static Type GetMemberType(this MemberInfo memberInfo) + { + return memberInfo.MemberType switch + { + MemberTypes.Field => ((FieldInfo)memberInfo).FieldType, + MemberTypes.Property => ((PropertyInfo)memberInfo).PropertyType, + MemberTypes.Event => ((EventInfo)memberInfo).EventHandlerType, + MemberTypes.Method => ((MethodInfo)memberInfo).ReturnType, + MemberTypes.Constructor => memberInfo.DeclaringType, + MemberTypes.TypeInfo => (Type)memberInfo, + _ => null + } ?? throw new ArgumentException( + $"The member type '{memberInfo.MemberType}' is not supported or its runtime type cannot be determined.", + nameof(memberInfo)); + } +} diff --git a/src/Ramstack.ExpressionParser/Internal/TypeUtils.cs b/src/Ramstack.ExpressionParser/Internal/TypeUtils.cs index fb3122a..93772d1 100644 --- a/src/Ramstack.ExpressionParser/Internal/TypeUtils.cs +++ b/src/Ramstack.ExpressionParser/Internal/TypeUtils.cs @@ -1,180 +1,180 @@ -using System.Reflection; - -namespace Ramstack.Parsing.Internal; - -/// -/// Provides type utility methods. -/// -public static class TypeUtils -{ - private static ReadOnlySpan PrimitiveConversions => - [ - /* Empty */ 0, - /* Object */ 0, - /* DBNull */ 0, - /* Boolean */ Primitives.Boolean, - /* Char */ Primitives.Char | Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* SByte */ Primitives.SByte | Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* Byte */ Primitives.Byte | Primitives.Char | Primitives.UInt16 | Primitives.Int16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* Int16 */ Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* UInt16 */ Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* Int32 */ Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* UInt32 */ Primitives.UInt32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* Int64 */ Primitives.Int64 | Primitives.Single | Primitives.Double, - /* UInt64 */ Primitives.UInt64 | Primitives.Single | Primitives.Double, - /* Single */ Primitives.Single | Primitives.Double, - /* Double */ Primitives.Double, - /* Decimal */ Primitives.Decimal, - /* DateTime */ Primitives.DateTime, - /* Unknown */ 0, - /* String */ Primitives.String - ]; - - /// - /// Determines whether the is a numeric type. - /// - /// The to test. - /// - /// A value indicating whether the is a numeric type. - /// - public static bool IsNumeric(Type type) - { - if (!type.IsEnum) - { - switch (Type.GetTypeCode(type)) - { - case TypeCode.Char: - case TypeCode.SByte: - case TypeCode.Byte: - case TypeCode.Int16: - case TypeCode.Int32: - case TypeCode.Int64: - case TypeCode.Double: - case TypeCode.Single: - case TypeCode.UInt16: - case TypeCode.UInt32: - case TypeCode.UInt64: - case TypeCode.Decimal: - return true; - } - } - - return false; - } - - /// - /// Determines whether the specified type represents an integer type. - /// - /// The to evaluate. - /// - /// true if the type is an integer type (signed or unsigned); otherwise, false. - /// - /// - /// This method checks for the following integer types: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static bool IsInteger(Type type) - { - if (!type.IsEnum) - { - switch (Type.GetTypeCode(type)) - { - case TypeCode.SByte: - case TypeCode.Byte: - case TypeCode.Int16: - case TypeCode.UInt16: - case TypeCode.Int32: - case TypeCode.UInt32: - case TypeCode.Int64: - case TypeCode.UInt64: - return true; - } - } - - return false; - } - - - /// - /// Determines whether the can convert to the . - /// - /// The type to convert from. - /// The type to convert to. - /// - /// A value indicating whether the conversion is possible. - /// - public static bool CanConvertPrimitive(Type source, Type target) - { - if (source.IsEnum) - return false; - - if ((source == typeof(IntPtr) && target == typeof(IntPtr)) - || (source == typeof(UIntPtr) && target == typeof(UIntPtr))) - return true; - - var s = PrimitiveConversions[(int)Type.GetTypeCode(source)]; - var t = (Primitives)(1 << (int)Type.GetTypeCode(target)); - - return (s & t) != 0; - } - - /// - /// Attempts to find an implicit conversion operator. - /// - /// The type to convert from. - /// The type to convert to. - /// - /// The conversion operator. - /// - public static MethodInfo? FindConversionOperator(Type source, Type target) - { - var methods = source.GetMethods( - BindingFlags.Public - | BindingFlags.NonPublic - | BindingFlags.Static); - - foreach (var mi in methods) - { - if (mi.Name != "op_Implicit" || mi.ReturnType != target) - continue; - - if (mi.GetParameters()[0].ParameterType == source) - return mi; - } - - return null; - } - - #region Inner type: Primitives - - [Flags] - private enum Primitives - { - Boolean = 1 << TypeCode.Boolean, - Char = 1 << TypeCode.Char, - SByte = 1 << TypeCode.SByte, - Byte = 1 << TypeCode.Byte, - Int16 = 1 << TypeCode.Int16, - UInt16 = 1 << TypeCode.UInt16, - Int32 = 1 << TypeCode.Int32, - UInt32 = 1 << TypeCode.UInt32, - Int64 = 1 << TypeCode.Int64, - UInt64 = 1 << TypeCode.UInt64, - Single = 1 << TypeCode.Single, - Double = 1 << TypeCode.Double, - Decimal = 1 << TypeCode.Decimal, - DateTime = 1 << TypeCode.DateTime, - String = 1 << TypeCode.String - } - - #endregion -} +using System.Reflection; + +namespace Ramstack.Parsing.Internal; + +/// +/// Provides type utility methods. +/// +public static class TypeUtils +{ + private static ReadOnlySpan PrimitiveConversions => + [ + /* Empty */ 0, + /* Object */ 0, + /* DBNull */ 0, + /* Boolean */ Primitives.Boolean, + /* Char */ Primitives.Char | Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* SByte */ Primitives.SByte | Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* Byte */ Primitives.Byte | Primitives.Char | Primitives.UInt16 | Primitives.Int16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* Int16 */ Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* UInt16 */ Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* Int32 */ Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* UInt32 */ Primitives.UInt32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* Int64 */ Primitives.Int64 | Primitives.Single | Primitives.Double, + /* UInt64 */ Primitives.UInt64 | Primitives.Single | Primitives.Double, + /* Single */ Primitives.Single | Primitives.Double, + /* Double */ Primitives.Double, + /* Decimal */ Primitives.Decimal, + /* DateTime */ Primitives.DateTime, + /* Unknown */ 0, + /* String */ Primitives.String + ]; + + /// + /// Determines whether the is a numeric type. + /// + /// The to test. + /// + /// A value indicating whether the is a numeric type. + /// + public static bool IsNumeric(Type type) + { + if (!type.IsEnum) + { + switch (Type.GetTypeCode(type)) + { + case TypeCode.Char: + case TypeCode.SByte: + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.Int64: + case TypeCode.Double: + case TypeCode.Single: + case TypeCode.UInt16: + case TypeCode.UInt32: + case TypeCode.UInt64: + case TypeCode.Decimal: + return true; + } + } + + return false; + } + + /// + /// Determines whether the specified type represents an integer type. + /// + /// The to evaluate. + /// + /// true if the type is an integer type (signed or unsigned); otherwise, false. + /// + /// + /// This method checks for the following integer types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool IsInteger(Type type) + { + if (!type.IsEnum) + { + switch (Type.GetTypeCode(type)) + { + case TypeCode.SByte: + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.UInt16: + case TypeCode.Int32: + case TypeCode.UInt32: + case TypeCode.Int64: + case TypeCode.UInt64: + return true; + } + } + + return false; + } + + + /// + /// Determines whether the can convert to the . + /// + /// The type to convert from. + /// The type to convert to. + /// + /// A value indicating whether the conversion is possible. + /// + public static bool CanConvertPrimitive(Type source, Type target) + { + if (source.IsEnum) + return false; + + if ((source == typeof(IntPtr) && target == typeof(IntPtr)) + || (source == typeof(UIntPtr) && target == typeof(UIntPtr))) + return true; + + var s = PrimitiveConversions[(int)Type.GetTypeCode(source)]; + var t = (Primitives)(1 << (int)Type.GetTypeCode(target)); + + return (s & t) != 0; + } + + /// + /// Attempts to find an implicit conversion operator. + /// + /// The type to convert from. + /// The type to convert to. + /// + /// The conversion operator. + /// + public static MethodInfo? FindConversionOperator(Type source, Type target) + { + var methods = source.GetMethods( + BindingFlags.Public + | BindingFlags.NonPublic + | BindingFlags.Static); + + foreach (var mi in methods) + { + if (mi.Name != "op_Implicit" || mi.ReturnType != target) + continue; + + if (mi.GetParameters()[0].ParameterType == source) + return mi; + } + + return null; + } + + #region Inner type: Primitives + + [Flags] + private enum Primitives + { + Boolean = 1 << TypeCode.Boolean, + Char = 1 << TypeCode.Char, + SByte = 1 << TypeCode.SByte, + Byte = 1 << TypeCode.Byte, + Int16 = 1 << TypeCode.Int16, + UInt16 = 1 << TypeCode.UInt16, + Int32 = 1 << TypeCode.Int32, + UInt32 = 1 << TypeCode.UInt32, + Int64 = 1 << TypeCode.Int64, + UInt64 = 1 << TypeCode.UInt64, + Single = 1 << TypeCode.Single, + Double = 1 << TypeCode.Double, + Decimal = 1 << TypeCode.Decimal, + DateTime = 1 << TypeCode.DateTime, + String = 1 << TypeCode.String + } + + #endregion +} diff --git a/src/Ramstack.ExpressionParser/ParseErrorException.cs b/src/Ramstack.ExpressionParser/ParseErrorException.cs index 04cd7e8..0ea15fa 100644 --- a/src/Ramstack.ExpressionParser/ParseErrorException.cs +++ b/src/Ramstack.ExpressionParser/ParseErrorException.cs @@ -1,27 +1,27 @@ -namespace Ramstack.Parsing; - -/// -/// Represents an exception that occurs during parsing. -/// -public sealed class ParseErrorException : Exception -{ - /// - /// Initializes a new instance of the class - /// with a specified error message. - /// - /// The message that describes the parsing error. - public ParseErrorException(string? message) : base(message) - { - } - - /// - /// Initializes a new instance of the class - /// with a specified error message and a reference to the inner exception that caused this exception. - /// - /// The message that describes the parsing error. - /// The exception that caused the current exception, - /// or if no inner exception is specified. - public ParseErrorException(string? message, Exception? innerException) : base(message, innerException) - { - } -} +namespace Ramstack.Parsing; + +/// +/// Represents an exception that occurs during parsing. +/// +public sealed class ParseErrorException : Exception +{ + /// + /// Initializes a new instance of the class + /// with a specified error message. + /// + /// The message that describes the parsing error. + public ParseErrorException(string? message) : base(message) + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message and a reference to the inner exception that caused this exception. + /// + /// The message that describes the parsing error. + /// The exception that caused the current exception, + /// or if no inner exception is specified. + public ParseErrorException(string? message, Exception? innerException) : base(message, innerException) + { + } +} diff --git a/src/Ramstack.ExpressionParser/Parsers/ConstantNumberParser.cs b/src/Ramstack.ExpressionParser/Parsers/ConstantNumberParser.cs index 222bff9..402736d 100644 --- a/src/Ramstack.ExpressionParser/Parsers/ConstantNumberParser.cs +++ b/src/Ramstack.ExpressionParser/Parsers/ConstantNumberParser.cs @@ -1,438 +1,438 @@ -namespace Ramstack.Parsing.Parsers; - -/// -/// Represents a parser for numeric literals following C# syntax rules. -/// -/// -/// This parser only matches the number itself, since the unary sign -/// is intercepted by the parser responsible for unary operations. -/// -internal sealed class ConstantNumberParser : Parser -{ - /// - /// Gets an instance of the numeric literal parser. - /// - /// - /// This parser only matches the number itself, since the unary sign - /// is intercepted by the parser responsible for unary operations. - /// - public static Parser NumericLiteral { get; } = new ConstantNumberParser(); - - /// - /// A lookup table for converting hexadecimal characters to their corresponding - /// integer values. Each entry in the table corresponds to a character code, - /// and the value indicates the integer value of the hexadecimal digit (0-15). - /// A value of 0xFF indicates that the character is not a valid hexadecimal digit. - /// - private static ReadOnlySpan HexTable => - [ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0x0A, 0x0B, 0x0C, 0xD, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - ]; - - /// - public override bool TryParse(ref ParseContext context, [NotNullWhen(true)] out object? value) - { - var s = context.Remaining; - if (s.Length == 0) - goto FAIL; - - var count = TryParseHexInteger(s, out var number); - if (count == 0) - { - count = TryParseBinInteger(s, out number); - if (count == 0) - { - count = TryParseInteger(s, out number); - if (count == 0) - goto FAIL; - - var p = TryParseReal(s, count, out var real); - if (p != 0) - { - value = real!; - context.Advance(p); - return true; - } - } - } - - count += AdjustNumericType(s[count..], number, out value); - context.Advance(count); - return true; - - FAIL: - value = null; - return false; - } - - private static int TryParseInteger(ReadOnlySpan s, out ulong value) - { - if (s.Length != 0) - { - var p = 0; - var r = 0ul; - - for (; (uint)p < (uint)s.Length; p++) - { - var d = (uint)s[p] - '0'; - if (d > 9) - { - if (p == 0) - { - goto FAIL; - } - - break; - } - - // - // Check for overflow - // - if (r > ulong.MaxValue / 10 - || (r == ulong.MaxValue / 10 && d > ulong.MaxValue % 10)) - goto FAIL; - - r = r * 10 + d; - } - - value = r; - return p; - } - - FAIL: - value = 0; - return 0; - } - - private static int TryParseHexInteger(ReadOnlySpan s, out ulong value) - { - if (s.StartsWith("0x") || s.StartsWith("0X")) - { - var p = 2; - var r = 0ul; - - for (; (uint)p < (uint)s.Length; p++) - { - var c = s[p]; - var d = c < HexTable.Length ? (uint)HexTable[c] : 0xFF; - - if (d == 0xFF) - { - if (p == 2) - { - goto FAIL; - } - - break; - } - - // - // Check for overflow - // - if (r > ulong.MaxValue / 16) - goto FAIL; - - r = r * 16 + d; - } - - value = r; - return p; - } - - FAIL: - value = 0; - return 0; - } - - private static int TryParseBinInteger(ReadOnlySpan s, out ulong value) - { - if (s.StartsWith("0b") || s.StartsWith("0B")) - { - var p = 2; - var r = 0ul; - - for (; (uint)p < (uint)s.Length; p++) - { - var d = (uint)s[p] - '0'; - if (d > 1) - { - if (p == 2) - { - goto FAIL; - } - - break; - } - - // - // Check for overflow - // - if (r > ulong.MaxValue >> 1) - goto FAIL; - - r = (r << 1) + d; - } - - value = r; - return p; - } - - FAIL: - value = 0; - return 0; - } - - private static int TryParseReal(ReadOnlySpan s, int p, out object? value) - { - // - // Float number pattern: \d+(\.\d+)?([Ee][-+]?\d+)? - // - - var i = p; - - if ((uint)i < (uint)s.Length && s[i] == '.') - { - var index = i + 1; - - if ((uint)index < (uint)s.Length && IsAsciiDigit(s[index])) - { - index++; - while ((uint)index < (uint)s.Length && IsAsciiDigit(s[index])) - index++; - - i = index; - } - } - - if ((uint)i < (uint)s.Length && (s[i] & ~0x20) == 'E') - { - var index = i + 1; - - if ((uint)index < (uint)s.Length) - { - // c == '+' || c == '-' - if ((s[index] - '+' & -3) == 0) - index++; - - if ((uint)index < (uint)s.Length && IsAsciiDigit(s[index])) - { - index++; - while ((uint)index < (uint)s.Length && IsAsciiDigit(s[index])) - index++; - - i = index; - } - } - } - - if (i != p) - { - if ((uint)i <= (uint)s.Length) - { - var suffix = (uint)i < (uint)s.Length ? s[i] & ~0x20 : '\0'; - s = s[..i]; - - switch (suffix) - { - case 'F': - i++; - value = ParseSingle(s); - return i; - - case 'M': - i++; - value = ParseDecimal(s); - return i; - - case 'D': - i++; - goto default; - - default: - value = ParseDouble(s); - return i; - } - } - } - - value = null; - return 0; - - static bool IsAsciiDigit(char c) => - (uint)c - '0' <= 9; - - [MethodImpl(MethodImplOptions.NoInlining)] - static object ParseSingle(ReadOnlySpan s) => - float.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture); - - [MethodImpl(MethodImplOptions.NoInlining)] - static object ParseDouble(ReadOnlySpan s) => - double.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture); - - [MethodImpl(MethodImplOptions.NoInlining)] - static object ParseDecimal(ReadOnlySpan s) => - decimal.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture); - } - - private static int AdjustNumericType(ReadOnlySpan s, ulong number, out object value) - { - var hasL = false; - var hasU = false; - - if (s.Length != 0) - { - var c0 = s[0] & ~0x20; - - if (c0 == 'D') - { - value = (double)number; - return 1; - } - - if (c0 == 'F') - { - value = (float)number; - return 1; - } - - if (c0 == 'M') - { - value = new decimal(number); - return 1; - } - - if (c0 is 'L' or 'U') - { - var c1 = s.Length > 1 ? s[1] & ~0x20 : '\0'; - switch ((c0, c1)) - { - case ('L', 'U'): - case ('U', 'L'): - hasL = true; - hasU = true; - break; - - case ('L', _): - hasL = true; - break; - - case ('U', _): - hasU = true; - break; - } - } - } - - // - // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#6453-integer-literals - // - // 6.4.5.3 Integer literals - // - // The type of an integer literal is determined as follows: - // - // * If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong. - // * If the literal is suffixed by U or u, it has the first of these types in which its value can be represented: uint, ulong. - // * If the literal is suffixed by L or l, it has the first of these types in which its value can be represented: long, ulong. - // * If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong. - // - - // - // Note: The following part of the spec is not implemented here. It is implemented in the unary minus analysis. - // The current parser matches only the number itself, since the unary sign (in this case, minus) is intercepted - // by the parser responsible for unary operations. - // - // * When an integer-literal representing the value 2147483648 (2**31) and no integer-type-suffix appears - // as the token immediately following a unary minus operator token (§12.9.3), the result (of both tokens) - // is a constant of type int with the value −2147483648 (−2**31). In all other situations, - // such an integer-literal is of type uint. - // - // * When an integer-literal representing the value 9223372036854775808 (2**63) and no integer-type-suffix - // or the integer-type-suffix L or l appears as the token immediately following a unary minus operator token (§12.9.3), - // the result (of both tokens) is a constant of type long with the value −9223372036854775808 (−2**63). - // In all other situations, such an integer-literal is of type ulong. - // - - // - // If the literal has no suffix, it has the first of these types - // in which its value can be represented: int, uint, long, ulong. - // - if (!hasL && !hasU) - { - switch (number) - { - case <= int.MaxValue: - value = (int)number; - break; - - case <= uint.MaxValue: - value = (uint)number; - break; - - case <= long.MaxValue: - value = (long)number; - break; - - default: - value = number; - break; - } - - return 0; - } - - // - // If the literal is suffixed by U or u, it has the first of these types - // in which its value can be represented: uint, ulong. - // - if (hasU && !hasL) - { - if (number <= uint.MaxValue) - value = (uint)number; - else - value = number; - - return 1; - } - - // - // If the literal is suffixed by L or l, it has the first of these types - // in which its value can be represented: long, ulong. - // - if (hasL && !hasU) - { - switch (number) - { - case <= long.MaxValue: - value = (long)number; - break; - - default: - value = number; - break; - } - - return 1; - } - - // - // If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong. - // - value = number; - return 2; - } -} +namespace Ramstack.Parsing.Parsers; + +/// +/// Represents a parser for numeric literals following C# syntax rules. +/// +/// +/// This parser only matches the number itself, since the unary sign +/// is intercepted by the parser responsible for unary operations. +/// +internal sealed class ConstantNumberParser : Parser +{ + /// + /// Gets an instance of the numeric literal parser. + /// + /// + /// This parser only matches the number itself, since the unary sign + /// is intercepted by the parser responsible for unary operations. + /// + public static Parser NumericLiteral { get; } = new ConstantNumberParser(); + + /// + /// A lookup table for converting hexadecimal characters to their corresponding + /// integer values. Each entry in the table corresponds to a character code, + /// and the value indicates the integer value of the hexadecimal digit (0-15). + /// A value of 0xFF indicates that the character is not a valid hexadecimal digit. + /// + private static ReadOnlySpan HexTable => + [ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0x0A, 0x0B, 0x0C, 0xD, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + ]; + + /// + public override bool TryParse(ref ParseContext context, [NotNullWhen(true)] out object? value) + { + var s = context.Remaining; + if (s.Length == 0) + goto FAIL; + + var count = TryParseHexInteger(s, out var number); + if (count == 0) + { + count = TryParseBinInteger(s, out number); + if (count == 0) + { + count = TryParseInteger(s, out number); + if (count == 0) + goto FAIL; + + var p = TryParseReal(s, count, out var real); + if (p != 0) + { + value = real!; + context.Advance(p); + return true; + } + } + } + + count += AdjustNumericType(s[count..], number, out value); + context.Advance(count); + return true; + + FAIL: + value = null; + return false; + } + + private static int TryParseInteger(ReadOnlySpan s, out ulong value) + { + if (s.Length != 0) + { + var p = 0; + var r = 0ul; + + for (; (uint)p < (uint)s.Length; p++) + { + var d = (uint)s[p] - '0'; + if (d > 9) + { + if (p == 0) + { + goto FAIL; + } + + break; + } + + // + // Check for overflow + // + if (r > ulong.MaxValue / 10 + || (r == ulong.MaxValue / 10 && d > ulong.MaxValue % 10)) + goto FAIL; + + r = r * 10 + d; + } + + value = r; + return p; + } + + FAIL: + value = 0; + return 0; + } + + private static int TryParseHexInteger(ReadOnlySpan s, out ulong value) + { + if (s.StartsWith("0x") || s.StartsWith("0X")) + { + var p = 2; + var r = 0ul; + + for (; (uint)p < (uint)s.Length; p++) + { + var c = s[p]; + var d = c < HexTable.Length ? (uint)HexTable[c] : 0xFF; + + if (d == 0xFF) + { + if (p == 2) + { + goto FAIL; + } + + break; + } + + // + // Check for overflow + // + if (r > ulong.MaxValue / 16) + goto FAIL; + + r = r * 16 + d; + } + + value = r; + return p; + } + + FAIL: + value = 0; + return 0; + } + + private static int TryParseBinInteger(ReadOnlySpan s, out ulong value) + { + if (s.StartsWith("0b") || s.StartsWith("0B")) + { + var p = 2; + var r = 0ul; + + for (; (uint)p < (uint)s.Length; p++) + { + var d = (uint)s[p] - '0'; + if (d > 1) + { + if (p == 2) + { + goto FAIL; + } + + break; + } + + // + // Check for overflow + // + if (r > ulong.MaxValue >> 1) + goto FAIL; + + r = (r << 1) + d; + } + + value = r; + return p; + } + + FAIL: + value = 0; + return 0; + } + + private static int TryParseReal(ReadOnlySpan s, int p, out object? value) + { + // + // Float number pattern: \d+(\.\d+)?([Ee][-+]?\d+)? + // + + var i = p; + + if ((uint)i < (uint)s.Length && s[i] == '.') + { + var index = i + 1; + + if ((uint)index < (uint)s.Length && IsAsciiDigit(s[index])) + { + index++; + while ((uint)index < (uint)s.Length && IsAsciiDigit(s[index])) + index++; + + i = index; + } + } + + if ((uint)i < (uint)s.Length && (s[i] & ~0x20) == 'E') + { + var index = i + 1; + + if ((uint)index < (uint)s.Length) + { + // c == '+' || c == '-' + if ((s[index] - '+' & -3) == 0) + index++; + + if ((uint)index < (uint)s.Length && IsAsciiDigit(s[index])) + { + index++; + while ((uint)index < (uint)s.Length && IsAsciiDigit(s[index])) + index++; + + i = index; + } + } + } + + if (i != p) + { + if ((uint)i <= (uint)s.Length) + { + var suffix = (uint)i < (uint)s.Length ? s[i] & ~0x20 : '\0'; + s = s[..i]; + + switch (suffix) + { + case 'F': + i++; + value = ParseSingle(s); + return i; + + case 'M': + i++; + value = ParseDecimal(s); + return i; + + case 'D': + i++; + goto default; + + default: + value = ParseDouble(s); + return i; + } + } + } + + value = null; + return 0; + + static bool IsAsciiDigit(char c) => + (uint)c - '0' <= 9; + + [MethodImpl(MethodImplOptions.NoInlining)] + static object ParseSingle(ReadOnlySpan s) => + float.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture); + + [MethodImpl(MethodImplOptions.NoInlining)] + static object ParseDouble(ReadOnlySpan s) => + double.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture); + + [MethodImpl(MethodImplOptions.NoInlining)] + static object ParseDecimal(ReadOnlySpan s) => + decimal.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture); + } + + private static int AdjustNumericType(ReadOnlySpan s, ulong number, out object value) + { + var hasL = false; + var hasU = false; + + if (s.Length != 0) + { + var c0 = s[0] & ~0x20; + + if (c0 == 'D') + { + value = (double)number; + return 1; + } + + if (c0 == 'F') + { + value = (float)number; + return 1; + } + + if (c0 == 'M') + { + value = new decimal(number); + return 1; + } + + if (c0 is 'L' or 'U') + { + var c1 = s.Length > 1 ? s[1] & ~0x20 : '\0'; + switch ((c0, c1)) + { + case ('L', 'U'): + case ('U', 'L'): + hasL = true; + hasU = true; + break; + + case ('L', _): + hasL = true; + break; + + case ('U', _): + hasU = true; + break; + } + } + } + + // + // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#6453-integer-literals + // + // 6.4.5.3 Integer literals + // + // The type of an integer literal is determined as follows: + // + // * If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong. + // * If the literal is suffixed by U or u, it has the first of these types in which its value can be represented: uint, ulong. + // * If the literal is suffixed by L or l, it has the first of these types in which its value can be represented: long, ulong. + // * If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong. + // + + // + // Note: The following part of the spec is not implemented here. It is implemented in the unary minus analysis. + // The current parser matches only the number itself, since the unary sign (in this case, minus) is intercepted + // by the parser responsible for unary operations. + // + // * When an integer-literal representing the value 2147483648 (2**31) and no integer-type-suffix appears + // as the token immediately following a unary minus operator token (§12.9.3), the result (of both tokens) + // is a constant of type int with the value −2147483648 (−2**31). In all other situations, + // such an integer-literal is of type uint. + // + // * When an integer-literal representing the value 9223372036854775808 (2**63) and no integer-type-suffix + // or the integer-type-suffix L or l appears as the token immediately following a unary minus operator token (§12.9.3), + // the result (of both tokens) is a constant of type long with the value −9223372036854775808 (−2**63). + // In all other situations, such an integer-literal is of type ulong. + // + + // + // If the literal has no suffix, it has the first of these types + // in which its value can be represented: int, uint, long, ulong. + // + if (!hasL && !hasU) + { + switch (number) + { + case <= int.MaxValue: + value = (int)number; + break; + + case <= uint.MaxValue: + value = (uint)number; + break; + + case <= long.MaxValue: + value = (long)number; + break; + + default: + value = number; + break; + } + + return 0; + } + + // + // If the literal is suffixed by U or u, it has the first of these types + // in which its value can be represented: uint, ulong. + // + if (hasU && !hasL) + { + if (number <= uint.MaxValue) + value = (uint)number; + else + value = number; + + return 1; + } + + // + // If the literal is suffixed by L or l, it has the first of these types + // in which its value can be represented: long, ulong. + // + if (hasL && !hasU) + { + switch (number) + { + case <= long.MaxValue: + value = (long)number; + break; + + default: + value = number; + break; + } + + return 1; + } + + // + // If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong. + // + value = number; + return 2; + } +} diff --git a/src/Ramstack.ExpressionParser/Properties/AssemblyInfo.cs b/src/Ramstack.ExpressionParser/Properties/AssemblyInfo.cs index 149faff..9d36346 100644 --- a/src/Ramstack.ExpressionParser/Properties/AssemblyInfo.cs +++ b/src/Ramstack.ExpressionParser/Properties/AssemblyInfo.cs @@ -1 +1 @@ -[module: SkipLocalsInit] +[module: SkipLocalsInit] diff --git a/src/Ramstack.ExpressionParser/Ramstack.ExpressionParser.csproj b/src/Ramstack.ExpressionParser/Ramstack.ExpressionParser.csproj index f61f318..7ca8cd2 100644 --- a/src/Ramstack.ExpressionParser/Ramstack.ExpressionParser.csproj +++ b/src/Ramstack.ExpressionParser/Ramstack.ExpressionParser.csproj @@ -1,72 +1,72 @@ - - - - net6.0 - Ramstack.Parsing - A flexible expression parser library for .NET, allowing dynamic evaluation and binding of expressions with context-aware support. - enable - enable - latest - true - true - - - - 649;1591 - CS8600;CS8601;CS8602;CS8603;CS8604;CS8610;CS8613;CS8614;CS8618;CS8619;CS8620;CS8625;CS8643;CS8653;CS8714 - - - - https://github.com/rameel/ramstack.expressionparser - Rameel - parser;expression;expression-parser - https://github.com/rameel/ramstack.expressionparser#readme - README.md - MIT - true - snupkg - true - true - true - true - - - - true - - - - - - - - - - - - - - - - - - - - - true - \ - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + + + + net6.0 + Ramstack.Parsing + A flexible expression parser library for .NET, allowing dynamic evaluation and binding of expressions with context-aware support. + enable + enable + latest + true + true + + + + 649;1591 + CS8600;CS8601;CS8602;CS8603;CS8604;CS8610;CS8613;CS8614;CS8618;CS8619;CS8620;CS8625;CS8643;CS8653;CS8714 + + + + https://github.com/rameel/ramstack.expressionparser + Rameel + parser;expression;expression-parser + https://github.com/rameel/ramstack.expressionparser#readme + README.md + MIT + true + snupkg + true + true + true + true + + + + true + + + + + + + + + + + + + + + + + + + + + true + \ + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt b/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt index 3dd97f7..d7c7b91 100644 --- a/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt +++ b/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt @@ -1,467 +1,467 @@ -1:byte + 2:byte -(Convert(Convert(1, Byte), Int32) + Convert(Convert(2, Byte), Int32)) - -1:short + 2 -(Convert(Convert(1, Int16), Int32) + 2) - -1 + 2:short -(1 + Convert(Convert(2, Int16), Int32)) - --1:sbyte --Convert(Convert(1, SByte), Int32) - --2147483648 --2147483648 - --0x80000000 --2147483648 - --9223372036854775808 --9223372036854775808 - --0x8000000000000000 --9223372036854775808 - --5000 >>> 4 -Convert((Convert(-5000, UInt32) >> 4), Int32) - -5000u >>> 4 -(5000 >> 4) - -5000 >>> 4 -Convert((Convert(5000, UInt32) >> 4), Int32) - --9223372036854775808 >>> 4 -Convert((Convert(-9223372036854775808, UInt64) >> 4), Int64) - -5000 >> 4 -(5000 >> 4) - -1:byte << 4 -(Convert(Convert(1, Byte), Int32) << 4) - -byte.MaxValue + 1 -(Convert(Byte.MaxValue, Int32) + 1) - -byte.MaxValue + byte.MinValue -(Convert(Byte.MaxValue, Int32) + Convert(Byte.MinValue, Int32)) - -~1:short -~(Convert(Convert(1, Int16), Int32)) - --100u -Convert(100, Int64) - -null ?? null ?? string.Empty -(null ?? (null ?? String.Empty)) - -(null ?? (null ?? string.Empty)) -(null ?? (null ?? String.Empty)) - -(null ?? (null ?? "")) -(null ?? (null ?? "")) - -1 == 1 ? 2 == 2 ? 3 == 3 ? 4 == 4 : 5 == 5 : 6 == 6 : 7 == 7 -IIF((1 == 1), IIF((2 == 2), IIF((3 == 3), (4 == 4), (5 == 5)), (6 == 6)), (7 == 7)) - -1 + 2 * 3 -(1 + (2 * 3)) - -1 * 2 + 3 -((1 * 2) + 3) - -Math.PI * 2 + 1 -((Math.PI * Convert(2, Double)) + Convert(1, Double)) - -Math.PI:float * 2 + 1 -((Convert(Math.PI, Single) * Convert(2, Single)) + Convert(1, Single)) - -2.93E5f + 2.17d -(Convert(293000, Double) + 2.17) - -2.93E5f + 2.17d + 1ul -((Convert(293000, Double) + 2.17) + Convert(1, Double)) - -18446744073709551615 + 1u -(18446744073709551615 + Convert(1, UInt64)) - --9223372036854775808 - 1 -(-9223372036854775808 - Convert(1, Int64)) - -9223372036854775807 - 1 -(9223372036854775807 - Convert(1, Int64)) - -0u - 9223372036854775808 -(Convert(0, UInt64) - 9223372036854775808) - -1m + 2 -(1 + Convert(2, Decimal)) - -1+2+3+4 -(((1 + 2) + 3) + 4) - -1d+2d -(1 + 2) - -1.2d+2.2d -(1.2 + 2.2) - -2u-1u*3u -(2 - (1 * 3)) - -2lu-1lu*3lu -(2 - (1 * 3)) - -2l-1l*3l -(2 - (1 * 3)) - -2ul-1ul*3ul -(2 - (1 * 3)) - -"test"[0] -"test".get_Chars(0) - -"test"[1 != 0 ? 0 : 1] -"test".get_Chars(IIF((1 != 0), 0, 1)) - -math.min(1, 2) -Min(1, 2) - -min(1, max(3, 4)) -Min(1, Max(3, 4)) - -100.tostring().tochararray()[0] -100.ToString().ToCharArray()[0] - -100.tostring().tochararray()[0].ToString().Length -100.ToString().ToCharArray()[0].ToString().Length - -100.tostring("D").Length -100.ToString("D").Length - -Guid.Newguid().ToString().Length > 0 -(NewGuid().ToString().Length > 0) - -"test".substring(1) -"test".Substring(1) - -"test".substring(1, 3) -"test".Substring(1, 3) - -"test".substring(1, 3).ToUpper().ToLowerInvariant() -"test".Substring(1, 3).ToUpper().ToLowerInvariant() - -object.equals(1, 1) -Equals(Convert(1, Object), Convert(1, Object)) - -object.referenceEquals(1, 1) -ReferenceEquals(Convert(1, Object), Convert(1, Object)) - -DateTime.Today -DateTime.Today - -DateTimeOffset.UnixEpoch -DateTimeOffset.UnixEpoch - -DateTime.Parse(DateTime.Now.ToString()) -Parse(DateTime.Now.ToString()) - -"test\u0020test" -"test test" - -(1 | 2 | 3 | 4) & 0xE -((((1 | 2) | 3) | 4) & 14) - -(10 == 10 || 20 == 20) ? (1 > 0 ? 10 : 20) : (0 < 1 ? 30 : 40) -IIF(((10 == 10) OrElse (20 == 20)), IIF((1 > 0), 10, 20), IIF((0 < 1), 30, 40)) - -0b11110000111100001111 -986895 - -"01234:56789".split(':', None) -"01234:56789".Split(:, StringSplitOptions.None) - -"01234:56789".split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.None) -"01234:56789".Split(:, Convert((Convert(StringSplitOptions.RemoveEmptyEntries, Int32) | Convert(StringSplitOptions.None, Int32)), StringSplitOptions)) - -StringSplitOptions.None & ~StringSplitOptions.RemoveEmptyEntries -Convert((Convert(StringSplitOptions.None, Int32) & Convert(Convert(~(Convert(StringSplitOptions.RemoveEmptyEntries, Int32)), StringSplitOptions), Int32)), StringSplitOptions) - -StringSplitOptions.None | StringSplitOptions.RemoveEmptyEntries -Convert((Convert(StringSplitOptions.None, Int32) | Convert(StringSplitOptions.RemoveEmptyEntries, Int32)), StringSplitOptions) - -~StringSplitOptions.RemoveEmptyEntries -Convert(~(Convert(StringSplitOptions.RemoveEmptyEntries, Int32)), StringSplitOptions) - -1 ^ 1 -(1 ^ 1) - -true ^ false -(True ^ False) - -true | false -(True Or False) - -true & false -(True And False) - -####################################### -# Precedence test -1 + 2 - 4 * 5 / 4 << 1 & -3 ^ 17 | ~5 >> 2 >>> 1 % 5 -((((((1 + 2) - ((4 * 5) / 4)) << 1) & -3) ^ 17) | Convert((Convert((~(5) >> 2), UInt32) >> (1 % 5)), Int32)) - -####################################### -###### Binary Numeric Promotions ###### -####################################### - -####################################### -# If either operand is of type decimal, the other operand is converted to type decimal -1m + 2 -(1 + Convert(2, Decimal)) - -1 + 2m -(Convert(1, Decimal) + 2) - -1m + 2:byte -(1 + Convert(Convert(2, Byte), Decimal)) - -1m + 2:sbyte -(1 + Convert(Convert(2, SByte), Decimal)) - -1m + 2:short -(1 + Convert(Convert(2, Int16), Decimal)) - -1m + 2:ushort -(1 + Convert(Convert(2, UInt16), Decimal)) - -1m + 2:int -(1 + Convert(2, Decimal)) - -1m + 2:uint -(1 + Convert(Convert(2, UInt32), Decimal)) - -1m + 2:long -(1 + Convert(Convert(2, Int64), Decimal)) - -1m + 2:ulong -(1 + Convert(Convert(2, UInt64), Decimal)) - - -####################################### -# If either operand is of type double, the other operand is converted to type double. - -1d + 2 -(1 + Convert(2, Double)) - -1 + 2d -(Convert(1, Double) + 2) - -1.0 + 2:byte -(1 + Convert(Convert(2, Byte), Double)) - -1.0 + 2:sbyte -(1 + Convert(Convert(2, SByte), Double)) - -1.0 + 2:short -(1 + Convert(Convert(2, Int16), Double)) - -1.0 + 2:ushort -(1 + Convert(Convert(2, UInt16), Double)) - -1.0 + 2:int -(1 + Convert(2, Double)) - -1.0 + 2:uint -(1 + Convert(Convert(2, UInt32), Double)) - -1.0 + 2:long -(1 + Convert(Convert(2, Int64), Double)) - -1.0 + 2:ulong -(1 + Convert(Convert(2, UInt64), Double)) - -####################################### -# If either operand is of type float, the other operand is converted to type float. - -1f + 2 -(1 + Convert(2, Single)) - -1 + 2f -(Convert(1, Single) + 2) - -1.0f + 2:byte -(1 + Convert(Convert(2, Byte), Single)) - -1.0f + 2:sbyte -(1 + Convert(Convert(2, SByte), Single)) - -1.0f + 2:short -(1 + Convert(Convert(2, Int16), Single)) - -1.0f + 2:ushort -(1 + Convert(Convert(2, UInt16), Single)) - -1.0f + 2:int -(1 + Convert(2, Single)) - -1.0f + 2:uint -(1 + Convert(Convert(2, UInt32), Single)) - -1.0f + 2:long -(1 + Convert(Convert(2, Int64), Single)) - -1.0f + 2:ulong -(1 + Convert(Convert(2, UInt64), Single)) - -####################################### -# If either operand is of type ulong, the other operand is converted to type ulong - -1ul + 2u -(1 + Convert(2, UInt64)) - -1u + 2ul -(Convert(1, UInt64) + 2) - -1ul + 2:byte -(1 + Convert(Convert(2, Byte), UInt64)) - -1ul + 2:ushort -(1 + Convert(Convert(2, UInt16), UInt64)) - -1ul + 2:uint -(1 + Convert(Convert(2, UInt32), UInt64)) - -1ul + 2:ulong -(1 + Convert(2, UInt64)) - -####################################### -# If either operand is of type long, the other operand is converted to type long. - -1L + 2 -(1 + Convert(2, Int64)) - -1 + 2L -(Convert(1, Int64) + 2) - -1L + 2:byte -(1 + Convert(Convert(2, Byte), Int64)) - -1L + 2:sbyte -(1 + Convert(Convert(2, SByte), Int64)) - -1L + 2:short -(1 + Convert(Convert(2, Int16), Int64)) - -1L + 2:ushort -(1 + Convert(Convert(2, UInt16), Int64)) - -1L + 2:int -(1 + Convert(2, Int64)) - -1L + 2:uint -(1 + Convert(Convert(2, UInt32), Int64)) - -1L + 2:long -(1 + Convert(2, Int64)) - -####################################### -# 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 either operand is of type uint, the other operand is converted to type uint. - -1u + 2 -(Convert(1, Int64) + Convert(2, Int64)) - -1 + 2u -(Convert(1, Int64) + Convert(2, Int64)) - -1u + 2:byte -(1 + Convert(Convert(2, Byte), UInt32)) - -1u + 2:sbyte -(Convert(1, Int64) + Convert(Convert(2, SByte), Int64)) - -1u + 2:short -(Convert(1, Int64) + Convert(Convert(2, Int16), Int64)) - -1u + 2:ushort -(1 + Convert(Convert(2, UInt16), UInt32)) - -1u + 2:int -(Convert(1, Int64) + Convert(2, Int64)) - -1u + 2:uint -(1 + Convert(2, UInt32)) - -####################################### -# Otherwise, both operands are converted to type int. - -1 + 2:byte -(1 + Convert(Convert(2, Byte), Int32)) - -1 + 2:sbyte -(1 + Convert(Convert(2, SByte), Int32)) - -1 + 2:short -(1 + Convert(Convert(2, Int16), Int32)) - -1 + 2:ushort -(1 + Convert(Convert(2, UInt16), Int32)) - -1 + 2:int -(1 + 2) - - -####################################### -###### Unary Numeric Promotions ###### -####################################### - -####################################### -# + operator - -+1:byte -+Convert(Convert(1, Byte), Int32) - -+1:sbyte -+Convert(Convert(1, SByte), Int32) - -+1:short -+Convert(Convert(1, Int16), Int32) - -+1:ushort -+Convert(Convert(1, UInt16), Int32) - -+1:int -+1 - -+1u -+1 - -+1L -+1 - -+1ul -+1 - -####################################### -# - operator - --1:byte --Convert(Convert(1, Byte), Int32) - --1:sbyte --Convert(Convert(1, SByte), Int32) - --1:short --Convert(Convert(1, Int16), Int32) - --1:ushort --Convert(Convert(1, UInt16), Int32) - --1:int --1 - --1u -Convert(1, Int64) - --1L --1 +1:byte + 2:byte +(Convert(Convert(1, Byte), Int32) + Convert(Convert(2, Byte), Int32)) + +1:short + 2 +(Convert(Convert(1, Int16), Int32) + 2) + +1 + 2:short +(1 + Convert(Convert(2, Int16), Int32)) + +-1:sbyte +-Convert(Convert(1, SByte), Int32) + +-2147483648 +-2147483648 + +-0x80000000 +-2147483648 + +-9223372036854775808 +-9223372036854775808 + +-0x8000000000000000 +-9223372036854775808 + +-5000 >>> 4 +Convert((Convert(-5000, UInt32) >> 4), Int32) + +5000u >>> 4 +(5000 >> 4) + +5000 >>> 4 +Convert((Convert(5000, UInt32) >> 4), Int32) + +-9223372036854775808 >>> 4 +Convert((Convert(-9223372036854775808, UInt64) >> 4), Int64) + +5000 >> 4 +(5000 >> 4) + +1:byte << 4 +(Convert(Convert(1, Byte), Int32) << 4) + +byte.MaxValue + 1 +(Convert(Byte.MaxValue, Int32) + 1) + +byte.MaxValue + byte.MinValue +(Convert(Byte.MaxValue, Int32) + Convert(Byte.MinValue, Int32)) + +~1:short +~(Convert(Convert(1, Int16), Int32)) + +-100u +Convert(100, Int64) + +null ?? null ?? string.Empty +(null ?? (null ?? String.Empty)) + +(null ?? (null ?? string.Empty)) +(null ?? (null ?? String.Empty)) + +(null ?? (null ?? "")) +(null ?? (null ?? "")) + +1 == 1 ? 2 == 2 ? 3 == 3 ? 4 == 4 : 5 == 5 : 6 == 6 : 7 == 7 +IIF((1 == 1), IIF((2 == 2), IIF((3 == 3), (4 == 4), (5 == 5)), (6 == 6)), (7 == 7)) + +1 + 2 * 3 +(1 + (2 * 3)) + +1 * 2 + 3 +((1 * 2) + 3) + +Math.PI * 2 + 1 +((Math.PI * Convert(2, Double)) + Convert(1, Double)) + +Math.PI:float * 2 + 1 +((Convert(Math.PI, Single) * Convert(2, Single)) + Convert(1, Single)) + +2.93E5f + 2.17d +(Convert(293000, Double) + 2.17) + +2.93E5f + 2.17d + 1ul +((Convert(293000, Double) + 2.17) + Convert(1, Double)) + +18446744073709551615 + 1u +(18446744073709551615 + Convert(1, UInt64)) + +-9223372036854775808 - 1 +(-9223372036854775808 - Convert(1, Int64)) + +9223372036854775807 - 1 +(9223372036854775807 - Convert(1, Int64)) + +0u - 9223372036854775808 +(Convert(0, UInt64) - 9223372036854775808) + +1m + 2 +(1 + Convert(2, Decimal)) + +1+2+3+4 +(((1 + 2) + 3) + 4) + +1d+2d +(1 + 2) + +1.2d+2.2d +(1.2 + 2.2) + +2u-1u*3u +(2 - (1 * 3)) + +2lu-1lu*3lu +(2 - (1 * 3)) + +2l-1l*3l +(2 - (1 * 3)) + +2ul-1ul*3ul +(2 - (1 * 3)) + +"test"[0] +"test".get_Chars(0) + +"test"[1 != 0 ? 0 : 1] +"test".get_Chars(IIF((1 != 0), 0, 1)) + +math.min(1, 2) +Min(1, 2) + +min(1, max(3, 4)) +Min(1, Max(3, 4)) + +100.tostring().tochararray()[0] +100.ToString().ToCharArray()[0] + +100.tostring().tochararray()[0].ToString().Length +100.ToString().ToCharArray()[0].ToString().Length + +100.tostring("D").Length +100.ToString("D").Length + +Guid.Newguid().ToString().Length > 0 +(NewGuid().ToString().Length > 0) + +"test".substring(1) +"test".Substring(1) + +"test".substring(1, 3) +"test".Substring(1, 3) + +"test".substring(1, 3).ToUpper().ToLowerInvariant() +"test".Substring(1, 3).ToUpper().ToLowerInvariant() + +object.equals(1, 1) +Equals(Convert(1, Object), Convert(1, Object)) + +object.referenceEquals(1, 1) +ReferenceEquals(Convert(1, Object), Convert(1, Object)) + +DateTime.Today +DateTime.Today + +DateTimeOffset.UnixEpoch +DateTimeOffset.UnixEpoch + +DateTime.Parse(DateTime.Now.ToString()) +Parse(DateTime.Now.ToString()) + +"test\u0020test" +"test test" + +(1 | 2 | 3 | 4) & 0xE +((((1 | 2) | 3) | 4) & 14) + +(10 == 10 || 20 == 20) ? (1 > 0 ? 10 : 20) : (0 < 1 ? 30 : 40) +IIF(((10 == 10) OrElse (20 == 20)), IIF((1 > 0), 10, 20), IIF((0 < 1), 30, 40)) + +0b11110000111100001111 +986895 + +"01234:56789".split(':', None) +"01234:56789".Split(:, StringSplitOptions.None) + +"01234:56789".split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.None) +"01234:56789".Split(:, Convert((Convert(StringSplitOptions.RemoveEmptyEntries, Int32) | Convert(StringSplitOptions.None, Int32)), StringSplitOptions)) + +StringSplitOptions.None & ~StringSplitOptions.RemoveEmptyEntries +Convert((Convert(StringSplitOptions.None, Int32) & Convert(Convert(~(Convert(StringSplitOptions.RemoveEmptyEntries, Int32)), StringSplitOptions), Int32)), StringSplitOptions) + +StringSplitOptions.None | StringSplitOptions.RemoveEmptyEntries +Convert((Convert(StringSplitOptions.None, Int32) | Convert(StringSplitOptions.RemoveEmptyEntries, Int32)), StringSplitOptions) + +~StringSplitOptions.RemoveEmptyEntries +Convert(~(Convert(StringSplitOptions.RemoveEmptyEntries, Int32)), StringSplitOptions) + +1 ^ 1 +(1 ^ 1) + +true ^ false +(True ^ False) + +true | false +(True Or False) + +true & false +(True And False) + +####################################### +# Precedence test +1 + 2 - 4 * 5 / 4 << 1 & -3 ^ 17 | ~5 >> 2 >>> 1 % 5 +((((((1 + 2) - ((4 * 5) / 4)) << 1) & -3) ^ 17) | Convert((Convert((~(5) >> 2), UInt32) >> (1 % 5)), Int32)) + +####################################### +###### Binary Numeric Promotions ###### +####################################### + +####################################### +# If either operand is of type decimal, the other operand is converted to type decimal +1m + 2 +(1 + Convert(2, Decimal)) + +1 + 2m +(Convert(1, Decimal) + 2) + +1m + 2:byte +(1 + Convert(Convert(2, Byte), Decimal)) + +1m + 2:sbyte +(1 + Convert(Convert(2, SByte), Decimal)) + +1m + 2:short +(1 + Convert(Convert(2, Int16), Decimal)) + +1m + 2:ushort +(1 + Convert(Convert(2, UInt16), Decimal)) + +1m + 2:int +(1 + Convert(2, Decimal)) + +1m + 2:uint +(1 + Convert(Convert(2, UInt32), Decimal)) + +1m + 2:long +(1 + Convert(Convert(2, Int64), Decimal)) + +1m + 2:ulong +(1 + Convert(Convert(2, UInt64), Decimal)) + + +####################################### +# If either operand is of type double, the other operand is converted to type double. + +1d + 2 +(1 + Convert(2, Double)) + +1 + 2d +(Convert(1, Double) + 2) + +1.0 + 2:byte +(1 + Convert(Convert(2, Byte), Double)) + +1.0 + 2:sbyte +(1 + Convert(Convert(2, SByte), Double)) + +1.0 + 2:short +(1 + Convert(Convert(2, Int16), Double)) + +1.0 + 2:ushort +(1 + Convert(Convert(2, UInt16), Double)) + +1.0 + 2:int +(1 + Convert(2, Double)) + +1.0 + 2:uint +(1 + Convert(Convert(2, UInt32), Double)) + +1.0 + 2:long +(1 + Convert(Convert(2, Int64), Double)) + +1.0 + 2:ulong +(1 + Convert(Convert(2, UInt64), Double)) + +####################################### +# If either operand is of type float, the other operand is converted to type float. + +1f + 2 +(1 + Convert(2, Single)) + +1 + 2f +(Convert(1, Single) + 2) + +1.0f + 2:byte +(1 + Convert(Convert(2, Byte), Single)) + +1.0f + 2:sbyte +(1 + Convert(Convert(2, SByte), Single)) + +1.0f + 2:short +(1 + Convert(Convert(2, Int16), Single)) + +1.0f + 2:ushort +(1 + Convert(Convert(2, UInt16), Single)) + +1.0f + 2:int +(1 + Convert(2, Single)) + +1.0f + 2:uint +(1 + Convert(Convert(2, UInt32), Single)) + +1.0f + 2:long +(1 + Convert(Convert(2, Int64), Single)) + +1.0f + 2:ulong +(1 + Convert(Convert(2, UInt64), Single)) + +####################################### +# If either operand is of type ulong, the other operand is converted to type ulong + +1ul + 2u +(1 + Convert(2, UInt64)) + +1u + 2ul +(Convert(1, UInt64) + 2) + +1ul + 2:byte +(1 + Convert(Convert(2, Byte), UInt64)) + +1ul + 2:ushort +(1 + Convert(Convert(2, UInt16), UInt64)) + +1ul + 2:uint +(1 + Convert(Convert(2, UInt32), UInt64)) + +1ul + 2:ulong +(1 + Convert(2, UInt64)) + +####################################### +# If either operand is of type long, the other operand is converted to type long. + +1L + 2 +(1 + Convert(2, Int64)) + +1 + 2L +(Convert(1, Int64) + 2) + +1L + 2:byte +(1 + Convert(Convert(2, Byte), Int64)) + +1L + 2:sbyte +(1 + Convert(Convert(2, SByte), Int64)) + +1L + 2:short +(1 + Convert(Convert(2, Int16), Int64)) + +1L + 2:ushort +(1 + Convert(Convert(2, UInt16), Int64)) + +1L + 2:int +(1 + Convert(2, Int64)) + +1L + 2:uint +(1 + Convert(Convert(2, UInt32), Int64)) + +1L + 2:long +(1 + Convert(2, Int64)) + +####################################### +# 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 either operand is of type uint, the other operand is converted to type uint. + +1u + 2 +(Convert(1, Int64) + Convert(2, Int64)) + +1 + 2u +(Convert(1, Int64) + Convert(2, Int64)) + +1u + 2:byte +(1 + Convert(Convert(2, Byte), UInt32)) + +1u + 2:sbyte +(Convert(1, Int64) + Convert(Convert(2, SByte), Int64)) + +1u + 2:short +(Convert(1, Int64) + Convert(Convert(2, Int16), Int64)) + +1u + 2:ushort +(1 + Convert(Convert(2, UInt16), UInt32)) + +1u + 2:int +(Convert(1, Int64) + Convert(2, Int64)) + +1u + 2:uint +(1 + Convert(2, UInt32)) + +####################################### +# Otherwise, both operands are converted to type int. + +1 + 2:byte +(1 + Convert(Convert(2, Byte), Int32)) + +1 + 2:sbyte +(1 + Convert(Convert(2, SByte), Int32)) + +1 + 2:short +(1 + Convert(Convert(2, Int16), Int32)) + +1 + 2:ushort +(1 + Convert(Convert(2, UInt16), Int32)) + +1 + 2:int +(1 + 2) + + +####################################### +###### Unary Numeric Promotions ###### +####################################### + +####################################### +# + operator + ++1:byte ++Convert(Convert(1, Byte), Int32) + ++1:sbyte ++Convert(Convert(1, SByte), Int32) + ++1:short ++Convert(Convert(1, Int16), Int32) + ++1:ushort ++Convert(Convert(1, UInt16), Int32) + ++1:int ++1 + ++1u ++1 + ++1L ++1 + ++1ul ++1 + +####################################### +# - operator + +-1:byte +-Convert(Convert(1, Byte), Int32) + +-1:sbyte +-Convert(Convert(1, SByte), Int32) + +-1:short +-Convert(Convert(1, Int16), Int32) + +-1:ushort +-Convert(Convert(1, UInt16), Int32) + +-1:int +-1 + +-1u +Convert(1, Int64) + +-1L +-1 diff --git a/tests/Ramstack.ExpressionParser.Tests/Data/StringConcat.txt b/tests/Ramstack.ExpressionParser.Tests/Data/StringConcat.txt index b3307fb..59ef257 100644 --- a/tests/Ramstack.ExpressionParser.Tests/Data/StringConcat.txt +++ b/tests/Ramstack.ExpressionParser.Tests/Data/StringConcat.txt @@ -1,32 +1,32 @@ -"1" + ("2" + "3") -Concat("1", "2", "3") - -("1" + "2") + "3" -Concat("1", "2", "3") - -("1" + "2" + "3" + "4" + "5") + ("6" + "7" + "8" + "9" + "0") -Concat(new [] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}) - -("1" + "2") + ("3" + "4" + "5") + ("6" + "7" + "8" + "9" + "0") -Concat(new [] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}) - -("1" + "2") + ("3" + "4" + "5") + ("6" + "7" + "8") + ("9" + "0") -Concat(new [] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}) - -("1" + "2" + ("3")) + ("4" + ("5" + "6")) + ("7" + "8" + ("9")) + "0" -Concat(new [] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}) - -"1" + 2 -Concat("1", Convert(2, Object)) - -"1" + 2 + "3" -Concat("1", Convert(2, Object), "3") - -"1" + 2 + "3" + 4 -Concat(new [] {"1", Convert(2, Object), "3", Convert(4, Object)}) - -"1" + 2 + "3" + 4 + 5 + 6 -Concat(new [] {"1", Convert(2, Object), "3", Convert(4, Object), Convert(5, Object), Convert(6, Object)}) - -"1" + 2 + "3" + (4 + 5) + 6 -Concat(new [] {"1", Convert(2, Object), "3", Convert((4 + 5), Object), Convert(6, Object)}) +"1" + ("2" + "3") +Concat("1", "2", "3") + +("1" + "2") + "3" +Concat("1", "2", "3") + +("1" + "2" + "3" + "4" + "5") + ("6" + "7" + "8" + "9" + "0") +Concat(new [] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}) + +("1" + "2") + ("3" + "4" + "5") + ("6" + "7" + "8" + "9" + "0") +Concat(new [] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}) + +("1" + "2") + ("3" + "4" + "5") + ("6" + "7" + "8") + ("9" + "0") +Concat(new [] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}) + +("1" + "2" + ("3")) + ("4" + ("5" + "6")) + ("7" + "8" + ("9")) + "0" +Concat(new [] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}) + +"1" + 2 +Concat("1", Convert(2, Object)) + +"1" + 2 + "3" +Concat("1", Convert(2, Object), "3") + +"1" + 2 + "3" + 4 +Concat(new [] {"1", Convert(2, Object), "3", Convert(4, Object)}) + +"1" + 2 + "3" + 4 + 5 + 6 +Concat(new [] {"1", Convert(2, Object), "3", Convert(4, Object), Convert(5, Object), Convert(6, Object)}) + +"1" + 2 + "3" + (4 + 5) + 6 +Concat(new [] {"1", Convert(2, Object), "3", Convert((4 + 5), Object), Convert(6, Object)}) diff --git a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs index eb6b9fb..0c99636 100644 --- a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs +++ b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs @@ -1,120 +1,120 @@ -using System.Globalization; -using System.Linq.Expressions; - -namespace Ramstack.Parsing; - -[TestFixture] -public class ExpressionParserTest -{ - private static List ExpressionSource => - GetResource("Expressions.txt"); - - private static List StringConcatSource => - GetResource("StringConcat.txt"); - - private static List ErrorsSource => - GetResource("Errors.txt"); - - private static List EvaluatesSource - { - get - { - var list = new List(); - list.Add(["""version.parse("1.2.3.4")""", Version.Parse("1.2.3.4")]); - list.Add(["""Math.Max(1d, 15)""", 15d]); - list.Add(["""DateTime.Today""", DateTime.Today]); - list.Add(["""sbyte.MinValue""", sbyte.MinValue]); - list.Add(["""-0x80000000""", int.MinValue]); - list.Add([""" 0x80000000""", 0x80000000]); - list.Add(["""-0x8000000000000000""", long.MinValue]); - list.Add([""" 0x8000000000000000""", 0x8000000000000000L]); - list.Add(["""ulong.MaxValue""", ulong.MaxValue]); - list.Add(["""Guid.Empty""", Guid.Empty]); - return list; - } - } - - [OneTimeSetUp] - public void Setup() - { - Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; - } - - [Test] - public void ContextTest() - { - var parameter = Expression.Parameter(typeof(UserInfo), "u"); - var binder = new ContextAwareBinder(parameter); - - var result = ExpressionParser.Parse("name != lastName && name.Length > 0", binder); - Assert.That(result.ToString(), Is.EqualTo("((u.Name != u.LastName) AndAlso (u.Name.Length > 0))")); - } - - [TestCaseSource(nameof(EvaluatesSource))] - public void EvaluateExpression(string expression, object result) => - Assert.That(ExpressionParser.Evaluate(expression), Is.EqualTo(result)); - - [TestCaseSource(nameof(ErrorsSource))] - public void ParseErrorExpression(string expression, string expected) - { - var result = ExpressionParser.Parse(expression, new DefaultBinder()); - - Console.WriteLine(result.ToString()); - - Assert.That(result.Success, Is.False); - Assert.That(result.ToString(), Is.EqualTo(expected)); - } - - [TestCaseSource(nameof(ExpressionSource))] - public void ParseExpressionTest(string source, string expected) - { - var result = ExpressionParser.Parse(source, new DefaultBinder()); - Assert.That(result.ToString(), Is.EqualTo(expected)); - } - - [TestCaseSource(nameof(StringConcatSource))] - public void StringConcatTest(string source, string expected) - { - var result = ExpressionParser.Parse(source, new DefaultBinder()); - Assert.That(result.ToString(), Is.EqualTo(expected)); - } - - private static List GetResource(string resourceName) - { - using var stream = typeof(ExpressionParserTest).Assembly.GetManifestResourceStream($"Ramstack.Parsing.Data.{resourceName}"); - using var reader = new StreamReader(stream!); - - var result = new List(); - - while (true) - { - string? s; - string? e; - - while ((s = reader.ReadLine()) is not null) - if (!string.IsNullOrWhiteSpace(s) && !s.StartsWith('#')) - break; - - while ((e = reader.ReadLine()) is not null) - if (!string.IsNullOrWhiteSpace(e) && !e.StartsWith('#')) - break; - - if (s is null || e is null) - break; - - s = s.Replace(@"\n", "\r\n"); - e = e.Replace(@"\n", "\r\n"); - - result.Add([s, e]); - } - - return result; - } - - public class UserInfo - { - public string? Name { get; set; } - public string? LastName { get; set; } - } -} +using System.Globalization; +using System.Linq.Expressions; + +namespace Ramstack.Parsing; + +[TestFixture] +public class ExpressionParserTest +{ + private static List ExpressionSource => + GetResource("Expressions.txt"); + + private static List StringConcatSource => + GetResource("StringConcat.txt"); + + private static List ErrorsSource => + GetResource("Errors.txt"); + + private static List EvaluatesSource + { + get + { + var list = new List(); + list.Add(["""version.parse("1.2.3.4")""", Version.Parse("1.2.3.4")]); + list.Add(["""Math.Max(1d, 15)""", 15d]); + list.Add(["""DateTime.Today""", DateTime.Today]); + list.Add(["""sbyte.MinValue""", sbyte.MinValue]); + list.Add(["""-0x80000000""", int.MinValue]); + list.Add([""" 0x80000000""", 0x80000000]); + list.Add(["""-0x8000000000000000""", long.MinValue]); + list.Add([""" 0x8000000000000000""", 0x8000000000000000L]); + list.Add(["""ulong.MaxValue""", ulong.MaxValue]); + list.Add(["""Guid.Empty""", Guid.Empty]); + return list; + } + } + + [OneTimeSetUp] + public void Setup() + { + Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; + Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; + } + + [Test] + public void ContextTest() + { + var parameter = Expression.Parameter(typeof(UserInfo), "u"); + var binder = new ContextAwareBinder(parameter); + + var result = ExpressionParser.Parse("name != lastName && name.Length > 0", binder); + Assert.That(result.ToString(), Is.EqualTo("((u.Name != u.LastName) AndAlso (u.Name.Length > 0))")); + } + + [TestCaseSource(nameof(EvaluatesSource))] + public void EvaluateExpression(string expression, object result) => + Assert.That(ExpressionParser.Evaluate(expression), Is.EqualTo(result)); + + [TestCaseSource(nameof(ErrorsSource))] + public void ParseErrorExpression(string expression, string expected) + { + var result = ExpressionParser.Parse(expression, new DefaultBinder()); + + Console.WriteLine(result.ToString()); + + Assert.That(result.Success, Is.False); + Assert.That(result.ToString(), Is.EqualTo(expected)); + } + + [TestCaseSource(nameof(ExpressionSource))] + public void ParseExpressionTest(string source, string expected) + { + var result = ExpressionParser.Parse(source, new DefaultBinder()); + Assert.That(result.ToString(), Is.EqualTo(expected)); + } + + [TestCaseSource(nameof(StringConcatSource))] + public void StringConcatTest(string source, string expected) + { + var result = ExpressionParser.Parse(source, new DefaultBinder()); + Assert.That(result.ToString(), Is.EqualTo(expected)); + } + + private static List GetResource(string resourceName) + { + using var stream = typeof(ExpressionParserTest).Assembly.GetManifestResourceStream($"Ramstack.Parsing.Data.{resourceName}"); + using var reader = new StreamReader(stream!); + + var result = new List(); + + while (true) + { + string? s; + string? e; + + while ((s = reader.ReadLine()) is not null) + if (!string.IsNullOrWhiteSpace(s) && !s.StartsWith('#')) + break; + + while ((e = reader.ReadLine()) is not null) + if (!string.IsNullOrWhiteSpace(e) && !e.StartsWith('#')) + break; + + if (s is null || e is null) + break; + + s = s.Replace(@"\n", "\r\n"); + e = e.Replace(@"\n", "\r\n"); + + result.Add([s, e]); + } + + return result; + } + + public class UserInfo + { + public string? Name { get; set; } + public string? LastName { get; set; } + } +} diff --git a/tests/Ramstack.ExpressionParser.Tests/Ramstack.ExpressionParser.Tests.csproj b/tests/Ramstack.ExpressionParser.Tests/Ramstack.ExpressionParser.Tests.csproj index e6091c5..b541671 100644 --- a/tests/Ramstack.ExpressionParser.Tests/Ramstack.ExpressionParser.Tests.csproj +++ b/tests/Ramstack.ExpressionParser.Tests/Ramstack.ExpressionParser.Tests.csproj @@ -1,40 +1,40 @@ - - - - net6.0 - Ramstack.Parsing - enable - enable - latest - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + net6.0 + Ramstack.Parsing + enable + enable + latest + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 8c551ac933866ad7e4de8a2bc960124b3bbdd4c2 Mon Sep 17 00:00:00 2001 From: rameel Date: Mon, 16 Nov 2026 23:12:15 +0500 Subject: [PATCH 2/2] build: enable analyzers and treat warnings as errors Rename the DefaultBinder.BindToType parameter to name to match Binder (CA1725), so the inherited documentation describes it. Suppress CA1716 for Expr.Call, since renaming it would break the public API. --- Directory.Build.props | 14 ++++++++++++++ src/Ramstack.ExpressionParser/DefaultBinder.cs | 6 +++--- .../Expressions/Expr.Call.cs | 2 ++ .../Ramstack.ExpressionParser.csproj | 5 ----- 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index ed14ea7..9e6caca 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,4 +2,18 @@ true + + + $(NoWarn);CS0649 + true + + + + true + latest + Recommended + Default + true + true + diff --git a/src/Ramstack.ExpressionParser/DefaultBinder.cs b/src/Ramstack.ExpressionParser/DefaultBinder.cs index 4556f34..3508f54 100644 --- a/src/Ramstack.ExpressionParser/DefaultBinder.cs +++ b/src/Ramstack.ExpressionParser/DefaultBinder.cs @@ -96,10 +96,10 @@ public void RegisterType(Type type, bool importAsStatic = false) } /// - public override Type? BindToType(Identifier typeName) + public override Type? BindToType(Identifier name) { - if (!PredefinedType.TryGetValue(typeName.Name, out var value)) - _types.TryGetValue(typeName.Name, out value); + if (!PredefinedType.TryGetValue(name.Name, out var value)) + _types.TryGetValue(name.Name, out value); return value.type; } diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs index 0c1754f..b1141e1 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs @@ -5,6 +5,8 @@ partial class Expr /// /// Represents a method call expression in an expression tree, consisting of a target expression and its parameters. /// + [SuppressMessage("Naming", "CA1716:Identifiers should not match keywords", + Justification = "The type is named after the ExprKind.Call expression kind, and renaming it would break the public API.")] public sealed class Call(Expr expression, IReadOnlyList parameters) : Expr(ExprKind.Call) { /// diff --git a/src/Ramstack.ExpressionParser/Ramstack.ExpressionParser.csproj b/src/Ramstack.ExpressionParser/Ramstack.ExpressionParser.csproj index 7ca8cd2..93189c1 100644 --- a/src/Ramstack.ExpressionParser/Ramstack.ExpressionParser.csproj +++ b/src/Ramstack.ExpressionParser/Ramstack.ExpressionParser.csproj @@ -11,11 +11,6 @@ true - - 649;1591 - CS8600;CS8601;CS8602;CS8603;CS8604;CS8610;CS8613;CS8614;CS8618;CS8619;CS8620;CS8625;CS8643;CS8653;CS8714 - - https://github.com/rameel/ramstack.expressionparser Rameel