//
// StringInlineConverterGenerator.cs
//
// Copyright (c) František Boháček. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.CodeDom.Compiler;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NosSmooth.PacketSerializersGenerator.Data;
using NosSmooth.PacketSerializersGenerator.Errors;
using NosSmooth.PacketSerializersGenerator.Extensions;
namespace NosSmooth.PacketSerializersGenerator.InlineConverterGenerators;
///
public class StringInlineConverterGenerator : IInlineConverterGenerator
{
///
public bool ShouldHandle(TypeSyntax? typeSyntax, ITypeSymbol? typeSymbol)
=> typeSyntax?.ToString().TrimEnd('?') == "string" || typeSymbol?.ToString().TrimEnd('?') == "string";
///
public IError? GenerateSerializerPart(IndentedTextWriter textWriter, string variableName, TypeSyntax? typeSyntax, ITypeSymbol? typeSymbol)
{
textWriter.WriteLine($"builder.Append({variableName} ?? \"-\");");
return null;
}
///
public IError? CallDeserialize(IndentedTextWriter textWriter, TypeSyntax? typeSyntax, ITypeSymbol? typeSymbol, bool nullable)
{
textWriter.WriteLine($"{Constants.HelperClass}.ParseString(ref stringEnumerator, {nullable.ToString().ToLower()});");
return null;
}
///
public void GenerateHelperMethods(IndentedTextWriter textWriter)
{
textWriter.WriteLine
(
@"
public static Result ParseString(ref PacketStringEnumerator stringEnumerator, bool nullable)
{{
var tokenResult = stringEnumerator.GetNextToken(out var packetToken);
if (!tokenResult.IsSuccess)
{{
return Result.FromError(tokenResult);
}}
if (nullable)
{{
if (packetToken.Token.Length == 1 && packetToken.Token[0] == '-')
{{
return Result.FromSuccess(null);
}}
}}
return packetToken.Token.ToString();
}}
"
);
}
}