Skip to content

Commit

Permalink
Enable analyzers for System.Text.Json.SourceGeneration (#69581)
Browse files Browse the repository at this point in the history
* Enable analyzers for System.Text.Json.SourceGeneration

* Fix another warning in release builds
  • Loading branch information
stephentoub committed May 20, 2022
1 parent 3914bcc commit 5a52a13
Show file tree
Hide file tree
Showing 18 changed files with 49 additions and 47 deletions.
45 changes: 25 additions & 20 deletions src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs
Expand Up @@ -28,7 +28,6 @@ private sealed partial class Emitter
private const string ElementInfoPropName = "ElementInfo";
internal const string GetConverterFromFactoryMethodName = "GetConverterFromFactory";
private const string InfoVarName = "info";
private const string JsonSerializerContextName = "JsonSerializerContext";
internal const string JsonContextVarName = "jsonContext";
private const string KeyInfoPropName = "KeyInfo";
private const string NumberHandlingPropName = "NumberHandling";
Expand All @@ -54,7 +53,6 @@ private sealed partial class Emitter
private const string EqualityComparerTypeRef = "global::System.Collections.Generic.EqualityComparer";
private const string IListTypeRef = "global::System.Collections.Generic.IList";
private const string KeyValuePairTypeRef = "global::System.Collections.Generic.KeyValuePair";
private const string ListTypeRef = "global::System.Collections.Generic.List";
private const string JsonEncodedTextTypeRef = "global::System.Text.Json.JsonEncodedText";
private const string JsonNamingPolicyTypeRef = "global::System.Text.Json.JsonNamingPolicy";
private const string JsonSerializerTypeRef = "global::System.Text.Json.JsonSerializer";
Expand All @@ -72,7 +70,6 @@ private sealed partial class Emitter
private const string JsonPropertyInfoTypeRef = "global::System.Text.Json.Serialization.Metadata.JsonPropertyInfo";
private const string JsonPropertyInfoValuesTypeRef = "global::System.Text.Json.Serialization.Metadata.JsonPropertyInfoValues";
private const string JsonTypeInfoTypeRef = "global::System.Text.Json.Serialization.Metadata.JsonTypeInfo";
private const string NotSupportedExceptionTypeRef = "global::System.NotSupportedException";

private static DiagnosticDescriptor TypeNotSupported { get; } = new DiagnosticDescriptor(
id: "SYSLIB1030",
Expand All @@ -98,8 +95,8 @@ private sealed partial class Emitter

private readonly HashSet<string> _emittedPropertyFileNames = new();

private bool _generateGetConverterMethodForTypes = false;
private bool _generateGetConverterMethodForProperties = false;
private bool _generateGetConverterMethodForTypes;
private bool _generateGetConverterMethodForProperties;

public Emitter(in JsonSourceGenerationContext sourceGenerationContext, SourceGenerationSpec generationSpec)
{
Expand Down Expand Up @@ -311,7 +308,7 @@ private void GenerateTypeInfo(TypeGenerationSpec typeGenerationSpec)
_generateGetConverterMethodForProperties |= typeGenerationSpec.HasPropertyFactoryConverters;
}

private string GenerateForTypeWithKnownConverter(TypeGenerationSpec typeMetadata)
private static string GenerateForTypeWithKnownConverter(TypeGenerationSpec typeMetadata)
{
string typeCompilableName = typeMetadata.TypeRef;
string typeFriendlyName = typeMetadata.TypeInfoPropertyName;
Expand All @@ -321,7 +318,7 @@ private string GenerateForTypeWithKnownConverter(TypeGenerationSpec typeMetadata
return GenerateForType(typeMetadata, metadataInitSource);
}

private string GenerateForTypeWithUnknownConverter(TypeGenerationSpec typeMetadata)
private static string GenerateForTypeWithUnknownConverter(TypeGenerationSpec typeMetadata)
{
string typeCompilableName = typeMetadata.TypeRef;
string typeFriendlyName = typeMetadata.TypeInfoPropertyName;
Expand Down Expand Up @@ -364,7 +361,7 @@ private string GenerateForTypeWithUnknownConverter(TypeGenerationSpec typeMetada
return GenerateForType(typeMetadata, metadataInitSource.ToString());
}

private string GenerateForNullable(TypeGenerationSpec typeMetadata)
private static string GenerateForNullable(TypeGenerationSpec typeMetadata)
{
string typeCompilableName = typeMetadata.TypeRef;
string typeFriendlyName = typeMetadata.TypeInfoPropertyName;
Expand All @@ -385,7 +382,7 @@ private string GenerateForNullable(TypeGenerationSpec typeMetadata)
return GenerateForType(typeMetadata, metadataInitSource);
}

private string GenerateForUnsupportedType(TypeGenerationSpec typeMetadata)
private static string GenerateForUnsupportedType(TypeGenerationSpec typeMetadata)
{
string typeCompilableName = typeMetadata.TypeRef;
string typeFriendlyName = typeMetadata.TypeInfoPropertyName;
Expand All @@ -395,7 +392,7 @@ private string GenerateForUnsupportedType(TypeGenerationSpec typeMetadata)
return GenerateForType(typeMetadata, metadataInitSource);
}

private string GenerateForEnum(TypeGenerationSpec typeMetadata)
private static string GenerateForEnum(TypeGenerationSpec typeMetadata)
{
string typeCompilableName = typeMetadata.TypeRef;
string typeFriendlyName = typeMetadata.TypeInfoPropertyName;
Expand Down Expand Up @@ -799,7 +796,11 @@ private string GeneratePropMetadataInitFunc(TypeGenerationSpec typeGenerationSpe
return sb.ToString();
}

private string GenerateCtorParamMetadataInitFunc(TypeGenerationSpec typeGenerationSpec)
private
#if !DEBUG
static
#endif
string GenerateCtorParamMetadataInitFunc(TypeGenerationSpec typeGenerationSpec)
{
const string parametersVarName = "parameters";

Expand Down Expand Up @@ -1048,7 +1049,7 @@ static string GetParamUnboxing(ParameterGenerationSpec spec, int index)
return method;
}

private string GenerateFastPathFuncForType(TypeGenerationSpec typeGenSpec, string serializeMethodBody, bool emitNullCheck)
private static string GenerateFastPathFuncForType(TypeGenerationSpec typeGenSpec, string serializeMethodBody, bool emitNullCheck)
{
Debug.Assert(!emitNullCheck || typeGenSpec.CanBeNull);

Expand All @@ -1065,7 +1066,7 @@ private string GenerateFastPathFuncForType(TypeGenerationSpec typeGenSpec, strin
}}";
}

private string GetEarlyNullCheckSource(bool canBeNull)
private static string GetEarlyNullCheckSource(bool canBeNull)
{
return canBeNull
? $@"if ({ValueVarName} == null)
Expand Down Expand Up @@ -1097,7 +1098,7 @@ private enum DefaultCheckType
Default,
}

private string WrapSerializationLogicInDefaultCheckIfRequired(string serializationLogic, string propValue, string propTypeRef, DefaultCheckType defaultCheckType)
private static string WrapSerializationLogicInDefaultCheckIfRequired(string serializationLogic, string propValue, string propTypeRef, DefaultCheckType defaultCheckType)
{
string comparisonLogic;

Expand All @@ -1121,7 +1122,7 @@ private string WrapSerializationLogicInDefaultCheckIfRequired(string serializati
}}";
}

private string GenerateForType(TypeGenerationSpec typeMetadata, string metadataInitSource, string? additionalSource = null)
private static string GenerateForType(TypeGenerationSpec typeMetadata, string metadataInitSource, string? additionalSource = null)
{
string typeCompilableName = typeMetadata.TypeRef;
string typeFriendlyName = typeMetadata.TypeInfoPropertyName;
Expand All @@ -1142,7 +1143,7 @@ private string GenerateForType(TypeGenerationSpec typeMetadata, string metadataI
}}{additionalSource}";
}

private string WrapWithCheckForCustomConverter(string source, string typeCompilableName, string typeFriendlyName, string numberHandlingNamedArg)
private static string WrapWithCheckForCustomConverter(string source, string typeCompilableName, string typeFriendlyName, string numberHandlingNamedArg)
=> @$"{JsonConverterTypeRef}? customConverter;
if ({OptionsInstanceVariableName}.Converters.Count > 0 && (customConverter = {RuntimeCustomConverterFetchingMethodName}(typeof({typeCompilableName}))) != null)
{{
Expand Down Expand Up @@ -1210,7 +1211,7 @@ private string GetLogicForDefaultSerializerOptionsInit()
}};";
}

private string GetFetchLogicForRuntimeSpecifiedCustomConverter()
private static string GetFetchLogicForRuntimeSpecifiedCustomConverter()
{
// TODO (https://github.com/dotnet/runtime/issues/52218): use a dictionary if count > ~15.
return @$"private {JsonConverterTypeRef}? {RuntimeCustomConverterFetchingMethodName}({TypeTypeRef} type)
Expand Down Expand Up @@ -1240,7 +1241,7 @@ private string GetFetchLogicForRuntimeSpecifiedCustomConverter()
}}";
}

private string GetFetchLogicForGetCustomConverter_PropertiesWithFactories()
private static string GetFetchLogicForGetCustomConverter_PropertiesWithFactories()
{
return @$"
Expand All @@ -1250,7 +1251,7 @@ private string GetFetchLogicForGetCustomConverter_PropertiesWithFactories()
}}";
}

private string GetFetchLogicForGetCustomConverter_TypesWithFactories()
private static string GetFetchLogicForGetCustomConverter_TypesWithFactories()
{
return @$"
Expand Down Expand Up @@ -1330,7 +1331,11 @@ private static string IndentSource(string source, int numIndentations)

private static string FormatBool(bool value) => value ? "true" : "false";

private string GetParamDefaultValueAsString(object? value, Type type, string typeRef)
private
#if !DEBUG
static
#endif
string GetParamDefaultValueAsString(object? value, Type type, string typeRef)
{
if (value == null)
{
Expand Down
Expand Up @@ -1144,10 +1144,10 @@ private bool IsValidDataExtensionPropertyType(Type type)
return genericArguments[0] == _stringType && (genericArguments[1] == _objectType || genericArguments[1] == _jsonElementType);
}

private Type GetCompatibleGenericBaseClass(Type type, Type baseType)
private static Type GetCompatibleGenericBaseClass(Type type, Type baseType)
=> type.GetCompatibleGenericBaseClass(baseType);

private void CacheMember(
private static void CacheMember(
PropertyGenerationSpec propGenSpec,
ref List<PropertyGenerationSpec> propGenSpecList,
ref Dictionary<string, PropertyGenerationSpec> ignoredMembers)
Expand Down Expand Up @@ -1243,7 +1243,7 @@ private static bool PropertyIsConstructorParameter(PropertyGenerationSpec propSp
};
}

private Type GetMemberClrType(MemberInfo memberInfo)
private static Type GetMemberClrType(MemberInfo memberInfo)
{
if (memberInfo is PropertyInfo propertyInfo)
{
Expand Down
Expand Up @@ -29,9 +29,9 @@ public sealed partial class JsonSourceGenerator : ISourceGenerator
public void Initialize(GeneratorInitializationContext context)
{
// Unfortunately, there is no cancellation token that can be passed here
// (the one in GeneratorInitializationContext is not safe to capture).
// (the one in GeneratorInitializationContext is not safe to capture).
// In practice this should still be ok as the generator driver itself will
// cancel after every file it processes.
// cancel after every file it processes.
context.RegisterForSyntaxNotifications(static () => new SyntaxContextReceiver(CancellationToken.None));
}

Expand Down
Expand Up @@ -8,7 +8,7 @@

namespace System.Text.Json.SourceGeneration
{
internal class ParameterGenerationSpec
internal sealed class ParameterGenerationSpec
{
public TypeGenerationSpec TypeGenerationSpec { get; init; }

Expand Down
Expand Up @@ -7,7 +7,7 @@

namespace System.Text.Json.Reflection
{
internal class AssemblyWrapper : Assembly
internal sealed class AssemblyWrapper : Assembly
{
private readonly MetadataLoadContextInternal _metadataLoadContext;

Expand Down
Expand Up @@ -9,7 +9,7 @@

namespace System.Text.Json.Reflection
{
internal class ConstructorInfoWrapper : ConstructorInfo
internal sealed class ConstructorInfoWrapper : ConstructorInfo
{
private readonly IMethodSymbol _ctor;
private readonly MetadataLoadContextInternal _metadataLoadContext;
Expand Down
Expand Up @@ -9,7 +9,7 @@

namespace System.Text.Json.Reflection
{
internal class CustomAttributeDataWrapper : CustomAttributeData
internal sealed class CustomAttributeDataWrapper : CustomAttributeData
{
public CustomAttributeDataWrapper(AttributeData a, MetadataLoadContextInternal metadataLoadContext)
{
Expand Down
Expand Up @@ -8,7 +8,7 @@

namespace System.Text.Json.Reflection
{
internal class FieldInfoWrapper : FieldInfo
internal sealed class FieldInfoWrapper : FieldInfo
{
private readonly IFieldSymbol _field;
private readonly MetadataLoadContextInternal _metadataLoadContext;
Expand Down
Expand Up @@ -7,7 +7,7 @@

namespace System.Text.Json.Reflection
{
internal class MemberInfoWrapper : MemberInfo
internal sealed class MemberInfoWrapper : MemberInfo
{
private readonly ISymbol _member;
private readonly MetadataLoadContextInternal _metadataLoadContext;
Expand Down
Expand Up @@ -12,7 +12,7 @@

namespace System.Text.Json.Reflection
{
internal class MetadataLoadContextInternal
internal sealed class MetadataLoadContextInternal
{
private readonly Compilation _compilation;

Expand Down
Expand Up @@ -8,7 +8,7 @@

namespace System.Text.Json.Reflection
{
internal class MethodInfoWrapper : MethodInfo
internal sealed class MethodInfoWrapper : MethodInfo
{
private readonly IMethodSymbol _method;
private readonly MetadataLoadContextInternal _metadataLoadContext;
Expand Down
Expand Up @@ -7,7 +7,7 @@

namespace System.Text.Json.Reflection
{
internal class ParameterInfoWrapper : ParameterInfo
internal sealed class ParameterInfoWrapper : ParameterInfo
{
private readonly IParameterSymbol _parameter;

Expand All @@ -27,7 +27,7 @@ public ParameterInfoWrapper(IParameterSymbol parameter, MetadataLoadContextInter

public override object DefaultValue => HasDefaultValue ? _parameter.ExplicitDefaultValue : null;

public override int Position => _parameter.Ordinal;
public override int Position => _parameter.Ordinal;

public override IList<CustomAttributeData> GetCustomAttributesData()
{
Expand Down
Expand Up @@ -8,7 +8,7 @@

namespace System.Text.Json.Reflection
{
internal class PropertyInfoWrapper : PropertyInfo
internal sealed class PropertyInfoWrapper : PropertyInfo
{
private readonly IPropertySymbol _property;
private MetadataLoadContextInternal _metadataLoadContext;
Expand Down
Expand Up @@ -67,4 +67,3 @@ public static MethodAttributes GetMethodAttributes(this IMethodSymbol methodSymb
}
}
}

Expand Up @@ -33,7 +33,7 @@ public static string GetCompilableName(this Type type)

sb.Append(baseName);

sb.Append("<");
sb.Append('<');

Type[] genericArgs = type.GetGenericArguments();
int genericArgCount = genericArgs.Length;
Expand All @@ -46,7 +46,7 @@ public static string GetCompilableName(this Type type)

sb.Append(string.Join(", ", genericArgNames));

sb.Append(">");
sb.Append('>');

compilableName = sb.ToString();
}
Expand Down
11 changes: 5 additions & 6 deletions src/libraries/System.Text.Json/gen/Reflection/TypeWrapper.cs
Expand Up @@ -12,7 +12,7 @@

namespace System.Text.Json.Reflection
{
internal class TypeWrapper : Type
internal sealed class TypeWrapper : Type
{
private readonly ITypeSymbol _typeSymbol;

Expand Down Expand Up @@ -147,19 +147,18 @@ public override string FullName

if (this.IsGenericType && !ContainsGenericParameters)
{
sb.Append("[");
sb.Append('[');

foreach (Type genericArg in GetGenericArguments())
{
sb.Append("[");
sb.Append('[');
sb.Append(genericArg.AssemblyQualifiedName);
sb.Append("]");
sb.Append(']');
}

sb.Append("]");
sb.Append(']');
}
}


_fullName = sb.ToString();
}
Expand Down
Expand Up @@ -11,7 +11,6 @@
<EnableDefaultEmbeddedResourceItems>false</EnableDefaultEmbeddedResourceItems>
<UsingToolXliff>true</UsingToolXliff>
<AnalyzerLanguage>cs</AnalyzerLanguage>
<RunAnalyzers>false</RunAnalyzers>
</PropertyGroup>

<PropertyGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Text.Json/gen/TypeGenerationSpec.cs
Expand Up @@ -12,7 +12,7 @@
namespace System.Text.Json.SourceGeneration
{
[DebuggerDisplay("Type={Type}, ClassType={ClassType}")]
internal class TypeGenerationSpec
internal sealed class TypeGenerationSpec
{
/// <summary>
/// Fully qualified assembly name, prefixed with "global::", e.g. global::System.Numerics.BigInteger.
Expand Down

0 comments on commit 5a52a13

Please sign in to comment.