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

function Import-BcCallGraphEngine {
    <#
    .SYNOPSIS
        Compiles the call graph engine (Resources/CallGraph/*.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: CallGraphEngine.cs (graph,
        pruning, metrics, impact) and CallGraphArchitecture.cs (parts, lookups, scaffold), compiled together as
        one assembly. 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.Explorer' -as [type]) { return }

    $folder = Join-Path -Path (Split-Path -Parent $PSScriptRoot) -ChildPath 'Resources/CallGraph'
    $sources = @(foreach ($name in 'CallGraphEngine.cs', 'CallGraphArchitecture.cs') { Join-Path -Path $folder -ChildPath $name })
    foreach ($s in $sources) { if (-not (Test-Path -LiteralPath $s)) { throw "The call graph engine source is missing: '$s'." } }

    # Windows PowerShell compiles against the .NET Framework and needs the assemblies named; PowerShell 7
    # references the whole shared framework already.
    $typeArgs = @{ Path = $sources }
    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)" }
}