Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 25 additions & 29 deletions src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ private string GenerateFastPathFuncForEnumerable(TypeGenerationSpec typeGenerati
}

string elementSerializationLogic = writerMethodToCall == null
? GetSerializeLogicForNonPrimitiveType(valueTypeGenerationSpec.TypeInfoPropertyName, valueToWrite, valueTypeGenerationSpec.GenerateSerializationLogic)
? GetSerializeLogicForNonPrimitiveType(valueTypeGenerationSpec, valueToWrite)
: $"{writerMethodToCall}Value({valueToWrite});";

string serializationLogic = $@"{WriterVarName}.WriteStartArray();
Expand All @@ -571,11 +571,7 @@ private string GenerateFastPathFuncForEnumerable(TypeGenerationSpec typeGenerati

{WriterVarName}.WriteEndArray();";

return GenerateFastPathFuncForType(
$"{typeGenerationSpec.TypeInfoPropertyName}{SerializeHandlerPropName}",
typeGenerationSpec.TypeRef,
serializationLogic,
typeGenerationSpec.CanBeNull);
return GenerateFastPathFuncForType(typeGenerationSpec, serializationLogic, emitNullCheck: typeGenerationSpec.CanBeNull);
}

private string GenerateFastPathFuncForDictionary(TypeGenerationSpec typeGenerationSpec)
Expand Down Expand Up @@ -603,7 +599,7 @@ private string GenerateFastPathFuncForDictionary(TypeGenerationSpec typeGenerati
else
{
elementSerializationLogic = $@"{WriterVarName}.WritePropertyName({keyToWrite});
{GetSerializeLogicForNonPrimitiveType(valueTypeGenerationSpec.TypeInfoPropertyName, valueToWrite, valueTypeGenerationSpec.GenerateSerializationLogic)}";
{GetSerializeLogicForNonPrimitiveType(valueTypeGenerationSpec, valueToWrite)}";
}

string serializationLogic = $@"{WriterVarName}.WriteStartObject();
Expand All @@ -615,11 +611,7 @@ private string GenerateFastPathFuncForDictionary(TypeGenerationSpec typeGenerati

{WriterVarName}.WriteEndObject();";

return GenerateFastPathFuncForType(
$"{typeGenerationSpec.TypeInfoPropertyName}{SerializeHandlerPropName}",
typeGenerationSpec.TypeRef,
serializationLogic,
typeGenerationSpec.CanBeNull);
return GenerateFastPathFuncForType(typeGenerationSpec, serializationLogic, emitNullCheck: typeGenerationSpec.CanBeNull);
}

private string GenerateForObject(TypeGenerationSpec typeMetadata)
Expand Down Expand Up @@ -729,7 +721,7 @@ private string GeneratePropMetadataInitFunc(TypeGenerationSpec typeGenerationSpe
string getterValue = memberMetadata switch
{
{ DefaultIgnoreCondition: JsonIgnoreCondition.Always } => "null",
{ CanUseGetter: true } => $"static (obj) => (({declaringTypeCompilableName})obj).{clrPropertyName}",
{ CanUseGetter: true } => $"static (obj) => (({declaringTypeCompilableName})obj).{clrPropertyName}{(memberMetadata.TypeGenerationSpec.CanContainNullableReferenceAnnotations ? "!" : "")}",
{ CanUseGetter: false, HasJsonInclude: true }
=> @$"static (obj) => throw new {InvalidOperationExceptionTypeRef}(""{string.Format(ExceptionMessages.InaccessibleJsonIncludePropertiesNotSupported, typeGenerationSpec.Type.Name, memberMetadata.ClrName)}"")",
_ => "null"
Expand Down Expand Up @@ -836,7 +828,6 @@ private string GenerateFastPathFuncForObject(TypeGenerationSpec typeGenSpec)
{
JsonSourceGenerationOptionsAttribute options = _currentContext.GenerationOptions;
string typeRef = typeGenSpec.TypeRef;
string serializeMethodName = $"{typeGenSpec.TypeInfoPropertyName}{SerializeHandlerPropName}";

if (!typeGenSpec.TryFilterSerializableProps(
options,
Expand All @@ -845,11 +836,9 @@ private string GenerateFastPathFuncForObject(TypeGenerationSpec typeGenSpec)
{
string exceptionMessage = string.Format(ExceptionMessages.InvalidSerializablePropertyConfiguration, typeRef);

return GenerateFastPathFuncForType(
serializeMethodName,
typeRef,
return GenerateFastPathFuncForType(typeGenSpec,
$@"throw new {InvalidOperationExceptionTypeRef}(""{exceptionMessage}"");",
canBeNull: false); // Skip null check since we want to throw an exception straightaway.
emitNullCheck: false); // Skip null check since we want to throw an exception straightaway.
}

StringBuilder sb = new();
Expand Down Expand Up @@ -905,7 +894,7 @@ private string GenerateFastPathFuncForObject(TypeGenerationSpec typeGenSpec)
{
serializationLogic = $@"
{WriterVarName}.WritePropertyName({propVarName});
{GetSerializeLogicForNonPrimitiveType(propertyTypeSpec.TypeInfoPropertyName, propValue, propertyTypeSpec.GenerateSerializationLogic)}";
{GetSerializeLogicForNonPrimitiveType(propertyTypeSpec, propValue)}";
}

JsonIgnoreCondition ignoreCondition = propertyGenSpec.DefaultIgnoreCondition ?? options.DefaultIgnoreCondition;
Expand Down Expand Up @@ -939,7 +928,7 @@ private string GenerateFastPathFuncForObject(TypeGenerationSpec typeGenSpec)
sb.Append($@"((global::{JsonConstants.IJsonOnSerializedFullName}){ValueVarName}).OnSerialized();");
};

return GenerateFastPathFuncForType(serializeMethodName, typeRef, sb.ToString(), typeGenSpec.CanBeNull);
return GenerateFastPathFuncForType(typeGenSpec, sb.ToString(), emitNullCheck: typeGenSpec.CanBeNull);
}

private static bool ShouldIncludePropertyForFastPath(PropertyGenerationSpec propertyGenSpec, JsonSourceGenerationOptionsAttribute options)
Expand Down Expand Up @@ -1039,14 +1028,20 @@ static string GetParamUnboxing(ParameterGenerationSpec spec, int index)
return method;
}

private string GenerateFastPathFuncForType(string serializeMethodName, string typeInfoTypeRef, string serializationLogic, bool canBeNull)
private string GenerateFastPathFuncForType(TypeGenerationSpec typeGenSpec, string serializeMethodBody, bool emitNullCheck)
{
Debug.Assert(!emitNullCheck || typeGenSpec.CanBeNull);

string serializeMethodName = $"{typeGenSpec.TypeInfoPropertyName}{SerializeHandlerPropName}";
// fast path serializers for reference types always support null inputs.
string valueTypeRef = $"{typeGenSpec.TypeRef}{(typeGenSpec.IsValueType ? "" : "?")}";

return $@"

private static void {serializeMethodName}({Utf8JsonWriterTypeRef} {WriterVarName}, {typeInfoTypeRef} {ValueVarName})
private static void {serializeMethodName}({Utf8JsonWriterTypeRef} {WriterVarName}, {valueTypeRef} {ValueVarName})
{{
{GetEarlyNullCheckSource(canBeNull)}
{serializationLogic}
{GetEarlyNullCheckSource(emitNullCheck)}
{serializeMethodBody}
}}";
}

Expand All @@ -1062,16 +1057,17 @@ private string GetEarlyNullCheckSource(bool canBeNull)
: null;
}

private string GetSerializeLogicForNonPrimitiveType(string typeInfoPropertyName, string valueToWrite, bool serializationLogicGenerated)
private string GetSerializeLogicForNonPrimitiveType(TypeGenerationSpec typeGenerationSpec, string valueExpr)
{
string typeInfoRef = $"{_currentContext.ContextTypeRef}.Default.{typeInfoPropertyName}";
string valueExprSuffix = typeGenerationSpec.CanContainNullableReferenceAnnotations ? "!" : "";

if (serializationLogicGenerated)
if (typeGenerationSpec.GenerateSerializationLogic)
{
return $"{typeInfoPropertyName}{SerializeHandlerPropName}({WriterVarName}, {valueToWrite});";
return $"{typeGenerationSpec.TypeInfoPropertyName}{SerializeHandlerPropName}({WriterVarName}, {valueExpr}{valueExprSuffix});";
}

return $"{JsonSerializerTypeRef}.Serialize({WriterVarName}, {valueToWrite}, {typeInfoRef});";
string typeInfoRef = $"{_currentContext.ContextTypeRef}.Default.{typeGenerationSpec.TypeInfoPropertyName}!";
return $"{JsonSerializerTypeRef}.Serialize({WriterVarName}, {valueExpr}{valueExprSuffix}, {typeInfoRef});";
}

private enum DefaultCheckType
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,7 @@ private TypeGenerationSpec GetOrAddTypeGenerationSpec(Type type, JsonSourceGener
bool hasInitOnlyProperties = false;
bool hasTypeFactoryConverter = false;
bool hasPropertyFactoryConverters = false;
bool canContainNullableReferenceAnnotations = type.CanContainNullableReferenceTypeAnnotations();

IList<CustomAttributeData> attributeDataList = CustomAttributeData.GetCustomAttributes(type);
foreach (CustomAttributeData attributeData in attributeDataList)
Expand Down Expand Up @@ -1011,6 +1012,7 @@ void CacheMemberHelper()
converterInstatiationLogic,
implementsIJsonOnSerialized : implementsIJsonOnSerialized,
implementsIJsonOnSerializing : implementsIJsonOnSerializing,
canContainNullableReferenceAnnotations: canContainNullableReferenceAnnotations,
hasTypeFactoryConverter : hasTypeFactoryConverter,
hasPropertyFactoryConverters : hasPropertyFactoryConverters);

Expand Down
24 changes: 24 additions & 0 deletions src/libraries/System.Text.Json/gen/Reflection/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,30 @@ public static bool IsNullableValueType(this Type type, out Type? underlyingType)
return false;
}

public static bool CanContainNullableReferenceTypeAnnotations(this Type type)
{
// Returns true iff Type instance has potential for receiving nullable reference type annotations,
// i.e. the type is a reference type or contains generic parameters that are reference types.

if (!type.IsValueType)
{
return true;
}

if (type.IsGenericType)
{
foreach (Type genericParam in type.GetGenericArguments())
{
if (CanContainNullableReferenceTypeAnnotations(genericParam))
{
return true;
}
}
}

return false;
}

public static bool IsObjectType(this Type type) => type.FullName == "System.Object";

public static bool IsStringType(this Type type) => type.FullName == "System.String";
Expand Down
7 changes: 7 additions & 0 deletions src/libraries/System.Text.Json/gen/TypeGenerationSpec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ internal class TypeGenerationSpec
public bool HasPropertyFactoryConverters { get; private set; }
public bool HasTypeFactoryConverter { get; private set; }

// The spec is derived from cached `System.Type` instances, which are generally annotation-agnostic.
// Hence we can only record the potential for nullable annotations being possible for the runtime type.
// TODO: consider deriving the generation spec from the Roslyn symbols directly.
public bool CanContainNullableReferenceAnnotations { get; private set; }

public string? ImmutableCollectionBuilderName
{
get
Expand Down Expand Up @@ -114,6 +119,7 @@ public void Initialize(
bool implementsIJsonOnSerialized,
bool implementsIJsonOnSerializing,
bool hasTypeFactoryConverter,
bool canContainNullableReferenceAnnotations,
bool hasPropertyFactoryConverters)
{
GenerationMode = generationMode;
Expand All @@ -136,6 +142,7 @@ public void Initialize(
ConverterInstantiationLogic = converterInstantiationLogic;
ImplementsIJsonOnSerialized = implementsIJsonOnSerialized;
ImplementsIJsonOnSerializing = implementsIJsonOnSerializing;
CanContainNullableReferenceAnnotations = canContainNullableReferenceAnnotations;
HasTypeFactoryConverter = hasTypeFactoryConverter;
HasPropertyFactoryConverters = hasPropertyFactoryConverters;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public interface ITestContext
public JsonTypeInfo<string> String { get; }
public JsonTypeInfo<(string Label1, int Label2, bool)> ValueTupleStringInt32Boolean { get; }
public JsonTypeInfo<RealWorldContextTests.ClassWithEnumAndNullable> ClassWithEnumAndNullable { get; }
public JsonTypeInfo<RealWorldContextTests.ClassWithNullableProperties> ClassWithNullableProperties { get; }
public JsonTypeInfo<ClassWithCustomConverter> ClassWithCustomConverter { get; }
public JsonTypeInfo<StructWithCustomConverter> StructWithCustomConverter { get; }
public JsonTypeInfo<ClassWithCustomConverterFactory> ClassWithCustomConverterFactory { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ namespace System.Text.Json.SourceGeneration.Tests
[JsonSerializable(typeof(string))]
[JsonSerializable(typeof((string Label1, int Label2, bool)))]
[JsonSerializable(typeof(RealWorldContextTests.ClassWithEnumAndNullable))]
[JsonSerializable(typeof(RealWorldContextTests.ClassWithNullableProperties))]
[JsonSerializable(typeof(ClassWithCustomConverter))]
[JsonSerializable(typeof(StructWithCustomConverter))]
[JsonSerializable(typeof(ClassWithCustomConverterFactory))]
Expand Down Expand Up @@ -72,6 +73,7 @@ public override void EnsureFastPathGeneratedAsExpected()
Assert.Null(MetadataAndSerializationContext.Default.String.SerializeHandler);
Assert.NotNull(MetadataAndSerializationContext.Default.ValueTupleStringInt32Boolean.SerializeHandler);
Assert.NotNull(MetadataAndSerializationContext.Default.ClassWithEnumAndNullable.SerializeHandler);
Assert.NotNull(MetadataAndSerializationContext.Default.ClassWithNullableProperties.SerializeHandler);
Assert.NotNull(MetadataAndSerializationContext.Default.ClassWithCustomConverter);
Assert.NotNull(MetadataAndSerializationContext.Default.StructWithCustomConverter);
Assert.NotNull(MetadataAndSerializationContext.Default.ClassWithCustomConverterFactory);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ namespace System.Text.Json.SourceGeneration.Tests
[JsonSerializable(typeof(string), GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof((string Label1, int Label2, bool)), GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(RealWorldContextTests.ClassWithEnumAndNullable), GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(RealWorldContextTests.ClassWithNullableProperties), GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(ClassWithCustomConverter), GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(StructWithCustomConverter), GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(ClassWithCustomConverterFactory), GenerationMode = JsonSourceGenerationMode.Metadata)]
Expand Down Expand Up @@ -69,6 +70,7 @@ public override void EnsureFastPathGeneratedAsExpected()
Assert.Null(MetadataWithPerTypeAttributeContext.Default.String.SerializeHandler);
Assert.Null(MetadataWithPerTypeAttributeContext.Default.ValueTupleStringInt32Boolean.SerializeHandler);
Assert.Null(MetadataWithPerTypeAttributeContext.Default.ClassWithEnumAndNullable.SerializeHandler);
Assert.Null(MetadataWithPerTypeAttributeContext.Default.ClassWithNullableProperties.SerializeHandler);
Assert.Null(MetadataWithPerTypeAttributeContext.Default.ClassWithCustomConverter.SerializeHandler);
Assert.Null(MetadataWithPerTypeAttributeContext.Default.StructWithCustomConverter.SerializeHandler);
Assert.Null(MetadataWithPerTypeAttributeContext.Default.ClassWithCustomConverterFactory.SerializeHandler);
Expand Down Expand Up @@ -104,6 +106,7 @@ public override void EnsureFastPathGeneratedAsExpected()
[JsonSerializable(typeof(string))]
[JsonSerializable(typeof((string Label1, int Label2, bool)))]
[JsonSerializable(typeof(RealWorldContextTests.ClassWithEnumAndNullable))]
[JsonSerializable(typeof(RealWorldContextTests.ClassWithNullableProperties))]
[JsonSerializable(typeof(ClassWithCustomConverter))]
[JsonSerializable(typeof(StructWithCustomConverter))]
[JsonSerializable(typeof(ClassWithCustomConverterFactory))]
Expand Down Expand Up @@ -169,6 +172,7 @@ public override void EnsureFastPathGeneratedAsExpected()
Assert.Null(MetadataContext.Default.String.SerializeHandler);
Assert.Null(MetadataContext.Default.ValueTupleStringInt32Boolean.SerializeHandler);
Assert.Null(MetadataContext.Default.ClassWithEnumAndNullable.SerializeHandler);
Assert.Null(MetadataContext.Default.ClassWithNullableProperties.SerializeHandler);
Assert.Null(MetadataContext.Default.ClassWithCustomConverter.SerializeHandler);
Assert.Null(MetadataContext.Default.StructWithCustomConverter.SerializeHandler);
Assert.Null(MetadataContext.Default.ClassWithCustomConverterFactory.SerializeHandler);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ namespace System.Text.Json.SourceGeneration.Tests
[JsonSerializable(typeof(string), GenerationMode = JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization)]
[JsonSerializable(typeof((string Label1, int Label2, bool)), GenerationMode = JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization)]
[JsonSerializable(typeof(RealWorldContextTests.ClassWithEnumAndNullable), GenerationMode = JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization)]
[JsonSerializable(typeof(RealWorldContextTests.ClassWithNullableProperties), GenerationMode = JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization)]
[JsonSerializable(typeof(ClassWithCustomConverter), GenerationMode = JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization)]
[JsonSerializable(typeof(StructWithCustomConverter), GenerationMode = JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization)]
[JsonSerializable(typeof(ClassWithCustomConverterFactory), GenerationMode = JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization)]
Expand Down Expand Up @@ -71,6 +72,7 @@ public override void EnsureFastPathGeneratedAsExpected()
Assert.Null(MixedModeContext.Default.String.SerializeHandler);
Assert.NotNull(MixedModeContext.Default.ValueTupleStringInt32Boolean.SerializeHandler);
Assert.NotNull(MixedModeContext.Default.ClassWithEnumAndNullable.SerializeHandler);
Assert.NotNull(MixedModeContext.Default.ClassWithNullableProperties.SerializeHandler);
Assert.Null(MixedModeContext.Default.ClassWithCustomConverter.SerializeHandler);
Assert.Null(MixedModeContext.Default.StructWithCustomConverter.SerializeHandler);
Assert.Null(MixedModeContext.Default.ClassWithCustomConverterFactory.SerializeHandler);
Expand Down
Loading