| | | 1 | | using Microsoft.CodeAnalysis; |
| | | 2 | | |
| | | 3 | | using NexusLabs.Needlr.Generators.Models; |
| | | 4 | | using NexusLabs.Needlr.Roslyn.Shared; |
| | | 5 | | |
| | | 6 | | namespace NexusLabs.Needlr.Generators; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Helper for discovering factory generation attributes from Roslyn symbols. |
| | | 10 | | /// </summary> |
| | | 11 | | internal static class FactoryDiscoveryHelper |
| | | 12 | | { |
| | | 13 | | private const string GenerateFactoryAttributeName = "GenerateFactoryAttribute"; |
| | | 14 | | private const string GenerateFactoryAttributeFullName = "NexusLabs.Needlr.GenerateFactoryAttribute"; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Checks if a type has the [GenerateFactory] attribute. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <param name="typeSymbol">The type symbol to check.</param> |
| | | 20 | | /// <returns>True if the type has [GenerateFactory]; otherwise, false.</returns> |
| | | 21 | | public static bool HasGenerateFactoryAttribute(INamedTypeSymbol typeSymbol) |
| | | 22 | | { |
| | 7419607 | 23 | | foreach (var attribute in typeSymbol.GetAttributes()) |
| | | 24 | | { |
| | 2165688 | 25 | | var attributeClass = attribute.AttributeClass; |
| | 2165688 | 26 | | if (attributeClass == null) |
| | | 27 | | continue; |
| | | 28 | | |
| | | 29 | | // Check for non-generic GenerateFactoryAttribute |
| | 2165688 | 30 | | var name = attributeClass.Name; |
| | 2165688 | 31 | | if (name == GenerateFactoryAttributeName) |
| | 33 | 32 | | return true; |
| | | 33 | | |
| | 2165655 | 34 | | var fullName = attributeClass.ToDisplayString(); |
| | 2165655 | 35 | | if (fullName == GenerateFactoryAttributeFullName) |
| | 0 | 36 | | return true; |
| | | 37 | | |
| | | 38 | | // Check for generic GenerateFactoryAttribute<T> |
| | 2165655 | 39 | | if (attributeClass.IsGenericType) |
| | | 40 | | { |
| | 38 | 41 | | var originalDef = attributeClass.OriginalDefinition; |
| | 38 | 42 | | if (originalDef.Name == GenerateFactoryAttributeName || |
| | 38 | 43 | | originalDef.ToDisplayString().StartsWith(GenerateFactoryAttributeFullName + "<")) |
| | 0 | 44 | | return true; |
| | | 45 | | } |
| | | 46 | | } |
| | | 47 | | |
| | 1544099 | 48 | | return false; |
| | | 49 | | } |
| | | 50 | | |
| | | 51 | | /// <summary> |
| | | 52 | | /// Gets the factory generation mode from the [GenerateFactory] attribute. |
| | | 53 | | /// </summary> |
| | | 54 | | /// <param name="typeSymbol">The type symbol to check.</param> |
| | | 55 | | /// <returns>The Mode value (1=Func, 2=Interface, 3=All), or 3 (All) if not specified.</returns> |
| | | 56 | | public static int GetFactoryGenerationMode(INamedTypeSymbol typeSymbol) |
| | | 57 | | { |
| | 116 | 58 | | foreach (var attribute in typeSymbol.GetAttributes()) |
| | | 59 | | { |
| | 31 | 60 | | var attributeClass = attribute.AttributeClass; |
| | 31 | 61 | | if (attributeClass == null) |
| | | 62 | | continue; |
| | | 63 | | |
| | 31 | 64 | | var name = attributeClass.Name; |
| | 31 | 65 | | var fullName = attributeClass.ToDisplayString(); |
| | | 66 | | |
| | 31 | 67 | | bool isFactoryAttribute = name == GenerateFactoryAttributeName || |
| | 31 | 68 | | fullName == GenerateFactoryAttributeFullName || |
| | 31 | 69 | | (attributeClass.IsGenericType && |
| | 31 | 70 | | attributeClass.OriginalDefinition.Name == GenerateFactoryAttributeName); |
| | | 71 | | |
| | 31 | 72 | | if (isFactoryAttribute) |
| | | 73 | | { |
| | | 74 | | // Check named argument "Mode" |
| | 58 | 75 | | foreach (var namedArg in attribute.NamedArguments) |
| | | 76 | | { |
| | 2 | 77 | | if (namedArg.Key == "Mode" && namedArg.Value.Value is int modeValue) |
| | | 78 | | { |
| | 2 | 79 | | return modeValue; |
| | | 80 | | } |
| | | 81 | | } |
| | | 82 | | } |
| | | 83 | | } |
| | | 84 | | |
| | 26 | 85 | | return 3; // Default is All (Func | Interface) |
| | | 86 | | } |
| | | 87 | | |
| | | 88 | | /// <summary> |
| | | 89 | | /// Gets the interface type from a generic [GenerateFactory<T>] attribute, if present. |
| | | 90 | | /// </summary> |
| | | 91 | | /// <param name="typeSymbol">The type symbol to check.</param> |
| | | 92 | | /// <returns>The fully qualified interface type name, or null if non-generic attribute is used.</returns> |
| | | 93 | | public static string? GetFactoryReturnInterfaceType(INamedTypeSymbol typeSymbol) |
| | | 94 | | { |
| | 116 | 95 | | foreach (var attribute in typeSymbol.GetAttributes()) |
| | | 96 | | { |
| | 31 | 97 | | var attributeClass = attribute.AttributeClass; |
| | 31 | 98 | | if (attributeClass == null) |
| | | 99 | | continue; |
| | | 100 | | |
| | | 101 | | // Check for generic GenerateFactoryAttribute<T> |
| | 31 | 102 | | if (attributeClass.IsGenericType) |
| | | 103 | | { |
| | 2 | 104 | | var originalDef = attributeClass.OriginalDefinition; |
| | 2 | 105 | | if (originalDef.Name == GenerateFactoryAttributeName) |
| | | 106 | | { |
| | | 107 | | // Extract the type argument |
| | 2 | 108 | | var typeArg = attributeClass.TypeArguments.FirstOrDefault(); |
| | 2 | 109 | | if (typeArg != null) |
| | | 110 | | { |
| | 2 | 111 | | return $"global::{typeArg.ToDisplayString()}"; |
| | | 112 | | } |
| | | 113 | | } |
| | | 114 | | } |
| | | 115 | | } |
| | | 116 | | |
| | 26 | 117 | | return null; |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | /// <summary> |
| | | 121 | | /// Partitions constructor parameters into injectable (DI-resolvable) and runtime (must be provided). |
| | | 122 | | /// </summary> |
| | | 123 | | /// <param name="typeSymbol">The type symbol to analyze.</param> |
| | | 124 | | /// <returns>A list of factory constructor infos, one for each viable constructor.</returns> |
| | | 125 | | /// <remarks> |
| | | 126 | | /// A type eligible for generated-constructor generation (<c>[GenerateConstructor]</c> |
| | | 127 | | /// or a positive field-level constructor guard trigger) has its effective constructor |
| | | 128 | | /// derived from <see cref="ConstructorGenerationDiscoveryHelper.TryGetModel"/> instead |
| | | 129 | | /// of <see cref="INamedTypeSymbol.InstanceConstructors"/>, which would otherwise only |
| | | 130 | | /// see the implicit parameterless constructor visible before the sibling |
| | | 131 | | /// <c>GeneratedConstructorGenerator</c> pass emits the real one within this |
| | | 132 | | /// compilation. The field-derived parameter list is partitioned into injectable and |
| | | 133 | | /// runtime groups using the exact same rule as a hand-written constructor. |
| | | 134 | | /// </remarks> |
| | | 135 | | public static IReadOnlyList<FactoryConstructorInfo> GetFactoryConstructors(INamedTypeSymbol typeSymbol) |
| | | 136 | | { |
| | 30 | 137 | | var generatedModel = ConstructorGenerationDiscoveryHelper.TryGetModel(typeSymbol); |
| | 30 | 138 | | if (generatedModel is not null) |
| | | 139 | | { |
| | 5 | 140 | | var generatedCtor = BuildGeneratedConstructorFactoryInfo(typeSymbol, generatedModel.Value); |
| | 5 | 141 | | return generatedCtor is null |
| | 5 | 142 | | ? Array.Empty<FactoryConstructorInfo>() |
| | 5 | 143 | | : new[] { generatedCtor.Value }; |
| | | 144 | | } |
| | | 145 | | |
| | 25 | 146 | | var result = new List<FactoryConstructorInfo>(); |
| | | 147 | | |
| | 106 | 148 | | foreach (var ctor in typeSymbol.InstanceConstructors) |
| | | 149 | | { |
| | 28 | 150 | | if (ctor.IsStatic) |
| | | 151 | | continue; |
| | | 152 | | |
| | 28 | 153 | | if (ctor.DeclaredAccessibility != Accessibility.Public) |
| | | 154 | | continue; |
| | | 155 | | |
| | | 156 | | // Extract XML documentation for parameters |
| | 28 | 157 | | var paramDocs = GetConstructorParameterDocumentation(ctor); |
| | | 158 | | |
| | 28 | 159 | | var injectableParams = new List<TypeDiscoveryHelper.ConstructorParameterInfo>(); |
| | 28 | 160 | | var runtimeParams = new List<TypeDiscoveryHelper.ConstructorParameterInfo>(); |
| | | 161 | | |
| | 174 | 162 | | foreach (var param in ctor.Parameters) |
| | | 163 | | { |
| | 59 | 164 | | var typeName = param.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); |
| | 59 | 165 | | paramDocs.TryGetValue(param.Name, out var docComment); |
| | | 166 | | |
| | 59 | 167 | | if (IsInjectableParameterType(param.Type)) |
| | | 168 | | { |
| | | 169 | | // Check for [FromKeyedServices] attribute |
| | 26 | 170 | | var serviceKey = GetFromKeyedServicesKey(param); |
| | 26 | 171 | | var paramInfo = new TypeDiscoveryHelper.ConstructorParameterInfo(typeName, serviceKey, param.Name, d |
| | 26 | 172 | | injectableParams.Add(paramInfo); |
| | | 173 | | } |
| | | 174 | | else |
| | | 175 | | { |
| | 33 | 176 | | var paramInfo = new TypeDiscoveryHelper.ConstructorParameterInfo(typeName, null, param.Name, docComm |
| | 33 | 177 | | runtimeParams.Add(paramInfo); |
| | | 178 | | } |
| | | 179 | | } |
| | | 180 | | |
| | | 181 | | // Only include constructors that have at least one runtime parameter |
| | | 182 | | // (otherwise normal registration works fine) |
| | 28 | 183 | | if (runtimeParams.Count > 0) |
| | | 184 | | { |
| | 27 | 185 | | result.Add(new FactoryConstructorInfo( |
| | 27 | 186 | | injectableParams.ToArray(), |
| | 27 | 187 | | runtimeParams.ToArray())); |
| | | 188 | | } |
| | | 189 | | } |
| | | 190 | | |
| | 25 | 191 | | return result; |
| | | 192 | | } |
| | | 193 | | |
| | | 194 | | /// <summary> |
| | | 195 | | /// Builds the single <see cref="FactoryConstructorInfo"/> for a generated |
| | | 196 | | /// constructor's field-derived parameter list, or <see langword="null"/> when no |
| | | 197 | | /// field is a runtime (non-injectable) parameter — matching the hand-written-constructor |
| | | 198 | | /// rule that a factory adds no value when every parameter is already container-resolvable. |
| | | 199 | | /// </summary> |
| | | 200 | | private static FactoryConstructorInfo? BuildGeneratedConstructorFactoryInfo( |
| | | 201 | | INamedTypeSymbol typeSymbol, |
| | | 202 | | GeneratedConstructorModel model) |
| | | 203 | | { |
| | | 204 | | // Paired by index with model.Fields: both are derived from the exact same |
| | | 205 | | // ordered, filtered field set (GeneratedConstructorEligibility.GetEligibleConstructorFields), |
| | | 206 | | // so the field's real ITypeSymbol (needed for injectability classification) lines |
| | | 207 | | // up with the model's already-normalized parameter name/type-name strings. |
| | 5 | 208 | | var fieldSymbols = GeneratedConstructorEligibility.GetEligibleConstructorFields(typeSymbol); |
| | | 209 | | |
| | 5 | 210 | | var injectableParams = new List<TypeDiscoveryHelper.ConstructorParameterInfo>(); |
| | 5 | 211 | | var runtimeParams = new List<TypeDiscoveryHelper.ConstructorParameterInfo>(); |
| | | 212 | | |
| | 30 | 213 | | for (var i = 0; i < model.Fields.Length; i++) |
| | | 214 | | { |
| | 10 | 215 | | var field = model.Fields[i]; |
| | 10 | 216 | | var paramInfo = new TypeDiscoveryHelper.ConstructorParameterInfo(field.ParameterTypeName, serviceKey: null, |
| | | 217 | | |
| | 10 | 218 | | if (IsInjectableParameterType(fieldSymbols[i].Type)) |
| | | 219 | | { |
| | 6 | 220 | | injectableParams.Add(paramInfo); |
| | | 221 | | } |
| | | 222 | | else |
| | | 223 | | { |
| | 4 | 224 | | runtimeParams.Add(paramInfo); |
| | | 225 | | } |
| | | 226 | | } |
| | | 227 | | |
| | 5 | 228 | | if (runtimeParams.Count == 0) |
| | 1 | 229 | | return null; |
| | | 230 | | |
| | 4 | 231 | | return new FactoryConstructorInfo(injectableParams.ToArray(), runtimeParams.ToArray()); |
| | | 232 | | } |
| | | 233 | | |
| | | 234 | | /// <summary> |
| | | 235 | | /// Extracts parameter documentation from a constructor's XML documentation comments. |
| | | 236 | | /// </summary> |
| | | 237 | | private static Dictionary<string, string> GetConstructorParameterDocumentation(IMethodSymbol constructor) |
| | | 238 | | { |
| | 28 | 239 | | var result = new Dictionary<string, string>(StringComparer.Ordinal); |
| | | 240 | | |
| | 28 | 241 | | var xmlDoc = constructor.GetDocumentationCommentXml(); |
| | 28 | 242 | | if (string.IsNullOrWhiteSpace(xmlDoc)) |
| | 23 | 243 | | return result; |
| | | 244 | | |
| | | 245 | | try |
| | | 246 | | { |
| | | 247 | | // Parse the XML documentation |
| | 5 | 248 | | var doc = System.Xml.Linq.XDocument.Parse(xmlDoc); |
| | 5 | 249 | | var paramElements = doc.Descendants("param"); |
| | | 250 | | |
| | 32 | 251 | | foreach (var param in paramElements) |
| | | 252 | | { |
| | 11 | 253 | | var nameAttr = param.Attribute("name"); |
| | 11 | 254 | | if (nameAttr is null || string.IsNullOrWhiteSpace(nameAttr.Value)) |
| | | 255 | | continue; |
| | | 256 | | |
| | | 257 | | // Get the inner text/content of the param element |
| | 11 | 258 | | var content = param.Value?.Trim(); |
| | 11 | 259 | | if (!string.IsNullOrWhiteSpace(content)) |
| | | 260 | | { |
| | 11 | 261 | | result[nameAttr.Value] = content!; |
| | | 262 | | } |
| | | 263 | | } |
| | 5 | 264 | | } |
| | 0 | 265 | | catch |
| | | 266 | | { |
| | | 267 | | // If XML parsing fails, return empty dictionary |
| | 0 | 268 | | } |
| | | 269 | | |
| | 5 | 270 | | return result; |
| | | 271 | | } |
| | | 272 | | |
| | | 273 | | private static string? GetFromKeyedServicesKey(IParameterSymbol param) |
| | | 274 | | { |
| | | 275 | | const string FromKeyedServicesAttributeName = "Microsoft.Extensions.DependencyInjection.FromKeyedServicesAttribu |
| | | 276 | | |
| | 52 | 277 | | foreach (var attr in param.GetAttributes()) |
| | | 278 | | { |
| | 0 | 279 | | var attrClass = attr.AttributeClass; |
| | 0 | 280 | | if (attrClass is null) |
| | | 281 | | continue; |
| | | 282 | | |
| | 0 | 283 | | var attrFullName = attrClass.ToDisplayString(); |
| | 0 | 284 | | if (attrFullName == FromKeyedServicesAttributeName) |
| | | 285 | | { |
| | | 286 | | // Extract the key from the constructor argument |
| | 0 | 287 | | if (attr.ConstructorArguments.Length > 0) |
| | | 288 | | { |
| | 0 | 289 | | var keyArg = attr.ConstructorArguments[0]; |
| | 0 | 290 | | if (keyArg.Value is string keyValue) |
| | | 291 | | { |
| | 0 | 292 | | return keyValue; |
| | | 293 | | } |
| | | 294 | | } |
| | | 295 | | } |
| | | 296 | | } |
| | | 297 | | |
| | 26 | 298 | | return null; |
| | | 299 | | } |
| | | 300 | | |
| | | 301 | | private static bool IsInjectableParameterType(ITypeSymbol typeSymbol) |
| | | 302 | | { |
| | | 303 | | // Interfaces and abstract classes are typically injectable |
| | 69 | 304 | | if (typeSymbol.TypeKind == TypeKind.Interface) |
| | 32 | 305 | | return true; |
| | | 306 | | |
| | 37 | 307 | | if (typeSymbol is INamedTypeSymbol namedType && namedType.IsAbstract) |
| | 0 | 308 | | return true; |
| | | 309 | | |
| | | 310 | | // Common framework types are injectable |
| | 37 | 311 | | var fullName = typeSymbol.ToDisplayString(); |
| | 37 | 312 | | if (fullName.StartsWith("Microsoft.Extensions.", StringComparison.Ordinal)) |
| | 0 | 313 | | return true; |
| | | 314 | | |
| | | 315 | | // Classes with [Singleton], [Scoped], or [Transient] are injectable |
| | 37 | 316 | | if (typeSymbol is INamedTypeSymbol classType) |
| | | 317 | | { |
| | 260 | 318 | | foreach (var attr in classType.GetAttributes()) |
| | | 319 | | { |
| | 93 | 320 | | var attrName = attr.AttributeClass?.Name; |
| | 93 | 321 | | if (attrName is "SingletonAttribute" or "ScopedAttribute" or "TransientAttribute") |
| | 0 | 322 | | return true; |
| | | 323 | | } |
| | | 324 | | } |
| | | 325 | | |
| | 37 | 326 | | return false; |
| | | 327 | | } |
| | | 328 | | |
| | | 329 | | /// <summary> |
| | | 330 | | /// Represents a constructor suitable for factory generation. |
| | | 331 | | /// </summary> |
| | | 332 | | public readonly struct FactoryConstructorInfo |
| | | 333 | | { |
| | | 334 | | public FactoryConstructorInfo( |
| | | 335 | | TypeDiscoveryHelper.ConstructorParameterInfo[] injectableParameters, |
| | | 336 | | TypeDiscoveryHelper.ConstructorParameterInfo[] runtimeParameters) |
| | | 337 | | { |
| | 31 | 338 | | InjectableParameters = injectableParameters; |
| | 31 | 339 | | RuntimeParameters = runtimeParameters; |
| | 31 | 340 | | } |
| | | 341 | | |
| | | 342 | | /// <summary>Parameters that can be resolved from the service provider.</summary> |
| | 90 | 343 | | public TypeDiscoveryHelper.ConstructorParameterInfo[] InjectableParameters { get; } |
| | | 344 | | |
| | | 345 | | /// <summary>Parameters that must be provided at factory call time.</summary> |
| | 210 | 346 | | public TypeDiscoveryHelper.ConstructorParameterInfo[] RuntimeParameters { get; } |
| | | 347 | | } |
| | | 348 | | } |