Search code examples
powershellclassabstract-syntax-tree

Get Class Source


A few months ago I wrote a small Use-ClassAccessors script to easier define class accessors (getters and setters). This works pretty well except for a minor constraint: The Use-ClassAccessors script needs to be invoked from the script file were the concerned class resides so that it can load the related AST information of the class. The unfortunate side effect is that the accessors are not always reloaded in the module¹ were I am working on with VSCode. The workaround is to a Kill Terminal and load a new one.

  1. The module psd1 also invokes the script that contains the class and the Use-ClassAccessors function with ScriptsToProcess but this apparently doesn't reload when changes are made to the class itself.

I suspect that I might be able to resolve this issue if I would be able to run the Use-ClassAccessors function from a static constructor as described here.

The point is that I have no clue how I might get to the (AST) source code of the class itself.

In other words:
Is there a way to retrieve the Class' own ScriptBlock from within the concerned class similar as I could do in a function:

function GetMyCode {
    Write-Host 'My Source Code:'
    $MyInvocation.MyCommand.ScriptBlock
}

Solution

  • This appears to be an XY problem: you don't actually need access to the source code (or resulting AST) to discover the information required, you can obtain it from the resulting type at runtime:

    $targetType = $ClassName -as [Type]
    
    if ($targetType.Assembly.GetName().Name -notmatch 'PowerShell Class Assembly') {
      # not a powershell class 
      return
    }
    
    $accessorMethods = $targetType.GetMethods() |? Name -Like "?et_${PropertyName}"