Skip to main content

rust_anything/
codegen_powershell.rs

1//! The PowerShell side of the JSON dispatcher: a wrapper script with the original functions,
2//! each calling `rust_anything_call` through P/Invoke methods that Reflection.Emit declares when
3//! the wrapper loads (no C# compiler, no `Add-Type`), and the driver `record`, `diff` and `bench`
4//! run in `pwsh`.
5
6use std::fmt::Write as _;
7
8use crate::bridge::Manifest;
9
10/// Encodes and decodes values as the other bridges do (`$num` markers for NaN, the infinities
11/// and -0), and makes one call into a library. Kept in one script variable so that a module that
12/// exports every function does not export these too.
13const CODEC_PS1: &str = r#"if ($null -eq $script:RustAnythingCodec) {
14    $script:RustAnythingCodec = @{}
15    $script:RustAnythingCodec.Options = [System.Text.Json.JsonSerializerOptions]::new()
16    $script:RustAnythingCodec.Options.Encoder = [System.Text.Encodings.Web.JavaScriptEncoder]::UnsafeRelaxedJsonEscaping
17    $script:RustAnythingCodec.Integers = [System.Collections.Generic.HashSet[type]]::new([type[]]@(
18        [int], [long], [int16], [byte], [sbyte], [uint16], [uint32], [uint64], [System.Numerics.BigInteger]))
19    $script:RustAnythingCodec.Escaped = '["\\\p{Cc}\p{Cs}]'
20    $script:RustAnythingCodec.Scalar = [regex]'^\{"ok":(?:(true|false|null)|(-?\d{1,18})|(-?\d+(?:\.\d+(?:[eE][-+]?\d+)?|[eE][-+]?\d+))|"([^"\\\p{Cc}]*)")\}$'
21    $script:RustAnythingCodec.String = {
22        param([string]$Text)
23        [System.Text.Json.JsonSerializer]::Serialize($Text, [string], $script:RustAnythingCodec.Options)
24    }
25    $script:RustAnythingCodec.Write = {
26        param($Value, [System.Text.StringBuilder]$Out)
27        $codec = $script:RustAnythingCodec
28        if ($null -eq $Value) {
29            [void]$Out.Append('null')
30            return
31        }
32        if ($Value -is [System.Management.Automation.PSObject]) { $b = $Value.psobject.BaseObject } else { $b = $Value }
33        if ($b -is [string]) {
34            if ($b -cmatch $codec.Escaped) {
35                [void]$Out.Append([System.Text.Json.JsonSerializer]::Serialize($b, [string], $codec.Options))
36            } else {
37                [void]$Out.Append('"').Append($b).Append('"')
38            }
39        } elseif ($codec.Integers.Contains($b.GetType())) {
40            [void]$Out.Append($b.ToString([cultureinfo]::InvariantCulture))
41        } elseif ($b -is [char]) {
42            [void]$Out.Append((& $codec.String ([string]$b)))
43        } elseif ($b -is [bool]) {
44            [void]$Out.Append($(if ($b) { 'true' } else { 'false' }))
45        } elseif ($b -is [System.Management.Automation.SwitchParameter]) {
46            [void]$Out.Append($(if ($b.IsPresent) { 'true' } else { 'false' }))
47        } elseif ($b -is [double] -or $b -is [float]) {
48            $d = [double]$b
49            if ([double]::IsNaN($d)) {
50                [void]$Out.Append('{"$num":"NaN"}')
51            } elseif ([double]::IsPositiveInfinity($d)) {
52                [void]$Out.Append('{"$num":"Infinity"}')
53            } elseif ([double]::IsNegativeInfinity($d)) {
54                [void]$Out.Append('{"$num":"-Infinity"}')
55            } elseif ($d -eq 0 -and [double]::IsNegative($d)) {
56                [void]$Out.Append('{"$num":"-0"}')
57            } else {
58                $s = $d.ToString('R', [cultureinfo]::InvariantCulture)
59                if ($s -notmatch '[.eE]') { $s += '.0' }
60                [void]$Out.Append($s)
61            }
62        } elseif ($b -is [decimal]) {
63            $s = $b.ToString([cultureinfo]::InvariantCulture)
64            if ($s -notmatch '[.eE]') { $s += '.0' }
65            [void]$Out.Append($s)
66        } elseif ($b -is [enum]) {
67            [void]$Out.Append((& $codec.String $b.ToString()))
68        } elseif ($b -is [System.Collections.IDictionary]) {
69            $entries = [object[]]@($b.GetEnumerator())
70            if ($b.GetType() -eq [hashtable]) {
71                $names = [string[]]::new($entries.Count)
72                for ($i = 0; $i -lt $entries.Count; $i++) { $names[$i] = [string]$entries[$i].Key }
73                [Array]::Sort($names, $entries, [StringComparer]::Ordinal)
74            }
75            [void]$Out.Append('{')
76            $first = $true
77            foreach ($e in $entries) {
78                if (-not $first) { [void]$Out.Append(',') }
79                $first = $false
80                [void]$Out.Append((& $codec.String ([string]$e.Key))).Append(':')
81                & $codec.Write $e.Value $Out
82            }
83            [void]$Out.Append('}')
84        } elseif ($b -is [System.Management.Automation.PSCustomObject]) {
85            [void]$Out.Append('{')
86            $first = $true
87            foreach ($p in $Value.psobject.Properties) {
88                if (-not $first) { [void]$Out.Append(',') }
89                $first = $false
90                [void]$Out.Append((& $codec.String $p.Name)).Append(':')
91                & $codec.Write $p.Value $Out
92            }
93            [void]$Out.Append('}')
94        } elseif ($b -is [System.Collections.IEnumerable]) {
95            [void]$Out.Append('[')
96            $first = $true
97            foreach ($x in $b) {
98                if (-not $first) { [void]$Out.Append(',') }
99                $first = $false
100                if ($x -is [string] -and $x -cnotmatch $codec.Escaped) {
101                    [void]$Out.Append('"').Append($x).Append('"')
102                } elseif ($x -is [int] -or $x -is [long]) {
103                    [void]$Out.Append($x.ToString([cultureinfo]::InvariantCulture))
104                } elseif ($null -eq $x) {
105                    [void]$Out.Append('null')
106                } else {
107                    & $codec.Write $x $Out
108                }
109            }
110            [void]$Out.Append(']')
111        } else {
112            [void]$Out.Append('{"$object":').Append((& $codec.String $b.GetType().FullName)).Append('}')
113        }
114    }
115    $script:RustAnythingCodec.Json = {
116        param($Value)
117        $out = [System.Text.StringBuilder]::new()
118        & $script:RustAnythingCodec.Write $Value $out
119        $out.ToString()
120    }
121    $script:RustAnythingCodec.DocumentOptions = [System.Text.Json.JsonDocumentOptions]::new()
122    $script:RustAnythingCodec.DocumentOptions.MaxDepth = 100000
123    $script:RustAnythingCodec.Element = {
124        param([System.Text.Json.JsonElement]$Element)
125        switch ($Element.ValueKind) {
126            'String' { return $Element.GetString() }
127            'Number' {
128                $raw = $Element.GetRawText()
129                if ($raw -cmatch '^-?\d+$') {
130                    $long = 0L
131                    if ([long]::TryParse($raw, [System.Globalization.NumberStyles]::AllowLeadingSign, [cultureinfo]::InvariantCulture, [ref]$long)) { return $long }
132                    return [System.Numerics.BigInteger]::Parse($raw, [cultureinfo]::InvariantCulture)
133                }
134                return [double]::Parse($raw, [cultureinfo]::InvariantCulture)
135            }
136            'True' { return $true }
137            'False' { return $false }
138            'Array' {
139                $list = [System.Collections.Generic.List[object]]::new()
140                foreach ($x in $Element.EnumerateArray()) { $list.Add((& $script:RustAnythingCodec.Element $x)) }
141                return , $list.ToArray()
142            }
143            'Object' {
144                $map = [System.Management.Automation.OrderedHashtable]::new()
145                foreach ($p in $Element.EnumerateObject()) { $map[$p.Name] = & $script:RustAnythingCodec.Element $p.Value }
146                return , $map
147            }
148        }
149    }
150    $script:RustAnythingCodec.Parse = {
151        param([string]$Json)
152        $document = [System.Text.Json.JsonDocument]::Parse($Json, $script:RustAnythingCodec.DocumentOptions)
153        try {
154            $v = & $script:RustAnythingCodec.Element $document.RootElement
155        } finally {
156            $document.Dispose()
157        }
158        if ($null -eq $v) { return }
159        , $v
160    }
161    $script:RustAnythingCodec.Unmark = {
162        param($Value)
163        if ($null -eq $Value) { return }
164        if ($Value -is [System.Collections.IDictionary]) {
165            if ($Value.Count -eq 1 -and $Value.Contains('$num')) {
166                switch ($Value['$num']) {
167                    'NaN' { return [double]::NaN }
168                    'Infinity' { return [double]::PositiveInfinity }
169                    '-Infinity' { return [double]::NegativeInfinity }
170                    '-0' { return [BitConverter]::Int64BitsToDouble([long]::MinValue) }
171                }
172            }
173            if ($Value.Count -eq 1 -and $Value.Contains('$undefined')) { return }
174            foreach ($k in @($Value.Keys)) { $Value[$k] = & $script:RustAnythingCodec.Unmark $Value[$k] }
175            return , $Value
176        }
177        if ($Value -is [array]) {
178            for ($i = 0; $i -lt $Value.Count; $i++) { $Value[$i] = & $script:RustAnythingCodec.Unmark $Value[$i] }
179            return , $Value
180        }
181        $Value
182    }
183    $script:RustAnythingCodec.Error = {
184        param([string]$Message)
185        if ($Message -match '(?s)^([A-Za-z_][\w.+]*): (.*)$') {
186            $type = $Matches[1] -as [type]
187            if ($null -ne $type -and [Exception].IsAssignableFrom($type)) {
188                try { return [Activator]::CreateInstance($type, [object[]]@($Matches[2])) } catch { }
189            }
190        }
191        [System.Management.Automation.RuntimeException]::new($Message)
192    }
193    $script:RustAnythingCodec.Load = {
194        param([string]$Path)
195        if (-not (Test-Path -LiteralPath $Path)) {
196            throw "rust-anything: no built library at $Path (run ``rust-anything build``)"
197        }
198        $name = 'RustAnything' + [guid]::NewGuid().ToString('N')
199        $assembly = [System.Reflection.Emit.AssemblyBuilder]::DefineDynamicAssembly([System.Reflection.AssemblyName]::new($name), 'Run')
200        $type = $assembly.DefineDynamicModule($name).DefineType("$name.Native", 'Public,Class,Abstract,Sealed')
201        $call = $type.DefinePInvokeMethod('rust_anything_call', $Path, 'Public,Static,PinvokeImpl,HideBySig',
202            'Standard', [IntPtr], [type[]]@([byte[]], [byte[]]), 'Cdecl', 'Ansi')
203        $call.SetImplementationFlags('PreserveSig')
204        $free = $type.DefinePInvokeMethod('rust_anything_free', $Path, 'Public,Static,PinvokeImpl,HideBySig',
205            'Standard', [void], [type[]]@([IntPtr]), 'Cdecl', 'Ansi')
206        $free.SetImplementationFlags('PreserveSig')
207        $type.CreateType()
208    }
209    $script:RustAnythingCodec.Call = {
210        param($Native, [string]$Name, [object[]]$Arguments)
211        $codec = $script:RustAnythingCodec
212        $utf8 = [System.Text.Encoding]::UTF8
213        $json = [System.Text.StringBuilder]::new()
214        & $codec.Write $Arguments $json
215        $ptr = $Native::rust_anything_call($utf8.GetBytes($Name + [char]0), $utf8.GetBytes($json.Append([char]0).ToString()))
216        if ($ptr -eq [IntPtr]::Zero) { throw "rust-anything: no answer from ``$Name``" }
217        try {
218            $text = [System.Runtime.InteropServices.Marshal]::PtrToStringUTF8($ptr)
219        } finally {
220            $Native::rust_anything_free($ptr)
221        }
222        $scalar = $codec.Scalar.Match($text)
223        if ($scalar.Success) {
224            $g = $scalar.Groups
225            if ($g[1].Success) {
226                if ($g[1].Value -eq 'true') { return $true }
227                if ($g[1].Value -eq 'false') { return $false }
228                return
229            }
230            if ($g[2].Success) { return [long]::Parse($g[2].Value, [cultureinfo]::InvariantCulture) }
231            if ($g[3].Success) { return [double]::Parse($g[3].Value, [cultureinfo]::InvariantCulture) }
232            return $g[4].Value
233        }
234        $answer = & $codec.Parse $text
235        if ($answer.Contains('panic')) { throw "Rust panic: $($answer['panic'])" }
236        if ($answer.Contains('error')) { throw (& $codec.Error ([string]$answer['error'])) }
237        $value = $answer['ok']
238        if ($text.Contains('"$')) { $value = & $codec.Unmark $value }
239        if ($null -eq $value) { return }
240        if ($value -is [array] -and $value.Count -ge 2) { return $value }
241        if ($value -is [array]) { return , $value }
242        $value
243    }
244}
245"#;
246
247pub fn wrapper_path(m: &Manifest) -> String {
248    format!("ps/{}.ps1", m.lib_name())
249}
250
251fn native_var(m: &Manifest) -> String {
252    format!("RustAnything_{}", m.lib_name())
253}
254
255pub fn wrapper(m: &Manifest) -> String {
256    let lib = m.lib_name();
257    let var = native_var(m);
258    let mut out = format!(
259        "# The Rust port of `{unit}`, generated by rust-anything: the same functions, each calling the\n\
260         # Rust library through P/Invoke. Dot-source it after the original functions are defined\n\
261         # (`rust-anything enable` does that), or on its own. Regenerate with `rust-anything refresh`.\n\n\
262         {CODEC_PS1}\n\
263         if ($null -eq $script:{var}) {{\n    \
264         $script:{var} = & $script:RustAnythingCodec.Load (Join-Path $PSScriptRoot $(if ($IsWindows) {{ '{lib}.dll' }} elseif ($IsMacOS) {{ 'lib{lib}.dylib' }} else {{ 'lib{lib}.so' }}))\n\
265         }}\n",
266        unit = m.unit,
267    );
268    for f in &m.exports {
269        let _ = write!(out, "\nfunction {} {{\n", f.name);
270        for line in crate::lang::powershell::param_text(f).lines() {
271            let _ = writeln!(out, "    {}", line.trim_end());
272        }
273        let _ = writeln!(
274            out,
275            "    $rustAnythingArgs = [object[]]::new({})",
276            f.params.len()
277        );
278        for (i, p) in f.params.iter().enumerate() {
279            let _ = writeln!(out, "    $rustAnythingArgs[{i}] = ${{{}}}", p.name);
280        }
281        let _ = writeln!(
282            out,
283            "    & $script:RustAnythingCodec.Call $script:{var} '{}' $rustAnythingArgs\n}}",
284            f.name.replace('\'', "''")
285        );
286    }
287    out
288}
289
290/// Each export's parameter names in order, so the driver can pass recorded arguments by name.
291pub fn targets(m: &Manifest) -> serde_json::Value {
292    serde_json::Value::Object(
293        m.exports
294            .iter()
295            .map(|f| {
296                (
297                    f.name.clone(),
298                    serde_json::json!({
299                        "params": f.params.iter().map(|p| p.name.clone()).collect::<Vec<_>>(),
300                    }),
301                )
302            })
303            .collect(),
304    )
305}
306
307pub fn driver() -> String {
308    format!("{DRIVER_HEAD}\n{CODEC_PS1}\n{DRIVER_PS1}")
309}
310
311const DRIVER_HEAD: &str = r#"param(
312    [string]$Mode,
313    [string]$TargetsPath,
314    [string]$CasesPath,
315    [string]$OutPath,
316    [int]$MinMs,
317    [Parameter(ValueFromRemainingArguments)][string[]]$Files
318)
319"#;
320
321const DRIVER_PS1: &str = r#"$codec = $script:RustAnythingCodec
322$utf8 = [System.Text.UTF8Encoding]::new($false)
323$targets = & $codec.Parse ([System.IO.File]::ReadAllText($TargetsPath))
324foreach ($file in $Files) {
325    if ($file.EndsWith('.psm1', [StringComparison]::OrdinalIgnoreCase)) {
326        Import-Module -Name $file -Force -Global -DisableNameChecking -ErrorAction Stop
327    } else {
328        . $file
329    }
330}
331$commands = @{}
332foreach ($name in $targets.Keys) {
333    $commands[$name] = Get-Command -Name $name -CommandType Function -ErrorAction Stop | Select-Object -First 1
334}
335
336function RustAnythingSplat($Target, $Arguments) {
337    $splat = [ordered]@{}
338    $params = $Target['params']
339    for ($i = 0; $i -lt $Arguments.Count -and $i -lt $params.Count; $i++) {
340        $a = $Arguments[$i]
341        if ($a -is [System.Collections.IDictionary] -and $a.Count -eq 1 -and $a.Contains('$undefined')) { continue }
342        $splat[$params[$i]] = & $codec.Unmark $a
343    }
344    $splat
345}
346
347function RustAnythingInvoke($Command, $Splat) {
348    $text = [System.Text.StringBuilder]::new()
349    $result = [ordered]@{}
350    try {
351        $all = @(& $Command @Splat 2>&1 3>&1 6>&1)
352        $items = [System.Collections.Generic.List[object]]::new()
353        foreach ($o in $all) {
354            if ($o -is [System.Management.Automation.InformationRecord]) {
355                [void]$text.Append([string]$o.MessageData).Append("`n")
356            } elseif ($o -is [System.Management.Automation.WarningRecord]) {
357                [void]$text.Append('WARNING: ').Append($o.Message).Append("`n")
358            } elseif ($o -is [System.Management.Automation.ErrorRecord]) {
359                [void]$text.Append('ERROR: ').Append($o.ToString()).Append("`n")
360            } else {
361                $items.Add($o)
362            }
363        }
364        if ($items.Count -eq 0) {
365            $value = $null
366        } elseif ($items.Count -eq 1) {
367            $value = $items[0]
368        } else {
369            $value = $items.ToArray()
370        }
371        $result['ok'] = & $codec.Json $value
372    } catch {
373        $result['error'] = & $codec.String $_.Exception.Message
374        $result['error_type'] = & $codec.String $_.Exception.GetType().FullName
375    }
376    if ($text.Length -gt 0) { $result['output'] = & $codec.String $text.ToString() }
377    $result
378}
379
380function RustAnythingFields($Fields) {
381    $parts = foreach ($k in $Fields.Keys) { (& $codec.String $k) + ':' + $Fields[$k] }
382    '{' + ($parts -join ',') + '}'
383}
384
385function RustAnythingCases([string]$Path) {
386    foreach ($line in [System.IO.File]::ReadLines($Path)) {
387        if ($line.Trim() -ne '') { , (& $codec.Parse $line) }
388    }
389}
390
391function RustAnythingExpected($Case) {
392    $fields = [ordered]@{}
393    foreach ($k in 'ok', 'error', 'error_type', 'output') {
394        if ($Case.Contains($k)) { $fields[$k] = & $codec.Json $Case[$k] }
395    }
396    $fields
397}
398
399function RustAnythingSame($Expected, $Got) {
400    if ($Got.Contains('error') -and $Got['error'].StartsWith('"Rust panic:')) { return $false }
401    $eo = if ($Expected.Contains('output')) { $Expected['output'] } else { '""' }
402    $go = if ($Got.Contains('output')) { $Got['output'] } else { '""' }
403    if ($eo -cne $go) { return $false }
404    if ($Expected.Contains('error')) {
405        return $Got.Contains('error') -and $Expected['error_type'] -ceq $Got['error_type']
406    }
407    -not $Got.Contains('error') -and $Expected['ok'] -ceq $Got['ok']
408}
409
410switch ($Mode) {
411    'record' {
412        $progress = $env:RUST_ANYTHING_PROGRESS
413        $writer = [System.IO.StreamWriter]::new($OutPath, $false, $utf8)
414        $writer.AutoFlush = $true
415        $cases = & $codec.Parse ([System.IO.File]::ReadAllText($CasesPath))
416        for ($index = 0; $index -lt $cases.Count; $index++) {
417            $c = $cases[$index]
418            if ($progress) { [System.IO.File]::AppendAllText($progress, "$index`n") }
419            $name = [string]$c['fn']
420            $arguments = @()
421            if ($c.Contains('args')) { $arguments = $c['args'] }
422            $got = RustAnythingInvoke $commands[$name] (RustAnythingSplat $targets[$name] $arguments)
423            $line = [ordered]@{ fn = & $codec.String $name; args = & $codec.Json $arguments }
424            foreach ($k in $got.Keys) { $line[$k] = $got[$k] }
425            $writer.WriteLine((RustAnythingFields $line))
426        }
427        $writer.Close()
428    }
429    'diff' {
430        $total = 0
431        $passed = 0
432        $mismatches = [System.Collections.Generic.List[string]]::new()
433        foreach ($c in RustAnythingCases $CasesPath) {
434            $total++
435            $name = [string]$c['fn']
436            $arguments = @()
437            if ($c.Contains('args')) { $arguments = $c['args'] }
438            $got = RustAnythingInvoke $commands[$name] (RustAnythingSplat $targets[$name] $arguments)
439            $expected = RustAnythingExpected $c
440            if (RustAnythingSame $expected $got) {
441                $passed++
442            } else {
443                $m = [ordered]@{
444                    fn = & $codec.String $name
445                    args = & $codec.Json $arguments
446                    expected = RustAnythingFields $expected
447                    actual = RustAnythingFields $got
448                }
449                $mismatches.Add((RustAnythingFields $m))
450            }
451        }
452        $summary = '{"total":' + $total + ',"passed":' + $passed + ',"failed":' + ($total - $passed) +
453            ',"missing":[],"mismatches":[' + ($mismatches -join ',') + ']}'
454        [System.IO.File]::WriteAllText($OutPath, $summary, $utf8)
455    }
456    'bench' {
457        $groups = [ordered]@{}
458        foreach ($c in RustAnythingCases $CasesPath) {
459            $name = [string]$c['fn']
460            if (-not $groups.Contains($name)) { $groups[$name] = [System.Collections.Generic.List[object]]::new() }
461            $arguments = @()
462            if ($c.Contains('args')) { $arguments = $c['args'] }
463            $groups[$name].Add((RustAnythingSplat $targets[$name] $arguments))
464        }
465        $parts = [System.Collections.Generic.List[string]]::new()
466        foreach ($name in $groups.Keys) {
467            $command = $commands[$name]
468            $prepared = $groups[$name]
469            $once = {
470                foreach ($splat in $prepared) {
471                    try { $null = & $command @splat 2>$null 3>$null 6>$null } catch { }
472                }
473            }
474            & $once
475            $passes = 0
476            $watch = [System.Diagnostics.Stopwatch]::StartNew()
477            while ($true) {
478                & $once
479                $passes++
480                if ($watch.Elapsed.TotalMilliseconds -ge $MinMs) { break }
481            }
482            $ns = $watch.Elapsed.TotalMilliseconds * 1e6 / ($passes * $prepared.Count)
483            $parts.Add((& $codec.String $name) + ':{"cases":' + $prepared.Count + ',"ns":' + $ns.ToString('R', [cultureinfo]::InvariantCulture) + '}')
484        }
485        [System.IO.File]::WriteAllText($OutPath, '{' + ($parts -join ',') + '}', $utf8)
486    }
487}
488"#;