| | | 1 | | using Microsoft.CodeAnalysis; |
| | | 2 | | using Microsoft.CodeAnalysis.Text; |
| | | 3 | | using NexusLabs.Needlr.Generators.Helpers; |
| | | 4 | | using NexusLabs.Needlr.Generators.Models; |
| | | 5 | | using System.Text; |
| | | 6 | | |
| | | 7 | | namespace NexusLabs.Needlr.Generators; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Incremental source generator that produces a compile-time type registry |
| | | 11 | | /// for dependency injection, eliminating runtime reflection. |
| | | 12 | | /// </summary> |
| | | 13 | | [Generator(LanguageNames.CSharp)] |
| | | 14 | | public sealed class TypeRegistryGenerator : IIncrementalGenerator |
| | | 15 | | { |
| | | 16 | | private const string GenerateTypeRegistryAttributeName = "NexusLabs.Needlr.Generators.GenerateTypeRegistryAttribute" |
| | | 17 | | |
| | | 18 | | public void Initialize(IncrementalGeneratorInitializationContext context) |
| | | 19 | | { |
| | | 20 | | // Combine compilation with analyzer config options to read MSBuild properties |
| | 465 | 21 | | var compilationAndOptions = context.CompilationProvider |
| | 465 | 22 | | .Combine(context.AnalyzerConfigOptionsProvider); |
| | | 23 | | |
| | | 24 | | // ForAttributeWithMetadataName doesn't work for assembly-level attributes. |
| | | 25 | | // Instead, we register directly on the compilation provider and check |
| | | 26 | | // compilation.Assembly.GetAttributes() for [GenerateTypeRegistry]. |
| | 465 | 27 | | context.RegisterSourceOutput(compilationAndOptions, static (spc, source) => |
| | 465 | 28 | | { |
| | 465 | 29 | | var (compilation, configOptions) = source; |
| | 465 | 30 | | |
| | 465 | 31 | | var attributeInfo = GetAttributeInfoFromCompilation(compilation); |
| | 465 | 32 | | if (attributeInfo == null) |
| | 1 | 33 | | return; |
| | 465 | 34 | | |
| | 464 | 35 | | var info = attributeInfo.Value; |
| | 464 | 36 | | var assemblyName = compilation.AssemblyName ?? "Generated"; |
| | 465 | 37 | | |
| | 465 | 38 | | // Read breadcrumb level from MSBuild property |
| | 464 | 39 | | var breadcrumbLevel = GetBreadcrumbLevel(configOptions); |
| | 464 | 40 | | var projectDirectory = GetProjectDirectory(configOptions); |
| | 464 | 41 | | var breadcrumbs = new BreadcrumbWriter(breadcrumbLevel); |
| | 465 | 42 | | |
| | 465 | 43 | | // Check if this is an AOT project |
| | 464 | 44 | | var isAotProject = IsAotProject(configOptions); |
| | 465 | 45 | | |
| | 464 | 46 | | var discoveryResult = DiscoverTypes( |
| | 464 | 47 | | compilation, |
| | 464 | 48 | | info.NamespacePrefixes, |
| | 464 | 49 | | info.ExcludeNamespacePrefixes, |
| | 464 | 50 | | info.IncludeSelf); |
| | 465 | 51 | | |
| | 465 | 52 | | // Discover referenced assemblies with [GenerateTypeRegistry] for forced loading. |
| | 465 | 53 | | // Done early so the empty-result check below can include this in its decision. |
| | 465 | 54 | | // Note: Order of force-loading doesn't matter; ordering is applied at service registration time |
| | 464 | 55 | | var referencedAssemblies = AssemblyDiscoveryHelper.DiscoverReferencedAssembliesWithTypeRegistry(compilation) |
| | 2 | 56 | | .OrderBy(a => a, StringComparer.OrdinalIgnoreCase) |
| | 464 | 57 | | .ToList(); |
| | 465 | 58 | | |
| | 465 | 59 | | // Nothing was discovered: no injectable types, factories, providers, options, |
| | 465 | 60 | | // interceptors, hosted services, plugins, no referenced assemblies to force-load, |
| | 465 | 61 | | // no inaccessible type errors, and no missing TypeRegistry warnings. |
| | 464 | 62 | | var nothingDiscovered = |
| | 464 | 63 | | discoveryResult.InjectableTypes.Count == 0 && |
| | 464 | 64 | | discoveryResult.PluginTypes.Count == 0 && |
| | 464 | 65 | | discoveryResult.Decorators.Count == 0 && |
| | 464 | 66 | | discoveryResult.InterceptedServices.Count == 0 && |
| | 464 | 67 | | discoveryResult.Factories.Count == 0 && |
| | 464 | 68 | | discoveryResult.Options.Count == 0 && |
| | 464 | 69 | | discoveryResult.HttpClients.Count == 0 && |
| | 464 | 70 | | discoveryResult.HostedServices.Count == 0 && |
| | 464 | 71 | | discoveryResult.Providers.Count == 0 && |
| | 464 | 72 | | discoveryResult.InaccessibleTypes.Count == 0 && |
| | 464 | 73 | | discoveryResult.MissingTypeRegistryPlugins.Count == 0 && |
| | 464 | 74 | | referencedAssemblies.Count == 0; |
| | 465 | 75 | | |
| | 465 | 76 | | // A type-less assembly that still carries [GenerateTypeRegistry] (guaranteed here by the |
| | 465 | 77 | | // attributeInfo guard above) is a declared Needlr participant. Consumers force-load |
| | 465 | 78 | | // typeof({Assembly}.Generated.TypeRegistry) for every attribute-carrying referenced |
| | 465 | 79 | | // assembly, so emitting nothing makes those consumers fail to compile with CS0234. Emit |
| | 465 | 80 | | // a minimal registry instead. It depends only on the attributes package (never the |
| | 465 | 81 | | // injection packages), so it compiles whether or not this assembly references them — a |
| | 465 | 82 | | // domain, contracts, or documentation-only project participates without being forced to |
| | 465 | 83 | | // take a dependency it would not otherwise have. |
| | 464 | 84 | | if (nothingDiscovered) |
| | 465 | 85 | | { |
| | 7 | 86 | | var emptyRegistrySource = CodeGen.EmptyTypeRegistryCodeGenerator.GenerateTypeRegistrySource(assemblyName |
| | 7 | 87 | | spc.AddSource("TypeRegistry.g.cs", SourceText.From(emptyRegistrySource, Encoding.UTF8)); |
| | 465 | 88 | | |
| | 7 | 89 | | var emptyBootstrapSource = CodeGen.EmptyTypeRegistryCodeGenerator.GenerateBootstrapSource(assemblyName, |
| | 7 | 90 | | spc.AddSource("NeedlrSourceGenBootstrap.g.cs", SourceText.From(emptyBootstrapSource, Encoding.UTF8)); |
| | 7 | 91 | | return; |
| | 465 | 92 | | } |
| | 465 | 93 | | |
| | 465 | 94 | | // Report errors for inaccessible internal types in referenced assemblies |
| | 5552 | 95 | | foreach (var inaccessibleType in discoveryResult.InaccessibleTypes) |
| | 465 | 96 | | { |
| | 2319 | 97 | | spc.ReportDiagnostic(Diagnostic.Create( |
| | 2319 | 98 | | DiagnosticDescriptors.InaccessibleInternalType, |
| | 2319 | 99 | | Location.None, |
| | 2319 | 100 | | inaccessibleType.TypeName, |
| | 2319 | 101 | | inaccessibleType.AssemblyName)); |
| | 465 | 102 | | } |
| | 465 | 103 | | |
| | 465 | 104 | | // Report errors for referenced assemblies with internal plugin types but no [GenerateTypeRegistry] |
| | 916 | 105 | | foreach (var missingPlugin in discoveryResult.MissingTypeRegistryPlugins) |
| | 465 | 106 | | { |
| | 1 | 107 | | spc.ReportDiagnostic(Diagnostic.Create( |
| | 1 | 108 | | DiagnosticDescriptors.MissingGenerateTypeRegistryAttribute, |
| | 1 | 109 | | Location.None, |
| | 1 | 110 | | missingPlugin.AssemblyName, |
| | 1 | 111 | | missingPlugin.TypeName)); |
| | 465 | 112 | | } |
| | 465 | 113 | | |
| | 465 | 114 | | // NDLRGEN020: Previously reported error if [Options] used in AOT project |
| | 465 | 115 | | // Now removed for parity - we generate best-effort code and let unsupported |
| | 465 | 116 | | // types fail at runtime (matching non-AOT ConfigurationBinder behavior) |
| | 465 | 117 | | |
| | 465 | 118 | | // NDLRGEN021: Report warning for non-partial positional records |
| | 1083 | 119 | | foreach (var opt in discoveryResult.Options.Where(o => o.IsNonPartialPositionalRecord)) |
| | 465 | 120 | | { |
| | 2 | 121 | | spc.ReportDiagnostic(Diagnostic.Create( |
| | 2 | 122 | | DiagnosticDescriptors.PositionalRecordMustBePartial, |
| | 2 | 123 | | Location.None, |
| | 2 | 124 | | opt.TypeName)); |
| | 465 | 125 | | } |
| | 465 | 126 | | |
| | 465 | 127 | | // NDLRGEN022: Detect disposable captive dependencies using inferred lifetimes |
| | 457 | 128 | | CaptiveDependencyAnalyzer.ReportDisposableCaptiveDependencies(spc, discoveryResult); |
| | 465 | 129 | | |
| | 457 | 130 | | var sourceText = GenerateTypeRegistrySource(discoveryResult, assemblyName, breadcrumbs, projectDirectory, is |
| | 457 | 131 | | spc.AddSource("TypeRegistry.g.cs", SourceText.From(sourceText, Encoding.UTF8)); |
| | 465 | 132 | | |
| | 457 | 133 | | var bootstrapText = CodeGen.BootstrapCodeGenerator.GenerateModuleInitializerBootstrapSource(assemblyName, re |
| | 457 | 134 | | spc.AddSource("NeedlrSourceGenBootstrap.g.cs", SourceText.From(bootstrapText, Encoding.UTF8)); |
| | 465 | 135 | | |
| | 465 | 136 | | // Generate interceptor proxy classes if any were discovered |
| | 457 | 137 | | if (discoveryResult.InterceptedServices.Count > 0) |
| | 465 | 138 | | { |
| | 14 | 139 | | var interceptorProxiesText = CodeGen.InterceptorCodeGenerator.GenerateInterceptorProxiesSource(discovery |
| | 14 | 140 | | spc.AddSource("InterceptorProxies.g.cs", SourceText.From(interceptorProxiesText, Encoding.UTF8)); |
| | 465 | 141 | | } |
| | 465 | 142 | | |
| | 465 | 143 | | // Generate factory classes if any were discovered |
| | 457 | 144 | | if (discoveryResult.Factories.Count > 0) |
| | 465 | 145 | | { |
| | 24 | 146 | | var factoriesText = CodeGen.FactoryCodeGenerator.GenerateFactoriesSource(discoveryResult.Factories, asse |
| | 24 | 147 | | spc.AddSource("Factories.g.cs", SourceText.From(factoriesText, Encoding.UTF8)); |
| | 465 | 148 | | } |
| | 465 | 149 | | |
| | 465 | 150 | | // Generate provider classes if any were discovered |
| | 457 | 151 | | if (discoveryResult.Providers.Count > 0) |
| | 465 | 152 | | { |
| | 465 | 153 | | // Interface-based providers go in the Generated namespace |
| | 35 | 154 | | var interfaceProviders = discoveryResult.Providers.Where(p => p.IsInterface).ToList(); |
| | 17 | 155 | | if (interfaceProviders.Count > 0) |
| | 465 | 156 | | { |
| | 11 | 157 | | var providersText = CodeGen.ProviderCodeGenerator.GenerateProvidersSource(interfaceProviders, assemb |
| | 11 | 158 | | spc.AddSource("Providers.g.cs", SourceText.From(providersText, Encoding.UTF8)); |
| | 465 | 159 | | } |
| | 465 | 160 | | |
| | 465 | 161 | | // Shorthand class providers need to be generated in their original namespace |
| | 35 | 162 | | var classProviders = discoveryResult.Providers.Where(p => !p.IsInterface && p.IsPartial).ToList(); |
| | 46 | 163 | | foreach (var provider in classProviders) |
| | 465 | 164 | | { |
| | 6 | 165 | | var providerText = CodeGen.ProviderCodeGenerator.GenerateShorthandProviderSource(provider, assemblyN |
| | 6 | 166 | | spc.AddSource($"Provider.{provider.SimpleTypeName}.g.cs", SourceText.From(providerText, Encoding.UTF |
| | 465 | 167 | | } |
| | 465 | 168 | | } |
| | 465 | 169 | | |
| | 465 | 170 | | // Generate options validator classes if any have validation methods |
| | 622 | 171 | | var optionsWithValidators = discoveryResult.Options.Where(o => o.HasValidatorMethod).ToList(); |
| | 457 | 172 | | if (optionsWithValidators.Count > 0) |
| | 465 | 173 | | { |
| | 18 | 174 | | var validatorsText = CodeGen.OptionsCodeGenerator.GenerateOptionsValidatorsSource(optionsWithValidators, |
| | 18 | 175 | | spc.AddSource("OptionsValidators.g.cs", SourceText.From(validatorsText, Encoding.UTF8)); |
| | 465 | 176 | | } |
| | 465 | 177 | | |
| | 465 | 178 | | // Generate DataAnnotations validator classes if any have DataAnnotation attributes |
| | 622 | 179 | | var optionsWithDataAnnotations = discoveryResult.Options.Where(o => o.HasDataAnnotations).ToList(); |
| | 457 | 180 | | if (optionsWithDataAnnotations.Count > 0) |
| | 465 | 181 | | { |
| | 18 | 182 | | var dataAnnotationsValidatorsText = CodeGen.OptionsCodeGenerator.GenerateDataAnnotationsValidatorsSource |
| | 18 | 183 | | spc.AddSource("OptionsDataAnnotationsValidators.g.cs", SourceText.From(dataAnnotationsValidatorsText, En |
| | 465 | 184 | | } |
| | 465 | 185 | | |
| | 465 | 186 | | // Generate parameterless constructors for partial positional records with [Options] |
| | 622 | 187 | | var optionsNeedingConstructors = discoveryResult.Options.Where(o => o.NeedsGeneratedConstructor).ToList(); |
| | 457 | 188 | | if (optionsNeedingConstructors.Count > 0) |
| | 465 | 189 | | { |
| | 7 | 190 | | var constructorsText = CodeGen.OptionsCodeGenerator.GeneratePositionalRecordConstructorsSource(optionsNe |
| | 7 | 191 | | spc.AddSource("OptionsConstructors.g.cs", SourceText.From(constructorsText, Encoding.UTF8)); |
| | 465 | 192 | | } |
| | 465 | 193 | | |
| | 465 | 194 | | // Generate ServiceCatalog for runtime introspection |
| | 457 | 195 | | var catalogText = CodeGen.ServiceCatalogCodeGenerator.GenerateServiceCatalogSource(discoveryResult, assembly |
| | 457 | 196 | | spc.AddSource("ServiceCatalog.g.cs", SourceText.From(catalogText, Encoding.UTF8)); |
| | 465 | 197 | | |
| | 465 | 198 | | // Generate diagnostic output files if configured |
| | 457 | 199 | | var diagnosticOptions = GetDiagnosticOptions(configOptions); |
| | 457 | 200 | | if (diagnosticOptions.Enabled) |
| | 465 | 201 | | { |
| | 95 | 202 | | var referencedAssemblyTypes = AssemblyDiscoveryHelper.DiscoverReferencedAssemblyTypesForDiagnostics(comp |
| | 95 | 203 | | var diagnosticsText = DiagnosticsGenerator.GenerateDiagnosticsSource(discoveryResult, assemblyName, proj |
| | 95 | 204 | | spc.AddSource("NeedlrDiagnostics.g.cs", SourceText.From(diagnosticsText, Encoding.UTF8)); |
| | 465 | 205 | | } |
| | 465 | 206 | | |
| | 465 | 207 | | // Generate IDE graph export if configured |
| | 457 | 208 | | if (ShouldExportGraph(configOptions)) |
| | 465 | 209 | | { |
| | 465 | 210 | | // Discover types from referenced assemblies with [GenerateTypeRegistry] for graph inclusion |
| | 4 | 211 | | var referencedAssemblyTypesForGraph = AssemblyDiscoveryHelper.DiscoverReferencedAssemblyTypesForGraph(co |
| | 465 | 212 | | |
| | 4 | 213 | | var graphJson = Export.GraphExporter.GenerateGraphJson( |
| | 4 | 214 | | discoveryResult, |
| | 4 | 215 | | assemblyName, |
| | 4 | 216 | | projectDirectory, |
| | 4 | 217 | | diagnostics: null, |
| | 4 | 218 | | referencedAssemblyTypes: referencedAssemblyTypesForGraph); |
| | 465 | 219 | | |
| | 465 | 220 | | // Embed graph as a comment in a generated file so it's accessible |
| | 465 | 221 | | // The actual JSON is written to obj folder via the generated code |
| | 4 | 222 | | var graphSourceText = Export.GraphExporter.GenerateGraphExportSource(graphJson, assemblyName, breadcrumb |
| | 4 | 223 | | spc.AddSource("NeedlrGraph.g.cs", SourceText.From(graphSourceText, Encoding.UTF8)); |
| | 465 | 224 | | } |
| | 922 | 225 | | }); |
| | 465 | 226 | | } |
| | | 227 | | |
| | | 228 | | private static BreadcrumbLevel GetBreadcrumbLevel(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider c |
| | | 229 | | { |
| | 464 | 230 | | if (configOptions.GlobalOptions.TryGetValue("build_property.NeedlrBreadcrumbLevel", out var levelStr) && |
| | 464 | 231 | | !string.IsNullOrWhiteSpace(levelStr)) |
| | | 232 | | { |
| | 259 | 233 | | if (levelStr.Equals("None", StringComparison.OrdinalIgnoreCase)) |
| | 17 | 234 | | return BreadcrumbLevel.None; |
| | 242 | 235 | | if (levelStr.Equals("Verbose", StringComparison.OrdinalIgnoreCase)) |
| | 28 | 236 | | return BreadcrumbLevel.Verbose; |
| | | 237 | | } |
| | | 238 | | |
| | | 239 | | // Default to Minimal |
| | 419 | 240 | | return BreadcrumbLevel.Minimal; |
| | | 241 | | } |
| | | 242 | | |
| | | 243 | | private static string? GetProjectDirectory(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider configOp |
| | | 244 | | { |
| | | 245 | | // Try to get the project directory from MSBuild properties |
| | 464 | 246 | | if (configOptions.GlobalOptions.TryGetValue("build_property.ProjectDir", out var projectDir) && |
| | 464 | 247 | | !string.IsNullOrWhiteSpace(projectDir)) |
| | | 248 | | { |
| | 0 | 249 | | return projectDir.TrimEnd('/', '\\'); |
| | | 250 | | } |
| | | 251 | | |
| | 464 | 252 | | return null; |
| | | 253 | | } |
| | | 254 | | |
| | | 255 | | private static DiagnosticOptions GetDiagnosticOptions(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvid |
| | | 256 | | { |
| | 457 | 257 | | configOptions.GlobalOptions.TryGetValue("build_property.NeedlrDiagnostics", out var enabled); |
| | 457 | 258 | | configOptions.GlobalOptions.TryGetValue("build_property.NeedlrDiagnosticsPath", out var outputPath); |
| | 457 | 259 | | configOptions.GlobalOptions.TryGetValue("build_property.NeedlrDiagnosticsFilter", out var filter); |
| | | 260 | | |
| | 457 | 261 | | return DiagnosticOptions.Parse(enabled, outputPath, filter); |
| | | 262 | | } |
| | | 263 | | |
| | | 264 | | /// <summary> |
| | | 265 | | /// Checks if the IDE graph export is enabled. |
| | | 266 | | /// </summary> |
| | | 267 | | private static bool ShouldExportGraph(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider configOptions |
| | | 268 | | { |
| | | 269 | | // Export graph is disabled by default |
| | | 270 | | // Enable with NeedlrExportGraph=true in project file |
| | 457 | 271 | | if (configOptions.GlobalOptions.TryGetValue("build_property.NeedlrExportGraph", out var exportGraph) && |
| | 457 | 272 | | exportGraph.Equals("true", StringComparison.OrdinalIgnoreCase)) |
| | | 273 | | { |
| | 4 | 274 | | return true; |
| | | 275 | | } |
| | 453 | 276 | | return false; |
| | | 277 | | } |
| | | 278 | | |
| | | 279 | | /// <summary> |
| | | 280 | | /// Checks if the project is configured for AOT compilation. |
| | | 281 | | /// Returns true if either PublishAot or IsAotCompatible is set to true. |
| | | 282 | | /// </summary> |
| | | 283 | | private static bool IsAotProject(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider configOptions) |
| | | 284 | | { |
| | 464 | 285 | | if (configOptions.GlobalOptions.TryGetValue("build_property.PublishAot", out var publishAot) && |
| | 464 | 286 | | publishAot.Equals("true", StringComparison.OrdinalIgnoreCase)) |
| | | 287 | | { |
| | 79 | 288 | | return true; |
| | | 289 | | } |
| | | 290 | | |
| | 385 | 291 | | if (configOptions.GlobalOptions.TryGetValue("build_property.IsAotCompatible", out var isAotCompatible) && |
| | 385 | 292 | | isAotCompatible.Equals("true", StringComparison.OrdinalIgnoreCase)) |
| | | 293 | | { |
| | 1 | 294 | | return true; |
| | | 295 | | } |
| | | 296 | | |
| | 384 | 297 | | return false; |
| | | 298 | | } |
| | | 299 | | |
| | | 300 | | private static AttributeInfo? GetAttributeInfoFromCompilation(Compilation compilation) |
| | | 301 | | { |
| | | 302 | | // Get assembly-level attributes directly from the compilation |
| | 1394 | 303 | | foreach (var attribute in compilation.Assembly.GetAttributes()) |
| | | 304 | | { |
| | 464 | 305 | | var attrClassName = attribute.AttributeClass?.ToDisplayString(); |
| | | 306 | | |
| | | 307 | | // Check if this is our attribute (various name format possibilities) |
| | 464 | 308 | | if (attrClassName != GenerateTypeRegistryAttributeName) |
| | | 309 | | continue; |
| | | 310 | | |
| | 464 | 311 | | string[]? namespacePrefixes = null; |
| | 464 | 312 | | string[]? excludeNamespacePrefixes = null; |
| | 464 | 313 | | var includeSelf = true; |
| | | 314 | | |
| | 1104 | 315 | | foreach (var namedArg in attribute.NamedArguments) |
| | | 316 | | { |
| | 88 | 317 | | switch (namedArg.Key) |
| | | 318 | | { |
| | | 319 | | case "IncludeNamespacePrefixes": |
| | 78 | 320 | | if (!namedArg.Value.IsNull && namedArg.Value.Values.Length > 0) |
| | | 321 | | { |
| | 78 | 322 | | namespacePrefixes = namedArg.Value.Values |
| | 79 | 323 | | .Where(v => v.Value is string) |
| | 79 | 324 | | .Select(v => (string)v.Value!) |
| | 78 | 325 | | .ToArray(); |
| | | 326 | | } |
| | 78 | 327 | | break; |
| | | 328 | | |
| | | 329 | | case "ExcludeNamespacePrefixes": |
| | 0 | 330 | | if (!namedArg.Value.IsNull && namedArg.Value.Values.Length > 0) |
| | | 331 | | { |
| | 0 | 332 | | excludeNamespacePrefixes = namedArg.Value.Values |
| | 0 | 333 | | .Where(v => v.Value is string) |
| | 0 | 334 | | .Select(v => (string)v.Value!) |
| | 0 | 335 | | .ToArray(); |
| | | 336 | | } |
| | 0 | 337 | | break; |
| | | 338 | | |
| | | 339 | | case "IncludeSelf": |
| | 10 | 340 | | if (namedArg.Value.Value is bool selfValue) |
| | | 341 | | { |
| | 10 | 342 | | includeSelf = selfValue; |
| | | 343 | | } |
| | | 344 | | break; |
| | | 345 | | } |
| | | 346 | | } |
| | | 347 | | |
| | 464 | 348 | | return new AttributeInfo(namespacePrefixes, excludeNamespacePrefixes, includeSelf); |
| | | 349 | | } |
| | | 350 | | |
| | 1 | 351 | | return null; |
| | | 352 | | } |
| | | 353 | | |
| | | 354 | | private static DiscoveryResult DiscoverTypes( |
| | | 355 | | Compilation compilation, |
| | | 356 | | string[]? namespacePrefixes, |
| | | 357 | | string[]? excludeNamespacePrefixes, |
| | | 358 | | bool includeSelf) |
| | | 359 | | { |
| | 464 | 360 | | var injectableTypes = new List<DiscoveredType>(); |
| | 464 | 361 | | var pluginTypes = new List<DiscoveredPlugin>(); |
| | 464 | 362 | | var decorators = new List<DiscoveredDecorator>(); |
| | 464 | 363 | | var openDecorators = new List<DiscoveredOpenDecorator>(); |
| | 464 | 364 | | var interceptedServices = new List<DiscoveredInterceptedService>(); |
| | 464 | 365 | | var factories = new List<DiscoveredFactory>(); |
| | 464 | 366 | | var options = new List<DiscoveredOptions>(); |
| | 464 | 367 | | var hostedServices = new List<DiscoveredHostedService>(); |
| | 464 | 368 | | var providers = new List<DiscoveredProvider>(); |
| | 464 | 369 | | var httpClients = new List<DiscoveredHttpClient>(); |
| | 464 | 370 | | var inaccessibleTypes = new List<InaccessibleType>(); |
| | 464 | 371 | | var prefixList = namespacePrefixes?.ToList(); |
| | 464 | 372 | | var excludePrefixList = excludeNamespacePrefixes?.ToList(); |
| | | 373 | | |
| | | 374 | | // Compute the generated namespace for the current assembly |
| | 464 | 375 | | var currentAssemblyName = compilation.Assembly.Name; |
| | 464 | 376 | | var safeAssemblyName = GeneratorHelpers.SanitizeIdentifier(currentAssemblyName); |
| | 464 | 377 | | var generatedNamespace = $"{safeAssemblyName}.Generated"; |
| | | 378 | | |
| | | 379 | | // Collect types from the current compilation if includeSelf is true |
| | 464 | 380 | | if (includeSelf) |
| | | 381 | | { |
| | 463 | 382 | | CollectTypesFromAssembly(compilation.Assembly, prefixList, excludePrefixList, injectableTypes, pluginTypes, |
| | | 383 | | } |
| | | 384 | | |
| | | 385 | | // Collect types from all referenced assemblies |
| | 157678 | 386 | | foreach (var reference in compilation.References) |
| | | 387 | | { |
| | 78375 | 388 | | if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assemblySymbol) |
| | | 389 | | { |
| | | 390 | | // Skip assemblies that already have [GenerateTypeRegistry] — those assemblies |
| | | 391 | | // register their own types at runtime via their own TypeRegistry and cascade |
| | | 392 | | // loading. Scanning them here would trigger false NDLRGEN001 errors for their |
| | | 393 | | // internal types. |
| | 78188 | 394 | | if (TypeDiscoveryHelper.HasGenerateTypeRegistryAttribute(assemblySymbol)) |
| | | 395 | | continue; |
| | | 396 | | |
| | | 397 | | // For referenced assemblies, they use their own generated namespace |
| | 78169 | 398 | | var refSafeAssemblyName = GeneratorHelpers.SanitizeIdentifier(assemblySymbol.Name); |
| | 78169 | 399 | | var refGeneratedNamespace = $"{refSafeAssemblyName}.Generated"; |
| | 78169 | 400 | | CollectTypesFromAssembly(assemblySymbol, prefixList, excludePrefixList, injectableTypes, pluginTypes, de |
| | | 401 | | } |
| | | 402 | | } |
| | | 403 | | |
| | | 404 | | // Expand open generic decorators into closed decorator registrations |
| | 464 | 405 | | if (openDecorators.Count > 0) |
| | | 406 | | { |
| | 6 | 407 | | CodeGen.DecoratorsCodeGenerator.ExpandOpenDecorators(injectableTypes, openDecorators, decorators); |
| | | 408 | | } |
| | | 409 | | |
| | | 410 | | // Filter out nested options types (types used as properties in other options types) |
| | 464 | 411 | | if (options.Count > 1) |
| | | 412 | | { |
| | 19 | 413 | | options = OptionsDiscoveryHelper.FilterNestedOptions(options, compilation); |
| | | 414 | | } |
| | | 415 | | |
| | | 416 | | // Check for referenced assemblies with internal plugin types but no [GenerateTypeRegistry] |
| | 464 | 417 | | var missingTypeRegistryPlugins = new List<MissingTypeRegistryPlugin>(); |
| | 157678 | 418 | | foreach (var reference in compilation.References) |
| | | 419 | | { |
| | 78375 | 420 | | if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assemblySymbol) |
| | | 421 | | { |
| | | 422 | | // Skip assemblies that already have [GenerateTypeRegistry] |
| | 78188 | 423 | | if (TypeDiscoveryHelper.HasGenerateTypeRegistryAttribute(assemblySymbol)) |
| | | 424 | | continue; |
| | | 425 | | |
| | | 426 | | // Look for internal types that implement Needlr plugin interfaces |
| | 3830500 | 427 | | foreach (var typeSymbol in TypeDiscoveryHelper.GetAllTypes(assemblySymbol.GlobalNamespace)) |
| | | 428 | | { |
| | 1837081 | 429 | | if (!TypeDiscoveryHelper.IsInternalOrLessAccessible(typeSymbol)) |
| | | 430 | | continue; |
| | | 431 | | |
| | 87423 | 432 | | if (!TypeDiscoveryHelper.ImplementsNeedlrPluginInterface(typeSymbol)) |
| | | 433 | | continue; |
| | | 434 | | |
| | | 435 | | // This is an internal plugin type in an assembly without [GenerateTypeRegistry] |
| | 1 | 436 | | var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol); |
| | 1 | 437 | | missingTypeRegistryPlugins.Add(new MissingTypeRegistryPlugin(typeName, assemblySymbol.Name)); |
| | | 438 | | } |
| | | 439 | | } |
| | | 440 | | } |
| | | 441 | | |
| | 464 | 442 | | return new DiscoveryResult(injectableTypes, pluginTypes, decorators, inaccessibleTypes, missingTypeRegistryPlugi |
| | | 443 | | } |
| | | 444 | | |
| | | 445 | | private static void CollectTypesFromAssembly( |
| | | 446 | | IAssemblySymbol assembly, |
| | | 447 | | IReadOnlyList<string>? namespacePrefixes, |
| | | 448 | | IReadOnlyList<string>? excludeNamespacePrefixes, |
| | | 449 | | List<DiscoveredType> injectableTypes, |
| | | 450 | | List<DiscoveredPlugin> pluginTypes, |
| | | 451 | | List<DiscoveredDecorator> decorators, |
| | | 452 | | List<DiscoveredOpenDecorator> openDecorators, |
| | | 453 | | List<DiscoveredInterceptedService> interceptedServices, |
| | | 454 | | List<DiscoveredFactory> factories, |
| | | 455 | | List<DiscoveredOptions> options, |
| | | 456 | | List<DiscoveredHostedService> hostedServices, |
| | | 457 | | List<DiscoveredProvider> providers, |
| | | 458 | | List<DiscoveredHttpClient> httpClients, |
| | | 459 | | List<InaccessibleType> inaccessibleTypes, |
| | | 460 | | Compilation compilation, |
| | | 461 | | bool isCurrentAssembly, |
| | | 462 | | string generatedNamespace) |
| | | 463 | | { |
| | 3834064 | 464 | | foreach (var typeSymbol in TypeDiscoveryHelper.GetAllTypes(assembly.GlobalNamespace)) |
| | | 465 | | { |
| | 1838400 | 466 | | if (!TypeDiscoveryHelper.MatchesNamespacePrefix(typeSymbol, namespacePrefixes)) |
| | | 467 | | continue; |
| | | 468 | | |
| | 1530574 | 469 | | if (TypeDiscoveryHelper.MatchesExclusionFilter(typeSymbol, excludeNamespacePrefixes)) |
| | | 470 | | continue; |
| | | 471 | | |
| | | 472 | | // .NET MAUI per-platform application entry points are framework-owned and carry |
| | | 473 | | // platform-generated interop members that are inaccessible from generated code. |
| | | 474 | | // Scanning them breaks the head build, so skip them before any discovery path runs. |
| | 1530574 | 475 | | if (TypeDiscoveryHelper.IsMauiPlatformEntryType(typeSymbol)) |
| | | 476 | | continue; |
| | | 477 | | |
| | | 478 | | // For referenced assemblies, check if the type would be registerable but is inaccessible |
| | 1530570 | 479 | | if (!isCurrentAssembly && TypeDiscoveryHelper.IsInternalOrLessAccessible(typeSymbol)) |
| | | 480 | | { |
| | | 481 | | // Check if this type would have been registered if it were accessible |
| | 73310 | 482 | | if (TypeDiscoveryHelper.WouldBeInjectableIgnoringAccessibility(typeSymbol) || |
| | 73310 | 483 | | TypeDiscoveryHelper.WouldBePluginIgnoringAccessibility(typeSymbol, compilation.Assembly)) |
| | | 484 | | { |
| | 2319 | 485 | | var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol); |
| | 2319 | 486 | | inaccessibleTypes.Add(new InaccessibleType(typeName, assembly.Name)); |
| | | 487 | | } |
| | 2319 | 488 | | continue; // Skip further processing for inaccessible types |
| | | 489 | | } |
| | | 490 | | |
| | | 491 | | // Check for [Options] attribute |
| | 1457260 | 492 | | if (OptionsAttributeHelper.HasOptionsAttribute(typeSymbol)) |
| | | 493 | | { |
| | 167 | 494 | | var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol); |
| | 167 | 495 | | var optionsAttrs = OptionsAttributeHelper.GetOptionsAttributes(typeSymbol); |
| | 167 | 496 | | var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath; |
| | | 497 | | |
| | | 498 | | // Detect positional record (record with primary constructor parameters) |
| | 167 | 499 | | var positionalRecordInfo = OptionsDiscoveryHelper.DetectPositionalRecord(typeSymbol); |
| | | 500 | | |
| | | 501 | | // Extract bindable properties for AOT code generation |
| | 167 | 502 | | var properties = OptionsDiscoveryHelper.ExtractBindableProperties(typeSymbol); |
| | | 503 | | |
| | 680 | 504 | | foreach (var optionsAttr in optionsAttrs) |
| | | 505 | | { |
| | | 506 | | // Determine validator type and method |
| | 173 | 507 | | var validatorTypeSymbol = optionsAttr.ValidatorType; |
| | 173 | 508 | | var targetType = validatorTypeSymbol ?? typeSymbol; // Look for method on options class or external |
| | 173 | 509 | | var methodName = optionsAttr.ValidateMethod ?? "Validate"; // Convention: "Validate" |
| | | 510 | | |
| | | 511 | | // Find validation method using convention-based discovery |
| | 173 | 512 | | var validatorMethodInfo = OptionsAttributeHelper.FindValidationMethod(targetType, methodName); |
| | 173 | 513 | | OptionsValidatorInfo? validatorInfo = validatorMethodInfo.HasValue |
| | 173 | 514 | | ? new OptionsValidatorInfo(validatorMethodInfo.Value.MethodName, validatorMethodInfo.Value.IsSta |
| | 173 | 515 | | : null; |
| | | 516 | | |
| | | 517 | | // Infer section name if not provided |
| | 173 | 518 | | var sectionName = optionsAttr.SectionName |
| | 173 | 519 | | ?? Helpers.OptionsNamingHelper.InferSectionName(typeSymbol.Name); |
| | | 520 | | |
| | 173 | 521 | | var validatorTypeName = validatorTypeSymbol != null |
| | 173 | 522 | | ? TypeDiscoveryHelper.GetFullyQualifiedName(validatorTypeSymbol) |
| | 173 | 523 | | : null; |
| | | 524 | | |
| | 173 | 525 | | options.Add(new DiscoveredOptions( |
| | 173 | 526 | | typeName, |
| | 173 | 527 | | sectionName, |
| | 173 | 528 | | optionsAttr.Name, |
| | 173 | 529 | | optionsAttr.ValidateOnStart, |
| | 173 | 530 | | assembly.Name, |
| | 173 | 531 | | sourceFilePath, |
| | 173 | 532 | | validatorInfo, |
| | 173 | 533 | | optionsAttr.ValidateMethod, |
| | 173 | 534 | | validatorTypeName, |
| | 173 | 535 | | positionalRecordInfo, |
| | 173 | 536 | | properties)); |
| | | 537 | | } |
| | | 538 | | } |
| | | 539 | | |
| | | 540 | | // Check for [HttpClientOptions] attribute |
| | 1457260 | 541 | | if (HttpClientOptionsAttributeHelper.HasHttpClientOptionsAttribute(typeSymbol)) |
| | | 542 | | { |
| | 0 | 543 | | var httpAttrInfo = HttpClientOptionsAttributeHelper.GetHttpClientOptionsAttribute(typeSymbol); |
| | 0 | 544 | | if (httpAttrInfo.HasValue) |
| | | 545 | | { |
| | | 546 | | // Try to read a literal ClientName property body, if any. |
| | 0 | 547 | | var clientNamePropResult = HttpClientOptionsAttributeHelper.TryGetClientNameProperty(typeSymbol, out |
| | 0 | 548 | | var propertyNameFromType = clientNamePropResult == ClientNamePropertyResult.Literal ? literalValue : |
| | | 549 | | |
| | 0 | 550 | | if (HttpClientOptionsAttributeHelper.TryResolveClientName( |
| | 0 | 551 | | typeSymbol, |
| | 0 | 552 | | httpAttrInfo.Value, |
| | 0 | 553 | | propertyNameFromType, |
| | 0 | 554 | | out var resolvedClientName)) |
| | | 555 | | { |
| | 0 | 556 | | var httpSectionName = HttpClientOptionsAttributeHelper.ResolveSectionName(httpAttrInfo.Value, re |
| | 0 | 557 | | var httpTypeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol); |
| | 0 | 558 | | var httpSourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath; |
| | 0 | 559 | | var capabilities = HttpClientOptionsAttributeHelper.DetectCapabilities(typeSymbol); |
| | | 560 | | |
| | 0 | 561 | | httpClients.Add(new DiscoveredHttpClient( |
| | 0 | 562 | | httpTypeName, |
| | 0 | 563 | | resolvedClientName, |
| | 0 | 564 | | httpSectionName, |
| | 0 | 565 | | assembly.Name, |
| | 0 | 566 | | capabilities, |
| | 0 | 567 | | httpSourceFilePath)); |
| | | 568 | | } |
| | | 569 | | } |
| | | 570 | | } |
| | | 571 | | |
| | | 572 | | // Check for [GenerateFactory] attribute - these types get factories instead of direct registration |
| | 1457260 | 573 | | if (FactoryDiscoveryHelper.HasGenerateFactoryAttribute(typeSymbol)) |
| | | 574 | | { |
| | 25 | 575 | | var factoryConstructors = FactoryDiscoveryHelper.GetFactoryConstructors(typeSymbol); |
| | 25 | 576 | | if (factoryConstructors.Count > 0) |
| | | 577 | | { |
| | | 578 | | // Has at least one constructor with runtime params - generate factory |
| | 24 | 579 | | var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol); |
| | 24 | 580 | | var interfaces = TypeDiscoveryHelper.GetRegisterableInterfaces(typeSymbol, compilation.Assembly); |
| | 30 | 581 | | var interfaceNames = interfaces.Select(i => TypeDiscoveryHelper.GetFullyQualifiedName(i)).ToArray(); |
| | 24 | 582 | | var generationMode = FactoryDiscoveryHelper.GetFactoryGenerationMode(typeSymbol); |
| | 24 | 583 | | var returnTypeOverride = FactoryDiscoveryHelper.GetFactoryReturnInterfaceType(typeSymbol); |
| | 24 | 584 | | var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath; |
| | | 585 | | |
| | 24 | 586 | | factories.Add(new DiscoveredFactory( |
| | 24 | 587 | | typeName, |
| | 24 | 588 | | interfaceNames, |
| | 24 | 589 | | assembly.Name, |
| | 24 | 590 | | generationMode, |
| | 24 | 591 | | factoryConstructors.ToArray(), |
| | 24 | 592 | | returnTypeOverride, |
| | 24 | 593 | | sourceFilePath)); |
| | | 594 | | |
| | 24 | 595 | | continue; // Don't add to injectable types - factory handles registration |
| | | 596 | | } |
| | | 597 | | // If no runtime params, fall through to normal registration (with warning in future analyzer) |
| | | 598 | | } |
| | | 599 | | |
| | | 600 | | // Check for DecoratorFor<T> attributes |
| | 1457236 | 601 | | var decoratorInfos = TypeDiscoveryHelper.GetDecoratorForAttributes(typeSymbol); |
| | 2914510 | 602 | | foreach (var decoratorInfo in decoratorInfos) |
| | | 603 | | { |
| | 19 | 604 | | var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath; |
| | 19 | 605 | | decorators.Add(new DiscoveredDecorator( |
| | 19 | 606 | | decoratorInfo.DecoratorTypeName, |
| | 19 | 607 | | decoratorInfo.ServiceTypeName, |
| | 19 | 608 | | decoratorInfo.Order, |
| | 19 | 609 | | assembly.Name, |
| | 19 | 610 | | sourceFilePath)); |
| | | 611 | | } |
| | | 612 | | |
| | | 613 | | // Check for OpenDecoratorFor attributes (source-gen only open generic decorators) |
| | 1457236 | 614 | | var openDecoratorInfos = OpenDecoratorDiscoveryHelper.GetOpenDecoratorForAttributes(typeSymbol); |
| | 2914486 | 615 | | foreach (var openDecoratorInfo in openDecoratorInfos) |
| | | 616 | | { |
| | 7 | 617 | | var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath; |
| | 7 | 618 | | openDecorators.Add(new DiscoveredOpenDecorator( |
| | 7 | 619 | | openDecoratorInfo.DecoratorType, |
| | 7 | 620 | | openDecoratorInfo.OpenGenericInterface, |
| | 7 | 621 | | openDecoratorInfo.Order, |
| | 7 | 622 | | assembly.Name, |
| | 7 | 623 | | sourceFilePath)); |
| | | 624 | | } |
| | | 625 | | |
| | | 626 | | // Check for Intercept attributes and collect intercepted services |
| | 1457236 | 627 | | if (InterceptorDiscoveryHelper.HasInterceptAttributes(typeSymbol)) |
| | | 628 | | { |
| | 14 | 629 | | var lifetime = TypeDiscoveryHelper.DetermineLifetime(typeSymbol); |
| | 14 | 630 | | if (lifetime.HasValue) |
| | | 631 | | { |
| | 14 | 632 | | var classLevelInterceptors = InterceptorDiscoveryHelper.GetInterceptAttributes(typeSymbol); |
| | 14 | 633 | | var methodLevelInterceptors = InterceptorDiscoveryHelper.GetMethodLevelInterceptAttributes(typeSymbo |
| | 14 | 634 | | var methods = InterceptorDiscoveryHelper.GetInterceptedMethods(typeSymbol, classLevelInterceptors, m |
| | | 635 | | |
| | 14 | 636 | | if (methods.Count > 0) |
| | | 637 | | { |
| | 14 | 638 | | var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol); |
| | 14 | 639 | | var interfaces = TypeDiscoveryHelper.GetRegisterableInterfaces(typeSymbol, compilation.Assembly) |
| | 28 | 640 | | var interfaceNames = interfaces.Select(i => TypeDiscoveryHelper.GetFullyQualifiedName(i)).ToArra |
| | | 641 | | |
| | | 642 | | // Collect all unique interceptor types |
| | 14 | 643 | | var allInterceptorTypes = classLevelInterceptors |
| | 14 | 644 | | .Concat(methodLevelInterceptors) |
| | 17 | 645 | | .Select(i => i.InterceptorTypeName) |
| | 14 | 646 | | .Distinct() |
| | 14 | 647 | | .ToArray(); |
| | | 648 | | |
| | 14 | 649 | | var interceptedSourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath; |
| | | 650 | | |
| | 14 | 651 | | interceptedServices.Add(new DiscoveredInterceptedService( |
| | 14 | 652 | | typeName, |
| | 14 | 653 | | interfaceNames, |
| | 14 | 654 | | assembly.Name, |
| | 14 | 655 | | lifetime.Value, |
| | 14 | 656 | | methods.ToArray(), |
| | 14 | 657 | | allInterceptorTypes, |
| | 14 | 658 | | interceptedSourceFilePath)); |
| | | 659 | | } |
| | | 660 | | } |
| | | 661 | | } |
| | | 662 | | |
| | | 663 | | // Check for injectable types (but skip types that are providers, which are handled separately) |
| | 1457236 | 664 | | if (TypeDiscoveryHelper.IsInjectableType(typeSymbol, isCurrentAssembly) && !ProviderDiscoveryHelper.HasProvi |
| | | 665 | | { |
| | | 666 | | // Determine lifetime first - only include types that are actually injectable |
| | 409762 | 667 | | var lifetime = TypeDiscoveryHelper.DetermineLifetime(typeSymbol); |
| | 409762 | 668 | | if (lifetime.HasValue) |
| | | 669 | | { |
| | 233541 | 670 | | var interfaces = TypeDiscoveryHelper.GetRegisterableInterfaces(typeSymbol, compilation.Assembly); |
| | 233541 | 671 | | var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol); |
| | 233794 | 672 | | var interfaceNames = interfaces.Select(i => TypeDiscoveryHelper.GetFullyQualifiedName(i)).ToArray(); |
| | | 673 | | |
| | | 674 | | // Capture interface locations for navigation |
| | 233541 | 675 | | var interfaceInfos = interfaces.Select(i => |
| | 233541 | 676 | | { |
| | 253 | 677 | | var ifaceLocation = i.Locations.FirstOrDefault(); |
| | 253 | 678 | | var ifaceFilePath = ifaceLocation?.SourceTree?.FilePath; |
| | 253 | 679 | | var ifaceLine = ifaceLocation?.GetLineSpan().StartLinePosition.Line + 1 ?? 0; |
| | 253 | 680 | | return new InterfaceInfo(TypeDiscoveryHelper.GetFullyQualifiedName(i), ifaceFilePath, ifaceLine) |
| | 233541 | 681 | | }).ToArray(); |
| | | 682 | | |
| | | 683 | | // Check for [DeferToContainer] attribute - use declared types instead of discovered constructors |
| | 233541 | 684 | | var deferredParams = TypeDiscoveryHelper.GetDeferToContainerParameterTypes(typeSymbol); |
| | | 685 | | TypeDiscoveryHelper.ConstructorParameterInfo[] constructorParams; |
| | 233541 | 686 | | if (deferredParams != null) |
| | | 687 | | { |
| | | 688 | | // DeferToContainer doesn't support keyed services - convert to simple params |
| | 10 | 689 | | constructorParams = deferredParams.Select(t => new TypeDiscoveryHelper.ConstructorParameterInfo( |
| | | 690 | | } |
| | | 691 | | else |
| | | 692 | | { |
| | 233536 | 693 | | constructorParams = TypeDiscoveryHelper.GetBestConstructorParametersWithKeys(typeSymbol)?.ToArra |
| | | 694 | | } |
| | | 695 | | |
| | | 696 | | // Get source file path and line for breadcrumbs (null for external assemblies) |
| | 233541 | 697 | | var location = typeSymbol.Locations.FirstOrDefault(); |
| | 233541 | 698 | | var sourceFilePath = location?.SourceTree?.FilePath; |
| | 233541 | 699 | | var sourceLine = location?.GetLineSpan().StartLinePosition.Line + 1 ?? 0; // Convert to 1-based |
| | | 700 | | |
| | | 701 | | // Get [Keyed] attribute keys |
| | 233541 | 702 | | var serviceKeys = TypeDiscoveryHelper.GetKeyedServiceKeys(typeSymbol); |
| | | 703 | | |
| | | 704 | | // Check if this type implements IDisposable or IAsyncDisposable |
| | 233541 | 705 | | var isDisposable = TypeDiscoveryHelper.IsDisposableType(typeSymbol); |
| | | 706 | | |
| | 233541 | 707 | | injectableTypes.Add(new DiscoveredType(typeName, interfaceNames, assembly.Name, lifetime.Value, cons |
| | | 708 | | } |
| | | 709 | | } |
| | | 710 | | |
| | | 711 | | // Check for hosted service types (BackgroundService or IHostedService implementations) |
| | 1457236 | 712 | | if (TypeDiscoveryHelper.IsHostedServiceType(typeSymbol, isCurrentAssembly)) |
| | | 713 | | { |
| | 7 | 714 | | var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol); |
| | 7 | 715 | | var constructorParams = TypeDiscoveryHelper.GetBestConstructorParametersWithKeys(typeSymbol)?.ToArray() |
| | 7 | 716 | | var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath; |
| | | 717 | | |
| | 7 | 718 | | hostedServices.Add(new DiscoveredHostedService( |
| | 7 | 719 | | typeName, |
| | 7 | 720 | | assembly.Name, |
| | 7 | 721 | | GeneratorLifetime.Singleton, // Hosted services are always singleton |
| | 7 | 722 | | constructorParams, |
| | 7 | 723 | | sourceFilePath)); |
| | | 724 | | } |
| | | 725 | | |
| | | 726 | | // Check for [Provider] attribute |
| | 1457236 | 727 | | if (ProviderDiscoveryHelper.HasProviderAttribute(typeSymbol)) |
| | | 728 | | { |
| | 18 | 729 | | var discoveredProvider = ProviderDiscoveryHelper.DiscoverProvider(typeSymbol, assembly.Name, generatedNa |
| | 18 | 730 | | if (discoveredProvider.HasValue) |
| | | 731 | | { |
| | 18 | 732 | | providers.Add(discoveredProvider.Value); |
| | | 733 | | } |
| | | 734 | | } |
| | | 735 | | |
| | | 736 | | // Check for plugin types (concrete class with parameterless ctor and interfaces) |
| | 1457236 | 737 | | if (TypeDiscoveryHelper.IsPluginType(typeSymbol, isCurrentAssembly)) |
| | | 738 | | { |
| | 405147 | 739 | | var pluginInterfaces = TypeDiscoveryHelper.GetPluginInterfaces(typeSymbol, compilation.Assembly); |
| | 405147 | 740 | | if (pluginInterfaces.Count > 0) |
| | | 741 | | { |
| | 1406 | 742 | | var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol); |
| | 2817 | 743 | | var interfaceNames = pluginInterfaces.Select(i => TypeDiscoveryHelper.GetFullyQualifiedName(i)).ToAr |
| | 1406 | 744 | | var attributeNames = TypeDiscoveryHelper.GetPluginAttributes(typeSymbol).ToArray(); |
| | 1406 | 745 | | var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath; |
| | 1406 | 746 | | var order = PluginOrderHelper.GetPluginOrder(typeSymbol); |
| | | 747 | | |
| | 1406 | 748 | | pluginTypes.Add(new DiscoveredPlugin(typeName, interfaceNames, assembly.Name, attributeNames, source |
| | | 749 | | } |
| | | 750 | | } |
| | | 751 | | |
| | | 752 | | // Check for IHubRegistrationPlugin implementations |
| | | 753 | | // NOTE: SignalR hub discovery is now handled by NexusLabs.Needlr.SignalR.Generators |
| | | 754 | | |
| | | 755 | | // Check for SemanticKernel plugin types (classes/statics with [KernelFunction] methods) |
| | | 756 | | // NOTE: SemanticKernel plugin discovery is now handled by NexusLabs.Needlr.SemanticKernel.Generators |
| | | 757 | | } |
| | 78632 | 758 | | } |
| | | 759 | | |
| | | 760 | | private static string GenerateTypeRegistrySource(DiscoveryResult discoveryResult, string assemblyName, BreadcrumbWri |
| | | 761 | | { |
| | 457 | 762 | | var builder = new StringBuilder(); |
| | 457 | 763 | | var safeAssemblyName = GeneratorHelpers.SanitizeIdentifier(assemblyName); |
| | 457 | 764 | | var hasOptions = discoveryResult.Options.Count > 0; |
| | 457 | 765 | | var hasHttpClients = discoveryResult.HttpClients.Count > 0; |
| | 457 | 766 | | var hasConfigBoundRegistrations = hasOptions || hasHttpClients; |
| | | 767 | | |
| | 457 | 768 | | breadcrumbs.WriteFileHeader(builder, assemblyName, "Needlr Type Registry"); |
| | 457 | 769 | | builder.AppendLine("#nullable enable"); |
| | 457 | 770 | | builder.AppendLine(); |
| | 457 | 771 | | builder.AppendLine("using System;"); |
| | 457 | 772 | | builder.AppendLine("using System.Collections.Generic;"); |
| | 457 | 773 | | builder.AppendLine(); |
| | 457 | 774 | | if (hasConfigBoundRegistrations) |
| | | 775 | | { |
| | 146 | 776 | | builder.AppendLine("using Microsoft.Extensions.Configuration;"); |
| | 146 | 777 | | if (isAotProject || hasHttpClients) |
| | | 778 | | { |
| | 78 | 779 | | builder.AppendLine("using Microsoft.Extensions.Options;"); |
| | | 780 | | } |
| | | 781 | | } |
| | 457 | 782 | | builder.AppendLine("using Microsoft.Extensions.DependencyInjection;"); |
| | 457 | 783 | | builder.AppendLine(); |
| | 457 | 784 | | builder.AppendLine("using NexusLabs.Needlr;"); |
| | 457 | 785 | | builder.AppendLine("using NexusLabs.Needlr.Generators;"); |
| | 457 | 786 | | builder.AppendLine(); |
| | 457 | 787 | | builder.AppendLine($"namespace {safeAssemblyName}.Generated;"); |
| | 457 | 788 | | builder.AppendLine(); |
| | 457 | 789 | | builder.AppendLine("/// <summary>"); |
| | 457 | 790 | | builder.AppendLine("/// Compile-time generated registry of injectable types and plugins."); |
| | 457 | 791 | | builder.AppendLine("/// This eliminates the need for runtime reflection-based type discovery."); |
| | 457 | 792 | | builder.AppendLine("/// </summary>"); |
| | 457 | 793 | | builder.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.Generators\", \"1 |
| | 457 | 794 | | builder.AppendLine("public static class TypeRegistry"); |
| | 457 | 795 | | builder.AppendLine("{"); |
| | | 796 | | |
| | 457 | 797 | | CodeGen.InjectableTypesCodeGenerator.GenerateInjectableTypesArray(builder, discoveryResult.InjectableTypes, brea |
| | 457 | 798 | | builder.AppendLine(); |
| | 457 | 799 | | CodeGen.PluginsCodeGenerator.GeneratePluginTypesArray(builder, discoveryResult.PluginTypes, breadcrumbs, project |
| | | 800 | | |
| | 457 | 801 | | builder.AppendLine(); |
| | 457 | 802 | | builder.AppendLine(" /// <summary>"); |
| | 457 | 803 | | builder.AppendLine(" /// Gets all injectable types discovered at compile time."); |
| | 457 | 804 | | builder.AppendLine(" /// </summary>"); |
| | 457 | 805 | | builder.AppendLine(" /// <returns>A read-only list of injectable type information.</returns>"); |
| | 457 | 806 | | builder.AppendLine(" public static IReadOnlyList<InjectableTypeInfo> GetInjectableTypes() => _types;"); |
| | 457 | 807 | | builder.AppendLine(); |
| | 457 | 808 | | builder.AppendLine(" /// <summary>"); |
| | 457 | 809 | | builder.AppendLine(" /// Gets all plugin types discovered at compile time."); |
| | 457 | 810 | | builder.AppendLine(" /// </summary>"); |
| | 457 | 811 | | builder.AppendLine(" /// <returns>A read-only list of plugin type information.</returns>"); |
| | 457 | 812 | | builder.AppendLine(" public static IReadOnlyList<PluginTypeInfo> GetPluginTypes() => _plugins;"); |
| | | 813 | | |
| | 457 | 814 | | if (hasConfigBoundRegistrations) |
| | | 815 | | { |
| | 146 | 816 | | builder.AppendLine(); |
| | 146 | 817 | | GenerateRegisterOptionsMethod(builder, discoveryResult.Options, discoveryResult.HttpClients, safeAssemblyNam |
| | | 818 | | } |
| | | 819 | | |
| | 457 | 820 | | if (discoveryResult.Providers.Count > 0) |
| | | 821 | | { |
| | 17 | 822 | | builder.AppendLine(); |
| | 17 | 823 | | CodeGen.DecoratorsCodeGenerator.GenerateRegisterProvidersMethod(builder, discoveryResult.Providers, safeAsse |
| | | 824 | | } |
| | | 825 | | |
| | 457 | 826 | | builder.AppendLine(); |
| | 457 | 827 | | CodeGen.DecoratorsCodeGenerator.GenerateApplyDecoratorsMethod(builder, discoveryResult.Decorators, discoveryResu |
| | | 828 | | |
| | 457 | 829 | | if (discoveryResult.HostedServices.Count > 0) |
| | | 830 | | { |
| | 6 | 831 | | builder.AppendLine(); |
| | 6 | 832 | | CodeGen.DecoratorsCodeGenerator.GenerateRegisterHostedServicesMethod(builder, discoveryResult.HostedServices |
| | | 833 | | } |
| | | 834 | | |
| | 457 | 835 | | builder.AppendLine("}"); |
| | | 836 | | |
| | 457 | 837 | | return builder.ToString(); |
| | | 838 | | } |
| | | 839 | | |
| | | 840 | | private static void GenerateRegisterOptionsMethod(StringBuilder builder, IReadOnlyList<DiscoveredOptions> options, I |
| | | 841 | | { |
| | 146 | 842 | | builder.AppendLine(" /// <summary>"); |
| | 146 | 843 | | builder.AppendLine(" /// Registers all discovered options types with the service collection."); |
| | 146 | 844 | | builder.AppendLine(" /// This binds configuration sections to strongly-typed options classes,"); |
| | 146 | 845 | | builder.AppendLine(" /// and wires up named HttpClient registrations for [HttpClientOptions] types."); |
| | 146 | 846 | | builder.AppendLine(" /// </summary>"); |
| | 146 | 847 | | builder.AppendLine(" /// <param name=\"services\">The service collection to configure.</param>"); |
| | 146 | 848 | | builder.AppendLine(" /// <param name=\"configuration\">The configuration root to bind options from.</param>") |
| | 146 | 849 | | builder.AppendLine(" public static void RegisterOptions(IServiceCollection services, IConfiguration configura |
| | 146 | 850 | | builder.AppendLine(" {"); |
| | | 851 | | |
| | 146 | 852 | | if (options.Count == 0 && httpClients.Count == 0) |
| | | 853 | | { |
| | 0 | 854 | | breadcrumbs.WriteInlineComment(builder, " ", "No options or HttpClient types discovered"); |
| | | 855 | | } |
| | | 856 | | else |
| | | 857 | | { |
| | 146 | 858 | | if (options.Count > 0) |
| | | 859 | | { |
| | 146 | 860 | | if (isAotProject) |
| | | 861 | | { |
| | 78 | 862 | | CodeGen.OptionsCodeGenerator.GenerateAotOptionsRegistration(builder, options, safeAssemblyName, brea |
| | | 863 | | } |
| | | 864 | | else |
| | | 865 | | { |
| | 68 | 866 | | CodeGen.OptionsCodeGenerator.GenerateReflectionOptionsRegistration(builder, options, safeAssemblyNam |
| | | 867 | | } |
| | | 868 | | } |
| | | 869 | | |
| | 146 | 870 | | if (httpClients.Count > 0) |
| | | 871 | | { |
| | 0 | 872 | | CodeGen.HttpClientCodeGenerator.EmitHttpClientRegistrations(builder, httpClients); |
| | | 873 | | } |
| | | 874 | | } |
| | | 875 | | |
| | 146 | 876 | | builder.AppendLine(" }"); |
| | 146 | 877 | | } |
| | | 878 | | |
| | | 879 | | } |