Skip to content

Commit

Permalink
Use C# 12 features
Browse files Browse the repository at this point in the history
  • Loading branch information
ltrzesniewski committed Dec 6, 2023
1 parent 7cb322c commit f560b2f
Show file tree
Hide file tree
Showing 41 changed files with 165 additions and 309 deletions.
6 changes: 3 additions & 3 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

root = true


[*]
trim_trailing_whitespace = true
insert_final_newline = true
Expand Down Expand Up @@ -28,5 +28,5 @@ trim_trailing_whitespace = false
[*.sh]
end_of_line = lf

[*.g4]
indent_style = tab
[*.cs]
resharper_indent_raw_literal_string = indent
4 changes: 2 additions & 2 deletions .github/workflows/on-push-do-doco.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ jobs:
release:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Run MarkdownSnippets
run: |
dotnet tool install --global MarkdownSnippets.Tool
Expand All @@ -19,4 +19,4 @@ jobs:
remote="https://${GITHUB_ACTOR}:${{secrets.GITHUB_TOKEN}}@github.com/${GITHUB_REPOSITORY}.git"
branch="${GITHUB_REF:11}"
git push "${remote}" ${branch} || echo "nothing to push"
shell: bash
shell: bash
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,5 @@ ZeroLog.LogMessage M(ZeroLog.Log log)
return test.RunAsync();
}

private class Test : ZeroLogAnalyzerTest<DiscardedLogMessageAnalyzer>
{
}
private class Test : ZeroLogAnalyzerTest<DiscardedLogMessageAnalyzer>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,5 @@ void N(string value) { }
return test.RunAsync();
}

private class Test : ZeroLogAnalyzerTest<LegacyStringInterpolationAnalyzer>
{
}
private class Test : ZeroLogAnalyzerTest<LegacyStringInterpolationAnalyzer>;
}
4 changes: 1 addition & 3 deletions src/ZeroLog.Analyzers.Tests/PrefixPatternAnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,5 @@ C M()
return test.RunAsync();
}

private class Test : ZeroLogAnalyzerTest<PrefixPatternAnalyzer>
{
}
private class Test : ZeroLogAnalyzerTest<PrefixPatternAnalyzer>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,5 @@ void M(ZeroLog.Log log)
return test.RunAsync();
}

private class Test : ZeroLogAnalyzerTest<UseStringInterpolationAnalyzer>
{
}
private class Test : ZeroLogAnalyzerTest<UseStringInterpolationAnalyzer>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,5 @@ void M(ZeroLog.Log log)
return test.RunAsync();
}

private class Test : ZeroLogCodeFixTest<UseStringInterpolationAnalyzer, UseStringInterpolationCodeFixProvider>
{
}
private class Test : ZeroLogCodeFixTest<UseStringInterpolationAnalyzer, UseStringInterpolationCodeFixProvider>;
}
10 changes: 5 additions & 5 deletions src/ZeroLog.Analyzers.Tests/ZeroLogAnalyzerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ namespace ZeroLog.Analyzers.Tests;

internal static class ZeroLogAnalyzerTest
{
private static readonly ReferenceAssemblies _net7ReferenceAssemblies = new(
"net7.0",
new PackageIdentity("Microsoft.NETCore.App.Ref", "7.0.0"),
Path.Combine("ref", "net7.0")
private static readonly ReferenceAssemblies _netReferenceAssemblies = new(
"net8.0",
new PackageIdentity("Microsoft.NETCore.App.Ref", "8.0.0"),
Path.Combine("ref", "net8.0")
);

public static void ConfigureTest(AnalyzerTest<NUnitVerifier> test)
{
test.ReferenceAssemblies = _net7ReferenceAssemblies;
test.ReferenceAssemblies = _netReferenceAssemblies;
test.TestState.AdditionalReferences.Add(typeof(LogManager).Assembly);
}
}
Expand Down
22 changes: 5 additions & 17 deletions src/ZeroLog.Analyzers/UseStringInterpolationAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,24 +61,13 @@ private static void AnalyzeCompilationStart(CompilationStartAnalysisContext comp
);
}

private class Analysis
private class Analysis(INamedTypeSymbol logTypeSymbol, INamedTypeSymbol logMessageTypeSymbol, IMethodSymbol logMethodSymbol)
{
private readonly INamedTypeSymbol _logTypeSymbol;
private readonly INamedTypeSymbol _logMessageTypeSymbol;
private readonly IMethodSymbol _logMethodSymbol;

public Analysis(INamedTypeSymbol logTypeSymbol, INamedTypeSymbol logMessageTypeSymbol, IMethodSymbol logMethodSymbol)
{
_logTypeSymbol = logTypeSymbol;
_logMessageTypeSymbol = logMessageTypeSymbol;
_logMethodSymbol = logMethodSymbol;
}

public void AnalyzeOperation(OperationAnalysisContext operationContext)
{
var invocation = (IInvocationOperation)operationContext.Operation;

if (!SymbolEqualityComparer.Default.Equals(invocation.TargetMethod, _logMethodSymbol))
if (!SymbolEqualityComparer.Default.Equals(invocation.TargetMethod, logMethodSymbol))
return;

var rootMethodInvocation = FindSimplifiableLogBuilderInvocationOperation(invocation.Instance);
Expand All @@ -96,7 +85,7 @@ public void AnalyzeOperation(OperationAnalysisContext operationContext)

var invocationOperation = (IInvocationOperation)operation;

if (SymbolEqualityComparer.Default.Equals(invocationOperation.TargetMethod.ContainingType, _logMessageTypeSymbol))
if (SymbolEqualityComparer.Default.Equals(invocationOperation.TargetMethod.ContainingType, logMessageTypeSymbol))
{
if (invocationOperation.TargetMethod.Name is not (ZeroLogFacts.MethodNames.Append or ZeroLogFacts.MethodNames.AppendEnum))
return null;
Expand All @@ -106,8 +95,7 @@ public void AnalyzeOperation(OperationAnalysisContext operationContext)
return null;

// Don't suggest a simplification if there is a verbatim string interpolation
if (valueArgument.Value.Kind == OperationKind.InterpolatedString
&& valueArgument.Value.Syntax is InterpolatedStringExpressionSyntax interpolatedStringSyntax
if (valueArgument.Value is { Kind: OperationKind.InterpolatedString, Syntax: InterpolatedStringExpressionSyntax interpolatedStringSyntax }
&& interpolatedStringSyntax.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken))
{
return null;
Expand All @@ -123,7 +111,7 @@ public void AnalyzeOperation(OperationAnalysisContext operationContext)

operation = invocationOperation.Instance;
}
else if (SymbolEqualityComparer.Default.Equals(invocationOperation.TargetMethod.ContainingType, _logTypeSymbol))
else if (SymbolEqualityComparer.Default.Equals(invocationOperation.TargetMethod.ContainingType, logTypeSymbol))
{
if (invocationOperation.TargetMethod.Parameters.IsEmpty && ZeroLogFacts.IsLogLevelName(invocationOperation.TargetMethod.Name))
return invocationOperation;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ private static async Task<Document> FixNode(Document document,

rootNode = rootNode.ReplaceNode(
logMethodInvocation,
logBuilderInvocation.WithArgumentList(ArgumentList(SeparatedList(new[] { Argument(resultExpression) })))
logBuilderInvocation.WithArgumentList(ArgumentList(SeparatedList([Argument(resultExpression)])))
.WithTrailingTrivia(logMethodInvocation.GetTrailingTrivia())
);

Expand Down
21 changes: 8 additions & 13 deletions src/ZeroLog.Impl.Base/Support/Attributes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,22 @@
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue)]
internal sealed class NotNullAttribute : Attribute
{
}
internal sealed class NotNullAttribute : Attribute;
}

namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
internal sealed class InterpolatedStringHandlerAttribute : Attribute
{
public InterpolatedStringHandlerAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
internal sealed class InterpolatedStringHandlerAttribute : Attribute;

[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute
{
public InterpolatedStringHandlerArgumentAttribute(string argument) => Arguments = new string[] { argument };
public InterpolatedStringHandlerArgumentAttribute(string argument)
=> Arguments = [argument];

public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) => Arguments = arguments;
public InterpolatedStringHandlerArgumentAttribute(params string[] arguments)
=> Arguments = arguments;

public string[] Arguments { get; }
}
Expand Down
4 changes: 2 additions & 2 deletions src/ZeroLog.Impl.Full/Appenders/StreamAppender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace ZeroLog.Appenders;
/// </summary>
public abstract class StreamAppender : Appender
{
private byte[] _byteBuffer = Array.Empty<byte>();
private byte[] _byteBuffer = [];

private Encoding _encoding = Encoding.UTF8;
private bool _useSpanGetBytes;
Expand Down Expand Up @@ -104,5 +104,5 @@ private void UpdateEncodingSpecificData()
}

internal static bool OverridesSpanGetBytes(Type encodingType)
=> encodingType.GetMethod(nameof(System.Text.Encoding.GetBytes), BindingFlags.Public | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(Span<byte>) })?.DeclaringType == encodingType;
=> encodingType.GetMethod(nameof(System.Text.Encoding.GetBytes), BindingFlags.Public | BindingFlags.Instance, [typeof(ReadOnlySpan<char>), typeof(Span<byte>)])?.DeclaringType == encodingType;
}
2 changes: 1 addition & 1 deletion src/ZeroLog.Impl.Full/Appenders/TextWriterAppender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,5 +94,5 @@ private void SetTextWriter(TextWriter? newTextWriter)
}

internal static bool OverridesSpanWrite(Type textWriterType)
=> textWriterType.GetMethod(nameof(System.IO.TextWriter.Write), BindingFlags.Public | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>) })?.DeclaringType == textWriterType;
=> textWriterType.GetMethod(nameof(System.IO.TextWriter.Write), BindingFlags.Public | BindingFlags.Instance, [typeof(ReadOnlySpan<char>)])?.DeclaringType == textWriterType;
}
15 changes: 4 additions & 11 deletions src/ZeroLog.Impl.Full/BufferSegmentProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,9 @@ public static BufferSegment CreateStandaloneSegment(int bufferSize)
}
}

internal unsafe struct BufferSegment
internal unsafe struct BufferSegment(byte* data, int length, byte[]? underlyingBuffer)
{
public readonly byte* Data;
public readonly int Length;
public readonly byte[]? UnderlyingBuffer;

public BufferSegment(byte* data, int length, byte[]? underlyingBuffer)
{
Data = data;
Length = length;
UnderlyingBuffer = underlyingBuffer;
}
public readonly byte* Data = data;
public readonly int Length = length;
public readonly byte[]? UnderlyingBuffer = underlyingBuffer;
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ internal sealed class ResolvedLoggerConfiguration
private ResolvedLoggerConfiguration(IEnumerable<Appender[]> appendersByLogLevel)
{
_appendersByLogLevel = appendersByLogLevel.ToArray();
_appendersByLogLevel[(int)LogLevel.None] = Array.Empty<Appender>();
_appendersByLogLevel[(int)LogLevel.None] = [];
Debug.Assert(_appendersByLogLevel.Length == _levelCount);

Level = LogLevel.None;
Expand Down Expand Up @@ -103,7 +103,7 @@ internal static ResolvedLoggerConfiguration SingleAppender(LogLevel level, Appen
var appenderArray = new[] { appender ?? new NoopAppender() };

var appendersByLogLevel = Enumerable.Range(0, _levelCount)
.Select(i => i >= (int)level ? appenderArray : Array.Empty<Appender>());
.Select(i => i >= (int)level ? appenderArray : []);

return new ResolvedLoggerConfiguration(appendersByLogLevel);
}
Expand Down
13 changes: 4 additions & 9 deletions src/ZeroLog.Impl.Full/EnumArg.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,14 @@ namespace ZeroLog;

[StructLayout(LayoutKind.Sequential)]
[SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Local")]
internal readonly struct EnumArg
[SuppressMessage("ReSharper", "ReplaceWithPrimaryConstructorParameter")]
internal readonly struct EnumArg(IntPtr typeHandle, ulong value)
{
private readonly IntPtr _typeHandle;
private readonly ulong _value;
private readonly IntPtr _typeHandle = typeHandle;
private readonly ulong _value = value;

public Type? Type => TypeUtil.GetTypeFromHandle(_typeHandle);

public EnumArg(IntPtr typeHandle, ulong value)
{
_typeHandle = typeHandle;
_value = value;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryFormat(Span<char> destination, out int charsWritten, ZeroLogConfiguration config)
{
Expand Down
14 changes: 4 additions & 10 deletions src/ZeroLog.Impl.Full/EnumCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ public ArrayEnumStrings(List<EnumItem> enumItems)
{
if (enumItems.Count == 0)
{
_strings = Array.Empty<string>();
_strings = [];
return;
}

Expand Down Expand Up @@ -239,15 +239,9 @@ public DictionaryEnumStrings(List<EnumItem> enumItems)
}
}

private struct EnumItem
private readonly struct EnumItem(Enum item)
{
public ulong Value { get; }
public string Name { get; }

public EnumItem(Enum item)
{
Value = ToUInt64Slow(item);
Name = item.ToString();
}
public ulong Value { get; } = ToUInt64Slow(item);
public string Name { get; } = item.ToString();
}
}
13 changes: 4 additions & 9 deletions src/ZeroLog.Impl.Full/Formatting/CharBufferBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,14 @@
namespace ZeroLog.Formatting;

[SuppressMessage("ReSharper", "ReplaceSliceWithRangeIndexer")]
internal ref struct CharBufferBuilder
[SuppressMessage("ReSharper", "ReplaceWithPrimaryConstructorParameter")]
internal ref struct CharBufferBuilder(Span<char> buffer)
{
private readonly Span<char> _buffer;
private int _pos;
private readonly Span<char> _buffer = buffer;
private int _pos = 0;

public int Length => _pos;

public CharBufferBuilder(Span<char> buffer)
{
_buffer = buffer;
_pos = 0;
}

public ReadOnlySpan<char> GetOutput()
=> _buffer.Slice(0, _pos);

Expand Down
2 changes: 1 addition & 1 deletion src/ZeroLog.Impl.Full/Formatting/HexUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace ZeroLog.Formatting;

internal static class HexUtils
{
private static readonly char[] _hexTable = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static readonly char[] _hexTable = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];

public static unsafe void AppendValueAsHex(byte* valuePtr, int size, Span<char> destination)
{
Expand Down
1 change: 1 addition & 0 deletions src/ZeroLog.Impl.Full/Formatting/PrefixWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ internal class PrefixWriter

public string Pattern { get; }

[SuppressMessage("ReSharper", "ConvertToPrimaryConstructor")]
public PrefixWriter(string pattern)
{
Pattern = pattern;
Expand Down
4 changes: 2 additions & 2 deletions src/ZeroLog.Impl.Full/LogMessage.Impl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ unsafe partial class LogMessage
internal LogMessage(string message)
{
ConstantMessage = message;
_strings = Array.Empty<string>();
_strings = [];
}

internal LogMessage(BufferSegment bufferSegment, int stringCapacity)
{
stringCapacity = Math.Min(stringCapacity, byte.MaxValue);
_strings = stringCapacity > 0 ? new string[stringCapacity] : Array.Empty<string>();
_strings = stringCapacity > 0 ? new string[stringCapacity] : [];

_startOfBuffer = bufferSegment.Data;
_dataPointer = bufferSegment.Data;
Expand Down
Loading

0 comments on commit f560b2f

Please sign in to comment.