Skip to content

Commit b9b9b36

Browse files
committed
Convert MethodInfo to compiled delegate call
1 parent 908a6df commit b9b9b36

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

src/PowerShellEditorServices/Services/Symbols/Vistors/AstOperations.cs

+22-9
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
using System;
55
using System.Collections.Generic;
66
using System.Diagnostics;
7+
using System.IO;
78
using System.Linq;
9+
using System.Linq.Expressions;
810
using System.Management.Automation;
911
using System.Management.Automation.Language;
1012
using System.Reflection;
@@ -21,13 +23,26 @@ namespace Microsoft.PowerShell.EditorServices.Services.Symbols
2123
/// </summary>
2224
internal static class AstOperations
2325
{
24-
// TODO: When netstandard is upgraded to 2.0, see if
25-
// Delegate.CreateDelegate can be used here instead
26-
private static readonly MethodInfo s_extentCloneWithNewOffset = typeof(PSObject).Assembly
27-
.GetType("System.Management.Automation.Language.InternalScriptPosition")
28-
.GetMethod("CloneWithNewOffset", BindingFlags.Instance | BindingFlags.NonPublic);
26+
private static readonly Func<IScriptPosition, int, IScriptPosition> s_clonePositionWithNewOffset;
27+
static AstOperations()
28+
{
29+
Type internalScriptPositionType = typeof(PSObject).GetTypeInfo().Assembly
30+
.GetType("System.Management.Automation.Language.InternalScriptPosition");
31+
32+
MethodInfo cloneWithNewOffsetMethod = internalScriptPositionType.GetMethod("CloneWithNewOffset", BindingFlags.Instance | BindingFlags.NonPublic);
33+
34+
ParameterExpression originalPosition = Expression.Parameter(typeof(IScriptPosition));
35+
ParameterExpression newOffset = Expression.Parameter(typeof(int));
36+
37+
var parameters = new ParameterExpression[] { originalPosition, newOffset };
38+
s_clonePositionWithNewOffset = Expression.Lambda<Func<IScriptPosition, int, IScriptPosition>>(
39+
Expression.Call(
40+
Expression.Convert(originalPosition, internalScriptPositionType),
41+
cloneWithNewOffsetMethod,
42+
newOffset),
43+
parameters).Compile();
44+
}
2945

30-
// TODO: BRING THIS BACK
3146
/// <summary>
3247
/// Gets completions for the symbol found in the Ast at
3348
/// the given file offset.
@@ -60,9 +75,7 @@ public static async Task<CommandCompletion> GetCompletionsAsync(
6075
ILogger logger,
6176
CancellationToken cancellationToken)
6277
{
63-
IScriptPosition cursorPosition = (IScriptPosition)s_extentCloneWithNewOffset.Invoke(
64-
scriptAst.Extent.StartScriptPosition,
65-
new object[] { fileOffset });
78+
IScriptPosition cursorPosition = s_clonePositionWithNewOffset(scriptAst.Extent.StartScriptPosition, fileOffset);
6679

6780
logger.LogTrace(
6881
string.Format(

0 commit comments

Comments
 (0)