From ca0b461bbe26463aa86c315e959b8b3992ad2a72 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Sat, 14 Nov 2026 21:35:34 +0100 Subject: [PATCH] Make reading, parsing and comparing an API fast on large assemblies Benchmarks (benchmarks/Nullean.PublicApi.Benchmarks) measured reading, writing, parsing and comparing System.Collections.Immutable and CoreLib. On CoreLib, comparing an API with its own .api file took 39 seconds and 4.4 GB: for every member and parameter it wrote both types out as C#, and writing a type looked at every member of the type it was in, so a type with 1,772 members took 5 seconds alone. It now compares the models and writes C# only for a change, builds a member's path only for a change, pairs members by a structural identity instead of a string key, and checks attributes and constraints on the models first: 20 ms and 23 MB. Reading CoreLib took 407 ms and 832 MB: decoding an attribute's enum argument scanned every type in the assembly, and every attribute check built its type's name again. Both are looked up once now, nullable attributes are read from their blob, primitive types and empty lists are shared, and names are compared in place: 108 ms and 109 MB. Parsing CoreLib's 35,751 lines took 160 ms and 120 MB: a line is checked for a type declaration once, the word under the cursor is kept, a member without type parameters keeps its scope, and locations are indexed only when asked for: 122 ms and 72 MB. Most of what is left is collecting the model, which survives; the tool turns off concurrent GC, which halves that. ApiDeclarationWriter writes one type's declarations and references, so a caller writing many of them builds the type's names once. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + Directory.Packages.props | 5 + api/Nullean.PublicApi.net10.0.api | 6 + api/Nullean.PublicApi.netstandard2.0.api | 6 + assembly-differ.slnx | 1 + .../Nullean.PublicApi.Benchmarks.csproj | 18 ++ .../Nullean.PublicApi.Benchmarks/Program.cs | 46 +++ src/Nullean.PublicApi.Diff/ApiComparison.cs | 276 ++++++++++++++---- src/Nullean.PublicApi/ApiParser.cs | 101 +++++-- src/Nullean.PublicApi/ApiReader.cs | 71 +++-- src/Nullean.PublicApi/ApiWriter.cs | 64 ++-- src/Nullean.PublicApi/Signatures.cs | 52 +++- src/assembly-differ/assembly-differ.csproj | 2 + 13 files changed, 529 insertions(+), 120 deletions(-) create mode 100644 benchmarks/Nullean.PublicApi.Benchmarks/Nullean.PublicApi.Benchmarks.csproj create mode 100644 benchmarks/Nullean.PublicApi.Benchmarks/Program.cs diff --git a/AGENTS.md b/AGENTS.md index 289f438..983dd63 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,7 @@ distroless container (`ghcr.io/nullean/assembly-differ`) and a GitHub Action (`a | `src/Nullean.PublicApi.Diff` | the `Nullean.PublicApi.Diff` package (netstandard2.0, net10.0): `ApiComparison` compares two rich models and classifies each change by who it breaks, binary or source, and extension points; `ApiDiff`, `VersionChange` and `UsageFilter` are the JustAssembly-compatible comparison behind the commands' reports, on the internal model in `JustAssembly/` | | `tests/Nullean.PublicApi.Tests` | TUnit tests of the reader, writer, parser and comparison (`Properties`: CsCheck properties over libraries `GeneratedLibrary` writes from a choice sequence, checked against Roslyn, round-tripped, split and compared both ways) (`ComparisonTests`: one old and new library per rule, snapshotted): `.api` snapshots of C# samples; `RoslynOracleTests`, which checks every visible signature of framework assemblies against Roslyn's reading of them; `ParserTests`, which parse each `.api` file back and require the same text and the same model, field by field (`ModelDump`) | | `tests/assembly-differ.Tests` | TUnit tests that run the built tool as a process on assemblies Roslyn compiles from C# source | +| `benchmarks/Nullean.PublicApi.Benchmarks` | BenchmarkDotNet: reading, writing, parsing and comparing System.Collections.Immutable and CoreLib, with allocations. `dotnet run -c Release --project benchmarks/Nullean.PublicApi.Benchmarks -- --filter '*' --inProcess` (in process: BenchmarkDotNet 0.15 does not know net11.0 yet) | | `build/scripts` | the F# build ([Runna.Fs](https://www.nuget.org/packages/Runna.Fs), net11.0) the `mise` tasks and CI call | | `build/keys` | the strong-name key the tool's and the libraries' assemblies are signed with | | `action.yml` | the GitHub Action: runs the `edge` container image | diff --git a/Directory.Packages.props b/Directory.Packages.props index f1b2022..5d93826 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -37,6 +37,11 @@ + + + + + diff --git a/api/Nullean.PublicApi.net10.0.api b/api/Nullean.PublicApi.net10.0.api index cf44add..cc5eadc 100644 --- a/api/Nullean.PublicApi.net10.0.api +++ b/api/Nullean.PublicApi.net10.0.api @@ -79,6 +79,12 @@ namespace Nullean.PublicApi New = 32 AllowsRefStruct = 64 + sealed class ApiDeclarationWriter + ApiDeclarationWriter(ApiType type) + string Declaration() + string Declaration(ApiMember member) + string Reference(ApiTypeReference type) + sealed class ApiDocument ApiAssembly Assembly { get; } int? LineOf(object node) diff --git a/api/Nullean.PublicApi.netstandard2.0.api b/api/Nullean.PublicApi.netstandard2.0.api index 2c69bc2..40fdca0 100644 --- a/api/Nullean.PublicApi.netstandard2.0.api +++ b/api/Nullean.PublicApi.netstandard2.0.api @@ -79,6 +79,12 @@ namespace Nullean.PublicApi New = 32 AllowsRefStruct = 64 + sealed class ApiDeclarationWriter + ApiDeclarationWriter(ApiType type) + string Declaration() + string Declaration(ApiMember member) + string Reference(ApiTypeReference type) + sealed class ApiDocument ApiAssembly Assembly { get; } int? LineOf(object node) diff --git a/assembly-differ.slnx b/assembly-differ.slnx index 153cc63..01a9f26 100644 --- a/assembly-differ.slnx +++ b/assembly-differ.slnx @@ -23,5 +23,6 @@ + diff --git a/benchmarks/Nullean.PublicApi.Benchmarks/Nullean.PublicApi.Benchmarks.csproj b/benchmarks/Nullean.PublicApi.Benchmarks/Nullean.PublicApi.Benchmarks.csproj new file mode 100644 index 0000000..f255ee0 --- /dev/null +++ b/benchmarks/Nullean.PublicApi.Benchmarks/Nullean.PublicApi.Benchmarks.csproj @@ -0,0 +1,18 @@ + + + net11.0 + Exe + false + enable + enable + + + + + + + + + + + diff --git a/benchmarks/Nullean.PublicApi.Benchmarks/Program.cs b/benchmarks/Nullean.PublicApi.Benchmarks/Program.cs new file mode 100644 index 0000000..d2fc9a2 --- /dev/null +++ b/benchmarks/Nullean.PublicApi.Benchmarks/Program.cs @@ -0,0 +1,46 @@ +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Running; +using Nullean.PublicApi; +using Nullean.PublicApi.Diff; + +BenchmarkSwitcher.FromAssembly(typeof(PublicApiBenchmarks).Assembly).Run(args); + +/// +/// Reading an assembly's API from metadata, writing it as a .api file, parsing the file, and comparing two APIs, for +/// a framework assembly of each size. Run with: dotnet run -c Release --project benchmarks/Nullean.PublicApi.Benchmarks +/// +[MemoryDiagnoser] +public class PublicApiBenchmarks +{ + private byte[] _image = []; + private ApiAssembly _api = null!; + private string _text = ""; + private ApiAssembly _parsed = null!; + + [Params("System.Collections.Immutable", "System.Private.CoreLib")] + public string Assembly { get; set; } = ""; + + [GlobalSetup] + public void Setup() + { + var path = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator).First( + p => Path.GetFileNameWithoutExtension(p) == Assembly + ); + _image = File.ReadAllBytes(path); + _api = ApiReader.Read(new MemoryStream(_image)); + _text = ApiWriter.Write(_api); + _parsed = ApiParser.Parse(_text).Assembly; + } + + [Benchmark] + public ApiAssembly Read() => ApiReader.Read(new MemoryStream(_image)); + + [Benchmark] + public string Write() => ApiWriter.Write(_api); + + [Benchmark] + public ApiDocument Parse() => ApiParser.Parse(_text); + + [Benchmark] + public ApiComparisonResult Compare() => ApiComparison.Compare(_api, _parsed); +} diff --git a/src/Nullean.PublicApi.Diff/ApiComparison.cs b/src/Nullean.PublicApi.Diff/ApiComparison.cs index 3b389c9..db0fb17 100644 --- a/src/Nullean.PublicApi.Diff/ApiComparison.cs +++ b/src/Nullean.PublicApi.Diff/ApiComparison.cs @@ -30,23 +30,84 @@ public static ApiComparisonResult Compare(ApiAssembly oldApi, ApiAssembly newApi } /// Pairs two lists by key, in the new list's order with the removed ones after. - private static void Pair(IReadOnlyList oldItems, IReadOnlyList newItems, Func key, Action visit) where T : class + private static readonly System.Runtime.CompilerServices.ConditionalWeakTable Writers = new(); + + /// The writer for a type, built once: it looks at the whole type to decide which names to write in full. + private static ApiDeclarationWriter Writer(ApiType type) => Writers.GetValue(type, t => new ApiDeclarationWriter(t)); + + private static void Pair(IReadOnlyList oldItems, IReadOnlyList newItems, Func key, Action visit) where T : class => + Pair(oldItems, newItems, new KeyComparer(key), visit); + + /// Pairs two lists by identity, in the new list's order with the removed ones after. + private static void Pair(IReadOnlyList oldItems, IReadOnlyList newItems, IEqualityComparer identity, Action visit) where T : class { - var old = new Dictionary(StringComparer.Ordinal); + var old = new Dictionary(oldItems.Count, identity); foreach (var item in oldItems) - old[key(item)] = item; - var seen = new HashSet(StringComparer.Ordinal); + old[item] = item; + var paired = new HashSet(identity); foreach (var item in newItems) { - var k = key(item); - seen.Add(k); - visit(old.TryGetValue(k, out var match) ? match : null, item); + paired.Add(item); + visit(old.TryGetValue(item, out var match) ? match : null, item); } foreach (var item in oldItems) - if (!seen.Contains(key(item))) + if (!paired.Contains(item)) visit(item, null); } + private sealed class KeyComparer(Func key) : IEqualityComparer + { + public bool Equals(T? x, T? y) => x is not null && y is not null && key(x) == key(y); + + public int GetHashCode(T obj) => StringComparer.Ordinal.GetHashCode(key(obj)); + } + + /// + /// A member's identity, compared on the models: its kind, name, number of type parameters and parameter types as the + /// runtime sees them, the same as 's string key without writing one per member. + /// + private sealed class MemberIdentity : IEqualityComparer + { + public static readonly MemberIdentity Instance = new(); + + public bool Equals(ApiMember? x, ApiMember? y) + { + if (x is null || y is null || x.GetType() != y.GetType() || x.Name != y.Name) + return false; + switch (x, y) + { + case (ApiProperty a, ApiProperty b): + return SameParameters(a.Parameters, b.Parameters); + case (ApiMethod a, ApiMethod b): + return a.TypeParameters.Count == b.TypeParameters.Count && SameParameters(a.Parameters, b.Parameters) && + (a.Kind != ApiMethodKind.Conversion || Context.SameRuntime(a.ReturnType, b.ReturnType)); + default: + return true; + } + } + + private static bool SameParameters(IReadOnlyList a, IReadOnlyList b) + { + if (a.Count != b.Count) + return false; + for (var i = 0; i < a.Count; i++) + if ((a[i].RefKind == ApiRefKind.None) != (b[i].RefKind == ApiRefKind.None) || !Context.SameRuntime(a[i].Type, b[i].Type)) + return false; + return true; + } + + public int GetHashCode(ApiMember obj) + { + var count = obj switch + { + ApiMethod m => m.Parameters.Count * 31 + m.TypeParameters.Count, + ApiProperty p => p.Parameters.Count, + _ => 0, + }; + return (StringComparer.Ordinal.GetHashCode(obj.Name) * 397) ^ (count * 17) ^ obj.GetType().GetHashCode(); + } + } + private sealed class Context(ApiComparisonOptions options, ApiAssembly newApi) { public List Changes { get; } = []; @@ -80,7 +141,7 @@ public void Type(ApiType? oldType, ApiType? newType, List path) var here = path.Append(TypeSegment(type)).ToList(); if (oldType is null) { - Add(here, ApiChangeKind.Added, "", null, ApiWriter.Declaration(newType!), ApiAudience.None, ApiCompatibility.None, null, newType, newType); + Add(here, ApiChangeKind.Added, "", null, Writer(newType!).Declaration(), ApiAudience.None, ApiCompatibility.None, null, newType, newType); return; } if (newType is null) @@ -89,7 +150,7 @@ public void Type(ApiType? oldType, ApiType? newType, List path) here, ApiChangeKind.Removed, "", - ApiWriter.Declaration(oldType), + Writer(oldType).Declaration(), null, ApiAudience.Callers, Both, @@ -149,10 +210,8 @@ void Changed(string part, string? old, string? @new, ApiAudience breaks, ApiComp if (oldType.Kind == ApiTypeKind.Delegate && newType.Kind == ApiTypeKind.Delegate) { - var oldSignature = ApiWriter.Declaration(oldType); - var newSignature = ApiWriter.Declaration(newType); if (Key(oldType.Members.OfType().First(), oldType) != Key(newType.Members.OfType().First(), newType)) - Changed("signature", oldSignature, newSignature, ApiAudience.Callers, Both); + Changed("signature", Writer(oldType).Declaration(), Writer(newType).Declaration(), ApiAudience.Callers, Both); else Member( oldType.Members.OfType().First(), @@ -164,12 +223,7 @@ void Changed(string part, string? old, string? @new, ApiAudience breaks, ApiComp ); } else - Pair( - oldType.Members, - newType.Members, - m => Key(m, oldType.Members.Contains(m) ? oldType : newType), - (o, n) => Member(o, n, oldType, newType, here) - ); + Pair(oldType.Members, newType.Members, MemberIdentity.Instance, (o, n) => Member(o, n, oldType, newType, here)); Pair(oldType.NestedTypes, newType.NestedTypes, t => t.Name, (o, n) => Type(o, n, here)); } @@ -181,8 +235,8 @@ private void Bases(ApiType oldType, ApiType newType, Action i, StringComparer.Ordinal); var newInterfaces = newType.Interfaces.ToDictionary(Erase, i => i, StringComparer.Ordinal); foreach (var removed in oldInterfaces.Where(i => !newInterfaces.ContainsKey(i.Key))) - changed("interfaces", ApiWriter.Reference(removed.Value, oldType), null, ApiAudience.Callers, Both, null); + changed("interfaces", Writer(oldType).Reference(removed.Value), null, ApiAudience.Callers, Both, null); foreach (var added in newInterfaces.Where(i => !oldInterfaces.ContainsKey(i.Key))) { // an interface that extends another now asks its implementers for that one's members too var breaks = newType.Kind == ApiTypeKind.Interface && AsksSomething(added.Value) ? ApiAudience.Implementers : ApiAudience.None; - changed("interfaces", null, ApiWriter.Reference(added.Value, newType), breaks, breaks == ApiAudience.None ? ApiCompatibility.None : Both, null); + changed("interfaces", null, Writer(newType).Reference(added.Value), breaks, breaks == ApiAudience.None ? ApiCompatibility.None : Both, null); } } @@ -258,6 +312,8 @@ private static void TypeParameters( ApiCompatibility.Source, null ); + if (SameConstraints(o, n)) + continue; var oldConstraints = Constraints(o, oldType); var newConstraints = Constraints(n, newType); foreach (var added in newConstraints.Except(oldConstraints)) @@ -267,6 +323,17 @@ private static void TypeParameters( } } + /// Whether two type parameters have the same constraints, checked on the models before anything is written out. + private static bool SameConstraints(ApiTypeParameter a, ApiTypeParameter b) + { + if (a.Constraints != b.Constraints || a.ConstraintTypes.Count != b.ConstraintTypes.Count) + return false; + for (var i = 0; i < a.ConstraintTypes.Count; i++) + if (!Same(a.ConstraintTypes[i], b.ConstraintTypes[i], Sameness.Exact)) + return false; + return true; + } + private static string Variance(ApiVariance variance) => variance switch { ApiVariance.Out => "out", @@ -294,7 +361,7 @@ private static List Constraints(ApiTypeParameter parameter, ApiType cont ApiConstraints.New => "new()", _ => flag.ToString().ToLowerInvariant(), }); - constraints.AddRange(parameter.ConstraintTypes.Select(t => ApiWriter.Reference(t, context))); + constraints.AddRange(parameter.ConstraintTypes.Select(t => Writer(context).Reference(t))); // allows ref struct loosens a constraint; taking it away is the break if ((parameter.Constraints & ApiConstraints.AllowsRefStruct) == 0) constraints.Add("not ref struct"); @@ -307,33 +374,24 @@ private void Member(ApiMember? oldMember, ApiMember? newMember, ApiType oldType, { var member = newMember ?? oldMember!; var declaring = newMember is null ? oldType : newType; - var here = delegateInvoke ? path : path.Append(MemberSegment(member, declaring)).ToList(); + // the path is only written out for a change: most members have none + List? here = null; + + List Here() => here ??= delegateInvoke ? path : path.Append(MemberSegment(member, declaring)).ToList(); if (oldMember is null) { var (breaks, compatibility, note) = Obligation(newMember!, newType); - Add( - here, - ApiChangeKind.Added, - "", - null, - ApiWriter.Declaration(newMember!, newType), - breaks, - compatibility, - newType, - newMember, - newMember, - note - ); + Add(Here(), ApiChangeKind.Added, "", null, Writer(newType).Declaration(newMember!), breaks, compatibility, newType, newMember, newMember, note); return; } if (newMember is null) { - var removed = ApiWriter.Declaration(oldMember, oldType); + var removed = Writer(oldType).Declaration(oldMember); // an override, or a member that moved to a base class here, is still found through the base if (MovedToBase(oldMember, oldType, newType) is { } baseName) Add( - here, + Here(), ApiChangeKind.Removed, "", removed, @@ -354,7 +412,7 @@ private void Member(ApiMember? oldMember, ApiMember? newMember, ApiType oldType, ? "an overload with more optional parameters replaces it; callers compile, but compiled callers fail" : null; Add( - here, + Here(), ApiChangeKind.Removed, "", removed, @@ -371,7 +429,7 @@ private void Member(ApiMember? oldMember, ApiMember? newMember, ApiType oldType, } void Changed(string part, string? old, string? @new, ApiAudience breaks, ApiCompatibility compatibility, string? note = null) => - Add(here, ApiChangeKind.Changed, part, old, @new, breaks, compatibility, oldType, oldMember, newMember, note); + Add(Here(), ApiChangeKind.Changed, part, old, @new, breaks, compatibility, oldType, oldMember, newMember, note); Accessibility( oldMember.Accessibility, @@ -434,6 +492,8 @@ void Changed(string part, string? old, string? @new, ApiAudience breaks, ApiComp ); for (var i = 0; i < Math.Min(o.TypeParameters.Count, n.TypeParameters.Count); i++) { + if (SameConstraints(o.TypeParameters[i], n.TypeParameters[i])) + continue; var oldConstraints = Constraints(o.TypeParameters[i], oldType); var newConstraints = Constraints(n.TypeParameters[i], newType); foreach (var added in newConstraints.Except(oldConstraints)) @@ -720,23 +780,107 @@ private static void TypeOf( Action changed ) { - var oldText = ApiWriter.Reference(old, oldType); - var newText = ApiWriter.Reference(@new, newType); - if (Erase(old) != Erase(@new)) + // nearly every type is unchanged: compare the models, and write the C# only for a change + if (Same(old, @new, Sameness.Exact)) + return; + var oldText = Writer(oldType).Reference(old); + var newText = Writer(newType).Reference(@new); + if (!Same(old, @new, Sameness.Runtime)) changed(part, oldText, newText, ApiAudience.Callers, Both, null); - else if (TupleNames(old) != TupleNames(@new)) + else if (!Same(old, @new, Sameness.TupleNames)) changed(part, oldText, newText, ApiAudience.Callers, ApiCompatibility.Source, "callers that use the element names"); else if (oldText != newText) changed(part, oldText, newText, ApiAudience.None, ApiCompatibility.None, "nullability"); } - private static string TupleNames(ApiTypeReference type) => type switch + internal static bool SameRuntime(ApiTypeReference a, ApiTypeReference b) => Same(a, b, Sameness.Runtime); + + private enum Sameness { - ApiTupleType tuple => "(" + string.Join(",", tuple.Elements.Select(e => e.Name + ":" + TupleNames(e.Type))) + ")", - ApiNamedType named => - string.Join(",", named.TypeArguments.Select(TupleNames)) + (named.DeclaringType is null ? "" : "/" + TupleNames(named.DeclaringType)), - ApiArrayType array => TupleNames(array.ElementType), - _ => "", + /// The same type to the runtime: nullability, tuple names, dynamic and native integers aside. + Runtime, + + /// The same to the runtime, with the same tuple element names. + TupleNames, + + /// The same in every part, nullability included. + Exact, + } + + /// Whether two types are the same, as far as looks, without writing either out. + private static bool Same(ApiTypeReference a, ApiTypeReference b, Sameness sameness) + { + while (a is ApiModifiedType modifiedA && sameness != Sameness.Exact) + a = modifiedA.Type; + while (b is ApiModifiedType modifiedB && sameness != Sameness.Exact) + b = modifiedB.Type; + if (sameness == Sameness.Exact && a.IsNullable != b.IsNullable) + return false; + if (sameness != Sameness.Exact) + { + // dynamic is object, and nint IntPtr, to the runtime + a = Runtime(a); + b = Runtime(b); + } + switch (a, b) + { + case (ApiNamedType x, ApiNamedType y): + if (x.Name != y.Name || x.Namespace != y.Namespace || x.TypeArguments.Count != y.TypeArguments.Count) + return false; + if ( + (x.DeclaringType is null) != (y.DeclaringType is null) || + (x.DeclaringType is not null && !Same(x.DeclaringType, y.DeclaringType!, sameness)) + ) + return false; + for (var i = 0; i < x.TypeArguments.Count; i++) + if (!Same(x.TypeArguments[i], y.TypeArguments[i], sameness)) + return false; + return true; + case (ApiTupleType x, ApiTupleType y): + if (x.Elements.Count != y.Elements.Count) + return false; + for (var i = 0; i < x.Elements.Count; i++) + if ( + (sameness != Sameness.Runtime && x.Elements[i].Name != y.Elements[i].Name) || + !Same(x.Elements[i].Type, y.Elements[i].Type, sameness) + ) + return false; + return true; + case (ApiArrayType x, ApiArrayType y): + return x.Rank == y.Rank && Same(x.ElementType, y.ElementType, sameness); + case (ApiPointerType x, ApiPointerType y): + return Same(x.ElementType, y.ElementType, sameness); + case (ApiFunctionPointerType x, ApiFunctionPointerType y): + if (x.IsUnmanaged != y.IsUnmanaged || x.ParameterTypes.Count != y.ParameterTypes.Count || !Same(x.ReturnType, y.ReturnType, sameness)) + return false; + for (var i = 0; i < x.ParameterTypes.Count; i++) + if (!Same(x.ParameterTypes[i], y.ParameterTypes[i], sameness)) + return false; + return true; + case (ApiTypeParameterReference x, ApiTypeParameterReference y): + return x.Name == y.Name && x.IsMethodParameter == y.IsMethodParameter; + case (ApiDynamicType, ApiDynamicType): + return true; + case (ApiNativeIntegerType x, ApiNativeIntegerType y): + return x.IsUnsigned == y.IsUnsigned; + case (ApiModifiedType x, ApiModifiedType y): + return x.IsRequired == y.IsRequired && Same(x.Modifier, y.Modifier, sameness) && Same(x.Type, y.Type, sameness); + default: + return false; + } + } + + private static readonly ApiNamedType RuntimeObject = new("System", "Object", null, [], false); + private static readonly ApiNamedType RuntimeIntPtr = new("System", "IntPtr", null, [], true); + private static readonly ApiNamedType RuntimeUIntPtr = new("System", "UIntPtr", null, [], true); + + private static ApiTypeReference Runtime(ApiTypeReference type) => type switch + { + ApiDynamicType => RuntimeObject, + ApiNativeIntegerType { IsUnsigned: true } => RuntimeUIntPtr, + ApiNativeIntegerType => RuntimeIntPtr, + // a tuple is its ValueTuple; Same compares tuples element by element, which is the same thing + _ => type, }; private static void Accessibility(ApiAccessibility old, ApiAccessibility @new, Action changed) @@ -798,6 +942,9 @@ private static void Attributes( Action changed ) { + // the reader and the parser both order attributes, so unchanged ones are equal in order + if (old.Count == @new.Count && SameAttributes(old, @new)) + return; var oldByName = old.GroupBy(a => a.Type.FullName).ToDictionary(g => g.Key, g => g.Select(Text).OrderBy(t => t, StringComparer.Ordinal).ToList()); var newByName = @new.GroupBy(a => a.Type.FullName).ToDictionary(g => g.Key, g => g.Select(Text).OrderBy(t => t, StringComparer.Ordinal).ToList()); foreach (var name in oldByName.Keys.Union(newByName.Keys).OrderBy(n => n, StringComparer.Ordinal)) @@ -811,6 +958,20 @@ private static void Attributes( } } + private static bool SameAttributes(IReadOnlyList old, IReadOnlyList @new) + { + for (var i = 0; i < old.Count; i++) + { + var (a, b) = (old[i], @new[i]); + if (!Same(a.Type, b.Type, Sameness.Exact) || a.Arguments.Count != b.Arguments.Count) + return false; + for (var j = 0; j < a.Arguments.Count; j++) + if (a.Arguments[j] != b.Arguments[j]) + return false; + } + return true; + } + private static bool IsError(IReadOnlyList attributes) => attributes.Any(a => a.Type.FullName == Obsolete && a.Arguments.Count >= 2 && a.Arguments[1] == "true"); @@ -953,15 +1114,14 @@ private static string MemberSegment(ApiMember member, ApiType declaring) { // a path names a member by its identity, which nullability is not part of: either version gives the same one string Types(IEnumerable parameters) => - string.Join(", ", parameters.Select(p => ApiWriter.Reference(WithoutAnnotations(p.Type), declaring))); + string.Join(", ", parameters.Select(p => Writer(declaring).Reference(WithoutAnnotations(p.Type)))); return member switch { ApiMethod { Kind: ApiMethodKind.Constructor } m => NonGeneric(declaring.Name) + "(" + Types(m.Parameters) + ")", ApiMethod { Kind: ApiMethodKind.Conversion } m => - (m.Name == "op_Implicit" ? "implicit" : "explicit") + " operator " + ApiWriter.Reference(m.ReturnType, declaring) + "(" + Types( - m.Parameters - ) + ")", + (m.Name == "op_Implicit" ? "implicit" : "explicit") + " operator " + Writer(declaring).Reference(m.ReturnType) + "(" + Types(m.Parameters) + + ")", ApiMethod m => m.Name + (m.TypeParameters.Count == 0 ? "" : "<" + string.Join(", ", m.TypeParameters.Select(p => p.Name)) + ">") + "(" + Types( m.Parameters diff --git a/src/Nullean.PublicApi/ApiParser.cs b/src/Nullean.PublicApi/ApiParser.cs index c7c821b..59cc6a2 100644 --- a/src/Nullean.PublicApi/ApiParser.cs +++ b/src/Nullean.PublicApi/ApiParser.cs @@ -31,19 +31,42 @@ public sealed record ApiLocation(string? File, int Line); /// Parsed .api files: the API they describe, and where each type and member is declared. public sealed class ApiDocument { - private readonly ConditionalWeakTable _locations; + // declarations in parse order; looked up by reference only when a location is asked for, which reports do for the + // few that changed: hashing every declaration up front cost more than the rest of parsing + private readonly List<(object Node, ApiLocation Location)> _declarations; + private Dictionary? _locations; - internal ApiDocument(ApiAssembly assembly, ConditionalWeakTable locations) + internal ApiDocument(ApiAssembly assembly, List<(object Node, ApiLocation Location)> declarations) { Assembly = assembly; - _locations = locations; + _declarations = declarations; } /// The API the files describe. Its version, public key token and target framework are not in them and are left empty. public ApiAssembly Assembly { get; } /// Where a type or member was declared; null for anything else. - public ApiLocation? LocationOf(object node) => _locations.TryGetValue(node, out var location) ? location : null; + public ApiLocation? LocationOf(object node) + { + if (_locations is null) + { + var locations = new Dictionary(_declarations.Count, ByReference.Instance); + foreach (var (declaration, location) in _declarations) + locations[declaration] = location; + _locations = locations; + } + return _locations.TryGetValue(node, out var found) ? found : null; + } + + /// Types and members are records, equal by value: two declarations alike are still at two places. + internal sealed class ByReference : IEqualityComparer + { + public static readonly ByReference Instance = new(); + + public new bool Equals(object? x, object? y) => ReferenceEquals(x, y); + + public int GetHashCode(object obj) => RuntimeHelpers.GetHashCode(obj); + } /// The line a type or member was declared on, counted from one; null for anything else. public int? LineOf(object node) => LocationOf(node)?.Line; @@ -63,7 +86,7 @@ public static class ApiParser /// A file is not a .api file, or the files are of different assemblies. public static ApiDocument Parse(IEnumerable<(string? File, string Text)> files) { - var locations = new ConditionalWeakTable(); + var locations = new List<(object Node, ApiLocation Location)>(); string? name = null; var types = new List(); foreach (var (file, text) in files) @@ -99,7 +122,7 @@ private sealed class Parser { private readonly List _lines = []; private readonly string? _file; - private readonly ConditionalWeakTable _locations; + private readonly List<(object Node, ApiLocation Location)> _locations; // (namespace, metadata name) of every top-level type the file declares or its header names private readonly Dictionary<(string, string), Declared> _own = []; @@ -108,7 +131,10 @@ private sealed class Parser private readonly HashSet<(string Namespace, string Path)> _externalInterfaces = []; private readonly Dictionary> _byShortName = new(StringComparer.Ordinal); - public Parser(string text, string? file, ConditionalWeakTable locations) + // the lines that declare a type, which the first pass finds + private readonly HashSet _typeLines = []; + + public Parser(string text, string? file, List<(object Node, ApiLocation Location)> locations) { _file = file; _locations = locations; @@ -208,8 +234,9 @@ private void Declare(int start) { string? ns = null; var stack = new List(); - foreach (var line in _lines.Skip(start)) + for (var index = start; index < _lines.Count; index++) { + var line = _lines[index]; if (line.Depth == 0) { ns = line.Text.StartsWith("namespace ", StringComparison.Ordinal) ? Namespace(line.Text.Substring("namespace ".Length).Trim()) : ns; @@ -218,6 +245,7 @@ private void Declare(int start) } if (ns is null || !IsTypeLine(line.Text, out var kind, out var typeName, out var typeParameters)) continue; + _typeLines.Add(index); while (stack.Count >= line.Depth) stack.RemoveAt(stack.Count - 1); var parent = stack.Count > 0 ? stack[stack.Count - 1] : null; @@ -242,7 +270,7 @@ private static bool IsTypeLine(string text, out ApiTypeKind kind, out string nam kind = ApiTypeKind.Class; name = string.Empty; typeParameters = []; - if (text.StartsWithChar('[')) + if (text.StartsWithChar('[') || !MayDeclareType(text)) return false; var cursor = new Cursor(text, 0); while (true) @@ -297,6 +325,12 @@ private static bool IsTypeLine(string text, out ApiTypeKind kind, out string nam return true; } + /// Whether a line holds a type keyword at all, which most member lines do not; checked before reading it word by word. + private static bool MayDeclareType(string text) => + text.Contains("class ") || text.Contains("struct ") || text.Contains("interface ") || text.Contains("enum ") || text.Contains( + "record " + ) || text.Contains("delegate "); + private static string LastWord(string text) => text.Substring(text.LastIndexOf(' ') + 1); /// @@ -438,7 +472,7 @@ private ApiType Type(ref int i, int depth, string ns, (ApiType Type, Declared De m => m is ApiMethod { Kind: ApiMethodKind.Constructor } )); var type = shell with { Members = members, NestedTypes = nested, CanBeExtendedOutside = canBeExtended }; - _locations.Add(type, new ApiLocation(_file, line.Number)); + _locations.Add((type, new ApiLocation(_file, line.Number))); return type; } @@ -462,7 +496,7 @@ private bool StartsType(int i) var depth = _lines[i].Depth; while (i < _lines.Count && _lines[i].Depth == depth && _lines[i].Text.StartsWithChar('[')) i++; - return i < _lines.Count && _lines[i].Depth == depth && IsTypeLine(_lines[i].Text, out _, out _, out _); + return i < _lines.Count && _lines[i].Depth == depth && _typeLines.Contains(i); } private static ApiAccessibility? Accessibility(Cursor cursor) @@ -580,7 +614,7 @@ private ApiMember Member(ref int i, int depth, ApiType type, Declared declared, var member = type.Kind == ApiTypeKind.Enum ? EnumValue(cursor, attributes, enumType!) : Declaration(cursor, type, scope, attributes, returnAttributes, indexerName); - _locations.Add(member, new ApiLocation(_file, line.Number)); + _locations.Add((member, new ApiLocation(_file, line.Number))); return member; } @@ -805,9 +839,13 @@ private static List MethodTypeParameters(Cursor cursor) var paren = ParameterList(text, cursor.Position); if (paren < 0) return []; - var head = text.Substring(0, paren).TrimEnd(); - if (!head.EndsWithChar('>')) + // most methods have none: look at the character before the parenthesis before taking anything apart + var last = paren - 1; + while (last >= 0 && text[last] == ' ') + last--; + if (last < 0 || text[last] != '>') return []; + var head = text.Substring(0, last + 1); var open = MatchingOpen(head, head.Length - 1); // the list must follow a name, not be a generic return type's arguments if (open <= 0 || !IsNameCharacter(head[open - 1]) || head.LastIndexOf(' ', open) < cursor.Position) @@ -1059,7 +1097,9 @@ _ when symbol.StartsWith("op_", StringComparison.Ordinal) => symbol, /// The names a declaration can use: the types in the file and its header, and the type parameters in scope. private sealed class Scope(Parser parser, Declared? declaring, IReadOnlyList methodTypeParameters) { - public Scope With(IReadOnlyList parameters) => new(parser, declaring, [.. methodTypeParameters, .. parameters]); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1859", Justification = "callers pass both lists and arrays")] + public Scope With(IReadOnlyList parameters) => + parameters.Count == 0 ? this : new(parser, declaring, [.. methodTypeParameters, .. parameters]); private ApiTypeParameter? MethodParameter(string name) => methodTypeParameters.LastOrDefault(p => p.Name == name); @@ -1306,7 +1346,12 @@ static string Metadata((string Name, List? Arguments) segment) for (var top = segments.Count - 1; top >= 0; top--) { - var ns = string.Join(".", segments.Take(top).Select(s => s.Name)); + var ns = top switch + { + 0 => string.Empty, + 1 => segments[0].Name, + _ => string.Join(".", segments.Take(top).Select(s => s.Name)), + }; if (top == 1 && segments[0].Name == "global::") ns = string.Empty; var name = Metadata(segments[top]); @@ -1328,6 +1373,14 @@ static string Metadata((string Name, List? Arguments) segment) continue; var own = parser._own.TryGetValue((resolved, name), out var declared) ? declared : null; + if (top == segments.Count - 1) + return new ApiNamedType( + resolved, + name, + null, + segments[top].Arguments ?? [], + own?.IsValueType ?? parser._externalValueTypes.Contains((resolved, name)) + ); var path = name; var named = new ApiNamedType(resolved, name, null, segments[top].Arguments ?? [], false); for (var n = top + 1; n < segments.Count; n++) @@ -1335,10 +1388,11 @@ static string Metadata((string Name, List? Arguments) segment) var nestedName = Metadata(segments[n]); path += "/" + nestedName; own = own is not null && own.Nested.TryGetValue(nestedName, out var nested) ? nested : null; - named = new ApiNamedType(resolved, nestedName, named, segments[n].Arguments ?? [], false); + var isLast = n == segments.Count - 1; + var isValueType = isLast && (own?.IsValueType ?? parser._externalValueTypes.Contains((resolved, path))); + named = new ApiNamedType(resolved, nestedName, named, segments[n].Arguments ?? [], isValueType); } - var isValueType = own?.IsValueType ?? parser._externalValueTypes.Contains((resolved, path)); - return named with { IsValueType = isValueType }; + return named; } if (allowMissing) return null; @@ -1509,13 +1563,20 @@ public void End() private static bool IsWordCharacter(char c) => char.IsLetterOrDigit(c) || c is '_' or '@' or '$'; + private int _peekedAt = -1; + private string _peeked = string.Empty; + + /// The word at the cursor; the parser looks at a word before taking it, so the last one is kept. public string PeekWord() { Skip(); + if (_peekedAt == Position) + return _peeked; var end = Position; while (end < Text.Length && IsWordCharacter(Text[end])) end++; - return Text.Substring(Position, end - Position); + _peekedAt = Position; + return _peeked = Text.Substring(Position, end - Position); } /// The character after the word at the cursor, past spaces. diff --git a/src/Nullean.PublicApi/ApiReader.cs b/src/Nullean.PublicApi/ApiReader.cs index 6f36f9a..ba40a5f 100644 --- a/src/Nullean.PublicApi/ApiReader.cs +++ b/src/Nullean.PublicApi/ApiReader.cs @@ -143,7 +143,7 @@ private ApiAssembly ReadAssembly() modifiers |= ApiTypeModifiers.Abstract; else if (isSealed) modifiers |= ApiTypeModifiers.Sealed; - if (type.GetMethods().Any(m => _reader.GetString(_reader.GetMethodDefinition(m).Name) == "$")) + if (type.GetMethods().Any(m => _reader.StringComparer.Equals(_reader.GetMethodDefinition(m).Name, "$"))) modifiers |= ApiTypeModifiers.Record; } if (kind == ApiTypeKind.Struct) @@ -158,7 +158,7 @@ private ApiAssembly ReadAssembly() (kind == ApiTypeKind.Class && !isSealed && type .GetMethods() .Select(_reader.GetMethodDefinition) - .Any(m => _reader.GetString(m.Name) == ".ctor" && MemberAccessibility(m.Attributes & MethodAttributes.MemberAccessMask) is not null)); + .Any(m => _reader.StringComparer.Equals(m.Name, ".ctor") && MemberAccessibility(m.Attributes & MethodAttributes.MemberAccessMask) is not null)); ApiTypeReference? baseType = null; if (kind == ApiTypeKind.Class && !type.BaseType.IsNil && _types.FullName(type.BaseType) != "System.Object") @@ -483,7 +483,7 @@ bool isStruct var propertyType = Annotate(rawType, property.GetCustomAttributes(), typeContext, propertyOffset + (isByReference ? 1 : 0)); // an indexer's parameters are the getter's, or all but the setter's last - var parameters = new List(); + IReadOnlyList parameters = []; if (signature.ParameterTypes.Length > 0) { var source = getter ?? setter!.Value; @@ -634,7 +634,8 @@ private ApiMemberModifiers Modifiers(MethodDefinition method, ApiType declaring) return modifiers; } - private List ReadParameters(MethodDefinition method, ImmutableArray types, byte? methodContext) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1859", Justification = "a method without parameters shares one empty list")] + private IReadOnlyList ReadParameters(MethodDefinition method, ImmutableArray types, byte? methodContext) { var rows = new Parameter?[types.Length]; foreach (var handle in method.GetParameters()) @@ -644,6 +645,8 @@ private List ReadParameters(MethodDefinition method, ImmutableArra rows[parameter.SequenceNumber - 1] = parameter; } + if (types.Length == 0) + return []; var parameters = new List(types.Length); for (var i = 0; i < types.Length; i++) { @@ -796,16 +799,16 @@ private ApiTypeReference Annotate(ApiTypeReference type, IEnumerable? Nullable(IEnumerable attributes) + private byte[]? Nullable(IEnumerable attributes) { foreach (var handle in attributes) { @@ -816,12 +819,21 @@ private ApiTypeReference Annotate(ApiTypeReference type, IEnumerable? NullableFlags(CustomAttribute attribute) => TryDecode(attribute) switch + /// + /// A NullableAttribute's flags, read from its blob: the prolog, then a byte or an array of them. Nearly every member has + /// one, so it is not decoded the general way. + /// + private byte[]? NullableFlags(CustomAttribute attribute) { - { FixedArguments: [{ Value: byte flag }] } => [flag], - { FixedArguments: [{ Value: ImmutableArray> flags }] } => flags.Select(f => (byte)f.Value!).ToList(), - _ => null, - }; + var blob = _reader.GetBlobReader(attribute.Value); + if (blob.Length < 5 || blob.ReadUInt16() != 1) + return null; + // prolog, one byte, the named argument count + if (blob.Length == 5) + return [blob.ReadByte()]; + var count = blob.ReadInt32(); + return count < 0 || count > blob.RemainingBytes ? null : blob.ReadBytes(count); + } // attributes @@ -833,9 +845,25 @@ private bool HasAttribute(IEnumerable attributes, string return false; } - private string AttributeTypeName(CustomAttribute attribute) => AttributeType(attribute)?.FullName ?? string.Empty; + // an assembly applies the same few attributes many times: name each constructor's type once + private readonly Dictionary _attributeTypes = []; + private readonly Dictionary _attributeTypeNames = []; + + private string AttributeTypeName(CustomAttribute attribute) + { + if (!_attributeTypeNames.TryGetValue(attribute.Constructor, out var name)) + _attributeTypeNames[attribute.Constructor] = name = AttributeType(attribute)?.FullName ?? string.Empty; + return name; + } private ApiNamedType? AttributeType(CustomAttribute attribute) + { + if (!_attributeTypes.TryGetValue(attribute.Constructor, out var type)) + _attributeTypes[attribute.Constructor] = type = ResolveAttributeType(attribute); + return type; + } + + private ApiNamedType? ResolveAttributeType(CustomAttribute attribute) { var constructor = attribute.Constructor; EntityHandle parent = constructor.Kind switch @@ -865,7 +893,8 @@ private bool HasAttribute(IEnumerable attributes, string } } - private List Attributes(IEnumerable attributes) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1859", Justification = "a declaration without attributes shares one empty list")] + private IReadOnlyList Attributes(IEnumerable attributes) { var result = new List(); foreach (var handle in attributes) @@ -892,7 +921,13 @@ private List Attributes(IEnumerable attribu } result.Add(new ApiAttribute(type, arguments)); } - return result.OrderBy(a => a.Type.FullName, StringComparer.Ordinal).ThenBy(a => string.Join(",", a.Arguments), StringComparer.Ordinal).ToList(); + // most declarations have none, and share one empty list + return result.Count switch + { + 0 => [], + 1 => result, + _ => result.OrderBy(a => a.Type.FullName, StringComparer.Ordinal).ThenBy(a => string.Join(",", a.Arguments), StringComparer.Ordinal).ToList(), + }; } private static string Literal(CustomAttributeTypedArgument argument) => argument.Value switch diff --git a/src/Nullean.PublicApi/ApiWriter.cs b/src/Nullean.PublicApi/ApiWriter.cs index 0ee0e5c..43e715e 100644 --- a/src/Nullean.PublicApi/ApiWriter.cs +++ b/src/Nullean.PublicApi/ApiWriter.cs @@ -104,30 +104,20 @@ private static string Chunk(string ns, ApiSplit split) } /// A type's declaration line, as in a .api file: public sealed class Widget : Shape. - public static string Declaration(ApiType type) - { - var builder = new StringBuilder(); - new Writer(builder, new Names(Alone(type))).Type(type with { Members = type.Kind == ApiTypeKind.Delegate ? type.Members : [], NestedTypes = [] }, 0); - return LastLine(builder); - } + public static string Declaration(ApiType type) => new ApiDeclarationWriter(type).Declaration(); /// A member's declaration line, as in a .api file: public void Draw(Canvas canvas). - public static string Declaration(ApiMember member, ApiType declaringType) - { - var builder = new StringBuilder(); - new Writer(builder, new Names(Alone(declaringType))).Member(member, declaringType, 0); - return LastLine(builder); - } + public static string Declaration(ApiMember member, ApiType declaringType) => new ApiDeclarationWriter(declaringType).Declaration(member); /// A type as a declaration spells it, with short names: List<string?>. public static string Reference(ApiTypeReference type, ApiType? context = null) => - new Writer(new StringBuilder(), new Names(context is null ? new ApiAssembly(string.Empty, new Version(), null, null, []) : Alone(context))).Reference( - type - ); + context is null + ? new Writer(new StringBuilder(), new Names(new ApiAssembly(string.Empty, new Version(), null, null, []))).Reference(type) + : new ApiDeclarationWriter(context).Reference(type); - private static ApiAssembly Alone(ApiType type) => new(string.Empty, new Version(), null, null, [type]); + internal static ApiAssembly Alone(ApiType type) => new(string.Empty, new Version(), null, null, [type]); - private static string LastLine(StringBuilder builder) + internal static string LastLine(StringBuilder builder) { var lines = builder.ToString().TrimEnd('\n').Split('\n'); return lines[lines.Length - 1].Trim(); @@ -147,7 +137,7 @@ internal static string NonGeneric(string metadataName) } /// Decides which top-level types are written by their short name, and which other assemblies' types the header lists. - private sealed class Names + internal sealed class Names { private readonly HashSet<(string Namespace, string Name)> _qualified = []; private readonly HashSet<(string Namespace, string Path)> _values = []; @@ -307,7 +297,7 @@ private void Collect(ApiTypeReference type, HashSet<(string, string)> used) } : null; - private sealed class Writer(StringBuilder builder, Names names) + internal sealed class Writer(StringBuilder builder, Names names) { public void Type(ApiType type, int depth) { @@ -745,3 +735,39 @@ public enum ApiSplit /// The assembly's name for an API in one file; otherwise the namespace or namespaces the file holds, global for the global namespace. /// The file's text. public sealed record ApiFile(string Name, string Text); + +/// +/// Writes one type's declarations, its members' and the types they use, the way a .api file does. Deciding +/// which names to write in full looks at the whole type, so build one per type and reuse it. +/// +public sealed class ApiDeclarationWriter +{ + private readonly ApiType _type; + private readonly ApiWriter.Names _names; + + /// A writer in the context of . + public ApiDeclarationWriter(ApiType type) + { + _type = type; + _names = new ApiWriter.Names(ApiWriter.Alone(type)); + } + + /// The type's declaration line: sealed class Widget : Shape. + public string Declaration() + { + var builder = new StringBuilder(); + new ApiWriter.Writer(builder, _names).Type(_type with { Members = _type.Kind == ApiTypeKind.Delegate ? _type.Members : [], NestedTypes = [] }, 0); + return ApiWriter.LastLine(builder); + } + + /// A member's declaration line: void Draw(Canvas canvas). + public string Declaration(ApiMember member) + { + var builder = new StringBuilder(); + new ApiWriter.Writer(builder, _names).Member(member, _type, 0); + return ApiWriter.LastLine(builder); + } + + /// A type as a declaration in this type spells it: List<string?>. + public string Reference(ApiTypeReference type) => new ApiWriter.Writer(new StringBuilder(), _names).Reference(type); +} diff --git a/src/Nullean.PublicApi/Signatures.cs b/src/Nullean.PublicApi/Signatures.cs index 32de76b..9648c3c 100644 --- a/src/Nullean.PublicApi/Signatures.cs +++ b/src/Nullean.PublicApi/Signatures.cs @@ -26,7 +26,41 @@ MetadataReader reader public ApiTypeReference GetPrimitiveType(PrimitiveTypeCode typeCode) => Primitive(typeCode); - internal static ApiNamedType Primitive(PrimitiveTypeCode typeCode) => typeCode switch + // the records are immutable, so every reference to int or string shares one, made once + private static readonly ApiNamedType?[] Primitives = BuildPrimitives(); + + private static ApiNamedType?[] BuildPrimitives() + { + var primitives = new ApiNamedType?[64]; + foreach (var code in new[] + { + PrimitiveTypeCode.Boolean, + PrimitiveTypeCode.Byte, + PrimitiveTypeCode.SByte, + PrimitiveTypeCode.Char, + PrimitiveTypeCode.Int16, + PrimitiveTypeCode.UInt16, + PrimitiveTypeCode.Int32, + PrimitiveTypeCode.UInt32, + PrimitiveTypeCode.Int64, + PrimitiveTypeCode.UInt64, + PrimitiveTypeCode.Single, + PrimitiveTypeCode.Double, + PrimitiveTypeCode.IntPtr, + PrimitiveTypeCode.UIntPtr, + PrimitiveTypeCode.Object, + PrimitiveTypeCode.String, + PrimitiveTypeCode.TypedReference, + PrimitiveTypeCode.Void, + }) + primitives[(int)code] = NewPrimitive(code); + return primitives; + } + + internal static ApiNamedType Primitive(PrimitiveTypeCode typeCode) => + (int)typeCode < Primitives.Length && Primitives[(int)typeCode] is { } primitive ? primitive : NewPrimitive(typeCode); + + private static ApiNamedType NewPrimitive(PrimitiveTypeCode typeCode) => typeCode switch { PrimitiveTypeCode.Boolean => InSystem("Boolean", true), PrimitiveTypeCode.Byte => InSystem("Byte", true), @@ -180,12 +214,16 @@ public ApiTypeReference GetTypeFromSerializedName(string name) return named; } + private Dictionary? _enumTypes; + public PrimitiveTypeCode GetUnderlyingEnumType(ApiTypeReference type) { // an enum this assembly defines says; one from elsewhere is assumed to be an int, which nearly all are - if (type is ApiNamedType named) + if (_enumTypes is null) + { + _enumTypes = new Dictionary(StringComparer.Ordinal); foreach (var handle in reader.TypeDefinitions) - if (Definition(handle).FullName == named.FullName) + if (Definition(handle) is { IsValueType: true } definition) foreach (var fieldHandle in reader.GetTypeDefinition(handle).GetFields()) { var field = reader.GetFieldDefinition(fieldHandle); @@ -193,7 +231,8 @@ public PrimitiveTypeCode GetUnderlyingEnumType(ApiTypeReference type) (field.Attributes & System.Reflection.FieldAttributes.Static) == 0 && field.DecodeSignature(this, TypeContext.None) is ApiNamedType { Namespace: "System" } underlying ) - return underlying.Name switch + { + _enumTypes[definition.FullName] = underlying.Name switch { "Byte" => PrimitiveTypeCode.Byte, "SByte" => PrimitiveTypeCode.SByte, @@ -206,7 +245,10 @@ public PrimitiveTypeCode GetUnderlyingEnumType(ApiTypeReference type) "Boolean" => PrimitiveTypeCode.Boolean, _ => PrimitiveTypeCode.Int32, }; + break; + } } - return PrimitiveTypeCode.Int32; + } + return type is ApiNamedType named && _enumTypes.TryGetValue(named.FullName, out var code) ? code : PrimitiveTypeCode.Int32; } } diff --git a/src/assembly-differ/assembly-differ.csproj b/src/assembly-differ/assembly-differ.csproj index 290f057..a19e3c8 100644 --- a/src/assembly-differ/assembly-differ.csproj +++ b/src/assembly-differ/assembly-differ.csproj @@ -6,6 +6,8 @@ assembly-differ AssemblyDiffer true + + false assembly-differ Major true