Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 5.6k
Ensure source generated metadata properties are read-only.#76540
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jeffhandley
merged 2 commits into
dotnet:main
from
eiriktsarpalis:fix-sourcegen-metadata-mutationOct 12, 2022
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
36 changes: 16 additions & 20 deletions
36 src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -3,11 +3,8 @@ | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Globalization; | ||
| using System.Reflection; | ||
| using System.Reflection.Metadata; | ||
| using System.Text.Json; | ||
| using System.Text.Json.Reflection; | ||
| using System.Text.Json.Serialization; | ||
| using Microsoft.CodeAnalysis; | ||
| @@ -28,6 +25,7 @@ private sealed partial class Emitter | ||
| private const string DefaultOptionsStaticVarName = "s_defaultOptions"; | ||
| private const string DefaultContextBackingStaticVarName = "s_defaultContext"; | ||
| internal const string GetConverterFromFactoryMethodName = "GetConverterFromFactory"; | ||
| private const string MakeReadOnlyMethodName = "MakeReadOnly"; | ||
| private const string InfoVarName = "info"; | ||
| private const string PropertyInfoVarName = "propertyInfo"; | ||
| internal const string JsonContextVarName = "jsonContext"; | ||
| @@ -1010,6 +1008,8 @@ private static string GenerateFastPathFuncForType(TypeGenerationSpec typeGenSpec | ||
| return $@" | ||
| // Intentionally not a static method because we create a delegate to it. Invoking delegates to instance | ||
| // methods is almost as fast as virtual calls. Static methods need to go through a shuffle thunk. | ||
| private void {serializeMethodName}({Utf8JsonWriterTypeRef} {WriterVarName}, {valueTypeRef} {ValueVarName}) | ||
| {{ | ||
| {GetEarlyNullCheckSource(emitNullCheck)} | ||
| @@ -1085,16 +1085,19 @@ private static string GenerateForType(TypeGenerationSpec typeMetadata, string me | ||
| /// </summary> | ||
| public {typeInfoPropertyTypeRef} {typeFriendlyName} | ||
| {{ | ||
| get => _{typeFriendlyName} ??= {typeMetadata.CreateTypeInfoMethodName}({OptionsInstanceVariableName}); | ||
| get => _{typeFriendlyName} ??= {typeMetadata.CreateTypeInfoMethodName}({OptionsInstanceVariableName}, makeReadOnly: true); | ||
| }} | ||
| // Intentionally not a static method because we create a delegate to it. Invoking delegates to instance | ||
| // methods is almost as fast as virtual calls. Static methods need to go through a shuffle thunk. | ||
| private {typeInfoPropertyTypeRef} {typeMetadata.CreateTypeInfoMethodName}({JsonSerializerOptionsTypeRef} {OptionsLocalVariableName}) | ||
| private {typeInfoPropertyTypeRef} {typeMetadata.CreateTypeInfoMethodName}({JsonSerializerOptionsTypeRef} {OptionsLocalVariableName}, bool makeReadOnly) | ||
| {{ | ||
| {typeInfoPropertyTypeRef}? {JsonTypeInfoReturnValueLocalVariableName} = null; | ||
| {WrapWithCheckForCustomConverter(metadataInitSource, typeCompilableName)} | ||
| if (makeReadOnly) | ||
| {{ | ||
| {JsonTypeInfoReturnValueLocalVariableName}.{MakeReadOnlyMethodName}(); | ||
| }} | ||
| return {JsonTypeInfoReturnValueLocalVariableName}; | ||
| }} | ||
| {additionalSource}"; | ||
| @@ -1271,30 +1274,23 @@ private string GetGetTypeInfoImplementation() | ||
| // Explicit IJsonTypeInfoResolver implementation | ||
| sb.AppendLine(); | ||
| sb.Append(@$"{JsonTypeInfoTypeRef}? {JsonTypeInfoResolverTypeRef}.GetTypeInfo({TypeTypeRef} type, {JsonSerializerOptionsTypeRef} {OptionsLocalVariableName}) | ||
| {{ | ||
| if ({OptionsInstanceVariableName} == {OptionsLocalVariableName}) | ||
eiriktsarpalis marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| {{ | ||
| return this.GetTypeInfo(type); | ||
| }} | ||
| else | ||
| {{"); | ||
| {{"); | ||
| // TODO (https://github.com/dotnet/runtime/issues/52218): Make this Dictionary-lookup-based if root-serializable type count > 64. | ||
| foreach (TypeGenerationSpec metadata in types) | ||
| { | ||
| if (metadata.ClassType != ClassType.TypeUnsupportedBySourceGen) | ||
| { | ||
| sb.Append($@" | ||
| if (type == typeof({metadata.TypeRef})) | ||
| {{ | ||
| return {metadata.CreateTypeInfoMethodName}({OptionsLocalVariableName}); | ||
| }} | ||
| if (type == typeof({metadata.TypeRef})) | ||
| {{ | ||
| return {metadata.CreateTypeInfoMethodName}({OptionsLocalVariableName}, makeReadOnly: false); | ||
| }} | ||
| "); | ||
| } | ||
| } | ||
| sb.Append($@" | ||
| return null; | ||
| }} | ||
| return null; | ||
| }} | ||
| "); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2 ...ibraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfo.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
24 changes: 23 additions & 1 deletion
24 src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -256,6 +256,23 @@ public JsonPolymorphismOptions? PolymorphismOptions | ||
| } | ||
| } | ||
| /// <summary> | ||
| /// Specifies whether the current instance has been locked for modification. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// A <see cref="JsonTypeInfo"/> instance can be locked either if | ||
| /// it has been passed to one of the <see cref="JsonSerializer"/> methods, | ||
| /// has been associated with a <see cref="JsonSerializerContext"/> instance, | ||
| /// or a user explicitly called the <see cref="MakeReadOnly"/> method on the instance. | ||
| /// </remarks> | ||
| public bool IsReadOnly { get; private set; } | ||
| /// <summary> | ||
| /// Locks the current instance for further modification. | ||
| /// </summary> | ||
| /// <remarks>This method is idempotent.</remarks> | ||
| public void MakeReadOnly() => IsReadOnly = true; | ||
| private protected JsonPolymorphismOptions? _polymorphismOptions; | ||
| internal object? CreateObjectWithArgs { get; set; } | ||
| @@ -477,7 +494,7 @@ internal JsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions | ||
| internal void VerifyMutable() | ||
| { | ||
| if (_isConfigured) | ||
| if (IsReadOnly) | ||
| { | ||
| ThrowHelper.ThrowInvalidOperationException_TypeInfoImmutable(); | ||
| } | ||
| @@ -511,6 +528,7 @@ void ConfigureLocked() | ||
| { | ||
| Configure(); | ||
| IsReadOnly = true; | ||
| _isConfigured = true; | ||
| } | ||
| catch (Exception e) | ||
| @@ -693,6 +711,7 @@ public static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonSerializerOptions o | ||
| /// <returns>A blank <see cref="JsonPropertyInfo"/> instance.</returns> | ||
| /// <exception cref="ArgumentNullException"><paramref name="propertyType"/> or <paramref name="name"/> is null.</exception> | ||
| /// <exception cref="ArgumentException"><paramref name="propertyType"/> cannot be used for serialization.</exception> | ||
| /// <exception cref="InvalidOperationException">The <see cref="JsonTypeInfo"/> instance has been locked for further modification.</exception> | ||
| [RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)] | ||
| [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] | ||
| public JsonPropertyInfo CreateJsonPropertyInfo(Type propertyType, string name) | ||
| @@ -712,6 +731,7 @@ public JsonPropertyInfo CreateJsonPropertyInfo(Type propertyType, string name) | ||
| ThrowHelper.ThrowArgumentException_CannotSerializeInvalidType(nameof(propertyType), propertyType, Type, name); | ||
| } | ||
| VerifyMutable(); | ||
| JsonPropertyInfo propertyInfo = CreatePropertyUsingReflection(propertyType); | ||
| propertyInfo.Name = name; | ||
| @@ -748,6 +768,8 @@ internal void CacheMember(JsonPropertyInfo jsonPropertyInfo, JsonPropertyDiction | ||
| Debug.Assert(jsonPropertyInfo.MemberName != null, "MemberName can be null in custom JsonPropertyInfo instances and should never be passed in this method"); | ||
| string memberName = jsonPropertyInfo.MemberName; | ||
| jsonPropertyInfo.EnsureChildOf(this); | ||
eiriktsarpalis marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| if (jsonPropertyInfo.IsExtensionData) | ||
| { | ||
| if (ExtensionDataProperty != null) | ||
64 changes: 64 additions & 0 deletions
64 ...tem.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSerializerContextTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
15 changes: 12 additions & 3 deletions
15 ...t.Json.Tests/Serialization/MetadataTests/DefaultJsonTypeInfoResolverTests.JsonTypeInfo.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
6 changes: 6 additions & 0 deletions
6 src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OptionsTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.