Public/Expand-MemberExpression.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
using namespace Antlr4.StringTemplate.Compiler
using namespace Microsoft.PowerShell.EditorServices.Extensions
using namespace System.Collections.Generic
using namespace System.Management.Automation.Language
using namespace System.Reflection

function Expand-MemberExpression {
    <#
    .EXTERNALHELP EditorServicesCommandSuite-help.xml
    #>

    [EditorCommand(DisplayName='Expand Member Expression')]
    [CmdletBinding()]
    param(
        [Parameter(Position=1, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.Language.Ast]
        $Ast = (Find-Ast -AtCursor),

        [ValidateSet('GetMethod', 'InvokeMember', 'VerboseGetMethod', 'GetValue', 'SetValue')]
        [string]
        $TemplateName,

        [switch]
        $NoParameterNameComments
    )
    begin {
        try {
            $groupSource = Get-Content -Raw $PSScriptRoot\..\Templates\MemberExpression.stg
            $group = New-StringTemplateGroup -Definition $groupSource -ErrorAction Stop

            $instance = $group.GetType().
                GetProperty('Instance', [BindingFlags]'Instance, NonPublic').
                GetValue($group)

            $renderer = [MemberExpressionRenderer]::new()
            $instance.RegisterRenderer([string], $renderer)
            $instance.RegisterRenderer([type], [TypeRenderer]::new())
        } catch {
            ThrowError -Exception ([TemplateException]::new($Strings.TemplateGroupCompileError, $null)) `
                       -Id        TemplateGroupCompileError `
                       -Category  InvalidData `
                       -Target    $PSItem
        }
}
    process {
        $context = $psEditor.GetEditorContext()
        $memberExpressionAst = $Ast

        if ($memberExpressionAst -isnot [MemberExpressionAst]) {

            $memberExpressionAst = $Ast | Find-Ast { $PSItem -is [MemberExpressionAst] } -Ancestor -First

            if ($memberExpressionAst -isnot [MemberExpressionAst]) {
                ThrowError -Exception ([InvalidOperationException]::new($Strings.MissingMemberExpressionAst)) `
                           -Id        MissingMemberExpressionAst `
                           -Category  InvalidOperation `
                           -Target    $Ast `
                           -Show
            }
        }
        [Stack[ExtendedMemberExpressionAst]]$expressionAsts = $memberExpressionAst
        if ($memberExpressionAst.Expression -is [MemberExpressionAst]) {
            for ($nested = $memberExpressionAst.Expression; $nested; $nested = $nested.Expression) {
                if ($nested -is [MemberExpressionAst]) {
                    $expressionAsts.Push($nested)
                } else { break }
            }
        }
        [List[string]]$expressions = @()
        while ($expressionAsts.Count -and ($current = $expressionAsts.Pop())) {

            # Throw if we couldn't find member information at any point.
            if (-not ($current.InferredMember)) {
                ThrowError -Exception ([MissingMemberException]::new($current.Expression, $current.Member.Value)) `
                           -Id        MissingMember `
                           -Category  InvalidResult `
                           -Target    $Ast `
                           -Show
            }

            switch ($current.Expression) {
                { $PSItem -is [MemberExpressionAst] } {
                    $variable = $renderer.TransformMemberName($PSItem.InferredMember.Name)
                }
                { $PSItem -is [VariableExpressionAst] } {
                    $variable = $PSItem.VariablePath.UserPath
                }
                { $PSItem -is [TypeExpressionAst] } {
                    $source = $current.InferredMember.ReflectedType
                }
            }
            if ($variable) {
                $source = '${0}' -f $variable

                # We don't want to build out reflection expressions for public members so we chain
                # them together in one of the expressions.
                while (($current.InferredMember.IsPublic            -or
                        $current.InferredMember.GetMethod.IsPublic) -and
                        $expressionAsts.Count) {
                    $source += '.{0}' -f $current.InferredMember.Name

                    if ($current.InferredMember.MemberType -eq 'Method') {
                        $source += '({0})' -f $current.Arguments.Extent.Text
                    }
                    $current = $expressionAsts.Pop()
                }
            }

            if ($psEditor) {
                $scriptFile     = $context.CurrentFile.GetType().
                                                       GetField('scriptFile', 60).
                                                       GetValue($context.CurrentFile)

                $line           = $scriptFile.GetLine($memberExpressionAst.Extent.StartLineNumber)
                $indentOffset   = [regex]::Match($line, '^\s*').Value
            }

            $templateParameters = @{
                ast                  = $current
                source               = $source
                includeParamComments = -not $NoParameterNameComments
            }
            $member = $current.InferredMember

            # Automatically use the more explicit VerboseGetMethod template if building a reflection
            # statement for a method with multiple overloads with the same parameter count.
            $needsVerbose = $member -is [MethodInfo] -and -not
                            $member.IsPublic -and
                            $member.ReflectedType.GetMethods(60).Where{
                                $PSItem.Name -eq $current.InferredMember.Name -and
                                $PSItem.GetParameters().Count -eq $member.GetParameters().Count }.
                                Count -gt 1

            if ($TemplateName -and -not $expressionAsts.Count) {
                $templateParameters.template = $TemplateName
            } elseif ($needsVerbose) {
                $templateParameters.template = 'VerboseGetMethod'
            }
            $expression = Invoke-StringTemplate -Group $group -Name Main -Parameters $templateParameters
            $expressions.Add($expression)
        }

        $result = $expressions -join (,[Environment]::NewLine * 2) `
                               -split '\r?\n' `
                               -join ([Environment]::NewLine + $indentOffset)
        if ($psEditor) {
            Set-ScriptExtent -Extent $memberExpressionAst.Extent `
                             -Text   $result
        } else {
            $result
        }
    }
}