-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRustSharpMetadata.cs
More file actions
1407 lines (1273 loc) · 66.4 KB
/
Copy pathRustSharpMetadata.cs
File metadata and controls
1407 lines (1273 loc) · 66.4 KB
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using RustSharp.Semantics;
namespace RustSharp.CodeGen.IL;
/// <summary>
/// A deterministic function export carried in Rust# assembly metadata. <see
/// cref="Name"/> is the emitted CLR method name retained for v1 compatibility;
/// <see cref="SourceQualifiedName"/> is the source/HIR identity used to link
/// ownership evidence, and <see cref="IsPublic"/> controls cross-package use.
/// </summary>
public sealed record RustSharpMetadataFunction(
string Name,
string Signature,
string? SourceQualifiedName = null,
bool IsPublic = true);
/// <summary>A field in a versioned Rust# nominal value layout.</summary>
public sealed record RustSharpMetadataField(string Name, string Type);
/// <summary>
/// A closed nominal value layout exported by a producer. Field order is part
/// of the source contract and is therefore retained in the metadata document.
/// </summary>
public sealed record RustSharpMetadataValueType(
string Name,
IEnumerable<RustSharpMetadataField>? Fields = null);
/// <summary>A closed generic instance carried in Rust# assembly metadata.</summary>
public sealed record RustSharpMetadataGenericInstance(string FunctionId, string Arguments);
/// <summary>
/// Ownership evidence persisted for one emitted function. The backend never
/// infers safety from CLR value semantics; consumers can use these facts to
/// decide whether a producer was checked with the declared ownership pass.
/// </summary>
public sealed record RustSharpMetadataOwnershipFunction(
string FunctionId,
string PanicStrategy,
IEnumerable<string>? DropOrder = null,
IEnumerable<string>? Outcomes = null,
IEnumerable<string>? BorrowFacts = null);
/// <summary>
/// Explicit ownership and panic terms for one imported call. CLR signatures
/// cannot carry these language-level terms, so consumers validate this record
/// before emitting a cross-package MemberRef.
/// </summary>
public sealed record RustSharpMetadataCallContract(
string FunctionId,
string PanicStrategy,
IEnumerable<string>? ParameterContracts = null,
string? ReturnContract = null)
{
public const string ScalarSchema = "rustsharp-scalar-call-v1";
/// <summary>An explicit schema for a complete source-generated scalar contract.</summary>
public string? Schema { get; init; }
}
/// <summary>A bounded result returned when an independent assembly is imported.</summary>
public sealed record RustSharpMetadataImportResult(
string AssemblyPath,
RustSharpMetadataDocument? Document,
string? GenericMetadataJson,
Guid? ModuleVersionId,
IReadOnlyList<string> Diagnostics)
{
/// <summary>The CLR AssemblyDef name, which may differ from the file name.</summary>
public string? AssemblyName { get; init; }
public bool IsSuccessful => Document is not null && Diagnostics.Count == 0;
}
/// <summary>
/// Versioned language metadata that is embedded in generated assemblies. CLR
/// metadata cannot express Rust ownership, profile or monomorphization facts;
/// this bounded document is the consumer-facing contract for those facts.
/// </summary>
public sealed partial record RustSharpMetadataDocument
{
public const string SchemaVersion = "rustsharp-metadata-v1";
public const int MaximumFunctions = 4096;
public const int MaximumGenericInstances = 4096;
public const int MaximumTraits = 4096;
public const int MaximumOwnershipFunctions = 4096;
public const int MaximumOwnershipFactsPerFunction = 4096;
public const int MaximumCallContracts = 4096;
public const int MaximumCallTermsPerFunction = 256;
public const int MaximumValueTypes = 4096;
public const int MaximumFieldsPerValueType = 256;
public const int MaximumJsonCharacters = 1_000_000;
public RustSharpMetadataDocument(
string profile,
string sourceSha256,
IEnumerable<RustSharpMetadataFunction>? functions = null,
IEnumerable<RustSharpMetadataGenericInstance>? genericInstances = null,
IEnumerable<string>? traitImplementations = null,
string? mirSnapshot = null,
IEnumerable<RustSharpMetadataOwnershipFunction>? ownership = null,
string? cleanupSnapshot = null,
IEnumerable<RustSharpMetadataCallContract>? callContracts = null,
IEnumerable<RustSharpMetadataValueType>? valueTypes = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(profile);
ArgumentException.ThrowIfNullOrWhiteSpace(sourceSha256);
if (profile.Length > 256 || sourceSha256.Length != 64 ||
sourceSha256.Any(static character => !Uri.IsHexDigit(character)))
throw new ArgumentException("Rust# metadata identity is invalid.");
Schema = SchemaVersion;
Profile = profile;
SourceSha256 = sourceSha256;
Functions = NormalizeFunctions(functions);
GenericInstances = NormalizeGenericInstances(genericInstances);
TraitImplementations = NormalizeStrings(traitImplementations, MaximumTraits, "trait implementations");
MirSnapshot = mirSnapshot is null ? null : LimitText(mirSnapshot, MaximumJsonCharacters);
Ownership = NormalizeOwnership(ownership);
CleanupSnapshot = cleanupSnapshot is null ? null : LimitText(cleanupSnapshot, MaximumJsonCharacters);
CallContracts = NormalizeCallContracts(callContracts);
ValueTypes = NormalizeValueTypes(valueTypes);
Json = Serialize(this);
if (Json.Length > MaximumJsonCharacters)
throw new ArgumentException("Rust# metadata JSON exceeds its size limit.");
}
public string Schema { get; }
public string Profile { get; }
public string SourceSha256 { get; }
public ImmutableArray<RustSharpMetadataFunction> Functions { get; }
public ImmutableArray<RustSharpMetadataGenericInstance> GenericInstances { get; }
public ImmutableArray<string> TraitImplementations { get; }
public string? MirSnapshot { get; }
public ImmutableArray<RustSharpMetadataOwnershipFunction> Ownership { get; }
/// <summary>Optional deterministic P1-08 cleanup projection snapshot.</summary>
public string? CleanupSnapshot { get; }
/// <summary>Explicit imported-call ownership and panic terms.</summary>
public ImmutableArray<RustSharpMetadataCallContract> CallContracts { get; }
/// <summary>Closed nominal layouts used by aggregate MemberRefs.</summary>
public ImmutableArray<RustSharpMetadataValueType> ValueTypes { get; }
[JsonIgnore]
public string Json { get; }
public static RustSharpMetadataDocument ForProgram(
string profile,
ReadOnlySpan<byte> sourceBytes,
IReadOnlyList<ClrLirMethod> methods,
IEnumerable<RustSharpMetadataGenericInstance>? genericInstances = null,
IEnumerable<string>? traitImplementations = null,
string? mirSnapshot = null,
IEnumerable<RustSharpMetadataOwnershipFunction>? ownership = null,
string? cleanupSnapshot = null,
IEnumerable<RustSharpMetadataCallContract>? callContracts = null,
IEnumerable<RustSharpMetadataValueType>? valueTypes = null)
{
ArgumentNullException.ThrowIfNull(methods);
if (methods.Count > MaximumFunctions) throw new ArgumentException("Too many methods.", nameof(methods));
var linkClock = Stopwatch.StartNew();
var functions = new RustSharpMetadataFunction[methods.Count];
for (int index = 0; index < methods.Count; index++)
{
ClrLirMethod method = methods[index] ?? throw new ArgumentException("Method cannot be null.", nameof(methods));
string signature = string.Join(",", method.Parameters.Select(static type => type.ToString())) +
"->" + method.ReturnType;
functions[index] = new(
method.Name,
signature,
method.SourceQualifiedName ?? method.Name,
method.IsPublic);
}
IEnumerable<RustSharpMetadataCallContract>? linkedContracts = callContracts?.Select(contract =>
{
// Ownership evidence may use the internal `#value` body identity,
// while the emitted method carries the source identity. Resolve
// the contract against the actual function table so a producer
// never publishes a self-referential but unimportable term.
RustSharpMetadataFunction? target = ResolveTarget(contract.FunctionId);
return target is null
? contract
: contract with { FunctionId = LinkedIdentity(target) };
});
IEnumerable<RustSharpMetadataOwnershipFunction>? linkedOwnership = ownership?.Select(value =>
{
// The ownership pass may report its internal body identity with a
// `#value` suffix. Persist the emitted source identity so consumers
// can correlate the evidence with the generated MethodDef.
RustSharpMetadataFunction? target = ResolveTarget(value.FunctionId);
return target is null
? value
: value with { FunctionId = LinkedIdentity(target) };
});
return new(profile, Convert.ToHexString(SHA256.HashData(sourceBytes)), functions,
genericInstances, traitImplementations, mirSnapshot, linkedOwnership, cleanupSnapshot, linkedContracts,
valueTypes);
RustSharpMetadataFunction? ResolveTarget(string functionId)
{
CheckLinkBudget();
// A closed CLR identity takes precedence over a source alias shared
// by several generic instances. Source-only evidence cannot choose
// one of those instances without its emitted specialization ID.
RustSharpMetadataFunction? emitted = functions.FirstOrDefault(function => function.Name == functionId);
if (emitted is not null) return emitted;
RustSharpMetadataFunction[] matches = functions.Where(function =>
function.SourceQualifiedName == functionId ||
function.SourceQualifiedName == functionId + "#value" ||
function.SourceQualifiedName + "#value" == functionId).Take(2).ToArray();
if (matches.Length > 1)
throw new ArgumentException("Ambiguous source call evidence requires an emitted CLR specialization ID.", nameof(callContracts));
return matches.FirstOrDefault();
}
string LinkedIdentity(RustSharpMetadataFunction target)
{
CheckLinkBudget();
return target.SourceQualifiedName is { } source &&
functions.Count(function => function.SourceQualifiedName == source) == 1
? source : target.Name;
}
void CheckLinkBudget()
{
if (linkClock.Elapsed > TimeSpan.FromSeconds(5))
throw new TimeoutException("Source-to-CLR metadata linking exceeded its bounded budget.");
}
}
/// <summary>
/// Returns a document reconciled with the actual LIR layouts. A producer
/// cannot omit layouts when it emits nominal values, and a supplied layout
/// list must match declaration order exactly.
/// </summary>
public RustSharpMetadataDocument WithValueTypes(IEnumerable<RustSharpMetadataValueType> valueTypes)
{
ArgumentNullException.ThrowIfNull(valueTypes);
RustSharpMetadataValueType[] actual = NormalizeValueTypes(valueTypes).ToArray();
if (ValueTypes.Length != 0 && !ValueTypesEqual(ValueTypes, actual))
throw new ArgumentException("Rust# metadata value layouts do not match emitted layouts.", nameof(valueTypes));
return ValueTypes.Length == 0
? new(Profile, SourceSha256, Functions, GenericInstances, TraitImplementations, MirSnapshot,
Ownership, CleanupSnapshot, CallContracts, actual)
: this;
}
private static bool ValueTypesEqual(
IReadOnlyList<RustSharpMetadataValueType> expected,
RustSharpMetadataValueType[] actual)
{
if (expected.Count != actual.Length) return false;
for (int index = 0; index < expected.Count; index++)
{
RustSharpMetadataValueType left = expected[index];
RustSharpMetadataValueType right = actual[index];
RustSharpMetadataField[] leftFields = left.Fields?.ToArray() ?? [];
RustSharpMetadataField[] rightFields = right.Fields?.ToArray() ?? [];
if (!string.Equals(left.Name, right.Name, StringComparison.Ordinal) ||
leftFields.Length != rightFields.Length)
return false;
for (int fieldIndex = 0; fieldIndex < leftFields.Length; fieldIndex++)
{
if (!string.Equals(leftFields[fieldIndex].Name, rightFields[fieldIndex].Name, StringComparison.Ordinal) ||
!string.Equals(leftFields[fieldIndex].Type, rightFields[fieldIndex].Type, StringComparison.Ordinal))
return false;
}
}
return true;
}
private static ImmutableArray<RustSharpMetadataFunction> NormalizeFunctions(IEnumerable<RustSharpMetadataFunction>? values)
{
if (values is null) return [];
RustSharpMetadataFunction[] result = Materialize(values, MaximumFunctions, nameof(values));
if (result.Any(static value => value is null))
throw new ArgumentException("Rust# metadata function count is out of bounds.", nameof(values));
var names = new HashSet<string>(StringComparer.Ordinal);
var sourceNames = new HashSet<string>(StringComparer.Ordinal);
foreach (RustSharpMetadataFunction value in result)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value.Name);
ArgumentException.ThrowIfNullOrWhiteSpace(value.Signature);
if (value.Name.Length > 4096 || value.Signature.Length > 4096)
throw new ArgumentException("Rust# metadata function identity is too long.", nameof(values));
if (!names.Add(value.Name))
throw new ArgumentException("Rust# metadata function names must be unique.", nameof(values));
if (value.SourceQualifiedName is not null &&
(string.IsNullOrWhiteSpace(value.SourceQualifiedName) || value.SourceQualifiedName.Length > 4096))
throw new ArgumentException("Rust# metadata source function identity is invalid.", nameof(values));
// A source item may have several closed generic instances or
// overloads. Its source identity is unique only together with
// the declared signature; rejecting the source name alone would
// make valid monomorphized functions impossible to emit.
if (value.SourceQualifiedName is not null &&
!sourceNames.Add(value.SourceQualifiedName + "\u001f" + value.Signature))
throw new ArgumentException("Rust# metadata source function identities must be unique for a signature.", nameof(values));
}
return [.. result.OrderBy(static value => value.Name, StringComparer.Ordinal)
.ThenBy(static value => value.Signature, StringComparer.Ordinal)
.ThenBy(static value => value.SourceQualifiedName, StringComparer.Ordinal)];
}
private static ImmutableArray<RustSharpMetadataGenericInstance> NormalizeGenericInstances(IEnumerable<RustSharpMetadataGenericInstance>? values)
{
if (values is null) return [];
RustSharpMetadataGenericInstance[] result = Materialize(values, MaximumGenericInstances, nameof(values));
if (result.Any(static value => value is null))
throw new ArgumentException("Rust# generic metadata count is out of bounds.", nameof(values));
foreach (RustSharpMetadataGenericInstance value in result)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value.FunctionId);
ArgumentException.ThrowIfNullOrWhiteSpace(value.Arguments);
}
return [.. result.OrderBy(static value => value.FunctionId, StringComparer.Ordinal)
.ThenBy(static value => value.Arguments, StringComparer.Ordinal)];
}
private static ImmutableArray<string> NormalizeStrings(IEnumerable<string>? values, int maximum, string label)
{
if (values is null) return [];
string[] result = Materialize(values, maximum, nameof(values));
if (result.Any(string.IsNullOrWhiteSpace))
throw new ArgumentException($"Rust# metadata {label} are invalid.", nameof(values));
return [.. result.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)];
}
private static ImmutableArray<RustSharpMetadataOwnershipFunction> NormalizeOwnership(
IEnumerable<RustSharpMetadataOwnershipFunction>? values)
{
if (values is null) return [];
RustSharpMetadataOwnershipFunction[] result = Materialize(
values, MaximumOwnershipFunctions, nameof(values));
if (result.Any(static value => value is null))
throw new ArgumentException("Rust# ownership metadata count is out of bounds.", nameof(values));
var normalized = new List<RustSharpMetadataOwnershipFunction>(result.Length);
foreach (RustSharpMetadataOwnershipFunction value in result)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value.FunctionId);
ArgumentException.ThrowIfNullOrWhiteSpace(value.PanicStrategy);
if (value.FunctionId.Length > 4096 || value.PanicStrategy.Length > 64)
throw new ArgumentException("Rust# ownership metadata identity is too long.", nameof(values));
string[] drops = NormalizeFacts(value.DropOrder, "drop order");
string[] outcomes = NormalizeFacts(value.Outcomes, "outcomes");
string[] borrows = NormalizeFacts(value.BorrowFacts, "borrow facts");
normalized.Add(new(value.FunctionId, value.PanicStrategy, drops, outcomes, borrows));
}
return [.. normalized
.OrderBy(static value => value.FunctionId, StringComparer.Ordinal)
.ThenBy(static value => value.PanicStrategy, StringComparer.Ordinal)
.ThenBy(static value => string.Join("\u001f", value.DropOrder ?? []), StringComparer.Ordinal)
.ThenBy(static value => string.Join("\u001f", value.Outcomes ?? []), StringComparer.Ordinal)
.ThenBy(static value => string.Join("\u001f", value.BorrowFacts ?? []), StringComparer.Ordinal)];
static string[] NormalizeFacts(IEnumerable<string>? facts, string label)
{
if (facts is null) return [];
var result = new List<string>();
using IEnumerator<string> enumerator = facts.GetEnumerator();
while (enumerator.MoveNext())
{
if (result.Count >= MaximumOwnershipFactsPerFunction)
throw new ArgumentException($"Rust# ownership {label} exceed their bound.", nameof(values));
string fact = enumerator.Current ?? string.Empty;
if (string.IsNullOrWhiteSpace(fact) || fact.Length > 4096)
throw new ArgumentException($"Rust# ownership {label} are invalid.", nameof(values));
result.Add(fact);
}
// These sequences are evidence, not sets. Preserve declaration
// order and repeated terms (for example two equal borrow facts
// attached to different MIR positions) so a consumer can replay
// the producer contract exactly.
return result.ToArray();
}
}
private static ImmutableArray<RustSharpMetadataCallContract> NormalizeCallContracts(
IEnumerable<RustSharpMetadataCallContract>? values)
{
if (values is null) return [];
RustSharpMetadataCallContract[] result = Materialize(values, MaximumCallContracts, nameof(values));
if (result.Any(static value => value is null))
throw new ArgumentException("Rust# call contract count is out of bounds.", nameof(values));
var normalized = new List<RustSharpMetadataCallContract>(result.Length);
var identities = new HashSet<string>(StringComparer.Ordinal);
foreach (RustSharpMetadataCallContract value in result)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value.FunctionId);
ArgumentException.ThrowIfNullOrWhiteSpace(value.PanicStrategy);
if (value.FunctionId.Length > 4096 || value.PanicStrategy.Length > 64 ||
(!string.Equals(value.PanicStrategy, "unwind", StringComparison.Ordinal) &&
!string.Equals(value.PanicStrategy, "abort", StringComparison.Ordinal)))
{
throw new ArgumentException("Rust# call contract identity or panic strategy is invalid.", nameof(values));
}
if (!identities.Add(value.FunctionId))
throw new ArgumentException("Rust# call contract function IDs must be unique.", nameof(values));
string[] parameters = NormalizeTerms(value.ParameterContracts, "parameter contracts");
string? returnContract = value.ReturnContract;
if (returnContract is not null)
{
if (string.IsNullOrWhiteSpace(returnContract) || returnContract.Length > 128 ||
returnContract.Contains('\0'))
throw new ArgumentException("Rust# call contract return term is invalid.", nameof(values));
returnContract = returnContract.Trim();
}
if (value.Schema is { } schema &&
(string.IsNullOrWhiteSpace(schema) || schema.Length > 128 || schema.Contains('\0')))
throw new ArgumentException("Rust# call contract schema is invalid.", nameof(values));
normalized.Add(new(value.FunctionId, value.PanicStrategy, parameters, returnContract)
{
Schema = value.Schema,
});
}
return [.. normalized.OrderBy(static value => value.FunctionId, StringComparer.Ordinal)];
static string[] NormalizeTerms(IEnumerable<string>? terms, string label)
{
if (terms is null) return [];
string[] result = Materialize(terms, MaximumCallTermsPerFunction, label);
if (result.Any(static term => string.IsNullOrWhiteSpace(term) || term.Length > 128 || term.Contains('\0')))
throw new ArgumentException($"Rust# call contract {label} are invalid.", nameof(values));
// Parameter contracts are positional: equal terms at different
// argument indices must remain separate and in declaration order.
return [.. result.Select(static term => term.Trim())];
}
}
private static ImmutableArray<RustSharpMetadataValueType> NormalizeValueTypes(
IEnumerable<RustSharpMetadataValueType>? values)
{
if (values is null) return [];
RustSharpMetadataValueType[] result = Materialize(values, MaximumValueTypes, nameof(values));
if (result.Any(static value => value is null))
throw new ArgumentException("Rust# value layout count is out of bounds.", nameof(values));
var names = new HashSet<string>(StringComparer.Ordinal);
var normalized = new List<RustSharpMetadataValueType>(result.Length);
foreach (RustSharpMetadataValueType value in result)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value.Name);
if (value.Name.Length > 1024 || !names.Add(value.Name))
throw new ArgumentException("Rust# value layout identities must be unique and bounded.", nameof(values));
RustSharpMetadataField[] fields = Materialize(
value.Fields ?? [], MaximumFieldsPerValueType, "value fields");
var fieldNames = new HashSet<string>(StringComparer.Ordinal);
foreach (RustSharpMetadataField field in fields)
{
if (field is null || string.IsNullOrWhiteSpace(field.Name) ||
string.IsNullOrWhiteSpace(field.Type) || field.Name.Length > 1024 ||
field.Type.Length > 1024 || !fieldNames.Add(field.Name) ||
field.Type.Contains('\0'))
throw new ArgumentException("Rust# value layout fields are invalid or duplicated.", nameof(values));
}
normalized.Add(new(value.Name, fields));
}
return [.. normalized.OrderBy(static value => value.Name, StringComparer.Ordinal)];
}
private static T[] Materialize<T>(IEnumerable<T> values, int maximum, string parameterName)
{
ArgumentNullException.ThrowIfNull(values);
var result = new List<T>(Math.Min(maximum, 16));
using IEnumerator<T> enumerator = values.GetEnumerator();
while (enumerator.MoveNext())
{
if (result.Count >= maximum)
throw new ArgumentException("Rust# metadata collection exceeds its bound.", parameterName);
result.Add(enumerator.Current);
}
return result.ToArray();
}
private static string Serialize(RustSharpMetadataDocument document) =>
JsonSerializer.Serialize(document, MetadataJsonContext.Default.RustSharpMetadataDocument);
private static string LimitText(string value, int maximum) =>
value.Length <= maximum ? value : throw new ArgumentException("Rust# metadata text exceeds its size limit.");
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
WriteIndented = false, GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(RustSharpMetadataDocument))]
[JsonSerializable(typeof(MetadataPayload))]
private sealed partial class MetadataJsonContext : JsonSerializerContext;
/// <summary>Parses and canonicalizes a persisted metadata document.</summary>
public static RustSharpMetadataDocument Parse(string json)
{
ArgumentNullException.ThrowIfNull(json);
if (json.Length > MaximumJsonCharacters)
throw new ArgumentException("Rust# metadata JSON exceeds its size limit.", nameof(json));
RustSharpMetadataReader.ValidateNoDuplicateProperties(Encoding.UTF8.GetBytes(json));
using JsonDocument document = JsonDocument.Parse(json, new JsonDocumentOptions
{
MaxDepth = 128,
AllowTrailingCommas = false,
CommentHandling = JsonCommentHandling.Disallow,
});
if (document.RootElement.ValueKind != JsonValueKind.Object)
throw new ArgumentException("Rust# metadata root must be an object.", nameof(json));
MetadataPayload? parsed = JsonSerializer.Deserialize(
json, MetadataJsonContext.Default.MetadataPayload);
if (parsed is null)
throw new ArgumentException("Rust# metadata document is empty.", nameof(json));
if (!string.Equals(parsed.Schema, SchemaVersion, StringComparison.Ordinal))
throw new ArgumentException("Unsupported Rust# metadata schema.", nameof(json));
if (parsed.Profile is null || parsed.SourceSha256 is null)
throw new ArgumentException("Rust# metadata identity is incomplete.", nameof(json));
// Reconstruct through the validating constructor. The document has
// derived Schema/Json state and is intentionally not a direct
// deserialization target.
var canonical = new RustSharpMetadataDocument(
parsed.Profile,
parsed.SourceSha256,
parsed.Functions,
parsed.GenericInstances,
parsed.TraitImplementations,
parsed.MirSnapshot,
parsed.Ownership,
parsed.CleanupSnapshot,
parsed.CallContracts,
parsed.ValueTypes);
// Older v1 producers predate the ownership extension and therefore do
// not contain an `ownership` property. Return the canonical document
// while accepting that additive shape for cross-package compatibility.
return canonical;
}
private sealed class MetadataPayload
{
public string? Schema { get; set; }
public string? Profile { get; set; }
public string? SourceSha256 { get; set; }
public RustSharpMetadataFunction[]? Functions { get; set; }
public RustSharpMetadataGenericInstance[]? GenericInstances { get; set; }
public string[]? TraitImplementations { get; set; }
public string? MirSnapshot { get; set; }
public RustSharpMetadataOwnershipFunction[]? Ownership { get; set; }
public string? CleanupSnapshot { get; set; }
public RustSharpMetadataCallContract[]? CallContracts { get; set; }
public RustSharpMetadataValueType[]? ValueTypes { get; set; }
}
}
/// <summary>Reads the embedded AssemblyMetadataAttribute without loading generated code.</summary>
public static class RustSharpMetadataReader
{
public const string AttributeKey = "RustSharp.Metadata.v1";
public static string? FindJson(System.Reflection.Metadata.MetadataReader metadata)
{
ArgumentNullException.ThrowIfNull(metadata);
string? found = null;
foreach (System.Reflection.Metadata.CustomAttributeHandle handle in metadata.GetAssemblyDefinition().GetCustomAttributes())
{
System.Reflection.Metadata.CustomAttribute attribute = metadata.GetCustomAttribute(handle);
string? name = TryGetAttributeTypeName(metadata, attribute.Constructor);
if (!string.Equals(name, "System.Reflection.AssemblyMetadataAttribute", StringComparison.Ordinal)) continue;
string? value = TryDecodeValue(metadata, attribute.Value);
if (value is null || !value.StartsWith(AttributeKey + "\u001f", StringComparison.Ordinal))
continue;
string json = value[(AttributeKey.Length + 1)..];
if (found is not null)
throw new InvalidDataException("The assembly contains duplicate Rust# metadata attributes.");
found = json;
}
return found;
}
/// <summary>Reads and validates the canonical Rust# metadata document.</summary>
public static RustSharpMetadataDocument? ReadDocument(System.Reflection.Metadata.MetadataReader metadata)
{
string? json = FindJson(metadata);
return json is null ? null : RustSharpMetadataDocument.Parse(json);
}
/// <summary>Reads the metadata attribute from a PE without loading its assembly.</summary>
public static RustSharpMetadataDocument ReadAssembly(string assemblyPath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(assemblyPath);
string fullPath = Path.GetFullPath(assemblyPath);
using FileStream stream = new(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read,
64 * 1024, FileOptions.SequentialScan);
using var pe = new PEReader(stream, PEStreamOptions.LeaveOpen);
if (!pe.HasMetadata)
throw new BadImageFormatException("The assembly does not contain CLR metadata.");
return ReadDocument(pe.GetMetadataReader()) ??
throw new InvalidDataException("The assembly has no Rust# metadata attribute.");
}
internal static void ValidateNoDuplicateProperties(ReadOnlySpan<byte> json)
{
var reader = new Utf8JsonReader(json, new JsonReaderOptions
{
AllowTrailingCommas = false,
CommentHandling = JsonCommentHandling.Disallow,
MaxDepth = 128,
});
var objects = new Stack<HashSet<string>>();
int tokenCount = 0;
while (reader.Read())
{
if (++tokenCount > 16_384)
throw new JsonException("Rust# metadata exceeds its token limit.");
if (reader.TokenType == JsonTokenType.StartObject)
objects.Push(new HashSet<string>(StringComparer.Ordinal));
else if (reader.TokenType == JsonTokenType.PropertyName)
{
if (objects.Count == 0 || !objects.Peek().Add(reader.GetString() ?? string.Empty))
throw new JsonException("Rust# metadata contains a duplicate property.");
}
else if (reader.TokenType == JsonTokenType.EndObject)
{
if (objects.Count == 0) throw new JsonException("Rust# metadata object structure is invalid.");
objects.Pop();
}
}
if (objects.Count != 0)
throw new JsonException("Rust# metadata object is incomplete.");
}
private static string? TryGetAttributeTypeName(System.Reflection.Metadata.MetadataReader metadata,
System.Reflection.Metadata.EntityHandle constructor)
{
System.Reflection.Metadata.EntityHandle parent = constructor.Kind switch
{
System.Reflection.Metadata.HandleKind.MemberReference => metadata.GetMemberReference((System.Reflection.Metadata.MemberReferenceHandle)constructor).Parent,
System.Reflection.Metadata.HandleKind.MethodDefinition => ((System.Reflection.Metadata.EntityHandle)constructor),
_ => default,
};
if (parent.Kind != System.Reflection.Metadata.HandleKind.TypeReference) return null;
System.Reflection.Metadata.TypeReference reference = metadata.GetTypeReference((System.Reflection.Metadata.TypeReferenceHandle)parent);
return metadata.GetString(reference.Namespace) + "." + metadata.GetString(reference.Name);
}
private static string? TryDecodeValue(System.Reflection.Metadata.MetadataReader metadata,
System.Reflection.Metadata.BlobHandle value)
{
try
{
System.Reflection.Metadata.BlobReader reader = metadata.GetBlobReader(value);
if (reader.ReadUInt16() != 1) return null;
string? key = reader.ReadSerializedString();
string? json = reader.ReadSerializedString();
return key is null || json is null ? null : key + "\u001f" + json;
}
catch (Exception exception) when (exception is BadImageFormatException or
ArgumentException or InvalidOperationException)
{
// Malformed custom-attribute blobs are untrusted PE input. Treat
// them as an absent Rust# attribute instead of leaking a parser
// exception to a consumer inspecting an otherwise readable PE.
return null;
}
}
}
/// <summary>
/// Imports Rust# metadata from an independently built assembly. This is a
/// read-only contract: it validates profile/schema/linkage and never executes
/// producer code or uses reflection-based discovery.
/// </summary>
public static class RustSharpMetadataConsumer
{
public const string MissingMetadata = "RSC0010";
public const string InvalidMetadata = "RSC0011";
public const string ProfileMismatch = "RSC0012";
public const string ExportMissing = "RSC0013";
public const int MaximumAssemblyBytes = 256 * 1024 * 1024;
public static RustSharpMetadataImportResult ReadAssembly(
string assemblyPath,
string? expectedProfile = null,
IEnumerable<string>? requiredFunctions = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(assemblyPath);
string fullPath = Path.GetFullPath(assemblyPath);
var diagnostics = new List<string>();
RustSharpMetadataDocument? document = null;
string? generic = null;
Guid? mvid = null;
string? assemblyName = null;
try
{
FileInfo info = new(fullPath);
if (!info.Exists) throw new FileNotFoundException("Rust# producer assembly was not found.", fullPath);
if (info.Length <= 0 || info.Length > MaximumAssemblyBytes)
throw new InvalidDataException("Rust# producer assembly exceeds its bounded size.");
using FileStream stream = new(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read,
64 * 1024, FileOptions.SequentialScan);
using var pe = new PEReader(stream, PEStreamOptions.LeaveOpen);
if (!pe.HasMetadata) throw new BadImageFormatException("Producer assembly has no CLR metadata.");
MetadataReader metadata = pe.GetMetadataReader();
assemblyName = metadata.GetString(metadata.GetAssemblyDefinition().Name);
document = RustSharpMetadataReader.ReadDocument(metadata);
if (document is null)
{
diagnostics.Add(MissingMetadata + ": producer assembly has no Rust# metadata attribute.");
}
else
{
if (expectedProfile is not null && !string.Equals(document.Profile, expectedProfile, StringComparison.Ordinal))
diagnostics.Add(ProfileMismatch + ": producer profile does not match the consumer profile.");
ValidateGeneratedFunctions(metadata, document, diagnostics);
ValidateGeneratedValueTypes(metadata, document, diagnostics);
ValidateOwnershipContracts(document, diagnostics);
ValidateCallContracts(document, diagnostics);
ValidateRequiredFunctions(document, requiredFunctions, diagnostics);
}
ModuleDefinition module = metadata.GetModuleDefinition();
mvid = metadata.GetGuid(module.Mvid);
generic = TryReadGenericResource(pe, metadata, diagnostics);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or
BadImageFormatException or InvalidDataException or ArgumentException or JsonException or
EndOfStreamException or OverflowException or InvalidOperationException or NotSupportedException)
{
diagnostics.Add(InvalidMetadata + ": " + Trim(exception.Message));
}
return new(fullPath, document, generic, mvid, diagnostics.AsReadOnly())
{
AssemblyName = assemblyName,
};
}
public static RustSharpMetadataFunction? FindFunction(
RustSharpMetadataDocument document, string functionId)
{
ArgumentNullException.ThrowIfNull(document);
ArgumentException.ThrowIfNullOrWhiteSpace(functionId);
return document.Functions.FirstOrDefault(function =>
string.Equals(function.Name, functionId, StringComparison.Ordinal) ||
string.Equals(function.SourceQualifiedName, functionId, StringComparison.Ordinal) ||
string.Equals(function.SourceQualifiedName, functionId + "#value", StringComparison.Ordinal) ||
string.Equals(function.SourceQualifiedName + "#value", functionId, StringComparison.Ordinal));
}
private static void ValidateCallContracts(
RustSharpMetadataDocument document,
List<string> diagnostics)
{
var seen = new HashSet<string>(StringComparer.Ordinal);
var contracted = new HashSet<string>(StringComparer.Ordinal);
var clock = Stopwatch.StartNew();
var ownershipPanics = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (RustSharpMetadataOwnershipFunction ownership in document.Ownership)
{
CheckBudget();
if (FindFunction(document, ownership.FunctionId) is { } target)
ownershipPanics.TryAdd(target.Name, ownership.PanicStrategy);
}
foreach (RustSharpMetadataCallContract contract in document.CallContracts)
{
CheckBudget();
RustSharpMetadataFunction? function = FindFunction(document, contract.FunctionId);
if (function is null)
{
AddContractDiagnostic(diagnostics,
"call contract references unknown function '" + Trim(contract.FunctionId) + "'.");
continue;
}
contracted.Add(function.Name);
// CLR and source IDs are aliases for one callable MethodDef. Two
// records under different aliases must not supply conflicting facts.
if (!seen.Add(function.Name))
{
AddContractDiagnostic(diagnostics,
"call contract for resolved function '" + Trim(function.Name) + "' is duplicated.");
continue;
}
if (contract.Schema is not null && contract.Schema != RustSharpMetadataCallContract.ScalarSchema)
AddContractDiagnostic(diagnostics, "call contract has an unsupported schema.");
if (!string.Equals(contract.PanicStrategy, "unwind", StringComparison.Ordinal) &&
!string.Equals(contract.PanicStrategy, "abort", StringComparison.Ordinal))
{
AddContractDiagnostic(diagnostics,
"call contract for '" + Trim(contract.FunctionId) + "' has an unsupported panic strategy.");
}
int arrow = function.Signature.IndexOf("->", StringComparison.Ordinal);
if (arrow < 0 || function.Signature.IndexOf("->", arrow + 2, StringComparison.Ordinal) >= 0)
{
AddContractDiagnostic(diagnostics,
"call contract target '" + Trim(contract.FunctionId) + "' has an invalid function signature.");
continue;
}
string[] parameters = string.IsNullOrWhiteSpace(function.Signature[..arrow])
? [] : function.Signature[..arrow].Split(',', StringSplitOptions.None);
string[] terms = (contract.ParameterContracts ?? []).ToArray();
bool scalarSchema = contract.Schema == RustSharpMetadataCallContract.ScalarSchema;
if ((terms.Length != 0 || scalarSchema) && terms.Length != parameters.Length)
{
AddContractDiagnostic(diagnostics,
"call contract for '" + Trim(contract.FunctionId) + "' does not cover every parameter.");
}
for (int index = 0; index < Math.Min(terms.Length, parameters.Length); index++)
{
if (!TermMatchesType(terms[index], parameters[index], isReturn: false, scalarSchema))
AddContractDiagnostic(diagnostics, "call contract parameter " +
index.ToString(CultureInfo.InvariantCulture) + " for '" + Trim(contract.FunctionId) +
"' is unsupported or contradicts its CLR signature.");
}
string returnType = function.Signature[(arrow + 2)..];
if ((contract.ReturnContract is null && scalarSchema) ||
(contract.ReturnContract is { } result &&
!TermMatchesType(result, returnType, isReturn: true, scalarSchema)))
AddContractDiagnostic(diagnostics, "call contract return for '" + Trim(contract.FunctionId) +
"' is missing, unsupported or contradicts its CLR signature.");
if (ownershipPanics.TryGetValue(function.Name, out string? panic) && panic != contract.PanicStrategy)
AddContractDiagnostic(diagnostics, "call contract panic strategy for '" +
Trim(contract.FunctionId) + "' contradicts its ownership evidence.");
}
// CLR signatures do not encode Rust# ownership or panic semantics.
// Require an explicit contract whenever an exported function carries
// a nominal value or managed reference. Accepting these methods with
// an omitted contract would let a consumer guess move/borrow terms
// from CLR value semantics and silently bypass the package boundary.
foreach (RustSharpMetadataFunction function in document.Functions)
{
CheckBudget();
if (RequiresOwnershipContract(function) && !contracted.Contains(function.Name))
{
AddContractDiagnostic(diagnostics,
"exported function '" + Trim(function.Name) +
"' has a value or reference signature but no ownership call contract.");
}
}
void CheckBudget()
{
if (document.CallContracts.Length > RustSharpMetadataDocument.MaximumCallContracts ||
document.Ownership.Length > RustSharpMetadataDocument.MaximumOwnershipFunctions ||
clock.Elapsed > TimeSpan.FromSeconds(5))
throw new InvalidDataException("Imported call contracts exceeded their bounded validation budget.");
}
static bool TermMatchesType(string term, string type, bool isReturn, bool scalarSchema)
{
if (scalarSchema)
return type is "I32" or "Bool" ? term == "copy" :
isReturn && type == "Void" && term == "unit";
return term switch
{
"copy" => type is "I32" or "Bool",
"move" => type.StartsWith("Value(", StringComparison.Ordinal),
"borrow:shared" or "borrow:mut" or "borrow:mutable" =>
type.StartsWith('&'),
"unit" => isReturn && type == "Void",
_ => false,
};
}
static bool RequiresOwnershipContract(RustSharpMetadataFunction function)
{
// Closed generic helper MethodDefs are generated implementation
// details. Their source declaration's contract is represented by
// the specialization metadata and is reconciled separately.
if (function.Name.StartsWith("generic_", StringComparison.Ordinal)) return false;
string signature = function.Signature;
// Signatures are canonicalized by the metadata writer. A bounded
// token scan is sufficient here and avoids accepting arbitrary
// nested syntax as a contract-bearing type.
return signature.Contains("Value(", StringComparison.Ordinal) ||
signature.Contains('&');
}
}
private static void ValidateOwnershipContracts(
RustSharpMetadataDocument document,
List<string> diagnostics)
{
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (RustSharpMetadataOwnershipFunction ownership in document.Ownership)
{
RustSharpMetadataFunction? function = FindFunction(document, ownership.FunctionId);
if (function is not null && !seen.Add(function.Name))
{
AddContractDiagnostic(diagnostics,
"ownership contract function ID '" + Trim(ownership.FunctionId) + "' is duplicated.");
continue;
}
if (function is null)
{
AddContractDiagnostic(diagnostics,
"ownership contract references unknown function '" + Trim(ownership.FunctionId) + "'.");
}
if (!string.Equals(ownership.PanicStrategy, "unwind", StringComparison.Ordinal) &&
!string.Equals(ownership.PanicStrategy, "abort", StringComparison.Ordinal))
{
AddContractDiagnostic(diagnostics,
"ownership contract for '" + Trim(ownership.FunctionId) + "' has an unsupported panic strategy.");
}
}
}
/// <summary>
/// Correlates the language-level export list with the generated Program
/// type in the PE. The JSON attribute is untrusted input: accepting its
/// names or signatures without checking the MethodDef table would let a
/// stale or forged document describe methods that are not actually
/// callable from the producer assembly.
/// </summary>
private static void ValidateGeneratedFunctions(
MetadataReader metadata,
RustSharpMetadataDocument document,
List<string> diagnostics)
{
const string generatedNamespace = "RustSharp.Generated";
const string generatedTypeName = "Program";
int typeRows = metadata.GetTableRowCount(TableIndex.TypeDef);
int typeLimit = Math.Min(typeRows, RustSharpMetadataDocument.MaximumFunctions + 1);
TypeDefinitionHandle programHandle = default;
int programCount = 0;
for (int row = 1; row <= typeLimit; row++)
{
TypeDefinitionHandle handle = MetadataTokens.TypeDefinitionHandle(row);
TypeDefinition definition = metadata.GetTypeDefinition(handle);
if (string.Equals(metadata.GetString(definition.Namespace), generatedNamespace, StringComparison.Ordinal) &&
string.Equals(metadata.GetString(definition.Name), generatedTypeName, StringComparison.Ordinal))
{
programHandle = handle;
programCount++;
}
}
if (typeRows > typeLimit)
{
AddContractDiagnostic(diagnostics,
"generated type table exceeds its bounded correlation limit.");
}
if (programCount == 0)
{
AddContractDiagnostic(diagnostics,
"generated RustSharp.Generated.Program type is missing.");
return;
}
if (programCount != 1)
{
AddContractDiagnostic(diagnostics,
"generated RustSharp.Generated.Program type is duplicated.");
return;
}
TypeDefinition program = metadata.GetTypeDefinition(programHandle);
var actual = new Dictionary<string, GeneratedMethodShape>(StringComparer.Ordinal);
int methodCount = 0;
foreach (MethodDefinitionHandle handle in program.GetMethods())
{
if (++methodCount > RustSharpMetadataDocument.MaximumFunctions)
{
AddContractDiagnostic(diagnostics,
"generated method table exceeds its bounded correlation limit.");
break;
}