Skip to main content

rust_anything/
codegen_csharp.rs

1//! The C# side of the JSON bridge: a wrapper with the original classes and signatures under
2//! `<namespace>.Rust`, each method calling the Rust library through P/Invoke, and the driver that
3//! records the original and diffs the wrapper.
4
5use std::fmt::Write as _;
6
7use crate::bridge::Manifest;
8use crate::ts::exports::ExportedFn;
9
10pub fn wrapper_path(m: &Manifest) -> String {
11    format!("cs/{}.cs", native_class(m).trim_end_matches("Native"))
12}
13
14pub fn native_class(m: &Manifest) -> String {
15    format!("{}Native", crate::codegen_ruby::camel(&m.lib_name()))
16}
17
18fn codec_class(m: &Manifest) -> String {
19    format!("{}Codec", crate::codegen_ruby::camel(&m.lib_name()))
20}
21
22/// `(namespace, class, method)` of an exported static method, from its prototype
23/// (`Acme.Text.Slug.Slugify(string text)`).
24pub fn qualified(f: &ExportedFn) -> (String, String, String) {
25    let proto = f.prototype.as_deref().unwrap_or(&f.name);
26    let head = proto.split('(').next().unwrap_or(proto).trim();
27    let (class, method) = head.rsplit_once('.').unwrap_or(("", head));
28    let (ns, class) = class.rsplit_once('.').unwrap_or(("", class));
29    (ns.to_string(), class.to_string(), method.to_string())
30}
31
32/// The namespace of the wrapper classes for an original namespace.
33pub fn rust_namespace(ns: &str) -> String {
34    if ns.is_empty() {
35        "Rust".into()
36    } else {
37        format!("{ns}.Rust")
38    }
39}
40
41/// `{ name: { original: "Ns.Class", rust: "Ns.Rust.Class", method } }` for the driver.
42pub fn targets(m: &Manifest) -> serde_json::Value {
43    serde_json::Value::Object(
44        m.exports
45            .iter()
46            .map(|f| {
47                let (ns, class, method) = qualified(f);
48                let join = |ns: &str| {
49                    if ns.is_empty() {
50                        class.clone()
51                    } else {
52                        format!("{ns}.{class}")
53                    }
54                };
55                (
56                    f.name.clone(),
57                    serde_json::json!({
58                        "original": join(&ns),
59                        "rust": join(&rust_namespace(&ns)),
60                        "method": method,
61                    }),
62                )
63            })
64            .collect(),
65    )
66}
67
68fn usings(m: &Manifest) -> Vec<String> {
69    let mut files: Vec<&str> = m.exports.iter().map(|f| f.file.as_str()).collect();
70    files.sort_unstable();
71    files.dedup();
72    let mut out: Vec<String> = Vec::new();
73    for file in files {
74        let text = std::fs::read_to_string(m.root.join(file)).unwrap_or_default();
75        for line in crate::lang::csharp::using_directives(&text) {
76            if !line.starts_with("global ") && !out.contains(&line) {
77                out.push(line);
78            }
79        }
80    }
81    out
82}
83
84fn param_list(f: &ExportedFn) -> String {
85    f.params
86        .iter()
87        .map(|p| {
88            let ty = p.native_type.as_deref().unwrap_or("object");
89            match &p.default {
90                Some(d) => format!("{ty} {} = {d}", p.name),
91                None => format!("{ty} {}", p.name),
92            }
93        })
94        .collect::<Vec<_>>()
95        .join(", ")
96}
97
98fn codec(class: &str, visibility: &str) -> String {
99    CODEC_CS
100        .replace("__CODEC__", class)
101        .replace("__VISIBILITY__", visibility)
102}
103
104pub fn wrapper(m: &Manifest) -> String {
105    let native = native_class(m);
106    let codec_name = codec_class(m);
107    let mut out = format!(
108        "// The Rust port of `{unit}`, generated by rust-anything: the same classes and methods under\n\
109         // `<namespace>.Rust`, each calling the Rust library through P/Invoke. Call them in place of\n\
110         // the originals (or alias them: `using Slug = Acme.Text.Rust.Slug;`).\n\
111         // Regenerate with `rust-anything refresh`.\n\n\
112         #nullable enable\n\n",
113        unit = m.unit,
114    );
115    for line in usings(m) {
116        let _ = writeln!(out, "{line}");
117    }
118    let _ = write!(
119        out,
120        "\nnamespace RustAnything\n{{\n{codec}\n    internal static class {native}\n    {{\n        \
121         internal const string Library = \"{lib}\";\n\n        \
122         public sealed class RustPanicException : global::System.Exception\n        {{\n            \
123         public RustPanicException(string message) : base(\"Rust panic: \" + message) {{ }}\n        }}\n\n        \
124         [global::System.Runtime.InteropServices.DllImport(Library, CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl)]\n        \
125         private static extern global::System.IntPtr rust_anything_call(byte[] name, byte[] args);\n\n        \
126         [global::System.Runtime.InteropServices.DllImport(Library, CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl)]\n        \
127         private static extern void rust_anything_free(global::System.IntPtr ptr);\n\n        \
128         private static byte[] Z(string s)\n        {{\n            \
129         var bytes = global::System.Text.Encoding.UTF8.GetBytes(s);\n            \
130         global::System.Array.Resize(ref bytes, bytes.Length + 1);\n            return bytes;\n        }}\n\n        \
131         private static global::System.Text.Json.JsonElement Invoke(string name, object?[] args)\n        {{\n            \
132         var ptr = rust_anything_call(Z(name), Z({codec_name}.Serialize(args)));\n            \
133         if (ptr == global::System.IntPtr.Zero)\n            {{\n                \
134         throw new global::System.InvalidOperationException(\"rust-anything: no answer from `\" + name + \"`\");\n            }}\n            \
135         string text;\n            \
136         try\n            {{\n                \
137         text = global::System.Runtime.InteropServices.Marshal.PtrToStringUTF8(ptr) ?? \"\";\n            }}\n            \
138         finally\n            {{\n                rust_anything_free(ptr);\n            }}\n            \
139         using var doc = global::System.Text.Json.JsonDocument.Parse(text, {codec_name}.DocumentOptions);\n            \
140         var root = doc.RootElement;\n            \
141         if (root.TryGetProperty(\"ok\", out var ok))\n            {{\n                return ok.Clone();\n            }}\n            \
142         if (root.TryGetProperty(\"panic\", out var panic))\n            {{\n                \
143         throw new RustPanicException(panic.GetString() ?? \"\");\n            }}\n            \
144         throw {codec_name}.Error(root.GetProperty(\"error\").GetString() ?? \"\");\n        }}\n\n        \
145         internal static T Call<T>(string name, object?[] args) => {codec_name}.Deserialize<T>(Invoke(name, args));\n\n        \
146         internal static void CallVoid(string name, object?[] args) => Invoke(name, args);\n    }}\n}}\n",
147        codec = codec(&codec_name, "internal"),
148        lib = m.lib_name(),
149    );
150    let mut by_class: Vec<((String, String), Vec<String>)> = Vec::new();
151    for f in &m.exports {
152        let (ns, class, method) = qualified(f);
153        let ret = f.native_return.as_deref().unwrap_or("void");
154        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
155        let array = format!("new object?[] {{ {} }}", args.join(", "));
156        let call = if ret == "void" {
157            format!(
158                "global::RustAnything.{native}.CallVoid(\"{}\", {array})",
159                f.name
160            )
161        } else {
162            format!(
163                "global::RustAnything.{native}.Call<{ret}>(\"{}\", {array})",
164                f.name
165            )
166        };
167        let def = format!(
168            "public static {ret} {method}({params}) =>\n    {call};",
169            params = param_list(f),
170        );
171        let key = (rust_namespace(&ns), class);
172        match by_class.iter_mut().find(|(k, _)| *k == key) {
173            Some((_, defs)) => defs.push(def),
174            None => by_class.push((key, vec![def])),
175        }
176    }
177    for ((ns, class), defs) in by_class {
178        let _ = write!(
179            out,
180            "\nnamespace {ns}\n{{\n    public static class {class}\n    {{\n"
181        );
182        for (i, def) in defs.iter().enumerate() {
183            if i > 0 {
184                out.push('\n');
185            }
186            for line in def.lines() {
187                let _ = writeln!(out, "        {line}");
188            }
189        }
190        out.push_str("    }\n}\n");
191    }
192    out
193}
194
195pub fn driver() -> String {
196    format!(
197        "#nullable enable\n\nnamespace RustAnything.Driver\n{{\n{}\n}}\n\n{DRIVER_CS}",
198        codec("DriverCodec", "internal")
199    )
200}
201
202/// The driver's project: the owning project's sources, its package references and settings.
203pub fn project(
204    framework: &str,
205    sources: &[std::path::PathBuf],
206    project_text: Option<&str>,
207) -> String {
208    let setting = |name: &str, fallback: &str| -> String {
209        project_text
210            .and_then(|t| {
211                let t = crate::lang::syntax::without_xml_comments(t);
212                let value = t
213                    .split(&format!("<{name}>"))
214                    .nth(1)?
215                    .split(&format!("</{name}>"))
216                    .next()?
217                    .trim()
218                    .to_string();
219                (!value.is_empty()).then_some(value)
220            })
221            .unwrap_or_else(|| fallback.to_string())
222    };
223    let mut items = String::new();
224    for s in sources {
225        let _ = writeln!(
226            items,
227            "    <Compile Include=\"{}\" />",
228            xml_escape(&s.to_string_lossy())
229        );
230    }
231    if let Some(text) = project_text {
232        for tag in package_references(text) {
233            let _ = writeln!(items, "    {tag}");
234        }
235    }
236    format!(
237        "<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    \
238         <OutputType>Exe</OutputType>\n    \
239         <TargetFramework>{framework}</TargetFramework>\n    \
240         <AssemblyName>RustAnythingDriver</AssemblyName>\n    \
241         <RootNamespace>RustAnything.Driver</RootNamespace>\n    \
242         <StartupObject>RustAnything.Driver.Program</StartupObject>\n    \
243         <EnableDefaultCompileItems>false</EnableDefaultCompileItems>\n    \
244         <Nullable>{nullable}</Nullable>\n    \
245         <ImplicitUsings>{implicit}</ImplicitUsings>\n    \
246         <LangVersion>latest</LangVersion>\n    \
247         <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n    \
248         <WarningLevel>0</WarningLevel>\n    \
249         <TreatWarningsAsErrors>false</TreatWarningsAsErrors>\n    \
250         <RollForward>Major</RollForward>\n    \
251         <SatelliteResourceLanguages>en</SatelliteResourceLanguages>\n  \
252         </PropertyGroup>\n  <ItemGroup>\n{items}    <Compile Include=\"Driver.cs\" />\n  </ItemGroup>\n</Project>\n",
253        nullable = setting("Nullable", "disable"),
254        implicit = setting("ImplicitUsings", "disable"),
255    )
256}
257
258const BUILD_ONLY: &[&str] = &[
259    "Microsoft.SourceLink.",
260    "Microsoft.NETFramework.ReferenceAssemblies",
261    "Microsoft.CodeAnalysis.NetAnalyzers",
262    "Microsoft.CodeAnalysis.PublicApiAnalyzers",
263    "Microsoft.CodeAnalysis.BannedApiAnalyzers",
264    "StyleCop.Analyzers",
265    "Nerdbank.GitVersioning",
266    "MinVer",
267    "coverlet.",
268    "Roslynator.",
269    "SonarAnalyzer.",
270];
271
272/// The project's unconditional `<PackageReference>` tags, without build-only tooling (Source Link,
273/// reference assemblies, analyzers, versioning): references under a `Condition` target other
274/// frameworks than the driver's.
275pub fn package_references(project: &str) -> Vec<String> {
276    let text = crate::lang::syntax::without_xml_comments(project);
277    let mut out = Vec::new();
278    for group in text.split("<ItemGroup").skip(1) {
279        let head = group.split('>').next().unwrap_or("");
280        if head.contains("Condition") {
281            continue;
282        }
283        let body = group.split("</ItemGroup>").next().unwrap_or(group);
284        for tag in body.split("<PackageReference").skip(1) {
285            let end = match (tag.find("/>"), tag.find("</PackageReference>")) {
286                (Some(a), Some(b)) if a < b => a + 2,
287                (Some(a), None) => a + 2,
288                (_, Some(b)) => b + "</PackageReference>".len(),
289                (None, None) => continue,
290            };
291            let tag = &tag[..end];
292            let open = tag.split('>').next().unwrap_or(tag);
293            let name = open
294                .split("Include=\"")
295                .nth(1)
296                .and_then(|r| r.split('"').next())
297                .unwrap_or("");
298            if open.contains("Condition") || BUILD_ONLY.iter().any(|b| name.starts_with(b)) {
299                continue;
300            }
301            out.push(format!("<PackageReference{tag}"));
302        }
303    }
304    out
305}
306
307fn xml_escape(s: &str) -> String {
308    s.replace('&', "&amp;")
309        .replace('<', "&lt;")
310        .replace('>', "&gt;")
311        .replace('"', "&quot;")
312}
313
314const CODEC_CS: &str = r#"    __VISIBILITY__ static class __CODEC__
315    {
316        internal static readonly global::System.Text.Json.JsonSerializerOptions Options = Make();
317
318        internal static readonly global::System.Text.Json.JsonDocumentOptions DocumentOptions =
319            new global::System.Text.Json.JsonDocumentOptions { MaxDepth = 4096 };
320
321        private static global::System.Text.Json.JsonSerializerOptions Make()
322        {
323            var o = new global::System.Text.Json.JsonSerializerOptions
324            {
325                Encoder = global::System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
326                IncludeFields = true,
327                MaxDepth = 4096,
328            };
329            o.Converters.Add(new DoubleConverter());
330            o.Converters.Add(new SingleConverter());
331            o.Converters.Add(new StringConverter());
332            return o;
333        }
334
335        private sealed class StringConverter : global::System.Text.Json.Serialization.JsonConverter<string>
336        {
337            public override bool HandleNull => false;
338
339            public override string? Read(ref global::System.Text.Json.Utf8JsonReader r, global::System.Type t, global::System.Text.Json.JsonSerializerOptions o)
340            {
341                if (r.TokenType != global::System.Text.Json.JsonTokenType.StartObject)
342                {
343                    return r.GetString();
344                }
345                var units = new global::System.Text.StringBuilder();
346                var found = false;
347                while (r.Read() && r.TokenType != global::System.Text.Json.JsonTokenType.EndObject)
348                {
349                    var key = r.GetString();
350                    r.Read();
351                    if (key == "$utf16" && r.TokenType == global::System.Text.Json.JsonTokenType.StartArray)
352                    {
353                        found = true;
354                        while (r.Read() && r.TokenType != global::System.Text.Json.JsonTokenType.EndArray)
355                        {
356                            units.Append((char)r.GetUInt16());
357                        }
358                    }
359                    else
360                    {
361                        r.Skip();
362                    }
363                }
364                if (!found)
365                {
366                    throw new global::System.Text.Json.JsonException("not a string");
367                }
368                return units.ToString();
369            }
370
371            public override void Write(global::System.Text.Json.Utf8JsonWriter w, string v, global::System.Text.Json.JsonSerializerOptions o)
372            {
373                for (var i = 0; i < v.Length; i++)
374                {
375                    if (char.IsHighSurrogate(v[i]) && i + 1 < v.Length && char.IsLowSurrogate(v[i + 1]))
376                    {
377                        i++;
378                    }
379                    else if (char.IsSurrogate(v[i]))
380                    {
381                        w.WriteStartObject();
382                        w.WriteStartArray("$utf16");
383                        foreach (var c in v)
384                        {
385                            w.WriteNumberValue((int)c);
386                        }
387                        w.WriteEndArray();
388                        w.WriteEndObject();
389                        return;
390                    }
391                }
392                w.WriteStringValue(v);
393            }
394        }
395
396        private static double ReadNumber(ref global::System.Text.Json.Utf8JsonReader r)
397        {
398            if (r.TokenType != global::System.Text.Json.JsonTokenType.StartObject)
399            {
400                return r.GetDouble();
401            }
402            string? v = null;
403            while (r.Read() && r.TokenType != global::System.Text.Json.JsonTokenType.EndObject)
404            {
405                var key = r.GetString();
406                r.Read();
407                if (key == "$num" && r.TokenType == global::System.Text.Json.JsonTokenType.String)
408                {
409                    v = r.GetString();
410                }
411                else
412                {
413                    r.Skip();
414                }
415            }
416            return v switch
417            {
418                "NaN" => double.NaN,
419                "Infinity" => double.PositiveInfinity,
420                "-Infinity" => double.NegativeInfinity,
421                "-0" => -0.0,
422                _ => throw new global::System.Text.Json.JsonException("not a number"),
423            };
424        }
425
426        private static void WriteNumber(global::System.Text.Json.Utf8JsonWriter w, double v, global::System.Action plain)
427        {
428            string? special = double.IsNaN(v) ? "NaN"
429                : double.IsPositiveInfinity(v) ? "Infinity"
430                : double.IsNegativeInfinity(v) ? "-Infinity"
431                : v == 0 && double.IsNegative(v) ? "-0"
432                : null;
433            if (special == null)
434            {
435                plain();
436                return;
437            }
438            w.WriteStartObject();
439            w.WriteString("$num", special);
440            w.WriteEndObject();
441        }
442
443        private sealed class DoubleConverter : global::System.Text.Json.Serialization.JsonConverter<double>
444        {
445            public override double Read(ref global::System.Text.Json.Utf8JsonReader r, global::System.Type t, global::System.Text.Json.JsonSerializerOptions o) => ReadNumber(ref r);
446
447            public override void Write(global::System.Text.Json.Utf8JsonWriter w, double v, global::System.Text.Json.JsonSerializerOptions o) =>
448                WriteNumber(w, v, () => w.WriteNumberValue(v));
449        }
450
451        private sealed class SingleConverter : global::System.Text.Json.Serialization.JsonConverter<float>
452        {
453            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);
454
455            public override void Write(global::System.Text.Json.Utf8JsonWriter w, float v, global::System.Text.Json.JsonSerializerOptions o) =>
456                WriteNumber(w, v, () => w.WriteNumberValue(v));
457        }
458
459        internal static string Serialize(object?[] args) =>
460            global::System.Text.Json.JsonSerializer.Serialize(args, Options);
461
462        internal static T Deserialize<T>(global::System.Text.Json.JsonElement e) =>
463            global::System.Text.Json.JsonSerializer.Deserialize<T>(e, Options)!;
464
465        internal static global::System.Exception Error(string message)
466        {
467            var i = message.IndexOf(": ", global::System.StringComparison.Ordinal);
468            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_]*)*$"))
469            {
470                var name = message.Substring(0, i);
471                var type = global::System.Type.GetType(name);
472                if (type == null)
473                {
474                    foreach (var a in global::System.AppDomain.CurrentDomain.GetAssemblies())
475                    {
476                        type = a.GetType(name);
477                        if (type != null)
478                        {
479                            break;
480                        }
481                    }
482                }
483                if (type != null && typeof(global::System.Exception).IsAssignableFrom(type))
484                {
485                    try
486                    {
487                        if (global::System.Activator.CreateInstance(type, message.Substring(i + 2)) is global::System.Exception e)
488                        {
489                            return e;
490                        }
491                    }
492                    catch (global::System.Exception)
493                    {
494                    }
495                }
496            }
497            return new global::System.InvalidOperationException(message);
498        }
499    }
500"#;
501
502const DRIVER_CS: &str = r#"namespace RustAnything.Driver
503{
504    using global::System;
505    using global::System.Collections.Generic;
506    using global::System.IO;
507    using global::System.Reflection;
508    using global::System.Text.Json;
509
510    public static class Program
511    {
512        private sealed class Result
513        {
514            public JsonElement? Ok;
515            public string? Error;
516            public string? ErrorType;
517            public string Output = "";
518        }
519
520        private static bool IsUndefined(JsonElement e) =>
521            e.ValueKind == JsonValueKind.Object && e.TryGetProperty("$undefined", out _);
522
523        private static object? Missing(ParameterInfo p)
524        {
525            if (p.HasDefaultValue && p.DefaultValue != null && p.DefaultValue != DBNull.Value)
526            {
527                return p.DefaultValue;
528            }
529            return p.ParameterType.IsValueType && Nullable.GetUnderlyingType(p.ParameterType) == null
530                ? Activator.CreateInstance(p.ParameterType)
531                : null;
532        }
533
534        private static object?[]? Arguments(MethodInfo m, JsonElement args)
535        {
536            var ps = m.GetParameters();
537            var given = new List<JsonElement>();
538            if (args.ValueKind == JsonValueKind.Array)
539            {
540                foreach (var a in args.EnumerateArray())
541                {
542                    given.Add(a);
543                }
544            }
545            if (given.Count > ps.Length)
546            {
547                return null;
548            }
549            var out_ = new object?[ps.Length];
550            for (var i = 0; i < ps.Length; i++)
551            {
552                if (i >= given.Count || IsUndefined(given[i]))
553                {
554                    out_[i] = Missing(ps[i]);
555                    continue;
556                }
557                try
558                {
559                    out_[i] = given[i].Deserialize(ps[i].ParameterType, DriverCodec.Options);
560                }
561                catch (Exception)
562                {
563                    return null;
564                }
565            }
566            return out_;
567        }
568
569        private static Result Call(MethodInfo m, object?[] args)
570        {
571            var result = new Result();
572            var old = Console.Out;
573            var sw = new StringWriter();
574            Console.SetOut(sw);
575            try
576            {
577                var r = m.Invoke(null, BindingFlags.DoNotWrapExceptions, null, args, null);
578                result.Ok = m.ReturnType == typeof(void)
579                    ? JsonSerializer.SerializeToElement<object?>(null, DriverCodec.Options)
580                    : JsonSerializer.SerializeToElement(r, m.ReturnType, DriverCodec.Options);
581            }
582            catch (Exception e)
583            {
584                result.Error = e.Message;
585                result.ErrorType = e.GetType().FullName;
586            }
587            finally
588            {
589                Console.Out.Flush();
590                Console.SetOut(old);
591            }
592            result.Output = sw.ToString();
593            return result;
594        }
595
596        private static string Canonical(MethodInfo m, JsonElement e)
597        {
598            if (m.ReturnType == typeof(void))
599            {
600                return e.GetRawText();
601            }
602            try
603            {
604                return JsonSerializer.Serialize(e.Deserialize(m.ReturnType, DriverCodec.Options), m.ReturnType, DriverCodec.Options);
605            }
606            catch (Exception)
607            {
608                return e.GetRawText();
609            }
610        }
611
612        private static void WriteResult(Utf8JsonWriter w, Result r)
613        {
614            if (r.Error != null || r.ErrorType != null)
615            {
616                w.WriteString("error", r.Error ?? "");
617                w.WriteString("error_type", r.ErrorType ?? "");
618            }
619            else
620            {
621                w.WritePropertyName("ok");
622                r.Ok!.Value.WriteTo(w);
623            }
624            if (r.Output.Length > 0)
625            {
626                w.WriteString("output", r.Output);
627            }
628        }
629
630        private static MethodInfo Method(Assembly asm, JsonElement targets, string fn, string side)
631        {
632            var t = targets.GetProperty(fn);
633            var typeName = t.GetProperty(side).GetString()!;
634            var type = asm.GetType(typeName) ?? throw new InvalidOperationException("no type " + typeName);
635            return type.GetMethod(t.GetProperty("method").GetString()!, BindingFlags.Public | BindingFlags.Static)
636                ?? throw new InvalidOperationException("no method " + fn + " on " + typeName);
637        }
638
639        private static JsonWriterOptions WriterOptions => new JsonWriterOptions
640        {
641            Encoder = DriverCodec.Options.Encoder,
642            SkipValidation = true,
643        };
644
645        public static int Main(string[] argv)
646        {
647            var mode = argv[0];
648            var side = argv.Length > 5 ? "rust" : "original";
649            if (argv.Length > 6)
650            {
651                var libName = argv[5];
652                var libPath = argv[6];
653                global::System.Runtime.InteropServices.NativeLibrary.SetDllImportResolver(
654                    typeof(Program).Assembly,
655                    (name, asm, path) => name == libName
656                        ? global::System.Runtime.InteropServices.NativeLibrary.Load(libPath)
657                        : IntPtr.Zero);
658            }
659            var asm = typeof(Program).Assembly;
660            using var targetsDoc = JsonDocument.Parse(File.ReadAllText(argv[1]), DriverCodec.DocumentOptions);
661            var targets = targetsDoc.RootElement;
662            var casesPath = argv[2];
663            var outPath = argv[3];
664            var minMs = long.Parse(argv[4]);
665            var lines = new List<JsonDocument>();
666            if (mode == "record")
667            {
668                using var all = JsonDocument.Parse(File.ReadAllText(casesPath), DriverCodec.DocumentOptions);
669                foreach (var c in all.RootElement.EnumerateArray())
670                {
671                    lines.Add(JsonDocument.Parse(c.GetRawText(), DriverCodec.DocumentOptions));
672                }
673            }
674            else
675            {
676                foreach (var line in File.ReadLines(casesPath))
677                {
678                    if (line.Trim().Length > 0)
679                    {
680                        lines.Add(JsonDocument.Parse(line, DriverCodec.DocumentOptions));
681                    }
682                }
683            }
684            var progress = Environment.GetEnvironmentVariable("RUST_ANYTHING_PROGRESS");
685            switch (mode)
686            {
687                case "record":
688                {
689                    using var file = File.Create(outPath);
690                    for (var index = 0; index < lines.Count; index++)
691                    {
692                        if (!string.IsNullOrEmpty(progress))
693                        {
694                            File.AppendAllText(progress, index + "\n");
695                        }
696                        var c = lines[index].RootElement;
697                        var fn = c.GetProperty("fn").GetString()!;
698                        var args = c.TryGetProperty("args", out var a) ? a : default;
699                        var m = Method(asm, targets, fn, side);
700                        var converted = Arguments(m, args);
701                        if (converted == null)
702                        {
703                            continue;
704                        }
705                        var r = Call(m, converted);
706                        var buffer = new MemoryStream();
707                        try
708                        {
709                            using (var w = new Utf8JsonWriter(buffer, WriterOptions))
710                            {
711                                w.WriteStartObject();
712                                w.WriteString("fn", fn);
713                                w.WritePropertyName("args");
714                                if (args.ValueKind == JsonValueKind.Undefined)
715                                {
716                                    w.WriteStartArray();
717                                    w.WriteEndArray();
718                                }
719                                else
720                                {
721                                    args.WriteTo(w);
722                                }
723                                WriteResult(w, r);
724                                w.WriteEndObject();
725                            }
726                        }
727                        catch (Exception)
728                        {
729                            continue;
730                        }
731                        buffer.WriteByte((byte)'\n');
732                        buffer.Position = 0;
733                        buffer.CopyTo(file);
734                        file.Flush();
735                    }
736                    break;
737                }
738                case "diff":
739                {
740                    int total = 0, passed = 0, failed = 0;
741                    var mismatches = new List<(JsonElement c, Result r)>();
742                    foreach (var doc in lines)
743                    {
744                        var c = doc.RootElement;
745                        total++;
746                        var fn = c.GetProperty("fn").GetString()!;
747                        var m = Method(asm, targets, fn, side);
748                        var converted = Arguments(m, c.GetProperty("args"));
749                        var r = converted == null
750                            ? new Result { Error = "the recorded arguments do not convert to the parameter types", ErrorType = "RustAnything.InputError" }
751                            : Call(m, converted);
752                        var expectedOutput = c.TryGetProperty("output", out var o) ? o.GetString() ?? "" : "";
753                        bool same;
754                        if (r.ErrorType != null && r.ErrorType.EndsWith("RustPanicException", StringComparison.Ordinal))
755                        {
756                            same = false;
757                        }
758                        else if (expectedOutput != r.Output)
759                        {
760                            same = false;
761                        }
762                        else if (c.TryGetProperty("error_type", out var et))
763                        {
764                            same = r.ErrorType != null && r.ErrorType == et.GetString();
765                        }
766                        else
767                        {
768                            same = r.ErrorType == null && c.TryGetProperty("ok", out var ok)
769                                && Canonical(m, ok) == Canonical(m, r.Ok!.Value);
770                        }
771                        if (same)
772                        {
773                            passed++;
774                        }
775                        else
776                        {
777                            failed++;
778                            mismatches.Add((c, r));
779                        }
780                    }
781                    using var file = File.Create(outPath);
782                    using var w = new Utf8JsonWriter(file, WriterOptions);
783                    w.WriteStartObject();
784                    w.WriteNumber("total", total);
785                    w.WriteNumber("passed", passed);
786                    w.WriteNumber("failed", failed);
787                    w.WriteStartArray("missing");
788                    w.WriteEndArray();
789                    w.WriteStartArray("mismatches");
790                    foreach (var (c, r) in mismatches)
791                    {
792                        w.WriteStartObject();
793                        w.WritePropertyName("fn");
794                        c.GetProperty("fn").WriteTo(w);
795                        w.WritePropertyName("args");
796                        c.GetProperty("args").WriteTo(w);
797                        w.WriteStartObject("expected");
798                        foreach (var key in new[] { "ok", "error", "error_type", "output" })
799                        {
800                            if (c.TryGetProperty(key, out var v))
801                            {
802                                w.WritePropertyName(key);
803                                v.WriteTo(w);
804                            }
805                        }
806                        w.WriteEndObject();
807                        w.WriteStartObject("actual");
808                        WriteResult(w, r);
809                        w.WriteEndObject();
810                        w.WriteEndObject();
811                    }
812                    w.WriteEndArray();
813                    w.WriteEndObject();
814                    break;
815                }
816                case "bench":
817                {
818                    var groups = new Dictionary<string, (MethodInfo m, List<object?[]> args)>();
819                    var order = new List<string>();
820                    foreach (var doc in lines)
821                    {
822                        var c = doc.RootElement;
823                        var fn = c.GetProperty("fn").GetString()!;
824                        if (!groups.ContainsKey(fn))
825                        {
826                            groups[fn] = (Method(asm, targets, fn, side), new List<object?[]>());
827                            order.Add(fn);
828                        }
829                        var converted = Arguments(groups[fn].m, c.GetProperty("args"));
830                        if (converted != null)
831                        {
832                            groups[fn].args.Add(converted);
833                        }
834                    }
835                    var old = Console.Out;
836                    Console.SetOut(TextWriter.Null);
837                    using var file = File.Create(outPath);
838                    using var w = new Utf8JsonWriter(file, WriterOptions);
839                    w.WriteStartObject();
840                    foreach (var fn in order)
841                    {
842                        var (m, prepared) = groups[fn];
843                        if (prepared.Count == 0)
844                        {
845                            continue;
846                        }
847                        void Once()
848                        {
849                            foreach (var args in prepared)
850                            {
851                                try
852                                {
853                                    m.Invoke(null, BindingFlags.DoNotWrapExceptions, null, (object?[])args.Clone(), null);
854                                }
855                                catch (Exception)
856                                {
857                                }
858                            }
859                        }
860                        Once();
861                        var passes = 0;
862                        var watch = global::System.Diagnostics.Stopwatch.StartNew();
863                        while (true)
864                        {
865                            Once();
866                            passes++;
867                            if (watch.ElapsedMilliseconds >= minMs)
868                            {
869                                break;
870                            }
871                        }
872                        var ns = watch.Elapsed.TotalMilliseconds * 1e6 / (passes * (double)prepared.Count);
873                        w.WriteStartObject(fn);
874                        w.WriteNumber("cases", prepared.Count);
875                        w.WriteNumber("ns", ns);
876                        w.WriteEndObject();
877                    }
878                    w.WriteEndObject();
879                    Console.SetOut(old);
880                    break;
881                }
882            }
883            return 0;
884        }
885    }
886}
887"#;
888
889#[cfg(test)]
890mod tests {
891    use super::*;
892
893    #[test]
894    fn keeps_unconditional_package_references_without_build_tooling() {
895        let project = r#"<Project Sdk="Microsoft.NET.Sdk">
896  <ItemGroup>
897    <PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" Version="1.0.0"/>
898    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
899    <!-- <PackageReference Include="Commented.Out" Version="1.0.0" /> -->
900    <PackageReference Include="Serilog"><Version>4.0.0</Version></PackageReference>
901  </ItemGroup>
902  <ItemGroup Condition=" '$(TargetFramework)' == 'net45' ">
903    <PackageReference Include="System.Memory" Version="4.5.3"/>
904  </ItemGroup>
905</Project>"#;
906        assert_eq!(
907            package_references(project),
908            [
909                r#"<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />"#,
910                r#"<PackageReference Include="Serilog"><Version>4.0.0</Version></PackageReference>"#,
911            ]
912        );
913    }
914}