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