Modules/businessdev.ALbuild.Apps/Private/Import-BcCallGraphEngine.ps1

function Import-BcCallGraphEngine {
    <#
    .SYNOPSIS
        Compiles the call graph engine (Resources/CallGraph/CallGraphEngine.cs) once per session.
 
    .DESCRIPTION
        Parsing, pruning and analysing a call graph of several hundred thousand records is too slow in
        PowerShell, so the work is done by a small C# engine compiled with Add-Type. The source is written
        for C# 5, the compiler Windows PowerShell 5.1 uses. Idempotent: a loaded engine is reused.
    #>

    [CmdletBinding()]
    param()

    if ('ALbuild.CallGraph.Analyzer' -as [type]) { return }

    $source = Join-Path -Path (Split-Path -Parent $PSScriptRoot) -ChildPath 'Resources/CallGraph/CallGraphEngine.cs'
    if (-not (Test-Path -LiteralPath $source)) { throw "The call graph engine source is missing: '$source'." }

    # Windows PowerShell compiles against the .NET Framework and needs the assemblies named; PowerShell 7
    # references the whole shared framework already.
    $typeArgs = @{ TypeDefinition = [System.IO.File]::ReadAllText($source) }
    if ($PSVersionTable.PSEdition -ne 'Core') {
        Add-Type -AssemblyName System.IO.Compression
        $typeArgs['ReferencedAssemblies'] = @('System.IO.Compression', 'System.Xml', 'System.Core')
    }
    try { Add-Type @typeArgs -ErrorAction Stop }
    catch { throw "Could not compile the call graph engine: $($_.Exception.Message)" }
}