rust-anything 4.0.0

Rewrite your app in Rust, one piece at a time, checked against the original's recorded behavior at every step. TypeScript/JavaScript, Python, C, Go, Ruby, Java, Kotlin, PHP, C# and PowerShell
Documentation
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
//! The C# side of the JSON bridge: a wrapper with the original classes and signatures under
//! `<namespace>.Rust`, each method calling the Rust library through P/Invoke, and the driver that
//! records the original and diffs the wrapper.

use std::fmt::Write as _;

use crate::bridge::Manifest;
use crate::ts::exports::ExportedFn;

pub fn wrapper_path(m: &Manifest) -> String {
    format!("cs/{}.cs", native_class(m).trim_end_matches("Native"))
}

pub fn native_class(m: &Manifest) -> String {
    format!("{}Native", crate::codegen_ruby::camel(&m.lib_name()))
}

fn codec_class(m: &Manifest) -> String {
    format!("{}Codec", crate::codegen_ruby::camel(&m.lib_name()))
}

/// `(namespace, class, method)` of an exported static method, from its prototype
/// (`Acme.Text.Slug.Slugify(string text)`).
pub fn qualified(f: &ExportedFn) -> (String, String, String) {
    let proto = f.prototype.as_deref().unwrap_or(&f.name);
    let head = proto.split('(').next().unwrap_or(proto).trim();
    let (class, method) = head.rsplit_once('.').unwrap_or(("", head));
    let (ns, class) = class.rsplit_once('.').unwrap_or(("", class));
    (ns.to_string(), class.to_string(), method.to_string())
}

/// The namespace of the wrapper classes for an original namespace.
pub fn rust_namespace(ns: &str) -> String {
    if ns.is_empty() {
        "Rust".into()
    } else {
        format!("{ns}.Rust")
    }
}

/// `{ name: { original: "Ns.Class", rust: "Ns.Rust.Class", method } }` for the driver.
pub fn targets(m: &Manifest) -> serde_json::Value {
    serde_json::Value::Object(
        m.exports
            .iter()
            .map(|f| {
                let (ns, class, method) = qualified(f);
                let join = |ns: &str| {
                    if ns.is_empty() {
                        class.clone()
                    } else {
                        format!("{ns}.{class}")
                    }
                };
                (
                    f.name.clone(),
                    serde_json::json!({
                        "original": join(&ns),
                        "rust": join(&rust_namespace(&ns)),
                        "method": method,
                    }),
                )
            })
            .collect(),
    )
}

fn usings(m: &Manifest) -> Vec<String> {
    let mut files: Vec<&str> = m.exports.iter().map(|f| f.file.as_str()).collect();
    files.sort_unstable();
    files.dedup();
    let mut out: Vec<String> = Vec::new();
    for file in files {
        let text = std::fs::read_to_string(m.root.join(file)).unwrap_or_default();
        for line in crate::lang::csharp::using_directives(&text) {
            if !line.starts_with("global ") && !out.contains(&line) {
                out.push(line);
            }
        }
    }
    out
}

fn param_list(f: &ExportedFn) -> String {
    f.params
        .iter()
        .map(|p| {
            let ty = p.native_type.as_deref().unwrap_or("object");
            match &p.default {
                Some(d) => format!("{ty} {} = {d}", p.name),
                None => format!("{ty} {}", p.name),
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

fn codec(class: &str, visibility: &str) -> String {
    CODEC_CS
        .replace("__CODEC__", class)
        .replace("__VISIBILITY__", visibility)
}

pub fn wrapper(m: &Manifest) -> String {
    let native = native_class(m);
    let codec_name = codec_class(m);
    let mut out = format!(
        "// The Rust port of `{unit}`, generated by rust-anything: the same classes and methods under\n\
         // `<namespace>.Rust`, each calling the Rust library through P/Invoke. Call them in place of\n\
         // the originals (or alias them: `using Slug = Acme.Text.Rust.Slug;`).\n\
         // Regenerate with `rust-anything refresh`.\n\n\
         #nullable enable\n\n",
        unit = m.unit,
    );
    for line in usings(m) {
        let _ = writeln!(out, "{line}");
    }
    let _ = write!(
        out,
        "\nnamespace RustAnything\n{{\n{codec}\n    internal static class {native}\n    {{\n        \
         internal const string Library = \"{lib}\";\n\n        \
         public sealed class RustPanicException : global::System.Exception\n        {{\n            \
         public RustPanicException(string message) : base(\"Rust panic: \" + message) {{ }}\n        }}\n\n        \
         [global::System.Runtime.InteropServices.DllImport(Library, CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl)]\n        \
         private static extern global::System.IntPtr rust_anything_call(byte[] name, byte[] args);\n\n        \
         [global::System.Runtime.InteropServices.DllImport(Library, CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl)]\n        \
         private static extern void rust_anything_free(global::System.IntPtr ptr);\n\n        \
         private static byte[] Z(string s)\n        {{\n            \
         var bytes = global::System.Text.Encoding.UTF8.GetBytes(s);\n            \
         global::System.Array.Resize(ref bytes, bytes.Length + 1);\n            return bytes;\n        }}\n\n        \
         private static global::System.Text.Json.JsonElement Invoke(string name, object?[] args)\n        {{\n            \
         var ptr = rust_anything_call(Z(name), Z({codec_name}.Serialize(args)));\n            \
         if (ptr == global::System.IntPtr.Zero)\n            {{\n                \
         throw new global::System.InvalidOperationException(\"rust-anything: no answer from `\" + name + \"`\");\n            }}\n            \
         string text;\n            \
         try\n            {{\n                \
         text = global::System.Runtime.InteropServices.Marshal.PtrToStringUTF8(ptr) ?? \"\";\n            }}\n            \
         finally\n            {{\n                rust_anything_free(ptr);\n            }}\n            \
         using var doc = global::System.Text.Json.JsonDocument.Parse(text, {codec_name}.DocumentOptions);\n            \
         var root = doc.RootElement;\n            \
         if (root.TryGetProperty(\"ok\", out var ok))\n            {{\n                return ok.Clone();\n            }}\n            \
         if (root.TryGetProperty(\"panic\", out var panic))\n            {{\n                \
         throw new RustPanicException(panic.GetString() ?? \"\");\n            }}\n            \
         throw {codec_name}.Error(root.GetProperty(\"error\").GetString() ?? \"\");\n        }}\n\n        \
         internal static T Call<T>(string name, object?[] args) => {codec_name}.Deserialize<T>(Invoke(name, args));\n\n        \
         internal static void CallVoid(string name, object?[] args) => Invoke(name, args);\n    }}\n}}\n",
        codec = codec(&codec_name, "internal"),
        lib = m.lib_name(),
    );
    let mut by_class: Vec<((String, String), Vec<String>)> = Vec::new();
    for f in &m.exports {
        let (ns, class, method) = qualified(f);
        let ret = f.native_return.as_deref().unwrap_or("void");
        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
        let array = format!("new object?[] {{ {} }}", args.join(", "));
        let call = if ret == "void" {
            format!(
                "global::RustAnything.{native}.CallVoid(\"{}\", {array})",
                f.name
            )
        } else {
            format!(
                "global::RustAnything.{native}.Call<{ret}>(\"{}\", {array})",
                f.name
            )
        };
        let def = format!(
            "public static {ret} {method}({params}) =>\n    {call};",
            params = param_list(f),
        );
        let key = (rust_namespace(&ns), class);
        match by_class.iter_mut().find(|(k, _)| *k == key) {
            Some((_, defs)) => defs.push(def),
            None => by_class.push((key, vec![def])),
        }
    }
    for ((ns, class), defs) in by_class {
        let _ = write!(
            out,
            "\nnamespace {ns}\n{{\n    public static class {class}\n    {{\n"
        );
        for (i, def) in defs.iter().enumerate() {
            if i > 0 {
                out.push('\n');
            }
            for line in def.lines() {
                let _ = writeln!(out, "        {line}");
            }
        }
        out.push_str("    }\n}\n");
    }
    out
}

pub fn driver() -> String {
    format!(
        "#nullable enable\n\nnamespace RustAnything.Driver\n{{\n{}\n}}\n\n{DRIVER_CS}",
        codec("DriverCodec", "internal")
    )
}

/// The driver's project: the owning project's sources, its package references and settings.
pub fn project(
    framework: &str,
    sources: &[std::path::PathBuf],
    project_text: Option<&str>,
) -> String {
    let setting = |name: &str, fallback: &str| -> String {
        project_text
            .and_then(|t| {
                let t = crate::lang::syntax::without_xml_comments(t);
                let value = t
                    .split(&format!("<{name}>"))
                    .nth(1)?
                    .split(&format!("</{name}>"))
                    .next()?
                    .trim()
                    .to_string();
                (!value.is_empty()).then_some(value)
            })
            .unwrap_or_else(|| fallback.to_string())
    };
    let mut items = String::new();
    for s in sources {
        let _ = writeln!(
            items,
            "    <Compile Include=\"{}\" />",
            xml_escape(&s.to_string_lossy())
        );
    }
    if let Some(text) = project_text {
        for tag in package_references(text) {
            let _ = writeln!(items, "    {tag}");
        }
    }
    format!(
        "<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    \
         <OutputType>Exe</OutputType>\n    \
         <TargetFramework>{framework}</TargetFramework>\n    \
         <AssemblyName>RustAnythingDriver</AssemblyName>\n    \
         <RootNamespace>RustAnything.Driver</RootNamespace>\n    \
         <StartupObject>RustAnything.Driver.Program</StartupObject>\n    \
         <EnableDefaultCompileItems>false</EnableDefaultCompileItems>\n    \
         <Nullable>{nullable}</Nullable>\n    \
         <ImplicitUsings>{implicit}</ImplicitUsings>\n    \
         <LangVersion>latest</LangVersion>\n    \
         <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n    \
         <WarningLevel>0</WarningLevel>\n    \
         <TreatWarningsAsErrors>false</TreatWarningsAsErrors>\n    \
         <RollForward>Major</RollForward>\n    \
         <SatelliteResourceLanguages>en</SatelliteResourceLanguages>\n  \
         </PropertyGroup>\n  <ItemGroup>\n{items}    <Compile Include=\"Driver.cs\" />\n  </ItemGroup>\n</Project>\n",
        nullable = setting("Nullable", "disable"),
        implicit = setting("ImplicitUsings", "disable"),
    )
}

const BUILD_ONLY: &[&str] = &[
    "Microsoft.SourceLink.",
    "Microsoft.NETFramework.ReferenceAssemblies",
    "Microsoft.CodeAnalysis.NetAnalyzers",
    "Microsoft.CodeAnalysis.PublicApiAnalyzers",
    "Microsoft.CodeAnalysis.BannedApiAnalyzers",
    "StyleCop.Analyzers",
    "Nerdbank.GitVersioning",
    "MinVer",
    "coverlet.",
    "Roslynator.",
    "SonarAnalyzer.",
];

/// The project's unconditional `<PackageReference>` tags, without build-only tooling (Source Link,
/// reference assemblies, analyzers, versioning): references under a `Condition` target other
/// frameworks than the driver's.
pub fn package_references(project: &str) -> Vec<String> {
    let text = crate::lang::syntax::without_xml_comments(project);
    let mut out = Vec::new();
    for group in text.split("<ItemGroup").skip(1) {
        let head = group.split('>').next().unwrap_or("");
        if head.contains("Condition") {
            continue;
        }
        let body = group.split("</ItemGroup>").next().unwrap_or(group);
        for tag in body.split("<PackageReference").skip(1) {
            let end = match (tag.find("/>"), tag.find("</PackageReference>")) {
                (Some(a), Some(b)) if a < b => a + 2,
                (Some(a), None) => a + 2,
                (_, Some(b)) => b + "</PackageReference>".len(),
                (None, None) => continue,
            };
            let tag = &tag[..end];
            let open = tag.split('>').next().unwrap_or(tag);
            let name = open
                .split("Include=\"")
                .nth(1)
                .and_then(|r| r.split('"').next())
                .unwrap_or("");
            if open.contains("Condition") || BUILD_ONLY.iter().any(|b| name.starts_with(b)) {
                continue;
            }
            out.push(format!("<PackageReference{tag}"));
        }
    }
    out
}

fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

const CODEC_CS: &str = r#"    __VISIBILITY__ static class __CODEC__
    {
        internal static readonly global::System.Text.Json.JsonSerializerOptions Options = Make();

        internal static readonly global::System.Text.Json.JsonDocumentOptions DocumentOptions =
            new global::System.Text.Json.JsonDocumentOptions { MaxDepth = 4096 };

        private static global::System.Text.Json.JsonSerializerOptions Make()
        {
            var o = new global::System.Text.Json.JsonSerializerOptions
            {
                Encoder = global::System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                IncludeFields = true,
                MaxDepth = 4096,
            };
            o.Converters.Add(new DoubleConverter());
            o.Converters.Add(new SingleConverter());
            o.Converters.Add(new StringConverter());
            return o;
        }

        private sealed class StringConverter : global::System.Text.Json.Serialization.JsonConverter<string>
        {
            public override bool HandleNull => false;

            public override string? Read(ref global::System.Text.Json.Utf8JsonReader r, global::System.Type t, global::System.Text.Json.JsonSerializerOptions o)
            {
                if (r.TokenType != global::System.Text.Json.JsonTokenType.StartObject)
                {
                    return r.GetString();
                }
                var units = new global::System.Text.StringBuilder();
                var found = false;
                while (r.Read() && r.TokenType != global::System.Text.Json.JsonTokenType.EndObject)
                {
                    var key = r.GetString();
                    r.Read();
                    if (key == "$utf16" && r.TokenType == global::System.Text.Json.JsonTokenType.StartArray)
                    {
                        found = true;
                        while (r.Read() && r.TokenType != global::System.Text.Json.JsonTokenType.EndArray)
                        {
                            units.Append((char)r.GetUInt16());
                        }
                    }
                    else
                    {
                        r.Skip();
                    }
                }
                if (!found)
                {
                    throw new global::System.Text.Json.JsonException("not a string");
                }
                return units.ToString();
            }

            public override void Write(global::System.Text.Json.Utf8JsonWriter w, string v, global::System.Text.Json.JsonSerializerOptions o)
            {
                for (var i = 0; i < v.Length; i++)
                {
                    if (char.IsHighSurrogate(v[i]) && i + 1 < v.Length && char.IsLowSurrogate(v[i + 1]))
                    {
                        i++;
                    }
                    else if (char.IsSurrogate(v[i]))
                    {
                        w.WriteStartObject();
                        w.WriteStartArray("$utf16");
                        foreach (var c in v)
                        {
                            w.WriteNumberValue((int)c);
                        }
                        w.WriteEndArray();
                        w.WriteEndObject();
                        return;
                    }
                }
                w.WriteStringValue(v);
            }
        }

        private static double ReadNumber(ref global::System.Text.Json.Utf8JsonReader r)
        {
            if (r.TokenType != global::System.Text.Json.JsonTokenType.StartObject)
            {
                return r.GetDouble();
            }
            string? v = null;
            while (r.Read() && r.TokenType != global::System.Text.Json.JsonTokenType.EndObject)
            {
                var key = r.GetString();
                r.Read();
                if (key == "$num" && r.TokenType == global::System.Text.Json.JsonTokenType.String)
                {
                    v = r.GetString();
                }
                else
                {
                    r.Skip();
                }
            }
            return v switch
            {
                "NaN" => double.NaN,
                "Infinity" => double.PositiveInfinity,
                "-Infinity" => double.NegativeInfinity,
                "-0" => -0.0,
                _ => throw new global::System.Text.Json.JsonException("not a number"),
            };
        }

        private static void WriteNumber(global::System.Text.Json.Utf8JsonWriter w, double v, global::System.Action plain)
        {
            string? special = double.IsNaN(v) ? "NaN"
                : double.IsPositiveInfinity(v) ? "Infinity"
                : double.IsNegativeInfinity(v) ? "-Infinity"
                : v == 0 && double.IsNegative(v) ? "-0"
                : null;
            if (special == null)
            {
                plain();
                return;
            }
            w.WriteStartObject();
            w.WriteString("$num", special);
            w.WriteEndObject();
        }

        private sealed class DoubleConverter : global::System.Text.Json.Serialization.JsonConverter<double>
        {
            public override double Read(ref global::System.Text.Json.Utf8JsonReader r, global::System.Type t, global::System.Text.Json.JsonSerializerOptions o) => ReadNumber(ref r);

            public override void Write(global::System.Text.Json.Utf8JsonWriter w, double v, global::System.Text.Json.JsonSerializerOptions o) =>
                WriteNumber(w, v, () => w.WriteNumberValue(v));
        }

        private sealed class SingleConverter : global::System.Text.Json.Serialization.JsonConverter<float>
        {
            public override float Read(ref global::System.Text.Json.Utf8JsonReader r, global::System.Type t, global::System.Text.Json.JsonSerializerOptions o) => (float)ReadNumber(ref r);

            public override void Write(global::System.Text.Json.Utf8JsonWriter w, float v, global::System.Text.Json.JsonSerializerOptions o) =>
                WriteNumber(w, v, () => w.WriteNumberValue(v));
        }

        internal static string Serialize(object?[] args) =>
            global::System.Text.Json.JsonSerializer.Serialize(args, Options);

        internal static T Deserialize<T>(global::System.Text.Json.JsonElement e) =>
            global::System.Text.Json.JsonSerializer.Deserialize<T>(e, Options)!;

        internal static global::System.Exception Error(string message)
        {
            var i = message.IndexOf(": ", global::System.StringComparison.Ordinal);
            if (i > 0 && global::System.Text.RegularExpressions.Regex.IsMatch(message.Substring(0, i), @"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$"))
            {
                var name = message.Substring(0, i);
                var type = global::System.Type.GetType(name);
                if (type == null)
                {
                    foreach (var a in global::System.AppDomain.CurrentDomain.GetAssemblies())
                    {
                        type = a.GetType(name);
                        if (type != null)
                        {
                            break;
                        }
                    }
                }
                if (type != null && typeof(global::System.Exception).IsAssignableFrom(type))
                {
                    try
                    {
                        if (global::System.Activator.CreateInstance(type, message.Substring(i + 2)) is global::System.Exception e)
                        {
                            return e;
                        }
                    }
                    catch (global::System.Exception)
                    {
                    }
                }
            }
            return new global::System.InvalidOperationException(message);
        }
    }
"#;

const DRIVER_CS: &str = r#"namespace RustAnything.Driver
{
    using global::System;
    using global::System.Collections.Generic;
    using global::System.IO;
    using global::System.Reflection;
    using global::System.Text.Json;

    public static class Program
    {
        private sealed class Result
        {
            public JsonElement? Ok;
            public string? Error;
            public string? ErrorType;
            public string Output = "";
        }

        private static bool IsUndefined(JsonElement e) =>
            e.ValueKind == JsonValueKind.Object && e.TryGetProperty("$undefined", out _);

        private static object? Missing(ParameterInfo p)
        {
            if (p.HasDefaultValue && p.DefaultValue != null && p.DefaultValue != DBNull.Value)
            {
                return p.DefaultValue;
            }
            return p.ParameterType.IsValueType && Nullable.GetUnderlyingType(p.ParameterType) == null
                ? Activator.CreateInstance(p.ParameterType)
                : null;
        }

        private static object?[]? Arguments(MethodInfo m, JsonElement args)
        {
            var ps = m.GetParameters();
            var given = new List<JsonElement>();
            if (args.ValueKind == JsonValueKind.Array)
            {
                foreach (var a in args.EnumerateArray())
                {
                    given.Add(a);
                }
            }
            if (given.Count > ps.Length)
            {
                return null;
            }
            var out_ = new object?[ps.Length];
            for (var i = 0; i < ps.Length; i++)
            {
                if (i >= given.Count || IsUndefined(given[i]))
                {
                    out_[i] = Missing(ps[i]);
                    continue;
                }
                try
                {
                    out_[i] = given[i].Deserialize(ps[i].ParameterType, DriverCodec.Options);
                }
                catch (Exception)
                {
                    return null;
                }
            }
            return out_;
        }

        private static Result Call(MethodInfo m, object?[] args)
        {
            var result = new Result();
            var old = Console.Out;
            var sw = new StringWriter();
            Console.SetOut(sw);
            try
            {
                var r = m.Invoke(null, BindingFlags.DoNotWrapExceptions, null, args, null);
                result.Ok = m.ReturnType == typeof(void)
                    ? JsonSerializer.SerializeToElement<object?>(null, DriverCodec.Options)
                    : JsonSerializer.SerializeToElement(r, m.ReturnType, DriverCodec.Options);
            }
            catch (Exception e)
            {
                result.Error = e.Message;
                result.ErrorType = e.GetType().FullName;
            }
            finally
            {
                Console.Out.Flush();
                Console.SetOut(old);
            }
            result.Output = sw.ToString();
            return result;
        }

        private static string Canonical(MethodInfo m, JsonElement e)
        {
            if (m.ReturnType == typeof(void))
            {
                return e.GetRawText();
            }
            try
            {
                return JsonSerializer.Serialize(e.Deserialize(m.ReturnType, DriverCodec.Options), m.ReturnType, DriverCodec.Options);
            }
            catch (Exception)
            {
                return e.GetRawText();
            }
        }

        private static void WriteResult(Utf8JsonWriter w, Result r)
        {
            if (r.Error != null || r.ErrorType != null)
            {
                w.WriteString("error", r.Error ?? "");
                w.WriteString("error_type", r.ErrorType ?? "");
            }
            else
            {
                w.WritePropertyName("ok");
                r.Ok!.Value.WriteTo(w);
            }
            if (r.Output.Length > 0)
            {
                w.WriteString("output", r.Output);
            }
        }

        private static MethodInfo Method(Assembly asm, JsonElement targets, string fn, string side)
        {
            var t = targets.GetProperty(fn);
            var typeName = t.GetProperty(side).GetString()!;
            var type = asm.GetType(typeName) ?? throw new InvalidOperationException("no type " + typeName);
            return type.GetMethod(t.GetProperty("method").GetString()!, BindingFlags.Public | BindingFlags.Static)
                ?? throw new InvalidOperationException("no method " + fn + " on " + typeName);
        }

        private static JsonWriterOptions WriterOptions => new JsonWriterOptions
        {
            Encoder = DriverCodec.Options.Encoder,
            SkipValidation = true,
        };

        public static int Main(string[] argv)
        {
            var mode = argv[0];
            var side = argv.Length > 5 ? "rust" : "original";
            if (argv.Length > 6)
            {
                var libName = argv[5];
                var libPath = argv[6];
                global::System.Runtime.InteropServices.NativeLibrary.SetDllImportResolver(
                    typeof(Program).Assembly,
                    (name, asm, path) => name == libName
                        ? global::System.Runtime.InteropServices.NativeLibrary.Load(libPath)
                        : IntPtr.Zero);
            }
            var asm = typeof(Program).Assembly;
            using var targetsDoc = JsonDocument.Parse(File.ReadAllText(argv[1]), DriverCodec.DocumentOptions);
            var targets = targetsDoc.RootElement;
            var casesPath = argv[2];
            var outPath = argv[3];
            var minMs = long.Parse(argv[4]);
            var lines = new List<JsonDocument>();
            if (mode == "record")
            {
                using var all = JsonDocument.Parse(File.ReadAllText(casesPath), DriverCodec.DocumentOptions);
                foreach (var c in all.RootElement.EnumerateArray())
                {
                    lines.Add(JsonDocument.Parse(c.GetRawText(), DriverCodec.DocumentOptions));
                }
            }
            else
            {
                foreach (var line in File.ReadLines(casesPath))
                {
                    if (line.Trim().Length > 0)
                    {
                        lines.Add(JsonDocument.Parse(line, DriverCodec.DocumentOptions));
                    }
                }
            }
            var progress = Environment.GetEnvironmentVariable("RUST_ANYTHING_PROGRESS");
            switch (mode)
            {
                case "record":
                {
                    using var file = File.Create(outPath);
                    for (var index = 0; index < lines.Count; index++)
                    {
                        if (!string.IsNullOrEmpty(progress))
                        {
                            File.AppendAllText(progress, index + "\n");
                        }
                        var c = lines[index].RootElement;
                        var fn = c.GetProperty("fn").GetString()!;
                        var args = c.TryGetProperty("args", out var a) ? a : default;
                        var m = Method(asm, targets, fn, side);
                        var converted = Arguments(m, args);
                        if (converted == null)
                        {
                            continue;
                        }
                        var r = Call(m, converted);
                        var buffer = new MemoryStream();
                        try
                        {
                            using (var w = new Utf8JsonWriter(buffer, WriterOptions))
                            {
                                w.WriteStartObject();
                                w.WriteString("fn", fn);
                                w.WritePropertyName("args");
                                if (args.ValueKind == JsonValueKind.Undefined)
                                {
                                    w.WriteStartArray();
                                    w.WriteEndArray();
                                }
                                else
                                {
                                    args.WriteTo(w);
                                }
                                WriteResult(w, r);
                                w.WriteEndObject();
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                        buffer.WriteByte((byte)'\n');
                        buffer.Position = 0;
                        buffer.CopyTo(file);
                        file.Flush();
                    }
                    break;
                }
                case "diff":
                {
                    int total = 0, passed = 0, failed = 0;
                    var mismatches = new List<(JsonElement c, Result r)>();
                    foreach (var doc in lines)
                    {
                        var c = doc.RootElement;
                        total++;
                        var fn = c.GetProperty("fn").GetString()!;
                        var m = Method(asm, targets, fn, side);
                        var converted = Arguments(m, c.GetProperty("args"));
                        var r = converted == null
                            ? new Result { Error = "the recorded arguments do not convert to the parameter types", ErrorType = "RustAnything.InputError" }
                            : Call(m, converted);
                        var expectedOutput = c.TryGetProperty("output", out var o) ? o.GetString() ?? "" : "";
                        bool same;
                        if (r.ErrorType != null && r.ErrorType.EndsWith("RustPanicException", StringComparison.Ordinal))
                        {
                            same = false;
                        }
                        else if (expectedOutput != r.Output)
                        {
                            same = false;
                        }
                        else if (c.TryGetProperty("error_type", out var et))
                        {
                            same = r.ErrorType != null && r.ErrorType == et.GetString();
                        }
                        else
                        {
                            same = r.ErrorType == null && c.TryGetProperty("ok", out var ok)
                                && Canonical(m, ok) == Canonical(m, r.Ok!.Value);
                        }
                        if (same)
                        {
                            passed++;
                        }
                        else
                        {
                            failed++;
                            mismatches.Add((c, r));
                        }
                    }
                    using var file = File.Create(outPath);
                    using var w = new Utf8JsonWriter(file, WriterOptions);
                    w.WriteStartObject();
                    w.WriteNumber("total", total);
                    w.WriteNumber("passed", passed);
                    w.WriteNumber("failed", failed);
                    w.WriteStartArray("missing");
                    w.WriteEndArray();
                    w.WriteStartArray("mismatches");
                    foreach (var (c, r) in mismatches)
                    {
                        w.WriteStartObject();
                        w.WritePropertyName("fn");
                        c.GetProperty("fn").WriteTo(w);
                        w.WritePropertyName("args");
                        c.GetProperty("args").WriteTo(w);
                        w.WriteStartObject("expected");
                        foreach (var key in new[] { "ok", "error", "error_type", "output" })
                        {
                            if (c.TryGetProperty(key, out var v))
                            {
                                w.WritePropertyName(key);
                                v.WriteTo(w);
                            }
                        }
                        w.WriteEndObject();
                        w.WriteStartObject("actual");
                        WriteResult(w, r);
                        w.WriteEndObject();
                        w.WriteEndObject();
                    }
                    w.WriteEndArray();
                    w.WriteEndObject();
                    break;
                }
                case "bench":
                {
                    var groups = new Dictionary<string, (MethodInfo m, List<object?[]> args)>();
                    var order = new List<string>();
                    foreach (var doc in lines)
                    {
                        var c = doc.RootElement;
                        var fn = c.GetProperty("fn").GetString()!;
                        if (!groups.ContainsKey(fn))
                        {
                            groups[fn] = (Method(asm, targets, fn, side), new List<object?[]>());
                            order.Add(fn);
                        }
                        var converted = Arguments(groups[fn].m, c.GetProperty("args"));
                        if (converted != null)
                        {
                            groups[fn].args.Add(converted);
                        }
                    }
                    var old = Console.Out;
                    Console.SetOut(TextWriter.Null);
                    using var file = File.Create(outPath);
                    using var w = new Utf8JsonWriter(file, WriterOptions);
                    w.WriteStartObject();
                    foreach (var fn in order)
                    {
                        var (m, prepared) = groups[fn];
                        if (prepared.Count == 0)
                        {
                            continue;
                        }
                        void Once()
                        {
                            foreach (var args in prepared)
                            {
                                try
                                {
                                    m.Invoke(null, BindingFlags.DoNotWrapExceptions, null, (object?[])args.Clone(), null);
                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                        Once();
                        var passes = 0;
                        var watch = global::System.Diagnostics.Stopwatch.StartNew();
                        while (true)
                        {
                            Once();
                            passes++;
                            if (watch.ElapsedMilliseconds >= minMs)
                            {
                                break;
                            }
                        }
                        var ns = watch.Elapsed.TotalMilliseconds * 1e6 / (passes * (double)prepared.Count);
                        w.WriteStartObject(fn);
                        w.WriteNumber("cases", prepared.Count);
                        w.WriteNumber("ns", ns);
                        w.WriteEndObject();
                    }
                    w.WriteEndObject();
                    Console.SetOut(old);
                    break;
                }
            }
            return 0;
        }
    }
}
"#;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn keeps_unconditional_package_references_without_build_tooling() {
        let project = r#"<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" Version="1.0.0"/>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
    <!-- <PackageReference Include="Commented.Out" Version="1.0.0" /> -->
    <PackageReference Include="Serilog"><Version>4.0.0</Version></PackageReference>
  </ItemGroup>
  <ItemGroup Condition=" '$(TargetFramework)' == 'net45' ">
    <PackageReference Include="System.Memory" Version="4.5.3"/>
  </ItemGroup>
</Project>"#;
        assert_eq!(
            package_references(project),
            [
                r#"<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />"#,
                r#"<PackageReference Include="Serilog"><Version>4.0.0</Version></PackageReference>"#,
            ]
        );
    }
}