|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Collections.Immutable; |
| 5 | +using Microsoft.CodeAnalysis; |
| 6 | +using Microsoft.CodeAnalysis.Text; |
| 7 | +using System.Text; |
| 8 | +using Microsoft.CodeAnalysis.CSharp; |
| 9 | +using System.IO; |
| 10 | + |
| 11 | +namespace Microsoft.Extensions.Validation.ValidationsGenerator; |
| 12 | + |
| 13 | +public sealed partial class ValidationsGenerator : IIncrementalGenerator |
| 14 | +{ |
| 15 | + public static string GeneratedCodeConstructor => $@"global::System.CodeDom.Compiler.GeneratedCodeAttribute(""{typeof(ValidationsGenerator).Assembly.FullName}"", ""{typeof(ValidationsGenerator).Assembly.GetName().Version}"")"; |
| 16 | + public static string GeneratedCodeAttribute => $"[{GeneratedCodeConstructor}]"; |
| 17 | + |
| 18 | + internal static void Emit(SourceProductionContext context, (InterceptableLocation? AddValidation, ImmutableArray<ValidatableType> ValidatableTypes) emitInputs) |
| 19 | + { |
| 20 | + if (emitInputs.AddValidation is null) |
| 21 | + { |
| 22 | + // Avoid generating code if no AddValidation call was found. |
| 23 | + return; |
| 24 | + } |
| 25 | + var source = Emit(emitInputs.AddValidation, emitInputs.ValidatableTypes); |
| 26 | + context.AddSource("ValidatableInfoResolver.g.cs", SourceText.From(source, Encoding.UTF8)); |
| 27 | + } |
| 28 | + |
| 29 | + private static string Emit(InterceptableLocation addValidation, ImmutableArray<ValidatableType> validatableTypes) => $$""" |
| 30 | +#nullable enable annotations |
| 31 | +//------------------------------------------------------------------------------ |
| 32 | +// <auto-generated> |
| 33 | +// This code was generated by a tool. |
| 34 | +// |
| 35 | +// Changes to this file may cause incorrect behavior and will be lost if |
| 36 | +// the code is regenerated. |
| 37 | +// </auto-generated> |
| 38 | +//------------------------------------------------------------------------------ |
| 39 | +#nullable enable |
| 40 | +#pragma warning disable ASP0029 |
| 41 | +
|
| 42 | +namespace System.Runtime.CompilerServices |
| 43 | +{ |
| 44 | + {{GeneratedCodeAttribute}} |
| 45 | + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] |
| 46 | + file sealed class InterceptsLocationAttribute : System.Attribute |
| 47 | + { |
| 48 | + public InterceptsLocationAttribute(int version, string data) |
| 49 | + { |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | +
|
| 54 | +namespace Microsoft.Extensions.Validation.Generated |
| 55 | +{ |
| 56 | + {{GeneratedCodeAttribute}} |
| 57 | + file sealed class GeneratedValidatablePropertyInfo : global::Microsoft.Extensions.Validation.ValidatablePropertyInfo |
| 58 | + { |
| 59 | + public GeneratedValidatablePropertyInfo( |
| 60 | + [param: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] |
| 61 | + global::System.Type containingType, |
| 62 | + global::System.Type propertyType, |
| 63 | + string name, |
| 64 | + string displayName) : base(containingType, propertyType, name, displayName) |
| 65 | + { |
| 66 | + ContainingType = containingType; |
| 67 | + Name = name; |
| 68 | + } |
| 69 | +
|
| 70 | + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] |
| 71 | + internal global::System.Type ContainingType { get; } |
| 72 | + internal string Name { get; } |
| 73 | +
|
| 74 | + protected override global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes() |
| 75 | + => ValidationAttributeCache.GetValidationAttributes(ContainingType, Name); |
| 76 | + } |
| 77 | +
|
| 78 | + {{GeneratedCodeAttribute}} |
| 79 | + file sealed class GeneratedValidatableTypeInfo : global::Microsoft.Extensions.Validation.ValidatableTypeInfo |
| 80 | + { |
| 81 | + public GeneratedValidatableTypeInfo( |
| 82 | + [param: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.Interfaces)] |
| 83 | + global::System.Type type, |
| 84 | + ValidatablePropertyInfo[] members) : base(type, members) { } |
| 85 | + } |
| 86 | +
|
| 87 | + {{GeneratedCodeAttribute}} |
| 88 | + file class GeneratedValidatableInfoResolver : global::Microsoft.Extensions.Validation.IValidatableInfoResolver |
| 89 | + { |
| 90 | + public bool TryGetValidatableTypeInfo(global::System.Type type, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out global::Microsoft.Extensions.Validation.IValidatableInfo? validatableInfo) |
| 91 | + { |
| 92 | + validatableInfo = null; |
| 93 | +{{EmitTypeChecks(validatableTypes)}} |
| 94 | + return false; |
| 95 | + } |
| 96 | +
|
| 97 | + // No-ops, rely on runtime code for ParameterInfo-based resolution |
| 98 | + public bool TryGetValidatableParameterInfo(global::System.Reflection.ParameterInfo parameterInfo, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out global::Microsoft.Extensions.Validation.IValidatableInfo? validatableInfo) |
| 99 | + { |
| 100 | + validatableInfo = null; |
| 101 | + return false; |
| 102 | + } |
| 103 | + } |
| 104 | +
|
| 105 | + {{GeneratedCodeAttribute}} |
| 106 | + file static class GeneratedServiceCollectionExtensions |
| 107 | + { |
| 108 | + {{addValidation.GetInterceptsLocationAttributeSyntax()}} |
| 109 | + public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddValidation(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services, global::System.Action<global::Microsoft.Extensions.Validation.ValidationOptions>? configureOptions = null) |
| 110 | + { |
| 111 | + // Use non-extension method to avoid infinite recursion. |
| 112 | + return global::Microsoft.Extensions.DependencyInjection.ValidationServiceCollectionExtensions.AddValidation(services, options => |
| 113 | + { |
| 114 | + options.Resolvers.Insert(0, new GeneratedValidatableInfoResolver()); |
| 115 | + if (configureOptions is not null) |
| 116 | + { |
| 117 | + configureOptions(options); |
| 118 | + } |
| 119 | + }); |
| 120 | + } |
| 121 | + } |
| 122 | +
|
| 123 | + {{GeneratedCodeAttribute}} |
| 124 | + file static class ValidationAttributeCache |
| 125 | + { |
| 126 | + private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName); |
| 127 | + private static readonly global::System.Collections.Concurrent.ConcurrentDictionary<CacheKey, global::System.ComponentModel.DataAnnotations.ValidationAttribute[]> _cache = new(); |
| 128 | +
|
| 129 | + public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes( |
| 130 | + [global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] |
| 131 | + global::System.Type containingType, |
| 132 | + string propertyName) |
| 133 | + { |
| 134 | + var key = new CacheKey(containingType, propertyName); |
| 135 | + return _cache.GetOrAdd(key, static k => |
| 136 | + { |
| 137 | + var results = new global::System.Collections.Generic.List<global::System.ComponentModel.DataAnnotations.ValidationAttribute>(); |
| 138 | +
|
| 139 | + // Get attributes from the property |
| 140 | + var property = k.ContainingType.GetProperty(k.PropertyName); |
| 141 | + if (property != null) |
| 142 | + { |
| 143 | + var propertyAttributes = global::System.Reflection.CustomAttributeExtensions |
| 144 | + .GetCustomAttributes<global::System.ComponentModel.DataAnnotations.ValidationAttribute>(property, inherit: true); |
| 145 | +
|
| 146 | + results.AddRange(propertyAttributes); |
| 147 | + } |
| 148 | +
|
| 149 | + // Check constructors for parameters that match the property name |
| 150 | + // to handle record scenarios |
| 151 | + foreach (var constructor in k.ContainingType.GetConstructors()) |
| 152 | + { |
| 153 | + // Look for parameter with matching name (case insensitive) |
| 154 | + var parameter = global::System.Linq.Enumerable.FirstOrDefault( |
| 155 | + constructor.GetParameters(), |
| 156 | + p => string.Equals(p.Name, k.PropertyName, global::System.StringComparison.OrdinalIgnoreCase)); |
| 157 | +
|
| 158 | + if (parameter != null) |
| 159 | + { |
| 160 | + var paramAttributes = global::System.Reflection.CustomAttributeExtensions |
| 161 | + .GetCustomAttributes<global::System.ComponentModel.DataAnnotations.ValidationAttribute>(parameter, inherit: true); |
| 162 | +
|
| 163 | + results.AddRange(paramAttributes); |
| 164 | +
|
| 165 | + break; |
| 166 | + } |
| 167 | + } |
| 168 | +
|
| 169 | + return results.ToArray(); |
| 170 | + }); |
| 171 | + } |
| 172 | + } |
| 173 | +} |
| 174 | +"""; |
| 175 | + |
| 176 | + private static string EmitTypeChecks(ImmutableArray<ValidatableType> validatableTypes) |
| 177 | + { |
| 178 | + var sw = new StringWriter(); |
| 179 | + var cw = new CodeWriter(sw, baseIndent: 3); |
| 180 | + foreach (var validatableType in validatableTypes) |
| 181 | + { |
| 182 | + var typeName = validatableType.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); |
| 183 | + cw.WriteLine($"if (type == typeof({typeName}))"); |
| 184 | + cw.StartBlock(); |
| 185 | + cw.WriteLine($"validatableInfo = new GeneratedValidatableTypeInfo("); |
| 186 | + cw.Indent++; |
| 187 | + cw.WriteLine($"type: typeof({typeName}),"); |
| 188 | + if (validatableType.Members.IsDefaultOrEmpty) |
| 189 | + { |
| 190 | + cw.WriteLine("members: []"); |
| 191 | + } |
| 192 | + else |
| 193 | + { |
| 194 | + cw.WriteLine("members: ["); |
| 195 | + cw.Indent++; |
| 196 | + foreach (var member in validatableType.Members) |
| 197 | + { |
| 198 | + EmitValidatableMemberForCreate(member, cw); |
| 199 | + } |
| 200 | + cw.Indent--; |
| 201 | + cw.WriteLine("]"); |
| 202 | + } |
| 203 | + cw.Indent--; |
| 204 | + cw.WriteLine(");"); |
| 205 | + cw.WriteLine("return true;"); |
| 206 | + cw.EndBlock(); |
| 207 | + } |
| 208 | + return sw.ToString(); |
| 209 | + } |
| 210 | + |
| 211 | + private static void EmitValidatableMemberForCreate(ValidatableProperty member, CodeWriter cw) |
| 212 | + { |
| 213 | + cw.WriteLine("new GeneratedValidatablePropertyInfo("); |
| 214 | + cw.Indent++; |
| 215 | + cw.WriteLine($"containingType: typeof({member.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}),"); |
| 216 | + cw.WriteLine($"propertyType: typeof({member.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}),"); |
| 217 | + cw.WriteLine($"name: \"{member.Name}\","); |
| 218 | + cw.WriteLine($"displayName: \"{member.DisplayName}\""); |
| 219 | + cw.Indent--; |
| 220 | + cw.WriteLine("),"); |
| 221 | + } |
| 222 | +} |
0 commit comments