refactor(source-generators): simplify and restructure code generation logic#279
Merged
Conversation
…g in MapHandlerIncrementalGenerator - Replaced nested tuple access with meaningful variable names for readability. - Streamlined length checks for variable groups.
…consistency - Replaced `LambdaHostOutputGenerator` with `MinimalLambdaEmitter` for naming alignment. - Updated references to reflect the new class and method names across templates and tests. - Removed unused `OpenTelemetrySources.cs`. - Updated `MapHandlerIncrementalGenerator` to `MinimalLambdaGenerator`.
…nsions - Added `WellKnownTypes` utility for resolving and caching common type metadata. - Implemented `BoundedCacheWithFactory` for efficient caching of compilation-related data. - Introduced several extension methods for simplifying syntax and symbol analysis. - Enhanced generator context handling with a new `GeneratorContext` class. - Added specialized enumerable and functional utilities to support incremental source generation.
…etadata - Added multiple AWS Lambda and MinimalLambda-related types for enhanced source generation support. - Updated `WellKnownTypeData` to include both new types and their string representations.
…d handler analysis - Added `HandlerSyntaxProvider` to consolidate and streamline syntax logic for handler methods. - Refactored `MinimalLambdaGenerator` to use the new `HandlerSyntaxProvider` for handler registration. - Updated `CompilationInfo` to remove `BuilderInfos` and include handler-related simplifications. - Deprecated redundant provider calls like `MapHandlerSyntaxProvider` and `OnInitSyntaxProvider`.
…r generation logic - Updated `GeneratorContext` to include `Node` for enhanced contextual data access. - Replaced `GeneratorAttributeSyntaxContext` with a more generalized `GeneratorSyntaxContext`. - Simplified `MapHandlerSources.Generate` method by removing unused `builderInfo` parameter. - Removed redundant test for main `Test_ExpressionLambda` overload in unit tests. - Added detailed logic for handler transformation in `HandlerSyntaxProvider` to support route handlers. - Included helper methods for resolving invocation operations and route handler arguments.
… and enhance handler logic - Introduced `HigherOrderMethodInfoExtensions` with a `Create` factory method for flexible instantiation. - Updated `HandlerSyntaxProvider` to use `HigherOrderMethodInfo.Create` for handler information generation. - Renamed `TryGetRouteHandlerMethod` to `TryGetHandlerMethod` for clarity and contextual alignment. - Removed redundant code and comments for improved maintainability.
…fiedName` - Renamed `GetAsGlobal` method to `ToGloballyQualifiedName` for improved clarity and expressiveness. - Updated all references to `GetAsGlobal` across source and test files. - Introduced `GetMethodSignature` utility for extracting method signatures with type details. - Extended unit tests to cover scenarios involving the updated method and handler casting logic.
…ion and diagnostics - Introduced `MapHandlerExtractors` to handle parameter assignment extraction logic with diagnostics. - Added `DiagnosticInfo` and `Result` to encapsulate diagnostic data and improve error handling. - Updated `HigherOrderMethodInfo.Create` to integrate parameter assignment and diagnostics. - Enhanced `HandlerSyntaxProvider` to utilize parameter assignment extraction during handler creation. - Adjusted `InterceptableLocationInfo` with extensions to support diagnostic-related transformations. - Fixed a typo in `MapHandlerSources.cs`, correcting `LocatioOpn` to `Location`.
…andlerExtractors` - Replaced `foreach` loops with LINQ-based `Select` for cleaner parameter processing. - Removed redundant code blocks and simplified conditional flows for better readability. - Improved maintainability by consolidating logic for event, context, and DI-based parameter handling. - Enhanced default injection to distinguish required and optional parameters clearly.
… `HigherOrderMethodInfo` - Renamed tuple fields in parameter assignment to improve clarity (`Assignment`, `Diagnostic`). - Updated aggregation logic to use renamed tuple fields within assignment processing. - Added initialization of `HigherOrderMethodInfo` with parameter and diagnostic data for better encapsulation. - Removed unused variable `location` to clean up redundant code.
…andling logic - Introduced `ParameterInfo2` and accompanying extensions for structured parameter handling. - Enhanced `MapHandlerExtractors` with detailed logic for context, events, and DI-based parameters. - Refactored `HigherOrderMethodInfo.Create` to utilize `ParameterInfo2` for improved encapsulation. - Added support for extraction of `IsAwaitable`, `HasReturnType`, and return type classifications. - Commented out `OnInit` logic in `OutputFormattingLambdaApplicationExtensions` for future review. - Improved `Result` class with new mapping and binding functionality for diagnostics.
…`MapHandlerExtractors` - Refactored DI-based parameter resolution logic to use a ternary expression for improved clarity. - Removed redundant comments and unified optional and required DI injection logic.
…dlerExtractors` - Replaced nested `if` structure with a single ternary expression for clarity and conciseness. - Removed redundant comments to improve readability of the event resolution logic.
- Deleted unnecessary `ParameterInfo` comments in generated snapshot files for clarity. - Ensured no functional changes to existing logic or behavior.
…andling logic - Removed the `Result` and `DiagnosticResult<T>` classes to streamline diagnostics and result handling. - Refactored `MapHandlerExtractors` to incorporate new parameter extraction logic. - Introduced `ParameterInfo2` to enhance encapsulation of parameter metadata and simplify assignment logic. - Updated `HigherOrderMethodInfo.Create` for improved parameter diagnostics and encapsulation. - Added new utility extensions for handling well-known types and simplified method signatures. - Replaced conditional checks with LINQ and centralized logic for DI and event parameters. - Improved maintainability by consolidating key functionalities into specialized methods.
…dSymbolExtensions` - Moved `GetCastableSignature`, `IsAwaitable`, and `HasMeaningfulReturnType` from `HigherOrderMethodInfo` to `MethodSymbolExtensions` to improve modularity and reusability. - Updated references to encapsulate method-related operations within the new extension class. - Streamlined the structure of `HigherOrderMethodInfo` by removing redundant code logic.
…mplify and enhance functionality - Updated parameter handling in `MapHandlerParameterInfo` for better encapsulation and clarity. - Replaced `ParameterInfo2` with `MapHandlerParameterInfo`, introducing new properties like `IsEvent` and `IsStream`. - Simplified response and event feature resolution by removing nested conditionals. - Consolidated logic for parameter assignment extraction into `ParameterSymbolExtensions`. - Introduced support for keyed DI services and streamlined their handling. - Updated `HigherOrderMethodInfo` to reflect enhanced assignment and diagnostic logic. - Modularized logic for stream and non-stream event parameters for improved maintainability. - Added `MethodType` enum to classify supported method types (e.g., `MapHandler`, `OnInit`, `OnShutdown`).
…ty and reduce redundancy - Commented out redundant parameter handling logic in `GenericHandlerSources` and related code blocks. - Simplified `DiagnosticGenerator` by commenting out unused diagnostic generation logic. - Adjusted minor formatting issues in `InterceptableLocationInfo` and `HigherOrderMethodInfo`. - Improved maintainability by isolating unused logic for future iteration or removal.
…ble handling - Updated `MapHandler.scriban` to use unwrapped response types for improved consistency. - Refactored parameter assignment in `MapHandlerParameterInfo` to handle keyed services more effectively. - Introduced `UnwrapReturnType` in `MethodSymbolExtensions` to simplify handling of task-based return types. - Adjusted generated snapshot files for nullable input and response type scenarios. - Simplified response feature resolution by standardizing on unwrapped types. - Enhanced `HigherOrderMethodInfo` with proper unwrapped response type data. - Updated snapshot tests to cover new nullable and unwrapped type handling.
…OrderMethodInfo` - Deleted the `IsResponseTypeBool` property and related logic from `HigherOrderMethodInfo`. - Simplified response type handling by removing unused checks for boolean return types.
…stic handling - Added `LocationInfo` property to `MapHandlerParameterInfo` for improved diagnostic context. - Refactored parameter handling to use `IsTypeMatch` and `IsAnyTypeMatch` for cleaner code. - Introduced helper methods in `LocationInfo` for creation from various syntax elements. - Replaced `Diagnostic.Create` with `Diagnostic.CreateLocationInfo` for better location tracking. - Improved encapsulation and modularity in well-known types extensions.
…e diagnostics flow - Added `MapHandlerParameterSource` enum to classify parameter sources (e.g., Event, Context, Services). - Introduced `KeyedServicesKey` in `MapHandlerParameterInfo` for specifying keys for DI services. - Integrated `ReportMultipleEvents` diagnostics to handle invalid multiple events scenario. - Updated `HigherOrderMethodInfo` creation logic to include new diagnostic flow and parameter sources. - Refactored DI parameter resolution to support keyed services using `GetDiParameterAssignment`. - Streamlined diagnostics collection in `DiagnosticGenerator` for improved modularity.
…d handling logic - Changed `MapHandlerParameterInfo` from `record struct` to `record` for improved extensibility. - Updated `HigherOrderMethodInfo` to align with new parameter handling and diagnostics structure. - Introduced additional constructor usage for `MapHandlerParameterInfo` to streamline initialization. - Made `ReportMultipleEvents` private for better encapsulation and access control. - Added `WhereNotNull` extension method for nullable value providers to improve null handling logic in generators.
…oved clarity and lazy initialization - Replaced redundant null-check logic with `Lazy<string>` initialization for `eventAttribute`. - Reordered properties in `IMethodInfo` for consistent ordering and readability. - Simplified LINQ usage in diagnostics generation for `assignments.Where(a => a.IsEvent)`.
…eamlined diagnostics and results - Added `CollectDiagnosticResults` to simplify diagnostics and result aggregation using LINQ. - Replaced existing diagnostics aggregation logic in `HigherOrderMethodInfo` with the new utility method. - Updated `EnumerableExtensions` with new generic helper for enhanced result handling. - Improved maintainability by reducing repetitive code across result and diagnostics collection.
…tionMethodInfo` and introduce `LifecycleMethodInfo` - Replaced `HigherOrderMethodInfo` with `InvocationMethodInfo` for better encapsulation and clarity. - Introduced `LifecycleMethodInfo` to handle `OnInit` and `OnShutdown` method types. - Refactored method type classification to use `MethodType` enum for improved maintainability and readability. - Updated syntax providers and diagnostic logic to align with the new method info handling structure. - Simplified diagnostic aggregation and method invocation assignment using the updated models. - Improved modularity by extracting shared method-related logic into reusable components.
…method info structures - Added support for aggregating diagnostics from `OnInit` and `OnShutdown` invocation information. - Removed `InterceptableLocationInfo` from `InvocationMethodInfo` and added `LifecycleMethodInfo` fields. - Refactored `LifecycleMethodInfo` to include `InterceptableLocationAttribute` and `DelegateCastType`. - Streamlined diagnostic generation logic in `DiagnosticGenerator` to leverage updated method info models.
…with `MapHandlerMethodInfo` - Renamed `InvocationMethodInfo` to `MapHandlerMethodInfo` for improved readability and scope clarity. - Removed `MapHandlerParameterSource` enum from `MapHandlerParameterInfo` and moved it to a separate file. - Introduced `LifecycleHandlerParameterInfo` to enhance parameter handling for lifecycle-related methods. - Updated syntax providers, diagnostics, and emitters to align with the new `MapHandlerMethodInfo` structure. - Refactored parameter resolution logic to improve modularity and streamline handler generation.
…fecycle method support - Refactored `HasMeaningfulReturnType` to support unwrapped return types with `out` parameter. - Replaced inline `UnwrapReturnType` calls with method invocation for cleaner logic. - Introduced `CreateForInit` and `CreateForShutdown` methods in `LifecycleMethodInfo` for clarity. - Migrated `IsAnyTypeMatch` to extensions for streamlined type matching logic. - Updated lifecycle method handling to align with refactored return type logic.
…diagnostics handling - Replaced tuple decomposition in `UseMiddlewareTInfo` with direct `diagnostics` collection. - Changed `DiagnosticInfos` in `ClassInfo.Create` from `array` to `List` for better performance. - Enhanced maintainability and consistency by delegating diagnostics aggregation logic.
…e parameter handling - Renamed `ParameterInfo` to `MiddlewareParameterInfo` for clarity and better alignment with usage context. - Refactored `ClassInfo` to `MiddlewareClassInfo` to better represent middleware-specific logic. - Updated extensions and syntax providers to accommodate the renamed models. - Improved diagnostics generation and handling in parameter creation methods. - Removed outdated and unused `MethodInfo` model and its related extensions.
…ostics from snapshot tests - Cleaned up outdated diagnostic comments across multiple `LambdaHandler.g.verified.cs` snapshot files. - Improved readability and maintainability of the test snapshots by removing unnecessary noise. - Ensured no functional changes to the test logic or middleware handling.
…template for parameter handling - Introduced `AllFromServices` property in `MiddlewareClassInfo` for streamlined parameter checks. - Updated `UseMiddlewareT` template to utilize `AllFromServices` and `parameter_infos` for clarity. - Replaced outdated `parameters` logic with `parameter_infos` and refactored related assignments. - Improved maintainability by consolidating and simplifying parameter resolution logic.
…ParameterInfo` in type mappings - Updated `WellKnownTypeData` to use `System.Reflection.ParameterInfo` for consistency with standard types. - Removed outdated reference to `MiddlewareParameterInfo` in the well-known types array.
- Refactored `MiddlewareParameterInfo` to include improved attribute checks for `FromArguments` and `FromServices`. - Added `AllParametersFromServices` property to `MiddlewareClassInfo` to simplify parameter validation. - Updated `UseMiddlewareT` template to leverage `AllParametersFromServices` for cleaner code generation. - Consolidated `IsDecoratedWithAttribute` logic in `ParameterSymbolExtensions` for improved reusability. - Renamed `MiddlewareParameterInfo` fields for better clarity and alignment with usage context. - Removed outdated and unused commented code across test snapshots for better readability.
…ter source handling - Deleted `KeyedServiceKeyInfo`, `TypeInfo`, and `MapHandlerParameterSource` as they are no longer used. - Consolidated the usage of `MapHandlerParameterSource` into `ParameterSource` for reduced redundancy. - Updated parameter source assignments in related models for consistency. - Improved maintainability by cleaning up outdated logic and references.
…emplate clarity - Added support for diagnostic generation from `UseMiddlewareTInfos` in `DiagnosticGenerator`. - Updated `UseMiddlewareT` template to improve formatting and reduce redundant whitespace. - Included `liquid` language settings in `.DotSettings` with default `Reformat` configuration. - Improved consistency in `Rearrange` and `Reformat` settings across various language configurations.
…and clean up duplication - Converted `DiagnosticInfo` from `struct` to `record` for better immutability and pattern matching. - Simplified equality checks and hash code generation in `DiagnosticInfo`. - Removed redundant value access in `DiagnosticResult` methods to streamline code.
…th consolidated properties - Removed `TypeSymbolExtensions.IsTask` and `IsValueTask` methods as they were unused. - Replaced `ToGloballyQualifiedName` and `ToNotNullableGloballyQualifiedName` methods with `QualifiedName` and `QualifiedNullableName` properties for simplicity. - Updated all references to use `QualifiedName` and `QualifiedNullableName`. - Removed redundant `GetTypeKind` logic from `TypeSymbolExtensions` to streamline type analysis. - Improved readability and maintainability by removing outdated code and consolidation of extension logic.
…inline code generation - Deleted `UseMiddlewareTSource` class as it is no longer needed for `UseMiddlewareT` generation logic. - Inlined template rendering directly in `MinimalLambdaEmitter` for simplifying code and reducing indirection. - Improved maintainability by eliminating a redundant layer of abstraction.
… and enhance `DiagnosticResult` - Replaced method body in `CollectDiagnosticResults` with lambda expression for simplicity. - Consolidated list initialization within `Aggregate` for improved readability. - Renamed `Do` method to `Switch` in `DiagnosticResult` for better clarity and intent. - Made `DiagnosticResult` a `sealed` class to prevent inheritance. - Added implicit conversion from `T` to `DiagnosticResult<T>` for cleaner usage.
…ge and refactor attribute logic - Replaced `ToInterceptsLocationAttribute` method with `Attribute` property for better clarity and brevity. - Made `InterceptableLocationInfo` a `sealed` record for improved immutability and design consistency. - Updated all references to use the new `Attribute` property, reducing redundant method calls. - Improved maintainability and readability by streamlining attribute handling logic.
…ctionalExtensions.Map` - Updated `Map` method in `FunctionalExtensions` to combine type constraints on generic parameters. - Improved readability and reduced redundancy by merging method overloads.
…sed code - Improved formatting and reduced redundant whitespace in `UseMiddlewareT` template for better clarity. - Enhanced diagnostics in tests to ensure generation errors are caught and reported comprehensively. - Removed unused mappings, constants, and commented-out code throughout the source generator. - Simplified `SyntaxProviders` and refactored invocation operation logic for readability and efficiency. - Consolidated redundant extension methods and improved code maintainability.
…leanup legacy code - Deleted `NamedTypeSymbolExtensions` and related methods due to redundancy and lack of usage. - Removed unnecessary extension methods from `EnumerableExtensions` to reduce duplication. - Cleaned up obsolete commented-out code in `DiagnosticGenerator` for better maintainability. - Reorganized folder structure for models to align with updated source generator logic.
…ns and refactor usages - Deleted `WellKnownTypesExtensions` to eliminate redundancy and unused methods. - Updated `IsAnyTypeMatch` and `IsTypeMatch` calls to use `IsType` for consistency and simplicity. - Removed `TypeImplementsInterface` and replaced its logic with direct interface checks. - Simplified type matching throughout models and syntax providers for better maintainability. - Improved code readability by consolidating type-checking logic.
…diagnostics collection - Renamed `SyntaxExtensions` to `SyntaxNodeExtensions` for better semantic clarity. - Renamed `TypeExtractorExtensions` to `TypeSymbolExtensions` to align with updated naming conventions. - Updated `CollectDiagnosticResults` method to fix type parameter naming inconsistency and improve readability.
…mline processing - Improved error messages in `UseMiddlewareTInfo` and `MiddlewareClassInfo` for better debugging. - Added validation for concrete middleware class types to ensure they are non-abstract and non-interface. - Refactored constructor logic to simplify diagnostics collection and streamline parameter handling. - Optimized `TryGetInvocationOperation` in `UseMiddlewareTSyntaxProvider` for readability and efficiency. - Enhanced type argument location handling for better accuracy in diagnostics.
…lewareClassInfo` - Removed unused diagnostics list initialization for efficiency. - Updated validation to return diagnostics directly, reducing intermediate steps. - Refactored `TryCreate` method to streamline logic and improve readability.
… `Handlers` grouping - Moved files from `LifecycleHandlers`, `InvocationHandlers`, and `Shared` to a unified `Handlers` folder. - Renamed files and namespaces to align with the updated folder structure. - Improved code organization for better maintainability and discoverability.
…arity and consistency - Changed namespaces in `Emitters` and `Models` to align with folder structure. - Updated imports to reflect the new organization. - Improved project maintainability by enforcing a consistent namespace hierarchy.
… parameter symbol extensions - Made `IsFromEvent` and `IsFromKeyedService` methods more concise using lambda expressions. - Refactored keyed service detection logic into `IsFromKeyedService` for clearer separation of concerns. - Simplified `GetDiParameterAssignment` to streamline type and key handling in DI contexts. - Cleaned up redundant usages of `DiagnosticResult` in extracted keyed service attributes. - Adjusted settings in `.DotSettings` file to improve consistency in code formatting rules.
…wareTInfo` - Replaced redundant `TryGetLocationInfo` calls with a concise implementation for type argument location. - Removed unused `locationInfo` variable and associated logic to streamline code. - Refactored `TryGetLocationInfo` method to directly return `Location`. - Improved readability by consolidating type argument diagnostics logic.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

🚀 Pull Request
📋 Summary
This PR refactors the source generator codebase to simplify the code generation logic and improve maintainability. The changes consolidate handler generation, introduce a
WellKnownTypessystem for type caching, and reorganize theModelsfolder structure for better clarity.Key improvements:
HandlerSyntaxProviderto unify handler analysis across MapHandler and lifecycle methodsWellKnownTypessystem with bounded caching to reduce redundant type lookupsModelsfolder intoHandlers,Middleware, andSharedgroupingsDiagnosticResultpatternMapHandlerParameterInfoandLifecycleHandlerParameterInfomodelsTechnical details:
MapHandlerSyntaxProvider,OnInitSyntaxProvider,OnShutdownSyntaxProvider) with unifiedHandlerSyntaxProviderMethodSymbolExtensionsandParameterSymbolExtensionsto centralize symbol analysisUseMiddlewareTgeneration by inlining logic and improving template structure✅ Checklist
🧪 Related Issues or PRs
N/A - Internal refactoring to improve code quality and maintainability
💬 Notes for Reviewers
This is a substantial refactoring that touches many files (126 files changed). The core functionality remains the same, but the internal architecture has been significantly improved:
Models/- now organized byHandlers/,Middleware/, andShared/WellKnownTypesimplementation - this is a new pattern for type cachingHandlerSyntaxProvider- consolidates logic from 3 separate providersThe refactoring maintains backward compatibility - all existing tests pass with updated snapshots where template formatting changed.