Skip to content

Commit 7dd3942

Browse files
authored
Merge pull request #1 from ProjektMing/accessibility-fix
Ensure generated converters match source type accessibility
2 parents 6c8f5d1 + 6dd9047 commit 7dd3942

File tree

2 files changed

+62
-76
lines changed

2 files changed

+62
-76
lines changed

sandbox/ConsoleApp1/Program.cs

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,6 @@
11
using Cysharp.AI;
2-
using Cysharp.AI.Internal;
3-
using System.Buffers;
4-
using System.Collections.Generic;
5-
using System.Data;
6-
using System.IO.Pipelines;
7-
using System.Text;
8-
using System.Text.Json;
9-
using System.Text.Json.Serialization;
10-
using System.Xml.Linq;
11-
12-
13-
var item = new Item
14-
{
15-
Status = "OK",
16-
Users = [new(1, "Alice", "Admin"), new(2, "Bob", "User")]
17-
};
2+
3+
var item = new Item { Status = "OK", Users = [new(1, "Alice", "Admin"), new(2, "Bob", "User")] };
184

195
var toon = Cysharp.AI.Converters.ItemSimpleObjectConverter.Encode(item);
206

@@ -24,20 +10,18 @@
2410
// 2,Bob,User
2511
Console.WriteLine(toon);
2612

27-
2813
[GenerateToonSimpleObjectConverter]
29-
public record Item
14+
record Item
3015
{
3116
public required string Status { get; init; }
3217
public required User[] Users { get; init; }
3318
}
3419

3520
[GenerateToonTabularArrayConverter]
36-
public record User(int Id, string Name, string Role);
37-
21+
record User(int Id, string Name, string Role);
3822

3923
[GenerateToonSimpleObjectConverter]
40-
public class SimpleClass
24+
class SimpleClass
4125
{
4226
public int Id { get; set; }
4327
public string? Name { get; set; }
@@ -48,13 +32,14 @@ public class SimpleClass
4832
// public User2 MyProperty1000 { get; set; }
4933
}
5034

51-
52-
public enum MyEnum
35+
enum MyEnum
5336
{
54-
Fruit, Orange, Apple
37+
Fruit,
38+
Orange,
39+
Apple,
5540
}
5641

57-
public class User2
42+
class User2
5843
{
5944
public List<int>? MyProperty2 { get; set; }
6045
}

src/ToonEncoder.Generator/ToonEncoderGenerator.cs

Lines changed: 52 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
using Microsoft.CodeAnalysis;
2-
using Microsoft.CodeAnalysis.Text;
3-
using System.Diagnostics.CodeAnalysis;
1+
using System.Diagnostics.CodeAnalysis;
42
using System.Text;
3+
using Microsoft.CodeAnalysis;
4+
using Microsoft.CodeAnalysis.CSharp;
5+
using Microsoft.CodeAnalysis.Text;
56

67
namespace Cysharp.AI;
78

@@ -13,34 +14,34 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
1314
context.RegisterPostInitializationOutput(EmitAttributes);
1415

1516
var tabularArray = context.SyntaxProvider.ForAttributeWithMetadataName("Cysharp.AI.GenerateToonTabularArrayConverterAttribute",
16-
(node, cancellationToken) => true,
17-
(context, cancellationToken) =>
18-
{
19-
if (context.TargetSymbol is ITypeSymbol typeSymbol)
17+
(node, cancellationToken) => true,
18+
(context, cancellationToken) =>
2019
{
21-
return new ToonObjectInfo(typeSymbol);
22-
}
23-
else
24-
{
25-
return null;
26-
}
20+
if (context.TargetSymbol is ITypeSymbol typeSymbol)
21+
{
22+
return new ToonObjectInfo(typeSymbol);
23+
}
24+
else
25+
{
26+
return null;
27+
}
2728
})
2829
.Where(x => x != null);
2930

3031
context.RegisterSourceOutput(tabularArray, EmitTabularArrayConverter!);
3132

3233
var simpleObject = context.SyntaxProvider.ForAttributeWithMetadataName("Cysharp.AI.GenerateToonSimpleObjectConverterAttribute",
33-
(node, cancellationToken) => true,
34-
(context, cancellationToken) =>
35-
{
36-
if (context.TargetSymbol is ITypeSymbol typeSymbol)
34+
(node, cancellationToken) => true,
35+
(context, cancellationToken) =>
3736
{
38-
return new ToonObjectInfo(typeSymbol);
39-
}
40-
else
41-
{
42-
return null;
43-
}
37+
if (context.TargetSymbol is ITypeSymbol typeSymbol)
38+
{
39+
return new ToonObjectInfo(typeSymbol);
40+
}
41+
else
42+
{
43+
return null;
44+
}
4445
})
4546
.Where(x => x != null);
4647

@@ -83,23 +84,23 @@ static void EmitTabularArrayConverter(SourceProductionContext sourceProductionCo
8384
{
8485
return;
8586
}
86-
87+
var accessible = objectInfo.AccessibilityKeyWord;
8788
var converterName = $"{objectInfo.ElementFullName.Replace("global::", "").Replace(".", "_")}TabularArrayConverter";
8889
var arrayType = $"{objectInfo.ElementFullName}[]?";
8990
var utf8FieldNames = string.Join(", ", objectInfo.PropertyNames.Select(n => $"\"{n}\"u8.ToArray()"));
9091
var encodeRow = string.Join("\n", objectInfo.PropertyNames.Select((name, index) =>
91-
{
92-
var kind = objectInfo.PropertyKinds![index];
93-
var str = kind switch
94-
{
95-
ToonPrimitiveKind.Boolean => $"toonWriter.WriteBoolean(item.{name});",
96-
ToonPrimitiveKind.String => $"toonWriter.WriteString(item.{name});",
97-
ToonPrimitiveKind.Number => $"toonWriter.WriteNumber(item.{name});",
92+
{
93+
var kind = objectInfo.PropertyKinds![index];
94+
var str = kind switch
95+
{
96+
ToonPrimitiveKind.Boolean => $"toonWriter.WriteBoolean(item.{name});",
97+
ToonPrimitiveKind.String => $"toonWriter.WriteString(item.{name});",
98+
ToonPrimitiveKind.Number => $"toonWriter.WriteNumber(item.{name});",
9899
ToonPrimitiveKind.NullableBoolean => $"if (item.{name} == null) {{ toonWriter.WriteNull(); }} else {{ toonWriter.WriteBoolean(item.{name}); }}",
99100
ToonPrimitiveKind.NullableNumber => $"if (item.{name} == null) {{ toonWriter.WriteNull(); }} else {{ toonWriter.WriteNumber(item.{name}); }}",
100101
ToonPrimitiveKind.NullableString => $"if (item.{name} == null) {{ toonWriter.WriteNull(); }} else {{ toonWriter.WriteString(item.{name}); }}",
101102
_ => throw new NotSupportedException($"Unsupported property type for Toon serialization: {kind}"),
102-
};
103+
};
103104
return " "/* indent */ + str;
104105
}));
105106

@@ -121,7 +122,7 @@ static void EmitTabularArrayConverter(SourceProductionContext sourceProductionCo
121122
122123
namespace Cysharp.AI.Converters
123124
{
124-
public class {{converterName}} : JsonConverter<{{arrayType}}>
125+
{{accessible}} class {{converterName}} : JsonConverter<{{arrayType}}>
125126
{
126127
static readonly ReadOnlyMemory<byte>[] utf8FieldNames = [{{utf8FieldNames}}];
127128
@@ -241,6 +242,7 @@ static void EmitSimpleObjectConverter(SourceProductionContext sourceProductionCo
241242

242243
const string defaultIndent = " ";
243244
var encodeRow = new StringBuilder();
245+
var accessible = objectInfo.AccessibilityKeyWord;
244246
for (int i = 0; i < objectInfo.PropertyNames!.Length; i++)
245247
{
246248
var name = objectInfo.PropertyNames[i];
@@ -355,7 +357,7 @@ void EmitValueLine(string instanceName, string propertyName, ToonPrimitiveKind k
355357
356358
namespace Cysharp.AI.Converters
357359
{
358-
public class {{converterName}} : JsonConverter<{{objectType}}>
360+
{{accessible}} class {{converterName}} : JsonConverter<{{objectType}}>
359361
{
360362
{{utf8FieldNamesDeclaration}}
361363
@@ -450,6 +452,7 @@ public Location CreateLocation()
450452

451453
public record ToonObjectInfo
452454
{
455+
public string AccessibilityKeyWord { get; }
453456
public string ElementFullName { get; }
454457
public bool IsReferenceType { get; }
455458
public LocationSlim Location { get; }
@@ -467,6 +470,7 @@ public record ToonObjectInfo
467470

468471
public ToonObjectInfo(ITypeSymbol symbol)
469472
{
473+
AccessibilityKeyWord = SyntaxFacts.GetText(symbol.DeclaredAccessibility);
470474
ElementFullName = symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
471475
IsReferenceType = symbol.IsReferenceType;
472476

@@ -501,9 +505,9 @@ public ToonObjectInfo(ITypeSymbol symbol)
501505
})
502506
.ToArray();
503507

504-
PropertyNames = nameAndKinds.Select(x => x.Name).ToArray();
505-
PropertyKinds = nameAndKinds.Select(x => x.Kind).ToArray();
506-
NestedArrayInfos = nameAndKinds.Select(x => x.NestedInfo!).ToArray();
508+
PropertyNames = [.. nameAndKinds.Select(x => x.Name)];
509+
PropertyKinds = [.. nameAndKinds.Select(x => x.Kind)];
510+
NestedArrayInfos = [.. nameAndKinds.Select(x => x.NestedInfo!)];
507511

508512
static (ToonPrimitiveKind, ToonObjectInfo?) GetToonPrimitive(ITypeSymbol t)
509513
{
@@ -613,11 +617,11 @@ public bool VerifyTabularArray(SourceProductionContext sourceProductionContext)
613617
if (hasUnsupported)
614618
{
615619
sourceProductionContext.ReportDiagnostic(Diagnostic.Create(new DiagnosticDescriptor(
616-
"TEG001",
617-
"Unsupported Property Type for Toon Tabular Array Converter",
618-
$"The property type is not supported for Toon Tabular Array serialization in {ElementFullName.Replace("global::", "")}.{string.Join(", ", unsupportedPropertyNames ?? [])}.",
619-
"ToonEncoderGenerator",
620-
DiagnosticSeverity.Error,
620+
"TEG001",
621+
"Unsupported Property Type for Toon Tabular Array Converter",
622+
$"The property type is not supported for Toon Tabular Array serialization in {ElementFullName.Replace("global::", "")}.{string.Join(", ", unsupportedPropertyNames ?? [])}.",
623+
"ToonEncoderGenerator",
624+
DiagnosticSeverity.Error,
621625
isEnabledByDefault: true), Location.CreateLocation()));
622626

623627
return false;
@@ -641,10 +645,7 @@ public bool VerifySimpleObject(SourceProductionContext sourceProductionContext)
641645
{
642646
void AddUnsupported()
643647
{
644-
if (unsupportedPropertyNames == null)
645-
{
646-
unsupportedPropertyNames = new List<string>();
647-
}
648+
unsupportedPropertyNames ??= [];
648649
unsupportedPropertyNames.Add(PropertyNames![i]);
649650
hasUnsupported = true;
650651
}
@@ -683,11 +684,11 @@ void AddUnsupported()
683684
if (hasUnsupported)
684685
{
685686
sourceProductionContext.ReportDiagnostic(Diagnostic.Create(new DiagnosticDescriptor(
686-
"TEG002",
687-
"Unsupported Property Type for Toon Simple Object Converter",
688-
$"The property type is not supported for Toon Simple Object serialization in {ElementFullName.Replace("global::", "")}.{string.Join(", ", unsupportedPropertyNames)}. Property must be toon-primitive or primitive-array or tabular-array convertible array.",
689-
"ToonEncoderGenerator",
690-
DiagnosticSeverity.Error,
687+
"TEG002",
688+
"Unsupported Property Type for Toon Simple Object Converter",
689+
$"The property type is not supported for Toon Simple Object serialization in {ElementFullName.Replace("global::", "")}.{string.Join(", ", unsupportedPropertyNames)}. Property must be toon-primitive or primitive-array or tabular-array convertible array.",
690+
"ToonEncoderGenerator",
691+
DiagnosticSeverity.Error,
691692
isEnabledByDefault: true), Location.CreateLocation()));
692693

693694
return false;

0 commit comments

Comments
 (0)