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()))
}
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())
}
pub fn rust_namespace(ns: &str) -> String {
if ns.is_empty() {
"Rust".into()
} else {
format!("{ns}.Rust")
}
}
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")
)
}
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.",
];
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('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
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>"#,
]
);
}
}