Skip to content
Prev Previous commit
Next Next commit
Use LINQ Min and Max methods; don't create second list for methods be…
…st matched on defaults
  • Loading branch information
jmlidbetter committed Jun 22, 2020
commit 86d21f1696f79cf1f6b8eedd0a287ad1d7fdccbb
15 changes: 9 additions & 6 deletions src/runtime/methodbinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth
{
// Order matched methods by number of kwargs matched and get the max possible number
// of kwargs matched
var bestKwargMatchCount = argMatchedMethods.OrderBy((x) => x.KwargsMatched).Reverse().ToArray()[0].KwargsMatched;
var bestKwargMatchCount = argMatchedMethods.Max(x => x.KwargsMatched);

List<MatchedMethod> bestKwargMatches = new List<MatchedMethod>(argMatchedMethods.Count());
foreach (MatchedMethod testMatch in argMatchedMethods)
Expand All @@ -375,18 +375,21 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth
}

// Order by the number of defaults required and find the smallest
var fewestDefaultsRequired = bestKwargMatches.OrderBy((x) => x.DefaultsNeeded).ToArray()[0].DefaultsNeeded;
var fewestDefaultsRequired = bestKwargMatches.Min(x => x.DefaultsNeeded);
int bestCount = 0;
int bestMatchIndex = -1;

List<MatchedMethod> bestDefaultsMatches = new List<MatchedMethod>(bestKwargMatches.Count());
foreach (MatchedMethod testMatch in bestKwargMatches)
{
if (testMatch.DefaultsNeeded == fewestDefaultsRequired)
{
bestDefaultsMatches.Add(testMatch);
bestCount++;
if (bestMatchIndex == -1)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not having this check will cause tests to fail because a different overload is picked- e.g. MethodTest.TestOverloadedObjectTwo(5, 5) will get the (Object, Object) overload rather than the (Int, Int) overload

bestMatchIndex = bestKwargMatches.IndexOf(testMatch);
}
}

if (bestDefaultsMatches.Count() > 1 && fewestDefaultsRequired > 0)
if (bestCount > 1 && fewestDefaultsRequired > 0)
{
// Best effort for determining method to match on gives multiple possible
// matches and we need at least one default argument - bail from this point
Expand All @@ -400,7 +403,7 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth
// in the case of (a) we're done by default. For (b) regardless of which
// method we choose, all arguments are specified _and_ can be converted
// from python to C# so picking any will suffice
MatchedMethod bestMatch = bestDefaultsMatches.ToArray()[0];
MatchedMethod bestMatch = bestKwargMatches.ElementAt(bestMatchIndex);
var margs = bestMatch.ManagedArgs;
var outs = bestMatch.Outs;
var mi = bestMatch.Method;
Expand Down