diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs index 2243242..cbcf7f9 100644 --- a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs +++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs @@ -185,8 +185,66 @@ private static List CreateInjectingArguments(MethodInfo method, IRea list.Add(Convert(arg, parameter.ParameterType)); } + // + // As in C#, a parameter array without arguments gets an empty array, + // and an omitted optional parameter gets its default value. + // + for (var i = list.Count; i < parameters.Length; i++) + { + var parameter = parameters[i]; + + if (parameter.GetCustomAttribute() is not null) + { + list.Add(Expression.NewArrayInit(parameter.ParameterType.GetElementType()!)); + } + else if (parameter.IsOptional) + { + list.Add(CreateDefaultArgument(parameter)); + } + else + { + // + // A required parameter is left without an argument only for a method that does not + // accept these arguments, so let Expression.Call report the argument count. + // + break; + } + } + return list; + static Expression CreateDefaultArgument(ParameterInfo parameter) + { + var type = parameter.ParameterType; + var value = parameter.DefaultValue; + + // + // A parameter declared with [Optional] and without a default value gets Type.Missing + // if its type is object, and the default value of its type otherwise, as in C#. + // + if (value is Missing) + return type == typeof(object) + ? Expression.Constant(value, type) + : Expression.Default(type); + + // + // The default value of a struct, as in 'Guid guid = default', is also stored as null. + // + if (value is null) + return type.IsValueType && !type.IsNullable() + ? Expression.Default(type) + : Expression.Constant(null, type); + + // + // The default value of a nullable enum is stored as its underlying integer. + // + var underlyingType = Nullable.GetUnderlyingType(type) ?? type; + if (underlyingType.IsEnum && value.GetType() != underlyingType) + value = Enum.ToObject(underlyingType, value); + + return Expression.Constant(value, type); + } + static Expression Convert(Expression argument, Type conversionType) { if (argument.Type == conversionType) diff --git a/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs b/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs index 23f69f4..d63dbbb 100644 --- a/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs +++ b/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs @@ -275,21 +275,48 @@ private static int FindMostSpecific( // 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; + var usesDefaults1 = UsesDefaultArguments(p1, paramArrayType1, types.Length); + var usesDefaults2 = UsesDefaultArguments(p2, paramArrayType2, types.Length); - if (p2.Length > p1.Length) - return 2; + // + // As in C#, a method whose parameters all get arguments is better than a method + // that needs default arguments, and methods that both need them are ambiguous. + // + if (usesDefaults1 != usesDefaults2) + return usesDefaults1 ? 2 : 1; + + // + // Methods without default arguments differ in length only in their expanded form, + // and the one with more declared parameters is better. + // + if (!usesDefaults1) + { + if (p1.Length > p2.Length) + return 1; + + if (p2.Length > p1.Length) + return 2; + } } return 0; } return p1Less ? 1 : 2; + + static bool UsesDefaultArguments(ParameterInfo[] parameters, Type? paramArrayType, int argumentCount) + { + // + // In the expanded form, the parameter array takes the remaining arguments, possibly none. + // + var count = paramArrayType is not null + ? parameters.Length - 1 + : parameters.Length; + + return count > argumentCount; + } } private static int FindMostSpecificType(Type c1, Type c2, Type t) diff --git a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs index ef72055..4df0300 100644 --- a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs +++ b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs @@ -1,6 +1,7 @@ using System.Globalization; using System.Linq.Expressions; using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; using Ramstack.Parsing.Expressions; @@ -147,9 +148,23 @@ public void Evaluate_ArrayForParamArray_PassesArray(string expression, object ex [TestCase("Count(Numbers)", 1)] [TestCase("Count(Words, Words)", 2)] [TestCase("""string.Join(",", "a", "b")""", "a,b")] + [TestCase("Sum()", 0)] + [TestCase("Count()", 0)] public void Evaluate_ElementsForParamArray_CreatesArray(string expression, object expected) => Assert.That(ExpressionParser.Evaluate(expression, new ParamArrayContext()), Is.EqualTo(expected)); + [TestCase("Defaults()", "1 Monday True null")] + [TestCase("""Defaults(5, DayOfWeek.Friday, Guid.NewGuid(), "a")""", "5 Friday False a")] + [TestCase("Mixed(1)", "1 2 0")] + [TestCase("Mixed(1, 3)", "1 3 0")] + [TestCase("Mixed(1, 3, 4, 5)", "1 3 2")] + [TestCase("WithMissing()", "Missing 0")] + [TestCase("""string.Format("x")""", "x")] + [TestCase(""" "a,b".Split(",").Length """, 2)] + [TestCase(""" "a,b".Split(',').Length """, 2)] + public void Evaluate_OmittedOptionalArguments_UsesDefaultValues(string expression, object expected) => + Assert.That(ExpressionParser.Evaluate(expression, new OptionalContext()), Is.EqualTo(expected)); + [TestCase("!Flag", false)] [TestCase("!NullableFlag", true)] [TestCase("!WithLogicalNot", true)] @@ -174,6 +189,25 @@ public void LogicalNotOnOnesComplementOnlyTest() public void Evaluate_ByteArgument_DoesNotSelectCharOverload(string expression, string expected) => Assert.That(ExpressionParser.Evaluate(expression, new OverloadContext()), Is.EqualTo(expected)); + [TestCase("WithDefault(1)", "(int)")] + [TestCase("WithDefault(1, 2)", "(int, int = 0)")] + [TestCase("ParamsOrDefault(1)", "(int, int = 0)")] + [TestCase("Expanded(1, 2, 3)", "(int, int, params int[])")] + [TestCase("ExpandedOrDefault(1)", "(int, params int[])")] + public void Evaluate_OmittedOptionalArguments_SelectsOverloadAsCSharp(string expression, string expected) => + Assert.That(ExpressionParser.Evaluate(expression, new OverloadContext()), Is.EqualTo(expected)); + + [TestCase("BothDefaults(1)")] + [TestCase("ExpandedBothDefaults(1)")] + public void Parse_OverloadsWithDefaultArguments_ReturnsAmbiguityError(string expression) + { + var parameter = Expression.Parameter(typeof(OverloadContext), "c"); + var result = ExpressionParser.Parse(expression, new ContextAwareBinder(parameter)); + + Assert.That(result.Success, Is.False); + Assert.That(result.ErrorMessage, Does.StartWith("Ambiguous match found")); + } + [Test] public void Parse_ByteArgumentForCharParameter_ReturnsError() { @@ -372,6 +406,24 @@ public class OverloadContext public static string Pick(char _) => "char"; public static string Pick(int _) => "int"; public static string OnlyChar(char _) => "char"; + + public static string WithDefault(int a) => "(int)"; + public static string WithDefault(int a, int b = 0) => "(int, int = 0)"; + + public static string ParamsOrDefault(int a, params int[] rest) => "(int, params int[])"; + public static string ParamsOrDefault(int a, int b = 0) => "(int, int = 0)"; + + public static string Expanded(int a, params int[] rest) => "(int, params int[])"; + public static string Expanded(int a, int b, params int[] rest) => "(int, int, params int[])"; + + public static string ExpandedOrDefault(int a, params int[] rest) => "(int, params int[])"; + public static string ExpandedOrDefault(int a, int b = 0, params int[] rest) => "(int, int = 0, params int[])"; + + public static string BothDefaults(int a, int b = 0) => "(int, int = 0)"; + public static string BothDefaults(int a, int b = 0, int c = 0) => "(int, int = 0, int = 0)"; + + public static string ExpandedBothDefaults(int a, int b = 0, params int[] rest) => "(int, int = 0, params int[])"; + public static string ExpandedBothDefaults(int a, int b = 0, int c = 0, params int[] rest) => "(int, int = 0, int = 0, params int[])"; } public class ParamArrayContext @@ -384,4 +436,16 @@ public class ParamArrayContext public static int Count(params object[] values) => values.Length; public bool IsWords(params string[] values) => ReferenceEquals(values, Words); } + + public class OptionalContext + { + public static string Defaults(int number = 1, DayOfWeek? day = DayOfWeek.Monday, Guid id = default, string? text = null) => + $"{number} {day} {id == Guid.Empty} {text ?? "null"}"; + + public static string Mixed(int a, int b = 2, params int[] rest) => + $"{a} {b} {rest.Length}"; + + public static string WithMissing([Optional] object value, [Optional] int number) => + $"{value.GetType().Name} {number}"; + } }