Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 147 additions & 19 deletions src/ApiBuilderTests/Splitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ public static async Task Run()
var outputDir = Path.Combine(SplitOutputDir, framework);

var definedSymbols = GetPreprocessorSymbolsForFramework(framework);
var typeForwardedToLines = new List<string>();
var typeForwards = new List<TypeForward>();

foreach (var csFile in csFiles)
{
Expand All @@ -293,13 +293,13 @@ public static async Task Run()
lines = RemoveComments(lines);
lines = RemoveEmptyLines(lines);

// Extract ALL TypeForwardedTo lines first, before checking if file should be skipped
var forwardedToLines = lines.Where(l => l.TrimStart().Contains("TypeForwardedTo")).ToList();
if (forwardedToLines.Count > 0)
// Extract ALL TypeForwardedTo lines first, before checking if file should be skipped.
// Each keeps the preserved conditions (e.g. FeatureMemory && !RefsBclMemory) that enclosed it.
if (lines.Any(_ => _.Contains("TypeForwardedTo")))
{
typeForwardedToLines.AddRange(forwardedToLines);
// Remove TypeForwardedTo lines from the file
lines = lines.Where(l => !l.TrimStart().Contains("TypeForwardedTo")).ToList();
var (remaining, forwards) = ExtractTypeForwards(lines);
typeForwards.AddRange(forwards);
lines = remaining;

// Clean up again after removing TypeForwardedTo lines
lines = RemoveEmptyConditionalBlocks(lines);
Expand All @@ -321,27 +321,155 @@ public static async Task Run()
}

// Write consolidated TypeForwardeds.cs file if we have any TypeForwardedTo attributes
if (typeForwardedToLines.Count > 0)
if (typeForwards.Count > 0)
{
var typeForwardedsPath = Path.Combine(outputDir, "TypeForwardeds.cs");
var consolidatedLines = new List<string>
{
"// <auto-generated />",
"#pragma warning disable",
"using System.Runtime.CompilerServices;"
};
// Simplify TypeForwardedTo references by removing the namespace prefix
var simplifiedLines = typeForwardedToLines
.Select(line => line.Replace("System.Runtime.CompilerServices.TypeForwardedTo", "TypeForwardedTo"))
.ToList();
consolidatedLines.AddRange(simplifiedLines);
var consolidatedLines = BuildTypeForwardedsLines(typeForwards);
var consolidatedContent = string.Join("\n", ConvertSpacesToTabs(consolidatedLines)) + "\n";
Directory.CreateDirectory(outputDir);
await File.WriteAllTextAsync(typeForwardedsPath, consolidatedContent);
}
}
}

/// <summary>
/// A TypeForwardedTo line lifted out of a split file, with the preserved condition that enclosed it
/// (null when it was not inside any preserved conditional block).
/// </summary>
public record TypeForward(string Line, string? Guard);

/// <summary>
/// Removes the TypeForwardedTo lines from processed file lines. Each is returned with the conjunction of the
/// preserved conditional branches it sat in, so moving it to TypeForwardeds.cs does not drop its guard.
/// A line in an #elif or #else branch is guarded by the negation of the earlier branches too.
/// </summary>
public static (List<string> Remaining, List<TypeForward> Forwards) ExtractTypeForwards(List<string> lines)
{
var remaining = new List<string>();
var forwards = new List<TypeForward>();
var frames = new Stack<GuardFrame>();

foreach (var line in lines)
{
var trimmed = line.TrimStart();
if (trimmed.StartsWith("#if ") || trimmed.StartsWith("#if("))
{
frames.Push(new(trimmed[3..].Trim()));
}
else if (trimmed.StartsWith("#elif ") || trimmed.StartsWith("#elif("))
{
var frame = frames.Peek();
frame.Previous.Add(frame.Current!);
frame.Current = trimmed[5..].Trim();
}
else if (trimmed == "#else")
{
var frame = frames.Peek();
frame.Previous.Add(frame.Current!);
frame.Current = null;
}
else if (trimmed == "#endif")
{
frames.Pop();
}
else if (trimmed.Contains("TypeForwardedTo"))
{
forwards.Add(new(trimmed, BuildGuard(frames)));
continue;
}

remaining.Add(line);
}

return (remaining, forwards);
}

/// <summary>
/// Builds the TypeForwardeds.cs lines: unguarded forwards first, then one #if block per distinct guard.
/// </summary>
public static List<string> BuildTypeForwardedsLines(List<TypeForward> forwards)
{
var lines = new List<string>
{
"// <auto-generated />",
"#pragma warning disable",
"using System.Runtime.CompilerServices;"
};

var groups = forwards
.GroupBy(_ => _.Guard)
.OrderBy(_ => _.Key != null);
foreach (var group in groups)
{
if (group.Key != null)
{
lines.Add($"#if {group.Key}");
}

// Simplify TypeForwardedTo references by removing the namespace prefix
lines.AddRange(group.Select(_ => _.Line.Replace("System.Runtime.CompilerServices.TypeForwardedTo", "TypeForwardedTo")));

if (group.Key != null)
{
lines.Add("#endif");
}
}

return lines;
}

static string? BuildGuard(Stack<GuardFrame> frames)
{
// Stack enumerates innermost first; the guard reads outermost first.
// Negations are already self-contained; a positive condition needs parentheses when it has || and is joined with &&.
var parts = new List<(string Text, bool Negated)>();
foreach (var frame in frames.Reverse())
{
parts.AddRange(frame.Previous.Select(_ => (Negate(_), true)));
if (frame.Current != null)
{
parts.Add((frame.Current, false));
}
}

if (parts.Count == 0)
{
return null;
}

if (parts.Count == 1)
{
return parts[0].Text;
}

return string.Join(" && ", parts.Select(_ => !_.Negated && _.Text.Contains("||") ? $"({_.Text})" : _.Text));
}

static string Negate(string condition)
{
if (IsSymbol(condition))
{
return $"!{condition}";
}

if (condition.StartsWith('!') && IsSymbol(condition[1..]))
{
return condition[1..];
}

return $"!({condition})";
}

static bool IsSymbol(string condition) =>
condition.Length > 0 &&
condition.All(_ => char.IsLetterOrDigit(_) || _ == '_');

class GuardFrame(string current)
{
public List<string> Previous { get; } = [];
public string? Current { get; set; } = current;
}

/// <summary>
/// Removes empty and whitespace-only lines from the list.
/// </summary>
Expand Down
119 changes: 119 additions & 0 deletions src/ApiBuilderTests/SplitterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1147,6 +1147,125 @@ public async Task TypeForwardedToExtraction_HandlesMultipleAttributes()
await Assert.That(forwardedToLines[2]).Contains("Boolean");
}

[Test]
public async Task ExtractTypeForwards_KeepsPreservedGuard()
{
// Same shape as Base64Url.cs: the forward must stay excluded when the consumer references Microsoft.Bcl.Memory
var source = """
#if FeatureMemory && !RefsBclMemory
#if !NET9_0_OR_GREATER
namespace System.Buffers.Text;
static class Base64Url { }
#else
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Buffers.Text.Base64Url))]
#endif
#endif
""";

var lines = Splitter.ProcessFile(source, Splitter.GetPreprocessorSymbolsForFramework("net9.0"));
var (remaining, forwards) = Splitter.ExtractTypeForwards(lines);
remaining = Splitter.RemoveEmptyConditionalBlocks(remaining);

await Assert.That(forwards.Count).IsEqualTo(1);
await Assert.That(forwards[0].Guard).IsEqualTo("FeatureMemory && !RefsBclMemory");
await Assert.That(forwards[0].Line).IsEqualTo("[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Buffers.Text.Base64Url))]");
await Assert.That(remaining.Count).IsEqualTo(0);
}

[Test]
public async Task ExtractTypeForwards_UnguardedHasNullGuard()
{
var lines = new List<string>
{
"[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.String))]"
};

var (remaining, forwards) = Splitter.ExtractTypeForwards(lines);

await Assert.That(forwards.Count).IsEqualTo(1);
await Assert.That(forwards[0].Guard).IsNull();
await Assert.That(remaining.Count).IsEqualTo(0);
}

[Test]
public async Task ExtractTypeForwards_NegatesEarlierBranches()
{
var lines = new List<string>
{
"#if FeatureA",
"class InA { }",
"#elif FeatureB || FeatureC",
"[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.String))]",
"#else",
"[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Int32))]",
"#endif",
"#if !FeatureD",
"#if FeatureE",
"class InE { }",
"#else",
"[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Boolean))]",
"#endif",
"#endif"
};

var (remaining, forwards) = Splitter.ExtractTypeForwards(lines);

await Assert.That(forwards.Count).IsEqualTo(3);
await Assert.That(forwards[0].Guard).IsEqualTo("!FeatureA && (FeatureB || FeatureC)");
await Assert.That(forwards[1].Guard).IsEqualTo("!FeatureA && !(FeatureB || FeatureC)");
await Assert.That(forwards[2].Guard).IsEqualTo("!FeatureD && !FeatureE");
var remainingText = string.Join("\n", remaining);
await Assert.That(remainingText).DoesNotContain("TypeForwardedTo");
await Assert.That(remainingText).Contains("class InA { }");
await Assert.That(remainingText).Contains("class InE { }");
}

[Test]
public async Task BuildTypeForwardedsLines_GroupsByGuard()
{
var forwards = new List<Splitter.TypeForward>
{
new("[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(A))]", "FeatureMemory"),
new("[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(B))]", null),
new("[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))]", "FeatureMemory && !RefsBclMemory"),
new("[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(D))]", "FeatureMemory"),
new("[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(E))]", null)
};

var lines = Splitter.BuildTypeForwardedsLines(forwards);

await Assert.That(string.Join("\n", lines)).IsEqualTo(
"""
// <auto-generated />
#pragma warning disable
using System.Runtime.CompilerServices;
[assembly: TypeForwardedTo(typeof(B))]
[assembly: TypeForwardedTo(typeof(E))]
#if FeatureMemory
[assembly: TypeForwardedTo(typeof(A))]
[assembly: TypeForwardedTo(typeof(D))]
#endif
#if FeatureMemory && !RefsBclMemory
[assembly: TypeForwardedTo(typeof(C))]
#endif
""");
}

[Test]
public async Task TypeForwardeds_Net9_Base64UrlKeepsBclMemoryGuard()
{
// Microsoft.Bcl.Memory 11 has no net9.0 build, so on net9.0 its netstandard2.1 Base64Url clashes with the
// in-box one. The forward must be excluded when RefsBclMemory is defined, as it is in Base64Url.cs.
var path = Path.Combine(Splitter.SplitOutputDir, "net9.0", "TypeForwardeds.cs");
var lines = (await File.ReadAllLinesAsync(path)).ToList();

var index = lines.FindIndex(_ => _.Contains("typeof(System.Buffers.Text.Base64Url)"));
await Assert.That(index).IsGreaterThan(0);

var guard = lines.Take(index).LastOrDefault(_ => _.StartsWith("#if ") || _ == "#endif");
await Assert.That(guard).IsEqualTo("#if FeatureMemory && !RefsBclMemory");
}

[Test]
public async Task ContainsTypes_DoesNotIncludeTypeForwardedTo()
{
Expand Down
26 changes: 16 additions & 10 deletions src/Split/net10.0/TypeForwardeds.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
// <auto-generated />
#pragma warning disable
using System.Runtime.CompilerServices;
[assembly: TypeForwardedTo(typeof(System.Buffers.ArrayBufferWriter<>))]
[assembly: TypeForwardedTo(typeof(System.Buffers.Text.Base64Url))]
[assembly: TypeForwardedTo(typeof(System.Numerics.BitOperations))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CallerArgumentExpressionAttribute))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CollectionBuilderAttribute))]
[assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.CollectionsMarshal))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CompilerLoweringPreserveAttribute))]
Expand All @@ -28,13 +25,10 @@
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.OverloadResolutionPriorityAttribute))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.ParamCollectionAttribute))]
[assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.PosixSignal))]
[assembly: TypeForwardedTo(typeof(System.Buffers.ReadOnlySpanAction<,>))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.RequiredMemberAttribute))]
[assembly: TypeForwardedTo(typeof(System.Runtime.Versioning.RequiresPreviewFeaturesAttribute))]
[assembly: TypeForwardedTo(typeof(System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.SkipLocalsInitAttribute))]
[assembly: TypeForwardedTo(typeof(System.Buffers.SpanAction<,>))]
[assembly: TypeForwardedTo(typeof(System.Text.SpanLineEnumerator))]
[assembly: TypeForwardedTo(typeof(System.Diagnostics.StackTraceHiddenAttribute))]
[assembly: TypeForwardedTo(typeof(System.Diagnostics.CodeAnalysis.StringSyntaxAttribute))]
[assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.SuppressGCTransitionAttribute))]
Expand All @@ -43,8 +37,6 @@
[assembly: TypeForwardedTo(typeof(System.Diagnostics.UnreachableException))]
[assembly: TypeForwardedTo(typeof(System.Diagnostics.CodeAnalysis.UnscopedRefAttribute))]
[assembly: TypeForwardedTo(typeof(System.IO.Compression.ZLibStream))]
[assembly: TypeForwardedTo(typeof(System.Index))]
[assembly: TypeForwardedTo(typeof(System.Range))]
[assembly: TypeForwardedTo(typeof(System.Reflection.NullabilityInfo))]
[assembly: TypeForwardedTo(typeof(System.Reflection.NullabilityInfoContext))]
[assembly: TypeForwardedTo(typeof(System.Diagnostics.CodeAnalysis.AllowNullAttribute))]
Expand All @@ -65,8 +57,6 @@
[assembly: TypeForwardedTo(typeof(System.Runtime.Versioning.TargetPlatformAttribute))]
[assembly: TypeForwardedTo(typeof(System.Runtime.Versioning.UnsupportedOSPlatformAttribute))]
[assembly: TypeForwardedTo(typeof(System.Runtime.Versioning.UnsupportedOSPlatformGuardAttribute))]
[assembly: TypeForwardedTo(typeof(System.Text.RegularExpressions.ValueMatch))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.DefaultInterpolatedStringHandler))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute))]
[assembly: TypeForwardedTo(typeof(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute))]
Expand All @@ -76,3 +66,19 @@
[assembly: TypeForwardedTo(typeof(System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute))]
[assembly: TypeForwardedTo(typeof(System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute))]
[assembly: TypeForwardedTo(typeof(System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute))]
#if FeatureMemory
[assembly: TypeForwardedTo(typeof(System.Buffers.ArrayBufferWriter<>))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CollectionBuilderAttribute))]
[assembly: TypeForwardedTo(typeof(System.Buffers.ReadOnlySpanAction<,>))]
[assembly: TypeForwardedTo(typeof(System.Buffers.SpanAction<,>))]
[assembly: TypeForwardedTo(typeof(System.Text.SpanLineEnumerator))]
[assembly: TypeForwardedTo(typeof(System.Text.RegularExpressions.ValueMatch))]
[assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.DefaultInterpolatedStringHandler))]
#endif
#if FeatureMemory && !RefsBclMemory
[assembly: TypeForwardedTo(typeof(System.Buffers.Text.Base64Url))]
#endif
#if FeatureValueTuple && !RefsBclMemory
[assembly: TypeForwardedTo(typeof(System.Index))]
[assembly: TypeForwardedTo(typeof(System.Range))]
#endif
Loading
Loading