Skip to content

Commit

Permalink
Generate Range without ValueTuple dependency on older frameworks
Browse files Browse the repository at this point in the history
  • Loading branch information
sharwell committed Jan 4, 2022
1 parent 080f89d commit 749d35c
Show file tree
Hide file tree
Showing 2 changed files with 364 additions and 103 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -151,39 +151,150 @@ public override string ToString()
}
";

private const string SystemRangeSource = @"// <auto-generated/>
private static readonly string SystemRangeSource = GetSystemRangeSource(hasValueTuple: true);

private static readonly string SystemRangeWithoutValueTupleSource = GetSystemRangeSource(hasValueTuple: false);

public void Initialize(IncrementalGeneratorInitializationContext context)
{
var referencedTypesData = context.CompilationProvider.Select(
(compilation, cancellationToken) =>
{
var hasIndex = IsCompilerTypeAvailable(compilation, "System.Index");
var hasRange = IsCompilerTypeAvailable(compilation, "System.Range");
var hasValueTuple = IsCompilerTypeAvailable(compilation, "System.ValueTuple`2");

return new ReferencedTypesData(
hasIndex: hasIndex,
hasRange: hasRange,
hasValueTuple: hasValueTuple);
});

context.RegisterSourceOutput(
referencedTypesData,
(context, referencedTypesData) =>
{
var forwarders = new List<string>();

if (referencedTypesData.HasIndex == TypeDefinitionLocation.None)
{
context.AddSource("Index.g.cs", SystemIndexSource.ReplaceLineEndings("\r\n"));
}
else if (referencedTypesData.HasIndex == TypeDefinitionLocation.Referenced)
{
forwarders.Add("Index");
}

if (referencedTypesData.HasRange == TypeDefinitionLocation.None)
{
if (referencedTypesData.HasValueTuple != TypeDefinitionLocation.None)
{
context.AddSource("Range.g.cs", SystemRangeSource.ReplaceLineEndings("\r\n"));
}
else
{
context.AddSource("Range.g.cs", SystemRangeWithoutValueTupleSource.ReplaceLineEndings("\r\n"));
}
}
else if (referencedTypesData.HasRange == TypeDefinitionLocation.Referenced)
{
forwarders.Add("Range");
}

if (forwarders.Count > 0)
{
var compilerForwarders = $@"// <auto-generated/>
#nullable enable
using System;
using System.Runtime.CompilerServices;
{string.Join("\r\n", forwarders.Select(forwarder => $"[assembly: TypeForwardedTo(typeof({forwarder}))]"))}
";

context.AddSource("IndexRangeForwarders.g.cs", compilerForwarders.ReplaceLineEndings("\r\n"));
}
});
}

private static string GetSystemRangeSource(bool hasValueTuple)
{
string getOffsetAndLengthMethod;
if (hasValueTuple)
{
getOffsetAndLengthMethod = @"
/// <summary>Calculate the start offset and length of range object using a collection length.</summary>
/// <param name=""length"">The length of the collection that the range will be used with. length has to be a positive value.</param>
/// <remarks>
/// For performance reason, we don't validate the input length parameter against negative values.
/// It is expected Range will be used with collections which always have non negative length/count.
/// We validate the range is inside the length scope though.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public (int Offset, int Length) GetOffsetAndLength(int length)
{
int start;
Index startIndex = Start;
if (startIndex.IsFromEnd)
start = length - startIndex.Value;
else
start = startIndex.Value;
int end;
Index endIndex = End;
if (endIndex.IsFromEnd)
end = length - endIndex.Value;
else
end = endIndex.Value;
if ((uint)end > (uint)length || (uint)start > (uint)end)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
return (start, end - start);
}
";
}
else
{
getOffsetAndLengthMethod = string.Empty;
}

return $@"// <auto-generated/>
#nullable enable
namespace System
{
{{
using System.Runtime.CompilerServices;
/// <summary>Represent a range has start and end indexes.</summary>
/// <remarks>
/// Range is used by the C# compiler to support the range syntax.
/// <code>
/// int[] someArray = new int[5] { 1, 2, 3, 4, 5 };
/// int[] subArray1 = someArray[0..2]; // { 1, 2 }
/// int[] subArray2 = someArray[1..^0]; // { 2, 3, 4, 5 }
/// int[] someArray = new int[5] {{ 1, 2, 3, 4, 5 }};
/// int[] subArray1 = someArray[0..2]; // {{ 1, 2 }}
/// int[] subArray2 = someArray[1..^0]; // {{ 2, 3, 4, 5 }}
/// </code>
/// </remarks>
internal readonly struct Range : IEquatable<Range>
{
{{
/// <summary>Represent the inclusive start index of the Range.</summary>
public Index Start { get; }
public Index Start {{ get; }}
/// <summary>Represent the exclusive end index of the Range.</summary>
public Index End { get; }
public Index End {{ get; }}
/// <summary>Construct a Range object using the start and end indexes.</summary>
/// <param name=""start"">Represent the inclusive start index of the range.</param>
/// <param name=""end"">Represent the exclusive end index of the range.</param>
public Range(Index start, Index end)
{
{{
Start = start;
End = end;
}
}}
/// <summary>Indicates whether the current Range object is equal to another object of the same type.</summary>
/// <param name=""value"">An object to compare with this object</param>
Expand All @@ -198,19 +309,19 @@ value is Range r &&
/// <summary>Returns the hash code for this instance.</summary>
public override int GetHashCode()
{
{{
var value64 = ((ulong)unchecked((uint)Start.GetHashCode()) << 32) + unchecked((uint)End.GetHashCode());
return value64.GetHashCode();
}
}}
/// <summary>Converts the value of the current Range object to its equivalent string representation.</summary>
public override string ToString()
{
return $""{getFromEndSpecifier(Start)}{toString(Start)}..{getFromEndSpecifier(End)}{toString(End)}"";
{{
return $""{{getFromEndSpecifier(Start)}}{{toString(Start)}}..{{getFromEndSpecifier(End)}}{{toString(End)}}"";
static string getFromEndSpecifier(Index index) => index.IsFromEnd ? ""^"" : string.Empty;
static string toString(Index index) => ((uint)index.Value).ToString();
}
}}
/// <summary>Create a Range object starting from start index to the end of the collection.</summary>
public static Range StartAt(Index start) => new Range(start, Index.End);
Expand All @@ -220,94 +331,9 @@ public override string ToString()
/// <summary>Create a Range object starting from first element to the end.</summary>
public static Range All => new Range(Index.Start, Index.End);
/// <summary>Calculate the start offset and length of range object using a collection length.</summary>
/// <param name=""length"">The length of the collection that the range will be used with. length has to be a positive value.</param>
/// <remarks>
/// For performance reason, we don't validate the input length parameter against negative values.
/// It is expected Range will be used with collections which always have non negative length/count.
/// We validate the range is inside the length scope though.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public (int Offset, int Length) GetOffsetAndLength(int length)
{
int start;
Index startIndex = Start;
if (startIndex.IsFromEnd)
start = length - startIndex.Value;
else
start = startIndex.Value;
int end;
Index endIndex = End;
if (endIndex.IsFromEnd)
end = length - endIndex.Value;
else
end = endIndex.Value;
if ((uint)end > (uint)length || (uint)start > (uint)end)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
return (start, end - start);
}
}
}
{getOffsetAndLengthMethod} }}
}}
";

public void Initialize(IncrementalGeneratorInitializationContext context)
{
var referencedTypesData = context.CompilationProvider.Select(
(compilation, cancellationToken) =>
{
var hasIndex = IsCompilerTypeAvailable(compilation, "System.Index");
var hasRange = IsCompilerTypeAvailable(compilation, "System.Range");

return new ReferencedTypesData(
hasIndex: hasIndex,
hasRange: hasRange);
});

context.RegisterSourceOutput(
referencedTypesData,
(context, referencedTypesData) =>
{
var forwarders = new List<string>();

if (referencedTypesData.HasIndex == TypeDefinitionLocation.None)
{
context.AddSource("Index.g.cs", SystemIndexSource.ReplaceLineEndings("\r\n"));
}
else if (referencedTypesData.HasIndex == TypeDefinitionLocation.Referenced)
{
forwarders.Add("Index");
}

if (referencedTypesData.HasRange == TypeDefinitionLocation.None)
{
context.AddSource("Range.g.cs", SystemRangeSource.ReplaceLineEndings("\r\n"));
}
else if (referencedTypesData.HasRange == TypeDefinitionLocation.Referenced)
{
forwarders.Add("Range");
}

if (forwarders.Count > 0)
{
var compilerForwarders = $@"// <auto-generated/>
#nullable enable
using System;
using System.Runtime.CompilerServices;
{string.Join("\r\n", forwarders.Select(forwarder => $"[assembly: TypeForwardedTo(typeof({forwarder}))]"))}
";

context.AddSource("IndexRangeForwarders.g.cs", compilerForwarders.ReplaceLineEndings("\r\n"));
}
});
}

private static TypeDefinitionLocation IsCompilerTypeAvailable(Compilation compilation, string fullyQualifiedMetadataName)
Expand All @@ -322,15 +348,18 @@ private static TypeDefinitionLocation IsCompilerTypeAvailable(Compilation compil

private sealed class ReferencedTypesData
{
public ReferencedTypesData(TypeDefinitionLocation hasIndex, TypeDefinitionLocation hasRange)
public ReferencedTypesData(TypeDefinitionLocation hasIndex, TypeDefinitionLocation hasRange, TypeDefinitionLocation hasValueTuple)
{
HasIndex = hasIndex;
HasRange = hasRange;
HasValueTuple = hasValueTuple;
}

public TypeDefinitionLocation HasIndex { get; }

public TypeDefinitionLocation HasRange { get; }

public TypeDefinitionLocation HasValueTuple { get; }
}
}
}
Loading

0 comments on commit 749d35c

Please sign in to comment.