Use native rust library for parsing packages (#21)

This commit is contained in:
RobbersDaughter 2024-05-17 20:46:07 +02:00 • committed by GitHub
commit 796c5d19c5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
53 changed files with 237 additions and 1043 deletions

3
.gitmodules vendored Normal file
View file

@ -0,0 +1,3 @@
[submodule "tanks-backend/servicepoint"]
path = tanks-backend/servicepoint
url = https://github.com/kaesaecracker/servicepoint.git

6
package-lock.json generated
View file

@ -1,6 +0,0 @@
{
"name": "cccb-tanks-cs",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}

View file

@ -48,27 +48,31 @@ export default function PlayerInfo({player}: { player: string }) {
return <Column className="PlayerInfo">
<h3>
Playing as {lastJsonMessage.name}
Playing as {lastJsonMessage.player.name}
</h3>
<table>
<tbody>
<ScoreRow name="magazine" value={lastJsonMessage.tank?.magazine}/>
{lastJsonMessage.tank && <>
<ScoreRow name="magazine" value={`${lastJsonMessage.tank.usedBullets} / ${lastJsonMessage.tank.maxBullets}`}/>
<ScoreRow name="position" value={`(${Math.round(lastJsonMessage.tank.pixelPosition.x)}|${Math.round(lastJsonMessage.tank.pixelPosition.y)})`}/>
<ScoreRow name="orientation" value={lastJsonMessage.tank.orientation}/>
<ScoreRow name="bullet speed" value={lastJsonMessage.tank.bulletStats.speed}/>
<ScoreRow name="bullet acceleration" value={lastJsonMessage.tank.bulletStats.acceleration}/>
<ScoreRow name="smart bullets" value={lastJsonMessage.tank.bulletStats.smart}/>
<ScoreRow name="explosive bullets" value={lastJsonMessage.tank.bulletStats.explosive}/>
<ScoreRow name="moving" value={lastJsonMessage.tank.moving}/>
</>}
<ScoreRow name="controls" value={lastJsonMessage.controls}/>
<ScoreRow name="position" value={lastJsonMessage.tank?.position}/>
<ScoreRow name="orientation" value={lastJsonMessage.tank?.orientation}/>
<ScoreRow name="moving" value={lastJsonMessage.tank?.moving}/>
<ScoreRow name="kills" value={lastJsonMessage.player.scores.kills}/>
<ScoreRow name="deaths" value={lastJsonMessage.player.scores.deaths}/>
<ScoreRow name="walls destroyed" value={lastJsonMessage.player.scores.wallsDestroyed}/>
<ScoreRow name="bullets fired" value={lastJsonMessage.player.scores.shotsFired}/>
<ScoreRow name="power ups collected" value={lastJsonMessage.player.scores.powerUpsCollected}/>
<ScoreRow name="pixels moved" value={lastJsonMessage.player.scores.pixelsMoved}/>
<ScoreRow name="score" value={lastJsonMessage.player.scores.overallScore}/>
<ScoreRow name="kills" value={lastJsonMessage.scores.kills}/>
<ScoreRow name="deaths" value={lastJsonMessage.scores.deaths}/>
<ScoreRow name="walls destroyed" value={lastJsonMessage.scores.wallsDestroyed}/>
<ScoreRow name="bullets fired" value={lastJsonMessage.scores.shotsFired}/>
<ScoreRow name="power ups collected" value={lastJsonMessage.scores.powerUpsCollected}/>
<ScoreRow name="pixels moved" value={lastJsonMessage.scores.pixelsMoved}/>
<ScoreRow name="score" value={lastJsonMessage.scores.overallScore}/>
<ScoreRow name="connections" value={lastJsonMessage.openConnections}/>
<ScoreRow name="connections" value={lastJsonMessage.player.openConnections}/>
</tbody>
</table>
</Column>;

View file

@ -14,24 +14,28 @@ export type Scores = {
readonly pixelsMoved: number;
};
type Tank = {
readonly pixelPosition: { x: number; y: number };
readonly orientation: number;
readonly moving: boolean;
readonly bulletStats: BulletStats;
readonly reloadingUntil: string;
readonly nextShotAfter: string;
readonly usedBullets: number;
readonly maxBullets: number;
}
export type Player = {
readonly name: string;
readonly scores: Scores;
};
type TankInfo = {
readonly magazine: string;
readonly position: { x: number; y: number };
readonly orientation: number;
readonly moving: boolean;
readonly openConnections: number;
readonly lastInput: string;
}
export type PlayerInfoMessage = {
readonly name: string;
readonly scores: Scores;
readonly player: Player;
readonly controls: string;
readonly tank?: TankInfo;
readonly openConnections: number;
readonly tank?: Tank;
}
export type MapInfo = {
@ -40,6 +44,13 @@ export type MapInfo = {
readonly preview: string;
}
export type BulletStats = {
speed: number;
acceleration: number,
explosive: boolean,
smart: boolean
};
export function useMyWebSocket<T = unknown>(url: string, options: Options = {}) {
return useWebSocket<T>(url, {
shouldReconnect: () => true,

View file

@ -11,3 +11,5 @@
**/bin
**/Dockerfile*
**/obj
**/target
**/examples

View file

@ -1,42 +0,0 @@
using System.Diagnostics;
namespace DisplayCommands;
public sealed class ByteGrid(ushort width, ushort height) : IEquatable<ByteGrid>
{
public ushort Height { get; } = height;
public ushort Width { get; } = width;
internal Memory<byte> Data { get; } = new byte[width * height].AsMemory();
public byte this[ushort x, ushort y]
{
get => Data.Span[GetIndex(x, y)];
set => Data.Span[GetIndex(x, y)] = value;
}
public bool Equals(ByteGrid? other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Height == other.Height && Width == other.Width && Data.Span.SequenceEqual(other.Data.Span);
}
private int GetIndex(ushort x, ushort y)
{
Debug.Assert(x < Width);
Debug.Assert(y < Height);
return x + y * Width;
}
public void Clear() => Data.Span.Clear();
public override bool Equals(object? obj) => ReferenceEquals(this, obj) || (obj is ByteGrid other && Equals(other));
public override int GetHashCode() => HashCode.Combine(Height, Width, Data);
public static bool operator ==(ByteGrid? left, ByteGrid? right) => Equals(left, right);
public static bool operator !=(ByteGrid? left, ByteGrid? right) => !Equals(left, right);
}

View file

@ -1,71 +0,0 @@
using System.Diagnostics;
using System.Text;
namespace DisplayCommands;
public sealed class Cp437Grid(ushort width, ushort height) : IEquatable<Cp437Grid>
{
private readonly ByteGrid _byteGrid = new(width, height);
private readonly Encoding _encoding = Encoding.GetEncoding(437);
public ushort Height { get; } = height;
public ushort Width { get; } = width;
internal Memory<byte> Data => _byteGrid.Data;
public char this[ushort x, ushort y]
{
get => ByteToChar(_byteGrid[x, y]);
set => _byteGrid[x, y] = CharToByte(value);
}
public string this[ushort row]
{
get
{
var rowStart = row * Width;
return _encoding.GetString(_byteGrid.Data[rowStart..(rowStart + Width)].Span);
}
set
{
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(row, Height, nameof(row));
ArgumentOutOfRangeException.ThrowIfGreaterThan(value.Length, Width, nameof(value));
ushort x = 0;
for (; x < value.Length; x++)
_byteGrid[x, row] = CharToByte(value[x]);
for (; x < Width; x++)
_byteGrid[x, row] = CharToByte(' ');
}
}
private byte CharToByte(char c)
{
ReadOnlySpan<char> valuesStr = stackalloc char[] { c };
Span<byte> convertedStr = stackalloc byte[1];
var consumed = _encoding.GetBytes(valuesStr, convertedStr);
Debug.Assert(consumed == 1);
return convertedStr[0];
}
private char ByteToChar(byte b)
{
ReadOnlySpan<byte> valueBytes = stackalloc byte[] { b };
Span<char> resultStr = stackalloc char[1];
var consumed = _encoding.GetChars(valueBytes, resultStr);
Debug.Assert(consumed == 1);
return resultStr[0];
}
public bool Equals(Cp437Grid? other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Height == other.Height && Width == other.Width && _byteGrid.Equals(other._byteGrid);
}
public override bool Equals(object? obj) => ReferenceEquals(this, obj) || (obj is Cp437Grid other && Equals(other));
public override int GetHashCode() => HashCode.Combine(_byteGrid, Height, Width);
public static bool operator ==(Cp437Grid? left, Cp437Grid? right) => Equals(left, right);
public static bool operator !=(Cp437Grid? left, Cp437Grid? right) => !Equals(left, right);
}

View file

@ -1,23 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="../shared.props" />
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0"/>
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2"/>
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0"/>
<PackageReference Include="System.Text.Encoding.CodePages" Version="8.0.0"/>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1"/>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1"/>
<ProjectReference Include="../EndiannessSourceGenerator/EndiannessSourceGenerator.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false"/>
</ItemGroup>
</Project>

View file

@ -1,25 +0,0 @@
using System.Text;
using DisplayCommands.Internals;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DisplayCommands;
public static class DisplayExtensions
{
static DisplayExtensions()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
public static IServiceCollection AddDisplay(
this IServiceCollection services,
IConfigurationSection? configurationSection = null
)
{
services.AddSingleton<IDisplayConnection, DisplayConnection>();
if (configurationSection != null)
services.Configure<DisplayConfiguration>(configurationSection);
return services;
}
}

View file

@ -1,2 +0,0 @@
global using System;
global using System.Threading.Tasks;

View file

@ -1,24 +0,0 @@
namespace DisplayCommands;
public interface IDisplayConnection
{
ValueTask SendClearAsync();
ValueTask SendCp437DataAsync(ushort x, ushort y, Cp437Grid grid);
ValueTask SendBrightnessAsync(byte brightness);
ValueTask SendCharBrightnessAsync(ushort x, ushort y, ByteGrid luma);
ValueTask SendHardResetAsync();
ValueTask SendFadeOutAsync(byte loops);
public ValueTask SendBitmapLinearWindowAsync(ushort x, ushort y, PixelGrid pixels);
/// <summary>
/// Returns the IPv4 address that is associated with the interface with which the display is reachable.
/// </summary>
/// <returns>IPv4 as text</returns>
public string GetLocalIPv4();
}

View file

@ -1,17 +0,0 @@
namespace DisplayCommands.Internals;
internal enum DisplayCommand : ushort
{
Clear = 0x0002,
Cp437Data = 0x0003,
CharBrightness = 0x0005,
Brightness = 0x0007,
HardReset = 0x000b,
FadeOut = 0x000d,
[Obsolete("ignored by display code")] BitmapLegacy = 0x0010,
BitmapLinear = 0x0012,
BitmapLinearWin = 0x0013,
BitmapLinearAnd = 0x0014,
BitmapLinearOr = 0x0015,
BitmapLinearXor = 0x0016
}

View file

@ -1,126 +0,0 @@
using System.Buffers;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Options;
namespace DisplayCommands.Internals;
internal sealed class DisplayConnection(IOptions<DisplayConfiguration> options) : IDisplayConnection, IDisposable
{
private readonly ArrayPool<byte> _arrayPool = ArrayPool<byte>.Shared;
private readonly UdpClient _udpClient = new(options.Value.Hostname, options.Value.Port);
public ValueTask SendClearAsync()
{
var header = new HeaderWindow { Command = (ushort)DisplayCommand.Clear };
return SendAsync(header, Memory<byte>.Empty);
}
public ValueTask SendCp437DataAsync(ushort x, ushort y, Cp437Grid grid)
{
var header = new HeaderWindow
{
Command = (ushort)DisplayCommand.Cp437Data,
Height = grid.Height,
Width = grid.Width,
PosX = x,
PosY = y
};
return SendAsync(header, grid.Data);
}
public ValueTask SendCharBrightnessAsync(ushort x, ushort y, ByteGrid luma)
{
var header = new HeaderWindow
{
Command = (ushort)DisplayCommand.CharBrightness,
PosX = x,
PosY = y,
Height = luma.Height,
Width = luma.Width
};
return SendAsync(header, luma.Data);
}
public async ValueTask SendBrightnessAsync(byte brightness)
{
var header = new HeaderWindow { Command = (ushort)DisplayCommand.Brightness };
var payloadBuffer = _arrayPool.Rent(1);
var payload = payloadBuffer.AsMemory(0, 1);
payload.Span[0] = brightness;
await SendAsync(header, payload);
_arrayPool.Return(payloadBuffer);
}
public ValueTask SendHardResetAsync()
{
var header = new HeaderWindow { Command = (ushort)DisplayCommand.HardReset };
return SendAsync(header, Memory<byte>.Empty);
}
public async ValueTask SendFadeOutAsync(byte loops)
{
var header = new HeaderWindow { Command = (ushort)DisplayCommand.FadeOut };
var payloadBuffer = _arrayPool.Rent(1);
var payload = payloadBuffer.AsMemory(0, 1);
payload.Span[0] = loops;
await SendAsync(header, payload);
_arrayPool.Return(payloadBuffer);
}
public ValueTask SendBitmapLinearWindowAsync(ushort x, ushort y, PixelGrid pixels)
{
var header = new HeaderWindow
{
Command = (ushort)DisplayCommand.BitmapLinearWin,
PosX = x,
PosY = y,
Width = (ushort)(pixels.Width / 8),
Height = pixels.Height
};
return SendAsync(header, pixels.Data);
}
public string GetLocalIPv4()
{
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0);
socket.Connect(options.Value.Hostname, options.Value.Port);
var endPoint = socket.LocalEndPoint as IPEndPoint ?? throw new NotSupportedException();
return endPoint.Address.ToString();
}
private async ValueTask SendAsync(HeaderWindow header, Memory<byte> payload)
{
int headerSize;
unsafe
{
// because we specified the struct layout, no platform-specific padding will be added and this is be safe.
headerSize = sizeof(HeaderWindow);
}
Debug.Assert(headerSize == 10);
var messageSize = headerSize + payload.Length;
var buffer = _arrayPool.Rent(messageSize);
var message = buffer.AsMemory(0, messageSize);
MemoryMarshal.Write(message.Span, header);
payload.CopyTo(message[headerSize..]);
await _udpClient.SendAsync(message);
_arrayPool.Return(buffer);
}
public void Dispose() => _udpClient.Dispose();
}

View file

@ -1,10 +0,0 @@
namespace DisplayCommands.Internals;
internal enum DisplaySubCommand : ushort
{
BitmapNormal = 0x0,
BitmapCompressZ = 0x677a,
BitmapCompressBz = 0x627a,
BitmapCompressLz = 0x6c7a,
BitmapCompressZs = 0x7a73
}

View file

@ -1,19 +0,0 @@
using System.Runtime.InteropServices;
using EndiannessSourceGenerator;
namespace DisplayCommands.Internals;
[StructEndianness(IsLittleEndian = false)]
[StructLayout(LayoutKind.Sequential, Pack = 16, Size = 10)]
internal partial struct HeaderBitmap
{
private ushort _command;
private ushort _offset;
private ushort _length;
private ushort _subCommand;
private ushort _reserved;
}

View file

@ -1,19 +0,0 @@
using System.Runtime.InteropServices;
using EndiannessSourceGenerator;
namespace DisplayCommands.Internals;
[StructEndianness(IsLittleEndian = false)]
[StructLayout(LayoutKind.Sequential, Pack = 16, Size = 10)]
internal partial struct HeaderWindow
{
private ushort _command;
private ushort _posX;
private ushort _posY;
private ushort _width;
private ushort _height;
}

View file

@ -1,59 +0,0 @@
using System.Diagnostics;
namespace DisplayCommands;
public sealed class PixelGrid(ushort width, ushort height) : IEquatable<PixelGrid>
{
private readonly ByteGrid _byteGrid = new((ushort)(width / 8u), height);
public ushort Width { get; } = width;
public ushort Height { get; } = height;
public Memory<byte> Data => _byteGrid.Data;
public bool this[ushort x, ushort y]
{
get
{
Debug.Assert(y < Height);
var (byteIndex, bitInByteMask) = GetIndexes(x);
var byteVal = _byteGrid[byteIndex, y];
return (byteVal & bitInByteMask) != 0;
}
set
{
Debug.Assert(y < Height);
var (byteIndex, bitInByteMask) = GetIndexes(x);
if (value)
_byteGrid[byteIndex, y] |= bitInByteMask;
else
_byteGrid[byteIndex, y] &= (byte)(ushort.MaxValue ^ bitInByteMask);
}
}
public void Clear() => _byteGrid.Clear();
public bool Equals(PixelGrid? other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Width == other.Width && Height == other.Height && _byteGrid.Equals(other._byteGrid);
}
public override bool Equals(object? obj) => ReferenceEquals(this, obj) || (obj is PixelGrid other && Equals(other));
public override int GetHashCode() => HashCode.Combine(_byteGrid, Width, Height);
public static bool operator ==(PixelGrid? left, PixelGrid? right) => Equals(left, right);
public static bool operator !=(PixelGrid? left, PixelGrid? right) => !Equals(left, right);
private (ushort byteIndex, byte bitInByteMask) GetIndexes(int x)
{
Debug.Assert(x < Width);
var byteIndex = (ushort)(x / 8);
Debug.Assert(byteIndex < Width);
var bitInByteIndex = (byte)(7 - x % 8);
Debug.Assert(bitInByteIndex < 8);
var bitInByteMask = (byte)(1 << bitInByteIndex);
return (byteIndex, bitInByteMask);
}
}

View file

@ -1,18 +1,10 @@
FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build-server
RUN apk add clang binutils musl-dev build-base zlib-static cmake openssl-dev openssl-libs-static openssl
RUN apk add rust cargo
WORKDIR /src/tanks-server
# dependencies
COPY ./shared.props .
COPY ./TanksServer.sln .
COPY ./EndiannessSourceGenerator/EndiannessSourceGenerator.csproj EndiannessSourceGenerator/EndiannessSourceGenerator.csproj
COPY ./DisplayCommands/DisplayCommands.csproj DisplayCommands/DisplayCommands.csproj
COPY ./TanksServer/TanksServer.csproj TanksServer/TanksServer.csproj
RUN dotnet restore --runtime linux-musl-x64 TanksServer.sln
#build
COPY . .
RUN dotnet build TanksServer/TanksServer.csproj -c Release -r linux-musl-x64 -o /build
RUN dotnet publish TanksServer/TanksServer.csproj -c Release -r linux-musl-x64 -o /app

View file

@ -1,260 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace EndiannessSourceGenerator;
internal class DebugMeException(string message) : Exception(message);
internal class InvalidUsageException(string message) : Exception(message);
[Generator]
public class StructEndiannessSourceGenerator : ISourceGenerator
{
private const string Namespace = "EndiannessSourceGenerator";
private const string AttributeName = "StructEndiannessAttribute";
private const string IsLittleEndianProperty = "IsLittleEndian";
private const string AttributeSourceCode =
$$"""
// <auto-generated/>
namespace {{Namespace}}
{
[System.AttributeUsage(System.AttributeTargets.Struct)]
public class {{AttributeName}}: System.Attribute
{
public required bool {{IsLittleEndianProperty}} { get; init; }
}
}
""";
public void Initialize(GeneratorInitializationContext context)
{
// Register the attribute source
context.RegisterForPostInitialization(i => i.AddSource($"{AttributeName}.g.cs", AttributeSourceCode));
}
public void Execute(GeneratorExecutionContext context)
{
var treesWithStructsWithAttributes = context.Compilation.SyntaxTrees
.Where(st => st.GetRoot().DescendantNodes()
.OfType<StructDeclarationSyntax>()
.Any(p => p.DescendantNodes()
.OfType<AttributeSyntax>()
.Any()))
.ToList();
foreach (var tree in treesWithStructsWithAttributes)
{
var semanticModel = context.Compilation.GetSemanticModel(tree);
var structsWithAttributes = tree.GetRoot().DescendantNodes()
.OfType<StructDeclarationSyntax>()
.Where(cd => cd.DescendantNodes()
.OfType<AttributeSyntax>()
.Any());
foreach (var structDeclaration in structsWithAttributes)
{
var foundAttribute = GetEndiannessAttribute(structDeclaration, semanticModel);
if (foundAttribute == null)
continue; // not my type
var structIsLittleEndian = GetStructIsLittleEndian(foundAttribute);
HandleStruct(context, structDeclaration, semanticModel, structIsLittleEndian);
}
}
}
private static void HandleStruct(GeneratorExecutionContext context, TypeDeclarationSyntax structDeclaration,
SemanticModel semanticModel, bool structIsLittleEndian)
{
var isPartial = structDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.PartialKeyword));
if (!isPartial)
throw new InvalidUsageException("struct is not marked partial");
var accessibilityModifier = structDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.InternalKeyword))
? Token(SyntaxKind.InternalKeyword)
: Token(SyntaxKind.PublicKeyword);
var structType = semanticModel.GetDeclaredSymbol(structDeclaration);
if (structType == null)
throw new DebugMeException("struct type info is null");
var structNamespace = structType.ContainingNamespace?.ToDisplayString();
if (structNamespace == null)
throw new InvalidUsageException("struct has to be contained in a namespace");
if (structDeclaration.Members.Any(m => m.IsKind(SyntaxKind.PropertyDeclaration)))
throw new InvalidUsageException("struct cannot have properties");
var fieldDeclarations = structDeclaration.Members
.Where(m => m.IsKind(SyntaxKind.FieldDeclaration)).OfType<FieldDeclarationSyntax>();
var generatedCode = CompilationUnit()
.WithUsings(List<UsingDirectiveSyntax>([
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.Buffers.Binary"))
]))
.WithMembers(List<MemberDeclarationSyntax>([
FileScopedNamespaceDeclaration(IdentifierName(structNamespace)),
StructDeclaration(structType.Name)
.WithModifiers(TokenList([accessibilityModifier, Token(SyntaxKind.PartialKeyword)]))
.WithMembers(GenerateStructProperties(fieldDeclarations, semanticModel, structIsLittleEndian))
]))
.NormalizeWhitespace()
.ToFullString();
context.AddSource(
$"{structNamespace}.{structType.Name}.g.cs",
SourceText.From(generatedCode, Encoding.UTF8)
);
}
private static SyntaxList<MemberDeclarationSyntax> GenerateStructProperties(
IEnumerable<FieldDeclarationSyntax> fieldDeclarations, SemanticModel semanticModel, bool structIsLittleEndian)
{
var result = new List<MemberDeclarationSyntax>();
foreach (var field in fieldDeclarations)
{
if (!field.Modifiers.Any(m => m.IsKind(SyntaxKind.PrivateKeyword)))
throw new InvalidUsageException("fields have to be private");
var variableDeclaration = field.DescendantNodes()
.OfType<VariableDeclarationSyntax>()
.FirstOrDefault();
if (variableDeclaration == null)
throw new DebugMeException("variable declaration of field declaration null");
var variableTypeInfo = semanticModel.GetTypeInfo(variableDeclaration.Type).Type;
if (variableTypeInfo == null)
throw new DebugMeException("variable type info of field declaration null");
var typeName = variableTypeInfo.ToDisplayString();
var fieldName = variableDeclaration.Variables.First().Identifier.ToString();
result.Add(GenerateProperty(typeName, structIsLittleEndian, fieldName));
}
return new SyntaxList<MemberDeclarationSyntax>(result);
}
private static PropertyDeclarationSyntax GenerateProperty(string typeName,
bool structIsLittleEndian, string fieldName)
{
var propertyName = GeneratePropertyName(fieldName);
var fieldIdentifier = IdentifierName(fieldName);
ExpressionSyntax condition = MemberAccessExpression(
kind: SyntaxKind.SimpleMemberAccessExpression,
expression: IdentifierName("BitConverter"),
name: IdentifierName("IsLittleEndian")
);
if (!structIsLittleEndian)
condition = PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, condition);
var reverseEndiannessMethod = MemberAccessExpression(
kind: SyntaxKind.SimpleMemberAccessExpression,
expression: IdentifierName("BinaryPrimitives"),
name: IdentifierName("ReverseEndianness")
);
var valueIdentifier = IdentifierName("value");
return PropertyDeclaration(ParseTypeName(typeName), propertyName)
.WithModifiers(TokenList([Token(SyntaxKind.PublicKeyword)]))
.WithAccessorList(AccessorList(List<AccessorDeclarationSyntax>([
AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
.WithExpressionBody(ArrowExpressionClause(ConditionalExpression(
condition: condition,
whenTrue: fieldIdentifier,
whenFalse: InvocationExpression(
expression: reverseEndiannessMethod,
argumentList: ArgumentList(SingletonSeparatedList(
Argument(fieldIdentifier)
))
)
)))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken)),
AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
.WithExpressionBody(ArrowExpressionClause(AssignmentExpression(
kind: SyntaxKind.SimpleAssignmentExpression,
left: fieldIdentifier,
right: ConditionalExpression(
condition: condition,
whenTrue: valueIdentifier,
whenFalse: InvocationExpression(
expression: reverseEndiannessMethod,
argumentList: ArgumentList(SingletonSeparatedList(
Argument(valueIdentifier)
))
)
)
)))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
]))
);
}
private static SyntaxToken GeneratePropertyName(string fieldName)
{
var propertyName = fieldName;
if (propertyName.StartsWith("_"))
propertyName = propertyName.Substring(1);
if (!char.IsLetter(propertyName, 0) || char.IsUpper(propertyName, 0))
throw new InvalidUsageException("field names have to start with a lower case letter");
propertyName = propertyName.Substring(0, 1).ToUpperInvariant()
+ propertyName.Substring(1);
return Identifier(propertyName);
}
private static AttributeSyntax? GetEndiannessAttribute(SyntaxNode structDeclaration, SemanticModel semanticModel)
{
AttributeSyntax? foundAttribute = null;
foreach (var attributeSyntax in structDeclaration.DescendantNodes().OfType<AttributeSyntax>())
{
var attributeTypeInfo = semanticModel.GetTypeInfo(attributeSyntax).Type;
if (attributeTypeInfo == null)
throw new DebugMeException("attribute type info is null");
if (attributeTypeInfo.ContainingNamespace?.Name != Namespace)
continue;
if (attributeTypeInfo.Name != AttributeName)
continue;
foundAttribute = attributeSyntax;
break;
}
return foundAttribute;
}
private static bool GetStructIsLittleEndian(AttributeSyntax foundAttribute)
{
var endiannessArguments = foundAttribute.ArgumentList;
if (endiannessArguments == null)
throw new InvalidUsageException("endianness attribute has no arguments");
var isLittleEndianArgumentSyntax = endiannessArguments.Arguments
.FirstOrDefault(argumentSyntax =>
argumentSyntax.NameEquals?.Name.Identifier.ToString() == IsLittleEndianProperty);
if (isLittleEndianArgumentSyntax == null)
throw new InvalidUsageException("endianness attribute argument not found");
bool? structIsLittleEndian = isLittleEndianArgumentSyntax.Expression.Kind() switch
{
SyntaxKind.FalseLiteralExpression => false,
SyntaxKind.TrueLiteralExpression => true,
SyntaxKind.DefaultLiteralExpression => false,
_ => throw new InvalidUsageException($"{IsLittleEndianProperty} has to be set with a literal")
};
return structIsLittleEndian.Value;
}
}

View file

@ -1,25 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="../shared.props" />
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<IsRoslynComponent>true</IsRoslynComponent>
<PackageId>EndiannessSourceGenerator</PackageId>
<IsAotCompatible>false</IsAotCompatible>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.9.2" PrivateAssets="all" />
</ItemGroup>
</Project>

Some files were not shown because too many files have changed in this diff Show more